use super::event_store::EventStore;
use super::tracer_events::*;
use crate::llm::models::ResponseEvidence;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
pub struct TracerSystem {
event_store: Arc<EventStore>,
enabled: Arc<AtomicBool>,
}
impl TracerSystem {
pub fn new(event_store: Option<Arc<EventStore>>, enabled: bool) -> Self {
Self {
event_store: event_store.unwrap_or_else(|| Arc::new(EventStore::default())),
enabled: Arc::new(AtomicBool::new(enabled)),
}
}
pub fn is_enabled(&self) -> bool {
self.enabled.load(Ordering::SeqCst)
}
pub fn enable(&self) {
self.enabled.store(true, Ordering::SeqCst);
}
pub fn disable(&self) {
self.enabled.store(false, Ordering::SeqCst);
}
pub fn record_event(&self, event: Box<dyn TracerEvent>) {
if !self.is_enabled() {
return;
}
self.event_store.store(event);
}
pub fn record_llm_call(
&self,
model: impl Into<String>,
messages: Vec<HashMap<String, serde_json::Value>>,
temperature: f64,
tools: Option<Vec<HashMap<String, serde_json::Value>>>,
source: impl Into<String>,
correlation_id: impl Into<String>,
) {
if !self.is_enabled() {
return;
}
let event = Box::new(LlmCallTracerEvent {
timestamp: current_timestamp(),
correlation_id: correlation_id.into(),
source: source.into(),
model: model.into(),
messages,
temperature,
tools,
});
self.event_store.store(event);
}
pub fn record_llm_response(
&self,
model: impl Into<String>,
content: impl Into<String>,
tool_calls: Option<Vec<HashMap<String, serde_json::Value>>>,
call_duration_ms: Option<f64>,
source: impl Into<String>,
correlation_id: impl Into<String>,
) {
self.record_llm_response_with_evidence(
model,
content,
tool_calls,
call_duration_ms,
ResponseEvidence::default(),
source,
correlation_id,
);
}
#[allow(clippy::too_many_arguments)]
pub fn record_llm_response_with_evidence(
&self,
model: impl Into<String>,
content: impl Into<String>,
tool_calls: Option<Vec<HashMap<String, serde_json::Value>>>,
call_duration_ms: Option<f64>,
evidence: ResponseEvidence,
source: impl Into<String>,
correlation_id: impl Into<String>,
) {
if !self.is_enabled() {
return;
}
let event = Box::new(LlmResponseTracerEvent {
timestamp: current_timestamp(),
correlation_id: correlation_id.into(),
source: source.into(),
model: model.into(),
content: content.into(),
tool_calls,
call_duration_ms,
evidence,
});
self.event_store.store(event);
}
#[allow(clippy::too_many_arguments)]
pub fn record_tool_call(
&self,
tool_name: impl Into<String>,
arguments: HashMap<String, serde_json::Value>,
result: serde_json::Value,
caller: Option<String>,
call_duration_ms: Option<f64>,
source: impl Into<String>,
correlation_id: impl Into<String>,
) {
if !self.is_enabled() {
return;
}
let event = Box::new(ToolCallTracerEvent {
timestamp: current_timestamp(),
correlation_id: correlation_id.into(),
source: source.into(),
tool_name: tool_name.into(),
arguments,
result,
caller,
call_duration_ms,
});
self.event_store.store(event);
}
#[allow(clippy::too_many_arguments)]
pub fn record_tool_batch(
&self,
batch_id: impl Into<String>,
tool_names: Vec<String>,
success_count: usize,
failure_count: usize,
call_duration_ms: f64,
caller: Option<String>,
source: impl Into<String>,
correlation_id: impl Into<String>,
) {
if !self.is_enabled() {
return;
}
let event = Box::new(ToolBatchTracerEvent {
timestamp: current_timestamp(),
correlation_id: correlation_id.into(),
source: source.into(),
batch_id: batch_id.into(),
tool_names,
success_count,
failure_count,
call_duration_ms,
caller,
});
self.event_store.store(event);
}
pub fn record_agent_interaction(
&self,
from_agent: impl Into<String>,
to_agent: impl Into<String>,
event_type: impl Into<String>,
event_id: Option<String>,
source: impl Into<String>,
correlation_id: impl Into<String>,
) {
if !self.is_enabled() {
return;
}
let event = Box::new(AgentInteractionTracerEvent {
timestamp: current_timestamp(),
correlation_id: correlation_id.into(),
source: source.into(),
from_agent: from_agent.into(),
to_agent: to_agent.into(),
event_type: event_type.into(),
event_id,
});
self.event_store.store(event);
}
pub fn get_event_summaries(
&self,
start_time: Option<f64>,
end_time: Option<f64>,
filter_func: Option<&dyn super::EventFilterFn>,
) -> Vec<String> {
self.event_store.get_event_summaries(start_time, end_time, filter_func)
}
pub fn get_last_n_summaries(
&self,
n: usize,
filter_func: Option<&dyn super::EventFilterFn>,
) -> Vec<String> {
self.event_store.get_last_n_summaries(n, filter_func)
}
pub fn count_events(
&self,
start_time: Option<f64>,
end_time: Option<f64>,
filter_func: Option<&dyn super::EventFilterFn>,
) -> usize {
self.event_store.count_events(start_time, end_time, filter_func)
}
pub fn clear(&self) {
self.event_store.clear();
}
pub fn len(&self) -> usize {
self.event_store.len()
}
pub fn is_empty(&self) -> bool {
self.event_store.is_empty()
}
}
impl Default for TracerSystem {
fn default() -> Self {
Self::new(None, true)
}
}
fn current_timestamp() -> f64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs_f64()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_tracer_system() {
let tracer = TracerSystem::default();
assert!(tracer.is_enabled());
assert_eq!(tracer.len(), 0);
}
#[test]
fn test_enable_disable() {
let tracer = TracerSystem::default();
assert!(tracer.is_enabled());
tracer.disable();
assert!(!tracer.is_enabled());
tracer.enable();
assert!(tracer.is_enabled());
}
#[test]
fn test_record_llm_call() {
let tracer = TracerSystem::default();
tracer.record_llm_call("llama3.2", vec![], 0.7, None, "test", "corr-123");
assert_eq!(tracer.len(), 1);
}
#[test]
fn test_record_llm_response() {
let tracer = TracerSystem::default();
tracer.record_llm_response(
"llama3.2",
"Hello, world!",
None,
Some(150.5),
"test",
"corr-456",
);
assert_eq!(tracer.len(), 1);
}
#[test]
fn record_llm_response_with_evidence_keeps_evidence_unchanged() {
use crate::tracer::testing::{capturing_tracer, responses};
let (tracer, captured) = capturing_tracer();
let evidence = ResponseEvidence {
usage: Some(serde_json::json!({"prompt_eval_count": 7})),
provider_model: Some("qwen3:32b".to_string()),
finish_reason: Some("length".to_string()),
metadata: HashMap::from([("total_duration".to_string(), serde_json::json!(12))]),
};
tracer.record_llm_response_with_evidence(
"qwen3",
"partial",
None,
None,
evidence.clone(),
"test",
"corr",
);
let events = responses(&captured);
assert_eq!(events.len(), 1);
assert_eq!(events[0].model, "qwen3");
assert_eq!(events[0].evidence, evidence);
}
#[test]
fn test_record_tool_call() {
let tracer = TracerSystem::default();
let mut args = HashMap::new();
args.insert("input".to_string(), serde_json::json!("test"));
tracer.record_tool_call(
"example_tool",
args,
serde_json::json!({"output": "result"}),
Some("agent1".to_string()),
Some(25.0),
"test",
"corr-789",
);
assert_eq!(tracer.len(), 1);
}
#[test]
fn test_record_agent_interaction() {
let tracer = TracerSystem::default();
tracer.record_agent_interaction(
"agent1",
"agent2",
"message",
Some("evt-123".to_string()),
"test",
"corr-abc",
);
assert_eq!(tracer.len(), 1);
}
#[test]
fn test_disabled_tracer_doesnt_record() {
let tracer = TracerSystem::new(None, false);
assert!(!tracer.is_enabled());
tracer.record_llm_call("llama3.2", vec![], 1.0, None, "test", "corr-123");
assert_eq!(tracer.len(), 0);
}
#[test]
fn test_clear() {
let tracer = TracerSystem::default();
tracer.record_llm_call("llama3.2", vec![], 1.0, None, "test", "corr-123");
assert_eq!(tracer.len(), 1);
tracer.clear();
assert_eq!(tracer.len(), 0);
assert!(tracer.is_empty());
}
#[test]
fn test_multiple_events() {
let tracer = TracerSystem::default();
for i in 0..5 {
tracer.record_llm_call("llama3.2", vec![], 1.0, None, "test", format!("corr-{}", i));
}
assert_eq!(tracer.len(), 5);
}
}