The Countly AI SDK adds LLM observability to your application. It wraps the AI library you already use, such as OpenAI, Anthropic, or LangChain, and sends the token usage, cost, latency, tool calls, and errors of every model call to your Countly Server.
Because the data arrives in Countly as standard events, you can analyze AI usage with the same features you use for the rest of your product. This article explains what the SDK captures, how to set it up, and how to confirm that it works.
Availability
The Countly AI SDK is a set of npm packages, one per supported framework. Performance Monitoring traces require Countly Enterprise. Community Edition ignores them, while all other data is accepted.
Overview
Once you wrap your AI client, the SDK captures the following for every model call, with no further code changes:
- Token usage: input and output totals, plus cached, reasoning, and audio or image tokens where the provider reports them.
- Cost: calculated from built-in pricing for 47 models, with overrides for fine-tuned or unlisted models.
- Latency: total duration, plus time to first token for streamed responses.
- Tool calls: which tools the model requested, and their outcome when the framework reports it.
- Errors: categorized as rate limit, context length, content filter, timeout, authentication, or API errors.
Each LLM generation becomes one [CLY]_llm_interaction event. A multi-step agent turn produces one event per generation, and all events of a turn share the same run_id, so you can still analyze the turn as a whole. You can also record user feedback, such as a thumbs up or thumbs down on an answer, as a [CLY]_llm_interaction_feedback event.
The SDK supports the following frameworks and providers. Install only the package for the one you use.
| Framework | Package | Integration | Minimum Peer Version |
|---|---|---|---|
| OpenAI | @countly/ai-sdk-openai |
observeOpenAI() |
openai 4.68.0 |
| Anthropic | @countly/ai-sdk-anthropic |
observeAnthropic() |
@anthropic-ai/sdk 0.30.0 |
| Google GenAI | @countly/ai-sdk-google-genai |
observeGoogleGenAI() |
@google/genai 1.0.0 |
| Cohere | @countly/ai-sdk-cohere |
observeCohere() |
cohere-ai 7.0.0 |
| Vercel AI SDK | @countly/ai-sdk-vercel |
countlyTelemetry() |
ai 4.0.0 |
| LangChain | @countly/ai-sdk-langchain |
CountlyCallbackHandler |
@langchain/core 0.3.0 |
| Mastra | @countly/ai-sdk-mastra |
CountlyMastraExporter |
@mastra/core 1.26.0 and @mastra/observability 1.11.0 |
| LlamaIndex | @countly/ai-sdk-llamaindex |
CountlyLlamaIndexTracer |
llamaindex 0.8.0 |
Once the data reaches your Countly Server, the following features can use it:
| Data Sent | Where to Analyze It |
|---|---|
| LLM interaction, tool, and feedback events | AI Analytics (Countly 27.0 and later), Drill, Formulas, Funnels, and Cohorts |
| Latency traces | Performance Monitoring (Enterprise only) |
| LLM errors | Crash AnalyticsCrashes |
Prerequisites
Before you start, make sure you have the following:
- Your app key and Server URL: both come from the Countly app you want to send AI data to.
- Node.js 20.19 or later (or 22.12 or later on the 22.x line). The packages are ESM-only, so if you bundle to CommonJS, your bundler must inline them.
- A supported framework at or above the minimum peer version listed in the table above.
- Your Countly device ID strategy: the ID your web or mobile Countly SDK already uses for each person. See Linking AI Calls to User Profiles below.
Getting Started
Installing the Adapter
Install the adapter for your framework. The shared core package, @countly/ai-sdk-core, is installed automatically, and no other Countly SDK is required.
npm install @countly/ai-sdk-openai
Replace @countly/ai-sdk-openai with the package name from the table above if you use a different framework.
Wrapping Your AI Client
Every adapter takes the same configuration object. The only required fields are appKey and url. After wrapping, you use your AI client exactly as before.
import OpenAI from "openai";
import { observeOpenAI } from "@countly/ai-sdk-openai";
const openai = observeOpenAI(new OpenAI(), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId, // see "Linking AI Calls to User Profiles"
});
// Use the client exactly as before. Tracking is automatic.
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Explain quantum computing" }],
});
Anthropic, Google GenAI, and Cohere follow the same pattern with observeAnthropic(), observeGoogleGenAI(), and observeCohere().
import { countlyTelemetry } from "@countly/ai-sdk-vercel";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
const telemetry = countlyTelemetry({
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId,
apiBaseURL: "https://api.openai.com/v1", // optional: records which endpoint served the call
});
const { text } = await generateText({
model: openai("gpt-4o"),
prompt: "Explain quantum computing",
experimental_telemetry: { integrations: [telemetry] },
});
A multi-step generateText call produces one event per step. Calls to embed(), embedMany(), and rerank() are not generations, so they produce no events.
import { ChatOpenAI } from "@langchain/openai";
import { CountlyCallbackHandler } from "@countly/ai-sdk-langchain";
const handler = new CountlyCallbackHandler({
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId,
});
// Works with any LangChain chain, agent, or LLM
const llm = new ChatOpenAI({ model: "gpt-4o" });
const response = await llm.invoke("Hello", { callbacks: [handler] });
import { Mastra } from "@mastra/core/mastra";
import { Observability } from "@mastra/observability";
import { RequestContext } from "@mastra/core/request-context";
import { CountlyMastraExporter } from "@countly/ai-sdk-mastra";
const mastra = new Mastra({
observability: new Observability({
configs: {
default: {
serviceName: "my-ai-app",
exporters: [
new CountlyMastraExporter({
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
requestContextDeviceIdKey: "countlyDeviceId",
}),
],
},
},
}),
});
// In your request handler, pass the device ID through Mastra's request context
const ctx = new RequestContext();
ctx.set("countlyDeviceId", req.header("x-countly-device-id"));
await mastra.getAgent("intent").stream(messages, { requestContext: ctx });
The exporter must sit inside new Observability({...}) and be passed through Mastra's observability field. If you pass it directly as exporters on Mastra, no data reaches Countly.
Linking AI Calls to User Profiles
Each event carries a device ID that ties it to a profile in Countly. The AI SDK never opens a session, so it can attach AI activity to an existing profile but cannot create a real one.
Use the device ID your app already reports
Pass the same device ID that your web or mobile Countly SDK uses for that person. Any other value, such as a database ID the client SDK has never seen, a request ID, or no ID at all, creates a profile with zero sessions.
Prompt, token, and cost totals still look correct, but every user-based AI metric (e.g., AI users, adoption rate, and AI vs. non-AI comparisons) silently reads zero.
For the four most common mistakes and how to check your setup, see Attributing AI Activity to the Right User.
In a Multi-User Backend
Have your client send its Countly device ID with each request, then scope it per request with AsyncLocalStorage. The SDK calls getDeviceId for each event, so every call is attributed to the right person.
import { AsyncLocalStorage } from "node:async_hooks";
const store = new AsyncLocalStorage();
app.use((req, res, next) => {
// The same ID the client-side Countly SDK reports
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,
});
If you cannot send the client's ID to your backend, do the reverse: call Countly.change_id(yourUserId, true) in the client SDK so it adopts your ID, then pass that same ID to the AI SDK.
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(),
});
Choosing an Observability Level
The observabilityLevel setting controls how much detail leaves your application. It does not change what is measured, only what is sent.
| Level | What Is Sent | Privacy |
|---|---|---|
0 (default) |
[CLY]_llm_interaction events: tokens, cost, latency, and the names of requested tools |
No prompt text, no per-tool events |
1 |
Adds a [CLY]_llm_tool_used event per tool call |
Tool names are visible |
2 |
Adds [CLY]_llm_tool_usage_parameter events with tool argument values, plus previews of prompts and responses (200 characters by default) |
Prompt text leaves your application |
We recommend starting at level 1. Use level 2 only when you need to debug individual conversations.
Level 2 data cannot be masked on the Server
Countly's server-side data masking does not currently cover the AI event fields. Text previews, tool argument values, and feedback comments stay unmasked even when masking is enabled. If prompt text must not leave your infrastructure, keep level 2 off.
Flushing Before Your Process Exits
The SDK buffers events and sends them every 10 seconds or every 20 events, whichever comes first. Its timer does not keep your process alive, so a script, cron job, or serverless function can exit before the last batch is sent.
In short-lived processes, flush explicitly before exiting. The Vercel AI SDK, LangChain, LlamaIndex, and Mastra integrations all expose the same two methods:
await telemetry.flush(); // send buffered events now
await telemetry.shutdown(); // flush, then stop sending
On Mastra, shutdown() also sends any turn that is still running, marked as status: "incomplete", so nothing is lost or misreported.
Verifying the Integration
You can confirm that AI calls reach Countly and attach to the right profile in about five minutes.
- Add
debug: trueto your configuration. The SDK then logs transport errors and dropped batches. - Make one instrumented AI call, and note the device ID you passed.
- Wait up to 10 seconds for the batch to be sent, or call
flush(). - In Countly, open User ProfilesProfiles and search for that exact device ID.
| 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 profile. |
| The profile exists but has zero sessions and was created by your AI call | ID mismatch. Revisit Linking AI Calls to User Profiles. |
| No profile at all |
The data never arrived. Check the debug logs, the onDropped callback, and transport.stats(). |
Configuring Common Options
All adapters accept the same configuration fields. The most commonly used ones are listed below.
| Field | Default | Description |
|---|---|---|
appKey |
Required | Your Countly app key |
url |
Required | Your Countly Server URL |
getDeviceId |
None | Function that returns the device ID for each event |
deviceId |
None | Static device ID, used when getDeviceId is not set |
observabilityLevel |
0 |
0, 1, or 2, as described above |
tags |
[] |
Labels for cost attribution and filtering |
environment |
"production" |
Environment label, e.g., production, staging, or development |
costModel |
None | Custom pricing per model, in dollars per million tokens |
trackAPM |
true |
Send latency traces to Performance Monitoring (Enterprise only)Send latency traces. Countly 27.0 does not store them: latency reaches AI Analytics on the interaction events |
debug |
false |
Log transport errors and dropped batches |
disabled |
false |
Turn off all tracking without removing the wrapper |
To price a fine-tuned or unlisted model, add it to costModel. 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: {
"ft:gpt-4o-mini:my-org": { input_per_mtok: 0.3, output_per_mtok: 1.2 },
},
});
FAQ and Troubleshooting
Why Do I Get 403 Errors From My Self-Hosted Countly Server?
Your url most likely points to an endpoint that requires authentication. Set it to the endpoint that accepts SDK data without a server-side token, which is typically your frontend endpoint. Countly Cloud users (*.count.ly) do not need to change anything.
Why Do I See Prompts and Cost but Zero AI Users?
The device ID you pass does not match the one the rest of your Countly setup reports. The volume numbers count every event, but user-based metrics only count profiles that have sessions. Follow Verifying the Integration to confirm, then fix the ID as described in Attributing AI Activity to the Right User.
If your application is backend-only, such as a batch pipeline or an internal agent, no profile has sessions. In that case, a zero means your app has no session-bearing users, not that nobody adopted AI.
Why Do My OpenAI Streaming Calls Show No Tokens or Cost?
OpenAI only reports token usage for streams when you ask for it. Add stream_options to your streaming calls:
const stream = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello" }],
stream: true,
stream_options: { include_usage: true },
});
Why Do Some of My Calls Have No Cost?
The model is not in the built-in pricing table. Instead of reporting a misleading $0, the SDK omits the cost fields and sets cost_priced to unpriced_model. Add the model to costModel to price it. When the provider reports no token usage at all, cost_priced is no_usage.
Why Is My Tool Call Status "Unknown"?
With the OpenAI, Anthropic, Google GenAI, and Cohere adapters, the SDK sees the model request a tool, but your code runs that tool, so the outcome is not observable. The SDK records unknown rather than assuming success. The Vercel AI SDK, LangChain, LlamaIndex, and Mastra integrations report the real outcome and duration.