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:
155
crates/nexus-api/src/tap.rs
Normal file
155
crates/nexus-api/src/tap.rs
Normal file
@ -0,0 +1,155 @@
|
||||
//! Reicht den Antwortstrom der Engine unverändert durch und merkt sich nur
|
||||
//! ein kurzes Stück vom Ende, um daraus die Token-Zahlen zu lesen. Wenn der
|
||||
//! Strom endet oder abbricht (Client getrennt), wird die Anfrage vollständig
|
||||
//! protokolliert: Anfrage-Log, Metriken und eine Zeile im Betriebslog.
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::body::Bytes;
|
||||
use futures_util::Stream;
|
||||
use nexus_store::RequestLogEntry;
|
||||
use tracing::Span;
|
||||
|
||||
use crate::state::AppState;
|
||||
use crate::usage::find_usage;
|
||||
|
||||
/// Wie viele Bytes vom Ende der Antwort für die Token-Suche vorgehalten werden.
|
||||
const TAIL_BYTES: usize = 16 * 1024;
|
||||
|
||||
type Upstream = Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send>>;
|
||||
|
||||
/// Alles, was zum Protokollieren am Ende nötig ist.
|
||||
pub struct Finish {
|
||||
pub state: Arc<AppState>,
|
||||
pub span: Span,
|
||||
pub correlation: String,
|
||||
pub key_id: Option<i64>,
|
||||
/// Name aus der Anfrage, gekürzt (nur für das Anfrage-Log).
|
||||
pub model_logged: String,
|
||||
/// Registrierter Modellname (Metrik-Label).
|
||||
pub model_metric: String,
|
||||
pub wait_ms: Option<u64>,
|
||||
pub status: u16,
|
||||
pub started: Instant,
|
||||
pub latency_ms: u64,
|
||||
pub engine: String,
|
||||
pub instance_id: u64,
|
||||
}
|
||||
|
||||
pub struct Tap {
|
||||
inner: Upstream,
|
||||
tail: Vec<u8>,
|
||||
finish: Option<Finish>,
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
impl Tap {
|
||||
pub fn new(inner: Upstream, finish: Finish) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
tail: Vec::new(),
|
||||
finish: Some(finish),
|
||||
failed: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, bytes: &[u8]) {
|
||||
self.tail.extend_from_slice(bytes);
|
||||
if self.tail.len() > TAIL_BYTES * 2 {
|
||||
let cut = self.tail.len() - TAIL_BYTES;
|
||||
self.tail.drain(..cut);
|
||||
}
|
||||
}
|
||||
|
||||
fn complete(&mut self, aborted: bool) {
|
||||
let Some(f) = self.finish.take() else {
|
||||
return;
|
||||
};
|
||||
let usage = find_usage(&self.tail);
|
||||
self.tail = Vec::new();
|
||||
let duration_ms = f.started.elapsed().as_millis() as u64;
|
||||
let tokens_in = usage.and_then(|u| u.prompt);
|
||||
let tokens_out = usage.and_then(|u| u.completion);
|
||||
let entry = RequestLogEntry {
|
||||
correlation: f.correlation.clone(),
|
||||
api_key_id: f.key_id,
|
||||
model: Some(f.model_logged.clone()),
|
||||
status: f.status,
|
||||
wait_ms: f.wait_ms,
|
||||
latency_ms: Some(f.latency_ms),
|
||||
duration_ms: Some(duration_ms),
|
||||
tokens_in,
|
||||
tokens_out,
|
||||
engine: Some(f.engine.clone()),
|
||||
instance_id: Some(f.instance_id),
|
||||
aborted,
|
||||
};
|
||||
if f.key_id.is_some()
|
||||
&& let Err(e) = f.state.store().log_request(&entry)
|
||||
{
|
||||
f.span.in_scope(|| {
|
||||
tracing::error!(fehler = %e, "Anfrage-Log konnte nicht geschrieben werden");
|
||||
});
|
||||
}
|
||||
f.state.runtime.metrics.record_request(
|
||||
&f.model_metric,
|
||||
f.status,
|
||||
duration_ms,
|
||||
tokens_in,
|
||||
tokens_out,
|
||||
aborted,
|
||||
);
|
||||
// Erzeugungsgeschwindigkeit ab dem Beginn der Antwort.
|
||||
let generating_ms = duration_ms.saturating_sub(f.latency_ms).max(1);
|
||||
let tokens_per_s =
|
||||
tokens_out.map(|n| (n as f64 * 1000.0 / generating_ms as f64 * 10.0).round() / 10.0);
|
||||
f.span.in_scope(|| {
|
||||
tracing::info!(
|
||||
status = f.status,
|
||||
duration_ms,
|
||||
latency_ms = f.latency_ms,
|
||||
model = %f.model_metric,
|
||||
engine = %f.engine,
|
||||
instance_id = f.instance_id,
|
||||
tokens_in,
|
||||
tokens_out,
|
||||
tokens_per_s,
|
||||
aborted,
|
||||
"Antwort abgeschlossen"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for Tap {
|
||||
type Item = Result<Bytes, reqwest::Error>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
match self.inner.as_mut().poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(bytes))) => {
|
||||
self.push(&bytes);
|
||||
Poll::Ready(Some(Ok(bytes)))
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
self.failed = true;
|
||||
Poll::Ready(Some(Err(e)))
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
let failed = self.failed;
|
||||
self.complete(failed);
|
||||
Poll::Ready(None)
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tap {
|
||||
fn drop(&mut self) {
|
||||
// Noch nicht abgeschlossen: Der Client hat die Verbindung getrennt.
|
||||
self.complete(true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user