Anthropic Go tracing with Future AGI
Trace the Anthropic Go SDK (anthropic-sdk-go) with traceAI Go middleware: one LLM span per Messages call, including streaming and tool use, sent over OTLP.
traceaianthropic (module github.com/future-agi/traceAI/go/anthropic) traces Go services that call Claude with the official SDK, github.com/anthropics/anthropic-sdk-go. Install its middleware once with option.WithMiddleware when you build the client. Every Messages.New and Messages.NewStreaming call of that client becomes one LLM span with the request, the response, the model, the token counts and the finish reason. The SDK keeps its own HTTP client and retry policy.
A run of the example on this page is one trace:
weather-agent your agent span (AGENT)
├── anthropic.messages.create the model asks for get_weather (LLM)
├── execute_tool get_weather your tool span (TOOL)
└── anthropic.messages.create the final answer, streamed (LLM)
Use a different guide for:
| Module | github.com/future-agi/traceAI/go/anthropic v0.1.0 (package traceaianthropic) |
| Anthropic SDK | github.com/anthropics/anthropic-sdk-go v1.82.0 or later |
| Go | 1.26 or later |
| Source | traceAI go/anthropic |
1. Install
go get github.com/future-agi/traceAI/go/anthropic@v0.1.0 github.com/anthropics/anthropic-sdk-go@v1.82.0
The module brings the OpenTelemetry SDK and the OTLP/HTTP exporter in at the versions it requires. Run go mod tidy once your code imports them.
2. Set environment variables
export FI_API_KEY="your-futureagi-api-key"
export FI_SECRET_KEY="your-futureagi-secret-key"
export FI_PROJECT_NAME="my-service"
export ANTHROPIC_API_KEY="your-anthropic-api-key"
FI_BASE_URL is optional (default https://api.futureagi.com; set it to your own collector when you self-host). The Anthropic SDK reads ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL itself; the middleware reads neither.
3. Create the tracer provider
The module uses the OpenTelemetry API only and does not build an exporter. Use the stock OpenTelemetry OTLP/HTTP exporter with the three things Future AGI needs: both auth headers, the project_name resource attribute, and an uncompressed body (the collector rejects gzip).
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
traceaianthropic "github.com/future-agi/traceAI/go/anthropic"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
)
func newTracerProvider(ctx context.Context) (*sdktrace.TracerProvider, error) {
apiKey, secretKey := os.Getenv("FI_API_KEY"), os.Getenv("FI_SECRET_KEY")
project := os.Getenv("FI_PROJECT_NAME")
if apiKey == "" || secretKey == "" || project == "" {
return nil, errors.New("set FI_API_KEY, FI_SECRET_KEY and FI_PROJECT_NAME")
}
base := strings.TrimRight(envOr("FI_BASE_URL", "https://api.futureagi.com"), "/")
exp, err := otlptracehttp.New(ctx,
otlptracehttp.WithEndpointURL(base+"/tracer/v1/traces"),
otlptracehttp.WithHeaders(map[string]string{
"X-Api-Key": apiKey,
"X-Secret-Key": secretKey,
}),
otlptracehttp.WithCompression(otlptracehttp.NoCompression),
)
if err != nil {
return nil, err
}
res, err := resource.Merge(resource.Default(), resource.NewSchemaless(
attribute.String("project_name", project),
attribute.String("project_type", "observe"),
attribute.String("service.name", project),
))
if err != nil {
return nil, err
}
return sdktrace.NewTracerProvider(
sdktrace.WithResource(res),
sdktrace.WithBatcher(exp),
), nil
}
func shutdown(tp *sdktrace.TracerProvider) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := tp.Shutdown(ctx); err != nil {
fmt.Fprintln(os.Stderr, "trace export:", err)
}
}
resource.Default() adds only the SDK name and version and OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES if you set them. No host, process or OS detector is added, so no host name, user name or local path is exported.
4. Add the middleware and flush on exit
Build the client with the middleware, and give the SDK and the middleware the same tracer provider:
func newClient(tp *sdktrace.TracerProvider, opts ...option.RequestOption) anthropic.Client {
opts = append([]option.RequestOption{
option.WithTracerProvider(tp),
option.WithMiddleware(traceaianthropic.Middleware(traceaianthropic.WithTracerProvider(tp))),
}, opts...)
return anthropic.NewClient(opts...)
}
tp, err := newTracerProvider(ctx)
if err != nil {
return err
}
defer shutdown(tp) // flush before exit
// The SDK reads ANTHROPIC_API_KEY (and ANTHROPIC_BASE_URL) as usual.
client := newClient(tp)
anthropic-sdk-go v1.81.0 and later opens a span for each Messages call itself, named anthropic.messages.create, through the tracer provider you give it with option.WithTracerProvider (or the global one). The middleware adds the Future AGI attributes to that span, so one call is one span. Instead of passing the provider twice, you can register it once with otel.SetTracerProvider(tp), which covers both. If you turn the SDK’s spans off (option.WithoutOpenTelemetry() or ANTHROPIC_OPEN_TELEMETRY=false), the middleware opens a client span of its own with the same name and the same gen_ai.* attributes.
Call the SDK as usual. defer shutdown(tp) matters: the batch exporter sends spans in the background, and spans still queued when the process exits are lost.
A stream is one span:
s := client.Messages.NewStreaming(ctx, params)
defer s.Close()
var final anthropic.Message
for s.Next() {
if err := final.Accumulate(s.Current()); err != nil {
return "", err
}
}
No span is opened per event. The span gets the message the events assemble, and its token counts from the stream’s message_start and final message_delta events.
5. Sessions and your own spans
Put a session id on the context; every Messages span started from it carries session.id, and Future AGI groups those traces into one session. ContextWithUserID does the same for user.id (use an opaque id, not an email address). A call on a context without them gets neither; the module never invents one.
sessionCtx := traceaianthropic.ContextWithSessionID(ctx, *session)
answer, err := runAgent(sessionCtx, client, tracer, *model, *question, *stream)
The middleware spans the model calls. Your agent loop and your tool code are yours to span. SessionIDFromContext and UserIDFromContext read the ids back, so your own spans can carry them too:
func contextAttributes(ctx context.Context) []attribute.KeyValue {
var attrs []attribute.KeyValue
if id, ok := traceaianthropic.SessionIDFromContext(ctx); ok {
attrs = append(attrs, attribute.String("session.id", id))
}
if id, ok := traceaianthropic.UserIDFromContext(ctx); ok {
attrs = append(attrs, attribute.String("user.id", id))
}
return attrs
}
ctx, agent := tracer.Start(sessionCtx, "weather-agent", trace.WithAttributes(
attribute.String("gen_ai.span.kind", "AGENT"),
attribute.String("gen_ai.operation.name", "invoke_agent"),
attribute.String("gen_ai.agent.name", "weather-agent"),
), trace.WithAttributes(contextAttributes(sessionCtx)...))
Tool calls the model asks for are recorded on the LLM span; the middleware does not span your tool code. The example adds a TOOL span of its own:
_, span := tracer.Start(ctx, "execute_tool "+tu.Name, trace.WithAttributes(
attribute.String("gen_ai.span.kind", "TOOL"),
attribute.String("gen_ai.operation.name", "execute_tool"),
attribute.String("gen_ai.tool.name", tu.Name),
attribute.String("gen_ai.tool.call.id", tu.ID),
), trace.WithAttributes(contextAttributes(ctx)...))
defer span.End()
The example’s custom agent and tool spans contain only identity, session and status metadata, never prompts, answers, tool arguments or results. Content is captured only by the middleware, under the privacy settings. The FI_HIDE_* settings do not filter attributes you set yourself; if you add content to your own spans, check traceaianthropic.TraceConfigFromEnv() first.
6. Run the example
The complete program (agent span, a get_weather tool call, the tool span, a streamed answer, a failing call) is examples/traceai/anthropic-go/main.go in this docs repo. In a directory with main.go:
go mod init example.com/anthropic-go-example
go get github.com/future-agi/traceAI/go/anthropic@v0.1.0 github.com/anthropics/anthropic-sdk-go@v1.82.0
go mod tidy
go run . -stream -fail
It prints the trace id. Open Observe → your project → Tracing: the LLM spans show the model, provider anthropic, input, output and cache token counts, and the conversation (system instruction, user turn, the model’s tool call, the tool result, the answer). The -fail call is a separate trace with an ERROR span.
What is captured
| Attribute | When |
|---|---|
gen_ai.span.kind = LLM, gen_ai.operation.name = chat, gen_ai.provider.name = anthropic | every Messages call |
gen_ai.request.model, gen_ai.response.model, gen_ai.response.id | from the request and the response |
gen_ai.usage.input_tokens | every input token: the API’s input_tokens plus its cache read and cache creation tokens, as the OpenTelemetry GenAI conventions for Anthropic require and as the SDK’s own span does |
gen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_write.input_tokens | the two cache counts, on their own keys. Uncached input is gen_ai.usage.input_tokens minus both |
gen_ai.usage.output_tokens, gen_ai.response.finish_reasons | from the response, or the stream’s final message_delta |
input.value, output.value | the request body and the response message (for a stream, the message the events assemble), as JSON; content, on by default |
gen_ai.input.messages, gen_ai.system_instructions, gen_ai.output.messages | the messages as JSON in the GenAI shape, including tool_call and tool_call_response parts; content, on by default |
gen_ai.tool.definitions, gen_ai.request.parameters | the request’s tools, and its settings (max_tokens, temperature, top_p, top_k, stream, tool_choice, thinking, service_tier) |
session.id, user.id | only from ContextWithSessionID and ContextWithUserID |
error.type, span status ERROR | on errors (see Errors) |
For example, a response with 12 uncached input tokens, 100 cache-read tokens and 20 cache-write tokens gives gen_ai.usage.input_tokens = 132, gen_ai.usage.cache_read.input_tokens = 100 and gen_ai.usage.cache_write.input_tokens = 20.
Who sets these depends on who opens the span. With the SDK’s own span (the default), anthropic-sdk-go sets the model, response id, token counts, status and error.type, and the middleware adds the span kind, the content, the tool definitions, the request parameters, the finish reasons and the session and user ids. With the SDK’s spans off, the middleware sets all of them itself, with the same keys and the same token arithmetic.
Never captured, in any mode: the Anthropic API key and other request headers, the Future AGI keys, the authorization_token of an MCP server in a request body, error message text in the span status or error.type, and stack traces. The span that anthropic-sdk-go opens also carries the SDK’s own attributes, such as the API address in server.address and url.full.
Privacy
Content is captured by default, as in every traceAI instrumentor. The traceAI switches, with the same names and defaults as the Python package, turn it off. They are read once, when Middleware is called, so set them before you build the client, or pass traceaianthropic.WithTraceConfig(traceaianthropic.TraceConfig{...}).
| Variable | Effect |
|---|---|
FI_HIDE_INPUTS=true | input.value becomes __REDACTED__; no input messages, system instructions, tool definitions or stop sequences |
FI_HIDE_OUTPUTS=true | output.value becomes __REDACTED__ (including an API error body); no output messages |
FI_HIDE_INPUT_MESSAGES=true / FI_HIDE_OUTPUT_MESSAGES=true | drop gen_ai.input.messages and gen_ai.system_instructions / gen_ai.output.messages; keep input.value / output.value |
FI_HIDE_INPUT_TEXT=true / FI_HIDE_OUTPUT_TEXT=true | the text of every part of the input / output messages, including tool-call arguments and tool results, becomes __REDACTED__; keep roles, tool names and ids |
FI_HIDE_INPUT_IMAGES=true | leave image and document parts out of the input messages, and replace image data in input.value with __REDACTED__ |
FI_HIDE_LLM_INVOCATION_PARAMETERS=true | drop gen_ai.request.parameters |
FI_BASE64_IMAGE_MAX_LENGTH | longest base64 image or document kept in input.value (default 32000) |
A switch is true or false in any case; any other value logs a warning and keeps the default, false. The model, token counts, finish reason and error type stay in every mode.
The message and text switches alone do not keep content out of input.value and output.value. Those keep the full request body and response message. To withhold prompts and answers from telemetry, set FI_HIDE_INPUTS=true and FI_HIDE_OUTPUTS=true.
Tool data follows the conversation. The model’s tool-call arguments are output of the call that asks for the tool, and input of the next call, which sends them back with your tool result. To hide tool data across a conversation, set both FI_HIDE_INPUTS=true and FI_HIDE_OUTPUTS=true.
The SDK’s content mode. anthropic-sdk-go’s own span carries no content unless you set ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content (or option.WithOpenTelemetryTracesContentMode). Leave it unset: the SDK does not read the FI_HIDE_* switches, so with it set, the SDK exports content they do not remove. The middleware logs a warning when the variable is set together with one of the content switches: FI_HIDE_INPUTS, FI_HIDE_OUTPUTS, FI_HIDE_INPUT_MESSAGES, FI_HIDE_OUTPUT_MESSAGES, FI_HIDE_INPUT_TEXT or FI_HIDE_OUTPUT_TEXT. FI_HIDE_INPUT_IMAGES and FI_HIDE_LLM_INVOCATION_PARAMETERS do not trigger it.
The switches change exported telemetry only, never the requests sent to Anthropic or the answer your program prints.
Errors, cancellation and retries
- An HTTP 4xx or 5xx response ends the span with status ERROR and
error.typeset to the API’s error type, such asrate_limit_errororauthentication_error, never the error message. With content on,output.valueholds the API’s error body;FI_HIDE_OUTPUTS=truehides it. The SDK still returns its*anthropic.Errorto you unchanged. - A stream is one span, whether it ends normally, fails, is closed early or its context is canceled. With the SDK’s own span (the default), the SDK sets the span’s status. When the middleware opens the span itself (SDK spans off), a stream
errorevent, a stream that ends beforemessage_stop, a canceled or timed-out context, or closing the stream before its end marks the span ERROR, witherror.typesuch asoverloaded_error,api_error,canceledortimeout. - The SDK retries some failures itself (
option.WithMaxRetriessets how many). With the SDK’s own span, a retried call is still one span. With the SDK’s spans off, the middleware runs once per HTTP attempt, so each attempt is its own span and a retry carrieshttp.request.resend_count. Calling again after an error is a new call and a new span; start a span around the calls, as the example’s agent span does, so they share one trace.
Not supported
- The middleware adds nothing to other endpoints (
count_tokens, batches, files, models). Only Messages calls are traced. - Amazon Bedrock and Google Vertex AI clients of the same SDK accept the middleware, but this guide does not cover them.
- Cost is not computed in Go; Future AGI prices the model from the token counts.
Troubleshooting
- No traces. Check that the process calls
shutdown(tp)(ortp.Shutdown) before it exits, and thatFI_API_KEY,FI_SECRET_KEYandFI_PROJECT_NAMEare set. The exporter URL must be the full traces URL,{FI_BASE_URL}/tracer/v1/traces. - Export errors about the body. Keep
otlptracehttp.WithCompression(otlptracehttp.NoCompression); the collector rejects gzip. - Spans in the wrong project or none at all.
project_namemust be a resource attribute on the tracer provider, not a span attribute. - Spans missing Future AGI attributes, or in another provider. The SDK opens the span through the provider you give it with
option.WithTracerProvider(or the global one), and the middleware adds its attributes to that span. Give both the same provider, asnewClientdoes, or callotel.SetTracerProvider(tp)once. - Content exported although
FI_HIDE_*is set. UnsetANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE, and set the switches before the client is built. - Every retry is a separate trace. Start a parent span around the call (step 5).
Questions & Discussion