strands/conversation_manager/
mod.rs1pub(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
52pub(crate) const DEFAULT_COMPRESSION_THRESHOLD: f64 = 0.7;
54
55#[non_exhaustive]
57pub struct ConversationManagerReduceOptions<'a> {
58 pub agent: &'a mut LocalAgent,
60 pub model: Arc<dyn Model>,
63 pub error: Option<ContextWindowOverflowError>,
66 pub invocation_context: Option<InvocationContext>,
69}
70
71impl<'a> ConversationManagerReduceOptions<'a> {
72 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 #[must_use]
84 pub fn with_error(mut self, error: ContextWindowOverflowError) -> Self {
85 self.error = Some(error);
86 self
87 }
88
89 #[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#[derive(Debug, Clone, Copy, Default, PartialEq)]
108#[non_exhaustive]
109pub enum ProactiveCompression {
110 #[default]
112 Disabled,
113 Enabled,
115 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 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#[async_trait]
178pub trait ConversationManager: Send + Sync + 'static {
179 fn name(&self) -> &str;
181
182 async fn reduce(&self, options: ConversationManagerReduceOptions<'_>) -> Result<bool>;
192
193 fn compression_threshold(&self) -> Option<f64> {
197 None
198 }
199
200 async fn init_agent(&self, _agent: &mut LocalAgent) -> Result<()> {
206 Ok(())
207 }
208}
209
210#[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
231pub(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
242async 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;