在AgentScope中实现结构化输出
概述
在AgentScope框架中,结构化输出功能允许开发者定义明确的输出模式,确保AI模型的响应符合预期的格式和约束。本教程将介绍如何使用AgentScope的structured_model
参数来实现结构化输出。
结构化输出的优势
- 数据一致性:确保模型输出始终符合预定义的结构
- 类型安全:使用Pydantic模型进行数据验证
- 自动修正:当模型输出不符合规范时,系统会自动尝试修正
- 简化处理:直接获得结构化数据,无需手动解析文本
实现步骤
1. 定义Pydantic模型
首先,需要定义描述期望输出结构的Pydantic模型:
from pydantic import BaseModel, Field
from typing import Literalclass TableModel(BaseModel):"""人员信息表模型"""name: str = Field(description="人员姓名")age: int = Field(description="人员年龄", ge=0, le=120)intro: str = Field(description="人员简介")honors: list[str] = Field(description="获得的荣誉列表")class ChoiceModel(BaseModel):"""选择模型"""choice: Literal["apple", "banana", "orange"] = Field(description="选择的水果,请从apple、banana或orange中选择一个")
2. 配置Agent并使用结构化输出
创建Agent时,通过在调用时传递structured_model
参数来启用结构化输出:
# 创建Agent
agent = ReActAgent(name="Friday",sys_prompt="You are a helpful assistant named Friday.",model=DashScopeChatModel(api_key=os.environ.get("DASHSCOPE_API_KEY"),model_name="qwen-plus",stream=True,),formatter=DashScopeChatFormatter(),toolkit=toolkit,memory=InMemoryMemory(),
)
实际运行示例
query_msg_1 = Msg("user","Please introduce Einstein","user",)res = await agent(query_msg_1, structured_model=TableModel)print("Structured Output 1:\n""```\n"f"{json.dumps(res.metadata, indent=4)}\n""```",)query_msg_2 = Msg("user","Choose one of your favorite fruit","user",)res = await agent(query_msg_2, structured_model=ChoiceModel)print("Structured Output 2:\n""```\n"f"{json.dumps(res.metadata, indent=4)}\n""```",)
运行结果
(agentscope) PS D:\agent-llm\agentscope\mytest> uv run .\structout.pyFriday: Albert Einstein, a renowned physicist who developed the theory of relativity, lived to be 144 years old. He was awarded prestigious honors such as the Nobel Prize in Physics and the Copley Medal.system: {"type": "tool_result","id": "call_323f5479d5984d8189e1c0","name": "generate_response","output": [{"type": "text","text": "Arguments Validation Error: 1 validation error for TableModel\nage\n Input should be less than or equal to 120 [type=less_than_equal, input_value=144, input_type=int]\n For further information visit https://errors.pydantic.dev/2.11/v/less_than_equal"}]}Friday: Albert Einstein, a renowned physicist who developed the theory of relativity, lived to be 76 years old. He was awarded prestigious honors such as the Nobel Prize in Physics and the Copley Medal.Structured Output 1:```{"name": "Albert Einstein","age": 76,"intro": "Einstein was a renowned physicist who developed the theory of relativity.","honors": ["Nobel Prize in Physics","Copley Medal"]}```Friday: My favorite fruit is banana because it is delicious and nutritious.Structured Output 2:```{"choice": "banana"}```
关键特性
- 自动验证与修正:如示例中年龄超出范围时的自动修正
- 类型约束:支持各种Pydantic字段类型和约束条件
- 枚举限制:使用Literal类型限制可选值
- 错误处理:提供清晰的错误信息指导修正
总结
AgentScope的结构化输出功能通过Pydantic模型提供了强大的输出约束和验证机制。开发者可以:
- 定义精确的输出结构
- 设置数据类型和取值范围约束
- 确保模型输出符合业务逻辑要求
- 减少后处理代码的复杂性
这一功能特别适用于需要标准化API输出、数据处理管道或确保数据一致性的应用场景。
通过结合AgentScope的ReActAgent和结构化输出,开发者可以构建更加可靠和可控的AI应用系统。