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

工具(Tools)

核心概念官网快照 · 2026-11-10阅读英文原文 ↗
Rig 0.46.0 实际适配版

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

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

工具让 Agent 不只生成文本:它们把你的 Rust 函数开放给模型,让模型调用函数来获取数据、执行计算或访问外部系统。模型请求工具时,Rig 会解析参数、运行你的代码、把结果传回模型,再继续循环。

开始之前

完整示例#

下面的程序定义两个工具:Add 手动实现 Tool trait,Subtract 则由 #[rig::rig_tool] 宏从普通函数生成,然后将两者都接入 Agent。

rust
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
use rig::tool::{ToolContext, ToolExecutionError};
use serde::Deserialize;
use serde_json::json;


#[derive(Deserialize)]
struct AddArgs {
    x: i64,
    y: i64,
}


// A tool implemented by hand against the `Tool` trait.
struct Add;


impl Tool for Add {
    const NAME: &'static str = "add";
    type Args = AddArgs;
    type Output = i64;
    type Error = ToolExecutionError;


    fn description(&self) -> String {
        "Add x and y together".to_string()
    }


    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "x": { "type": "integer", "description": "The first number" },
                "y": { "type": "integer", "description": "The second number" }
            },
            "required": ["x", "y"]
        })
    }


    async fn call(&self, _ctx: &mut ToolContext, args: AddArgs) -> Result<i64, ToolExecutionError> {
        Ok(args.x + args.y)
    }
}


// A tool generated from a function. The macro creates a unit struct named
// after the function in PascalCase (`subtract` -> `Subtract`).
#[rig::rig_tool(description = "Subtract y from x")]
fn subtract(x: i64, y: i64) -> Result<i64, ToolExecutionError> {
    Ok(x - y)
}


#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let calculator = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
        .preamble("You are a calculator. Use the provided tools to answer arithmetic questions.")
        .tool(Add)
        .tool(Subtract)
        .build();


    let answer = calculator
        .prompt("What is (5 - 2) + 10?")
        .max_turns(4)
        .await?
        .output();
    println!("{answer}");


    Ok(())
}

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

text
(5 - 2) + 10 = 13

一次模型调用可以请求一个或多个工具。工具执行后,通常还需再次调用模型,让它根据结果继续处理或回答。因此,涉及工具的提问需要足够的模型调用次数,可以在请求上设置 .max_turns(n),或在构建器上设置 .default_max_turns(n);预算耗尽时,运行会返回 PromptError::MaxTurns。

Tool trait#

每个类型化工具都实现 rig::tool::Tool。use rig::prelude::*; 会将 Tool 和 ToolContext 引入作用域;本页代码片段均假设已经这样导入。

  • const NAME:模型调用工具时使用的名称,必须在 Agent 内唯一。
  • type Args:实现 Deserialize 的类型,模型的 JSON 参数会被解析为此类型。解析失败的参数不会进入你的代码;模型会收到“参数无效”的结果。
  • type Output:成功调用的返回值。任何实现 Serialize 的类型都可使用,参见工具输出。
  • type Error:你的错误类型,必须实现 std::error::Error。
  • description() 和 parameters():发送给服务商的说明文本和 JSON Schema。模型根据 schema 了解如何调用工具,因此应描述每个字段。
  • call(&self, ctx, args):实际工作逻辑。ctx 是本次调用的 ToolContext,不需要时可以忽略。
  • map_error(&self, error):可选。将你的错误转换为模型和钩子看到的内容,参见工具失败时。

用 schemars 派生 schema#

手写 parameters JSON 容易出错。可以在 Cargo.toml 添加 schemars = "1",为参数结构体派生 JsonSchema,并用 /// 文档注释描述每个字段:

rust
use schemars::JsonSchema;


#[derive(Deserialize, JsonSchema)]
struct AddArgs {
    /// The first number to add.
    x: i64,
    /// The second number to add.
    y: i64,
}


struct Add;


impl Tool for Add {
    const NAME: &'static str = "add";
    type Args = AddArgs;
    type Output = i64;
    type Error = std::convert::Infallible;


    fn description(&self) -> String {
        "Add x and y together".to_string()
    }


    fn parameters(&self) -> serde_json::Value {
        schemars::schema_for!(AddArgs).to_value()
    }


    async fn call(&self, _ctx: &mut ToolContext, args: AddArgs) -> Result<i64, Self::Error> {
        Ok(args.x + args.y)
    }
}

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

#[rig::rig_tool] 宏#

多数工具不需要手写 impl。在返回 Result<T, E> 的同步或 async 函数上添加 #[rig::rig_tool],宏会生成:

  • 按函数名转为 PascalCase 命名的单元结构体,例如 get_weather 变为 GetWeather,可传给 .tool(...);
  • 带有派生 JSON Schema 的参数结构体,例如 GetWeatherParameters;
  • 工具 trait 实现,以及一个 static GET_WEATHER: GetWeather 实例。
rust
use rig::tool::ToolExecutionError;


/// Look up the current temperature for a city.
#[rig::rig_tool(params(city = "City name, e.g. `Paris`"))]
async fn get_weather(
    city: String,
    /// Temperature unit: `celsius` (default) or `fahrenheit`.
    unit: Option<String>,
) -> Result<String, ToolExecutionError> {
    let unit = unit.unwrap_or_else(|| "celsius".to_string());
    if city.is_empty() {
        return Err(ToolExecutionError::invalid_args("`city` must not be empty"));
    }
    Ok(format!("It is 21 degrees {unit} in {city}."))
}

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

宏接受以下选项,全部可省略:

  • name = "...":工具名,默认为函数名。
  • description = "...":工具描述,默认为函数的文档注释。
  • params(arg = "...", ...):参数描述。参数上的 /// 文档注释也有效。两种方式都没提供时会生成占位描述,因此请补充描述。
  • required(arg, ...):模型必须提供的参数。

未指定 required(...) 时,所有非 Option 参数都必填,Option 参数都可选。如果显式提供 required(...) 列表,未列入的参数将变为可选;模型省略它们时,会使用 Default::default(),因此这些参数类型必须实现 Default。将 Option 参数列入 required(...) 会导致编译错误。

如果函数的第一个参数是 &mut rig::tool::ToolContext,它会收到工具上下文;上下文不会出现在模型参数里。如果以更短的路径导入 ToolContext,请给该参数标记 #[rig(context)],让宏能识别它。

工具输出#

type Output 可以是任何实现 Serialize 的类型。Rig 会将其转成模型看到的工具结果:String 变为文本块,其他类型,例如数字、结构体和 serde_json::Value,变为 JSON 块。若要自行控制内容,可返回 ToolOutput:

rust
use rig::tool::ToolOutput;


let text = ToolOutput::text("Search complete: 3 results.");
let json = ToolOutput::json(json!({ "count": 3 }));
// Several blocks, including images, for multimodal tools.
let blocks = ToolOutput::content(vec![
    ToolResultContent::text("Here is the chart:"),
    ToolResultContent::json(json!({ "series": [1, 2, 3] })),
])?;

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

工具输出会成为下一轮的提示输入,因此应保持精简:在工具内部筛选和汇总,而不是直接返回原始 API 响应。

工具失败时#

工具返回 Err 不会结束运行。Rig 会将错误转为失败的工具结果,发送给模型,然后继续循环:模型可以修正参数后重试、尝试另一个工具,或向用户解释失败原因。

模型读取到什么取决于错误类型。Rig 会将每个工具错误转换为 ToolExecutionError,它将两类文本分开:供日志和钩子使用的 message,以及模型读取的 model output。

  • 任意错误类型,例如 io::Error、reqwest::Error 或你自己的枚举,由默认 map_error 包装。模型只能看到笼统反馈 the tool failed,因此路径、主机或凭证等内部细节不会泄露到对话中。你的代码仍可通过 error.message() 和 error.downcast_ref::<E>() 访问原始错误。
  • 你自行构建的 ToolExecutionError 会向模型展示它的消息。可以按失败类型选择构造器:invalid_args、not_found、permission_denied、timeout、rate_limited、network、provider、cancelled 和 other。refused(..) 表示主动拒绝。

应面向模型编写这些消息:"Division by zero; y must not be 0"(除数为零;y 不能为 0)有助于恢复,"error 500" 则没有帮助。每次恢复尝试都消耗一个轮次,因此要给 .max_turns(..) 留出余量。

如果既要为自己的代码保留类型化错误,又要给模型提供有用消息,可以覆盖 map_error:

rust
use rig::tool::ToolExecutionError;


#[derive(Debug, thiserror::Error)]
enum LookupError {
    #[error("no customer with id {0}")]
    NotFound(String),
    #[error("database unreachable at {0}")]
    Database(String),
}


#[derive(Deserialize)]
struct LookupArgs {
    id: String,
}


struct LookupCustomer;


impl Tool for LookupCustomer {
    const NAME: &'static str = "lookup_customer";
    type Args = LookupArgs;
    type Output = String;
    type Error = LookupError;


    fn description(&self) -> String {
        "Look up a customer by id".to_string()
    }


    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": { "id": { "type": "string" } },
            "required": ["id"]
        })
    }


    fn map_error(&self, error: LookupError) -> ToolExecutionError {
        match error {
            // Safe and useful for the model: say what went wrong.
            LookupError::NotFound(_) => ToolExecutionError::not_found(error.to_string()),
            // The message names an internal host: log it, tell the model less.
            LookupError::Database(_) => ToolExecutionError::network(error.to_string())
                .with_model_feedback("the customer database is unavailable; try again later")
                .with_code("DB_DOWN")
                .with_source(error),
        }
    }


    async fn call(&self, _ctx: &mut ToolContext, args: LookupArgs) -> Result<String, LookupError> {
        Err(LookupError::NotFound(args.id))
    }
}

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

with_code、with_retryable 和 with_http_status 添加结构化信息,供钩子据此处理;这些信息都不会发送给模型。

还有两种失败采用不同处理方式。参数不符合 Args 时,会像其他工具错误一样,变成发给模型的 invalid_args 结果。调用不存在的工具时,运行则会返回 PromptError::UnknownToolCall,除非钩子进行了恢复,参见钩子。

工具上下文#

工具需要的某些值不应来自模型,例如已登录用户、租户 ID 或请求 ID。请改用 ToolContext 传递。上下文值是类型化的:为类型派生 ContextValue、Serialize 和 Deserialize,在运行前插入,再在工具内部读取。

rust
use rig::tool::ToolExecutionError;


/// The signed-in user. Set by the host, never by the model.
#[derive(Serialize, Deserialize, rig::ContextValue)]
struct UserId(String);


/// Host-only metadata the tool reports back about its call.
#[derive(Serialize, Deserialize, rig::ContextValue)]
#[context(key = "orders.rows_read")]
struct RowsRead(usize);


#[derive(Deserialize)]
struct NoArgs {}


struct ListOrders;


impl Tool for ListOrders {
    const NAME: &'static str = "list_orders";
    type Args = NoArgs;
    type Output = Vec<String>;
    type Error = ToolExecutionError;


    fn description(&self) -> String {
        "List the signed-in user's recent orders".to_string()
    }


    fn parameters(&self) -> serde_json::Value {
        json!({ "type": "object", "properties": {} })
    }


    async fn call(&self, ctx: &mut ToolContext, _args: NoArgs) -> Result<Vec<String>, ToolExecutionError> {
        let user = ctx.require::<UserId>()?;
        let orders = vec![format!("order #1001 for {}", user.0)];
        ctx.insert_result(RowsRead(orders.len()))?;
        Ok(orders)
    }
}

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

用 .tool_context(..) 为每次运行设置上下文。Rig 会给每个工具调用各自的副本:

rust
use rig::tool::ToolContext;


let mut context = ToolContext::new();
context.insert(UserId("u_42".to_string()))?;


let reply = agent
    .prompt("What did I order recently?")
    .tool_context(context)
    .max_turns(3)
    .await?;

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

  • 值不存在时,ctx.get::<T>() 返回 Ok(None);ctx.require::<T>() 返回错误,? 会将其变成失败的工具结果。
  • ctx.insert_result(..) 为本次调用结果添加仅应用程序可见的元数据,模型永远看不到。钩子从结果事件中读取它;tool_result_outcomes 示例正是用它决定失败是否应停止运行。
  • 每个槽位以 ContextValue::KEY 为键:默认是类型名,也可用 #[context(key = "...")] 指定。值以序列化数据存储,因此共享句柄,例如 Arc<Mutex<_>>、连接池和 channel,应放在工具结构体上。

运行时定义的工具#

如果工具名称、描述或 schema 只能在运行时确定,例如从配置加载或根据 API 规范生成,可使用名称、描述、JSON Schema 和接收原始 JSON 参数的异步闭包,构建 DynamicTool:

rust
use rig::message::ToolName;
use rig::tool::{DynamicTool, ToolExecutionError, ToolOutput};


let echo = DynamicTool::new(
    ToolName::new("echo")?,
    "Repeat the input text back",
    json!({
        "type": "object",
        "properties": { "text": { "type": "string" } },
        "required": ["text"]
    }),
    |args| {
        Box::pin(async move {
            let text = args["text"]
                .as_str()
                .ok_or_else(|| ToolExecutionError::invalid_args("`text` must be a string"))?;
            Ok(ToolOutput::text(text))
        })
    },
);


let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
    .dynamic_tool(echo)
    .build();

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

ToolName::new 会拒绝空名称。可以用 .dynamic_tools(vec![..]) 一次添加多个工具;闭包需要工具上下文时,使用 DynamicTool::new_with_context。

可移植工具与内置工具#

0.46.0 统一使用 Tool。不需要上下文时,把 call 的参数命名为 _ctx 即可;#[rig::rig_tool] 也生成该 trait 的实现。

Rig 提供一个内置工具 rig::tool::builtin::ThinkTool。它给模型提供名为 think 的工具,将输入原样返回,作为工具调用之间的推理草稿区。

rust
use rig::tool::builtin::ThinkTool;


let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
    .tool(ThinkTool)
    .build();

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

设计好用的工具#

模型通过阅读名称、描述和参数 schema 来选择工具。这些文本就是接口,大多数工具使用失败都源于这些说明,而不是模型本身。

  • 使用有描述性的名称,采用 snake_case,避免缩写:search_orders 比 so 更好。
  • 面向模型写描述。说明工具做什么、什么时候使用,以及什么时候不应使用。
  • 描述每个参数,并尽量减少参数数量、降低复杂度。相比填写嵌套对象,模型填写三个说明清楚的字符串或数字字段通常可靠得多。
  • 每次请求只提供少量工具。工具列表变长时,选择效果会下降,大致在超过十到二十个工具之后更明显。可以将大量工具分配给不同专用 Agent,或使用检索工具,让每次请求只看到相关的少量工具。
  • 返回精简结果。对于大型或敏感数据,可返回由你的代码稍后解析的 ID,而不是直接返回数据本身。

检索工具#

工具很多时,每次请求都发送所有定义既浪费 token,也容易让模型困惑。检索工具会被向量化后存入向量存储。每次模型调用前,Agent 用提问文本搜索;如果当前轮只包含工具结果,就使用最近一条用户消息的文本搜索,然后只向模型提供最接近的匹配项。

下面的示例用 EmbeddingsBuilder 和 InMemoryVectorStore 构建索引。如果还不熟悉,先看向量嵌入和向量存储与 RAG。

可检索工具还需要实现 ToolEmbedding,提供要生成嵌入的文本和重建工具的方法:

rust
use rig::tool::ToolEmbedding;


#[derive(Debug, thiserror::Error)]
#[error("init error")]
struct InitError;


#[derive(Deserialize)]
struct AddArgs { x: i64, y: i64 }


struct Add;


impl Tool for Add {
    const NAME: &'static str = "add";
    type Args = AddArgs;
    type Output = i64;
    type Error = std::convert::Infallible;


    fn description(&self) -> String {
        "Add x and y together".to_string()
    }


    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": { "x": { "type": "integer" }, "y": { "type": "integer" } },
            "required": ["x", "y"]
        })
    }


    async fn call(&self, _ctx: &mut ToolContext, args: AddArgs) -> Result<i64, Self::Error> {
        Ok(args.x + args.y)
    }
}


impl ToolEmbedding for Add {
    type InitError = InitError;
    type Context = ();
    type State = ();


    fn init(_state: (), _context: ()) -> Result<Self, InitError> {
        Ok(Add)
    }


    fn embedding_docs(&self) -> Vec<String> {
        vec!["Add x and y together".into(), "sum, plus, addition".into()]
    }


    fn context(&self) {}
}

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

将工具收集到 ToolSet 中,为它们的 schema 生成嵌入,再通过 .retrieved_tools(n, index, toolset) 接入索引:

rust
use rig::tool::ToolSet;


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


let mut toolset = ToolSet::default();
toolset.add_retrieved_tool(Add)?;


let embeddings = EmbeddingsBuilder::new(embedding_model.clone())
    .documents(toolset.schemas()?)?
    .build()
    .await?;
let index = InMemoryVectorStore::from_documents_with_id_f(embeddings, |tool| tool.name.clone())
    .index(embedding_model);


let agent = AgentBuilder::new(client.completion(openai::GPT_5_5))
    .preamble("You are a calculator.")
    .retrieved_tools(1, index, toolset)
    .build();

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

通过 .tool(..) 添加的静态工具始终会提供给模型;检索工具只有排在前 n 名时才会提供。完整程序见 rag_dynamic_tools 示例。

在 Agent 之间共享工具#

每个 Agent 的工具都保存在工具服务器中。你可以自行构建一个,让多个 Agent 共享同一组工具,或在 Agent 运行时增删工具:

rust
use rig::tool::server::ToolServer;


let tools = ToolServer::new().tool(ThinkTool).run();


let model = OpenAI::from_env()?.completion(openai::GPT_5_5);
let researcher = AgentBuilder::new(model.clone())
    .tool_server_handle(tools.clone())
    .build();
let writer = AgentBuilder::new(model)
    .tool_server_handle(tools.clone())
    .build();


// Changes to the server reach both agents.
tools.remove_tool("think");

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

句柄的克隆成本很低;只要还有任意一个克隆存在,服务器就会继续运行。

强制工具调用#

AgentBuilder::tool_choice(ToolChoice::Required) 会在每一轮强制调用工具,模型因此永远没有机会写出最终答案,运行最终会返回 PromptError::MaxTurns。只应将它用于单轮任务。若要只在首轮强制使用工具,然后让模型回答,应在检查 ctx.turn() 的钩子中设置该选项;参见请求补丁和 force_tool_first_turn 示例。

自行执行工具#

可以绕过 Agent 循环,在自己的代码中处理工具调用:通过原始补全请求发送工具定义,从响应中读取工具调用,再用 ToolSet 执行:

rust
use rig::completion::CompletionRequest;
use rig::message::{AssistantContent, Message};
use rig::tool::ToolSet;


let model = OpenAI::from_env()?.completion(openai::GPT_5_5);
let mut tools = ToolSet::default();
tools.add_tool(ThinkTool);


let request = CompletionRequest::new(Message::user("Think about 2 + 2, then answer."))
    .tools(tools.tool_definitions());
let response = model.call(request).await?;


for content in &response.choice {
    if let AssistantContent::ToolCall(call) = content {
        let args = serde_json::to_string(&call.function.arguments)?;
        let result = tools
            .execute(&call.function.name, args, &mut ToolContext::new())
            .await;
        println!("{} -> {}", call.function.name, result.output().render());
    }
}

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

ToolSet::execute 不会以自身调用失败的形式返回:它总会返回一个 ToolResult,表示成功、错误、拒绝或跳过;result.output() 保存模型应读取的内容。把它作为工具结果消息传回,再循环直到模型停止调用工具。完整循环见 manual_tool_calls 示例。

MCP 工具#

工具不必位于你的 crate 中。模型上下文协议让 Agent 能将其他进程提供的工具,与自己的工具一起使用,例如文件系统访问、浏览器、数据库和 SaaS 集成。Rig 的 MCP 支持位于 rig::tool::rmcp,通过 rmcp feature 启用。配置方法和完整示例见模型上下文协议。

API 参考(工具)

下一步#

智能体:将工具接入 Agent,运行多轮工具调用循环。

钩子:观察、改写、跳过或停止工具调用及其结果。

模型上下文协议:将外部 MCP 工具与自己的工具一起接入 Agent。

结构化输出:无需手写工具,就能从模型获取类型化数据。

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

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