在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應用系統。