1use super::event_store::EventStore;
8use super::tracer_events::*;
9use crate::llm::models::ResponseEvidence;
10use std::collections::HashMap;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::Arc;
13use std::time::{SystemTime, UNIX_EPOCH};
14
15pub struct TracerSystem {
21 event_store: Arc<EventStore>,
22 enabled: Arc<AtomicBool>,
23}
24
25impl TracerSystem {
26 pub fn new(event_store: Option<Arc<EventStore>>, enabled: bool) -> Self {
33 Self {
34 event_store: event_store.unwrap_or_else(|| Arc::new(EventStore::default())),
35 enabled: Arc::new(AtomicBool::new(enabled)),
36 }
37 }
38
39 pub fn is_enabled(&self) -> bool {
41 self.enabled.load(Ordering::SeqCst)
42 }
43
44 pub fn enable(&self) {
46 self.enabled.store(true, Ordering::SeqCst);
47 }
48
49 pub fn disable(&self) {
51 self.enabled.store(false, Ordering::SeqCst);
52 }
53
54 pub fn record_event(&self, event: Box<dyn TracerEvent>) {
60 if !self.is_enabled() {
61 return;
62 }
63 self.event_store.store(event);
64 }
65
66 pub fn record_llm_call(
77 &self,
78 model: impl Into<String>,
79 messages: Vec<HashMap<String, serde_json::Value>>,
80 temperature: Option<f64>,
81 tools: Option<Vec<HashMap<String, serde_json::Value>>>,
82 source: impl Into<String>,
83 correlation_id: impl Into<String>,
84 ) {
85 if !self.is_enabled() {
86 return;
87 }
88
89 let event = Box::new(LlmCallTracerEvent {
90 timestamp: current_timestamp(),
91 correlation_id: correlation_id.into(),
92 source: source.into(),
93 model: model.into(),
94 messages,
95 temperature,
96 tools,
97 });
98
99 self.event_store.store(event);
100 }
101
102 pub fn record_llm_response(
117 &self,
118 model: impl Into<String>,
119 content: impl Into<String>,
120 tool_calls: Option<Vec<HashMap<String, serde_json::Value>>>,
121 call_duration_ms: Option<f64>,
122 source: impl Into<String>,
123 correlation_id: impl Into<String>,
124 ) {
125 self.record_llm_response_with_evidence(
126 model,
127 content,
128 tool_calls,
129 call_duration_ms,
130 ResponseEvidence::default(),
131 source,
132 correlation_id,
133 );
134 }
135
136 #[allow(clippy::too_many_arguments)]
148 pub fn record_llm_response_with_evidence(
149 &self,
150 model: impl Into<String>,
151 content: impl Into<String>,
152 tool_calls: Option<Vec<HashMap<String, serde_json::Value>>>,
153 call_duration_ms: Option<f64>,
154 evidence: ResponseEvidence,
155 source: impl Into<String>,
156 correlation_id: impl Into<String>,
157 ) {
158 if !self.is_enabled() {
159 return;
160 }
161
162 let event = Box::new(LlmResponseTracerEvent {
163 timestamp: current_timestamp(),
164 correlation_id: correlation_id.into(),
165 source: source.into(),
166 model: model.into(),
167 content: content.into(),
168 tool_calls,
169 call_duration_ms,
170 evidence,
171 });
172
173 self.event_store.store(event);
174 }
175
176 #[allow(clippy::too_many_arguments)]
188 pub fn record_tool_call(
189 &self,
190 tool_name: impl Into<String>,
191 arguments: HashMap<String, serde_json::Value>,
192 result: serde_json::Value,
193 caller: Option<String>,
194 call_duration_ms: Option<f64>,
195 source: impl Into<String>,
196 correlation_id: impl Into<String>,
197 ) {
198 if !self.is_enabled() {
199 return;
200 }
201
202 let event = Box::new(ToolCallTracerEvent {
203 timestamp: current_timestamp(),
204 correlation_id: correlation_id.into(),
205 source: source.into(),
206 tool_name: tool_name.into(),
207 arguments,
208 result,
209 caller,
210 call_duration_ms,
211 });
212
213 self.event_store.store(event);
214 }
215
216 #[allow(clippy::too_many_arguments)]
218 pub fn record_tool_batch(
219 &self,
220 batch_id: impl Into<String>,
221 tool_names: Vec<String>,
222 success_count: usize,
223 failure_count: usize,
224 call_duration_ms: f64,
225 caller: Option<String>,
226 source: impl Into<String>,
227 correlation_id: impl Into<String>,
228 ) {
229 if !self.is_enabled() {
230 return;
231 }
232
233 let event = Box::new(ToolBatchTracerEvent {
234 timestamp: current_timestamp(),
235 correlation_id: correlation_id.into(),
236 source: source.into(),
237 batch_id: batch_id.into(),
238 tool_names,
239 success_count,
240 failure_count,
241 call_duration_ms,
242 caller,
243 });
244
245 self.event_store.store(event);
246 }
247
248 pub fn record_agent_interaction(
259 &self,
260 from_agent: impl Into<String>,
261 to_agent: impl Into<String>,
262 event_type: impl Into<String>,
263 event_id: Option<String>,
264 source: impl Into<String>,
265 correlation_id: impl Into<String>,
266 ) {
267 if !self.is_enabled() {
268 return;
269 }
270
271 let event = Box::new(AgentInteractionTracerEvent {
272 timestamp: current_timestamp(),
273 correlation_id: correlation_id.into(),
274 source: source.into(),
275 from_agent: from_agent.into(),
276 to_agent: to_agent.into(),
277 event_type: event_type.into(),
278 event_id,
279 });
280
281 self.event_store.store(event);
282 }
283
284 pub fn get_event_summaries(
296 &self,
297 start_time: Option<f64>,
298 end_time: Option<f64>,
299 filter_func: Option<&dyn super::EventFilterFn>,
300 ) -> Vec<String> {
301 self.event_store.get_event_summaries(start_time, end_time, filter_func)
302 }
303
304 pub fn get_last_n_summaries(
315 &self,
316 n: usize,
317 filter_func: Option<&dyn super::EventFilterFn>,
318 ) -> Vec<String> {
319 self.event_store.get_last_n_summaries(n, filter_func)
320 }
321
322 pub fn count_events(
334 &self,
335 start_time: Option<f64>,
336 end_time: Option<f64>,
337 filter_func: Option<&dyn super::EventFilterFn>,
338 ) -> usize {
339 self.event_store.count_events(start_time, end_time, filter_func)
340 }
341
342 pub fn clear(&self) {
344 self.event_store.clear();
345 }
346
347 pub fn len(&self) -> usize {
349 self.event_store.len()
350 }
351
352 pub fn is_empty(&self) -> bool {
354 self.event_store.is_empty()
355 }
356}
357
358impl Default for TracerSystem {
359 fn default() -> Self {
360 Self::new(None, true)
361 }
362}
363
364fn current_timestamp() -> f64 {
366 SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs_f64()
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn test_new_tracer_system() {
375 let tracer = TracerSystem::default();
376 assert!(tracer.is_enabled());
377 assert_eq!(tracer.len(), 0);
378 }
379
380 #[test]
381 fn test_enable_disable() {
382 let tracer = TracerSystem::default();
383 assert!(tracer.is_enabled());
384
385 tracer.disable();
386 assert!(!tracer.is_enabled());
387
388 tracer.enable();
389 assert!(tracer.is_enabled());
390 }
391
392 #[test]
393 fn test_record_llm_call() {
394 let tracer = TracerSystem::default();
395
396 tracer.record_llm_call("llama3.2", vec![], Some(0.7), None, "test", "corr-123");
397
398 assert_eq!(tracer.len(), 1);
399 }
400
401 #[test]
402 fn test_record_llm_response() {
403 let tracer = TracerSystem::default();
404
405 tracer.record_llm_response(
406 "llama3.2",
407 "Hello, world!",
408 None,
409 Some(150.5),
410 "test",
411 "corr-456",
412 );
413
414 assert_eq!(tracer.len(), 1);
415 }
416
417 #[test]
418 fn record_llm_response_with_evidence_keeps_evidence_unchanged() {
419 use crate::tracer::testing::{capturing_tracer, responses};
420
421 let (tracer, captured) = capturing_tracer();
422 let evidence = ResponseEvidence {
423 usage: Some(serde_json::json!({"prompt_eval_count": 7})),
424 provider_model: Some("qwen3:32b".to_string()),
425 finish_reason: Some("length".to_string()),
426 metadata: HashMap::from([("total_duration".to_string(), serde_json::json!(12))]),
427 };
428
429 tracer.record_llm_response_with_evidence(
430 "qwen3",
431 "partial",
432 None,
433 None,
434 evidence.clone(),
435 "test",
436 "corr",
437 );
438
439 let events = responses(&captured);
440 assert_eq!(events.len(), 1);
441 assert_eq!(events[0].model, "qwen3");
442 assert_eq!(events[0].evidence, evidence);
443 }
444
445 #[test]
446 fn test_record_tool_call() {
447 let tracer = TracerSystem::default();
448 let mut args = HashMap::new();
449 args.insert("input".to_string(), serde_json::json!("test"));
450
451 tracer.record_tool_call(
452 "example_tool",
453 args,
454 serde_json::json!({"output": "result"}),
455 Some("agent1".to_string()),
456 Some(25.0),
457 "test",
458 "corr-789",
459 );
460
461 assert_eq!(tracer.len(), 1);
462 }
463
464 #[test]
465 fn test_record_agent_interaction() {
466 let tracer = TracerSystem::default();
467
468 tracer.record_agent_interaction(
469 "agent1",
470 "agent2",
471 "message",
472 Some("evt-123".to_string()),
473 "test",
474 "corr-abc",
475 );
476
477 assert_eq!(tracer.len(), 1);
478 }
479
480 #[test]
481 fn test_disabled_tracer_doesnt_record() {
482 let tracer = TracerSystem::new(None, false);
483 assert!(!tracer.is_enabled());
484
485 tracer.record_llm_call("llama3.2", vec![], Some(1.0), None, "test", "corr-123");
486
487 assert_eq!(tracer.len(), 0);
488 }
489
490 #[test]
491 fn test_clear() {
492 let tracer = TracerSystem::default();
493
494 tracer.record_llm_call("llama3.2", vec![], Some(1.0), None, "test", "corr-123");
495
496 assert_eq!(tracer.len(), 1);
497
498 tracer.clear();
499 assert_eq!(tracer.len(), 0);
500 assert!(tracer.is_empty());
501 }
502
503 #[test]
504 fn test_multiple_events() {
505 let tracer = TracerSystem::default();
506
507 for i in 0..5 {
508 tracer.record_llm_call(
509 "llama3.2",
510 vec![],
511 Some(1.0),
512 None,
513 "test",
514 format!("corr-{}", i),
515 );
516 }
517
518 assert_eq!(tracer.len(), 5);
519 }
520}