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 is retried: the parse error is fed back to the model as an extra user message and the loop continues, up to twice (MAX_RESOLVE_RETRIES, counted against max_iterations). Only once the retries are spent does the run end as an Err, which the entrypoint reports once — the loop itself stays quiet.

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 retried with the parse error fed back to the model, and the corrective message lands in the history. Give the loop a bigger budget or the prompt a sharper shape if the model keeps missing it.

Xun 1.4.2dev (unreleased; source 51d23f3, 2026-10-16) documentation, generated from the source tree.