English
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
- 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.
- 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 whenresponse_formatis set. - The final text is repaired, then validated —
json_repairfirst (models wrap JSON in prose or leave trailing commas), thenModel.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 againstmax_iterations). Only once the retries are spent does the run end as anErr, 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
| Aspect | Behaviour |
|---|---|
| Return type | execute(schema=M) → Result[M, ErrorInfo]; the overloads make the payload type M (or str without a schema) at lint time. |
| History | The 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 results | Unchanged: tools may return any JSON-serializable value, images included. Validation applies to the agent's final answer only. |
| Failure | A 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. |