1use adk_core::history::ProviderOrigin;
14use adk_core::history::{balanced_content_cut, held_call_content_limit};
15use adk_core::intra_compaction::{
16 CompactedHistory, CompactionTrigger, HistoryCompactionRequest, HistoryCompactor,
17 IntraCompactionConfig, NativeCompactionRequest, compaction_summary, estimate_content_tokens,
18 estimate_tokens, is_native_compaction,
19};
20use adk_core::{
21 BaseEventsSummarizer, Content, Event, EventCompaction, GenerateContentConfig,
22 InvocationContext, Llm, LlmEventSummarizer, LlmRequest, NativeCompaction, Part, Result,
23 ToolDeclarations,
24};
25use async_trait::async_trait;
26use futures::StreamExt;
27use std::collections::HashMap;
28use std::sync::atomic::{AtomicBool, Ordering};
29use std::sync::{Arc, Mutex, PoisonError};
30
31use crate::context::MutableSession;
32
33pub struct IntraInvocationCompactor {
64 config: IntraCompactionConfig,
65 summarizer: Option<Arc<dyn BaseEventsSummarizer>>,
67 #[cfg(feature = "context-compaction")]
68 strategy: Option<Arc<crate::compaction::CompactionConfig>>,
69 compacted_this_cycle: AtomicBool,
71}
72
73impl std::fmt::Debug for IntraInvocationCompactor {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.debug_struct("IntraInvocationCompactor")
76 .field("config", &self.config)
77 .field("summarizer", &self.summarizer.as_ref().map(|_| "<dyn BaseEventsSummarizer>"))
78 .finish_non_exhaustive()
79 }
80}
81
82impl IntraInvocationCompactor {
83 pub fn new(config: IntraCompactionConfig, summarizer: Arc<dyn BaseEventsSummarizer>) -> Self {
85 Self {
86 config,
87 summarizer: Some(summarizer),
88 #[cfg(feature = "context-compaction")]
89 strategy: None,
90 compacted_this_cycle: AtomicBool::new(false),
91 }
92 }
93
94 pub fn with_model_summary(config: IntraCompactionConfig) -> Self {
97 Self {
98 config,
99 summarizer: None,
100 #[cfg(feature = "context-compaction")]
101 strategy: None,
102 compacted_this_cycle: AtomicBool::new(false),
103 }
104 }
105
106 #[cfg(feature = "context-compaction")]
110 pub fn with_strategy(
111 base: IntraCompactionConfig,
112 config: Arc<crate::compaction::CompactionConfig>,
113 ) -> Self {
114 Self {
115 config: IntraCompactionConfig {
116 token_threshold: Some(config.context_budget as u64),
117 ..base
118 },
119 summarizer: None,
120 strategy: Some(config),
121 compacted_this_cycle: AtomicBool::new(false),
122 }
123 }
124
125 pub fn config(&self) -> &IntraCompactionConfig {
127 &self.config
128 }
129
130 pub async fn maybe_compact(&self, events: &[Event]) -> Result<Option<Vec<Event>>> {
144 let Some(summarizer) = self.summarizer.as_ref() else {
145 return Ok(None);
146 };
147 if self
149 .compacted_this_cycle
150 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
151 .is_err()
152 {
153 return Ok(None);
154 }
155
156 let estimated = estimate_tokens(events, self.config.chars_per_token);
157 if estimated <= self.config.threshold_for(None) {
158 self.compacted_this_cycle.store(false, Ordering::SeqCst);
161 return Ok(None);
162 }
163
164 let overlap = self.config.overlap_event_count.min(events.len());
168 let summarize_end = adk_core::history::balanced_cut(
169 events,
170 adk_core::held_call_compaction_limit(events, events.len().saturating_sub(overlap)),
171 );
172
173 if summarize_end == 0 {
174 self.compacted_this_cycle.store(false, Ordering::SeqCst);
176 return Ok(None);
177 }
178
179 let events_to_summarize = &events[..summarize_end];
180 let overlap_events = &events[summarize_end..];
181
182 match summarizer.summarize_events(events_to_summarize).await {
184 Ok(Some(summary_event)) => {
185 let summary_tokens = estimate_tokens(
188 std::slice::from_ref(&summary_event),
189 self.config.chars_per_token,
190 );
191 let replaced_tokens =
192 estimate_tokens(events_to_summarize, self.config.chars_per_token);
193 if summary_tokens >= replaced_tokens {
194 tracing::info!(
195 summary.tokens = summary_tokens,
196 replaced.tokens = replaced_tokens,
197 "intra-invocation summary is not smaller than the history it replaces; keeping the history"
198 );
199 return Ok(None);
200 }
201 let mut compacted = Vec::with_capacity(1 + overlap_events.len());
202 compacted.push(summary_event);
203 compacted.extend_from_slice(overlap_events);
204 Ok(Some(compacted))
205 }
206 Ok(None) => {
207 Ok(None)
209 }
210 Err(e) => {
211 tracing::warn!(
213 error = %e.diagnostics(),
214 "intra-invocation compaction failed, continuing with uncompacted history"
215 );
216 Ok(None)
217 }
218 }
219 }
220
221 pub fn reset_cycle(&self) {
223 self.compacted_this_cycle.store(false, Ordering::SeqCst);
224 }
225
226 async fn compact_history(
228 &self,
229 ctx: Arc<dyn InvocationContext>,
230 model: Arc<dyn Llm>,
231 request: HistoryCompactionRequest<'_>,
232 session: Option<&MutableSession>,
233 ) -> Outcome {
234 let chars_per_token = self.config.chars_per_token;
235 let threshold = self.config.threshold_for(model.context_window());
236 let estimated = estimate_content_tokens(request.preamble, chars_per_token)
237 + estimate_content_tokens(request.history, chars_per_token);
238 let size = estimated.max(request.reported_prompt_tokens.unwrap_or(0));
239 if request.trigger == CompactionTrigger::BeforeModelCall && size <= threshold {
240 return Outcome::BelowThreshold;
241 }
242 tracing::info!(
243 agent.name = %ctx.agent_name(),
244 history.entries = request.history.len(),
245 history.tokens = size,
246 threshold,
247 trigger = ?request.trigger,
248 "compacting the agent's history"
249 );
250 let scope =
252 adk_core::ModelCallScope::for_run(ctx.run_config(), ctx.app_name(), ctx.agent_name());
253 #[cfg(feature = "context-compaction")]
254 if let Some(strategy) = &self.strategy {
255 return scope
256 .within(self.compact_with_strategy(ctx.as_ref(), strategy, request.history))
257 .await;
258 }
259 scope.within(self.summarize(ctx.as_ref(), model, &request, threshold, session)).await
260 }
261
262 async fn compact_in_background(
271 self: &Arc<Self>,
272 ctx: Arc<dyn InvocationContext>,
273 model: Arc<dyn Llm>,
274 request: HistoryCompactionRequest<'_>,
275 session: Option<&MutableSession>,
276 background: &BackgroundCompactions,
277 may_start: bool,
278 ) -> Outcome {
279 let key = BackgroundKey::of(ctx.as_ref());
280 let history = request.history;
281 let chars_per_token = self.config.chars_per_token;
282 let window = model.context_window();
283 let threshold = self.config.threshold_for(window);
284 let size = (estimate_content_tokens(request.preamble, chars_per_token)
285 + estimate_content_tokens(history, chars_per_token))
286 .max(request.reported_prompt_tokens.unwrap_or(0));
287 let due = request.trigger == CompactionTrigger::ContextLimitExceeded || size > threshold;
288 if let Some(pending) = background.take(&key, |pending| due || pending.task.is_finished()) {
289 let waited = !pending.task.is_finished();
290 let cut = pending.summarized.len();
291 let covers = pending.covers(history);
292 let elapsed = pending.started.elapsed();
293 match pending.task.await {
294 Ok(Some(summary)) if covers => {
295 tracing::info!(
296 agent.name = %ctx.agent_name(),
297 summarized.entries = cut,
298 compaction.waited = waited,
299 compaction.elapsed_ms = elapsed.as_millis() as u64,
300 "swapping in a summary written in the background"
301 );
302 let compacted = self.swap_in(ctx.as_ref(), summary, history, cut, session);
303 return Outcome::Compacted(Box::new(compacted));
304 }
305 Ok(Some(_)) => tracing::info!(
306 agent.name = %ctx.agent_name(),
307 "the history changed while the summary was written; discarding it"
308 ),
309 Ok(None) => {}
310 Err(error) => tracing::warn!(error = %error, "background compaction stopped"),
311 }
312 }
313 if due {
314 return self.compact_history(ctx, model, request, session).await;
315 }
316 if !may_start
317 || size <= self.config.background_threshold_for(window)
318 || background.contains(&key)
319 {
320 return Outcome::BelowThreshold;
321 }
322 if held_call_content_limit(history, history.len()) < history.len() {
325 tracing::debug!(agent.name = %ctx.agent_name(), "a held call defers background compaction");
326 return Outcome::BelowThreshold;
327 }
328 let scope =
329 adk_core::ModelCallScope::for_run(ctx.run_config(), ctx.app_name(), ctx.agent_name());
330 if scope.check_governance().is_err() {
331 return Outcome::BelowThreshold;
332 }
333 let Some(cut) = self.cut(ctx.as_ref(), history, threshold, session) else {
334 return Outcome::NothingToCompact;
335 };
336 let summarized = history[..cut].to_vec();
337 let events = as_events(ctx.as_ref(), &summarized);
338 let template = Template::of(&request);
339 let native = self.native(model.as_ref());
340 let compactor = Arc::clone(self);
341 let entries = summarized.clone();
342 let task = tokio::spawn(scope.within(async move {
343 compactor.write_summary(model, native, &template, &entries, events).await
344 }));
345 tracing::info!(
346 agent.name = %ctx.agent_name(),
347 summarized.entries = cut,
348 history.tokens = size,
349 threshold,
350 "started a compaction in the background"
351 );
352 background.insert(
353 key,
354 PendingCompaction { summarized, started: std::time::Instant::now(), task },
355 );
356 Outcome::BelowThreshold
357 }
358
359 async fn summarize(
363 &self,
364 ctx: &dyn InvocationContext,
365 model: Arc<dyn Llm>,
366 request: &HistoryCompactionRequest<'_>,
367 threshold: u64,
368 session: Option<&MutableSession>,
369 ) -> Outcome {
370 let history = request.history;
371 let Some(cut) = self.cut(ctx, history, threshold, session) else {
372 return Outcome::NothingToCompact;
373 };
374 let native = self.native(model.as_ref());
375 let events = as_events(ctx, &history[..cut]);
376 let template = Template::of(request);
377 match self.write_summary(model, native, &template, &history[..cut], events).await {
378 Some(summary) => {
379 Outcome::Compacted(Box::new(self.swap_in(ctx, summary, history, cut, session)))
380 }
381 None => Outcome::Kept,
382 }
383 }
384
385 fn cut(
390 &self,
391 ctx: &dyn InvocationContext,
392 history: &[Content],
393 threshold: u64,
394 session: Option<&MutableSession>,
395 ) -> Option<usize> {
396 let chars_per_token = self.config.chars_per_token;
397 let overlap = self.config.overlap_event_count.min(history.len());
398 let mut within_budget = history.len();
399 let mut kept_tokens = 0;
400 for (index, content) in history.iter().enumerate().rev() {
401 kept_tokens += estimate_content_tokens(std::slice::from_ref(content), chars_per_token);
402 if kept_tokens > threshold / 2 && index + 1 < history.len() {
404 break;
405 }
406 within_budget = index;
407 }
408 let cut = balanced_content_cut(
409 history,
410 held_call_content_limit(
411 history,
412 history.len().saturating_sub(overlap).max(within_budget),
413 ),
414 );
415 let cut = recorded_cut(ctx, history, cut, session).map_or(cut, |recorded| recorded.cut);
416 (cut > 0).then_some(cut)
417 }
418
419 fn native(&self, model: &dyn Llm) -> Option<NativeCompaction> {
422 if self.summarizer.is_some() || !self.config.native {
423 return None;
424 }
425 model.native_compaction()
426 }
427
428 async fn write_summary(
434 &self,
435 model: Arc<dyn Llm>,
436 native: Option<NativeCompaction>,
437 template: &Template,
438 summarized: &[Content],
439 events: Vec<Event>,
440 ) -> Option<Summary> {
441 let chars_per_token = self.config.chars_per_token;
442 let replaced_tokens = estimate_content_tokens(summarized, chars_per_token);
443 if let Some(native) = native
444 && let Some(compaction) = native_summary(model.as_ref(), template, summarized).await
445 {
446 let summary_tokens = text_tokens(&compaction.content, chars_per_token);
447 if summary_tokens >= replaced_tokens {
448 tracing::info!(
449 summary.tokens = summary_tokens,
450 replaced.tokens = replaced_tokens,
451 "provider summary is not smaller than the history it replaces; keeping the history"
452 );
453 return None;
454 }
455 return Some(Summary {
456 content: compaction.content,
457 origin: compaction.origin,
458 native: Some(native),
459 tokens: summary_tokens,
460 replaced_tokens,
461 });
462 }
463 let summarizer = self
464 .summarizer
465 .clone()
466 .unwrap_or_else(|| Arc::new(LlmEventSummarizer::new(model)) as _);
467 let text = match summarizer.summarize_events(&events).await {
468 Ok(Some(event)) => summary_text(&event),
469 Ok(None) => return None,
470 Err(error) => {
471 tracing::warn!(
473 error = %error.diagnostics(),
474 "history compaction failed; continuing with the history as it is"
475 );
476 return None;
477 }
478 };
479 if text.trim().is_empty() {
480 return None;
481 }
482 let content = compaction_summary(&text);
483 let summary_tokens =
484 estimate_content_tokens(std::slice::from_ref(&content), chars_per_token);
485 if summary_tokens >= replaced_tokens {
486 tracing::info!(
487 summary.tokens = summary_tokens,
488 replaced.tokens = replaced_tokens,
489 "history summary is not smaller than the history it replaces; keeping the history"
490 );
491 return None;
492 }
493 Some(Summary {
494 content,
495 origin: None,
496 native: None,
497 tokens: summary_tokens,
498 replaced_tokens,
499 })
500 }
501
502 fn swap_in(
505 &self,
506 ctx: &dyn InvocationContext,
507 summary: Summary,
508 history: &[Content],
509 cut: usize,
510 session: Option<&MutableSession>,
511 ) -> CompactedHistory {
512 let keep_thinking = summary.native.is_some_and(|native| native.keeps_thinking)
515 && history.get(cut).is_some_and(|first| speaks(&history[cut - 1]) != speaks(first))
516 && !history.iter().any(has_requested_call);
517 let kept: Vec<Content> = if keep_thinking {
518 history[cut..].to_vec()
519 } else {
520 without_thinking(&history[cut..]).collect()
521 };
522 let recorded =
523 recorded_cut(ctx, history, cut, session).filter(|recorded| recorded.cut == cut);
524 let event = recorded.map(|recorded| {
525 let mut event = Event::new(ctx.invocation_id());
526 event.author = ctx.agent_name().to_string();
527 event.branch = ctx.branch().to_string();
528 if let Some(origin) = &summary.origin {
531 origin.record(&mut event.llm_response.provider_metadata);
532 if keep_thinking
533 && let Some(metadata) = event.llm_response.provider_metadata.as_mut()
534 {
535 metadata[KEEPS_THINKING_KEY] = serde_json::Value::Bool(true);
536 }
537 }
538 event.actions.compaction = Some(EventCompaction {
539 compacted_content: summary.content.clone(),
540 ..recorded.span
541 });
542 event
543 });
544 tracing::info!(
545 agent.name = %ctx.agent_name(),
546 compaction.provider = summary.native.map(|native| native.provider).unwrap_or("runner"),
547 summarized.entries = cut,
548 kept.entries = history.len() - cut,
549 kept.thinking = keep_thinking,
550 summary.tokens = summary.tokens,
551 replaced.tokens = summary.replaced_tokens,
552 recorded = event.is_some(),
553 "history compacted"
554 );
555 let history = std::iter::once(summary.content).chain(kept).collect();
556 CompactedHistory { history, event }
557 }
558
559 #[cfg(feature = "context-compaction")]
562 async fn compact_with_strategy(
563 &self,
564 ctx: &dyn InvocationContext,
565 config: &crate::compaction::CompactionConfig,
566 history: &[Content],
567 ) -> Outcome {
568 let held_from = held_call_content_limit(history, history.len());
569 let events = as_events(ctx, &history[..held_from]);
570 let ids: HashMap<String, usize> =
571 events.iter().enumerate().map(|(index, event)| (event.id.clone(), index)).collect();
572 let compacted = match crate::compaction::apply_compaction_with_retry(config, events).await {
573 Ok(compacted) => compacted,
574 Err(error) => {
575 tracing::warn!(
576 error = %error.diagnostics(),
577 "history compaction failed; continuing with the history as it is"
578 );
579 return Outcome::Kept;
580 }
581 };
582 let mut tail_from = compacted.len();
585 let mut next = held_from;
586 while tail_from > 0
587 && next > 0
588 && ids.get(&compacted[tail_from - 1].id) == Some(&(next - 1))
589 {
590 tail_from -= 1;
591 next -= 1;
592 }
593 let mut shortened: Vec<Content> = compacted[..tail_from]
594 .iter()
595 .filter_map(|event| {
596 let content = event.content()?;
597 Some(if ids.contains_key(&event.id) {
599 content.clone()
600 } else {
601 compaction_summary(&text_of(content))
602 })
603 })
604 .collect();
605 let kept: Vec<Content> = compacted[tail_from..]
606 .iter()
607 .filter_map(|event| event.content().cloned())
608 .chain(history[held_from..].iter().cloned())
609 .collect();
610 shortened.extend(without_thinking(&kept));
611 let chars_per_token = self.config.chars_per_token;
612 if estimate_content_tokens(&shortened, chars_per_token)
613 >= estimate_content_tokens(history, chars_per_token)
614 {
615 return Outcome::Kept;
616 }
617 Outcome::Compacted(Box::new(CompactedHistory { history: shortened, event: None }))
618 }
619}
620
621#[async_trait]
622impl HistoryCompactor for IntraInvocationCompactor {
623 async fn compact(
624 &self,
625 ctx: Arc<dyn InvocationContext>,
626 model: Arc<dyn Llm>,
627 request: HistoryCompactionRequest<'_>,
628 ) -> Result<Option<CompactedHistory>> {
629 Ok(self.compact_history(ctx, model, request, None).await.compacted())
630 }
631}
632
633enum Outcome {
635 BelowThreshold,
637 NothingToCompact,
639 Kept,
641 Compacted(Box<CompactedHistory>),
643}
644
645impl Outcome {
646 fn compacted(self) -> Option<CompactedHistory> {
647 match self {
648 Self::Compacted(compacted) => Some(*compacted),
649 Self::BelowThreshold | Self::NothingToCompact | Self::Kept => None,
650 }
651 }
652}
653
654pub(crate) struct RunCompactor {
658 compactor: Arc<IntraInvocationCompactor>,
659 session: Arc<MutableSession>,
660 retry_from: Mutex<HashMap<String, usize>>,
663 background: Option<Arc<BackgroundCompactions>>,
666}
667
668impl RunCompactor {
669 pub(crate) fn new(
670 compactor: Arc<IntraInvocationCompactor>,
671 session: Arc<MutableSession>,
672 ) -> Self {
673 Self { compactor, session, retry_from: Mutex::new(HashMap::new()), background: None }
674 }
675
676 pub(crate) fn with_background(
679 mut self,
680 background: Option<Arc<BackgroundCompactions>>,
681 ) -> Self {
682 self.background = background;
683 self
684 }
685}
686
687const BACKGROUND_SUMMARY_TTL: std::time::Duration = std::time::Duration::from_secs(60 * 60);
690
691#[derive(Default)]
694pub(crate) struct BackgroundCompactions {
695 pending: Mutex<HashMap<BackgroundKey, PendingCompaction>>,
696}
697
698#[derive(Debug, Clone, PartialEq, Eq, Hash)]
700struct BackgroundKey {
701 app: String,
702 user: String,
703 session: String,
704 agent: String,
705 branch: String,
706}
707
708impl BackgroundKey {
709 fn of(ctx: &dyn InvocationContext) -> Self {
710 Self {
711 app: ctx.app_name().to_string(),
712 user: ctx.user_id().to_string(),
713 session: ctx.session_id().to_string(),
714 agent: ctx.agent_name().to_string(),
715 branch: ctx.branch().to_string(),
716 }
717 }
718}
719
720struct PendingCompaction {
722 summarized: Vec<Content>,
724 started: std::time::Instant,
725 task: tokio::task::JoinHandle<Option<Summary>>,
726}
727
728impl PendingCompaction {
729 fn covers(&self, history: &[Content]) -> bool {
732 let visible = |content: &Content| {
733 let mut content = content.clone();
734 adk_core::history::strip_native(&mut content);
735 content
736 };
737 history.len() > self.summarized.len()
738 && history
739 .iter()
740 .zip(&self.summarized)
741 .all(|(current, summarized)| visible(current) == visible(summarized))
742 }
743}
744
745impl BackgroundCompactions {
746 fn take(
748 &self,
749 key: &BackgroundKey,
750 ready: impl FnOnce(&PendingCompaction) -> bool,
751 ) -> Option<PendingCompaction> {
752 let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
753 if !pending.get(key).is_some_and(ready) {
754 return None;
755 }
756 pending.remove(key)
757 }
758
759 fn contains(&self, key: &BackgroundKey) -> bool {
760 self.pending.lock().unwrap_or_else(PoisonError::into_inner).contains_key(key)
761 }
762
763 fn insert(&self, key: BackgroundKey, compaction: PendingCompaction) {
765 let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
766 pending.retain(|_, waiting| {
767 let fresh = waiting.started.elapsed() < BACKGROUND_SUMMARY_TTL;
768 if !fresh {
769 waiting.task.abort();
770 }
771 fresh
772 });
773 pending.insert(key, compaction);
774 }
775}
776
777impl std::fmt::Debug for RunCompactor {
778 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
779 f.debug_struct("RunCompactor").field("compactor", &self.compactor).finish_non_exhaustive()
780 }
781}
782
783#[async_trait]
784impl HistoryCompactor for RunCompactor {
785 async fn compact(
786 &self,
787 ctx: Arc<dyn InvocationContext>,
788 model: Arc<dyn Llm>,
789 request: HistoryCompactionRequest<'_>,
790 ) -> Result<Option<CompactedHistory>> {
791 let agent = ctx.agent_name().to_string();
792 let retry_from =
793 || self.retry_from.lock().unwrap_or_else(PoisonError::into_inner).get(&agent).copied();
794 let paused = request.trigger == CompactionTrigger::BeforeModelCall
795 && retry_from().is_some_and(|from| request.history.len() < from);
796 if paused && self.background.is_none() {
797 return Ok(None);
798 }
799 let history_len = request.history.len();
800 let reads_run_session = std::ptr::addr_eq(
803 ctx.session() as *const dyn adk_core::Session,
804 Arc::as_ptr(&self.session),
805 );
806 let session = reads_run_session.then_some(self.session.as_ref());
807 let outcome = match &self.background {
808 Some(background) => {
810 self.compactor
811 .compact_in_background(ctx, model, request, session, background, !paused)
812 .await
813 }
814 None => self.compactor.compact_history(ctx, model, request, session).await,
815 };
816 let mut retry_from = self.retry_from.lock().unwrap_or_else(PoisonError::into_inner);
817 match &outcome {
818 Outcome::BelowThreshold | Outcome::NothingToCompact => {}
819 Outcome::Compacted(_) => {
820 retry_from.remove(&agent);
821 }
822 Outcome::Kept => {
823 let step = self.compactor.config.overlap_event_count.max(1);
824 retry_from.insert(agent, history_len + step);
825 }
826 }
827 Ok(outcome.compacted())
828 }
829}
830
831fn without_thinking(kept: &[Content]) -> impl Iterator<Item = Content> + '_ {
834 kept.iter().filter_map(|content| {
835 let mut content = content.clone();
836 content.parts.retain(|part| !matches!(part, Part::Thinking { .. }));
837 (!content.parts.is_empty()).then_some(content)
838 })
839}
840
841pub(crate) const KEEPS_THINKING_KEY: &str = "adk_compaction_keeps_thinking";
844
845const NATIVE_SUMMARY_MAX_TOKENS: i32 = 16_384;
848
849struct NativeSummary {
851 content: Content,
852 origin: Option<ProviderOrigin>,
853}
854
855struct Summary {
857 content: Content,
859 origin: Option<ProviderOrigin>,
861 native: Option<NativeCompaction>,
863 tokens: u64,
864 replaced_tokens: u64,
865}
866
867#[derive(Clone, Default)]
871struct Template {
872 preamble: Vec<Content>,
873 tools: Option<ToolDeclarations>,
874 config: Option<GenerateContentConfig>,
875}
876
877impl Template {
878 fn of(request: &HistoryCompactionRequest<'_>) -> Self {
879 Self {
880 preamble: request.preamble.to_vec(),
881 tools: request.tools.cloned(),
882 config: request.config.cloned(),
883 }
884 }
885}
886
887fn text_tokens(content: &Content, chars_per_token: u32) -> u64 {
889 let text = Content {
890 role: content.role.clone(),
891 parts: content
892 .parts
893 .iter()
894 .filter(|part| matches!(part, Part::Text { .. }))
895 .cloned()
896 .collect(),
897 };
898 estimate_content_tokens(std::slice::from_ref(&text), chars_per_token)
899}
900
901fn recorded_cut(
904 ctx: &dyn InvocationContext,
905 history: &[Content],
906 cut: usize,
907 session: Option<&MutableSession>,
908) -> Option<SessionCut> {
909 session
910 .filter(|_| ctx.branch().is_empty())
911 .and_then(|session| session.read_events(|events| session_cut(events, history, cut)))
912}
913
914async fn native_summary(
919 model: &dyn Llm,
920 template: &Template,
921 summarized: &[Content],
922) -> Option<NativeSummary> {
923 let contents = template
926 .preamble
927 .iter()
928 .chain(summarized)
929 .cloned()
930 .map(|mut content| {
931 content.strip_generated_call_ids();
932 if !matches!(content.role.as_str(), "model" | "assistant") {
933 adk_core::history::strip_native(&mut content);
934 }
935 content
936 })
937 .collect();
938 let mut llm_request = LlmRequest::new(model.name(), contents);
939 if let Some(tools) = &template.tools {
940 llm_request.tools = tools.clone();
941 }
942 let config = llm_request.config.insert(template.config.clone().unwrap_or_default());
943 config.max_output_tokens =
944 Some(config.max_output_tokens.unwrap_or(0).max(NATIVE_SUMMARY_MAX_TOKENS));
945 config.response_schema = None;
946 config.stop_sequences.clear();
947 NativeCompactionRequest::new().apply(&mut llm_request);
948
949 let mut responses = match adk_core::generate_metered(model, llm_request, false).await {
950 Ok(responses) => responses,
951 Err(error) => {
952 tracing::warn!(
953 error = %error.diagnostics(),
954 "provider compaction failed; summarizing with the runner's summarizer"
955 );
956 return None;
957 }
958 };
959 let mut compaction = None;
960 while let Some(response) = responses.next().await {
961 match response {
962 Ok(response) if response.error_code.is_some() => {
963 tracing::warn!(
964 error.code = response.error_code.as_deref().unwrap_or_default(),
965 "provider compaction was declined; summarizing with the runner's summarizer"
966 );
967 return None;
968 }
969 Ok(response) => {
970 if let Some(content) = response.content.filter(is_native_compaction) {
971 let origin = ProviderOrigin::of_response(response.provider_metadata.as_ref());
972 compaction = Some((content, origin));
973 }
974 }
975 Err(error) => {
976 tracing::warn!(
977 error = %error.diagnostics(),
978 "provider compaction failed; summarizing with the runner's summarizer"
979 );
980 return None;
981 }
982 }
983 }
984 let Some((mut content, origin)) = compaction else {
985 tracing::warn!(
986 "the provider returned no compaction; summarizing with the runner's summarizer"
987 );
988 return None;
989 };
990 adk_core::history::mark_origin(&mut content, origin.as_ref());
991 Some(NativeSummary { content, origin })
992}
993
994fn speaks(content: &Content) -> bool {
996 matches!(content.role.as_str(), "model" | "assistant")
997}
998
999fn has_requested_call(content: &Content) -> bool {
1002 content.parts.iter().any(|part| match part {
1003 Part::FunctionCall { id: Some(id), .. } | Part::FunctionResponse { id: Some(id), .. } => {
1004 adk_core::RequestedCall::is_requested_id(id)
1005 }
1006 _ => false,
1007 })
1008}
1009
1010fn as_events(ctx: &dyn InvocationContext, contents: &[Content]) -> Vec<Event> {
1013 contents
1014 .iter()
1015 .map(|content| {
1016 let mut event = Event::new(ctx.invocation_id());
1017 event.author = match content.role.as_str() {
1018 "user" => "user".to_string(),
1019 _ => ctx.agent_name().to_string(),
1020 };
1021 event.set_content(content.clone());
1022 event
1023 })
1024 .collect()
1025}
1026
1027fn summary_text(event: &Event) -> String {
1029 event
1030 .actions
1031 .compaction
1032 .as_ref()
1033 .map(|compaction| &compaction.compacted_content)
1034 .or(event.llm_response.content.as_ref())
1035 .map(text_of)
1036 .unwrap_or_default()
1037}
1038
1039fn text_of(content: &Content) -> String {
1040 content.parts.iter().filter_map(Part::text).collect::<Vec<_>>().join("\n")
1041}
1042
1043struct SessionCut {
1045 cut: usize,
1047 span: EventCompaction,
1049}
1050
1051fn session_cut(events: &[Event], history: &[Content], cut: usize) -> Option<SessionCut> {
1057 let earlier = events.iter().rev().find_map(|event| event.actions.compaction.as_ref());
1058 let visible = |event: &&Event| {
1059 event.actions.compaction.is_none()
1060 && !event.llm_response.partial
1061 && earlier.is_none_or(|compaction| event.timestamp > compaction.end_timestamp)
1062 };
1063 (cut.div_ceil(2).max(1)..=cut).rev().filter(|&at| at < history.len()).find_map(|at| {
1064 if balanced_content_cut(history, at) != at {
1065 return None;
1066 }
1067 let first_kept = &history[at];
1068 let mut matches = events
1069 .iter()
1070 .enumerate()
1071 .filter(|(_, event)| visible(event) && same_turn(event, first_kept));
1072 let (index, anchor) = matches.next()?;
1073 if matches.next().is_some() {
1074 return None;
1075 }
1076 let end = events[..index]
1077 .iter()
1078 .map(|event| event.timestamp)
1079 .filter(|timestamp| *timestamp < anchor.timestamp)
1080 .max()?;
1081 if events[index..]
1082 .iter()
1083 .any(|event| event.timestamp.timestamp_millis() <= end.timestamp_millis())
1084 {
1085 return None;
1086 }
1087 let start = events
1088 .first()
1089 .map(|event| event.timestamp)
1090 .into_iter()
1091 .chain(earlier.map(|compaction| compaction.start_timestamp))
1092 .min()?;
1093 let span = EventCompaction {
1094 start_timestamp: start,
1095 end_timestamp: end,
1096 compacted_content: Content::new("model"),
1097 };
1098 Some(SessionCut { cut: at, span })
1099 })
1100}
1101
1102fn same_turn(event: &Event, content: &Content) -> bool {
1105 let Some(recorded) = &event.llm_response.content else {
1106 return false;
1107 };
1108 let role = match (event.author.as_str(), recorded.role.as_str()) {
1109 ("user", _) => "user",
1110 (_, role @ ("function" | "tool")) => role,
1111 _ => "model",
1112 };
1113 let key = |content: &Content| -> Vec<String> {
1114 content
1115 .parts
1116 .iter()
1117 .filter_map(|part| match part {
1118 Part::Text { text } => Some(format!("text:{text}")),
1119 Part::FunctionCall { name, id, .. } => {
1120 Some(format!("call:{}", id.as_deref().unwrap_or(name)))
1121 }
1122 Part::FunctionResponse { function_response, id, .. } => {
1123 Some(format!("response:{}", id.as_deref().unwrap_or(&function_response.name)))
1124 }
1125 _ => None,
1126 })
1127 .collect()
1128 };
1129 let wanted = key(content);
1130 role == content.role && !wanted.is_empty() && key(recorded) == wanted
1131}
1132
1133#[cfg(test)]
1134mod tests {
1135 use super::*;
1136 use adk_core::{
1137 Content, EventActions, EventCompaction, FunctionResponseData, Part,
1138 ToolConfirmationRequest, confirmation_pending_response, held_tool_calls,
1139 };
1140 use async_trait::async_trait;
1141 use serde_json::json;
1142
1143 struct Summary;
1144
1145 #[async_trait]
1146 impl BaseEventsSummarizer for Summary {
1147 async fn summarize_events(&self, events: &[Event]) -> Result<Option<Event>> {
1148 let mut event = Event::new("compaction");
1149 event.actions = EventActions {
1150 compaction: Some(EventCompaction {
1151 start_timestamp: events[0].timestamp,
1152 end_timestamp: events[events.len() - 1].timestamp,
1153 compacted_content: Content::new("model").with_text("summary"),
1154 }),
1155 ..Default::default()
1156 };
1157 Ok(Some(event))
1158 }
1159 }
1160
1161 fn event(author: &str, parts: Vec<Part>) -> Event {
1162 let mut event = Event::new("inv-1");
1163 event.author = author.to_string();
1164 event.set_content(Content { role: "model".to_string(), parts });
1165 event
1166 }
1167
1168 fn config(
1169 token_threshold: u64,
1170 overlap_event_count: usize,
1171 chars_per_token: u32,
1172 ) -> IntraCompactionConfig {
1173 IntraCompactionConfig {
1174 token_threshold: Some(token_threshold),
1175 overlap_event_count,
1176 chars_per_token,
1177 ..IntraCompactionConfig::default()
1178 }
1179 }
1180
1181 #[tokio::test]
1182 async fn a_held_call_and_the_events_after_it_are_never_summarized() {
1183 let mut events: Vec<Event> = (0..6)
1184 .map(|index| {
1185 event("user", vec![Part::Text { text: format!("message {index} ").repeat(50) }])
1186 })
1187 .collect();
1188 events.push(event(
1189 "ops",
1190 vec![Part::FunctionCall {
1191 name: "transfer".to_string(),
1192 args: json!({ "amount": 10 }),
1193 id: Some("c1".to_string()),
1194 thought_signature: None,
1195 }],
1196 ));
1197 events.push(event(
1198 "ops",
1199 vec![Part::FunctionResponse {
1200 function_response: FunctionResponseData::new(
1201 "transfer",
1202 confirmation_pending_response("held"),
1203 ),
1204 id: Some("c1".to_string()),
1205 annotations: None,
1206 }],
1207 ));
1208 let mut hold = Event::new("inv-1");
1209 hold.author = "ops".to_string();
1210 hold.actions.tool_confirmation = Some(ToolConfirmationRequest {
1211 tool_name: "transfer".to_string(),
1212 function_call_id: Some("c1".to_string()),
1213 args: json!({ "amount": 10 }),
1214 acting: None,
1215 origin: None,
1216 evidence: Vec::new(),
1217 });
1218 events.push(hold);
1219 let start = chrono::Utc::now();
1220 for (index, event) in events.iter_mut().enumerate() {
1221 event.timestamp = start + chrono::Duration::milliseconds(index as i64);
1222 }
1223
1224 let compactor = IntraInvocationCompactor::new(config(1, 0, 4), Arc::new(Summary));
1225 let compacted = compactor.maybe_compact(&events).await.unwrap().expect("compacted");
1226 assert_eq!(compacted.len(), 4, "the summary, then the held call's three events");
1227 assert_eq!(held_tool_calls(&compacted, "ops", "").len(), 1);
1228 }
1229
1230 fn call_and_result(id: &str) -> [Event; 2] {
1231 [
1232 event(
1233 "desk",
1234 vec![Part::FunctionCall {
1235 name: "lookup".to_string(),
1236 args: json!({}),
1237 id: Some(id.to_string()),
1238 thought_signature: None,
1239 }],
1240 ),
1241 event(
1242 "desk",
1243 vec![Part::FunctionResponse {
1244 function_response: FunctionResponseData::new("lookup", json!({"ok": true})),
1245 id: Some(id.to_string()),
1246 annotations: None,
1247 }],
1248 ),
1249 ]
1250 }
1251
1252 #[tokio::test]
1253 async fn the_kept_events_never_start_on_a_result_whose_call_was_summarized() {
1254 let mut events = vec![event("user", vec![Part::Text { text: "background ".repeat(100) }])];
1255 events.extend(call_and_result("c1"));
1256 events.push(event("desk", vec![Part::Text { text: "a1".to_string() }]));
1257 events.push(event("user", vec![Part::Text { text: "q2".to_string() }]));
1258
1259 let compactor = IntraInvocationCompactor::new(config(1, 3, 4), Arc::new(Summary));
1261 let compacted = compactor.maybe_compact(&events).await.unwrap().expect("compacted");
1262 assert_eq!(compacted.len(), 5, "the summary, then the call, its result, a1 and q2");
1263 assert_eq!(compacted[1].id, events[1].id);
1264 }
1265
1266 #[tokio::test]
1267 async fn a_summary_that_does_not_shrink_the_history_is_not_used() {
1268 let mut events = vec![event("user", vec![Part::Text { text: "q".to_string() }])];
1269 events.push(event("desk", vec![Part::Text { text: "a".to_string() }]));
1270 events.push(event("user", vec![Part::Text { text: "q2".to_string() }]));
1271 let compactor = IntraInvocationCompactor::new(config(0, 1, 1), Arc::new(Summary));
1272 assert!(compactor.maybe_compact(&events).await.unwrap().is_none());
1274 }
1275
1276 fn recorded(author: &str, content: Content, at: chrono::DateTime<chrono::Utc>) -> Event {
1277 let mut event = Event::new("inv-1");
1278 event.author = author.to_string();
1279 event.timestamp = at;
1280 event.set_content(content);
1281 event
1282 }
1283
1284 fn call(id: &str) -> Content {
1285 Content {
1286 role: "model".to_string(),
1287 parts: vec![Part::FunctionCall {
1288 name: "lookup".to_string(),
1289 args: json!({}),
1290 id: Some(id.to_string()),
1291 thought_signature: None,
1292 }],
1293 }
1294 }
1295
1296 fn result(id: &str) -> Content {
1297 Content {
1298 role: "function".to_string(),
1299 parts: vec![Part::FunctionResponse {
1300 function_response: FunctionResponseData::new("lookup", json!({"ok": true})),
1301 id: Some(id.to_string()),
1302 annotations: None,
1303 }],
1304 }
1305 }
1306
1307 #[test]
1308 fn a_compaction_is_recorded_up_to_the_event_before_the_first_kept_entry() {
1309 let history = vec![
1310 Content::new("user").with_text("find A1"),
1311 call("c1"),
1312 result("c1"),
1313 call("c2"),
1314 result("c2"),
1315 ];
1316 let start = chrono::Utc::now();
1317 let ms = |n: i64| start + chrono::Duration::milliseconds(n);
1318 let events = vec![
1319 recorded("user", history[0].clone(), ms(0)),
1320 recorded("desk", history[1].clone(), ms(10)),
1321 recorded("desk", history[2].clone(), ms(20)),
1322 recorded("desk", history[3].clone(), ms(30)),
1323 recorded("desk", history[4].clone(), ms(40)),
1324 ];
1325 let cut = session_cut(&events, &history, 3).expect("placed");
1326 assert_eq!((cut.cut, cut.span.start_timestamp, cut.span.end_timestamp), (3, ms(0), ms(20)));
1327
1328 let mut repeated = history.clone();
1330 repeated[4] = Content::new("user").with_text("find A1");
1331 let mut events = events;
1332 events[4] = recorded("user", repeated[4].clone(), ms(40));
1333 let cut = session_cut(&events, &repeated, 4).expect("placed earlier");
1334 assert_eq!((cut.cut, cut.span.end_timestamp), (3, ms(20)));
1335
1336 events[3].timestamp = ms(20) + chrono::Duration::microseconds(5);
1338 assert!(session_cut(&events, &repeated, 4).is_none());
1339 }
1340}