Structured Output
StructuredOutputHook parses an Agent's final text reply as JSON, validates it against a Pydantic model or a JSON schema, and returns the result as an Agent output. Downstream components get the parsed JSON value, such as a dict or a list, instead of a string, so you don't need a separate JSON parsing step after the Agent.
| Configured on | The Agent component, as a StructuredOutputHook registered under the on_exit hook point |
| Key classes | StructuredOutputHook |
| Import path | haystack.hooks.structured_output |
| API reference | Hooks |
| GitHub link | https://github.com/deepset-ai/haystack/blob/main/haystack/hooks/structured_output/ |
| Package name | haystack-ai |
Overview
Structured output is one use of the Agent's general hooks mechanism. Registered under on_exit, StructuredOutputHook runs when the Agent is about to stop:
- If the Agent stopped with a text reply (
exit_reasonis"text"), the hook parses the reply as JSON and validates it against the schema. A markdown code fence around the whole reply, such as```json, is removed first. On success, it stores the result in the configuredStatekey. With a Pydantic model, the stored value is its JSON-compatible model dump. - If the reply isn't valid JSON or doesn't match the schema and retries are left, the hook adds a user message describing the error and keeps the Agent running, so the model can correct its reply.
max_retriessets how many retries are allowed and defaults to 2. Retries count toward the Agent'smax_agent_steps. - If no retries are left, or the Agent stopped on another exit condition (for example, a reply cut off by the model's output token limit), the hook stores
Noneand logs a warning.
The hook works with any chat generator. When your chat generator supports native structured output, such as text_format on OpenAIResponsesChatGenerator, pass the same schema there too. The model is then constrained to produce valid JSON, and the hook turns it into an Agent output. Native structured output still lets the Agent call tools before it answers.
Usage
Basic setup
The key the hook writes to must be declared in the Agent's state_schema, otherwise the hook raises a ValueError when the Agent runs. Declaring it also makes it an Agent output you can read from the result or connect to another component in a pipeline. The hook writes to structured_output by default:
from pydantic import BaseModel
from haystack.components.agents import Agent
from haystack.components.generators.chat import OpenAIResponsesChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.hooks.structured_output import StructuredOutputHook
class CityInfo(BaseModel):
city: str
country: str
agent = Agent(
chat_generator=OpenAIResponsesChatGenerator(
model="gpt-5.4-nano", generation_kwargs={"text_format": CityInfo}
),
state_schema={"structured_output": {"type": dict}},
hooks={"on_exit": [StructuredOutputHook(schema=CityInfo)]},
)
result = agent.run(
messages=[ChatMessage.from_user("Which city is the Eiffel Tower in?")]
)
print(result["structured_output"])
# >> {'city': 'Paris', 'country': 'France'}
To rebuild the Pydantic model from the output, use CityInfo.model_validate(result["structured_output"]).
Using a JSON schema
Pass a JSON schema dict instead of a Pydantic model, and use state_key to store the result under a different key:
city_schema = {
"type": "object",
"properties": {"city": {"type": "string"}, "country": {"type": "string"}},
"required": ["city", "country"],
}
agent = Agent(
chat_generator=OpenAIResponsesChatGenerator(model="gpt-5.4-nano"),
system_prompt="Answer only with a JSON object with the keys `city` and `country`.",
state_schema={"city_info": {"type": dict}},
hooks={
"on_exit": [StructuredOutputHook(schema=city_schema, state_key="city_info")]
},
)
Without native structured output, the system prompt asks the model for JSON, and retries cover the replies that don't match.
Things to keep in mind
- The result replaces the previous value. The hook ignores the state key's handler, so a
listkey holds exactly the validated result, orNone, rather than appending to the existing value. - Register the hook last. If you use other
on_exithooks, listStructuredOutputHooklast so it parses the final reply after the other hooks have made their changes. If one of those hooks keeps the Agent running by settingcontinue_run,StructuredOutputHookskips parsing and parses the reply at the next exit instead. - The output can be missing.
on_exithooks don't run when the Agent stops becausemax_agent_stepsis reached or a hook setsstop_run. If the hook never ran during the run, thestructured_outputkey is missing from the result, so read it withresult.get("structured_output"). - Retries are counted per turn. The hook tags its correction messages and counts the ones added since the last user message. Correction messages from earlier turns of a conversation don't count. System reminders added by other hooks, such as
StepBudgetReminderHook, don't start a new turn. If a compaction hook removes correction messages from the conversation, the count starts over. - Cut-off replies aren't retried. When the model hits its output token limit, the Agent stops with
exit_reasonset to"length", and the hook storesNonewithout retrying. Raise the token limit in the chat generator instead. - Serialization. When you serialize an Agent with this hook, a Pydantic model is stored by its import path. Its module must be on the deserialization allowlist (
HAYSTACK_DESERIALIZATION_ALLOWLIST) to load it again.