feat: Metriken, Token-Auswertung und Protokollierung am Ende der Antwort (#1050)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
87
crates/nexus-api/src/usage.rs
Normal file
87
crates/nexus-api/src/usage.rs
Normal file
@ -0,0 +1,87 @@
|
||||
//! Liest die Token-Zahlen aus dem Ende einer Engine-Antwort.
|
||||
//!
|
||||
//! Die Engines schicken `usage` am Ende der JSON-Antwort bzw. im letzten
|
||||
//! Datenblock eines SSE-Streams. Gelesen wird nur ein kurzes Stück vom Ende
|
||||
//! der Antwort, ausschließlich um die beiden Zahlen zu finden; der Text wird
|
||||
//! weder gespeichert noch protokolliert.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Prompt- und Ausgabe-Tokens laut Engine.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TokenUsage {
|
||||
pub prompt: Option<u64>,
|
||||
pub completion: Option<u64>,
|
||||
}
|
||||
|
||||
/// Sucht das letzte `"usage"`-Objekt mit Token-Zahlen im Ende einer Antwort.
|
||||
pub fn find_usage(tail: &[u8]) -> Option<TokenUsage> {
|
||||
let text = String::from_utf8_lossy(tail);
|
||||
let mut starts: Vec<usize> = text.match_indices("\"usage\"").map(|(i, _)| i).collect();
|
||||
starts.reverse();
|
||||
for start in starts {
|
||||
let rest = text[start + "\"usage\"".len()..].trim_start();
|
||||
let Some(rest) = rest.strip_prefix(':') else {
|
||||
continue;
|
||||
};
|
||||
let mut stream = serde_json::Deserializer::from_str(rest.trim_start()).into_iter::<Value>();
|
||||
let Some(Ok(Value::Object(map))) = stream.next() else {
|
||||
continue;
|
||||
};
|
||||
let prompt = map.get("prompt_tokens").and_then(Value::as_u64);
|
||||
let completion = map.get("completion_tokens").and_then(Value::as_u64);
|
||||
if prompt.is_some() || completion.is_some() {
|
||||
return Some(TokenUsage { prompt, completion });
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn findet_usage_in_einer_json_antwort_auch_mit_nachfolgendem_feld() {
|
||||
let body = br#"{"id":"x","choices":[{"message":{"content":"hi"}}],"usage":{"prompt_tokens":32,"completion_tokens":146,"total_tokens":178,"prompt_tokens_details":{"cached_tokens":0}},"timings":{"cache_n":0}}"#;
|
||||
assert_eq!(
|
||||
find_usage(body),
|
||||
Some(TokenUsage {
|
||||
prompt: Some(32),
|
||||
completion: Some(146)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findet_usage_im_letzten_sse_block() {
|
||||
let body = b"data: {\"choices\":[{\"delta\":{\"content\":\"a\"}}]}\n\n: keep-alive\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":18,\"completion_tokens\":50,\"total_tokens\":68}}\n\ndata: [DONE]\n\n";
|
||||
let u = find_usage(body).unwrap();
|
||||
assert_eq!((u.prompt, u.completion), (Some(18), Some(50)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_und_text_im_inhalt_werden_uebergangen() {
|
||||
let body = br#"data: {"usage":{"prompt_tokens":1,"completion_tokens":2}}
|
||||
|
||||
data: {"choices":[{"delta":{"content":"das Wort \"usage\" und \"usage\": 5"}}],"usage":null}
|
||||
"#;
|
||||
let u = find_usage(body).unwrap();
|
||||
assert_eq!((u.prompt, u.completion), (Some(1), Some(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ohne_usage_oder_mit_kaputtem_ende_gibt_es_nichts() {
|
||||
assert_eq!(find_usage(b"{\"choices\":[]}"), None);
|
||||
assert_eq!(find_usage(b"\"usage\":{\"prompt_tokens\":"), None);
|
||||
assert_eq!(find_usage(b""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auch_ungueltiges_utf8_im_abgeschnittenen_anfang_stoert_nicht() {
|
||||
let mut body = vec![0xE4, 0xB8];
|
||||
body.extend_from_slice(br#"x"usage":{"prompt_tokens":3,"completion_tokens":4}}"#);
|
||||
let u = find_usage(&body).unwrap();
|
||||
assert_eq!((u.prompt, u.completion), (Some(3), Some(4)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user