Control what content leaves the process
Content is message text, tool arguments and results, the system prompt and the tool catalog. weft decides per destination whether it leaves the process: otel.Local and otel.Studio receive it, every third-party destination receives the records with their content fields emptied. On a content-on destination otel.ContentConfig redacts and caps it; weft.Content(false) keeps one agent’s content out of every destination.
Redact email addresses on the local sink and send a third-party collector shape only, in production/main.go:
email := regexp.MustCompile(`[\w.+-]+@[\w-]+\.[\w.]+`)redact := func(kind weft.ContentKind, s string) string { return email.ReplaceAllString(s, "[email]") // every content field of every kind}p, err := otel.Start(ctx, otel.Local(path), // content on: the redactor and the cap apply otel.OTLP(collectorURL, otel.NoContent()), // a third party: shape only, no content otel.Content(otel.ContentConfig{ MaxBytes: 16 << 10, // one event field, delta, prompt or catalog body; never the transcript Redact: redact, }), otel.NoEnv(),)The model still reads the address; the local sink stores [email]; the collector stores every event marked stripped and no transcript.
How it works
Section titled “How it works”The core captures content only when some destination asks for it, through the OTel Logs API’s Enabled question, so a pipeline whose destinations are all content-off makes the core emit no transcript records at all. Each destination’s processor chain then clones every record and shapes it on its own: a content-off chain strips it, a content-on chain redacts and caps it. One destination’s policy never changes what another receives. Spans carry no message, argument or result content, whatever the policy; the policy governs log record bodies. Two things do ride spans under any policy: the error text of a failed run, model call or attempt (a failed tool call’s span carries only its error.type), and every weft.Metadata pair (such as weft.session.title or weft.page_url).
Every record says what it holds in its weft.content attribute:
weft.content | Meaning |
|---|---|
full | as emitted; a content-on chain may still have redacted or capped it |
stripped | a content-off destination’s chain stripped it |
none | the core captured none: no destination wanted content, or the agent has weft.Content(false); also every session marker record, which carries none by nature |
Per-destination content
Section titled “Per-destination content”The defaults: otel.Local and otel.Studio are content-on; otel.OTLP, otel.Exporters, otel.Datadog and otel.Langfuse (traces only, so never any record) are content-off, so content never reaches a third party by accident. Two destination options override the default:
| Option | Effect |
|---|---|
otel.WithContent(cfg...) | content on for this destination, optionally with its own ContentConfig |
otel.NoContent() | content off: event and delta bodies stripped, transcript records dropped |
otel.Content(cfg) sets the pipeline-wide ContentConfig every content-on destination applies; WithContent(cfg) replaces it for one destination. ContentConfig has two fields:
| Field | Applies to | Default |
|---|---|---|
MaxBytes | one event field or delta body, a prompt record’s text, a tools record’s body (whole tool entries dropped from the end, so it stays JSON). Never a transcript record (a capped transcript is not replay-grade), nor tool_start arguments or a pending call’s arguments: those are JSON documents, redacted but never cut | 0 means 32 KiB; negative means no cap |
Redact | every content field before the cap (Redaction) | nil: identity |
A cut sets weft.content.truncated_bytes (the bytes removed) on the record. The default 32 KiB cap applies to the catalog too: an MCP server’s large catalog arrives truncated on the local sink unless you raise MaxBytes there.
What a content-off chain does, per record kind:
| Record | Content-off destination receives |
|---|---|
event, delta | the same shape with the content fields emptied (the table below), marked stripped |
messages (the transcript), prompt, tools, raw | nothing: dropped |
request | kept with params.stop emptied and messages_ref.index removed (messages_ref.count stays); hashes, names and numbers survive; marked stripped |
| bridged app log line | body and string attribute values "", marked stripped, when the destination takes app logs at all (app logs) |
The environment can add destinations too. WEFT_STUDIO_URL, or a running Studio’s discovery file when it is unset, adds a Studio destination, content on. An OTEL_EXPORTER_OTLP_ENDPOINT destination is content-off unless OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true. otel.NoEnv() turns all of them off; WEFT_DISCOVERY=off turns off the discovery file alone (Environment variables).
What content-on carries
Section titled “What content-on carries”A content-on destination receives, besides events, deltas and the transcript, what each model call was given: the composed system prompt (a prompt record) and the tool catalog (a tools record), under the same policy. They are redactable (the prompt) and capped (both), and a content-off destination drops them. If a system prompt must not leave the process, redact it with the prompt kind or turn content off for that destination. This holds since weft 0.10.0, when ADR 0028 reversed the earlier rule that no record carries the instructions text.
Content kinds
Section titled “Content kinds”weft.ContentKind names what a content field holds. It is the first argument Redact receives, so a redactor can treat tool results differently from user text. The core puts eight kinds into records; weft/otel adds one for bridged log lines and one for weft/thread’s session records:
| Kind | Value | Holds |
|---|---|---|
weft.ContentText | text | assistant text and text deltas; in a transcript, the text parts of every role |
weft.ContentReasoning | reasoning | reasoning text and deltas |
weft.ContentArgs | args | tool call arguments and argument deltas |
weft.ContentResult | result | tool results |
weft.ContentMessages | messages | whole transcript batches; weft/otel redacts them part by part with the four kinds above |
weft.ContentPrompt | prompt | the composed system text of a prompt record |
weft.ContentStop | stop | one stop sequence of a request record’s params |
weft.ContentRaw | raw | one wire body of a raw record (development only) |
otel.ContentLog | log | a bridged app log line’s message and string attributes |
otel.ContentThread | thread | since 0.18.0, each string of a thread record’s content object: who decided, a deny reason, a resolve’s result, a steer’s text, a summary |
The core uses the kinds in one place, weft.StripContent’s table of which field of which event is content.
Redaction
Section titled “Redaction”Redact func(kind weft.ContentKind, s string) string sees each content field before the cap. It sees event and delta bodies, and transcript records, part by part with the kinds of the table above. It sees a prompt record’s text, each stop sequence and a raw record’s text bodies. It sees a bridged log line’s message and string attributes. It sees each string of a session record’s content as otel.ContentThread, also capped at MaxBytes. A content-off destination strips a session record’s content whole. The package example ExampleContentThread denies a parked call in a thread session with Who and a reason, and its redactor sees both, [agent-7 need a photo], under that kind. It never sees ids, names, roles, signatures, file parts or hashes, and a tools record is capped, never redacted. Steered user text, the arguments of calls pending approval on run_finish, and a subagent’s nested events are redacted like the rest.
It changes the record, never what the model sees: the tool result in res.Messages still holds the address in the example above.
Redaction fails closed:
- A panic in
Redactis contained. The event goes out stripped and the transcript record not at all; both count as the destination’s dropped records. - A transcript record that cannot be decoded for redaction is dropped and counted, never exported unredacted. So is a raw record whose body does not survive
Redact. - Redacted tool arguments that are no longer JSON are exported as a JSON string.
- A base64 raw body (a binary response) is not text and is not passed to
Redact.
Before weft 0.8.0, Redact did not see transcript records, so a masking redactor left the whole transcript unredacted on the local sink; from 0.8.0 on it applies to them part by part. Capture itself is decided at each emission (the agent’s weft.Content, else the Enabled question), not when the agent is built, so an agent built before otel.Install still gets the pipeline’s policy.
The agent veto
Section titled “The agent veto”weft.Content(capture bool) overrides what the destinations ask for, for one agent’s runs:
| Option | Records carry content |
|---|---|
| none (the default) | as the logger in force answers Enabled: when some destination wants content |
weft.Content(false) | never, even when a destination wants it; records keep their shape and positions, marked none |
weft.Content(true) | event bodies always, even with no destination asking (tests); transcript, prompt and tools records are still emitted only when a destination asks for them |
Use weft.Content(false) for an agent whose data must never be recorded, whichever destinations an operator configures. The package example ExampleContent records a run under Content(false) and prints its tool_start record, whose args is null.
Strip content
Section titled “Strip content”weft.StripContent(ev) returns the event with every content field emptied: what a content-off destination receives. It is the one content-shaping table; weft/otel calls it, and you can call it to apply the same rule to events you forward yourself, from a weft.Tap for example:
ev := weft.ToolFinish{Seq: 4, CallID: "call_1", Name: "lookup_order", Content: "order 1234 has shipped to jane@example.com"}out := weft.StripContent(ev).(weft.ToolFinish) // what a content-off destination receivesfmt.Fprintf(w, "stripped: name=%s call=%s content=%q\n", out.Name, out.CallID, out.Content)
// This agent's records never carry content, whatever a destination asks for.payroll := weft.New(script(), weft.Name("payroll-bot"), lookup, weft.Content(false), weft.TracerProvider(tp), weft.LoggerProvider(lp))stripped: name=lookup_order call=call_1 content=""content(false): succeeded events: 8 transcript batches: 0 the address stored: false| Event | Emptied | Kept |
|---|---|---|
text_delta, reasoning_delta | text | run_id |
tool_args_delta | args | run_id, name |
tool_start | args (becomes null) | seq, call_id, name |
tool_finish | content | seq, call_id, name, is_error |
steered | messages (becomes []) | seq, step |
run_finish | each pending call’s args | usage, steps, pending ids and names, stopped_by |
run_start, step_start, step_finish | nothing: no content | all |
nested | recurses into the child event | the envelope |
A stripped record still attributes and orders: ids, names, counts, positions and usage survive. It is no longer replay-grade, by design. The package example ExampleStripContent prints a stripped tool_finish as JSON.
Raw provider bodies
Section titled “Raw provider bodies”otel.RawBodies(true) records each model call attempt’s HTTP exchange, the request and response a first-party adapter sent and received, as one weft.raw record per attempt. It is a development tool and the pipeline enforces that:
- It takes effect only behind the development gate:
WEFT_ENV=devwhen the pipeline starts, orotel.DevMode()in code (aWEFT_ENVset to anything butdevoverrules it). OtherwiseStartlogs one WARN naming the cause,otel: RawBodies ignored: WEFT_ENV is not dev(underotel.NoEnv()withoutDevMode,… otel.NoEnv reads no WEFT_ENV), and nothing is recorded. WhenWEFT_ENVoverrulesDevMode, the single WARN isotel: DevMode ignored: WEFT_ENV=<value>(Record provider wire bodies). - Raw records go to Local and Studio destinations with content on, never to Datadog, Langfuse, OTLP or
Exporters, and not to a Local or Studio destination underNoContent(). - Each body is capped at 256 KiB. Credential headers and query values are stripped before emission and named in the record.
Redactsees the text bodies with therawkind. - The gate is the pipeline’s
LoggerProvider: it embeds the SDK provider (LoggerProvider.LoggerProvider) and adds the markerLoggerProvider.RawBodiesthe core asks before it buffers a body: true only withotel.RawBodies(true)and the development gate atStart. Its twinLoggerProvider.DevDetailreports the development detail level the same way (otel.DevDetail()and the gate), which the core asks before it starts a layer span or keeps a repair’s original arguments. Passp.LoggerProvider()toweft.LoggerProvider, or rely onInstall’s global registration: a stock SDK provider has no marker and never records raw bodies. ALoggerProviderof your own that wraps the pipeline’s (one that filters or adds attributes) must let the core reach the markers in one of three ways: embed the pipeline’s*otel.LoggerProvider, forwardRawBodies()andDevDetail()to it, or declareUnwrap() log.LoggerProviderreturning it. The core asks each provider for the markers first and only then unwraps, at most 64 hops. Without one of them both markers are hidden, sootel.RawBodies(true)andotel.DevDetail()record nothing, and no WARN says so, since the gate passed atStart.
Record provider wire bodies shows the option in a program.
Complete example
Section titled “Complete example”The Production pages share one example program; contentPolicy and stripContent are this page’s:
// Command production runs the examples of the Production pages —// deploying, content and privacy, retention, limits, storage backends// and Studio operations:// go run ./production. Every Studio is a stand-in on a loopback port// over a fresh SQLite file and the model is scripted with wefttest, so// it runs offline.package main
import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "log" "net" "net/http" "net/http/httptest" "os" "os/signal" "path/filepath" "regexp" "strings" "syscall" "time"
"github.com/weftgo/weft" "github.com/weftgo/weft/obsdb" "github.com/weftgo/weft/obsdb/sqlite" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/studio" "github.com/weftgo/weft/thread" "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"`}
// lookup returns a customer's email address: the content the pages keep// out of the records.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 to jane@example.com", 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() { dir, err := os.MkdirTemp("", "weft-production-") if err != nil { log.Fatal(err) } defer func() { _ = os.RemoveAll(dir) }() // The shutdown example waits for SIGINT or SIGTERM; here it stops // itself after one turn so the program ends. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() if err := run(ctx, os.Stdout, dir); err != nil { log.Fatal(err) } if err := runOperations(ctx, os.Stdout, dir); err != nil { log.Fatal(err) }}
func run(ctx context.Context, w io.Writer, dir string) error { steps := []struct { name string fn func(context.Context, io.Writer, string) error }{ {"content policy", contentPolicy}, {"strip content", stripContent}, {"hosted studio", hostedStudio}, {"retention", retention}, {"tool limits", toolLimits}, {"graceful shutdown", gracefulShutdown}, } for _, s := range steps { fmt.Fprintln(w, "==", s.name) if err := s.fn(ctx, w, dir); err != nil { return fmt.Errorf("%s: %w", s.name, err) } } return nil}
// contentPolicy records one run twice: into the local sink with a// redactor and a cap, and into a third-party OTLP collector with// content off.func contentPolicy(ctx context.Context, w io.Writer, dir string) error { collectorURL, collectorDB, stopCollector, err := standInStudio(filepath.Join(dir, "collector.db")) if err != nil { return err } defer stopCollector() path := filepath.Join(dir, "redacted.db")
email := regexp.MustCompile(`[\w.+-]+@[\w-]+\.[\w.]+`) redact := func(kind weft.ContentKind, s string) string { return email.ReplaceAllString(s, "[email]") // every content field of every kind } p, err := otel.Start(ctx, otel.Local(path), // content on: the redactor and the cap apply otel.OTLP(collectorURL, otel.NoContent()), // a third party: shape only, no content otel.Content(otel.ContentConfig{ MaxBytes: 16 << 10, // one event field, delta, prompt or catalog body; never the transcript Redact: redact, }), otel.NoEnv(), ) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err }
local, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = local.Close() }() stored, err := everything(ctx, local, res.ID) if err != nil { return err } fmt.Fprintln(w, "the model saw:", toolResult(res)) fmt.Fprintln(w, "local sink holds [email]:", strings.Contains(stored, "[email]"), "the address:", strings.Contains(stored, "jane@example.com"))
rec, err := collectorDB.Run(ctx, res.ID) if err != nil { return err } page, err := collectorDB.Events(ctx, res.ID, -1, 50) if err != nil { return err } stripped := 0 for _, e := range page.Events { if e.Content == "stripped" { stripped++ } } fmt.Fprintln(w, "collector:", rec.Status, "events:", rec.EventCount, "stripped:", stripped, "transcript batches:", rec.MessageCount) return nil}
// stripContent shows the core's content table and the agent-side veto.func stripContent(ctx context.Context, w io.Writer, dir string) error { path := filepath.Join(dir, "vetoed.db") p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal()) // Local: content on if err != nil { return err } tp, lp := p.TracerProvider(), p.LoggerProvider()
ev := weft.ToolFinish{Seq: 4, CallID: "call_1", Name: "lookup_order", Content: "order 1234 has shipped to jane@example.com"} out := weft.StripContent(ev).(weft.ToolFinish) // what a content-off destination receives fmt.Fprintf(w, "stripped: name=%s call=%s content=%q\n", out.Name, out.CallID, out.Content)
// This agent's records never carry content, whatever a destination asks for. payroll := weft.New(script(), weft.Name("payroll-bot"), lookup, weft.Content(false), weft.TracerProvider(tp), weft.LoggerProvider(lp))
res, err := payroll.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err } db, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = db.Close() }() rec, err := db.Run(ctx, res.ID) if err != nil { return err } stored, err := everything(ctx, db, res.ID) if err != nil { return err } fmt.Fprintln(w, "content(false):", rec.Status, "events:", rec.EventCount, "transcript batches:", rec.MessageCount, "the address stored:", strings.Contains(stored, "jane@example.com")) return nil}
// hostedStudio is setup C: a Studio behind a Token, its own ingest// token, one allowed origin and a retention, and an app exporting to it.func hostedStudio(ctx context.Context, w io.Writer, dir string) error { db, err := sqlite.Open(filepath.Join(dir, "hosted.db")) if err != nil { return err } defer func() { _ = db.Close() }() apiToken, ingestToken := "api-secret", "ingest-secret" // in production: from your secret store
srv := studio.New( studio.DB(db), // the hosted database (SQLite here; clickhouse.Open in a fleet) studio.Token(apiToken), // every /api route: Authorization: Bearer <apiToken> studio.IngestToken(ingestToken), // /v1/traces and /v1/logs: Authorization: Bearer <ingestToken> studio.AllowOrigins("https://app.example.com"), // the app page that loads the devtools panel studio.Retain(30*24*time.Hour), // delete runs not running, last seen 30 days ago ) defer func() { _ = srv.Close() }() // stops the sweeper mux := http.NewServeMux() mux.Handle("/studio/", http.StripPrefix("/studio", srv.Handler())) ts := httptest.NewServer(mux) defer ts.Close() base := ts.URL + "/studio"
// The app's side: export to the hosted Studio with the ingest token. p, err := otel.Start(ctx, otel.Studio(base, ingestToken), otel.NoEnv(), otel.NoGlobal()) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Metadata(map[string]string{"weft.public_id": "pub_jane"})) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err }
noToken, _ := get(base+"/api/runs", "") withToken, body := get(base+"/api/runs", apiToken) fmt.Fprintln(w, "GET /api/runs without a token:", noToken, "with it:", withToken, "lists the run:", strings.Contains(body, res.ID)) _, meta := get(base+"/api/meta", apiToken) var m struct { Retention string `json:"retention"` } _ = json.Unmarshal([]byte(meta), &m) fmt.Fprintln(w, "retention:", m.Retention)
// Your backend mints a panel token for one conversation's public id. tok, err := mintPanelToken(base, apiToken, "pub_jane") if err != nil { return err } own, _ := get(base+"/api/runs?public_id=pub_jane", tok) other, _ := get(base+"/api/runs?public_id=pub_other", tok) fmt.Fprintln(w, "panel token, its public id:", own, "another:", other) return nil}
// retention keeps runs 30 days and shows what a sweep 30 days later// deletes, then gives the space back.func retention(ctx context.Context, w io.Writer, dir string) error { path := filepath.Join(dir, "retained.db") p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal()) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err } db, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = db.Close() }()
srv := studio.New(studio.DB(db), studio.Retain(30*24*time.Hour)) // sweeps at New, then hourly defer func() { _ = srv.Close() }() // Close stops the sweeper page, err := db.Runs(ctx, obsdb.RunQuery{}) if err != nil { return err } fmt.Fprintln(w, "kept under a 30-day retention:", len(page.Runs), "run") // a fresh run is never swept
later := time.Now().Add(30*24*time.Hour + time.Minute) // the clock, 30 days on n, err := sweepAndVacuum(ctx, db, later, 30*24*time.Hour) if err != nil { return err } page, err = db.Runs(ctx, obsdb.RunQuery{}) if err != nil { return err } fmt.Fprintln(w, "30 days later: swept", n, "runs; left:", len(page.Runs)) return nil}
// sweepAndVacuum is one sweep as Retain's sweeper runs it at now, then// VACUUM: what `weft vacuum --retain` does.func sweepAndVacuum(ctx context.Context, db obsdb.DB, now time.Time, retain time.Duration) (int, error) { cutoff := now.Add(-retain) // what Retain's sweeper computes each pass n, err := db.Sweep(ctx, cutoff) // runs not running, last seen before cutoff, with their children if err != nil { return n, err } err = db.Vacuum(ctx) // SQLite: VACUUM; ClickHouse: OPTIMIZE TABLE … FINAL return n, err}
// ReportInput is the report tool's argument.type ReportInput struct { Month string `json:"month" jsonschema:"the month, YYYY-MM"`}
// toolLimits runs two tools against their limits: a result past its cap// and a handler past its deadline.func toolLimits(ctx context.Context, w io.Writer, _ string) error { report := weft.Tool("monthly_report", "Export a month's orders as CSV.", func(_ context.Context, in ReportInput) (string, error) { return strings.Repeat("order,status\n", 5_000), nil // 65,000 bytes }, weft.MaxResultBytes(4<<10), // this tool's results are cut at 4 KiB, with a marker weft.Timeout(10*time.Second), ) slow := weft.Tool("carrier_status", "Ask the carrier where a parcel is.", func(ctx context.Context, in LookupInput) (string, error) { select { case <-ctx.Done(): // honour ctx: the deadline cancels it return "", ctx.Err() case <-time.After(time.Minute): return "in transit", nil } }, weft.Timeout(50*time.Millisecond), // past it: an error result, the run goes on ) agt := weft.New(model(), report, slow, weft.MaxSteps(5), // budget: ErrMaxSteps past 5 model calls weft.UsageLimit(weft.Usage{OutputTokens: 20_000}), // budget: ErrUsageLimit past 20,000 output tokens ) res, err := agt.Generate(ctx, weft.Prompt("Report for 2026-09, and where is parcel 1234?")) if err != nil { return err } for _, m := range res.Messages { for _, part := range m.Content { if r, ok := part.(weft.ToolResultPart); ok { if r.IsError { fmt.Fprintf(w, "%s (error): %s\n", r.Name, r.Content) continue } fmt.Fprintf(w, "%s (%d bytes): …%s\n", r.Name, len(r.Content), tail(r.Content, 28)) } } } return nil}
func model() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "monthly_report", Args: `{"month":"2026-09"}`}, wefttest.Call{Name: "carrier_status", Args: `{"order_id":"1234"}`}, ), wefttest.Say("The report is partial; the carrier did not answer."), )}
// gracefulShutdown serves one agent over HTTP with a thread session and// an embedded Studio, then shuts every piece down in order once ctx ends.func gracefulShutdown(ctx context.Context, w io.Writer, dir string) error { path := filepath.Join(dir, "app.db") ctx, cancel := context.WithCancel(ctx) defer cancel() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return err } done := make(chan error, 1) go func() { done <- serve(ctx, ln, path) }()
// One request, then the signal. resp, err := http.Post("http://"+ln.Addr().String()+"/chat", "text/plain", strings.NewReader("Where is order 1234?")) if err != nil { return err } reply, _ := io.ReadAll(resp.Body) _ = resp.Body.Close() fmt.Fprintln(w, "reply:", string(reply)) cancel() if err := <-done; err != nil { return err }
db, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = db.Close() }() page, err := db.Runs(context.Background(), obsdb.RunQuery{}) if err != nil { return err } for _, r := range page.Runs { fmt.Fprintln(w, "after shutdown the sink holds:", r.Agent, r.Status, "turn", r.Turn) } return nil}
// serve runs the app until ctx ends, then shuts down: HTTP first, then// the session, then Studio, then the recording pipeline.func serve(ctx context.Context, ln net.Listener, dbPath string) error { shutdownRecording := otel.Install(otel.Local(dbPath), otel.NoEnv()) agt := weft.New(script(), weft.Name("support-bot"), lookup) s, err := thread.Create(ctx, thread.Memory(), agt, thread.NoAutoCompact()) // in production: jsonl.Open or sqlite.Open if err != nil { shutdownRecording() return err } inspector := studio.New(studio.DB(otel.LocalDB())) mux := http.NewServeMux() mux.Handle("/studio/", http.StripPrefix("/studio", inspector.Handler())) mux.HandleFunc("POST /chat", func(rw http.ResponseWriter, r *http.Request) { var prompt bytes.Buffer _, _ = prompt.ReadFrom(r.Body) turn, err := s.Send(r.Context(), weft.User(prompt.String())) if err != nil { http.Error(rw, err.Error(), http.StatusServiceUnavailable) return } res, err := turn.Wait() if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } _, _ = io.WriteString(rw, res.Text()) }) httpSrv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} go func() { _ = httpSrv.Serve(ln) }()
<-ctx.Done() // SIGINT or SIGTERM in main stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() err = errors.Join( httpSrv.Shutdown(stopCtx), // 1. stop taking requests; in-flight handlers finish s.Close(stopCtx), // 2. drain the running turn and the queue, give the writer lease up inspector.Close(), // 3. stop Retain's sweeper and the playground link ) shutdownRecording() // 4. flush every destination (5 s budget), close the local sink last return err}
// standInStudio serves a Studio over a fresh SQLite file on a loopback// port: its OTLP ingest takes loopback peers without an ingest token.func standInStudio(path string) (url string, db obsdb.DB, stop func(), err error) { db, err = sqlite.Open(path) if err != nil { return "", nil, nil, err } srv := studio.New(studio.DB(db)) ts := httptest.NewServer(srv.Handler()) return ts.URL, db, func() { ts.Close(); _ = srv.Close(); _ = db.Close() }, nil}
// everything is every stored body of a run: its events and its// transcript, joined.func everything(ctx context.Context, db obsdb.DB, runID string) (string, error) { var sb strings.Builder page, err := db.Events(ctx, runID, -1, 500) if err != nil { return "", err } for _, e := range page.Events { b, _ := json.Marshal(e) sb.Write(b) } batches, err := db.Transcript(ctx, runID) if err != nil { return "", err } for _, b := range batches { sb.Write(b) } return sb.String(), nil}
func get(url, token string) (int, string) { req, _ := http.NewRequest(http.MethodGet, url, nil) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } resp, err := http.DefaultClient.Do(req) if err != nil { return 0, err.Error() } defer func() { _ = resp.Body.Close() }() b, _ := io.ReadAll(resp.Body) return resp.StatusCode, string(b)}
func mintPanelToken(base, apiToken, publicID string) (string, error) { body := strings.NewReader(`{"public_id":"` + publicID + `","ttl":"15m"}`) req, _ := http.NewRequest(http.MethodPost, base+"/api/panel-tokens", body) req.Header.Set("Authorization", "Bearer "+apiToken) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer func() { _ = resp.Body.Close() }() var out struct { Token string `json:"token"` } if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { return "", err } if out.Token == "" { return "", fmt.Errorf("panel-tokens: %s", resp.Status) } return out.Token, nil}
// toolResult is the text of the run's first tool result: what the model// read, never changed by a destination's redactor.func toolResult(res *weft.RunResult) string { for _, m := range res.Messages { for _, part := range m.Content { if r, ok := part.(weft.ToolResultPart); ok { return r.Content } } } return ""}
func tail(s string, n int) string { s = strings.ReplaceAll(s, "\n", `\n`) if len(s) <= n { return s } return s[len(s)-n:]}View on GitHub · run it from docs-site/examples:
go run ./productiongo test ./production== content policythe model saw: order 1234 has shipped to jane@example.comlocal sink holds [email]: true the address: falsecollector: succeeded events: 8 stripped: 8 transcript batches: 0== strip contentstripped: name=lookup_order call=call_1 content=""content(false): succeeded events: 8 transcript batches: 0 the address stored: falseThe rest of the output belongs to the other Production pages. TestProduction in main_test.go pins it: the address never reaches the local sink, and the collector holds only stripped events and no transcript.
Best practices & gotchas
Section titled “Best practices & gotchas”- Turn content on for a third party only on purpose. Every destination but Local and Studio is content-off by default;
WithContent()is the opt-in. (Source:otel/config.go:90-99; ADR 0024 “Content: off by default”) - Redact on the content-on destinations; strip on the rest.
Redactruns only where content is on; a content-off destination never sees content to redact. (Source:otel/options.go:307-327) - Raise
MaxByteson the local sink if you need whole catalogs and long results. The default 32 KiB cut is marked withweft.content.truncated_bytes; the transcript is never cut. (Source:otel/options.go:23-31) - The model-visible tool-result cap is a different limit.
weft.MaxResultBytes(64 KiB) cuts what the model reads;MaxBytescuts only what a destination stores (Limits). (Source:core/agent.go:22-29) - Spans carry no message content, but they do carry errors and metadata. A traces-only destination holds structure, timing, usage, the error text of failed runs, model calls and attempts, and every
weft.Metadatapair; keep secrets out of error strings and metadata. (Source:core/content.go:40-44;core/observe.go:386-387, 519-520, 683, 710, 784;core/report.go:480; AGENTS.md block 3,weft.Metadata)
See also
Section titled “See also”- Send records to Studio, Datadog, Langfuse or any OTLP backend
- Record every run with otel.Install
- Bridge your app’s slog lines into runs
- Secure Studio
- Glossary: content policy
Symbols used: otel.Start · otel.Install · otel.Local · otel.Studio · otel.OTLP · otel.NoEnv · otel.Content · otel.ContentConfig · otel.WithContent · otel.NoContent · otel.RawBodies · otel.ContentLog · otel.LoggerProvider · weft.Content · weft.ContentKind · weft.StripContent · weft.ToolFinish · weft.New · weft.Tool · weft.TracerProvider · weft.LoggerProvider · weft.Tap · sqlite.Open · wefttest.Script