- Agent verwaltet die in seiner Konfiguration festgelegten vLLM-Instanzen: Start in eigener Prozessgruppe, Bereitschaft über /health, Stoppen der ganzen Gruppe, Absturzerkennung mit Log-Auszug, Stoppen aller beim Beenden - Proxy bindet vLLM unter /vllm an, leitet nach dem Feld model an die Instanz weiter und erfährt die Instanzen vom Agenten - Scheduler reserviert beim Verdrängen den Platz für das anfragende Modell, damit keine andere wartende Anfrage ihn belegt (kein Hin- und Herladen) - tools/fake_vllm.py zum Testen ohne GPU, agent.example.toml Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
11 KiB
Rust
310 lines
11 KiB
Rust
//! 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 | Engine::Vllm => 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(
|
|
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("/vllm").unwrap_or("/").to_string();
|
|
// Entwickler- und Verwaltungsendpunkte von vLLM
|
|
if matches!(
|
|
path.as_str(),
|
|
"/sleep" | "/wake_up" | "/is_sleeping" | "/reset_prefix_cache" | "/reset_mm_cache"
|
|
| "/start_profile" | "/stop_profile" | "/collective_rpc" | "/scale_elastic_ep"
|
|
| "/update_weights" | "/load_lora_adapter" | "/unload_lora_adapter"
|
|
) {
|
|
return openai_error(StatusCode::FORBIDDEN, "vLLM-Instanzen verwaltet der Proxy");
|
|
}
|
|
if method == Method::GET && matches!(path.as_str(), "/models" | "/v1/models") {
|
|
// Gestoppte Instanzen können nicht antworten; die Liste kommt deshalb vom Proxy.
|
|
let data: Vec<Value> = st
|
|
.sched
|
|
.catalog_models(Engine::Vllm)
|
|
.into_iter()
|
|
.map(|id| json!({ "id": id, "object": "model", "owned_by": "vllm" }))
|
|
.collect();
|
|
return Json(json!({ "object": "list", "data": data })).into_response();
|
|
}
|
|
handle(st, Some(key_id), Engine::Vllm, path, uri.query(), method, headers, body).await
|
|
}
|
|
|
|
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::Ollama && !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 target = 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()),
|
|
};
|
|
target = st.sched.model_url(&key);
|
|
// /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"));
|
|
}
|
|
}
|
|
|
|
// Ohne Modell geht die Anfrage an den ersten Rechner. vLLM hat keine gemeinsame Adresse.
|
|
if target.is_none() && engine == Engine::Vllm {
|
|
if path == "/health" {
|
|
return StatusCode::OK.into_response();
|
|
}
|
|
return openai_error(StatusCode::BAD_REQUEST, "das Feld model fehlt");
|
|
}
|
|
let target = target.or_else(|| {
|
|
let node = st.sched.nodes_with(engine).first().copied()?;
|
|
st.sched.engine_url(node, engine).map(str::to_string)
|
|
});
|
|
let Some(base) = target 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, engine, record }).await
|
|
}
|