Skip to main content

agent_base/engine/
auto_continue.rs

1use async_trait::async_trait;
2
3use crate::types::AgentResult;
4
5use super::middleware::{Middleware, PostLlmCtx};
6
7/// Middleware that automatically injects a continuation message when the LLM
8/// response is truncated by the token limit (e.g. `max_tokens` / `length`)
9/// and no tool calls are present.
10///
11/// This turns a silent truncation into an automatic retry: the react loop
12/// will push the follow-up as a user message and call the LLM again.
13///
14/// # When it triggers
15/// - `finish_reason` is `Truncated` **and**
16/// - `actions` is empty (tool-call truncation is already handled by the
17///   react-loop's built-in truncation guard, which injects error results
18///   instead of executing incomplete tool calls).
19///
20/// # Usage
21/// ```ignore
22/// use agent_base::engine::{AgentBuilder, auto_continue::AutoContinueMiddleware};
23///
24/// let runtime = AgentBuilder::new(client)
25///     .middleware(AutoContinueMiddleware::new())
26///     .build()?;
27/// ```
28pub struct AutoContinueMiddleware {
29    /// The message to inject as a user turn when truncation is detected.
30    prompt: String,
31}
32
33impl AutoContinueMiddleware {
34    /// Create a new middleware with the default continuation prompt.
35    pub fn new() -> Self {
36        Self {
37            prompt: "Please continue.".to_string(),
38        }
39    }
40
41    /// Create a new middleware with a custom continuation prompt.
42    pub fn with_prompt(prompt: impl Into<String>) -> Self {
43        Self {
44            prompt: prompt.into(),
45        }
46    }
47}
48
49impl Default for AutoContinueMiddleware {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55#[async_trait]
56impl Middleware for AutoContinueMiddleware {
57    async fn on_post_llm(&self, ctx: &mut PostLlmCtx) -> AgentResult<()> {
58        if ctx.finish_reason.is_truncated() && ctx.actions().is_empty() {
59            tracing::info!(
60                session_id = ctx.session_id.id,
61                turn = ctx.turn_count,
62                "text-only response truncated — injecting auto-continue prompt"
63            );
64            ctx.follow_up_message = Some(self.prompt.clone());
65        }
66        Ok(())
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use crate::engine::executor::ParseOutcome;
74    use crate::types::{Action, ActionFormat, FinishReason, SessionId};
75
76    fn ctx(finish_reason: FinishReason, tool_calls: Vec<(String, String, String)>) -> PostLlmCtx {
77        let actions = tool_calls
78            .into_iter()
79            .map(|(id, name, args)| Action {
80                id,
81                name,
82                args: serde_json::Value::String(args),
83                identity: String::new(),
84                format: ActionFormat::ToolCall,
85            })
86            .collect::<Vec<Action>>();
87        let parse = if actions.is_empty() {
88            ParseOutcome::Empty
89        } else {
90            ParseOutcome::Actions(actions)
91        };
92        PostLlmCtx {
93            session_id: SessionId::new(1),
94            full_text: "partial answer...".to_string(),
95            parse,
96            available_tools: vec![],
97            turn_count: 1,
98            total_actions: 0,
99            nudge_count: 0,
100            turn_actions: 0,
101            skip_push: false,
102            follow_up_message: None,
103            finish_reason,
104        }
105    }
106
107    #[tokio::test]
108    async fn triggers_on_truncated_text_only() {
109        let mw = AutoContinueMiddleware::new();
110        let mut c = ctx(
111            FinishReason::Truncated {
112                reason: Some("max_tokens".into()),
113            },
114            vec![],
115        );
116        mw.on_post_llm(&mut c).await.unwrap();
117        assert_eq!(c.follow_up_message, Some("Please continue.".to_string()));
118    }
119
120    #[tokio::test]
121    async fn triggers_on_truncated_no_reason() {
122        let mw = AutoContinueMiddleware::new();
123        let mut c = ctx(FinishReason::Truncated { reason: None }, vec![]);
124        mw.on_post_llm(&mut c).await.unwrap();
125        assert_eq!(c.follow_up_message, Some("Please continue.".to_string()));
126    }
127
128    #[tokio::test]
129    async fn skips_when_tool_calls_present() {
130        let mw = AutoContinueMiddleware::new();
131        let mut c = ctx(
132            FinishReason::Truncated {
133                reason: Some("length".into()),
134            },
135            vec![("id".into(), "shell".into(), "{}".into())],
136        );
137        mw.on_post_llm(&mut c).await.unwrap();
138        assert!(c.follow_up_message.is_none());
139    }
140
141    #[tokio::test]
142    async fn skips_when_stop() {
143        let mw = AutoContinueMiddleware::new();
144        let mut c = ctx(FinishReason::Stop, vec![]);
145        mw.on_post_llm(&mut c).await.unwrap();
146        assert!(c.follow_up_message.is_none());
147    }
148
149    #[tokio::test]
150    async fn skips_when_tool_use() {
151        let mw = AutoContinueMiddleware::new();
152        let mut c = ctx(FinishReason::ToolUse, vec![]);
153        mw.on_post_llm(&mut c).await.unwrap();
154        assert!(c.follow_up_message.is_none());
155    }
156
157    #[tokio::test]
158    async fn custom_prompt() {
159        let mw = AutoContinueMiddleware::with_prompt("Continue please.");
160        let mut c = ctx(
161            FinishReason::Truncated {
162                reason: Some("max_tokens".into()),
163            },
164            vec![],
165        );
166        mw.on_post_llm(&mut c).await.unwrap();
167        assert_eq!(c.follow_up_message, Some("Continue please.".to_string()));
168    }
169}