Erster Stand des Omega AI Proxy

- Ollama-API an der Wurzel und llama-server (Router-Modus) unter /llamacpp,
  unverändert durchgereicht mit Streaming
- API-Keys in SQLite, Verwaltung über die Kommandozeile
- Verbuchung der Nutzung mit Token-Zahlen aus den Antworten
- Speicherverwaltung: Laden und Entladen durch den Proxy, Messung des
  Speicherbedarfs, Warteschlange, Mindestverweildauer, Abgleich mit den Engines
- Audit-Log für Keys und Modellwechsel
- omega-agent meldet den belegten Speicher (nvidia-smi bzw. /proc/meminfo)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Stephan RehfeldandClaude Opus 5.5 committed 2026-11-20 11:25:44 +01:00
commit c5d618ed09
16 files changed
+4289

No files matched your search

+179
View File
@@ -0,0 +1,179 @@
//! 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,
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>,
/// Nutzung verbuchen
pub record: bool,
}
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;
if f.record {
record(&db, &usage);
}
let engine = if usage.engine == Engine::Ollama.as_str() { Engine::Ollama } else { Engine::LlamaCpp };
return engine_error(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,
db: f.record.then_some(db),
_guard: f.guard,
};
builder
.body(Body::from_stream(tap))
.unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
}
fn record(db: &Db, usage: &Usage) {
if let Err(e) = db.record_usage(usage) {
tracing::warn!("Nutzung nicht gespeichert: {e:#}");
}
}
/// 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,
db: Option<Arc<Db>>,
_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 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);
}
}
}
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);
if let Poll::Ready(Some(Ok(chunk))) = &poll {
let chunk = chunk.clone();
self.scan_chunk(&chunk);
}
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;
if let Some(db) = &self.db {
record(db, &self.usage);
}
}
}