1use std::sync::Arc;
19use std::time::Duration;
20
21use async_trait::async_trait;
22use futures::StreamExt;
23use gadk_genai::{Content, FinishReason, GenerateContentConfig, Part};
24use gadk_model::{Backend, Llm, LlmRequest, ModelError};
25
26use super::go_fmt::{as_go_floats, go_sprint};
27use super::{
28 CompactionConfigError, SummarizeFailure, SummarizeResult, Summarizer, content, is_prose_part,
29};
30use crate::Event;
31
32type BoxError = Box<dyn std::error::Error + Send + Sync>;
33
34pub const CONVERSATION_HISTORY_PLACEHOLDER: &str = "{conversation_history}";
37
38pub(crate) const DEFAULT_PROMPT_TEMPLATE: &str = concat!(
40 "The following is a conversation history between a user and an AI agent.",
41 " It may or may not start from a compacted history. Please identify and",
42 " reiterate the user request, summarize the context so far, focusing on",
43 " key decisions made and information obtained, as well as any unresolved",
44 " questions or tasks. ",
45 "CRITICAL INSTRUCTIONS: ",
46 "1. Explicitly identify and state the primary language used by the user ",
47 "at the top of your summary (e.g., \"Conversation Language: English\"). ",
48 "2. If the agent called any tools, accurately list the exact tool names ",
49 "used to maintain tool grounding. ",
50 "3. Maintain a section titled \"Durable facts\" listing every concrete ",
51 "detail the user has stated: identifiers, names, dates, numbers, chosen ",
52 "options and the reasons given for them. Copy each one verbatim. This ",
53 "history may already be a summary of a summary, so any durable fact ",
54 "present in the history MUST be carried forward unchanged, even if it is ",
55 "old and the recent turns are about something else. Never drop or ",
56 "generalize a durable fact to save space; drop narrative instead. ",
57 "The rest of the summary should be concise and capture the",
58 " essence of the interaction.\n\n",
59 "{conversation_history}"
60);
61
62const DEFAULT_MAX_TOOL_CONTENT_CHARS: i32 = 2000;
64const DEFAULT_MAX_TRANSCRIPT_CHARS: i32 = 200_000;
66const TRUNCATION_SUFFIX_BUDGET: i32 = 32;
68pub(crate) const LINE_BREAKERS: &str = "\r\n\u{b}\u{c}\u{85}\u{2028}\u{2029}";
70
71#[derive(Clone, Default)]
73pub struct LlmSummarizerConfig {
74 pub model: Option<Arc<dyn Llm>>,
76 pub prompt_template: String,
79 pub max_tool_content_chars: i32,
81 pub max_transcript_chars: i32,
83 pub timeout: Duration,
85 pub generate_content_config: Option<GenerateContentConfig>,
88}
89
90pub struct LlmSummarizer {
92 pub(crate) model: Arc<dyn Llm>,
93 pub(crate) prompt_template: String,
94 pub(crate) max_tool_content_chars: i32,
95 pub(crate) max_transcript_chars: i32,
96 pub(crate) gen_config: Option<GenerateContentConfig>,
97 pub(crate) timeout: Duration,
98}
99
100#[derive(Debug, thiserror::Error)]
102enum ModelCallFailed {
103 #[error("summarizer model call failed: {0}")]
104 Model(#[source] ModelError),
105 #[error("summarizer model call failed: context deadline exceeded")]
106 DeadlineExceeded,
107}
108
109impl LlmSummarizer {
110 pub fn new(cfg: LlmSummarizerConfig) -> Result<LlmSummarizer, CompactionConfigError> {
113 let Some(model) = cfg.model else {
114 return Err(CompactionConfigError::new(
115 "LlmSummarizerConfig.model is required",
116 ));
117 };
118 let template = if cfg.prompt_template.is_empty() {
119 DEFAULT_PROMPT_TEMPLATE.to_owned()
120 } else {
121 cfg.prompt_template
122 };
123 if !template.contains(CONVERSATION_HISTORY_PLACEHOLDER) {
124 return Err(CompactionConfigError::new(format!(
125 "prompt_template must contain the placeholder \"{CONVERSATION_HISTORY_PLACEHOLDER}\""
126 )));
127 }
128 let max_transcript = if cfg.max_transcript_chars == 0 {
129 DEFAULT_MAX_TRANSCRIPT_CHARS
130 } else {
131 cfg.max_transcript_chars
132 };
133 let max_chars = if cfg.max_tool_content_chars == 0 {
134 DEFAULT_MAX_TOOL_CONTENT_CHARS
135 } else {
136 cfg.max_tool_content_chars
137 };
138 Ok(LlmSummarizer {
139 model,
140 prompt_template: template,
141 max_tool_content_chars: max_chars,
142 max_transcript_chars: max_transcript,
143 timeout: cfg.timeout,
144 gen_config: summarizer_gen_config(cfg.generate_content_config.as_ref()),
145 })
146 }
147
148 async fn call_model(&self, req: LlmRequest) -> Result<SummarizeResult, BoxError> {
151 let mut responses = self.model.generate_content(req, false);
152 let mut finish_reason: Option<FinishReason> = None;
153 while let Some(item) = responses.next().await {
154 let resp = item.map_err(ModelCallFailed::Model)?;
155 if resp.partial {
157 continue;
158 }
159 if let Some(r) = &resp.finish_reason {
160 finish_reason = Some(r.clone());
161 }
162 if !has_text(resp.content.as_ref()) {
163 continue;
164 }
165 if let Some(r) = finish_reason.as_ref().filter(|r| **r != FinishReason::Stop) {
166 return Err(Box::new(SummarizeFailure {
167 usage: resp.usage_metadata,
168 source: format!(
169 "summarizer stopped before finishing (finish reason \"{}\"), so the summary is incomplete",
170 r.as_str()
171 )
172 .into(),
173 }));
174 }
175 return Ok(SummarizeResult {
176 content: resp.content,
177 usage: resp.usage_metadata,
178 });
179 }
180 match finish_reason {
181 Some(r) => Err(format!(
182 "summarizer returned no usable content (finish reason \"{}\")",
183 r.as_str()
184 )
185 .into()),
186 None => Err("summarizer returned no usable content".into()),
187 }
188 }
189
190 pub(crate) fn format_events(&self, events: &[Event], cap: i32) -> String {
192 let mut lines: Vec<String> = Vec::new();
193 for ev in events {
194 let Some(c) = content(ev).filter(|c| !c.parts.is_empty()) else {
195 continue;
196 };
197 let is_compaction = ev.actions.compaction.is_some();
198 let author = escape_lines(&ev.author);
199 for p in &c.parts {
200 if p.thought && !p.text.is_empty() {
201 if !is_compaction {
203 lines.push(format!(
204 "{author} (thought): {}",
205 escape_lines(&self.truncate_to(&p.text, cap))
206 ));
207 }
208 } else if !p.text.is_empty() {
209 lines.push(format!(
210 "{author}: {}",
211 escape_lines(&self.truncate_to(&p.text, cap))
212 ));
213 }
214 if let Some(fc) = &p.function_call {
215 lines.push(format!(
216 "{author} called tool: {}({})",
217 escape_lines(&fc.name),
218 escape_lines(&self.truncate_to(&stringify(&fc.args), cap))
219 ));
220 }
221 if let Some(fr) = &p.function_response {
222 lines.push(format!(
223 "Tool response from {}: {}",
224 escape_lines(&fr.name),
225 escape_lines(&self.truncate_to(&stringify(&fr.response), cap))
226 ));
227 }
228 let kind = placeholder_kind(p);
229 if !kind.is_empty() {
230 lines.push(format!(
231 "{author}: [{}]",
232 escape_lines(&self.truncate_to(&kind, cap))
233 ));
234 }
235 }
236 }
237 lines.join("\n")
238 }
239
240 pub(crate) fn truncate_to(&self, text: &str, cap: i32) -> String {
243 let Ok(cap) = usize::try_from(cap) else {
244 return text.to_owned();
245 };
246 if text.len() <= cap {
247 return text.to_owned();
248 }
249 let n = text.chars().count();
250 if n <= cap {
251 return text.to_owned();
252 }
253 let kept: String = text.chars().take(cap).collect();
254 format!("{kept}... [truncated {} chars]", n - cap)
255 }
256
257 pub(crate) fn render_transcript(&self, events: &[Event]) -> Result<String, BoxError> {
259 let mut transcript = self.format_events(events, self.max_tool_content_chars);
260 let mut size = rune_count(&transcript);
261 if self.max_transcript_chars < 0 || size <= self.max_transcript_chars {
262 return Ok(transcript);
263 }
264 let parts = count_rendered_parts(events);
265 if parts > 0 {
266 let cap = self.max_transcript_chars / parts - self.per_part_overhead(events);
267 if cap > 0 && (self.max_tool_content_chars < 0 || cap < self.max_tool_content_chars) {
268 let shrunk = self.format_events(events, cap);
269 let shrunk_size = rune_count(&shrunk);
270 if shrunk_size < size {
271 transcript = shrunk;
272 size = shrunk_size;
273 }
274 }
275 }
276 if size <= self.max_transcript_chars {
277 return Ok(transcript);
278 }
279 Err(format!(
280 "rendered transcript is {size} characters, over the {} limit, for a window of {} events: compact a smaller window",
281 self.max_transcript_chars,
282 events.len()
283 )
284 .into())
285 }
286
287 fn per_part_overhead(&self, events: &[Event]) -> i32 {
289 let longest = events.iter().map(|ev| ev.author.len()).max().unwrap_or(0);
290 i32::try_from(longest)
291 .unwrap_or(i32::MAX)
292 .saturating_add(3 + TRUNCATION_SUFFIX_BUDGET)
293 }
294}
295
296#[async_trait]
297impl Summarizer for LlmSummarizer {
298 async fn summarize_events(&self, events: &[Event]) -> Result<SummarizeResult, BoxError> {
300 if events.is_empty() {
301 return Ok(SummarizeResult::default());
302 }
303 let transcript = self.render_transcript(events)?;
304 let prompt =
305 self.prompt_template
306 .replacen(CONVERSATION_HISTORY_PLACEHOLDER, &transcript, 1);
307 let req = LlmRequest {
308 model: self.model.name().to_owned(),
309 contents: vec![Content::from_text(prompt, "user")],
310 config: self.gen_config.clone(),
312 ..Default::default()
313 };
314 if self.timeout.is_zero() {
315 return self.call_model(req).await;
316 }
317 match tokio::time::timeout(self.timeout, self.call_model(req)).await {
318 Ok(res) => res,
319 Err(_) => Err(Box::new(ModelCallFailed::DeadlineExceeded)),
320 }
321 }
322
323 fn type_name(&self) -> &str {
325 "LLMSummarizer"
326 }
327
328 fn google_variant(&self) -> Option<Backend> {
330 self.model.google_variant()
331 }
332}
333
334fn has_text(c: Option<&Content>) -> bool {
336 c.is_some_and(|c| {
337 c.parts
338 .iter()
339 .any(|p| !p.thought && !p.text.trim().is_empty())
340 })
341}
342
343fn rune_count(s: &str) -> i32 {
345 i32::try_from(s.chars().count()).unwrap_or(i32::MAX)
346}
347
348fn stringify(v: &serde_json::Map<String, serde_json::Value>) -> String {
350 if v.is_empty() {
351 return String::new();
352 }
353 let mut keys: Vec<&String> = v.keys().collect();
354 keys.sort();
355 let body = keys
356 .iter()
357 .map(|k| format!("{k}: {}", go_sprint(&as_go_floats(&v[k.as_str()]))))
358 .collect::<Vec<_>>()
359 .join(", ");
360 format!("{{{body}}}")
361}
362
363fn escape_lines(text: &str) -> String {
365 if !text.contains(|c| LINE_BREAKERS.contains(c)) {
366 return text.to_owned();
367 }
368 let mut out = String::with_capacity(text.len() + 8);
369 let mut chars = text.chars().peekable();
370 while let Some(c) = chars.next() {
371 if c == '\r' && chars.peek() == Some(&'\n') {
372 chars.next();
373 out.push_str("\\n");
374 } else if LINE_BREAKERS.contains(c) {
375 out.push_str("\\n");
376 } else {
377 out.push(c);
378 }
379 }
380 out
381}
382
383pub(crate) fn summarizer_gen_config(
385 cfg: Option<&GenerateContentConfig>,
386) -> Option<GenerateContentConfig> {
387 let cfg = cfg?;
388 Some(GenerateContentConfig {
389 safety_settings: cfg.safety_settings.clone(),
390 temperature: cfg.temperature,
391 top_p: cfg.top_p,
392 top_k: cfg.top_k,
393 seed: cfg.seed,
394 labels: cfg.labels.clone(),
395 ..Default::default()
396 })
397}
398
399fn placeholder_kind(p: &Part) -> String {
401 if let Some(b) = &p.inline_data {
402 mime_or(&b.mime_type, "inline data")
403 } else if let Some(f) = &p.file_data {
404 mime_or(&f.mime_type, "file")
405 } else if p.executable_code.is_some() {
406 "executable code".to_owned()
407 } else if p.code_execution_result.is_some() {
408 "code execution result".to_owned()
409 } else {
410 String::new()
411 }
412}
413
414fn mime_or(mime_type: &str, fallback: &str) -> String {
416 if mime_type.is_empty() {
417 fallback.to_owned()
418 } else {
419 format!("{mime_type} attachment")
420 }
421}
422
423pub(crate) fn count_rendered_parts(events: &[Event]) -> i32 {
425 let mut n = 0i32;
426 for ev in events {
427 let Some(c) = content(ev) else { continue };
428 for p in &c.parts {
429 if !p.text.is_empty()
430 || p.function_call.is_some()
431 || p.function_response.is_some()
432 || is_prose_part(p)
433 || !placeholder_kind(p).is_empty()
434 {
435 n += 1;
436 }
437 }
438 }
439 n
440}
441
442#[cfg(test)]
443#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
444mod tests {
445 use super::*;
446
447 #[test]
448 fn escape_lines_treats_crlf_as_one_break() {
449 assert_eq!(escape_lines("a\r\nb\rc\nd\u{2028}e"), "a\\nb\\nc\\nd\\ne");
450 assert_eq!(escape_lines("plain"), "plain");
451 }
452
453 #[test]
454 fn default_template_ends_with_the_placeholder() {
455 assert!(
456 DEFAULT_PROMPT_TEMPLATE.ends_with(&format!("\n\n{CONVERSATION_HISTORY_PLACEHOLDER}"))
457 );
458 assert_eq!(
459 DEFAULT_PROMPT_TEMPLATE
460 .matches(CONVERSATION_HISTORY_PLACEHOLDER)
461 .count(),
462 1
463 );
464 }
465
466 #[test]
467 fn summarizer_gen_config_keeps_the_six_fields() {
468 let input = GenerateContentConfig {
469 temperature: Some(0.1),
470 top_p: Some(0.2),
471 top_k: Some(3.0),
472 seed: Some(4),
473 labels: [("k".to_owned(), "v".to_owned())].into(),
474 max_output_tokens: 9,
475 ..Default::default()
476 };
477 let got = summarizer_gen_config(Some(&input)).unwrap();
478 assert_eq!(
479 (
480 got.temperature,
481 got.top_p,
482 got.top_k,
483 got.seed,
484 got.labels.clone(),
485 got.max_output_tokens
486 ),
487 (
488 Some(0.1),
489 Some(0.2),
490 Some(3.0),
491 Some(4),
492 input.labels.clone(),
493 0
494 )
495 );
496 assert!(summarizer_gen_config(None).is_none());
497 }
498}