openai agent实践
rag系列文章目录
文章目录
- rag系列文章目录
- 前言
- 一、openai agent简介
- 二、openai agent实践
- 总结
前言
2025开年以来,随着deepseek的爆火,大模型以及应用正在快速的迭代。随着一款大模型agent,即manus,横空出世,openai也紧接着发布了openai agent,下面主要简要介绍下这个agent。
一、openai agent简介
OpenAI Agent SDK 是一个由 OpenAI 发布的框架,旨在帮助开发者构建多代理 AI 应用。它提供代理(Agents)、交接(Handoffs)和防护栏(Guardrails)等基本组件,支持创建复杂的多代理工作流,如客户支持系统或任务路由系统。它轻量级,易于学习,适合快速原型开发和生产环境。
与其他 AI 代理框架(如 LangChain 和 LlamaIndex)相比,OpenAI Agent SDK 有以下不同:
• 多代理协作:特别强调代理之间的交接,适合需要分工的场景,如 triage 代理路由任务。LangChain 和 LlamaIndex 更注重单个代理的功能扩展。
• 简单性:提供少量抽象,学习曲线低,相比 LangChain 的丰富功能更易上手。
• 内置追踪:自带追踪功能,方便调试,LangChain 和 LlamaIndex 可能需额外配置。
二、openai agent实践
1.工具调用
Agent基本的功能就是工具调用,以下是openai agent的工具调用,和langchain的工具调用有类似之处。
import agents
from agents import Agent, Runner, function_tool, handoff, OpenAIChatCompletionsModel
@function_tool
def web_search(query: str) -> str:
"""Simulate a web search for the given query."""
# In a real application, this would call a web search API
with agents.custom_span("WebSearch"): # Add a custom span for tracing this action
return f"Web search results for '{query}': [Sample result 1, Sample result 2]"
@function_tool
def get_weather(city: str) -> str:
"""Fetch the weather for a given city."""
# Placeholder for a real API call
print("---------------------------")
return f"The weather in {city} is sunny."
2.大模型
大模型是agent的大脑,这里定义大模型的client,在创建agent时可以引用这个client。
from openai import AsyncOpenAI
openai_client = AsyncOpenAI(
api_key="sk-S",
base_url="https://ss/v1"
)
3.构建agent
这里构建了一个天气agent,负责处理天气相关的工作。
weather_agent = Agent(
name="Weather Assistant",
instructions="Help users with weather queries.",
model=OpenAIChatCompletionsModel(
openai_client=openai_client,
model="gpt-4o-2024-05-13"
), tools=[get_weather]
)
4.handoff
openai agent的一大亮点就是多个agent之间的交接,如下所示,有一个专门负责处理天气问题的agent,主agent需要做天气相关的工作时,可以把它交接给天气agent处理,这个agent进行tool调用查询天气情况。
# Create the main support agent with tools and handoff
main_agent = Agent(
name="SupportAssistant",
instructions=(
"You are a customer support assistant. Answer user queries and use the web search tool "
"when needed. For get weather , hand off to Weather Assistant."
),
tools=[web_search], # Equip the agent with the web search tool
handoffs=[handoff(weather_agent)], # Configure handoff to the specialized agent
model=OpenAIChatCompletionsModel(
openai_client=openai_client,
model="gpt-4o-2024-05-13"
)
)
5.agent执行
以下是agent开始启动执行的代码,agent的整个执行过程,可以开启日志,详细观察里面的调用过程。
# Enable verbose logging to see detailed output in the console
agents.enable_verbose_stdout_logging()
if __name__ == '__main__':
# Run the agent synchronously with a sample input and handle exceptions
try:
with agents.trace("CustomerSupportQuery"): # Start a trace to monitor the entire operation
result = Runner.run_sync(main_agent, "What's the weather in Paris?")
print("Final Output:", result.final_output) # Print the agent's response
except agents.InputGuardrailTripwireTriggered as e:
print("Input was rejected by guardrail:", e)
except agents.OutputGuardrailTripwireTriggered as e:
print("Output was rejected by guardrail:", e)
except agents.MaxTurnsExceeded:
print("Agent exceeded maximum turns.")
except agents.ModelBehaviorError as e:
print("Model produced an invalid response:", e)
except agents.AgentsException as e:
print("An error occurred:", e)
总结
OpenAI Agent是一个轻量级框架,适合构建多代理 AI 应用,强调简单性和协作,没有langchain复杂。虽然很多功能还不是特别成熟完善,但是它在快速发展,相信更多的人后面会使用它。