agent_base/engine/
tool_enforcement.rs1use async_trait::async_trait;
2
3use crate::engine::middleware::{Middleware, PostLlmCtx};
4use crate::types::AgentResult;
5
6pub struct ToolEnforcementConfig {
7 pub max_nudges: usize,
8 pub nudge_message: String,
9 pub first_turn_only: bool,
10 pub min_tools_threshold: usize,
11}
12
13impl Default for ToolEnforcementConfig {
14 fn default() -> Self {
15 Self {
16 max_nudges: 3,
17 nudge_message: "CRITICAL: You have tools available but did not call any. \
18 Call the appropriate tool NOW. \
19 关键提示:你有可用的工具但没有调用。立即使用工具执行。"
20 .to_string(),
21 first_turn_only: true,
22 min_tools_threshold: 1,
23 }
24 }
25}
26
27pub struct ToolEnforcementMiddleware {
28 config: ToolEnforcementConfig,
29}
30
31impl ToolEnforcementMiddleware {
32 pub fn new(config: ToolEnforcementConfig) -> Self {
33 Self { config }
34 }
35}
36
37#[async_trait]
38impl Middleware for ToolEnforcementMiddleware {
39 async fn on_post_llm(&self, ctx: &mut PostLlmCtx) -> AgentResult<()> {
40 if ctx.available_tools.len() < self.config.min_tools_threshold {
41 return Ok(());
42 }
43 if self.config.first_turn_only && ctx.total_tool_calls > 0 {
44 return Ok(());
45 }
46 if ctx.is_tool_call {
47 return Ok(());
48 }
49 if ctx.full_text.is_empty() {
50 return Ok(());
51 }
52
53 if ctx.nudge_count >= self.config.max_nudges {
54 return Ok(());
55 }
56
57 ctx.nudge_count += 1;
59
60 tracing::info!(
61 nudge_count = ctx.nudge_count,
62 full_text_len = ctx.full_text.len(),
63 "ToolEnforcement: suppressing text response, injecting nudge"
64 );
65
66 ctx.skip_push = true;
67 ctx.follow_up_message = Some(self.config.nudge_message.clone());
68
69 Ok(())
70 }
71}