Skip to main content
Version: 3.5

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 onThe Agent component, as a StructuredOutputHook registered under the on_exit hook point
Key classesStructuredOutputHook
Import pathhaystack.hooks.structured_output
API referenceHooks
GitHub linkhttps://github.com/deepset-ai/haystack/blob/main/haystack/hooks/structured_output/
Package namehaystack-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_reason is "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 configured State key. 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_retries sets how many retries are allowed and defaults to 2. Retries count toward the Agent's max_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 None and 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:

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

python
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 list key holds exactly the validated result, or None, rather than appending to the existing value.
  • Register the hook last. If you use other on_exit hooks, list StructuredOutputHook last so it parses the final reply after the other hooks have made their changes. If one of those hooks keeps the Agent running by setting continue_run, StructuredOutputHook skips parsing and parses the reply at the next exit instead.
  • The output can be missing. on_exit hooks don't run when the Agent stops because max_agent_steps is reached or a hook sets stop_run. If the hook never ran during the run, the structured_output key is missing from the result, so read it with result.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_reason set to "length", and the hook stores None without 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.