Skip to main content

strands/context_manager/
presets.rs

1//! Strategy presets: named building blocks that resolve to strategy configurations.
2//!
3//! The preset name is the stable contract; the strategies it expands to may be retuned between
4//! releases. Use [`Offload`] strategies directly for a pinned configuration.
5
6use std::fmt;
7use std::str::FromStr;
8use std::sync::Arc;
9
10use super::methods::truncate::TruncateConfig;
11use super::strategies::deferred_tool_loading::{DeferConditions, DeferTarget};
12use super::strategies::offload::{ConditionValue, Offload, OffloadConditions, OffloadTarget, SummarizeConfig};
13use super::types::ContextStrategy;
14use crate::error::{Error, Result};
15
16/// A named strategy preset (`StrategyPresetName`).
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum StrategyPresetName {
20    /// Summarizes the oldest 30% of messages at 70% context utilization
21    /// (`proactiveSummarization`).
22    ProactiveSummarization,
23    /// Truncates tool results over 2,500 tokens to a 1,000-token preview (`largeToolOffloading`).
24    LargeToolOffloading,
25    /// Drops the oldest messages when the context window is full (`overflowProtection`).
26    OverflowProtection,
27    /// Drops tool results outside the newest five tool-result messages (`staleToolCleanup`).
28    StaleToolCleanup,
29    /// Experimental: from 20 tools, the SDK's own included, defers tools' input schemas until the
30    /// model loads them (`deferredToolLoading`). Claude 4.5 and later defer natively through
31    /// `AnthropicModel`, most other models get each deferred tool as a stub (name and
32    /// description), and models that can't use stubs (`DeferredToolLoading::Unsupported`) get
33    /// every spec. The SDK's own tools and tools without parameters are always sent in full and
34    /// every other tool is deferred, so the model loads even its most used tools first;
35    /// [`Offload::defer`] keeps the ones you name.
36    DeferredToolLoading,
37}
38
39/// Every preset, in their canonical order.
40pub(crate) const STRATEGY_PRESET_NAMES: [StrategyPresetName; 5] = [
41    StrategyPresetName::ProactiveSummarization,
42    StrategyPresetName::LargeToolOffloading,
43    StrategyPresetName::OverflowProtection,
44    StrategyPresetName::StaleToolCleanup,
45    StrategyPresetName::DeferredToolLoading,
46];
47
48impl StrategyPresetName {
49    /// The preset's config name, such as `largeToolOffloading`.
50    #[must_use]
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::ProactiveSummarization => "proactiveSummarization",
54            Self::LargeToolOffloading => "largeToolOffloading",
55            Self::OverflowProtection => "overflowProtection",
56            Self::StaleToolCleanup => "staleToolCleanup",
57            Self::DeferredToolLoading => "deferredToolLoading",
58        }
59    }
60}
61
62impl fmt::Display for StrategyPresetName {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(self.as_str())
65    }
66}
67
68impl FromStr for StrategyPresetName {
69    type Err = Error;
70
71    fn from_str(name: &str) -> Result<Self> {
72        STRATEGY_PRESET_NAMES
73            .into_iter()
74            .find(|preset| preset.as_str() == name)
75            .ok_or_else(|| {
76                let valid: Vec<&str> = STRATEGY_PRESET_NAMES.iter().map(|preset| preset.as_str()).collect();
77                Error::other(format!(
78                    "Unknown strategy preset: \"{name}\". Valid presets: {}",
79                    valid.join(", ")
80                ))
81            })
82    }
83}
84
85/// A strategy or a preset name in [`ContextManagerConfig::strategies`](super::ContextManagerConfig).
86#[derive(Clone)]
87#[non_exhaustive]
88pub enum StrategyEntry {
89    /// A strategy, used as is.
90    Strategy(Arc<dyn ContextStrategy>),
91    /// A preset, expanded to its strategies.
92    Preset(StrategyPresetName),
93}
94
95impl fmt::Debug for StrategyEntry {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        match self {
98            Self::Strategy(strategy) => f.debug_tuple("Strategy").field(&strategy.name()).finish(),
99            Self::Preset(preset) => f.debug_tuple("Preset").field(preset).finish(),
100        }
101    }
102}
103
104impl From<StrategyPresetName> for StrategyEntry {
105    fn from(preset: StrategyPresetName) -> Self {
106        Self::Preset(preset)
107    }
108}
109
110impl From<Arc<dyn ContextStrategy>> for StrategyEntry {
111    fn from(strategy: Arc<dyn ContextStrategy>) -> Self {
112        Self::Strategy(strategy)
113    }
114}
115
116impl<S: ContextStrategy> From<S> for StrategyEntry {
117    fn from(strategy: S) -> Self {
118        Self::Strategy(Arc::new(strategy))
119    }
120}
121
122fn conditions(
123    context_utilization: Option<&str>,
124    block_threshold: Option<u64>,
125    preserve_recent: Option<ConditionValue>,
126) -> OffloadConditions {
127    OffloadConditions {
128        context_utilization: context_utilization.map(ConditionValue::from),
129        block_threshold: block_threshold.map(ConditionValue::from),
130        preserve_recent,
131    }
132}
133
134fn preview(tokens: f64) -> TruncateConfig {
135    TruncateConfig {
136        preview_tokens: Some(tokens),
137        ..TruncateConfig::default()
138    }
139}
140
141/// The strategies a preset stands for. Defaults are tuning decisions, not API promises.
142pub(crate) fn resolve_preset(name: StrategyPresetName) -> Result<Vec<Arc<dyn ContextStrategy>>> {
143    let strategy: Arc<dyn ContextStrategy> = match name {
144        StrategyPresetName::ProactiveSummarization => Arc::new(
145            Offload::summarize(OffloadTarget::All, SummarizeConfig::default())?.when(conditions(
146                Some("70%"),
147                None,
148                Some("70%".into()),
149            ))?,
150        ),
151        StrategyPresetName::LargeToolOffloading => Arc::new(
152            Offload::truncate(OffloadTarget::ToolResults, preview(1000.0))?.when(conditions(None, Some(2500), None))?,
153        ),
154        StrategyPresetName::OverflowProtection => {
155            Arc::new(Offload::drop(OffloadTarget::All)?.when(conditions(Some("100%"), None, Some(4.into())))?)
156        }
157        StrategyPresetName::StaleToolCleanup => {
158            Arc::new(Offload::drop(OffloadTarget::ToolResults)?.when(conditions(None, None, Some(5.into())))?)
159        }
160        StrategyPresetName::DeferredToolLoading => {
161            Arc::new(Offload::defer(DeferTarget::ToolSpecs)?.when(DeferConditions {
162                tool_count: Some(20.into()),
163                ..DeferConditions::default()
164            })?)
165        }
166    };
167    Ok(vec![strategy])
168}
169
170/// Expands presets in a mixed list of strategies and presets, keeping the order.
171pub(crate) fn resolve_strategies(entries: &[StrategyEntry]) -> Result<Vec<Arc<dyn ContextStrategy>>> {
172    let mut strategies = Vec::new();
173    for entry in entries {
174        match entry {
175            StrategyEntry::Strategy(strategy) => strategies.push(strategy.clone()),
176            StrategyEntry::Preset(preset) => strategies.extend(resolve_preset(*preset)?),
177        }
178    }
179    Ok(strategies)
180}
181
182#[cfg(test)]
183#[path = "presets/tests.rs"]
184mod tests;