LiveKit 语音智能体中的监督者模式

LiveKit 文档介绍监督者模式,由一个长期存活的 Agent 掌控整段会话,把收集信息、校验、取数等离散工作分派给专职 AgentTask,并整合其结果后继续对话。

LiveKit docs › 建置代理 › 逻辑与结构 › 模式 › 监事 --- # 主管模式 > 中央特工路线在控制会话的同时执行专家任务. ## 概览 监督模式保持单一 [代理服务器](https://docs.livekit.io/agents/logic/agents-handoffs.md) 长期控制某场会议,并将离散工作带给专家 [任务](https://docs.livekit.io/agents/logic/tasks.md)。主管决定每个任务何时运行,整合结果,继续对话。每个任务都是独立的,有自己的指令、工具和LLM环路。这使得主管能够协调一组有重点的子代理,而不是在一个快速中处理所有事务。 当一个代理人在授权收集结构化信息、运行核查步骤或检索外部数据等重点行动时,应该保持对齐状态时使用这个模式。 主管仍然是对话的切入点,而专家则处理狭窄的工作并返回结果。 ## 何时使用主管模式 主管模式是构建语音 AI 应用程序的几个选项之一。 选择最简单的符合您工作流程的构造 : - **单人代理 [工具](https://docs.livekit.io/agents/logic/tools.md)** 如果一套指令和工具足够的话,可以处理对话。 - **主管模式** 当一个代理人继续控制,同时将分散作业下放给重点突出的、可重复使用的任务时,这是适当的。 - **[副代表代表团](https://docs.livekit.io/agents/logic/patterns/subagent-delegation.md)** 当授权的工作是缓慢的推理而不应该拖住对话时,是合适的。由于主管模式,对话会等待打字结果。随着副代理授权,对话会继续下去,结果会稍后到达。 - **[代理交接](https://docs.livekit.io/agents/logic/agents-handoffs.md)** 当一个代理人的角色完成,另一个代理人应该用不同的指令或工具来接任时,是合适的. 原始代理人不参与后续步骤. - **[工作队](https://docs.livekit.io/agents/logic/tasks.md#taskgroup)** 适合有秩序的多步骤授权,用户可能需要重新审视早先的步骤。 这些模式并不是相互排斥的,而且经常在更复杂的语音AI应用中组合。 对话的不同阶段可能使用不同的模式。例如,一个接收代理可能利用主管模式来收集结构化信息,然后交给一个使用自己监督模式进行付款收集的计费代理。 关于代理模式的更广阔背景,请参见 LiveKit 的博客文章。 [主管模式](https://livekit.com/blog/supervisor-pattern-voice-agents),则 [ReAct图案](https://livekit.com/blog/react-pattern-voice-agents),则 [human-in-the-loop图案](https://livekit.com/blog/human-in-the-loop-voice-agents). ## 模式解剖学 模式有三部分: - **督导者.** 长寿 `Agent` 其指示界定了现有专家、何时援引每一专家以及如何解释其成果。 - **专家们** 一个或多个 `AgentTask` 实例,每个实例都有焦点指示、自己的工具和输入结果。见 [任务和工作组](https://docs.livekit.io/agents/logic/tasks.md) 用于完成全部任务 API 。 - **代表团露面了。** 启动专家的机制。 最常见的方法是主管身上的功能工具:工具机体即时化并等待任务,然后将结果返回到LLM。 或者,生命周期钩子(`on_enter` 或 时 间 `on_exit`)可以在决定点触发任务. 工具和任务是不同的构造。 一个工具是能够执行任何操作的常规代码: 调用 API , 写入数据库, 或启动任务。 一个任务是一个与它自己的 LLM 循环的子协议, 它反过来可以调用工具。 从工具开始任务是多个切入点之一 ; 见 。 [正在执行任务](https://docs.livekit.io/agents/logic/tasks.md#run-task) 对其他人和运行时间的限制。 ## 设计主管 模式的有效性取决于几个设计选择. ### 规模化任务 决定任务中属于什么,工具与主管本身: - **工具**:不需要LLM推理的单一定型操作,例如由ID获取记录,发送电子邮件,或进行计算. - **任务**: 重点突出的次对话,需要推理,并可能跨越多个转折,如收集结构化地址,处理同意流,或核实身份. - **主管**:对话框架和路由逻辑. 域特定推理不应该住在这里. 一个有用的准则是,如果模型需要询问澄清问题,则工作属于一项任务。如果它是带有参数的单个函数调用,则属于一个工具。 ### 撰写主管指令 主管的指令应该明确指定每个专家工具的名称,并描述何时使用这些工具。要具体一些,因为路由行为在很大程度上取决于这些描述。指令还应该界定如何解释每个结果。例如:“之后” `lookup_order` 返回时,摘要列出命令状态,并询问用户是否想要作出修改。” 主管设定对话的基调,专家任务定义他们自己的行为,而主管设定整体互动. ### 审定结果 将任务结果作为未信任的输入, 直至主管验证。 在继续对话前检查结果, 并定义错误或意外输出的恢复路径。 尽管任务结果已输入, 但仍需要验证其中的值 。 ## 示例:专家任务之间的路径 以下主管通过前往不同的专家任务处理两种客户请求. `LookupOrderTask` 收集命令编号并返回命令状态。 `UpdateAddressTask` 收集新的运算地址并返回确认。主管将每个任务显示一个函数工具;LLM根据用户的说法选择正确的工具。 **Python 键**: ```python from dataclasses import dataclass from livekit.agents import Agent, AgentTask, function_tool # Typed result returned when LookupOrderTask completes. @dataclass class OrderLookupResult: order_id: str status: str # Typed result returned when UpdateAddressTask completes. @dataclass class AddressUpdateResult: address: str # The generic parameter ties this task to the type it returns. class LookupOrderTask(AgentTask[OrderLookupResult]): def __init__(self, chat_ctx=None) -> None: super().__init__( instructions=( "Ask the customer for their order number. " "If they don't have one, ask them to check their email." ), chat_ctx=chat_ctx, ) async def on_enter(self) -> None: await self.session.generate_reply( instructions="Ask for the order number." ) # Task-internal tool. The task's LLM calls this when the user # provides an order number. Calling self.complete(...) ends the # task and returns the typed result to the supervisor. @function_tool() async def order_number_collected(self, order_id: str) -> None: """Call when the customer has provided their order number.""" # In a real system, look up the order in your database here. self.complete(OrderLookupResult(order_id=order_id, status="shipped")) class UpdateAddressTask(AgentTask[AddressUpdateResult]): def __init__(self, chat_ctx=None) -> None: super().__init__( instructions=( "Collect the customer's new shipping address: street, city, " "state, and zip code. Read it back to confirm before completing." ), chat_ctx=chat_ctx, ) async def on_enter(self) -> None: await self.session.generate_reply( instructions="Ask for the new shipping address." ) @function_tool() async def address_confirmed(self, address: str) -> None: """Call once the customer has confirmed their new address.""" self.complete(AddressUpdateResult(address=address)) class CustomerServiceAgent(Agent): def __init__(self) -> None: super().__init__( instructions=( "You are a customer service representative. Greet the caller " "and ask how you can help. Route their request:\n" "- For questions about order status, call lookup_order.\n" "- For shipping address changes, call update_address.\n" "After a tool returns, summarize the outcome and ask whether " "the caller needs anything else." ), ) # Routing tool called by the supervisor's LLM to delegate to # the specialist task. The tool body instantiates and awaits the task, # then returns its result string back to the LLM, which uses it to # continue the conversation. @function_tool() async def lookup_order(self) -> str: """Use when the customer wants to check the status of an order.""" result = await LookupOrderTask( chat_ctx=self.chat_ctx.copy(exclude_instructions=True), ) return f"Order {result.order_id} is {result.status}." @function_tool() async def update_address(self) -> str: """Use when the customer wants to change their shipping address.""" result = await UpdateAddressTask( chat_ctx=self.chat_ctx.copy(exclude_instructions=True), ) return f"Updated shipping address to: {result.address}." ``` --- **节点.js**: ```tsx import { llm, voice } from '@livekit/agents'; import { z } from 'zod'; // Typed result returned when LookupOrderTask completes. interface OrderLookupResult { orderId: string; status: string; } // Typed result returned when UpdateAddressTask completes. interface AddressUpdateResult { address: string; } // The generic parameter ties this task to the type it returns. function createLookupOrderTask(chatCtx?: llm.ChatContext) { const task = voice.AgentTask.create<OrderLookupResult>({ instructions: "Ask the customer for their order number. If they don't have one, " + 'ask them to check their email.', chatCtx, tools: [ // Task-internal tool. The task's LLM calls this when the user // provides an order number. Calling task.complete(...) ends the // task and returns the typed result to the supervisor. llm.tool({ name: 'orderNumberCollected', description: 'Call when the customer has provided their order number.', parameters: z.object({ orderId: z.string().describe('The order number'), }), execute: async ({ orderId }) => { task.complete({ orderId, status: 'shipped' }); }, }), ], onEnter(ctx) { ctx.session.generateReply({ instructions: 'Ask for the order number.', }); }, }); return task; } function createUpdateAddressTask(chatCtx?: llm.ChatContext) { const task = voice.AgentTask.create<AddressUpdateResult>({ instructions: "Collect the customer's new shipping address: street, city, state, " + 'and zip code. Read it back to confirm before completing.', chatCtx, tools: [ llm.tool({ name: 'addressConfirmed', description: 'Call once the customer has confirmed their new address.', parameters: z.object({ address: z.string().describe('The full shipping address'), }), execute: async ({ address }) => { task.complete({ address }); }, }), ], onEnter(ctx) { ctx.session.generateReply({ instructions: 'Ask for the new shipping address.', }); }, }); return task; } const customerServiceAgent = voice.Agent.create({ instructions: 'You are a customer service representative. Greet the caller and ' + 'ask how you can help. Route their request:\n' + '- For questions about order status, call lookupOrder.\n' + '- For shipping address changes, call updateAddress.\n' + 'After a tool returns, summarize the outcome and ask whether the ' + 'caller needs anything else.', tools: [ // Routing tool called by the supervisor's LLM to delegate to // the specialist task. The tool body instantiates and awaits the task, // then returns its result string back to the LLM, which uses it to // continue the conversation. llm.tool({ name: 'lookupOrder', description: 'Use when the customer wants to check the status of an order.', execute: async (_, { ctx }) => { const result = await createLookupOrderTask( ctx.session.currentAgent.chatCtx.copy({ excludeInstructions: true }), ).run(); return `Order ${result.orderId} is ${result.status}.`; }, }), llm.tool({ name: 'updateAddress', description: 'Use when the customer wants to change their shipping address.', execute: async (_, { ctx }) => { const result = await createUpdateAddressTask( ctx.session.currentAgent.chatCtx.copy({ excludeInstructions: true }), ).run(); return `Updated shipping address to: ${result.address}.`; }, }), ], }); ``` 主管的指令指定每个专家的名字,并描述何时引用; LLM 使用这些描述来路由收到的请求。 每个任务在调用其工具时开始, 接管会话直至调用 `complete(...)`,然后将输入的结果返回给主管进行其余的谈话。 传上司的 [聊天上下文](https://docs.livekit.io/agents/logic/chat-context.md) 进入一个任务,使专家看到 之前,看 [将对话历史传递给任务](https://docs.livekit.io/agents/logic/tasks.md#passing-context). ## 最佳做法 - **保持专家任务的重点.** 每个任务一个目标, 并有明确的打字结果。 分割任务, 任务范围会扩大 。 - **在主管指示中准确描述路线。** 该模型依赖于工具描述和指令来正确路由. 模糊导致路由错误. - **在继续之前验证任务结果。** 输入的结果仍然需要值级验证(例如空的或畸形的字段). - **只在有需要时才能传递对话语境 。** 如果一项任务不需要历史,省略它会提高性能并减少噪音. See. [将对话历史传递给任务](https://docs.livekit.io/agents/logic/tasks.md#passing-context). - **独立测试主管和每项任务。** 每个任务都是自成一体的单位,有打字合同,所以您可以自己验证它们。要测试主管整体,用有代表性的用户输入来驱动它,并断言它会向正确的任务或工具行进,并处理结果。见 。 [单位测试](https://docs.livekit.io/testing/unit-tests.md). - **通过模拟验证组装的流量.** 在确认各项工作后,请使用 [代理模拟](https://docs.livekit.io/testing/simulations.md) 以验证 end-to-end 对话。 ## 追加资源 下列资源就本指南所讨论的专题提供了更多信息。 - **[工作流量](https://docs.livekit.io/agents/logic/workflows.md)**: 模拟多步语音 AI 应用 具有代理,交接,和任务. - **[任务组( T)](https://docs.livekit.io/agents/logic/tasks.md)**: 定义返回输入结果的短寿命工作单位。 - **[代理和交割](https://docs.livekit.io/agents/logic/agents-handoffs.md)**:在具有不同指令或工具的代理之间转移长寿命控制. - **[工具定义和使用](https://docs.livekit.io/agents/logic/tools.md)**: 为外部行动或引发授权界定可采用模式的职能。 - **[测试和评价](https://docs.livekit.io/testing.md)**: 独立测试主管和每项任务. --- 此文件在2026 - 12-01T09: 38:26.330Z. 本文件的最新版本见: [https://docs.livekit.io/agents/logic/patterns/supervisor.md](https://docs.livekit.io/agents/logic/patterns/supervisor.md). 要探索所有 LiveKit 文档,请参见 [页:1](https://docs.livekit.io/llms.txt).

查看原始来源