Docs Learn
Tracing
Add anthropic4s-otel4s and pass a telemetry to the client. Nothing else in your code changes.
You will learn
- How to build a traced client with otel4s
- What a span records, and what it leaves out by default
- How to trace an agent run you already have
Switch it on#
Build an OtelTelemetry from your tracer provider and hand it to Anthropic4s.resource:
for {
telemetry <- OtelTelemetry[IO](otel.tracerProvider)
client = Anthropic4s.resource[IO](config, telemetry)
} yield client
What a trace shows#
- Each API request is a
CLIENTspan, retries included. - An agent run is one tree, with a span per request and per tool call.
- Model, token usage, stop reason and request ids are recorded as
gen_ai.*andanthropic.*attributes.
Trace an agent you already have#
The Traced example runs the WeatherAgent
unchanged: the agent takes any AnthropicClient[IO], so it is given a traced one. Spans go over
OTLP to localhost:4318 unless OTEL_EXPORTER_OTLP_ENDPOINT says otherwise, and
docker compose up -d in the repository starts a collector with Grafana on
http://localhost:3000.
object Traced extends IOApp.Simple {
def run: IO[Unit] =
OtelJava.autoConfigured[IO]().use { otel =>
for {
// Content mode also records prompts, replies and tool arguments, which makes a demo trace
// readable. The default, MetadataOnly, is the right choice for real user data.
telemetry <- OtelTelemetry[IO](
otel.tracerProvider,
OtelConfig.default.withContentMode(ContentMode.Content)
)
config <- AnthropicConfig.fromEnv[IO]
// One trace: the runner span, a span per request, a span per tool call.
_ <- Anthropic4s.resource[IO](config, telemetry).use(WeatherAgent.agent)
} yield ()
}
}
The overview page has Grafana Tempo screenshots of this exact run: six spans, 7.55 seconds.
Recap
OtelTelemetry[IO](otel.tracerProvider), thenAnthropic4s.resource[IO](config, telemetry).- A span per request and per tool call; one tree per agent run.
- No prompt text on spans unless you choose
ContentMode.Content.
Every snippet on this page is copied, character for character, from the
anthropic4s repository: its README, docs/play.md or examples/,
which compiles with the build.