Skip to main content

strands/conversation_manager/
mod.rs

1//! Conversation history management.
2//!
3//! A [`ConversationManager`] keeps the history within the model's context window. When the model
4//! reports a [`ContextWindowOverflowError`], the agent calls [`ConversationManager::reduce`] with
5//! the error and retries the call if the history was reduced; when the error persists it leaves
6//! the agent loop. With proactive compression enabled, the agent also calls `reduce` (without an
7//! error) before a model call whose projected input exceeds the threshold.
8//!
9//! The built-in managers are [`SlidingWindowConversationManager`] (the default, 40 messages),
10//! [`SummarizingConversationManager`] and [`NullConversationManager`].
11//!
12//! ```
13//! use strands::Agent;
14//! use strands::conversation_manager::{SlidingWindowConversationManager, SlidingWindowConversationManagerConfig};
15//! use strands::testing::MockModel;
16//!
17//! let manager = SlidingWindowConversationManager::new(SlidingWindowConversationManagerConfig {
18//!     window_size: Some(20),
19//!     ..Default::default()
20//! })?;
21//! let agent = Agent::builder()
22//!     .model(MockModel::new())
23//!     .conversation_manager(manager)
24//!     .printer(false)
25//!     .build()?;
26//! # let _ = agent;
27//! # Ok::<(), strands::Error>(())
28//! ```
29
30pub(crate) mod compression;
31mod null_conversation_manager;
32mod sliding_window_conversation_manager;
33mod summarizing_conversation_manager;
34
35use std::fmt;
36use std::sync::Arc;
37
38use async_trait::async_trait;
39
40pub use null_conversation_manager::NullConversationManager;
41pub use sliding_window_conversation_manager::{
42    SlidingWindowConversationManager, SlidingWindowConversationManagerConfig,
43};
44pub use summarizing_conversation_manager::{SummarizingConversationManager, SummarizingConversationManagerConfig};
45
46use crate::agent::{InvocationContext, LocalAgent};
47use crate::error::{ContextWindowOverflowError, Error, Result};
48use crate::hooks::{AfterModelCallEvent, BeforeModelCallEvent};
49use crate::models::Model;
50use crate::plugins::Plugin;
51
52/// The default proactive compression threshold (`DEFAULT_COMPRESSION_THRESHOLD`).
53pub(crate) const DEFAULT_COMPRESSION_THRESHOLD: f64 = 0.7;
54
55/// What [`ConversationManager::reduce`] gets (`ConversationManagerReduceOptions`).
56#[non_exhaustive]
57pub struct ConversationManagerReduceOptions<'a> {
58    /// The agent; reduce `agent.messages_mut()` in place.
59    pub agent: &'a mut LocalAgent,
60    /// The model of the call that triggered the reduction. Use it to size the reduction;
61    /// managers that reduce through a model call resolve their own, usually the aux model.
62    pub model: Arc<dyn Model>,
63    /// The overflow that triggered the call, or `None` for proactive compression. When set,
64    /// `reduce` must remove enough history for the next call to succeed.
65    pub error: Option<ContextWindowOverflowError>,
66    /// The request the reduction runs for; a nested model call adds to its usage, but its limits
67    /// do not apply.
68    pub invocation_context: Option<InvocationContext>,
69}
70
71impl<'a> ConversationManagerReduceOptions<'a> {
72    /// Options for a proactive reduction of `agent`'s history.
73    pub fn new(agent: &'a mut LocalAgent, model: Arc<dyn Model>) -> Self {
74        Self {
75            agent,
76            model,
77            error: None,
78            invocation_context: None,
79        }
80    }
81
82    /// Marks the reduction as recovery from `error`.
83    #[must_use]
84    pub fn with_error(mut self, error: ContextWindowOverflowError) -> Self {
85        self.error = Some(error);
86        self
87    }
88
89    /// Sets the request the reduction runs for.
90    #[must_use]
91    pub fn with_invocation_context(mut self, invocation_context: Option<InvocationContext>) -> Self {
92        self.invocation_context = invocation_context;
93        self
94    }
95}
96
97impl fmt::Debug for ConversationManagerReduceOptions<'_> {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.debug_struct("ConversationManagerReduceOptions")
100            .field("model", &self.model.model_id())
101            .field("error", &self.error)
102            .finish_non_exhaustive()
103    }
104}
105
106/// When proactive compression runs.
107#[derive(Debug, Clone, Copy, Default, PartialEq)]
108#[non_exhaustive]
109pub enum ProactiveCompression {
110    /// Only reactive overflow recovery (`false` or omitted).
111    #[default]
112    Disabled,
113    /// Compress at 70% of the context window (`true`).
114    Enabled,
115    /// Compress at this ratio of the context window, in `(0, 1]` (`{ compressionThreshold }`).
116    Threshold(f64),
117}
118
119impl From<bool> for ProactiveCompression {
120    fn from(enabled: bool) -> Self {
121        if enabled { Self::Enabled } else { Self::Disabled }
122    }
123}
124
125impl ProactiveCompression {
126    /// The threshold ratio, or `None` when disabled.
127    ///
128    /// # Errors
129    ///
130    /// A threshold outside `(0, 1]`.
131    pub fn threshold(self) -> Result<Option<f64>> {
132        let threshold = match self {
133            Self::Disabled => return Ok(None),
134            Self::Enabled => DEFAULT_COMPRESSION_THRESHOLD,
135            Self::Threshold(threshold) => threshold,
136        };
137        if threshold.is_nan() || threshold <= 0.0 || threshold > 1.0 {
138            return Err(Error::other(format!(
139                "compressionThreshold must be between 0 (exclusive) and 1 (inclusive), got {threshold}"
140            )));
141        }
142        Ok(Some(threshold))
143    }
144}
145
146/// A conversation history strategy (`ConversationManager`).
147///
148/// The agent registers it as a plugin: on a context-window overflow it calls
149/// [`reduce`](Self::reduce) with the error and retries when it returns `true`; before a model
150/// call it calls `reduce` without an error when [`compression_threshold`](Self::compression_threshold)
151/// is set and the projected input reaches it. [`init_agent`](Self::init_agent) adds any other
152/// hooks the strategy needs.
153///
154/// ```
155/// use strands::async_trait;
156/// use strands::conversation_manager::{ConversationManager, ConversationManagerReduceOptions};
157///
158/// struct LastTenMessages;
159///
160/// #[async_trait]
161/// impl ConversationManager for LastTenMessages {
162///     fn name(&self) -> &str {
163///         "my:last-10-messages"
164///     }
165///
166///     async fn reduce(&self, options: ConversationManagerReduceOptions<'_>) -> strands::Result<bool> {
167///         let messages = options.agent.messages_mut();
168///         if messages.len() <= 10 {
169///             return Ok(false);
170///         }
171///         let excess = messages.len() - 10;
172///         messages.drain(..excess);
173///         Ok(true)
174///     }
175/// }
176/// ```
177#[async_trait]
178pub trait ConversationManager: Send + Sync + 'static {
179    /// A stable identifier, also the plugin name.
180    fn name(&self) -> &str;
181
182    /// Reduces the history and returns whether it changed (`reduce`).
183    ///
184    /// With `options.error` set this is overflow recovery and must make progress, or the overflow
185    /// leaves the agent loop. Without it, it is best-effort proactive compression.
186    ///
187    /// # Errors
188    ///
189    /// A reduction that failed. During recovery the error replaces the overflow error; during
190    /// proactive compression it is logged and the call proceeds.
191    async fn reduce(&self, options: ConversationManagerReduceOptions<'_>) -> Result<bool>;
192
193    /// The proactive compression threshold, or `None` when only overflow recovery runs: the
194    /// ratio of the context window, in `(0, 1]`, at which a model call reduces first. The agent
195    /// checks it when the manager is initialized and fails otherwise.
196    fn compression_threshold(&self) -> Option<f64> {
197        None
198    }
199
200    /// Registers the strategy's own hooks, after the overflow and compression hooks.
201    ///
202    /// # Errors
203    ///
204    /// A failed initialization; the agent's first invocation reports it.
205    async fn init_agent(&self, _agent: &mut LocalAgent) -> Result<()> {
206        Ok(())
207    }
208}
209
210/// A shared manager is a manager, so the builder's `conversation_manager(..)` takes one by value
211/// or as an `Arc`.
212#[async_trait]
213impl<M: ConversationManager + ?Sized> ConversationManager for Arc<M> {
214    fn name(&self) -> &str {
215        (**self).name()
216    }
217
218    async fn reduce(&self, options: ConversationManagerReduceOptions<'_>) -> Result<bool> {
219        (**self).reduce(options).await
220    }
221
222    fn compression_threshold(&self) -> Option<f64> {
223        (**self).compression_threshold()
224    }
225
226    async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
227        (**self).init_agent(agent).await
228    }
229}
230
231/// Registers a conversation manager's hooks on an agent (`ConversationManager.initAgent`).
232pub(crate) struct ConversationManagerPlugin {
233    manager: Arc<dyn ConversationManager>,
234}
235
236impl ConversationManagerPlugin {
237    pub(crate) fn new(manager: Arc<dyn ConversationManager>) -> Self {
238        Self { manager }
239    }
240}
241
242/// Reactive overflow recovery: a reduction error fails the invocation with it.
243async fn recover_from_overflow(manager: &dyn ConversationManager, event: &mut AfterModelCallEvent<'_>) -> Result<()> {
244    let Some(Error::ContextWindowOverflow(error)) = event.error() else {
245        return Ok(());
246    };
247    let error = error.clone();
248    let model = event.model().clone();
249    let invocation_context = InvocationContext::auxiliary(event.invocation_context());
250    let options = ConversationManagerReduceOptions::new(event.agent_mut(), model)
251        .with_error(error)
252        .with_invocation_context(invocation_context);
253    if manager.reduce(options).await? {
254        event.set_retry(true);
255    }
256    Ok(())
257}
258
259async fn compress_proactively(manager: &dyn ConversationManager, event: &mut BeforeModelCallEvent<'_>) {
260    let Some(threshold) = manager.compression_threshold() else {
261        return;
262    };
263    let Some(projected) = event.projected_input_tokens() else {
264        return;
265    };
266    let ratio = event.model().estimate_utilization(projected);
267    if ratio < threshold {
268        return;
269    }
270    tracing::debug!(
271        "projected_tokens=<{projected}>, ratio=<{ratio:.2}>, compression_threshold=<{threshold}> | compression threshold exceeded, reducing context"
272    );
273    let model = event.model().clone();
274    let invocation_context = InvocationContext::auxiliary(event.invocation_context());
275    let options =
276        ConversationManagerReduceOptions::new(event.agent_mut(), model).with_invocation_context(invocation_context);
277    if let Err(error) = manager.reduce(options).await {
278        tracing::warn!(
279            "conversation_manager=<{}> | proactive compression failed, continuing | error=<{error}>",
280            manager.name()
281        );
282    }
283}
284
285#[async_trait]
286impl Plugin for ConversationManagerPlugin {
287    fn name(&self) -> &str {
288        self.manager.name()
289    }
290
291    async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
292        if let Some(threshold) = self.manager.compression_threshold() {
293            ProactiveCompression::Threshold(threshold).threshold()?;
294        }
295        let manager = self.manager.clone();
296        agent.add_async_hook::<AfterModelCallEvent<'_>>(move |event| {
297            let manager = manager.clone();
298            Box::pin(async move { recover_from_overflow(manager.as_ref(), event).await })
299        });
300        let manager = self.manager.clone();
301        agent.add_async_hook::<BeforeModelCallEvent<'_>>(move |event| {
302            let manager = manager.clone();
303            Box::pin(async move { compress_proactively(manager.as_ref(), event).await })
304        });
305        self.manager.init_agent(agent).await
306    }
307}
308
309#[cfg(test)]
310mod tests;