Extract structured data from a messy document
weft.Output[T] turns extraction into a tool call: it registers submit_output with T’s schema, and the run ends on the first call whose arguments decode. A submission whose arguments fail to decode into T comes back to the model as an INVALID_INPUT result naming the field, so the model repairs it in the next step. mw.RepairJSON fixes what the model cannot: arguments cut mid-object or wrapped in a Markdown fence.
The extractor in cookbook/extraction/main.go:
return weft.New(model, weft.Name("extractor"), weft.Instructions("You extract invoices into structured data. Numbers use a dot as the decimal "+ "separator; dates are YYYY-MM-DD. Submit with submit_output."), weft.Output[Invoice](), // submit_output, with Invoice's schema weft.WrapModel(mw.RepairJSON()), // closes cut arguments, strips a Markdown fence weft.MaxSteps(5), // bounds the repair loop too)How it works
Section titled “How it works”The shape comes from the weft-arena scenario rw.structured-extraction. An OCR’d German invoice has noise, comma decimals and a dotted date. The target is a Go struct with nested line items:
// Invoice is the extraction target. The tags become submit_output's// schema; jsonschema text is what the model reads for each field.type Invoice struct { Vendor string `json:"vendor" jsonschema:"the issuing company"` InvoiceNumber string `json:"invoice_number" jsonschema:"as printed, e.g. NL-2026-0917"` IssueDate string `json:"issue_date" jsonschema:"YYYY-MM-DD"` Currency string `json:"currency" jsonschema:"ISO 4217 code, e.g. EUR"` Lines []Line `json:"lines" jsonschema:"one entry per printed line item"` Total float64 `json:"total" jsonschema:"the printed total, dot as decimal separator"`}
type Line struct { Description string `json:"description"` Quantity int `json:"quantity" jsonschema:"a whole number"` UnitPrice float64 `json:"unit_price" jsonschema:"dot as decimal separator"`}The struct’s JSON tags and jsonschema text become submit_output’s input schema, reflected as weft.Tool reflects a handler’s input. The jsonschema text is what the model reads for each field: say the format you want there.
The scripted model submits twice:
- Step 0 sends
"quantity":"two". The arguments fail to decode, so the run takes no output from them:INVALID_INPUT: tool "submit_output": field "lines.0.quantity": expected integer, got string. The run goes on. - Step 1 sends the corrected invoice, but wrapped in a
```jsonfence.mw.RepairJSONstrips the fence before the loop sees the call, the arguments decode, and the run ends.
Run it and read the value
Section titled “Run it and read the value”weft.GenerateAs runs the agent and returns the decoded value from the last valid submission:
inv, res, err := weft.GenerateAs[Invoice](ctx, agt, weft.Prompt("Extract this invoice:\n\n"+scan))if err != nil { return err // ErrNoOutput when the run ended without a valid submission}A run that ends without a valid submission returns weft.ErrNoOutput with the result still set, so you can read the transcript. A run that keeps calling tools until MaxSteps fails with ErrMaxSteps instead, a run error with the partial result on the error. weft.OutputOf decodes the same value from any RunResult, such as the one you hold after Stream and Wait; the program checks it agrees with GenerateAs.
Decoding checks types and shape, not meaning: there is no separate schema validation, and a missing field decodes as its zero value. Check what only your application knows after the run:
// The schema checks types; the arithmetic is the application's to check.var sum float64for _, l := range inv.Lines { sum += float64(l.Quantity) * l.UnitPrice}fmt.Fprintf(w, "lines add up to the total: %t\n", math.Abs(sum-inv.Total) < 0.005)Repair messy JSON
Section titled “Repair messy JSON”A model’s tool-call arguments arrive damaged in two common ways: cut off mid-object when the reply hit a limit, or wrapped in a Markdown fence. mw.RepairJSON is model middleware: it re-encodes a tool call’s arguments once when they are not valid JSON, closing unterminated strings, objects and arrays and stripping fences. When the result parses, it replaces the original; when it does not, the arguments pass through unchanged and fail decoding as they would have, so the model still sees an INVALID_INPUT result.
Without it, step 1’s fenced submission reads INVALID_INPUT: tool "submit_output": invalid JSON at offset 1: invalid character '`' looking for beginning of value, and the run spends another step. The package example ExampleRepairJSON closes a cut {"city":"Par into {"city":"Par"}.
A repair can only close what is there. A submission cut after its first line item decodes as a valid Invoice with one line and a zero total. Decoding cannot tell, which is one more reason for the check above.
What to look at in Studio
Section titled “What to look at in Studio”The program records the run with otel.Install(otel.Local("")):
- The run’s
stopped_byreadsoutput_submitted, and the run page shows an OUTPUT card with the typed output’s JSON beside the prompt and the answer (the header). - Step 0’s rejected submission counts as one of the run’s
tool_errors. Its result names the field, so you can see what the model got wrong. - The transcript holds the repaired arguments, because
mw.RepairJSONrewrites the model’s event before the loop records it. Since 0.20.0 it also reports the repair: step 1’s call carriesweft.tool.args_repairedon itsexecute_toolspan, the step’schatspan aweft.repairevent of kindfence, and the run’srepairedcounter reads 1 (The onion in the record). The fenced original is on that event only underotel.DevDetail(), and in the provider’s raw body underotel.RawBodies(both dev only).


The weft features it combines
Section titled “The weft features it combines”| Feature | What it does here | Guide |
|---|---|---|
weft.Output[Invoice] | the submit_output tool and the stop | Get structured output from a run |
weft.GenerateAs, OutputOf | the decoded value | Get structured output from a run |
INVALID_INPUT results | the repair loop for schema failures | Tool errors are data, run errors are yours |
mw.RepairJSON | unwraps fenced and cut arguments | Add behaviour with middleware |
weft.MaxSteps | bounds the repair loop | How does a run stop? |
The program
Section titled “The program”// Command extraction is the recipe "Extract structured data from a messy// document": go run ./cookbook/extraction. An OCR'd invoice becomes a// typed Invoice through weft.Output. The model's first submission has a// field of the wrong type and comes back to it as an INVALID_INPUT// result; its second arrives wrapped in a Markdown fence, and// mw.RepairJSON unwraps it before the loop decodes it. The model is// scripted with wefttest, so it runs offline; the run is recorded to the// local sink ($WEFT_DB, else ./.weft/weft.db).package main
import ( "context" "fmt" "io" "math" "os"
"github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/wefttest")
// Invoice is the extraction target. The tags become submit_output's// schema; jsonschema text is what the model reads for each field.type Invoice struct { Vendor string `json:"vendor" jsonschema:"the issuing company"` InvoiceNumber string `json:"invoice_number" jsonschema:"as printed, e.g. NL-2026-0917"` IssueDate string `json:"issue_date" jsonschema:"YYYY-MM-DD"` Currency string `json:"currency" jsonschema:"ISO 4217 code, e.g. EUR"` Lines []Line `json:"lines" jsonschema:"one entry per printed line item"` Total float64 `json:"total" jsonschema:"the printed total, dot as decimal separator"`}
type Line struct { Description string `json:"description"` Quantity int `json:"quantity" jsonschema:"a whole number"` UnitPrice float64 `json:"unit_price" jsonschema:"dot as decimal separator"`}
const scan = `NORDLICHT GmbH ~~ Rechnung / INVOICE ~~ Nr: NL-2026-0917Datum 14.09.2026 Kunde: Acme SARL2 x Kaffeemühle Pro (grinder) @ 399,00 EUR1 x Wartungsvertrag 12M (service) @ 312,00 EUR5 x Filter Set @ 24,90 EURGESAMT / TOTAL 1.234,50 EUR(scan quality low, page 1/1)`
// script is the model: a submission with "two" for a quantity, then the// corrected one inside a Markdown fence.func script() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{ID: "s1", Name: "submit_output", Args: `{"vendor":"Nordlicht GmbH","invoice_number":"NL-2026-0917","issue_date":"2026-09-14","currency":"EUR",` + `"lines":[{"description":"Kaffeemühle Pro","quantity":"two","unit_price":399}],"total":1234.5}`}), wefttest.ToolCalls(wefttest.Call{ID: "s2", Name: "submit_output", Args: "```json\n" + `{"vendor":"Nordlicht GmbH","invoice_number":"NL-2026-0917","issue_date":"2026-09-14","currency":"EUR",` + `"lines":[{"description":"Kaffeemühle Pro","quantity":2,"unit_price":399},` + `{"description":"Wartungsvertrag 12M","quantity":1,"unit_price":312},` + `{"description":"Filter Set","quantity":5,"unit_price":24.9}],"total":1234.5}` + "\n```"}), )}
// newExtractor builds the extraction agent over model.func newExtractor(model weft.Model) *weft.Agent { return weft.New(model, weft.Name("extractor"), weft.Instructions("You extract invoices into structured data. Numbers use a dot as the decimal "+ "separator; dates are YYYY-MM-DD. Submit with submit_output."), weft.Output[Invoice](), // submit_output, with Invoice's schema weft.WrapModel(mw.RepairJSON()), // closes cut arguments, strips a Markdown fence weft.MaxSteps(5), // bounds the repair loop too )}
func run(ctx context.Context, w io.Writer) error { defer otel.Install(otel.Local(""))()
agt := newExtractor(script()) inv, res, err := weft.GenerateAs[Invoice](ctx, agt, weft.Prompt("Extract this invoice:\n\n"+scan)) if err != nil { return err // ErrNoOutput when the run ended without a valid submission } for _, st := range res.Steps { for _, r := range st.Results { fmt.Fprintf(w, "step %d %s %s → %s (error: %t)\n", st.Index, r.CallID, r.Name, r.Content, r.IsError) } } fmt.Fprintf(w, "invoice: %s %s %s %s, %d lines, total %.2f\n", inv.Vendor, inv.InvoiceNumber, inv.IssueDate, inv.Currency, len(inv.Lines), inv.Total)
// The schema checks types; the arithmetic is the application's to check. var sum float64 for _, l := range inv.Lines { sum += float64(l.Quantity) * l.UnitPrice } fmt.Fprintf(w, "lines add up to the total: %t\n", math.Abs(sum-inv.Total) < 0.005)
again, err := weft.OutputOf[Invoice](res) // the same value, from the result alone if err != nil { return err } fmt.Fprintln(w, "OutputOf agrees:", again.InvoiceNumber == inv.InvoiceNumber && len(again.Lines) == len(inv.Lines))
row, err := otel.LocalDB().Run(ctx, res.ID) if err != nil { return err } fmt.Fprintf(w, "recorded: status=%s stopped_by=%s tool_errors=%d\n", row.Status, row.StoppedBy, row.Problems.ToolErrors) 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 ./cookbook/extractiongo test ./cookbook/extractionstep 0 s1 submit_output → INVALID_INPUT: tool "submit_output": field "lines.0.quantity": expected integer, got string (error: true)step 1 s2 submit_output → recorded (error: false)invoice: Nordlicht GmbH NL-2026-0917 2026-09-14 EUR, 3 lines, total 1234.50lines add up to the total: trueOutputOf agrees: truerecorded: status=succeeded stopped_by=output_submitted tool_errors=1The tests also pin that the fenced submission fails without mw.RepairJSON, that a cut submission is closed, and that the transcript holds the repaired arguments.
Best practices & gotchas
Section titled “Best practices & gotchas”- Validate meaning after the run. Decoding checks types; totals, dates and cross-field rules are the application’s. A repaired cut submission can decode with fields missing. (Source:
weft/core/mw/repairjson.go:14-20, testTestCutSubmissionIsClosed) - Bound the repair loop with
MaxSteps. Each rejected submission costs a step, and a model that never gets it right ends at the step budget withErrMaxSteps, notErrNoOutput. (Source:weft/core/output.go:26-45, AGENTS.md rule 13) - Say the format in the
jsonschematag. It is the model’s only description of the field: decimal separator, date format, units. (Source:weft/core/tool.go:136godoc) GenerateAsruns and decodes;OutputOfdecodes from anyRunResult. Both read the last valid submission; useOutputOfafterStreamandWait. (Source:weft/core/output.go:121, 125)
See also
Section titled “See also”- Get structured output from a run:
Output, the streaming decoder, partial values - Add behaviour with middleware (the two seams):
RepairJSONamong the reference middleware - Tool errors are data, run errors are yours
- Survive flaky infrastructure
Symbols used: weft.Output · weft.GenerateAs · weft.OutputOf · weft.ErrNoOutput · weft.ErrMaxSteps · weft.MaxSteps · weft.Tool · weft.WrapModel · weft.Instructions · mw.RepairJSON · otel.Install · otel.RawBodies · obsdb.Problems · wefttest.Script