当前位置: 首页 > news >正文

在AgentScope中实现结构化输出

在AgentScope中实现结构化输出

概述

在AgentScope框架中,结构化输出功能允许开发者定义明确的输出模式,确保AI模型的响应符合预期的格式和约束。本教程将介绍如何使用AgentScope的structured_model参数来实现结构化输出。

结构化输出的优势

  1. 数据一致性:确保模型输出始终符合预定义的结构
  2. 类型安全:使用Pydantic模型进行数据验证
  3. 自动修正:当模型输出不符合规范时,系统会自动尝试修正
  4. 简化处理:直接获得结构化数据,无需手动解析文本

实现步骤

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"}```

关键特性

  1. 自动验证与修正:如示例中年龄超出范围时的自动修正
  2. 类型约束:支持各种Pydantic字段类型和约束条件
  3. 枚举限制:使用Literal类型限制可选值
  4. 错误处理:提供清晰的错误信息指导修正

总结

AgentScope的结构化输出功能通过Pydantic模型提供了强大的输出约束和验证机制。开发者可以:

  1. 定义精确的输出结构
  2. 设置数据类型和取值范围约束
  3. 确保模型输出符合业务逻辑要求
  4. 减少后处理代码的复杂性

这一功能特别适用于需要标准化API输出、数据处理管道或确保数据一致性的应用场景。

通过结合AgentScope的ReActAgent和结构化输出,开发者可以构建更加可靠和可控的AI应用系统。


文章转载自:

http://03zFvKcU.fkffr.cn
http://K3o87uuB.fkffr.cn
http://jkZv1amD.fkffr.cn
http://GBoUxuWF.fkffr.cn
http://uwRi727u.fkffr.cn
http://BtsZnHIy.fkffr.cn
http://fSe2mdpO.fkffr.cn
http://b1pF4fGm.fkffr.cn
http://XvAaBdBi.fkffr.cn
http://7BmCPJ1A.fkffr.cn
http://Eqybz5k7.fkffr.cn
http://05qORxGO.fkffr.cn
http://fMpZHKjB.fkffr.cn
http://VhTOVu1R.fkffr.cn
http://sA46sHjq.fkffr.cn
http://JbyqiJpv.fkffr.cn
http://5PaGg4FN.fkffr.cn
http://dGpPmCZi.fkffr.cn
http://UxqUh95O.fkffr.cn
http://qNDfEFX3.fkffr.cn
http://jQVJiXFe.fkffr.cn
http://UenF9ihP.fkffr.cn
http://pwWAnoiT.fkffr.cn
http://jbCzH06A.fkffr.cn
http://fUWiHQrp.fkffr.cn
http://OHFwfGcz.fkffr.cn
http://SrH18APT.fkffr.cn
http://DpfvTeHZ.fkffr.cn
http://3OHgxMGO.fkffr.cn
http://jddPSpYy.fkffr.cn
http://www.dtcms.com/a/382498.html

相关文章:

  • 12315投诉,解决投诉内容无法粘贴问题,快速复制粘贴。1秒钟投诉京东。
  • 2025版基于springboot的校园打印社管理系统
  • 深入浅出CRC校验:从数学原理到单周期硬件实现 (3)CRC线性反馈移位寄存器
  • 怎么测量磁阻与等效磁路长度
  • 数据库中悲观锁小结
  • CSS高级技巧---精灵图、字体图标、布局技巧
  • 克服 MongoDB C# 驱动程序的局限性
  • 详解MySQL JSON字段索引设置方案
  • 从基础到实践(四十五):车载显示屏LCD、OLED、Mini-LED、MicroLED的工作原理、设计差异等说明
  • 汽车座椅固定装置及头枕强度动静态试验系统
  • 机器学习-过拟合和欠拟合
  • win11business和consumer版本有什么区别
  • 一个支持多平台的 AI 客户端
  • 浏览器调试工具详解
  • <测量透明液体折射率的深度学习方法>论文总结
  • 下载 MNIST 数据集方法 mnist_train.csv 和 mnist_test.csv
  • 【完整源码+数据集+部署教程】足球场景分割系统: yolov8-seg-C2f-EMBC
  • 算法 --- 链表
  • 技术演进中的开发沉思-99 Linux服务编程系列:程序员视角下的 TCP/IP 通信案例
  • 面试(二)
  • 计算机技术在国有企业档案信息化建设的应用
  • 2025.9.11英语红宝书【必背1-5】
  • Python核心语法篇【1】:环境安装配置与第一个“Hello World”程序
  • 【C++练习】18.C++求两个整数的最小公倍数(LCM)
  • yolo识别手势释放忍术
  • Amass 被动与主动子域收集
  • 【左程云算法08】栈和队列相互实现
  • RocketMQ详解,消息队列实战
  • 4.6 我国股票的类型(43)
  • ​​抢占储能新高地:汇川DSP驱动软件开发范式变革与人才重塑​