74 lines
2.3 KiB
Rust
74 lines
2.3 KiB
Rust
//! `POST /v1/chat/completions`: prüft Key und Modell, startet bei Bedarf die
|
|
//! Instanz und reicht Anfrage und Antwort durch (auch als SSE-Stream).
|
|
|
|
use std::sync::Arc;
|
|
|
|
use axum::body::{Body, Bytes};
|
|
use axum::extract::State;
|
|
use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE};
|
|
use axum::http::{HeaderMap, StatusCode};
|
|
use axum::response::Response;
|
|
use serde_json::Value;
|
|
|
|
use crate::auth::{Authed, requested_priority};
|
|
use crate::error::ApiError;
|
|
use crate::state::AppState;
|
|
|
|
pub async fn completions(
|
|
State(state): State<Arc<AppState>>,
|
|
Authed(key): Authed,
|
|
headers: HeaderMap,
|
|
body: Bytes,
|
|
) -> Result<Response, ApiError> {
|
|
let _priority = requested_priority(&headers, &key)?;
|
|
|
|
let request: Value = serde_json::from_slice(&body)
|
|
.map_err(|e| ApiError::bad_request(format!("Der Body ist kein gültiges JSON: {e}")))?;
|
|
let model = request
|
|
.get("model")
|
|
.and_then(Value::as_str)
|
|
.ok_or_else(|| ApiError::bad_request("Das Feld \"model\" fehlt."))?
|
|
.to_string();
|
|
|
|
if !key.rights.allows(&model) {
|
|
return Err(ApiError::model_not_found(&model));
|
|
}
|
|
let plan = state
|
|
.store()
|
|
.start_plan(&model)
|
|
.map_err(|e| {
|
|
eprintln!("FEHLER Startplan für \"{model}\": {e}");
|
|
ApiError::internal()
|
|
})?
|
|
.ok_or_else(|| ApiError::model_not_found(&model))?;
|
|
|
|
let endpoint = state.runtime.ensure(&plan).await.map_err(|e| {
|
|
eprintln!("FEHLER {e}");
|
|
ApiError::engine_unavailable()
|
|
})?;
|
|
|
|
let upstream = state
|
|
.http
|
|
.post(format!("{}/v1/chat/completions", endpoint.base_url))
|
|
.header(CONTENT_TYPE, "application/json")
|
|
.body(body)
|
|
.send()
|
|
.await
|
|
.map_err(|e| {
|
|
eprintln!("FEHLER Weiterleitung an {}: {e}", endpoint.base_url);
|
|
ApiError::upstream()
|
|
})?;
|
|
|
|
let status =
|
|
StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
|
|
let mut response = Response::builder().status(status);
|
|
for name in [CONTENT_TYPE, CACHE_CONTROL] {
|
|
if let Some(value) = upstream.headers().get(&name) {
|
|
response = response.header(name, value);
|
|
}
|
|
}
|
|
response
|
|
.body(Body::from_stream(upstream.bytes_stream()))
|
|
.map_err(|_| ApiError::internal())
|
|
}
|