use std::time::Instant;
use opentelemetry::KeyValue;
use opentelemetry::metrics::{Counter, Histogram, Meter};
use tracing::Subscriber;
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing_subscriber::Layer;
use tracing_subscriber::layer::Context;
use tracing_subscriber::registry::{LookupSpan, SpanRef};
const DURATION_BUCKETS: [f64; 14] = [
0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92,
];
const TOKEN_BUCKETS: [f64; 14] = [
1.0, 4.0, 16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0, 262144.0, 1048576.0, 4194304.0,
16777216.0, 67108864.0,
];
pub(crate) struct GenAiMetrics {
duration: Histogram<f64>,
tokens: Histogram<u64>,
extra_tokens: Histogram<u64>,
tool_calls: Counter<u64>,
tool_successes: Counter<u64>,
tool_errors: Counter<u64>,
tool_duration: Histogram<f64>,
requests: Counter<u64>,
request_duration: Histogram<f64>,
}
impl GenAiMetrics {
pub(crate) fn new(meter: &Meter) -> Self {
Self {
duration: meter
.f64_histogram("gen_ai.client.operation.duration")
.with_unit("s")
.with_description("GenAI operation duration")
.with_boundaries(DURATION_BUCKETS.to_vec())
.build(),
tokens: meter
.u64_histogram("gen_ai.client.token.usage")
.with_unit("{token}")
.with_description("Number of input and output tokens used")
.with_boundaries(TOKEN_BUCKETS.to_vec())
.build(),
extra_tokens: meter
.u64_histogram("rig.token.usage")
.with_unit("{token}")
.with_description(
"Cached input and reasoning tokens, by rig.token.type. Subsets of the input and output tokens, not added to them",
)
.with_boundaries(TOKEN_BUCKETS.to_vec())
.build(),
tool_calls: meter
.u64_counter("rig.tool.call_count")
.with_unit("{call}")
.with_description("Tool calls, one per execute_tool span")
.build(),
tool_successes: meter
.u64_counter("rig.tool.success_count")
.with_unit("{call}")
.with_description("Tool calls that returned a result")
.build(),
tool_errors: meter
.u64_counter("rig.tool.error_count")
.with_unit("{call}")
.with_description("Tool calls that failed")
.build(),
tool_duration: meter
.f64_histogram("rig.tool.duration")
.with_unit("s")
.with_description("Tool call duration")
.with_boundaries(DURATION_BUCKETS.to_vec())
.build(),
requests: meter
.u64_counter("rig.model.request_count")
.with_unit("{request}")
.with_description("Model request attempts (chat spans) made by the agent")
.build(),
request_duration: meter
.f64_histogram("rig.model.request_duration")
.with_unit("s")
.with_description("Duration of each model request attempt (chat span)")
.with_boundaries(DURATION_BUCKETS.to_vec())
.build(),
}
}
}
#[derive(Default)]
struct Operation {
started: Option<Instant>,
name: Option<String>,
provider: Option<String>,
model: Option<String>,
agent: Option<String>,
tool: Option<String>,
outcome: Option<String>,
tool_error: Option<String>,
error: Option<String>,
input_tokens: Option<u64>,
output_tokens: Option<u64>,
cache_read_tokens: Option<u64>,
cache_creation_tokens: Option<u64>,
reasoning_tokens: Option<u64>,
}
impl Operation {
fn set(&mut self, field: &str, value: String) {
match field {
"gen_ai.operation.name" => self.name = Some(value),
"gen_ai.provider.name" => self.provider = Some(value),
"gen_ai.request.model" => self.model = Some(value),
"gen_ai.agent.name" => self.agent = Some(value),
"gen_ai.tool.name" => self.tool = Some(value),
"gen_ai.tool.call.outcome" => self.outcome = Some(value),
"gen_ai.tool.error.type" => self.tool_error = Some(value),
"error.type" => self.error = Some(value),
"gen_ai.usage.input_tokens" => self.input_tokens = value.parse().ok(),
"gen_ai.usage.output_tokens" => self.output_tokens = value.parse().ok(),
"gen_ai.usage.cache_read.input_tokens" => self.cache_read_tokens = value.parse().ok(),
"gen_ai.usage.cache_creation.input_tokens" => {
self.cache_creation_tokens = value.parse().ok();
}
"gen_ai.usage.reasoning_tokens" => self.reasoning_tokens = value.parse().ok(),
_ => {}
}
}
fn attributes(&self) -> Vec<KeyValue> {
let fields = [
("gen_ai.operation.name", &self.name),
("gen_ai.provider.name", &self.provider),
("gen_ai.request.model", &self.model),
("gen_ai.tool.name", &self.tool),
("error.type", &self.error),
];
fields
.into_iter()
.filter_map(|(key, value)| {
value
.as_ref()
.map(|value| KeyValue::new(key, value.clone()))
})
.collect()
}
}
impl Visit for Operation {
fn record_str(&mut self, field: &Field, value: &str) {
self.set(field.name(), value.to_owned());
}
fn record_u64(&mut self, field: &Field, value: u64) {
self.set(field.name(), value.to_string());
}
fn record_i64(&mut self, field: &Field, value: i64) {
self.set(field.name(), value.to_string());
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
let text = format!("{value:?}");
self.set(field.name(), text.trim_matches('"').to_owned());
}
}
fn is_model_call(name: &str) -> bool {
matches!(
name,
"chat"
| "text_completion"
| "generate_content"
| "embeddings"
| "rerank"
| "transcription"
| "image_generation"
| "audio_generation"
)
}
fn enclosing_agent<R>(span: &SpanRef<'_, R>) -> Option<String>
where
R: for<'a> LookupSpan<'a>,
{
span.scope().skip(1).find_map(|ancestor| {
ancestor
.extensions()
.get::<Operation>()
.and_then(|operation| operation.agent.clone())
})
}
impl<S> Layer<S> for GenAiMetrics
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
let mut operation = Operation::default();
attrs.record(&mut operation);
if let Some(span) = ctx.span(id) {
operation.started = Some(Instant::now());
span.extensions_mut().insert(operation);
}
}
fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
if let Some(span) = ctx.span(id)
&& let Some(operation) = span.extensions_mut().get_mut::<Operation>()
{
values.record(operation);
}
}
fn on_close(&self, id: Id, ctx: Context<'_, S>) {
let Some(span) = ctx.span(&id) else {
return;
};
let Some(operation) = span.extensions_mut().remove::<Operation>() else {
return;
};
let (Some(name), Some(started)) = (&operation.name, operation.started) else {
return;
};
let elapsed = started.elapsed().as_secs_f64();
let attributes = operation.attributes();
self.duration.record(elapsed, &attributes);
if is_model_call(name) {
for (kind, count) in [
("input", operation.input_tokens),
("output", operation.output_tokens),
] {
if let Some(count) = count {
let mut attributes = attributes.clone();
attributes.push(KeyValue::new("gen_ai.token.type", kind));
self.tokens.record(count, &attributes);
}
}
}
let mut labels = Vec::new();
if let Some(agent) = operation.agent.clone().or_else(|| enclosing_agent(&span)) {
labels.push(KeyValue::new("gen_ai.agent.name", agent));
}
match name.as_str() {
"execute_tool" => {
if let Some(tool) = &operation.tool {
labels.push(KeyValue::new("gen_ai.tool.name", tool.clone()));
}
self.tool_calls.add(1, &labels);
let mut duration_labels = labels.clone();
match operation.outcome.as_deref() {
Some("success") => self.tool_successes.add(1, &labels),
Some("error") => {
let kind = operation
.tool_error
.clone()
.unwrap_or_else(|| "error".to_owned());
let mut failure = labels.clone();
failure.push(KeyValue::new("error.type", kind.clone()));
self.tool_errors.add(1, &failure);
duration_labels.push(KeyValue::new("error.type", kind));
}
_ => {}
}
self.tool_duration.record(elapsed, &duration_labels);
}
"chat" => {
for (kind, count) in [
("cache_read", operation.cache_read_tokens),
("cache_creation", operation.cache_creation_tokens),
("reasoning", operation.reasoning_tokens),
] {
if let Some(count) = count {
let mut attributes = attributes.clone();
attributes.push(KeyValue::new("rig.token.type", kind));
self.extra_tokens.record(count, &attributes);
}
}
self.requests.add(1, &labels);
self.request_duration.record(elapsed, &labels);
}
_ => {}
}
}
}