1use std::sync::Arc;
11
12use async_trait::async_trait;
13use futures::StreamExt;
14
15use bamboo_compression::{HeuristicSummarizer, Summarizer};
16use bamboo_domain::ReasoningEffort;
17use bamboo_domain::{
18 ContextBlock, ContextBlockPriority, ContextBlockStability, ContextBlockType, Message, Role,
19};
20use bamboo_llm::LLMChunk;
21use bamboo_llm::{LLMProvider, LLMRequestOptions};
22
23#[derive(Debug, Clone, Default)]
25pub enum SummaryMode {
26 #[default]
28 FullRewrite,
29 IncrementalMerge,
31}
32
33pub struct LlmSummarizer {
42 llm: Arc<dyn LLMProvider>,
43 model: String,
44 existing_summary: Option<String>,
46 context_blocks: Vec<ContextBlock>,
48 custom_instructions: Option<String>,
50 summary_mode: SummaryMode,
52 heuristic_fallback_on_error: bool,
58}
59
60impl LlmSummarizer {
61 pub fn new(
62 llm: Arc<dyn LLMProvider>,
63 model: String,
64 existing_summary: Option<String>,
65 task_list_prompt: Option<String>,
66 ) -> Self {
67 let context_blocks = task_list_prompt
68 .as_deref()
69 .map(str::trim)
70 .filter(|value| !value.is_empty())
71 .map(|task_list| {
72 vec![ContextBlock::new(
73 ContextBlockType::TaskSnapshot,
74 ContextBlockPriority::High,
75 ContextBlockStability::RoundDynamic,
76 "Current Task List",
77 task_list,
78 )]
79 })
80 .unwrap_or_default();
81
82 Self {
83 llm,
84 model,
85 existing_summary,
86 context_blocks,
87 custom_instructions: None,
88 summary_mode: SummaryMode::default(),
89 heuristic_fallback_on_error: true,
90 }
91 }
92
93 pub fn with_heuristic_fallback_on_error(mut self, enabled: bool) -> Self {
98 self.heuristic_fallback_on_error = enabled;
99 self
100 }
101
102 pub fn with_context_blocks(mut self, context_blocks: Vec<ContextBlock>) -> Self {
103 self.context_blocks = context_blocks;
104 self
105 }
106
107 pub fn with_custom_instructions(mut self, instructions: Option<String>) -> Self {
108 self.custom_instructions = instructions;
109 self
110 }
111
112 pub fn with_summary_mode(mut self, mode: SummaryMode) -> Self {
113 self.summary_mode = mode;
114 self
115 }
116
117 fn build_summarization_messages(&self, messages: &[Message]) -> Vec<Message> {
119 let mut prompt_messages = Vec::new();
120
121 let system_prompt = match self.summary_mode {
122 SummaryMode::FullRewrite => {
123 r#"You are a conversation summarizer. Your task is to create a concise but reliable working-memory summary for a conversation that was removed due to context window limits.
124
125Guidelines:
126- First capture the in-flight work right before compression (what was being done, where, and with which tool/file)
127- Distinguish clearly between CURRENT ACTIVE work, COMPLETED work, and OBSOLETE or superseded work
128- Do not restate old tasks as active unless they are still unresolved
129- The provided current task list is the source of truth for active work
130- Preserve key decisions, constraints, file paths, code changes, tool findings, blockers, and important outcomes
131- Preserve error messages, test results (pass/fail counts), and function/variable names that are relevant to active work
132- If earlier plans conflict with newer messages or the current task list, mark them as obsolete or completed
133- Explicitly evaluate each clear user requirement (e.g. requirement 1, requirement 2) with a status and evidence
134- Keep the next step specific and aligned with the active work only
135- Use structured sections
136- Write in the same language as the original conversation"#
137 }
138 SummaryMode::IncrementalMerge => {
139 r#"You are updating an existing conversation summary with new information from recent messages.
140
141Guidelines:
142- Incorporate new information into the existing summary structure
143- Mark previously active work as completed if the new messages confirm completion
144- Remove or condense information that is no longer relevant
145- Preserve all key decisions, file paths, and constraints that remain active
146- If new messages conflict with the existing summary, the new messages take precedence
147- Keep the summary focused on what is currently active and relevant
148- The provided current task list is the source of truth for active work
149- Maintain the same structured sections as the existing summary
150- Write in the same language as the original conversation
151- Be concise: avoid repeating information already well-captured in the existing summary"#
152 }
153 };
154
155 prompt_messages.push(Message::system(system_prompt));
156
157 let mut user_content = String::new();
158
159 if let Some(ref existing) = self.existing_summary {
160 user_content.push_str("## Previous Summary\n\n");
161 user_content.push_str(existing);
162 user_content.push_str("\n\n---\n\n");
163 }
164
165 if !self.context_blocks.is_empty() {
166 user_content.push_str("## Compression Context Blocks\n\n");
167 for block in &self.context_blocks {
168 user_content.push_str(&format!(
169 "### {}\n- type: {}\n- priority: {}\n- stability: {}\n\n{}\n\n",
170 block.title.trim(),
171 block.block_type.as_str(),
172 block.priority.as_str(),
173 block.stability.as_str(),
174 block.content.trim(),
175 ));
176 }
177 user_content.push_str("---\n\n");
178 }
179
180 if let Some(ref instructions) = self.custom_instructions {
181 if !instructions.trim().is_empty() {
182 user_content.push_str("## Custom Compression Instructions\n\n");
183 user_content.push_str(instructions.trim());
184 user_content.push_str("\n\n---\n\n");
185 }
186 }
187
188 user_content.push_str(
189 "## Required Output Sections\n1. Pre-compression in-flight work (what was being done immediately before compression)\n2. Current active objective\n3. Requirement checklist (Requirement | Status: completed/in_progress/pending/blocked/obsolete | Evidence)\n4. Active tasks\n5. Completed tasks\n6. Obsolete or superseded tasks\n7. Important context and constraints\n8. Files, code, and tool findings\n9. Open issues and next step\n\n",
190 );
191
192 user_content.push_str("## Messages to Summarize\n\n");
193
194 for message in messages {
195 let role_label = match message.role {
196 Role::User => "User",
197 Role::Assistant => "Assistant",
198 Role::Tool => "Tool Result",
199 Role::System => continue,
200 };
201
202 if let Some(ref tool_calls) = message.tool_calls {
203 if !tool_calls.is_empty() {
204 let tool_names: Vec<&str> = tool_calls
205 .iter()
206 .map(|tc| tc.function.name.as_str())
207 .collect();
208 user_content.push_str(&format!(
209 "**{}** [called tools: {}]:\n",
210 role_label,
211 tool_names.join(", ")
212 ));
213 } else {
214 user_content.push_str(&format!("**{}**:\n", role_label));
215 }
216 } else {
217 user_content.push_str(&format!("**{}**:\n", role_label));
218 }
219
220 if let Some(ref tool_call_id) = message.tool_call_id {
221 user_content.push_str(&format!("(tool_call_id: {})\n", tool_call_id));
222 }
223
224 let content = &message.content;
225 const MAX_CONTENT_CHARS: usize = 2000;
226 if content.chars().count() > MAX_CONTENT_CHARS {
227 let truncated: String = content.chars().take(MAX_CONTENT_CHARS).collect();
228 user_content.push_str(&truncated);
229 user_content.push_str("... [truncated]\n\n");
230 } else {
231 user_content.push_str(content);
232 user_content.push_str("\n\n");
233 }
234 }
235
236 user_content.push_str(
237 "\n---\n\nReturn only the summary text. Be explicit about what is active now versus what is already completed or no longer relevant.",
238 );
239
240 prompt_messages.push(Message::user(user_content));
241
242 prompt_messages
243 }
244
245 async fn collect_stream_response(
247 &self,
248 messages: &[Message],
249 ) -> Result<String, bamboo_compression::types::BudgetError> {
250 let options = LLMRequestOptions {
253 session_id: None,
254 reasoning_effort: Some(ReasoningEffort::High),
255 parallel_tool_calls: None,
256 responses: None,
257 request_purpose: Some("compression".to_string()),
258 cache: None,
259 };
260 let stream = self
261 .llm
262 .chat_stream_with_options(messages, &[], Some(8192), &self.model, Some(&options))
263 .await
264 .map_err(|e| {
265 bamboo_compression::types::BudgetError::TokenCountError(format!(
266 "LLM summarization call failed: {}",
267 e
268 ))
269 })?;
270
271 let mut content = String::new();
272 let mut stream = stream;
273
274 while let Some(chunk_result) = stream.next().await {
275 match chunk_result {
276 Ok(LLMChunk::Token(text)) => content.push_str(&text),
277 Ok(LLMChunk::Done) => break,
278 Ok(_) => {} Err(e) => {
280 tracing::warn!("LLM summarization stream error: {}", e);
281 if !content.is_empty() {
282 break;
283 }
284 return Err(bamboo_compression::types::BudgetError::TokenCountError(
285 format!("LLM summarization stream failed: {}", e),
286 ));
287 }
288 }
289 }
290
291 Ok(content)
292 }
293}
294
295impl std::fmt::Debug for LlmSummarizer {
296 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 f.debug_struct("LlmSummarizer")
298 .field("model", &self.model)
299 .field("has_existing_summary", &self.existing_summary.is_some())
300 .field("context_block_count", &self.context_blocks.len())
301 .finish()
302 }
303}
304
305#[async_trait]
306impl Summarizer for LlmSummarizer {
307 async fn summarize(
308 &self,
309 messages: &[Message],
310 ) -> Result<String, bamboo_compression::types::BudgetError> {
311 if messages.is_empty() {
312 return Ok("No conversation history to summarize.".to_string());
313 }
314
315 let prompt_messages = self.build_summarization_messages(messages);
316
317 tracing::info!(
318 "LlmSummarizer: summarizing {} messages using model '{}' (existing_summary={})",
319 messages.len(),
320 self.model,
321 self.existing_summary.is_some()
322 );
323
324 match self.collect_stream_response(&prompt_messages).await {
325 Ok(summary) if !summary.trim().is_empty() => {
326 tracing::info!("LlmSummarizer: generated summary ({} chars)", summary.len());
327 Ok(summary)
328 }
329 Ok(_) => {
330 tracing::warn!(
331 "LlmSummarizer: LLM returned empty summary, falling back to heuristic"
332 );
333 HeuristicSummarizer::new().summarize(messages).await
334 }
335 Err(e) if self.heuristic_fallback_on_error => {
336 tracing::warn!(
337 "LlmSummarizer: LLM call failed ({}), falling back to heuristic",
338 e
339 );
340 HeuristicSummarizer::new().summarize(messages).await
341 }
342 Err(e) => {
346 tracing::warn!(
347 "LlmSummarizer: LLM call failed ({}); surfacing error (heuristic fallback disabled)",
348 e
349 );
350 Err(e)
351 }
352 }
353 }
354
355 fn estimate_summary_tokens(&self, message_count: usize) -> u32 {
356 (message_count * 80).min(2000) as u32
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364 use bamboo_domain::ReasoningEffort;
365 use bamboo_llm::{LLMChunk, LLMError, LLMRequestOptions, LLMStream};
366 use futures::stream;
367 use std::sync::Mutex;
368
369 struct DummyProvider;
370
371 #[async_trait]
372 impl LLMProvider for DummyProvider {
373 async fn chat_stream(
374 &self,
375 _messages: &[Message],
376 _tools: &[bamboo_domain::ToolSchema],
377 _max_output_tokens: Option<u32>,
378 _model: &str,
379 ) -> Result<LLMStream, LLMError> {
380 Ok(Box::pin(stream::iter(vec![
381 Ok::<LLMChunk, LLMError>(LLMChunk::Token("dummy summary".to_string())),
382 Ok::<LLMChunk, LLMError>(LLMChunk::Done),
383 ])))
384 }
385 }
386 fn llm_summarizer_prompt_includes_context_blocks_and_state_sections() {
387 let summarizer = LlmSummarizer::new(
388 Arc::new(DummyProvider),
389 "gpt-4o-mini".to_string(),
390 Some("Earlier summary".to_string()),
391 Some(
392 "## Current Task List\n[/] task_1: Fix compression bounce\n[x] task_0: Analyze bug"
393 .to_string(),
394 ),
395 )
396 .with_context_blocks(vec![
397 ContextBlock::new(
398 ContextBlockType::TaskSnapshot,
399 ContextBlockPriority::High,
400 ContextBlockStability::RoundDynamic,
401 "Current Task List",
402 "[/] task_1: Fix compression bounce",
403 ),
404 ContextBlock::new(
405 ContextBlockType::ExternalMemory,
406 ContextBlockPriority::Medium,
407 ContextBlockStability::RoundDynamic,
408 "External Memory (Persistent)",
409 "Session note body",
410 ),
411 ]);
412 let messages = vec![
413 Message::user("继续做压缩修复"),
414 Message::assistant("我先检查 trigger 与 target", None),
415 ];
416
417 let prompt_messages = summarizer.build_summarization_messages(&messages);
418 assert_eq!(prompt_messages.len(), 2);
419 assert_eq!(prompt_messages[0].role, Role::System);
420 assert!(prompt_messages[1]
421 .content
422 .contains("## Compression Context Blocks"));
423 assert!(prompt_messages[1].content.contains("Current Task List"));
424 assert!(prompt_messages[1]
425 .content
426 .contains("External Memory (Persistent)"));
427 assert!(prompt_messages[1]
428 .content
429 .contains("Current active objective"));
430 assert!(prompt_messages[1].content.contains("Requirement checklist"));
431 assert!(prompt_messages[1].content.contains("Active tasks"));
432 assert!(prompt_messages[1].content.contains("Completed tasks"));
433 assert!(prompt_messages[1]
434 .content
435 .contains("Obsolete or superseded tasks"));
436 assert!(prompt_messages[1].content.contains("Earlier summary"));
437 }
438
439 #[derive(Default)]
440 struct ReasoningCaptureProvider {
441 captured_reasoning: Mutex<Vec<Option<ReasoningEffort>>>,
442 }
443
444 #[async_trait]
445 impl LLMProvider for ReasoningCaptureProvider {
446 async fn chat_stream(
447 &self,
448 _messages: &[Message],
449 _tools: &[bamboo_domain::ToolSchema],
450 _max_output_tokens: Option<u32>,
451 _model: &str,
452 ) -> Result<LLMStream, LLMError> {
453 Ok(Box::pin(stream::iter(vec![
454 Ok::<LLMChunk, LLMError>(LLMChunk::Token("captured summary".to_string())),
455 Ok::<LLMChunk, LLMError>(LLMChunk::Done),
456 ])))
457 }
458
459 async fn chat_stream_with_options(
460 &self,
461 messages: &[Message],
462 tools: &[bamboo_domain::ToolSchema],
463 max_output_tokens: Option<u32>,
464 model: &str,
465 options: Option<&LLMRequestOptions>,
466 ) -> Result<LLMStream, LLMError> {
467 self.captured_reasoning
468 .lock()
469 .expect("captured reasoning lock should not be poisoned")
470 .push(options.and_then(|o| o.reasoning_effort));
471 self.chat_stream(messages, tools, max_output_tokens, model)
472 .await
473 }
474 }
475
476 #[tokio::test]
477 async fn llm_summarizer_requests_high_reasoning_effort_for_summary_calls() {
478 let provider = Arc::new(ReasoningCaptureProvider::default());
479 let summarizer = LlmSummarizer::new(
480 provider.clone(),
481 "gpt-5-mini".to_string(),
482 None,
483 Some("task list".to_string()),
484 );
485 let messages = vec![
486 Message::user("请总结最近三轮"),
487 Message::assistant("已完成第一步并准备第二步", None),
488 ];
489
490 let summary = summarizer
491 .summarize(&messages)
492 .await
493 .expect("summary generation should succeed");
494 assert_eq!(summary, "captured summary");
495
496 let captured = provider
497 .captured_reasoning
498 .lock()
499 .expect("captured reasoning lock should not be poisoned");
500 assert_eq!(captured.as_slice(), [Some(ReasoningEffort::High)]);
501 }
502
503 #[derive(Default)]
505 struct RequestOptionsCaptureProvider {
506 captured_reasoning: Mutex<Vec<Option<ReasoningEffort>>>,
507 captured_max_tokens: Mutex<Vec<Option<u32>>>,
508 }
509
510 #[async_trait]
511 impl LLMProvider for RequestOptionsCaptureProvider {
512 async fn chat_stream(
513 &self,
514 _messages: &[Message],
515 _tools: &[bamboo_domain::ToolSchema],
516 _max_output_tokens: Option<u32>,
517 _model: &str,
518 ) -> Result<LLMStream, LLMError> {
519 Ok(Box::pin(stream::iter(vec![
520 Ok::<LLMChunk, LLMError>(LLMChunk::Token("captured summary".to_string())),
521 Ok::<LLMChunk, LLMError>(LLMChunk::Done),
522 ])))
523 }
524
525 async fn chat_stream_with_options(
526 &self,
527 messages: &[Message],
528 tools: &[bamboo_domain::ToolSchema],
529 max_output_tokens: Option<u32>,
530 model: &str,
531 options: Option<&LLMRequestOptions>,
532 ) -> Result<LLMStream, LLMError> {
533 self.captured_reasoning
534 .lock()
535 .expect("lock should not be poisoned")
536 .push(options.and_then(|o| o.reasoning_effort));
537 self.captured_max_tokens
538 .lock()
539 .expect("lock should not be poisoned")
540 .push(max_output_tokens);
541 self.chat_stream(messages, tools, max_output_tokens, model)
542 .await
543 }
544 }
545
546 #[tokio::test]
547 async fn llm_summarizer_sufficient_max_tokens_for_high_reasoning() {
548 let provider = Arc::new(RequestOptionsCaptureProvider::default());
549 let summarizer = LlmSummarizer::new(
550 provider.clone(),
551 "gpt-5-mini".to_string(),
552 None,
553 Some("task list".to_string()),
554 );
555 let messages = vec![
556 Message::user("请总结最近三轮"),
557 Message::assistant("已完成第一步并准备第二步", None),
558 ];
559
560 let summary = summarizer
561 .summarize(&messages)
562 .await
563 .expect("summary generation should succeed");
564 assert_eq!(summary, "captured summary");
565
566 let captured_reasoning = provider
567 .captured_reasoning
568 .lock()
569 .expect("lock should not be poisoned");
570 let captured_max_tokens = provider
571 .captured_max_tokens
572 .lock()
573 .expect("lock should not be poisoned");
574 assert_eq!(captured_reasoning.as_slice(), [Some(ReasoningEffort::High)]);
575 let max_tokens = captured_max_tokens[0].expect("max_output_tokens should be set");
576 assert!(
578 max_tokens > 4096,
579 "max_output_tokens ({}) must exceed thinking budget (4096) to avoid truncation",
580 max_tokens
581 );
582 }
583
584 #[test]
585 fn full_rewrite_mode_uses_default_system_prompt() {
586 let summarizer =
587 LlmSummarizer::new(Arc::new(DummyProvider), "model".to_string(), None, None)
588 .with_summary_mode(SummaryMode::FullRewrite);
589 let messages = vec![Message::user("hello"), Message::assistant("hi", None)];
590 let prompts = summarizer.build_summarization_messages(&messages);
591 let system = &prompts[0].content;
592 assert!(
593 system.contains("conversation summarizer"),
594 "FullRewrite prompt should contain 'conversation summarizer'"
595 );
596 assert!(
597 !system.contains("updating an existing"),
598 "FullRewrite prompt should not contain incremental language"
599 );
600 }
601
602 #[test]
603 fn incremental_merge_mode_uses_update_system_prompt() {
604 let summarizer = LlmSummarizer::new(
605 Arc::new(DummyProvider),
606 "model".to_string(),
607 Some("Previous summary content".to_string()),
608 None,
609 )
610 .with_summary_mode(SummaryMode::IncrementalMerge);
611 let messages = vec![Message::user("hello"), Message::assistant("hi", None)];
612 let prompts = summarizer.build_summarization_messages(&messages);
613 let system = &prompts[0].content;
614 assert!(
615 system.contains("updating an existing conversation summary"),
616 "IncrementalMerge prompt should contain 'updating an existing conversation summary'"
617 );
618 assert!(
619 system.contains("Incorporate new information"),
620 "IncrementalMerge prompt should mention incorporating new information"
621 );
622 }
623
624 #[test]
625 fn default_summary_mode_is_full_rewrite() {
626 assert!(matches!(SummaryMode::default(), SummaryMode::FullRewrite));
627 }
628
629 #[test]
630 fn incremental_merge_includes_existing_summary_in_user_content() {
631 let summarizer = LlmSummarizer::new(
632 Arc::new(DummyProvider),
633 "model".to_string(),
634 Some("Previous summary content".to_string()),
635 None,
636 )
637 .with_summary_mode(SummaryMode::IncrementalMerge);
638 let messages = vec![
639 Message::user("new work"),
640 Message::assistant("doing it", None),
641 ];
642 let prompts = summarizer.build_summarization_messages(&messages);
643 let user_content = &prompts[1].content;
644 assert!(
645 user_content.contains("Previous Summary"),
646 "IncrementalMerge user prompt should include the existing summary"
647 );
648 assert!(
649 user_content.contains("Previous summary content"),
650 "IncrementalMerge user prompt should include the actual summary text"
651 );
652 }
653
654 struct FailingProvider;
656
657 #[async_trait]
658 impl LLMProvider for FailingProvider {
659 async fn chat_stream(
660 &self,
661 _messages: &[Message],
662 _tools: &[bamboo_domain::ToolSchema],
663 _max_output_tokens: Option<u32>,
664 _model: &str,
665 ) -> Result<LLMStream, LLMError> {
666 Err(LLMError::Api("http 500 transient".to_string()))
667 }
668 }
669
670 fn summary_messages() -> Vec<Message> {
671 vec![
672 Message::user("do the work"),
673 Message::assistant("working on it", None),
674 Message::user("keep going"),
675 ]
676 }
677
678 #[tokio::test]
679 async fn summarize_falls_back_to_heuristic_on_llm_error_by_default() {
680 let summarizer =
684 LlmSummarizer::new(Arc::new(FailingProvider), "model".to_string(), None, None);
685 let out = summarizer.summarize(&summary_messages()).await;
686 assert!(
687 out.is_ok(),
688 "default heuristic fallback should recover from a transient LLM error, got {out:?}"
689 );
690 }
691
692 #[tokio::test]
693 async fn summarize_surfaces_llm_error_when_heuristic_fallback_disabled() {
694 let summarizer =
699 LlmSummarizer::new(Arc::new(FailingProvider), "model".to_string(), None, None)
700 .with_heuristic_fallback_on_error(false);
701 let out = summarizer.summarize(&summary_messages()).await;
702 assert!(
703 out.is_err(),
704 "with the heuristic fallback disabled, a transient LLM error must surface"
705 );
706 }
707}