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

AgentRunner

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

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

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

AgentRunner 是 agent.prompt(...) 的返回值,代表 Agent 循环的一次运行。它以 Agent 的配置为起点,接受单次运行设置;在你用 .await、.stream() 或 .run_channel() 驱动它之前,不会执行任何操作。

从最便捷到最底层,共有三层:

  • Agent 保存可复用配置:模型、系统提示词、工具、上下文、记忆和默认钩子。
  • AgentRunner 驱动一次提问经过 Agent 循环。它持有轮数预算、历史、记忆行为、工具并发数、工具上下文、请求覆盖项和额外钩子等单次运行设置。
  • AgentRun 是 runner 驱动的可序列化、无 I/O 状态机。只有在运行需要跨进程暂停和恢复时,才需要自行逐步推进它,参见持久化运行。

执行一次运行#

rust
use futures::StreamExt;
use rig::agent::MultiTurnStreamItem;
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};


#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
        .preamble("You are a helpful assistant.")
        .build();


    // Await the runner: run the loop to completion and get a `PromptResponse`.
    let response = agent
        .prompt("Find the answer and show your work.")
        .max_turns(5)
        .await?;


    println!("answer: {}", response.output());
    println!("model calls: {}", response.completion_calls.len());
    println!("tokens: {:?}", response.usage.total_tokens);


    // Or stream the same run: deltas and tool activity, then the final response.
    let mut stream = agent.prompt("Now explain it to a child.").max_turns(5).stream();
    while let Some(item) = stream.next().await {
        if let MultiTurnStreamItem::FinalResponse(done) = item? {
            println!("\n{}", done.output());
        }
    }


    Ok(())
}

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

runner 有三种执行方式。它们共用运行构建、工具执行、记忆处理、tracing span 和钩子,因此不管选择哪种,运行行为都一致;流式路径会额外产生流式增量事件。

调用方式 返回值 适用场景
.await 或 .run().await Result<PromptResponse, PromptError> 获取最终答案、用量和对话记录。
.stream() StreamingResult,即 MultiTurnStreamItem 事件流 实时接收文本、推理、工具调用和结果,参见流式输出。
.run_channel() 一个 future 和一个 RunEvents 事件源 应用程序有自己的异步执行器或定时更新循环(tick):在任意位置启动 future,在其他位置轮询事件。

agent.prompt_typed::<T>(p) 返回同一个 runner,只是输出变为类型化输出,参见结构化输出。agent.chat(p, &mut history) 相当于 prompt(p).history(..),再将本次运行的消息追加到 history。

单次运行设置#

循环#

方法 改变的内容
max_turns(n) 本次运行的模型调用总预算,包括首次调用和每次重试。超出时返回 PromptError::MaxTurns。默认使用 Agent 的 default_max_turns,未设置时为 1。
history(messages) 提问之前的聊天历史。本次运行会绕过对话记忆。
conversation(id) 加载和保存 Agent 记忆时使用的对话 ID。
without_memory() 禁用本次运行的记忆加载和保存。
add_hook(hook) 在 Agent 默认钩子之后追加钩子,参见钩子。
tool_concurrency(n) 同一模型轮次最多并发执行 n 个工具调用。默认 1;0 也按 1 处理。
tool_context(ctx) 类型化、仅供运行时使用的值,会克隆到每个工具调用中,绝不发送给模型。
max_invalid_tool_call_retries(n) 无效工具调用通过 Retry 恢复的次数预算。重试也计入 max_turns。
max_consecutive_malformed_tool_calls(n) 连续 n 轮出现不是 JSON 对象的工具参数后失败。默认不限制。
unhandled_invalid_tool_call(policy) 对没有钩子处理的未知或不允许的工具调用,选择 Fail(默认)或 Ignore。
using_model(label) / using_model_value(model) 为本次运行使用已注册模型路由或任意模型,参见在运行时选择模型。

请求#

AgentBuilder 上的每项请求设置,都可以为一次运行覆盖:preamble(..) / without_preamble(),document(..) / documents(..)(额外上下文),temperature(..) / without_temperature(),max_tokens(..) / without_max_tokens(),tool_choice(..) / without_tool_choice(),merge_additional_params(..) / replace_additional_params(..) / without_additional_params(),类型化生成选项(reasoning、cache、seed、top_p、stop、service_tier、verbosity、parallel_tool_calls),以及 provider_option(..)。

rust
let response = agent
    .prompt("Write a haiku about the borrow checker.")
    .preamble("You are a poet. Answer with the poem only.")
    .temperature(1.0)
    .max_tokens(200)
    .await?;

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

这些设置作用于本次运行中的每一次模型调用。如果只想更改某一轮,例如仅首轮,请改为从钩子返回请求补丁。

轮数与无效工具调用#

max_turns 是 Agent 循环的安全边界,精确规定本次运行允许的模型调用次数。先调用工具再回答至少需要 2 次。如果模型持续调用工具直到超出预算,运行会返回 PromptError::MaxTurns,其中携带截至当时积累的历史。

Rig 无法分派的工具调用,例如未知名称或当前 ToolChoice 不允许的工具,默认会让运行返回 PromptError::UnknownToolCall,除非钩子处理了它,或者设置 unhandled_invalid_tool_call(UnhandledInvalidToolCall::Ignore) 将这些调用丢弃并继续。max_invalid_tool_call_retries 只在钩子用 Retry 处理调用时生效。钩子侧的恢复方式见钩子。

对话记忆#

如果 Agent 有记忆存储,runner 会在第一次模型调用前加载历史,并在成功结束后保存本轮消息。.conversation(name) 指定日志名称;未指定时使用 Agent 的名称,匿名 Agent 默认使用 agent。共享存储的不同用户应使用不同名称。

rust
use rig::{AgentBuilder, completion::PromptError};
use rig::memory::MemoryStore;
use rig::providers::openai::{self, OpenAI};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
        .memory(MemoryStore::default()).build();
    match agent.prompt("What did I ask earlier?").conversation("user-42").await {
        Ok(response) => println!("{}", response.output()),
        Err(error) => {
            if let PromptError::Memory { error: store_error, response } = &error {
                eprintln!("conversation persistence failed: {store_error}");
                if let Some(finished) = response {
                    eprintln!("finished answer (save not confirmed): {}", finished.output());
                    // Recover/reconcile persistence; do not repeat a tool-using run blindly.
                } else {
                    eprintln!("history could not be loaded; the model was not called");
                }
            }
            return Err(error.into());
        }
    }
    Ok(())
}

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

加载或保存失败都返回 Err(PromptError::Memory { error, response })。加载失败时 response 为 None,模型未调用;保存失败时其中保留已完成的响应,但不能宣称保存成功。先核对存储状态并恢复写入,避免直接重跑已经执行过工具的请求。传入 .history(..) 或 .without_memory() 会绕过记忆加载和保存。参见记忆。

工具并发#

模型在一轮内生成多个工具调用时,runner 可以并发执行它们:

rust
let response = agent
    .prompt("Check inventory, shipping, and pricing.")
    .max_turns(3)
    .tool_concurrency(3)
    .await?;

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

提交到历史中的调用仍保持模型生成时的顺序。当 tool_concurrency > 1 时,日志、span 和钩子回调等副作用可能交错发生,因此必须保证它们可以安全并发执行。

工具上下文#

tool_context 将仅供运行时使用的值传给工具,例如租户 ID、认证 token、请求元数据,以及其他不应让模型看到的数据。每种值类型声明一个稳定的键;工具从 call 收到的 ToolContext 中读取这些值。

rust
use rig::tool::ToolContext;


#[derive(serde::Serialize, serde::Deserialize, rig::ContextValue)]
#[context(key = "tenant_id")]
struct TenantId(String);


let mut context = ToolContext::new();
context.insert(TenantId("acme".into()))?;


let response = agent
    .prompt("Update my account preferences.")
    .tool_context(context)
    .await?;

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

在工具内部,用 ctx.get::<TenantId>()? 或 ctx.require::<TenantId>()? 读回该值。不要为了让工具读到机密,就把机密放进提示词。工具侧用法见工具上下文。

恢复持久化的运行#

agent.resume(run) 返回一个 runner,用于继续执行序列化后的 AgentRun,而不是从一次提问开始。运行中已持久化的内容以该运行自身为准,包括提问、历史和轮数预算;Agent 与 runner 则提供模型、工具、钩子和请求设置。待处理的工具调用会使用 Agent 的工具执行,然后循环照常继续:

rust
let run: rig::AgentRun = serde_json::from_str(&saved)?;
let response = agent.resume(run).tool_concurrency(4).await?;

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

恢复的运行不会加载或保存对话记忆,这由负责持久化该运行的调用方处理。如何生成可持久化的运行,参见持久化运行。

另请参阅#

  • 智能体:构建 Agent,理解 runner 驱动的循环。
  • 钩子:观察并控制 runner 事件。
  • 持久化运行:自行逐步执行、暂停和恢复循环。
  • 工具:定义 runner 执行的工具。
  • 记忆:conversation(..) 使用的对话记忆。
  • 流式输出:消费流式运行。

钩子:观察并控制提问、模型调用、工具调用和结果。

持久化运行:暂停运行以等待审批,持久化保存后再恢复。

流式输出:流式执行运行,无需等待完整响应。

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

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