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

钩子(Hooks)

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

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

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

AgentRunner 驱动模型调用和工具执行时,钩子让你的代码观察并控制 Agent 循环。它们可用于日志、指标、审计记录、审批流程、防护规则、逐轮请求修改、模型路由、响应重试、无效工具调用恢复,以及流式 UI 集成。

钩子是实现 AgentHook 的类型。这个 trait 为每类事件提供一个方法,每个方法都有让运行继续的默认实现,因此你只需实现关心的事件。每个方法返回一个动作类型,告诉运行接下来该做什么。

添加钩子#

为一次运行添加钩子,就在提问上设置;为所有运行添加,则在 Agent 构建器上设置:

rust
use rig::agent::{AgentHook, DispatchAction, DispatchEvent, HookContext};


struct ToolAudit;


impl AgentHook for ToolAudit {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        // `on_dispatch` fires for model calls too; only log tool calls.
        if let (Some(name), Some(args)) = (event.tool_name(), event.tool_args()) {
            println!("calling {name} with {args}");
        }
        DispatchAction::proceed()
    }
}


// Every run of this agent is audited...
let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
    .add_hook(ToolAudit)
    .build();


// ...and this one run gets an extra hook on top.
let response = agent
    .prompt("Check the account balance, then summarize it.")
    .max_turns(3)
    .add_hook(ToolAudit)
    .await?;

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

钩子按注册顺序执行:先执行 Agent 的钩子,再执行本次运行的钩子。多个钩子的结果如何组合取决于事件,参见组合钩子。

事件与动作#

方法 触发时机 返回类型 钩子可以做什么
on_run_start 第一次模型调用之前,只触发一次 RunStartAction continue_run()、rewrite(prompt)、stop(reason)
on_completion_call 每次模型请求之前 CompletionCallAction continue_run()、用 patch(RequestPatch) 修改本轮请求、stop(reason)
on_model_select 补全调用钩子之后、每次模型请求之前,同步执行 ModelSelectionAction continue_run()、select(label)、stop(reason)
on_model_turn_finished 收到每个模型轮次后、执行工具或结束运行之前 ModelTurnAction continue_run()、repeat()、retry_with_feedback(text)、stop(reason)
on_invalid_tool_call 模型调用未知或不允许的工具,或发送了不是 JSON 对象的参数 Option<InvalidToolCallAction> 用 None 留给后续钩子处理,或返回 fail()、retry(feedback)、repair(name)、skip(reason)、stop(reason)
on_dispatch 模型调用或工具调用执行前 DispatchAction proceed()、skip(reason)(工具调用)、stop(reason)、rewrite_tool_args(..)、patch(..)、deny(report)
on_outcome 模型调用或工具调用返回后 OutcomeAction proceed()、rewrite_tool_result(..)、rewrite_tool_output(..)、replace(..)、stop(reason)
on_text_delta 仅流式运行:每个文本片段 ObservationAction continue_run()、stop(reason)
on_reasoning_delta 仅流式运行:每个推理片段 ObservationAction continue_run()、stop(reason)
on_tool_call_delta 仅流式运行:每个工具调用参数片段 ObservationAction continue_run()、stop(reason)
on_run_settled 运行以响应或错误结束时,只触发一次 () 只能观察

任何事件返回 stop(reason) 都会以 PromptError::Cancelled 结束运行,错误中携带截至当时的历史。等待完整结果的运行与流式运行触发相同的事件;流式运行额外增加三个增量事件,其中内容在模型轮次被接受之前都只是暂定内容。

每个方法都会收到包含本次运行信息的 HookContext:

  • run_id()、turn()(从 1 开始的模型调用序号)、is_streaming() 和 agent_name();
  • scratchpad():本次运行所有钩子共享的类型化内存状态,例如重试计数器;
  • append_entry(kind, &value) / entries(kind) / last_entry(kind):保存在运行可序列化状态中的记录。持久化运行恢复后,钩子能看到暂停前保存的条目。

请求补丁#

在 on_completion_call 中返回 CompletionCallAction::patch,就能修改某一轮的请求而不改变 Agent:例如在首轮强制使用工具、为关键步骤降低温度、缩小提供给模型的工具范围、添加上下文文档,或替换本轮发送的历史。

rust
use rig::agent::{AgentHook, CompletionCallAction, CompletionCallEvent, HookContext, RequestPatch};
use rig::message::ToolChoice;


struct SearchFirst;


impl AgentHook for SearchFirst {
    async fn on_completion_call(
        &self,
        ctx: &HookContext,
        _event: CompletionCallEvent<'_>,
    ) -> CompletionCallAction {
        if ctx.turn() == 1 {
            CompletionCallAction::patch(
                RequestPatch::new()
                    .active_tools(["search_web"])
                    .tool_choice(ToolChoice::Required)
                    .temperature(0.0),
            )
        } else {
            CompletionCallAction::continue_run()
        }
    }
}

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

补丁只作用于一轮,不会持续生效:每一轮都会再次触发这个事件。这就是示例检查 ctx.turn() 的原因。如果钩子每轮都设置 ToolChoice::Required,模型就永远不能停止调用工具并给出答案,运行最终会以 PromptError::MaxTurns 结束。

RequestPatch 可以设置 preamble、temperature、max_tokens、tool_choice、active_tools(对模型公开的工具允许列表)、additional_params(浅合并到 Agent 的同名参数)、context / extra_context(为本轮添加的文档),以及 history。如果缩小了 active_tools,请确保 tool_choice 指定的工具仍在提供给模型的工具中。

选择模型#

on_model_select 按注册标签选择下一次调用使用哪个模型。标签通过 AgentBuilder::named_model 或 model_route 注册。事件携带 default_model、目前的 selected_model,以及上次调用所用的 previous_model,因此钩子可以在失败后回退到其他模型,或在收到工具结果后升级模型。它是同步方法:依据事件、上下文和 scratchpad 做决定,不执行 I/O。完整示例见在运行时选择模型。

重试响应#

在 Rig 对模型轮次采取行动前,on_model_turn_finished 能看到该轮的内容、用量、结束原因和原始服务商响应。拒绝不含工具调用的轮次,可以让模型重新回答:

  • ModelTurnAction::repeat() 丢弃响应,使用相同的提问和历史再次请求。
  • ModelTurnAction::retry_with_feedback(text) 保留响应,并把你的反馈作为用户消息加入,让模型自行纠正。
rust
use rig::agent::{AgentHook, HookContext, ModelTurnAction, ModelTurnFinished};
use rig::completion::FinishReason;


/// Ask for a shorter answer when the model ran out of output tokens, at most twice.
struct RetryTruncated;


#[derive(Clone, Default)]
struct Retries(usize);


impl AgentHook for RetryTruncated {
    async fn on_model_turn_finished(
        &self,
        ctx: &HookContext,
        event: ModelTurnFinished<'_>,
    ) -> ModelTurnAction {
        if event.finish_reason != Some(&FinishReason::Length) {
            return ModelTurnAction::continue_run();
        }
        let attempt = ctx.scratchpad().update(|retries: &mut Retries| {
            retries.0 += 1;
            retries.0
        });
        if attempt > 2 {
            return ModelTurnAction::stop("response kept getting truncated");
        }
        ModelTurnAction::retry_with_feedback("That was cut off. Answer again, more briefly.")
    }
}

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

每次重试都是一次模型调用,会计入 max_turns,因此要为重试预留预算。Rig 没有单独的重试次数限制,可以像上例一样在 scratchpad 中自行计数。重试含有工具调用的轮次会被拒绝;应改用 on_dispatch 控制这些调用。

工具调用:审批与防护规则#

on_dispatch 在每次模型调用和工具调用执行之前运行。对于工具调用,event.tool_name() 和 event.tool_args() 返回调用信息,由钩子决定:

  • DispatchAction::proceed():执行工具。
  • DispatchAction::skip(reason):不执行工具;模型会收到以 reason 为内容的工具结果,并可据此调整。
  • DispatchAction::rewrite_tool_args(event.kind, args):使用替换后的 JSON 参数执行。
  • DispatchAction::stop(reason):结束运行。
rust
use rig::agent::{AgentHook, DispatchAction, DispatchEvent, HookContext};


struct TransferPolicy {
    max_auto_transfer: u64,
}


impl AgentHook for TransferPolicy {
    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        let (Some(tool_name), Some(args)) = (event.tool_name(), event.tool_args()) else {
            return DispatchAction::proceed(); // not a tool call
        };
        if tool_name != "transfer_funds" {
            return DispatchAction::proceed();
        }


        let amount = serde_json::from_str::<serde_json::Value>(args)
            .ok()
            .and_then(|v| v.get("amount").and_then(|a| a.as_u64()));


        match amount {
            Some(n) if n <= self.max_auto_transfer => DispatchAction::proceed(),
            Some(n) => DispatchAction::skip(format!(
                "denied by policy: ${n} exceeds the ${} automatic transfer limit",
                self.max_auto_transfer
            )),
            None => DispatchAction::skip("denied by policy: missing transfer amount"),
        }
    }
}

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

钩子是异步的,因此 on_dispatch 也可以等待人工决策:打印调用,读取批准、拒绝或编辑的回答,再返回对应动作。这类检查应采用默认拒绝策略:没有回答或回答不明确,都按拒绝处理,绝不视为批准。进程内审批只能存续于正在运行的任务中;如果决策可能花费数小时,或来自其他进程,应改为持久化该运行,参见持久化运行。Rig 的 agent_with_approval_policy 和 agent_with_human_in_the_loop 示例完整展示了这两种进程内审批方式。

钩子中的防护规则属于用户体验和策略控制,并不是安全边界。真正的授权也必须在工具内部或其背后的服务中执行。

工具结果#

on_outcome 在模型调用或工具调用返回后运行。对于工具调用,event.tool_result() 提供结果,OutcomeAction::rewrite_tool_result(&event, text) 则替换模型看到的内容,用于脱敏、截断或规范化输出:

rust
use rig::agent::{AgentHook, HookContext, OutcomeAction, OutcomeEvent};


struct TruncateResults;


impl AgentHook for TruncateResults {
    async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
        let Some(result) = event.tool_result() else {
            return OutcomeAction::proceed(); // a model response, or a failed call
        };
        let text = result.output().render();
        if text.len() <= 4_000 {
            return OutcomeAction::proceed();
        }
        let cut = text.char_indices().nth(4_000).map_or(text.len(), |(i, _)| i);
        OutcomeAction::rewrite_tool_result(&event, format!("{}… [truncated]", &text[..cut]))
    }
}

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

对于模型调用,event.completion() 返回服务商响应,包括内容、用量和响应 ID;适合在这里记录原始响应或计量。

无效工具调用#

模型调用未知工具、本轮 ToolChoice 不允许的工具,或发送了不是 JSON 对象的参数时,会触发 on_invalid_tool_call。InvalidToolCallContext 携带生成的 tool_name、args、available_tools、reason 和历史。返回 None 可把决定留给下一个钩子,也可以返回动作:

rust
use rig::agent::{
    AgentHook, HookContext, InvalidToolCallAction, InvalidToolCallContext, InvalidToolCallReason,
};


struct RepairDefaultApi;


impl AgentHook for RepairDefaultApi {
    async fn on_invalid_tool_call(
        &self,
        _ctx: &HookContext,
        event: &InvalidToolCallContext,
    ) -> Option<InvalidToolCallAction> {
        match event.reason {
            InvalidToolCallReason::UnknownTool if event.tool_name == "default_api" => {
                Some(InvalidToolCallAction::repair("search_web"))
            }
            InvalidToolCallReason::UnknownTool => Some(InvalidToolCallAction::retry(format!(
                "Use one of these tools: {:?}",
                event.available_tools
            ))),
            _ => None,
        }
    }
}

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

  • fail() 使运行以 PromptError::UnknownToolCall 失败。
  • retry(feedback) 加入纠正反馈,再次请求模型。需要在本次运行上用 max_invalid_tool_call_retries(n) 允许重试;每次重试也会计入 max_turns。
  • repair(tool_name) 改写工具名,并再次对照允许的工具检查。
  • skip(reason) 不执行任何操作,直接以 reason 回答该调用。此时 Rig 也不会执行本轮的其他工具调用,而是将它们回答为未执行。
  • stop(reason) 结束运行。

如果所有钩子都返回 None,未知或不允许的工具会导致运行失败;若设置了 unhandled_invalid_tool_call(UnhandledInvalidToolCall::Ignore),则会被丢弃。格式错误的参数会收到指出问题的反馈。格式错误的参数不能通过修复名称解决,因此返回 repair 前应先检查 event.reason。

流式增量#

在流式运行中,on_text_delta、on_reasoning_delta 和 on_tool_call_delta 会在每个片段到来时触发。每个事件携带新的 delta,以及该部分目前累积的 aggregated 文本,方便实时更新 UI,或停止输出违反内容策略的运行。在模型轮次被接受前,增量都是暂定内容。如何直接消费事件流,见流式输出。

组合钩子#

钩子按注册顺序执行,各事件用适合自身的方式组合结果:

  • 链式传递:on_run_start 的改写、on_model_select 的选择,以及 on_dispatch / on_outcome 的改写,都会传递给下一钩子;后者看到的是更新后的提问、模型、参数或结果。最后一次修改生效;停止或拒绝会终止整条链。
  • 合并:所有钩子返回的 on_completion_call 补丁按顺序合并,因此上下文钩子和采样钩子都能生效。停止会终止这个过程。
  • 首个决定生效:对于 on_model_turn_finished、on_invalid_tool_call 和增量事件,第一个返回非继续动作(或非 None)的钩子做出决定,后续钩子不会再收到该事件。
  • 全部观察:on_run_settled 会执行每一个钩子。

如果多个策略必须组合成一个决定,应在同一个钩子内部组合它们。

用 observes 选择要接收的事件#

observes(kind) 告诉 Rig 钩子关心哪些事件。在 0.46.0 中,默认订阅除嵌入、重排序、检索和自定义操作分派之外的事件。记忆读写由存储接口处理,不属于这里的分派事件。可以覆盖 observes 订阅上述默认排除的四类事件,也可以让 Rig 跳过钩子不关心的高频事件,减少工作:

rust
use rig::agent::{AgentHook, DispatchAction, DispatchEvent, HookContext, StepEventKind};


struct ToolOnlyHook;


impl AgentHook for ToolOnlyHook {
    fn observes(&self, kind: StepEventKind) -> bool {
        matches!(kind, StepEventKind::ToolDispatch)
    }


    async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
        if let Some(name) = event.tool_name() {
            println!("tool: {name}");
        }
        DispatchAction::proceed()
    }
}

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

如果钩子对 ToolDispatch 或 CompletionDispatch 返回 false,这些分派发生时就完全不会调用它,因此它也无法对它们设置关卡。请保留钩子需要控制的事件种类。

最佳实践#

  • 保持钩子轻量。钩子在执行流程中被直接等待,因此缓慢的钩子会推迟下一次模型调用或工具执行。
  • 将繁重的日志处理、网络写入和审计持久化交给后台任务。
  • 使用 tool_concurrency > 1 时,确保钩子状态能安全共享;单次运行的状态应放在 scratchpad 中,不应放进钩子结构体。
  • 将钩子防护规则视为用户体验和策略控制,而不是授权边界。
  • 多条规则需要产生一个决定时,优先使用一个组合策略钩子。

另请参阅#

AgentRunner:配置触发钩子的单次运行驱动器。

持久化运行:暂停运行等待审批,稍后恢复。

流式输出:将钩子与流式文本、工具调用增量结合使用。

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

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