1use std::sync::OnceLock;
2
3use metrics::{IntoLabels, Label, counter, describe_counter};
4
5static METRICS_INIT: OnceLock<bool> = OnceLock::new();
6
7pub fn lazy_init() {
9 METRICS_INIT.get_or_init(|| {
10 describe_counter!("swiftide.usage.prompt_tokens", "token usage for the prompt");
11 describe_counter!(
12 "swiftide.usage.completion_tokens",
13 "token usage for the completion"
14 );
15 describe_counter!("swiftide.usage.total_tokens", "total token usage");
16 true
17 });
18}
19
20pub fn emit_usage(
22 model: &str,
23 prompt_tokens: u64,
24 completion_tokens: u64,
25 total_tokens: u64,
26 custom_metadata: Option<impl IntoLabels>,
27) {
28 let model = model.to_string();
29 let mut metadata = vec![];
30
31 if let Some(custom_metadata) = custom_metadata {
32 metadata.extend(custom_metadata.into_labels());
33 }
34 metadata.push(Label::new("model", model));
35
36 lazy_init();
37 counter!("swiftide.usage.prompt_tokens", metadata.iter()).increment(prompt_tokens);
38 counter!("swiftide.usage.completion_tokens", metadata.iter()).increment(completion_tokens);
39 counter!("swiftide.usage.total_tokens", metadata.iter()).increment(total_tokens);
40}