ag2-structured-output
Skill12 starsChanged 9 days agoApache-2.0View on GitHub
Get a typed Python value back from an AG2 `Agent` instead of free text. Pass `response_schema=` (a Pydantic model, dataclass, primitive, union, `ResponseSchema`, or `@response_schema` validator) and read the parsed result via `await reply.content()`. Use when the user wants validated structured output, classification, extraction, or scoring. Covers `ResponseSchema`, `@response_schema`, `PromptedSchema` (for providers without native structured output), `Annotated[str, Field(...)]` constraints, per-turn override, validation retries (`content(retries=)`), and primitive embedding. Works with `OpenAIResponsesConfig`, `AnthropicConfig`, `GeminiConfig` etc.; decision-only providers (`OpenAIDecisionsConfig`, `TypeSafeConfig`) treat the schema as the question. For basic agent setup see `ag2-quickstart`, for tools `ag2-add-custom-tool`.
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- ag2ai/build-with-ag2edited, first seen Oct 9, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- ag2ai/build-with-ag2★ 25288% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository27 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- ag2-a2aSkill
- ag2-acpSkill
- ag2-add-custom-toolSkill
- ag2-ag-uiSkill
- ag2-eval-comparisonSkill
- ag2-evaluationSkill
- ag2-hitlSkill
- ag2-knowledge-and-memorySkill
- ag2-liveSkill
- ag2-mcpSkill
- ag2-middlewareSkill
- ag2-multimodal-inputSkill
- ag2-network-discussionSkill
- ag2-network-governanceSkill
- ag2-network-quickstartSkill
- ag2-network-tools-and-viewsSkill
- ag2-network-workflowSkill
- ag2-observers-and-alertsSkill
- ag2-overviewSkill
- ag2-quickstartSkill
- ag2-shell-toolSkill
- ag2-subagent-delegationSkill
- ag2-telemetrySkill
- ag2-testingSkill
- ag2-use-builtin-toolsSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 147
When validation fails, automatically re-ask the model:
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Structured output
When to use
- The user wants a Pydantic model, dataclass, dict, primitive, or union back — not a string.
- They're doing classification, extraction, scoring, normalisation, or anything where downstream code parses the reply.
- They want automatic retry on validation failure.
60-second recipe
from pydantic import BaseModel, Field
from typing import Annotated
from ag2 import Agent
from ag2.config import OpenAIResponsesConfig
class TicketTriage(BaseModel):
category: Annotated[str, Field(description="e.g. billing, bug, account_access")]
urgency: Annotated[str, Field(description="low, medium, or high")]
summary_one_line: Annotated[str, Field(description="Max 120 characters", max_length=120)]
agent = Agent(
"triage",
prompt="You triage support messages. Be conservative with urgency.",
config=OpenAIResponsesConfig(model="gpt-4.1-mini"),
response_schema=TicketTriage,
)
reply = await agent.ask("I was charged twice and can't export reports. Quarter close blocked.")
triage = await reply.content() # → typed TicketTriage
print(triage.category, triage.urgency)reply.body is still the raw model text; await reply.content() runs validation and returns the parsed value. If validation fails, content() raises (e.g. pydantic.ValidationError).
Schema types you can pass
| Type | What you get |
Primitive (int, float, bool) | Bare value, framework wraps in {"data": ...} for the API |
Annotated[str, Field(max_length=...)] | Constrained string (a bare str means plain text, no validation) |
dataclass | Instance of the dataclass |
Pydantic BaseModel | Instance of the model |
Union (int | str, (int, str)) | One of the alternatives |
dict[K, V], TypedDict | Validated dict |
ResponseSchema(...) | Same as above, with explicit name / description for the provider |
@response_schema callable | Custom validation/parsing logic |
PromptedSchema(inner) | Schema injected into the system prompt for providers without native structured output |
ResponseSchema — name your payload
Helps the provider treat the structured output as a named contract:
from ag2 import Agent, ResponseSchema
schema = ResponseSchema(int | str, name="ByteWidth", description="Number of bits in one byte.")
agent = Agent("assistant", config=config, response_schema=schema)@response_schema — custom validation
For clamping, regex cleanup, decoding wrapped JSON, or combining fields:
from ag2 import Agent, response_schema
@response_schema
def parse_rating(content: str) -> int:
"""Parse a rating and clamp to 1–5."""
return max(1, min(5, int(content)))
agent = Agent("assistant", config=config, response_schema=parse_rating)Multi-parameter form synthesises a JSON object schema from the parameter names:
from typing import Annotated
from pydantic import Field
from ag2 import response_schema
@response_schema
def extract_listing(
title: Annotated[str, Field(description="Product name")],
price_usd: Annotated[float, Field(description="Price in USD", ge=0)],
in_stock: Annotated[bool, Field(description="True if it ships now")],
) -> dict:
return {"title": title, "price_usd": price_usd, "in_stock": in_stock}The function also participates in dependency injection — Context, Variable, Inject, Depends work the same way as in tools (and don't appear in the JSON schema).
A single content: str parameter means no JSON schema is sent — you get the raw model text (it may arrive wrapped in a markdown json code fence). Async validators are supported:
import json, re
@response_schema
async def parse_json(content: str) -> dict:
text = re.sub(r"^`{3}(?:json)?\s*|\s*`{3}$", "", content.strip()) # drop a markdown fence
return json.loads(text)PromptedSchema — for providers without native structured output
Injects the JSON schema into the system prompt instead of using response_format:
from ag2 import Agent, PromptedSchema
agent = Agent("assistant", config=config, response_schema=PromptedSchema(int))Wraps any inner schema (type, ResponseSchema, @response_schema callable). The validation logic stays the same; only the wire format changes. It does not strip markdown fences — some models (e.g. Claude Haiku) wrap the JSON in a markdown code fence and fail validation, so prefer native structured output where the provider has it (OpenAI, Anthropic, Gemini all do).
Custom prompt template:
PromptedSchema(int, prompt_template="Reply with JSON matching this schema:\n{schema}")Per-turn override
agent = Agent("assistant", config=config)
turn = await agent.ask("How many seconds in a minute?", response_schema=int)
print(await turn.content()) # 60
turn2 = await turn.ask("Say hello.") # back to default (no schema)Pass response_schema=None to drop a schema set on the agent for one call.
Retries
When validation fails, automatically re-ask the model:
result = await reply.content(retries=3) # initial + up to 3 re-asks
result = await reply.content(retries=math.inf) # interactive only — could loop foreverThe validation error is sent back to the model as a follow-up so it can correct itself.
Primitive embedding (embed)
Bare primitives (int, float, bool, list[T], primitive unions) get wrapped in {"data": ...} by default — most structured-output APIs handle objects more reliably than bare values. content() transparently unwraps. Opt out:
ResponseSchema(int, name="RawInt", embed=False) # model must produce a bare 42
@response_schema(embed=False)
def parse_rating(value: int) -> int: ...OpenAI's native structured output only accepts object schemas, so embed=False on a primitive returns HTTP 400 there — keep the default, or combine with PromptedSchema.
Decision models
With OpenAIDecisionsConfig / TypeSafeConfig the schema (bool, an Enum, an IntEnum rubric) is the question; the model returns probabilities instead of text. See website/docs/user-guide/decision_models.mdx.
Going deeper
- Working starter:
assets/recipe_builder.py(mirrorscode_examples/02) — Pydantic model +@tool+response_schema=. - Full reference:
website/docs/user-guide/structured_output.mdx— covers every schema type, multi-param@response_schema,Fieldconstraints,PromptedSchema, retries, embedding semantics.
Common pitfalls
- Reading
reply.bodywhen you wanted typed output —reply.bodyis the raw text.await reply.content()does the parsing. - Forgetting
awaitoncontent()— it's async; you'll get a coroutine, not the value. - No
descriptionin the Pydantic field — the LLM may guess what to put in each field. Add aField(description=...)for every non-obvious key. - Numeric bounds on Anthropic —
Field(ge=..., le=...)onint/floatbecomesminimum/maximum, which Anthropic's native schema rejects (HTTP 400). Clamp in a@response_schemabody instead. Stringmax_lengthis fine. - Provider doesn't support native structured output — wrap with
PromptedSchema(...)rather than fighting the API. retries=math.infin production — will loop forever on a model that can't comply. Use a finite count.- Per-turn override is single-turn — passing
response_schema=intto oneask()doesn't change the agent's default. The next turn returns to whatever was set on the constructor.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

