The platform for continuously improving AI agents.
use anyhow::Result;
use serde_json::Value;
use crate::{model::SpanRecord, semconv::GEN_AI_CONVERSATION_ID};
pub trait SpanSource: Send + Sync {
fn recent_spans(&self, since_received_ms: i64, limit: usize) -> Result<Vec<SpanRecord>>;
}
pub fn conversation_id(span: &SpanRecord) -> Option<String> {
span.attributes
.as_object()
.and_then(|attrs| attrs.get(GEN_AI_CONVERSATION_ID))
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(ToString::to_string)
}
pub fn group_key(span: &SpanRecord) -> String {
if let Some(id) = conversation_id(span) {
format!("conversation:{id}")
} else {
format!("trace:{}", span.trace_id)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::usage::SpanUsage;
fn sample_span(attrs: Value) -> SpanRecord {
SpanRecord {
span_id: "1111111111111111".into(),
trace_id: "0af7651916cd43dd8448eb211c80319c".into(),
parent_span_id: None,
name: "agent.run".into(),
kind: 1,
start_time_ns: 1_000,
end_time_ns: 2_000,
duration_ns: 1_000,
status_code: 0,
status_message: String::new(),
service_name: "svc".into(),
resource_attrs: json!({}),
scope_name: String::new(),
scope_version: String::new(),
attributes: attrs,
events: json!([]),
links: json!([]),
usage: SpanUsage::default(),
received_at_ms: 1_000,
}
}
#[test]
fn group_key_prefers_conversation_id_over_trace_id() {
let with_conv = sample_span(json!({ "gen_ai.conversation.id": "conv-42" }));
assert_eq!(group_key(&with_conv), "conversation:conv-42");
let blank_conv = sample_span(json!({ "gen_ai.conversation.id": " " }));
assert_eq!(
group_key(&blank_conv),
"trace:0af7651916cd43dd8448eb211c80319c"
);
let no_conv = sample_span(json!({}));
assert_eq!(group_key(&no_conv), "trace:0af7651916cd43dd8448eb211c80319c");
}
}