LlamaIndex.TS reports what its models do through a callback manager. The Countly AI SDK listens on that callback manager, so every generation your queries, chat engines, and agents make reaches your Countly Server with its tokens, cost, latency, and tool calls.
This article walks you through registering the tracer, attributing each call to the right person, and covering the places where LlamaIndex does not report enough on its own, most importantly errors.
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. See Getting Started with SDKs if you do not have them yet.
- 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.
llamaindex0.8.0 or later.- 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
Install the LlamaIndex adapter. The shared core package, @countly/ai-sdk-core, is installed automatically.
npm install @countly/ai-sdk-llamaindex
Registering the Tracer
Create a CountlyLlamaIndexTracer and register it on LlamaIndex's global callback manager. You then use LlamaIndex exactly as before.
import { Settings } from "llamaindex";
import { CountlyLlamaIndexTracer } from "@countly/ai-sdk-llamaindex";
const tracer = new CountlyLlamaIndexTracer({
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId, // see "Passing the Device ID"
});
// Attach to LlamaIndex's callback manager
tracer.register(Settings.callbackManager);
register() subscribes the tracer to five callback events: llm-start, llm-stream, llm-end, llm-tool-call, and llm-tool-result. Keep a reference to the tracer. You need it to report errors, flush, and detach.
Passing the Device ID
The tracer calls getDeviceId each time it records an event. On a server that handles 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 for this person
store.run({ countlyDeviceId: req.header("x-countly-device-id") }, next);
});
The ID must be the one your web or mobile Countly SDK already reports for that person. Any other value, including your own user ID when the client SDK does not use it, creates a profile with no sessions, and every user-based AI metric then reads zero. For the full rule, the browser setup, and a five-minute check, see Attributing AI Activity to the Right User.
Captured Data
For each LLM call, the tracer sends one [CLY]_llm_interaction event with the following:
- Latency: total duration, plus time to first token.
- Tokens and cost: input and output totals, with cache read, cache write, and reasoning tokens where the provider reports them.
- Model and endpoint: the model, and which kind of endpoint served the call.
- Streamed calls: for a stream, LlamaIndex hands the tracer an array of chunks instead of the provider's response, and the tracer recovers the model and token counts from them.
At observability level 1 and above, each tool call also becomes a [CLY]_llm_tool_used event with its name, call_id, observed status, and latency, attached to the generation that requested it. At level 2, tool arguments and text previews are added. The tracer keeps concurrent calls apart, and it adds each call's tokens and cost to the person's profile.
LlamaIndex passes each provider's usage through in that provider's own shape. The tracer reads these shapes:
| Provider | What the Tracer Reads |
|---|---|
| OpenAI | OpenAI's usage object |
| Anthropic | Usage, including both cache buckets (read and write) |
| Gemini | Usage, with thoughtsTokenCount recorded as reasoning tokens |
| Cohere | meta.tokens |
Nothing is invented. A count the provider did not report is omitted, and the row carries usage_state: "not_reported". A dimension the tracer could not read carries "unknown".
Handling LlamaIndex-Specific Behavior
Reporting Errors Yourself
LlamaIndex has no error event. When a call throws, llm-end is never dispatched, so no callback listener can see the failure. If you do not hand the error to the tracer, your error rate in Countly reads a perfect zero.
try {
const response = await queryEngine.query({ query });
}
catch (err) {
tracer.recordError(err); // emits a status: "error" interaction and a crash report
throw err;
}
When a single call is in flight, the tracer attributes the failure to it, so that call's latency and prompt are kept. If you have the LlamaIndex call ID, pass it as recordError(err, { id }). If the failure happened before any call started, pass { model, provider } instead.
Grouping an Agent Loop Into a Single Run
LlamaIndex creates a fresh ID for every chat() call and exposes no turn identity. Without help, every generation is its own run: each has its own run_id, and generation_index is always 0.
To group an agent loop's generations into one run, supply getPromptId. Return an ID you already track for the request, such as a chat message ID, and the tracer uses it as the run_id of every interaction and tool event in that turn. Return undefined to keep one run per call.
app.use((req, res, next) => {
store.run({
countlyDeviceId: req.header("x-countly-device-id"),
turnId: req.body.messageId, // your own ID for this turn
}, next);
});
const tracer = new CountlyLlamaIndexTracer({
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId,
getPromptId: () => store.getStore()?.turnId,
});
tracer.register(Settings.callbackManager);
The same ID also lets you record feedback without reading an ID back first. See Collecting Feedback below.
Understanding Tool Failures
LlamaIndex dispatches llm-tool-result only when a tool returns. A tool that throws produces no event. The tracer still reports that call, with status: "unknown" rather than a success it did not see, when the next generation starts or when you call shutdown().
Detecting the API Endpoint
The tracer reads api_host_type and api_host from the LLM instance behind each event. If a provider class stores its base URL under a name the tracer does not recognize, the row reports api_host_type: "unknown" instead of a guess.
Collecting Feedback
Feedback, such as a thumbs up on an answer, is not collected automatically. Capture each call's IDs with the onPrompt callback, which fires after every tracked LLM call, then record the rating with createFeedbackTracker, which this package re-exports:
import { Settings } from "llamaindex";
import { CountlyLlamaIndexTracer, createFeedbackTracker } from "@countly/ai-sdk-llamaindex";
const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };
let lastPrompt;
const tracer = new CountlyLlamaIndexTracer({
...countly,
onPrompt: (info) => { lastPrompt = info; }, // fires after every tracked LLM call
});
tracer.register(Settings.callbackManager);
const feedback = createFeedbackTracker(countly, { sdk_adapter: "llamaindex" });
const response = await queryEngine.query({ query: "Explain quantum computing" });
// Later, when the person rates the answer:
feedback.track({
prompt_id: lastPrompt.prompt_id, // the turn's run_id
rating: "thumbs_up", // or "thumbs_down", or any custom string
deviceId: req.header("x-countly-device-id"), // the same device ID as the interaction
});
To rate one specific generation instead of the turn, pass lastPrompt.event_id as prompt_id, together with run_id. If you supply getPromptId, you can skip the read-back and pass your own ID directly, e.g., feedback.track({ prompt_id: messageId, rating: "thumbs_up" }). For ratings, scores, categories, and comments, see Collecting User Feedback on AI Responses.
Flushing and Detaching the Tracer
The tracer buffers events and sends them every 10 seconds or every 20 events, whichever comes first. Its timer does not keep your process alive, so in a script, cron job, or serverless function, flush before the process exits:
await tracer.flush(); // send buffered events
await tracer.shutdown(); // flush, then stop the transport
tracer.unregister(Settings.callbackManager); // detach the handlers
shutdown() also reports any tool call whose result never arrived, with status: "unknown". If you collect feedback, call feedback.shutdown() as well.
Verifying the Integration
- Add
debug: trueto the tracer configuration. It then logs transport errors and dropped batches. - Add an
onPromptcallback that logs its argument. It fires after every tracked LLM call, so a silent callback means the tracer is not seeing your calls. - Make one query or chat call, and note the device ID you passed.
- Wait up to 10 seconds for the batch to be sent, or call
tracer.flush(). - In Countly, open User ProfilesProfiles and search for that exact device ID. The profile should already exist, have sessions, and show the new AI activity.
If onPrompt never fires, check that you called tracer.register(Settings.callbackManager) before running the query. If the profile exists but has zero sessions, the device ID does not match the one your client SDK reports. For a general checklist, see How to Validate Your Countly SDK Integration.
FAQ and Troubleshooting
Why Do Other Examples Use CountlyEventHandler?
CountlyEventHandler is the earlier name of the same class, kept as a deprecated alias. Switch to CountlyLlamaIndexTracer and attach it with register(). Older examples that attach only handleLLMStart and handleLLMEnd to the callback manager never receive the llm-stream, llm-tool-call, or llm-tool-result events, so every tool call goes unreported.
Why Do Some of My Rows Have No Token Counts?
The provider did not report usage for that call. Instead of recording zero, the tracer omits the token fields and sets usage_state to "not_reported", so a missing count is never mistaken for a free call.
Why Do My Rows Have No Conversation or Agent Name?
The tracer cannot observe a conversation ID or an agent name through LlamaIndex's callback events, so thread_id, agent_name, and workflow_name are not populated on LlamaIndex rows. To tie a turn's generations together, use getPromptId, as described in Grouping an Agent Loop Into a Single Run.