The Countly AI SDK Anthropic adapter wraps your existing Anthropic client and reports every Claude model call it makes to your Countly Server. You keep calling the Messages API exactly as before, and the adapter records token usage, cost, latency, tool use, and errors in the background.
This article walks you through installing the adapter, wrapping the client, and handling both streaming surfaces. It also lists which Anthropic entrypoints are tracked, what the adapter can and cannot observe, and how to confirm that data arrives.
Before you start
This article covers the Anthropic 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 Anthropic TypeScript SDK:
@anthropic-ai/sdk0.30.0 or later. The adapter is tested against 0.88.x. The 0.30.0 floor is not yet exercised in CI, so treat older 0.x versions as untested rather than verified. - 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 Anthropic 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-anthropic
Wrapping the Anthropic Client
Pass your Anthropic client to observeAnthropic() 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 Anthropic from "@anthropic-ai/sdk";
import { observeAnthropic } from "@countly/ai-sdk-anthropic";
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);
});
const anthropic = observeAnthropic(new Anthropic(), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId,
observabilityLevel: 1, // also send one event per tool call
tags: ["chatbot", "customer-support"],
environment: "production",
});
// Use the client exactly as before. Tracking is automatic.
const message = await anthropic.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello" }],
});
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 the browser and multi-user backend patterns.
Tracking Streamed Responses
Both Anthropic streaming surfaces are tracked, and the adapter reports the call once the stream ends, however you consume it.
// messages.stream(): reported whether you use finalMessage(), finalText(),
// done(), a plain for await loop, or an .on("finalMessage") handler
const stream = anthropic.messages.stream({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello" }],
});
const finalMessage = await stream.finalMessage();
// messages.create() with stream: true: the event is built from the raw event stream
const raw = await anthropic.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello" }],
stream: true,
});
for await (const event of raw) {
// handle each event as usual
}
With messages.create() and stream: true, the adapter reads usage from message_start and the stop reason and output tokens from message_delta. It passes controller, tee(), and toReadableStream() through untouched.
Abandoned streams carry no usage
A stream you abandon early, e.g., with break, is still recorded as status: "incomplete", but with no token usage or cost. Anthropic only reports output tokens in message_delta, and pricing the input alone would present a partial cost as a complete one.
Checking Which Calls Are Tracked
The adapter tracks the Messages API. The table lists every entrypoint the adapter documentation names.
| Entrypoint | Tracked? | Notes |
|---|---|---|
client.messages.create() |
Yes | Including stream: true
|
client.messages.stream() |
Yes | Reported however you consume the stream |
client.beta.messages |
No | Generations produce no events |
client.messages.batches |
No | Generations produce no events |
client.completions |
No | Generations produce no events |
Set debug: true in your configuration, and the SDK warns once when your code touches one of the untracked entrypoints.
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_inputis Anthropic's total input count, including bothcache_read_input_tokensandcache_creation_input_tokens, so it reconciles with the Anthropic Console. The cache read and cache write counts are reported as subsets, and the fresh remainder is reported separately asusage_input_fresh. -
Cost: calculated from built-in model pricing. When a model is not in the pricing table, the cost fields are omitted and
cost_priced: "unpriced_model"says why, instead of a misleading $0. - Latency: total duration, plus time to first token for streamed calls, measured from the first content event.
-
Tool calls: client
tool_useblocks,mcp_tool_useblocks, and the built-inserver_tool_usetools, each with itscall_id. Web search and web fetch are reported asretrieval, and the code execution tools ascode_interpreter. Separate tool events are sent at observability level 1 or higher. -
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. -
Request configuration, such as
temperature. - Errors with categorization, latency traces for Performance Monitoring (Enterprise only), and per-profile token and cost counters.Errors with categorization, and per-profile token and cost counters.
Uncaptured Data
-
Client tool outcomes: a
tool_useblock is the model requesting a tool, and its result travels in your next request. The tool event therefore carriesstatus: "unknown"rather than an assumed success. Server tools and MCP tools return their result in the same message, so those events carry the real outcome. - Reasoning tokens: Anthropic does not report thinking tokens separately from output, so there is no reasoning subset. Thinking text is not sent as a preview field either.
- Frequency and presence penalties: these are not part of the Anthropic API, so they never appear in the request configuration.
- Audio and image tokens: the adapter does not break out modality tokens.
-
Conversation, agent, and workflow names:
thread_id,agent_name, andworkflow_nameare not available from a wrapped client. - Any call made through an untracked entrypoint, as listed in the table above.
Configuring the Adapter
The adapter accepts the same configuration object as every other Countly AI SDK adapter. These are the fields you are most likely to set:
| Field | Default | Description |
|---|---|---|
appKey |
Required | Your Countly app key |
url |
Required | Your Countly Server URL |
getDeviceId |
None | Function that returns the device ID, called for each event when it is recorded |
deviceId |
None | Static device ID, used when getDeviceId is not set |
observabilityLevel |
0 |
0 sends metrics only, 1 adds tool calls, and 2 adds text previews |
tags |
[] |
Labels for cost attribution |
environment |
"production" |
Environment label |
costModel |
None | Custom pricing overrides |
getPromptId |
None | Function that returns your own turn ID. The value becomes the event's run_id, and returning undefined falls back to an auto-generated ID |
The adapter also accepts debug and onPrompt, which this article uses below.
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. The adapter stamps it on both streamed and non-streamed calls as run_id, and you pass the same value as prompt_id when you record feedback. It also lets you match the event against your own logs.
import Anthropic from "@anthropic-ai/sdk";
import { observeAnthropic, createFeedbackTracker } from "@countly/ai-sdk-anthropic";
const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };
const anthropic = observeAnthropic(new Anthropic(), {
...countly,
getPromptId: () => store.getStore()?.messageId, // undefined falls back to an auto-generated ID
});
const feedback = createFeedbackTracker(countly, { sdk_adapter: "anthropic" });
// 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 instead of the whole turn, and the onPrompt flow in full.
Verifying the Integration
You can confirm that Anthropic 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
messages.create(), and note the device ID you passed. If you stream, let the stream finish, because an abandoned stream carries no usage. - 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?
The model is not in the built-in pricing table, so the event omits every cost field and sets cost_priced to unpriced_model. Add the model to costModel to price it. Model names are prefix-matched, so one entry covers dated versions of a model.
observeAnthropic(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 },
},
});
When Anthropic reported no usage at all, cost_priced is no_usage instead.
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 Anthropic 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.
Why Did My Anthropic Cache Costs Drop After Upgrading?
Earlier versions billed cache-write tokens on top of an input count that already contained them, which charged cache writes at 2.25x instead of 1.25x. Since schema v2 (version 0.0.6), every token is billed exactly once, so calls that write to the prompt cache now cost less than before. The new figure is the correct one.