
Structured output: an agent’s answer in a fixed shape
Get a typed, checked answer from any tool-calling model by making the answer a final tool.
On the agent compass Stage 4 of 4 · DecideA chatbot’s last message is written for a human.
The last step of many agents is written for a program: the crash-triage agent, the companion code’s agent that reads crash reports from the remind practice service and files issues in a tracker, has to say which reports share a cause, where the bug lives, which test proves it, and which tracker issue it belongs to.
Code that scrapes those facts out of prose works until the model words things differently, which it will.
The answer needs a shape the program can decode.
Below, the triage agent gets such a shape. This page covers both approaches, says which one the companion code uses by default, and then turns to what matters more than the format: verifying what the answer claims.
Two ways to get structure
A constrained reply. Structured outputs is a request option, response_format, that tells the API to make the reply conform to a JSON Schema.
Support varies by model and by provider, so check it before you rely on it.
On OpenRouter, leaving out require_parameters allows routing to a provider that doesn’t honor response_format.
Many providers also won’t apply it in a turn that offers tools. Reserve it for single calls that use no tools, for example condensing the early turns of a long conversation.
A final tool. Give the agent an extra tool, submit_diagnosis in this case, and make its arguments the answer.
Nothing about it is special: the schema comes from the same generator as every other tool’s, the arguments go through the same decoder and checks, and a rejected call produces an ordinary tool error.
Any model that supports tool calling can use it.
The companion code takes this route by default.
The answer as a Go type
The answer is declared as a Go struct, tagged the same way as the argument structs on the tool design page, so its schema is generated:
// A Diagnosis is the agent's answer for one crash group: which reports
// share a cause, where the code is wrong, the test that shows it, and
// what was done about it.
type Diagnosis struct {
Fingerprint string `json:"fingerprint" desc:"the group's fingerprint, from crash_list"`
Reports []string `json:"reports" desc:"the IDs of every report in the group"`
Category string `json:"category" enum:"nil_value,out_of_range,concurrency,bad_input,other"`
RootCause Location `json:"root_cause" desc:"where the code is wrong, which may not be where it crashed"`
Evidence string `json:"evidence" desc:"why this is the cause: what you read and ran"`
Reproducer Location `json:"reproducer,omitzero" desc:"the test you wrote that fails before the fix; leave out for already_fixed and duplicate"`
Fix string `json:"fix,omitzero" desc:"what you changed, for status fixed"`
Status string `json:"status" enum:"fixed,already_fixed,duplicate,not_a_bug,needs_human"`
Issue int `json:"issue,omitzero" desc:"the issue you filed, for status fixed or needs_human"`
Duplicate int `json:"duplicate,omitzero" desc:"for status duplicate: the open issue it duplicates"`
}
// A Location is a function in a file of remind's source.
type Location struct {
File string `json:"file" desc:"a file path, such as store/store.go"`
Function string `json:"function" desc:"a function or method, such as (*Store).Get or TestGetDeleted"`
}
Fields that code will switch on, the status above all, are enumerations.
Each field’s description explains it to the model, and the descriptions spell out the easy-to-miss points, such as a root cause that “may not be where it crashed”.
A field the model has nothing for is meant to be left out of the JSON rather than sent as null.
There is one Diagnosis for each crash group, and the grader of the crash catalog, the set of seeded crashes the agent is tested on, reads the same record.
How the loop ends on it
Marking a tool Final changes the loop’s stopping rule.
When a call to that tool succeeds, the run is over and the call’s arguments are the run’s result:
// finished reports whether a reply held a successful call to the final
// tool, and returns its arguments, the run's answer. A call that failed
// went back to the model as an error, and the run goes on.
func finished(byName map[string]Tool, calls []ToolCall,
answers []Message) (jsontext.Value, bool) {
for i, c := range calls {
if byName[c.Name].Final && i < len(answers) &&
!answers[i].IsError {
return c.Arguments, true
}
}
return nil, false
}
If the call is rejected, the model receives the error as a tool result and keeps going. That gives the final tool the power to turn an answer down and lets the model correct it. Once a final call succeeds, nothing else in that reply runs: later calls in the reply get “not run” as their result, so the answer matches the code exactly as it stood at the moment of acceptance.
A model that writes its answer as plain text instead of calling the tool gets a nudge: a user message telling it to call the tool once it is finished, or to carry on with the work.
If two nudges don’t help, the run ends with ErrNoFinalAnswer, a sign that the program never received an answer it could use; callers test for it with errors.Is.
Checking what the answer claims
The schema makes sure the answer has the right fields and types.
Whether the content is correct is a separate matter, and a model sounds just as sure when it is wrong.
submit_diagnosis therefore verifies everything it can before it says yes:
- Each report belongs to one group and only one.
- A group marked duplicate points at an issue that is open, and a group marked fixed points at an issue that exists.
- For a fixed group, the reproducer, a test the agent wrote that fails because of the bug, is run twice. Against the untouched original plus the tests the agent wrote, it has to fail; against the agent’s changed code it has to pass.
The reproducer check is the one that tests the substance of the claim. If the test already passes before the fix, it says nothing about the crash, no matter how convincing the fix is. A test name that doesn’t match any test gets a dedicated message, because that usually means a typo. Every failed check comes back to the model as an error explaining the problem, and the run continues.
There are limits to what this can catch. A test can fail for an unrelated reason, a fix can land in the wrong place, and a flaky test might get through by chance. The crash catalog’s grader narrows that gap with hidden tests the agent never sees.
submit_diagnosis before its answer is accepted.One run, end to end
go run ./ch07 replays a recorded run of anthropic/claude-haiku-5.5 on one catalog task (the example’s page).
The task has four crash reports: two are crashes already in the tracker, and two come from a bug located away from the line that crashed.
The agent got the difficult part right.
The crash is a nil pointer dereference inside api.owned, but the defect is in store.Get: for a deleted reminder it returns neither a reminder nor an error.
Guarding against nil in owned would have ended the panic while leaving every other caller of Get open to the same bug.
Because the answer was typed, its error was easy to see too.
The catalog’s grader checked it against the expected answer 16 ways, and 12 passed.
All four failures came from one mistake: the agent marked the two crashes already in the tracker as fixed when they should have been duplicates of the existing issues.
The system prompt gave no instruction for a crash that matches a filed issue, so the first revision of the prompt adds one.
In a prose answer the mistake would have been one clause in a paragraph; in a struct it shows up as failed checks.
The run used 17 turns and cost $0.034.
When to use which
Reach for it
- A final tool, when the agent already calls tools or has to run on many models. It works on any model that can call tools, and because the recorded run’s answer was typed, the catalog’s grader showed its one mistake as four failed checks out of 16.
- A constrained reply, for a single call with no tools. The companion code’s summary call sends a JSON Schema as
response_formatwithrequire_parametersset, so OpenRouter routes only to providers that apply it.
Leave it out
- Trusting the shape alone. A schema can’t tell a passing reproducer from a failing one;
submit_diagnosisruns the test on the original code and on the fix before it accepts the answer.
Whichever you choose, validate in your own code as well: decode strictly, enforce enumerations and required fields, and test every claim in the answer that a program is able to test.
Try it
From the code directory of a clone of the companion repository, with no key set:
$ go run ./ch07
This replays the run described above against a fresh copy of the remind service, which the command sets up itself; every tool really executes, including the reproducer check’s go test runs, and the grader’s checks print at the end.
The final tool and its checks are in ch07/triage/diagnosis.go.
type Diagnosis struct {
Fingerprint string `json:"fingerprint" desc:"the group's fingerprint, from crash_list"`
Reports []string `json:"reports" desc:"the IDs of every report in the group"`
Category string `json:"category" enum:"nil_value,out_of_range,concurrency,bad_input,other"`
RootCause Location `json:"root_cause" desc:"where the code is wrong, which may not be where it crashed"`
Evidence string `json:"evidence" desc:"why this is the cause: what you read and ran"`
Reproducer Location `json:"reproducer,omitzero" desc:"the test you wrote that fails before the fix; leave out for already_fixed and duplicate"`
Fix string `json:"fix,omitzero" desc:"what you changed, for status fixed"`
Status string `json:"status" enum:"fixed,already_fixed,duplicate,not_a_bug,needs_human"`
Issue int `json:"issue,omitzero" desc:"the issue you filed, for status fixed or needs_human"`
Duplicate int `json:"duplicate,omitzero" desc:"for status duplicate: the open issue it duplicates"`
}
A Diagnosis is the agent's answer for one crash group: which reports share a cause, where the code is wrong, the test that shows it, and what was done about it.
A Diagnosis is the agent's answer for one crash group: which reports share a cause, where the code is wrong, the test that shows it, and what was done about it. type Diagnosis struct { Fingerprint string `json:"fingerprint" desc:"the group's fingerprint, from crash_list"` Reports []string `json:"reports" desc:"the IDs of every report in the group"` Category string `json:"category" enum:"nil_value,out_of_range,concurrency,bad_input,other"` RootCause Location `json:"root_cause" desc:"where the code is wrong, which may not be where it crashed"` Evidence string `json:"evidence" desc:"why this is the cause: what you read and ran"` Reproducer Location `json:"reproducer,omitzero" desc:"the test you wrote that fails before the fix; leave out for already_fixed and duplicate"` Fix string `json:"fix,omitzero" desc:"what you changed, for status fixed"` Status string `json:"status" enum:"fixed,already_fixed,duplicate,not_a_bug,needs_human"` Issue int `json:"issue,omitzero" desc:"the issue you filed, for status fixed or needs_human"` Duplicate int `json:"duplicate,omitzero" desc:"for status duplicate: the open issue it duplicates"` }. In ch07/triage/diagnosis.go, line 25.
field Fingerprint string `json:"fingerprint" desc:"the group's fingerprint, from crash_list"`
field Fingerprint string `json:"fingerprint" desc:"the group's fingerprint, from crash_list"`. In ch07/triage/diagnosis.go, line 26.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
field Reports []string `json:"reports" desc:"the IDs of every report in the group"`
field Reports []string `json:"reports" desc:"the IDs of every report in the group"`. In ch07/triage/diagnosis.go, line 27.
field Category string `json:"category" enum:"nil_value,out_of_range,concurrency,bad_input,other"`
field Category string `json:"category" enum:"nil_value,out_of_range,concurrency,bad_input,other"`. In ch07/triage/diagnosis.go, line 28.
field RootCause Location `json:"root_cause" desc:"where the code is wrong, which may not be where it crashed"`
field RootCause Location `json:"root_cause" desc:"where the code is wrong, which may not be where it crashed"`. In ch07/triage/diagnosis.go, line 29.
type Location struct {
File string `json:"file" desc:"a file path, such as store/store.go"`
Function string `json:"function" desc:"a function or method, such as (*Store).Get or TestGetDeleted"`
}
A Location is a function in a file of remind's source.
A Location is a function in a file of remind's source. type Location struct { File string `json:"file" desc:"a file path, such as store/store.go"` Function string `json:"function" desc:"a function or method, such as (*Store).Get or TestGetDeleted"` }. In ch07/triage/diagnosis.go, line 39.
field Evidence string `json:"evidence" desc:"why this is the cause: what you read and ran"`
field Evidence string `json:"evidence" desc:"why this is the cause: what you read and ran"`. In ch07/triage/diagnosis.go, line 30.
field Reproducer Location `json:"reproducer,omitzero" desc:"the test you wrote that fails before the fix; leave out for already_fixed and duplicate"`
field Reproducer Location `json:"reproducer,omitzero" desc:"the test you wrote that fails before the fix; leave out for already_fixed and duplicate"`. In ch07/triage/diagnosis.go, line 31.
field Fix string `json:"fix,omitzero" desc:"what you changed, for status fixed"`
field Fix string `json:"fix,omitzero" desc:"what you changed, for status fixed"`. In ch07/triage/diagnosis.go, line 32.
field Status string `json:"status" enum:"fixed,already_fixed,duplicate,not_a_bug,needs_human"`
field Status string `json:"status" enum:"fixed,already_fixed,duplicate,not_a_bug,needs_human"`. In ch07/triage/diagnosis.go, line 33.
field Issue int `json:"issue,omitzero" desc:"the issue you filed, for status fixed or needs_human"`
field Issue int `json:"issue,omitzero" desc:"the issue you filed, for status fixed or needs_human"`. In ch07/triage/diagnosis.go, line 34.
type int int
int is a signed integer type that is at least 32 bits in size.
int is a signed integer type that is at least 32 bits in size. type int int. Documented at pkg.go.dev, builtin.int.
field Duplicate int `json:"duplicate,omitzero" desc:"for status duplicate: the open issue it duplicates"`
field Duplicate int `json:"duplicate,omitzero" desc:"for status duplicate: the open issue it duplicates"`. In ch07/triage/diagnosis.go, line 35.
field File string `json:"file" desc:"a file path, such as store/store.go"`
field File string `json:"file" desc:"a file path, such as store/store.go"`. In ch07/triage/diagnosis.go, line 40.
field Function string `json:"function" desc:"a function or method, such as (*Store).Get or TestGetDeleted"`
field Function string `json:"function" desc:"a function or method, such as (*Store).Get or TestGetDeleted"`. In ch07/triage/diagnosis.go, line 41.
func finished(byName map[string]Tool, calls []ToolCall,
answers []Message) (jsontext.Value, bool)
finished reports whether a reply held a successful call to the final tool, and returns its arguments, the run's answer.
finished reports whether a reply held a successful call to the final tool, and returns its arguments, the run's answer. func finished(byName map[string]Tool, calls []ToolCall, answers []Message) (jsontext.Value, bool). In ch07/agent/final.go, line 40.
var byName map[string]Tool
var byName map[string]Tool. In ch07/agent/final.go, line 40.
type Tool struct {
Def ToolDef
Run func(ctx context.Context, args jsontext.Value) (string, error)
// Safety flags (chapter 7). A tool with neither flag set may change
// something outside the run.
ReadOnly bool // it only looks things up
Idempotent bool // running it twice has the same effect as once
// Final marks the tool that ends the run: once a call to it
// ...
}
Tool is the harness's side of a tool: the definition the model sees, and the Go function that runs it.
Tool is the harness's side of a tool: the definition the model sees, and the Go function that runs it. type Tool struct { Def ToolDef Run func(ctx context.Context, args jsontext.Value) (string, error) // Safety flags (chapter 7). A tool with neither flag set may change // something outside the run. ReadOnly bool // it only looks things up Idempotent bool // running it twice has the same effect as once // Final marks the tool that ends the run: once a call to it // ... }. In ch07/agent/types.go, line 104.
type ToolCall struct {
ID string
Name string
Arguments jsontext.Value // JSON the model wrote; may be invalid
}
ToolCall is the model asking the harness to run a tool.
ToolCall is the model asking the harness to run a tool. type ToolCall struct { ID string Name string Arguments jsontext.Value // JSON the model wrote; may be invalid }. In ch07/agent/types.go, line 61.
type Message struct {
Role string // "system", "user", "assistant", or "tool"
Content string // empty when the message has tool calls
ToolCalls []ToolCall // set on assistant messages that call tools
ToolCallID string // on tool messages: the call this answers
IsError bool // set on tool messages that report a failure
// ReasoningDetails is a reasoning model's record of its thinking,
// sent back unchanged with the tool calls it led to (chapter 4).
ReasoningDetails jsontext.Value
}
Message is one entry in the conversation.
Message is one entry in the conversation. type Message struct { Role string // "system", "user", "assistant", or "tool" Content string // empty when the message has tool calls ToolCalls []ToolCall // set on assistant messages that call tools ToolCallID string // on tool messages: the call this answers IsError bool // set on tool messages that report a failure // ReasoningDetails is a reasoning model's record of its thinking, // sent back unchanged with the tool calls it led to (chapter 4). ReasoningDetails jsontext.Value }. In ch07/agent/types.go, line 33.
package jsontext ("encoding/json/jsontext")
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785.
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. package jsontext ("encoding/json/jsontext"). Documented at pkg.go.dev, encoding/json/jsontext.
type Value []byte
Value represents a single raw JSON value, which may be one of the following:
Value represents a single raw JSON value, which may be one of the following: type Value []byte. Documented at pkg.go.dev, encoding/json/jsontext.Value.
type bool bool
bool is the set of boolean values, true and false.
bool is the set of boolean values, true and false. type bool bool. Documented at pkg.go.dev, builtin.bool.
field Final bool
Final marks the tool that ends the run: once a call to it succeeds, its arguments become Result.Final (chapter 7).
Final marks the tool that ends the run: once a call to it succeeds, its arguments become Result.Final (chapter 7). field Final bool. In ch07/agent/types.go, line 115.
func len(v Type) int
The len built-in function returns the length of v, according to its type:
The len built-in function returns the length of v, according to its type: func len(v Type) int. Documented at pkg.go.dev, builtin.len.
field IsError bool
set on tool messages that report a failure
set on tool messages that report a failure field IsError bool. In ch07/agent/types.go, line 38.
field Arguments jsontext.Value
JSON the model wrote; may be invalid
JSON the model wrote; may be invalid field Arguments jsontext.Value. In ch07/agent/types.go, line 64.
const true = 0 == 0
Untyped bool.
Untyped bool. const true = 0 == 0. Documented at pkg.go.dev, builtin.true.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
const false = 0 != 0
Untyped bool.
Untyped bool. const false = 0 != 0. Documented at pkg.go.dev, builtin.false.

