How do I trace a data analysis agent built with the Claude Agent SDK?
Rius traces a Claude Agent SDK data analysis agent with an observe root span for each task and a manual generation filled from the run’s ResultMessage, so every analysis gets tokens and cost. You then add your own spans for retrieval and for each stage, and scope a session and a user around the run. The Claude Agent SDK drives the Claude Code runtime in a separate process, so Rius has nothing to hook automatically and you add this tracing yourself.
How it works
The Claude Agent SDK runs the model in a separate Claude Code process, so no model client runs in your code. The Claude Agent SDK integration is therefore explicit, in two pieces:
- An
observewrapper withkind=SpanKind.AGENTmakes each task the root span. - A manual generation wraps the
query()loop. You fill it from theResultMessagewith token usage, the real model id and the collected answer. Rius computes cost from the model and tokens, as list-price estimates in US dollars.
A data analysis agent has more structure than one model turn, and the code in your own process can add it with observe and generic spans:
- A run root. One
AGENTspan per question, so each analysis is one trace. - Retrieval. A
RETRIEVERspan for the lookup of schemas, tables or documents before the model runs. It records the data source id, how many documents you asked for, and the ids and scores of what came back. These are metadata, not document text. - A step per stage. A function wrapped with
observefor each stage of your pipeline, such as picking tables or analyzing. A bareobservemakes aCHAINspan named after the function. - Session and user.
rius.session()groups the turns of one conversation.rius.user()ties traces to the person asking. Both stamp every span started inside the scope.
The runtime’s own work, such as its tool calls, sub-turns and file operations, happens inside the Claude Code process. The generation records the turn’s totals only.
Set it up
- Install the SDK next to the Claude Agent SDK. The base package is enough, and the
claudeCLI must be installed and authenticated.
pip install glassflow-rius claude-agent-sdk- Build the run root, the retrieval span, a stage step and the generation. Names such as
pick_tables,search_catalogandschema-catalogare your own. Use a full model id such asclaude-haiku-4-5, not an alias likehaiku, because an alias produces a generation with no cost.
import rius
from claude_agent_sdk import (
AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query,
)
from rius import SpanKind
rius.init(api_key="ri_...", service_name="data-analysis-agent")
MODEL = "claude-haiku-4-5"
@rius.observe(name="pick-tables")
def pick_tables(question: str) -> list:
with rius.start_as_current_span(
kind=SpanKind.RETRIEVER, data_source_id="schema-catalog", top_k=5
) as obs:
obs.set_input(question)
docs = search_catalog(question) # your own lookup
obs.set_retrieved_documents([{"id": d.id, "score": d.score} for d in docs])
return docs
@rius.observe(name="analyze")
async def analyze(question: str, docs: list) -> str:
prompt = f"{question}\n\nTables: {[d.id for d in docs]}"
options = ClaudeAgentOptions(model=MODEL, max_turns=1)
parts = []
with rius.start_as_current_generation(
"claude_agent_turn", model=MODEL, provider="anthropic", input=prompt
) as gen:
async for message in query(prompt=prompt, 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"),
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
@rius.observe(name="handle-task", kind=SpanKind.AGENT)
async def run_analysis(question: str) -> str:
docs = pick_tables(question)
return await analyze(question, docs)- Scope the session and the user around each request. Use your conversation id and an opaque user id rather than an email.
async def handle(question: str, conversation_id: str, user_id: str) -> str:
with rius.session(conversation_id):
with rius.user(user_id):
return await run_analysis(question)The Claude Agent SDK’s session_id only arrives in the messages after the root span has started, so it can name the session only when you resume a stored conversation. See Tracing your code for span kinds, sessions and users in full.
- Run one question and open the trace in the console. Check for the root
AGENTspan, the retrieval span, your stage steps, and the generation with a full model id, tokens and cost.
What you get
- One trace per question, with the run root at the top and the retrieval and stage spans nested under it.
- The generation with the model, token counts including cache reads and writes, and a cost computed by Rius.
- A trace shape like this one:
handle-task AGENT
├─ pick-tables CHAIN
│ └─ retrieval schema-catalog RETRIEVER
└─ analyze CHAIN
└─ claude_agent_turn LLM claude-haiku-4-5, tokens + cost- Retrieval spans that show which data source was searched and the ids and scores of the documents returned.
- Traces grouped by session and attributed to users, so you can follow one conversation or one person across runs.
- The runtime’s inner steps are not spans. The generation covers the whole turn as one unit.
When something else fits
- If you need a span for every step the Claude Code runtime takes internally, this integration does not provide it. The generation records the turn’s totals only.
- If your analysis code also calls a model client in your own process, the matching integration on the Integrations page records those calls automatically, with no manual generation.