1use std::fmt;
61use std::time::Instant;
62
63use metrics::Label;
64use tracing::Span;
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum Operation {
70 Chat,
72 TextCompletion,
74 GenerateContent,
76 Embeddings,
78}
79
80impl Operation {
81 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106#[non_exhaustive]
107pub enum Modality {
108 Text,
110 Image,
112 Audio,
114 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 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
137pub fn chat(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
142 CallBuilder::new(Operation::Chat, provider, model)
143}
144
145pub fn text_completion(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
147 CallBuilder::new(Operation::TextCompletion, provider, model)
148}
149
150pub fn generate_content(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
152 CallBuilder::new(Operation::GenerateContent, provider, model)
153}
154
155pub fn embeddings(provider: impl Into<String>, model: impl Into<String>) -> CallBuilder {
157 CallBuilder::new(Operation::Embeddings, provider, model)
158}
159
160#[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 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 pub fn server(mut self, address: impl Into<String>, port: u16) -> Self {
209 self.server = Some((address.into(), port));
210 self
211 }
212
213 pub fn max_tokens(mut self, tokens: u32) -> Self {
215 self.max_tokens = Some(tokens.into());
216 self
217 }
218
219 pub fn temperature(mut self, temperature: f64) -> Self {
221 self.temperature = Some(temperature);
222 self
223 }
224
225 pub fn top_p(mut self, top_p: f64) -> Self {
227 self.top_p = Some(top_p);
228 self
229 }
230
231 pub fn top_k(mut self, top_k: u32) -> Self {
233 self.top_k = Some(top_k.into());
234 self
235 }
236
237 pub fn frequency_penalty(mut self, penalty: f64) -> Self {
239 self.frequency_penalty = Some(penalty);
240 self
241 }
242
243 pub fn presence_penalty(mut self, penalty: f64) -> Self {
245 self.presence_penalty = Some(penalty);
246 self
247 }
248
249 pub fn seed(mut self, seed: i64) -> Self {
251 self.seed = Some(seed);
252 self
253 }
254
255 pub fn choices(mut self, count: u32) -> Self {
258 self.choices = (count != 1).then_some(count.into());
259 self
260 }
261
262 pub fn streamed(mut self) -> Self {
265 self.stream = true;
266 self
267 }
268
269 pub fn conversation_id(mut self, id: impl Into<String>) -> Self {
271 self.conversation_id = Some(id.into());
272 self
273 }
274
275 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#[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#[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 labels: Vec<Label>,
375 response_model: Option<String>,
376 input: Tokens,
377 output: Tokens,
378 last_chunk: Option<Instant>,
379}
380
381impl Call {
382 pub fn span(&self) -> &Span {
385 &self.span
386 }
387
388 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 pub fn response_id(self, id: &str) -> Self {
412 self.span.record("gen_ai.response.id", id);
413 self
414 }
415
416 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 pub fn input_tokens(self, tokens: u64) -> Self {
427 self.input_tokens_of(Modality::Text, tokens)
428 }
429
430 pub fn input_tokens_of(mut self, modality: Modality, tokens: u64) -> Self {
433 self.input.add(modality, tokens);
434 self
435 }
436
437 pub fn output_tokens(self, tokens: u64) -> Self {
440 self.output_tokens_of(Modality::Text, tokens)
441 }
442
443 pub fn output_tokens_of(mut self, modality: Modality, tokens: u64) -> Self {
446 self.output.add(modality, tokens);
447 self
448 }
449
450 pub fn dimensions(self, count: u64) -> Self {
453 self.span.record("gen_ai.embeddings.dimension.count", count);
454 self
455 }
456
457 pub fn finish(self) {
459 self.end(None);
460 }
461
462 pub fn fail(self, error_type: &str) {
467 self.end(Some(error_type));
468 }
469
470 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 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 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
530pub 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}