Skip to main content

fm_rs/
context.rs

1//! Context window tracking and compaction helpers.
2
3use serde_json::Value;
4
5use crate::error::{Error, Result};
6use crate::model::SystemLanguageModel;
7use crate::options::GenerationOptions;
8use crate::session::Session;
9
10/// Conservative fallback context window size for Apple's on-device models.
11///
12/// Since the 26.4 SDK, the authoritative value is
13/// `SystemLanguageModel::context_size()`; pre-27 runtimes report the
14/// back-deployed default of 4096 tokens, while macOS/iOS 27 hardware can
15/// report larger windows. Prefer [`ContextLimit::for_model`], which queries
16/// the model and only falls back to this constant when the build SDK cannot
17/// report a size.
18///
19/// For production use, monitor [`ContextUsage::utilization`] and implement
20/// compaction strategies when approaching the limit.
21pub const DEFAULT_CONTEXT_TOKENS: usize = 4096;
22
23/// Configuration for estimating context usage.
24#[derive(Debug, Clone, Copy)]
25pub struct ContextLimit {
26    /// Maximum tokens available in the session context window.
27    pub max_tokens: usize,
28    /// Tokens reserved for the model's next response.
29    pub reserved_response_tokens: usize,
30    /// Estimated characters per token (English ~3-4, CJK ~1).
31    pub chars_per_token: usize,
32}
33
34impl ContextLimit {
35    /// Creates a new context limit with a max token budget.
36    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    /// Creates a configuration from the model-reported context size.
45    ///
46    /// Falls back to [`DEFAULT_CONTEXT_TOKENS`] only when the build SDK
47    /// cannot report a size ([`crate::Error::UnsupportedPlatform`]). Other
48    /// failures — such as Private Cloud Compute network or quota errors —
49    /// are propagated rather than silently mapped to a fake limit.
50    ///
51    /// # Errors
52    ///
53    /// Returns any non-platform error from `context_size()`, or an internal
54    /// error if the reported size does not fit in `usize`.
55    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    /// Creates a default configuration for on-device models.
73    ///
74    /// This uses the conservative [`DEFAULT_CONTEXT_TOKENS`] fallback;
75    /// prefer [`ContextLimit::for_model`] when a model handle is available.
76    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    /// Sets the reserved response tokens.
85    pub fn with_reserved_response_tokens(mut self, tokens: usize) -> Self {
86        self.reserved_response_tokens = tokens;
87        self
88    }
89
90    /// Sets the character-per-token estimate.
91    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/// Estimated context usage for a session.
100#[derive(Debug, Clone, Copy)]
101pub struct ContextUsage {
102    /// Estimated number of tokens consumed by the transcript.
103    pub estimated_tokens: usize,
104    /// Maximum tokens configured for the session.
105    pub max_tokens: usize,
106    /// Tokens reserved for the next response.
107    pub reserved_response_tokens: usize,
108    /// Estimated tokens available for prompts before hitting the limit.
109    pub available_tokens: usize,
110    /// Estimated utilization of the available budget (0.0 - 1.0+).
111    ///
112    /// Measured against `available_tokens` (the window minus the reserved
113    /// response budget). `over_limit` uses the exact integer counts and is
114    /// false at the boundary where utilization is 1.0.
115    pub utilization: f32,
116    /// Whether the estimate exceeds the available budget.
117    pub over_limit: bool,
118}
119
120/// Result of compacting a session into a new summarized session.
121pub struct CompactedSession {
122    /// Newly created session seeded with compacted summary instructions.
123    pub session: Session,
124    /// Compacted summary generated from the prior transcript.
125    pub summary: String,
126}
127
128/// Configuration for transcript compaction.
129#[derive(Debug, Clone)]
130pub struct CompactionConfig {
131    /// Estimated tokens per chunk sent to the summarizer.
132    pub chunk_tokens: usize,
133    /// Maximum tokens allowed for the rolling summary.
134    ///
135    /// As chunks are processed, the running summary can grow unbounded.
136    /// This limit ensures the summary is truncated to avoid exceeding
137    /// the model's context window during multi-chunk compaction.
138    pub max_summary_tokens: usize,
139    /// Instructions for the summarizer session.
140    pub instructions: String,
141    /// Options used for summary generation.
142    pub summary_options: GenerationOptions,
143    /// Estimated characters per token.
144    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
163/// Estimates token usage for the session transcript JSON.
164pub 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
192/// Compacts a transcript into a summary using the on-device model.
193pub 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
233/// Compacts a session transcript and creates a new summarized session when needed.
234///
235/// This helper implements a common context-window rollover pattern:
236/// 1. Estimate usage from the current session transcript.
237/// 2. If still within budget, return `Ok(None)`.
238/// 3. If over budget, summarize the transcript and return a fresh `Session`.
239///
240/// `base_instructions` are prepended to the generated summary in the compacted session.
241pub 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    // Report an ineffective compaction rather than letting a caller's
258    // compact-until-under-limit loop spin forever.
259    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
275/// Creates a new session from optional base instructions and a conversation summary.
276pub 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
287/// Builds instructions text for a compacted session.
288pub 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
300/// Extracts readable text from transcript JSON.
301pub 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
313/// Estimates tokens based on a characters-per-token heuristic.
314pub 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        // Truncate summary if it exceeds the token limit to prevent unbounded growth
332        let summary_tokens = estimate_tokens(current_summary, chars_per_token);
333        let truncated_summary = if summary_tokens > max_summary_tokens {
334            // Keep the end of the summary to preserve recent context
335            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        // A single line can exceed the chunk budget (transcript_to_text emits
363        // one line per message); split it so no chunk overflows the
364        // summarizer's context window.
365        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
387/// Splits a line into pieces of at most `max_chars` characters, in one pass.
388fn 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            // Track which keys we've already processed to avoid double-counting
416            let mut processed_content = false;
417
418            // If this is a message with role+content, add as "{role}: {content}"
419            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            // Add standalone text fields, skipping content/text if already included above
431            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            // Recurse into other fields
441            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}