strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API)
From-scratch rewrite of the Python serve (Python kept as behavioral spec). - engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog, abort, is_idle probe. - config: tolerant shared-JSON loader; foreign keys ignored so one file drives strata-ctl and uostream; CLI --config/--host/--port/--serve. - inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template via minijinja; channel-token dialect (reasoning streamed live); image bridge (in-process Vision, image=<path>); formatter assembling the API seam. - api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health; reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side execution); stop sequences with hold-back; abort on client disconnect. 69 tests green + 2 real-file ignored; clippy clean. Text, images and tools validated live against the real Inkling engine.
This commit is contained in:
commit
597ac432e1
30 files changed
+7541
No files matched your search
@@ -0,0 +1,130 @@
|
||||
//! The HTTP surface: routing, request extraction, and OpenAI-shaped errors.
|
||||
//!
|
||||
//! `POST /v1/chat/completions` (stream and non-stream) and `GET /v1/models`,
|
||||
//! plus a tiny `/health`. The handlers are thin: they delegate all behaviour
|
||||
//! to [`ChatService`] and only decide status codes and envelopes.
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{sse::Sse, IntoResponse, Json};
|
||||
use axum::routing::{get, post};
|
||||
use axum::Router;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use super::service::ChatService;
|
||||
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
|
||||
|
||||
/// Build the router. Mount this inside any axum `Router` or serve it directly.
|
||||
pub fn router(service: ChatService) -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/v1/models", get(models))
|
||||
.route("/v1/chat/completions", post(chat_completions))
|
||||
.with_state(AppState { service })
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
service: ChatService,
|
||||
}
|
||||
|
||||
/// An OpenAI error with the HTTP status the code implies.
|
||||
pub struct Error {
|
||||
status: StatusCode,
|
||||
body: ApiErrorEnvelope,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self {
|
||||
Self { status, body }
|
||||
}
|
||||
|
||||
/// Choose a status from the error's `code`; unknown codes are client 400s.
|
||||
fn from_envelope(env: ApiErrorEnvelope) -> Self {
|
||||
let status = match env.error.code.as_deref() {
|
||||
Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE,
|
||||
Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT,
|
||||
// engine_refused, and any client/parse error, is a 400
|
||||
_ => StatusCode::BAD_REQUEST,
|
||||
};
|
||||
Self::new(status, env)
|
||||
}
|
||||
|
||||
fn bad_request(msg: impl Into<String>) -> Self {
|
||||
Self::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
ApiErrorEnvelope::new(msg, "invalid_request_error", None),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for Error {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
(self.status, Json(self.body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
async fn health() -> &'static str {
|
||||
"ok"
|
||||
}
|
||||
|
||||
async fn models(State(st): State<AppState>) -> Json<ModelList> {
|
||||
Json(ModelList {
|
||||
object: "list",
|
||||
data: vec![ModelCard {
|
||||
id: st.service.model_name().to_string(),
|
||||
object: "model",
|
||||
created: super::types::now_unix(),
|
||||
owned_by: "strata-ctl".to_string(),
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
async fn chat_completions(
|
||||
State(st): State<AppState>,
|
||||
raw: axum::extract::Request,
|
||||
) -> axum::response::Response {
|
||||
// Parse manually so a malformed body yields an OpenAI-shaped 400 rather
|
||||
// than axum's default plain-text rejection.
|
||||
let req: ChatRequest = match json_body(raw).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
|
||||
if req.messages.is_empty() {
|
||||
return Error::bad_request("`messages` must not be empty").into_response();
|
||||
}
|
||||
|
||||
if req.stream {
|
||||
match st.service.stream(&req).await {
|
||||
Ok(stream) => {
|
||||
use futures::StreamExt;
|
||||
// Sse wants Stream<Item = Result<Event, E>>; our channel yields
|
||||
// plain Events, so lift them (errors are infallible here).
|
||||
let stream = stream.map(Ok::<_, std::convert::Infallible>);
|
||||
Sse::new(stream)
|
||||
.keep_alive(
|
||||
axum::response::sse::KeepAlive::new()
|
||||
.interval(std::time::Duration::from_secs(10))
|
||||
.text("ping"),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(env) => Error::from_envelope(env).into_response(),
|
||||
}
|
||||
} else {
|
||||
match st.service.complete(&req).await {
|
||||
Ok(resp) => Json(resp).into_response(),
|
||||
Err(env) => Error::from_envelope(env).into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and deserialize a JSON body, mapping any failure to our error type.
|
||||
async fn json_body<T: DeserializeOwned>(req: axum::extract::Request) -> Result<T, Error> {
|
||||
let bytes = axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024)
|
||||
.await
|
||||
.map_err(|e| Error::bad_request(format!("failed to read body: {e}")))?;
|
||||
serde_json::from_slice::<T>(&bytes)
|
||||
.map_err(|e| Error::bad_request(format!("invalid JSON body: {e}")))
|
||||
}
|
||||
Reference in new issue
Block a user