Skip to main content

artifactize_core/agent/session/
summary.rs

1//! `session show --summary`: what a saved conversation spent and did, computed from its
2//! session file alone.
3
4use std::collections::BTreeMap;
5
6use rig_core::message::{AssistantContent, Message, UserContent};
7use serde::Serialize;
8
9use super::Conversation;
10
11/// A saved conversation's backend, time span, turns, tokens and tool calls.
12#[derive(Debug, Serialize)]
13#[serde(rename_all = "camelCase")]
14pub struct Summary {
15    pub backend: Option<crate::config::Backend>,
16    pub model: Option<crate::config::ModelId>,
17    pub reasoning: Option<crate::config::Reasoning>,
18    /// The first and last event's time.
19    pub started_at: Option<crate::types::Timestamp>,
20    pub ended_at: Option<crate::types::Timestamp>,
21    #[serde(serialize_with = "crate::config::validation::milliseconds::serialize")]
22    pub duration_ms: Option<std::time::Duration>,
23    pub follow_ups: usize,
24    /// Every provider turn in order: the review's, then each follow-up's.
25    pub turns: Vec<Turn>,
26    /// The reported token counters of every attempt, summed.
27    pub tokens: BTreeMap<String, u64>,
28    /// By tool name.
29    pub tool_calls: BTreeMap<crate::types::CalledTool, ToolCalls>,
30}
31
32/// One provider request and its attempts.
33#[derive(Debug, Serialize)]
34#[serde(rename_all = "camelCase")]
35pub struct Turn {
36    /// The follow-up the turn answered; absent for the review's turns.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub follow_up: Option<u64>,
39    pub turn: u64,
40    pub attempts: u64,
41    /// The reported token counters of its attempts, summed.
42    pub tokens: BTreeMap<String, u64>,
43}
44
45#[derive(Debug, Default, Serialize)]
46pub struct ToolCalls {
47    pub calls: u64,
48    /// Calls whose result was an error, and calls never answered because the review or
49    /// follow-up stopped first.
50    pub failed: u64,
51}
52
53impl Summary {
54    pub fn new(conversation: &Conversation) -> Self {
55        let header = conversation.header();
56
57        let (started_at, ended_at) = (
58            conversation.header_at,
59            conversation
60                .events()
61                .last()
62                .map_or(conversation.header_at, |event| event.at),
63        );
64        let duration_ms = started_at
65            .zip(ended_at)
66            .map(|(start, end)| end.since(start));
67        let mut summary = Self {
68            backend: header.backend.clone(),
69            model: header.model.clone(),
70            reasoning: header.reasoning,
71            started_at,
72            ended_at,
73            duration_ms,
74            follow_ups: conversation.sends(),
75            turns: Vec::new(),
76            tokens: BTreeMap::new(),
77            tool_calls: BTreeMap::new(),
78        };
79        // Calls by tool, then the results that answered them and those that failed.
80        let mut answered = BTreeMap::<crate::types::CalledTool, (u64, u64)>::new();
81        for event in conversation.events() {
82            match &event.kind {
83                super::Kind::Attempt(attempt) => summary.attempt(event.send, attempt),
84                super::Kind::Message(event) => match event.message() {
85                    Message::Assistant { content, .. } => {
86                        for part in content {
87                            if let AssistantContent::ToolCall(call) = part {
88                                let name =
89                                    crate::types::CalledTool::called(call.function.name.as_str());
90                                summary.tool_calls.entry(name).or_default().calls += 1;
91                            }
92                        }
93                    }
94                    Message::User { content } => {
95                        let results = content.iter().filter_map(|part| match part {
96                            UserContent::ToolResult(result) => Some(result),
97                            _ => None,
98                        });
99                        for (index, result) in results.enumerate() {
100                            let (count, failed) = answered
101                                .entry(crate::types::CalledTool::called(result.name.as_str()))
102                                .or_default();
103                            *count += 1;
104                            *failed += u64::from(event.is_error.get(index) == Some(&true));
105                        }
106                    }
107                    Message::System { .. } => {}
108                },
109                _ => {}
110            }
111        }
112        for (name, calls) in &mut summary.tool_calls {
113            let (count, failed) = answered.get(name).copied().unwrap_or_default();
114            calls.failed = failed + calls.calls.saturating_sub(count);
115        }
116        summary
117    }
118
119    /// Count an attempt in its turn and in the totals.
120    fn attempt(&mut self, send: Option<usize>, attempt: &crate::llm::Attempt) {
121        let follow_up = send.map(|send| send as u64);
122        let turn = attempt.turn as u64;
123        if self
124            .turns
125            .last()
126            .is_none_or(|last| (last.follow_up, last.turn) != (follow_up, turn))
127        {
128            self.turns.push(Turn {
129                follow_up,
130                turn,
131                attempts: 0,
132                tokens: BTreeMap::new(),
133            });
134        }
135        let current = self.turns.last_mut().expect("the attempt's turn");
136        current.attempts += 1;
137        for (name, value) in attempt.usage.iter() {
138            for tokens in [&mut current.tokens, &mut self.tokens] {
139                let total = tokens.entry(name.clone()).or_default();
140                *total = total.saturating_add(*value);
141            }
142        }
143    }
144}
145
146/// Token counters as text, in a fixed order with readable names; `None` without any.
147pub fn tokens_text(tokens: &BTreeMap<String, u64>) -> Option<String> {
148    let parts: Vec<_> = [
149        ("inputTokens", "input"),
150        ("outputTokens", "output"),
151        ("cacheReadTokens", "cache read"),
152        ("cacheWriteTokens", "cache write"),
153        ("reasoningTokens", "reasoning"),
154    ]
155    .into_iter()
156    .filter_map(|(name, label)| Some(format!("{label} {}", tokens.get(name)?)))
157    .collect();
158    (!parts.is_empty()).then(|| parts.join(" ยท "))
159}
160
161#[cfg(test)]
162mod tests;