WithStructuredOutput to instruct the agent to respond with valid JSON matching a declared schema. The agent validates every final response and returns ErrInvalidOutput if the content is not conformant.
Quick start
How it works
- A system prompt hint is automatically appended asking the LLM to respond with valid JSON matching the schema.
- After each final response (stop reason
end_turn/stop), the content is validated:- Is it valid JSON?
- Does its top-level type match the schema’s
"type"field (if declared)?
- If validation fails,
RunandRunWithUsagereturn an error wrappingchainforge.ErrInvalidOutput.
Validation scope
The built-in validator checks:| Check | Description |
|---|---|
| Valid JSON | The response can be parsed as JSON. |
| Top-level type | If schema declares "type": "object", the response must be a JSON object ({...}). Same for array, string, number, boolean, null. |
github.com/santhosh-tekuri/jsonschema/v5 on the returned string.
Combining with tools
WithStructuredOutput only validates the final text response. Tool call results are not validated. This means multi-step agentic loops work normally; the schema check runs only when the LLM produces a terminal response.