Skip to main content

telemetry/
model.rs

1//! A `Model` that reports what the calls no turn made have cost.
2//!
3//! `api_request` was emitted from one place, inside the turn loop, so it
4//! described exactly the calls a turn makes and nothing else. The engine
5//! makes others: it extracts memories once a turn is over, summarizes for
6//! compaction, answers a `"type": "prompt"` hook, classifies an intent. Every
7//! one of them is a real request to a real provider that somebody pays for,
8//! and a host reading this telemetry saw none of them — a session with memory
9//! enabled undercounted by one call per turn, silently.
10//!
11//! They cannot be reported from where they are made. Two of those call sites
12//! live in `base`, which cannot depend on this crate, and threading a handle
13//! to each one would leave the next one to be added unreported again. What
14//! they have in common is the model they call, so that is where the counting
15//! goes: one decorator, and any call carrying an auxiliary [`CallOrigin`] is
16//! accounted for by the fact that it happened.
17//!
18//! The turn's own calls stay with the turn loop. It knows things this does
19//! not — which turn, how many messages went out, how many tools were offered
20//! — and an event reported from both places would be counted twice. Which is
21//! also the rule for wrapping: exactly once, around the model a session was
22//! built with. A model fetched from somewhere else — the task router hands
23//! out pool-level ones, shared and built before any session existed — is
24//! outside that wrapping and has to be wrapped by whoever fetched it. There
25//! is one such fetcher, `runtime::agent::Agent::model_for_task`.
26
27use std::sync::Arc;
28use std::time::Instant;
29
30use base::interface::model::{
31    CallKind, Model, ModelError, ModelEvent, ModelMessage, ModelStream, StreamParams, ToolDef,
32};
33use base::prompt::PromptBlock;
34use base::provider::ApiType;
35use futures::StreamExt;
36use tokio_util::sync::CancellationToken;
37
38use crate::events::{ApiRequestPayload, TelemetryEvent};
39use crate::handle::TelemetryHandle;
40
41pub struct TelemetryModel {
42    inner: Arc<dyn Model>,
43    handle: TelemetryHandle,
44    /// The model this session was configured with, so a call that went
45    /// somewhere else can say so. Auxiliary work often does — memory
46    /// extraction runs on a small one on purpose.
47    configured_model: String,
48}
49
50impl TelemetryModel {
51    pub fn new(inner: Arc<dyn Model>, handle: TelemetryHandle, configured_model: String) -> Self {
52        Self {
53            inner,
54            handle,
55            configured_model,
56        }
57    }
58}
59
60#[async_trait::async_trait]
61impl Model for TelemetryModel {
62    fn api_type(&self) -> ApiType {
63        self.inner.api_type()
64    }
65
66    fn provenance(&self) -> Option<String> {
67        self.inner.provenance()
68    }
69
70    async fn stream(
71        &self,
72        prompt_blocks: Vec<PromptBlock>,
73        tools: Vec<ToolDef>,
74        messages: Vec<ModelMessage>,
75        params: StreamParams,
76        cancel: CancellationToken,
77    ) -> Result<ModelStream, ModelError> {
78        let auxiliary = params
79            .origin
80            .as_ref()
81            .and_then(|origin| match &origin.kind {
82                CallKind::Auxiliary { purpose } => {
83                    Some((origin.session_id.clone(), purpose.clone()))
84                }
85                _ => None,
86            });
87        let Some((session_id, purpose)) = auxiliary else {
88            return self
89                .inner
90                .stream(prompt_blocks, tools, messages, params, cancel)
91                .await;
92        };
93
94        let started = Instant::now();
95        let model = params.model.clone();
96        let default_model = model == self.configured_model;
97        let message_count = messages.len();
98        let tool_count = tools.len();
99        let stream = self
100            .inner
101            .stream(prompt_blocks, tools, messages, params, cancel)
102            .await?;
103
104        // The event is emitted from inside the stream because that is where
105        // the answer is: usage arrives on the last event, and a caller that
106        // abandons the stream early never gets one — the same call would then
107        // be reported by the turn loop as having spent nothing either.
108        let handle = self.handle.clone();
109        let mut truncated = false;
110        let observed = stream.map(move |item| {
111            if let Ok(ModelEvent::Truncated) = &item {
112                truncated = true;
113            }
114            if let Ok(ModelEvent::EndTurn { stop_reason, usage }) = &item {
115                let _ = handle.record(TelemetryEvent::api_request(
116                    &session_id,
117                    0,
118                    None,
119                    ApiRequestPayload {
120                        model: model.clone(),
121                        input_tokens: usage.input_tokens as u64,
122                        output_tokens: usage.output_tokens as u64,
123                        cache_creation_tokens: usage.cache_creation_input_tokens as u64,
124                        cache_read_tokens: usage.cache_read_input_tokens as u64,
125                        latency_ms: started.elapsed().as_millis() as u64,
126                        stop_reason: stop_reason.clone(),
127                        input_message_count: message_count,
128                        tool_count,
129                        default_model,
130                        purpose: Some(purpose.clone()),
131                        truncated,
132                    },
133                ));
134            }
135            item
136        });
137        Ok(Box::new(Box::pin(observed)))
138    }
139}