lean_ctx_ext/core/
llm_feedback.rs1use std::collections::{BTreeMap, VecDeque};
3use std::fs::{File, OpenOptions};
4use std::io::{BufRead, BufReader, Write};
5use std::path::{Path, PathBuf};
6
7use serde::{Deserialize, Serialize};
8
9const LLM_FEEDBACK_FILE: &str = "llm_feedback.jsonl";
10const LLM_FEEDBACK_MAX_EVENTS: usize = 5_000;
11const LLM_FEEDBACK_MAX_BYTES: u64 = 8 * 1024 * 1024;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct LlmFeedbackEvent {
15 pub agent_id: String,
16 pub intent: Option<String>,
17 pub model: Option<String>,
18 pub llm_input_tokens: u64,
19 pub llm_output_tokens: u64,
20 pub latency_ms: Option<u64>,
21 pub note: Option<String>,
22 pub ctx_read_last_mode: Option<String>,
23 pub ctx_read_modes: Option<BTreeMap<String, u64>>,
24 pub timestamp: String,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize, Default)]
28pub struct LlmFeedbackSummary {
29 pub total_events: usize,
30 pub avg_output_ratio: f64,
31 pub avg_latency_ms: Option<f64>,
32 pub max_output_tokens: u64,
33 pub max_output_ratio: f64,
34 pub by_model: BTreeMap<String, ModelSummary>,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize, Default)]
38pub struct ModelSummary {
39 pub events: usize,
40 pub avg_output_ratio: f64,
41 pub avg_latency_ms: Option<f64>,
42 pub max_output_tokens: u64,
43}
44
45pub struct LlmFeedbackStore;
46
47impl LlmFeedbackStore {
48 pub fn record(mut event: LlmFeedbackEvent) -> Result<(), String> {
49 if event.agent_id.trim().is_empty() {
50 return Err("agent_id is required".to_string());
51 }
52 if event.llm_input_tokens == 0 {
53 return Err("llm_input_tokens must be > 0".to_string());
54 }
55 if event.llm_output_tokens == 0 {
56 return Err("llm_output_tokens must be > 0".to_string());
57 }
58 if let Some(n) = event.note.as_ref()
59 && n.len() > 2000
60 {
61 event.note = Some(n.chars().take(2000).collect());
62 }
63
64 let path = feedback_path();
65 ensure_parent_dir(&path)?;
66
67 let mut f = OpenOptions::new()
68 .create(true)
69 .append(true)
70 .open(&path)
71 .map_err(|e| format!("open {}: {e}", path.display()))?;
72
73 let line = serde_json::to_string(&event).map_err(|e| format!("serialize: {e}"))?;
74 f.write_all(line.as_bytes())
75 .and_then(|()| f.write_all(b"\n"))
76 .map_err(|e| format!("write {}: {e}", path.display()))?;
77
78 maybe_compact(&path)?;
79 Ok(())
80 }
81
82 pub fn status() -> LlmFeedbackStatus {
83 let path = feedback_path();
84 let bytes = std::fs::metadata(&path).map_or(0, |m| m.len());
85 LlmFeedbackStatus {
86 path,
87 bytes,
88 max_events: LLM_FEEDBACK_MAX_EVENTS,
89 max_bytes: LLM_FEEDBACK_MAX_BYTES,
90 }
91 }
92
93 pub fn reset() -> Result<(), String> {
94 let path = feedback_path();
95 if path.exists() {
96 std::fs::remove_file(&path).map_err(|e| format!("remove {}: {e}", path.display()))?;
97 }
98 Ok(())
99 }
100
101 pub fn recent(limit: usize) -> Vec<LlmFeedbackEvent> {
102 let path = feedback_path();
103 let mut out: VecDeque<LlmFeedbackEvent> = VecDeque::with_capacity(limit.max(1));
104 let Ok(f) = File::open(&path) else {
105 return Vec::new();
106 };
107 let reader = BufReader::new(f);
108 for line in reader.lines().map_while(Result::ok) {
109 if line.trim().is_empty() {
110 continue;
111 }
112 if let Ok(ev) = serde_json::from_str::<LlmFeedbackEvent>(&line) {
113 out.push_back(ev);
114 while out.len() > limit {
115 out.pop_front();
116 }
117 }
118 }
119 out.into_iter().collect()
120 }
121
122 pub fn summarize(limit: usize) -> LlmFeedbackSummary {
123 let events = Self::recent(limit);
124 summarize_events(&events)
125 }
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct LlmFeedbackStatus {
130 pub path: PathBuf,
131 pub bytes: u64,
132 pub max_events: usize,
133 pub max_bytes: u64,
134}
135
136fn summarize_events(events: &[LlmFeedbackEvent]) -> LlmFeedbackSummary {
137 if events.is_empty() {
138 return LlmFeedbackSummary::default();
139 }
140
141 let mut by_model: BTreeMap<String, Vec<&LlmFeedbackEvent>> = BTreeMap::new();
142 let mut ratio_sum = 0.0;
143 let mut ratio_max: f64 = 0.0;
144 let mut max_out = 0u64;
145 let mut latency_sum = 0u64;
146 let mut latency_n = 0u64;
147
148 for ev in events {
149 let ratio = ev.llm_output_tokens as f64 / ev.llm_input_tokens.max(1) as f64;
150 ratio_sum += ratio;
151 ratio_max = ratio_max.max(ratio);
152 max_out = max_out.max(ev.llm_output_tokens);
153 if let Some(ms) = ev.latency_ms {
154 latency_sum = latency_sum.saturating_add(ms);
155 latency_n += 1;
156 }
157 by_model
158 .entry(ev.model.clone().unwrap_or_else(|| "unknown".to_string()))
159 .or_default()
160 .push(ev);
161 }
162
163 let avg_latency_ms = if latency_n > 0 {
164 Some(latency_sum as f64 / latency_n as f64)
165 } else {
166 None
167 };
168
169 let mut model_summaries = BTreeMap::new();
170 for (model, evs) in by_model {
171 let mut r_sum = 0.0;
172 let mut max_out = 0u64;
173 let mut l_sum = 0u64;
174 let mut l_n = 0u64;
175 let n = evs.len();
176 for ev in &evs {
177 r_sum += ev.llm_output_tokens as f64 / ev.llm_input_tokens.max(1) as f64;
178 max_out = max_out.max(ev.llm_output_tokens);
179 if let Some(ms) = ev.latency_ms {
180 l_sum = l_sum.saturating_add(ms);
181 l_n += 1;
182 }
183 }
184 model_summaries.insert(
185 model,
186 ModelSummary {
187 events: n,
188 avg_output_ratio: r_sum / n.max(1) as f64,
189 avg_latency_ms: if l_n > 0 {
190 Some(l_sum as f64 / l_n as f64)
191 } else {
192 None
193 },
194 max_output_tokens: max_out,
195 },
196 );
197 }
198
199 LlmFeedbackSummary {
200 total_events: events.len(),
201 avg_output_ratio: ratio_sum / events.len().max(1) as f64,
202 avg_latency_ms,
203 max_output_tokens: max_out,
204 max_output_ratio: ratio_max,
205 by_model: model_summaries,
206 }
207}
208
209fn feedback_path() -> PathBuf {
210 crate::core::data_dir::lean_ctx_data_dir()
211 .unwrap_or_else(|_| PathBuf::from("."))
212 .join("feedback")
213 .join(LLM_FEEDBACK_FILE)
214}
215
216fn ensure_parent_dir(path: &Path) -> Result<(), String> {
217 let Some(parent) = path.parent() else {
218 return Ok(());
219 };
220 std::fs::create_dir_all(parent).map_err(|e| format!("create_dir_all {}: {e}", parent.display()))
221}
222
223fn maybe_compact(path: &Path) -> Result<(), String> {
224 let Ok(meta) = std::fs::metadata(path) else {
225 return Ok(());
226 };
227 if meta.len() <= LLM_FEEDBACK_MAX_BYTES {
228 return Ok(());
229 }
230
231 let f = File::open(path).map_err(|e| format!("open {}: {e}", path.display()))?;
232 let reader = BufReader::new(f);
233
234 let mut keep: VecDeque<String> = VecDeque::with_capacity(LLM_FEEDBACK_MAX_EVENTS);
235 for line in reader.lines().map_while(Result::ok) {
236 if line.trim().is_empty() {
237 continue;
238 }
239 keep.push_back(line);
240 while keep.len() > LLM_FEEDBACK_MAX_EVENTS {
241 keep.pop_front();
242 }
243 }
244
245 let dir = path.parent().unwrap_or_else(|| Path::new("."));
246 let tmp = dir.join(".llm_feedback.compact.tmp");
247 {
248 let mut out = File::create(&tmp).map_err(|e| format!("create {}: {e}", tmp.display()))?;
249 for line in keep {
250 out.write_all(line.as_bytes())
251 .and_then(|()| out.write_all(b"\n"))
252 .map_err(|e| format!("write {}: {e}", tmp.display()))?;
253 }
254 out.flush()
255 .map_err(|e| format!("flush {}: {e}", tmp.display()))?;
256 }
257
258 std::fs::rename(&tmp, path)
259 .map_err(|e| format!("rename {} -> {}: {e}", tmp.display(), path.display()))?;
260 Ok(())
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 #[test]
268 fn summarize_empty_is_default() {
269 let s = summarize_events(&[]);
270 assert_eq!(s.total_events, 0);
271 assert!(s.by_model.is_empty());
272 }
273}