strands/context_manager/methods/
truncate.rs1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum PreviewMode {
14 Head,
16 Tail,
18 #[default]
20 HeadTail,
21}
22
23impl PreviewMode {
24 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#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
37pub struct TruncateConfig {
38 pub preview_tokens: Option<f64>,
42 pub preview: Option<PreviewMode>,
46}
47
48impl TruncateConfig {
49 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)]
63pub(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#[derive(Debug, Clone, PartialEq)]
98pub(crate) struct TruncatedToolResult {
99 pub(crate) preview: String,
101 pub(crate) kept: Vec<ToolResultContent>,
103}
104
105pub(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
128pub(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}