交接
交接允许一个智能体将对话的一部分委派给另一个智能体。当不同智能体擅长特定领域时,这很有用。例如,在客服应用中,您可能有处理预订、退款或常见问题的智能体。
交接会以工具的形式呈现给 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 { Agent, handoff, RunContext } from '@openai/agents';
function onHandoff(ctx: RunContext) { console.log('Handoff called');}
const agent = new Agent({ name: 'My agent' });
const handoffObj = handoff(agent, { onHandoff, 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,});
当您的提示词提及交接时,LLMs 的响应更可靠。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.`,});