Skip to content

Structured Output ​

Pass a pydantic model to execute() and the answer comes back validated and typed:

python
from pydantic import BaseModel
from xun import Agent

class Story(BaseModel):
    title: str
    content: str

story = (
    Agent()
    .initialize()
    .instruct("Write a short story within 100 words.")
    .execute(schema=Story)          # Result[Story, ErrorInfo]
    .unwrap()
)
print(story.title)

How it is enforced ​

  1. The schema is attached to the last user message and rendered into the prompt, so the model is told the exact JSON shape it must produce as its final answer. Tool calls stay unrestricted — the constraint applies only to the terminating message.
  2. When the agent has no tools at all, the request additionally carries response_format={"type": "json_schema", …, "strict": False}, letting a capable provider enforce the shape. With tools registered this is deliberately skipped: several providers answer with JSON instead of calling a tool when response_format is set.
  3. The final text is repaired, then validated — json_repair first (models wrap JSON in prose or leave trailing commas), then Model.model_validate. Anything that still fails surfaces as an Err result plus an ErrorEvent.

Because the schema rides on a user message, there must be one: call instruct() before execute(schema=…); otherwise the run ends as an Err result.

Semantics ​

AspectBehaviour
Return typeexecute(schema=M) → Result[M, ErrorInfo]; the overloads make the payload type M (or str without a schema) at lint time.
HistoryThe schema is stored on that user message, so its prompt text stays in the history; what stops is the validation, which applies only to the run that asked for it.
Tool resultsUnchanged: tools may return any JSON-serializable value, images included. Validation applies to the agent's final answer only.
FailureA malformed final answer is an Err, not a retry loop — raise the iteration budget, re-instruct, or fix the prompt.

Xun 1.4.1 (unreleased; package 1.4.0, source 9e8246e, 2026-10-14) documentation, generated from the source tree.