1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5use tiktoken_rs::{cl100k_base, o200k_base};
6use flate2::write::{ZlibEncoder, GzEncoder};
7use flate2::Compression;
8use std::io::Write as _;
9
10pub struct ContextModule {
11 memory_store: Arc<Mutex<HashMap<String, Value>>>,
12 context_usage: Arc<Mutex<ContextUsage>>,
13}
14
15#[derive(Default)]
16struct ContextUsage {
17 total_tokens: usize,
18 used_tokens: usize,
19}
20
21impl ContextModule {
22 pub fn new() -> Self {
23 Self {
24 memory_store: Arc::new(Mutex::new(HashMap::new())),
25 context_usage: Arc::new(Mutex::new(ContextUsage::default())),
26 }
27 }
28
29 pub fn get_tools(&self) -> Vec<Value> {
30 vec![
31 json!({
32 "name": "ctx_context",
33 "description": "Get token usage statistics (total, left, used)",
34 "inputSchema": {
35 "type": "object",
36 "properties": {
37 "set_total": {
38 "type": "number",
39 "description": "Set the total context window size"
40 },
41 "add_used": {
42 "type": "number",
43 "description": "Add to used token count"
44 }
45 }
46 }
47 }),
48 json!({
49 "name": "ctx_compact",
50 "description": "Compress text using algorithms to reduce size",
51 "inputSchema": {
52 "type": "object",
53 "properties": {
54 "text": {
55 "type": "string",
56 "description": "Text to compress"
57 },
58 "algorithm": {
59 "type": "string",
60 "enum": ["zlib", "gzip"],
61 "description": "Compression algorithm (default: zlib)"
62 }
63 },
64 "required": ["text"]
65 }
66 }),
67 json!({
68 "name": "ctx_remove",
69 "description": "Clear context and reset usage",
70 "inputSchema": {
71 "type": "object",
72 "properties": {
73 "reset_memory": {
74 "type": "boolean",
75 "description": "Also clear memory store (default: false)"
76 }
77 }
78 }
79 }),
80 json!({
81 "name": "ctx_token_count",
82 "description": "Count tokens in text for various LLM providers",
83 "inputSchema": {
84 "type": "object",
85 "properties": {
86 "text": {
87 "type": "string",
88 "description": "Text to count tokens for"
89 },
90 "model": {
91 "type": "string",
92 "enum": ["gpt-4", "gpt-3.5-turbo", "claude-3", "claude-2", "o200k"],
93 "description": "Model to use for tokenization (default: gpt-4)"
94 }
95 },
96 "required": ["text"]
97 }
98 }),
99 json!({
100 "name": "ctx_memory_store",
101 "description": "Store data in memory (process lifetime)",
102 "inputSchema": {
103 "type": "object",
104 "properties": {
105 "key": {
106 "type": "string",
107 "description": "Key to store data under"
108 },
109 "value": {
110 "description": "Value to store (any JSON type)"
111 }
112 },
113 "required": ["key", "value"]
114 }
115 }),
116 json!({
117 "name": "ctx_memory_recall",
118 "description": "Retrieve stored data from memory",
119 "inputSchema": {
120 "type": "object",
121 "properties": {
122 "key": {
123 "type": "string",
124 "description": "Key to retrieve (omit to list all keys)"
125 }
126 }
127 }
128 }),
129 json!({
130 "name": "ctx_estimate_cost",
131 "description": "Estimate API costs for LLM providers",
132 "inputSchema": {
133 "type": "object",
134 "properties": {
135 "provider": {
136 "type": "string",
137 "enum": ["anthropic", "openai", "ollama", "glm"],
138 "description": "LLM provider"
139 },
140 "model": {
141 "type": "string",
142 "description": "Model name"
143 },
144 "input_tokens": {
145 "type": "number",
146 "description": "Number of input tokens"
147 },
148 "output_tokens": {
149 "type": "number",
150 "description": "Number of output tokens"
151 }
152 },
153 "required": ["provider", "model", "input_tokens", "output_tokens"]
154 }
155 }),
156 ]
157 }
158
159 pub async fn context(&self, args: Value) -> Result<Value> {
160 let mut usage = self.context_usage.lock().unwrap();
161
162 if let Some(total) = args["set_total"].as_u64() {
163 usage.total_tokens = total as usize;
164 }
165
166 if let Some(add_used) = args["add_used"].as_u64() {
167 usage.used_tokens += add_used as usize;
168 }
169
170 let left = usage.total_tokens.saturating_sub(usage.used_tokens);
171 let usage_percent = if usage.total_tokens > 0 {
172 (usage.used_tokens as f64 / usage.total_tokens as f64) * 100.0
173 } else {
174 0.0
175 };
176
177 Ok(json!({
178 "total": usage.total_tokens,
179 "used": usage.used_tokens,
180 "left": left,
181 "usage_percent": usage_percent
182 }))
183 }
184
185 pub async fn compact_context(&self, args: Value) -> Result<Value> {
186 let text = args["text"].as_str().context("Missing 'text' parameter")?;
187 let algorithm = args["algorithm"].as_str().unwrap_or("zlib");
188
189 let original_size = text.len();
190
191 let compressed = match algorithm {
192 "zlib" => {
193 let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
194 encoder.write_all(text.as_bytes())?;
195 encoder.finish()?
196 }
197 "gzip" => {
198 let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
199 encoder.write_all(text.as_bytes())?;
200 encoder.finish()?
201 }
202 _ => return Err(anyhow::anyhow!("Unknown compression algorithm: {}", algorithm)),
203 };
204
205 let compressed_size = compressed.len();
206 let compression_ratio = (compressed_size as f64 / original_size as f64) * 100.0;
207
208 use base64::{Engine, engine::general_purpose};
210 let encoded = general_purpose::STANDARD.encode(&compressed);
211
212 Ok(json!({
213 "original_size": original_size,
214 "compressed_size": compressed_size,
215 "compression_ratio_percent": compression_ratio,
216 "algorithm": algorithm,
217 "compressed_data": encoded,
218 "savings_bytes": original_size - compressed_size
219 }))
220 }
221
222 pub async fn remove_context(&self, args: Value) -> Result<Value> {
223 let reset_memory = args["reset_memory"].as_bool().unwrap_or(false);
224
225 let mut usage = self.context_usage.lock().unwrap();
226 usage.used_tokens = 0;
227
228 let memory_cleared = if reset_memory {
229 let mut store = self.memory_store.lock().unwrap();
230 let count = store.len();
231 store.clear();
232 count
233 } else {
234 0
235 };
236
237 Ok(json!({
238 "success": true,
239 "context_reset": true,
240 "memory_cleared": reset_memory,
241 "memory_items_cleared": memory_cleared
242 }))
243 }
244
245 pub async fn token_count(&self, args: Value) -> Result<Value> {
246 let text = args["text"].as_str().context("Missing 'text' parameter")?;
247 let model = args["model"].as_str().unwrap_or("gpt-4");
248
249 let token_count = match model {
250 "gpt-4" | "gpt-3.5-turbo" | "claude-3" | "claude-2" => {
251 let bpe = cl100k_base()?;
252 bpe.encode_with_special_tokens(text).len()
253 }
254 "o200k" => {
255 let bpe = o200k_base()?;
256 bpe.encode_with_special_tokens(text).len()
257 }
258 _ => {
259 let words = text.split_whitespace().count();
261 (words as f64 * 1.3) as usize }
263 };
264
265 let char_count = text.chars().count();
266 let byte_count = text.len();
267 let word_count = text.split_whitespace().count();
268
269 Ok(json!({
270 "token_count": token_count,
271 "char_count": char_count,
272 "byte_count": byte_count,
273 "word_count": word_count,
274 "model": model,
275 "tokens_per_word": if word_count > 0 { token_count as f64 / word_count as f64 } else { 0.0 }
276 }))
277 }
278
279 pub async fn memory_store(&self, args: Value) -> Result<Value> {
280 let key = args["key"].as_str().context("Missing 'key' parameter")?;
281 let value = args.get("value").context("Missing 'value' parameter")?;
282
283 let mut store = self.memory_store.lock().unwrap();
284 store.insert(key.to_string(), value.clone());
285
286 Ok(json!({
287 "success": true,
288 "key": key,
289 "stored": true,
290 "total_keys": store.len()
291 }))
292 }
293
294 pub async fn memory_recall(&self, args: Value) -> Result<Value> {
295 let store = self.memory_store.lock().unwrap();
296
297 if let Some(key) = args["key"].as_str() {
298 if let Some(value) = store.get(key) {
299 Ok(json!({
300 "key": key,
301 "value": value,
302 "found": true
303 }))
304 } else {
305 Ok(json!({
306 "key": key,
307 "found": false,
308 "error": "Key not found"
309 }))
310 }
311 } else {
312 let keys: Vec<String> = store.keys().cloned().collect();
314
315 Ok(json!({
316 "keys": keys,
317 "count": keys.len()
318 }))
319 }
320 }
321
322 pub async fn estimate_cost(&self, args: Value) -> Result<Value> {
323 let provider = args["provider"].as_str().context("Missing 'provider' parameter")?;
324 let model = args["model"].as_str().context("Missing 'model' parameter")?;
325 let input_tokens = args["input_tokens"].as_u64().context("Missing 'input_tokens' parameter")? as usize;
326 let output_tokens = args["output_tokens"].as_u64().context("Missing 'output_tokens' parameter")? as usize;
327
328 let (input_price_per_1m, output_price_per_1m) = match (provider, model) {
329 ("anthropic", "claude-opus-4") | ("anthropic", "claude-opus-4-6") => (15.0, 75.0),
331 ("anthropic", "claude-sonnet-4") | ("anthropic", "claude-sonnet-4-6") => (3.0, 15.0),
332 ("anthropic", "claude-haiku-4-5") | ("anthropic", "claude-haiku-4") => (0.80, 4.0),
333 ("anthropic", "claude-3-opus") => (15.0, 75.0),
334 ("anthropic", "claude-3-sonnet") | ("anthropic", "claude-3.5-sonnet") => (3.0, 15.0),
335 ("anthropic", "claude-3-haiku") | ("anthropic", "claude-3.5-haiku") => (0.25, 1.25),
336
337 ("openai", "gpt-4o") => (2.50, 10.0),
339 ("openai", "gpt-4o-mini") => (0.15, 0.60),
340 ("openai", "gpt-4-turbo") => (10.0, 30.0),
341 ("openai", "gpt-4") => (30.0, 60.0),
342 ("openai", "gpt-3.5-turbo") => (0.50, 1.50),
343 ("openai", "o1") => (15.0, 60.0),
344 ("openai", "o1-mini") => (3.0, 12.0),
345 ("openai", "o3-mini") => (1.10, 4.40),
346
347 ("ollama", _) => (0.0, 0.0),
349
350 ("glm", "glm-4") => (1.0, 3.0),
352
353 _ => return Err(anyhow::anyhow!("Unknown provider/model combination: {}/{}", provider, model)),
354 };
355
356 let input_cost = (input_tokens as f64 / 1_000_000.0) * input_price_per_1m;
357 let output_cost = (output_tokens as f64 / 1_000_000.0) * output_price_per_1m;
358 let total_cost = input_cost + output_cost;
359
360 Ok(json!({
361 "provider": provider,
362 "model": model,
363 "input_tokens": input_tokens,
364 "output_tokens": output_tokens,
365 "total_tokens": input_tokens + output_tokens,
366 "input_cost_usd": input_cost,
367 "output_cost_usd": output_cost,
368 "total_cost_usd": total_cost,
369 "pricing": {
370 "input_per_1m_tokens": input_price_per_1m,
371 "output_per_1m_tokens": output_price_per_1m
372 }
373 }))
374 }
375}