use std::sync::Arc;
use async_trait::async_trait;
use crate::{
AdkError, Content, ErrorCategory, ErrorComponent, Event, GenerateContentConfig,
InvocationContext, Llm, LlmRequest, Part, ToolDeclarations,
};
pub const DEFAULT_TOKEN_THRESHOLD: u64 = 100_000;
pub const DEFAULT_CONTEXT_WINDOW_FRACTION: f64 = 0.8;
pub const DEFAULT_BACKGROUND_FRACTION: f64 = 0.7;
#[derive(Debug, Clone, PartialEq)]
pub struct IntraCompactionConfig {
pub enabled: bool,
pub token_threshold: Option<u64>,
pub context_window_fraction: f64,
pub overlap_event_count: usize,
pub chars_per_token: u32,
pub native: bool,
pub background: bool,
pub background_fraction: f64,
}
impl Default for IntraCompactionConfig {
fn default() -> Self {
Self {
enabled: true,
token_threshold: None,
context_window_fraction: DEFAULT_CONTEXT_WINDOW_FRACTION,
overlap_event_count: 10,
chars_per_token: 4,
native: true,
background: false,
background_fraction: DEFAULT_BACKGROUND_FRACTION,
}
}
}
impl IntraCompactionConfig {
pub fn disabled() -> Self {
Self { enabled: false, ..Self::default() }
}
pub fn at_tokens(threshold: u64) -> Self {
Self { token_threshold: Some(threshold), ..Self::default() }
}
pub fn at_window_fraction(fraction: f64) -> Self {
Self { context_window_fraction: fraction, ..Self::default() }
}
pub fn with_overlap_event_count(mut self, count: usize) -> Self {
self.overlap_event_count = count;
self
}
pub fn with_native(mut self, native: bool) -> Self {
self.native = native;
self
}
pub fn in_background(mut self, fraction: f64) -> Self {
self.background = true;
self.background_fraction = fraction;
self
}
pub fn background_threshold_for(&self, context_window: Option<u64>) -> u64 {
let fraction = if self.background_fraction > 0.0 && self.background_fraction < 1.0 {
self.background_fraction
} else {
DEFAULT_BACKGROUND_FRACTION
};
(self.threshold_for(context_window) as f64 * fraction) as u64
}
pub fn threshold_for(&self, context_window: Option<u64>) -> u64 {
if let Some(threshold) = self.token_threshold {
return threshold;
}
let Some(window) = context_window else {
return DEFAULT_TOKEN_THRESHOLD;
};
let fraction = if self.context_window_fraction > 0.0 && self.context_window_fraction <= 1.0
{
self.context_window_fraction
} else {
DEFAULT_CONTEXT_WINDOW_FRACTION
};
(window as f64 * fraction) as u64
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompactionTrigger {
BeforeModelCall,
ContextLimitExceeded,
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct HistoryCompactionRequest<'a> {
pub preamble: &'a [Content],
pub history: &'a [Content],
pub reported_prompt_tokens: Option<u64>,
pub trigger: CompactionTrigger,
pub tools: Option<&'a ToolDeclarations>,
pub config: Option<&'a GenerateContentConfig>,
}
impl<'a> HistoryCompactionRequest<'a> {
pub fn new(history: &'a [Content], trigger: CompactionTrigger) -> Self {
Self {
preamble: &[],
history,
reported_prompt_tokens: None,
trigger,
tools: None,
config: None,
}
}
pub fn with_preamble(mut self, preamble: &'a [Content]) -> Self {
self.preamble = preamble;
self
}
pub fn with_reported_prompt_tokens(mut self, tokens: Option<u64>) -> Self {
self.reported_prompt_tokens = tokens;
self
}
pub fn with_tools(mut self, tools: &'a ToolDeclarations) -> Self {
self.tools = Some(tools);
self
}
pub fn with_config(mut self, config: Option<&'a GenerateContentConfig>) -> Self {
self.config = config;
self
}
}
#[derive(Debug, Clone)]
pub struct CompactedHistory {
pub history: Vec<Content>,
pub event: Option<Event>,
}
#[async_trait]
pub trait HistoryCompactor: Send + Sync + std::fmt::Debug {
async fn compact(
&self,
ctx: Arc<dyn InvocationContext>,
model: Arc<dyn Llm>,
request: HistoryCompactionRequest<'_>,
) -> crate::Result<Option<CompactedHistory>>;
}
pub const COMPACTION_SUMMARY_HEADING: &str =
"The earlier conversation was compacted to fit the model's context window. Summary:";
pub fn compaction_summary(summary: &str) -> Content {
crate::history::system_notice(&format!("{COMPACTION_SUMMARY_HEADING}\n{summary}"))
}
pub fn compaction_summary_text(summary: &str) -> String {
format!("{COMPACTION_SUMMARY_HEADING}\n{summary}")
}
pub const NATIVE_COMPACTION_KEY: &str = "adk_native_compaction";
pub fn is_native_compaction(content: &Content) -> bool {
matches!(content.role.as_str(), "model" | "assistant")
&& content.parts.iter().any(|part| {
let (Part::ServerToolCall { server_tool_call: payload }
| Part::ServerToolResponse { server_tool_response: payload }) = part
else {
return false;
};
payload.get(NATIVE_COMPACTION_KEY).and_then(serde_json::Value::as_bool) == Some(true)
})
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct NativeCompactionRequest {
pub instructions: Option<String>,
}
impl NativeCompactionRequest {
pub const EXTENSION_KEY: &'static str = "adk_native_compaction";
pub fn new() -> Self {
Self::default()
}
pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
pub fn apply(&self, request: &mut LlmRequest) {
let mut ask = serde_json::Map::new();
if let Some(instructions) = &self.instructions {
ask.insert("instructions".to_string(), serde_json::Value::from(instructions.clone()));
}
request
.config
.get_or_insert_with(GenerateContentConfig::default)
.extensions
.insert(Self::EXTENSION_KEY.to_string(), serde_json::Value::Object(ask));
}
pub fn of(request: &LlmRequest) -> Option<Self> {
let ask = request.config.as_ref()?.extensions.get(Self::EXTENSION_KEY)?.as_object()?;
Some(Self {
instructions: ask
.get("instructions")
.and_then(serde_json::Value::as_str)
.map(str::to_string),
})
}
}
pub fn is_context_limit_error(err: &AdkError) -> bool {
if err.component != ErrorComponent::Model || err.category != ErrorCategory::InvalidInput {
return false;
}
if err.code == "runner.context_overflow" {
return true;
}
let message = err.message.to_lowercase();
[
"prompt is too long",
"context length",
"context_length_exceeded",
"context window",
"context limit",
"maximum context",
"too many tokens",
"input is too long",
"input too long",
"input token count",
"exceeds the maximum number of tokens",
"request payload size exceeds",
"reduce the length of the messages",
]
.iter()
.any(|pattern| message.contains(pattern))
}
pub fn estimate_tokens(events: &[Event], chars_per_token: u32) -> u64 {
if chars_per_token == 0 {
return 0;
}
let total_chars: u64 = events.iter().map(|e| estimate_event_chars(e) as u64).sum();
total_chars / chars_per_token as u64
}
pub fn estimate_content_tokens(contents: &[Content], chars_per_token: u32) -> u64 {
if chars_per_token == 0 {
return 0;
}
let chars: u64 = contents
.iter()
.flat_map(|content| &content.parts)
.map(|part| estimate_part_chars(part) as u64)
.sum();
chars / chars_per_token as u64
}
fn estimate_event_chars(event: &Event) -> usize {
let mut chars = 0;
let summary = event.actions.compaction.as_ref().map(|compaction| &compaction.compacted_content);
for content in event.llm_response.content.iter().chain(summary) {
for part in &content.parts {
chars += estimate_part_chars(part);
}
}
if !event.actions.state_delta.is_empty() {
chars += json_len(&event.actions.state_delta);
}
chars
}
fn estimate_part_chars(part: &Part) -> usize {
match part {
Part::Text { text } => text.len(),
Part::Thinking { thinking, .. } => thinking.len(),
Part::FunctionCall { name, args, .. } => name.len() + json_len(args),
Part::FunctionResponse { function_response, .. } => {
function_response.name.len() + json_len(&function_response.response)
}
Part::InlineData { .. } | Part::FileData { .. } => 0,
Part::ServerToolCall { server_tool_call } => json_len(server_tool_call),
Part::ServerToolResponse { server_tool_response } => json_len(server_tool_response),
Part::EmbeddedResource { resource } => json_len(resource),
}
}
fn json_len<T: serde::Serialize + ?Sized>(value: &T) -> usize {
struct Count(usize);
impl std::io::Write for Count {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0 += bytes.len();
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut count = Count(0);
serde_json::to_writer(&mut count, value).map_or(0, |()| count.0)
}
pub fn render_part_for_summary(part: &Part) -> Option<String> {
let json = |value: &serde_json::Value| value.to_string();
Some(match part {
Part::Text { text } => text.clone(),
Part::Thinking { .. } | Part::ServerToolCall { .. } | Part::ServerToolResponse { .. } => {
return None;
}
Part::FunctionCall { name, args, .. } => format!("[function call] {name}({})", json(args)),
Part::FunctionResponse { function_response, .. } => {
let mut rendered = format!(
"[function response] {}: {}",
function_response.name,
json(&function_response.response)
);
for data in &function_response.inline_data {
rendered.push_str(&format!(" [inline data: {}]", data.mime_type));
}
for file in &function_response.file_data {
rendered.push_str(&format!(" [file: {} ({})]", file.file_uri, file.mime_type));
}
rendered
}
Part::InlineData { mime_type, data, .. } => {
format!("[inline data: {mime_type}, {} bytes]", data.len())
}
Part::FileData { mime_type, file_uri, .. } => format!("[file: {file_uri} ({mime_type})]"),
Part::EmbeddedResource { resource } => match resource {
crate::EmbeddedResource::Text(text) => format!("[resource {}] {}", text.uri, text.text),
crate::EmbeddedResource::Blob(blob) => format!(
"[resource {}: {}, {} bytes]",
blob.uri,
blob.mime_type.as_deref().unwrap_or("application/octet-stream"),
blob.data.len()
),
},
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Content, FunctionResponseData};
#[test]
fn the_default_is_on_at_a_fraction_of_the_window() {
assert_eq!(
IntraCompactionConfig::default(),
IntraCompactionConfig {
enabled: true,
token_threshold: None,
context_window_fraction: 0.8,
overlap_event_count: 10,
chars_per_token: 4,
native: true,
background: false,
background_fraction: DEFAULT_BACKGROUND_FRACTION,
}
);
}
#[test]
fn a_fixed_threshold_wins_and_a_bad_fraction_falls_back() {
let config = IntraCompactionConfig::default();
assert_eq!(config.threshold_for(Some(200_000)), 160_000);
assert_eq!(config.threshold_for(None), DEFAULT_TOKEN_THRESHOLD);
assert_eq!(IntraCompactionConfig::at_tokens(5).threshold_for(Some(200_000)), 5);
for fraction in [0.0, -1.0, 1.5, f64::NAN] {
let config = IntraCompactionConfig::at_window_fraction(fraction);
assert_eq!(config.threshold_for(Some(100)), 80, "fraction {fraction}");
}
assert_eq!(IntraCompactionConfig::at_window_fraction(0.5).threshold_for(Some(100)), 50);
}
#[test]
fn context_limit_errors_are_told_from_other_client_errors() {
let model_error = |message: &str| {
AdkError::new(
ErrorComponent::Model,
ErrorCategory::InvalidInput,
"model.api_error",
message.to_string(),
)
};
for message in [
"400: prompt is too long: 1048577 tokens > 1000000 maximum (invalid_request_error)",
"This model's maximum context length is 128000 tokens",
"context_length_exceeded",
"input length and `max_tokens` exceed context limit: 190000 + 32000 > 200000",
"The input token count (1100000) exceeds the maximum number of tokens allowed (1048576).",
] {
assert!(is_context_limit_error(&model_error(message)), "{message}");
}
for message in [
"max_tokens: 200000 > 128000, which is the maximum allowed number of output tokens",
"invalid x-api-key",
"tools.0.name: String should match pattern",
] {
assert!(!is_context_limit_error(&model_error(message)), "{message}");
}
let unavailable = AdkError::new(
ErrorComponent::Model,
ErrorCategory::Unavailable,
"model.api_error",
"prompt is too long",
);
assert!(!is_context_limit_error(&unavailable));
}
#[test]
fn contents_are_estimated_like_events() {
let call = Content {
role: "model".to_string(),
parts: vec![Part::FunctionCall {
name: "get_weather".to_string(),
args: serde_json::json!({"city": "NYC"}),
id: None,
thought_signature: None,
}],
};
let mut event = Event::new("inv-1");
event.set_content(call.clone());
assert_eq!(estimate_content_tokens(&[call], 1), 25);
assert_eq!(estimate_tokens(&[event], 1), 25);
}
#[test]
fn test_estimate_tokens_empty() {
assert_eq!(estimate_tokens(&[], 4), 0);
}
#[test]
fn test_estimate_tokens_zero_ratio() {
let mut event = Event::new("inv-1");
event.set_content(Content::new("user").with_text("Hello"));
assert_eq!(estimate_tokens(&[event], 0), 0);
}
#[test]
fn test_estimate_tokens_text_only() {
let mut event = Event::new("inv-1");
event.set_content(Content::new("user").with_text("Hello"));
assert_eq!(estimate_tokens(&[event], 4), 1);
}
#[test]
fn test_estimate_tokens_multiple_events() {
let mut e1 = Event::new("inv-1");
e1.set_content(Content::new("user").with_text("Hello")); let mut e2 = Event::new("inv-1");
e2.set_content(Content::new("model").with_text("World!")); assert_eq!(estimate_tokens(&[e1, e2], 4), 2);
}
#[test]
fn test_estimate_tokens_with_function_call() {
let mut event = Event::new("inv-1");
event.llm_response.content = Some(Content {
role: "model".to_string(),
parts: vec![Part::FunctionCall {
name: "get_weather".to_string(),
args: serde_json::json!({"city": "NYC"}),
id: None,
thought_signature: None,
}],
});
let tokens = estimate_tokens(&[event], 4);
assert!(tokens > 0);
}
#[test]
fn a_compaction_summary_counts_toward_the_estimate() {
let mut event = Event::new("inv-1");
event.actions.compaction = Some(crate::EventCompaction {
start_timestamp: chrono::Utc::now(),
end_timestamp: chrono::Utc::now(),
compacted_content: Content::new("model").with_text("a".repeat(40)),
});
assert_eq!(estimate_tokens(&[event], 4), 10);
}
#[test]
fn test_estimate_tokens_with_function_response() {
let mut event = Event::new("inv-1");
event.llm_response.content = Some(Content {
role: "function".to_string(),
parts: vec![Part::FunctionResponse {
function_response: FunctionResponseData::new(
"get_weather",
serde_json::json!({"temp": 72}),
),
id: None,
annotations: None,
}],
});
let tokens = estimate_tokens(&[event], 4);
assert!(tokens > 0);
}
}