RIG中文文档非官方中文译本

模型路由

实战指南官网快照 · 2026-11-10阅读英文原文 ↗
Rig 0.46.0 实际适配版

本页 7 个 Rust 代码块均有编译检查记录;片段已补齐所需上下文。 3 个代码块已更新。

查看逐块编译结果、运行前提与示例项目 →

模型路由决定由哪个模型回答请求。Rig 支持三个层面的路由:

  • 在多个 Agent 之间:低成本分类器或嵌入搜索选出一个专门的 Agent,再由它回答。
  • 在单个 Agent 内部:Agent 用标签持有多个模型,hook 在每次模型调用之前选择标签。例如用快模型规划和调用工具,用更强的模型撰写最终答案。
  • 从配置创建:配置文件或用户设置中的字符串,例如 "anthropic/claude-sonnet-5-5",在运行时转换为模型。

三者都基于同一个事实:Agent 不以服务商作为泛型参数。所有模型都以 impl Into<DynModel<Completion>> 接收,因此不同服务商的 Agent 和模型共享同一种类型,可以存进同一个 HashMap、Vec 或结构体字段。

在多个 Agent 之间路由#

路由 Agent 从固定列表中选择一个词来分类请求,再由对应专家回答。路由工作很简单,因此可以使用小模型:

mermaid
flowchart TD
    User[User] -->|Query| Router[Router agent]
    Router -->|rust| Rust[Rust agent]
    Router -->|maths| Maths[Maths agent]
    Rust --> Response
    Maths --> Response
rust
use std::collections::HashMap;


let openai = OpenAI::from_env()?;
let anthropic = Anthropic::from_env()?;


// Specialists from different providers share the `Agent` type.
let routes: HashMap<&str, Agent> = HashMap::from([
    (
        "rust",
        AgentBuilder::new(anthropic.completion(anthropic::CLAUDE_SONNET_5_5))
            .preamble("You are an expert Rust programmer.")
            .build(),
    ),
    (
        "maths",
        AgentBuilder::new(openai.completion(openai::GPT_5_5))
            .preamble("You are a mathematician who explains each step.")
            .build(),
    ),
]);


let router = AgentBuilder::new(openai.completion(openai::GPT_5_MINI))
    .preamble(
        "Classify the user's question. Reply with exactly one word from: rust, maths. \
         No other text.",
    )
    .build();


let question = "How do I use async with Rust?";
let topic = router.prompt(question).await?.output();


let Some(agent) = routes.get(topic.trim()) else {
    anyhow::bail!("no route for {topic:?}");
};
println!("{}", agent.prompt(question).await?.output());

完整代码与上下文 ↗编译通过 · Rig 0.46.0

务必处理未匹配情况:模型可能给出列表之外的答案。

使用嵌入进行语义路由#

LLM 对同一输入的分类结果可能变化。如果希望匹配更稳定,可以为每条路由的说明和示例问题生成嵌入,再按向量相似度选择最接近输入问题的路由。原理见向量嵌入。

rust
/// One route. The description and examples are embedded; `name` is the key.
#[derive(Embed, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
struct Route {
    name: String,
    #[embed]
    description: String,
    #[embed]
    examples: Vec<String>,
}


let embedding_model = OpenAI::from_env()?
    .embedding(openai::TEXT_EMBEDDING_3_SMALL, None)
    .erase();


let routes = vec![
    Route {
        name: "rust".into(),
        description: "Programming and software development in Rust".into(),
        examples: vec![
            "How do I write an async function in Rust?".into(),
            "Why does the borrow checker reject this code?".into(),
        ],
    },
    Route {
        name: "maths".into(),
        description: "Mathematics, calculations and equations".into(),
        examples: vec!["Solve this equation".into(), "What is 15% of 200?".into()],
    },
];


let embeddings = EmbeddingsBuilder::new(embedding_model.clone())
    .documents(routes)?
    .build()
    .await?;
let index = InMemoryVectorStore::from_documents(embeddings).index(embedding_model);


let request = VectorSearchRequest::builder()
    .query("How do I use async with Rust?")
    .samples(1)
    .build();


let route = index
    .top_n::<Route>(request)
    .await?
    .into_iter()
    .next()
    .map_or_else(|| "general".to_owned(), |hit| hit.document.name);
println!("route: {route}");

完整代码与上下文 ↗编译通过 · Rig 0.46.0

像上一节一样,用路由名称查找 Agent。对没有合适匹配的问题保留 general 回退路由;面对真实数据时,还可以设置最低 hit.score,低于该分数就回退。

在单个 Agent 内路由模型#

在多个 Agent 之间路由,是为整个请求选定一个 Agent。有时应当为每次模型调用分别选择:在使用工具的运行中,决定调用什么工具的请求可以交给快模型,撰写最终答案的请求交给更强模型。Agent 可以为此持有多个模型:

  • AgentBuilder::new(model) 将 model 注册到 default 标签下;AgentBuilder::named_model(label, model) 则用你指定的标签注册。
  • .model_route(label, model) 注册另一个运行时可选择的模型。
  • 带有 on_model_select 的 AgentHook 在每次模型调用前执行,返回 ModelSelectionAction::select(label)、::continue_run()(保留当前候选)或 ::stop(reason)(在调用前结束运行)。

这些模型可以来自不同服务商。历史以 Rig 的服务商中立格式保存,因此一个模型发出的工具调用,可以由另一个模型接收结果并继续处理。

rust
/// Plan and call tools on the fast model; answer on the strong one.
#[derive(Clone)]
struct FastThenStrong;


impl AgentHook for FastThenStrong {
    fn on_model_select(
        &self,
        context: &HookContext,
        _event: ModelSelection<'_>,
    ) -> ModelSelectionAction {
        // `turn()` is the one-based index of the model call in this run.
        if context.turn() == 1 {
            ModelSelectionAction::select("fast")
        } else {
            ModelSelectionAction::select("strong")
        }
    }
}


let agent = AgentBuilder::named_model("fast", OpenAI::from_env()?.completion(openai::GPT_5_MINI))
    .model_route(
        "strong",
        Anthropic::from_env()?.completion(anthropic::CLAUDE_OPUS_5_5),
    )
    // .tool(search_tool) ...
    .add_hook(FastThenStrong)
    .build();


let answer = agent
    .prompt("Research the question, then write a careful answer.")
    .max_turns(4)
    .await?;
println!("{answer}");

完整代码与上下文 ↗编译通过 · Rig 0.46.0

Hook 收到的 ModelSelection 描述待执行调用:将发送的 prompt 和 history、运行的 default_model、前面 hook 选择的 selected_model,以及上次调用使用的 previous_model。因此路由可以依赖对话内容,而不只是轮次编号。接口约定如下:

  • 通过 AgentBuilder::add_hook 添加的 hook 作用于该 Agent 的每次运行;在提示词上添加的 hook(agent.prompt(p).add_hook(h))只作用于本次运行。
  • 多个选择 hook 按注册顺序执行,每个都能看到前一个的选择;最后一次选择生效,停止决定会结束运行。
  • 每次模型调用前都会重新选择,包括重试和工具结果后的调用,因此运行可以中途换模型;已发出的调用不会切换。
  • 选择未注册的标签会导致运行失败。

runtime_model_routing 示例用预设模型完整演示双模型的工具往返,无需 API Key。

修改默认模型#

没有路由 hook 时,Agent 使用默认模型。可以只为一次运行修改,也可以修改 Agent 值本身:

rust
let mut agent = AgentBuilder::named_model("fast", OpenAI::from_env()?.completion(openai::GPT_5_MINI))
    .model_route("strong", OpenAI::from_env()?.completion(openai::GPT_5_5))
    .build();


// One run: start from a registered label, or from a model value.
let hard = agent.prompt("Prove that sqrt(2) is irrational.").using_model("strong").await?;
let other = agent
    .prompt("Say hello.")
    .using_model_value(Anthropic::from_env()?.completion(anthropic::CLAUDE_HAIKU_4_5))
    .await?;


// This agent value from now on: a registered label, or a new model.
agent.set_model_label("strong");
agent.set_model(Anthropic::from_env()?.completion(anthropic::CLAUDE_SONNET_5_5));

完整代码与上下文 ↗编译通过 · Rig 0.46.0

with_model_label 和 with_model 是按值接收的形式。设置默认模型只改变初始候选,路由 hook 仍会执行,也可能选中其他标签。若要强制使用一个模型,可不添加路由 hook,或在最后添加始终选择该模型的 hook。set_model 遵循值语义:Agent 的各个克隆保留自己的默认模型。

在运行时选择服务商和模型#

当服务商来自配置,例如设置文件、环境变量或 UI 中的用户选择时,可通过 Catalog 从 vendor/model 字符串创建模型。connect_with 通过 ConnectOptions 接收显式 Key,返回 DynModel<Completion>:

rust
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    use rig::catalog::Catalog;
    use rig::providers::registry::ConnectOptions;
    let model_name = "anthropic/claude-sonnet-5-5";
    let api_key = std::env::var("ANTHROPIC_API_KEY")?;
    let model = Catalog::builtin().connect_with(
        model_name, ConnectOptions::new().api_key(api_key),
    )?;
    let agent = rig::AgentBuilder::new(model)
        .preamble("You are a helpful assistant.").build();
    println!("{}", agent.prompt("Hello!").await?.output());
    Ok(())
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

引用使用 vendor/model,例如 deepseek/deepseek-v4-flash。ConnectOptions 还可设置协议族、自定义 HTTP 客户端和基础 URL;不要使用旧版冒号格式。

若要从各服务商惯用的环境变量读取凭证,直接使用 Catalog::connect(reference)。配置中保存模型引用字符串即可:

rust
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    use rig::catalog::Catalog;
    // Persist the reference text, not the removed ProviderRef type.
    let reference = "deepseek/deepseek-v4-flash";
    let stored = serde_json::to_string(reference)?;
    let restored: String = serde_json::from_str(&stored)?;
    let model = Catalog::builtin().connect(&restored)?;
    let _agent = rig::AgentBuilder::new(model).build();
    assert_eq!(restored, reference);
    Ok(())
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

这样创建的模型是普通 DynModel,可以作为 Agent 默认模型、model_route,或一次运行的 using_model_value。

查询模型信息#

rig::catalog::Catalog 列出已知模型及其上下文窗口、输出上限、输入模态、工具和结构化输出支持,以及价格。路由器可以据此选择符合请求要求的模型,connect 也可直接接收 catalog 条目:

rust
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    use rig::catalog::Catalog;
    use rig::providers::registry::ConnectOptions;
    let catalog = Catalog::builtin();
    let resolved = catalog.resolve("openai/gpt-5.5")?;
    let spec = resolved.spec;
    println!("{}: {:?} token context, tools: {}",
        spec.display_name, spec.context_window, spec.tools);
    if let Some(pricing) = &spec.pricing {
        println!("${} / ${} per million input/output tokens", pricing.input, pricing.output);
    }
    let model = catalog.connect_with("openai/gpt-5.5",
        ConnectOptions::new().api_key(std::env::var("OPENAI_API_KEY")?))?;
    let _agent = rig::AgentBuilder::new(model).build();
    Ok(())
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

Catalog::from_overrides 读取覆盖文件,with_overrides 将配置叠加到已有目录;from_models_dev 用于 models.dev 数据。resolve 返回 Result<Resolved, _>,模型信息位于 .spec。

另请参阅#

本文译自 Rig 官方英文文档,中文翻译未经官方审核。代码已按 Rig 0.46.0 更新;英文快照保存在 source,验证范围见版本说明。
原文版权归 Playgrounds / Rig 作者所有 · MIT 许可 · 升级与验证记录 · 站点地图

搜索中文概念、方法名或英文术语。