Skip to content

Extract structured data from a messy document

View as Markdown

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:

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
)

cookbook/extraction/main.go on GitHub

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:

cookbook/extraction/main.go
// 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"`
}

cookbook/extraction/main.go on GitHub

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:

  1. 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.
  2. Step 1 sends the corrected invoice, but wrapped in a ```json fence. mw.RepairJSON strips the fence before the loop sees the call, the arguments decode, and the run ends.

weft.GenerateAs runs the agent and returns the decoded value from the last valid submission:

cookbook/extraction/main.go
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
}

cookbook/extraction/main.go on GitHub

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:

cookbook/extraction/main.go
// 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)

cookbook/extraction/main.go on GitHub

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.

The program records the run with otel.Install(otel.Local("")):

  • The run’s stopped_by reads output_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.RepairJSON rewrites the model’s event before the loop records it. Since 0.20.0 it also reports the repair: step 1’s call carries weft.tool.args_repaired on its execute_tool span, the step’s chat span a weft.repair event of kind fence, and the run’s repaired counter reads 1 (The onion in the record). The fenced original is on that event only under otel.DevDetail(), and in the provider’s raw body under otel.RawBodies (both dev only).
The extractor's run in Studio: the OUTPUT card shows the typed invoice JSON with "repaired after 1 invalid submission" under it, and the header counts one invalid-input tool errorThe extractor's run in Studio: the OUTPUT card shows the typed invoice JSON with "repaired after 1 invalid submission" under it, and the header counts one invalid-input tool error
The extractor's run: the OUTPUT card with the typed invoice, "repaired after 1 invalid submission", and the header's count of one invalid-input tool error.
FeatureWhat it does hereGuide
weft.Output[Invoice]the submit_output tool and the stopGet structured output from a run
weft.GenerateAs, OutputOfthe decoded valueGet structured output from a run
INVALID_INPUT resultsthe repair loop for schema failuresTool errors are data, run errors are yours
mw.RepairJSONunwraps fenced and cut argumentsAdd behaviour with middleware
weft.MaxStepsbounds the repair loopHow does a run stop?
cookbook/extraction/main.go
// 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-0917
Datum 14.09.2026 Kunde: Acme SARL
2 x Kaffeemühle Pro (grinder) @ 399,00 EUR
1 x Wartungsvertrag 12M (service) @ 312,00 EUR
5 x Filter Set @ 24,90 EUR
GESAMT / 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 cookbook/extraction/main.go on GitHub

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

Terminal window
go run ./cookbook/extraction
go test ./cookbook/extraction
step 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.50
lines add up to the total: true
OutputOf agrees: true
recorded: status=succeeded stopped_by=output_submitted tool_errors=1

The 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.

  • 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, test TestCutSubmissionIsClosed)
  • 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 with ErrMaxSteps, not ErrNoOutput. (Source: weft/core/output.go:26-45, AGENTS.md rule 13)
  • Say the format in the jsonschema tag. It is the model’s only description of the field: decimal separator, date format, units. (Source: weft/core/tool.go:136 godoc)
  • GenerateAs runs and decodes; OutputOf decodes from any RunResult. Both read the last valid submission; use OutputOf after Stream and Wait. (Source: weft/core/output.go:121, 125)

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