[OpenAI-Agent-SDK]格式化定义工具输出与agent输出

    相比直接使用LLM,使用prompt调优来规范LLM的格式化输出,这一步在OpenAI-agent-sdk中内部已经处理好了,用户直接通过定义tool 的输出格式,以及agent的输出格式,这些格式可以是pydantic的BaseModel类。

    格式化输出是agent能够规范完成任务的基础。比如本例中,agent输出FinalResult类定义了question_is_weather_related字段,也就是如果天气助手收到与天气无关的问题,其返回这个字段为False,那么我们在编排多个agent时,可以利用这个字段的信息优化multi-agent的编排流程。

比如,下面例子中,

工具输出定义:
class Weather(BaseModel):
    city: str
    temperature_range: str
    conditions: str
    

agent输出格式定义:

class FinalResult(BaseModel):
    answer: str
    temperatures: float
    question_is_weather_related: bool

import asyncio

from pydantic import BaseModel

from agents import Agent, Runner, function_tool



class Weather(BaseModel):
    city: str
    temperature_range: str
    conditions: str
    

class FinalResult(BaseModel):
    answer: str
    temperatures: float
    question_is_weather_related: bool


@function_tool
def get_weather(city: str) -> Weather:
    print("[debug] get_weather called")
    return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind.")


agent = Agent(
    name="weather助手",
    model = 'gpt-4o-mini',
    instructions="You are a helpful agent.",
    output_type=FinalResult,
    tools=[get_weather])


async def main():
    result = await Runner.run(agent, input="What's the weather in Tokyo?")
    print(result.final_output)
    print(type(result.final_output))
    
    result = await Runner.run(agent, input="非常简洁地介绍一下秦始皇")
    print(result.final_output)
    print(type(result.final_output))  # 返回的 final_output 的type is FinalResult 
    # The weather in Tokyo is sunny.


if __name__ == "__main__":
    asyncio.run(main())

谢谢大家

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chenxin0215

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值