Token counts, cost, and latency tell you what a model did. They do not tell you whether the answer helped. The Countly AI SDK can record a thumbs up, a thumbs down, a score, or a comment on any AI response, and link it back to the exact interaction it rates.
Each rating arrives in Countly as a [CLY]_llm_interaction_feedback event that joins to the rated interaction. That join is what lets you build prompt to feedback funnels and compare satisfaction by model, provider, or agent. This article shows how to capture the ID of each answer, record a rating against it, and confirm that the rating arrives.
Before you start
This article assumes you have already installed an AI SDK adapter and wrapped your AI client, as described in Tracking LLM Usage with the Countly AI SDK. It applies to every adapter: OpenAI, Anthropic, Google GenAI, Cohere, Vercel AI SDK, LangChain, Mastra, and LlamaIndex.
Understanding How Feedback Works
Feedback is not collected automatically. You wire it from your own interface, for example the thumbs up and thumbs down buttons under each answer. The flow is the same for every adapter:
- The adapter reports the ID of each generation it tracks through the
onPromptcallback. - Your app stores that ID next to the answer it shows, or returns it to the client.
- When the person rates the answer, you pass the ID to a feedback tracker, which sends a
[CLY]_llm_interaction_feedbackevent.
A rating can target a whole turn or a single generation. A turn is everything one request to your AI produced: a single wrapped-client call, or every generation of a multi-step agent run. All generations of a turn share one run_id.
| What You Rate | Pass as prompt_id | Also Pass | parent_event_key on the Row |
|---|---|---|---|
| The whole turn (default) |
PromptInfo.prompt_id, which is identical to run_id
|
Nothing | "run" |
| One generation of a multi-step turn | PromptInfo.event_id |
run_id: PromptInfo.run_id |
"[CLY]_llm_interaction" |
The parent_event_key field records which of the two you chose, so nobody analyzing the data has to guess what a rating belongs to. In most chat interfaces, a person sees one answer per turn, so rating the whole turn is the right default.
Prerequisites
Before you start, make sure you have the following:
-
A working AI SDK adapter: your AI calls already reach Countly as
[CLY]_llm_interactionevents. - A rating control in your interface: e.g., thumbs up and thumbs down buttons, a star rating, or a comment box.
- The device ID of the person giving the rating: it must be the same ID your Countly client SDK uses for that person, as explained in Attributing AI Activity to the Right User.
You do not need an extra package. Every adapter re-exports createFeedbackTracker.
Recording Feedback
Capturing the Prompt ID
Add an onPrompt callback to your adapter configuration. The SDK calls it with a PromptInfo object for every generation it records.
import OpenAI from "openai";
import { observeOpenAI, createFeedbackTracker } from "@countly/ai-sdk-openai";
const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };
let lastPrompt; // the PromptInfo of the most recent generation
const openai = observeOpenAI(new OpenAI(), {
...countly,
onPrompt: (info) => { lastPrompt = info; }, // fires once per generation
});
The PromptInfo object carries these fields:
| Field | Meaning |
|---|---|
prompt_id |
The turn. Identical to run_id. |
run_id |
The turn identity shared by every row the turn emits |
event_id |
The ID of this one generation's row |
generation_index |
The 0-based position of this generation within the turn |
provider, model, status
|
What served the generation, and how it ended |
thread_id, agent_name, workflow_name, trace_id
|
Mastra only |
onPrompt fires per generation, not per turn
In a multi-step turn, the callback runs once for each generation, and the last call describes the final generation. Its prompt_id still identifies the whole turn, but its event_id identifies only that final generation.
Store the ID next to the answer you render, for example in the message record in your database, or return it to your client with the response. Read it back when the person rates the answer.
A single shared variable such as lastPrompt is fine in a script or a browser tab. In a server that handles many people at once, an overlapping request can overwrite it before you read it. On a server, supply your own turn ID instead, as described in Supplying Your Own Turn ID below.
Creating a Feedback Tracker
Feedback usually arrives long after the AI call returned, sometimes minutes later. For that reason it has its own tracker instead of hanging off the wrapped client. Create one tracker for the life of your process, with the same app key and Server URL as your adapter.
import { createFeedbackTracker } from "@countly/ai-sdk-anthropic";
const feedback = createFeedbackTracker(
{ appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" },
{ sdk_adapter: "anthropic" }, // the adapter that produced the rated interaction
);
The second argument stamps the adapter name on every feedback row, so you can slice feedback by adapter the same way as interactions. The OpenAI package fills it in for you. With every other adapter, pass it yourself: "anthropic", "google-genai", "cohere", "ai-sdk" (Vercel AI SDK), "langchain", "llamaindex", or "mastra".
Recording a Rating
When the person rates an answer, call track() with the stored ID and the rating:
// When the person clicks thumbs up under the answer
feedback.track({
prompt_id: storedPromptId, // the prompt_id you stored with the answer
rating: "thumbs_up", // or "thumbs_down", or any custom string
score: 0.9, // optional: a number from 0 to 1
category: "helpful", // optional: e.g., hallucination, irrelevant, harmful
comment: "Great answer", // optional: free-form text
deviceId: countlyDeviceId, // the person's Countly device ID
});
| Field | Required | Description |
|---|---|---|
prompt_id |
Yes | What is rated: the turn by default, or one generation's event_id
|
run_id |
Only when rating one generation | The turn the rated generation belongs to. Defaults to prompt_id. |
rating |
Yes |
"thumbs_up", "thumbs_down", or any custom string |
score |
No | A numeric score from 0 to 1 |
category |
No | A label such as hallucination, irrelevant, or harmful
|
comment |
No | Free-form text from the person |
deviceId |
Strongly recommended | The person's Countly device ID, so the feedback lands on the same profile as the interaction |
model, provider, agent_name, workflow_name, trace_id
|
No | Describe the rated answer on the feedback row itself. Copy them from PromptInfo. |
The descriptive fields are worth passing. With model and provider on the feedback row, a satisfaction breakdown by model works without joining back to an interaction that may fall outside the time range you are looking at.
You do not set rating_kind. The SDK derives it from what you pass: binary, score, category, or other. A thumbs up or thumbs down counts as binary, so a numeric score is never averaged into a thumbs-up rate.
Pass the person's device ID on every rating
Without deviceId, the rating falls back to the tracker's own configuration and, failing that, to a random per-process ID that belongs to nobody. The feedback still arrives, but it no longer sits on the profile of the person who gave it.
Feedback comments cannot be masked on the Server
Countly's server-side data masking does not currently cover the AI event fields, and that includes the feedback comment. If comments may contain personal data that must not be stored unmasked, leave the field out or scrub it before calling track().
Rating One Generation Instead of the Whole Turn
If your interface shows the output of each step separately, for example an agent that displays intermediate answers, you can rate a single generation. Pass that generation's event_id as prompt_id, together with its run_id:
feedback.track({
prompt_id: info.event_id, // this one generation's row
run_id: info.run_id, // the turn it belongs to
rating: "thumbs_down",
deviceId: countlyDeviceId,
});
The row's parent_event_key is then "[CLY]_llm_interaction" instead of "run".
Using Mastra's Built-In Feedback
The Mastra exporter records Mastra's own signals with no extra code. Every scorer result and every recordedSpan.addFeedback() call becomes a [CLY]_llm_interaction_feedback event against the run that produced it. Use createFeedbackTracker only for feedback that comes from your own interface.
On Mastra, onPrompt fires only when a generation was actually recorded. A trace with no model call in it, such as a workflow root, never triggers it.
Flushing Feedback Before Your Process Exits
Feedback is batched like interaction events: the tracker sends every 10 seconds or every 20 events, whichever comes first. Its timer does not keep your process alive, so a script or serverless function can exit before the last rating is sent. Flush before exiting:
await feedback.flush(); // send buffered feedback now
await feedback.shutdown(); // flush, then stop the tracker
The tracker has its own buffer, separate from the adapter's. Flushing the adapter does not send pending feedback, and flushing the tracker does not send pending interactions.
Supplying Your Own Turn ID
If your app already has a stable ID for each request, such as a chat message ID or a job ID, give it to the SDK instead of capturing the generated one. Your ID becomes the run_id of every row in the turn, so you can record feedback against it directly, with no onPrompt round trip. This is also the safest pattern on a multi-user server.
Return undefined from your callback to fall back to a generated ID for that call. How you supply the ID depends on the adapter:
OpenAI, Anthropic, Google GenAI, and Cohere accept a getPromptId callback. Scope your ID to the request with AsyncLocalStorage:
import { AsyncLocalStorage } from "node:async_hooks";
const messageStore = new AsyncLocalStorage();
const openai = observeOpenAI(new OpenAI(), {
...countly,
getPromptId: () => messageStore.getStore()?.messageId, // undefined falls back to a generated ID
});
// In your request handler
await messageStore.run({ messageId }, () =>
openai.chat.completions.create({ model: "gpt-4o", messages }),
);
// Later, when the person rates the answer
feedback.track({ prompt_id: messageId, rating: "thumbs_up", deviceId: countlyDeviceId });
Without getPromptId, every call is its own turn. If your code makes several calls to answer one message, getPromptId is what groups them into one run.
const telemetry = countlyTelemetry({
...countly,
getPromptId: () => promptStore.getStore()?.promptId,
});
await promptStore.run({ promptId: messageId }, () =>
generateText({
model: openai("gpt-4o"),
prompt: "Explain quantum computing",
experimental_telemetry: { integrations: [telemetry] },
}),
);
feedback.track({ prompt_id: messageId, rating: "thumbs_up", deviceId: countlyDeviceId });
The callback is read once per generateText or streamText call, and every step of that call shares the ID. Even without it, all steps of one call already share a run_id.
const handler = new CountlyCallbackHandler({
...countly,
getPromptId: () => promptStore.getStore()?.promptId,
});
await promptStore.run({ promptId: messageId }, () =>
chain.invoke(input, { callbacks: [handler] }),
);
By default, LangChain already groups a turn under the ID of its outermost chain or agent run. Supply getPromptId when you want your own ID, or when one turn spans several separate chain invocations.
const tracer = new CountlyLlamaIndexTracer({
...countly,
getPromptId: () => promptStore.getStore()?.promptId,
});
tracer.register(Settings.callbackManager);
LlamaIndex exposes no turn identity of its own, so without getPromptId every generation becomes its own run, and generation_index is always 0. If you want to rate an agent loop as one turn, getPromptId is the only way to group its generations.
Mastra has no wrapped client, so the exporter reads your ID from Mastra's request context. Name the key with requestContextPromptIdKey, then put the ID on the context before you start the agent or workflow:
const exporter = new CountlyMastraExporter({
...countly,
requestContextDeviceIdKey: "countlyDeviceId",
requestContextPromptIdKey: "countlyPromptId",
});
// In your request handler, before the run starts
const ctx = new RequestContext();
ctx.set("countlyDeviceId", req.header("x-countly-device-id"));
ctx.set("countlyPromptId", messageId);
await mastra.getAgent("intent").stream(messages, { requestContext: ctx });
Mastra copies the request context when it creates each span, so a value you add inside a step never reaches the root span and cannot group the turn. Without this key, a workflow and the agents it calls appear as several separate runs.
Verifying Feedback
You can confirm that a rating arrives and joins the right interaction in a few minutes.
- Add
debug: trueto your adapter configuration and to the configuration you pass tocreateFeedbackTracker. The SDK then logs transport errors and dropped batches. - Make one instrumented AI call. Note its
prompt_id(or your own ID) and the device ID you passed. - Record a rating with
feedback.track(), then callawait feedback.flush(). - In Countly, find the
[CLY]_llm_interaction_feedbackevent and check that itsprompt_idandrun_idmatch the interaction you rated. - Open User ProfilesProfiles, search for the device ID, and check that the feedback sits on the same profile as the interaction.
| What You See | What It Means |
|---|---|
The feedback event's run_id matches the interaction's run_id, on a profile with sessions |
Correct. The rating is linked to the answer and to the person. |
The feedback arrives, but its run_id matches no interaction |
Wrong ID. You stored an ID from a different call, or the turn was split into several runs. Check Supplying Your Own Turn ID for your adapter. |
| The feedback sits on a profile with zero sessions | Device ID mismatch. Pass the ID your Countly client SDK uses. |
| No feedback event at all |
Not sent yet, or dropped. Call flush() and check the debug logs. |
For general checks on whether data reaches your Server, see How to Validate Your Countly SDK Integration.