LionAG2: Recursive Exploratory Research with AG2 beta — structured output with response_schema 2/10
Turn free-text model replies into validated Pydantic objects — and why that matters for multi-agent pipelines
LionAG2: Recursive Exploratory Research with AG2 beta — structured output with response_schema (2/10)
In this tutorial, we will take a look at how [ag2](https://docs.ag2.ai/latest/docs/beta/motivation/) handles structured output and how we can use that in our research pipeline.
Structured output is when an AI model produces output can be parsed and validated into a data object, enabling AI output to be manipulated programmatically. This forms the basis of the bulk of today’s workflow automation and processes, in fact, the tool use ability of language model also roots in structured output. Consider the exa research example from yesterday, how exactly did the tool got triggered?
We asked the model about something, with explicit mandate on exa tool usages, and the following things happened:
- the tool schema (what to put into the tool interface as parameter) gets injected into instruction sent to the model along side your user prompt
- the model creates structured output matching function signature of those tools
- the function gets matched to a real function object, and arguments get parsed, tools invoked, and results stored
- the framework sends a second API call, including the tool results, the model then returns a final outputs
Today we will extend that with one more step, we will ask the model to also produce a structured output in its final response, the point of which will be obvious in the next tutorial.
Setup
pip install 'ag2[openai, exa]'
Make sure you have openai and exa api key saved in your environment.
import os
from dotenv import load_dotenv
from IPython.display import Markdown, display
from pydantic import BaseModel, Field
from autogen.beta import Agent
from autogen.beta.config import OpenAIConfig
from autogen.beta.tools import ExaToolkit
load_dotenv()
config = OpenAIConfig(
model="gpt-5.4-mini",
api_key=os.getenv("OPENAI_API_KEY"),
base_url="https://api.openai.com/v1",
)
exa_tool = ExaToolkit(api_key=os.getenv("EXA_API_KEY"))
Structured Research Findings
- Define structures in pydantic models
class Citation(BaseModel):
title: str = Field(description="The cited work or source.")
relevance: str = Field(description="One sentence on why this source supports the finding.")
class Finding(BaseModel):
"""One self-contained research result."""
topic: str = Field(description="The specific aspect of the question this finding addresses.")
summary: str = Field(description="2-3 sentences capturing the core mechanism or claim.")
citations: list[Citation] = Field(description="Sources behind the summary; emit [] if none.")
novelty: float = Field(ge=0.0, le=1.0, description="0 = textbook, 1 = cutting edge.")
- Declare the agent with
[response_schema](https://docs.ag2.ai/latest/docs/beta/structured_output/)
theorist = Agent(
name="theorist",
prompt="You're a careful theoretical physicist. Be specific.",
config=config,
response_schema=Finding,
tools=[exa_tool]
)
- Run and collect the result
reply = await theorist.ask("Produce drill innovatively into high-Tc superconductivity as a structured finding.")
finding: Finding = await reply.content()
print(type(finding).__name__, "|", finding.topic, "| novelty=", finding.novelty)
Finding | High-Tc superconductivity: mechanism and current theoretical status | novelty= 1.0
Let’s read into what the model produced, since finding is now a pydantic model object, we can directly use its attributes likefinding.summary and others.
lines = [f"### {finding.topic} — novelty={finding.novelty:.2f}", "", finding.summary]
for c in finding.citations:
lines.append(f"- **{c.title}** — {c.relevance}")
display(Markdown("\n".join(lines)))
### High-Tc superconductivity: mechanism and current theoretical status — novelty=1.00
The central theoretical issue in high-Tc superconductivity, especially in cuprates, is still the lack of a universally accepted microscopic mechanism that explains both pairing and the material-dependent Tc trends. Recent work increasingly supports strong-coupling, magnetically driven physics: short-range spin fluctuations, superexchange, and possibly resonant/Feshbach-like interactions between doped carriers and nearby bound states are prominent candidates, while phonons appear insufficient as a sole pairing glue in cuprates. At the same time, ab initio many-body approaches are beginning to reproduce empirically important trends such as pressure and layer dependence, suggesting that predictive, material-specific modeling is becoming feasible even if the full pairing mechanism remains unsettled.
- **High-temperature superconductivity | Nature Reviews Physics (2021)** — Summarizes the field’s open problem: no established microscopic theory and multiple competing ideas about unconventional pairing in high-Tc materials.
- **Ab initio quantum many-body description of superconducting trends in the cuprates (2025)** — Shows that first-principles many-body calculations can reproduce pressure and layer trends and points to superexchange and covalency as useful descriptors.
- **Feshbach hypothesis of high-Tc superconductivity in cuprates (2025)** — Proposes a strong-coupling resonance mechanism tied to doped Mott insulators and spin-polaron physics, illustrating one innovative route beyond conventional glue pictures.
- **Charge Correlations in Cuprate Superconductors (2024)** — Documents the ubiquity of charge-density-wave correlations and their competition/intertwining with superconductivity, a key part of the modern cuprate phase diagram.
Notes
In this set up, we are asking the model to produce the citation, which is typically not the most desirable practice, as we know models can output whatever they wish without regard of reality or what is actually in their context. For example, how do you know that the model actually used certain info from the cited sources, if so, where? How do you know that the model didn’t hallucinate the citation all together?
This is the reason why we like structured output, it enables these kinds of questions to be answered programmatically, instead of dumping everything to another model and ask,
hey dude, is this free of hallucination and all citations real?
In next tutorial, we will explore how to make use of the structured output from one agent run, and then see how to wire multiple runs together.
메타데이터
- post_id
- 83a6f83c47bd
- slug
- lionag2-recursive-exploratory-research-with-ag2-beta-structured-output-with-response-schema-2-10-83a6f83c47bd
- url
- https://medium.com/@haiyangli_38602/lionag2-recursive-exploratory-research-with-ag2-beta-structured-output-with-response-schema-2-10-83a6f83c47bd
- canonical_url
- https://medium.com/@haiyangli_38602/lionag2-recursive-exploratory-research-with-ag2-beta-structured-output-with-response-schema-2-10-83a6f83c47bd
- author_url
- https://medium.com/@haiyangli_38602
- status
- ok
- fetched_at
- 2026-06-09 15:37:30