按运行时条件选择代理的RoutedAgent路由机制
RoutedAgent通过显式路由函数在每次调用时从多个代理中选出一个执行,支持出错回退、规划模式切换和按输入复杂度自动分流,与固定编排的工作流代理和由LLM决定交接的委派方式不同。
## 代理商之间的路线[¶](<https://adk.dev/agents/routing/#route-between-agents>) 支持于 ADKTypeScript v1.0.0 实验 实验 代理路线是实验性的,将来释放时可能会有变化。 [反馈](<https://github.com/google/adk-js/issues/new?template=feature_request.md>)! 在为不同的任务构建代理时,可以定义一个路径函数,选择在运行时处理每个引用的哪个. `RoutedAgent` 提供此能力, 启用代理在错误、 A/ B 测试、 规划模式和自动路由的输入复杂度后折返。 如果选中代理在输出前失败, 路由函数会被再次调用错误上下文, 这样它就可以选择一个倒返 。 `RoutedAgent` 与 [工作流程代理商](<https://adk.dev/agents/workflow-agents/>) 喜欢 `SequentialAgent` 或 时 间 `ParallelAgent`,它以固定模式协调多个代理,并且来自 [LLM 驱动的代表团](<https://adk.dev/agents/custom-agents/#delegation>),其中LLM决定向哪个代理人移交。 `RoutedAgent`,您会写一个选择 **一个** 每个引用的代理。关于模型级路径,参见 [模式路线](<https://adk.dev/agents/models/routing/>). ## 路线如何运作[¶](<https://adk.dev/agents/routing/#how-routing-works>) 两者 `RoutedAgent` 财务报告和财务报告 [`RoutedLlm`](<https://adk.dev/agents/models/routing/>) 由处理选择和故障的共享路由工具提供动力。 路由器函数接收可用代理和当前上下文的映射,并返回代理运行的密钥。它可以是同步的,也可以是同步的: TypeScript ``` type AgentRouter = ( agents: Readonly<Record<string, BaseAgent>>, context: InvocationContext, errorContext?: { failedKeys: ReadonlySet<string>; lastError: unknown }, ) => Promise<string | undefined> | string | undefined; ``` **密码 `agents` 参数** 接受一个或一个 `Record<string, BaseAgent>` 带有明确的密钥,或一系列代理。如果提供了数组,则每个代理的 `name` 属性被用作其密钥。 **失败行为 :** - 路由器首先使用无 `errorContext` 用于进行初始选择。 - 如果选中代理人丢出错误 **在产生任何事件之前**中,路由器再次被调用 `errorContext` 包含 `failedKeys` 财务报告和财务报告 `lastError`. - 如果选中代理人丢出错误 **产生事件后**,错误直接传播而无需重试,因为部分结果已经释放出来。 - 已经尝试的密钥无法重选。 如果路由器返回先前失败的密钥, 错误会传播 。 - 如果路由器返回 `undefined`,则路由停止,然后抛出最后一个错误。 ## 基本用途[¶](<https://adk.dev/agents/routing/#basic-usage>) 创建多个代理, 定义返回密钥的路由器函数, 并将其包裹在一个 `RoutedAgent`。以下实例中,两个代理商之间基于一个外部配置值的路径,在引用之间可以改变: TypeScript ``` import { LlmAgent, RoutedAgent, InMemoryRunner } from '@google/adk'; const agentA = new LlmAgent({ name: 'agent_a', model: 'gemini-flash-latest', instruction: 'You are Agent A. Always identify yourself as Agent A.', }); const agentB = new LlmAgent({ name: 'agent_b', model: 'gemini-flash-latest', instruction: 'You are Agent B. Always identify yourself as Agent B.', }); // External configuration that can change at runtime const config = { selectedAgent: 'agent_a' }; const routedAgent = new RoutedAgent({ name: 'my_routed_agent', agents: { agent_a: agentA, agent_b: agentB }, router: () => config.selectedAgent, }); const runner = new InMemoryRunner({ agent: routedAgent, appName: 'my_app', }); const session = await runner.sessionService.createSession({ appName: 'my_app', userId: 'user_1', }); const run = runner.runAsync({ userId: 'user_1', sessionId: session.id, newMessage: { role: 'user', parts: [{ text: 'Who are you?' }] }, }); for await (const event of run) { if (event.content?.parts?.[0]?.text) { console.log(event.content.parts[0].text); } } ``` 变动 `config.selectedAgent` 改为: `'agent_b'` 在下次引用到另一个代理人之前。 ## 错误后退[¶](<https://adk.dev/agents/routing/#fallback-on-error>) 当代理失败时, 路由器再次被调用 `errorContext` 因此它可以选择一个倒置。 Faultover 只有在代理失败后才产生任何事件时才适用(参见 [路线如何运作](<https://adk.dev/agents/routing/#how-routing-works>))以下实例检查 `errorContext.failedKeys` 以避免重选失败的代理 : TypeScript ``` import { BaseAgent, InvocationContext, LlmAgent, RoutedAgent, } from '@google/adk'; const primaryAgent = new LlmAgent({ name: 'primary', model: 'gemini-flash-latest', instruction: 'You are the primary agent.', }); const fallbackAgent = new LlmAgent({ name: 'fallback', model: 'gemini-pro-latest', instruction: 'You are the fallback agent.', }); const router = ( agents: Readonly<Record<string, BaseAgent>>, context: InvocationContext, // errorContext is provided when a previously selected agent fails errorContext?: { failedKeys: ReadonlySet<string>; lastError: unknown }, ) => { if (!errorContext) { return 'primary'; // Try primary first } if (errorContext.failedKeys.has('primary')) { return 'fallback'; // Fall back if primary failed } return undefined; // No more options, propagate the error }; const routedAgent = new RoutedAgent({ name: 'my_routed_agent', agents: { primary: primaryAgent, fallback: fallbackAgent }, router, }); ``` ## 规划模式[¶](<https://adk.dev/agents/routing/#planning-mode>) 路由器可以读取任何外部状态,以便在具有不同指令、模型和工具的代理之间进行选择。这使得您可以执行一个规划模式,使代理机能够动态地切换行为。例如,一个基本代理机可能已经读写工具,而一个规划代理机则被限制只读访问,并使用更强大的模型进行分析。 下面的例子显示一个不同的 `RoutedAgent` 配置。见 [基本用途](<https://adk.dev/agents/routing/#basic-usage>) 以备不时之需。 TypeScript ``` import { FunctionTool, LlmAgent, RoutedAgent, } from '@google/adk'; import { z } from 'zod'; const readFileTool = new FunctionTool({ name: 'read_file', description: 'Reads content from a file.', parameters: z.object({ filePath: z.string() }), execute: (args) => ({ content: `Contents of ${args.filePath}` }), }); const writeFileTool = new FunctionTool({ name: 'write_file', description: 'Writes content to a file.', parameters: z.object({ filePath: z.string(), content: z.string() }), execute: (args) => ({ result: `Wrote to ${args.filePath}` }), }); const basicAgent = new LlmAgent({ name: 'basic', model: 'gemini-flash-latest', instruction: 'You are a basic assistant. Use tools to help the user.', tools: [readFileTool, writeFileTool], }); const planningAgent = new LlmAgent({ name: 'planning', model: 'gemini-flash-latest', instruction: 'You are a planning expert. Analyze carefully. You can only read files.', tools: [readFileTool], }); // Toggle this to switch between basic and planning agents let planningMode = false; const routedAgent = new RoutedAgent({ name: 'my_routed_agent', agents: { basic: basicAgent, planning: planningAgent }, router: () => (planningMode ? 'planning' : 'basic'), }); ``` 设定 `planningMode = true` 使用其限制的工具集和不同的指示,以向规划代理人引路。 ## 按复杂程度分列的自动路由[¶](<https://adk.dev/agents/routing/#auto-routing-by-complexity>) 路由器功能可以调用一个轻量级分类器模型,将输入和路由相应分类到不同的代理,因为路由器可以是async,所以可以在选择代理之前让LLM在内部调用. 下面的例子显示一个不同的 `RoutedAgent` 配置。见 [基本用途](<https://adk.dev/agents/routing/#basic-usage>) 以备不时之需。 TypeScript ``` import { BaseAgent, Gemini, InvocationContext, LlmAgent, RoutedAgent, } from '@google/adk'; const simpleAgent = new LlmAgent({ name: 'simple', model: 'gemini-flash-latest', instruction: 'You are a simple assistant for basic questions.', }); const complexAgent = new LlmAgent({ name: 'complex', model: 'gemini-pro-latest', instruction: 'You are an expert assistant for complex analysis.', }); // Lightweight model to classify input complexity const classifierModel = new Gemini({ model: 'gemini-flash-latest' }); const router = async ( agents: Readonly<Record<string, BaseAgent>>, context: InvocationContext, ) => { // Extract the user's input text const text = context.userContent?.parts?.[0]?.text || ''; if (!text) return 'simple'; const prompt = `Classify this request as 'simple' or 'complex'. ` + `Reply with ONLY that word.\nRequest: "${text}"`; const generator = classifierModel.generateContentAsync({ contents: [{ role: 'user', parts: [{ text: prompt }] }], toolsDict: {}, liveConnectConfig: {}, }); let classification = ''; for await (const resp of generator) { if (resp.content?.parts?.[0]?.text) { classification += resp.content.parts[0].text; } } return classification.toLowerCase().includes('complex') ? 'complex' : 'simple'; }; const routedAgent = new RoutedAgent({ name: 'my_routed_agent', agents: { simple: simpleAgent, complex: complexAgent }, router, }); ```
查看原始来源