---
title: Extract structured data from a messy document
description: Turn an OCR'd invoice into a typed Go struct with weft.Output and weft.GenerateAs, let the model repair a submission that fails to decode, and unwrap fenced or cut JSON with mw.RepairJSON.
url: https://weftgo.dev/docs/examples/structured-extraction/
type: how-to
sources:
  - weft/core/output.go:24 (ErrNoOutput), 26-45 (Output, the repair loop is the ordinary tool-error loop), 121 (GenerateAs), 159 (OutputOf)
  - weft/core/mw/repairjson.go:14-25 (RepairJSON closes, strips fences, passes the unrepairable through)
  - weft/core/tool.go:136 (Tool's schema from struct tags; Output reflects the same way), 306-319 (INVALID_INPUT comes from the decode failing; no separate schema validation)
  - 'weft/obsdb/problems.go:31-36 (ToolErrors), 45-48 (Repaired: execute_tool spans with weft.tool.args_repaired true), 176-177 (the token), 235-236 (the count)'
  - 'weft/core/mw/repairjson.go:51-59 (RepairJSON reports each repair, Reporter.Repair), 86-120 (the kinds: a fenced payload that parses is `fence`); weft/core/layers.go:457-500 (Repair: the weft.repair event, its kind, the original only at the development detail level); weft/core/observe.go:610-614, 1099-1125 (the call''s execute_tool span carries weft.tool.args_repaired); weft/CHANGELOG.md:35 (0.20.0, U23.1)'
  - weft/otel/options.go:165 (RawBodies)
  - weft/AGENTS.md:184-193 (block 4b)
  - weft/mw/example_test.go:129 (ExampleRepairJSON)
  - 'weft-arena/internal/suites/realworld_more.go: rwStructuredExtraction (inspiration only)'
  - docs-site/examples/cookbook/extraction/main.go, main_test.go TestExtraction, TestFenceNeedsRepairJSON, TestCutSubmissionIsClosed, TestTranscriptHoldsTheRepairedArgs
---

# Extract structured data from a messy document

[`weft.Output[T]`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RepairJSON) fixes what the model cannot: arguments cut mid-object or wrapped in a Markdown fence.

The extractor in `cookbook/extraction/main.go`:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/extraction/main.go)

## 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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/extraction/main.go)

The struct's JSON tags and `jsonschema` text become `submit_output`'s input schema, reflected as [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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.

## Run it and read the value

[`weft.GenerateAs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#GenerateAs) runs the agent and returns the decoded value from the last valid submission:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/extraction/main.go)

A run that ends without a valid submission returns [`weft.ErrNoOutput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/extraction/main.go)

## 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-RepairJSON) 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

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](https://weftgo.dev/docs/observe/studio/run-page/#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](https://weftgo.dev/docs/guides/middleware/#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 error](https://weftgo.dev/docs/_astro/studio-run-extraction.light.zQloozjz.webp)

*The extractor's run: the OUTPUT card with the typed invoice, &quot;repaired after 1 invalid submission&quot;, and the header's count of one invalid-input tool error.*

## 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](https://weftgo.dev/docs/guides/structured-output/) |
| `weft.GenerateAs`, `OutputOf` | the decoded value | [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/) |
| `INVALID_INPUT` results | the repair loop for schema failures | [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) |
| `mw.RepairJSON` | unwraps fenced and cut arguments | [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) |
| `weft.MaxSteps` | bounds the repair loop | [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) |

## The program

````go title="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)
	}
}
````

[cookbook/extraction/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/extraction/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/cookbook/extraction) · run it from `docs-site/examples`:

```sh
go run ./cookbook/extraction
go test ./cookbook/extraction
```

```text
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.

## 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`, 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)

## See also

- [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/): `Output`, the streaming decoder, partial values
- [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/): `RepairJSON` among the reference middleware
- [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/)
- [Survive flaky infrastructure](https://weftgo.dev/docs/examples/flaky-infrastructure/)

Symbols used: [`weft.Output`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) · [`weft.GenerateAs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#GenerateAs) · [`weft.OutputOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OutputOf) · [`weft.ErrNoOutput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoOutput) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`mw.RepairJSON`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RepairJSON) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.RawBodies`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#RawBodies) · [`obsdb.Problems`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Problems) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
