Handoffs(任务交接)
Handoffs 允许一个 agent 将任务委托给另一个 agent。这在不同 agent 专注于不同领域的场景中特别有用。比如,一个客服应用可能有多个 agent,分别专门处理订单状态查询、退款请求、常见问题等不同任务。
在 LLM 中,Handoffs 被表示为工具。所以如果要交接给一个名为 Refund Agent 的 agent,对应的工具名称就会是 transfer_to_refund_agent。
创建 handoff
所有 agent 都有一个 handoffs 参数,它可以直接接收一个 Agent 对象,或者一个用于自定义 Handoff 的 Handoff 对象。
你可以使用 Agents SDK 提供的 handoff() 函数来创建 handoff。这个函数允许你指定要交接给哪个 agent,以及可选的覆盖设置和输入过滤器。
基本用法
下面是创建简单 handoff 的方法:
from agents import Agent, handoff
billing_agent = Agent(name="Billing agent")
refund_agent = Agent(name="Refund agent")
# (1)!
triage_agent = Agent(name="Triage agent", handoffs=[billing_agent, handoff(refund_agent)])
- 你可以直接使用 agent(如
billing_agent),或者使用handoff()函数。
通过 handoff() 函数自定义 handoffs
handoff() 函数让你可以自定义各种设置:
agent:这是将要接手任务的 agent。tool_name_override:默认情况下,会使用Handoff.default_tool_name()函数,生成形如transfer_to_<agent_name>的名称。你可以覆盖这个默认值。tool_description_override:覆盖来自Handoff.default_tool_description()的默认工具描述。on_handoff:当 handoff 被调用时执行的回调函数。这对于在知道 handoff 被调用时立即启动数据获取等操作很有用。这个函数接收 agent 上下文,也可以选择接收 LLM 生成的输入。输入数据由input_type参数控制。input_type:handoff 预期的输入类型(可选)。input_filter:这让你可以过滤下一个 agent 接收到的输入。详见下文。
from agents import Agent, handoff, RunContextWrapper
def on_handoff(ctx: RunContextWrapper[None]):
print("Handoff 被调用了")
agent = Agent(name="My agent")
handoff_obj = handoff(
agent=agent,
on_handoff=on_handoff,
tool_name_override="custom_handoff_tool",
tool_description_override="自定义描述",
)
Handoff 输入
在某些情况下,你希望 LLM 在调用 handoff 时提供一些数据。例如,假设有一个交接到"升级处理 agent"的情况。你可能想要提供一个原因,以便记录日志。
from pydantic import BaseModel
from agents import Agent, handoff, RunContextWrapper
class EscalationData(BaseModel):
reason: str
async def on_handoff(ctx: RunContextWrapper[None], input_data: EscalationData):
print(f"升级处理 agent 被调用,原因是:{input_data.reason}")
agent = Agent(name="Escalation agent")
handoff_obj = handoff(
agent=agent,
on_handoff=on_handoff,
input_type=EscalationData,
)
输入过滤器
当 handoff 发生时,新的 agent 会接管对话,并能看到之前的整个对话历史。如果你想改变这一点,可以设置一个 input_filter。输入过滤器是一个函数,它通过 HandoffInputData 接收现有输入,并必须返回一个新的 HandoffInputData。
有一些常见模式(例如从历史记录中删除所有工具调用)已经在 agents.extensions.handoff_filters 中为你实现了。
from agents import Agent, handoff
from agents.extensions import handoff_filters
agent = Agent(name="FAQ agent")
handoff_obj = handoff(
agent=agent,
input_filter=handoff_filters.remove_all_tools, # (1)!
)
- 这将在调用
FAQ agent时自动从历史记录中删除所有工具。
推荐的提示语
为了确保 LLM 正确理解 handoffs,我们建议在你的 agent 中包含有关 handoffs 的信息。我们在 agents.extensions.handoff_prompt.RECOMMENDED_PROMPT_PREFIX 中提供了一个建议的前缀,或者你可以调用 agents.extensions.handoff_prompt.prompt_with_handoff_instructions 来自动将推荐的数据添加到你的提示中。