Skip to main content

braid_model/
context.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3
4/// Rough token estimate: 1 token ≈ 4 bytes of UTF-8 text.
5pub const fn estimate_tokens(text: &str) -> usize {
6    text.len() / 4
7}
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct ContextChunk {
11    pub source: String,
12    pub label: String,
13    pub content: String,
14    pub captured_at: DateTime<Utc>,
15    pub token_estimate: usize,
16}
17
18impl ContextChunk {
19    pub fn new(source: &'static str, label: impl Into<String>, content: impl Into<String>) -> Self {
20        let content = content.into();
21        let token_estimate = estimate_tokens(&content);
22        Self {
23            source: source.into(),
24            label: label.into(),
25            content,
26            captured_at: chrono::Utc::now(),
27            token_estimate,
28        }
29    }
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct ContextSummary {
34    pub content: String,
35    pub summarized_at: DateTime<Utc>,
36    pub source_chunk_count: usize,
37    pub token_estimate: usize,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct ContextSnapshot {
42    pub chunks: Vec<ContextChunk>,
43    pub summary: Option<ContextSummary>,
44    pub assembled_at: DateTime<Utc>,
45    pub token_estimate: usize,
46    pub dropped_chunks: usize,
47}
48
49impl ContextSnapshot {
50    pub fn render(&self) -> String {
51        let mut parts = Vec::new();
52        if let Some(summary) = &self.summary {
53            parts.push(format!("## Context Summary\n{}", summary.content));
54        }
55        for chunk in &self.chunks {
56            parts.push(format!(
57                "## {}: {}\n{}",
58                chunk.source, chunk.label, chunk.content
59            ));
60        }
61        parts.join("\n\n")
62    }
63
64    pub fn total_tokens(&self) -> usize {
65        let summary_tokens = self.summary.as_ref().map_or(0, |s| s.token_estimate);
66        let chunk_tokens: usize = self.chunks.iter().map(|c| c.token_estimate).sum();
67        summary_tokens + chunk_tokens
68    }
69}