When AI data in Countly looks wrong, the cause is rarely a bug. More often, the SDK is telling you honestly that it could not observe something, or a small configuration detail is keeping events from arriving where you expect them.
This article lists the most common symptoms, each with its cause and resolution. Start with Checking Delivery First, because it rules out the problems that look like everything else.
Before you start
This article assumes you have already installed an AI SDK adapter and wrapped your AI client, as described in Tracking LLM Usage with the Countly AI SDK.
Reading Missing Values Correctly
The SDK never fills a gap with a guess. When it cannot read a dimension, such as the provider or the endpoint type, it writes an explicit "unknown" or "not_reported". When it cannot take a measurement, such as token counts or cost, it leaves the field out and adds a marker that says why.
So a missing cost is not a cost of zero, and a missing token count is not a free call. Two markers on every [CLY]_llm_interaction event explain what happened:
| Marker | Values | What It Governs |
|---|---|---|
usage_state |
reported, not_reported
|
Every usage_* and cost_* field |
cost_priced |
priced, priced_modality_approx, unpriced_model, no_usage
|
Every cost_* field. Cost fields are present only when the value is priced or priced_modality_approx. |
Some fields are also absent because the provider has nothing to report. For example, OpenAI, Google GenAI, and Cohere have no cache-write billing bucket, so usage_cache_write never appears on their events. Check what each adapter can observe in the AI SDK Event Data Reference before treating a missing field as a bug.
Checking Delivery First
Before you chase a specific symptom, confirm that events leave your application. Turn on debug logging and register an onDropped callback:
const openai = observeOpenAI(new OpenAI(), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
debug: true,
onDropped: (events, reason) => {
// reason is "send_failed" or "buffer_full"
console.warn(`Countly AI SDK dropped ${events.length} events: ${reason}`);
},
});
| Tool | What It Tells You |
|---|---|
debug: true |
Logs transport errors, dropped batches, and token counts an adapter reported inconsistently. The OpenAI and Anthropic adapters also warn once when your code uses a method they do not track. |
onDropped(events, reason) |
Called when events are discarded for good, with the reason "send_failed" or "buffer_full". It is the only way to learn that your prompt and cost counts are under-reported. |
transport.stats() |
Returns running counts as { buffered, deadLettered, dropped }
|
It also helps to know how the SDK delivers events, so you can tell a delay from a loss:
- Batching: events are sent every 10 seconds or every 20 events, whichever comes first.
-
Retries: a failed send is retried with backoff, up to three attempts. A
429response is retried after the delay in itsRetry-Afterheader. Client errors (400,401,403,413, and422) are not retried. - Dead-letter buffer: events that still fail are kept in memory, up to 1,000, and sent again once a later request succeeds.
-
Overflow: beyond 10,000 buffered events (
maxBufferSize), the oldest are dropped, andonDroppedfires. - Restarts: the buffer lives in memory, so a crash or restart loses whatever was not sent yet.
If delivery looks healthy, check that the events landed on the right profile, as described in Attributing AI Activity to the Right User.
Resolving Common Issues
Receiving 403 Errors From a Self-Hosted Countly Server
Cause: your url points to an endpoint that requires authentication. The SDK sends events the same way a client SDK does, without a server-side token. Client errors are not retried, so the affected batches do not arrive.
Resolution: set url to the endpoint that accepts SDK data without a token, which is typically your frontend endpoint. Countly Cloud users (*.count.ly) do not need to change anything.
Seeing Prompts and Cost but Zero AI Users
Cause: the device ID you pass does not match the one your Countly client SDK reports for the same person. Volume metrics, such as prompts, tokens, and cost, count every event. User-based metrics, such as AI users and adoption rate, only count device IDs that also have sessions, and the AI SDK never opens a session.
Resolution: pass the device ID your web or mobile Countly SDK already uses, resolved per request. The device ID article linked above explains the four common mistakes and a five-minute check.
If your application is backend-only, such as a batch pipeline or an internal agent, no profile has sessions. In that case a zero is correct: it means your app has no session-bearing profiles, not that nobody adopted AI. Read the volume metrics instead.
Seeing No Tokens or No Cost on Some Calls
Cause: the SDK could not measure the call, or could not price it. The two markers on the event tell you which:
| What the Event Shows | Cause | Resolution |
|---|---|---|
An OpenAI streaming call with usage_state: "not_reported" and no token or cost fields |
OpenAI only includes usage in a stream when you ask for it | Add stream_options: { include_usage: true } to your streaming calls |
Tokens are present, no cost fields, and cost_priced: "unpriced_model"
|
The model is not in the built-in pricing table | Add the model to costModel
|
cost_priced: "no_usage" |
The provider reported no token usage at all | Check the provider's request options for a usage setting, such as the OpenAI stream option above |
An Anthropic stream with status: "incomplete" and no usage |
Your code stopped reading the stream early. Anthropic reports output tokens only at the end, and the SDK does not present a partial cost as a complete one. | Expected. Read the stream to the end when you need its cost. |
cost_priced: "priced_modality_approx" |
The call used audio or image tokens, which are priced approximately | Expected. Treat the cost as an estimate. |
The OpenAI fix looks like this:
const stream = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello" }],
stream: true,
stream_options: { include_usage: true }, // required for token and cost data on streams
});
To price a fine-tuned or unlisted model, add it to costModel in dollars per million tokens. Model names are prefix-matched, so gpt-4.1-mini-2025-XX uses the price of gpt-4.1-mini.
observeOpenAI(client, {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
costModel: {
"my-fine-tuned-model": { input_per_mtok: 0.5, output_per_mtok: 1.5 },
},
});
For how cost is split into components, see Understanding and Customizing AI Cost Calculation.
Seeing an Unknown API Host Type
Cause: api_host_type: "unknown" means the SDK could not observe which endpoint served the call. It does not mean the call went somewhere unusual. Most adapters read the endpoint from the client's base URL, but some cannot:
- Vercel AI SDK: its telemetry events do not carry the provider client's base URL.
-
Mastra: Mastra does not report the endpoint at all, so every Mastra event reports
"unknown"out of the box, and the "By host type" breakdown stays empty for Mastra traffic. -
Cohere: a custom
fetcherorfetchoverride, e.g., for Bedrock or SageMaker, reroutes the request without recording where it went. - LlamaIndex: a provider class that exposes its base URL under a name the SDK does not recognize.
Resolution: on the Vercel AI SDK, pass the base URL as apiBaseURL. The SDK uses it only to classify the endpoint, and it sends the hostname alone, never the path, query, or credentials:
const telemetry = countlyTelemetry({
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
apiBaseURL: "https://api.openai.com/v1",
});
On Mastra, you can report the endpoint yourself with a span output processor. The steps are in Integrating the Countly AI SDK with Mastra. The Cohere and LlamaIndex cases have no documented workaround, so "unknown" is the correct value there.
Seeing an Unknown Tool Status
Cause: with the OpenAI, Anthropic, Google GenAI, and Cohere adapters, the SDK sees the model request a tool, but your own code runs it, so the outcome is not observable. The SDK records "unknown" rather than assuming success. There are two exceptions: OpenAI's hosted Responses tools (MCP, file search, and code interpreter), and Anthropic's server-side and MCP tools, both of which return their outcome in the same response.
The Vercel AI SDK, LangChain, LlamaIndex, and Mastra integrations report the real outcome and duration. The one gap is LlamaIndex: a tool that throws produces no event, so it is reported as "unknown" at the next generation or on shutdown().
Resolution: this is expected behavior, not a bug. When you analyze tool error rates, rely on events from the framework integrations.
No tool events at all?
Per-tool [CLY]_llm_tool_used events require observabilityLevel: 1 or higher. At the default level 0, only the tools_requested and tool_request_count summaries on the interaction event are sent.
Losing Events When a Short-Lived Process Ends
Cause: the SDK buffers events in memory, and its flush timer does not keep your process alive. A script, cron job, or serverless function can exit before the last batch is sent.
Resolution: flush explicitly before the process exits.
await telemetry.flush(); // send buffered events now
await telemetry.shutdown(); // flush, then stop sending
| Integration | Object to Flush | What to Know |
|---|---|---|
| Vercel AI SDK | The countlyTelemetry() integration |
None |
| LangChain | The CountlyCallbackHandler
|
A generation that requested tools is held until the tool outcomes arrive. Flushing releases it, so without a flush it is lost. |
| LlamaIndex | The CountlyLlamaIndexTracer
|
Call tracer.unregister(Settings.callbackManager) afterward to detach it |
| Mastra | The CountlyMastraExporter
|
flush() does not send turns that are still running. shutdown() sends them, marked status: "incomplete". |
| Feedback | The tracker from createFeedbackTracker()
|
It has its own buffer, so flush it separately |
Finding Some Calls Not Tracked at All
Cause: each adapter tracks specific methods. Calls made through other methods produce no events. Operations that are not generations, such as embeddings, never produce an interaction event, by design.
| Adapter | Not Tracked |
|---|---|
| OpenAI | The chat.completions.stream() and responses.stream() helper runners; embeddings, moderations, files, and batches
|
| Anthropic |
client.beta.messages, client.messages.batches, and client.completions
|
| Google GenAI |
live.* sessions; models.embedContent, countTokens, generateImages, and generateVideos; caches.*, files.*, tunings.*, and operations.*
|
| Cohere |
embed, rerank, classify, and the other non-generation endpoints |
| Vercel AI SDK |
embed(), embedMany(), and rerank()
|
| LangChain, LlamaIndex, and Mastra | Steps with no model call, such as chain and retriever steps, workflow roots, RAG pipelines, and memory operations. Their tool events are still sent. |
Resolution:
-
OpenAI: call
chat.completions.create()orresponses.create()withstream: trueinstead of the stream helper runners. Both are tracked. -
Anthropic: use
client.messages.create()orclient.messages.stream(), which are tracked. -
OpenAI and Anthropic: set
debug: trueto get a one-time warning when your code touches an untracked method. -
Mastra, if nothing arrives at all: the exporter must sit inside
new Observability({...}), passed through Mastra'sobservabilityfield. Passed directly asexporterson Mastra, it receives no spans.
Seeing No Errors From LlamaIndex
Cause: LlamaIndex has no error event. When a call throws, it never dispatches the end event, so no callback listener can see the failure, and your error rate reads a perfect zero.
Resolution: hand the error to the tracer yourself:
try {
const response = await queryEngine.query({ query });
} catch (err) {
tracer.recordError(err); // sends a status "error" interaction and a crash report
throw err;
}
With a single call in flight, the SDK attributes the failure to it. Pass recordError(err, { id }) when you have the LlamaIndex call ID, or { model, provider } when the failure happened before any call started.
Missing Workflow Steps or Split Turns in Mastra
Cause: Mastra only traces workflow steps when the workflow is registered on the Mastra instance and run through it. A workflow you import and run on its own has no observability attached, so only the agent runs it calls are traced.
Resolution: register the workflow and run it through getWorkflow():
const mastra = new Mastra({
agents: { intentAgent, pluginsAgent },
workflows: { myWorkflow }, // register the workflow
observability: new Observability({ /* exporter config */ }),
});
// Run it through the instance so its spans reach the exporter
const run = await mastra.getWorkflow("myWorkflow").createRun();
await run.stream({ inputData, requestContext: ctx });
Register only the top-level workflow. Its nested workflows are traced automatically.
A related symptom is one turn appearing as several runs. Mastra traces a workflow and the agents it calls separately, so without your own turn ID they get different run_id values. Set requestContextPromptIdKey on the exporter, and put your ID on the request context before the run starts. A value you add inside a step does not reach the root span.
Getting ERR_MODULE_NOT_FOUND or CommonJS Import Errors
Cause 1: versions 0.0.4 and 0.0.5 threw ERR_MODULE_NOT_FOUND on a plain import in Node.js, on every version from 18.18 to 24.15. They only worked through a bundler.
Resolution: upgrade every @countly/ai-sdk-* package to 0.0.6 or later, and run Node.js 20.19 or later (or 22.12 or later on the 22.x line).
npm install @countly/ai-sdk-openai@latest
On Mastra, 0.0.6 also raises the peer minimums to @mastra/core 1.26.0 and @mastra/observability 1.11.0. Below those versions, cache tokens silently read zero.
Cause 2: the packages are ESM-only. A CommonJS bundle that leaves them external fails to load them.
Resolution: configure your bundler to inline the packages. For tsup or esbuild targeting CommonJS:
// tsup.config.js
import { defineConfig } from "tsup";
export default defineConfig({
format: ["cjs"],
external: [/^@mastra\//], // Mastra only: keep its runtime single-instance
noExternal: [/^@countly\/ai-sdk-/], // ESM-only: inline into the CommonJS bundle
});