Skip to content

Tag runs with metadata

View as Markdown

weft.Metadata attaches caller key/value pairs to one run: every span and every record of the run carries them, and so do the runs of its subagents. weft.WithMetadata puts the same pairs on a context, for every run started under it. weft.MetadataFromContext reads the merged pairs back. Metadata is reporting only: it changes nothing the model sees.

Tag a run in metadata/main.go:

metadata/main.go
res, err := agt.Generate(ctx,
weft.Prompt("Where is order 1234?"),
weft.Metadata(map[string]string{"tenant": "acme", "enduser.id": "u_42"}),
weft.Metadata(map[string]string{"request.id": "req_7"}), // several options merge; a later key wins
)

metadata/main.go on GitHub

The pairs are on the run’s invoke_agent span, its chat and execute_tool spans, and its records, so a trace backend can group or filter by tenant. The package example is ExampleMetadata.

Metadata is a run option. Several Metadata options merge in order, and a later key wins. The pairs ride the run’s context, so anything that receives that context can read them with MetadataFromContext: a weft.Tap, an OnRunEnd observer, a tool handler, or a subagent’s child run.

metadata/main.go
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in LookupInput) (string, error) {
tenant := weft.MetadataFromContext(ctx)["tenant"] // the run's pairs, in the handler
return "order " + in.OrderID + " of " + tenant + " has shipped", nil
})
agt := weft.New(model, lookup,
weft.Tap(func(ctx context.Context, ev weft.Event) {
if _, ok := ev.(weft.RunStart); ok {
md := weft.MetadataFromContext(ctx)
fmt.Fprintln(w, "run start: tenant =", md["tenant"], "user =", md["enduser.id"])
}
}),
)

metadata/main.go on GitHub

MetadataFromContext returns a copy of the pairs in force: the run’s own merged over its ancestors’. It returns nil when there are none.

Keys under weft. are the weft modules’ namespace by convention. weft/thread stamps weft.session.id and weft.turn on every turn’s run, and weft.public_id when the session has one, and an approval resume can name its decider with weft.approval.actor. The core does not police the prefix. Two keys also get the OpenTelemetry mirrors that backends group on: weft.session.id is repeated as gen_ai.conversation.id and session.id, and enduser.id as user.id. A run started on a tool call’s context, such as a subagent’s child run, also carries weft.parent.run.id and weft.parent.call.id on its invoke_agent span, beside the run’s weft.version and, for a named agent, weft.manifest.hash.

A weft.Subagent’s child run inherits the parent’s pairs, because they travel on the tool call’s context. An empty value means “none”: it is never stored, and it removes the key the run would otherwise inherit, from its parent run or from a WithMetadata context.

metadata/main.go
researcher := weft.New(wefttest.Script(wefttest.Say("notes"), wefttest.Say("notes")), weft.Name("researcher"), childTap)
lead := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}),
wefttest.Say("done"),
), weft.Subagent("research", "Research a topic.", researcher))
_, err := lead.Generate(ctx, weft.Prompt("Brief me."),
weft.Metadata(map[string]string{"tenant": "acme", "weft.session.id": "s_01"}))
if err != nil {
return err
}
// A run that is not the enclosing session's work says so with "":
_, err = researcher.Generate(weft.WithMetadata(ctx, map[string]string{"tenant": "acme", "weft.session.id": "s_01"}),
weft.Prompt("Standalone."),
weft.Metadata(map[string]string{"weft.session.id": ""}))

metadata/main.go on GitHub

The first child run prints weft.session.id="s_01". The second run reads an empty string because the key is gone: TestEmptyValueRemoves checks that the key is absent, not empty. weft/thread uses this to stamp weft.public_id as "" on a session that has none, so a turn started inside another session’s tool handler never reads as that session’s.

Metadata rides every span and record, so it is identity, not a payload:

LimitValue
Keys per run64
Key length128 bytes
Value length1024 bytes

An entry over a limit, or with an empty key, is dropped, never truncated, and counted on the run’s invoke_agent span as weft.metadata.dropped. An empty value is a removal and is not counted. Removals apply before additions: a key an empty value removes frees its slot first, so at 64 inherited keys a run that removes one and adds one keeps the new key, whatever the two keys’ sort order. At the key cap the weft. keys are kept first, then the rest in sorted key order, so a large tag set never costs a run its session identity.

WithMetadata(ctx, kv) returns a copy of ctx that carries kv for every run started under it. Use it where the code that learns a fact is not the code that calls Generate: net/http middleware that knows the tenant or the page before the handler runs.

metadata/main.go
tag := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ctx := weft.WithMetadata(r.Context(), map[string]string{
"tenant": r.Header.Get("X-Tenant"),
"region": "eu-west",
})
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
chat := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// The handler passes no metadata option: the run reads the context's pairs.
res, err := agt.Generate(r.Context(), weft.Prompt(r.FormValue("q")))
if err != nil {
http.Error(rw, err.Error(), http.StatusBadGateway)
return
}
fmt.Fprint(rw, res.Text())
})
handler := tag(chat)

metadata/main.go on GitHub

The handler passes no metadata option, and the run still reads tenant and region. The rules match Metadata:

  • Pairs merge over any the context already carries, a later key winning, under the same limits.
  • A run’s own Metadata options win over the context’s pairs.
  • A subagent’s child run inherits them as it inherits the parent’s.
  • An entry over a limit is dropped and counted on each run started under the returned context; that run’s children start from zero.

This is how scope.Header stamps the request’s page as weft.page_url on every run its handler starts. The package example is ExampleWithMetadata.

metadata/main.go tags a run, stamps pairs from HTTP middleware, shows inheritance and removal, and drops an over-long value:

metadata/main.go
// Command metadata runs the examples of the guide "Tag runs with
// metadata": go run ./metadata. Every model is scripted with wefttest,
// so it runs offline; swap in a provider adapter for a real one.
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
// perRun tags one run and reads the pairs back in a tap and in a tool.
func perRun(ctx context.Context, w io.Writer) error {
model := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
wefttest.Say("Order 1234 has shipped."),
)
type LookupInput struct {
OrderID string `json:"order_id" jsonschema:"the order to look up"`
}
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in LookupInput) (string, error) {
tenant := weft.MetadataFromContext(ctx)["tenant"] // the run's pairs, in the handler
return "order " + in.OrderID + " of " + tenant + " has shipped", nil
})
agt := weft.New(model, lookup,
weft.Tap(func(ctx context.Context, ev weft.Event) {
if _, ok := ev.(weft.RunStart); ok {
md := weft.MetadataFromContext(ctx)
fmt.Fprintln(w, "run start: tenant =", md["tenant"], "user =", md["enduser.id"])
}
}),
)
res, err := agt.Generate(ctx,
weft.Prompt("Where is order 1234?"),
weft.Metadata(map[string]string{"tenant": "acme", "enduser.id": "u_42"}),
weft.Metadata(map[string]string{"request.id": "req_7"}), // several options merge; a later key wins
)
if err != nil {
return err
}
fmt.Fprintln(w, "tool saw:", res.Steps[0].Results[0].Content)
return nil
}
// fromRequest stamps metadata in net/http middleware, before the
// handler starts a run.
func fromRequest(ctx context.Context, w io.Writer) error {
agt := weft.New(wefttest.Script(wefttest.Say("ok")),
weft.Tap(func(ctx context.Context, ev weft.Event) {
if _, ok := ev.(weft.RunStart); ok {
md := weft.MetadataFromContext(ctx)
fmt.Fprintln(w, "run start: tenant =", md["tenant"], "region =", md["region"])
}
}))
tag := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ctx := weft.WithMetadata(r.Context(), map[string]string{
"tenant": r.Header.Get("X-Tenant"),
"region": "eu-west",
})
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
chat := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// The handler passes no metadata option: the run reads the context's pairs.
res, err := agt.Generate(r.Context(), weft.Prompt(r.FormValue("q")))
if err != nil {
http.Error(rw, err.Error(), http.StatusBadGateway)
return
}
fmt.Fprint(rw, res.Text())
})
handler := tag(chat)
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/chat?q=hello", nil)
req.Header.Set("X-Tenant", "acme")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Fprintln(w, "response:", rec.Code, rec.Body.String())
return nil
}
// inherit shows a Subagent's child run inheriting the pairs, and an
// empty value removing one.
func inherit(ctx context.Context, w io.Writer) error {
childTap := weft.Tap(func(ctx context.Context, ev weft.Event) {
if _, ok := ev.(weft.RunStart); ok {
md := weft.MetadataFromContext(ctx)
fmt.Fprintf(w, "child run: tenant=%q weft.session.id=%q\n", md["tenant"], md["weft.session.id"])
}
})
researcher := weft.New(wefttest.Script(wefttest.Say("notes"), wefttest.Say("notes")), weft.Name("researcher"), childTap)
lead := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}),
wefttest.Say("done"),
), weft.Subagent("research", "Research a topic.", researcher))
_, err := lead.Generate(ctx, weft.Prompt("Brief me."),
weft.Metadata(map[string]string{"tenant": "acme", "weft.session.id": "s_01"}))
if err != nil {
return err
}
// A run that is not the enclosing session's work says so with "":
_, err = researcher.Generate(weft.WithMetadata(ctx, map[string]string{"tenant": "acme", "weft.session.id": "s_01"}),
weft.Prompt("Standalone."),
weft.Metadata(map[string]string{"weft.session.id": ""}))
return err
}
// limits shows an over-long value dropped, never truncated.
func limits(ctx context.Context, w io.Writer) error {
var got map[string]string
agt := weft.New(wefttest.Script(wefttest.Say("ok")),
weft.Tap(func(ctx context.Context, ev weft.Event) {
if _, ok := ev.(weft.RunStart); ok {
got = weft.MetadataFromContext(ctx)
}
}))
_, err := agt.Generate(ctx, weft.Prompt("hi"), weft.Metadata(map[string]string{
"tenant": "acme",
"notes": strings.Repeat("x", 1025), // over the 1024-byte value limit
}))
if err != nil {
return err
}
_, kept := got["notes"]
fmt.Fprintf(w, "keys kept: %d, notes kept: %t\n", len(got), kept)
return nil
}
func run(ctx context.Context, w io.Writer) error {
steps := []struct {
title string
fn func(context.Context, io.Writer) error
}{
{"per run", perRun},
{"from the request", fromRequest},
{"inherited", inherit},
{"limits", limits},
}
for _, s := range steps {
fmt.Fprintf(w, "== %s\n", s.title)
if err := s.fn(ctx, w); err != nil {
return fmt.Errorf("%s: %w", s.title, err)
}
}
return nil
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View metadata/main.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./metadata
go test ./metadata
== per run
run start: tenant = acme user = u_42
tool saw: order 1234 of acme has shipped
== from the request
run start: tenant = acme region = eu-west
response: 200 ok
== inherited
child run: tenant="acme" weft.session.id="s_01"
child run: tenant="acme" weft.session.id=""
== limits
keys kept: 1, notes kept: false
  • Put identity in metadata, not content. Pairs ride every span and record, and the limits drop anything over 1024 bytes without truncating it. (Source: weft/core/metadata.go:10-20, TestMetadataLimits)
  • Read the drop counter when a key is missing. A dropped pair leaves no trace except weft.metadata.dropped on the run’s invoke_agent span. (Source: weft/core/metadata.go:37-43)
  • Remove an inherited key with "", not by omitting it. A child run inherits every pair it does not override; only an empty value removes one. (Source: TestMetadataEmptyValueRemovesInherited, CHANGELOG 0.15.1)
  • Do not rely on metadata to change behaviour. It is reporting only; the model never sees it. Use run options to change what a run does. (Source: weft/core/metadata.go:70-71)
  • Leave the weft. prefix to weft’s modules. Those keys are kept first under the cap because they carry a run’s session identity. (Source: TestMetadataCapKeepsWeftKeys, CHANGELOG 0.8.0)

Symbols used: weft.Metadata · weft.WithMetadata · weft.MetadataFromContext · weft.Tap · weft.Tool · weft.Subagent · weft.New · weft.Prompt · scope.Header · wefttest.Script · ExampleMetadata · ExampleWithMetadata