Instrument an Anthropic agent
Trace Claude requests including tool use, streaming, and cache reads, without changing how your agent is written.
Before you start
- Node.js 20 or newer
- An Lilium project API key
- An agent built on the Anthropic TypeScript or Python SDK
Claude agents lean heavily on multi-turn tool use, which is exactly the structure a flat log loses. This guide produces a trace where each tool call sits underneath the model turn that requested it.
#Install and initialize
-
Install the SDK.
npm install @lilium/tracing @anthropic-ai/sdk -
Create one session for each logical agent run.
import { startSession } from '@lilium/tracing' const session = startSession({ agentId: 'research.agent', environment: process.env.NODE_ENV, })
#Keep your Anthropic client
import Anthropic from '@anthropic-ai/sdk'
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })For streaming calls, keep the corresponding Lilium span open until the stream completes.
#Trace the agent loop
A Claude agent usually loops until the model stops requesting tools. Wrap the whole loop, not each iteration, so the trace reflects one unit of work.
import { startSession } from '@lilium/tracing'
export async function research(question: string) {
const session = startSession({
name: 'research',
agentId: 'research.agent',
environment: process.env.NODE_ENV,
})
try {
const result = await session.run(async () => {
const messages = [{ role: 'user' as const, content: question }]
for (let turn = 0; turn < 8; turn += 1) {
const modelSpan = session.startSpan({
type: 'llm_call',
name: 'anthropic.messages.create',
provider: 'anthropic',
model: 'claude-sonnet-4-5',
input: { messages, tools },
})
let response
try {
response = await anthropic.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 2048,
tools,
messages,
})
modelSpan.end({
output: response.content,
promptTokens: response.usage.input_tokens,
completionTokens: response.usage.output_tokens,
metadata: {
cacheReadTokens: response.usage.cache_read_input_tokens ?? 0,
cacheCreationTokens: response.usage.cache_creation_input_tokens ?? 0,
},
})
} catch (error) {
modelSpan.end({ status: 'error', error })
throw error
}
if (response.stop_reason !== 'tool_use') {
return response
}
const results = await Promise.all(
response.content
.filter((block) => block.type === 'tool_use')
.map((block) =>
modelSpan.traceToolCall(
block.name,
() => runTool(block),
{ input: block.input },
),
),
)
messages.push({ role: 'assistant', content: response.content })
messages.push({ role: 'user', content: results })
}
throw new Error('Research agent exceeded its turn limit')
})
await session.end({ output: result })
return result
} catch (error) {
await session.end({ status: 'error', error })
throw error
}
}#Control captured payloads
Research agents often handle text you do not want leaving your infrastructure. Redact values
before attaching them to input or output, or omit those fields and keep only timing,
provider, model, and token metadata.
const safeQuestion = question.replace(/\b[\w.]+@[\w.]+\b/g, '[email]')
const span = session.startSpan({
type: 'llm_call',
name: 'anthropic.messages.create',
input: { question: safeQuestion },
})#Verify the trace
One root span named research, one child per model turn, and one grandchild per tool call.
Token counts should appear on each model turn, with cache usage available in metadata.
#Where to go next
Traces and spans explains the data model, and
measuring agent cost covers the attribution
dimensions worth setting on metadata while you are here.
Common questions
Attach cache creation and cache read counts as span metadata until dedicated native fields are available. OpenTelemetry integrations that emit standard GenAI cache attributes are enriched automatically.
Wrap each executed tool with session.traceToolCall. Its arguments, result, timing, and failure state then appear as a first-class tool span.
This guide covers the TypeScript package. Python can export standard OpenTelemetry spans to the same OTLP endpoint, but there is not yet a matching native Python package.