adk_core/intra_compaction.rs
1//! Auto-compaction: when an agent's history is compacted during a run, the token estimate
2//! that decides it, and the hook an agent calls before each model call.
3//!
4//! [`IntraCompactionConfig`] sets the threshold: by default a fraction of the model's
5//! context window ([`Llm::context_window`]), or
6//! [`DEFAULT_TOKEN_THRESHOLD`](crate::intra_compaction::DEFAULT_TOKEN_THRESHOLD) when the model
7//! reports none. [`HistoryCompactor`] is the hook: the runner installs one on
8//! [`RunConfig::history_compactor`](crate::RunConfig::history_compactor) at the start of each
9//! run, and `LlmAgent` and `CodeActAgent` call it before every model call, and once more when
10//! the model rejects a request as longer than its context window
11//! ([`is_context_limit_error`](crate::intra_compaction::is_context_limit_error)).
12//!
13//! The session-level [`EventsCompactionConfig`](crate::EventsCompactionConfig) compacts after
14//! every N invocations instead; both summarize through
15//! [`BaseEventsSummarizer`](crate::BaseEventsSummarizer).
16
17use std::sync::Arc;
18
19use async_trait::async_trait;
20
21use crate::{
22 AdkError, Content, ErrorCategory, ErrorComponent, Event, GenerateContentConfig,
23 InvocationContext, Llm, LlmRequest, Part, ToolDeclarations,
24};
25
26/// The threshold, in estimated tokens, when the model reports no context window.
27///
28/// The smallest context window of a current hosted model is about 128,000 tokens; this stays
29/// below it.
30pub const DEFAULT_TOKEN_THRESHOLD: u64 = 100_000;
31
32/// The share of the model's context window a request may reach before it is compacted.
33///
34/// The rest leaves room for the response and for the error of a character-based estimate.
35pub const DEFAULT_CONTEXT_WINDOW_FRACTION: f64 = 0.8;
36
37/// The share of the threshold at which a background compaction starts
38/// ([`IntraCompactionConfig::background`]).
39pub const DEFAULT_BACKGROUND_FRACTION: f64 = 0.7;
40
41/// When an agent's history is compacted during a run.
42///
43/// Before each model call, `LlmAgent` and `CodeActAgent` ask the run's
44/// [`HistoryCompactor`] to compact their history once the estimated request
45/// ([`estimate_content_tokens`]) or the prompt size the provider reported for the previous
46/// call passes [`threshold_for`](Self::threshold_for) the model. The runner's compactor
47/// summarizes all but the most recent history entries: at most `overlap_event_count` of
48/// them, within half the threshold.
49///
50/// The default is on: the threshold is [`DEFAULT_CONTEXT_WINDOW_FRACTION`] of the model's
51/// context window, or [`DEFAULT_TOKEN_THRESHOLD`] when the model reports none. A fixed
52/// `token_threshold` takes precedence over the window.
53///
54/// # Example
55///
56/// ```rust
57/// use adk_core::IntraCompactionConfig;
58/// use adk_core::intra_compaction::DEFAULT_TOKEN_THRESHOLD;
59///
60/// // On by default, at 80% of a 1,000,000-token window.
61/// let config = IntraCompactionConfig::default();
62/// assert_eq!(config.threshold_for(Some(1_000_000)), 800_000);
63/// assert_eq!(config.threshold_for(None), DEFAULT_TOKEN_THRESHOLD);
64///
65/// // A fixed threshold, whatever the window.
66/// let fixed = IntraCompactionConfig::at_tokens(50_000);
67/// assert_eq!(fixed.threshold_for(Some(1_000_000)), 50_000);
68///
69/// assert!(!IntraCompactionConfig::disabled().enabled);
70/// ```
71#[derive(Debug, Clone, PartialEq)]
72pub struct IntraCompactionConfig {
73 /// Whether history is compacted during a run.
74 pub enabled: bool,
75 /// A fixed threshold in estimated tokens. `None` derives it from the model's context
76 /// window.
77 pub token_threshold: Option<u64>,
78 /// The share of the model's context window a request may reach, when `token_threshold`
79 /// is `None` and the model reports its window. Values outside `(0, 1]` use
80 /// [`DEFAULT_CONTEXT_WINDOW_FRACTION`].
81 pub context_window_fraction: f64,
82 /// The most recent history entries kept as they are, within half the threshold.
83 pub overlap_event_count: usize,
84 /// Characters per token for the estimate (default: 4).
85 pub chars_per_token: u32,
86 /// Whether a model whose provider compacts conversations itself
87 /// ([`Llm::native_compaction`]) writes the summary, in place of the runner's summarizer
88 /// (default: `true`). A summarizer or strategy configured on the runner takes precedence.
89 pub native: bool,
90 /// Whether the summary is written off the critical path (default: `false`): once a request
91 /// passes `background_fraction` of the threshold, the runner starts the summary while the
92 /// agent goes on, and swaps it in before a later model call, in this run or the session's
93 /// next. A request that reaches the threshold first waits for it.
94 pub background: bool,
95 /// The share of the threshold at which a background compaction starts. Values outside
96 /// `(0, 1)` use [`DEFAULT_BACKGROUND_FRACTION`].
97 pub background_fraction: f64,
98}
99
100impl Default for IntraCompactionConfig {
101 fn default() -> Self {
102 Self {
103 enabled: true,
104 token_threshold: None,
105 context_window_fraction: DEFAULT_CONTEXT_WINDOW_FRACTION,
106 overlap_event_count: 10,
107 chars_per_token: 4,
108 native: true,
109 background: false,
110 background_fraction: DEFAULT_BACKGROUND_FRACTION,
111 }
112 }
113}
114
115impl IntraCompactionConfig {
116 /// Compaction turned off.
117 pub fn disabled() -> Self {
118 Self { enabled: false, ..Self::default() }
119 }
120
121 /// Compaction once a request passes `threshold` estimated tokens, whatever the model's
122 /// window.
123 pub fn at_tokens(threshold: u64) -> Self {
124 Self { token_threshold: Some(threshold), ..Self::default() }
125 }
126
127 /// Compaction once a request passes `fraction` of the model's context window.
128 pub fn at_window_fraction(fraction: f64) -> Self {
129 Self { context_window_fraction: fraction, ..Self::default() }
130 }
131
132 /// Keeps the `count` most recent history entries as they are.
133 pub fn with_overlap_event_count(mut self, count: usize) -> Self {
134 self.overlap_event_count = count;
135 self
136 }
137
138 /// Whether a model whose provider compacts conversations itself writes the summary.
139 ///
140 /// # Example
141 ///
142 /// ```rust
143 /// use adk_core::IntraCompactionConfig;
144 ///
145 /// // Always summarize with the runner's summarizer, even on a model that compacts natively.
146 /// let config = IntraCompactionConfig::default().with_native(false);
147 /// assert!(!config.native);
148 /// ```
149 pub fn with_native(mut self, native: bool) -> Self {
150 self.native = native;
151 self
152 }
153
154 /// Writes summaries off the critical path, starting each once a request passes `fraction`
155 /// of the threshold.
156 ///
157 /// The summary costs a model call that may come earlier than the threshold requires, and
158 /// it is swapped in only when the history still starts with the entries it covers.
159 ///
160 /// # Example
161 ///
162 /// ```rust
163 /// use adk_core::IntraCompactionConfig;
164 ///
165 /// // Start summarizing at 60% of the threshold, so the next turn rarely waits for it.
166 /// let config = IntraCompactionConfig::default().in_background(0.6);
167 /// assert!(config.background);
168 /// assert_eq!(config.background_threshold_for(Some(1_000_000)), 480_000);
169 /// ```
170 pub fn in_background(mut self, fraction: f64) -> Self {
171 self.background = true;
172 self.background_fraction = fraction;
173 self
174 }
175
176 /// The estimated tokens at which a background compaction starts, for a model with
177 /// `context_window` tokens: `background_fraction` of [`threshold_for`](Self::threshold_for).
178 pub fn background_threshold_for(&self, context_window: Option<u64>) -> u64 {
179 let fraction = if self.background_fraction > 0.0 && self.background_fraction < 1.0 {
180 self.background_fraction
181 } else {
182 DEFAULT_BACKGROUND_FRACTION
183 };
184 (self.threshold_for(context_window) as f64 * fraction) as u64
185 }
186
187 /// The threshold, in estimated tokens, for a model with `context_window` tokens.
188 ///
189 /// A fixed `token_threshold` wins; otherwise the window times
190 /// `context_window_fraction`, or [`DEFAULT_TOKEN_THRESHOLD`] for an unknown window.
191 pub fn threshold_for(&self, context_window: Option<u64>) -> u64 {
192 if let Some(threshold) = self.token_threshold {
193 return threshold;
194 }
195 let Some(window) = context_window else {
196 return DEFAULT_TOKEN_THRESHOLD;
197 };
198 let fraction = if self.context_window_fraction > 0.0 && self.context_window_fraction <= 1.0
199 {
200 self.context_window_fraction
201 } else {
202 DEFAULT_CONTEXT_WINDOW_FRACTION
203 };
204 (window as f64 * fraction) as u64
205 }
206}
207
208/// Why an agent asks its run's [`HistoryCompactor`] to compact.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum CompactionTrigger {
211 /// Before a model call: compacts when the request has passed the threshold.
212 BeforeModelCall,
213 /// The model rejected the request as longer than its context window
214 /// ([`is_context_limit_error`]): compacts whatever the estimate says, so the call can be
215 /// sent once more.
216 ContextLimitExceeded,
217}
218
219/// What an agent asks its run's [`HistoryCompactor`] to compact.
220///
221/// # Example
222///
223/// ```rust
224/// use adk_core::{CompactionTrigger, Content, HistoryCompactionRequest, ToolDeclarations};
225///
226/// let instructions = [Content::new("system").with_text("You are a release assistant.")];
227/// let history = [Content::new("user").with_text("Draft the release notes.")];
228/// let tools = ToolDeclarations::new();
229/// let request = HistoryCompactionRequest::new(&history, CompactionTrigger::BeforeModelCall)
230/// .with_preamble(&instructions)
231/// .with_tools(&tools)
232/// .with_reported_prompt_tokens(Some(12_000));
233/// assert_eq!(request.preamble.len(), 1);
234/// assert_eq!(request.reported_prompt_tokens, Some(12_000));
235/// ```
236#[derive(Debug, Clone, Copy)]
237#[non_exhaustive]
238pub struct HistoryCompactionRequest<'a> {
239 /// Contents sent with every request and never compacted, such as the agent's
240 /// instructions. They count toward the estimate.
241 pub preamble: &'a [Content],
242 /// The conversation the agent continues from, which compaction may shorten.
243 pub history: &'a [Content],
244 /// The prompt tokens the provider reported for the agent's previous request in this run,
245 /// a lower bound on the size of the next one until the history is compacted.
246 pub reported_prompt_tokens: Option<u64>,
247 /// Why compaction is asked for.
248 pub trigger: CompactionTrigger,
249 /// The tools the agent's next request declares. A provider that compacts natively reads
250 /// them with the conversation, and binds the kept turns' thinking to them.
251 pub tools: Option<&'a ToolDeclarations>,
252 /// The generation config of the agent's next request: its thinking and output settings.
253 pub config: Option<&'a GenerateContentConfig>,
254}
255
256impl<'a> HistoryCompactionRequest<'a> {
257 /// A request to compact `history`, with no preamble, tools or config.
258 pub fn new(history: &'a [Content], trigger: CompactionTrigger) -> Self {
259 Self {
260 preamble: &[],
261 history,
262 reported_prompt_tokens: None,
263 trigger,
264 tools: None,
265 config: None,
266 }
267 }
268
269 /// Contents sent ahead of the history and never compacted, such as instructions.
270 pub fn with_preamble(mut self, preamble: &'a [Content]) -> Self {
271 self.preamble = preamble;
272 self
273 }
274
275 /// The prompt tokens the provider reported for the agent's previous request.
276 pub fn with_reported_prompt_tokens(mut self, tokens: Option<u64>) -> Self {
277 self.reported_prompt_tokens = tokens;
278 self
279 }
280
281 /// The tools the agent's next request declares.
282 pub fn with_tools(mut self, tools: &'a ToolDeclarations) -> Self {
283 self.tools = Some(tools);
284 self
285 }
286
287 /// The generation config of the agent's next request.
288 pub fn with_config(mut self, config: Option<&'a GenerateContentConfig>) -> Self {
289 self.config = config;
290 self
291 }
292}
293
294/// A compacted history.
295#[derive(Debug, Clone)]
296pub struct CompactedHistory {
297 /// What replaces [`HistoryCompactionRequest::history`]: a summary, then the most recent
298 /// entries as they were.
299 pub history: Vec<Content>,
300 /// The event that records the compaction in the session
301 /// ([`EventActions::compaction`](crate::EventActions::compaction)), so later runs start
302 /// from the summary. The agent yields it. `None` when the compaction is kept to this
303 /// agent's working history.
304 pub event: Option<Event>,
305}
306
307/// Compacts an agent's history before a model call.
308///
309/// The runner installs one on [`RunConfig::history_compactor`](crate::RunConfig::history_compactor)
310/// at the start of each run, from [`IntraCompactionConfig`] and a summarizer or compaction
311/// strategy. `LlmAgent` and `CodeActAgent` call it before every model call
312/// ([`CompactionTrigger::BeforeModelCall`]) and once after a model rejects a request as too
313/// long ([`CompactionTrigger::ContextLimitExceeded`]); an agent that calls a model itself does
314/// the same. `Ok(None)` leaves the history as it is.
315///
316/// A compactor never separates a function response from its call
317/// ([`balanced_content_cut`](crate::history::balanced_content_cut)), keeps a call still held
318/// for confirmation and everything after it
319/// ([`held_call_content_limit`](crate::history::held_call_content_limit)), and makes any model
320/// call inside a [`ModelCallScope`](crate::ModelCallScope) for `ctx`, so it counts against the
321/// run's budget and spend ledger.
322///
323/// # Example
324///
325/// ```rust
326/// use adk_core::intra_compaction::{
327/// CompactedHistory, HistoryCompactionRequest, HistoryCompactor,
328/// };
329/// use adk_core::{InvocationContext, Llm, Result, async_trait};
330/// use std::sync::Arc;
331///
332/// /// Keeps the 20 most recent entries once there are more than 40.
333/// #[derive(Debug)]
334/// struct KeepRecent;
335///
336/// #[async_trait]
337/// impl HistoryCompactor for KeepRecent {
338/// async fn compact(
339/// &self,
340/// _ctx: Arc<dyn InvocationContext>,
341/// _model: Arc<dyn Llm>,
342/// request: HistoryCompactionRequest<'_>,
343/// ) -> Result<Option<CompactedHistory>> {
344/// let history = request.history;
345/// if history.len() <= 40 {
346/// return Ok(None);
347/// }
348/// let cut = adk_core::history::balanced_content_cut(history, history.len() - 20);
349/// let note = adk_core::history::system_notice("Earlier turns were removed.");
350/// let kept = std::iter::once(note).chain(history[cut..].iter().cloned()).collect();
351/// Ok(Some(CompactedHistory { history: kept, event: None }))
352/// }
353/// }
354/// # let _: Arc<dyn HistoryCompactor> = Arc::new(KeepRecent);
355/// ```
356#[async_trait]
357pub trait HistoryCompactor: Send + Sync + std::fmt::Debug {
358 /// Compacts `request.history` for a call to `model` by the agent `ctx` runs, or returns
359 /// `Ok(None)` to leave it as it is.
360 ///
361 /// # Errors
362 ///
363 /// An error ends the agent's turn with it. The runner's compactor returns none: a summary
364 /// that fails leaves the history as it is.
365 async fn compact(
366 &self,
367 ctx: Arc<dyn InvocationContext>,
368 model: Arc<dyn Llm>,
369 request: HistoryCompactionRequest<'_>,
370 ) -> crate::Result<Option<CompactedHistory>>;
371}
372
373/// The first line of every compaction summary [`compaction_summary`] builds.
374pub const COMPACTION_SUMMARY_HEADING: &str =
375 "The earlier conversation was compacted to fit the model's context window. Summary:";
376
377/// The history entry a compaction summary takes: a
378/// [system notice](crate::history::system_notice) headed [`COMPACTION_SUMMARY_HEADING`].
379///
380/// A user-role notice, so a request that starts with it is valid on every provider, and it
381/// never stands in for the person's last message.
382///
383/// # Example
384///
385/// ```rust
386/// use adk_core::history::is_system_notice;
387/// use adk_core::intra_compaction::compaction_summary;
388///
389/// let summary = compaction_summary("The user asked for the Q3 figures; two were found.");
390/// assert!(is_system_notice(&summary));
391/// ```
392pub fn compaction_summary(summary: &str) -> Content {
393 crate::history::system_notice(&format!("{COMPACTION_SUMMARY_HEADING}\n{summary}"))
394}
395
396/// The text of a compaction summary: [`COMPACTION_SUMMARY_HEADING`], then `summary`.
397///
398/// A provider-native compaction ([`is_native_compaction`]) carries it as the text every
399/// provider reads, next to the signed copy only its own provider reads.
400///
401/// # Example
402///
403/// ```rust
404/// use adk_core::intra_compaction::{COMPACTION_SUMMARY_HEADING, compaction_summary_text};
405///
406/// let text = compaction_summary_text("Two invoices were found.");
407/// assert_eq!(text, format!("{COMPACTION_SUMMARY_HEADING}\nTwo invoices were found."));
408/// ```
409pub fn compaction_summary_text(summary: &str) -> String {
410 format!("{COMPACTION_SUMMARY_HEADING}\n{summary}")
411}
412
413/// Key a provider sets to `true` in the replay-only copy
414/// ([`REPLAY_ONLY_KEY`](crate::history::REPLAY_ONLY_KEY)) of a compaction it wrote itself.
415pub const NATIVE_COMPACTION_KEY: &str = "adk_native_compaction";
416
417/// Whether `content` is a compaction a provider wrote itself: a model turn holding the
418/// summary as text ([`compaction_summary_text`]) and the provider's signed copy, flagged
419/// [`NATIVE_COMPACTION_KEY`].
420///
421/// The copy is a native item: it reaches only the provider and model that wrote it
422/// ([`retain_replayable`](crate::history::retain_replayable)); every other provider reads
423/// the text.
424///
425/// # Example
426///
427/// ```rust
428/// use adk_core::intra_compaction::{compaction_summary_text, is_native_compaction};
429/// use adk_core::{Content, Part};
430///
431/// let mut compaction = Content::new("model").with_text(compaction_summary_text("Done so far."));
432/// assert!(!is_native_compaction(&compaction));
433/// compaction.parts.push(Part::ServerToolResponse {
434/// server_tool_response: serde_json::json!({
435/// "type": "anthropic_message",
436/// "adk_replay_only": true,
437/// "adk_native_compaction": true,
438/// "content": [{"type": "compaction", "content": "Done so far.", "signature": "sig"}],
439/// }),
440/// });
441/// assert!(is_native_compaction(&compaction));
442/// ```
443pub fn is_native_compaction(content: &Content) -> bool {
444 matches!(content.role.as_str(), "model" | "assistant")
445 && content.parts.iter().any(|part| {
446 let (Part::ServerToolCall { server_tool_call: payload }
447 | Part::ServerToolResponse { server_tool_response: payload }) = part
448 else {
449 return false;
450 };
451 payload.get(NATIVE_COMPACTION_KEY).and_then(serde_json::Value::as_bool) == Some(true)
452 })
453}
454
455/// Asks a model for its provider's own compaction of a request's conversation, in place of
456/// a reply.
457///
458/// The runner's auto-compaction sends it to a model that reports
459/// [`Llm::native_compaction`]: the request carries the conversation to summarize with the
460/// agent's instructions, tools and config, and the response's content is the compaction
461/// ([`is_native_compaction`]). A model that does not compact natively ignores it.
462///
463/// Carried in the request's `config.extensions` under [`EXTENSION_KEY`](Self::EXTENSION_KEY).
464///
465/// # Example
466///
467/// ```rust
468/// use adk_core::LlmRequest;
469/// use adk_core::intra_compaction::NativeCompactionRequest;
470///
471/// let mut request = LlmRequest::new("claude-sonnet-5-5", vec![]);
472/// assert_eq!(NativeCompactionRequest::of(&request), None);
473/// NativeCompactionRequest::new().with_instructions("Keep every order number.").apply(&mut request);
474/// assert_eq!(
475/// NativeCompactionRequest::of(&request).and_then(|ask| ask.instructions),
476/// Some("Keep every order number.".to_string())
477/// );
478/// ```
479#[derive(Debug, Clone, Default, PartialEq, Eq)]
480#[non_exhaustive]
481pub struct NativeCompactionRequest {
482 /// A summarization prompt that replaces the provider's own.
483 pub instructions: Option<String>,
484}
485
486impl NativeCompactionRequest {
487 /// Key of the request in `GenerateContentConfig::extensions`.
488 pub const EXTENSION_KEY: &'static str = "adk_native_compaction";
489
490 /// A compaction with the provider's own summarization prompt.
491 pub fn new() -> Self {
492 Self::default()
493 }
494
495 /// Replaces the provider's summarization prompt with `instructions`.
496 pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
497 self.instructions = Some(instructions.into());
498 self
499 }
500
501 /// Marks `request` as asking for this compaction.
502 pub fn apply(&self, request: &mut LlmRequest) {
503 let mut ask = serde_json::Map::new();
504 if let Some(instructions) = &self.instructions {
505 ask.insert("instructions".to_string(), serde_json::Value::from(instructions.clone()));
506 }
507 request
508 .config
509 .get_or_insert_with(GenerateContentConfig::default)
510 .extensions
511 .insert(Self::EXTENSION_KEY.to_string(), serde_json::Value::Object(ask));
512 }
513
514 /// The compaction `request` asks for, if any.
515 pub fn of(request: &LlmRequest) -> Option<Self> {
516 let ask = request.config.as_ref()?.extensions.get(Self::EXTENSION_KEY)?.as_object()?;
517 Some(Self {
518 instructions: ask
519 .get("instructions")
520 .and_then(serde_json::Value::as_str)
521 .map(str::to_string),
522 })
523 }
524}
525
526/// Whether `err` is a model's refusal of a request longer than its context window.
527///
528/// Providers report it as a client error (`InvalidInput`) with their own wording: Anthropic's
529/// "prompt is too long", OpenAI's `context_length_exceeded` ("maximum context length"),
530/// Gemini's "input token count exceeds the maximum number of tokens allowed", and the
531/// runner's own `runner.context_overflow`.
532///
533/// # Example
534///
535/// ```rust
536/// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
537/// use adk_core::intra_compaction::is_context_limit_error;
538///
539/// let too_long = AdkError::new(
540/// ErrorComponent::Model,
541/// ErrorCategory::InvalidInput,
542/// "model.anthropic.api_error",
543/// "400: prompt is too long: 1048577 tokens > 1000000 maximum (invalid_request_error)",
544/// );
545/// assert!(is_context_limit_error(&too_long));
546/// assert!(!is_context_limit_error(&AdkError::model("connection refused")));
547/// ```
548pub fn is_context_limit_error(err: &AdkError) -> bool {
549 if err.component != ErrorComponent::Model || err.category != ErrorCategory::InvalidInput {
550 return false;
551 }
552 if err.code == "runner.context_overflow" {
553 return true;
554 }
555 let message = err.message.to_lowercase();
556 [
557 "prompt is too long",
558 "context length",
559 "context_length_exceeded",
560 "context window",
561 "context limit",
562 "maximum context",
563 "too many tokens",
564 "input is too long",
565 "input too long",
566 "input token count",
567 "exceeds the maximum number of tokens",
568 "request payload size exceeds",
569 "reduce the length of the messages",
570 ]
571 .iter()
572 .any(|pattern| message.contains(pattern))
573}
574
575/// Estimate token count from a list of events using a character heuristic.
576///
577/// Sums the character lengths of all text parts and serialized function call/response
578/// actions across all events, then divides by `chars_per_token` (integer division).
579///
580/// # Arguments
581///
582/// * `events` - The conversation events to estimate tokens for.
583/// * `chars_per_token` - The character-to-token ratio (e.g., 4 means ~4 chars per token).
584///
585/// # Returns
586///
587/// Estimated token count. Returns 0 if `chars_per_token` is 0 or events are empty.
588///
589/// # Example
590///
591/// ```rust
592/// use adk_core::intra_compaction::estimate_tokens;
593/// use adk_core::{Event, Content, Part};
594///
595/// let mut event = Event::new("inv-1");
596/// event.set_content(Content::new("user").with_text("Hello, world!"));
597/// let tokens = estimate_tokens(&[event], 4);
598/// assert_eq!(tokens, 3); // 13 chars / 4 = 3
599/// ```
600pub fn estimate_tokens(events: &[Event], chars_per_token: u32) -> u64 {
601 if chars_per_token == 0 {
602 return 0;
603 }
604 let total_chars: u64 = events.iter().map(|e| estimate_event_chars(e) as u64).sum();
605 total_chars / chars_per_token as u64
606}
607
608/// Estimate the token count of model contents with the [`estimate_tokens`] heuristic.
609///
610/// # Example
611///
612/// ```rust
613/// use adk_core::Content;
614/// use adk_core::intra_compaction::estimate_content_tokens;
615///
616/// let history = [Content::new("user").with_text("Hello, world!")];
617/// assert_eq!(estimate_content_tokens(&history, 4), 3);
618/// ```
619pub fn estimate_content_tokens(contents: &[Content], chars_per_token: u32) -> u64 {
620 if chars_per_token == 0 {
621 return 0;
622 }
623 let chars: u64 = contents
624 .iter()
625 .flat_map(|content| &content.parts)
626 .map(|part| estimate_part_chars(part) as u64)
627 .sum();
628 chars / chars_per_token as u64
629}
630
631/// Estimate the character count of a single event.
632///
633/// Counts characters from:
634/// - Text parts (text length)
635/// - Thinking parts (thinking text length)
636/// - Function call parts (serialized args length + name length)
637/// - Function response parts (serialized response length + name length)
638/// - A compaction event's summary, which stands in for the events it covers
639/// - Serialized actions (state_delta as JSON)
640fn estimate_event_chars(event: &Event) -> usize {
641 let mut chars = 0;
642
643 let summary = event.actions.compaction.as_ref().map(|compaction| &compaction.compacted_content);
644 for content in event.llm_response.content.iter().chain(summary) {
645 for part in &content.parts {
646 chars += estimate_part_chars(part);
647 }
648 }
649
650 // Count serialized actions (state_delta)
651 if !event.actions.state_delta.is_empty() {
652 chars += json_len(&event.actions.state_delta);
653 }
654
655 chars
656}
657
658/// Estimate the character count of a single content part.
659fn estimate_part_chars(part: &Part) -> usize {
660 match part {
661 Part::Text { text } => text.len(),
662 Part::Thinking { thinking, .. } => thinking.len(),
663 Part::FunctionCall { name, args, .. } => name.len() + json_len(args),
664 Part::FunctionResponse { function_response, .. } => {
665 function_response.name.len() + json_len(&function_response.response)
666 }
667 // Binary/file data and server tool calls contribute minimally to text token count
668 Part::InlineData { .. } | Part::FileData { .. } => 0,
669 Part::ServerToolCall { server_tool_call } => json_len(server_tool_call),
670 Part::ServerToolResponse { server_tool_response } => json_len(server_tool_response),
671 Part::EmbeddedResource { resource } => json_len(resource),
672 }
673}
674
675/// The serialized JSON length of `value`, counted without building the string, since the
676/// estimate runs before every model call.
677fn json_len<T: serde::Serialize + ?Sized>(value: &T) -> usize {
678 struct Count(usize);
679 impl std::io::Write for Count {
680 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
681 self.0 += bytes.len();
682 Ok(bytes.len())
683 }
684 fn flush(&mut self) -> std::io::Result<()> {
685 Ok(())
686 }
687 }
688 let mut count = Count(0);
689 serde_json::to_writer(&mut count, value).map_or(0, |()| count.0)
690}
691
692/// A one-line rendering of `part` for a summarizer prompt; `None` for thinking and for
693/// provider-native items (server-side tool calls and results).
694///
695/// Text is kept as it is. Function calls and responses keep their name and JSON payload,
696/// data and file parts their type and reference, and embedded resources their URI, so a
697/// summary keeps the facts a tool returned. The session compaction summarizer
698/// (`LlmEventSummarizer`) and the runner's `SummarisationCompaction` both render events with
699/// it.
700///
701/// # Example
702///
703/// ```rust
704/// use adk_core::intra_compaction::render_part_for_summary;
705/// use adk_core::{FunctionResponseData, Part};
706/// use serde_json::json;
707///
708/// let result = Part::FunctionResponse {
709/// function_response: FunctionResponseData::new("lookup", json!({"status": "shipped"})),
710/// id: None,
711/// annotations: None,
712/// };
713/// assert_eq!(
714/// render_part_for_summary(&result).as_deref(),
715/// Some(r#"[function response] lookup: {"status":"shipped"}"#)
716/// );
717/// let thought = Part::Thinking { thinking: "hmm".into(), signature: None };
718/// assert_eq!(render_part_for_summary(&thought), None);
719/// let native = Part::ServerToolResponse { server_tool_response: json!({"type": "anthropic_message"}) };
720/// assert_eq!(render_part_for_summary(&native), None);
721/// ```
722pub fn render_part_for_summary(part: &Part) -> Option<String> {
723 let json = |value: &serde_json::Value| value.to_string();
724 Some(match part {
725 Part::Text { text } => text.clone(),
726 // Provider-native items are private to the provider that produced them; a payload can
727 // hold its reasoning, and the summary is sent to whichever model summarizes.
728 Part::Thinking { .. } | Part::ServerToolCall { .. } | Part::ServerToolResponse { .. } => {
729 return None;
730 }
731 Part::FunctionCall { name, args, .. } => format!("[function call] {name}({})", json(args)),
732 Part::FunctionResponse { function_response, .. } => {
733 let mut rendered = format!(
734 "[function response] {}: {}",
735 function_response.name,
736 json(&function_response.response)
737 );
738 for data in &function_response.inline_data {
739 rendered.push_str(&format!(" [inline data: {}]", data.mime_type));
740 }
741 for file in &function_response.file_data {
742 rendered.push_str(&format!(" [file: {} ({})]", file.file_uri, file.mime_type));
743 }
744 rendered
745 }
746 Part::InlineData { mime_type, data, .. } => {
747 format!("[inline data: {mime_type}, {} bytes]", data.len())
748 }
749 Part::FileData { mime_type, file_uri, .. } => format!("[file: {file_uri} ({mime_type})]"),
750 Part::EmbeddedResource { resource } => match resource {
751 crate::EmbeddedResource::Text(text) => format!("[resource {}] {}", text.uri, text.text),
752 crate::EmbeddedResource::Blob(blob) => format!(
753 "[resource {}: {}, {} bytes]",
754 blob.uri,
755 blob.mime_type.as_deref().unwrap_or("application/octet-stream"),
756 blob.data.len()
757 ),
758 },
759 })
760}
761
762#[cfg(test)]
763mod tests {
764 use super::*;
765 use crate::{Content, FunctionResponseData};
766
767 #[test]
768 fn the_default_is_on_at_a_fraction_of_the_window() {
769 assert_eq!(
770 IntraCompactionConfig::default(),
771 IntraCompactionConfig {
772 enabled: true,
773 token_threshold: None,
774 context_window_fraction: 0.8,
775 overlap_event_count: 10,
776 chars_per_token: 4,
777 native: true,
778 background: false,
779 background_fraction: DEFAULT_BACKGROUND_FRACTION,
780 }
781 );
782 }
783
784 #[test]
785 fn a_fixed_threshold_wins_and_a_bad_fraction_falls_back() {
786 let config = IntraCompactionConfig::default();
787 assert_eq!(config.threshold_for(Some(200_000)), 160_000);
788 assert_eq!(config.threshold_for(None), DEFAULT_TOKEN_THRESHOLD);
789 assert_eq!(IntraCompactionConfig::at_tokens(5).threshold_for(Some(200_000)), 5);
790 for fraction in [0.0, -1.0, 1.5, f64::NAN] {
791 let config = IntraCompactionConfig::at_window_fraction(fraction);
792 assert_eq!(config.threshold_for(Some(100)), 80, "fraction {fraction}");
793 }
794 assert_eq!(IntraCompactionConfig::at_window_fraction(0.5).threshold_for(Some(100)), 50);
795 }
796
797 #[test]
798 fn context_limit_errors_are_told_from_other_client_errors() {
799 let model_error = |message: &str| {
800 AdkError::new(
801 ErrorComponent::Model,
802 ErrorCategory::InvalidInput,
803 "model.api_error",
804 message.to_string(),
805 )
806 };
807 for message in [
808 "400: prompt is too long: 1048577 tokens > 1000000 maximum (invalid_request_error)",
809 "This model's maximum context length is 128000 tokens",
810 "context_length_exceeded",
811 "input length and `max_tokens` exceed context limit: 190000 + 32000 > 200000",
812 "The input token count (1100000) exceeds the maximum number of tokens allowed (1048576).",
813 ] {
814 assert!(is_context_limit_error(&model_error(message)), "{message}");
815 }
816 for message in [
817 "max_tokens: 200000 > 128000, which is the maximum allowed number of output tokens",
818 "invalid x-api-key",
819 "tools.0.name: String should match pattern",
820 ] {
821 assert!(!is_context_limit_error(&model_error(message)), "{message}");
822 }
823 let unavailable = AdkError::new(
824 ErrorComponent::Model,
825 ErrorCategory::Unavailable,
826 "model.api_error",
827 "prompt is too long",
828 );
829 assert!(!is_context_limit_error(&unavailable));
830 }
831
832 #[test]
833 fn contents_are_estimated_like_events() {
834 let call = Content {
835 role: "model".to_string(),
836 parts: vec![Part::FunctionCall {
837 name: "get_weather".to_string(),
838 args: serde_json::json!({"city": "NYC"}),
839 id: None,
840 thought_signature: None,
841 }],
842 };
843 let mut event = Event::new("inv-1");
844 event.set_content(call.clone());
845 // "get_weather" (11) + {"city":"NYC"} (14) = 25 chars.
846 assert_eq!(estimate_content_tokens(&[call], 1), 25);
847 assert_eq!(estimate_tokens(&[event], 1), 25);
848 }
849
850 #[test]
851 fn test_estimate_tokens_empty() {
852 assert_eq!(estimate_tokens(&[], 4), 0);
853 }
854
855 #[test]
856 fn test_estimate_tokens_zero_ratio() {
857 let mut event = Event::new("inv-1");
858 event.set_content(Content::new("user").with_text("Hello"));
859 assert_eq!(estimate_tokens(&[event], 0), 0);
860 }
861
862 #[test]
863 fn test_estimate_tokens_text_only() {
864 let mut event = Event::new("inv-1");
865 // "Hello" = 5 chars, 5 / 4 = 1
866 event.set_content(Content::new("user").with_text("Hello"));
867 assert_eq!(estimate_tokens(&[event], 4), 1);
868 }
869
870 #[test]
871 fn test_estimate_tokens_multiple_events() {
872 let mut e1 = Event::new("inv-1");
873 e1.set_content(Content::new("user").with_text("Hello")); // 5 chars
874 let mut e2 = Event::new("inv-1");
875 e2.set_content(Content::new("model").with_text("World!")); // 6 chars
876 // Total: 11 chars / 4 = 2
877 assert_eq!(estimate_tokens(&[e1, e2], 4), 2);
878 }
879
880 #[test]
881 fn test_estimate_tokens_with_function_call() {
882 let mut event = Event::new("inv-1");
883 event.llm_response.content = Some(Content {
884 role: "model".to_string(),
885 parts: vec![Part::FunctionCall {
886 name: "get_weather".to_string(),
887 args: serde_json::json!({"city": "NYC"}),
888 id: None,
889 thought_signature: None,
890 }],
891 });
892 let tokens = estimate_tokens(&[event], 4);
893 // "get_weather" = 11 chars + {"city":"NYC"} serialized
894 assert!(tokens > 0);
895 }
896
897 #[test]
898 fn a_compaction_summary_counts_toward_the_estimate() {
899 let mut event = Event::new("inv-1");
900 event.actions.compaction = Some(crate::EventCompaction {
901 start_timestamp: chrono::Utc::now(),
902 end_timestamp: chrono::Utc::now(),
903 compacted_content: Content::new("model").with_text("a".repeat(40)),
904 });
905 assert_eq!(estimate_tokens(&[event], 4), 10);
906 }
907
908 #[test]
909 fn test_estimate_tokens_with_function_response() {
910 let mut event = Event::new("inv-1");
911 event.llm_response.content = Some(Content {
912 role: "function".to_string(),
913 parts: vec![Part::FunctionResponse {
914 function_response: FunctionResponseData::new(
915 "get_weather",
916 serde_json::json!({"temp": 72}),
917 ),
918 id: None,
919 annotations: None,
920 }],
921 });
922 let tokens = estimate_tokens(&[event], 4);
923 assert!(tokens > 0);
924 }
925}