- 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>
263 lines
9.0 KiB
Rust
263 lines
9.0 KiB
Rust
//! Reicht Anfragen unverändert an eine Engine durch und liest dabei die Token-Zahlen mit.
|
|
|
|
use std::{
|
|
pin::Pin,
|
|
sync::Arc,
|
|
task::{Context, Poll},
|
|
time::Instant,
|
|
};
|
|
|
|
use axum::{
|
|
body::Body,
|
|
http::{HeaderMap, HeaderName, Method, StatusCode, header},
|
|
response::{IntoResponse, Response},
|
|
};
|
|
use bytes::Bytes;
|
|
use futures_util::{Stream, StreamExt};
|
|
use serde_json::Value;
|
|
|
|
use crate::{
|
|
db::{Db, Usage},
|
|
engines::Engine,
|
|
recording::{Capture, Recorder},
|
|
routes::engine_error,
|
|
scheduler::Guard,
|
|
};
|
|
|
|
/// Größte Zeile, in der noch nach Token-Zahlen gesucht wird (nicht gestreamte Antworten
|
|
/// bestehen aus einer einzigen Zeile, Embeddings können groß sein).
|
|
const MAX_LINE: usize = 16 * 1024 * 1024;
|
|
|
|
fn is_hop_by_hop(name: &HeaderName) -> bool {
|
|
matches!(
|
|
name.as_str(),
|
|
"connection"
|
|
| "keep-alive"
|
|
| "proxy-authenticate"
|
|
| "proxy-authorization"
|
|
| "te"
|
|
| "trailer"
|
|
| "transfer-encoding"
|
|
| "upgrade"
|
|
| "host"
|
|
| "content-length"
|
|
)
|
|
}
|
|
|
|
pub struct Forward {
|
|
pub method: Method,
|
|
pub url: String,
|
|
pub headers: HeaderMap,
|
|
pub body: Bytes,
|
|
pub usage: Usage,
|
|
pub guard: Option<Guard>,
|
|
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 {
|
|
let started = Instant::now();
|
|
let mut req = http.request(f.method, &f.url).body(f.body);
|
|
for (name, value) in &f.headers {
|
|
// Der Key des Benutzers geht nicht an die Engine.
|
|
if !is_hop_by_hop(name) && name != header::AUTHORIZATION {
|
|
req = req.header(name, value);
|
|
}
|
|
}
|
|
|
|
let mut usage = f.usage;
|
|
let resp = match req.send().await {
|
|
Ok(resp) => resp,
|
|
Err(e) => {
|
|
tracing::warn!("{}: {e}", f.url);
|
|
usage.status = StatusCode::BAD_GATEWAY.as_u16();
|
|
usage.duration_ms = started.elapsed().as_millis() as u64;
|
|
// Die Anfrage hat die Engine nie erreicht und zählt deshalb nicht.
|
|
if let Some(t) = usage.counted_at.take()
|
|
&& let Err(e) = db.refund_request(usage.key_id, usage.user_id, usage.quota_id, t)
|
|
{
|
|
tracing::warn!("Anfrage nicht zurückgebucht: {e:#}");
|
|
}
|
|
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");
|
|
}
|
|
};
|
|
|
|
let status = resp.status();
|
|
usage.status = status.as_u16();
|
|
let mut builder = Response::builder().status(status);
|
|
for (name, value) in resp.headers() {
|
|
if !is_hop_by_hop(name) {
|
|
builder = builder.header(name, value);
|
|
}
|
|
}
|
|
let tap = Tap {
|
|
inner: Box::pin(resp.bytes_stream()),
|
|
line: Vec::new(),
|
|
usage,
|
|
started,
|
|
completed: false,
|
|
db: f.record.then_some(db),
|
|
capture: f.capture,
|
|
recorder: f.recorder,
|
|
_guard: f.guard,
|
|
};
|
|
builder
|
|
.body(Body::from_stream(tap))
|
|
.unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
|
|
}
|
|
|
|
/// 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
|
|
&& !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:#}");
|
|
}
|
|
}
|
|
}
|
|
|
|
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 {
|
|
inner: Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send>>,
|
|
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>,
|
|
}
|
|
|
|
impl Tap {
|
|
fn scan_chunk(&mut self, chunk: &[u8]) {
|
|
for part in chunk.split_inclusive(|&b| b == b'\n') {
|
|
if self.line.len() + part.len() <= MAX_LINE {
|
|
self.line.extend_from_slice(part);
|
|
} else {
|
|
self.line.clear();
|
|
}
|
|
if part.ends_with(b"\n") {
|
|
let line = std::mem::take(&mut self.line);
|
|
self.parse_line(&line);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn parse_line(&mut self, line: &[u8]) {
|
|
// 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 };
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Stream for Tap {
|
|
type Item = reqwest::Result<Bytes>;
|
|
|
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
|
let poll = self.inner.poll_next_unpin(cx);
|
|
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
|
|
}
|
|
}
|
|
|
|
impl Drop for Tap {
|
|
fn drop(&mut self) {
|
|
if !self.line.is_empty() {
|
|
let line = std::mem::take(&mut self.line);
|
|
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);
|
|
}
|
|
}
|