1use serde::de::{MapAccess, Visitor};
5use serde::ser::SerializeMap;
6use std::sync::{Arc, Mutex, PoisonError};
7
8#[cfg(feature = "otel")]
9use opentelemetry::metrics::{Counter, Histogram};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use super::tracer::{LoopSpan, Tracer};
13use crate::models::streaming::{Metrics, Usage};
14use crate::types::Message;
15
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase")]
19#[non_exhaustive]
20pub struct ToolMetricsData {
21 pub call_count: u64,
23 pub success_count: u64,
25 pub error_count: u64,
27 pub total_time: u64,
29}
30
31impl ToolMetricsData {
32 #[must_use]
34 pub fn with_call_count(mut self, call_count: u64) -> Self {
35 self.call_count = call_count;
36 self
37 }
38
39 #[must_use]
41 pub fn with_success_count(mut self, success_count: u64) -> Self {
42 self.success_count = success_count;
43 self
44 }
45
46 #[must_use]
48 pub fn with_error_count(mut self, error_count: u64) -> Self {
49 self.error_count = error_count;
50 self
51 }
52
53 #[must_use]
55 pub fn with_total_time(mut self, total_time: u64) -> Self {
56 self.total_time = total_time;
57 self
58 }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq)]
63#[non_exhaustive]
64pub struct ToolUsage {
65 pub metrics: ToolMetricsData,
67 pub average_time: f64,
69 pub success_rate: f64,
71}
72
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76#[non_exhaustive]
77pub struct AgentLoopMetricsData {
78 pub cycle_id: String,
80 pub duration: u64,
82 pub usage: Usage,
84}
85
86impl AgentLoopMetricsData {
87 pub fn new(cycle_id: impl Into<String>, duration: u64, usage: Usage) -> Self {
89 Self {
90 cycle_id: cycle_id.into(),
91 duration,
92 usage,
93 }
94 }
95}
96
97#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100#[non_exhaustive]
101pub struct InvocationMetricsData {
102 pub cycles: Vec<AgentLoopMetricsData>,
104 pub usage: Usage,
106}
107
108impl InvocationMetricsData {
109 pub fn new(cycles: Vec<AgentLoopMetricsData>, usage: Usage) -> Self {
111 Self { cycles, usage }
112 }
113}
114
115#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118#[non_exhaustive]
119pub struct AgentMetrics {
120 #[serde(default)]
122 pub cycle_count: u64,
123 #[serde(default)]
125 pub accumulated_usage: Usage,
126 #[serde(default)]
128 pub accumulated_metrics: Metrics,
129 #[serde(default)]
131 pub agent_invocations: Vec<InvocationMetricsData>,
132 #[serde(default, with = "named_metrics")]
134 pub tool_metrics: Vec<(String, ToolMetricsData)>,
135 #[serde(default)]
137 pub total_duration: u64,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub latest_context_size: Option<u64>,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub projected_context_size: Option<u64>,
144}
145
146impl AgentMetrics {
147 pub fn new() -> Self {
149 Self::default()
150 }
151
152 #[must_use]
154 pub fn with_latest_context_size(mut self, size: u64) -> Self {
155 self.latest_context_size = Some(size);
156 self
157 }
158
159 #[must_use]
161 pub fn with_projected_context_size(mut self, size: u64) -> Self {
162 self.projected_context_size = Some(size);
163 self
164 }
165
166 #[must_use]
168 pub fn latest_agent_invocation(&self) -> Option<&InvocationMetricsData> {
169 self.agent_invocations.last()
170 }
171
172 #[must_use]
174 pub fn accumulated_data(&self) -> (&Usage, &Metrics) {
175 (&self.accumulated_usage, &self.accumulated_metrics)
176 }
177
178 #[must_use]
180 #[allow(clippy::cast_precision_loss, reason = "millisecond totals stay far below 2^52")]
181 pub fn average_cycle_time(&self) -> f64 {
182 if self.cycle_count == 0 {
183 return 0.0;
184 }
185 self.total_duration as f64 / self.cycle_count as f64
186 }
187
188 #[must_use]
190 pub fn tool(&self, name: &str) -> Option<&ToolMetricsData> {
191 self.tool_metrics
192 .iter()
193 .find_map(|(tool, metrics)| (tool == name).then_some(metrics))
194 }
195
196 #[must_use]
198 #[allow(
199 clippy::cast_precision_loss,
200 reason = "call counts and millisecond totals stay far below 2^52"
201 )]
202 pub fn tool_usage(&self) -> Vec<(String, ToolUsage)> {
203 self.tool_metrics
204 .iter()
205 .map(|(name, metrics)| {
206 let calls = metrics.call_count as f64;
207 let (average_time, success_rate) = if metrics.call_count == 0 {
208 (0.0, 0.0)
209 } else {
210 (metrics.total_time as f64 / calls, metrics.success_count as f64 / calls)
211 };
212 let usage = ToolUsage {
213 metrics: *metrics,
214 average_time,
215 success_rate,
216 };
217 (name.clone(), usage)
218 })
219 .collect()
220 }
221}
222
223mod named_metrics {
224 use super::*;
225
226 pub(super) fn serialize<S: Serializer>(
227 metrics: &[(String, ToolMetricsData)],
228 serializer: S,
229 ) -> Result<S::Ok, S::Error> {
230 let mut map = serializer.serialize_map(Some(metrics.len()))?;
231 for (name, data) in metrics {
232 map.serialize_entry(name, data)?;
233 }
234 map.end()
235 }
236
237 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
238 deserializer: D,
239 ) -> Result<Vec<(String, ToolMetricsData)>, D::Error> {
240 deserializer.deserialize_map(NamedVisitor)
241 }
242
243 struct NamedVisitor;
244
245 impl<'de> Visitor<'de> for NamedVisitor {
246 type Value = Vec<(String, ToolMetricsData)>;
247
248 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 formatter.write_str("a map of tool metrics by tool name")
250 }
251
252 fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
253 let mut metrics = Vec::new();
254 while let Some(entry) = access.next_entry()? {
255 metrics.push(entry);
256 }
257 Ok(metrics)
258 }
259 }
260}
261
262const MAX_INVOCATION_HISTORY: usize = 50;
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub(crate) enum InstrumentKind {
267 Counter,
268 Histogram,
269}
270
271#[derive(Debug, Clone, Copy)]
273#[cfg_attr(
274 not(test),
275 allow(
276 dead_code,
277 reason = "the instruments read the names under otel; the conformance test reads all"
278 )
279)]
280pub(crate) struct InstrumentSpec {
281 pub(crate) kind: InstrumentKind,
282 pub(crate) name: &'static str,
283 pub(crate) description: &'static str,
284 pub(crate) unit: Option<&'static str>,
285}
286
287const fn counter(name: &'static str, description: &'static str) -> InstrumentSpec {
288 InstrumentSpec {
289 kind: InstrumentKind::Counter,
290 name,
291 description,
292 unit: None,
293 }
294}
295
296const fn histogram(name: &'static str, description: &'static str, unit: &'static str) -> InstrumentSpec {
297 InstrumentSpec {
298 kind: InstrumentKind::Histogram,
299 name,
300 description,
301 unit: Some(unit),
302 }
303}
304
305const CYCLE_COUNT: InstrumentSpec = counter("gen_ai.agent.cycle.count", "Number of agent loop cycles executed");
306const INVOCATION_COUNT: InstrumentSpec = counter("gen_ai.agent.invocation.count", "Number of agent invocations");
307const CYCLE_DURATION: InstrumentSpec = histogram(
308 "gen_ai.agent.cycle.duration",
309 "Duration of agent loop cycles in milliseconds",
310 "ms",
311);
312const TOOL_CALL_COUNT: InstrumentSpec = counter("gen_ai.agent.tool.call.count", "Number of tool calls");
313const TOOL_ERROR_COUNT: InstrumentSpec = counter("gen_ai.agent.tool.error.count", "Number of failed tool calls");
314const TOOL_DURATION: InstrumentSpec = histogram(
315 "gen_ai.agent.tool.duration",
316 "Duration of tool calls in milliseconds",
317 "ms",
318);
319const TOKENS_INPUT: InstrumentSpec = counter("gen_ai.agent.tokens.input", "Input tokens consumed");
320const TOKENS_OUTPUT: InstrumentSpec = counter("gen_ai.agent.tokens.output", "Output tokens consumed");
321const MODEL_LATENCY: InstrumentSpec = histogram(
322 "gen_ai.agent.model.latency",
323 "Model invocation latency in milliseconds",
324 "ms",
325);
326const TIME_TO_FIRST_TOKEN: InstrumentSpec = histogram(
328 "gen_ai.server.time_to_first_token",
329 "Time to generate first token for successful responses",
330 "s",
331);
332
333#[cfg_attr(not(test), allow(dead_code, reason = "the conformance test reads the table"))]
335pub(crate) const INSTRUMENTS: [InstrumentSpec; 10] = [
336 CYCLE_COUNT,
337 INVOCATION_COUNT,
338 CYCLE_DURATION,
339 TOOL_CALL_COUNT,
340 TOOL_ERROR_COUNT,
341 TOOL_DURATION,
342 TOKENS_INPUT,
343 TOKENS_OUTPUT,
344 MODEL_LATENCY,
345 TIME_TO_FIRST_TOKEN,
346];
347
348#[cfg(feature = "otel")]
350#[derive(Debug)]
351struct Instruments {
352 cycle_count: Counter<u64>,
353 invocation_count: Counter<u64>,
354 cycle_duration: Histogram<f64>,
355 tool_call_count: Counter<u64>,
356 tool_error_count: Counter<u64>,
357 tool_duration: Histogram<f64>,
358 tokens_input: Counter<u64>,
359 tokens_output: Counter<u64>,
360 model_latency: Histogram<f64>,
361 time_to_first_token: Histogram<f64>,
362}
363
364#[cfg(feature = "otel")]
365impl Instruments {
366 fn new(meter: &opentelemetry::metrics::Meter) -> Self {
367 let counter = |spec: InstrumentSpec| meter.u64_counter(spec.name).with_description(spec.description).build();
368 let histogram = |spec: InstrumentSpec| {
369 let builder = meter.f64_histogram(spec.name).with_description(spec.description);
370 match spec.unit {
371 Some(unit) => builder.with_unit(unit).build(),
372 None => builder.build(),
373 }
374 };
375 Self {
376 cycle_count: counter(CYCLE_COUNT),
377 invocation_count: counter(INVOCATION_COUNT),
378 cycle_duration: histogram(CYCLE_DURATION),
379 tool_call_count: counter(TOOL_CALL_COUNT),
380 tool_error_count: counter(TOOL_ERROR_COUNT),
381 tool_duration: histogram(TOOL_DURATION),
382 tokens_input: counter(TOKENS_INPUT),
383 tokens_output: counter(TOKENS_OUTPUT),
384 model_latency: histogram(MODEL_LATENCY),
385 time_to_first_token: histogram(TIME_TO_FIRST_TOKEN),
386 }
387 }
388}
389
390#[allow(clippy::cast_precision_loss, reason = "millisecond durations stay far below 2^52")]
391#[cfg(feature = "otel")]
392fn as_f64(value: u64) -> f64 {
393 value as f64
394}
395
396#[derive(Debug)]
399pub(crate) struct Meter {
400 metrics: AgentMetrics,
401 #[cfg(feature = "otel")]
402 instruments: Instruments,
403}
404
405impl Default for Meter {
406 fn default() -> Self {
407 Self::new()
408 }
409}
410
411fn elapsed_ms(start: tokio::time::Instant) -> u64 {
412 u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)
413}
414
415impl Meter {
416 pub(crate) fn new() -> Self {
417 Self {
418 metrics: AgentMetrics::default(),
419 #[cfg(feature = "otel")]
420 instruments: Instruments::new(&super::utils::service_meter()),
421 }
422 }
423
424 #[cfg(all(test, feature = "otel"))]
426 pub(crate) fn with_otel_meter(meter: &opentelemetry::metrics::Meter) -> Self {
427 Self {
428 metrics: AgentMetrics::default(),
429 instruments: Instruments::new(meter),
430 }
431 }
432
433 pub(crate) fn metrics(&self) -> AgentMetrics {
435 self.metrics.clone()
436 }
437
438 pub(crate) fn start_new_invocation(&mut self) {
440 if self.metrics.agent_invocations.len() >= MAX_INVOCATION_HISTORY {
441 self.metrics.agent_invocations.remove(0);
442 }
443 self.metrics.agent_invocations.push(InvocationMetricsData::default());
444 #[cfg(feature = "otel")]
445 self.instruments.invocation_count.add(1, &[]);
446 }
447
448 pub(crate) fn start_cycle(&mut self) -> (String, tokio::time::Instant) {
451 self.metrics.cycle_count = self.metrics.cycle_count.saturating_add(1);
452 #[cfg(feature = "otel")]
453 self.instruments.cycle_count.add(1, &[]);
454 let cycle_id = format!("cycle-{}", self.metrics.cycle_count);
455 if let Some(invocation) = self.metrics.agent_invocations.last_mut() {
456 invocation
457 .cycles
458 .push(AgentLoopMetricsData::new(cycle_id.clone(), 0, Usage::default()));
459 }
460 (cycle_id, tokio::time::Instant::now())
461 }
462
463 pub(crate) fn end_cycle(&mut self, start: tokio::time::Instant) {
465 let duration = elapsed_ms(start);
466 #[cfg(feature = "otel")]
467 self.instruments.cycle_duration.record(as_f64(duration), &[]);
468 self.metrics.total_duration = self.metrics.total_duration.saturating_add(duration);
469 if let Some(last) = self
470 .metrics
471 .agent_invocations
472 .last_mut()
473 .and_then(|invocation| invocation.cycles.last_mut())
474 {
475 last.duration = duration;
476 }
477 }
478
479 pub(crate) fn end_tool_call(&mut self, tool_name: &str, duration_ms: u64, success: bool) {
481 let index = match self.metrics.tool_metrics.iter().position(|(name, _)| name == tool_name) {
482 Some(index) => index,
483 None => {
484 self.metrics
485 .tool_metrics
486 .push((tool_name.to_owned(), ToolMetricsData::default()));
487 self.metrics.tool_metrics.len() - 1
488 }
489 };
490 let entry = &mut self.metrics.tool_metrics[index].1;
491 entry.call_count = entry.call_count.saturating_add(1);
492 entry.total_time = entry.total_time.saturating_add(duration_ms);
493 #[cfg(feature = "otel")]
494 let attributes = [opentelemetry::KeyValue::new("gen_ai.tool.name", tool_name.to_owned())];
495 #[cfg(feature = "otel")]
496 {
497 self.instruments.tool_call_count.add(1, &attributes);
498 self.instruments.tool_duration.record(as_f64(duration_ms), &attributes);
499 }
500 if success {
501 entry.success_count = entry.success_count.saturating_add(1);
502 } else {
503 entry.error_count = entry.error_count.saturating_add(1);
504 #[cfg(feature = "otel")]
505 self.instruments.tool_error_count.add(1, &attributes);
506 }
507 }
508
509 pub(crate) fn update_cycle(&mut self, usage: Option<&Usage>, metrics: Option<&Metrics>) {
511 if let Some(usage) = usage {
512 self.update_usage(usage);
513 }
514 let Some(metrics) = metrics else {
515 return;
516 };
517 let total = &mut self.metrics.accumulated_metrics.latency_ms;
518 *total = total.saturating_add(metrics.latency_ms);
519 #[cfg(feature = "otel")]
520 {
521 self.instruments.model_latency.record(as_f64(metrics.latency_ms), &[]);
522 if let Some(ttfb) = metrics.time_to_first_byte_ms.filter(|ttfb| *ttfb > 0) {
523 self.instruments.time_to_first_token.record(as_f64(ttfb) / 1000.0, &[]);
524 }
525 }
526 }
527
528 fn update_usage(&mut self, usage: &Usage) {
529 self.metrics.accumulated_usage.accumulate(usage);
530 let prompt = usage.total_prompt_tokens();
531 self.metrics.latest_context_size = Some(prompt);
532 self.metrics.projected_context_size = Some(prompt.saturating_add(usage.output_tokens));
533 #[cfg(feature = "otel")]
534 {
535 self.instruments.tokens_input.add(usage.input_tokens, &[]);
536 self.instruments.tokens_output.add(usage.output_tokens, &[]);
537 }
538 let Some(invocation) = self.metrics.agent_invocations.last_mut() else {
539 return;
540 };
541 invocation.usage.accumulate(usage);
542 if let Some(cycle) = invocation.cycles.last_mut() {
543 cycle.usage.accumulate(usage);
544 }
545 }
546}
547
548pub(crate) struct Cycle {
551 meter: Arc<Mutex<Meter>>,
552 start: tokio::time::Instant,
553 span: Option<LoopSpan>,
554}
555
556impl Cycle {
557 pub(crate) fn start(meter: &Arc<Mutex<Meter>>, tracer: &Arc<Tracer>, messages: &[Message]) -> Self {
559 let (cycle_id, start) = meter.lock().unwrap_or_else(PoisonError::into_inner).start_cycle();
560 let span = tracer.start_agent_loop_span(&cycle_id, messages);
561 Self {
562 meter: meter.clone(),
563 start,
564 span: Some(span),
565 }
566 }
567
568 pub(crate) fn close(&mut self, error: Option<&str>) {
570 let Some(span) = self.span.take() else {
571 return;
572 };
573 self.meter
574 .lock()
575 .unwrap_or_else(PoisonError::into_inner)
576 .end_cycle(self.start);
577 span.end(error);
578 }
579}
580
581impl Drop for Cycle {
582 fn drop(&mut self) {
583 self.close(None);
584 }
585}
586
587#[cfg(test)]
588mod tests {
589 use serde_json::json;
590
591 use super::*;
592
593 #[test]
594 fn serializes_in_the_ts_to_json_order() {
595 let metrics = AgentMetrics {
596 tool_metrics: vec![(
597 "calc".into(),
598 ToolMetricsData::default()
599 .with_call_count(2)
600 .with_success_count(1)
601 .with_error_count(1)
602 .with_total_time(30),
603 )],
604 ..AgentMetrics::new().with_latest_context_size(5)
605 };
606 let json = serde_json::to_string(&metrics).unwrap();
607 assert_eq!(
608 json,
609 r#"{"cycleCount":0,"accumulatedUsage":{"inputTokens":0,"outputTokens":0,"totalTokens":0},"accumulatedMetrics":{"latencyMs":0},"agentInvocations":[],"toolMetrics":{"calc":{"callCount":2,"successCount":1,"errorCount":1,"totalTime":30}},"totalDuration":0,"latestContextSize":5}"#
610 );
611 let restored: AgentMetrics = serde_json::from_str(&json).unwrap();
612 assert_eq!(restored, metrics);
613 }
614
615 #[test]
616 fn computes_averages() {
617 let metrics = AgentMetrics {
618 cycle_count: 4,
619 total_duration: 10,
620 tool_metrics: vec![(
621 "calc".into(),
622 ToolMetricsData::default()
623 .with_call_count(4)
624 .with_success_count(3)
625 .with_error_count(1)
626 .with_total_time(20),
627 )],
628 ..AgentMetrics::new()
629 };
630 assert!((metrics.average_cycle_time() - 2.5).abs() < f64::EPSILON);
631 let usage = metrics.tool_usage();
632 assert!((usage[0].1.average_time - 5.0).abs() < f64::EPSILON);
633 assert!((usage[0].1.success_rate - 0.75).abs() < f64::EPSILON);
634 assert_eq!(metrics.tool("calc").map(|m| m.call_count), Some(4));
635 assert!(AgentMetrics::new().latest_agent_invocation().is_none());
636 assert_eq!(json!(AgentMetrics::new().average_cycle_time()), json!(0.0));
637 }
638}