Skip to main content

rudderstack-ai

CI

Product analytics for the AI features of a Python backend. rudderstack-ai observes your OpenAI, OpenAI Agents SDK, Anthropic, Amazon Bedrock, Google Gen AI, LiteLLM, LangChain / LangGraph or Claude Agent SDK calls, and your MCP servers, and sends the standard AI events (spec v0.4) through the RudderStack client your app already uses. The Node.js package is @rudderstack/ai; both send the same events, pinned by the shared fixtures in spec/fixtures.

How it fits

your request handler ── ai_interaction ── wrapped client / LangChain handler / tracked_query
                              │
                              └─ your rudder-sdk-python client ─▶ RudderStack ─▶ warehouse, destinations, audiences
  • One event per answer segment. However many model calls, agents and tool steps an answer takes, you get one ai_response_received with its totals: tokens, cost, latency, models, tool calls, status. The prompt, the answer and later feedback share an interaction_id; every event carries conversation_id.
  • Product analytics, not debugging. The events land next to your other product events, keyed to the same userId, so you can build funnels, retention and audiences ("users whose refund questions went unresolved"). It complements tracing tools (Langfuse, LangSmith, Braintrust, APM): set trace_id to join the two, or export your OpenTelemetry spans through the same pipe (Advanced: OpenTelemetry export).
  • Private by default. Events carry IDs and metrics. Prompt, answer and feedback text are sent only when you turn on content capture, and are then masked.
  • Never in the way. Clients are wrapped, not patched (except LiteLLM, whose module functions are patched in place: instrument_litellm()); the SDK never throws into your LLM call or flush() (its own errors are logged), and provider errors reach your code unchanged. Delivery errors from the RudderStack client are handled by that client: pass its on_error callback to observe them (an exception raised from the client's own consumer thread is not the SDK's to catch). Server-side only.

Install

Python 3.12 or later. Install the extra for each library you use: openai, anthropic, google-genai (Gemini API or Vertex AI), bedrock (boto3 Bedrock Runtime), langchain (LangChain, LangGraph, Deep Agents), openai-agents (OpenAI Agents SDK), claude-agent-sdk, litellm (LiteLLM SDK), mcp (MCP servers built on the official mcp package), and tracing for OpenTelemetry spans (rudderstack.ai.tracing); check is only for the migration check. all installs every integration extra, not tracing or check.

pip install "rudderstack-ai[openai]"  # or: uv add "rudderstack-ai[openai]"

The package has no dependencies of its own. It sends events through your rudder-sdk-python client (rudderstack.analytics) and never creates one.

Quick start

import rudderstack.analytics as rudder_analytics
from openai import OpenAI

import rudderstack.ai
from rudderstack.ai import ai_interaction, track_action
from rudderstack.ai.openai import wrap_openai

rudder_analytics.write_key = "<WRITE_KEY>"
rudder_analytics.dataPlaneUrl = "<DATA_PLANE_URL>"
rudderstack.ai.configure(analytics=rudder_analytics)  # once, at startup

client = wrap_openai(OpenAI())


def answer(user_id: str, chat_id: str, question: str) -> dict[str, str | None]:
    with ai_interaction(user_id=user_id, conversation_id=chat_id, feature="support_bot") as interaction:
        reply = client.chat.completions.create(
            model="gpt-4.1-mini", messages=[{"role": "user", "content": question}]
        )
        interaction.set_outcome("resolved")
    return {"answer": reply.choices[0].message.content, "interaction_id": interaction.id}


def feedback(user_id: str, chat_id: str, interaction_id: str, thumbs_up: bool) -> None:
    track_action(
        "feedback_given",
        interaction_id=interaction_id,
        conversation_id=chat_id,
        user_id=user_id,
        action_details={"feedback_type": "thumbs", "feedback_value": thumbs_up},
    )

This sends ai_user_prompt_created and ai_response_received for the answer and ai_user_action for the feedback. In a script, worker or serverless handler, call rudderstack.ai.flush() before exiting (Serverless and workers). examples/ has a runnable app per integration, a background agent, three tracing apps and a full-stack chat app (FastAPI, Anthropic and the RudderStack JavaScript SDK). Each runs against the real APIs with your keys, or offline against the bundled mock server.

Choose your integration

Use one integration per call path. Everything inside one ai_interaction becomes one answer, and a call reported by two integrations (a wrapped client used by LangChain, a wrapper plus a tracing span) is counted once.

Rules that apply to every chat app:

  • Cost precedence: use the provider or gateway's reported cost first, then a registered model price; omit cost when neither is known.
  • One ai_interaction per user turn, not per conversation. Pass your chat thread's ID as conversation_id. A one-shot feature with no thread (a Generate button, a suggested fix) sets one_shot=True: without an explicit or context conversation ID, conversation_id is the interaction's ID. The default still mints a separate conversation ID. Resending the history on every turn is fine: usage is counted per model call, not from the history.
  • Streaming responses: a route that returns a stream must keep the interaction open until the stream ends. Pass the generator through interaction.bind() (example).
  • Thread pools: ThreadPoolExecutor and loop.run_in_executor do not copy context; wrap the function with rudderstack.ai.propagate(fn) (asyncio.to_thread copies it).
  • A call outside any interaction still sends its own ai_response_received (trigger: user when identity is in context, else system), but no prompt event and no classification.

What each integration tracks and its edge cases: docs/integrations.md.

OpenAI

from openai import AsyncOpenAI
from rudderstack.ai.openai import wrap_openai

# AzureOpenAI or a compatible endpoint: provider="azure.ai.openai", "openrouter"...
client = wrap_openai(AsyncOpenAI())
  • Streamed chat calls report usage only when the response includes it. The wrapper asks for it (stream_options.include_usage) on every host, including compatible endpoints (Azure, Groq, OpenRouter, Ollama, vLLM), and hides the extra chunk unless you asked for it. A request the host rejects (HTTP 400 or 422 naming the parameter, or with no error code) is sent once more as you wrote it, so a working call never breaks; once a host names the parameter, that client and its with_options() copies stop adding it there. Other rejections (a content filter, a prompt too long) are not resent. stream_usage=True always adds it (no resend), False never does.
  • finish_reason uses Chat Completions' terms on both APIs: a Responses output with only tool calls is tool_calls, incomplete at max_output_tokens is length, a refusal (message.refusal, a Responses refusal part) is refusal; a streamed Chat Completions refusal keeps the wire's stop. When the answer's last call finished at length the answer is response_status: incomplete with error_type: length, and at content_filter it is error with error_type: content_filter, streamed or not, chat.completions.parse() raising or not; the call keeps its tokens and cost. A refusal is visible through finish_reason only and stays success. responses.parse() raising on truncated structured output is a failed call (Known limitations).
  • The wrapper is a proxy: isinstance(client, OpenAI) is False. Pass rudderstack.ai.unwrap(client) to code that checks the class.

OpenAI Agents SDK

from agents import SQLiteSession
from rudderstack.ai.openai_agents import tracked_run, tracked_run_streamed

result = await tracked_run(
    triage_agent,
    question,
    tracking={"user_id": user_id, "feature": "support_agent"},
    session=SQLiteSession(chat_id),
)

stream = tracked_run_streamed(triage_agent, question, tracking={"user_id": user_id})
async for event in stream.stream_events():
    render(event)

tracked_run(agent, input, *, tracking=None, **run_kwargs) runs Runner.run (tracked_run_sync: Runner.run_sync) and reports the whole run, across handoffs, as one interaction; inside ai_interaction (or with tracking["interaction"]) it reports into that one instead. run_kwargs go to the Runner unchanged, and your hooks still run. tracking takes the interaction options plus analytics and provider (the label for every call, default openai, for OpenAI-compatible endpoints).

  • Model calls: each model response is one call, attributed to the agent that made it (agent_name in usage_breakdown), with the agent's configured model name, input, output, reasoning (when the provider reports them) and cached tokens, and finish_reason: stop for a completed response. A response that wrap_openai already recorded (the same provider response ID) is counted once and gains the agent name.
  • Tools: every tool the model requested is a tool call: function tools, hosted tools (web_search) and handoffs (transfer_to_<agent>). A local function tool also reports its duration and outcome; the Agents SDK's default failure output ("An error occurred while running the tool.") counts as a failure. Hosted tools and handoffs have no known outcome.
  • Agents used as tools: the nested run's model calls are recorded from Agents SDK trace spans and attributed to the nested agent, with the model name the provider reported. This needs Agents SDK tracing (on by default; RunConfig(tracing_disabled=True) or OPENAI_AGENTS_DISABLE_TRACING turn it off, and then only the top-level calls are counted). The nested run's own tools are not tracked. The helpers register a process-wide trace processor once and leave exporters alone; if you replace processors with set_trace_processors, include register_openai_agents_tracing()'s processor.
  • Statuses: a guardrail tripwire ends the run with response_status: error and error_type: guardrail_trip. A run stopped at max_turns, or a Responses API run cut off at the output-token limit, is incomplete (error_type max_turns / length; the last call keeps its usage). A run waiting on tool approvals (interruptions) is paused with pause_reason: approval. A provider error fails the call in flight (attributed to the running agent) and the run; calls before it keep their usage.
  • MCP servers: tool_meta_resolver=rudderstack_mcp_tool_meta() on an MCPServerStdio / MCPServerStreamableHttp / MCPServerSse sends the interaction's IDs in each tools/call _meta, so a server tracked with wrap_mcp_server joins its calls to this answer (MCP servers).
  • Conversation: tracking conversation_id, then the Runner's conversation_id, then the session's ID, then a generated ID.
  • Streaming: the interaction ends when stream_events() finishes or fails, or when you stop consuming it or call cancel() (cancelled).
  • Classification: interactions these helpers open are not classified unless you pass classify=True in tracking.

Anthropic

from anthropic import Anthropic
from rudderstack.ai.anthropic import wrap_anthropic

# AnthropicBedrock: provider="aws.bedrock"; AnthropicVertex: "gcp.vertex_ai"
client = wrap_anthropic(Anthropic())

Google Gen AI (Gemini and Vertex AI)

from google import genai
from rudderstack.ai.google_genai import wrap_google_genai

client = wrap_google_genai(genai.Client(api_key=os.environ["GEMINI_API_KEY"]))
vertex = wrap_google_genai(genai.Client(vertexai=True, project="my-project", location="us-central1"))

Provider gcp.gemini for the Gemini API, gcp.vertex_ai for a Vertex AI client (provider= overrides it); the two are priced separately. Thinking tokens (thoughts_token_count) are output tokens and reasoning_tokens. embed_content and other methods pass through untracked (details).

Amazon Bedrock (Converse)

import boto3
from rudderstack.ai.bedrock import wrap_bedrock

client = wrap_bedrock(boto3.client("bedrock-runtime", region_name="us-east-1"))

LangChain and LangGraph

One callback handler covers LangChain, LangGraph and Deep Agents. Pass it in the run's config, not to a model's constructor (a handler that sees only model runs makes each model call its own answer, and logs a warning).

from rudderstack.ai.langchain import RudderStackCallbackHandler

handler = RudderStackCallbackHandler()

result = graph.invoke(
    {"messages": [("user", question)]},
    config={
        "callbacks": [handler],
        "configurable": {"thread_id": chat_id},
        "metadata": {"user_id": user_id, "feature": "support_agent"},
    },
)
  • Outside ai_interaction, the handler opens one interaction per root run (invoke / stream) with identity from metadata (user_id, anonymous_id, conversation_id, interaction_id, feature, intent, trace_id). Without conversation_id, LangGraph's thread_id is the conversation.
  • With a checkpointer, each invoke is one turn; resuming an interrupted graph (Command(resume=...)) opens a new interaction without a prompt event.
  • A graph that stops at interrupt() ends its answer with response_status: paused and pause_reason: human_input (inside ai_interaction too, unless a later call answers it), so nothing is left open while it waits, even across processes. To report the resume as the same turn, pass the same interaction_id in the metadata of both runs, for example one derived from the thread_id; Send branches and subgraphs stay in that interaction. See examples/langgraph-checkpoint.
  • A wrapped OpenAI or Anthropic client called directly from a graph node cannot see the handler's interaction. Wrap the run in ai_interaction to join them (that also turns on classification, which handler-opened interactions skip).
  • usage_breakdown[].agent_name comes from the agent_name / lc_agent_name metadata (LangChain agents and Deep Agents subagents set it) or an agent:<name> tag. Providers are reported with their OpenTelemetry names (aws.bedrock, gcp.vertex_ai, azure.ai.openai...). See Deep Agents across Claude and Gemini.
  • A model run's usage is summed over its prompts. A stream the consumer stops or a cancelled run is a cancelled call that keeps the tokens streamed so far (summed over chunks, as LangChain merges them), unpriced.

Claude Agent SDK

tracked_query is a drop-in for claude_agent_sdk.query(). Cost, tokens and per-model usage come from the SDK's ResultMessage.

Without an outer ai_interaction, each run opens its own interaction (one per turn for streaming input). Use require_interaction=True on tracked_query or tracked_messages to require a current interaction: otherwise it warns once and passes the stream through untracked.

Pass agent_name to tracked_query or tracked_messages to label a run, for example tracked_messages(query(prompt=question), agent_name='router'). Runs named router, main and summarizer inside one interaction produce separate usage_breakdown entries with agent_name, tokens and cost. Claude subagent names take precedence; calls and tools without a derived subagent name use the run's name. Omitting the option preserves unnamed main-loop groups. An untracked stream with require_interaction=True ignores it.

Pass primary=True to tracked_query or tracked_messages to use that run's main model (the served model of its main-loop calls) for primary_model and primary_provider. For router (haiku) → main (sonnet, primary) → summarizer (haiku), the primary model stays sonnet. The option works with agent_name; if several runs are marked, the last started marked run with a successful result wins, regardless of result or cleanup order. It defaults to False, preserving the last-successful-call rule. A marked run that records no successful call leaves that rule in place; a successful result stays primary even if a later consumer or stream error occurs. An untracked stream ignores it.

Claude model names in events use the family name: us.anthropic.claude-haiku-4-5-20251001-v1:0 and claude-haiku-4-5@20251001 both become claude-haiku-4-5. Each deployed raw ID is priced and credited once with its own usage, including when one usage alias covers multiple deployed IDs. Provider hints and providers observed in the run win over environment fallback. Without either, short Claude model names use CLAUDE_CODE_USE_BEDROCK=1 or CLAUDE_CODE_USE_VERTEX=1 from the query options environment, falling back to os.environ when no environment is supplied. An explicit env={} keeps the environment empty.

This changes exact model values in primary_model, per-call model and usage_breakdown[].model across integrations. Claude IDs are lowercased and repeatedly stripped of cloud profile and Anthropic vendor prefixes, Bedrock versions, Vertex @ suffixes and eight-digit date stamps. -latest and other aliases remain distinct. Update exact-value filters and dashboard joins to the canonical family name (for example, us.anthropic.claude-opus-5 → claude-opus-5), and combine historical deployment-specific groups when comparing totals. Other providers' IDs remain unchanged; pricing and credit hooks receive the raw ID.

from claude_agent_sdk import ClaudeAgentOptions
from rudderstack.ai.claude_agent_sdk import tracked_query


def save_usage(snapshot):
    if snapshot is None:
        session.delete_usage()  # delete the persisted baseline after an unfinished run
    else:
        session.save_usage(snapshot)  # JSON-serialisable; save with the session ID


async for message in tracked_query(
    prompt=question,
    options=ClaudeAgentOptions(resume=session.id),  # resume=None on the first turn
    usage_baseline=session.usage,  # None on the first turn
    on_usage_snapshot=save_usage,
    user_id=user_id,
):
    ...  # fully consume the stream before ending an outer interaction

on_usage_snapshot is called exactly once at stream close, after unfinished-turn cleanup, with the latest fresh result snapshot (the same value usage_snapshot(result) returns), or None when the run ends without a result, or its last result is cancelled or empty; an error result that reports usage is still a valid baseline. A run that throws or has an unfinished later turn also delivers None. Each accepted streaming-input prompt needs a result: the snapshot stays stale until no accepted prompts remain unanswered, even before any user message or assistant output. Save on a value and delete your persisted baseline on None. It also runs for an untracked stream with require_interaction. Sync and async callbacks are accepted; async callbacks run without delaying stream close. Callback failures are reported through configure(on_error=...) as user_callback, without breaking the stream. usage_snapshot(result) still works independently. Use contextlib.aclosing when you may stop consuming an async stream early, so cleanup and the callback run promptly:

from contextlib import aclosing

async with aclosing(tracked_query(prompt=question, on_usage_snapshot=save_usage, user_id=user_id)) as stream:
    async for message in stream:
        if should_stop(message):
            break
# Cleanup and save_usage have run before ending an outer interaction.

End an interaction after the tracked stream is fully consumed, or pass an explicit status to interaction.end(status=...). Ending while a provider stream is still unread records an empty cancelled answer. To return a stream from a handler, use interaction.bind(stream) to keep the interaction alive during consumption.

Resumed and continued sessions. On resume / continue_conversation, on later turns of a ClaudeSDKClient and on later results of a streaming-input query(), the SDK reports usage and cost for the whole session so far. The SDK subtracts the previous result it saw in this process; across processes, store usage_snapshot() and pass it as the next turn's usage_baseline. For tracked_messages of a known resumed session, pass resumed=True. Unknown restored history is detected when the main model’s excess input plus cache tokens, after subtracting all same-model calls this turn, exceeds the first main call’s input plus cache tokens; this allows one small title call (shared threshold cases). Without a baseline, a resumed turn counts its own tokens and prices them with your registered prices (no cost when none is registered). Turns it opens are classified only with classify=True.

Statuses. A turn stopped at max_turns or max_budget_usd, or cut off at max_tokens, is response_status: incomplete; a tool deferred by a PreToolUse hook ends it paused (pause_reason: deferred_tool). modelUsage.thinkingTokens is reasoning_tokens when the CLI records it.

Other frameworks

For a client without an integration, report each call:

from rudderstack.ai import ai_interaction

with ai_interaction(user_id=user_id, conversation_id=chat_id) as interaction:
    result = my_llm.generate(prompt)
    interaction.record_call(
        provider="acme",
        model="acme-large",
        input_tokens=result.input_tokens,  # including cached tokens
        output_tokens=result.output_tokens,
        response_id=result.id,  # de-duplicates a call reported twice
    )

For frameworks with their own lifecycle hooks, start_interaction() creates an interaction without entering it: run the work in with interaction.activate(): and call interaction.end().

Gateways and routers

  • OpenRouter: wrap_openai(OpenAI(base_url="https://openrouter.ai/api/v1"), provider="openrouter"). Its usage.cost is the call's cost (example).
  • LiteLLM proxy: wrap_openai(OpenAI(base_url="http://localhost:4000/v1"), provider="litellm"). The served deployment comes from the x-litellm-model-name header (the body's model is the alias you asked for), the cost from usage.cost or x-litellm-response-cost (example).

A gateway's call is reported under the served model's vendor (openai/gpt-4o → openai, full name in model). When a router or fallback served another model than the one asked for, requested_model (on usage_breakdown entries and ai_llm_response_received) holds the requested one; a dated version of the same model is not another model. Cost: the gateway's reported cost, then your registered price (Cloud model IDs and pricing), otherwise none. Details: docs/integrations.md.

LiteLLM

import litellm
from rudderstack.ai.litellm import instrument_litellm

instrument_litellm()  # once at startup
reply = litellm.completion(
    model="anthropic/claude-haiku-4-5", messages=messages, fallbacks=["gemini/gemini-3.5-flash-lite"]
)

Tracks litellm.completion / acompletion (sync, async, streamed), and so the frameworks built on LiteLLM (CrewAI, DSPy, smolagents). A call with fallbacks= is one call, from the model that answered. Cost is LiteLLM's response_cost, then a registered price. LiteLLM 1.83.1 and later require openai<3, so the litellm extra (>=1.88.6) cannot be installed alongside openai 3; that constraint is LiteLLM's. See docs/integrations.md and the fallback example.

Cloud model IDs and pricing

No prices ship with the SDK, and cloud providers name models their own way. A registered base-model price also covers:

  • Bedrock model IDs (provider aws.bedrock only): a leading cross-region inference profile (us., us-gov., eu., apac., jp., au., in., global.) and then the vendor prefix (anthropic., amazon., meta....) are stripped for the lookup, so claude-sonnet-4-5 prices us.anthropic.claude-sonnet-4-5-20250929-v1:0 and nova-pro prices amazon.nova-pro-v1:0.
  • Vertex AI revisions: claude-sonnet-4-5@20250929 matches claude-sonnet-4-5 through the usual version-suffix rule.
  • Gemini: every integration reports gcp.gemini for the Gemini API and gcp.vertex_ai for Vertex AI, which are priced separately, so register each provider you call. google and google.vertex (the labels before 0.5.0) are accepted aliases: a price for google prices gcp.gemini, one for google.vertex prices gcp.vertex_ai.
  • Routers: a vendor-prefixed name (openai/gpt-4o) is priced by the bare name (gpt-4o) on any provider.

Azure OpenAI deployment names are yours to choose, so they are never guessed. Map them:

from rudderstack.ai import configure, register_price

register_price("gpt-4o", input_per_mtok=2.5, output_per_mtok=10)
configure(azure_deployment_models={"support-prod": "gpt-4o"})

The mapping applies to calls with provider azure.ai.openai and only to the price lookup: events keep the deployment name. Each call replaces the previous mapping (None or {} clears it); clear_prices() leaves it in place. The suffix rule still never prices another model of the family: claude-sonnet-4-5 does not price anthropic.claude-sonnet-4-5-mini-v1:0. A price with no provider prices every provider; on equal names, a price for the call's provider beats one for its alias, which beats one with no provider.

Identity

Events need a userId or an anonymousId. Pass them explicitly, set them once per request with with ai_context(user_id=..., conversation_id=..., feature=...): (every interaction, wrapped call and track_action inside uses them), or let the request middleware read them from the RudderStack JavaScript SDK's cookies. ai_context uses contextvars, so concurrent requests and asyncio tasks never mix. Nested contexts inherit what they do not set.

Request middleware

When the page runs the RudderStack JavaScript SDK (v3), its cookies arrive with every same-origin request. The middleware wraps each request in ai_context(request=...), so events carry the browser's anonymousId and session without any identity plumbing. When the page does not run the JavaScript SDK (or for API-only clients), the cookies are absent and the middleware does nothing.

Framework Setup
FastAPI / Starlette (any ASGI app, HTTP and WebSocket) app.add_middleware(AIContextMiddleware); call configure() in the app's lifespan or at import
Django (sync and async) "rudderstack.ai.middleware.DjangoAIContextMiddleware" in MIDDLEWARE; call configure() in an AppConfig.ready()
Flask init_flask(app) in the app factory, after configure()

All three are in rudderstack.ai.middleware, which imports no framework. Without middleware, pass the request (Starlette, Django, Flask/Werkzeug, an ASGI scope, a WSGI environ or a header mapping) or the cookies (a Cookie header or a name-to-value map, e.g. from a queue message) yourself: ai_interaction(request=request) or ai_interaction(cookies={"rl_anonymous_id": anonymous_id}).

Cookie Becomes Rule
rl_anonymous_id anonymousId unless set explicitly
rl_session context.sessionId while the session is active; never sessionStart
rl_user_id userId fallback only: ignored when a user_id or anonymous_id is set explicitly or in ai_context

Precedence: arguments of the interaction (or track_action), then ai_context values, then cookies. A context={"sessionId": ...} you set wins too. Only these three cookies are read; unreadable cookies are skipped. A WebSocket keeps its handshake's cookies for its whole life.

Stale rl_user_id after logout. The JavaScript SDK keeps rl_user_id until the page calls rudderanalytics.reset(), so on a shared browser it can name the previous user. Pass the server's own user_id (or an anonymous_id for a logged-out visitor) whenever you know it, call reset() on logout, or turn the fallback off with configure(identity_from_cookies=False) (per interaction: identity_from_cookies=False).

Legacy v1.1 cookies (RudderEncrypt:) are not supported; upgrade the browser SDK to v3.

Background agents

Use ai_task for LLM work no user is waiting on: a scheduled job, a webhook or queue worker, a Slack bot, a sub-agent. It is a system-triggered interaction: no prompt event, one ai_response_received per run.

from rudderstack.ai import ai_context, ai_task

with ai_context(account_id=workspace.id):
    with ai_task("alert-triage", on_behalf_of=alert.owner_id, trigger_source="schedule") as run:
        summary = summarise(alert)  # wrapped clients report into the run
        run.set_outcome("resolved")

It works as with, async with or a decorator (@ai_task("nightly-digest"), sync or async; each call is its own run).

  • Actor vs beneficiary. The actor is the system: userId stays unset (anonymousId: ai_system), and the request's identity and cookies are never used, so machine activity never counts as a person's. Put the customer in account_id and the person the work is for in on_behalf_of. For multi-tenant bots and cron jobs, also pass a stable workspace-specific anonymous_id and explicit conversation_id; otherwise the shared ai_system ID merges unrelated machine traffic in identity-based analytics. Spans inside a task never carry the person's identity either.
  • Chaining. Inside another interaction or task, a task is chained to it: parent_interaction_id and conversation_id are the current interaction's, and trigger_source defaults to agent. Pass parent_interaction_id="..." to link a run started elsewhere (e.g. from a queue message), or None to start a new chain.
  • Flush. A task that is not chained to a running interaction flushes on exit (async with awaits it), so a cron job or Lambda delivers its events before it stops. Pass flush=False in a long-lived worker and flush at shutdown; flush=True makes a chained task flush too.
  • Classification is off for tasks; ai_task(..., classify=True) turns it on, and the task waits for the label before flushing (inside an event loop, use async with for that).

MCP servers

Agents are the users of an MCP server. wrap_mcp_server (the mcp extra) tracks a server built on the official mcp package: on 2.x, MCPServer or the low-level Server; on 1.x, FastMCP (from mcp.server.fastmcp import FastMCP) or its low-level Server. Every calling client and every tool call becomes a spec event, attributed to the signed-in customer, without touching a tool:

from mcp.server.mcpserver import MCPServer
import rudderstack.analytics as rudder_analytics
from rudderstack.ai.mcp import wrap_mcp_server

server = MCPServer("workspace-mcp", version="1.4.0")
# ... @server.tool(), @server.resource(), @server.prompt() as usual

wrap_mcp_server(
    server,
    analytics=rudder_analytics,
    # auth is the verified OAuth AccessToken (None without auth); userId defaults to its subject.
    identify=lambda auth: {"account_id": auth.claims["workspace_id"]} if auth else None,
    event_rules={"tools": {"create_audience": "audience_created"}},  # also a product event
    request_context={"intents": ["debug_delivery", "build_audience"]},
)
server.run("streamable-http")
Event When
mcp_client_seen First request per client name, OAuth client and user in client_seen_window (24 h): at initialize on the handshake versions (2025-11-25 and earlier), after the first successful request on 2026-07-28
mcp_tool_called Every tools/call: status, error type, duration, argument names (never values), invalid arguments, retries, result size and content types (never the result)
mcp_elicitation_completed The user answered (or did not) a question the server asked: elicitation/create on the handshake versions, an input_required round on 2026-07-28
mcp_resource_read, mcp_prompt_used Every resources/read (by template or name, never a URI with IDs) and prompts/get
mcp_feedback_submitted Opt-in (feedback_requests={"capabilities": ["bulk_export"]}): the agent called the injected submit_feedback tool
mcp_capability_requested Deprecated: use feedback_requests (FeedbackRequests). Opt-in (capability_requests={"capabilities": ["bulk_export"]}): the agent called the injected request_capability tool
mcp_event_subscription_changed, mcp_event_delivered Experimental, opt-in (mcp_events=True): track_mcp_event_subscription and wrap_mcp_event_sender

Tool, prompt and argument names are emitted only when the server's own registry lists them (otherwise unknown; argument names are sorted by code point, with unlisted and duplicate names collapsed), protocol_version only as YYYY-MM-DD and client capabilities only from the MCP set (else unknown). request_id is an integer or whole-number float up to 9007199254740991 as a decimal string, any non-empty string sha256: plus the first 16 hex characters of its SHA-256, and anything else (empty, null, boolean, fraction, out of range) unknown; a declared-event callback's request_id, argument_keys, invalid_arguments, tool_name and client labels are replaced or cleaned the same way, under their snake_case names. Client name, title and version have Unicode control characters removed, whitespace collapsed and trimmed, and are capped at 64 code points (empty values are omitted; a title alone is kept). Call counters, client-seen windows, remembered and session clients and pending input_required continuations (dropped after an hour) are keyed by server, raw account, raw user and raw session or interaction ID, so one caller never inherits another's.

On mcp 2.x both protocol eras work with the same code: the initialize handshake (2025-11-25 and earlier) and the stateless 2026-07-28 envelope. mcp 1.x serves the handshake versions only, with the same events and options. A calling agent joins its calls to its own answer by sending com.rudderstack/interaction_id and its trace (W3C traceparent, else com.rudderstack/trace_id) in the request's _meta; no other _meta key is read. An OpenAI Agents SDK client sends them with rudderstack_mcp_tool_meta(): com.rudderstack/trace_id only when the interaction has a trace_id, traceparent only when a link_trace_id=True span processor linked the interaction and the active span is in that trace; by default neither (details). Values read off the wire are capped (IDs at 256 characters); tool arguments, results, resource contents and prompt text are never sent. request_context is off by default: omitted, None or False adds no schema argument and leaves client arguments untouched. Opt in with wrap_mcp_server(server, request_context=True) or an options dict such as request_context={"intents": ["debug_delivery"], "user_sentiment": True} (an empty dict also enables it). When enabled, the integration adds optional context to each tool's input schema and strips it before the tool runs; a high-level MCPServer or FastMCP tool that declares its own request_context always keeps it. On a low-level Server, request_context is a reserved argument name: a tool's own request_context is kept only once the SDK has seen the tool in a tools/list; name tool arguments something else. identify(auth) (sync or async) returns the user and account; without it, userId is the token's subject, and a request whose identify raises is sent anonymously. On stateless endpoints and servers rebuilt per request, client name and version fall back to the latest handled initialize for the same OAuth client ID and user identity (user_id, else anonymous_id), after initialize params, per-request _meta clientInfo, session state and resolve_client. client_info_fallback(ctx) runs only when all those sources, including the remembered client, supply no name or version; a title alone permits the fallback. It has the same signature and exception swallowing as resolve_client, and supplies client details to mcp_client_seen on eligible requests just like resolve_client. Remembering uses client_seen_window (default 24 hours; zero disables it), is bounded to 10,000 entries with the oldest evicted, and skips empty keys. One user running two clients under the same OAuth client can be attributed to whichever initialized last. mcp_session_id is still absent on stateless endpoints. Every MCP request event carries oauth_client_id and auth_method with the same values and omission rules as mcp_client_seen; token_scopes and country remain on mcp_client_seen only. Seen clients, remembered client names and call counters are kept in memory per server name, per process (bounded, oldest first): servers wrapped under one name share them (a server rebuilt per request keeps counting), so give each distinct server a unique name; each replica or restart emits its own mcp_client_seen and restarts its counters. See docs/mcp.md for every option and examples/mcp-server for a server over stdio and Streamable HTTP (examples/mcp-server-lowlevel for a low-level Server, examples/mcp-server-fastmcp-v1 for mcp 1.x FastMCP, examples/openai-agents-mcp for an agent whose answers join the server's calls).

Product signals

Feedback

Return interaction.id with the answer, then report what the user did with it through track_action() (quick start). Action types: feedback_given, feedback_retracted, feedback_dismissed, copied_response, shared, exported, reported, regenerated, accepted, rejected, edited (the user kept an AI suggestion unchanged, discarded it, or kept it after changing it) and clicked_through (with card_kind / target_type in action_details). feedback_retracted clears the interaction's feedback, so the latest feedback_given / feedback_retracted per interaction_id is the final state. conversation_id is required (argument or ai_context); without it the event is dropped with a warning. For a one-shot interaction, pass its ID as both. feedback_text is sent only with content capture on. When the client app (web or mobile) sends its own copy (source: client), configure(server_feedback=False) turns the server copy off.

Scores

Production evaluation, opt-in: configure(evaluator=fn) runs your function after each successful answer, in the background, and sends one ai_interaction_scored per score it returns ({"evaluation_name": "groundedness", "score_value": 0.9, "evaluator": "model"}). Scores from elsewhere, such as a human review, go through track_score(interaction_id=..., conversation_id=..., evaluation_name=..., score_value=..., evaluator="human"). An explanation is sent only with content capture on, masked and capped at 280 characters. Details: docs/events.md.

Intent classification

Opt-in. After each answer, your own model client labels the interaction with one of your intents and an outcome, sent as one ai_interaction_classified. Nothing waits for it. intent can always be other and outcome unclear (an off-list or missing label), even when your lists leave them out. To send labels from your own pipeline (any interaction, including errored ones), call track_classification(interaction_id=..., conversation_id=..., intent=..., outcome=...): details.

import anthropic

rudderstack.ai.configure(
    classifier={
        "client": anthropic.Anthropic(),  # or AsyncAnthropic, OpenAI, AsyncOpenAI: your key, your provider
        "model": "claude-haiku-4-5",
        "intents": ["refund_request", "order_status", "bug_report"],
        "outcomes": ["resolved", "partial", "unresolved", "escalated", "unclear"],  # optional; the default
        "intent_summary": False,  # optional: a one-sentence masked summary
        "timeout_ms": 5000,  # optional
    }
)
# Or your own function (sync or async; it receives a rudderstack.ai.Turn): {"classify": fn, ...}

One label per interaction you open (ai_interaction, start_interaction) that succeeded; errors and cancelled answers are skipped. Interactions an integration opens on its own are not classified: a wrapped call outside any interaction, a LangChain run outside one, a tracked_query turn outside one. To label them, wrap the request in ai_interaction, or pass classify=True to tracked_query / tracked_messages / record_claude_result. Tasks: ai_task(..., classify=True). Opt one interaction out with ai_interaction(classify=False). flush() / aflush() wait for pending classifications before flushing. Labels, input, cost, async clients, failures and limits: docs/events.md.

Declared tool events

Rules turn tool calls into your own product events (save_memory → memory_captured), next to the standard events:

rudderstack.ai.configure(
    event_rules={
        "tools": {
            "save_memory": "memory_captured",
            "create_ticket": rudderstack.ai.ToolRule(
                event="ticket_created",
                properties=lambda args, result: {"priority": args.get("priority")},
                when=lambda args, result: result is not None,
            ),
        }
    }
)

A rule is an event name or a ToolRule (or a mapping with event, properties, when). args is what the model passed (decoded JSON), result what the tool returned or your app sent back to the model, None when unseen. Each call sends its event once, when its result is known or when the interaction ends (tool_status: unknown). Wrap the whole tool loop in one ai_interaction to get results. Names starting with ai_ or mcp_ are reserved; a malformed rule raises at configure().

Tool breakdown

configure(tool_breakdown=True) (or per run: ai_interaction(tool_breakdown=True)) adds one entry per agent and tool identity to ai_response_received. Entries include measured-only duration totals, maxima and coverage, fixed error categories, MCP server/tool splits and nested parent_tool where integrations expose them. Tool names only, never inputs or outputs. Details: docs/events.md.

Multi-agent

usage_breakdown has one entry per agent, provider, served model and differing requested model, and tool_breakdown one per agent, MCP server, tool and parent tool, so the same model or tool used by several agents stays apart. Agents are named by:

  • LangChain / LangGraph: agent_name / lc_agent_name run metadata (Deep Agents subagents set it), an agent:<name> tag, the parent run's agent, the handler's agent_name, else the root run's name (a LangGraph graph or Deep Agents agent).
  • Claude Agent SDK: a subagent's calls and tools take the subagent_type of the Task / Agent call that launched it, and its tools carry that call's name as parent_tool; calls and tools without a derived subagent name use the run's agent_name, when supplied. Each model's tokens and cost still add up to the SDK's modelUsage: a subagent's answer, which is not streamed, counts from its tool result's usage; when the streamed messages still fall short, the main loop keeps the result's own usage and the subagents share the rest, and a model's cost is split between its agents by Claude's price ratios.
  • record_call and record_tool_call: the agent_name you pass.

Every usage_breakdown entry has cache_write_tokens (summed in total_cache_write_tokens) and error_count (failed calls, retries included). Nested ai_tasks report separately; roll a run tree up by parent_interaction_id (query).

Privacy

Sent by default: IDs (userId, anonymousId, conversation_id, interaction_id), the fields you set (feature, intent, outcome, run fields), models, providers, token counts, cost, latency, status, error categories, tool names and counts. Never sent: prompt, answer and feedback text (unless content capture is on), tool arguments and results, request headers, any cookie other than the three above, traits or emails.

Content capture. configure(capture_content=True) adds prompt_text, response_text and action_details.feedback_text, and, with emit_llm_calls, each call's input_messages, output_text and output_tool_calls; ai_interaction(capture_content=True) turns it on for one interaction. prompt_text comes from ai_interaction(prompt_text=...) or the tracked_query prompt; response_text from interaction.end(response_text=...) or the Claude Agent SDK result. Treat captured text as personal data. With capture off, content-named custom properties are dropped regardless of camelCase, PascalCase, hyphens, spaces or casing; unrelated properties such as promptLength are kept. SDK-owned names are reserved under the same normalization even with capture on.

Masking is on by default for all captured text, the classifier's intent_summary and captured span content:

Pattern Replaced by
Email addresses [email]
Phone numbers (international + form, US shapes, 98765 43210) [phone]
Payment card numbers (Luhn-valid) [card]
IPv4 and IPv6 addresses [ip]
US Social Security numbers [ssn]
IBANs (checksum-valid) [iban]
PEM private keys, API keys and tokens (sk-, sk_live_, rk_live_, AIza, ya29., xox?-, gh?_, AKIA/ASIA, JWTs, Bearer), passwords in URLs, api_key= / token: / password= values [secret]

Limits: patterns catch fixed shapes only. Names, postal addresses and free-form IDs are not caught, some phone shapes are missed, and an order number shaped like a phone number is masked. Text over 32,000 characters is not scanned: the field is withheld.

The redact hook runs after the built-in patterns, for what they cannot catch:

rudderstack.ai.configure(redact=lambda text: my_ner.mask_names(text))
rudderstack.ai.configure(redact=False)  # opt out of masking entirely

A hook that raises or returns a non-string drops the field, so unmasked text is never sent. redact=None restores the default. The patterns are shared with the Node.js SDK (spec/fixtures/redaction-v0.1.json).

rudderstack.ai.mask_text(text) applies the built-ins to text you send yourself, such as a declared tool event's properties, which are sent as returned.

Serverless and workers

The RudderStack client sends events from a background queue. Before a short-lived process or handler exits, flush:

import rudderstack.ai


def handler(event: object, context: object) -> object:  # AWS Lambda
    try:
        return run_agent(event)
    finally:
        rudderstack.ai.flush()  # inside an event loop: await rudderstack.ai.aflush()

flush() waits for pending classifications and evaluations, then drains every RudderStack client the SDK has used (the configured one and those passed to contexts, interactions, wrappers and tracing) until its queue is empty, all within one deadline: 10 seconds, or flush(timeout=...). It never raises, never ends open interactions, and returns False (reported as flush_timeout) when the deadline came first, so a data plane that never answers cannot hang the handler. Because it drains your client's queue, your own client.flush() afterwards has nothing left to fail on: when your client's flush() raises, the SDK passes your client's error, unchanged, to on_error as flush_failed (from flush(), shutdown(), ai_task and tracing.force_flush(), including an error raised after the deadline), and flush(), shutdown() and force_flush() return False, so handle flush errors there (Troubleshooting). rudder-sdk-python reports delivery errors to its own on_error as before. With tracing, also call tracing.force_flush() (or use processor="simple"), since spans wait in the span processor's batch.

A non-chained ai_task flushes for you: its classification (when opted in) and the flush share a 2 second deadline (ai_task(..., flush={"timeout": 5}) changes it), and a plain with inside a running event loop flushes on a thread without waiting.

Long-running servers. On shutdown, call shutdown(): it stops starting new classifications and evaluations, ends every interaction still open as response_status: incomplete with end_reason: shutdown, then flushes. It never closes your client, and the SDK installs no signal handlers:

import signal

signal.signal(signal.SIGTERM, lambda *_: rudderstack.ai.shutdown())  # or in your framework's shutdown hook

Scripts that just end. With flush_on_exit (on by default), an atexit hook flushes for at most 2 seconds when events were sent since the last flush. It runs before the RudderStack client's own exit hook, which sends only the batch in progress. configure(flush_on_exit=False) turns it off.

Production. Tracking failures are contained and reported through on_error (Troubleshooting). Memory is capped by limits (Configuration): past a cap new interactions run untracked, and an interaction left open for an hour is ended as incomplete with end_reason: ttl_expired. For bursty traffic, size the client: upload_size (events per request, 100 by default) and max_queue_size (10,000; past it events are dropped, reported as limit_reached).

Events

Event When
ai_user_prompt_created A user-triggered interaction starts (sent with its first model call)
ai_response_received The interaction ends: totals, status, models, cost, usage_breakdown
ai_user_action track_action(): feedback, copy, share, report, regenerate, accept, reject, edit, click-through
ai_interaction_classified The classifier or track_classification() labelled the interaction (opt-in)
ai_interaction_scored An evaluator or track_score() scored the interaction (opt-in)
ai_llm_response_received One per model call (opt-in, emit_llm_calls=True; do not sum it with the totals). Carries call_index and, with emit_spans, the matching span_id (overflow aggregates omit it); with capture_content also input_messages, input_truncated, output_text and output_tool_calls (personal data, masked like prompt_text; see docs/events.md)
your declared tool events One per call of a tool named in event_rules
mcp_* From a wrapped MCP server (MCP servers)

Every event carries conversation_id, interaction_id, feature and surface (where the user met the AI: web, slack, api...; set it on ai_context or the interaction) when set, and context.wrapperLibrary with the integration and specVersion. Property tables, sample payloads, cost rules and warehouse column types: docs/events.md. Load spec/rudderstack-catalog/ as a tracking plan before the first events arrive, so cost columns are created as decimals.

Every event's properties stay within 30,000 serialized bytes, since RudderStack rejects an event over 32 KiB. An event over that budget first shortens a call's input_messages (oldest after the system prompt), then loses its captured text (output_text, output_tool_calls, response_text, prompt_text, action_details.feedback_text), then tool_breakdown and usage_breakdown entries from the end, so its metrics still arrive; a declared tool event (chat or MCP) is sent without its properties() output.

Configuration

Option Default
analytics none Your RudderStack client (the rudderstack.analytics module or a Client). A client passed to an interaction, ai_context or integration wins.
prices none USD per 1M tokens ({"gpt-4.1-mini": {"input_per_mtok": 0.40, "output_per_mtok": 1.60}}), merged into the registry. Your rates; none ship with the package.
capture_content False Send prompt, response and feedback text (masked).
emit_llm_calls False Also send ai_llm_response_received per model call.
emit_spans False Send provider wrapper chat spans and manual span() operations, independently of emit_llm_calls; see tracing.
tool_breakdown False Add tool_breakdown to ai_response_received.
identity_from_cookies True Read the JavaScript SDK's cookies from a request.
redact built-in masking A (text) -> str hook run after masking, or False to turn masking off.
event_rules none {"tools": {name: rule}}: declared tool events.
classifier none Intent classification: {client, model, intents, ...} or {classify, ...}.
evaluator none (turn) -> score(s), sync or async: sends ai_interaction_scored after each successful answer.
server_feedback True False stops track_action() when the client app sends its own ai_user_action.
azure_deployment_models none {deployment: model}: price Azure OpenAI deployments as that model (Cloud model IDs).
on_error one warning per kind (error, {"kind", "where"}): told about every failure the SDK contained (Troubleshooting).
flush_on_exit True Flush for at most 2 s at interpreter exit when events were sent since the last flush.
sample_rates none {event_name: rate}: send that share of each event, keyed on interaction_id; kept events carry sample_rate (Sampling).
limits see Limits Limits(...) or {"max_open_interactions": ...}: memory caps (10,000 open interactions, a 1 h interaction TTL, 1,000 stored calls per interaction, 10,000 entries per integration map).

configure() changes only the options you pass; None clears analytics, event_rules, classifier, evaluator and azure_deployment_models, and restores the default redact. Prices match a model exactly or followed by a version suffix (-2025-04-14, -20251001, -0613, -v2, :0, @20241022, -latest): gpt-4o prices gpt-4o-2024-08-06, never gpt-4o-mini. A price can also carry tier_multipliers (by service_tier), long_context rates and server_tool_per_call fees (Cost). The full API is in docs/api.md; every public function has a docstring and type hints.

Sampling

sample_rates cuts the volume of high-frequency events, such as ai_llm_response_received and mcp_tool_called, at the source:

rudderstack.ai.configure(sample_rates={"ai_llm_response_received": 0.1, "mcp_tool_called": 0.05})
  • What is kept. An event with a rate below 1 is sent for that share of interactions. The draw is a hash of interaction_id (the same in the Python, Node.js and Go SDKs), so every sampled event of one interaction is kept or dropped together, and an interaction kept at a lower rate is also kept at every higher one. An event without an interaction_id (mcp_client_seen) is drawn at random.
  • The stamp. A kept event carries sample_rate (0.1); weight each row by 1 / sample_rate to estimate totals. Events without a rate below 1 carry none.
  • The default. Events you do not list are all sent. Leave ai_response_received out: cost totals, answer counts and the client/server gap need every answer, and its llm_call_count, tool_call_count and token totals still count the calls whose own events were sampled out. You can list it; then every metric built on it is an estimate.
  • Scope. It applies to the events the SDK sends through track (product, declared tool and MCP events). ai_otel_span events from tracing follow your OpenTelemetry sampler and the processor's filter.
  • Validation. Rates replace the previous ones; None clears them. A non-numeric rate raises TypeError; a rate outside 0 to 1 or an empty event name raises ValueError; either way nothing changes.

Sampling runs before the event reaches your RudderStack client, so it works with any client version. A before_enqueue hook on the client (where your rudder-sdk-python version has one) still sees every event the SDK sends, sample_rate included, and stays the place for app-wide drop and edit rules. A hook that drops some of the sampled events itself makes sample_rate overstate what arrived: sample in sample_rates, not in the hook.

Advanced: OpenTelemetry export

rudderstack.ai.tracing (the tracing extra) sends each AI span from your OpenTelemetry instrumentation to RudderStack as one ai_otel_span event, or, with register_tracing(product_events=True), builds the product events from spans instead of wrapping clients. Add create_span_processor() next to your vendor's processor, or let register_tracing() set one up. The span events join ai_response_received on interaction_id; trace_id is set from the spans only when you register the processor with link_trace_id=True (the join). Options, event shape and limits: docs/tracing.md.

Checking a migration

Moving AI events your app already sends through RudderStack to this SDK? The check extra adds a migration check; production code never imports it. Record the events while you drive the app, once per switch setting. In the test or harness, make the recorder the app's own RudderStack client where the app builds it, before the app calls configure() and reads its switches, so legacy calls and switch-off runs are recorded too:

from rudderstack.ai.testing import Recorder

app.analytics = Recorder("events.jsonl")  # wherever the app's rudderstack.analytics client comes from
pip install "rudderstack-ai[check]"
python -m rudderstack.ai.check events.jsonl --expect-legacy chatTurnCompleted \
  --feature support_bot --surface web --user-id demo_user_1 --expect-joins
python -m rudderstack.ai.check legacy-off.jsonl --absent chatTurnCompleted
python -m rudderstack.ai.check ai-off.jsonl --no-ai-events --expect-legacy chatTurnCompleted
python -m rudderstack.ai.check what-changes ai-off.jsonl events.jsonl  # redacted before/after diff for the PR

check validates every event against the spec this version emits (and client copies against the client-event schema), and checks that legacy events keep sending (--expect-legacy) or stop when their switch is off (--absent, counted by provenance: events without context.wrapperLibrary, so an AI event with the same name does not count), that no AI event is sent with the AI switch off (--no-ai-events), client/server joins in both directions (--expect-joins, feedback copies per action type included, honouring --client-opt-out client_prompt|client_response|client_feedback|server_feedback, --feedback-endpoint and --client-surface for surfaces with a browser client), that app-caught failures are not reported as success (--failed-interaction <id>), plus identity (--user-id, --expect-session, and --mcp-user-id or --mcp-anonymous for MCP servers), content capture and MCP flags (--help). Exit code 0 passes, 1 fails, 2 is bad usage or an unreadable file. The Node.js (npx @rudderstack/ai check) and Go (aicheck) SDKs ship the same check, with the same output.

Troubleshooting

Symptom Cause
No events, warning "no RudderStack client" configure(analytics=...) was not called before the first event.
Events missing in a script, worker or Lambda The process exited before the client's queue was sent: flush() (or shutdown() in a server).
Every model call is its own ai_response_received Calls run outside ai_interaction: in a thread pool (use propagate), in a stream that outlives the interaction (use bind(); a warning names the interaction), or with the LangChain handler on a model instead of the run config.
No cost No price registered for the model, or the name does not match (Configuration). A compatible endpoint that rejects stream_options sends no usage for streamed calls.
Cost column holds whole numbers The warehouse created it as an integer: docs/events.md.
No ai_interaction_classified The interaction was opened by an integration, the answer did not succeed, or an async client ran without an event loop (warning).
Prompt event arrives late It is held until the first model call starts, so it carries that call's integration tag.
register_tracing() raises RuntimeError The global provider is not an SDK TracerProvider, or already has a RudderStack processor. Use create_span_processor().

Set RUDDERSTACK_AI_DEBUG to any non-empty value (1, even 0; it is read on every log call) to log everything tracking drops or ignores at debug level on the rudderstack.ai and rudderstack.ai.tracing loggers: through your logging handlers when you configured any, else to stderr prefixed [rudderstack-ai]. Errors are logged by type only, never their message or traceback; event payloads and captured text are never logged. Without it, warnings still go the same way (most once each), and logging.getLogger("rudderstack.ai").setLevel(logging.DEBUG) turns on the debug records through your own handlers. Tracking never raises into your code.

Tracking failures are contained: your call, your result and your exception are never changed. Each one is reported once per kind as a warning, or to your hook:

def on_error(error: BaseException, info: rudderstack.ai.ErrorInfo) -> None:
    metrics.increment("rudderstack_ai.error", tags={"kind": info["kind"], "where": info["where"]})


rudderstack.ai.configure(on_error=on_error)  # at most one call per kind per minute

Kinds: internal (an SDK bug or a value it could not handle), user_callback (your redact, classifier, evaluator, event-rule or identify function raised; the documented fallback is used), limit_reached (a memory cap or the client's queue dropped data), redaction_timeout, flush_timeout, flush_failed (your RudderStack client's own flush() raised; the error passed is your client's, unchanged) and client_outdated. A hook that raises is ignored.

Compatibility

Supported Tested in CI
Python 3.12+ 3.12, 3.13, 3.14
openai >=2.0.0,<4 2.0.0 and latest
anthropic >=1.0.0,<2 1.0.0 and latest
google-genai >=2.0.0,<3 2.0.0 and latest
langchain-core >=1.2.0,<2 1.2.0 and latest, with LangGraph 1.x and Deep Agents 0.7
claude-agent-sdk >=0.2.82,<0.3 0.2.82 and latest
openai-agents >=0.8.4,<0.25 0.8.4 and latest
boto3 / botocore (Bedrock) >=1.37.24,<2 1.37.24 and latest
litellm >=1.88.6,<2 1.88.6 and latest
mcp (MCP servers) >=1.30.0,<3 1.30.0 and latest
opentelemetry-api / -sdk / -exporter-otlp-proto-common (tracing) >=1.30.0,<2 1.30.0 and latest
rudder-sdk-python 2.x, or any object with its track() signature 2.1.9
Web frameworks (middleware) Starlette/FastAPI, Django, Flask Starlette 1.7, Django 6.1, Flask 3.1

Upgrading to AI events spec v0.4

Events carry specVersion 0.4.0. The server schema and conformance fixture are now ai-events-v0.4.schema.json and conformance-v0.4.json. The client schema remains ai-client-events-v0.2.schema.json, following the v0.3 release precedent. The migration checker accepts both 0.3.0 and 0.4.0 captures.

  • One-shot and client events (SDK-5989): opt into one_shot=True for interactions without a thread. Client events cover prompts, suggestions, feedback, exports, conversation and agent controls, limits and declared tools on web and mobile.
  • Server fields (SDK-5990): blocked answers, denied tools, confidence, credits, per-call timing and purpose, fallback and BYOK flags, agent versions, variants, MCP result sizes, compaction and context_limit errors.
  • Sampling (SDK-5992): sample_rates controls each event; kept events carry sample_rate. Events of one interaction share a stable draw. Answers are unsampled by default.
  • Pause/resume (SDK-5991): paused and final answer segments share an interaction ID, including after JSON restore. Final answers carry pause counts and total paused time. Optional ai_task_started fires once per new background run.

Upgrading to 0.7.0

No API was removed.

  • app_error: an answer that fails in your own code after a successful model call has error_type: app_error, not api_error. An error from a model call, or one that carries a provider signal (HTTP status, provider error code or provider error class), keeps its type. Update queries that count api_error as all failures.
  • Usage on failed streams: a streamed call that fails partway keeps the tokens it already reported and still counts in llm_call_count (unpriced). A Claude Agent SDK run that ends without a result counts the calls its assistant messages reported.
  • MCP: a request that sends "_meta": null is now tracked like one without _meta.

Upgrading from 0.4.0 to 0.5.0

No API was removed. Events follow spec v0.3 (context.wrapperLibrary.specVersion 0.3.0): that release used ai-events-v0.3.schema.json and conformance-v0.3.json; the current schema and conformance fixture are v0.4. No field was renamed or removed, and every new field is optional. Behaviour changes:

  • Statuses. An answer whose last call was cut off at the output-token limit (finish_reason: length, Anthropic's, Bedrock's and the Claude Agent SDK's max_tokens, Gemini's MAX_TOKENS) is response_status: incomplete with error_type: length, and a filtered one (content_filter) is error; in 0.4.0 a completed call was success whatever its finish_reason. The call keeps its tokens and cost. A run stopped at a turn or budget cap (max_turns, max_budget_usd) is incomplete, no longer error; status_for_exception() follows the same rules.
  • paused answers carry pause_reason (approval, human_input, deferred_tool, auth_required, else other).
  • trace_id from spans is opt-in. In 0.4.0 the tracing span processor set it from the first span started inside the interaction; now trace_id is sent only when you pass one (trace_id=, set_trace_id()) or register the processor with link_trace_id=True (register_tracing(link_trace_id=True) or create_span_processor(link_trace_id=True)). A value you pass always wins.
  • Google provider labels. wrap_google_genai reports gcp.gemini (was google) and gcp.vertex_ai (was google.vertex), the names LangChain, LiteLLM and the Claude Agent SDK already sent. Update dashboards and filters on provider / primary_provider.
  • Gemini API and Vertex AI prices are separate. Prices registered for google and google.vertex keep working (they price gcp.gemini and gcp.vertex_ai). If your Vertex AI calls relied on a price registered for google, also register it with provider="gcp.vertex_ai" (Cloud model IDs and pricing).
  • OpenAI Agents SDK: a Responses API run cut off at the output-token limit is incomplete with error_type: length and keeps its last call's usage (was api_error without it). A response item reported incomplete is finish_reason: length (was incomplete), and a failed one is a failed call.
  • MCP _meta: rudderstack_mcp_tool_meta() sends com.rudderstack/trace_id when the interaction has a trace_id, and traceparent only when link_trace_id=True linked it and the active span is in that trace (before: traceparent whenever an OpenTelemetry span was active).
  • Event size. An event over the 30,000-byte properties budget is trimmed (Events) instead of being sent whole and rejected by RudderStack; a declared tool event is sent without its properties() output.
  • flush(), aflush() and a non-chained ai_task wait at most 10 seconds for the RudderStack clients; flush() returns False when one did not finish.
  • The all extra no longer installs tracing: add rudderstack-ai[tracing] if you export spans.
  • Declared tool event names starting with mcp_ are rejected, like ai_.
  • The classifier's default outcomes add escalated.
  • Masking also catches PEM private keys and Google ya29. tokens.
  • Claude Agent SDK calls carry reasoning_tokens when the CLI records thinkingTokens.
  • LangChain with Gemini: Gemini finish reasons are mapped as for Google Gen AI: MAX_TOKENS is length (an incomplete answer), SAFETY and the other blocked reasons content_filter (an error); before, both answers were success.
  • An OpenAI Responses or Anthropic stream that ends without its final event keeps the tokens seen so far (unpriced) on its failed call.

New in 0.5.0: MCP servers, scores (evaluator, track_score), surface, prompt attachments, the accepted / rejected / edited / clicked_through actions, server_feedback, service tiers, long-context and server-tool prices, and RUDDERSTACK_AI_DEBUG.

Upgrading from 0.2.0

No API was removed. Behaviour changes:

  • Masking is on. Captured prompt_text, response_text and feedback_text (and captured span content in ai_otel_span) arrive masked. configure(redact=False) restores the 0.2.0 output.
  • Price matching is stricter. A registered name prices only that model and its dated or versioned variants, no longer any model it is a prefix of. Register each model family you use (gpt-4o-mini separately from gpt-4o).
  • Cost rounding is half-up at 8 decimals, like the Node.js SDK (0.2.0 rounded half-to-even): about 1% of values differ by 1e-8.
  • LangChain providers use OpenTelemetry names: amazon_bedrock → aws.bedrock, google_vertexai → gcp.vertex_ai, google_genai → gcp.gemini, azure → azure.ai.openai. Update prices registered with provider= and dashboards grouped by provider.
  • Tracing identity (user.id, rudderstack.anonymous_id) is added only to AI spans, and never to spans inside ai_task.
  • ai_task chained inside another interaction no longer flushes by default (flush=True restores it).
  • A missing RudderStack client logs a warning (once) instead of a debug message; end(status=...) with an invalid status derives the status and warns instead of dropping the event.
  • Deprecated (still working, removed in 1.0): Interaction.adopt_analytics, note_integration, flush_prompt, record_span_call, note_outcome, mark_first_token, track_stream, untrack_stream; start_interaction(integration=...); and from rudderstack.ai.tracing: AnalyticsClient, __version__, the CONTENT_* constants, is_content_attribute, is_content_event.

New since 0.2.0: identity from cookies and rudderstack.ai.middleware, intent classification, declared tool events, tool breakdown, masking, flush() / aflush(), propagate(), estimate_cost(), register_prices(), error helpers. See the changelog.

Known limitations

  • OpenAI and Anthropic with_streaming_response and streamed with_raw_response emit spans with emit_spans=True, with HTTP status and without consuming the body or recording product usage. Non-streamed raw responses also finish only the span, without parsed usage or content. A non-streamed responses.create(background=True) is only queued; polling is not intercepted. Use record_call for its eventual usage.
  • A structured responses.parse() call cut off at the token limit raises while parsing, before the SDK returns the response: it is recorded as a failed call without its tokens.
  • A streamed LangChain ChatOpenAI call has no response_id (langchain-openai replaces it with a run ID).
  • openai-agents before 0.22.0 returns a failed or incomplete Responses response in a non-streamed run without raising and without its status: the call is reported as a success, unpriced, though it keeps its usage.
  • claude-agent-sdk before 0.2.126 drops ResultMessage.terminal_reason: an aborted run is reported as a success, and a deferred tool is detected from deferred_tool_use only.
  • The .stream() helpers are observed through a private attribute of the SDK; if a future SDK renames it, calls still work but go untracked (CI's latest-versions job catches it).
  • MCP: only servers are tracked (not MCP clients), on mcp 2.x and 1.x (2026-07-28 on 2.x only); windows and counters are in memory per server name, per process (details).
  • Python's own SDKs: the Claude Agent SDK's Python parser drops mcp_tool_use blocks before the SDK sees them; the OpenAI Agents SDK for Python drops a Chat Completions finish_reason (a completion cut off at the token limit is a success with finish_reason: stop) and reports a missing reasoning count as 0.
  • Node.js only: the Vercel AI SDK integration (and with it the Vercel AI Gateway). Python only: the LiteLLM SDK integration (Node.js covers LiteLLM through its proxy), the Django and Flask middleware, and aflush() next to the synchronous flush().

Contributing

See CONTRIBUTING.md and RELEASING.md. Report security issues as described in SECURITY.md.

License

MIT

For approvals and human input, task.pause(reason="approval") emits a paused segment and returns a JSON snapshot. Restore it with ai_task("job", resume=snapshot) in another worker, or call task.resume() in process. The final segment includes pause_count and total_paused_ms. configure(emit_task_started=True) exposes newly started tasks. See Pauses and resumes and the approval loop.

Metadata

Release files for rudderstack-ai 0.13.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rudderstack-ai 0.13.0
File Size Uploaded Provenance Actions
rudderstack_ai-0.13.0.tar.gz 328.4 kB With provenance Details for rudderstack_ai-0.13.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rudderstack-ai 0.13.0
File Interpreter ABI Platform Actions
rudderstack_ai-0.13.0-py3-none-any.whl Python 3 none any Details for rudderstack_ai-0.13.0-py3-none-any.whl

Total release size: 652.2 kB

Release files / rudderstack_ai-0.13.0.tar.gz

Download URL rudderstack_ai-0.13.0.tar.gz
Size 328.4 kB
Tags Source
SHA-256 checksum
How to use checksums
6b8220194d5459d6e65005c45313736fc44ffc307ad5027b6c4292d115fb25c1
BLAKE2b-256 checksum
How to use checksums
ba501e798577ff34617d4e3b93cdc25929dd0f31cd48673fb761ab66000df4f1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / rudderstack_ai-0.13.0-py3-none-any.whl

Download URL rudderstack_ai-0.13.0-py3-none-any.whl
Size 323.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e0698741f5c9ea7f75a178981daef9856db5d1db383a2fa8764c50db45187273
BLAKE2b-256 checksum
How to use checksums
019dcb78310a0e45d18377eda7108a4ffdce39c62a24e243efde3097c8adc1ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for rudderstack-ai 0.13.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for rudderstack_ai-0.13.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page