运行智能体
你可以通过 Runner 类来运行智能体。你有 3 种选择:
Runner.run():异步运行并返回RunResult。Runner.run_sync():同步方法,底层只是运行.run()。Runner.run_streamed():异步运行并返回RunResultStreaming。它以流式模式调用 LLM,并在接收到事件时将这些事件流式传输给你。
from agents import Agent, Runner
async def main():
agent = Agent(name="Assistant", instructions="You are a helpful assistant")
result = await Runner.run(agent, "Write a haiku about recursion in programming.")
print(result.final_output)
# Code within the code,
# Functions calling themselves,
# Infinite loop's dance
更多信息请参阅结果指南。
智能体循环
当你在 Runner 中使用 run 方法时,需要传入一个起始智能体和输入。输入可以是字符串(会被视为一条用户消息),也可以是输入项列表(即 OpenAI Responses API 中的 items)。
Runner 随后会运行一个循环:
- 我们使用当前输入为当前智能体调用 LLM。
- LLM 生成其输出。
- 如果 LLM 返回
final_output,循环结束并返回结果。 - 如果 LLM 进行了 handoff,我们会更新当前智能体和输入,并重新运行循环。
- 如果 LLM 产生了工具调用,我们会运行这些工具调用,追加结果,然后重新运行循环。
- 如果 LLM 返回
- 如果超过传入的
max_turns,我们会抛出MaxTurnsExceeded异常。
Note
判断 LLM 输出是否被视为“最终输出”的规则是:它生成了所需类型的文本输出,并且没有任何工具调用。
流式传输
流式传输允许你在 LLM 运行时额外接收流式事件。流结束后,RunResultStreaming 将包含本次运行的完整信息,包括产生的所有新输出。你可以调用 .stream_events() 来获取流式事件。更多信息请参阅流式传输指南。
运行配置
run_config 参数允许你为智能体运行配置一些全局设置:
model:允许设置全局要使用的 LLM 模型,不受每个 Agent 的model影响。model_provider:用于查找模型名称的模型提供方,默认为 OpenAI。model_settings:覆盖智能体级别的设置。例如,你可以设置全局的temperature或top_p。input_guardrails、output_guardrails:要在所有运行中包含的一组输入或输出安全防护措施。handoff_input_filter:用于所有 handoffs 的全局输入过滤器(如果 handoff 本身尚未设置)。输入过滤器允许你编辑发送给新智能体的输入。更多详情请参阅Handoff.input_filter文档。nest_handoff_history:可选开启的 beta 功能,会在调用下一个智能体之前,将先前的对话记录折叠为一条 assistant 消息。在我们稳定嵌套任务转移期间,此功能默认关闭;设置为True以启用,或保持False以透传原始对话记录。当你未传入RunConfig时,所有Runner方法都会自动创建一个RunConfig,因此 quickstarts 和示例保持默认关闭;任何显式的Handoff.input_filter回调仍会覆盖它。单个 handoff 可以通过Handoff.nest_handoff_history覆盖此设置。handoff_history_mapper:可选的可调用对象。在你选择启用nest_handoff_history时,它会在每次收到归一化的对话记录(history + handoff items)时被调用。它必须返回要转发给下一个智能体的、完全一致的输入项列表,从而让你无需编写完整的 handoff 过滤器即可替换内置摘要。tracing_disabled:允许你为整个运行禁用追踪。tracing:传入TracingConfig以覆盖本次运行的导出器、进程或追踪元数据。trace_include_sensitive_data:配置追踪中是否包含潜在敏感数据,例如 LLM 与工具调用的输入/输出。workflow_name、trace_id、group_id:设置本次运行的追踪工作流名称、trace ID 和 trace group ID。我们建议至少设置workflow_name。group ID 是可选字段,可让你跨多次运行关联 traces。trace_metadata:要包含在所有 traces 上的元数据。session_input_callback:在使用 Sessions 时,自定义在每轮之前如何将新的用户输入与会话历史合并。call_model_input_filter:用于在模型调用前立即编辑已完全准备好的模型输入(instructions 和输入项)的钩子,例如用于裁剪历史或注入系统提示词。
嵌套任务转移(nested handoffs)以可选开启的 beta 形式提供。通过传入 RunConfig(nest_handoff_history=True) 来启用折叠对话记录的行为,或对特定 handoff 设置 handoff(..., nest_handoff_history=True) 以为该 handoff 启用。如果你更倾向于保留原始对话记录(默认行为),请不要设置该标志,或提供一个 handoff_input_filter(或 handoff_history_mapper)来按你的需求逐字转发对话。若要在不编写自定义 mapper 的情况下更改生成摘要中使用的包装文本,请调用 set_conversation_history_wrappers(并通过 reset_conversation_history_wrappers 恢复默认值)。
对话/聊天线程
调用任意 run 方法都可能导致一个或多个智能体运行(因此会有一次或多次 LLM 调用),但它表示聊天对话中的一次逻辑轮次。例如:
- 用户轮次:用户输入文本
- Runner 运行:第一个智能体调用 LLM、运行工具、handoff 到第二个智能体,第二个智能体运行更多工具,然后生成输出。
在智能体运行结束时,你可以选择向用户展示什么。例如,你可以向用户展示智能体生成的每一条新 item,或仅展示最终输出。无论哪种方式,用户随后可能会提出后续问题,此时你可以再次调用 run 方法。
手动对话管理
你可以使用 RunResultBase.to_input_list() 方法手动管理对话历史,以获取下一轮所需的输入:
async def main():
agent = Agent(name="Assistant", instructions="Reply very concisely.")
thread_id = "thread_123" # Example thread ID
with trace(workflow_name="Conversation", group_id=thread_id):
# First turn
result = await Runner.run(agent, "What city is the Golden Gate Bridge in?")
print(result.final_output)
# San Francisco
# Second turn
new_input = result.to_input_list() + [{"role": "user", "content": "What state is it in?"}]
result = await Runner.run(agent, new_input)
print(result.final_output)
# California
使用 Sessions 的自动对话管理
为了更简单,你可以使用 Sessions 自动处理对话历史,而无需手动调用 .to_input_list():
from agents import Agent, Runner, SQLiteSession
async def main():
agent = Agent(name="Assistant", instructions="Reply very concisely.")
# Create session instance
session = SQLiteSession("conversation_123")
thread_id = "thread_123" # Example thread ID
with trace(workflow_name="Conversation", group_id=thread_id):
# First turn
result = await Runner.run(agent, "What city is the Golden Gate Bridge in?", session=session)
print(result.final_output)
# San Francisco
# Second turn - agent automatically remembers previous context
result = await Runner.run(agent, "What state is it in?", session=session)
print(result.final_output)
# California
Sessions 会自动:
- 在每次运行前检索对话历史
- 在每次运行后存储新消息
- 为不同的 session ID 维护彼此独立的对话
更多详情请参阅 Sessions 文档。
服务端托管的对话
你也可以让 OpenAI conversation state 功能在服务端管理对话状态,而不是在本地使用 to_input_list() 或 Sessions 来处理。这样你无需手动重发所有历史消息,就能保留对话历史。更多详情请参阅 OpenAI Conversation state guide。
OpenAI 提供两种方式来跨轮次跟踪状态:
1. 使用 conversation_id
你先使用 OpenAI Conversations API 创建一个对话,然后在后续每次调用中复用它的 ID:
from agents import Agent, Runner
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main():
agent = Agent(name="Assistant", instructions="Reply very concisely.")
# Create a server-managed conversation
conversation = await client.conversations.create()
conv_id = conversation.id
while True:
user_input = input("You: ")
result = await Runner.run(agent, user_input, conversation_id=conv_id)
print(f"Assistant: {result.final_output}")
2. 使用 previous_response_id
另一种选择是响应串联(response chaining),其中每一轮都显式链接到上一轮的 response ID。
from agents import Agent, Runner
async def main():
agent = Agent(name="Assistant", instructions="Reply very concisely.")
previous_response_id = None
while True:
user_input = input("You: ")
# Setting auto_previous_response_id=True enables response chaining automatically
# for the first turn, even when there's no actual previous response ID yet.
result = await Runner.run(
agent,
user_input,
previous_response_id=previous_response_id,
auto_previous_response_id=True,
)
previous_response_id = result.last_response_id
print(f"Assistant: {result.final_output}")
Call model input filter
使用 call_model_input_filter 在模型调用前编辑模型输入。该钩子接收当前智能体、上下文,以及合并后的输入项(包含存在时的会话历史),并返回新的 ModelInputData。
from agents import Agent, Runner, RunConfig
from agents.run import CallModelData, ModelInputData
def drop_old_messages(data: CallModelData[None]) -> ModelInputData:
# Keep only the last 5 items and preserve existing instructions.
trimmed = data.model_data.input[-5:]
return ModelInputData(input=trimmed, instructions=data.model_data.instructions)
agent = Agent(name="Assistant", instructions="Answer concisely.")
result = Runner.run_sync(
agent,
"Explain quines",
run_config=RunConfig(call_model_input_filter=drop_old_messages),
)
你可以通过 run_config 为每次运行设置该钩子,或将其设为你的 Runner 的默认值,用于脱敏敏感数据、裁剪过长历史,或注入额外的系统指导。
长时间运行的智能体与 human-in-the-loop
Temporal
你可以使用 Agents SDK 的 Temporal 集成来运行持久的、长时间运行的工作流,包括 human-in-the-loop 任务。观看 Temporal 与 Agents SDK 协作完成长时间任务的演示,请参见此视频,并在此查看文档。
Restate
你可以使用 Agents SDK 的 Restate 集成来实现轻量级、持久的智能体,包括人工审批、handoffs 与会话管理。该集成需要 Restate 的单二进制运行时作为依赖,并支持将智能体作为进程/容器或无服务器函数运行。 更多详情请阅读概览或查看文档。
异常
SDK 会在某些情况下抛出异常。完整列表见 agents.exceptions。概览如下:
AgentsException:SDK 内部抛出的所有异常的基类。它作为通用类型,所有其他具体异常都从它派生。MaxTurnsExceeded:当智能体运行超过传入Runner.run、Runner.run_sync或Runner.run_streamed方法的max_turns限制时抛出。它表示智能体无法在指定的交互轮次数内完成任务。ModelBehaviorError:当底层模型(LLM)产生意外或无效输出时发生。可能包括:- JSON 格式错误:当模型为工具调用或其直接输出提供了格式错误的 JSON 结构,尤其是在定义了特定
output_type的情况下。 - 与工具相关的意外失败:当模型未按预期方式使用工具时
- JSON 格式错误:当模型为工具调用或其直接输出提供了格式错误的 JSON 结构,尤其是在定义了特定
UserError:当你(使用 SDK 编写代码的人)在使用 SDK 时发生错误而抛出。通常源于错误的代码实现、无效配置或对 SDK API 的误用。InputGuardrailTripwireTriggered、OutputGuardrailTripwireTriggered:当输入安全防护措施或输出安全防护措施的条件分别被满足时抛出。输入安全防护措施会在处理前检查传入消息,而输出安全防护措施会在交付前检查智能体的最终响应。