相比直接使用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())
谢谢大家