跳转到内容

交接

交接使一个智能体可以将对话的一部分委托给另一个智能体。当不同智能体在特定领域各有所长时,这非常有用。例如在客服应用中,您可能有负责预订、退款或常见问题的智能体。

交接在 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 handoffs
const triageAgent = Agent.create({
name: 'Triage agent',
handoffs: [billingAgent, handoff(refundAgent)],
});

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.`,
});