Skip to main content

oxtel_genai/
lib.rs

1//! Spans and metrics for calls to generative AI models, as the
2//! OpenTelemetry GenAI semantic conventions describe them: a span for each
3//! call, how long it took, and the tokens it used. Part of
4//! [oxtel](https://github.com/agentstatelabs/oxtel).
5//!
6//! It works with any model client: say what the call is when it starts,
7//! make the call inside its span, and say how it went when it ends.
8//!
9//! ```
10//! # struct Reply { model: String, prompt_eval_count: u64, eval_count: u64 }
11//! # fn ollama_chat() -> Result<Reply, ()> {
12//! #     Ok(Reply { model: "llama3.2:latest".into(), prompt_eval_count: 26, eval_count: 298 })
13//! # }
14//! let call = oxtel_genai::chat("ollama", "llama3.2")
15//!     .server("localhost", 11434)
16//!     .temperature(0.2)
17//!     .start();
18//! // Make the call inside the span: in async code, `.instrument(call.span().clone())`.
19//! match call.span().in_scope(ollama_chat) {
20//!     Ok(reply) => call
21//!         .response_model(&reply.model)
22//!         .input_tokens(reply.prompt_eval_count)
23//!         .output_tokens(reply.eval_count)
24//!         .finish(),
25//!     Err(_) => call.fail("timeout"),
26//! }
27//! ```
28//!
29//! That records:
30//!
31//! - **A client span** named `chat llama3.2`, with `gen_ai.operation.name`,
32//!   `gen_ai.provider.name`, `gen_ai.request.model`, `server.address` and
33//!   `server.port`, the request's settings, and the response's model, id
34//!   and token counts. A failed call is an error, with `error.type`.
35//! - **`gen_ai.client.inference.duration`**, in seconds.
36//! - **Token usage**: `gen_ai.client.inference.usage.input_tokens` and
37//!   `.output_tokens`, counters by `gen_ai.token.modality` for totals and
38//!   cost, and `gen_ai.client.inference.operation.input_tokens` and
39//!   `.output_tokens`, histograms of the tokens each call used.
40//! - For a streamed response, with [`Call::chunk`] as each chunk arrives,
41//!   `gen_ai.client.inference.time_to_first_chunk` and
42//!   `gen_ai.client.inference.time_per_output_chunk`.
43//!
44//! An [`embeddings`] call isn't inference, so it records
45//! `gen_ai.client.operation.duration` instead, and its input tokens on its
46//! span only.
47//!
48//! **No prompt or completion content is recorded**: messages, system
49//! instructions and tool definitions can hold anything, and they're the
50//! conventions' opt-in attributes.
51//!
52//! Spans are recorded with `tracing` and metrics with `metrics`, so they go
53//! wherever the program's subscriber and recorder send them: with
54//! `oxtel::init()`, to OTLP or Prometheus, with the buckets the conventions
55//! advise. Arrays can't be `tracing` fields, so `gen_ai.response.finish_reasons`
56//! and `gen_ai.request.stop_sequences` aren't recorded. The GenAI
57//! conventions are still in development, so the names may change in a
58//! later release, as they do upstream.
59
60use std::fmt;
61use std::time::Instant;
62
63use metrics::Label;
64use tracing::Span;
65
66/// What a call asks of the model: `gen_ai.operation.name`.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum Operation {
70    /// A chat completion, such as OpenAI's Chat API or Ollama's `/api/chat`.
71    Chat,
72    /// A plain text completion, such as Ollama's `/api/generate`.
73    TextCompletion,
74    /// Multimodal content generation, such as Gemini's Generate Content.
75    GenerateContent,
76    /// Embeddings for some input.
77    Embeddings,
78}
79
80impl Operation {
81    /// The name the conventions give it, such as `chat`.
82    pub fn name(self) -> &'static str {
83        match self {
84            Operation::Chat => "chat",
85            Operation::TextCompletion => "text_completion",
86            Operation::GenerateContent => "generate_content",
87            Operation::Embeddings => "embeddings",
88        }
89    }
90
91    /// Inference generates output, and gets the `gen_ai.client.inference.*`
92    /// metrics; other operations get `gen_ai.client.operation.duration`.
93    fn is_inference(self) -> bool {
94        !matches!(self, Operation::Embeddings)
95    }
96}
97
98impl fmt::Display for Operation {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.write_str(self.name())
101    }
102}
103
104/// What kind of input or output tokens are: `gen_ai.token.modality`.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106#[non_exhaustive]
107pub enum Modality {
108    /// Text tokens.
109    Text,
110    /// Image tokens.
111    Image,
112    /// Audio tokens.
113    Audio,
114    /// Tokens of a kind the provider doesn't say.
115    Unknown,
116}
117
118impl Modality {
119    const ALL: [Modality; 4] = [
120        Modality::Text,
121        Modality::Image,
122        Modality::Audio,
123        Modality::Unknown,
124    ];
125
126    /// The name the conventions give it, such as `text`.
127    pub fn name(self) -> &'static str {
128        match self {
129            Modality::Text => "text",
130            Modality::Image => "image",
131            Modality::Audio => "audio",
132            Modality::Unknown => "unknown",
133        }
134    }
135}
136
137/// A chat completion call to `model` from `provider`, such as `openai`,
138/// `anthropic`, `gcp.gemini` or `ollama`: see
139/// [`gen_ai.provider.name`](https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/)
140/// for the names the conventions know.
141pub fn chat(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
142    CallBuilder::new(Operation::Chat, provider, model)
143}
144
145/// A text completion call.
146pub fn text_completion(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
147    CallBuilder::new(Operation::TextCompletion, provider, model)
148}
149
150/// A multimodal content generation call.
151pub fn generate_content(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
152    CallBuilder::new(Operation::GenerateContent, provider, model)
153}
154
155/// An embeddings call.
156pub fn embeddings(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
157    CallBuilder::new(Operation::Embeddings, provider, model)
158}
159
160/// A model call about to be made. Each setting is recorded on the span, as
161/// the conventions name it; leave out what the request doesn't set.
162#[derive(Clone, Debug)]
163#[must_use = "a call is recorded only once it's started"]
164pub struct CallBuilder {
165    operation: Operation,
166    provider: String,
167    model: String,
168    server: Option<(String, u16)>,
169    max_tokens: Option<i64>,
170    temperature: Option<f64>,
171    top_p: Option<f64>,
172    top_k: Option<i64>,
173    frequency_penalty: Option<f64>,
174    presence_penalty: Option<f64>,
175    seed: Option<i64>,
176    choices: Option<i64>,
177    stream: bool,
178    conversation_id: Option<String>,
179}
180
181impl CallBuilder {
182    /// A call for `operation` to `model` from `provider`.
183    pub fn new(
184        operation: Operation,
185        provider: impl Into<String>,
186        model: impl Into<String>,
187    ) -> CallBuilder {
188        CallBuilder {
189            operation,
190            provider: provider.into(),
191            model: model.into(),
192            server: None,
193            max_tokens: None,
194            temperature: None,
195            top_p: None,
196            top_k: None,
197            frequency_penalty: None,
198            presence_penalty: None,
199            seed: None,
200            choices: None,
201            stream: false,
202            conversation_id: None,
203        }
204    }
205
206    /// The host and port the call goes to: `server.address` and
207    /// `server.port`.
208    pub fn server(mut self, address: impl Into<String>, port: u16) -> Self {
209        self.server = Some((address.into(), port));
210        self
211    }
212
213    /// `gen_ai.request.max_tokens`.
214    pub fn max_tokens(mut self, tokens: u32) -> Self {
215        self.max_tokens = Some(tokens.into());
216        self
217    }
218
219    /// `gen_ai.request.temperature`.
220    pub fn temperature(mut self, temperature: f64) -> Self {
221        self.temperature = Some(temperature);
222        self
223    }
224
225    /// `gen_ai.request.top_p`.
226    pub fn top_p(mut self, top_p: f64) -> Self {
227        self.top_p = Some(top_p);
228        self
229    }
230
231    /// `gen_ai.request.top_k`.
232    pub fn top_k(mut self, top_k: u32) -> Self {
233        self.top_k = Some(top_k.into());
234        self
235    }
236
237    /// `gen_ai.request.frequency_penalty`.
238    pub fn frequency_penalty(mut self, penalty: f64) -> Self {
239        self.frequency_penalty = Some(penalty);
240        self
241    }
242
243    /// `gen_ai.request.presence_penalty`.
244    pub fn presence_penalty(mut self, penalty: f64) -> Self {
245        self.presence_penalty = Some(penalty);
246        self
247    }
248
249    /// `gen_ai.request.seed`.
250    pub fn seed(mut self, seed: i64) -> Self {
251        self.seed = Some(seed);
252        self
253    }
254
255    /// How many candidate responses the request asks for:
256    /// `gen_ai.request.choice.count`, recorded unless it's 1.
257    pub fn choices(mut self, count: u32) -> Self {
258        self.choices = (count != 1).then_some(count.into());
259        self
260    }
261
262    /// The response is streamed: `gen_ai.request.stream`. Call
263    /// [`Call::chunk`] as each chunk arrives.
264    pub fn streamed(mut self) -> Self {
265        self.stream = true;
266        self
267    }
268
269    /// The conversation the call belongs to: `gen_ai.conversation.id`.
270    pub fn conversation_id(mut self, id: impl Into<String>) -> Self {
271        self.conversation_id = Some(id.into());
272        self
273    }
274
275    /// Starts the call's span and clock. Make the call inside the span.
276    pub fn start(self) -> Call {
277        describe_metrics();
278        let operation = self.operation;
279        let (address, port) = match &self.server {
280            Some((address, port)) => (Some(address.as_str()), Some(*port)),
281            None => (None, None),
282        };
283        let span = tracing::info_span!(
284            target: "oxtel_genai",
285            "GenAI client call",
286            otel.name = format!("{} {}", operation.name(), self.model),
287            otel.kind = "client",
288            gen_ai.operation.name = operation.name(),
289            gen_ai.provider.name = self.provider.as_str(),
290            gen_ai.request.model = self.model.as_str(),
291            server.address = address,
292            server.port = port,
293            gen_ai.request.max_tokens = self.max_tokens,
294            gen_ai.request.temperature = self.temperature,
295            gen_ai.request.top_p = self.top_p,
296            gen_ai.request.top_k = self.top_k,
297            gen_ai.request.frequency_penalty = self.frequency_penalty,
298            gen_ai.request.presence_penalty = self.presence_penalty,
299            gen_ai.request.seed = self.seed,
300            gen_ai.request.choice.count = self.choices,
301            gen_ai.request.stream = self.stream.then_some(true),
302            gen_ai.conversation.id = self.conversation_id.as_deref(),
303            gen_ai.response.id = tracing::field::Empty,
304            gen_ai.response.model = tracing::field::Empty,
305            gen_ai.response.time_to_first_chunk = tracing::field::Empty,
306            gen_ai.usage.input_tokens = tracing::field::Empty,
307            gen_ai.usage.output_tokens = tracing::field::Empty,
308            gen_ai.embeddings.dimension.count = tracing::field::Empty,
309            error.type = tracing::field::Empty,
310            otel.status_code = tracing::field::Empty,
311        );
312        let mut labels = vec![
313            Label::new("gen_ai.operation.name", operation.name()),
314            Label::new("gen_ai.provider.name", self.provider),
315            Label::new("gen_ai.request.model", self.model),
316        ];
317        if let Some((address, port)) = self.server {
318            labels.push(Label::new("server.address", address));
319            labels.push(Label::new("server.port", port.to_string()));
320        }
321        Call {
322            span,
323            started: Instant::now(),
324            operation,
325            labels,
326            response_model: None,
327            input: Tokens::default(),
328            output: Tokens::default(),
329            last_chunk: None,
330        }
331    }
332}
333
334/// Token counts by modality, and whether any were given.
335#[derive(Debug, Default)]
336struct Tokens {
337    counts: [u64; 4],
338    known: bool,
339}
340
341impl Tokens {
342    fn add(&mut self, modality: Modality, tokens: u64) {
343        let i = Modality::ALL
344            .iter()
345            .position(|m| *m == modality)
346            .expect("every modality is in ALL");
347        self.counts[i] += tokens;
348        self.known = true;
349    }
350
351    fn total(&self) -> Option<u64> {
352        self.known.then(|| self.counts.iter().sum())
353    }
354
355    fn by_modality(&self) -> impl Iterator<Item = (Modality, u64)> + '_ {
356        Modality::ALL
357            .into_iter()
358            .zip(self.counts)
359            .filter(|&(_, n)| n > 0)
360    }
361}
362
363/// A model call under way. Say how it went with [`finish`](Call::finish)
364/// or [`fail`](Call::fail); a call dropped without either, as when its
365/// future is cancelled, ends its span without a status and records no
366/// metrics.
367#[derive(Debug)]
368#[must_use = "a call records its metrics when it finishes or fails"]
369pub struct Call {
370    span: Span,
371    started: Instant,
372    operation: Operation,
373    /// The labels every metric of the call has.
374    labels: Vec<Label>,
375    response_model: Option<String>,
376    input: Tokens,
377    output: Tokens,
378    last_chunk: Option<Instant>,
379}
380
381impl Call {
382    /// The call's span. Make the call inside it, so what the client logs
383    /// and the HTTP request it makes are part of it.
384    pub fn span(&self) -> &Span {
385        &self.span
386    }
387
388    /// A chunk of a streamed response arrived. The first records
389    /// `gen_ai.response.time_to_first_chunk` and
390    /// `gen_ai.client.inference.time_to_first_chunk`, and each later one
391    /// `gen_ai.client.inference.time_per_output_chunk`.
392    pub fn chunk(&mut self) {
393        let now = Instant::now();
394        let labels = self.metric_labels(None);
395        match self.last_chunk.replace(now) {
396            None => {
397                let seconds = (now - self.started).as_secs_f64();
398                self.span
399                    .record("gen_ai.response.time_to_first_chunk", seconds);
400                metrics::histogram!("gen_ai.client.inference.time_to_first_chunk", labels)
401                    .record(seconds);
402            }
403            Some(previous) => {
404                metrics::histogram!("gen_ai.client.inference.time_per_output_chunk", labels)
405                    .record((now - previous).as_secs_f64());
406            }
407        }
408    }
409
410    /// The id the provider gave the response: `gen_ai.response.id`.
411    pub fn response_id(self, id: &str) -> Self {
412        self.span.record("gen_ai.response.id", id);
413        self
414    }
415
416    /// The model that answered, which can be more exact than the one asked
417    /// for, such as `llama3.2:latest`: `gen_ai.response.model`.
418    pub fn response_model(mut self, model: &str) -> Self {
419        self.span.record("gen_ai.response.model", model);
420        self.response_model = Some(model.to_string());
421        self
422    }
423
424    /// The input tokens the call used, as text. When the provider reports
425    /// both used and billable tokens, give the billable ones.
426    pub fn input_tokens(self, tokens: u64) -> Self {
427        self.input_tokens_of(Modality::Text, tokens)
428    }
429
430    /// The input tokens of one modality the call used. Calls for different
431    /// modalities add up.
432    pub fn input_tokens_of(mut self, modality: Modality, tokens: u64) -> Self {
433        self.input.add(modality, tokens);
434        self
435    }
436
437    /// The output tokens the call used, as text, including any spent on
438    /// reasoning.
439    pub fn output_tokens(self, tokens: u64) -> Self {
440        self.output_tokens_of(Modality::Text, tokens)
441    }
442
443    /// The output tokens of one modality the call used. Calls for different
444    /// modalities add up.
445    pub fn output_tokens_of(mut self, modality: Modality, tokens: u64) -> Self {
446        self.output.add(modality, tokens);
447        self
448    }
449
450    /// How many dimensions each embedding has:
451    /// `gen_ai.embeddings.dimension.count`.
452    pub fn dimensions(self, count: u64) -> Self {
453        self.span.record("gen_ai.embeddings.dimension.count", count);
454        self
455    }
456
457    /// The call succeeded: records its duration and token usage.
458    pub fn finish(self) {
459        self.end(None);
460    }
461
462    /// The call failed. `error_type` says why, in few enough words to be a
463    /// metric label: the provider's error code, such as
464    /// `rate_limit_exceeded`, an HTTP status such as `429`, or `timeout`.
465    /// Token counts given before failing are still recorded.
466    pub fn fail(self, error_type: &str) {
467        self.end(Some(error_type));
468    }
469
470    /// The labels of the call's metrics: what it was, what answered, and
471    /// how it failed if it did.
472    fn metric_labels(&self, error: Option<&str>) -> Vec<Label> {
473        let mut labels = self.labels.clone();
474        if let Some(model) = &self.response_model {
475            labels.push(Label::new("gen_ai.response.model", model.clone()));
476        }
477        if let Some(error) = error {
478            labels.push(Label::new("error.type", error.to_string()));
479        }
480        labels
481    }
482
483    fn end(self, error: Option<&str>) {
484        let elapsed = self.started.elapsed().as_secs_f64();
485        if let Some(tokens) = self.input.total() {
486            self.span.record("gen_ai.usage.input_tokens", tokens);
487        }
488        if let Some(tokens) = self.output.total() {
489            self.span.record("gen_ai.usage.output_tokens", tokens);
490        }
491        if let Some(error) = error {
492            self.span.record("error.type", error);
493            self.span.record("otel.status_code", "error");
494        }
495        let labels = self.metric_labels(error);
496        if !self.operation.is_inference() {
497            metrics::histogram!("gen_ai.client.operation.duration", labels).record(elapsed);
498            return;
499        }
500        metrics::histogram!("gen_ai.client.inference.duration", labels.clone()).record(elapsed);
501        // Token usage only when the call says what it used: the conventions
502        // forbid reporting counts that can't be had.
503        for (tokens, histogram, counter) in [
504            (
505                &self.input,
506                "gen_ai.client.inference.operation.input_tokens",
507                "gen_ai.client.inference.usage.input_tokens",
508            ),
509            (
510                &self.output,
511                "gen_ai.client.inference.operation.output_tokens",
512                "gen_ai.client.inference.usage.output_tokens",
513            ),
514        ] {
515            let Some(total) = tokens.total() else {
516                continue;
517            };
518            metrics::histogram!(histogram, labels.clone()).record(total as f64);
519            // The usage counters have no error.type.
520            let usage = self.metric_labels(None);
521            for (modality, count) in tokens.by_modality() {
522                let mut usage = usage.clone();
523                usage.push(Label::new("gen_ai.token.modality", modality.name()));
524                metrics::counter!(counter, usage).increment(count);
525            }
526        }
527    }
528}
529
530/// Gives the current `metrics` recorder the units and descriptions of the
531/// GenAI client metrics, so durations are in seconds with the conventions'
532/// buckets. [`CallBuilder::start`] does this each time, so there's no need
533/// to call it yourself.
534pub fn describe_metrics() {
535    for (name, description) in [
536        (
537            "gen_ai.client.inference.duration",
538            "GenAI client inference operation duration.",
539        ),
540        (
541            "gen_ai.client.operation.duration",
542            "GenAI operation duration.",
543        ),
544        (
545            "gen_ai.client.inference.time_to_first_chunk",
546            "Time to receive the first chunk of a streamed response.",
547        ),
548        (
549            "gen_ai.client.inference.time_per_output_chunk",
550            "Time per output chunk, after the first.",
551        ),
552    ] {
553        metrics::describe_histogram!(name, metrics::Unit::Seconds, description);
554    }
555    metrics::describe_histogram!(
556        "gen_ai.client.inference.operation.input_tokens",
557        "The number of input (prompt) tokens used per inference operation."
558    );
559    metrics::describe_histogram!(
560        "gen_ai.client.inference.operation.output_tokens",
561        "The number of output (completion) tokens used per inference operation."
562    );
563    metrics::describe_counter!(
564        "gen_ai.client.inference.usage.input_tokens",
565        "The number of input (prompt) tokens used, including cached tokens."
566    );
567    metrics::describe_counter!(
568        "gen_ai.client.inference.usage.output_tokens",
569        "The number of output (completion) tokens used, including reasoning tokens."
570    );
571}