The Countly AI SDK adapter for Google GenAI wraps your @google/genai client and sends the token usage, cost, latency, function calls, and errors of every Gemini generation to your Countly Server. You keep calling the client exactly as before, whether you use the Gemini API or Vertex AI.
This article covers installing and wrapping the client, how streams and chat sessions are tracked, which surfaces are not tracked, and what each event contains. For a general introduction to the SDK, see Tracking LLM Usage with the Countly AI SDK.
Prerequisites
Before you start, make sure you have the following:
-
@google/genai1.0.0 or later: the adapter declares it as a required peer dependency. - 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 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
npm install @countly/ai-sdk-google-genai
The shared core package, @countly/ai-sdk-core, is installed automatically.
Wrapping the Client
Pass your GoogleGenAI instance to observeGoogleGenAI() with your Countly configuration. The only required fields are appKey and url. The wrapped client has the same API as the original, so the rest of your code does not change.
import { GoogleGenAI } from "@google/genai";
import { observeGoogleGenAI } from "@countly/ai-sdk-google-genai";
const client = observeGoogleGenAI(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId, // see "Passing the Device ID"
});
// Use the client exactly as before. Tracking is automatic.
const response = await client.models.generateContent({
model: "gemini-2.5-pro",
contents: "Explain quantum computing",
});
Instrumentation is isolated from the provider call. If something goes wrong inside the Countly AI SDK, you lose that one event, but your Gemini call still succeeds and your code never receives an exception from the SDK.
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, token and cost totals look correct while every user-based AI metric reads zero.
In a multi-user backend, have your client send its Countly device ID with each request, and scope it per 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);
});
For browser setups, account switching, and how to check the result, see Attributing AI Activity to the Right User.
Tracking Streams and Chat Sessions
models.generateContentStream() is tracked with no extra configuration:
const stream = await client.models.generateContentStream({
model: "gemini-2.5-flash",
contents: "Hello",
});
for await (const chunk of stream) {
process.stdout.write(chunk.text || "");
}
The adapter accumulates the stream into a single event:
- Text is concatenated across chunks.
- Every
functionCallpart is collected, since these arrive before the final chunk. - Token usage is taken from the last chunk that reports
usageMetadata. Gemini reports it cumulatively, so it is never summed. - Time to first token is recorded as
latency_ttft, alongside the total latency.
If you break out of the loop early, the adapter still emits an event for the tokens the request consumed.
Chat sessions are wrapped too. Calls to sendMessage() and sendMessageStream() on a chat created with chats.create() produce the same events as models.generateContent(), and each message is counted exactly once.
const chat = client.chats.create({ model: "gemini-2.5-flash" });
const answer = await chat.sendMessage({ message: "Hello" });
Understanding What Is Tracked
Tracked vs. Untracked Surfaces
The adapter tracks generations only. Calls that do not generate content pass through the wrapper untouched and produce no events.
| Surface | Status |
|---|---|
models.generateContent, models.generateContentStream
|
Tracked |
chats.create().sendMessage, chats.create().sendMessageStream
|
Tracked |
models.embedContent, countTokens, generateImages, generateVideos
|
Not tracked: not generations |
live.* (bidirectional sessions) |
Not tracked |
caches.*, files.*, tunings.*, operations.*
|
Not tracked |
Understanding the Captured Data
Each tracked generation becomes one [CLY]_llm_interaction event. Gemini reports some of its token buckets differently from other providers, so the adapter maps them onto the same totals every Countly AI SDK adapter uses:
| Event Field | Taken From | Notes |
|---|---|---|
usage_input |
promptTokenCount + toolUsePromptTokenCount
|
Total input. promptTokenCount already includes cached tokens. |
usage_output |
candidatesTokenCount + thoughtsTokenCount
|
Total output, including thinking tokens, so they are priced |
usage_reasoning |
thoughtsTokenCount |
Subset of usage_output
|
usage_cache_read |
cachedContentTokenCount |
Subset of usage_input
|
usage_total |
Calculated by the SDK | Sum of input and output |
usage_cache_write |
Not reported | Gemini has no cache-creation billing bucket, so the field is absent, which is not the same as 0
|
Each event also carries the following:
-
Cost: calculated from built-in model pricing. When Gemini reports audio or image tokens in
promptTokensDetailsorcandidatesTokensDetails, the cost is markedpriced_modality_approxrather than presented as exact. - Latency: total duration in whole milliseconds, plus time to first token for streams.
-
Endpoint:
api_host_type(e.g.,vendor_direct,gateway, orlocal_infra) and the bare hostname inapi_host. On Vertex AI, the regional endpoint is derived from the client'svertexaiandlocationsettings. The path and query are never sent, so an API key in the URL cannot leak. -
Finish reason: Gemini values such as
STOP,MAX_TOKENS,SAFETY, andRECITATIONare normalized tostop,length,tool_calls,content_filter,error,other, ornot_reported. -
Function calls: each call the model requests, with its
call_idwhen the model supplies one. - Errors: categorized, and sent to Crash AnalyticsCrashes.
- Performance Monitoring traces and per-person token and cost counters. Traces require Countly Enterprise.Per-person token and cost counters.
Gemini also returns content-bearing metadata: groundingMetadata, citationMetadata, logprobsResult, and safetyRatings. At observability levels 0 and 1, only derived counts are sent: grounding_chunk_count, citation_count, safety_blocked_count, and avg_logprobs. The full metadata is sent only at level 2, alongside the text previews.
Collecting Feedback and Supplying Your Own Prompt ID
User feedback, such as a thumbs up or thumbs down on an answer, is not collected automatically. You capture the prompt_id of each call with the onPrompt callback, then record feedback against it with createFeedbackTracker, which this package re-exports.
If your app already has an ID for the interaction, such as a chat message ID or a request ID, return it from getPromptId. The adapter calls it once per tracked call, before the request runs, and uses the value as the run_id of every event in that turn. Return undefined to fall back to a generated ID. You can then record feedback against your own ID without waiting for onPrompt:
import { GoogleGenAI } from "@google/genai";
import { observeGoogleGenAI, createFeedbackTracker } from "@countly/ai-sdk-google-genai";
const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };
const client = observeGoogleGenAI(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }), {
...countly,
getPromptId: () => requestStore.getStore()?.messageId,
});
const feedback = createFeedbackTracker(countly, { sdk_adapter: "google-genai" });
// Later, when the person rates the answer, pass the same message ID
// and the same device ID as the interaction:
feedback.track({
prompt_id: messageId,
rating: "thumbs_up",
deviceId: countlyDeviceId,
});
For ratings, scores, categories, comments, and rating a single generation instead of the whole turn, see Collecting User Feedback on AI Responses.
Verifying the Integration
- Add
debug: trueto your configuration. The SDK then logs transport errors and dropped batches. - Make one
models.generateContent()call, and note the device ID you passed. - Keep the process running for at least ten seconds. Events are sent every ten seconds or every 20 events, whichever comes first, and the send timer does not keep your process alive, so a one-off script can exit before the batch leaves.
- In Countly, open User ProfilesProfiles and search for that exact device ID. The profile should already exist and have sessions from your client-side Countly SDK.
If the profile exists but has zero sessions, the device ID does not match your client-side SDK. If there is no profile at all, the event never arrived: check the debug output, and add an onDropped callback to your configuration to see events that were discarded.
FAQ and Troubleshooting
Why Do Some of My Gemini Calls Have No Cost?
The model is not in the built-in pricing table. Instead of reporting a misleading $0, the SDK omits the cost fields and sets cost_priced to unpriced_model. To price it, add the model to costModel, in dollars per million tokens:
observeGoogleGenAI(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
costModel: {
"YOUR_MODEL_NAME": { input_per_mtok: 0.5, output_per_mtok: 1.5 },
},
});
When Gemini reports no usage at all, the token fields are absent too, and usage_state is not_reported. For how cost is calculated, see Understanding and Customizing AI Cost Calculation.
Why Is My Function Call Status "Unknown"?
The Gemini response carries the model's request to call a function, never its outcome, because your code runs the function. The adapter records status: "unknown" rather than claiming a success it never observed.
Why Is a Call Marked Incomplete When Gemini Returned No Error?
Gemini blocked the prompt before generating anything. The response comes back successfully, with a promptFeedback.blockReason and no content, and the adapter records it as status: "incomplete" so that it does not count as a completed answer.
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.