examples/functionality/structured_output/README.md
This example showcases structured output generation using AgentScope with Pydantic models. It demonstrates how to constrain AI model outputs to follow specific data structures and formats, ensuring consistent and parseable responses.
TableModel: Structured person information
name: Person's name (string)age: Person's age (integer,0-120)intro: One-sentence introduction (string)honors: List of honors/achievements (array of strings)ChoiceModel: Constrained choice selection
choice: Must be one of "apple", "banana", or "orange"export DASHSCOPE_API_KEY="your_dashscope_api_key_here"
python main.py
Structured Output 1:
{
"name": "Albert Einstein",
"age": 76,
"intro": 1,
"honors": [
"Nobel Prize in Physics (1921)",
"Copley Medal (1925)"
]
}
Structured Output 2:
{
"choice": "apple"
}
💡Note: The specific content will vary with each run since the agent generates different responses, but the JSON structure will always conform to the predefined Pydantic models (
TableModelandChoiceModel).
Create your own structured output models for specific use cases, for example:
from typing import Optional
from pydantic import BaseModel, Field, EmailStr
class BusinessModel(BaseModel):
"""Business information extraction model."""
company_name: str = Field(description="Name of the company")
industry: str = Field(description="Industry sector")
founded_year: int = Field(description="Year founded", ge=1800, le=2024)
headquarters: str = Field(description="Location of headquarters")
employee_count: Optional[int] = Field(description="Number of employees", ge=1)
email: Optional[EmailStr] = Field(description="Contact email address")
website: Optional[str] = Field(description="Company website URL")
# Usage
query = Msg("user", "Tell me about Tesla Inc.", "user")
res = await agent(query, structured_model=BusinessModel)