Skip to main content

strands/context_manager/strategies/offload/
truncate.rs

1//! The truncate strategy: replaces oversized content with a preview, or elides the middle of the
2//! conversation.
3
4use std::sync::Arc;
5
6use async_trait::async_trait;
7
8use super::base::{OffloadBehavior, OffloadCore};
9use super::conditions::OffloadConditions;
10use super::target::{OffloadTarget, media_kind};
11use crate::agent::{InvocationContext, LocalAgent};
12use crate::context_manager::archive::Archive;
13use crate::context_manager::message_trimming::{FormattedPlaceholder, remove_messages, with_pairs};
14use crate::context_manager::methods::truncate::{TruncateConfig, truncate_text_block, truncate_tool_result_block};
15use crate::context_manager::placeholder::{format_elided, format_offloaded, is_offloaded};
16use crate::context_manager::types::{ContextState, ContextStrategy};
17use crate::error::{Error, Result};
18use crate::models::CountTokensOptions;
19use crate::types::{ContentBlock, Message, OffloadMethod, ToolResultContent};
20
21struct TruncateBehavior {
22    config: TruncateConfig,
23    preview_tokens: f64,
24}
25
26impl TruncateBehavior {
27    #[allow(clippy::cast_precision_loss, reason = "token counts are far below 2^52")]
28    /// The eligible messages between the head and tail kept within the preview token budget.
29    async fn select_middle(&self, eligible: &[usize], agent: &LocalAgent) -> Result<Vec<usize>> {
30        let head_budget = self.preview_tokens * self.config.preview.unwrap_or_default().head_share();
31        let head_count = count_within_budget(eligible.iter().copied(), head_budget, agent).await?;
32        let rest = &eligible[head_count..];
33        let tail_count =
34            count_within_budget(rest.iter().rev().copied(), self.preview_tokens - head_budget, agent).await?;
35        Ok(rest[..rest.len() - tail_count].to_vec())
36    }
37}
38
39#[allow(clippy::cast_precision_loss, reason = "token counts are far below 2^52")]
40/// How many leading messages fit within `budget` tokens.
41async fn count_within_budget(indices: impl Iterator<Item = usize>, budget: f64, agent: &LocalAgent) -> Result<usize> {
42    let mut total = 0u64;
43    let mut count = 0;
44    for index in indices {
45        total += agent
46            .model()
47            .count_tokens(
48                std::slice::from_ref(&agent.messages()[index]),
49                CountTokensOptions::default(),
50            )
51            .await?;
52        if total as f64 > budget {
53            break;
54        }
55        count += 1;
56    }
57    Ok(count)
58}
59
60#[async_trait]
61impl OffloadBehavior for TruncateBehavior {
62    async fn replace_block(
63        &self,
64        core: &OffloadCore,
65        block: &ContentBlock,
66        tokens: u64,
67        message: &Message,
68        _agent: &LocalAgent,
69        archive_ref: Option<&str>,
70        _tool_name: Option<&str>,
71        _invocation_context: Option<&InvocationContext>,
72    ) -> Result<Option<ContentBlock>> {
73        match block {
74            ContentBlock::ToolResult(result) => {
75                let Some(truncated) = truncate_tool_result_block(result, &self.config) else {
76                    return Ok(None);
77                };
78                tracing::debug!(
79                    "tool_use_id=<{}>, tokens=<{tokens}> | truncated tool result",
80                    result.tool_use_id
81                );
82                let mut content = vec![ToolResultContent::Text(core.placeholder(
83                    &truncated.preview,
84                    archive_ref,
85                    tokens,
86                ))];
87                content.extend(truncated.kept);
88                Ok(Some(ContentBlock::ToolResult(result.clone().with_content(content))))
89            }
90            ContentBlock::Text(text) => {
91                let Some(preview) = truncate_text_block(text, &self.config) else {
92                    return Ok(None);
93                };
94                tracing::debug!(
95                    "tracking_id=<{}>, tokens=<{tokens}> | truncated text block",
96                    message.tracking_id()
97                );
98                Ok(Some(ContentBlock::Text(core.placeholder(
99                    &preview,
100                    archive_ref,
101                    tokens,
102                ))))
103            }
104            other => {
105                tracing::debug!(
106                    "tracking_id=<{}>, tokens=<{tokens}> | offloaded media block",
107                    message.tracking_id()
108                );
109                Ok(Some(ContentBlock::Text(core.placeholder(
110                    &format_offloaded(tokens, media_kind(other)),
111                    archive_ref,
112                    tokens,
113                ))))
114            }
115        }
116    }
117
118    /// Middle-out: keeps the oldest and newest eligible messages within the preview budget and
119    /// elides the rest.
120    async fn apply_per_message(&self, core: &OffloadCore, context: &mut ContextState<'_>) -> Result<bool> {
121        let removable = core.removable_messages(context.agent).await?;
122        let middle = with_pairs(
123            context.agent.messages(),
124            &self.select_middle(&removable, context.agent).await?,
125        );
126        // A middle of only placeholders has nothing new to elide.
127        let messages = context.agent.messages();
128        if middle
129            .iter()
130            .all(|&index| messages[index].content.iter().all(is_offloaded))
131        {
132            return Ok(false);
133        }
134        let text = FormattedPlaceholder::new(format_elided);
135        let archive = core.archive();
136        remove_messages(context.agent, &middle, &text, OffloadMethod::Truncate, archive.as_ref()).await
137    }
138}
139
140/// Replaces oversized content with a preview (`Offload.truncate`), built with
141/// [`Offload::truncate`](super::Offload::truncate). On whole messages it keeps the oldest and
142/// newest within the preview budget and elides the rest.
143pub struct TruncateStrategy {
144    core: Arc<OffloadCore>,
145    behavior: Arc<TruncateBehavior>,
146}
147
148impl TruncateStrategy {
149    pub(crate) fn new(
150        target: OffloadTarget,
151        config: TruncateConfig,
152        conditions: Option<OffloadConditions>,
153    ) -> Result<Self> {
154        let core = OffloadCore::new(OffloadMethod::Truncate, target, conditions)?;
155        let preview_tokens = config.resolve_preview_tokens();
156        // Every message over a threshold is larger than previewTokens, so middle-out would elide
157        // them all, as drop does.
158        if core.matcher.matches_all() && core.conditions.block_threshold.is_some() {
159            return Err(Error::other(
160                "Offload.truncate('*') doesn't take a blockThreshold; use Offload.drop('*') to remove large messages, or Offload.truncate('toolResults') to preview large blocks",
161            ));
162        }
163        // A percent needs the context window, so init checks it.
164        if let Some(threshold) = core.conditions.block_threshold.filter(|threshold| !threshold.is_share) {
165            check_threshold_exceeds_preview(threshold.value, &js_count(threshold.value), preview_tokens)?;
166        }
167        Ok(Self {
168            core: Arc::new(core),
169            behavior: Arc::new(TruncateBehavior { config, preview_tokens }),
170        })
171    }
172
173    /// A copy of this strategy, with the same target and config, under `conditions` (`when`). A
174    /// strategy keeps per-agent state, so give each agent its own.
175    ///
176    /// # Errors
177    ///
178    /// An invalid condition value, conditions that leave the strategy unable to run, a
179    /// `block_threshold` on whole messages, or one no larger than the preview.
180    pub fn when(&self, conditions: OffloadConditions) -> Result<Self> {
181        Self::new(
182            self.core.target().clone(),
183            self.behavior.config.clone(),
184            Some(conditions),
185        )
186    }
187}
188
189#[allow(
190    clippy::cast_possible_truncation,
191    clippy::cast_sign_loss,
192    reason = "a whole token count"
193)]
194fn js_count(value: f64) -> String {
195    (value as u64).to_string()
196}
197
198fn js_tokens(value: f64) -> String {
199    if value.fract() == 0.0 {
200        return js_count(value);
201    }
202    value.to_string()
203}
204
205#[allow(clippy::cast_precision_loss, reason = "token counts are far below 2^52")]
206fn check_threshold_exceeds_preview(tokens: f64, shown: &str, preview_tokens: f64) -> Result<()> {
207    if tokens > preview_tokens {
208        return Ok(());
209    }
210    Err(Error::other(format!(
211        "blockThreshold ({shown}) must be greater than previewTokens ({}) to ensure truncation converges; raise blockThreshold or lower previewTokens",
212        js_tokens(preview_tokens)
213    )))
214}
215
216impl std::fmt::Debug for TruncateStrategy {
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        f.debug_struct("TruncateStrategy")
219            .field("target", self.core.target())
220            .field("conditions", &self.core.offload_conditions)
221            .field("config", &self.behavior.config)
222            .finish_non_exhaustive()
223    }
224}
225
226#[async_trait]
227impl ContextStrategy for TruncateStrategy {
228    fn name(&self) -> &str {
229        &self.core.name
230    }
231
232    /// Checks a percent `block_threshold` against the preview, then initializes the strategy.
233    #[allow(clippy::cast_precision_loss, reason = "token counts are far below 2^52")]
234    fn init(&self, agent: &mut LocalAgent, archive: Option<&Archive>) -> Result<()> {
235        if self
236            .core
237            .conditions
238            .block_threshold
239            .is_some_and(|threshold| threshold.is_share)
240            && let Some(tokens) = self.core.conditions.threshold_tokens(agent)
241        {
242            check_threshold_exceeds_preview(
243                tokens as f64,
244                &format!("{tokens} tokens of the context window"),
245                self.behavior.preview_tokens,
246            )?;
247        }
248        self.core.init(self.behavior.clone(), agent, archive)
249    }
250
251    async fn apply(&self, context: &mut ContextState<'_>) -> Result<bool> {
252        self.core.apply(self.behavior.as_ref(), context).await
253    }
254}