跳转到内容

模型之间的路由(即数据传输路径)

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

实验性的(Experimental)

模型路由功能目前仍处于实验阶段,未来可能会在版本更新中进行修改。我们欢迎您的任何反馈或建议。 反馈!

An LlmAgent 默认情况下,系统会使用一个模型。当您需要为每个请求动态地选择不同的模型时,可以定义一个路由函数来决定使用哪个模型。 RoutedLlm 该功能允许模型在出现错误时自动切换到备用模型,支持不同模型之间的 A/B 测试,并根据输入数据的复杂性自动选择相应的处理路径。如果所选模型在生成任何输出之前就发生了故障,系统会再次调用路由函数,并提供相应的错误信息,以便系统能够选择另一个模型来继续处理请求。

传递一个…… RoutedLlm 作为…… LlmAgent's model 参数。使用。 RoutedLlm **当只有模型在不同路由之间有所不同时**:如果你还需要切换相应的指令、工具或子代理(sub-agents),请使用相应的功能或工具来进行调整。 RoutedAgent 相反。

路由机制是如何工作的

The LlmRouter 该函数接收一个包含所有可用模型的映射(map),以及当前的状态(current)。 LlmRequest并返回要使用的模型的键:

type LlmRouter = (
  models: Readonly<Record<string, BaseLlm>>,
  request: LlmRequest,
  errorContext?: { failedKeys: ReadonlySet<string>; lastError: unknown },
) => Promise<string | undefined> | string | undefined;

The models 该参数可以接受以下两种值中的任意一种: Record<string, BaseLlm> 使用显式的键(explicit keys),或者一个键数组(an array of keys)。 BaseLlm 如果提供了数组,那么每个模型的名称将被用作该模型的键。

故障转移(Failover)遵循与……相同的规则。 RoutedAgent:路由器会被重新调用(即会再次执行相应的操作)。 errorContext **只有当所选模型在产生任何响应之前就发生故障时,才会执行后续操作。** 一旦模型成功产生了响应,错误信息会直接被传递出去,而不会被重试处理。此时,路由器可以返回相应的结果。 undefined 停止重试,并将最后一个错误信息传递给后续的处理流程。

实时连接(Live connections): RoutedLlm.connect() 在连接时选择相应的模型。一旦建立了实时连接,就无法在传输过程中更换模型。

基本用法

以下示例创建了一个……(具体内容需要根据上下文来确定)。 RoutedLlm 该系统首先尝试使用主模型(primary model)进行处理;如果主模型失败,则会转而使用备用模型(secondary model)。路由器会对此过程进行监控(即进行检查)。 errorContext.failedKeys 为了避免重新选择那些已经失败(即无法正常运行)的模型:

import {
  BaseLlm,
  Gemini,
  LlmRequest,
  LlmAgent,
  RoutedLlm,
  InMemoryRunner,
} from '@google/adk';

const primaryModel = new Gemini({ model: 'gemini-flash-latest' });
const fallbackModel = new Gemini({ model: 'gemini-pro-latest' });

const router = (
  models: Readonly<Record<string, BaseLlm>>,
  request: LlmRequest,
  // errorContext is provided when a previously selected model 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 routedLlm = new RoutedLlm({
  models: { primary: primaryModel, fallback: fallbackModel },
  router,
});

// Use RoutedLlm as the model for an LlmAgent
const agent = new LlmAgent({
  name: 'my_agent',
  model: routedLlm,
  instruction: 'You are a helpful assistant.',
});

const runner = new InMemoryRunner({ agent, 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: 'Hello!' }] },
});

for await (const event of run) {
  if (event.content?.parts?.[0]?.text) {
    console.log(event.content.parts[0].text);
  }
}