Skip to main content

strands/context_manager/methods/
truncate.rs

1//! The truncate reduction method: replaces content with a head, tail or head-and-tail preview.
2
3use crate::context_manager::js_text::{Utf16Text, with_separators};
4use crate::context_manager::placeholder::{format_truncated, is_offloaded_content};
5use crate::types::{TextBlock, ToolResultBlock, ToolResultContent};
6
7const DEFAULT_PREVIEW_TOKENS: f64 = 1000.0;
8const CHARS_PER_TOKEN: f64 = 4.0;
9
10/// Which part of the text a preview keeps.
11#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum PreviewMode {
14    /// The start of the text.
15    Head,
16    /// The end of the text.
17    Tail,
18    /// 60% from the start and 40% from the end (the default).
19    #[default]
20    HeadTail,
21}
22
23impl PreviewMode {
24    /// The share of the preview budget kept from the head; the rest is kept from the tail
25    /// (`PREVIEW_HEAD_SHARE`).
26    pub(crate) fn head_share(self) -> f64 {
27        match self {
28            Self::Head => 1.0,
29            Self::Tail => 0.0,
30            Self::HeadTail => 0.6,
31        }
32    }
33}
34
35/// Configuration of the truncate method (`TruncateConfig`).
36#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
37pub struct TruncateConfig {
38    /// Tokens of text to keep as the preview. Defaults to 1,000. Content that already fits is left
39    /// unchanged. For a whole-message truncate, the budget of whole messages kept at the head and
40    /// tail; the rest are replaced by one `[... earlier messages elided, ~N tokens ...]` marker.
41    pub preview_tokens: Option<f64>,
42    /// Which part of the text to keep. Defaults to [`PreviewMode::HeadTail`]. For a whole-message
43    /// truncate, [`PreviewMode::Head`] keeps only the oldest messages and [`PreviewMode::Tail`] only
44    /// the newest.
45    pub preview: Option<PreviewMode>,
46}
47
48impl TruncateConfig {
49    /// The preview token budget, defaulting to 1,000 and never below 0 (`resolvePreviewTokens`).
50    pub(crate) fn resolve_preview_tokens(&self) -> f64 {
51        self.preview_tokens
52            .filter(|tokens| tokens.is_finite())
53            .map_or(DEFAULT_PREVIEW_TOKENS, |tokens| tokens.max(0.0))
54    }
55}
56
57#[allow(
58    clippy::cast_possible_truncation,
59    clippy::cast_sign_loss,
60    clippy::cast_precision_loss,
61    reason = "character counts are far below 2^52 and the floored values are non-negative"
62)]
63/// A preview of `full_text` with a truncation header, or `full_text` itself when it already fits
64/// or the preview would not be shorter.
65pub(crate) fn build_preview(full_text: &str, block_count: usize, config: &TruncateConfig) -> String {
66    let preview_chars = config.resolve_preview_tokens() * CHARS_PER_TOKEN;
67    let text = Utf16Text::new(full_text);
68    let total_chars = text.len();
69    if total_chars as f64 <= preview_chars {
70        return full_text.to_owned();
71    }
72    let head_share = config.preview.unwrap_or_default().head_share();
73    let head_chars = (preview_chars * head_share).floor() as usize;
74    let tail_chars = (preview_chars as usize).saturating_sub(head_chars);
75    let head = text.slice(0, head_chars);
76    let tail = if tail_chars > 0 {
77        text.slice(total_chars.saturating_sub(tail_chars), total_chars)
78    } else {
79        String::new()
80    };
81    let elided = total_chars.saturating_sub(head_chars + tail_chars);
82    let marker = format!("[... {} chars elided ...]", with_separators(elided as u64));
83    let preview = [head, marker, tail]
84        .into_iter()
85        .filter(|part| !part.is_empty())
86        .collect::<Vec<_>>()
87        .join("\n\n");
88    let tokens = (total_chars as f64 / CHARS_PER_TOKEN).ceil() as u64;
89    let result = format_truncated(block_count, tokens, &preview);
90    if Utf16Text::new(&result).len() >= total_chars {
91        return full_text.to_owned();
92    }
93    result
94}
95
96/// A tool result split by [`truncate_tool_result_block`] (`TruncatedToolResult`).
97#[derive(Debug, Clone, PartialEq)]
98pub(crate) struct TruncatedToolResult {
99    /// Preview of the result's text and JSON items.
100    pub(crate) preview: String,
101    /// Items kept as they are: media, whose payload can't be previewed as text, and placeholders.
102    pub(crate) kept: Vec<ToolResultContent>,
103}
104
105/// Splits a tool result into a preview of its text and JSON items and the items kept as they are;
106/// `None` when nothing would be truncated.
107pub(crate) fn truncate_tool_result_block(
108    block: &ToolResultBlock,
109    config: &TruncateConfig,
110) -> Option<TruncatedToolResult> {
111    let mut textual = Vec::new();
112    let mut kept = Vec::new();
113    for content in &block.content {
114        match content {
115            ToolResultContent::Text(text) if !is_offloaded_content(content) => textual.push(text.text.clone()),
116            ToolResultContent::Json(_) => textual.push(serde_json::to_string(content).unwrap_or_default()),
117            other => kept.push(other.clone()),
118        }
119    }
120    if textual.is_empty() {
121        return None;
122    }
123    let full_text = textual.join("\n");
124    let preview = build_preview(&full_text, textual.len(), config);
125    (preview != full_text).then_some(TruncatedToolResult { preview, kept })
126}
127
128/// The preview of a text block, or `None` when the preview would not be shorter
129/// (`truncateTextBlock`).
130pub(crate) fn truncate_text_block(block: &TextBlock, config: &TruncateConfig) -> Option<String> {
131    let preview = build_preview(&block.text, 1, config);
132    (preview != block.text).then_some(preview)
133}