Aufzeichnung für Debugging, Token der llama.cpp-Endpunkte, keine Token bei Abbrüchen
- Aufzeichnung der nächsten N Anfragen eines eigenen Keys (höchstens 100, höchstens 7 Tage); Einträge mit XChaCha20-Poly1305 verschlüsselt, je Aufzeichnung ein eigener, mit dem Hauptschlüssel verschlüsselter Schlüssel - Gestreamte Antworten werden zusammengesetzt, Einträge sind in der Größe begrenzt; die Key-Übersicht zeigt den Stand - Fertige Aufzeichnungen liegen eine Stunde bereit, Benachrichtigung ohne Inhalte im Postausgang; Download nur durch den Inhaber, danach werden Einträge und Schlüssel gelöscht, sonst nach Ablauf der Frist - Token aus tokens_evaluated/tokens_predicted der eigenen Endpunkte von llama-server (/completion usw.) - Erhält der Client die Antwort nicht vollständig, zählt die Anfrage, ihre Token nicht; usage markiert sie als aborted - CLI: recording start/stop/list/download, outbox list - Unit-Tests und tests/multispark/recording_test.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
abe72e643d
commit
b9815583b5
16 files changed
+1161
-26
No files matched your search
+84
-14
@@ -19,6 +19,7 @@ use serde_json::Value;
|
||||
use crate::{
|
||||
db::{Db, Usage},
|
||||
engines::Engine,
|
||||
recording::{Capture, Recorder},
|
||||
routes::engine_error,
|
||||
scheduler::Guard,
|
||||
};
|
||||
@@ -53,6 +54,9 @@ pub struct Forward {
|
||||
pub engine: Engine,
|
||||
/// Nutzung verbuchen
|
||||
pub record: bool,
|
||||
/// Die Anfrage wird für Debugging aufgezeichnet.
|
||||
pub capture: Option<Capture>,
|
||||
pub recorder: Arc<Recorder>,
|
||||
}
|
||||
|
||||
pub async fn forward(http: &reqwest::Client, db: Arc<Db>, f: Forward) -> Response {
|
||||
@@ -81,6 +85,9 @@ pub async fn forward(http: &reqwest::Client, db: Arc<Db>, f: Forward) -> Respons
|
||||
if f.record {
|
||||
record(&db, &usage);
|
||||
}
|
||||
if let Some(capture) = &f.capture {
|
||||
save_capture(&db, &f.recorder, capture, usage.status, true);
|
||||
}
|
||||
return engine_error(f.engine, StatusCode::BAD_GATEWAY, "Backend nicht erreichbar");
|
||||
}
|
||||
};
|
||||
@@ -98,7 +105,10 @@ pub async fn forward(http: &reqwest::Client, db: Arc<Db>, f: Forward) -> Respons
|
||||
line: Vec::new(),
|
||||
usage,
|
||||
started,
|
||||
completed: false,
|
||||
db: f.record.then_some(db),
|
||||
capture: f.capture,
|
||||
recorder: f.recorder,
|
||||
_guard: f.guard,
|
||||
};
|
||||
builder
|
||||
@@ -106,12 +116,15 @@ pub async fn forward(http: &reqwest::Client, db: Arc<Db>, f: Forward) -> Respons
|
||||
.unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
|
||||
}
|
||||
|
||||
/// Speichert die Anfrage und bucht ihre Token, falls sie gezählt wurde.
|
||||
/// Speichert die Anfrage und bucht ihre Token, falls sie gezählt wurde. Abgebrochene Anfragen
|
||||
/// zählen als Anfrage, aber ohne Token.
|
||||
fn record(db: &Db, usage: &Usage) {
|
||||
if let Err(e) = db.record_usage(usage) {
|
||||
tracing::warn!("Nutzung nicht gespeichert: {e:#}");
|
||||
}
|
||||
if let Some(t) = usage.counted_at {
|
||||
if let Some(t) = usage.counted_at
|
||||
&& !usage.aborted
|
||||
{
|
||||
let (prompt, completion) = (usage.prompt_tokens.unwrap_or(0), usage.completion_tokens.unwrap_or(0));
|
||||
if let Err(e) = db.book_tokens(usage.key_id, usage.user_id, usage.quota_id, t, prompt, completion) {
|
||||
tracing::warn!("Token nicht gebucht: {e:#}");
|
||||
@@ -119,6 +132,29 @@ fn record(db: &Db, usage: &Usage) {
|
||||
}
|
||||
}
|
||||
|
||||
fn save_capture(db: &Db, recorder: &Recorder, capture: &Capture, status: u16, aborted: bool) {
|
||||
let entry = capture.entry(status, aborted);
|
||||
if let Err(e) = db.write_recording_entry(capture, &entry, &recorder.cfg, &recorder.vault) {
|
||||
tracing::warn!("Aufzeichnung {}: Eintrag nicht gespeichert: {e:#}", capture.recording_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Token-Zahlen einer Zeile, soweit sie welche enthält: OpenAI-Format (`usage`), Ollama
|
||||
/// (`prompt_eval_count`, `eval_count`) und die eigenen Endpunkte von llama-server
|
||||
/// (`tokens_evaluated`, `tokens_predicted`).
|
||||
fn token_counts(v: &Value) -> Option<(Option<u64>, Option<u64>)> {
|
||||
let num = |v: &Value, k: &str| v.get(k).and_then(Value::as_u64);
|
||||
if let Some(u) = v.get("usage").filter(|u| u.is_object()) {
|
||||
return Some((num(u, "prompt_tokens"), num(u, "completion_tokens")));
|
||||
}
|
||||
for (prompt, completion) in [("prompt_eval_count", "eval_count"), ("tokens_evaluated", "tokens_predicted")] {
|
||||
if num(v, prompt).is_some() || num(v, completion).is_some() {
|
||||
return Some((num(v, prompt), num(v, completion)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Leitet den Antwortstrom weiter und sucht zeilenweise nach Token-Zahlen. Wird der Strom
|
||||
/// beendet oder vom Client abgebrochen, wird die Nutzung verbucht und das Modell freigegeben.
|
||||
struct Tap {
|
||||
@@ -126,7 +162,12 @@ struct Tap {
|
||||
line: Vec<u8>,
|
||||
usage: Usage,
|
||||
started: Instant,
|
||||
/// Der Strom ist bis zu seinem Ende gelaufen; sonst hat der Client abgebrochen oder die
|
||||
/// Verbindung zur Engine ist abgerissen.
|
||||
completed: bool,
|
||||
db: Option<Arc<Db>>,
|
||||
capture: Option<Capture>,
|
||||
recorder: Arc<Recorder>,
|
||||
_guard: Option<Guard>,
|
||||
}
|
||||
|
||||
@@ -146,21 +187,16 @@ impl Tap {
|
||||
}
|
||||
|
||||
fn parse_line(&mut self, line: &[u8]) {
|
||||
// Ollama sendet NDJSON, das OpenAI-Format Server-Sent Events ("data: {...}").
|
||||
// Ollama sendet NDJSON, das OpenAI-Format und llama-server Server-Sent Events ("data: {...}").
|
||||
let line = line.trim_ascii();
|
||||
let line = line.strip_prefix(b"data:").map(<[u8]>::trim_ascii).unwrap_or(line);
|
||||
if !line.starts_with(b"{") {
|
||||
return;
|
||||
}
|
||||
let Ok(v) = serde_json::from_slice::<Value>(line) else { return };
|
||||
let num = |v: &Value, k: &str| v.get(k).and_then(Value::as_u64);
|
||||
if let Some(u) = v.get("usage").filter(|u| u.is_object()) {
|
||||
self.usage.prompt_tokens = num(u, "prompt_tokens").or(self.usage.prompt_tokens);
|
||||
self.usage.completion_tokens = num(u, "completion_tokens").or(self.usage.completion_tokens);
|
||||
}
|
||||
if num(&v, "prompt_eval_count").is_some() || num(&v, "eval_count").is_some() {
|
||||
self.usage.prompt_tokens = num(&v, "prompt_eval_count").or(self.usage.prompt_tokens);
|
||||
self.usage.completion_tokens = num(&v, "eval_count").or(self.usage.completion_tokens);
|
||||
if let Some((prompt, completion)) = token_counts(&v) {
|
||||
self.usage.prompt_tokens = prompt.or(self.usage.prompt_tokens);
|
||||
self.usage.completion_tokens = completion.or(self.usage.completion_tokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,9 +206,16 @@ impl Stream for Tap {
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let poll = self.inner.poll_next_unpin(cx);
|
||||
if let Poll::Ready(Some(Ok(chunk))) = &poll {
|
||||
let chunk = chunk.clone();
|
||||
self.scan_chunk(&chunk);
|
||||
match &poll {
|
||||
Poll::Ready(Some(Ok(chunk))) => {
|
||||
let chunk = chunk.clone();
|
||||
self.scan_chunk(&chunk);
|
||||
if let Some(capture) = &mut self.capture {
|
||||
capture.push(&chunk);
|
||||
}
|
||||
}
|
||||
Poll::Ready(None) => self.completed = true,
|
||||
_ => {}
|
||||
}
|
||||
poll
|
||||
}
|
||||
@@ -185,8 +228,35 @@ impl Drop for Tap {
|
||||
self.parse_line(&line);
|
||||
}
|
||||
self.usage.duration_ms = self.started.elapsed().as_millis() as u64;
|
||||
self.usage.aborted = !self.completed;
|
||||
if self.usage.aborted {
|
||||
// Bei Abbrüchen werden keine Token gezählt.
|
||||
self.usage.prompt_tokens = None;
|
||||
self.usage.completion_tokens = None;
|
||||
}
|
||||
if let Some(db) = &self.db {
|
||||
record(db, &self.usage);
|
||||
if let Some(capture) = &self.capture {
|
||||
save_capture(db, &self.recorder, capture, self.usage.status, self.usage.aborted);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn token_fields_of_all_engines() {
|
||||
let openai = json!({ "usage": { "prompt_tokens": 5, "completion_tokens": 3 }, "timings": { "prompt_n": 1 } });
|
||||
assert_eq!(token_counts(&openai), Some((Some(5), Some(3))), "usage hat Vorrang vor timings");
|
||||
assert_eq!(token_counts(&json!({ "usage": null })), None, "OpenAI-Chunk ohne usage");
|
||||
let ollama = json!({ "done": true, "prompt_eval_count": 7, "eval_count": 2 });
|
||||
assert_eq!(token_counts(&ollama), Some((Some(7), Some(2))));
|
||||
let llama = json!({ "stop": true, "tokens_evaluated": 4, "tokens_predicted": 9, "timings": { "prompt_n": 1 } });
|
||||
assert_eq!(token_counts(&llama), Some((Some(4), Some(9))));
|
||||
assert_eq!(token_counts(&json!({ "content": "Hal", "stop": false })), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user