Skip to content

Use your own OpenTelemetry SDK

View as Markdown

weft’s core reports every run through the OpenTelemetry API, its one dependency. Register an SDK globally and every agent’s spans and log records reach it with no weft option; or pass your providers to one agent with weft.TracerProvider and weft.LoggerProvider. Exporters and backends stay yours; weft/otel is one way to configure them, not a requirement.

Give an agent an SDK tracer provider and logger provider, in otelx/main.go:

otelx/main.go
spans := tracetest.NewInMemoryExporter() // your exporter: OTLP, stdout, a vendor's
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(spans))
defer func() { _ = tp.Shutdown(ctx) }()
records := &recordKinds{}
lp := sdklog.NewLoggerProvider(sdklog.WithProcessor(sdklog.NewSimpleProcessor(records)))
defer func() { _ = lp.Shutdown(ctx) }()
agt := weft.New(script(), weft.Name("support-bot"), lookup,
weft.TracerProvider(tp), // spans: invoke_agent › chat, execute_tool
weft.LoggerProvider(lp), // records: events, deltas, transcript batches
)
if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
return err
}

otelx/main.go on GitHub

The in-memory exporters stand in for yours: an OTLP exporter, stdout, a vendor’s.

The core’s only dependencies are the OTel trace API (go.opentelemetry.io/otel v1.46.0, with semconv v1.41.0) and the Logs API (go.opentelemetry.io/otel/log v0.22.0); the SDK, exporters and weft/otel live outside it.

weft.TracerProvider(tp) sets the provider the agent’s runs report spans to. Without it, runs use the global tracer provider of go.opentelemetry.io/otel, a no-op until an SDK registers one. So a program that sets up an SDK globally gets weft’s spans with no option, and a test or a program that injects its dependencies passes its own provider instead of touching the global.

weft.LoggerProvider(lp) does the same for records, through the OTel Logs API (go.opentelemetry.io/otel/log): the run’s events, deltas, transcript batches and request records. Without it, runs use the Logs API’s global provider. Agent.LoggerProvider() returns the provider an agent emits through, for code whose own records must land beside the run’s: weft/thread’s compaction marker uses it. Two more accessors, since 0.18.0, serve the same code. Agent.TracerProvider() returns the tracer provider the runs open their spans on, the option’s value or the global resolved at New; weft/thread opens its summarizer’s chat spans through it. Agent.ContentCapture() returns (capture, set bool): set is false when no weft.Content option was given (content then follows the logger, as below), and capture is the option’s value when it was. weft/thread asks it, so Content(false) keeps its session records’ content out as it keeps the runs’. ExampleAgent_ContentCapture reads all three back.

The globals are read once, at weft.New. Before any SDK is set, the OTel API’s global is a placeholder that forwards to the first provider ever set, and only that one. An SDK registered after New therefore reaches the agent only when it is the process’s first global registration. An agent built after a provider was already set keeps that provider for good, whatever is set later.

Content follows the provider’s answer. The core asks the logger’s Enabled before it puts content into a record, unless the agent says otherwise with weft.Content: Content(true) always, Content(false) never. The SDK’s simple and batch processors answer yes to every record, so a stock sdklog.LoggerProvider receives full content: transcript batches, request records, the catalog. weft/otel’s destinations answer per destination instead. To keep content out of your provider:

otelx/main.go
quiet := weft.New(script(), weft.Name("support-bot"), lookup,
weft.TracerProvider(tp), weft.LoggerProvider(lp),
weft.Content(false), // no content in this agent's records, whatever the provider answers
)

otelx/main.go on GitHub

Spans never carry content, whichever provider you use. A stock SDK provider also never receives raw provider bodies: those need weft/otel’s provider and otel.RawBodies.

To use weft/otel’s pipeline with your own exporters instead, pass them as a destination with otel.Exporters (Your own exporters). otel.Install registers its providers globally, so agents built after it need no option. An agent built before it reaches the pipeline only when no SDK was set globally earlier in the process. Beside a global SDK of your own, start the pipeline with otel.Start(ctx, otel.NoGlobal(), …), so it does not replace your SDK as the global, and pass p.TracerProvider() and p.LoggerProvider() from otel.Start to the agent.

Every run reports one span tree, children nested under their parents:

invoke_agent support-bot the run (Internal)
├─ chat <model> one model call: a step (Client)
│ └─ attempt one try, when the model chain reports attempts (Client)
├─ execute_tool lookup_order one tool call (Internal)
│ └─ invoke_agent research a Subagent child run, under its delegating call
└─ chat <model>

No span carries content: no prompt, message, tool argument or tool result, only ids, names, counts, durations, reasons and error types. Error text does travel: a failed run or model call records its error as the span’s exception, with status Error. Every span carries weft.run.id and the run’s metadata. weft.version on the run span and the resource is the framework’s release, pinned by a test so it cannot go stale across a release.

SpanKey attributes
invoke_agentgen_ai.agent.name, gen_ai.provider.name, gen_ai.request.model, weft.version, weft.instructions.hash, weft.manifest.hash; for a child weft.parent.run.id and weft.parent.call.id; at the end the run’s gen_ai.usage.* totals (subagents included), weft.run.steps, weft.run.events, weft.run.messages, weft.run.stop_reason, weft.run.stopped_by, weft.cancel.cause, error.type
chatweft.step.index, weft.stream, the model asked; at the end the call’s gen_ai.usage.*, gen_ai.response.finish_reasons (stop, tool_calls, max_tokens), gen_ai.response.model, weft.model.tool_calls, weft.ttft_ms, error.type
attemptweft.attempt.index (from 1), weft.attempt.layer (fallback on mw.Fallback’s backup), weft.attempt.wait_ms, weft.attempt.retry_after_ms, http.response.status_code, error.type
execute_toolgen_ai.tool.name, gen_ai.tool.call.id, weft.step.index, weft.tool.seq; weft.tool.result_bytes, weft.tool.truncated_bytes, weft.tool.timeout_ms, weft.tool.queue_ms, weft.tool.pending, weft.tool.approved, weft.tool.denied, error.type

error.type on a run span is a closed table of snake_case tokens: max_steps, usage_limit, loop_detected, model_retries_exceeded, model_contract, no_output, model_error (a provider failure, the default) and others, plus context.Canceled and context.DeadlineExceeded. On a tool span it is the ToolError code when there is one (INVALID_INPUT, NO_SUCH_TOOL, RETRY, your own), else timeout, panic, the context error, the error’s own ErrorType() string when an error in its chain declares one (weft/mcp’s mcp_transport, for example), or tool_error. A cancelled tool call reports context.Canceled like its run. The record contract §3 lists every attribute and when it is set.

Spans and slog lines are the loop’s own reporting, not an observer: a weft.Tap sees the same events and receives the span-carrying context. ExampleTracerProvider prints a run’s span tree.

Every record is one OTel log record from the logger github.com/weftgo/weft/core, with an EventName, a JSON body, severity INFO (WARN for an errored tool_finish), and the attributes weft.record (its kind), weft.run.id, gen_ai.agent.name, weft.content and the run’s metadata:

weft.recordOne perPosition
eventdurable event, run_start to run_finishweft.event.pos
deltastreamed text, reasoning or argument deltaweft.delta.pos
messagestranscript batch (content on only)weft.messages.index
request, prompt, toolsmodel-call attempt; distinct system prompt; distinct catalogtheir own .index
rawHTTP exchange, otel.RawBodies in development onlyweft.raw.index
compactionthread session compaction, emitted by weft/threadnone: keyed on weft.compaction.hash
heartbeatopen run every 10 s, emitted by weft/otel’s pipeline only, never storednone

Each positioned kind’s positions run from 0 per run. A record carries the trace and span ids of the context it was emitted on: event, delta and transcript records the invoke_agent span’s, the model-call records the chat span’s. Join records to spans on weft’s ids (weft.run.id, weft.step.index, gen_ai.tool.call.id), not on span ids, which are zero without an SDK. ExampleLoggerProvider prints a run’s record sequence; the record contract §4 gives every body.

weft writes the OTel GenAI conventions (semconv v1.41.0) beside its own keys, so a GenAI-aware backend renders its traces:

KeyWhere
gen_ai.operation.nameevery span but attempt: invoke_agent, chat, execute_tool
gen_ai.agent.nameinvoke_agent; every record
gen_ai.provider.name, gen_ai.request.modelinvoke_agent, chat, attempt
gen_ai.response.modelchat, attempt on success; the step_finish record
gen_ai.response.finish_reasonschat
gen_ai.usage.input_tokens, gen_ai.usage.output_tokensinvoke_agent (run totals), chat (the call’s)
gen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_creation.input_tokens, gen_ai.usage.reasoning.output_tokensthe same spans, when non-zero
gen_ai.tool.name, gen_ai.tool.call.idexecute_tool; tool_start and tool_finish records
gen_ai.conversation.idevery span and record of a run with a weft.session.id, and, under weft/otel’s pipeline, its heartbeats
error.typefailed spans

weft never writes the conventions’ opt-in content attributes, the input and output messages on spans: content travels in log records under each destination’s content policy.

weft emits no OpenTelemetry metrics, only spans and log records. It never uses a MeterProvider, so the conventions’ gen_ai.client.token.usage and gen_ai.client.operation.duration histograms are not produced, and a metrics pipeline wired to weft receives nothing. Token counts are on the spans instead: the gen_ai.usage.* attributes of invoke_agent and chat in the table above.

When weft/otel builds the providers, three options shape them:

otelx/main_test.go
p, err := otel.Start(ctx, otel.NoEnv(), otel.NoGlobal(),
otel.Service("support-api"), // service.name; else OTEL_SERVICE_NAME, else the binary's name
otel.Resource(sdkresource.NewSchemaless(attribute.String("deployment.environment.name", "staging"))),
otel.Sampler(sdktrace.NeverSample()), // spans only: records are never sampled
otel.Exporters(spanExp, sdklog.Exporter(multi{logExp, svc})),
)

otelx/main_test.go on GitHub

  • otel.Service(name) sets service.name; without it, OTEL_SERVICE_NAME, else the binary’s name. Studio shows each run’s service and filters traces by it.
  • otel.Resource(r) merges r over the detected resource. The order, lowest first: the binary’s name and weft.version, then OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES, then Service, then Resource.
  • otel.Sampler(s) sets the trace sampler; the default is ParentBased(AlwaysOn). It applies to spans only: records are log records and are never sampled, so a run sampled out of tracing still has its events and transcript. TestResourceAndSampling runs under NeverSample, gets no span, and still gets the run’s records.

With your own SDK, set the resource and sampler on your providers as usual; weft adds nothing to them.

otel.FromSDKSpans and otel.FromSDKRecords turn what an SDK exporter receives into obsdb’s model, value for value what Studio’s OTLP ingest makes of the same data:

otelx/main.go
converted := otel.FromSDKSpans(spans.GetSpans().Snapshots()) // obsdb.Span values, as OTLP ingest makes them

otelx/main.go on GitHub

Use them in an exporter of your own that writes to an obsdb.DB (db.Write(ctx, obsdb.Batch{Spans: …, Records: …})), or to assert on spans in a test.

With no provider registered and no option, both providers are the API’s no-ops: spans are non-recording, Enabled answers no, and nothing is marshalled for a record. A whole two-step run on this path stays under 160 allocations (128 measured), with no goroutine, lock or background flush. TestWithoutAnSDK runs the example’s agent with no provider and gets the same answer.

The weft repository’s examples/otel is its own module with the real SDK. A stdout exporter prints the span tree of a run that delegates to a subagent, and its test asserts the tree through the SDK’s in-memory exporter. Its acceptance test checks that every record correlates to the run’s trace, event positions are contiguous, and the transcript records rebuild the transcript byte for byte. All of it runs offline.

otelx/main.go
// Command otelx runs the example of the guide "Use your own
// OpenTelemetry SDK": go run ./otelx. The agent reports to an SDK
// tracer provider and logger provider the program built itself, with
// in-memory exporters; the model is scripted with wefttest, so it runs
// offline.
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"sort"
"strings"
"sync"
"go.opentelemetry.io/otel/attribute"
sdklog "go.opentelemetry.io/otel/sdk/log"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"github.com/weftgo/weft"
"github.com/weftgo/weft/otel"
"github.com/weftgo/weft/wefttest"
)
// LookupInput is the lookup tool's argument.
type LookupInput struct {
OrderID string `json:"order_id" jsonschema:"the order to look up"`
}
var lookup = weft.Tool("lookup_order", "Look up an order by ID.",
func(_ context.Context, in LookupInput) (string, error) {
return "order " + in.OrderID + " has shipped", nil
})
// script is a two-step dialogue: one tool call, then an answer.
func script() *wefttest.Model {
return wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
wefttest.Say("Order 1234 has shipped."),
)
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context, w io.Writer) error {
spans := tracetest.NewInMemoryExporter() // your exporter: OTLP, stdout, a vendor's
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(spans))
defer func() { _ = tp.Shutdown(ctx) }()
records := &recordKinds{}
lp := sdklog.NewLoggerProvider(sdklog.WithProcessor(sdklog.NewSimpleProcessor(records)))
defer func() { _ = lp.Shutdown(ctx) }()
agt := weft.New(script(), weft.Name("support-bot"), lookup,
weft.TracerProvider(tp), // spans: invoke_agent › chat, execute_tool
weft.LoggerProvider(lp), // records: events, deltas, transcript batches
)
if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
return err
}
stubs := spans.GetSpans()
sort.Slice(stubs, func(i, j int) bool { return stubs[i].StartTime.Before(stubs[j].StartTime) })
byID := map[string]tracetest.SpanStub{}
for _, s := range stubs {
byID[s.SpanContext.SpanID().String()] = s
}
for _, s := range stubs {
depth := 0
for p := s.Parent; p.IsValid(); p = byID[p.SpanID().String()].Parent {
depth++
}
fmt.Fprintf(w, "%s%s%s\n", strings.Repeat(" ", depth), s.Name, keyAttrs(s.Attributes))
}
fmt.Fprintln(w, "records:", records.summary())
quiet := weft.New(script(), weft.Name("support-bot"), lookup,
weft.TracerProvider(tp), weft.LoggerProvider(lp),
weft.Content(false), // no content in this agent's records, whatever the provider answers
)
records.reset()
if _, err := quiet.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
return err
}
fmt.Fprintln(w, "records with Content(false):", records.summary())
converted := otel.FromSDKSpans(spans.GetSpans().Snapshots()) // obsdb.Span values, as OTLP ingest makes them
fmt.Fprintln(w, "converted spans:", len(converted)) // both runs: 4 spans each
return nil
}
// keyAttrs prints the span attributes the page talks about, in a fixed
// order, for the spans that carry them.
func keyAttrs(kvs []attribute.KeyValue) string {
want := []string{"gen_ai.operation.name", "weft.step.index", "gen_ai.tool.name",
"gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.response.finish_reasons", "weft.run.stopped_by"}
have := map[string]string{}
for _, kv := range kvs {
have[string(kv.Key)] = kv.Value.Emit()
}
var b strings.Builder
for _, k := range want {
if v, ok := have[k]; ok {
fmt.Fprintf(&b, " %s=%s", strings.TrimPrefix(strings.TrimPrefix(k, "gen_ai."), "weft."), v)
}
}
return b.String()
}
// recordKinds is a log exporter that counts records by weft.record kind
// and weft.content value.
type recordKinds struct {
mu sync.Mutex
n map[string]int
}
func (r *recordKinds) Export(_ context.Context, recs []sdklog.Record) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.n == nil {
r.n = map[string]int{}
}
for _, rec := range recs {
kind, content := "", ""
rec.WalkAttributes(func(kv attribute.KeyValue) bool {
switch kv.Key {
case "weft.record":
kind = kv.Value.AsString()
case "weft.content":
content = kv.Value.AsString()
}
return true
})
r.n[kind+"("+content+")"]++
}
return nil
}
func (r *recordKinds) reset() {
r.mu.Lock()
defer r.mu.Unlock()
r.n = nil
}
func (r *recordKinds) summary() string {
r.mu.Lock()
defer r.mu.Unlock()
var out []string
for k, v := range r.n {
out = append(out, fmt.Sprintf("%s %d", k, v))
}
sort.Strings(out)
return strings.Join(out, ", ")
}
func (*recordKinds) Shutdown(context.Context) error { return nil }
func (*recordKinds) ForceFlush(context.Context) error { return nil }

View otelx/main.go on GitHub

From docs-site/examples:

Terminal window
go run ./otelx
go test ./otelx
invoke_agent support-bot operation.name=invoke_agent usage.input_tokens=20 usage.output_tokens=10 run.stopped_by=final_answer
chat script operation.name=chat step.index=0 usage.input_tokens=10 usage.output_tokens=5 response.finish_reasons=["tool_calls"]
execute_tool lookup_order operation.name=execute_tool step.index=0 tool.name=lookup_order
chat script operation.name=chat step.index=1 usage.input_tokens=10 usage.output_tokens=5 response.finish_reasons=["stop"]
records: delta(full) 1, event(full) 8, messages(full) 4, request(full) 2, tools(full) 1
records with Content(false): delta(none) 1, event(none) 8, request(stripped) 2
converted spans: 8

The stock logger provider received full content: four transcript batches, two request records and the catalog. With weft.Content(false) the same run sends no transcript or catalog record, its events and deltas marked none and its request records stripped.

  • Decide content before you hand weft a stock provider. Its processors answer yes to every record, so transcripts and tool results reach your exporter. Use weft.Content(false), or weft/otel with a content-off destination. (Source: weft.Content godoc; TestOwnSDK)
  • Join on weft ids, not span ids. Span ids are zero without an SDK and missing when sampled out; every record carries weft.run.id. (Source: record contract §1, §4)
  • Sampling never thins records. A Sampler drops spans only; to send fewer records, use otel.Signals or otel.NoDeltas on a destination. (Source: otel.Sampler godoc; TestResourceAndSampling)
  • Do not wait for weft metrics. There is no MeterProvider option and no gen_ai.client.* histogram; read token counts from the spans’ gen_ai.usage.* attributes. (Source: weft/docs/adr/0016-observability.md:290-294)
  • Install the pipeline before you build agents, or pass its providers. An agent binds to the global providers at weft.New. One built after your own global SDK, or after an earlier otel.Install, keeps reporting there: a later Install never reaches it. Once that earlier pipeline is shut down, its runs are recorded nowhere, with no error and no WARN. Call otel.Install once, at startup, before weft.New; otherwise build the agent with weft.TracerProvider(p.TracerProvider()) and weft.LoggerProvider(p.LoggerProvider()), p from otel.Start(ctx, otel.NoGlobal(), …) when your own SDK stays the global. (Source: weft/core/agent.go:698-710, weft/otel/pipeline.go:313-314, 842-847; scratch proof in sources)
  • Pass providers explicitly in tests. The globals are process-wide; weft.TracerProvider and weft.LoggerProvider keep a test’s spans its own. (Source: weft.TracerProvider godoc)

Symbols used: weft.TracerProvider · weft.LoggerProvider · weft.Content · Agent.LoggerProvider · weft.Tap · otel.Service · otel.Resource · otel.Sampler · otel.FromSDKSpans · otel.FromSDKRecords · otel.Exporters · otel.Start · obsdb.Batch · ExampleTracerProvider · ExampleLoggerProvider