Agent 是 Rig 中使用大语言模型的主要构建单元。它把补全模型、系统提示词、可选的上下文文档和一组工具组合在一起,并替你运行 Agent 循环:把问题发给模型,执行模型调用的工具,将结果传回模型,然后重复这一过程,直到模型给出答案。只要你希望调用模型而不手写这个循环,就可以使用 Agent——从简单聊天机器人,到会使用工具的助手,再到 RAG 系统,都适用。
开始之前
- 给项目添加
rig和tokio,参见安装。 - 导出模型服务商的 API Key(如
OPENAI_API_KEY),确保OpenAI::from_env()能成功执行。 - 了解模型生成这一层会有帮助,但不是前提。
最小 Agent#
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let model = OpenAI::from_env()?.completion(openai::GPT_5_5);
let agent = AgentBuilder::new(model)
.preamble("You are a helpful assistant.")
.temperature(0.7)
.build();
let response = agent.prompt("Hello!").await?;
println!("{}", response.output());
Ok(())
}Hello! How can I help you today?使用 AgentBuilder::new(model)...build() 构建 Agent,再用 agent.prompt(...).await? 运行。结果是一个 PromptResponse;output() 以 String 返回最终答案。响应也实现了 Display,所以 println!("{response}") 会打印相同的文本。本页其余内容都是在此基础上添加的可选配置。
Agent 由什么组成#
AgentBuilder 收集每次调用这个 Agent 时共用的配置:
- 模型与请求设置:补全模型、系统提示词(
preamble)、temperature和max_tokens等采样参数、reasoning(..)等跨服务商通用的生成选项,以及默认调用轮数上限(default_max_turns)。 - 上下文:添加到每次请求中的文档。静态上下文始终发送;动态上下文在每次提问时从向量存储中检索。
- 工具:模型可以调用的能力。静态工具始终提供给模型;检索工具则在每次提问时从向量存储中选取。
- 对话记忆(可选):在每次提问前加载历史、结束后保存新一轮消息的后端。参见对话。
- 默认钩子(可选):用于观察或控制每次运行的代码。参见钩子。
Agent 实现了 Clone,也可以安全地在任务间共享(Send + Sync + 'static),因此构建一次即可重复使用。
Agent 循环如何工作#
Agent 的所有操作都在一个循环中完成。向它提问后,Rig 会:
- 构建补全请求,组合系统提示词、静态上下文、从向量存储检索的动态上下文、对话历史,以及所有可用工具的定义。
- 发送给模型。一次模型调用就是一轮(turn)。
- 检查响应。
- 如果模型返回文本,循环结束,该文本就是结果。
- 如果模型请求调用工具,Rig 就逐个执行:将 JSON 参数解析成你的
Args类型,运行你的call实现,再把结果作为工具结果消息追加到对话中。模型可以在一轮内请求调用多个工具;Rig 执行后会把所有结果一起返回。 - 带着更新后的历史回到第 2 步,让模型使用工具结果,直到它生成文本答案或耗尽轮数预算。
flowchart TD
P["agent.prompt(...)"] --> M["Send request to model<br/>(preamble + context + history + tools)"]
M --> D{"Model response"}
D -- "text" --> F["Return the answer"]
D -- "tool calls" --> T["Rig executes the tools,<br/>appends results to history"]
T --> B{"Turn budget left?"}
B -- "yes" --> M
B -- "no" --> E["Err(PromptError::MaxTurns)"]本文档将其称为 Agent 循环;其他地方也可能叫“工具调用循环”,指的是同一件事。
轮数预算#
轮数预算用于防止 Agent 无限循环:每一轮都有延迟和 token 成本,因此循环不能无限执行。max_turns 是一次运行允许发起的模型调用总次数,包括首次调用、每轮工具结果之后的调用,以及每次重试。
默认预算为 1,即 Agent 调用模型一次。普通问答用一次就够了,但先调用工具再回答至少需要 2 次。如果模型尚未回答,预算就耗尽,提问会返回 PromptError::MaxTurns。这个错误携带截至当时积累的历史,方便你检查发生了什么。
可以用 .max_turns(n) 为一次提问设置预算,也可以用 AgentBuilder::default_max_turns(n) 为所有提问设置默认值:
let response = tool_agent
.prompt("Please calculate 2 + 5, then multiply the result by 3")
.max_turns(5) // two rounds of tool calls plus the answer, with room to spare
.await?;
println!("{response}");2 + 5 = 7, and 7 × 3 = 21.Rig 不限制上限,但应按照实际预期的最长工具调用链选择数值,让困惑的模型尽快失败,而不是持续消耗 token。错误处理方式见错误处理。
工具调用出错时#
有两种不同的失败情况,行为也不同:
- 你的工具返回错误。 运行不会结束:Rig 把失败的工具结果传给模型,循环继续,让模型重试或解释失败原因。默认情况下,模型只会收到笼统的反馈(
the tool failed);如果希望提供有用的信息,可返回ToolExecutionError或覆盖map_error。参见工具失败时。 - 模型生成了 Rig 无法分派的调用:例如不存在的工具名、当前
ToolChoice不允许的工具,或者参数不是 JSON 对象。默认情况下,未知或不允许的工具会让提问返回PromptError::UnknownToolCall;格式错误的参数则会收到纠正反馈,让模型再试一次。如果希望从未知工具名中恢复,例如带反馈重试、修复名称或跳过调用,可以在钩子中实现on_invalid_tool_call。
若要自行观察、改写或否决单个工具调用,用于日志、审批流程或防护规则,请使用钩子。
提问与响应#
agent.prompt(p) 此时还不会发送任何内容,它返回用于一次运行的 AgentRunner。可以链式设置本次运行的选项,再选择执行方式:
.await(或.run().await)运行整个循环直至完成,返回PromptResponse。.stream()在事件发生时产生文本增量、工具调用、工具结果和最终响应,参见流式输出。
PromptResponse 不只有文本。你可以用它控制预算、制作仪表盘、按用户计量,或继续对话:
let response = agent.prompt("What is 2 + 2?").max_turns(3).await?;
println!("answer: {}", response.output());
println!(
"tokens: {:?} in / {:?} out across {} model calls",
response.usage.input_tokens,
response.usage.output_tokens,
response.requests(),
);
println!("messages produced by this run: {}", response.messages.len());answer: 2 + 2 = 4.
tokens: Some(28) in / Some(12) out across 1 model calls
messages produced by this run: 2usage汇总循环中所有轮次的 token 用量。每项计数都是Option:None表示服务商没有报告该数值。completion_calls按模型调用拆分用量,最后一项可以看出最终请求的上下文有多大;同时还包含每次调用的结束原因和原始服务商响应。messages包含本次运行提交的消息:提问、工具调用和结果,以及答案,可以直接追加到你维护的历史中。content保存最终助手轮次的结构化内容,适合需要文本以外信息的场景。
这些数值也会记录到 tracing span 中,参见可观测性。
对话#
Agent 是无状态的:除非你提供前面的对话轮次,否则每次提问都从头开始。你可以:
- 用
agent.prompt(p).history(history)自行传入历史,并从response.messages记录新一轮消息; - 使用
agent.chat(p, &mut history):它发送历史,并在成功后把本次运行的消息追加到历史中; - 在构建器上使用
.memory(backend)接入对话记忆,并在提问时使用.conversation(id),让 Rig 替你加载、保存每个对话的历史。
记忆介绍了这三种方式,以及持久化后端和限制历史增长的策略。现成的对话 REPL 见构建命令行聊天机器人。
结构化输出#
如果需要类型化的值而不是文本,使用 prompt_typed::<T>()。Rig 会将 T 的 JSON Schema 作为本次运行的结构化输出 schema 发送给服务商;支持原生结构化输出的服务商会据此约束响应,然后 Rig 将最终答案反序列化:
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct Forecast {
city: String,
temperature_f: f64,
}
let forecast: Forecast = agent
.prompt_typed::<Forecast>("Give me a plausible forecast for New York.")
.retries(1) // re-run once if the output doesn't parse as `Forecast`
.await?
.output;
println!("{} will be {}°F", forecast.city, forecast.temperature_f);类型化运行支持与 prompt 相同的单次运行设置。它返回 TypedPromptResponse<T>,其中包含解析后的 output,以及 usage、completion_calls 和 messages;失败则返回 StructuredOutputError。若要将 schema 固定在 Agent 上,使用 AgentBuilder::output_schema::<T>(),再通过 output_mode(OutputMode::..) 选择把 schema 传给服务商的方式。面向信息提取的 Agent 见提取器。
上下文#
Agent 可以自动为每次模型请求添加上下文:
- 静态上下文(
AgentBuilder::context(text))附加到每次请求,适合少量固定参考资料。 - 动态上下文(
AgentBuilder::dynamic_context(n, index))在每次模型调用前,从向量存储检索最相关的n个文档并附加到请求。这就是 RAG;向量存储与 RAG介绍了索引构建和完整 Agent 示例。
工具#
如 Agent 循环所述,Agent 会自动解析工具调用、执行工具,并把结果传回模型。在构建器上接入工具:
.tool(t):实现Tooltrait 的静态工具,始终提供给模型。.dynamic_tool(t)/.dynamic_tools(ts):在运行时以DynamicTool值定义的工具。.retrieved_tools(n, index, toolset):每次提问时从向量存储检索工具,只提供最相关的n个。
let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
.preamble("You are a calculator. Use the tools to compute results.")
.tool(Add)
.default_max_turns(3) // tool call(s), then the answer
.build();
let response = agent.prompt("What is 2 + 5?").await?;工具的编写、运行时上下文的传递和检索配置见工具。
用 ToolChoice 控制工具使用#
默认情况下,模型自由决定调用工具还是直接回答。需要约束这种行为时,可以在构建器上设置 ToolChoice,或者在提问时用 .tool_choice(..) 为本次运行设置:
use rig::message::ToolChoice;
let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
.preamble("You are a calculator. Always compute with tools, never in your head.")
.tool_choice(ToolChoice::Required) // the model must call a tool before answering
.build();ToolChoice::Auto:默认值,模型可以调用工具,也可以直接回答。ToolChoice::None:工具可见,但不得调用。ToolChoice::Required:模型必须调用至少一个工具。ToolChoice::Specific { function_names }:模型必须调用指定名称中的某个工具。
在 Agent 上设置的 ToolChoice 会作用于每一轮,因此 Required 会持续强制调用工具,模型永远不会得到一个可以停下来回答的轮次。如果只想强制第一步,例如回答前总是先搜索,请通过钩子修改首轮请求,参见请求补丁。
把 Agent 作为工具#
一个 Agent 可以作为工具交给另一个 Agent。这是管理者—工作者模式的基础:协调 Agent 像调用其他工具一样,调用专门的工作 Agent,将子任务交给它们。
agent.into_tool()? 将 Agent 转成 DynamicTool。它接收一个 prompt 字符串,向 Agent 提问,再返回答案。工具使用 Agent 的 name 作为名称;没有名称时使用 agent_tool。工具描述包含 Agent 的 description 和系统提示词,因此应为工作 Agent 同时设置这两项:
let model = OpenAI::from_env()?.completion(openai::GPT_5_5).erase();
// The worker: a specialised sub-agent.
let bob = AgentBuilder::new(model.clone())
.name("bob")
.description("An employee who handles admin tasks at FooBar Inc.")
.preamble("You are Bob, an admin employee. Your manager Alice may ask you to do things.")
.build();
// The manager: prompts Bob by calling him as a tool.
let alice = AgentBuilder::new(model)
.name("alice")
.preamble("You are Alice, a manager in the admin department. You manage Bob.")
.dynamic_tool(bob.into_tool()?)
.build();
let response = alice
.prompt("Ask Bob to draft a welcome email and tell me what he wrote.")
.max_turns(3)
.await?;
println!("{response}");erase() 将模型转为类型擦除后的 DynModel,这样同一个句柄就可以克隆后交给多个 Agent。工作 Agent 使用自己的轮数预算(default_max_turns),工具调用则继承管理 Agent 的工具上下文。群体式和基于 actor 的架构见多 Agent 系统。
在运行时选择模型#
一个 Agent 可以持有多个模型,并在每次模型调用时选择其一。用 AgentBuilder::named_model(label, model) 和 .model_route(label, model) 为模型注册标签,再按标签选择:
- 为整次运行选择:在提问上调用
.using_model("label"); - 为单次模型调用选择:在钩子的
on_model_select中返回ModelSelectionAction::select("label")。
use rig::agent::{AgentHook, HookContext, ModelSelection, ModelSelectionAction};
/// A cheap model for the first call; the stronger one once tool results are in.
struct CheapFirst;
impl AgentHook for CheapFirst {
fn on_model_select(&self, ctx: &HookContext, _event: ModelSelection<'_>) -> ModelSelectionAction {
if ctx.turn() == 1 {
ModelSelectionAction::select("fast")
} else {
ModelSelectionAction::select("strong")
}
}
}
let client = OpenAI::from_env()?;
let agent = AgentBuilder::named_model("fast", client.completion(openai::GPT_5_4_MINI))
.model_route("strong", client.completion(openai::GPT_5_5))
.add_hook(CheapFirst)
.build();
// Or skip the hook and pick one model for a whole run:
let response = agent.prompt("Summarize Rust's ownership rules.").using_model("strong").await?;要更改现有 Agent 的默认模型,可调用 agent.set_model(model),或者使用按值接收 Agent 的 with_model(model),换入任意模型;set_model_label("label") 则切换到已经注册的路由。模型选择策略见模型路由。
附加参数#
推理强度、缓存和随机种子等常用选项,在构建器上都有类型化设置方法,例如 .reasoning(Effort::High)、.cache(..)、.seed(..) 等。每个服务商会明确映射这些设置或拒绝它们。对于 Rig 尚未建模的服务商参数,可用 AgentBuilder::additional_params() 传入原始 JSON,它会合并到每次补全请求中:
use rig::completion::Effort;
let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
.preamble("You are a helpful agent.")
.reasoning(Effort::High)
.additional_params(json!({ "user": "user-42" }))
.build();运行与钩子#
每次提问都由 AgentRunner 驱动。它持有该次运行专属的内容:轮数预算、历史、记忆、工具并发数与上下文、单次运行的请求覆盖项和钩子。钩子让你的代码观察并控制循环的每一步:改写提问、修改请求、选择模型、重试响应、批准或拒绝工具调用、改写工具结果,或停止运行。使用 AgentBuilder::add_hook 为所有运行安装钩子,或在提问上调用 .add_hook(..),只为一次运行添加。
如果运行需要跨越进程生命周期,例如等待数小时由人工批准工具调用,请自行逐步推进可序列化的 AgentRun 状态机。
使用 Agent,还是手写工作流?#
Agent 让模型决定控制流程,适合无法预先确定步骤的开放式任务。如果步骤已经明确,用普通 Rust 按顺序调用 Agent 更简单、更便宜,流程也更确定。如何选择,参见工作流页面中的 Agent 还是工作流?。
另请参阅#
- 模型生成:Agent 下方的模型层
- AgentRunner:单次运行设置和执行方式
- 钩子:观察并控制 Agent 运行
- 持久化运行:自行逐步执行、暂停和恢复 Agent 循环
- 工具:用可调用函数扩展 Agent
- 记忆:对话历史、压缩和长期记忆
- 流式输出:逐 token 输出 Agent 响应
- 错误处理:处理
PromptError::MaxTurns和暂时性故障 - 构建 RAG 系统:完整的检索增强 Agent
下一步#
AgentRunner:调整单次运行设置,选择运行的执行方式。
钩子:观察并控制提问、模型调用、工具调用和结果。
工具:编写可调用函数,为 Agent 配置静态工具和检索工具。
记忆:用策略限制对话历史,并跨会话保存。
流式输出:逐 token 输出 Agent 响应,无需等待完整回复。
向量存储与 RAG:用向量存储支持 dynamic_context,构建检索增强 Agent。