How do I trace an agent built with the Claude Agent SDK and deployed to a Kubernetes deployment?
Rius traces a Claude Agent SDK agent on Kubernetes with one rius.init() at process start, an observe root for each task, and a manual generation filled from the run result. Call init() once at module level, name the agent with service_name or RIUS_AGENT_NAME, and call client.shutdown() when the pod receives SIGTERM. Each task then arrives as a trace with tokens and cost, and each running process shows up as its own instance.
How it works
The Claude Agent SDK drives the Claude Code runtime in a separate process, so no model client runs in your process and auto-instrumentation has nothing to hook. Coverage is manual and has two pieces. An observe wrapper makes each task the root AGENT span. A manual generation wraps the query() loop and is filled from the run’s ResultMessage with token usage, the real model id and the answer. Rius computes cost on its side from those tokens. The runtime’s inner steps, such as tool calls and file operations, produce no spans, so you see the turn’s totals only. A failed run does not raise: it ends with a ResultMessage whose is_error is true, so check that field if you want the task to fail. This is the one integration that needs this manual layer. The Claude Agent SDK integration page has the full recipe, and Integrations lists the rest.
Three things matter in a long-running deployment:
- Where init goes. A pod runs one long-lived process, so call
init()once at import time, before the first task. Do not call it inside a request or task handler. - Shutdown. Spans export in batches from a background thread. Kubernetes stops a pod with
SIGTERM, and Python’s default response ends the process without running the exit hook that would drain the queue. The SDK installs no signal handlers, so an unhandledSIGTERMor aSIGKILLloses the last batch and skips the finalstoppedheartbeat, and the instance reportsgone, which is how Rius shows a crash. Callclient.shutdown()from aSIGTERMhandler for a clean stop. - The agent name. The agent is grouped under the service name unless you set
RIUS_AGENT_NAME. Each process has its own instance ID, so replicas show as separate instances under one agent.
Set it up
- Install the SDK in your image with
pip install glassflow-rius claude-agent-sdk. The base package is enough, no extra applies. TheclaudeCLI must also be installed and authenticated in the image. The runtime uses the CLI’s auth, and an exportedANTHROPIC_API_KEYtakes precedence over a claude.ai login, so in a pod passANTHROPIC_API_KEYfrom a Secret. - Set the Rius settings as environment variables on the container:
RIUS_API_KEYfor your ingest key, from a Secret rather than baked into the image,RIUS_SERVICE_NAMEfor the agent’s name, and optionallyRIUS_AGENT_NAMEif the grouping name should differ from the service name. SetRIUS_MAIN_AGENT_VERSIONto your release, because that is the version the Agents page compares across rollouts. With these set,rius.init()needs no arguments. - Call
init()at module level, wrap each task inobservewith theAGENTkind, and fill the generation from theResultMessage:
import rius
from claude_agent_sdk import (
AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query,
)
from rius import SpanKind
client = rius.init() # reads RIUS_API_KEY and RIUS_SERVICE_NAME from the environment
MODEL = "claude-haiku-4-5"
@rius.observe(name="handle-task", kind=SpanKind.AGENT)
async def handle_task(task: str) -> str:
options = ClaudeAgentOptions(model=MODEL, max_turns=1)
parts = []
with rius.start_as_current_generation(
"claude_agent_turn", model=MODEL, provider="anthropic", input=task
) as gen:
async for message in query(prompt=task, options=options):
if isinstance(message, AssistantMessage):
parts.extend(
b.text for b in message.content if isinstance(b, TextBlock)
)
elif isinstance(message, ResultMessage):
usage = message.usage or {}
gen.set_usage(
input_tokens=usage.get("input_tokens"),
output_tokens=usage.get("output_tokens"),
cache_read_input_tokens=usage.get("cache_read_input_tokens"),
# Anthropic's payload still calls the write count "cache creation"
cache_write_input_tokens=usage.get("cache_creation_input_tokens"),
)
models = list((message.model_usage or {}).keys())
if models:
gen.set_response_model(models[0])
answer = "".join(parts)
gen.set_output(answer)
return answer- Use a full model id such as
claude-haiku-4-5, not an alias such ashaiku. An alias produces a generation with no cost. Keepprovider="anthropic"so the cache counts are added to the input tokens for you. - Shut the client down on
SIGTERM, never inside a task handler. If your server already handlesSIGTERM, such as uvicorn, callclient.shutdown()in its shutdown hook instead, for example a FastAPI lifespan. Start the process in exec form (CMD ["python", "app.py"]) so it receives the signal as PID 1. Kubernetes waitsterminationGracePeriodSeconds(30 by default) before it sendsSIGKILL, so leave room for the final export. Read Reliability for the full rules.
import signal
import sys
def on_sigterm(signum, frame):
client.shutdown() # drain queued spans, send the stopped heartbeat
sys.exit(0)
signal.signal(signal.SIGTERM, on_sigterm)- Scope each conversation with
rius.session(), using your own conversation id. The Claude Agent SDK’ssession_idonly arrives in the messages after the root span has started, so it can name the session only when you resume a stored conversation.
What you get
- One trace per task: a root
AGENTspan and a child generation with the model, tokens and a list-price cost estimate in US dollars. - An agent in the Agents view named after your service or
RIUS_AGENT_NAME, with one instance per running process. The heartbeat is on by default and needs the API key. - Version comparison across rollouts when you set
RIUS_MAIN_AGENT_VERSION. - A clean
stoppedsignal on a graceful shutdown, so a deliberate stop reads differently from a crash. - Optionally, a content-free snapshot of each span at start when you set
RIUS_PARTIAL_SPANSto true. A run that is still going is visible, and a run that dies with its process leaves a record.
When something else fits
- If your code calls the Anthropic API directly instead of driving the Claude Code runtime, the Anthropic auto-instrumentation records each model call, so you need no manual generation.
- If you need to see tool calls and sub-turns inside the Claude Code runtime, note that this integration records only the turn’s totals.