use crate::llm::models::ResponseEvidence;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
pub trait EventFilterFn: Send + Sync {
fn matches(&self, event: &dyn TracerEvent) -> bool;
}
impl<F> EventFilterFn for F
where
F: Fn(&dyn TracerEvent) -> bool + Send + Sync,
{
fn matches(&self, event: &dyn TracerEvent) -> bool {
self(event)
}
}
pub trait TracerEvent: Send + Sync {
fn timestamp(&self) -> f64;
fn correlation_id(&self) -> &str;
fn source(&self) -> &str;
fn printable_summary(&self) -> String;
fn as_any(&self) -> Option<&dyn Any> {
None
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmCallTracerEvent {
pub timestamp: f64,
pub correlation_id: String,
pub source: String,
pub model: String,
pub messages: Vec<HashMap<String, serde_json::Value>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
pub tools: Option<Vec<HashMap<String, serde_json::Value>>>,
}
impl TracerEvent for LlmCallTracerEvent {
fn timestamp(&self) -> f64 {
self.timestamp
}
fn correlation_id(&self) -> &str {
&self.correlation_id
}
fn source(&self) -> &str {
&self.source
}
fn printable_summary(&self) -> String {
let dt = DateTime::from_timestamp(self.timestamp as i64, 0)
.unwrap_or_else(|| DateTime::from_timestamp(0, 0).unwrap())
.with_timezone(&Local);
let time_str = dt.format("%H:%M:%S%.3f").to_string();
let mut summary = format!(
"[{}] LlmCallTracerEvent (correlation_id: {})\n Model: {}",
time_str, self.correlation_id, self.model
);
if !self.messages.is_empty() {
let msg_count = self.messages.len();
let plural = if msg_count != 1 { "s" } else { "" };
summary.push_str(&format!("\n Messages: {} message{}", msg_count, plural));
}
if let Some(temperature) = self.temperature {
summary.push_str(&format!("\n Temperature: {}", temperature));
}
if let Some(tools) = &self.tools {
let tool_names: Vec<String> = tools
.iter()
.filter_map(|t| t.get("name").and_then(|n| n.as_str()).map(|s| s.to_string()))
.collect();
if !tool_names.is_empty() {
summary.push_str(&format!("\n Available Tools: {}", tool_names.join(", ")));
}
}
summary
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmResponseTracerEvent {
pub timestamp: f64,
pub correlation_id: String,
pub source: String,
pub model: String,
pub content: String,
pub tool_calls: Option<Vec<HashMap<String, serde_json::Value>>>,
pub call_duration_ms: Option<f64>,
#[serde(flatten)]
pub evidence: ResponseEvidence,
}
impl TracerEvent for LlmResponseTracerEvent {
fn timestamp(&self) -> f64 {
self.timestamp
}
fn correlation_id(&self) -> &str {
&self.correlation_id
}
fn source(&self) -> &str {
&self.source
}
fn printable_summary(&self) -> String {
let dt = DateTime::from_timestamp(self.timestamp as i64, 0)
.unwrap_or_else(|| DateTime::from_timestamp(0, 0).unwrap())
.with_timezone(&Local);
let time_str = dt.format("%H:%M:%S%.3f").to_string();
let mut summary = format!(
"[{}] LlmResponseTracerEvent (correlation_id: {})\n Model: {}",
time_str, self.correlation_id, self.model
);
if !self.content.is_empty() {
let content_preview = if self.content.len() > 100 {
format!("{}...", &self.content[..100])
} else {
self.content.clone()
};
summary.push_str(&format!("\n Content: {}", content_preview));
}
if let Some(tool_calls) = &self.tool_calls {
let tool_count = tool_calls.len();
let plural = if tool_count != 1 { "s" } else { "" };
summary.push_str(&format!("\n Tool Calls: {} call{}", tool_count, plural));
}
if let Some(duration) = self.call_duration_ms {
summary.push_str(&format!("\n Duration: {:.2}ms", duration));
}
if let Some(provider_model) = &self.evidence.provider_model {
summary.push_str(&format!("\n Provider Model: {}", provider_model));
}
if let Some(finish_reason) = &self.evidence.finish_reason {
summary.push_str(&format!("\n Finish Reason: {}", finish_reason));
}
if let Some(usage) = &self.evidence.usage {
summary.push_str(&format!("\n Usage: {}", usage));
}
summary
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallTracerEvent {
pub timestamp: f64,
pub correlation_id: String,
pub source: String,
pub tool_name: String,
pub arguments: HashMap<String, serde_json::Value>,
pub result: serde_json::Value,
pub caller: Option<String>,
pub call_duration_ms: Option<f64>,
}
impl TracerEvent for ToolCallTracerEvent {
fn timestamp(&self) -> f64 {
self.timestamp
}
fn correlation_id(&self) -> &str {
&self.correlation_id
}
fn source(&self) -> &str {
&self.source
}
fn printable_summary(&self) -> String {
let dt = DateTime::from_timestamp(self.timestamp as i64, 0)
.unwrap_or_else(|| DateTime::from_timestamp(0, 0).unwrap())
.with_timezone(&Local);
let time_str = dt.format("%H:%M:%S%.3f").to_string();
let mut summary = format!(
"[{}] ToolCallTracerEvent (correlation_id: {})\n Tool: {}",
time_str, self.correlation_id, self.tool_name
);
if !self.arguments.is_empty() {
summary.push_str(&format!("\n Arguments: {:?}", self.arguments));
}
let result_str = self.result.to_string();
let result_preview = if result_str.len() > 100 {
format!("{}...", &result_str[..100])
} else {
result_str
};
summary.push_str(&format!("\n Result: {}", result_preview));
if let Some(caller) = &self.caller {
summary.push_str(&format!("\n Caller: {}", caller));
}
if let Some(duration) = self.call_duration_ms {
summary.push_str(&format!("\n Duration: {:.2}ms", duration));
}
summary
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolBatchTracerEvent {
pub timestamp: f64,
pub correlation_id: String,
pub source: String,
pub batch_id: String,
pub tool_names: Vec<String>,
pub success_count: usize,
pub failure_count: usize,
pub call_duration_ms: f64,
pub caller: Option<String>,
}
impl TracerEvent for ToolBatchTracerEvent {
fn timestamp(&self) -> f64 {
self.timestamp
}
fn correlation_id(&self) -> &str {
&self.correlation_id
}
fn source(&self) -> &str {
&self.source
}
fn printable_summary(&self) -> String {
let dt = DateTime::from_timestamp(self.timestamp as i64, 0)
.unwrap_or_else(|| DateTime::from_timestamp(0, 0).unwrap())
.with_timezone(&Local);
let time_str = dt.format("%H:%M:%S%.3f").to_string();
format!(
"[{}] ToolBatchTracerEvent (correlation_id: {})\n Batch: {}\n Tools: {}\n Outcome: {} ok / {} failed\n Duration: {:.2}ms",
time_str,
self.correlation_id,
self.batch_id,
self.tool_names.join(", "),
self.success_count,
self.failure_count,
self.call_duration_ms
)
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentInteractionTracerEvent {
pub timestamp: f64,
pub correlation_id: String,
pub source: String,
pub from_agent: String,
pub to_agent: String,
pub event_type: String,
pub event_id: Option<String>,
}
impl TracerEvent for AgentInteractionTracerEvent {
fn timestamp(&self) -> f64 {
self.timestamp
}
fn correlation_id(&self) -> &str {
&self.correlation_id
}
fn source(&self) -> &str {
&self.source
}
fn printable_summary(&self) -> String {
let dt = DateTime::from_timestamp(self.timestamp as i64, 0)
.unwrap_or_else(|| DateTime::from_timestamp(0, 0).unwrap())
.with_timezone(&Local);
let time_str = dt.format("%H:%M:%S%.3f").to_string();
let mut summary = format!(
"[{}] AgentInteractionTracerEvent (correlation_id: {})\n From: {} → To: {}\n Event Type: {}",
time_str, self.correlation_id, self.from_agent, self.to_agent, self.event_type
);
if let Some(event_id) = &self.event_id {
summary.push_str(&format!("\n Event ID: {}", event_id));
}
summary
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
fn current_timestamp() -> f64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs_f64()
}
#[test]
fn test_llm_call_event() {
let event = LlmCallTracerEvent {
timestamp: current_timestamp(),
correlation_id: "test-123".to_string(),
source: "test".to_string(),
model: "llama3.2".to_string(),
messages: vec![],
temperature: Some(0.7),
tools: None,
};
assert_eq!(event.correlation_id(), "test-123");
assert_eq!(event.model, "llama3.2");
assert!((event.temperature.expect("explicit temperature") - 0.7).abs() < f64::EPSILON);
let summary = event.printable_summary();
assert!(summary.contains("LlmCallTracerEvent"));
assert!(summary.contains("test-123"));
assert!(summary.contains("llama3.2"));
}
#[test]
fn test_llm_response_event() {
let event = LlmResponseTracerEvent {
timestamp: current_timestamp(),
correlation_id: "test-456".to_string(),
source: "test".to_string(),
model: "llama3.2".to_string(),
content: "Hello, world!".to_string(),
tool_calls: None,
call_duration_ms: Some(150.5),
evidence: ResponseEvidence::default(),
};
assert_eq!(event.content, "Hello, world!");
assert_eq!(event.call_duration_ms, Some(150.5));
let summary = event.printable_summary();
assert!(summary.contains("LlmResponseTracerEvent"));
assert!(summary.contains("Hello, world!"));
assert!(summary.contains("150.5"));
}
fn evidence() -> ResponseEvidence {
ResponseEvidence {
usage: Some(serde_json::json!({"prompt_tokens": 3, "completion_tokens": 5})),
provider_model: Some("gpt-4o-2024-08-06".to_string()),
finish_reason: Some("stop".to_string()),
metadata: HashMap::from([("id".to_string(), serde_json::json!("chatcmpl-1"))]),
}
}
fn response_event(evidence: ResponseEvidence) -> LlmResponseTracerEvent {
LlmResponseTracerEvent {
timestamp: current_timestamp(),
correlation_id: "corr".to_string(),
source: "test".to_string(),
model: "gpt-4o".to_string(),
content: "Hi".to_string(),
tool_calls: None,
call_duration_ms: None,
evidence,
}
}
#[test]
fn llm_response_event_serializes_evidence_as_flat_fields() {
let json = serde_json::to_value(response_event(evidence())).unwrap();
assert_eq!(json["model"], "gpt-4o");
assert_eq!(json["provider_model"], "gpt-4o-2024-08-06");
assert_eq!(json["finish_reason"], "stop");
assert_eq!(json["usage"], serde_json::json!({"prompt_tokens": 3, "completion_tokens": 5}));
assert_eq!(json["metadata"], serde_json::json!({"id": "chatcmpl-1"}));
}
#[test]
fn llm_response_event_serializes_unknown_evidence_as_null() {
let json = serde_json::to_value(response_event(ResponseEvidence::default())).unwrap();
assert!(json["usage"].is_null());
assert!(json["provider_model"].is_null());
assert!(json["finish_reason"].is_null());
}
#[test]
fn llm_response_event_deserializes_records_without_evidence() {
let json = serde_json::json!({
"timestamp": 1.0,
"correlation_id": "corr",
"source": "test",
"model": "gpt-4o",
"content": "Hi",
"tool_calls": null,
"call_duration_ms": null
});
let event: LlmResponseTracerEvent = serde_json::from_value(json).unwrap();
assert_eq!(event.evidence, ResponseEvidence::default());
}
#[test]
fn llm_response_summary_shows_reported_evidence() {
let summary = response_event(evidence()).printable_summary();
assert!(summary.contains("Provider Model: gpt-4o-2024-08-06"));
assert!(summary.contains("Finish Reason: stop"));
assert!(summary.contains("\"prompt_tokens\":3"));
}
#[test]
fn built_in_events_downcast_through_as_any() {
let event: Box<dyn TracerEvent> = Box::new(response_event(evidence()));
let typed = event
.as_any()
.and_then(|any| any.downcast_ref::<LlmResponseTracerEvent>())
.expect("response event downcasts");
assert_eq!(typed.evidence, evidence());
}
#[test]
fn test_tool_call_event() {
let mut args = HashMap::new();
args.insert("input".to_string(), serde_json::json!("test"));
let event = ToolCallTracerEvent {
timestamp: current_timestamp(),
correlation_id: "test-789".to_string(),
source: "test".to_string(),
tool_name: "example_tool".to_string(),
arguments: args,
result: serde_json::json!({"output": "result"}),
caller: Some("agent1".to_string()),
call_duration_ms: Some(25.0),
};
assert_eq!(event.tool_name, "example_tool");
assert_eq!(event.caller, Some("agent1".to_string()));
let summary = event.printable_summary();
assert!(summary.contains("ToolCallTracerEvent"));
assert!(summary.contains("example_tool"));
}
#[test]
fn test_agent_interaction_event() {
let event = AgentInteractionTracerEvent {
timestamp: current_timestamp(),
correlation_id: "test-abc".to_string(),
source: "test".to_string(),
from_agent: "agent1".to_string(),
to_agent: "agent2".to_string(),
event_type: "message".to_string(),
event_id: Some("evt-123".to_string()),
};
assert_eq!(event.from_agent, "agent1");
assert_eq!(event.to_agent, "agent2");
let summary = event.printable_summary();
assert!(summary.contains("AgentInteractionTracerEvent"));
assert!(summary.contains("agent1"));
assert!(summary.contains("agent2"));
}
}