Skip to main content

mojentic/tracer/
mod.rs

1//! Tracer system for observability and debugging
2//!
3//! The tracer system provides comprehensive observability into LLM interactions,
4//! tool executions, and agent communications. It records events with timestamps
5//! and correlation IDs, enabling detailed debugging and monitoring.
6//!
7//! # Architecture
8//!
9//! The tracer system consists of several key components:
10//!
11//! - **TracerEvent**: Base trait for all event types with timestamps and correlation IDs
12//! - **EventStore**: Thread-safe storage for events with callbacks and filtering
13//! - **TracerSystem**: Coordination layer providing convenience methods for recording events
14//! - **NullTracer**: Null object pattern for when tracing is disabled
15//!
16//! # Event Types
17//!
18//! - **LlmCallTracerEvent**: Records LLM calls with model, messages, temperature, and tools
19//! - **LlmResponseTracerEvent**: Records LLM responses with content, tool calls, and duration
20//! - **ToolCallTracerEvent**: Records tool executions with arguments, results, and duration
21//! - **AgentInteractionTracerEvent**: Records agent-to-agent communications
22//!
23//! # Usage Example
24//!
25//! ```rust,ignore
26//! use mojentic::tracer::{TracerSystem, LlmCallTracerEvent};
27//! use std::collections::HashMap;
28//!
29//! // Create a tracer system
30//! let tracer = TracerSystem::default();
31//!
32//! // Record an LLM call
33//! tracer.record_llm_call(
34//!     "llama3.2",
35//!     vec![],
36//!     0.7,
37//!     None,
38//!     "my_agent",
39//!     "correlation-123"
40//! );
41//!
42//! // Query events
43//! let events = tracer.get_events(None, None, None);
44//! for event in events {
45//!     println!("{}", event.printable_summary());
46//! }
47//! ```
48//!
49//! # Correlation IDs
50//!
51//! Correlation IDs are UUIDs that are copied from cause-to-effect across the system,
52//! enabling you to trace all events related to a single request or operation.
53//! This creates a complete audit trail for debugging and observability.
54
55pub mod event_store;
56pub mod null_tracer;
57pub mod tracer_events;
58pub mod tracer_system;
59
60// Re-export main types
61pub use event_store::{EventCallback, EventStore};
62pub use null_tracer::NullTracer;
63pub use tracer_events::{
64    AgentInteractionTracerEvent, EventFilterFn, LlmCallTracerEvent, LlmResponseTracerEvent,
65    ToolCallTracerEvent, TracerEvent,
66};
67pub use tracer_system::TracerSystem;
68
69#[cfg(test)]
70pub(crate) mod testing {
71    //! Test helpers that read typed events back out of a tracer.
72
73    use super::*;
74    use std::sync::{Arc, Mutex};
75
76    /// A typed copy of an LLM event that a [`capturing_tracer`] recorded.
77    #[derive(Debug, Clone)]
78    pub(crate) enum CapturedLlmEvent {
79        Call(LlmCallTracerEvent),
80        Response(LlmResponseTracerEvent),
81    }
82
83    /// Captured LLM events, in recording order.
84    pub(crate) type CapturedLlmEvents = Arc<Mutex<Vec<CapturedLlmEvent>>>;
85
86    /// A tracer that also keeps a typed copy of every LLM call and response event.
87    pub(crate) fn capturing_tracer() -> (Arc<TracerSystem>, CapturedLlmEvents) {
88        let captured: CapturedLlmEvents = Arc::new(Mutex::new(Vec::new()));
89        let sink = captured.clone();
90        let store = EventStore::new(Some(Arc::new(move |event: &dyn TracerEvent| {
91            let Some(any) = event.as_any() else { return };
92            let copy = if let Some(call) = any.downcast_ref::<LlmCallTracerEvent>() {
93                CapturedLlmEvent::Call(call.clone())
94            } else if let Some(response) = any.downcast_ref::<LlmResponseTracerEvent>() {
95                CapturedLlmEvent::Response(response.clone())
96            } else {
97                return;
98            };
99            sink.lock().unwrap().push(copy);
100        })));
101        (Arc::new(TracerSystem::new(Some(Arc::new(store)), true)), captured)
102    }
103
104    /// The LLM response events captured so far.
105    pub(crate) fn responses(captured: &CapturedLlmEvents) -> Vec<LlmResponseTracerEvent> {
106        captured
107            .lock()
108            .unwrap()
109            .iter()
110            .filter_map(|event| match event {
111                CapturedLlmEvent::Response(response) => Some(response.clone()),
112                CapturedLlmEvent::Call(_) => None,
113            })
114            .collect()
115    }
116}