NewSpan / End calls required.
The sub-modules are separate Go modules so you only pull in the provider SDK you actually use.
Install
How context-based trace-carrying works
Both instruments read the active trace from thecontext.Context you pass to each call. tl.NewTrace stores the trace in the context it returns. You pass that context down through your call stack — including to the instrumented client — and the instrument picks up the trace automatically.
InstrumentOpenAI
*openai.Client. The returned *InstrumentedOpenAIClient intercepts Chat.Completions.New and records each call as a SpanTypeLLM span on the active trace.
What is recorded automatically
| Field | Source |
|---|---|
span.name | "openai.chat.completions" |
span.type | "llm" |
span.model | params.Model |
span.input | Last user message from params.Messages |
span.output | response.Choices[0].Message.Content |
span.prompt_tokens | response.Usage.PromptTokens |
span.completion_tokens | response.Usage.CompletionTokens |
span.error | Error message if Chat.Completions.New returns a non-nil error |
Full example
Chat.Completions.New call is traced as a child span of "summarise-article" automatically. You do not need to open or close the span manually.
InstrumentAnthropic
*anthropic.Client. The returned *InstrumentedAnthropicClient intercepts Messages.New and records each call as a SpanTypeLLM span on the active trace.
What is recorded automatically
| Field | Source |
|---|---|
span.name | "anthropic.messages" |
span.type | "llm" |
span.model | params.Model |
span.input | Serialised params.Messages |
span.output | First text block in response.Content |
span.prompt_tokens | response.Usage.InputTokens |
span.completion_tokens | response.Usage.OutputTokens |
span.error | Error message if Messages.New returns a non-nil error |
Full example
Nil-trace passthrough behaviour
Both instruments check for an active trace in the context before opening a span. If the context carries no trace — for example, because a code path calls the provider client outside aNewTrace block — the instrument calls the underlying provider method directly and returns its result unchanged. No span is recorded and no error is returned.
This means you can safely instrument a shared client instance that is called from both traced and untraced code paths.
Combining auto-instrumentation with manual spans
Auto-instrumented spans are children of the active trace, at the same level as any manual spans you open. You can mix both styles freely:"vector-search" retrieval span followed by the auto-recorded "openai.chat" LLM span.
Accessing the active trace in other helpers
If you need to annotate the trace from inside a helper that only receives a context, usetrulayer.TraceFromContext:
trulayer.SpanFromContext to access the innermost active span: