Skip to main content

strands/conversation_manager/
summarizing_conversation_manager.rs

1//! The summarizing strategy.
2
3use std::fmt;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7use async_trait::async_trait;
8
9use super::compression::context_compression::{
10    DEFAULT_SUMMARIZATION_PROMPT, adjust_split_point_for_tool_pairs, generate_summary,
11};
12use super::compression::pin_message::{apply_pin_first, partition_pinned};
13use super::{ConversationManager, ConversationManagerReduceOptions, ProactiveCompression};
14use crate::agent::{InvocationContext, LocalAgent};
15use crate::error::{ContextWindowOverflowError, Error, Result};
16use crate::models::Model;
17
18const DEFAULT_SUMMARY_RATIO: f64 = 0.3;
19const DEFAULT_PRESERVE_RECENT_MESSAGES: usize = 10;
20
21/// Configuration for [`SummarizingConversationManager`] (`SummarizingConversationManagerConfig`).
22#[derive(Clone, Default, bon::Builder)]
23pub struct SummarizingConversationManagerConfig {
24    /// The model that writes summaries: this model > the agent's aux model > the agent's model.
25    pub model: Option<Arc<dyn Model>>,
26    /// The share of the oldest messages to summarize, clamped to `[0.1, 0.8]`. Defaults to 0.3.
27    pub summary_ratio: Option<f64>,
28    /// How many recent messages are never summarized. Defaults to 10.
29    pub preserve_recent_messages: Option<usize>,
30    /// The summarizer's system prompt. Defaults to the built-in summarization prompt.
31    #[builder(into)]
32    pub summarization_system_prompt: Option<String>,
33    /// Proactive compression before model calls. Defaults to disabled.
34    #[builder(into)]
35    pub proactive_compression: Option<ProactiveCompression>,
36    /// How many messages at the start of the conversation to pin permanently; they are never
37    /// summarized and move to the front.
38    pub pin_first: Option<usize>,
39}
40
41impl fmt::Debug for SummarizingConversationManagerConfig {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("SummarizingConversationManagerConfig")
44            .field("model", &self.model.as_ref().map(|model| model.model_id()))
45            .field("summary_ratio", &self.summary_ratio)
46            .field("preserve_recent_messages", &self.preserve_recent_messages)
47            .field("proactive_compression", &self.proactive_compression)
48            .field("pin_first", &self.pin_first)
49            .finish_non_exhaustive()
50    }
51}
52
53/// Summarizes the oldest messages when the context overflows (`SummarizingConversationManager`),
54/// replacing them with one user message that holds the summary.
55pub struct SummarizingConversationManager {
56    model: Option<Arc<dyn Model>>,
57    summary_ratio: f64,
58    preserve_recent_messages: usize,
59    summarization_system_prompt: String,
60    pin_first: Option<usize>,
61    pin_first_applied: AtomicBool,
62    compression_threshold: Option<f64>,
63}
64
65impl fmt::Debug for SummarizingConversationManager {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.debug_struct("SummarizingConversationManager")
68            .field("summary_ratio", &self.summary_ratio)
69            .field("preserve_recent_messages", &self.preserve_recent_messages)
70            .finish_non_exhaustive()
71    }
72}
73
74/// A summary that failed during overflow recovery: its message, with the overflow as the source.
75#[derive(Debug)]
76struct SummarizationFailed {
77    error: Error,
78    overflow: ContextWindowOverflowError,
79}
80
81impl fmt::Display for SummarizationFailed {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        self.error.fmt(f)
84    }
85}
86
87impl std::error::Error for SummarizationFailed {
88    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
89        Some(&self.overflow)
90    }
91}
92
93impl SummarizingConversationManager {
94    /// Creates the manager.
95    ///
96    /// # Errors
97    ///
98    /// A proactive compression threshold outside `(0, 1]`.
99    pub fn new(config: SummarizingConversationManagerConfig) -> Result<Self> {
100        let compression_threshold = config.proactive_compression.unwrap_or_default().threshold()?;
101        Ok(Self {
102            model: config.model,
103            summary_ratio: config.summary_ratio.unwrap_or(DEFAULT_SUMMARY_RATIO).clamp(0.1, 0.8),
104            preserve_recent_messages: config
105                .preserve_recent_messages
106                .unwrap_or(DEFAULT_PRESERVE_RECENT_MESSAGES),
107            summarization_system_prompt: config
108                .summarization_system_prompt
109                .unwrap_or_else(|| DEFAULT_SUMMARIZATION_PROMPT.to_owned()),
110            pin_first: config.pin_first,
111            pin_first_applied: AtomicBool::new(false),
112            compression_threshold,
113        })
114    }
115
116    /// The share of the oldest messages summarized per reduction, after clamping.
117    #[must_use]
118    pub fn summary_ratio(&self) -> f64 {
119        self.summary_ratio
120    }
121
122    async fn summarize_oldest(
123        &self,
124        agent: &mut LocalAgent,
125        model: &Arc<dyn Model>,
126        invocation_context: Option<&InvocationContext>,
127    ) -> Result<bool> {
128        let messages = agent.messages_mut();
129        #[allow(
130            clippy::cast_possible_truncation,
131            clippy::cast_sign_loss,
132            clippy::cast_precision_loss,
133            reason = "a non-negative message count times a ratio in [0.1, 0.8], floored"
134        )]
135        let by_ratio = ((messages.len() as f64 * self.summary_ratio).floor() as usize).max(1);
136        let count = by_ratio.min(messages.len().saturating_sub(self.preserve_recent_messages));
137        if count == 0 {
138            tracing::warn!(
139                "preserve_recent=<{}>, messages=<{}> | insufficient messages for summarization",
140                self.preserve_recent_messages,
141                messages.len()
142            );
143            return Ok(false);
144        }
145        let count = adjust_split_point_for_tool_pairs(messages, count)?;
146        if let Some(pin_first) = self.pin_first.filter(|count| *count > 0)
147            && !self.pin_first_applied.swap(true, Ordering::Relaxed)
148        {
149            apply_pin_first(messages, pin_first);
150        }
151        let (mut preserved, to_summarize) = partition_pinned(messages, 0, count);
152        if to_summarize.is_empty() {
153            tracing::warn!(
154                "messages=<{}> | all messages in summarize range are protected, unable to reduce",
155                messages.len()
156            );
157            return Ok(false);
158        }
159        let summary = generate_summary(
160            &to_summarize,
161            model,
162            Some(&self.summarization_system_prompt),
163            invocation_context,
164        )
165        .await?;
166        preserved.push(summary);
167        let messages = agent.messages_mut();
168        messages.splice(0..count, preserved);
169        Ok(true)
170    }
171}
172
173#[async_trait]
174impl ConversationManager for SummarizingConversationManager {
175    fn name(&self) -> &str {
176        "strands:summarizing-conversation-manager"
177    }
178
179    /// Summarizes with this model > the agent's aux model > the agent's model; the triggering
180    /// model is not used. During overflow recovery a failed summary is returned as the error, with
181    /// the overflow as its source; during proactive compression it is logged and `false` returned.
182    async fn reduce(&self, options: ConversationManagerReduceOptions<'_>) -> Result<bool> {
183        let ConversationManagerReduceOptions {
184            agent,
185            error,
186            invocation_context,
187            ..
188        } = options;
189        let model = self.model.clone().unwrap_or_else(|| agent.aux_model().clone());
190        let outcome = self.summarize_oldest(agent, &model, invocation_context.as_ref()).await;
191        match (outcome, error) {
192            (Ok(reduced), _) => Ok(reduced),
193            (Err(failure), Some(overflow)) => {
194                tracing::error!("error=<{failure}> | summarization failed");
195                Err(Error::other(SummarizationFailed {
196                    error: failure,
197                    overflow,
198                }))
199            }
200            (Err(failure), None) => {
201                tracing::warn!("error=<{failure}> | proactive summarization failed, continuing");
202                Ok(false)
203            }
204        }
205    }
206
207    fn compression_threshold(&self) -> Option<f64> {
208        self.compression_threshold
209    }
210}