agent_base/engine/
safety.rs1use async_trait::async_trait;
2
3use crate::engine::middleware::{Middleware, PostLlmCtx};
4use crate::types::{AgentResult, SafetyConfig};
5
6pub struct TurnToolLimitMiddleware {
15 max_tool_calls_per_turn: usize,
16}
17
18impl TurnToolLimitMiddleware {
19 pub fn new(max_tool_calls_per_turn: usize) -> Self {
20 Self {
21 max_tool_calls_per_turn,
22 }
23 }
24
25 pub fn from_config(config: &SafetyConfig) -> Self {
26 Self::new(config.max_tool_calls_per_turn)
27 }
28}
29
30#[async_trait]
31impl Middleware for TurnToolLimitMiddleware {
32 async fn on_post_llm(&self, ctx: &mut PostLlmCtx) -> AgentResult<()> {
33 if ctx.actions().is_empty() {
35 return Ok(());
36 }
37
38 if ctx.turn_actions >= self.max_tool_calls_per_turn {
40 tracing::warn!(
41 turn_actions = ctx.turn_actions,
42 max = self.max_tool_calls_per_turn,
43 pending_calls = ctx.actions().len(),
44 "TurnToolLimit: blocking tool calls — limit reached"
45 );
46
47 ctx.demote_to_text();
49
50 ctx.follow_up_message = Some(
52 "本轮工具调用已达上限。请根据已有结果总结并向用户报告。不要再调用工具。"
53 .to_string(),
54 );
55 }
56
57 Ok(())
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64 use crate::engine::executor::ParseOutcome;
65 use crate::types::{Action, ActionFormat, FinishReason, SessionId};
66
67 fn make_ctx(turn_actions: usize, pending_calls: usize) -> PostLlmCtx {
68 let actions = (0..pending_calls)
69 .map(|i| Action {
70 id: format!("call_{}", i),
71 name: "test_tool".to_string(),
72 args: serde_json::json!({}),
73 identity: "test_tool|{}".to_string(),
74 format: ActionFormat::ToolCall,
75 })
76 .collect::<Vec<Action>>();
77 let parse = if actions.is_empty() {
78 ParseOutcome::Empty
79 } else {
80 ParseOutcome::Actions(actions)
81 };
82 PostLlmCtx {
83 session_id: SessionId::new(1),
84 full_text: String::new(),
85 parse,
86 available_tools: vec!["test_tool".to_string()],
87 turn_count: 1,
88 total_actions: 0,
89 nudge_count: 0,
90 turn_actions,
91 skip_push: false,
92 follow_up_message: None,
93 finish_reason: FinishReason::Stop,
94 }
95 }
96
97 #[tokio::test]
98 async fn allows_calls_under_limit() {
99 let mw = TurnToolLimitMiddleware::new(8);
100 let mut ctx = make_ctx(3, 2);
101 mw.on_post_llm(&mut ctx).await.unwrap();
102 assert_eq!(ctx.actions().len(), 2);
103 assert!(ctx.follow_up_message.is_none());
104 }
105
106 #[tokio::test]
107 async fn blocks_calls_at_limit() {
108 let mw = TurnToolLimitMiddleware::new(8);
109 let mut ctx = make_ctx(8, 3);
110 mw.on_post_llm(&mut ctx).await.unwrap();
111 assert!(ctx.actions().is_empty());
112 assert!(!ctx.has_action_intent());
113 assert!(ctx.follow_up_message.is_some());
114 }
115
116 #[tokio::test]
117 async fn blocks_calls_over_limit() {
118 let mw = TurnToolLimitMiddleware::new(8);
119 let mut ctx = make_ctx(12, 2);
120 mw.on_post_llm(&mut ctx).await.unwrap();
121 assert!(ctx.actions().is_empty());
122 assert!(ctx.follow_up_message.is_some());
123 }
124
125 #[tokio::test]
126 async fn ignores_text_only_responses() {
127 let mw = TurnToolLimitMiddleware::new(8);
128 let mut ctx = make_ctx(10, 0); ctx.demote_to_text();
130 ctx.full_text = "just text".to_string();
131 mw.on_post_llm(&mut ctx).await.unwrap();
132 assert!(ctx.follow_up_message.is_none());
133 }
134
135 #[tokio::test]
136 async fn custom_limit() {
137 let mw = TurnToolLimitMiddleware::new(3);
138 let mut ctx = make_ctx(3, 1);
139 mw.on_post_llm(&mut ctx).await.unwrap();
140 assert!(ctx.actions().is_empty());
141 assert!(ctx.follow_up_message.is_some());
142 }
143}