Attributing AI Activity to the Right User

The Countly AI SDK attaches every AI call it tracks to a device ID. That ID decides which profile in Countly the call belongs to, and whether it counts toward the AI metrics that are about people, not volume.

Getting it wrong does not produce an error. Your prompt, token, and cost totals keep looking correct while every user-based AI metric reads zero. This article explains the one rule you need to follow, the four ways it usually goes wrong, and how to check your setup in five minutes.

Before you start

This article assumes you have already installed an AI SDK adapter and wrapped your AI client. It applies to every adapter: OpenAI, Anthropic, Google GenAI, Cohere, Vercel AI SDK, LangChain, Mastra, and LlamaIndex.

Understanding the Device ID Rule

The rule

The device ID you give the AI SDK must be the same ID the rest of your Countly instrumentation already uses for that person, usually your web or mobile Countly SDK.

The rule exists because of what the AI SDK sends. Every request it makes carries your app key, a device ID, and AI events, latency traces, or error reports. It never sends any of the following:

Never Sent Consequence
begin_session The device never opens a session
end_session, session_duration The device builds up no session time
metrics (platform, device, carrier, and so on) The profile has no device properties
user_details The profile has no name, e-mail, or custom properties

This is deliberate, and it will not change. If the SDK opened a session for every LLM call, it would invent activity that never happened and inflate metrics that have nothing to do with AI, such as daily active users, session length, and retention.

The result is simple to remember: the AI SDK can attach AI activity to a person, but it cannot create one. Identity has to come from where it already lives, which is your app's own Countly SDK or your authentication layer.

How Countly Uses the Device ID

AI metrics in Countly fall into two families, and only one of them depends on the device ID:

Family Examples Depends on the Device ID?
Volume Prompts, tokens, cost, latency, error rate, tool calls No. Every event counts, whatever its device ID.
User-based AI users, AI adoption rate, the tried AI to adopter to power user funnel, AI vs. non-AI comparisons, cost per user Yes. These compare the device IDs on AI events with your app's active users.

Countly builds the list of active users from sessions. A device ID that only ever appears on AI events has no sessions, so it drops out of that comparison. Nothing flags an error, because from the query's point of view nothing is wrong.

The signature of a mismatch

Volume metrics look healthy and plausible, while every user-based AI metric reads zero, or a small number that never grows no matter how much AI traffic you send. If you see this pattern, check your device ID before anything else.

Avoiding the Four Common Mistakes

These are listed in order of how often they happen.

Configuring No Device ID at All

observeOpenAI(client, { appKey: "...", url: "..." }); // no deviceId, no getDeviceId

Without a configured ID, the SDK falls back to a random ID generated once per process. This fallback keeps events from being dropped, but it is not a person, and it is not stable:

  • Every process restart creates a new one.
  • Every replica, container, pod, and serverless invocation has its own.
  • Nothing else in your stack has ever reported it.

A service that deploys daily therefore produces a new one-day-old "user" every day. Tiers that require repeat activity, such as adopter or power user, can never be reached. Do not ship this fallback to production.

Using an Internal ID That Countly Has Never Seen

getDeviceId: () => user.id, // your database primary key

This is only correct if your web or mobile Countly SDK also uses that same value. If the client SDK is still on its own generated ID, you have created two separate identities for the same person, and they never meet. See Making the Client Adopt Your ID below for how to align them.

Using a Per-Request or Per-Conversation ID

getDeviceId: () => requestId, // or a trace ID, thread ID, or session token

Every prompt becomes a new person. The count of people who tried AI grows with your traffic, while every repeat-activity tier stays at zero. If you need to correlate requests or conversations, use the run_id and thread_id fields that are already on every event. The device ID is the only field that means a person.

Running a Backend Without Client-Side Countly

A server-only deployment, such as a cron job, an internal agent, or a batch pipeline, has no sessions for anyone. This is a valid setup, not a mistake. However, the user-based metrics have no active users to compare against, so a zero there means your app has no session-bearing users, not that nobody adopted AI. Read the volume metrics instead.

Passing the Right Device ID

In every setup, the goal is the same: pass the ID your app's Countly SDK already uses, resolved for each request.

Reading the ID in the Browser

In the browser, each person runs in their own tab, so you can read the ID straight from the Countly Web SDK:

const openai = observeOpenAI(new OpenAI(), {
  appKey: "YOUR_APP_KEY",
  url: "https://your-countly-server.com",
  getDeviceId: () => Countly.get_device_id(),
});

The SDK calls getDeviceId synchronously each time it records an event, so if the person switches accounts, the next call picks up the new ID.

Passing the ID Through a Multi-User Backend

When your AI calls run on a server that handles many people at once, have the client send its Countly device ID with each request, for example in a header of your choice. On the server, scope it to the request with AsyncLocalStorage:

import { AsyncLocalStorage } from "node:async_hooks";
const store = new AsyncLocalStorage();

app.use((req, res, next) => {
  // The same ID the client-side Countly SDK reports,
  // NOT your database primary key (unless the client already uses it)
  store.run({ countlyDeviceId: req.header("x-countly-device-id") }, next);
});

observeOpenAI(client, {
  appKey: "YOUR_APP_KEY",
  url: "https://your-countly-server.com",
  getDeviceId: () => store.getStore()?.countlyDeviceId,
});

This works with every adapter that accepts getDeviceId, and it works under high concurrency. The SDK reads the ID when each event is recorded, not when the batch is sent, so every event keeps the ID of the request that produced it. Events from different people are sent as separate requests.

Do not use a shared variable on a server

Storing the current person's ID in a module-level variable that your middleware overwrites looks similar, but it breaks under load: two overlapping requests read each other's ID. getDeviceId must also be synchronous, so it cannot await a lookup.

Passing the ID in Mastra

The Mastra adapter reads the ID from Mastra's request context instead of from getDeviceId. Set it on the context before you start the agent or workflow:

import { RequestContext } from "@mastra/core/request-context";

const ctx = new RequestContext();
ctx.set("countlyDeviceId", req.header("x-countly-device-id"));
await mastra.getAgent("intent").stream(messages, { requestContext: ctx });

Mastra copies the context onto every span it creates during the run, and the Countly exporter reads the ID from there. The default key is countlyDeviceId. You can rename it with the requestContextDeviceIdKey option, or set that option to null to fall back to getDeviceId or deviceId.

Making the Client Adopt Your ID

If you cannot get the client's ID to your backend, do the reverse. Change the device ID in your web or mobile Countly SDK to your own user ID, with merging enabled, then pass that same ID to the AI SDK. In the Web SDK, that is Countly.change_id(yourUserId, true).

Merging keeps the person's existing history and moves it to the new ID, so it is the right choice when you are moving from SDK-generated IDs to your own. It is a costly operation on the Server, so call it when the person logs in, not on every request. Either direction works. Having two IDs for one person does not.

Understanding Resolution Priority

When more than one source provides an ID, the SDK uses the first one it finds, in this order:

  1. An ID set directly on the event.
  2. The Mastra request context (Mastra adapter only).
  3. Your getDeviceId() function.
  4. Your static deviceId setting.
  5. The per-process fallback ID. This is a last resort, not a default worth shipping.

Verifying the Device ID

This check takes about five minutes, and it is the only place where a mismatch is visible.

  1. Make one instrumented AI call and note the device ID you passed. Setting debug: true in the SDK configuration helps here.
  2. In Countly, open User ProfilesProfiles and search for that exact ID.
  3. Compare what you see with the table below.
What You See What It Means
The profile exists, has sessions, and was last seen before your AI call Correct. The AI activity is attached to a real person.
The profile exists but has zero sessions and was created by your AI call Mismatch. The ID is only known to the AI SDK. Review the four common mistakes above.
No profile at all The event never arrived. This is a delivery problem, not an identity one. Check the onDropped callback and transport.stats().

Look out for the second row. Everywhere else in Countly, it looks exactly like success.

Related Resources

Was this page helpful?
Reach out to us for any other questions.
Helpful?

Looking For More Help?