Every Countly AI SDK adapter takes one configuration object, CountlyAIConfig. This article lists every field it accepts, grouped by what the field controls, plus the few options that exist on a single adapter only.
It also explains how the SDK delivers events to your Countly Server: batching, retries, buffer limits, and how you find out when data was dropped. Only appKey and url are required. Everything else has a default that works for most applications.
Passing the Configuration
You pass the same object to whichever entry point your framework uses. A Mastra exporter, for example, accepts every shared field below in addition to its own options.
| Framework | Where the Configuration Goes |
|---|---|
| OpenAI, Anthropic, Google GenAI, Cohere | Second argument of observeOpenAI(), observeAnthropic(), observeGoogleGenAI(), or observeCohere()
|
| Vercel AI SDK | countlyTelemetry(config) |
| LangChain | new CountlyCallbackHandler(config) |
| Mastra | new CountlyMastraExporter(config) |
| LlamaIndex | new CountlyLlamaIndexTracer(config) |
A typical production configuration sets identity, a detail level, labels, and a drop handler:
import OpenAI from "openai";
import { observeOpenAI } from "@countly/ai-sdk-openai";
const openai = observeOpenAI(new OpenAI(), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
getDeviceId: () => store.getStore()?.countlyDeviceId,
observabilityLevel: 1,
environment: "staging",
source: "chat",
tags: ["support-bot"],
onDropped: (events, reason) => {
console.warn(`Countly AI SDK dropped ${events.length} events: ${reason}`);
},
});
createFeedbackTracker() takes a configuration object too, usually just appKey and url.
Configuration Fields
Connection
| Field | Type | Default | Description |
|---|---|---|---|
appKey |
string |
Required | The app key of the Countly app that receives the data |
url |
string |
Required | Your Countly Server URL. Events are sent to POST /i on it. |
On a self-hosted Countly Server, set url to the endpoint that accepts SDK data without a server-side token, which is typically your frontend endpoint. A 403 response means the URL points to an authenticated endpoint. Countly Cloud users (*.count.ly) do not need to change anything.
Identity
| Field | Type | Default | Description |
|---|---|---|---|
getDeviceId |
() => string | undefined |
None | Returns the device ID for each event. Called synchronously when the event is recorded, so it works with AsyncLocalStorage. |
deviceId |
string |
None | Static device ID, used when getDeviceId is not set or returns nothing |
getPromptId |
() => string | undefined |
None | Your own ID for the turn. It becomes run_id on every row the turn emits. Return undefined to use a generated ID. |
When more than one source provides a device ID, the SDK uses the first match: an ID set directly on the event, the Mastra request context (Mastra only), getDeviceId(), deviceId, and finally a random ID generated once per process. That last one is a fallback, not a person, so do not ship it to production.
The device ID must match the ID your web or mobile Countly SDK uses for the same person. Otherwise, every user-based AI metric reads zero. See Attributing AI Activity to the Right User for the full rule and how to verify it.
Detail and Privacy
| Field | Type | Default | Description |
|---|---|---|---|
observabilityLevel |
0 | 1 | 2 |
0 |
0: interaction events only. 1: adds one event per tool call. 2: adds tool argument values and text previews. |
textPreviewLength |
number |
200 |
Maximum characters per prompt, response, or reasoning preview. Level 2 only. Capped at 8192. |
paramValueLength |
number |
1024 |
Maximum characters of one tool argument value. Level 2 only. Capped at 8192. |
The level controls what leaves your process, not what is measured. The two length caps cannot be raised past 8192 by configuration: paramValueLength protects ingestion, because a single multi-megabyte tool argument would otherwise make the whole batch fail. Truncated values are marked as truncated on the event.
Level 2 sends prompt text
At level 2, text previews and tool argument values leave your application, and Countly's server-side data masking does not currently cover these fields. Keep level 2 off where prompt text must not leave your infrastructure.
Labels
| Field | Type | Default | Description |
|---|---|---|---|
tags |
string[] |
[] |
Labels for cost attribution and filtering. Sent as one comma-joined string. |
environment |
string |
"production" |
Environment label, e.g., production, staging, or development |
source |
string |
"api" |
Source label, e.g., api, chat, batch, or agent |
All three appear on every event the SDK sends, so you can filter or break down any AI metric by them.
Cost
| Field | Type | Default | Description |
|---|---|---|---|
costModel |
Object keyed by model name | None | Custom prices in dollars per million tokens. Each entry takes input_per_mtok and output_per_mtok, and optionally cached_per_mtok, cache_write_per_mtok, and reason_per_mtok. |
Built-in pricing covers 47 models. Model names are prefix-matched, so gpt-4.1-mini-2025-XX uses the price of gpt-4.1-mini. A model with no price gets no cost fields rather than a cost of zero. See Understanding and Customizing AI Cost Calculation for how cost is computed.
Tracking Toggles
| Field | Type | Default | Description |
|---|---|---|---|
trackAPM |
boolean |
true |
Send latency traces to Performance Monitoring. Enterprise only: Community Edition ignores them.Send latency traces. Countly 27.0 does not store them: latency reaches AI Analytics on the interaction events. A trace is sent only when a latency was actually measured. |
trackErrors |
boolean |
true |
Send failed LLM calls to Crash AnalyticsCrashes as crash reports, categorized as rate limit, context length, content filter, timeout, authentication, or API errors |
disabled |
boolean |
false |
Turn off all tracking without removing the wrapper. Calls pass straight through. |
Delivery and Buffering
| Field | Type | Default | Description |
|---|---|---|---|
flushInterval |
number (ms) |
10000 |
How often buffered events are sent. The timer never keeps your process alive. |
maxBatchSize |
number |
20 |
Number of buffered events that triggers an immediate send |
maxBufferSize |
number |
10000 |
Maximum events held in memory. Beyond it, the oldest events are dropped, so a stalled endpoint cannot exhaust your application's memory. |
requestTimeout |
number (ms) |
15000 |
Timeout for each request, so a hung connection cannot block flush() or shutdown() forever |
Events are sent when either limit is reached first: 10 seconds or 20 events, by default. See Understanding Delivery Behavior below for what happens when a send fails.
Callbacks
| Field | Type | Default | Description |
|---|---|---|---|
onPrompt |
(info) => void |
None | Called once per generation with its identity: prompt_id, run_id, event_id, generation_index, provider, model, status, and more. Use it to capture the ID you record feedback against. |
onDropped |
(events, reason) => void |
None | Called when events are discarded. reason is "send_failed" or "buffer_full". |
onDropped is the only way your application learns that its prompt, token, or cost counts in Countly are lower than reality. We recommend wiring it to your own logging or metrics in production.
Debugging
| Field | Type | Default | Description |
|---|---|---|---|
debug |
boolean |
false |
Logs transport errors, dropped batches, and token counts an adapter reported inconsistently. On Mastra, it also logs unrecognized spans. |
Turn it on while you set up the integration, then turn it off in production and rely on onDropped instead.
Adapter-Specific Options
A few options exist on one adapter only. They are accepted in addition to every shared field above, because each adapter's configuration extends the same CountlyAIConfig object.
| Option | Adapter | Default | Description |
|---|---|---|---|
apiBaseURL |
Vercel AI SDK | None | The provider's base URL. The Vercel AI SDK does not expose it, so without this option api_host_type is unknown. Only the hostname is sent. |
requestContextDeviceIdKey |
Mastra | "countlyDeviceId" |
Request context key that holds the device ID. null disables it and falls back to getDeviceId or deviceId. |
requestContextThreadIdKey |
Mastra | "threadId" |
Request context key that holds the conversation ID. Falls back to Mastra's own thread ID. null disables it. |
requestContextWorkflowNameKey |
Mastra | "workflowName" |
Request context key that holds the workflow name. Falls back to the root workflow's name. null disables it. |
requestContextPromptIdKey |
Mastra | None (opt-in) | Request context key that holds your ID for the turn, which becomes run_id. getPromptId takes precedence over it. |
On Mastra, set request context values before you start the agent or workflow. Mastra copies the context when it creates each span, so a value set inside a step does not reach the root span. A host-supplied turn ID is also the only way to group a workflow with the agent runs it starts, because Mastra records them as separate traces.
The LlamaIndex tracer has no extra configuration options, but it adds methods: register() and unregister() attach it to a callback manager, and recordError(err) reports a failed call, because LlamaIndex dispatches no event when a call throws. The OpenAI, Anthropic, Google GenAI, Cohere, and LangChain adapters document no options beyond the shared fields.
Understanding Delivery Behavior
The SDK buffers events in memory and sends them to your Countly Server in batches. The table below describes how it handles each situation.
| Situation | What the SDK Does |
|---|---|
| Server error or network failure | Retries up to three times, waiting about 200 ms, 1 s, and 5 s, with random jitter |
| 429 Too Many Requests | Waits for the time given in the Retry-After header, then retries |
| Client error (400, 401, 403, 413, or 422) | Does not retry, because the same request would fail again |
| A retry after the Server already accepted the batch | Every retry of a batch carries the same batch_id, so a batch whose response was lost is not counted twice |
| All retries fail | Moves the events to a dead-letter buffer of up to 1000 events and calls onDropped with "send_failed". They are queued again after a later send succeeds. |
The buffer exceeds maxBufferSize
|
Drops the oldest events and calls onDropped with "buffer_full"
|
| Several events belong to different people | Groups them by device ID and sends one request per device |
| Process restarts or crashes | Loses whatever is still buffered, because the buffer lives in memory only |
You can read the running counts at any time with transport.stats(), which returns { buffered, deadLettered, dropped }.
Flushing Before Exit
The flush timer does not keep your process alive, so a script, cron job, or serverless function can exit before the last batch is sent. Call flush() to send buffered events now, or shutdown() to flush and stop. shutdown() keeps flushing until the buffer is empty, so events recorded during the final send are not lost.
On Mastra, flush() does not send turns that are still running. shutdown() does, and marks them with status: "incomplete".
Related Resources
For the fields these settings produce on each event, see AI SDK Event Data Reference.