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,137 @@
|
||||
//! The seam between the HTTP/OpenAI layer and the token-level engine.
|
||||
//!
|
||||
//! The engine only ever sees and emits **token ids**. Everything that turns
|
||||
//! chat messages into a token prompt, and the token stream back into text
|
||||
//! split across reasoning / answer / tool calls, lives behind [`Formatter`] —
|
||||
//! which the Inkling chat template + HF tokenizer + dialect parser will
|
||||
//! implement. Keeping it a trait means the whole API layer (routing,
|
||||
//! streaming, usage, finish reasons) is buildable and testable now, against a
|
||||
//! trivial formatter, without the tokenizer wired up yet.
|
||||
|
||||
use crate::engine::{EngineError, Sampling};
|
||||
|
||||
use super::types::{ApiErrorEnvelope, ChatRequest};
|
||||
|
||||
/// What the engine needs for one generation: the prompt ids, a token budget,
|
||||
/// and the per-request sampling keys.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Prompt {
|
||||
pub ids: Vec<u32>,
|
||||
pub max_new: u32,
|
||||
pub sampling: Sampling,
|
||||
/// Per-request temp files (e.g. materialized images) the service removes
|
||||
/// once generation is done. Empty for text-only requests.
|
||||
pub temp_files: Vec<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
/// A decoded slice of the model's output, already classified. The formatter
|
||||
/// decides what is thinking and what is the answer; the API layer just routes
|
||||
/// them to `reasoning_content` vs `content`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Piece {
|
||||
Reasoning(String),
|
||||
Content(String),
|
||||
/// A structured tool call parsed from the model output. `arguments` is the
|
||||
/// JSON-encoded argument object, as OpenAI's `function.arguments` string.
|
||||
ToolCall {
|
||||
name: String,
|
||||
arguments: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Piece::Reasoning(s) | Piece::Content(s) => s.is_empty(),
|
||||
Piece::ToolCall { .. } => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Incremental token->text decoder for one in-flight request. Fed one id at a
|
||||
/// time as the engine streams `T`; may buffer (a BPE/dialect parser rarely
|
||||
/// yields a whole grapheme per token) and returns zero or more pieces.
|
||||
pub trait Decoder: Send {
|
||||
fn push(&mut self, id: u32) -> Vec<Piece>;
|
||||
/// Flush any held partial at end of stream. `reason` is the engine's finish
|
||||
/// word (`"length"`, `"stop"`, ...): some dialects surface truncated
|
||||
/// thinking only when the budget expired.
|
||||
fn finish(&mut self, reason: Option<&str>) -> Vec<Piece>;
|
||||
}
|
||||
|
||||
/// Messages <-> tokens + output parsing, for a specific model dialect.
|
||||
pub trait Formatter: Send + Sync {
|
||||
/// The id this formatter serves (reported in `/v1/models` and responses).
|
||||
fn model_name(&self) -> &str;
|
||||
|
||||
/// The formatter's default token budget when the request sets none.
|
||||
fn default_max_new(&self) -> u32 {
|
||||
2048
|
||||
}
|
||||
|
||||
/// Render the conversation to a prompt and derive the engine request.
|
||||
/// Errors map straight to an HTTP 400.
|
||||
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope>;
|
||||
|
||||
/// A fresh output decoder for one request.
|
||||
fn decoder(&self) -> Box<dyn Decoder>;
|
||||
}
|
||||
|
||||
/// Convenience: run a decoder over a whole id slice (the non-streaming path).
|
||||
pub fn decode_all(dec: &mut dyn Decoder, ids: &[u32], reason: Option<&str>) -> Vec<Piece> {
|
||||
let mut out = Vec::new();
|
||||
for &id in ids {
|
||||
out.extend(dec.push(id));
|
||||
}
|
||||
out.extend(dec.finish(reason));
|
||||
out
|
||||
}
|
||||
|
||||
/// Collapse pieces into (reasoning, content) strings.
|
||||
pub fn split_pieces(pieces: Vec<Piece>) -> (String, String) {
|
||||
let mut reasoning = String::new();
|
||||
let mut content = String::new();
|
||||
for p in pieces {
|
||||
match p {
|
||||
Piece::Reasoning(s) => reasoning.push_str(&s),
|
||||
Piece::Content(s) => content.push_str(&s),
|
||||
Piece::ToolCall { .. } => {}
|
||||
}
|
||||
}
|
||||
(reasoning, content)
|
||||
}
|
||||
|
||||
/// Everything a decoder produced, collapsed: reasoning text, answer text, and
|
||||
/// the structured tool calls (name, JSON-encoded arguments) in emission order.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Decoded {
|
||||
pub reasoning: String,
|
||||
pub content: String,
|
||||
pub tool_calls: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// Collapse pieces into a [`Decoded`], keeping tool calls structured.
|
||||
pub fn decode_pieces(pieces: Vec<Piece>) -> Decoded {
|
||||
let mut d = Decoded::default();
|
||||
for p in pieces {
|
||||
match p {
|
||||
Piece::Reasoning(s) => d.reasoning.push_str(&s),
|
||||
Piece::Content(s) => d.content.push_str(&s),
|
||||
Piece::ToolCall { name, arguments } => d.tool_calls.push((name, arguments)),
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Map an engine failure to an OpenAI error envelope + HTTP status code.
|
||||
pub fn engine_error(err: EngineError) -> (u16, ApiErrorEnvelope) {
|
||||
use crate::engine::EngineError::*;
|
||||
let (status, kind, code) = match &err {
|
||||
Refused(_) => (400, "invalid_request_error", Some("engine_refused")),
|
||||
Silent(_) => (504, "engine_error", Some("engine_silent")),
|
||||
Died | Spawn(_) => (503, "engine_error", Some("engine_unavailable")),
|
||||
Startup(_) => (503, "engine_error", Some("engine_startup")),
|
||||
};
|
||||
let envelope = ApiErrorEnvelope::bad_request(err.to_string(), kind, code.map(str::to_string));
|
||||
(status, envelope)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! The OpenAI-compatible HTTP API.
|
||||
//!
|
||||
//! Layers on top of [`crate::engine`]: [`types`] is the wire contract,
|
||||
//! [`formatter`] the token<->text seam, [`service`] the completion logic, and
|
||||
//! [`routes`] the axum router.
|
||||
|
||||
pub mod formatter;
|
||||
pub mod routes;
|
||||
pub mod service;
|
||||
pub mod stop;
|
||||
pub mod types;
|
||||
|
||||
pub use formatter::{Decoder, Formatter, Piece, Prompt};
|
||||
pub use routes::router;
|
||||
pub use service::ChatService;
|
||||
pub use types::{ChatMessage, ChatRequest, ChatResponse, ModelList, Role};
|
||||
@@ -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}")))
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! The completion service: turns an OpenAI request into engine calls and
|
||||
//! back into OpenAI responses, driving the [`Formatter`] seam and the shared
|
||||
//! [`Engine`].
|
||||
//!
|
||||
//! Non-streaming runs the engine to completion and decodes the whole token
|
||||
//! list. Streaming bridges the engine's token callback to an SSE stream over a
|
||||
//! channel: a background task owns the request (and thus the engine's lock)
|
||||
//! while the HTTP handler just forwards what the task puts on the channel.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::response::sse::Event;
|
||||
use futures::Stream;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tokio_stream::wrappers::UnboundedReceiverStream;
|
||||
|
||||
use crate::engine::{Engine, EngineLine, Outcome};
|
||||
|
||||
use super::formatter::{self, Formatter, Piece};
|
||||
use super::stop::StopFilter;
|
||||
use super::types::{
|
||||
completion_id, now_unix, tool_call_id, ApiErrorEnvelope, ChatChunk, ChatMessage, ChatRequest,
|
||||
ChatResponse, Choice, Delta, FinishReason, FunctionCall, Role, StreamChoice, ToolCall, Usage,
|
||||
};
|
||||
|
||||
/// Shared handle passed around the HTTP layer.
|
||||
#[derive(Clone)]
|
||||
pub struct ChatService {
|
||||
engine: Arc<Engine>,
|
||||
fmt: Arc<dyn Formatter>,
|
||||
}
|
||||
|
||||
impl ChatService {
|
||||
pub fn new(engine: Arc<Engine>, fmt: Arc<dyn Formatter>) -> Self {
|
||||
Self { engine, fmt }
|
||||
}
|
||||
|
||||
pub fn model_name(&self) -> &str {
|
||||
self.fmt.model_name()
|
||||
}
|
||||
|
||||
/// One-shot completion.
|
||||
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
|
||||
let prompt = self.fmt.build_prompt(req)?;
|
||||
let outcome = self
|
||||
.engine
|
||||
.generate(prompt.max_new, &prompt.sampling, &prompt.ids, |_| {})
|
||||
.await
|
||||
.map_err(formatter_error)?;
|
||||
|
||||
// drop per-request temp files (materialized images) now generation is done
|
||||
for p in &prompt.temp_files {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
|
||||
let mut dec = self.fmt.decoder();
|
||||
let reason = outcome.done.as_ref().map(|d| d.finish.as_str());
|
||||
let decoded =
|
||||
formatter::decode_pieces(formatter::decode_all(dec.as_mut(), &outcome.tokens, reason));
|
||||
|
||||
// Structured tool calls (llama.cpp --jinja behaviour): the client executes
|
||||
// them; finish_reason becomes "tool_calls" when any were produced.
|
||||
let tool_calls: Vec<ToolCall> = decoded
|
||||
.tool_calls
|
||||
.iter()
|
||||
.map(|(name, arguments)| ToolCall {
|
||||
id: tool_call_id(),
|
||||
kind: "function".to_string(),
|
||||
function: FunctionCall {
|
||||
name: name.clone(),
|
||||
arguments: arguments.clone(),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
let has_tools = !tool_calls.is_empty();
|
||||
let stops = req.stop.clone().map(|s| s.into_vec()).unwrap_or_default();
|
||||
let (content, stop_hit) = super::stop::truncate_at_stop(&decoded.content, &stops);
|
||||
let finish = if has_tools {
|
||||
FinishReason::ToolCalls
|
||||
} else if stop_hit {
|
||||
FinishReason::Stop
|
||||
} else {
|
||||
finish_reason(&outcome, prompt.max_new)
|
||||
};
|
||||
|
||||
Ok(ChatResponse {
|
||||
id: completion_id(),
|
||||
object: "chat.completion",
|
||||
created: now_unix(),
|
||||
model: req.model.clone(),
|
||||
choices: vec![Choice {
|
||||
index: 0,
|
||||
message: ChatMessage {
|
||||
role: Role::Assistant,
|
||||
content: (!content.is_empty()).then_some(serde_json::Value::String(content)),
|
||||
tool_call_id: None,
|
||||
tool_calls: has_tools.then_some(tool_calls),
|
||||
name: None,
|
||||
reasoning_content: (!decoded.reasoning.is_empty()).then_some(decoded.reasoning),
|
||||
},
|
||||
finish_reason: finish,
|
||||
}],
|
||||
usage: usage_of(
|
||||
&outcome,
|
||||
prompt.ids.len() as u32,
|
||||
outcome.tokens.len() as u32,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
/// Streaming completion: an SSE item stream. `build_prompt` errors surface
|
||||
/// synchronously (as `Err`) so the handler can still answer with a plain
|
||||
/// HTTP error before any bytes are sent.
|
||||
pub async fn stream(
|
||||
&self,
|
||||
req: &ChatRequest,
|
||||
) -> Result<impl Stream<Item = Event> + Send + 'static, ApiErrorEnvelope> {
|
||||
let prompt = self.fmt.build_prompt(req)?;
|
||||
|
||||
let id = completion_id();
|
||||
let created = now_unix();
|
||||
let model = req.model.clone();
|
||||
|
||||
// Unbounded: the token callback is synchronous and must never block on
|
||||
// (or lose events to) backpressure; a request is bounded by max_new.
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
|
||||
let engine = self.engine.clone();
|
||||
let fmt = self.fmt.clone();
|
||||
|
||||
let (p_ids, p_max, p_sampling, p_temp) = (
|
||||
prompt.ids,
|
||||
prompt.max_new,
|
||||
prompt.sampling,
|
||||
prompt.temp_files,
|
||||
);
|
||||
let p_stops = req.stop.clone().map(|s| s.into_vec()).unwrap_or_default();
|
||||
tokio::spawn(async move {
|
||||
// Open the stream the way OpenAI clients expect: role first.
|
||||
send(
|
||||
&tx,
|
||||
&id,
|
||||
created,
|
||||
&model,
|
||||
Delta {
|
||||
role: Some("assistant"),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
let mut dec = fmt.decoder();
|
||||
let mut st = EmitState {
|
||||
tool_idx: 0,
|
||||
had_tools: false,
|
||||
stops: StopFilter::new(p_stops),
|
||||
stop_hit: false,
|
||||
};
|
||||
|
||||
// Race generation against client disconnect. `tx.closed()` borrows
|
||||
// the sender (no clone: a cloned sender would keep the channel open
|
||||
// and the SSE stream would never end). On disconnect we abort the
|
||||
// engine, then let the request drain its own DONE.
|
||||
let mut gen_fut = Box::pin(engine.generate(p_max, &p_sampling, &p_ids, |line| {
|
||||
if let EngineLine::Token(tok) = line {
|
||||
for piece in dec.push(*tok) {
|
||||
send_piece(&tx, &id, created, &model, &piece, &mut st, &engine);
|
||||
}
|
||||
}
|
||||
}));
|
||||
let mut closed_fut = Box::pin(tx.closed());
|
||||
let gen = tokio::select! {
|
||||
r = gen_fut.as_mut() => r,
|
||||
_ = closed_fut.as_mut() => {
|
||||
let _ = engine.abort().await;
|
||||
gen_fut.as_mut().await
|
||||
}
|
||||
};
|
||||
drop(gen_fut);
|
||||
drop(closed_fut);
|
||||
|
||||
// Flush whatever the decoder still holds (with the finish word, so
|
||||
// the dialect can surface truncated thinking on "length").
|
||||
let reason = gen
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|o| o.done.as_ref())
|
||||
.map(|d| d.finish.as_str());
|
||||
for piece in dec.finish(reason) {
|
||||
send_piece(&tx, &id, created, &model, &piece, &mut st, &engine);
|
||||
}
|
||||
|
||||
// flush any content held back as a possible partial stop match
|
||||
let tail = st.stops.flush();
|
||||
if !tail.is_empty() {
|
||||
send(
|
||||
&tx,
|
||||
&id,
|
||||
created,
|
||||
&model,
|
||||
Delta {
|
||||
content: Some(tail),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
// drop per-request temp files (materialized images)
|
||||
for p in &p_temp {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
|
||||
let finish = if st.had_tools {
|
||||
FinishReason::ToolCalls
|
||||
} else if st.stop_hit {
|
||||
FinishReason::Stop
|
||||
} else {
|
||||
match &gen {
|
||||
Ok(out) => finish_reason(out, p_max),
|
||||
Err(_) => FinishReason::Stop,
|
||||
}
|
||||
};
|
||||
send(&tx, &id, created, &model, Delta::default(), Some(finish));
|
||||
let _ = tx.send(Event::default().data("[DONE]"));
|
||||
|
||||
if let Err(e) = gen {
|
||||
tracing::warn!(error = %e, "streaming generation ended in error");
|
||||
}
|
||||
});
|
||||
|
||||
Ok(UnboundedReceiverStream::new(rx))
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutable per-request emit state for the streaming path (kept in one struct so
|
||||
/// the token callback borrows a single thing).
|
||||
struct EmitState {
|
||||
tool_idx: u32,
|
||||
had_tools: bool,
|
||||
stops: StopFilter,
|
||||
stop_hit: bool,
|
||||
}
|
||||
|
||||
fn send_piece(
|
||||
tx: &UnboundedSender<Event>,
|
||||
id: &str,
|
||||
created: u64,
|
||||
model: &str,
|
||||
piece: &Piece,
|
||||
st: &mut EmitState,
|
||||
abort_engine: &Arc<Engine>,
|
||||
) {
|
||||
let delta = match piece {
|
||||
Piece::Content(s) => {
|
||||
// filter the answer through the stop matcher (hold-back included)
|
||||
let emit = st.stops.feed(s);
|
||||
if st.stops.hit && !st.stop_hit {
|
||||
st.stop_hit = true;
|
||||
// stop reached: abort the engine so we don't keep generating
|
||||
let e = abort_engine.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = e.abort().await;
|
||||
});
|
||||
}
|
||||
if emit.is_empty() {
|
||||
return;
|
||||
}
|
||||
Delta {
|
||||
content: Some(emit),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
Piece::Reasoning(s) if !s.is_empty() => Delta {
|
||||
reasoning_content: Some(s.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
Piece::ToolCall { name, arguments } => {
|
||||
// llama.cpp wire shape: one delta carries index+id+type+function.
|
||||
// Emitting the whole call at once is valid; clients accumulate by index.
|
||||
let tc = serde_json::json!([{
|
||||
"index": st.tool_idx,
|
||||
"id": tool_call_id(),
|
||||
"type": "function",
|
||||
"function": { "name": name, "arguments": arguments },
|
||||
}]);
|
||||
st.tool_idx += 1;
|
||||
st.had_tools = true;
|
||||
Delta {
|
||||
tool_calls: Some(tc),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
send(tx, id, created, model, delta, None);
|
||||
}
|
||||
|
||||
/// Push one SSE `data:` event holding a `chat.completion.chunk`.
|
||||
fn send(
|
||||
tx: &UnboundedSender<Event>,
|
||||
id: &str,
|
||||
created: u64,
|
||||
model: &str,
|
||||
delta: Delta,
|
||||
finish: Option<FinishReason>,
|
||||
) {
|
||||
let body = ChatChunk {
|
||||
id: id.to_string(),
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: model.to_string(),
|
||||
choices: vec![StreamChoice {
|
||||
index: 0,
|
||||
delta,
|
||||
finish_reason: finish,
|
||||
}],
|
||||
};
|
||||
match Event::default().json_data(&body) {
|
||||
Ok(ev) => {
|
||||
let _ = tx.send(ev);
|
||||
}
|
||||
Err(e) => tracing::error!(error = %e, "failed to serialize SSE chunk"),
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_reason(outcome: &Outcome, max_new: u32) -> FinishReason {
|
||||
match &outcome.done {
|
||||
Some(d) if d.finish == "length" => FinishReason::Length,
|
||||
Some(d) => FinishReason::from_engine(&d.finish),
|
||||
// No DONE (e.g. aborted): if we filled the budget, call it length.
|
||||
None if (outcome.tokens.len() as u32) >= max_new => FinishReason::Length,
|
||||
None => FinishReason::Stop,
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage {
|
||||
match &outcome.done {
|
||||
Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion)),
|
||||
None => Usage::new(prompt_len, completion),
|
||||
}
|
||||
}
|
||||
|
||||
/// Engine error -> OpenAI error envelope (the status code is applied by routes).
|
||||
fn formatter_error(err: crate::engine::EngineError) -> ApiErrorEnvelope {
|
||||
formatter::engine_error(err).1
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
//! Stop-sequence filtering for the content channel (OpenAI `stop`).
|
||||
//!
|
||||
//! Mirrors the reference's stop matcher: scan the emitted answer text for any
|
||||
//! stop string, truncate at the first hit, and hold back a trailing partial
|
||||
//! match so a stop string split across streaming deltas is still caught. The
|
||||
//! reasoning channel is left untouched (stop applies to the answer).
|
||||
|
||||
/// Incremental stop matcher over the content text.
|
||||
pub struct StopFilter {
|
||||
stops: Vec<String>,
|
||||
pending: String,
|
||||
/// A full stop string was matched; nothing more should be emitted.
|
||||
pub hit: bool,
|
||||
}
|
||||
|
||||
impl StopFilter {
|
||||
pub fn new(stops: Vec<String>) -> Self {
|
||||
let stops = stops.into_iter().filter(|s| !s.is_empty()).collect();
|
||||
Self {
|
||||
stops,
|
||||
pending: String::new(),
|
||||
hit: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn active(&self) -> bool {
|
||||
!self.stops.is_empty()
|
||||
}
|
||||
|
||||
/// Feed content text; return the safe-to-emit prefix. Sets `hit` when a
|
||||
/// stop string completes (the returned prefix stops just before it).
|
||||
pub fn feed(&mut self, text: &str) -> String {
|
||||
if self.hit {
|
||||
return String::new();
|
||||
}
|
||||
if self.stops.is_empty() {
|
||||
return text.to_string();
|
||||
}
|
||||
self.pending.push_str(text);
|
||||
|
||||
// earliest full match across all stop strings
|
||||
let mut cut: Option<usize> = None;
|
||||
for s in &self.stops {
|
||||
if let Some(i) = self.pending.find(s.as_str()) {
|
||||
cut = Some(cut.map_or(i, |c| c.min(i)));
|
||||
}
|
||||
}
|
||||
if let Some(i) = cut {
|
||||
let emit = self.pending[..i].to_string();
|
||||
self.pending.clear();
|
||||
self.hit = true;
|
||||
return emit;
|
||||
}
|
||||
|
||||
// hold back the longest suffix that is a proper prefix of any stop
|
||||
let hold = self.hold_suffix_len();
|
||||
let emit_len = self.pending.len() - hold;
|
||||
let emit = self.pending[..emit_len].to_string();
|
||||
self.pending.drain(..emit_len);
|
||||
emit
|
||||
}
|
||||
|
||||
/// Flush whatever is held at end of stream (empty if a stop was hit).
|
||||
pub fn flush(&mut self) -> String {
|
||||
if self.hit {
|
||||
String::new()
|
||||
} else {
|
||||
std::mem::take(&mut self.pending)
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest char-aligned suffix of `pending` that is a proper prefix of a
|
||||
/// stop string (so a stop split across deltas is not emitted prematurely).
|
||||
fn hold_suffix_len(&self) -> usize {
|
||||
let max = self.stops.iter().map(|s| s.len()).max().unwrap_or(0);
|
||||
let mut k = max.saturating_sub(1).min(self.pending.len());
|
||||
while k > 0 {
|
||||
let start = self.pending.len() - k;
|
||||
if self.pending.is_char_boundary(start) {
|
||||
let suffix = &self.pending[start..];
|
||||
if self.stops.iter().any(|s| s.starts_with(suffix)) {
|
||||
return k;
|
||||
}
|
||||
}
|
||||
k -= 1;
|
||||
}
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Truncate a whole content string at the earliest stop string. Returns the
|
||||
/// truncated text and whether a stop was hit (the non-streaming path).
|
||||
pub fn truncate_at_stop(content: &str, stops: &[String]) -> (String, bool) {
|
||||
let mut cut: Option<usize> = None;
|
||||
for s in stops {
|
||||
if s.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(i) = content.find(s.as_str()) {
|
||||
cut = Some(cut.map_or(i, |c| c.min(i)));
|
||||
}
|
||||
}
|
||||
match cut {
|
||||
Some(i) => (content[..i].to_string(), true),
|
||||
None => (content.to_string(), false),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_stops_passes_through() {
|
||||
let mut f = StopFilter::new(vec![]);
|
||||
assert_eq!(f.feed("hello world"), "hello world");
|
||||
assert!(!f.hit);
|
||||
assert_eq!(f.flush(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_match_truncates() {
|
||||
let mut f = StopFilter::new(vec!["STOP".into()]);
|
||||
assert_eq!(f.feed("abcSTOPdef"), "abc");
|
||||
assert!(f.hit);
|
||||
assert_eq!(f.feed("more"), "");
|
||||
assert_eq!(f.flush(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_match_is_held_then_caught() {
|
||||
let mut f = StopFilter::new(vec!["STOP".into()]);
|
||||
// "ST" is a prefix of STOP: held back, not emitted
|
||||
assert_eq!(f.feed("abcST"), "abc");
|
||||
assert!(!f.hit);
|
||||
// completing the stop across the next delta
|
||||
assert_eq!(f.feed("OPdef"), "");
|
||||
assert!(f.hit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_prefix_flushed_at_end() {
|
||||
let mut f = StopFilter::new(vec!["STOP".into()]);
|
||||
assert_eq!(f.feed("abcST"), "abc");
|
||||
// never completed: the held tail is flushed at end of stream
|
||||
assert_eq!(f.flush(), "ST");
|
||||
assert!(!f.hit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn earliest_of_many_stops() {
|
||||
let mut f = StopFilter::new(vec!["zz".into(), "ab".into()]);
|
||||
assert_eq!(f.feed("xxabzz"), "xx");
|
||||
assert!(f.hit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multibyte_boundary_safe() {
|
||||
let mut f = StopFilter::new(vec!["§".into()]);
|
||||
assert_eq!(f.feed("ciao§mondo"), "ciao");
|
||||
assert!(f.hit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_whole() {
|
||||
let (t, hit) = truncate_at_stop("helloSTOPworld", &["STOP".into()]);
|
||||
assert_eq!(t, "hello");
|
||||
assert!(hit);
|
||||
let (t, hit) = truncate_at_stop("hello", &["STOP".into()]);
|
||||
assert_eq!(t, "hello");
|
||||
assert!(!hit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Wire types for the OpenAI-compatible surface we expose.
|
||||
//!
|
||||
//! Only the subset of `/v1/chat/completions` and `/v1/models` we implement is
|
||||
//! modelled; request fields we do not act on yet still deserialize (with
|
||||
//! `#[serde(default)]`) so a standard client never gets a hard parse error for
|
||||
//! sending them. Field names follow the OpenAI spec exactly (snake_case).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The role of a chat participant. `Tool` is the OpenAI function/tool result
|
||||
/// role; `Developer` is the newer spelling of `System`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Role {
|
||||
System,
|
||||
Developer,
|
||||
User,
|
||||
Assistant,
|
||||
Tool,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Role::System | Role::Developer => "system",
|
||||
Role::User => "user",
|
||||
Role::Assistant => "assistant",
|
||||
Role::Tool => "tool",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool the assistant asked to call (assistant turn) — parsed from the
|
||||
/// model output by the formatter. Carried opaquely so the tool-loop decision
|
||||
/// (server- vs client-side) stays separable from this layer.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ToolCall {
|
||||
pub id: String,
|
||||
#[serde(rename = "type", default)]
|
||||
pub kind: String,
|
||||
pub function: FunctionCall,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FunctionCall {
|
||||
pub name: String,
|
||||
/// JSON-encoded arguments, as the model produced them.
|
||||
pub arguments: String,
|
||||
}
|
||||
|
||||
/// One message of the conversation.
|
||||
///
|
||||
/// `content` is a string in the common case but OpenAI allows a parts array
|
||||
/// (multimodal); we keep it as `serde_json::Value` and let the formatter
|
||||
/// interpret it, so plain-text and image-part requests both deserialize.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ChatMessage {
|
||||
pub role: Role,
|
||||
#[serde(default)]
|
||||
pub content: Option<serde_json::Value>,
|
||||
/// Present on tool-result messages: the call this message answers for.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tool_call_id: Option<String>,
|
||||
/// Assistant turn: calls the model wants made.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tool_calls: Option<Vec<ToolCall>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// Our extension: the model's chain-of-thought, when the client asks to
|
||||
/// receive it (matches several OpenAI-compatible servers).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning_content: Option<String>,
|
||||
}
|
||||
|
||||
impl ChatMessage {
|
||||
/// The plain-text view of `content`, if it is a string.
|
||||
pub fn text(&self) -> Option<&str> {
|
||||
self.content.as_ref().and_then(|c| c.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// A `stop` sequence, or list of them, from the request.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Stop {
|
||||
One(String),
|
||||
Many(Vec<String>),
|
||||
}
|
||||
|
||||
impl Stop {
|
||||
pub fn into_vec(self) -> Vec<String> {
|
||||
match self {
|
||||
Stop::One(s) => vec![s],
|
||||
Stop::Many(v) => v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /v1/chat/completions` body (the fields we recognise).
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ChatRequest {
|
||||
#[serde(default)]
|
||||
pub model: String,
|
||||
pub messages: Vec<ChatMessage>,
|
||||
#[serde(default)]
|
||||
pub stream: bool,
|
||||
#[serde(default)]
|
||||
pub temperature: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub top_p: Option<f64>,
|
||||
/// Newer spelling; both accepted, `max_completion_tokens` wins if present.
|
||||
#[serde(default)]
|
||||
pub max_tokens: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub max_completion_tokens: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub frequency_penalty: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub presence_penalty: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub seed: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub stop: Option<Stop>,
|
||||
/// Tool definitions. Parsed but not yet acted on: kept so the request
|
||||
/// round-trips and so the (undecided) tool loop can plug in here.
|
||||
#[serde(default)]
|
||||
pub tools: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub tool_choice: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl ChatRequest {
|
||||
pub fn max_new(&self, fallback: u32) -> u32 {
|
||||
self.max_completion_tokens
|
||||
.or(self.max_tokens)
|
||||
.unwrap_or(fallback)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Usage {
|
||||
pub prompt_tokens: u32,
|
||||
pub completion_tokens: u32,
|
||||
pub total_tokens: u32,
|
||||
}
|
||||
|
||||
impl Usage {
|
||||
pub fn new(prompt_tokens: u32, completion_tokens: u32) -> Self {
|
||||
Self {
|
||||
prompt_tokens,
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why generation stopped (OpenAI spelling).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FinishReason {
|
||||
Stop,
|
||||
Length,
|
||||
ToolCalls,
|
||||
/// Chain-of-thought ran to its budget before any answer (our extension,
|
||||
/// mirrors several servers).
|
||||
#[serde(rename = "content_filter")]
|
||||
ContentFilter,
|
||||
}
|
||||
|
||||
impl FinishReason {
|
||||
/// Map the engine's own `DONE <finish>` word onto OpenAI's vocabulary.
|
||||
pub fn from_engine(finish: &str) -> Self {
|
||||
match finish {
|
||||
"length" => FinishReason::Length,
|
||||
// stop, eos, im_end, endoftext, ... all mean "the model stopped"
|
||||
_ => FinishReason::Stop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `choices[0]` of a non-streaming response.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Choice {
|
||||
pub index: u32,
|
||||
pub message: ChatMessage,
|
||||
pub finish_reason: FinishReason,
|
||||
}
|
||||
|
||||
/// Full non-streaming response.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ChatResponse {
|
||||
pub id: String,
|
||||
#[serde(rename = "object")]
|
||||
pub object: &'static str,
|
||||
pub created: u64,
|
||||
pub model: String,
|
||||
pub choices: Vec<Choice>,
|
||||
pub usage: Usage,
|
||||
}
|
||||
|
||||
/// Streaming delta: like a message but every field optional, sent incrementally.
|
||||
#[derive(Debug, Clone, Serialize, Default)]
|
||||
pub struct Delta {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub role: Option<&'static str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub content: Option<String>,
|
||||
/// Streaming tool-call deltas carry an `index` (and partial `function`
|
||||
/// fragments), so this is kept as raw JSON rather than `Vec<ToolCall>`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tool_calls: Option<serde_json::Value>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning_content: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct StreamChoice {
|
||||
pub index: u32,
|
||||
pub delta: Delta,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub finish_reason: Option<FinishReason>,
|
||||
}
|
||||
|
||||
/// One SSE chunk of a streaming completion.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ChatChunk {
|
||||
pub id: String,
|
||||
#[serde(rename = "object")]
|
||||
pub object: &'static str,
|
||||
pub created: u64,
|
||||
pub model: String,
|
||||
pub choices: Vec<StreamChoice>,
|
||||
}
|
||||
|
||||
/// `GET /v1/models` element and envelope.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ModelCard {
|
||||
pub id: String,
|
||||
#[serde(rename = "object")]
|
||||
pub object: &'static str,
|
||||
pub created: u64,
|
||||
pub owned_by: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ModelList {
|
||||
#[serde(rename = "object")]
|
||||
pub object: &'static str,
|
||||
pub data: Vec<ModelCard>,
|
||||
}
|
||||
|
||||
/// OpenAI-standard error envelope: `{"error": {...}}`.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ApiErrorBody {
|
||||
pub message: String,
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub param: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub code: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ApiErrorEnvelope {
|
||||
pub error: ApiErrorBody,
|
||||
}
|
||||
|
||||
impl ApiErrorEnvelope {
|
||||
pub fn new(message: impl Into<String>, kind: impl Into<String>, code: Option<String>) -> Self {
|
||||
Self {
|
||||
error: ApiErrorBody {
|
||||
message: message.into(),
|
||||
kind: kind.into(),
|
||||
param: None,
|
||||
code,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A 400-shaped client error (also used for engine refusals).
|
||||
pub fn bad_request(
|
||||
message: impl Into<String>,
|
||||
kind: impl Into<String>,
|
||||
code: Option<String>,
|
||||
) -> Self {
|
||||
Self::new(message, kind, code)
|
||||
}
|
||||
}
|
||||
|
||||
/// Ids look like `chatcmpl-<opaque>`; we build one from the wall clock and a
|
||||
/// process counter rather than pulling a uuid crate.
|
||||
pub fn completion_id() -> String {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
let n = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
format!("chatcmpl-{nanos:x}{n:x}")
|
||||
}
|
||||
|
||||
/// Seconds since the epoch, for the `created` fields.
|
||||
pub fn now_unix() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Ids for tool calls look like `call_<opaque>` (OpenAI spelling).
|
||||
pub fn tool_call_id() -> String {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
let n = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
format!("call_{nanos:x}{n:x}")
|
||||
}
|
||||
Reference in new issue
Block a user