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:
commit
c5d618ed09
16 files changed
+4289
No files matched your search
@@ -0,0 +1,272 @@
|
||||
//! Schnittstellen: Ollama an der Wurzel, llama-server unter /llamacpp, vLLM unter /vllm.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
Extension, Json, Router,
|
||||
body::Bytes,
|
||||
extract::{DefaultBodyLimit, Request, State},
|
||||
http::{HeaderMap, Method, StatusCode, Uri, header},
|
||||
middleware::{self, Next},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{any, get},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
db::{Db, Usage},
|
||||
engines::Engine,
|
||||
forward::{Forward, forward},
|
||||
scheduler::{SchedError, Scheduler},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub db: Arc<Db>,
|
||||
pub sched: Arc<Scheduler>,
|
||||
/// Ohne Gesamt-Timeout, weil Antworten lange streamen können
|
||||
pub http: reqwest::Client,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct KeyId(i64);
|
||||
|
||||
pub fn router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.route("/omega/status", get(status))
|
||||
.route("/llamacpp/{*rest}", any(llamacpp))
|
||||
.route("/vllm/{*rest}", any(vllm))
|
||||
.fallback(ollama)
|
||||
.layer(middleware::from_fn_with_state(state.clone(), auth))
|
||||
.layer(DefaultBodyLimit::max(256 * 1024 * 1024))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Fehler im Format der Ollama-API
|
||||
pub fn error_response(status: StatusCode, message: &str) -> Response {
|
||||
(status, Json(json!({ "error": message }))).into_response()
|
||||
}
|
||||
|
||||
/// Fehler im Format der OpenAI-API
|
||||
pub fn openai_error(status: StatusCode, message: &str) -> Response {
|
||||
let kind = if status.is_client_error() { "invalid_request_error" } else { "server_error" };
|
||||
(status, Json(json!({ "error": { "message": message, "type": kind, "code": status.as_u16() } })))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub fn engine_error(engine: Engine, status: StatusCode, message: &str) -> Response {
|
||||
match engine {
|
||||
Engine::Ollama => error_response(status, message),
|
||||
Engine::LlamaCpp => openai_error(status, message),
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth(State(st): State<AppState>, mut req: Request, next: Next) -> Response {
|
||||
// Ollama-Clients prüfen mit "/" und /api/version, ob der Server läuft.
|
||||
let path = req.uri().path();
|
||||
if matches!(*req.method(), Method::GET | Method::HEAD) && (path == "/" || path == "/api/version") {
|
||||
return next.run(req).await;
|
||||
}
|
||||
|
||||
let key = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim);
|
||||
let Some(key) = key else {
|
||||
return error_response(StatusCode::UNAUTHORIZED, "API-Key fehlt (Authorization: Bearer <key>)");
|
||||
};
|
||||
match st.db.authenticate(key) {
|
||||
Ok(Some(id)) => {
|
||||
req.extensions_mut().insert(KeyId(id));
|
||||
next.run(req).await
|
||||
}
|
||||
Ok(None) => error_response(StatusCode::UNAUTHORIZED, "ungültiger oder widerrufener API-Key"),
|
||||
Err(e) => {
|
||||
tracing::error!("Key-Prüfung: {e:#}");
|
||||
error_response(StatusCode::INTERNAL_SERVER_ERROR, "interner Fehler")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn status(State(st): State<AppState>) -> Json<Value> {
|
||||
Json(st.sched.snapshot())
|
||||
}
|
||||
|
||||
async fn vllm() -> Response {
|
||||
openai_error(StatusCode::NOT_IMPLEMENTED, "vLLM ist noch nicht angebunden")
|
||||
}
|
||||
|
||||
async fn ollama(
|
||||
State(st): State<AppState>,
|
||||
key: Option<Extension<KeyId>>,
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let path = uri.path().to_string();
|
||||
if path.starts_with("/api/blobs")
|
||||
|| matches!(path.as_str(), "/api/pull" | "/api/push" | "/api/delete" | "/api/copy" | "/api/create")
|
||||
{
|
||||
return error_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"Modelle verwalten nur Administratoren direkt auf dem Server",
|
||||
);
|
||||
}
|
||||
if method == Method::GET && matches!(path.as_str(), "/api/tags" | "/api/ps") {
|
||||
return merged_list(&st, Engine::Ollama, &path, "models").await;
|
||||
}
|
||||
let key_id = key.map(|k| k.0.0);
|
||||
handle(st, key_id, Engine::Ollama, path, uri.query(), method, headers, body).await
|
||||
}
|
||||
|
||||
async fn llamacpp(
|
||||
State(st): State<AppState>,
|
||||
Extension(KeyId(key_id)): Extension<KeyId>,
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let path = uri.path().strip_prefix("/llamacpp").unwrap_or("/").to_string();
|
||||
if path.starts_with("/models/") || path.starts_with("/slots") {
|
||||
return openai_error(
|
||||
StatusCode::FORBIDDEN,
|
||||
"Laden, Entladen und Slots verwaltet der Proxy",
|
||||
);
|
||||
}
|
||||
if method == Method::GET && matches!(path.as_str(), "/models" | "/v1/models") {
|
||||
return merged_list(&st, Engine::LlamaCpp, &path, "data").await;
|
||||
}
|
||||
handle(st, Some(key_id), Engine::LlamaCpp, path, uri.query(), method, headers, body).await
|
||||
}
|
||||
|
||||
/// Modelllisten aller Rechner zu einer zusammenführen
|
||||
async fn merged_list(st: &AppState, engine: Engine, path: &str, field: &str) -> Response {
|
||||
let mut merged: Option<Value> = None;
|
||||
for node in st.sched.nodes_with(engine) {
|
||||
let base = st.sched.engine_url(node, engine).expect("Engine konfiguriert");
|
||||
let resp = match st.http.get(format!("{base}{path}")).send().await {
|
||||
Ok(r) if r.status().is_success() => r.json::<Value>().await,
|
||||
Ok(r) => {
|
||||
tracing::warn!("{base}{path}: {}", r.status());
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("{base}{path}: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Ok(mut v) = resp else { continue };
|
||||
match &mut merged {
|
||||
None => merged = Some(v),
|
||||
Some(m) => {
|
||||
let items = v.get_mut(field).and_then(Value::as_array_mut).map(std::mem::take);
|
||||
if let (Some(target), Some(items)) = (m.get_mut(field).and_then(Value::as_array_mut), items) {
|
||||
for item in items {
|
||||
let id = |v: &Value| v.get("name").or(v.get("id")).cloned();
|
||||
if !target.iter().any(|t| id(t) == id(&item)) {
|
||||
target.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match merged {
|
||||
Some(v) => Json(v).into_response(),
|
||||
None => engine_error(engine, StatusCode::BAD_GATEWAY, "Backend nicht erreichbar"),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_openai_path(engine: Engine, path: &str) -> bool {
|
||||
path.starts_with("/v1/") || (engine == Engine::LlamaCpp && !path.starts_with("/api/"))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn handle(
|
||||
st: AppState,
|
||||
key_id: Option<i64>,
|
||||
engine: Engine,
|
||||
path: String,
|
||||
query: Option<&str>,
|
||||
method: Method,
|
||||
headers: HeaderMap,
|
||||
mut body: Bytes,
|
||||
) -> Response {
|
||||
let mut json_body = if body.is_empty() { None } else { serde_json::from_slice::<Value>(&body).ok() };
|
||||
let model = json_body
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("model"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
|
||||
let mut node = None;
|
||||
let mut guard = None;
|
||||
if let Some(model) = &model {
|
||||
let key = match st.sched.locate(engine, model).await {
|
||||
Ok(key) => key,
|
||||
Err(e) => return engine_error(engine, StatusCode::NOT_FOUND, &e.to_string()),
|
||||
};
|
||||
node = Some(key.node);
|
||||
// /api/show liest nur Metadaten und braucht kein geladenes Modell.
|
||||
if !(engine == Engine::Ollama && path == "/api/show") {
|
||||
match st.sched.acquire(key).await {
|
||||
Ok(g) => guard = Some(g),
|
||||
Err(e) => {
|
||||
let status = match e {
|
||||
SchedError::UnknownModel(_) => StatusCode::NOT_FOUND,
|
||||
SchedError::Timeout(_) => StatusCode::SERVICE_UNAVAILABLE,
|
||||
SchedError::LoadFailed(_) => StatusCode::BAD_GATEWAY,
|
||||
};
|
||||
return engine_error(engine, status, &e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wenige, gezielte Änderungen an der Anfrage; alles andere geht unverändert durch.
|
||||
if let Some(Value::Object(obj)) = &mut json_body {
|
||||
let mut changed = false;
|
||||
if engine == Engine::Ollama && path.starts_with("/api/") && guard.is_some() {
|
||||
// Entladen entscheidet der Proxy, nicht der Client.
|
||||
obj.insert("keep_alive".into(), json!(-1));
|
||||
changed = true;
|
||||
}
|
||||
if is_openai_path(engine, &path) && obj.get("stream") == Some(&Value::Bool(true)) {
|
||||
// Token-Zahlen auch beim Streaming anfordern
|
||||
let opts = obj.entry("stream_options").or_insert_with(|| json!({}));
|
||||
if let Value::Object(opts) = opts
|
||||
&& !opts.contains_key("include_usage") {
|
||||
opts.insert("include_usage".into(), Value::Bool(true));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
body = Bytes::from(serde_json::to_vec(obj).expect("JSON serialisierbar"));
|
||||
}
|
||||
}
|
||||
|
||||
let node = node.or_else(|| st.sched.nodes_with(engine).first().copied());
|
||||
let Some(base) = node.and_then(|n| st.sched.engine_url(n, engine)) else {
|
||||
return engine_error(engine, StatusCode::NOT_FOUND, "Engine nicht konfiguriert");
|
||||
};
|
||||
let url = match query {
|
||||
Some(q) => format!("{base}{path}?{q}"),
|
||||
None => format!("{base}{path}"),
|
||||
};
|
||||
|
||||
let usage = Usage {
|
||||
key_id: key_id.unwrap_or(0),
|
||||
engine: engine.as_str(),
|
||||
model,
|
||||
path: path.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
// Unauthentifizierte Statusabfragen ("/", /api/version) werden nicht verbucht.
|
||||
let db = st.db.clone();
|
||||
let record = key_id.is_some();
|
||||
forward(&st.http, db, Forward { method, url, headers, body, usage, guard, record }).await
|
||||
}
|
||||
Reference in new issue
Block a user