The Countly AI SDK adapter for Cohere wraps your cohere-ai client and sends the token usage, cost, latency, tool calls, and errors of every chat generation to your Countly Server. It supports both the v2 and v1 chat APIs, streamed or not, and you keep calling the client exactly as before.
This article covers installing and wrapping the client, how streams are tracked, which endpoints are not tracked, and what each event contains. For a general introduction to the SDK, see Tracking LLM Usage with the Countly AI SDK.
Prerequisites
Before you start, make sure you have the following:
-
cohere-ai7.0.0 or later: the adapter declares it as a required peer dependency. - 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 Countly 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 Integration
Installing the Adapter
npm install @countly/ai-sdk-cohere
The shared core package, @countly/ai-sdk-core, is installed automatically.
Wrapping the Client
Pass your Cohere client to observeCohere() with your Countly configuration. The only required fields are appKey and url. The wrapped client has the same API as the original, so the rest of your code does not change.
import { CohereClient } from "cohere-ai";
import { observeCohere } from "@countly/ai-sdk-cohere";
const cohere = observeCohere(new CohereClient({ token: process.env.CO_API_KEY }), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId, // see "Passing the Device ID"
});
// Use the client exactly as before. Tracking is automatic.
const response = await cohere.v2.chat({
model: "command-r-plus",
messages: [{ role: "user", content: "Hello" }],
});
If you use CohereClientV2, wrap it the same way. Its top-level chat() and chatStream() are tracked.
import { CohereClient } from "cohere-ai";
import { observeCohere } from "@countly/ai-sdk-cohere";
const cohere = observeCohere(new CohereClient({ token: process.env.CO_API_KEY }), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId,
});
const response = await cohere.chat({
model: "command-r",
message: "Hello",
});
Instrumentation is isolated from the provider call. A tool call whose arguments the model emitted as malformed JSON, for example, still produces an event and never crashes your code.
Passing the Device ID
Every event carries a device ID that ties it to a profile in Countly. It must be the same ID your web or mobile Countly SDK already uses for that person. Otherwise, token and cost totals look correct while every user-based AI metric reads zero.
In a multi-user backend, have your client send its Countly device ID with each request, and scope it per 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
store.run({ countlyDeviceId: req.header("x-countly-device-id") }, next);
});
For browser setups, account switching, and how to check the result, see Attributing AI Activity to the Right User.
Tracking Streamed Responses
chatStream() and v2.chatStream() are tracked with no extra configuration:
const stream = await cohere.v2.chatStream({
model: "command-r-plus",
messages: [{ role: "user", content: "Hello" }],
});
for await (const event of stream) {
// render the event
}
The adapter builds the event from the stream itself: content-delta, tool-call-*, and message-end on v2, or stream-end on v1. It sends the event once the stream finishes, with the same usage, cost, tool, and finish reason data as a non-streamed call, plus time to first token as latency_ttft.
If your code abandons a stream halfway, the event is recorded with status: "incomplete". Cohere still bills the tokens, but the event only claims what the adapter observed.
Understanding What Is Tracked
Tracked vs. Untracked Surfaces
The adapter tracks chat generations only. Every other method passes through the wrapper untouched and produces no events.
| Surface | Status |
|---|---|
v2.chat, v2.chatStream
|
Tracked |
chat, chatStream (v1 API, or v2 on CohereClientV2) |
Tracked |
embed, rerank, classify, and other non-generation endpoints |
Not tracked: not generations |
Understanding the Captured Data
Each tracked generation becomes one [CLY]_llm_interaction event. The adapter reads token usage from either response shape, usage.tokens on v2 or meta.tokens on v1, and maps it onto the same totals every Countly AI SDK adapter uses:
| Event Field | What It Holds |
|---|---|
usage_input, usage_output
|
Input and output token totals |
usage_cache_read |
Cached input tokens, from cachedTokens. A subset of usage_input. |
usage_cache_write |
Not reported. Cohere has no cache-creation billing bucket, so the field is absent, which is not the same as 0. |
usage_reasoning |
Not reported. Cohere does not return a separate reasoning token count. |
Each event also carries the following:
-
Cost: calculated from built-in model pricing, with
cost_pricedstating whether the model had a price. -
Latency:
latency_totalin whole milliseconds, pluslatency_ttftfor streams. -
Endpoint:
api_host_type(e.g.,vendor_direct,gateway, orlocal_infra) and the bare hostname inapi_host, read fromoptions.baseURLorclient.baseUrl, or the Cohere production URL when you configure neither. The path, query, and credentials are never sent. -
Finish reason: normalized from Cohere values such as
COMPLETE,MAX_TOKENS,STOP_SEQUENCE,TOOL_CALL, andERROR. -
Tool calls: in both the function and legacy formats, with the provider's
call_id. If the model emits a tool's arguments as malformed JSON, the tool still gets an event, since its name is valid data, and the number of unparsed arguments is reported inprovider_metadata. - Errors: categorized, and sent to Crash AnalyticsCrashes.
- Performance Monitoring traces and per-person token and cost counters. Traces require Countly Enterprise.Per-person token and cost counters.
At observability level 2, the event also carries the text output, and the model's toolPlan and thinking blocks as text_reasoning. At lower levels, no text leaves your application.
Collecting Feedback and Supplying Your Own Prompt ID
User feedback, such as a thumbs up or thumbs down on an answer, is not collected automatically. You capture the prompt_id of each call with the onPrompt callback, then record feedback against it with createFeedbackTracker, which this package re-exports.
If your app already has an ID for the interaction, such as a request ID or a trace ID, return it from getPromptId. The adapter uses it as the run_id of every event in that turn, and falls back to a generated ID whenever the callback returns undefined. You can then record feedback against your own ID without waiting for onPrompt:
import { CohereClientV2 } from "cohere-ai";
import { observeCohere, createFeedbackTracker } from "@countly/ai-sdk-cohere";
const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };
const cohere = observeCohere(new CohereClientV2({ token: process.env.CO_API_KEY }), {
...countly,
getPromptId: () => requestStore.getStore()?.requestId,
});
const feedback = createFeedbackTracker(countly, { sdk_adapter: "cohere" });
// Later, when the person rates the answer, pass the same request ID
// and the same device ID as the interaction:
feedback.track({
prompt_id: requestId,
rating: "thumbs_up",
deviceId: countlyDeviceId,
});
To group the events of one turn in Countly, use run_id. On the [CLY]_llm_interaction event itself, prompt_id points at that event's own event_id. For ratings, scores, categories, and comments, see Collecting User Feedback on AI Responses.
Verifying the Integration
- Add
debug: trueto your configuration. The SDK then logs transport errors and dropped batches. - Make one
v2.chat()call, and note the device ID you passed. - Keep the process running for at least ten seconds. Events are sent every ten seconds or every 20 events, whichever comes first, and the send timer does not keep your process alive, so a one-off script can exit before the batch leaves.
- In Countly, open User ProfilesProfiles and search for that exact device ID. The profile should already exist and have sessions from your client-side Countly SDK.
If the profile exists but has zero sessions, the device ID does not match your client-side SDK. If there is no profile at all, the event never arrived: check the debug output, and add an onDropped callback to your configuration to see events that were discarded.
FAQ and Troubleshooting
Why Does My Endpoint Show as "unknown" on Bedrock or SageMaker?
You route Cohere requests through a fetcher or fetch override, as the Bedrock and SageMaker setups do. The override sends the request somewhere else without recording where, so the adapter cannot see the real endpoint and reports api_host_type as unknown rather than guessing.
Why Do Some of My Cohere 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. To price it, add the model to costModel, in dollars per million tokens:
observeCohere(new CohereClient({ token: process.env.CO_API_KEY }), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
costModel: {
"YOUR_MODEL_NAME": { input_per_mtok: 0.5, output_per_mtok: 1.5 },
},
});
When the response reports no usage at all, the token fields are omitted too, never zeroed, and usage_state is not_reported. For how cost is calculated, see Understanding and Customizing AI Cost Calculation.
Why Is My Tool Call Status "Unknown"?
The Cohere response carries the model's request to call a tool, never its outcome, because your code runs the tool. The adapter records status: "unknown" rather than claiming a success it never observed.
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.