Integrating the Countly AI SDK with LangChain

The Countly AI SDK integration for LangChain is a callback handler. You pass CountlyCallbackHandler in the callbacks option of a chain, agent, or model call, and it reports every real LLM run inside that call to your Countly Server, with its tokens, cost, latency, and tool outcomes.

This article covers the setup, what the handler records, the behavior that is specific to LangChain, and how to confirm that it works. For an introduction to the Countly AI SDK as a whole, see Tracking LLM Usage with the Countly AI SDK.

Prerequisites

Before you start, make sure you have the following:

  • LangChain (the @langchain/core package), version 0.3.0 or later.
  • Node.js 20.19 or later (or 22.12 or later on the 22.x line). The package is ESM-only, so if you bundle to CommonJS, your bundler must inline it.
  • Your app key and Server URL: both come from the Countly app you want to send AI data to. See Getting Started with SDKs 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.

Installing the Package

Install the LangChain adapter. The shared core package, @countly/ai-sdk-core, is installed automatically, and no other Countly SDK is required.

npm install @countly/ai-sdk-langchain

Wiring Up the Callback Handler

Create the handler once with your Countly settings, then pass it in the callbacks option of each call you want to track. The only required settings are appKey and url. The handler works with any LangChain chain, agent, or LLM.

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, // see "Passing the Device ID"
});

const result = await chain.invoke(input, { callbacks: [handler] });

A model can be tracked on its own in the same way:

import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({ model: "gpt-4o" });
const response = await llm.invoke("Hello", { callbacks: [handler] });

The handler groups a turn by LangChain's root run, which is the outermost chain or agent run it sees. Pass it to the outermost call of a turn, so that every model and tool run inside that call belongs to the same turn.

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, your token and cost totals look right while every user-based AI metric reads zero.

In a backend that serves many people at once, have the client send its Countly device ID with each request, and scope it to the 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);
});

The handler calls getDeviceId each time it records an event, so every call is attributed to the person who made it. For the full rule, the common mistakes, and the browser setup, see Attributing AI Activity to the Right User.

Grouping Turns into Conversations

The handler fills in thread_id from the run's metadata. It looks for any of these keys: thread_id, threadId, session_id, sessionId, or conversation_id. Nothing else in LangChain's callback data can identify a conversation, so without one of these keys, thread_id stays empty.

const result = await chain.invoke(input, {
  callbacks: [handler],
  metadata: { thread_id: conversationId },
});

LangGraph already puts its configurable.thread_id into the run metadata, so a LangGraph thread becomes the thread_id with no extra step. A thread is a conversation, not a person: keep using the device ID for the person.

Understanding the Captured Data

Each real LLM run becomes one [CLY]_llm_interaction event. LangChain only dispatches the relevant callback around an actual model invocation, so a chain, agent, or retriever step never produces an event of its own. Its main fields are listed below.

Field What It Holds
model The real model ID, read from the response metadata, invocation_params, or the model's constructor fields
provider_metadata.lc_class The LangChain class name, e.g., ChatOpenAI, which is never used as the model
provider The vendor, inferred from the model ID, or unknown when it cannot be resolved
run_id, trace_id The same values on every generation of one chain or agent turn
generation_index The generation's position in the turn, starting at 0
span_id, parent_span_id LangChain's run hierarchy
usage_input, usage_output Token totals from LangChain's standardized usage_metadata, with cache read, cache write, reasoning, and audio subsets
tools_requested, tool_request_count Which tools the generation asked for, and how many calls it asked for
api_host_type, api_host The endpoint, classified from the client's baseURL in the model's constructor fields
thread_id The conversation, from the run's metadata

Each event also records the finish reason, status, cost, and request settings. The rest depends on your observability level and on what LangChain reports:

  • Tool calls: at level 1 and above, each tool call also produces a [CLY]_llm_tool_used event, and level 2 adds a [CLY]_llm_tool_usage_parameter event per argument. The outcome, duration, and error come from LangChain's handleToolEnd and handleToolError callbacks, so they are real observations. An outcome the handler never saw is recorded as unknown, never as a success.
  • Text: at level 2, the events also carry previews of the prompt and the answer.
  • Errors: LLM errors and tool errors are tracked separately.

A chain that runs tools but never calls a model sends no [CLY]_llm_interaction event. Its tool events are still sent, grouped by run_id.

The handler never fills in a value LangChain did not report. When the provider reports no token usage, the token and cost fields are omitted, and the event is marked usage_state: "not_reported" and cost_priced: "no_usage", rather than showing 0 tokens and $0. Only the host of baseURL is sent: the path, query string, and any credentials never leave your application.

Understanding LangChain Behavior

Holding Generations Until Their Tools Finish

A tool runs after the generation that requested it. So when a generation inside a chain requests tools, the handler holds its event until the tool outcomes arrive, and only then sends it.

A held generation is released by the first of these:

  • The next generation of the same turn.
  • The end of the chain.
  • A call to flush() or shutdown().

The event is stamped with the time of the real model call, not the time it was sent, so timelines in Countly stay correct. However, a held generation lives only in memory until it is released, which is why flushing matters more with LangChain than with most frameworks.

Measuring Latency and Streaming

Each event's latency_total is the duration of that LLM run. With LangChain, run_latency_total is the same value as latency_total, so it describes the generation, not the whole turn.

Streaming calls are tracked, but LangChain reports only the final aggregated output to the handler. Time to first token is not available, so latency_ttft is absent.

Flushing Before Shutdown

The handler 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.

await handler.flush();    // release held generations, then send buffered events
await handler.shutdown(); // flush, then stop the transport

Call flush() or shutdown() before your process exits

Without it, any generation still waiting for its tool outcomes is lost, along with every event the transport has not sent yet. This applies to every short-lived process, and to a long-running server when it stops.

Use flush() when the process keeps running afterward, and shutdown() when it is about to exit. If you record feedback, the feedback tracker has its own flush() and shutdown() methods, so call those as well.

Correlating Feedback with a Turn

Feedback, such as a thumbs up or thumbs down on an answer, is not collected automatically. You record it from your UI against the turn it rates, and the turn is identified by its run_id. By default, that is LangChain's root run ID, so every generation and tool call of one turn already shares it. For ratings, scores, categories, and comments in depth, see Collecting User Feedback on AI Responses.

Supplying Your Own Turn ID

If you already create your own ID upstream, e.g., a request ID shared across services, or one that must span several separate chain invocations, return it from getPromptId. It then becomes the turn's run_id instead of the root run ID. Return undefined to fall back to the default.

import { AsyncLocalStorage } from "node:async_hooks";
const promptStore = new AsyncLocalStorage();

const handler = new CountlyCallbackHandler({
  appKey: "YOUR_APP_KEY",
  url: "https://your-countly-server.com",
  getPromptId: () => promptStore.getStore()?.promptId, // undefined means the default
});

promptStore.run({ promptId: "chat-req-42" }, () =>
  chain.invoke(input, { callbacks: [handler] }),
);

The handler calls getPromptId once for every event it sends, including interaction, error, and run-scoped tool events. Your ID is then on all of them, so you can record feedback against it directly.

Recording Feedback

Without your own ID, capture the default one with the onPrompt callback, which fires after every tracked LLM call. Then record feedback with createFeedbackTracker, which this package re-exports, so no extra install is needed.

import { CountlyCallbackHandler, createFeedbackTracker } from "@countly/ai-sdk-langchain";

const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };

let lastPrompt;
const handler = new CountlyCallbackHandler({
  ...countly,
  onPrompt: (info) => { lastPrompt = info; }, // fires after every tracked LLM call
});

const feedback = createFeedbackTracker(countly, { sdk_adapter: "langchain" });

// Later, when the person rates the answer
feedback.track({
  prompt_id: lastPrompt.prompt_id, // the turn's run_id
  rating: "thumbs_up",
  deviceId: countlyDeviceId, // the same device ID as the interaction
});

In a real app, store prompt_id alongside the rendered message, or return it to your client, and read it back when the person rates the answer. Passing prompt_id rates the whole turn. To rate one generation instead, pass its event_id as prompt_id, together with its run_id.

Verifying the Integration

You can confirm that generations arrive, group correctly, and attach to the right profile in a few minutes.

  1. Add debug: true to your handler settings. The handler then logs transport errors and dropped batches.
  2. Run one agent or chain turn that calls a tool, and note the device ID you passed.
  3. Call await handler.flush(). This also releases any generation that is still being held.
  4. In Countly, find the [CLY]_llm_interaction events for that device ID. You should see one event per LLM run, all with the same run_id, a real model ID in model, and generation_index values of 0, 1, and so on.
  5. Open User ProfilesProfiles and search for the device ID. The profile should already have sessions from your client-side Countly SDK.

If each generation has its own run_id, check that you passed the handler to the outermost call of the turn. If a profile exists but has zero sessions, the device ID does not match your client-side Countly SDK. For a general checklist, 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 I Get ERR_MODULE_NOT_FOUND When I Import the Package?

You are most likely on version 0.0.4 or 0.0.5. Both threw ERR_MODULE_NOT_FOUND on a plain Node.js import, and only worked through a bundler. Upgrade to 0.0.6 or later, where every internal import resolves correctly in plain Node.js.

How Do I Use the Package From a CommonJS Project?

The package is ESM-only, so a bundler that outputs CommonJS must inline it rather than leave it as an external require. With tsup or esbuild, match the whole @countly/ai-sdk- scope:

// tsup.config.ts
import { defineConfig } from "tsup";

export default defineConfig({
  format: ["cjs"],
  noExternal: [/^@countly\/ai-sdk-/], // ESM-only: inline into the CommonJS bundle
});

Why Do Some Events Have No Cost?

The handler omits a value it could not observe instead of reporting 0, and the cost_priced marker tells you why. When it is no_usage, the provider did not report token usage to LangChain. When it is unpriced_model, the model is not in the built-in pricing table. To price an unlisted or fine-tuned model, add it to costModel, in dollars per million tokens:

const handler = new CountlyCallbackHandler({
  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 },
  },
});

Related Resources

Was this page helpful?
Reach out to us for any other questions.
Helpful?

Looking For More Help?