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 request carries no tools — none registered, or all disabled and filtered out by
required_capabilities— it additionally carriesresponse_format={"type": "json_schema", …, "strict": False}, letting a capable provider enforce the shape. When tools are on the request 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 as a synthetic user message (UserMessage.is_synthetic=True, with the schema re-attached) 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: a result is serialized to JSON (plain values, or objects exposing model_dump / to_json); anything else is recorded as a serialization error. Images reach the model only as attachments on a user message — via instruct(images=…), or the synthetic injection behind request_image / browser_screenshot. Validation applies to the agent's final answer only. |
| Failure | A malformed final answer is retried with the parse error fed back as a synthetic user message, which lands in the history. Compaction never treats a synthetic message as a real user turn. Give the loop a bigger budget or the prompt a sharper shape if the model keeps missing it. |