The Countly AI SDK OpenAI adapter wraps your existing OpenAI client and reports every model call it makes to your Countly Server. You keep calling the OpenAI API exactly as before, and the adapter records token usage, cost, latency, requested tools, and errors in the background.
This article walks you through installing the adapter, wrapping the client, and handling streamed responses. It also lists which OpenAI entrypoints are tracked, what the adapter can and cannot observe, and how to confirm that data arrives.
Before you start
This article covers the OpenAI adapter only. For how the Countly AI SDK works across all frameworks, including observability levels and cost calculation, read Tracking LLM Usage with the Countly AI SDK first.
Prerequisites
Before you start, make sure you have the following:
-
The OpenAI Node.js SDK:
openai4.68.0 or later. - 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.
- Your app key and Server URL: both come from the Countly app you want to send AI data to. See Getting Started with SDKs for where to find them.
- Your device ID strategy: the ID your web or mobile Countly SDK already uses for each person. See Passing the Device ID below.
Setting Up the OpenAI Adapter
Installing the Adapter
Install the adapter from npm. The shared core package, @countly/ai-sdk-core, is installed automatically, and no other Countly SDK is required on the server.
npm install @countly/ai-sdk-openai
Wrapping the OpenAI Client
Pass your OpenAI client to observeOpenAI() together with your Countly configuration. It returns a client with the same interface, so the rest of your code does not change. The only required fields are appKey and url.
import OpenAI from "openai";
import { observeOpenAI } from "@countly/ai-sdk-openai";
import { AsyncLocalStorage } from "node:async_hooks";
const store = new AsyncLocalStorage();
// Run once per request: scope the caller's Countly device ID to the request
app.use((req, res, next) => {
store.run({ countlyDeviceId: req.header("x-countly-device-id") }, next);
});
// Wrap the client. getDeviceId is called for each event when it is recorded.
const openai = observeOpenAI(new OpenAI(), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId,
});
// 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" }],
});
Passing the Device ID
The device ID ties each call to a profile in Countly. It must be the same ID your web or mobile Countly SDK already uses for that person, otherwise your prompt, token, and cost totals look correct while every user-based AI metric reads zero. Attributing AI Activity to the Right User explains the rule, the common mistakes, and how to check your setup.
In the browser, each person runs in their own tab, so there is no mixing of requests between people. A static deviceId is enough:
const openai = observeOpenAI(new OpenAI(), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
deviceId: countlyDeviceId, // the ID the Countly Web SDK reports for this person
});
If the person can switch accounts without reloading the page, use getDeviceId instead, so that each call reads the current ID.
Tracking Streamed Responses
Streamed calls are tracked through the same create() method. The adapter reports the call once the stream completes.
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
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
Add stream_options to every streamed call
OpenAI only includes token usage in a stream when you pass stream_options: { include_usage: true }. Without it, the event carries usage_state: "not_reported" and no token or cost fields, rather than a zero that would read as a free call.
If you break out of the loop early, or abort with stream.controller.abort(), the call is still recorded, because OpenAI bills for everything streamed so far. The event carries status: "incomplete" and error: "stream_cancelled".
The stream() helper runners are not tracked (see the next section), so stream with create() and stream: true when you want the call in Countly.
Checking Which Calls Are Tracked
The adapter tracks the OpenAI entrypoints that generate a model response. Everything else passes through untouched.
| Entrypoint | Tracked? | Notes |
|---|---|---|
client.chat.completions.create() |
Yes | Including stream: true
|
client.chat.completions.parse() |
Yes | |
client.responses.create() |
Yes | Including stream: true
|
client.responses.parse() |
Yes | |
client.chat.completions.stream() and client.responses.stream()
|
No | These helper runners build their own request through the unwrapped client |
embeddings, moderations, files, batches, and other non-generation operations |
No, by design | An operation that generates no response never produces an interaction event |
Set debug: true in your configuration to get a one-time warning when your code accesses an untracked generation entrypoint.
Understanding the Captured Data
Each tracked call produces one [CLY]_llm_interaction event. A wrapped client sees one call at a time, so each call is its own run unless you supply your own turn ID (see Recording Feedback and Supplying Your Own Turn ID below).
Captured Data
-
Token usage:
usage_inputandusage_outputare OpenAI's totals, so input includes cached tokens and output includes reasoning tokens. The cached, reasoning, and audio subsets are reported alongside, andusage_statestates whether OpenAI reported usage at all. -
Cost: calculated from built-in model pricing.
cost_pricedstates whether the model could be priced. An unpriced model carries no cost fields instead of a misleading $0. - Latency: total duration, plus time to first token for streamed calls.
-
Request configuration:
temperature,top_p,max_tokens, and the frequency and presence penalties, on streamed calls too. -
Endpoint:
api_host_type(vendor_direct,azure_openai,gateway, orlocal_infra) andapi_host, read from the client'sbaseURL. Only the hostname is sent: the path, query, and credentials never are. -
Tool calls: the tools the model requested and their parameters, each with a
call_idso repeat calls of one tool stay distinguishable. Separate tool events are sent at observability level 1 or higher, and parameter values at level 2. -
Errors: categorized as
rate_limit,context_length,content_filter,timeout, orauth_error. - Latency traces for Performance Monitoring (Enterprise only), and per-profile token and cost counters.Per-profile token and cost counters.
Uncaptured Data
-
Function tool outcomes: your code runs the tool, so the adapter cannot see whether it succeeded. The tool's
statusisunknownrather than an assumed success. The hosted Responses API tools (MCP, file search, and code interpreter) are the exception: OpenAI returns their outcome, so they report it. -
Cache writes: OpenAI has no cache-creation billing bucket, so
usage_cache_writeis absent. Absent is not the same as zero. - Image tokens: audio is the only modality the adapter breaks out.
-
Conversation, agent, and workflow names:
thread_id,agent_name, andworkflow_nameare not available from a wrapped client. -
Streamed usage without
include_usage, and any call made through an untracked entrypoint.
Recording Feedback and Supplying Your Own Turn ID
The adapter does not collect ratings on its own. To record a thumbs up, a score, or a comment, use createFeedbackTracker, which this package re-exports, so no extra install is needed. Every feedback event must point at the call it rates, and should carry the same device ID as that call.
The simplest way to link the two is to supply your own turn ID with getPromptId, such as a chat message ID you already have. It becomes the call's run_id, and you pass the same value as prompt_id when you record feedback. Return undefined to fall back to an auto-generated ID.
import OpenAI from "openai";
import { observeOpenAI, createFeedbackTracker } from "@countly/ai-sdk-openai";
const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };
const openai = observeOpenAI(new OpenAI(), {
...countly,
getPromptId: () => store.getStore()?.messageId, // your own ID, or undefined to auto-generate
});
const feedback = createFeedbackTracker(countly);
// Later, when the person rates the answer to that message
feedback.track({
prompt_id: messageId, // the same value getPromptId returned for the call
rating: "thumbs_up",
deviceId: countlyDeviceId, // the same device ID as the rated call
});
If you do not have your own ID, capture the generated one with the onPrompt callback instead. Feedback is batched like other events. Call feedback.flush() to send it immediately, or feedback.shutdown() when your process exits. Collecting User Feedback on AI Responses covers ratings, rating one generation of a multi-call turn, and the onPrompt flow in full.
Verifying the Integration
You can confirm that OpenAI calls reach Countly and attach to the right profile in a few minutes.
- Add
debug: trueto your configuration. The SDK then logs transport errors and dropped batches, and warns about untracked entrypoints. - Make one call through a tracked entrypoint, such as
chat.completions.create(), and note the device ID you passed. If you stream, includestream_options: { include_usage: true }. - Keep the process running for at least ten seconds. The SDK sends its buffer every ten seconds or every 20 events, and a process that exits sooner can lose the batch.
- In Countly, open User ProfilesProfiles and search for that exact device ID.
If the profile exists, has sessions, and was last seen before your AI call, the integration works. A profile with zero sessions that your AI call created means the device ID does not match the one your client SDK reports. No profile at all means the data never arrived: check the debug logs, and set an onDropped callback to see discarded events. For general checks, see How to Validate Your Countly SDK Integration.
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 Some of My Calls Have No Cost?
There are two common causes:
-
The model is not in the built-in pricing table. The event omits every cost field and sets
cost_pricedtounpriced_model. Add the model tocostModelto price it. Model names are prefix-matched, so one entry covers dated versions of a model. -
OpenAI reported no usage. This is usually a streamed call without
stream_options: { include_usage: true }, andcost_pricedisno_usage.
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 },
},
});
Why Do I Lose Events From Short-Lived Processes?
The SDK keeps events in an in-memory buffer and sends it every ten seconds or every 20 events, whichever comes first. Its timer does not keep your process alive, so a script, cron job, or serverless function that exits right after its last call can exit before that batch is sent.
The wrapped OpenAI client does not expose a flush method. The feedback tracker does, so call feedback.flush() before exit if you record feedback in the same process.