Skip to content

Structured outputs

Set output_schema on an agent to define a JSON contract. Where the model supports provider-enforced JSON, the provider enforces it. Otherwise abt asks for the schema as a tool call and retries once if the reply is prose. result.structured holds the parsed object.

output_schema:
  properties:
    event:
      type: string
      enum: [APPROVE, REQUEST_CHANGES, COMMENT]
      description: the type of the event
    body:
      type: string

All fields are required by default. Mark exceptions with optional:

output_schema:
  properties:
    summary:
      type: string
      description: the brief summary of the topic
    note:
      type: string
      description: some notes on the topic
  optional: [note]

Nested objects use the same schema shape — optional: applies to their fields independently:

output_schema:
  properties:
    meta:
      type: object
      properties:
        version:
          type: integer
        note:
          type: string
      optional: [note]

Supported field types: string, integer, number, boolean, array (with items), nested object, enum. Unknown types fall back to Any.

Pydantic contract (escape hatch)

Use when inline YAML can't express what you need:

  • Custom types — date, Decimal, UUID, EmailStr, any Python type
  • Cross-field validation — field A must be greater than field B
  • @field_validator / @model_validator — format checks, regex, business rules
# contracts/review.py
from datetime import date
from pydantic import BaseModel, model_validator
from typing import Literal

class DateRange(BaseModel):
    start: date
    end: date

    @model_validator(mode="after")
    def end_after_start(self) -> "DateRange":
        if self.end <= self.start:
            raise ValueError("end must be after start")
        return self
output_schema: review.DateRange

review.DateRange resolves to the class DateRange in contracts/review.py (under paths.contracts; no __init__.py needed). The class is imported when the agent runs, not at compile time: a wrong module or class name still passes abt compile and abt run --dry-run, then fails the real run with Class 'NoSuchModel' not found in …/contracts/review.py before any model call.

What happens when the model gets the shape wrong

Mis-packed args are repaired for free. Four cases, all corrected before validation: the whole payload nested under a parameters/arguments envelope; a list field handed a bare string (prose — "File a ticket" — or the list as JSON text — '["a", "b"]'); a field welded into a sibling by leaked tool-call framing; and framing left trailing a value with no sibling to recover ("…the table name.</summary></invoke>"). The content is there; only the container is wrong. Each repair logs at WARNING ([OUTPUT_SCHEMA_REPAIR] / [TOOL_CALL_ARTIFACT]).

A weld's close tag and open tag can each independently be the literal <parameter name="…"> form or a bare <field_name> form — "…</parameter><parameter name="confidence_score">0.15", "…</summary><action_items>[…]", and the two mixed combinations are all repaired the same way, since the model improvises framing rather than reproducing one fixed convention. A weld is only repaired when every tag name is a declared field of that schema, and it never overwrites a field the model filled properly — only one that is absent or empty. Framing in the middle of a value with no sibling to recover is left alone: an agent writing about tool-call syntax produces the same bytes, and rewriting its sentence is the worse failure.

A final reply in prose is retried once. With the default ToolStrategy (strict_tools: false) the schema is a tool call the model is asked to make. Some provider setups drop that force (Anthropic with extended thinking), and an agent with tools can then end its run in plain text, which would fail with Response is not valid JSON. abt adds one short message asking for the schema tool call and sends the model back for another turn. That turn is an ordinary model call: it counts against model_call_limit and token_budget, so a limit the prose turn already used up ends the run instead. If the retry is prose again, the run fails as before. It logs at WARNING ([STRUCTURED_OUTPUT_GUARD]). This also covers strict_tools: true on a model without native structured output, where LangChain falls back to the same tool call. On a model that has it (provider-enforced JSON) there is nothing to retry, so the guard is not attached and the agent's graph is unchanged. The extra graph step lowers the recursion_limit an agent with a tight model_call_limit.max_model_calls can run with, and abt reports that when the agent is built.

Models that reject a forced tool call. ToolStrategy asks for the schema tool call as a required one (tool_choice="any"). Claude Sonnet 5.5 and Opus 5.5 on Bedrock reject that outright, so on bedrock_converse abt asks any model whose ChatBedrockConverse.supports_tool_choice_values lacks any for auto instead, and logs that once when the model is built (INFO). The model may then end a turn in text, which the retry above covers, at the price of one extra model call. Measured on Sonnet 5.5 with a tool-using agent: the retry was needed on 4 of 4 runs, and on 0 of 5 once the prompt ended with "Give your final answer by calling the ContractName tool." Use the schema's class name; for an inline output_schema that is the agent name in PascalCase (ticket-triage is TicketTriage). Put that sentence in the prompt of tool-using agents on these models. Without tools, the same model called the schema tool directly.

A Bedrock model that langchain-aws does not know yet is treated as accepting no tool choice, so it runs without a forced call. If it does take one, say so in model_kwargs:

model_kwargs:
  supports_tool_choice_values: [auto, any, tool]

The anthropic and openai providers are not adjusted: they keep sending a required tool choice ({"type": "any"} and "required"), and Anthropic already drops it itself when extended thinking is on, which the retry above covers too.

A genuinely missing field always costs a retry. abt does not auto-fill it — defaulting summary="" turns a loud, recoverable error into a quiet wrong answer that still gets posted. The retry message names the missing fields, but it is still a full model call.

So every required field is a retry risk. Mark a field optional: when the model may genuinely have nothing to say there.

Notes

  • On validation failure: result.ok = False, downstream exposures are skipped.
  • result.structured is a plain dict — use it in exposure dispatchers or transformers.
  • strict_tools: true enables provider-native constrained decoding (see configuration).
  • See Tutorial 2: Content Review Workflow for a worked example.