Skip to main content

base/telemetry/
model.rs

1//! Model / LLM API events.
2
3use serde::Serialize;
4
5/// One completed model call: what it cost and what it was.
6///
7/// Emitted per call, which is what makes it the event a cost can be computed
8/// from — a turn is several calls, and every other number the engine reports is
9/// per turn.
10///
11/// No time-to-first-token and no retry count: the first is measured where the
12/// stream is consumed, not where a call is accounted for, and retries happen
13/// inside the client, under the model contract.
14#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
15pub struct ApiRequestPayload {
16    pub model: String,
17    pub input_tokens: u64,
18    pub output_tokens: u64,
19    /// Tokens this call wrote into the prompt cache, and tokens it read back
20    /// from it. Separate fields because they are separate prices — a read is
21    /// a fraction of ordinary input and a write is a premium on it.
22    pub cache_creation_tokens: u64,
23    pub cache_read_tokens: u64,
24    /// Wall clock for the whole call, request to last event.
25    pub latency_ms: u64,
26    pub stop_reason: String,
27    pub input_message_count: usize,
28    pub tool_count: usize,
29    /// Whether this call went to the model the session was configured with. A
30    /// fallback or a recovery switch makes it false.
31    pub default_model: bool,
32    /// What this call was for, when it was not a turn: extracting memories,
33    /// summarizing for compaction, answering a prompt hook. `None` is a call
34    /// the turn loop made, which is the common case and the one a reader
35    /// summing a turn's cost wants on its own.
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub purpose: Option<String>,
38    /// The provider closed the stream without marking the reply's end; what
39    /// arrived was taken as the whole reply.
40    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
41    pub truncated: bool,
42}
43
44/// A model call that failed: the provider refused it, or its stream broke
45/// before the reply was complete. Emitted once per failed attempt, whether
46/// or not the turn then recovers.
47#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
48pub struct ApiErrorPayload {
49    pub model: String,
50    /// `api`, `auth`, `rate_limited`, `overloaded`, `network`, `internal`,
51    /// `unsupported`.
52    pub error_kind: String,
53    /// The HTTP status, for an `api` error.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub http_status: Option<u16>,
56    pub error_message: String,
57    pub latency_ms: u64,
58}
59
60/// A model call that went to a different provider than the session's call
61/// before it.
62#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
63pub struct ProviderSwitchedPayload {
64    pub from: String,
65    pub to: String,
66    /// Why each provider before `to` in the order did not take the call; when
67    /// none was passed over, that `to` can take calls again.
68    pub reason: String,
69    /// `main`, `subagent`, `compact`, `memory`, `title`, `web_search`,
70    /// `web_fetch`.
71    pub task: String,
72}
73
74/// 会话 token 预算强制执行事件的载荷——`turn.token_budget` 90% 提醒注入
75/// 或 100% 硬停两种动作都用这个 payload,用 `action` 区分。
76#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
77pub struct BudgetEnforcedPayload {
78    pub action: BudgetEnforcedAction,
79    pub total_tokens_used: u64,
80    pub budget: u64,
81}
82
83#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, schemars::JsonSchema)]
84#[serde(rename_all = "snake_case")]
85#[non_exhaustive]
86pub enum BudgetEnforcedAction {
87    /// 达到 90% 阈值,向对话注入"请收尾"提醒,轮次继续。
88    WarningInjected,
89    /// 达到 100% 阈值,轮次被硬性中止。
90    TurnStopped,
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use crate::telemetry::TelemetryEvent;
97
98    #[test]
99    fn api_request_serializes() {
100        let event = TelemetryEvent::api_request(
101            "sess",
102            1,
103            None,
104            ApiRequestPayload {
105                model: "claude-sonnet-5".into(),
106                input_tokens: 1200,
107                output_tokens: 300,
108                cache_creation_tokens: 64,
109                cache_read_tokens: 900,
110                latency_ms: 2100,
111                stop_reason: "end_turn".into(),
112                input_message_count: 5,
113                tool_count: 12,
114                default_model: true,
115                purpose: None,
116                truncated: false,
117            },
118        );
119        assert_eq!(event.kind(), "api_request");
120        let v =
121            serde_json::to_value(event).expect("serialization of telemetry event should not fail");
122        assert_eq!(v["type"], "api_request");
123        assert_eq!(v["input_tokens"], 1200);
124        assert_eq!(v["cache_read_tokens"], 900);
125        assert!(v.get("truncated").is_none(), "{v}");
126    }
127
128    #[test]
129    fn budget_enforced_serializes_both_actions() {
130        for (action, expected) in [
131            (BudgetEnforcedAction::WarningInjected, "warning_injected"),
132            (BudgetEnforcedAction::TurnStopped, "turn_stopped"),
133        ] {
134            let event = TelemetryEvent::budget_enforced(
135                "sess",
136                3,
137                None,
138                BudgetEnforcedPayload {
139                    action,
140                    total_tokens_used: 950,
141                    budget: 1000,
142                },
143            );
144            assert_eq!(event.kind(), "budget_enforced");
145            let v = serde_json::to_value(event)
146                .expect("serialization of telemetry event should not fail");
147            assert_eq!(v["type"], "budget_enforced");
148            assert_eq!(v["action"], expected);
149            assert_eq!(v["budget"], 1000);
150        }
151    }
152}