mojentic 2.1.0

An LLM integration framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Tracer event types for tracking system interactions
//!
//! This module defines the core event types used by the tracer system to record
//! LLM calls, tool executions, and agent interactions. All events implement the
//! `TracerEvent` trait which provides timestamps, correlation IDs, and printable summaries.

use crate::llm::models::ResponseEvidence;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;

/// Trait for filtering tracer events
///
/// Implement this trait to create custom event filters. This trait is used
/// instead of raw closure types to avoid type complexity warnings.
pub trait EventFilterFn: Send + Sync {
    /// Test whether an event passes the filter
    fn matches(&self, event: &dyn TracerEvent) -> bool;
}

/// Implement EventFilterFn for any function that matches the signature
impl<F> EventFilterFn for F
where
    F: Fn(&dyn TracerEvent) -> bool + Send + Sync,
{
    fn matches(&self, event: &dyn TracerEvent) -> bool {
        self(event)
    }
}

/// Base trait for all tracer events
///
/// Tracer events are used to track system interactions for observability purposes.
/// They are distinct from regular events which are used for agent communication.
pub trait TracerEvent: Send + Sync {
    /// Get the timestamp when the event occurred
    fn timestamp(&self) -> f64;

    /// Get the correlation ID for tracing related events
    fn correlation_id(&self) -> &str;

    /// Get the source of the event
    fn source(&self) -> &str;

    /// Get a formatted string summary of the event
    fn printable_summary(&self) -> String;

    /// Expose the concrete event for downcasting, when the event type allows it.
    ///
    /// The built-in events return `Some(self)`, so an [`crate::tracer::EventCallback`]
    /// can read typed fields, for example the evidence on an
    /// [`LlmResponseTracerEvent`]:
    ///
    /// ```
    /// use mojentic::tracer::{LlmResponseTracerEvent, TracerEvent};
    ///
    /// fn finish_reason(event: &dyn TracerEvent) -> Option<String> {
    ///     event
    ///         .as_any()?
    ///         .downcast_ref::<LlmResponseTracerEvent>()?
    ///         .evidence
    ///         .finish_reason
    ///         .clone()
    /// }
    /// ```
    fn as_any(&self) -> Option<&dyn Any> {
        None
    }
}

/// Records when an LLM is called with specific messages
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmCallTracerEvent {
    /// Timestamp when the event occurred (Unix timestamp)
    pub timestamp: f64,
    /// UUID string that is copied from cause-to-affect for tracing events
    pub correlation_id: String,
    /// Source of the event
    pub source: String,
    /// The LLM model that was used
    pub model: String,
    /// The messages sent to the LLM (simplified representation)
    pub messages: Vec<HashMap<String, serde_json::Value>>,
    /// The temperature setting used for the call
    pub temperature: f64,
    /// The tools available to the LLM, if any
    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 (self.temperature - 1.0).abs() > f64::EPSILON {
            summary.push_str(&format!("\n   Temperature: {}", self.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)
    }
}

/// Records when an LLM responds to a call
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmResponseTracerEvent {
    /// Timestamp when the event occurred (Unix timestamp)
    pub timestamp: f64,
    /// UUID string that is copied from cause-to-affect for tracing events
    pub correlation_id: String,
    /// Source of the event
    pub source: String,
    /// The LLM model that was used
    pub model: String,
    /// The content of the LLM response
    pub content: String,
    /// Any tool calls made by the LLM
    pub tool_calls: Option<Vec<HashMap<String, serde_json::Value>>>,
    /// Duration of the LLM call in milliseconds
    pub call_duration_ms: Option<f64>,
    /// Provider-reported usage, provider model, finish reason and metadata.
    ///
    /// Serialized as the flat fields `usage`, `provider_model`,
    /// `finish_reason` and `metadata`. Unknown values stay null.
    #[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)
    }
}

/// Records when a tool is called during agent execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallTracerEvent {
    /// Timestamp when the event occurred (Unix timestamp)
    pub timestamp: f64,
    /// UUID string that is copied from cause-to-affect for tracing events
    pub correlation_id: String,
    /// Source of the event
    pub source: String,
    /// Name of the tool that was called
    pub tool_name: String,
    /// Arguments provided to the tool
    pub arguments: HashMap<String, serde_json::Value>,
    /// Result returned by the tool (as JSON value)
    pub result: serde_json::Value,
    /// Name of the agent or component that called the tool
    pub caller: Option<String>,
    /// Duration of the tool call in milliseconds
    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)
    }
}

/// Records the end-to-end execution of a parallel tool batch.
///
/// Per-call detail still lands as `ToolCallTracerEvent` events; the
/// batch event lets observers measure parallelism gains and correlate
/// calls dispatched together.
#[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)
    }
}

/// Records interactions between agents
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentInteractionTracerEvent {
    /// Timestamp when the event occurred (Unix timestamp)
    pub timestamp: f64,
    /// UUID string that is copied from cause-to-affect for tracing events
    pub correlation_id: String,
    /// Source of the event
    pub source: String,
    /// Name of the agent sending the event
    pub from_agent: String,
    /// Name of the agent receiving the event
    pub to_agent: String,
    /// Type of event being processed
    pub event_type: String,
    /// Unique identifier for the event
    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: 0.7,
            tools: None,
        };

        assert_eq!(event.correlation_id(), "test-123");
        assert_eq!(event.model, "llama3.2");
        assert!((event.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"));
    }
}