Add behaviour with middleware (the two seams)
Behaviour you add to a run attaches at two seams. weft.WrapModel wraps the agent’s model, so middleware sees every request the loop sends; weft.WrapTools wraps every tool call the loop dispatches. In both, the first middleware listed is the outermost, and package mw ships the reference set.
Both seams on one agent, in middleware/seams.go:
lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, _ struct{}) (string, error) { fmt.Fprintln(w, "handler: lookup_order") return "shipped", nil }, weft.WrapTools(trace(w, "tool")), // this tool only, inside the agent's chain)agt := weft.New( wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order"}), wefttest.Say("It has shipped."), ), weft.WrapModel(logRequests(w)), weft.WrapTools(trace(w, "outer"), trace(w, "inner")), // first listed = outermost lookup,)_, err := agt.Generate(ctx, weft.Prompt("Where is my order?"))logRequests prints a line per model request. The three trace middleware print before and after the rest of the chain, which shows the order a call takes:
model request: 1 messages, 1 toolsouter: before lookup_orderinner: before lookup_ordertool: before lookup_orderhandler: lookup_ordertool: after lookup_orderinner: after lookup_orderouter: after lookup_ordermodel request: 3 messages, 1 toolsThe two seams
Section titled “The two seams”Each seam is a function from the next link to a new one, the shape net/http routers such as chi use:
| Seam | Option | Middleware type | Wraps |
|---|---|---|---|
| Model | weft.WrapModel(mw...) | weft.ModelMiddleware: func(next weft.Model) weft.Model | every model call the loop makes |
| Tool | weft.WrapTools(mw...) | weft.ToolMiddleware: func(next weft.ToolCaller) weft.ToolCaller | every tool call the loop and Agent.CallTool dispatch |
WrapModel(a, b) calls a(b(model)); WrapTools(a, b) runs a(b(call)). A later WrapModel or WrapTools option appends inward. Nil entries are ignored. The model chain is built once, at weft.New.
WrapTools works on a tool too: passed to weft.Tool, it wraps that tool alone, inside the agent’s chain. A tool call goes through, in order: the agent’s middleware, the tool’s own middleware, then the base, which resolves the tool, checks RequireApproval, decodes the arguments and runs the handler.
Two seams is the whole set. Observation is a third thing, weft.Tap, which sees every event and changes nothing. A third seam needs an ADR. To see where each phase of a step and a tool call sits around the seams, read docs/life-of-a-call.md.
Model middleware
Section titled “Model middleware”A ModelMiddleware returns a weft.Model that wraps next. It sees each weft.ModelRequest as the loop built it, after PrepareStep, and every event the inner model yields. It may log, retry, substitute or rewrite:
// logRequests is a ModelMiddleware: it prints a line for every request// the loop sends, then streams the inner model's reply unchanged.func logRequests(w io.Writer) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return requestLogger{next: next, w: w} }}
type requestLogger struct { next weft.Model w io.Writer}
func (m requestLogger) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { fmt.Fprintf(m.w, "model request: %d messages, %d tools\n", len(req.Messages), len(req.Tools)) return m.next.Stream(ctx, req)}
// Info and Unwrap forward the inner model's identity and declare it.func (m requestLogger) Info() weft.ModelInfo { return weft.InfoOf(m.next) }func (m requestLogger) Unwrap() weft.Model { return m.next }A middleware may rewrite its own request. Each request carries its own copies of the slices, of each message’s Content, and of Params’ values. mw.Retry and mw.Fallback hand each attempt a fresh copy. So a write such as *req.Params.Temperature holds for that attempt alone. Nothing leaks to the agent, the run option, the caller’s variable, a later step or the next attempt:
// capTemperature is a ModelMiddleware that writes the request's own// temperature: since 0.18.1 each request, and each mw.Retry or// mw.Fallback attempt, carries its own copy of Params' values, so the// write reaches neither the agent, the run option, the caller's// variable, a later step nor the next attempt.func capTemperature(limit float64) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return tempCap{next: next, limit: limit} }}
type tempCap struct { next weft.Model limit float64}
func (m tempCap) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { if t := req.Params.Temperature; t != nil && *t > m.limit { *t = m.limit // this request's copy; the bytes inside parts stay read-only } return m.next.Stream(ctx, req)}
func (m tempCap) Info() weft.ModelInfo { return weft.InfoOf(m.next) }func (m tempCap) Unwrap() weft.Model { return m.next }TestCapTemperature runs it inside mw.Retry with a temperature of 0.9: both tries are sent 0.5, and the caller’s variable still reads 0.9. The bytes inside parts (Args, Data) stay shared and read-only.
Forward the inner model’s identity with weft.InfoOf, so RunStart.Model and the manifest still name the provider. Declare the wrapped model with an Unwrap method, so a caller can walk the chain with weft.Unwrap. A middleware that returns a nil Model panics at New. The package example ExampleWrapModel is the same shape.
Tool middleware
Section titled “Tool middleware”A weft.ToolCaller takes a call and returns the result text the model will see, or an error. A ToolMiddleware wraps one and may act before next (deny, decorate ctx, log), after it (map errors, audit), or instead of it:
// trace is a ToolMiddleware that prints before and after the rest of the// chain runs.func trace(w io.Writer, name string) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { fmt.Fprintf(w, "%s: before %s\n", name, call.Name) out, err := next(ctx, call) fmt.Fprintf(w, "%s: after %s\n", name, call.Name) return out, err } }}What the middleware returns decides what the model sees:
- A string and nil is the result.
- A
*weft.ToolErrorgives the model a code:&weft.ToolError{Code: "DENIED", Message: "this agent is read-only"}readsDENIED: this agent is read-only. - Any other error is rendered as its text, exactly as a handler error would be.
- An error wrapping
weft.ErrApprovalRequiredis the one non-result: the call parks onRunResult.Pending. See Require human approval for a tool.
A middleware panic is a tool "x" panicked: … result, never a run error: panic containment sits outside the chain. So does weft.Timeout, which bounds the whole chain. An unknown tool still runs the agent’s chain, so mw.Allow and mw.Audit see the attempt, before the base returns NO_SUCH_TOOL. The package example ExampleWrapTools denies every delete_ tool.
Pass facts on the context
Section titled “Pass facts on the context”Middleware that verifies something (a user, a tenant, a quota) puts it on ctx before calling next. The handler reads it back through a typed accessor, the same shape as weft.CallFromContext:
// The accessor pair: only this package can put a user on a context.type user struct{ Name string }
type userKey struct{}
func withUser(ctx context.Context, u user) context.Context { return context.WithValue(ctx, userKey{}, u)}
func userFrom(ctx context.Context) (user, bool) { u, ok := ctx.Value(userKey{}).(user) return u, ok}
// authenticate verifies the caller before next and puts the user on ctx.func authenticate(lookup func(ctx context.Context) (user, error)) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { u, err := lookup(ctx) if err != nil { return "", &weft.ToolError{Code: "UNAUTHENTICATED", Message: "sign in first", Err: err} } return next(withUser(ctx, u), call) } }}
// myOrders reads the verified user back; it never trusts the arguments// for who is calling.var myOrders = weft.Tool("my_orders", "List the caller's orders.", func(ctx context.Context, _ struct{}) (string, error) { u, ok := userFrom(ctx) if !ok { return "", weft.Errorf("UNAUTHENTICATED", "no user on the call") } return "orders for " + u.Name + ": 1234, 5678", nil })With a verified user, my_orders returns orders for ada: 1234, 5678. When the lookup fails, the middleware never calls next and the model reads UNAUTHENTICATED: sign in first; the cause stays on ToolError.Err for logs. Put only verified data on the context, and derive business values in the handler after decoding. The package example is ExampleWrapTools_context.
Reference middleware
Section titled “Reference middleware”Package mw holds small, dependency-free middleware for both seams. Copy one, compose them, or write your own:
| Middleware | Seam | What it does |
|---|---|---|
mw.Allow(permit) | tool | Runs a call only when permit(call) is true |
mw.Audit(logger) | tool | One Info line per call |
mw.MapErrors(fn) | tool | Shapes handler errors before the model sees them |
mw.Log(logger) | model | One Debug line before and one after each model call |
mw.Retry, mw.Fallback, mw.FallbackWhen | model | Retry with backoff, then fail over: Retry and fall back when a provider fails |
mw.RepairJSON | model | Closes a truncated or fenced tool-call argument object once: Get structured output from a run |
The tool trio together, with mw.Log on the model:
permit := func(c weft.Call) bool { return !strings.HasPrefix(c.Name, "delete_") }agt := weft.New(model, weft.WrapModel(mw.Log(logger)), // Debug: one line before and one after each model call weft.WrapTools( mw.Audit(logger), // observation: one Info line per call, with the cause mw.Allow(permit), // decision: DENIED: tool "x" is not allowed mw.MapErrors(nil), // shaping: plain errors → INTERNAL: tool "x" failed ), lookup, query, deleteOrder,)res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Status, report, then delete 1234."))The order follows the godoc’s: observation outermost, then the decision, then shaping. mw.Audit outside mw.Allow logs denied calls too. On the model seam the godoc’s order is mw.Log, mw.Fallback, mw.Retry, mw.RepairJSON, outermost first. mw ships no rate limiter, because golang.org/x/time would be its first dependency; Example_rateLimitMiddleware builds one from the standard library.
mw.Allow(permit) gates every call on a predicate over its weft.Call. A denied call never runs: the model reads DENIED: tool "delete_order" is not allowed and the loop moves on, with no retry and no prompt. A nil permit allows every call. Outside the loop (Agent.CallTool with a bare ctx) the Call is built from the call part alone. Allow is a fixed policy; a decision deferred to a person is approval. Package example: ExampleAllow.
mw.Audit(logger) logs one line per call at Info level, on slog.Default when logger is nil: run, step, call id, tool, duration, and the outcome. A failed call’s line carries the model-visible text as err and, for a *weft.ToolError with a cause, the cause as cause. Under the agent’s weft.Content(false) neither text is logged, only err_bytes (the text’s length) and the ToolError code. Audit changes nothing. Package example: ExampleAudit.
mw.Log(logger) writes a Debug line before each model call (provider, model, message and tool counts) and one after it (stop reason, usage, tool-call count, duration). Placed outermost it sees the outcome of retries and fallbacks; placed innermost, each attempt. A nil logger means slog.Default. Package example: ExampleLog.
Map errors
Section titled “Map errors”mw.MapErrors(fn) shapes handler errors in one place. A *weft.ToolError, a context error and ErrApprovalRequired pass through untouched; every other error goes through fn. With a nil fn, the default hides the text (database messages, stack fragments) behind INTERNAL: tool "query" failed and keeps the original as the ToolError’s cause, where mw.Audit and errors.As still find it. When fn returns nil, the original error stands. Package example: ExampleMapErrors.
Check middleware keeps model info
Section titled “Check middleware keeps model info”wefttest.ConformInfo(m) returns nil when model middleware m forwards the inner model’s identity unchanged, and an error otherwise, showing the Info it got and the one it wanted. The error names the function’s Go type, core.ModelMiddleware, not which middleware failed, so call it once per middleware. wefttest.ConformInfoT is the test-helper form. Add one line to your middleware’s tests, from middleware/middleware_test.go:
// The convention, checked: logRequests forwards the inner model's// identity, so RunStart.Model and the manifest still name the provider.func TestLogRequestsKeepsModelInfo(t *testing.T) { wefttest.ConformInfoT(t, logRequests(&bytes.Buffer{}))}The onion in the record
Section titled “The onion in the record”Since 0.20.0 the record says which middleware wrapped a call and what each layer decided, at three levels. All of it reports only: nothing here changes a call, a retry, a denial or a result.
The manifest lists the chain. Each agent’s manifest names its model_middleware and tool_middleware outer to inner, with a tool’s own middleware under the tool. It also lists the hooks the agent has: prepare_step, tap, on_run_end and tool_source. Each entry is {name, params?, source?, opaque?}, a weft.MiddlewareInfo.
A model layer may describe itself with an optional Describe() weft.MiddlewareInfo method. mw.Retry reports its budget and delays, mw.Fallback its backups, mw.Log and mw.RepairJSON their names. Any other model layer is named by its type, and the walk goes inward through Unwrap. A layer without Unwrap ends the walk and is marked opaque, so the chain never reads shorter than it is without saying so.
Put only configuration in Describe()’s Params: counts, durations, model names. Never put a secret or a closure’s captured value there. The manifest is hashed into every run’s weft.manifest.hash, and Studio serves it whole at GET /api/manifests/{hash}.
A tool middleware is a function, so it is named by what the function is:
agt := weft.New(wefttest.Script(), weft.Name("payments"), weft.WrapTools( mw.Allow(func(weft.Call) bool { return true }), // "mw.Allow", no source budget, // "<package>.budget" ("main.budget" in a command), source "<import path>/onion.go:17" func(next weft.ToolCaller) weft.ToolCaller { return next }, // "func@middleware/onion.go:38", that place its source ))b, err := weft.Manifest(agt)| Tool middleware | name | source |
|---|---|---|
weft’s own (mw.Allow, mw.Audit, mw.MapErrors) | its name, registered with weft.NameToolMiddleware | none |
| a named function or method | its package-qualified name, such as main.budget in a command | its position, such as github.com/x/app/budget.go:17 |
| a closure | func@<dir>/<file>:<line>, where it is written, such as func@app/main.go:42; Studio’s layer drawer shows it as main.go:42 | the same place, app/main.go:42 |
Wrap your own constructor’s closure in weft.NameToolMiddleware(name, mw) to give it a name instead. The name belongs to the function literal, not to one closure of it: every closure of that literal shares it, and a later call for the same literal replaces it, in agents already built too. A constructor that names each closure from its argument ("limit:"+name) leaves every agent’s manifest with the last name it was called with. weft.manifest.hash is computed once, at New, so an agent built before that last call keeps its old hash on every run while weft.Manifest(a) now holds the new name and hashes differently: its runs no longer match its own manifest, and they read stale against a registration or weft.json made later. Give each distinct name its own literal, or keep the name constant. The names do not depend on what the compiler inlined or on the Go version. A named function’s source is one form on every machine: the defining package’s import path, the file’s base name and the line, never an absolute path. A closure’s is its directory’s name and file. Because the manifest lists the onion, adding or removing middleware changes weft.manifest.hash (The manifest hash). ExampleMiddlewareInfo prints one.
The spans say what a layer decided. A tool middleware tells the call’s execute_tool span through weft.ToolReportFromContext(ctx), a ToolReporter:
// budget refuses wire_money and says so on the call's execute_tool span// (weft.tool.denied_by "budget"). Reporting changes nothing the model sees.func budget(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { if call.Name == "wire_money" { weft.ToolReportFromContext(ctx).Denied("budget") return "", &weft.ToolError{Code: weft.CodeDenied, Message: "over budget"} } return next(ctx, call) }}| Reporter call | Span attribute | Set by |
|---|---|---|
Denied(by) | weft.tool.denied_by | mw.Allow reports allow; a deny grant on a resume grant (with weft.grant.id), else approval |
Masked(original) | weft.tool.error_masked | mw.MapErrors: the hidden error’s kind, never its text. The kind is the first of: an ErrorKind() string method, a context error’s name, an ErrorType() method, a ToolError’s code, a standard sentinel through errors.Is (io.EOF, fs.ErrNotExist), else the error’s Go type. Studio and the devtools panel read a plain error’s type (*errors.errorString) as “plain error” and an errors.Join or two-%w error’s as “joined errors”; the attribute keeps the type. A mapping that only wraps reports nothing |
Three rules bound these reports. Denied(by) reaches the span only when the call then ends in an error. The last report of a kind wins. Outside a loop-dispatched call, Agent.CallTool included, ToolReportFromContext returns a reporter that discards every report.
A model middleware that rewrites a call’s arguments reports it with Reporter.Repair and a weft.RepairInfo (CallID, Kind, Original, Repaired): the step’s chat span gets a weft.repair event and the call weft.tool.args_repaired. mw.RepairJSON does this, with the kinds fence, unterminated, fence+unterminated and trim. mw.Retry marks the requests it sent again with weft.attempt.layer retry (Report attempts). The examples ExampleToolReportFromContext and ExampleReporter_Repair show both.
Development detail shows every layer. otel.DevDetail() adds one layer <name> span per WrapModel or WrapTools layer per call, named as the manifest names the layer. The spans nest outer to inner under the call’s chat or execute_tool span. Each carries weft.layer.name, weft.layer.kind (model or tool), weft.layer.index (0 the outermost) and error.type where the layer returned an error. The weft.repair event then carries the original arguments, capped at 4 KiB. A contained tool or middleware panic’s stack rides its execute_tool span as a weft.panic event, capped at 16 KiB. It is off by default: a span per layer is 2 to 6 more spans per call. Like RawBodies it takes effect only behind the development gate (WEFT_ENV=dev, or otel.DevMode()); otherwise Start logs otel: DevDetail ignored: …. Only the Local and Studio destinations with content on receive it (Record provider wire bodies).
Pass the pipeline’s logger provider to the agent with weft.LoggerProvider(p.LoggerProvider()), or rely on Install’s global registration. With the option the agent knows the level at New and builds the layer boundaries into its one model chain. Through the global provider it cannot: the first run builds a second chain, so your WrapModel constructors run twice and a stateful middleware holds two states. ExampleDevDetail shows it.
Studio draws all three in the run page’s “what wrapped this call” (Read a run in Studio).
Complete example
Section titled “Complete example”middleware/seams.go runs the chain-order demo, the context accessor with a good and a failed lookup, and the reference middleware on three parallel calls:
package main
import ( "context" "errors" "fmt" "io" "iter" "log/slog" "slices" "strings"
"github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/wefttest")
// logRequests is a ModelMiddleware: it prints a line for every request// the loop sends, then streams the inner model's reply unchanged.func logRequests(w io.Writer) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return requestLogger{next: next, w: w} }}
type requestLogger struct { next weft.Model w io.Writer}
func (m requestLogger) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { fmt.Fprintf(m.w, "model request: %d messages, %d tools\n", len(req.Messages), len(req.Tools)) return m.next.Stream(ctx, req)}
// Info and Unwrap forward the inner model's identity and declare it.func (m requestLogger) Info() weft.ModelInfo { return weft.InfoOf(m.next) }func (m requestLogger) Unwrap() weft.Model { return m.next }
// trace is a ToolMiddleware that prints before and after the rest of the// chain runs.func trace(w io.Writer, name string) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { fmt.Fprintf(w, "%s: before %s\n", name, call.Name) out, err := next(ctx, call) fmt.Fprintf(w, "%s: after %s\n", name, call.Name) return out, err } }}
// seamOrder runs one tool call through two agent middleware and one tool// middleware, and one model call through logRequests.func seamOrder(ctx context.Context, w io.Writer) error { lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, _ struct{}) (string, error) { fmt.Fprintln(w, "handler: lookup_order") return "shipped", nil }, weft.WrapTools(trace(w, "tool")), // this tool only, inside the agent's chain ) agt := weft.New( wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order"}), wefttest.Say("It has shipped."), ), weft.WrapModel(logRequests(w)), weft.WrapTools(trace(w, "outer"), trace(w, "inner")), // first listed = outermost lookup, ) _, err := agt.Generate(ctx, weft.Prompt("Where is my order?")) return err}
// The accessor pair: only this package can put a user on a context.type user struct{ Name string }
type userKey struct{}
func withUser(ctx context.Context, u user) context.Context { return context.WithValue(ctx, userKey{}, u)}
func userFrom(ctx context.Context) (user, bool) { u, ok := ctx.Value(userKey{}).(user) return u, ok}
// authenticate verifies the caller before next and puts the user on ctx.func authenticate(lookup func(ctx context.Context) (user, error)) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { u, err := lookup(ctx) if err != nil { return "", &weft.ToolError{Code: "UNAUTHENTICATED", Message: "sign in first", Err: err} } return next(withUser(ctx, u), call) } }}
// myOrders reads the verified user back; it never trusts the arguments// for who is calling.var myOrders = weft.Tool("my_orders", "List the caller's orders.", func(ctx context.Context, _ struct{}) (string, error) { u, ok := userFrom(ctx) if !ok { return "", weft.Errorf("UNAUTHENTICATED", "no user on the call") } return "orders for " + u.Name + ": 1234, 5678", nil })
// contextFacts runs my_orders once with a verified user and once with a// failed lookup.func contextFacts(ctx context.Context, w io.Writer) error { for _, lookup := range []func(context.Context) (user, error){ func(context.Context) (user, error) { return user{Name: "ada"}, nil }, func(context.Context) (user, error) { return user{}, errors.New("session expired") }, } { agt := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "my_orders"}), wefttest.Say("Done."), ), myOrders, weft.WrapTools(authenticate(lookup))) res, err := agt.Generate(ctx, weft.Prompt("Show my orders.")) if err != nil { return err } fmt.Fprintln(w, "my_orders →", res.Steps[0].Results[0].Content) } return nil}
// referenceSet runs the reference tool middleware together.func referenceSet(ctx context.Context, w io.Writer) error { // Drop the time and duration attributes so the output is stable. stable := func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey || a.Key == "dur" { return slog.Attr{} } return a } var logs strings.Builder logger := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: stable}))
lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, _ struct{}) (string, error) { return "shipped", nil }) query := weft.Tool("query", "Run a report query.", func(_ context.Context, _ struct{}) (string, error) { return "", errors.New("pq: SSL is not enabled on the server") }) deleteOrder := weft.Tool("delete_order", "Delete an order.", func(_ context.Context, _ struct{}) (string, error) { return "deleted", nil }) model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{ID: "c1", Name: "lookup_order"}, wefttest.Call{ID: "c2", Name: "query"}, wefttest.Call{ID: "c3", Name: "delete_order"}, ), wefttest.Say("Order shipped; the report and the delete failed."), )
permit := func(c weft.Call) bool { return !strings.HasPrefix(c.Name, "delete_") } agt := weft.New(model, weft.WrapModel(mw.Log(logger)), // Debug: one line before and one after each model call weft.WrapTools( mw.Audit(logger), // observation: one Info line per call, with the cause mw.Allow(permit), // decision: DENIED: tool "x" is not allowed mw.MapErrors(nil), // shaping: plain errors → INTERNAL: tool "x" failed ), lookup, query, deleteOrder, ) res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Status, report, then delete 1234.")) if err != nil { return err } for _, r := range res.Steps[0].Results { fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content) } // The calls ran in parallel, so their audit lines are sorted by call id. var audit []string for _, line := range strings.Split(strings.TrimSpace(logs.String()), "\n") { if strings.Contains(line, `msg="tool call"`) { audit = append(audit, line[strings.Index(line, "run="):]) } } slices.Sort(audit) for _, line := range audit { fmt.Fprintln(w, "audit:", line) } return nil}
// demoSeams is the middleware page's complete example.func demoSeams(ctx context.Context, w io.Writer) error { for _, demo := range []func(context.Context, io.Writer) error{seamOrder, contextFacts, referenceSet} { if err := demo(ctx, w); err != nil { return err } } return nil}Run it from docs-site/examples:
go run ./middleware seamsgo test ./middlewaremodel request: 1 messages, 1 toolsouter: before lookup_orderinner: before lookup_ordertool: before lookup_orderhandler: lookup_ordertool: after lookup_orderinner: after lookup_orderouter: after lookup_ordermodel request: 3 messages, 1 toolsmy_orders → orders for ada: 1234, 5678my_orders → UNAUTHENTICATED: sign in firstlookup_order → shippedquery → INTERNAL: tool "query" faileddelete_order → DENIED: tool "delete_order" is not allowedaudit: run=run-1 step=0 call=c1 tool=lookup_order result_bytes=7audit: run=run-1 step=0 call=c2 tool=query err="INTERNAL: tool \"query\" failed" cause="pq: SSL is not enabled on the server"audit: run=run-1 step=0 call=c3 tool=delete_order err="DENIED: tool \"delete_order\" is not allowed"Best practices & gotchas
Section titled “Best practices & gotchas”- List the outermost middleware first.
WrapModel(a, b)isa(b(model)); a later option appends inward. (Source:weft/core/agent.go:265-271,weft/core/tool.go:569-580) - Put
mw.Fallbackoutsidemw.Retry. Then the primary is retried to exhaustion before the backup is tried; the reverse retries the whole fallback chain. (Source:weft/core/mw/doc.go:15-19) - Forward
Infoand declareUnwrapin model middleware. WithoutInfo,RunStart.Modeland the manifest lose the provider;wefttest.ConformInfoTcatches it. (Source:weft/core/agent.go:246-253,weft/core/wefttest/conform.go:15-22) - Decorate
ctxonly with what the middleware verified. Handlers trust what an accessor returns; arguments come from the model. (Source:weft/docs/adr/0006-seams.md:59-64) - Observe events with
weft.Tap; reach for observing middleware only at the seam. A tap sees every event and changes nothing. Usemw.Auditormw.Logwhen you need the call’s context or its outcome where the call is made. (Source: AGENTS.md rule 10,weft/core/mw/doc.go:23,weft/core/mw/tool.go:45-53,weft/core/mw/model.go:297-302) - Expect parallel calls to log out of order. Tool calls in one step run concurrently, so
mw.Auditlines arrive in completion order; sort by call id when the order matters. (Source:docs-site/examples/middleware/seams.goreferenceSet, AGENTS.md rule 3)
See also
Section titled “See also”- How do tools work?
- Retry and fall back when a provider fails
- Require human approval for a tool
- Observe a run without changing it: Tap, OnRunEnd, OnMessages
- What is a Model? The provider contract
Symbols used: weft.WrapModel · weft.WrapTools · weft.ModelMiddleware · weft.ToolMiddleware · weft.ToolCaller · weft.ToolCallPart · weft.Model · weft.ModelRequest · weft.InfoOf · weft.Unwrap · weft.ToolError · weft.Errorf · weft.ErrApprovalRequired · weft.Call · weft.CallFromContext · weft.Tap · weft.Content · weft.RunID · Agent.CallTool · mw.Allow · mw.Audit · mw.MapErrors · mw.Log · wefttest.ConformInfo · wefttest.ConformInfoT · wefttest.Script