Get structured output from a run
weft.Output[T]() constrains a run’s final answer to the struct T, and weft.GenerateAs[T] runs the agent and returns that answer decoded. It works on every provider, because the answer is a tool call: the model calls submit_output with T’s fields as arguments.
In output/main.go, Verdict has two fields, approved (a bool) and reason (a string tagged jsonschema:"one sentence"):
agt := weft.New(model, weft.Instructions("Review refund requests."), weft.Output[Verdict]())
v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?"))if err != nil { return err}fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason)v is a Verdict. res is the ordinary *RunResult, with the transcript and usage.
How it works
Section titled “How it works”Output[T] registers a tool named submit_output. Its input schema is reflected from T the way weft.Tool reflects a handler’s input, and its description is model-visible contract text: Submit your final answer. Call this exactly once, when you are done: the run ends with it. A valid call’s result is recorded.
Output also adds the stop condition output_submitted. The run ends after the step in which a submit_output call produced a non-error result (ADR 0008).
An invalid submission is an ordinary tool error. Arguments that do not decode come back to the model as an ErrInvalidToolInput result naming the field, and the model calls again. In the example the model first sends "approved":"yes" and reads:
INVALID_INPUT: tool "submit_output": field "approved": expected boolean, got stringIts second call decodes, so the run takes two steps. Because repair is the tool-error loop, it needs no special handling and counts against weft.MaxSteps like any step.
What is refused is a wrong type, malformed JSON or trailing data, and an undeclared field under StrictInput; a missing field is not. A field the submission leaves out decodes to its zero value and the run ends on it, required in the schema or not: {"reason":"x"} gives Verdict{Approved: false, Reason: "x"} with a nil error after one step (How do tools work?).
T must be a struct or a pointer to one: providers require an object schema at the top level. Output panics otherwise. Other tools still work beside it; weft.New(model, weft.Output[Verdict](), lookup) lets the model call lookup before it submits.
Decode the output with GenerateAs
Section titled “Decode the output with GenerateAs”GenerateAs calls agt.Generate and decodes the last submit_output call that had a non-error result. A run that ends without one, because the model answered in text, returns weft.ErrNoOutput with the *RunResult still set, so the transcript is inspectable:
_, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?"))if errors.Is(err, weft.ErrNoOutput) { fmt.Fprintln(w, "no structured output; the model said:", res.Text())}A run error, such as a model failure, is returned as *RunError the way Generate returns it, and the *RunResult return is nil; the partial transcript is on the error’s .Result. A step-budget breach is such a run error: a model that still calls tools at weft.MaxSteps fails the run with a *RunError wrapping weft.ErrMaxSteps, not ErrNoOutput. The package example ExampleGenerateAs is the one-step version.
Read the output after a stream
Section titled “Read the output after a stream”weft.OutputOf[T](res) does the decode alone, for a run you streamed. Range over the events, take the result from run.Wait(), then decode:
run := agt.Stream(ctx, weft.Prompt("Refund order 7?"))for _, err := range run.Events() { if err != nil { return err }}res, err := run.Wait()if err != nil { return err}v, err := weft.OutputOf[Verdict](res)if err != nil { return err}fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason)OutputOf follows the same rule as GenerateAs: the newest submit_output call with a non-error result. It returns ErrNoOutput when there is none, or when the bytes do not decode into the type you pass, which means it differs from the type given to Output.
Show partial output while it streams
Section titled “Show partial output while it streams”An OutputDecoder turns submit_output’s argument deltas into a filling-in T, for a UI that renders a form as the model writes it. Create one with weft.NewOutputDecoder[T](), pass it every event you already consume, and draw what Feed returns:
run := agt.Stream(ctx, weft.Prompt("Refund order 42?"))dec := weft.NewOutputDecoder[Verdict]()for ev, err := range run.Events() { if err != nil { return err } if partial, ok := dec.Feed(ev); ok { fmt.Fprintf(w, "partial: approved=%t reason=%q\n", partial.Approved, partial.Reason) }}v, err := dec.Result()if err != nil { return err}fmt.Fprintf(w, "final: approved=%t reason=%q\n", v.Approved, v.Reason)partial: approved=true reason=""partial: approved=true reason="within pol"partial: approved=true reason="within policy"final: approved=true reason="within policy"Feed returns ok == true only when the partial changed. After each delta it decodes the longest closed prefix of the arguments so far: fields not yet written stay at their zero value, and a prefix that does not decode keeps the last good partial. Partials only grow. A later partial never holds fewer fields or array elements than an earlier one. A cut number shows its longest valid prefix (12e reads 12), so a partial number can still change as digits arrive. A cut true, false or null is dropped and its key reads null, so the field holds its zero value. An array element still being written drops back to where it began. A string grows only by appending. A dangling escape, a cut rune or a high surrogate awaiting its pair is held back until it completes. It is never shown as a backslash or U+FFFD. It ignores every event except this run’s StepStart and submit_output’s ToolStart, ToolArgsDelta and ToolFinish; Nested events from subagents are skipped.
Result returns the completed submission by the OutputOf rule, or ErrNoOutput when no valid call finished. Errors surface only there. A second submit_output call within a step starts the buffer over, so Result follows the last call.
Partials come from ToolArgsDelta events, which the OpenAI and Anthropic adapters stream. Gemini’s calls arrive whole, so with the Google adapter the decoder reports one value, at ToolStart. The decoder is never model-visible: it reads the stream and writes nothing back. The package example is ExampleOutputDecoder.
Repair malformed JSON arguments
Section titled “Repair malformed JSON arguments”mw.RepairJSON is model middleware that re-encodes a tool call’s arguments once when they are not valid JSON. It strips a Markdown fence, with any language tag (```json, ```JSON, ```javascript), and closes unterminated strings, objects and arrays; a run of trailing commas before the close is dropped. When the result parses, it replaces the original:
agt := weft.New(model, weft.Output[Verdict](), weft.WrapModel(mw.RepairJSON()), // strip fences, close cut-off JSON, once)v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?"))The scripted model in the example wraps its arguments in a ```json fence; with RepairJSON the run ends in one step. Arguments it cannot repair pass through unchanged, so the model still sees an INVALID_INPUT result. It touches tool-call events only, every tool’s, not only submit_output’s. See Add behaviour with middleware for where it sits in the chain.
Complete example
Section titled “Complete example”output/main.go runs every region against scripted models:
// Command output runs the examples of the guide "Get structured output// from a run": go run ./output. Every model is scripted with wefttest, so// it runs offline; swap in a provider adapter for a real one.package main
import ( "context" "encoding/json" "errors" "fmt" "io" "os"
"github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/wefttest")
// Verdict is the run's final answer. Its tags become submit_output's schema.type Verdict struct { Approved bool `json:"approved"` Reason string `json:"reason" jsonschema:"one sentence"`}
// generateAs: the first submission is invalid, the model repairs it, and// GenerateAs returns the decoded value.func generateAs(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "submit_output", Args: `{"approved":"yes","reason":"within policy"}`}), wefttest.ToolCalls(wefttest.Call{Name: "submit_output", Args: `{"approved":true,"reason":"within policy"}`}), ) agt := weft.New(model, weft.Instructions("Review refund requests."), weft.Output[Verdict]())
v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason) fmt.Fprintln(w, "steps:", res.NumSteps()) fmt.Fprintln(w, "the model first read:", res.Steps[0].Results[0].Content) return nil}
// noOutput: a run that ends in text returns ErrNoOutput with the result.func noOutput(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Looks fine to me.")) agt := weft.New(model, weft.Output[Verdict]()) _, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if errors.Is(err, weft.ErrNoOutput) { fmt.Fprintln(w, "no structured output; the model said:", res.Text()) } return nil}
// outputOf: stream the run, then decode the output from its result.func outputOf(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "submit_output", Args: `{"approved":false,"reason":"past the refund window"}`}), ) agt := weft.New(model, weft.Output[Verdict]()) run := agt.Stream(ctx, weft.Prompt("Refund order 7?")) for _, err := range run.Events() { if err != nil { return err } } res, err := run.Wait() if err != nil { return err } v, err := weft.OutputOf[Verdict](res) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason) return nil}
// decoder: render partial values while submit_output's arguments stream.func decoder(ctx context.Context, w io.Writer) error { turn := wefttest.Raw( weft.ModelToolCallDelta{Index: 0, Name: "submit_output", Args: `{"approved":true,`}, weft.ModelToolCallDelta{Index: 0, Name: "submit_output", Args: `"reason":"within pol`}, weft.ModelToolCallDelta{Index: 0, Name: "submit_output", Args: `icy"}`}, weft.ModelToolCall{ID: "c1", Name: "submit_output", Args: json.RawMessage(`{"approved":true,"reason":"within policy"}`)}, weft.ModelFinish{Reason: weft.StopToolCalls}, ) agt := weft.New(wefttest.Script(turn), weft.Output[Verdict]()) run := agt.Stream(ctx, weft.Prompt("Refund order 42?")) dec := weft.NewOutputDecoder[Verdict]() for ev, err := range run.Events() { if err != nil { return err } if partial, ok := dec.Feed(ev); ok { fmt.Fprintf(w, "partial: approved=%t reason=%q\n", partial.Approved, partial.Reason) } } v, err := dec.Result() if err != nil { return err } fmt.Fprintf(w, "final: approved=%t reason=%q\n", v.Approved, v.Reason) return nil}
// repairJSON: a model that wraps its arguments in a Markdown fence.func repairJSON(ctx context.Context, w io.Writer) error { fenced := wefttest.Raw( weft.ModelToolCall{ID: "c1", Name: "submit_output", Args: json.RawMessage("```json\n{\"approved\":true,\"reason\":\"within policy\"}\n```")}, weft.ModelFinish{Reason: weft.StopToolCalls}, ) model := wefttest.Script(fenced) agt := weft.New(model, weft.Output[Verdict](), weft.WrapModel(mw.RepairJSON()), // strip fences, close cut-off JSON, once ) v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason, "steps:", res.NumSteps()) return nil}
func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"GenerateAs", generateAs}, {"ErrNoOutput", noOutput}, {"OutputOf", outputOf}, {"OutputDecoder", decoder}, {"RepairJSON", repairJSON}, } 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 on GitHub · run it from docs-site/examples:
go run ./outputgo test ./output== GenerateAsapproved: true reason: within policysteps: 2the model first read: INVALID_INPUT: tool "submit_output": field "approved": expected boolean, got string== ErrNoOutputno structured output; the model said: Looks fine to me.== OutputOfapproved: false reason: past the refund window== OutputDecoderpartial: approved=true reason=""partial: approved=true reason="within pol"partial: approved=true reason="within policy"final: approved=true reason="within policy"== RepairJSONapproved: true reason: within policy steps: 1Best practices & gotchas
Section titled “Best practices & gotchas”- Check for
ErrNoOutputwitherrors.Is, and read the result. A model that answers in text ends the run successfully; the error is how you learn there is no value, andresstill holds what it said. (Source:weft/core/output.go:20-24, ADR 0008) - Describe a field whose name does not say what goes in it. A
jsonschema:"…"tag becomes the field’s description insubmit_output’s schema, as for any tool’s input. (Source:weft/core/output.go:26-32,weft/core/tool.go:115) - Do not register your own
submit_outputtool. The name is reserved; a duplicate panics as any duplicate tool does. (Source: ADR 0008, Consequences) - Feed the decoder every event; throttle the rendering instead.
Feedappends each delta’s bytes to its buffer, so a delta you skip is lost and later partials can show wrong values until the call’sToolStartre-seeds the buffer. EachFeedrescans the buffer, so cost grows with the square of the submission’s size: for large submissions, render less often, not feed less often. (Source:weft/core/output.go:213-219, 225-230) - Keep
submit_outputin aToolSourcelist and inOnlyTools. To both, it is an ordinary tool. A source advertises only the list it returns, andOnlyTools("lookup")keeps only the tools it names, so either one dropssubmit_output. The model’s submission then readsNO_SUCH_TOOL: no tool named "submit_output"andGenerateAsreturnsErrNoOutput.weft.ParkAllExceptis different: it never parks the submission. Name it in the narrowing, as inOnlyTools("lookup", "submit_output"). In a source, append the agent’s own definition: the entry ofagt.Tools()namedsubmit_output, whichAgent.Toolsreports even beside a source. The playground’stools_enabledandonly_toolsoverrides areOnlyToolstoo. (Source:weft/core/agent.go:802-809, 949-964;weft/core/run.go:483-488;weft/core/loop.go:1752;weft/runtime/executor.go:1374-1382) - Check required fields yourself. An omitted field is not an invalid submission:
GenerateAsreturns its zero value with a nil error, so a missingapprovedreads asfalse. Check the value afterGenerateAs, or refuse the call before it ends the run: aweft.WrapToolsmiddleware seessubmit_outputlike any tool, with the raw arguments in theToolCallPart’sArgs, before they are decoded. When it returnsweft.ModelRetry("approved is required: true or false"), the model readsRETRY: approved is required: true or false, the run goes on, and the model submits again. Those retries count againstMaxModelRetries(default 3). A pointer field (*bool) tells absent fromfalseafter the decode. (Source:weft/core/tool.go:192-221;weft/core/output.go:45-112;weft/core/loop.go:1783-1797, 1650-1657) - A subagent built with
Outputreturns its submission’s JSON. The parent’s tool result is the child’s last validsubmit_outputarguments, byte for byte. (Source:weft/core/subagent.go:265-276)
See also
Section titled “See also”- How do tools work?: the schema
Tis reflected into - How does a run stop?
- Stream a run’s events
- Add behaviour with middleware
Symbols used: weft.Output · weft.GenerateAs · weft.OutputOf · weft.ErrNoOutput · weft.OutputDecoder · weft.NewOutputDecoder · OutputDecoder.Feed · OutputDecoder.Result · mw.RepairJSON · weft.WrapModel · weft.MaxSteps · weft.ErrMaxSteps · weft.ErrInvalidToolInput · weft.RunError · weft.New · weft.Instructions · weft.Prompt · weft.ModelToolCallDelta · wefttest.Script · wefttest.Raw