跳转到内容

代理之间的通信路径(即数据传输的路线)

在 ADK 中得到支持。TypeScript v1.0.0实验性的(Experimental)

实验性的(Experimental)

代理路由功能仍处于测试阶段,未来版本中可能会发生变化。我们欢迎您的任何反馈或建议。 反馈!

在为不同的任务构建代理程序时,您可以定义一个路由函数,该函数在运行时决定由哪个代理程序来处理每次请求(即每次调用)。 RoutedAgent 该功能允许代理在遇到错误时切换到备用方案(即“fallback”机制),同时支持 A/B 测试、不同的规划模式,以及根据输入数据的复杂性自动选择路由方式。如果所选的代理在生成任何输出之前就发生了故障,系统会再次调用路由函数,并提供相应的错误信息,以便代理能够选择合适的备用方案继续执行任务。

RoutedAgent 与……不同 工作流代理(Workflow Agents) 喜欢;相似 SequentialAgent 或者 ParallelAgent这些组件负责按照固定的模式协调多个代理(agents)的运作。 由大型语言模型(LLM)驱动的 任务/职责分配机制在这里,大型语言模型(LLM)会决定将任务交给哪个代理来处理。 RoutedAgent你需要编写一个显式的路由函数(explicit routing function),该函数用于选择特定的路由路径。 one 每次调用时使用的代理(agent)。有关模型级路由(model-level routing)的信息,请参见…… 模型路由(Model Routing).

路由机制是如何工作的

两者都 RoutedAgent 和 RoutedLlm 这些系统由一个共享的路由工具提供支持,该工具负责处理路由选择及故障切换(即当某个路由出现故障时,系统会自动切换到另一个备用路由)。

`router` 函数接收可用代理的列表(即代理的映射信息)以及当前的上下文(`context`),并返回应该被调用的代理的标识符(即该代理的键)。该函数的执行可以是同步的(synchronous),也可以是异步的(async)。

type AgentRouter = (
  agents: Readonly<Record<string, BaseAgent>>,
  context: InvocationContext,
  errorContext?: { failedKeys: ReadonlySet<string>; lastError: unknown },
) => Promise<string | undefined> | string | undefined;

The agents 参数 可以接受以下任意一种情况: Record<string, BaseAgent> 可以使用显式的键(explicit keys),或者一个代理(agent)的数组。如果提供了数组,那么每个代理都会被单独处理。 name 该属性被用作其键(key)。

故障转移行为:

  • 首先,会尝试在没有其他参数的情况下调用该路由器(即仅使用路由器的基本功能)。 errorContext 为了进行最初的筛选(或选择)。
  • 如果选定的代理程序抛出错误…… 在释放任何事件之前此时,路由器会被再次调用(即再次执行相应的操作)。 errorContext 包含;含有 failedKeys 和 lastError.
  • 如果选定的代理程序抛出错误…… 在“yield events”之后错误会直接传播下去,而不会被重试;因为部分结果已经提前被发送出去了。
  • 已经尝试过使用某个密钥的情况下,该密钥无法被再次选中。如果路由器再次返回之前曾导致连接失败的那个密钥,错误信息将会继续被传递(即错误会继续在系统中传播)。
  • 如果路由器返回了相应的信息…… undefined在路由过程中,如果遇到问题或错误,系统会停止进一步的处理,并抛出相应的错误信息。

基本用法

创建多个代理(agents),定义一个路由函数(router function),该函数返回一个键(key),然后将这些代理和路由函数封装在一起。 RoutedAgent以下示例根据一个外部配置值来路由两个代理之间的通信;该配置值在每次调用时都可能发生变化:

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' 在下次调用该功能之前,系统会将该请求路由到另一个代理(agent)进行处理。

在发生错误时使用备用方案(即“回退机制”)。

当某个代理(agent)发生故障时,路由器会再次被调用(即重新执行相应的操作)。 errorContext 这样它就可以选择一个备用方案(即“fallback”)。只有当代理在生成任何事件之前就发生故障时,才会触发故障转移(failover)机制(详见……)。 路由机制是如何工作的以下示例用于进行检查(checks)。 errorContext.failedKeys 为了避免重新选择那些已经失败的代理(即那些无法正常工作的代理),……

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

规划模式(Planning mode)

路由器可以读取任何外部状态信息,从而在具有不同指令、模型和功能的代理之间进行选择。这使得你可以实现一种“规划模式”:在这种模式下,代理的行为会动态地发生变化。例如,一个普通的代理可能具备读写数据的能力;而一个用于进行规划的代理则仅被允许读取数据,并使用更强大的模型来进行分析。

以下示例展示了另一种情况(即不同的实现方式或结果)。 RoutedAgent “configuration”:请参阅相关文档。 **基本用法:** `basic` 是一个用于描述某种工具、功能或方法的基本属性或特性的术语。在编程或技术文档中,它通常用来说明某个组件、库或算法的最基本功能或使用方式。例如: “`basic` 是一个用于处理字符串的简单函数,它接受一个字符串作为参数,并返回一个新的字符串。” **API 标识符:** 在某些情况下,`basic` 也可能用作 API 的名称。例如,一个名为 `basic` 的 API 可能提供字符串处理服务。例如: ```json { "apiName": "basic", "version": "1.0.0", "description": "A simple API for string manipulation.", "methods": [ { "name": "capitalize", "description": "Converts the first letter of a string to uppercase." }, { "name": "toLowerCase", "description": "Converts the entire string to lowercase." } ] } ``` **占位符:** 在某些上下文中,`basic` 也可以作为占位符使用,表示某个尚未定义或具体的内容。例如: ```markdown - This is an example using the **basic** function. - The **basic** settings need to be configured before use. ``` 总之,`basic` 是一个多用途的术语,可以根据具体的上下文表示不同的含义。 有关完整的跑步者设置信息,请参阅……(此处应提供具体参考资料或链接)。

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

`Set` planningMode = true 在调用该功能以将请求路由到规划代理之前,需要先使用该规划代理的有限工具集及其特定的指令来处理请求。

根据任务的复杂度自动选择路由方式

路由器功能可以调用一个轻量级的分类模型来对输入数据进行分类,并据此将请求路由到不同的处理节点(即“代理”)。由于路由器支持异步操作,因此你可以在选择处理节点之前先在该路由器内部调用大型语言模型(LLM)的相关功能。

以下示例展示了另一种情况(即不同的实现方式或结果)。 RoutedAgent “configuration”:请参阅相关文档。 **基本用法:** `basic` 是一个用于描述某种工具、功能或方法的基本属性或特性的术语。在编程或技术文档中,它通常用来说明某个组件、库或算法的最基本功能或使用方式。例如: “`basic` 是一个用于处理字符串的简单函数,它接受一个字符串作为参数,并返回一个新的字符串。” **API 标识符:** 在某些情况下,`basic` 也可能用作 API 的名称。例如,一个名为 `basic` 的 API 可能提供字符串处理服务。例如: ```json { "apiName": "basic", "version": "1.0.0", "description": "A simple API for string manipulation.", "methods": [ { "name": "capitalize", "description": "Converts the first letter of a string to uppercase." }, { "name": "toLowerCase", "description": "Converts the entire string to lowercase." } ] } ``` **占位符:** 在某些上下文中,`basic` 也可以作为占位符使用,表示某个尚未定义或具体的内容。例如: ```markdown - This is an example using the **basic** function. - The **basic** settings need to be configured before use. ``` 总之,`basic` 是一个多用途的术语,可以根据具体的上下文表示不同的含义。 有关完整的跑步者设置信息,请参阅……(此处应提供具体参考资料或链接)。

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