随着DeepSeek的全球爆火,AI训练和推理成本持续下降,预计今年将迎来AI应用的大爆发。就在前几天,OpenAI迅速发布了自己的Agent SDK,意在抢占生态先机。前两年,Agent开发框架的市场首选还是LangChain,但LangChain的缺点在于上手成本较高,其内部高度抽象的设计往往需要开发者深入理解原理才能灵活使用。而OpenAI的Agent SDK则主打轻量易用,其最小化的抽象设计让开发者无需面对陡峭的学习曲线即可上手。那么,Agent SDK到底如何?我们来一探究竟。
首先,我们来看一下OpenAI官方提供的架构图:
从架构图中可以看到,Agent SDK提供了一个轻量且强大的架构,核心围绕着几个关键概念:Agent(代理)、Tools(工具)、Agent Loop(代理循环)、Handoff(任务交接)、Guardrails(任务护栏)、Tracing(任务状态跟踪) 。接下来我们逐一解释这些概念。
Agent
,就是一个由开发者赋予特定角色的LLM实例,能够使用各种工具来执行任务。Agent负责接收用户请求,在必要时通过预定义的工具执行子任务,最后给出响应。工具可以是任何Python函数,只需在函数上添加@function_tool即可。Agent SDK可以自动生成并验证工具的输入输出。例如,网页搜索工具或数据库查询工具可以被定义为Python函数,并提供给Agent使用。
另一个核心概念是Agent Loop(代理循环)
,指的是代理自动执行任务的迭代过程。在这个过程中,Agent首先根据特定角色尝试回应用户请求,如果它缺少必要的信息或需要进行外部操作,它就会调用合适的工具来执行任务,并将结果反馈给Agent。这个循环会持续进行,直到模型发出“任务完成”(即响应已完成)的信号为止。这样的自动化循环使得开发者可以专注于设计工作流,复杂的迭代管理(例如每次调用正确的函数、将结果传递给LLM并进行必要的迭代等)则由Agent SDK自动处理。
Handoff(任务交接)
是多Agent开发中的一个重要概念。它允许一个Agent将子任务交给另一个Agent,或将一个Agent的输出作为另一个Agent的输入,这使得设计多Agent协作工作流变得更加简便。OpenAI特别强调,Agent SDK的设计就是为了支持多个Agent协同工作,适用于客户支持自动化、多步骤研究、内容生成、代码审查或销售流程等场景。在多Agent协作的工作流中,Guardrails(任务护栏)
非常重要,它通过预定义的规则来验证Agent的行为。例如,开发者可以设计规则来验证传递给Agent的参数是否符合特定格式,如果不符合规则,代理循环会立即终止。
在开发Agent应用时,开发者可以专注于业务工作流的设计,Agent SDK会负责大部分的底层调度工作——处理工具调用、将结果传递给LLM并执行循环。因此,工作流的可观测性非常重要,它能帮助开发者清晰了解哪里出了问题,如何优化工作流,这就是Tracing(任务状态跟踪)
的能力。OpenAI在官方工作台中提供了一个追踪面板,开发者可以在其中可视化所有代理的行为——例如代理何时调用工具、收到哪些输入、生成了哪些输出。
说了这么多,接下来我们通过使用Agent SDK 实现一个具体的AI应用来实际的感受一下。
这个Agent应用模拟了OpenAI的Deep Research能力,结合用户提供的主题进行全面搜索与研究,最终输出一份专业的研究报告。为了实现这一点,我们可以通过三个Agent协作来完成任务(当然,效果目前还能达不到Deep Research的水平):
- 分类代理(Triage Agent) :负责理解研究主题、创建研究计划并协调整个研究流程
- 研究代理(Research Agent) :负责在网络上进行搜索,收集相关信息
- 编辑代理(Editor Agent) :负责将收集到的信息整合成一份完整的研究报告
其中Research Agent 和Editor Agent 我们分别为其定义结构化的输出:
- ResearchPlan:包含研究主题、搜索查询和重点领域
- ResearchReport:包含报告标题、大纲、内容、来源和字数统计
接着为了支持这个过程,我们需要为ResearchPlan规划一个工具集:
- save_important_fact:一个自定义工具,用来保存研究过程中发现的重要事实
- WebSearchTool:用于在网络上进行信息搜索
整体的工作流如下:
- 用户输入研究主题
- 分类代理分析主题,创建包含搜索查询和重点领域的研究计划
- 研究代理根据计划进行网络搜索并保存重要事实
- 编辑代理将所有研究结果汇总,生成结构化的研究报告
- 最终,报告以Markdown格式呈现,包含标题、大纲、内容、来源和字数统计
规划好方案,代码实现就一气呵成 :
首先实现 ResearchPlan 和 ResearchReport 的结构定义:
class ResearchPlan(BaseModel):
topic: str
search\_queries: list[str]
focus\_areas: list[str]
class ResearchReport(BaseModel):
title: str
outline: list[str]
report: str
sources: list[str]
word\_count: int
接着定义需要使用的工具,其中st
指的是Streamlit,这是一个用于创建数据科学和机器学习Web应用的Python库,可以让我们快速创建交互式应用程序。另外,这里之所以只定义了save\_important\_fact
,没有定义WebSearchTool
,是因为WebSearchTool
是OpenAI内置的工具。
@function\_tool
def save\_important\_fact(fact: str, source: str = None) -> str:
"""Save an important fact discovered during research.
Args:
fact: The important fact to save
source: Optional source of the fact
Returns:
Confirmation message
"""
if"collected\_facts"notin st.session\_state:
st.session\_state.collected\_facts = []
st.session\_state.collected\_facts.append({
"fact": fact,
"source": source or"Not specified",
"timestamp": datetime.now().strftime("%H:%M:%S")
})
returnf"Fact saved: {fact}"
最后定义好三个Agent, 并开始执行:
research\_agent = Agent(
name="Research Agent",
instructions="You are a research assistant. Given a search term, you search the web for that term and"
"produce a concise summary of the results. The summary must 2-3 paragraphs and less than 300"
"words. Capture the main points. Write succintly, no need to have complete sentences or good"
"grammar. This will be consumed by someone synthesizing a report, so its vital you capture the"
"essence and ignore any fluff. Do not include any additional commentary other than the summary"
"itself.",
model="gpt-4o",
tools=[
WebSearchTool(),
save\_important\_fact
],
)
editor\_agent = Agent(
name="Editor Agent",
handoff\_description="A senior researcher who writes comprehensive research reports",
instructions="You are a senior researcher tasked with writing a cohesive report for a research query. "
"You will be provided with the original query, and some initial research done by a research "
"assistant.\n"
"You should first come up with an outline for the report that describes the structure and "
"flow of the report. Then, generate the report and return that as your final output.\n"
"The final output should be in markdown format, and it should be lengthy and detailed. Aim "
"for 5-10 pages of content, at least 1000 words.Please answer in chinese.",
model="gpt-4o",
output\_type=ResearchReport,
)
triage\_agent = Agent(
name="Triage Agent",
instructions="""You are the coordinator of this research operation. Your job is to:
1. Understand the user's research topic
2. Create a research plan with the following elements:
- topic: A clear statement of the research topic
- search\_queries: A list of 3-5 specific search queries that will help gather information
- focus\_areas: A list of 3-5 key aspects of the topic to investigate
3. Hand off to the Research Agent to collect information
4. After research is complete, hand off to the Editor Agent who will write a comprehensive report
Make sure to return your plan in the expected structured format with topic, search\_queries, and focus\_areas.
Please answer in chinese.
""",
handoffs=[
handoff(research\_agent),
handoff(editor\_agent)
],
model="gpt-4o",
output\_type=ResearchPlan,
)
triage\_result = await Runner.run(
triage\_agent,
f"Research this topic thoroughly: {topic}. This research will be used to create a comprehensive research report."
)
triage_result能自动根据输入的主题先调用research_agent搜索主题相关的信息,再调用editor_agent总结成报告。最后我们再使用指的是Streamlit做一个漂亮的web界面。效果如下(第一张是research\_agent的结果,第二张是editor\_agent的结果
):
可以看到,使用起来非常简单,这种开奖即用的设计理念与openAI的生态相集成,如果后续使用该工具包的开发者变多后,将为OpenAI形成较大的壁垒。这也意味着OpenAI接下来会抓紧增强Agent SDK的各项能力,争取让其成为开发者开发AI应用的首选。
看起来,OpenAI推出Agent SDK是其希望构建自己的AI生态壁垒的重要一步,它的优势非常吸引人:OpenAI承担了构建Agent的复杂部分,提供了一个轻量、易用的框架。可以直接访问OpenAI的顶级模型和工具,保证了高性能和强大能力。集成的追踪和护栏机制提升了可靠性和透明度,对于企业应用尤为重要。而且它还开源,更加提升了开发者的安全感。
当然,也有一些风险和需要注意的地方。过度依赖OpenAI的生态系统可能成为长期隐患——就像云服务提供商的锁定效应一样,限制了灵活性。虽然支持其他模型,但脱离OpenAI的生态系统,使用起来就没有那么简便。另外,由于刚推出,可能会有一些莫名其妙的bug,工具生态上也没有LangChain那么成熟。