use std::collections::BTreeMap;
use rig_core::message::{AssistantContent, Message, UserContent};
use serde::Serialize;
use super::Conversation;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Summary {
pub backend: Option<crate::config::Backend>,
pub model: Option<crate::config::ModelId>,
pub reasoning: Option<crate::config::Reasoning>,
pub started_at: Option<crate::types::Timestamp>,
pub ended_at: Option<crate::types::Timestamp>,
#[serde(serialize_with = "crate::config::validation::milliseconds::serialize")]
pub duration_ms: Option<std::time::Duration>,
pub follow_ups: usize,
pub turns: Vec<Turn>,
pub tokens: BTreeMap<String, u64>,
pub tool_calls: BTreeMap<crate::types::CalledTool, ToolCalls>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Turn {
#[serde(skip_serializing_if = "Option::is_none")]
pub follow_up: Option<u64>,
pub turn: u64,
pub attempts: u64,
pub tokens: BTreeMap<String, u64>,
}
#[derive(Debug, Default, Serialize)]
pub struct ToolCalls {
pub calls: u64,
pub failed: u64,
}
impl Summary {
pub fn new(conversation: &Conversation) -> Self {
let header = conversation.header();
let (started_at, ended_at) = (
conversation.header_at,
conversation
.events()
.last()
.map_or(conversation.header_at, |event| event.at),
);
let duration_ms = started_at
.zip(ended_at)
.map(|(start, end)| end.since(start));
let mut summary = Self {
backend: header.backend.clone(),
model: header.model.clone(),
reasoning: header.reasoning,
started_at,
ended_at,
duration_ms,
follow_ups: conversation.sends(),
turns: Vec::new(),
tokens: BTreeMap::new(),
tool_calls: BTreeMap::new(),
};
let mut answered = BTreeMap::<crate::types::CalledTool, (u64, u64)>::new();
for event in conversation.events() {
match &event.kind {
super::Kind::Attempt(attempt) => summary.attempt(event.send, attempt),
super::Kind::Message(event) => match event.message() {
Message::Assistant { content, .. } => {
for part in content {
if let AssistantContent::ToolCall(call) = part {
let name =
crate::types::CalledTool::called(call.function.name.as_str());
summary.tool_calls.entry(name).or_default().calls += 1;
}
}
}
Message::User { content } => {
let results = content.iter().filter_map(|part| match part {
UserContent::ToolResult(result) => Some(result),
_ => None,
});
for (index, result) in results.enumerate() {
let (count, failed) = answered
.entry(crate::types::CalledTool::called(result.name.as_str()))
.or_default();
*count += 1;
*failed += u64::from(event.is_error.get(index) == Some(&true));
}
}
Message::System { .. } => {}
},
_ => {}
}
}
for (name, calls) in &mut summary.tool_calls {
let (count, failed) = answered.get(name).copied().unwrap_or_default();
calls.failed = failed + calls.calls.saturating_sub(count);
}
summary
}
fn attempt(&mut self, send: Option<usize>, attempt: &crate::llm::Attempt) {
let follow_up = send.map(|send| send as u64);
let turn = attempt.turn as u64;
if self
.turns
.last()
.is_none_or(|last| (last.follow_up, last.turn) != (follow_up, turn))
{
self.turns.push(Turn {
follow_up,
turn,
attempts: 0,
tokens: BTreeMap::new(),
});
}
let current = self.turns.last_mut().expect("the attempt's turn");
current.attempts += 1;
for (name, value) in attempt.usage.iter() {
for tokens in [&mut current.tokens, &mut self.tokens] {
let total = tokens.entry(name.clone()).or_default();
*total = total.saturating_add(*value);
}
}
}
}
pub fn tokens_text(tokens: &BTreeMap<String, u64>) -> Option<String> {
let parts: Vec<_> = [
("inputTokens", "input"),
("outputTokens", "output"),
("cacheReadTokens", "cache read"),
("cacheWriteTokens", "cache write"),
("reasoningTokens", "reasoning"),
]
.into_iter()
.filter_map(|(name, label)| Some(format!("{label} {}", tokens.get(name)?)))
.collect();
(!parts.is_empty()).then(|| parts.join(" ยท "))
}
#[cfg(test)]
mod tests;