Skip to main content

bamboo_engine/runtime/managers/adapters/
llm_mini_loop.rs

1use async_trait::async_trait;
2use bamboo_agent_core::tools::ToolCall;
3use bamboo_agent_core::{AgentError, Session};
4use bamboo_domain::{Message, Role};
5use bamboo_llm::LLMProvider;
6
7use crate::runtime::managers::mini_loop::{MiniLoopDecision, MiniLoopExecutor};
8
9/// Production `MiniLoopExecutor` backed by a real LLM provider.
10///
11/// Uses a fast/cheap model for lightweight decisions such as task complexity
12/// classification, compression decisions, retry classification, and routing.
13pub struct LLMMiniLoopExecutor {
14    provider: std::sync::Arc<dyn LLMProvider>,
15    model: String,
16    timeout_context: crate::runtime::stream::handler::StreamTimeoutContext,
17}
18
19impl LLMMiniLoopExecutor {
20    pub fn new(provider: std::sync::Arc<dyn LLMProvider>, model: String) -> Self {
21        Self {
22            provider,
23            model,
24            timeout_context: crate::runtime::stream::handler::StreamTimeoutContext::default(),
25        }
26    }
27
28    pub fn with_timeout_policy(
29        provider: std::sync::Arc<dyn LLMProvider>,
30        model: String,
31        policy: bamboo_config::StreamTimeoutConfig,
32        provider_name: Option<&str>,
33    ) -> Self {
34        let timeout_context = crate::runtime::stream::handler::StreamTimeoutContext::new(
35            policy,
36            provider_name,
37            Some(&model),
38        );
39        Self {
40            provider,
41            model,
42            timeout_context,
43        }
44    }
45}
46
47#[async_trait]
48impl MiniLoopExecutor for LLMMiniLoopExecutor {
49    async fn decide(
50        &self,
51        _session: &Session,
52        prompt: &str,
53        context: &str,
54    ) -> Result<MiniLoopDecision, AgentError> {
55        let user_content = if context.is_empty() {
56            prompt.to_string()
57        } else {
58            format!("Context:\n{}\n\n{}", context, prompt)
59        };
60
61        let now = chrono::Utc::now();
62        let messages = vec![
63            Message {
64                id: String::new(),
65                role: Role::System,
66                content: "You are a task complexity classifier. Respond with exactly one word: simple, standard, or complex.".to_string(),
67                reasoning: None,
68                reasoning_signature: None,
69                content_parts: None,
70                image_ocr: None,
71                phase: None,
72                tool_calls: None,
73                tool_call_id: None,
74                tool_success: None,
75                compressed: false,
76                compressed_by_event_id: None,
77                never_compress: false,
78                compression_level: 0,
79                created_at: now,
80                metadata: None,
81            },
82            Message {
83                id: String::new(),
84                role: Role::User,
85                content: user_content,
86                reasoning: None,
87                reasoning_signature: None,
88                content_parts: None,
89                image_ocr: None,
90                phase: None,
91                tool_calls: None,
92                tool_call_id: None,
93                tool_success: None,
94                compressed: false,
95                compressed_by_event_id: None,
96                never_compress: false,
97                compression_level: 0,
98                created_at: now,
99                metadata: None,
100            },
101        ];
102
103        let options = bamboo_llm::provider::LLMRequestOptions {
104            session_id: None,
105            reasoning_effort: None,
106            parallel_tool_calls: None,
107            required_tool: None,
108            responses: None,
109            request_purpose: Some("mini_loop".to_string()),
110            cache: None,
111        };
112        let stream = self
113            .provider
114            .chat_stream_with_options(&messages, &[], Some(256), &self.model, Some(&options))
115            .await
116            .map_err(|e| AgentError::LLM(e.to_string()))?;
117
118        let output = crate::runtime::stream::handler::consume_llm_stream_silent_with_context(
119            stream,
120            &tokio_util::sync::CancellationToken::new(),
121            "mini-loop",
122            &self.timeout_context,
123        )
124        .await?;
125
126        Ok(MiniLoopDecision {
127            answer: output.content.trim().to_string(),
128            prompt_tokens: 0,
129            completion_tokens: 0,
130        })
131    }
132
133    async fn evaluate_task(
134        &self,
135        _session: &Session,
136        _tool_calls: &[ToolCall],
137        _round: usize,
138    ) -> Result<MiniLoopDecision, AgentError> {
139        // Task evaluation is handled by the dedicated task_evaluation module.
140        // This implementation returns an empty decision as a fallback.
141        Ok(MiniLoopDecision {
142            answer: String::new(),
143            prompt_tokens: 0,
144            completion_tokens: 0,
145        })
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    use bamboo_agent_core::tools::ToolSchema;
153    use bamboo_domain::ReasoningEffort;
154    use bamboo_llm::provider::LLMRequestOptions;
155    use bamboo_llm::{LLMChunk, LLMError, LLMProvider, LLMStream};
156    use futures::stream;
157    use std::sync::{Arc, Mutex};
158
159    #[derive(Default)]
160    struct CaptureProvider {
161        captured_max_tokens: Mutex<Vec<Option<u32>>>,
162        captured_reasoning: Mutex<Vec<Option<ReasoningEffort>>>,
163    }
164
165    #[async_trait]
166    impl LLMProvider for CaptureProvider {
167        async fn chat_stream(
168            &self,
169            _messages: &[Message],
170            _tools: &[ToolSchema],
171            _max_output_tokens: Option<u32>,
172            _model: &str,
173        ) -> Result<LLMStream, LLMError> {
174            Ok(Box::pin(stream::iter(vec![
175                Ok::<LLMChunk, LLMError>(LLMChunk::Token("simple".to_string())),
176                Ok::<LLMChunk, LLMError>(LLMChunk::Done),
177            ])))
178        }
179
180        async fn chat_stream_with_options(
181            &self,
182            messages: &[Message],
183            tools: &[ToolSchema],
184            max_output_tokens: Option<u32>,
185            model: &str,
186            options: Option<&LLMRequestOptions>,
187        ) -> Result<LLMStream, LLMError> {
188            self.captured_max_tokens
189                .lock()
190                .expect("lock should not be poisoned")
191                .push(max_output_tokens);
192            self.captured_reasoning
193                .lock()
194                .expect("lock should not be poisoned")
195                .push(options.and_then(|o| o.reasoning_effort));
196            self.chat_stream(messages, tools, max_output_tokens, model)
197                .await
198        }
199    }
200
201    #[tokio::test]
202    async fn mini_loop_sends_no_reasoning_effort() {
203        let provider = Arc::new(CaptureProvider::default());
204        let executor = LLMMiniLoopExecutor::new(provider.clone(), "fast-model".to_string());
205        let session = Session::new("test", "model");
206
207        let decision = executor
208            .decide(&session, "classify this task", "")
209            .await
210            .expect("decide should succeed");
211        assert_eq!(decision.answer, "simple");
212
213        let captured_reasoning = provider
214            .captured_reasoning
215            .lock()
216            .expect("lock should not be poisoned");
217        assert_eq!(
218            captured_reasoning.as_slice(),
219            [None],
220            "mini_loop should not request reasoning to avoid thinking budget consuming output tokens"
221        );
222    }
223
224    #[tokio::test]
225    async fn mini_loop_max_tokens_accommodates_provider_default_reasoning() {
226        let provider = Arc::new(CaptureProvider::default());
227        let executor = LLMMiniLoopExecutor::new(provider.clone(), "fast-model".to_string());
228        let session = Session::new("test", "model");
229
230        let _ = executor
231            .decide(&session, "classify this task", "")
232            .await
233            .expect("decide should succeed");
234
235        let captured = provider
236            .captured_max_tokens
237            .lock()
238            .expect("lock should not be poisoned");
239        let max_tokens = captured[0].expect("max_output_tokens should be set");
240        // Even if the provider has a default_reasoning_effort of High (4096 thinking budget),
241        // 256 tokens is enough for the one-word response while leaving room for thinking.
242        assert!(
243            max_tokens >= 256,
244            "max_output_tokens ({}) should be at least 256 to accommodate potential provider default reasoning",
245            max_tokens
246        );
247    }
248}