How do I trace a research agent built with the Claude Agent SDK?
Rius traces a research agent built with the Claude Agent SDK with an observe root span, one generation per query() loop, and your own spans for retrieval and each stage. The Claude Agent SDK drives the Claude Code runtime in a separate process, so Rius has no automatic hook for it and you add the spans yourself. Each model turn then shows its model, tokens and cost, and you set a session and a user so runs group by conversation and person.
How it works
The Claude Agent SDK runs the model inside the Claude Code process, not in yours. No model client runs in your code, so auto-instrumentation has nothing to patch. The Claude Agent SDK integration is manual and has two parts:
- An
observewrapper makes each task the rootAGENTspan. - A manual generation wraps the
query()loop. You fill it from the run’sResultMessagewith token usage, the real model id and the collected answer. Rius computes cost from those, as a list-price estimate in US dollars.
A research agent usually has stages such as plan, gather and synthesize. Add your own spans from Tracing your code on top of that integration:
- A run root. One
AGENTspan for the whole question, so every stage nests under it. - A step per stage. A bare
observeon each stage function makes aCHAINspan named after the function. - Retrieval. A
RETRIEVERspan around your own search code, with the data source and the documents returned. It records identifiers and scores, not document text. - A generation per Claude turn. One for each
query()loop, nested under its stage.
The runtime’s inner work, such as its own tool calls, sub-turns and file operations, produces no spans. The generation records the turn’s totals only. Retrieval that runs in your own code is fully visible.
Set it up
- Install the base SDK and the Claude Agent SDK. No extra applies, and the
claudeCLI must be installed and authenticated. Forinit()options and keys, see the integration page.
pip install glassflow-rius claude-agent-sdk- Wrap the
query()loop in a generation and fill it from theResultMessage. Then add a stage function for each step and a retrieval span around your search.search,d.id,d.scoreandd.textstand for your own search code.
import rius
from claude_agent_sdk import (
AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query,
)
from rius import SpanKind
rius.init(api_key="ri_...", service_name="research-agent")
MODEL = "claude-haiku-4-5"
async def run_turn(name: str, prompt: str) -> str:
options = ClaudeAgentOptions(model=MODEL, max_turns=1)
parts = []
with rius.start_as_current_generation(
name, 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
async def plan(question: str) -> str:
return await run_turn("plan_turn", f"List sub-questions for: {question}")
@rius.observe
def gather(sub_questions: str) -> list[str]:
with rius.start_as_current_span(
kind=SpanKind.RETRIEVER, data_source_id="research-corpus", top_k=5
) as obs:
obs.set_input(sub_questions)
docs = search(sub_questions)
obs.set_retrieved_documents([{"id": d.id, "score": d.score} for d in docs])
return [d.text for d in docs]
@rius.observe
async def synthesize(question: str, notes: list[str]) -> str:
return await run_turn("synthesize_turn", question + "\n\n" + "\n".join(notes))
@rius.observe(name="research", kind=SpanKind.AGENT)
async def research(question: str) -> str:
sub_questions = await plan(question)
notes = gather(sub_questions)
return await synthesize(question, notes)
async def handle(question: str, conversation_id: str, user_id: str) -> str:
with rius.user(user_id), rius.session(conversation_id):
return await research(question)-
Use a full model id such as
claude-haiku-4-5, not an alias such ashaiku, for both the CLI option and the generation. Cost is computed from the requested model, and an alias produces a generation with no cost. Keepprovider="anthropic"and pass the cache counts as the snippet does. Cache-heavy agent loops would undercount badly without them. -
Scope each conversation with
rius.session()and 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. Scope each request withrius.user()and pass an opaque id rather than an email. Without a session scope, each trace is its own session. Without a user scope, spans are anonymous.
What you get
Each question is one trace that looks like this:
research AGENT
├─ plan CHAIN
│ └─ plan_turn LLM model, tokens, cost
├─ gather CHAIN
│ └─ retrieval research-corpus RETRIEVER
└─ synthesize CHAIN
└─ synthesize_turn LLM model, tokens, cost- Tokens and cost on every Claude turn, so you see which stage spends the most.
- The documents each retrieval returned, with scores, to check what the agent had in front of it.
- Exceptions raised in a stage recorded on that stage’s span. A failed Claude turn does not raise: it ends with a
ResultMessagewhoseis_erroris true, so check that field and raise if you want the failure recorded. - Traces grouped by conversation through the session, and by person through the user, so one user’s research runs sit together.
To verify, run one question and open the trace in the console. The root AGENT span and each generation with a full model id, tokens and cost should be there. A generation without cost means an alias was used as the model id.
When something else fits
If you need to see the runtime’s own tool calls and sub-turns as separate spans, this setup does not show them, because they run inside the Claude Code process. If your research agent calls a model client directly in your own process, use the matching integration and keep the stage and retrieval spans from this page.