Integrating the Countly AI SDK with Vercel AI SDK

The Countly AI SDK integration for the Vercel AI SDK tracks your generateText and streamText calls without wrapping your model or provider. You create a telemetry integration with countlyTelemetry() and hand it to each call through the AI SDK's own experimental_telemetry option.

From then on, every step of every call reaches your Countly Server with its tokens, cost, latency, and tool outcomes. This article covers the setup, what the integration records, the behavior that is specific to the Vercel AI SDK, 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:

  • The Vercel AI SDK (the ai package), version 4.0.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 Vercel AI SDK adapter. The shared core package, @countly/ai-sdk-core, is installed automatically, and no other Countly SDK is required.

npm install @countly/ai-sdk-vercel

The package is named @countly/ai-sdk-vercel.

Wiring Up the Integration

Create the integration once with your Countly settings, then pass it in the integrations list of experimental_telemetry on each call you want to track. The only required settings are appKey and url.

import { countlyTelemetry } from "@countly/ai-sdk-vercel";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

const telemetry = countlyTelemetry({
  appKey: "YOUR_APP_KEY",
  url: "https://your-countly-server.com",
  getDeviceId: () => store.getStore()?.countlyDeviceId, // see "Passing the Device ID"
  apiBaseURL: "https://api.openai.com/v1", // optional: see "Recording the API Endpoint"
});

const { text } = await generateText({
  model: openai("gpt-4o"),
  prompt: "Explain quantum computing",
  experimental_telemetry: { integrations: [telemetry] },
});

streamText takes the same experimental_telemetry option. A call without it is not tracked.

Use countlyTelemetry(), not CountlySpanProcessor

The package still exports CountlySpanProcessor for backward compatibility, but it is a no-op. The Vercel AI SDK no longer uses an OpenTelemetry span processor, so that class records nothing and only logs a deprecation warning.

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 integration 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.

Recording the API Endpoint

The AI SDK's telemetry events do not include the provider client's baseURL, so the integration cannot see which endpoint served a call. If you want that recorded, pass the same base URL your provider client uses as apiBaseURL.

The integration uses it only to classify api_host_type as vendor_direct, azure_openai, gateway, or local_infra, and to send the bare hostname as api_host. The path, query string, and any credentials in the URL are never sent. Without apiBaseURL, api_host_type is unknown and api_host is omitted.

Understanding the Captured Data

Each step of a tracked call becomes one [CLY]_llm_interaction event. Its main fields are listed below.

Field What It Holds
run_id The same value on every step of one generateText or streamText call
generation_index The step number, starting at 0
latency_total How long this step took
run_latency_total How long the whole call took, end to end
usage_input, usage_output The provider's token totals: input includes both cache buckets, and output includes reasoning
usage_cache_read, usage_cache_write, usage_reasoning Subsets of the totals above, so the cache premium is billed exactly once
tools_requested, tool_request_count Which tools the step asked for, and how many calls it asked for
Request settings (e.g., config_temperature) The temperature, top_p, max_tokens, and penalty settings of the call
api_host_type, api_host The endpoint that served the call, when you pass apiBaseURL

Each event also records the model, provider, finish reason, status, and cost, and errors are tracked as well. The rest of what the integration sends depends on your observability level:

  • Tool calls: at level 1 and above, each tool call also produces a [CLY]_llm_tool_used event. Its outcome (success or error) and duration come from the AI SDK's onToolCallFinish callback, so they are real observations. A tool whose outcome was never observed is recorded as unknown, never as a success.
  • Text: at level 2, the events also carry previews of the prompt, the answer, and any reasoning text.

Calls to embed(), embedMany(), and rerank() are model calls but not generations, so they send nothing at all. This is deliberate: an event for them would have no model and no tokens.

The integration never fills in a value the AI SDK did not report. The field is omitted instead, and the event's usage_state and cost_priced markers say why.

Understanding Vercel AI SDK Behavior

Getting One Event per Step

An event is one LLM generation, not one call. A multi-step generateText call that uses tools runs several generations, so it sends one event for each step. Each event carries that step's own model, tokens, finish reason, tool calls, and latency.

The integration deliberately ignores the AI SDK's totalUsage. Summing every step into one event is what used to make cost per prompt and latency percentiles wrong. To analyze a whole call, group its events by run_id: add up the steps' tokens and cost, and read the call's duration from run_latency_total.

Counting prompts

Because a tool-using call sends several events, the number of [CLY]_llm_interaction events is the number of generations. To count prompts, count distinct run_id values.

Measuring Latency

The integration measures latency from the AI SDK's own lifecycle callbacks. Each step's latency_total is exact, even when many calls are in flight at the same time.

The call's duration is harder. run_latency_total, and the first step's own latency_total, depend on pairing the call's start event with its finish event. AI SDK v6 integration events carry no call ID, so when two calls overlap, that pairing cannot be known. In that case, the integration omits the value rather than guessing it.

On a busy server, expect some events without run_latency_total, and keep in mind that they come from the moments when calls overlap.

Time to first token is not available. The AI SDK's integration events do not expose per-chunk timing, so latency_ttft is absent, even for streamText.

Flushing Before Shutdown

The integration 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 telemetry.flush();    // send buffered events now
await telemetry.shutdown(); // flush, then stop the transport

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. This section shows the two ways to get that ID. 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 for each request or message, return it from getPromptId. The integration calls it once per tracked call, and every step of that call uses the returned value as its run_id. Return undefined to fall back to a generated ID.

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

const telemetry = countlyTelemetry({
  appKey: "YOUR_APP_KEY",
  url: "https://your-countly-server.com",
  getPromptId: () => promptStore.getStore()?.promptId, // undefined means a generated ID
});

promptStore.run({ promptId: myMessageId }, async () => {
  await generateText({
    model: openai("gpt-4o"),
    prompt: "Explain quantum computing",
    experimental_telemetry: { integrations: [telemetry] },
  });
});

Your ID is then on every event of that call, so you can record feedback against myMessageId directly.

Recording Feedback

Without your own ID, capture the generated one with the onPrompt callback, which fires once per step. Then record feedback with createFeedbackTracker, which this package re-exports, so no extra install is needed.

import { countlyTelemetry, createFeedbackTracker } from "@countly/ai-sdk-vercel";

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

let lastPrompt;
const telemetry = countlyTelemetry({
  ...countly,
  onPrompt: (info) => { lastPrompt = info; }, // fires once per step
});

const feedback = createFeedbackTracker(countly, { sdk_adapter: "ai-sdk" });

// 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 step of a multi-step call instead, pass that step's event_id as prompt_id, together with its run_id.

Verifying the Integration

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

  1. Add debug: true to your countlyTelemetry() settings. The integration then logs transport errors and dropped batches.
  2. Make one generateText call that uses a tool, so that it takes at least two steps, and note the device ID you passed.
  3. Call await telemetry.flush(), or wait up to 10 seconds.
  4. In Countly, find the [CLY]_llm_interaction events for that device ID. You should see one event per step, all with the same run_id, 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 the events carry api_host_type: unknown, you have not passed apiBaseURL. 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 Tokens or Cost?

The integration omits a value it could not observe instead of reporting 0, and the markers on the event tell you why. When cost_priced is unpriced_model, the model is not in the built-in pricing table. When it is no_usage, the provider reported no token usage for that step. To price an unlisted or fine-tuned model, add it to costModel, in dollars per million tokens:

const telemetry = countlyTelemetry({
  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?