交接
交接让一个智能体将对话的一部分委托给另一个智能体。这在不同智能体专攻不同领域时很有用。比如在客服应用中,你可能有处理预订、退款或常见问题的智能体。
在 LLM 看来,交接被表示为工具。如果你将对话交接给名为 Refund Agent 的智能体,则工具名会是 transfer_to_refund_agent。
每个智能体都接受一个 handoffs 选项。它可以包含其他 Agent 实例,或由 handoff() 帮助函数返回的 Handoff 对象。
import { Agent, handoff } from '@openai/agents';
const billingAgent = new Agent({ name: 'Billing agent' });const refundAgent = new Agent({ name: 'Refund agent' });
// Use Agent.create method to ensure the finalOutput type considers handoffsconst triageAgent = Agent.create({ name: 'Triage agent', handoffs: [billingAgent, handoff(refundAgent)],});通过 handoff() 自定义交接
Section titled “通过 handoff() 自定义交接”handoff() 函数允许你微调生成的工具。
agent– 要交接到的智能体。toolNameOverride– 覆盖默认的transfer_to_<agent_name>工具名。toolDescriptionOverride– 覆盖默认工具描述。onHandoff– 发生交接时的回调。接收一个RunContext和可选的已解析输入。inputType– 交接所期望的输入模式。inputFilter– 过滤传递给下一个智能体的历史记录。
import { z } from 'zod';import { Agent, handoff, RunContext } from '@openai/agents';
const FooSchema = z.object({ foo: z.string() });
function onHandoff(ctx: RunContext, input?: { foo: string }) { console.log('Handoff called with:', input?.foo);}
const agent = new Agent({ name: 'My agent' });
const handoffObj = handoff(agent, { onHandoff, inputType: FooSchema, toolNameOverride: 'custom_handoff_tool', toolDescriptionOverride: 'Custom description',});有时你希望 LLM 在调用交接时提供数据。定义一个输入模式并在 handoff() 中使用它。
import { z } from 'zod';import { Agent, handoff, RunContext } from '@openai/agents';
const EscalationData = z.object({ reason: z.string() });type EscalationData = z.infer<typeof EscalationData>;
async function onHandoff( ctx: RunContext<EscalationData>, input: EscalationData | undefined,) { console.log(`Escalation agent called with reason: ${input?.reason}`);}
const agent = new Agent<EscalationData>({ name: 'Escalation agent' });
const handoffObj = handoff(agent, { onHandoff, inputType: EscalationData,});默认情况下,交接会接收整个对话历史。要修改传递给下一个智能体的内容,请提供一个 inputFilter。
常用的辅助函数位于 @openai/agents-core/extensions。
import { Agent, handoff } from '@openai/agents';import { removeAllTools } from '@openai/agents-core/extensions';
const agent = new Agent({ name: 'FAQ agent' });
const handoffObj = handoff(agent, { inputFilter: removeAllTools,});当提示词提到交接时,LLM 的响应更可靠。SDK 通过 RECOMMENDED_PROMPT_PREFIX 提供一个推荐前缀。
import { Agent } from '@openai/agents';import { RECOMMENDED_PROMPT_PREFIX } from '@openai/agents-core/extensions';
const billingAgent = new Agent({ name: 'Billing agent', instructions: `${RECOMMENDED_PROMPT_PREFIX}Fill in the rest of your prompt here.`,});