1use serde_json::Value;
4
5use crate::error::{Error, Result};
6use crate::model::SystemLanguageModel;
7use crate::options::GenerationOptions;
8use crate::session::Session;
9
10pub const DEFAULT_CONTEXT_TOKENS: usize = 4096;
22
23#[derive(Debug, Clone, Copy)]
25pub struct ContextLimit {
26 pub max_tokens: usize,
28 pub reserved_response_tokens: usize,
30 pub chars_per_token: usize,
32}
33
34impl ContextLimit {
35 pub fn new(max_tokens: usize) -> Self {
37 Self {
38 max_tokens,
39 reserved_response_tokens: 0,
40 chars_per_token: 4,
41 }
42 }
43
44 pub fn for_model<M: crate::model::LanguageModel + ?Sized>(model: &M) -> Result<Self> {
56 let max_tokens = match model.context_size() {
57 Ok(tokens) => usize::try_from(tokens).map_err(|_| {
58 crate::error::Error::InternalError(format!(
59 "Model context size {tokens} does not fit in usize"
60 ))
61 })?,
62 Err(crate::error::Error::UnsupportedPlatform(_)) => DEFAULT_CONTEXT_TOKENS,
63 Err(err) => return Err(err),
64 };
65 Ok(Self {
66 max_tokens,
67 reserved_response_tokens: 512,
68 chars_per_token: 4,
69 })
70 }
71
72 pub fn default_on_device() -> Self {
77 Self {
78 max_tokens: DEFAULT_CONTEXT_TOKENS,
79 reserved_response_tokens: 512,
80 chars_per_token: 4,
81 }
82 }
83
84 pub fn with_reserved_response_tokens(mut self, tokens: usize) -> Self {
86 self.reserved_response_tokens = tokens;
87 self
88 }
89
90 pub fn with_chars_per_token(mut self, chars: usize) -> Self {
92 if chars > 0 {
93 self.chars_per_token = chars;
94 }
95 self
96 }
97}
98
99#[derive(Debug, Clone, Copy)]
101pub struct ContextUsage {
102 pub estimated_tokens: usize,
104 pub max_tokens: usize,
106 pub reserved_response_tokens: usize,
108 pub available_tokens: usize,
110 pub utilization: f32,
116 pub over_limit: bool,
118}
119
120pub struct CompactedSession {
122 pub session: Session,
124 pub summary: String,
126}
127
128#[derive(Debug, Clone)]
130pub struct CompactionConfig {
131 pub chunk_tokens: usize,
133 pub max_summary_tokens: usize,
139 pub instructions: String,
141 pub summary_options: GenerationOptions,
143 pub chars_per_token: usize,
145}
146
147impl Default for CompactionConfig {
148 fn default() -> Self {
149 Self {
150 chunk_tokens: 800,
151 max_summary_tokens: 400,
152 instructions: "Summarize the conversation for future context. Preserve user intent, key facts, decisions, and open questions. Keep the summary concise."
153 .to_string(),
154 summary_options: GenerationOptions::builder()
155 .temperature(0.2)
156 .max_response_tokens(256)
157 .build(),
158 chars_per_token: 4,
159 }
160 }
161}
162
163pub fn context_usage_from_transcript(
165 transcript_json: &str,
166 limit: &ContextLimit,
167) -> Result<ContextUsage> {
168 let transcript_text = transcript_to_text(transcript_json)?;
169 let estimated_tokens = estimate_tokens(&transcript_text, limit.chars_per_token);
170 let available_tokens = limit
171 .max_tokens
172 .saturating_sub(limit.reserved_response_tokens);
173 let utilization = if available_tokens > 0 {
174 estimated_tokens as f32 / available_tokens as f32
175 } else if estimated_tokens > 0 {
176 1.0
177 } else {
178 0.0
179 };
180 let over_limit = estimated_tokens > available_tokens;
181
182 Ok(ContextUsage {
183 estimated_tokens,
184 max_tokens: limit.max_tokens,
185 reserved_response_tokens: limit.reserved_response_tokens,
186 available_tokens,
187 utilization,
188 over_limit,
189 })
190}
191
192pub fn compact_transcript(
194 model: &SystemLanguageModel,
195 transcript_json: &str,
196 config: &CompactionConfig,
197) -> Result<String> {
198 let transcript_text = transcript_to_text(transcript_json)?;
199 if transcript_text.trim().is_empty() {
200 return Ok(String::new());
201 }
202
203 let chunks = chunk_text(
204 &transcript_text,
205 config.chunk_tokens,
206 config.chars_per_token,
207 );
208
209 let mut summary = String::new();
210
211 for (chunk_index, chunk) in chunks.into_iter().enumerate() {
212 let session = Session::with_instructions(model, &config.instructions)?;
213 let prompt = build_summary_prompt(
214 &summary,
215 &chunk,
216 config.max_summary_tokens,
217 config.chars_per_token,
218 );
219 let response = session.respond(&prompt, &config.summary_options)?;
220 let updated = response.into_content();
221 if updated.trim().is_empty() {
222 return Err(Error::GenerationError(format!(
223 "Summarizer returned an empty response for transcript chunk {}",
224 chunk_index + 1
225 )));
226 }
227 summary = updated;
228 }
229
230 Ok(summary)
231}
232
233pub fn compact_session_if_needed(
242 model: &SystemLanguageModel,
243 session: &Session,
244 limit: &ContextLimit,
245 config: &CompactionConfig,
246 base_instructions: Option<&str>,
247) -> Result<Option<CompactedSession>> {
248 let usage = session.context_usage(limit)?;
249 if !usage.over_limit {
250 return Ok(None);
251 }
252
253 let transcript_json = session.transcript_json()?;
254 let summary = compact_transcript(model, &transcript_json, config)?;
255 let compacted = session_from_summary(model, base_instructions, &summary)?;
256
257 let compacted_usage = compacted.context_usage(limit)?;
260 if compacted_usage.over_limit {
261 return Err(crate::error::Error::InvalidInput(format!(
262 "Compacted session still exceeds the context budget \
263 ({} estimated tokens > {} available); reduce the base \
264 instructions, max_summary_tokens, or summary response limit",
265 compacted_usage.estimated_tokens, compacted_usage.available_tokens
266 )));
267 }
268
269 Ok(Some(CompactedSession {
270 session: compacted,
271 summary,
272 }))
273}
274
275pub fn session_from_summary(
277 model: &SystemLanguageModel,
278 base_instructions: Option<&str>,
279 summary: &str,
280) -> Result<Session> {
281 match compacted_instructions(base_instructions, summary) {
282 Some(instructions) => Session::with_instructions(model, &instructions),
283 None => Session::new(model),
284 }
285}
286
287pub fn compacted_instructions(base_instructions: Option<&str>, summary: &str) -> Option<String> {
289 let base = base_instructions.map_or("", str::trim);
290 let summary = summary.trim();
291
292 match (base.is_empty(), summary.is_empty()) {
293 (true, true) => None,
294 (false, true) => Some(base.to_string()),
295 (true, false) => Some(format!("Conversation summary:\n{summary}")),
296 (false, false) => Some(format!("{base}\n\nConversation summary:\n{summary}")),
297 }
298}
299
300pub fn transcript_to_text(transcript_json: &str) -> Result<String> {
302 let value: Value = serde_json::from_str(transcript_json)?;
303 let mut lines = Vec::new();
304 collect_transcript_lines(&value, &mut lines);
305
306 if lines.is_empty() {
307 Ok(transcript_json.to_string())
308 } else {
309 Ok(lines.join("\n"))
310 }
311}
312
313pub fn estimate_tokens(text: &str, chars_per_token: usize) -> usize {
315 let denom = chars_per_token.max(1);
316 let chars = text.chars().count();
317 chars.div_ceil(denom)
318}
319
320fn build_summary_prompt(
321 current_summary: &str,
322 chunk: &str,
323 max_summary_tokens: usize,
324 chars_per_token: usize,
325) -> String {
326 if current_summary.trim().is_empty() {
327 format!(
328 "Summarize the following conversation transcript:\n\n{chunk}\n\nReturn a concise summary."
329 )
330 } else {
331 let summary_tokens = estimate_tokens(current_summary, chars_per_token);
333 let truncated_summary = if summary_tokens > max_summary_tokens {
334 let max_chars = max_summary_tokens.saturating_mul(chars_per_token.max(1));
336 let char_count = current_summary.chars().count();
337 if char_count > max_chars {
338 let skip = char_count - max_chars;
339 format!(
340 "..{}",
341 current_summary.chars().skip(skip).collect::<String>()
342 )
343 } else {
344 current_summary.to_string()
345 }
346 } else {
347 current_summary.to_string()
348 };
349
350 format!(
351 "Update the summary with new conversation content.\n\nCurrent summary:\n{truncated_summary}\n\nNew transcript chunk:\n{chunk}\n\nReturn the updated concise summary."
352 )
353 }
354}
355
356fn chunk_text(text: &str, chunk_tokens: usize, chars_per_token: usize) -> Vec<String> {
357 let max_chars = chunk_tokens.max(1).saturating_mul(chars_per_token.max(1));
358 let mut chunks = Vec::new();
359 let mut current = String::new();
360
361 for line in text.lines() {
362 for piece in split_line(line, max_chars) {
366 let piece_len = piece.chars().count() + 1;
367 if !current.is_empty() && current.chars().count() + piece_len > max_chars {
368 chunks.push(current.trim_end().to_string());
369 current.clear();
370 }
371 current.push_str(piece);
372 current.push('\n');
373 }
374 }
375
376 if !current.trim().is_empty() {
377 chunks.push(current.trim_end().to_string());
378 }
379
380 if chunks.is_empty() {
381 chunks.push(text.to_string());
382 }
383
384 chunks
385}
386
387fn split_line(line: &str, max_chars: usize) -> Vec<&str> {
389 let max_chars = max_chars.max(1);
390 let mut pieces = Vec::new();
391 let mut piece_start = 0;
392 let mut piece_chars = 0;
393
394 for (byte_index, _) in line.char_indices() {
395 if piece_chars == max_chars {
396 pieces.push(&line[piece_start..byte_index]);
397 piece_start = byte_index;
398 piece_chars = 0;
399 }
400 piece_chars += 1;
401 }
402
403 pieces.push(&line[piece_start..]);
404 pieces
405}
406
407fn collect_transcript_lines(value: &Value, out: &mut Vec<String>) {
408 match value {
409 Value::Array(items) => {
410 for item in items {
411 collect_transcript_lines(item, out);
412 }
413 }
414 Value::Object(map) => {
415 let mut processed_content = false;
417
418 if let Some(role) = map.get("role").and_then(Value::as_str) {
420 let content = map
421 .get("content")
422 .and_then(Value::as_str)
423 .or_else(|| map.get("text").and_then(Value::as_str));
424 if let Some(content) = content {
425 out.push(format!("{role}: {content}"));
426 processed_content = true;
427 }
428 }
429
430 for key in ["content", "text", "prompt", "response", "instructions"] {
432 if processed_content && matches!(key, "content" | "text") {
433 continue;
434 }
435 if let Some(text) = map.get(key).and_then(Value::as_str) {
436 out.push(text.to_string());
437 }
438 }
439
440 for (key, value) in map {
442 if matches!(
443 key.as_str(),
444 "role" | "content" | "text" | "prompt" | "response" | "instructions"
445 ) {
446 continue;
447 }
448 collect_transcript_lines(value, out);
449 }
450 }
451 _ => {}
452 }
453}
454
455#[cfg(test)]
456mod tests {
457 use crate::context::{
458 ContextLimit, chunk_text, compacted_instructions, context_usage_from_transcript,
459 estimate_tokens,
460 };
461
462 #[test]
463 fn test_estimate_tokens() {
464 let text = "abcd";
465 assert_eq!(estimate_tokens(text, 4), 1);
466 assert_eq!(estimate_tokens(text, 3), 2);
467 }
468
469 #[test]
470 fn context_usage_at_available_token_boundary_is_not_over_limit() {
471 let usage = context_usage_from_transcript(r#"[{"content":"abcd"}]"#, &ContextLimit::new(1))
472 .expect("context usage should be estimated");
473
474 assert!((usage.utilization - 1.0).abs() < f32::EPSILON);
475 assert!(!usage.over_limit);
476 }
477
478 #[test]
479 fn test_chunk_text() {
480 let text = "Line one\nLine two\nLine three";
481 let chunks = chunk_text(text, 2, 4);
482 assert!(!chunks.is_empty());
483 }
484
485 #[test]
486 fn test_chunk_text_splits_single_line_exceeding_budget() {
487 let long_line = "x".repeat(100);
488 let chunks = chunk_text(&long_line, 2, 4);
489 assert!(chunks.len() > 1);
490 assert!(chunks.iter().all(|chunk| chunk.chars().count() <= 8));
491 let total: usize = chunks.iter().map(|chunk| chunk.chars().count()).sum();
492 assert_eq!(total, 100);
493 }
494
495 #[test]
496 fn test_compacted_instructions() {
497 assert_eq!(compacted_instructions(None, ""), None);
498 assert_eq!(
499 compacted_instructions(Some("You are helpful."), ""),
500 Some("You are helpful.".to_string())
501 );
502 assert_eq!(
503 compacted_instructions(None, "Summary body"),
504 Some("Conversation summary:\nSummary body".to_string())
505 );
506 assert_eq!(
507 compacted_instructions(Some("You are helpful."), "Summary body"),
508 Some("You are helpful.\n\nConversation summary:\nSummary body".to_string())
509 );
510 }
511}