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,2 @@
|
||||
/target
|
||||
.idea/
|
||||
Generated
+2290
File diff suppressed because it is too large.
Load diff
+27
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "strata-ctl"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Rust control layer for the Strata inference engine: OpenAI-compatible HTTP API over the engine's line protocol"
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "process", "io-util", "sync", "time", "macros", "signal", "net"] }
|
||||
tracing = "0.1"
|
||||
axum = "0.8"
|
||||
futures = "0.3.34"
|
||||
tokio-stream = "0.1.19"
|
||||
tokenizers = "0.23.2"
|
||||
minijinja = { version = "3.1.0", features = ["serde"] }
|
||||
image = "0.25.10"
|
||||
base64 = "0.23.1"
|
||||
ureq = "3.5.2"
|
||||
|
||||
[dev-dependencies]
|
||||
http-body-util = "0.1.5"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Live smoke demo of the OpenAI surface over a real TCP socket, driven by the
|
||||
//! scripted mock engine (tests/mock_engine.py) and a byte-level formatter — so
|
||||
//! you can `curl` it without a GPU or the Inkling tokenizer.
|
||||
//!
|
||||
//! cargo run --example serve_mock # listens on 127.0.0.1:8080
|
||||
//!
|
||||
//! curl -s localhost:8080/v1/models
|
||||
//! curl -s localhost:8080/v1/chat/completions -H 'content-type: application/json' \
|
||||
//! -d '{"model":"mock","messages":[{"role":"user","content":"hi"}]}'
|
||||
//! # streaming (watch the SSE flush token by token):
|
||||
//! curl -N localhost:8080/v1/chat/completions -H 'content-type: application/json' \
|
||||
//! -d '{"model":"mock","messages":[{"role":"user","content":"hi"}],"stream":true}'
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt};
|
||||
use strata_ctl::api::service::ChatService;
|
||||
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
|
||||
use strata_ctl::engine::Engine;
|
||||
|
||||
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
|
||||
|
||||
struct ByteFormatter;
|
||||
impl Formatter for ByteFormatter {
|
||||
fn model_name(&self) -> &str {
|
||||
"mock"
|
||||
}
|
||||
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
|
||||
let text = req
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|m| m.text())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
Ok(Prompt {
|
||||
ids: text.bytes().map(u32::from).collect(),
|
||||
max_new: req.max_new(64),
|
||||
sampling: Default::default(),
|
||||
temp_files: Vec::new(),
|
||||
})
|
||||
}
|
||||
fn decoder(&self) -> Box<dyn Decoder> {
|
||||
Box::new(ByteDecoder)
|
||||
}
|
||||
}
|
||||
struct ByteDecoder;
|
||||
impl Decoder for ByteDecoder {
|
||||
fn push(&mut self, id: u32) -> Vec<Piece> {
|
||||
if id < 256 {
|
||||
vec![Piece::Content(char::from(id as u8).to_string())]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
fn finish(&mut self, _reason: Option<&str>) -> Vec<Piece> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let engine = Arc::new(
|
||||
Engine::start(
|
||||
"python3",
|
||||
&[MOCK.to_string()],
|
||||
None,
|
||||
Duration::from_secs(15),
|
||||
)
|
||||
.await
|
||||
.expect("failed to start the mock engine (is python3 available?)"),
|
||||
);
|
||||
println!(
|
||||
"mock engine READY, context {} tokens",
|
||||
engine.ready().max_context
|
||||
);
|
||||
|
||||
let svc = ChatService::new(engine.clone(), Arc::new(ByteFormatter));
|
||||
let app = strata_ctl::api::router(svc);
|
||||
|
||||
let addr = std::env::var("ADDR").unwrap_or_else(|_| "127.0.0.1:8080".into());
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
||||
println!("listening on http://{addr} (Ctrl-C to stop)");
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
println!("\nshutting down");
|
||||
let _ = engine.shutdown().await;
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -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}")
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
//! Tolerant loader for the shared model config (`strata-inkling.json`).
|
||||
//!
|
||||
//! The same file configures several tools — this control layer, the upstream
|
||||
//! web shell, and the user's "uostream" front-end. So the contract is:
|
||||
//! **read what we understand, ignore everything else without failing.** In
|
||||
//! serde terms that means no `deny_unknown_fields`; every key we don't consume
|
||||
//! is captured in [`Config::extra`] so `--check` can report exactly what was
|
||||
//! skipped, and an unknown or future key can never break startup.
|
||||
//!
|
||||
//! We deliberately do NOT declare fields we don't act on yet (`arch`,
|
||||
//! `drafting`, `mcp_servers`, `cors_origins`, `allowed_hosts`, ...): they fall
|
||||
//! into `extra` untouched, which is precisely the "ignore what isn't ours"
|
||||
//! behaviour requested.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::engine::protocol::Sampling;
|
||||
|
||||
/// Per-request sampling defaults, the shape found under the JSON's `sampling`
|
||||
/// key. Extra knobs inside `sampling` are likewise tolerated and kept.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct SamplingDefaults {
|
||||
#[serde(default)]
|
||||
pub temperature: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub top_p: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub min_p: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub repetition_penalty: Option<f64>,
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
impl SamplingDefaults {
|
||||
/// The engine `GEN` sampling keys implied by these defaults. Only
|
||||
/// meaningful values become keys (e.g. `repetition_penalty = 1.0` is the
|
||||
/// neutral value and is dropped, matching the engine's own spelling).
|
||||
pub fn to_sampling(&self) -> Sampling {
|
||||
Sampling {
|
||||
temperature: self.temperature,
|
||||
top_p: self.top_p,
|
||||
min_p: self.min_p,
|
||||
repetition_penalty: self.repetition_penalty,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The subset of the config this layer acts on; everything else lives in
|
||||
/// [`Config::extra`].
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Config {
|
||||
/// Engine binary to spawn (required).
|
||||
#[serde(default)]
|
||||
pub exe: String,
|
||||
/// Arguments passed verbatim after `--serve`.
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub cwd: Option<String>,
|
||||
/// HF tokenizer directory (consumed by the Inkling formatter, later).
|
||||
#[serde(default)]
|
||||
pub tokenizer: Option<String>,
|
||||
#[serde(default)]
|
||||
pub model_name: Option<String>,
|
||||
/// Bind overrides (a CLI flag still wins over these).
|
||||
#[serde(default)]
|
||||
pub host: Option<String>,
|
||||
#[serde(default)]
|
||||
pub port: Option<u16>,
|
||||
/// Chain-of-thought effort; the formatter applies it (was the Python
|
||||
/// launcher's monkey-patch).
|
||||
#[serde(default)]
|
||||
pub reasoning_effort: Option<String>,
|
||||
#[serde(default)]
|
||||
pub sampling: SamplingDefaults,
|
||||
|
||||
/// Keys we understand but don't act on yet are NOT listed above, so they
|
||||
/// arrive here untouched — the "ignore what isn't ours" guarantee.
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("cannot read {path}: {source}")]
|
||||
Io {
|
||||
path: String,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("invalid JSON in {path}: {source}")]
|
||||
Parse {
|
||||
path: String,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
#[error("`exe` is required (the Strata engine binary to spawn)")]
|
||||
MissingExe,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Read and validate a config file.
|
||||
pub fn load(path: &Path) -> Result<Config, ConfigError> {
|
||||
let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Io {
|
||||
path: path.display().to_string(),
|
||||
source,
|
||||
})?;
|
||||
let cfg = Self::parse(&text, &path.display().to_string())?;
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
/// Parse from a JSON string (the `path` argument is only for error text).
|
||||
pub fn parse(text: &str, path: &str) -> Result<Config, ConfigError> {
|
||||
let cfg: Config = serde_json::from_str(text).map_err(|source| ConfigError::Parse {
|
||||
path: path.to_string(),
|
||||
source,
|
||||
})?;
|
||||
if cfg.exe.trim().is_empty() {
|
||||
return Err(ConfigError::MissingExe);
|
||||
}
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
/// Default config location, mirroring the Python launcher.
|
||||
pub fn default_path() -> PathBuf {
|
||||
let home = std::env::var("HOME").unwrap_or_default();
|
||||
PathBuf::from(home).join(".config/strata-inkling/strata-inkling.json")
|
||||
}
|
||||
|
||||
/// The full argv for the engine child: `--serve` first (once), then the
|
||||
/// configured args. Idempotent — many configs already include `--serve`.
|
||||
pub fn engine_argv(&self) -> Vec<String> {
|
||||
let mut argv = Vec::with_capacity(self.args.len() + 1);
|
||||
if !self.args.iter().any(|a| a == "--serve") {
|
||||
argv.push("--serve".to_string());
|
||||
}
|
||||
argv.extend(self.args.iter().cloned());
|
||||
argv
|
||||
}
|
||||
|
||||
/// Model id to advertise, defaulting to the exe's file name.
|
||||
pub fn model_name(&self) -> &str {
|
||||
self.model_name.as_deref().unwrap_or_else(|| {
|
||||
Path::new(&self.exe)
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("strata")
|
||||
})
|
||||
}
|
||||
|
||||
/// Effective bind host: CLI override > config > `127.0.0.1`.
|
||||
pub fn bind_host(&self, cli: Option<&str>) -> String {
|
||||
cli.or(self.host.as_deref())
|
||||
.unwrap_or("127.0.0.1")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Effective bind port: CLI override > config > `8095`.
|
||||
pub fn bind_port(&self, cli: Option<u16>) -> u16 {
|
||||
cli.or(self.port).unwrap_or(8095)
|
||||
}
|
||||
|
||||
/// The top-level keys present in the file that we are not acting on —
|
||||
/// reported by `--check` so the shared-file contract stays visible.
|
||||
pub fn ignored_keys(&self) -> Vec<&str> {
|
||||
self.extra.keys().map(|k| k.as_str()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// The user's real config, verbatim shape.
|
||||
const REAL: &str = r#"{
|
||||
"arch": "inkling2_loop",
|
||||
"exe": "/home/federico/Sviluppo/Progetti/strata/build-inkling/strata-inkling",
|
||||
"args": ["--serve", "--native", "/mnt/models/Inkling/model.gguf", "--max-context", "262144", "--parallel", "1"],
|
||||
"cwd": "/home/federico/Sviluppo/Progetti/strata/build-inkling",
|
||||
"tokenizer": "/home/federico/.config/strata-inkling/inkling-tok",
|
||||
"model_name": "Inkling-2-Mini",
|
||||
"host": "0.0.0.0",
|
||||
"cors_origins": ["*"],
|
||||
"allowed_hosts": ["*"],
|
||||
"reasoning_effort": "low",
|
||||
"drafting": "off",
|
||||
"mcp_servers": { "web_shell": { "command": "python3", "args": ["web_shell_mcp.py"] } },
|
||||
"sampling": { "temperature": 1.0, "top_p": 1.0, "min_p": 0.0, "repetition_penalty": 1.0 }
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn reads_the_fields_we_care_about() {
|
||||
let cfg = Config::parse(REAL, "test").unwrap();
|
||||
assert!(cfg.exe.ends_with("strata-inkling"));
|
||||
assert_eq!(cfg.args.len(), 7);
|
||||
assert_eq!(cfg.model_name(), "Inkling-2-Mini");
|
||||
assert_eq!(cfg.host.as_deref(), Some("0.0.0.0"));
|
||||
assert_eq!(cfg.reasoning_effort.as_deref(), Some("low"));
|
||||
assert_eq!(cfg.sampling.temperature, Some(1.0));
|
||||
assert_eq!(
|
||||
cfg.tokenizer.as_deref().unwrap(),
|
||||
"/home/federico/.config/strata-inkling/inkling-tok"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_keys_are_captured_not_fatal() {
|
||||
// the same file also carries uostream / other-tool settings
|
||||
let with_other = r#"{
|
||||
"exe": "/x/strata-inkling",
|
||||
"uostream": { "theme": "dark", "telemetry": true },
|
||||
"future_key": [1, 2, 3],
|
||||
"args": ["--serve"]
|
||||
}"#;
|
||||
let cfg = Config::parse(with_other, "test").unwrap();
|
||||
assert_eq!(cfg.exe, "/x/strata-inkling");
|
||||
assert!(cfg.extra.contains_key("uostream"));
|
||||
assert!(cfg.extra.contains_key("future_key"));
|
||||
let ignored = cfg.ignored_keys();
|
||||
assert!(ignored.contains(&"uostream") && ignored.contains(&"future_key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_but_unused_fields_report_as_ignored() {
|
||||
let cfg = Config::parse(REAL, "test").unwrap();
|
||||
// we don't act on these yet, so they must not be lost or cause errors
|
||||
for k in [
|
||||
"arch",
|
||||
"cors_origins",
|
||||
"allowed_hosts",
|
||||
"drafting",
|
||||
"mcp_servers",
|
||||
] {
|
||||
assert!(cfg.extra.contains_key(k), "{k} should be in ignored extras");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_argv_adds_serve_once() {
|
||||
// REAL args already contain --serve -> no duplicate
|
||||
let cfg = Config::parse(REAL, "test").unwrap();
|
||||
let argv = cfg.engine_argv();
|
||||
assert_eq!(argv.iter().filter(|a| *a == "--serve").count(), 1);
|
||||
|
||||
// a config without --serve gets it prepended
|
||||
let no_serve = r#"{"exe":"/x/e","args":["--native","m.gguf"]}"#;
|
||||
let argv = Config::parse(no_serve, "test").unwrap().engine_argv();
|
||||
assert_eq!(argv, vec!["--serve", "--native", "m.gguf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_exe_is_an_error() {
|
||||
let err = Config::parse(r#"{"args":["--serve"]}"#, "test").unwrap_err();
|
||||
assert!(matches!(err, ConfigError::MissingExe));
|
||||
let err = Config::parse(r#"{"exe":" "}"#, "test").unwrap_err();
|
||||
assert!(matches!(err, ConfigError::MissingExe));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_precedence_cli_over_config_over_default() {
|
||||
let cfg = Config::parse(REAL, "test").unwrap();
|
||||
assert_eq!(cfg.bind_host(None), "0.0.0.0");
|
||||
assert_eq!(cfg.bind_host(Some("127.0.0.1")), "127.0.0.1");
|
||||
assert_eq!(cfg.bind_port(None), 8095); // not in JSON -> default
|
||||
assert_eq!(cfg.bind_port(Some(1234)), 1234);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_defaults_map_to_engine_keys() {
|
||||
let cfg = Config::parse(REAL, "test").unwrap();
|
||||
let s = cfg.sampling.to_sampling();
|
||||
// temperature 1.0 is > 0 so it is sent; repetition_penalty 1.0 is the
|
||||
// neutral value so the engine-spelling builder drops it; min_p 0.0 off.
|
||||
assert_eq!(s.temperature, Some(1.0));
|
||||
assert_eq!(s.repetition_penalty, Some(1.0));
|
||||
let keys = s.keys();
|
||||
assert_eq!(keys, " temperature=1.0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! The engine side: line protocol ([`protocol`]) and process supervisor
|
||||
//! ([`supervisor`]).
|
||||
|
||||
pub mod protocol;
|
||||
pub mod supervisor;
|
||||
|
||||
pub use protocol::{EngineLine, Sampling};
|
||||
pub use supervisor::{Engine, EngineError, Outcome, Ready};
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Line protocol spoken by `strata --serve` on its stdin/stdout.
|
||||
//!
|
||||
//! The engine is a resident child process. We write one command per line and
|
||||
//! it answers with one line per event, per request:
|
||||
//!
|
||||
//! - out: `GEN <max_new> [key=value...] <id>,<id>,...` (also `BGEN <slot> ...`, `STOP`, `QUIT`)
|
||||
//! - in: `READY <ctx> [stop] [hold] [holdb]`, `INFO k=v ...`, `T <id>`,
|
||||
//! `PP <read> <total> [ms] [tok_s]`, `RESUME <n>`,
|
||||
//! `DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <finish> [...]`, `ERR <msg>`
|
||||
//!
|
||||
//! This module is pure parsing/formatting: no IO, so the semantics of every
|
||||
//! shape the engine can answer with are testable without a GPU. The field
|
||||
//! layout mirrors `StrataEngine` in `strata/terminal/serve/server.py` (the
|
||||
//! living spec) — in particular `DONE` grows extra positional fields across
|
||||
//! engine versions, so we only commit to the first five and keep the tail raw.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// One decoded line of engine stdout. Unknown prefixes are preserved as
|
||||
/// [`EngineLine::Other`] rather than dropped: the protocol grows, and a
|
||||
/// supervisor must not lose facts it does not model yet.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum EngineLine {
|
||||
/// First line after startup: the engine's real context size and which
|
||||
/// optional controls it honours (`stop`, `hold`, `holdb`).
|
||||
Ready {
|
||||
max_context: u32,
|
||||
can_stop: bool,
|
||||
can_hold: bool,
|
||||
can_hold_batch: bool,
|
||||
},
|
||||
/// `INFO key=value ...` — engine facts (version, expert slots, ...).
|
||||
Info(BTreeMap<String, String>),
|
||||
/// `T <id>` — one generated token id.
|
||||
Token(u32),
|
||||
/// `PP <read> <total> [ms] [tok_s]` — prompt prefill progress, one per chunk.
|
||||
Prefill {
|
||||
read: u32,
|
||||
total: u32,
|
||||
ms: f64,
|
||||
tok_s_mean: Option<f64>,
|
||||
},
|
||||
/// `RESUME <n>` — prompt tokens taken from the conversation cache, not re-read.
|
||||
Resume(u32),
|
||||
/// `DONE` — end of request, with the engine's figures. See [`Done`].
|
||||
Done(Done),
|
||||
/// `ERR <msg>` — the request (or command) failed.
|
||||
Err(String),
|
||||
/// Anything else the engine printed, verbatim.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The figures of a `DONE` line. Positional fields 1..=5 are stable across
|
||||
/// engine versions; 6+ arrived incrementally (drafts, cache hits, expert
|
||||
/// tiers, ...) and are kept in [`Done::extra`] rather than being guessed at.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Done {
|
||||
pub generated: u32,
|
||||
pub prompt_tokens: u32,
|
||||
pub prompt_ms: f64,
|
||||
pub decode_ms: f64,
|
||||
/// `stop` / `length` / `nonfinite` / ... — the engine's own word.
|
||||
pub finish: String,
|
||||
/// Raw remaining tokens of the line (draft stats, cache hits, kv pairs).
|
||||
pub extra: Vec<String>,
|
||||
}
|
||||
|
||||
/// The kind of a protocol line, for matches that do not need the payload.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LineKind {
|
||||
Ready,
|
||||
Info,
|
||||
Token,
|
||||
Prefill,
|
||||
Resume,
|
||||
Done,
|
||||
Err,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl EngineLine {
|
||||
/// Decodes one line of engine stdout (no trailing newline).
|
||||
pub fn parse(line: &str) -> EngineLine {
|
||||
let trimmed = line.trim();
|
||||
let mut it = trimmed.split_whitespace();
|
||||
match it.next() {
|
||||
Some("READY") => EngineLine::Ready {
|
||||
max_context: it.next().and_then(|v| v.parse().ok()).unwrap_or(0),
|
||||
can_stop: it.clone().any(|f| f == "stop"),
|
||||
can_hold: it.clone().any(|f| f == "hold"),
|
||||
can_hold_batch: it.any(|f| f == "holdb"),
|
||||
},
|
||||
Some("INFO") => EngineLine::Info(
|
||||
it.map(|kv| {
|
||||
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
|
||||
(k.to_string(), v.to_string())
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
Some("T") => EngineLine::Token(it.next().and_then(|v| v.parse().ok()).unwrap_or(0)),
|
||||
Some("PP") => {
|
||||
let f: Vec<&str> = it.collect();
|
||||
EngineLine::Prefill {
|
||||
read: f.first().and_then(|v| v.parse().ok()).unwrap_or(0),
|
||||
total: f.get(1).and_then(|v| v.parse().ok()).unwrap_or(0),
|
||||
ms: f.get(2).and_then(|v| v.parse().ok()).unwrap_or(0.0),
|
||||
tok_s_mean: f.get(3).and_then(|v| v.parse().ok()),
|
||||
}
|
||||
}
|
||||
Some("RESUME") => {
|
||||
EngineLine::Resume(it.next().and_then(|v| v.parse().ok()).unwrap_or(0))
|
||||
}
|
||||
Some("DONE") => {
|
||||
let f: Vec<&str> = it.collect();
|
||||
EngineLine::Done(Done {
|
||||
generated: f.first().and_then(|v| v.parse().ok()).unwrap_or(0),
|
||||
prompt_tokens: f.get(1).and_then(|v| v.parse().ok()).unwrap_or(0),
|
||||
prompt_ms: f.get(2).and_then(|v| v.parse().ok()).unwrap_or(0.0),
|
||||
decode_ms: f.get(3).and_then(|v| v.parse().ok()).unwrap_or(0.0),
|
||||
finish: f.get(4).copied().unwrap_or("unknown").to_string(),
|
||||
extra: f.into_iter().skip(5).map(String::from).collect(),
|
||||
})
|
||||
}
|
||||
Some("ERR") => EngineLine::Err(
|
||||
trimmed
|
||||
.strip_prefix("ERR")
|
||||
.map(|r| r.trim().to_string())
|
||||
.unwrap_or_default(),
|
||||
),
|
||||
_ => EngineLine::Other(trimmed.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Just the kind of the line, consuming it.
|
||||
pub fn into_kind(self) -> LineKind {
|
||||
match self {
|
||||
EngineLine::Ready { .. } => LineKind::Ready,
|
||||
EngineLine::Info(_) => LineKind::Info,
|
||||
EngineLine::Token(_) => LineKind::Token,
|
||||
EngineLine::Prefill { .. } => LineKind::Prefill,
|
||||
EngineLine::Resume(_) => LineKind::Resume,
|
||||
EngineLine::Done(_) => LineKind::Done,
|
||||
EngineLine::Err(_) => LineKind::Err,
|
||||
EngineLine::Other(_) => LineKind::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-request sampling and engine knobs, in the engine's own spelling.
|
||||
/// A field left `None` is not sent, so the engine default applies — matching
|
||||
/// `StrataEngine.sampling_keys`.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Sampling {
|
||||
pub temperature: Option<f64>,
|
||||
pub top_p: Option<f64>,
|
||||
pub top_k: Option<u32>,
|
||||
pub min_p: Option<f64>,
|
||||
/// OpenAI `repetition_penalty` -> engine `penalty_repeat`.
|
||||
pub repetition_penalty: Option<f64>,
|
||||
pub frequency_penalty: Option<f64>,
|
||||
pub presence_penalty: Option<f64>,
|
||||
pub penalty_last_n: Option<u32>,
|
||||
pub seed: Option<u64>,
|
||||
/// Inkling/Hy4 vision: an `image=<encoded path>` key per picture, in prompt order.
|
||||
pub images: Vec<String>,
|
||||
}
|
||||
|
||||
impl Sampling {
|
||||
/// Formats the ` key=value...` fragment of a GEN line (leading space when
|
||||
/// any key is set). Floats print like Python's `repr` (always a decimal
|
||||
/// point); the engine's parser expects that spelling.
|
||||
pub fn keys(&self) -> String {
|
||||
let mut out = String::new();
|
||||
let mut key = |k: &str, v: String| {
|
||||
out.push(' ');
|
||||
out.push_str(k);
|
||||
out.push('=');
|
||||
out.push_str(&v);
|
||||
};
|
||||
if let Some(t) = self.temperature.filter(|t| *t > 0.0) {
|
||||
key("temperature", fmt_float(t));
|
||||
}
|
||||
if let Some(tp) = self.top_p.filter(|tp| *tp < 1.0) {
|
||||
key("top_p", fmt_float(tp));
|
||||
}
|
||||
if let Some(tk) = self.top_k {
|
||||
// the engine's sampled path keeps at most 64 candidates
|
||||
key("top_k", (tk.clamp(1, 64)).to_string());
|
||||
}
|
||||
if let Some(mp) = self.min_p.filter(|mp| *mp > 0.0 && *mp <= 1.0) {
|
||||
key("min_p", fmt_float(mp));
|
||||
}
|
||||
let any_penalty = self.repetition_penalty.is_some_and(|p| p != 1.0)
|
||||
|| self.frequency_penalty.is_some_and(|p| p != 0.0)
|
||||
|| self.presence_penalty.is_some_and(|p| p != 0.0);
|
||||
if let Some(rp) = self.repetition_penalty.filter(|p| *p != 1.0) {
|
||||
key("penalty_repeat", fmt_float(rp));
|
||||
}
|
||||
if let Some(pf) = self.frequency_penalty.filter(|p| *p != 0.0) {
|
||||
key("penalty_freq", fmt_float(pf));
|
||||
}
|
||||
if let Some(pp) = self.presence_penalty.filter(|p| *p != 0.0) {
|
||||
key("penalty_present", fmt_float(pp));
|
||||
}
|
||||
if any_penalty {
|
||||
// a penalty without a window counts over nothing: default to 64
|
||||
let n = self.penalty_last_n.filter(|n| *n > 0).unwrap_or(64);
|
||||
key("penalty_last_n", n.to_string());
|
||||
}
|
||||
if let Some(seed) = self.seed.filter(|s| *s > 0) {
|
||||
key("seed", seed.to_string());
|
||||
}
|
||||
for path in &self.images {
|
||||
key("image", path.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_float(v: f64) -> String {
|
||||
// Python repr: 1.0 -> "1.0", 0.7 -> "0.7". Rust `{}` on an f64 already
|
||||
// keeps ".0" for integral values, so it matches for our ranges.
|
||||
let s = format!("{v}");
|
||||
if s.contains('.') {
|
||||
s
|
||||
} else {
|
||||
format!("{s}.0")
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `GEN <max_new> [keys] <ids>` line.
|
||||
pub fn gen_line(max_new: u32, sampling: &Sampling, ids: &[u32]) -> String {
|
||||
format!(
|
||||
"GEN {max_new}{} {}\n",
|
||||
sampling.keys(),
|
||||
ids.iter()
|
||||
.map(|i| i.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ready_flags() {
|
||||
assert_eq!(
|
||||
EngineLine::parse("READY 262144 stop hold"),
|
||||
EngineLine::Ready {
|
||||
max_context: 262144,
|
||||
can_stop: true,
|
||||
can_hold: true,
|
||||
can_hold_batch: false,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
EngineLine::parse("READY 4096"),
|
||||
EngineLine::Ready {
|
||||
max_context: 4096,
|
||||
can_stop: false,
|
||||
can_hold: false,
|
||||
can_hold_batch: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_pairs() {
|
||||
let EngineLine::Info(m) = EngineLine::parse("INFO version=0.1.39 expert_slots=64") else {
|
||||
panic!("not INFO");
|
||||
};
|
||||
assert_eq!(m["version"], "0.1.39");
|
||||
assert_eq!(m["expert_slots"], "64");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_and_resume() {
|
||||
assert_eq!(EngineLine::parse("T 151645"), EngineLine::Token(151645));
|
||||
assert_eq!(EngineLine::parse("RESUME 512"), EngineLine::Resume(512));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefill_progress() {
|
||||
assert_eq!(
|
||||
EngineLine::parse("PP 1024 8192 431.5 2373.2"),
|
||||
EngineLine::Prefill {
|
||||
read: 1024,
|
||||
total: 8192,
|
||||
ms: 431.5,
|
||||
tok_s_mean: Some(2373.2),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn done_five_fields() {
|
||||
let EngineLine::Done(d) = EngineLine::parse("DONE 41 128 90.5 310.25 stop") else {
|
||||
panic!("not DONE");
|
||||
};
|
||||
assert_eq!(d.generated, 41);
|
||||
assert_eq!(d.prompt_tokens, 128);
|
||||
assert_eq!(d.finish, "stop");
|
||||
assert!(d.extra.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn done_extra_fields_stay_raw() {
|
||||
// engine 0.1.3+: drafts/reused; 0.1.31+: expert tiers; then kv tails
|
||||
let EngineLine::Done(d) = EngineLine::parse(
|
||||
"DONE 41 128 90.5 310.25 length 7 10 55 3 40 1 2 3.5 120 9 chunk=2048",
|
||||
) else {
|
||||
panic!("not DONE");
|
||||
};
|
||||
assert_eq!(d.extra.len(), 11);
|
||||
assert_eq!(d.extra.last().unwrap(), "chunk=2048");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn err_message() {
|
||||
assert_eq!(
|
||||
EngineLine::parse("ERR GEN: unknown/unsupported key pen_from"),
|
||||
EngineLine::Err("GEN: unknown/unsupported key pen_from".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_line_preserved() {
|
||||
assert_eq!(
|
||||
EngineLine::parse("SOMETHING_NEW 1 2"),
|
||||
EngineLine::Other("SOMETHING_NEW 1 2".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_keys_match_engine_spelling() {
|
||||
let s = Sampling {
|
||||
temperature: Some(1.0),
|
||||
top_p: Some(0.9),
|
||||
top_k: Some(200), // clamped to the engine's 64-candidate path
|
||||
min_p: Some(0.0), // not sent: 0 means off
|
||||
seed: Some(42),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s.keys(), " temperature=1.0 top_p=0.9 top_k=64 seed=42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penalties_drag_the_window() {
|
||||
let s = Sampling {
|
||||
repetition_penalty: Some(1.1),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s.keys(), " penalty_repeat=1.1 penalty_last_n=64");
|
||||
// penalty 1.0 is the neutral value: nothing is sent, no window either
|
||||
let neutral = Sampling {
|
||||
repetition_penalty: Some(1.0),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(neutral.keys(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn greedy_temperature_not_sent() {
|
||||
// temperature=0 is the engine's default (greedy): forwarding it is noise
|
||||
let s = Sampling {
|
||||
temperature: Some(0.0),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s.keys(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gen_line_shape() {
|
||||
let s = Sampling {
|
||||
temperature: Some(0.8),
|
||||
images: vec!["%2Fmnt%2Fpic.png".into()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
gen_line(512, &s, &[1, 2, 300]),
|
||||
"GEN 512 temperature=0.8 image=%2Fmnt%2Fpic.png 1,2,300\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! Supervisor of the resident `strata --serve` child process.
|
||||
//!
|
||||
//! The engine speaks a line protocol on stdin/stdout (see [`super::protocol`]).
|
||||
//! This module owns the process: start, one request at a time (the Python
|
||||
//! layer serializes requests on a FIFO too — a `--parallel 1` engine has one
|
||||
//! control stream and one conversation cache), STOP-then-drain when a request
|
||||
//! ends early, and a clean QUIT on shutdown.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::process::Command;
|
||||
use tokio::process::{Child, ChildStdin, ChildStdout};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use super::protocol::{gen_line, Done, EngineLine, LineKind, Sampling};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
#[error("failed to spawn the engine: {0}")]
|
||||
Spawn(std::io::Error),
|
||||
#[error("the engine did not become ready: {0}")]
|
||||
Startup(String),
|
||||
#[error("the engine stopped unexpectedly")]
|
||||
Died,
|
||||
#[error("the engine refused the request: {0}")]
|
||||
Refused(String),
|
||||
#[error("the engine produced no output for {0:?}")]
|
||||
Silent(Duration),
|
||||
}
|
||||
|
||||
/// What the engine advertised on its `READY` line.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Ready {
|
||||
pub max_context: u32,
|
||||
pub can_stop: bool,
|
||||
pub can_hold: bool,
|
||||
pub can_hold_batch: bool,
|
||||
}
|
||||
|
||||
/// Everything one request collected from the engine's answer.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Outcome {
|
||||
/// The generated token ids, in order.
|
||||
pub tokens: Vec<u32>,
|
||||
/// The engine's figures from its `DONE` line.
|
||||
pub done: Option<Done>,
|
||||
/// Prompt tokens served from the conversation cache (`RESUME`).
|
||||
pub resumed: u32,
|
||||
}
|
||||
|
||||
/// A running engine plus the mutex that keeps one request on the wires at a
|
||||
/// time. Cheap to share: wrap in `Arc` and every HTTP handler contends on it.
|
||||
pub struct Engine {
|
||||
pipes: Mutex<Guarded>,
|
||||
/// The in-flight request's cancel flag and a second handle on stdin, so
|
||||
/// `abort` works while a request holds the lock (Python's `cancel` event
|
||||
/// and the STOP write from another thread).
|
||||
ctl: Abort,
|
||||
ready: Ready,
|
||||
info: Mutex<BTreeMap<String, String>>,
|
||||
silence: Duration,
|
||||
}
|
||||
|
||||
struct Abort {
|
||||
flag: std::sync::atomic::AtomicBool,
|
||||
stdin: tokio::sync::Mutex<ChildStdin>,
|
||||
}
|
||||
|
||||
/// The child and its pipes, handed to whoever holds the request lock.
|
||||
struct Guarded {
|
||||
child: Child,
|
||||
stdout: BufReader<ChildStdout>,
|
||||
dead: bool,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
/// Spawns `<exe> <args...>` (the supervisor is generic: the config layer
|
||||
/// builds the full argv, e.g. `["--serve", "--native", model, ...]` for the
|
||||
/// real engine) and waits, up to `ready_timeout`, for the `READY` line,
|
||||
/// logging the startup `INFO` facts on the way.
|
||||
pub async fn start(
|
||||
exe: &str,
|
||||
args: &[String],
|
||||
cwd: Option<&str>,
|
||||
ready_timeout: Duration,
|
||||
) -> Result<Self, EngineError> {
|
||||
let mut cmd = Command::new(exe);
|
||||
cmd.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
let mut child = cmd.spawn().map_err(EngineError::Spawn)?;
|
||||
let stdin = child.stdin.take().expect("stdin piped");
|
||||
let stdout = BufReader::new(child.stdout.take().expect("stdout piped"));
|
||||
let mut guarded = Guarded {
|
||||
child,
|
||||
stdout,
|
||||
dead: false,
|
||||
};
|
||||
let ctl = Abort {
|
||||
flag: std::sync::atomic::AtomicBool::new(false),
|
||||
stdin: Mutex::new(stdin),
|
||||
};
|
||||
|
||||
// Everything before READY is startup chatter; a protocol line that is
|
||||
// neither READY nor INFO means the engine refused to start (bad model
|
||||
// path, no VRAM, ...): surface it instead of timing out.
|
||||
let mut unexpected: Vec<String> = Vec::new();
|
||||
let mut startup_info: BTreeMap<String, String> = BTreeMap::new();
|
||||
let ready = match tokio::time::timeout(ready_timeout, async {
|
||||
loop {
|
||||
let line = match read_line(&mut guarded.stdout).await {
|
||||
Ok(l) => l,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
match EngineLine::parse(&line) {
|
||||
EngineLine::Ready {
|
||||
max_context,
|
||||
can_stop,
|
||||
can_hold,
|
||||
can_hold_batch,
|
||||
} => {
|
||||
return Ok(Ready {
|
||||
max_context,
|
||||
can_stop,
|
||||
can_hold,
|
||||
can_hold_batch,
|
||||
})
|
||||
}
|
||||
EngineLine::Info(kv) => {
|
||||
startup_info.extend(kv);
|
||||
}
|
||||
EngineLine::Err(msg) => {
|
||||
return Err(EngineError::Startup(format!(
|
||||
"the engine refused to start: {msg}"
|
||||
)))
|
||||
}
|
||||
_ => unexpected.push(line.trim().to_string()),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
Err(_) => {
|
||||
return Err(EngineError::Startup(format!(
|
||||
"timed out waiting for READY (saw: {unexpected:?})"
|
||||
)))
|
||||
}
|
||||
Ok(r) => r,
|
||||
}?;
|
||||
|
||||
for (k, v) in &startup_info {
|
||||
tracing::info!(key = %k, value = %v, "engine info");
|
||||
}
|
||||
Ok(Self {
|
||||
pipes: Mutex::new(guarded),
|
||||
ctl,
|
||||
ready,
|
||||
info: Mutex::new(startup_info),
|
||||
silence: Duration::from_secs(600),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn ready(&self) -> Ready {
|
||||
self.ready
|
||||
}
|
||||
|
||||
pub async fn info(&self) -> BTreeMap<String, String> {
|
||||
self.info.lock().await.clone()
|
||||
}
|
||||
|
||||
/// Runs one generation to completion, forwarding each engine line to
|
||||
/// `on_event` as it arrives. Returns when the engine prints `DONE`, or on
|
||||
/// refusal/death. Requests queue on the engine's lock — like the Python
|
||||
/// service's FIFO — since one engine has one control stream and one
|
||||
/// conversation cache.
|
||||
pub async fn generate<F>(
|
||||
&self,
|
||||
max_new: u32,
|
||||
sampling: &Sampling,
|
||||
ids: &[u32],
|
||||
mut on_event: F,
|
||||
) -> Result<Outcome, EngineError>
|
||||
where
|
||||
F: FnMut(&EngineLine),
|
||||
{
|
||||
let mut g = self.pipes.lock().await;
|
||||
if g.dead {
|
||||
return Err(EngineError::Died);
|
||||
}
|
||||
|
||||
let line = gen_line(max_new, sampling, ids);
|
||||
self.ctl
|
||||
.flag
|
||||
.store(false, std::sync::atomic::Ordering::Relaxed);
|
||||
if let Err(e) = self.send(&line).await {
|
||||
g.dead = true;
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let mut out = Outcome::default();
|
||||
loop {
|
||||
// `abort` (client gone, caller gave up) only needs to set the flag
|
||||
// and reach the engine's stdin: the DONE it triggers is drained
|
||||
// here, inside the request that owns the wires.
|
||||
if self.ctl.flag.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
self.send("STOP\n").await?;
|
||||
drain_to_done(&mut g.stdout).await?;
|
||||
return Err(EngineError::Refused("aborted".into()));
|
||||
}
|
||||
let raw = match tokio::time::timeout(self.silence, read_line(&mut g.stdout)).await {
|
||||
Err(_) => {
|
||||
// Computing a huge prompt or hung, we cannot tell: stop it
|
||||
// and report, like Python's silence watchdog. The DONE we
|
||||
// trigger is drained here, so the wires stay usable.
|
||||
let _ = self.send("STOP\n").await;
|
||||
let _ = drain_to_done(&mut g.stdout).await;
|
||||
return Err(EngineError::Silent(self.silence));
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
g.dead = true;
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Ok(raw)) => raw,
|
||||
};
|
||||
let parsed = EngineLine::parse(&raw);
|
||||
match &parsed {
|
||||
EngineLine::Token(id) => out.tokens.push(*id),
|
||||
EngineLine::Resume(n) => out.resumed = *n,
|
||||
EngineLine::Info(kv) => {
|
||||
self.info.lock().await.extend(kv.clone());
|
||||
}
|
||||
EngineLine::Done(done) => {
|
||||
out.done = Some(done.clone());
|
||||
on_event(&parsed);
|
||||
return Ok(out);
|
||||
}
|
||||
EngineLine::Err(msg) => {
|
||||
// An engine that ends a request on ERR may still print its
|
||||
// DONE: swallow it, or the next request would read it as
|
||||
// its own (serve/server.py `_swallow_trailing_done`).
|
||||
swallow_trailing_done(&mut g.stdout).await;
|
||||
return Err(EngineError::Refused(msg.clone()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
on_event(&parsed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one command to the engine's stdin (shared with `abort`, which
|
||||
/// may run while a request holds the read lock).
|
||||
async fn send(&self, line: &str) -> Result<(), EngineError> {
|
||||
let mut stdin = self.ctl.stdin.lock().await;
|
||||
write(&mut stdin, line).await
|
||||
}
|
||||
|
||||
/// Signals the in-flight request to stop (like Python's `cancel` event):
|
||||
/// sets the flag and pokes the engine with STOP. The request's own future
|
||||
/// drains to DONE, so this returns promptly even while a request holds the
|
||||
/// wires. `Ok(false)` when nothing is running to abort.
|
||||
pub async fn abort(&self) -> Result<bool, EngineError> {
|
||||
// If we can grab the read lock, no request owns the wires: nothing to
|
||||
// abort. Otherwise flag the running request (it drains) and send STOP.
|
||||
if self.pipes.try_lock().is_ok() {
|
||||
return Ok(false);
|
||||
}
|
||||
self.ctl
|
||||
.flag
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
self.send("STOP\n").await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// True when no request owns the wires (non-mutating probe, unlike abort).
|
||||
pub fn is_idle(&self) -> bool {
|
||||
self.pipes.try_lock().is_ok()
|
||||
}
|
||||
|
||||
/// `QUIT` and reap the child.
|
||||
pub async fn shutdown(&self) -> Result<(), EngineError> {
|
||||
let mut g = self.pipes.lock().await;
|
||||
if g.dead {
|
||||
return Ok(());
|
||||
}
|
||||
let _ = self.send("QUIT\n").await;
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), g.child.wait()).await;
|
||||
let _ = g.child.start_kill();
|
||||
g.dead = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn drain_to_done(stdout: &mut BufReader<ChildStdout>) -> Result<(), EngineError> {
|
||||
loop {
|
||||
match EngineLine::parse(&read_line(stdout).await?).into_kind() {
|
||||
LineKind::Done | LineKind::Err => return Ok(()),
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn swallow_trailing_done(stdout: &mut BufReader<ChildStdout>) {
|
||||
for _ in 0..4 {
|
||||
let Ok(Ok(raw)) = tokio::time::timeout(Duration::from_millis(300), read_line(stdout)).await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
match EngineLine::parse(&raw).into_kind() {
|
||||
LineKind::Done | LineKind::Err => return,
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn write(stdin: &mut ChildStdin, line: &str) -> Result<(), EngineError> {
|
||||
stdin
|
||||
.write_all(line.as_bytes())
|
||||
.await
|
||||
.map_err(|_| EngineError::Died)?;
|
||||
stdin.flush().await.map_err(|_| EngineError::Died)
|
||||
}
|
||||
|
||||
/// Reads one line; EOF (the engine exited) is [`EngineError::Died`].
|
||||
async fn read_line(stdout: &mut BufReader<ChildStdout>) -> Result<String, EngineError> {
|
||||
let mut line = String::new();
|
||||
let n = stdout
|
||||
.read_line(&mut line)
|
||||
.await
|
||||
.map_err(|_| EngineError::Died)?;
|
||||
if n == 0 {
|
||||
return Err(EngineError::Died);
|
||||
}
|
||||
Ok(line)
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
//! The Inkling-2-Mini output channel dialect, ported faithfully from
|
||||
//! `serve/inkling_dialect.py` **as patched by the launcher `run_strata_cot.py`**.
|
||||
//!
|
||||
//! The model emits special *channel tokens* that segment its output. The engine
|
||||
//! streams them to us as detokenized pieces, and the server drives us once per
|
||||
//! token via [`InklingDialect::feed_token`] with `is_special` set for the channel
|
||||
//! tokens (mirrors `server.py`: `parser.feed_token(piece, is_special=(t in
|
||||
//! inkling_special_ids))`). We translate that into typed pieces: reasoning
|
||||
//! (chain-of-thought) and content (the answer, plus tool invocations rendered as
|
||||
//! JSON inside a tool-call frame).
|
||||
//!
|
||||
//! Two behaviours come from the launcher patch, not the base class: thinking is
|
||||
//! streamed live as it arrives (rather than accumulated and hidden), and the
|
||||
//! reasoning effort is whatever the config sets. We reproduce that patched
|
||||
//! behaviour, which is what actually runs on this machine.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// Channel tag literals, exactly as the detokenizer spells them.
|
||||
pub mod tag {
|
||||
pub const MESSAGE_MODEL: &str = "<|message_model|>";
|
||||
pub const CONTENT_THINKING: &str = "<|content_thinking|>";
|
||||
pub const CONTENT_TEXT: &str = "<|content_text|>";
|
||||
pub const CONTENT_INVOKE_TOOL_JSON: &str = "<|content_invoke_tool_json|>";
|
||||
pub const CONTENT_INVOKE_TOOL_TEXT: &str = "<|content_invoke_tool_text|>";
|
||||
pub const CONTENT_XML: &str = "<|content_xml|>";
|
||||
pub const END_MESSAGE: &str = "<|end_message|>";
|
||||
pub const END_SAMPLING: &str = "<|content_model_end_sampling|>";
|
||||
pub const ENDOFTEXT: &str = "<|endoftext|>";
|
||||
/// The downstream OpenAI tool layer reads frames delimited by these; JSON
|
||||
/// inside them preserves arbitrary characters losslessly.
|
||||
pub const TOOL_CALL_OPEN: &str = "<tool_call>";
|
||||
pub const TOOL_CALL_CLOSE: &str = "</tool_call>";
|
||||
}
|
||||
|
||||
/// Which output channel a piece belongs to.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Reasoning,
|
||||
Content,
|
||||
}
|
||||
|
||||
/// A typed output chunk produced by the dialect.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Out {
|
||||
pub kind: Kind,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
fn reasoning(text: impl Into<String>) -> Self {
|
||||
Out {
|
||||
kind: Kind::Reasoning,
|
||||
text: text.into(),
|
||||
}
|
||||
}
|
||||
fn content(text: impl Into<String>) -> Self {
|
||||
Out {
|
||||
kind: Kind::Content,
|
||||
text: text.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The channel/structural tokens.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Tag {
|
||||
MessageModel,
|
||||
ContentThinking,
|
||||
ContentText,
|
||||
ContentInvokeToolJson,
|
||||
ContentInvokeToolText,
|
||||
ContentXml,
|
||||
EndMessage,
|
||||
EndSampling,
|
||||
EndOfText,
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
use tag::*;
|
||||
match self {
|
||||
Tag::MessageModel => MESSAGE_MODEL,
|
||||
Tag::ContentThinking => CONTENT_THINKING,
|
||||
Tag::ContentText => CONTENT_TEXT,
|
||||
Tag::ContentInvokeToolJson => CONTENT_INVOKE_TOOL_JSON,
|
||||
Tag::ContentInvokeToolText => CONTENT_INVOKE_TOOL_TEXT,
|
||||
Tag::ContentXml => CONTENT_XML,
|
||||
Tag::EndMessage => END_MESSAGE,
|
||||
Tag::EndSampling => END_SAMPLING,
|
||||
Tag::EndOfText => ENDOFTEXT,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Tag> {
|
||||
use tag::*;
|
||||
Some(match s {
|
||||
MESSAGE_MODEL => Tag::MessageModel,
|
||||
CONTENT_THINKING => Tag::ContentThinking,
|
||||
CONTENT_TEXT => Tag::ContentText,
|
||||
CONTENT_INVOKE_TOOL_JSON => Tag::ContentInvokeToolJson,
|
||||
CONTENT_INVOKE_TOOL_TEXT => Tag::ContentInvokeToolText,
|
||||
CONTENT_XML => Tag::ContentXml,
|
||||
END_MESSAGE => Tag::EndMessage,
|
||||
END_SAMPLING => Tag::EndSampling,
|
||||
ENDOFTEXT => Tag::EndOfText,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_TAGS: [Tag; 9] = [
|
||||
Tag::MessageModel,
|
||||
Tag::ContentThinking,
|
||||
Tag::ContentText,
|
||||
Tag::ContentInvokeToolJson,
|
||||
Tag::ContentInvokeToolText,
|
||||
Tag::ContentXml,
|
||||
Tag::EndMessage,
|
||||
Tag::EndSampling,
|
||||
Tag::EndOfText,
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
enum State {
|
||||
#[default]
|
||||
Idle,
|
||||
Header,
|
||||
Think,
|
||||
ThinkEnd,
|
||||
Text,
|
||||
TextEnd,
|
||||
ToolJson,
|
||||
ToolText,
|
||||
}
|
||||
|
||||
const MAX_HEADER_CHARS: usize = 128;
|
||||
const MAX_THINK_ACC: usize = 65536;
|
||||
|
||||
/// The tags valid as transitions in each state (mirrors `_tags_for`).
|
||||
fn tags_for(state: State) -> &'static [Tag] {
|
||||
use State::*;
|
||||
match state {
|
||||
Idle | Header | ThinkEnd | TextEnd => &ALL_TAGS,
|
||||
Think => &[
|
||||
Tag::EndMessage,
|
||||
Tag::ContentText,
|
||||
Tag::EndSampling,
|
||||
Tag::EndOfText,
|
||||
],
|
||||
Text => &[Tag::EndMessage, Tag::EndSampling, Tag::EndOfText],
|
||||
ToolJson | ToolText => &[Tag::EndMessage, Tag::EndSampling, Tag::EndOfText],
|
||||
}
|
||||
}
|
||||
|
||||
/// One instance per assistant reply: consumes the engine's token stream and
|
||||
/// yields typed reasoning/content pieces.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct InklingDialect {
|
||||
state: State,
|
||||
header_acc: String,
|
||||
tool_acc: String,
|
||||
think_acc: String,
|
||||
end_ws: String,
|
||||
emitted_visible: bool,
|
||||
/// How many tool frames have been rendered (diagnostics).
|
||||
pub calls: u32,
|
||||
}
|
||||
|
||||
impl InklingDialect {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Current state name, for tests and diagnostics.
|
||||
pub fn state(&self) -> &'static str {
|
||||
match self.state {
|
||||
State::Idle => "idle",
|
||||
State::Header => "header",
|
||||
State::Think => "think",
|
||||
State::ThinkEnd => "think_end",
|
||||
State::Text => "text",
|
||||
State::TextEnd => "text_end",
|
||||
State::ToolJson => "tool_json",
|
||||
State::ToolText => "tool_text",
|
||||
}
|
||||
}
|
||||
|
||||
/// Token-aware entry: `piece` is one detokenized token; ordinary BPE text
|
||||
/// (`is_special = false`) is literal content and can never drive a channel
|
||||
/// transition, even if it spells a tag. Real channel tokens do.
|
||||
pub fn feed_token(&mut self, piece: &str, is_special: bool) -> Vec<Out> {
|
||||
let mut out = Vec::new();
|
||||
if piece.is_empty() {
|
||||
return out;
|
||||
}
|
||||
if is_special {
|
||||
if let Some(tag) = Tag::parse(piece) {
|
||||
if tags_for(self.state).contains(&tag) {
|
||||
self.handle_tag(tag, &mut out);
|
||||
} else {
|
||||
// A real channel tag illegal in this state is emitted
|
||||
// verbatim in the current channel (e.g. quoted in thinking).
|
||||
self.emit(piece, &mut out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
self.emit(piece, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Flush at end of stream. `reason` is the finish word (`"length"`, ...).
|
||||
pub fn finish(&mut self, reason: Option<&str>) -> Vec<Out> {
|
||||
let mut out = Vec::new();
|
||||
self.finish_into(&mut out, reason);
|
||||
out
|
||||
}
|
||||
|
||||
/// `_emit_typed`, patched: live reasoning for the thinking states; base
|
||||
/// behaviour for everything else.
|
||||
fn emit(&mut self, chunk: &str, out: &mut Vec<Out>) {
|
||||
if chunk.is_empty() {
|
||||
return;
|
||||
}
|
||||
match self.state {
|
||||
// patched: thinking streams live instead of being hidden
|
||||
State::Think => {
|
||||
self.append_think(chunk);
|
||||
out.push(Out::reasoning(chunk));
|
||||
}
|
||||
State::ThinkEnd => {
|
||||
if chunk.trim().is_empty() {
|
||||
self.end_ws.push_str(chunk);
|
||||
return;
|
||||
}
|
||||
let combined = format!("{}{}{}", tag::END_MESSAGE, self.end_ws, chunk);
|
||||
self.append_think(&combined);
|
||||
out.push(Out::reasoning(combined));
|
||||
self.end_ws.clear();
|
||||
self.state = State::Think;
|
||||
}
|
||||
// ---- base `_emit_typed` for the remaining states ----
|
||||
State::TextEnd => {
|
||||
if chunk.trim().is_empty() {
|
||||
self.end_ws.push_str(chunk);
|
||||
return;
|
||||
}
|
||||
out.push(Out::content(format!(
|
||||
"{}{}{}",
|
||||
tag::END_MESSAGE,
|
||||
self.end_ws,
|
||||
chunk
|
||||
)));
|
||||
self.emitted_visible = true;
|
||||
self.end_ws.clear();
|
||||
self.state = State::Text;
|
||||
}
|
||||
State::Idle => {
|
||||
out.push(Out::content(chunk));
|
||||
if !chunk.trim().is_empty() {
|
||||
self.emitted_visible = true;
|
||||
self.state = State::Text;
|
||||
}
|
||||
}
|
||||
State::Text => {
|
||||
out.push(Out::content(chunk));
|
||||
if !chunk.trim().is_empty() {
|
||||
self.emitted_visible = true;
|
||||
}
|
||||
}
|
||||
State::Header => {
|
||||
self.header_acc.push_str(chunk);
|
||||
// A real tool-name header is short and single-line; newlines or
|
||||
// an over-long run mean the model skipped content_text and is
|
||||
// writing plain text (#6620).
|
||||
if self.header_acc.contains('\n')
|
||||
|| self.header_acc.chars().count() > MAX_HEADER_CHARS
|
||||
{
|
||||
let acc = std::mem::take(&mut self.header_acc);
|
||||
out.push(Out::content(acc));
|
||||
self.emitted_visible = true;
|
||||
self.state = State::Text;
|
||||
}
|
||||
}
|
||||
State::ToolJson | State::ToolText => {
|
||||
self.tool_acc.push_str(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn append_think(&mut self, chunk: &str) {
|
||||
if !chunk.is_empty() && self.think_acc.len() < MAX_THINK_ACC {
|
||||
let room = MAX_THINK_ACC - self.think_acc.len();
|
||||
let take = room.min(chunk.len());
|
||||
// slice on a char boundary
|
||||
let mut end = take;
|
||||
while end > 0 && !chunk.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
self.think_acc.push_str(&chunk[..end]);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_tag(&mut self, tag: Tag, out: &mut Vec<Out>) {
|
||||
match tag {
|
||||
Tag::EndSampling | Tag::EndOfText => {
|
||||
self.close_channel(out);
|
||||
self.state = State::Idle;
|
||||
}
|
||||
Tag::EndMessage => match self.state {
|
||||
State::Think => {
|
||||
self.end_ws.clear();
|
||||
self.state = State::ThinkEnd;
|
||||
}
|
||||
// Second end-message after a quoted one in thinking: absorb the
|
||||
// first, hold the second (#6675).
|
||||
State::ThinkEnd => {
|
||||
let held = format!("{}{}", tag::END_MESSAGE, self.end_ws);
|
||||
self.append_think(&held);
|
||||
self.end_ws.clear();
|
||||
}
|
||||
State::Text => {
|
||||
self.end_ws.clear();
|
||||
self.state = State::TextEnd;
|
||||
}
|
||||
// Adjacent quoted + real end-message in visible text: emit the
|
||||
// first, hold the second (#6675).
|
||||
State::TextEnd => {
|
||||
out.push(Out::content(format!("{}{}", tag::END_MESSAGE, self.end_ws)));
|
||||
self.emitted_visible = true;
|
||||
self.end_ws.clear();
|
||||
}
|
||||
_ => {
|
||||
self.close_channel(out);
|
||||
self.state = State::Idle;
|
||||
}
|
||||
},
|
||||
Tag::MessageModel => {
|
||||
self.close_channel(out);
|
||||
self.state = State::Header;
|
||||
self.header_acc.clear();
|
||||
}
|
||||
Tag::ContentThinking => {
|
||||
self.close_channel(out);
|
||||
self.header_acc.clear();
|
||||
self.think_acc.clear();
|
||||
self.state = State::Think;
|
||||
}
|
||||
Tag::ContentText => {
|
||||
if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) {
|
||||
self.close_channel(out);
|
||||
}
|
||||
self.header_acc.clear();
|
||||
self.state = State::Text;
|
||||
}
|
||||
Tag::ContentInvokeToolJson => {
|
||||
if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) {
|
||||
self.close_channel(out);
|
||||
}
|
||||
self.state = State::ToolJson;
|
||||
self.tool_acc.clear();
|
||||
}
|
||||
Tag::ContentInvokeToolText | Tag::ContentXml => {
|
||||
if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) {
|
||||
self.close_channel(out);
|
||||
}
|
||||
self.state = State::ToolText;
|
||||
self.tool_acc.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn close_channel(&mut self, out: &mut Vec<Out>) {
|
||||
// Snapshot to avoid holding a borrow of self across the mutation.
|
||||
let state = self.state;
|
||||
let header = std::mem::take(&mut self.header_acc);
|
||||
let tool = std::mem::take(&mut self.tool_acc);
|
||||
match state {
|
||||
State::ToolJson | State::ToolText => {
|
||||
let rendered = parse_tool_body(&header, &tool, state, false);
|
||||
if !rendered.is_empty() {
|
||||
if rendered.contains(tag::TOOL_CALL_OPEN) {
|
||||
self.calls += 1;
|
||||
}
|
||||
out.push(Out::content(rendered));
|
||||
self.emitted_visible = true;
|
||||
}
|
||||
}
|
||||
State::Header => {
|
||||
if !header.is_empty() {
|
||||
out.push(Out::content(header));
|
||||
self.emitted_visible = true;
|
||||
}
|
||||
}
|
||||
State::Think | State::ThinkEnd => {
|
||||
self.end_ws.clear();
|
||||
}
|
||||
State::TextEnd => self.end_ws.clear(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_into(&mut self, out: &mut Vec<Out>, reason: Option<&str>) {
|
||||
let state = self.state;
|
||||
let header = std::mem::take(&mut self.header_acc);
|
||||
let tool = std::mem::take(&mut self.tool_acc);
|
||||
let think = std::mem::take(&mut self.think_acc);
|
||||
|
||||
match state {
|
||||
State::Header if !header.is_empty() => {
|
||||
out.push(Out::content(header));
|
||||
self.emitted_visible = true;
|
||||
}
|
||||
State::ToolJson | State::ToolText
|
||||
if !tool.trim().is_empty() || !header.trim().is_empty() =>
|
||||
{
|
||||
let rendered = parse_tool_body(&header, &tool, state, true);
|
||||
if !rendered.is_empty() {
|
||||
if rendered.contains(tag::TOOL_CALL_OPEN) {
|
||||
self.calls += 1;
|
||||
}
|
||||
out.push(Out::content(rendered));
|
||||
self.emitted_visible = true;
|
||||
}
|
||||
}
|
||||
// #6682: budget expired inside thinking with no visible answer yet:
|
||||
// surface the truncated thinking rather than an empty 200 OK.
|
||||
State::Think | State::ThinkEnd
|
||||
if reason == Some("length")
|
||||
&& !self.emitted_visible
|
||||
&& !think.trim().is_empty() =>
|
||||
{
|
||||
out.push(Out::reasoning(think));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.end_ws.clear();
|
||||
self.state = State::Idle;
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize a call as OPEN newline json newline CLOSE, escaping the sequence
|
||||
/// "</" as "<\/" so a literal close-marker inside arguments cannot break the
|
||||
/// frame.
|
||||
fn safe_json_call(name: &str, arguments: Value) -> String {
|
||||
let mut obj = Map::new();
|
||||
obj.insert("name".into(), Value::String(name.to_string()));
|
||||
obj.insert("arguments".into(), arguments);
|
||||
let payload = Value::Object(obj).to_string().replace("</", "<\\/");
|
||||
format!(
|
||||
"{}\n{}\n{}",
|
||||
tag::TOOL_CALL_OPEN,
|
||||
payload,
|
||||
tag::TOOL_CALL_CLOSE
|
||||
)
|
||||
}
|
||||
|
||||
/// First "{" to last "}" (greedy): the fallback for a truncated/dirtied body.
|
||||
fn extract_object(raw: &str) -> Option<&str> {
|
||||
let start = raw.find('{')?;
|
||||
let end = raw.rfind('}')?;
|
||||
if end >= start {
|
||||
Some(&raw[start..=end])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize an arguments value: a JSON string parses to an object (or a
|
||||
/// {"raw": ...} wrapper); a non-object becomes {"value": ...}.
|
||||
fn normalize_args(value: Value) -> Value {
|
||||
match value {
|
||||
Value::String(s) => match serde_json::from_str::<Value>(&s) {
|
||||
Ok(parsed) if parsed.is_object() => parsed,
|
||||
_ => Value::Object(Map::from_iter([("raw".to_string(), Value::String(s))])),
|
||||
},
|
||||
v if v.is_object() => v,
|
||||
other => Value::Object(Map::from_iter([("value".to_string(), other)])),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the body of a tool channel into a tool-call frame.
|
||||
///
|
||||
/// Faithful for the JSON channel (the form Inkling emits: an object with a
|
||||
/// name and args/arguments). `tool_text` / `content_xml` bodies that are JSON
|
||||
/// or already carry a function marker are handled; the exotic XML attribute
|
||||
/// recovery is intentionally reduced to a raw payload (documented, not silent)
|
||||
/// since the OpenAI tool layer is not wired yet.
|
||||
fn parse_tool_body(header_name: &str, body: &str, kind: State, truncated: bool) -> String {
|
||||
let raw = body.trim();
|
||||
let fallback = header_name.trim();
|
||||
|
||||
if kind == State::ToolJson {
|
||||
// parse `raw`, recovering a `{...}` object if the whole thing is dirty
|
||||
let obj = serde_json::from_str::<Value>(raw)
|
||||
.ok()
|
||||
.or_else(|| extract_object(raw).and_then(|s| serde_json::from_str::<Value>(s).ok()));
|
||||
if let Some(Value::Object(map)) = obj {
|
||||
let name = map
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| fallback.to_string());
|
||||
let args = if map.contains_key("args") {
|
||||
normalize_args(map["args"].clone())
|
||||
} else if map.contains_key("arguments") {
|
||||
normalize_args(map["arguments"].clone())
|
||||
} else if map.contains_key("name") {
|
||||
// args are the remaining keys
|
||||
let rest: Map<String, Value> = map
|
||||
.iter()
|
||||
.filter(|(k, _)| k.as_str() != "name")
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
Value::Object(rest)
|
||||
} else {
|
||||
Value::Object(Map::new())
|
||||
};
|
||||
if !name.trim().is_empty() {
|
||||
return safe_json_call(name.trim(), args);
|
||||
}
|
||||
}
|
||||
if truncated && !raw.is_empty() && !raw.starts_with('{') {
|
||||
return raw.to_string();
|
||||
}
|
||||
if !fallback.is_empty() {
|
||||
let args = if raw.is_empty() {
|
||||
Value::Object(Map::new())
|
||||
} else {
|
||||
Value::Object(Map::from_iter([(
|
||||
"raw".to_string(),
|
||||
Value::String(raw.to_string()),
|
||||
)]))
|
||||
};
|
||||
return safe_json_call(fallback, args);
|
||||
}
|
||||
return raw.to_string();
|
||||
}
|
||||
|
||||
// tool_text / content_xml
|
||||
if raw.starts_with('{') {
|
||||
if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(raw) {
|
||||
let name = map
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| fallback.to_string());
|
||||
if let Some(args) = map.get("args").or(map.get("arguments")) {
|
||||
if args.is_object() && !name.trim().is_empty() {
|
||||
return safe_json_call(name.trim(), args.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if raw.contains("<function=") {
|
||||
return format!("{}\n{}\n{}", tag::TOOL_CALL_OPEN, raw, tag::TOOL_CALL_CLOSE);
|
||||
}
|
||||
if !fallback.is_empty() {
|
||||
let args = if raw.is_empty() {
|
||||
Value::Object(Map::new())
|
||||
} else {
|
||||
Value::Object(Map::from_iter([(
|
||||
"input".to_string(),
|
||||
Value::String(raw.to_string()),
|
||||
)]))
|
||||
};
|
||||
return safe_json_call(fallback, args);
|
||||
}
|
||||
raw.to_string()
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! `InklingFormatter`: the assembled model dialect implementing the API's
|
||||
//! [`Formatter`] seam. Prompt side = prepare_messages + chat template render +
|
||||
//! finish_prompt + tokenizer encode. Output side = incremental detokenization +
|
||||
//! the channel state machine, mapped to the API's reasoning/content pieces.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value as Json;
|
||||
|
||||
use crate::api::formatter::{Decoder, Formatter, Piece, Prompt};
|
||||
use crate::api::types::{ApiErrorEnvelope, ChatRequest};
|
||||
use crate::engine::protocol::Sampling;
|
||||
|
||||
use super::dialect::{InklingDialect, Kind, Out};
|
||||
use super::template::{finish_prompt, prepare_messages, ChatTemplate};
|
||||
use super::tokenizer::{Detok, InklingTokenizer};
|
||||
|
||||
/// The Inkling-2-Mini formatter: one per served model.
|
||||
pub struct InklingFormatter {
|
||||
tok: Arc<InklingTokenizer>,
|
||||
template: ChatTemplate,
|
||||
model: String,
|
||||
effort: Option<String>,
|
||||
max_new_default: u32,
|
||||
}
|
||||
|
||||
impl InklingFormatter {
|
||||
pub fn new(
|
||||
tok: Arc<InklingTokenizer>,
|
||||
template: ChatTemplate,
|
||||
model: String,
|
||||
effort: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
tok,
|
||||
template,
|
||||
model,
|
||||
effort,
|
||||
max_new_default: 2048,
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI messages -> the JSON the template expects, normalizing the newer
|
||||
/// `developer` role to `system` (the template's role map has no developer).
|
||||
fn messages_json(req: &ChatRequest) -> Json {
|
||||
let mut v = serde_json::to_value(&req.messages).unwrap_or_else(|_| Json::Array(vec![]));
|
||||
if let Some(arr) = v.as_array_mut() {
|
||||
for m in arr.iter_mut() {
|
||||
if m.get("role").and_then(|r| r.as_str()) == Some("developer") {
|
||||
m["role"] = Json::String("system".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl Formatter for InklingFormatter {
|
||||
fn model_name(&self) -> &str {
|
||||
&self.model
|
||||
}
|
||||
|
||||
fn default_max_new(&self) -> u32 {
|
||||
self.max_new_default
|
||||
}
|
||||
|
||||
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
|
||||
let mut msgs = Self::messages_json(req);
|
||||
prepare_messages(&mut msgs);
|
||||
|
||||
let tools = tools_for_choice(req)?;
|
||||
let rendered = self
|
||||
.template
|
||||
.render(&msgs, tools, self.effort.as_deref())
|
||||
.map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))?;
|
||||
|
||||
let has_tools = tools
|
||||
.and_then(|t| t.as_array())
|
||||
.map(|a| !a.is_empty())
|
||||
.unwrap_or(false);
|
||||
let prompt = finish_prompt(&rendered, has_tools, false);
|
||||
|
||||
let ids = self
|
||||
.tok
|
||||
.encode(&prompt)
|
||||
.map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))?;
|
||||
|
||||
// Images: materialize the conversation's image parts to local files the
|
||||
// engine reads via `image=<path>` keys, in the same order the template
|
||||
// rendered its placeholders.
|
||||
let sources = super::images::extract_sources(&msgs);
|
||||
let temp_files = if sources.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
super::images::materialize(&sources)
|
||||
.map_err(|e| ApiErrorEnvelope::new(e.to_string(), "invalid_request_error", None))?
|
||||
};
|
||||
let images = temp_files
|
||||
.iter()
|
||||
.map(|p| super::images::encode_path(&p.to_string_lossy()))
|
||||
.collect();
|
||||
|
||||
let sampling = Sampling {
|
||||
temperature: req.temperature,
|
||||
top_p: req.top_p,
|
||||
frequency_penalty: req.frequency_penalty,
|
||||
presence_penalty: req.presence_penalty,
|
||||
seed: req.seed,
|
||||
images,
|
||||
..Default::default()
|
||||
};
|
||||
Ok(Prompt {
|
||||
ids,
|
||||
max_new: req.max_new(self.max_new_default),
|
||||
sampling,
|
||||
temp_files,
|
||||
})
|
||||
}
|
||||
|
||||
fn decoder(&self) -> Box<dyn Decoder> {
|
||||
Box::new(InklingDecoder {
|
||||
tok: self.tok.clone(),
|
||||
detok: Detok::new(self.tok.clone()),
|
||||
dialect: InklingDialect::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Output decoder: detokenize each id, classify special vs text, drive the
|
||||
/// channel state machine, and map its typed output to API pieces.
|
||||
struct InklingDecoder {
|
||||
tok: Arc<InklingTokenizer>,
|
||||
detok: Detok,
|
||||
dialect: InklingDialect,
|
||||
}
|
||||
|
||||
/// Resolve `tool_choice` to the tools actually offered to the model. `none`
|
||||
/// hides them (the model cannot call); `auto`/absent offers them. Forcing
|
||||
/// (`required` or a named function) needs a prompt-opener the Inkling template
|
||||
/// does not provide, so it is rejected honestly rather than silently ignored.
|
||||
fn tools_for_choice(req: &ChatRequest) -> Result<Option<&Json>, ApiErrorEnvelope> {
|
||||
let unsupported = |msg: &str| {
|
||||
Err(ApiErrorEnvelope::new(
|
||||
msg.to_string(),
|
||||
"invalid_request_error",
|
||||
None,
|
||||
))
|
||||
};
|
||||
match req.tool_choice.as_ref() {
|
||||
None => Ok(req.tools.as_ref()),
|
||||
Some(Json::String(s)) => match s.as_str() {
|
||||
"auto" => Ok(req.tools.as_ref()),
|
||||
"none" => Ok(None),
|
||||
"required" => unsupported(
|
||||
"tool_choice \"required\" (forced calling) is not supported by this model yet",
|
||||
),
|
||||
other => unsupported(&format!("unknown tool_choice: {other}")),
|
||||
},
|
||||
Some(Json::Object(_)) => unsupported(
|
||||
"tool_choice forcing a specific function is not supported by this model yet",
|
||||
),
|
||||
Some(_) => unsupported("invalid tool_choice"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a rendered tool frame (`...\n{"name":...,"arguments":{...}}\n`)
|
||||
/// back into a structured call. This is the OpenAI tool layer the reference
|
||||
/// keeps in a separate JsonOutputParser; non-frame text stays content.
|
||||
fn frame_to_call(text: &str) -> Option<(String, String)> {
|
||||
let t = text.trim();
|
||||
let inner = t
|
||||
.strip_prefix(super::dialect::tag::TOOL_CALL_OPEN)?
|
||||
.strip_suffix(super::dialect::tag::TOOL_CALL_CLOSE)?
|
||||
.trim();
|
||||
let v: Json = serde_json::from_str(inner).ok()?;
|
||||
let name = v.get("name")?.as_str()?.trim().to_string();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let args = v
|
||||
.get("arguments")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Json::Object(Default::default()));
|
||||
Some((name, args.to_string()))
|
||||
}
|
||||
|
||||
/// Map one dialect output to API pieces: a tool frame becomes a structured
|
||||
/// `ToolCall`, anything else stays reasoning/content.
|
||||
fn out_to_pieces(o: Out) -> Vec<Piece> {
|
||||
match o.kind {
|
||||
Kind::Reasoning if !o.text.is_empty() => vec![Piece::Reasoning(o.text)],
|
||||
Kind::Content => {
|
||||
if let Some((name, arguments)) = frame_to_call(&o.text) {
|
||||
vec![Piece::ToolCall { name, arguments }]
|
||||
} else if !o.text.is_empty() {
|
||||
vec![Piece::Content(o.text)]
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for InklingDecoder {
|
||||
fn push(&mut self, id: u32) -> Vec<Piece> {
|
||||
let piece = self.detok.push(id);
|
||||
let is_special = self.tok.is_special(id);
|
||||
self.dialect
|
||||
.feed_token(&piece, is_special)
|
||||
.into_iter()
|
||||
.flat_map(out_to_pieces)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn finish(&mut self, reason: Option<&str>) -> Vec<Piece> {
|
||||
// flush any held partial text, then let the dialect close its channels
|
||||
let tail = self.detok.finish();
|
||||
let mut out: Vec<Piece> = self
|
||||
.dialect
|
||||
.feed_token(&tail, false)
|
||||
.into_iter()
|
||||
.flat_map(out_to_pieces)
|
||||
.collect();
|
||||
out.extend(
|
||||
self.dialect
|
||||
.finish(reason)
|
||||
.into_iter()
|
||||
.flat_map(out_to_pieces),
|
||||
);
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Image bridge for Inkling's in-process Vision.
|
||||
//!
|
||||
//! OpenAI/Anthropic image parts (base64 data URLs, http(s) URLs, local paths)
|
||||
//! are materialized to local files the engine reads itself via `image=<path>`
|
||||
//! keys, in prompt order — mirroring `serve.write_images` + `inkling_kind`.
|
||||
//! Unsupported formats (WebP/TIFF/AVIF, which agents like omp send) are
|
||||
//! normalized to PNG; JPEG/PNG/BMP/GIF pass through untouched.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use base64::Engine;
|
||||
use serde_json::Value as Json;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ImageError {
|
||||
#[error("unsupported image source: {0}")]
|
||||
Unsupported(String),
|
||||
#[error("image decode failed: {0}")]
|
||||
Decode(String),
|
||||
#[error("image io: {0}")]
|
||||
Io(String),
|
||||
#[error("image fetch failed: {0}")]
|
||||
Fetch(String),
|
||||
}
|
||||
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// `inkling_kind.encode_path`: the engine only decodes `%20` and `%25`, so we
|
||||
/// encode exactly those two — not a full percent-encoding (slashes stay literal).
|
||||
pub fn encode_path(path: &str) -> String {
|
||||
path.replace('%', "%25").replace(' ', "%20")
|
||||
}
|
||||
|
||||
/// Image source strings of the conversation, in prompt order (one per image
|
||||
/// content part, message by message) — the order the template renders its
|
||||
/// `<|content_image|><|unused_200054|>` placeholders.
|
||||
pub fn extract_sources(messages: &Json) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let Some(arr) = messages.as_array() else {
|
||||
return out;
|
||||
};
|
||||
for m in arr {
|
||||
let Some(content) = m.get("content").and_then(|c| c.as_array()) else {
|
||||
continue;
|
||||
};
|
||||
for part in content {
|
||||
if let Some(src) = part_source(part) {
|
||||
out.push(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Pull the source string out of one content part, across the OpenAI, Responses
|
||||
/// and Anthropic shapes. Anthropic base64 blocks are folded into a data URL.
|
||||
fn part_source(part: &Json) -> Option<String> {
|
||||
let ty = part.get("type")?.as_str()?;
|
||||
match ty {
|
||||
"image_url" => {
|
||||
let iu = part.get("image_url")?;
|
||||
if let Some(s) = iu.as_str() {
|
||||
return Some(s.to_string());
|
||||
}
|
||||
iu.get("url")?.as_str().map(str::to_string)
|
||||
}
|
||||
"input_image" => part
|
||||
.get("image_url")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string),
|
||||
"image" => {
|
||||
let src = part.get("source")?;
|
||||
if let Some(s) = src.as_str() {
|
||||
return Some(s.to_string());
|
||||
}
|
||||
if src.get("type").and_then(|t| t.as_str()) == Some("base64") {
|
||||
let mt = src
|
||||
.get("media_type")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("image/png");
|
||||
let data = src.get("data")?.as_str()?;
|
||||
return Some(format!("data:{mt};base64,{data}"));
|
||||
}
|
||||
src.get("url").and_then(|u| u.as_str()).map(str::to_string)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Materialize sources to unique local files under `strata-inkling-images`.
|
||||
/// Returns the paths (to hand the engine, in order); the caller removes them
|
||||
/// once the request is done.
|
||||
pub fn materialize(sources: &[String]) -> Result<Vec<PathBuf>, ImageError> {
|
||||
let base = std::env::temp_dir().join("strata-inkling-images");
|
||||
std::fs::create_dir_all(&base).map_err(|e| ImageError::Io(e.to_string()))?;
|
||||
let nonce = format!(
|
||||
"{}-{}",
|
||||
std::process::id(),
|
||||
SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
);
|
||||
let mut out = Vec::new();
|
||||
for (idx, src) in sources.iter().enumerate() {
|
||||
let raw = load_bytes(src)?;
|
||||
let (data, ext) = normalize(raw)?;
|
||||
let p = base.join(format!("{nonce}-{idx}{ext}"));
|
||||
std::fs::write(&p, &data).map_err(|e| ImageError::Io(e.to_string()))?;
|
||||
out.push(p);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Bytes of one source: base64 data URL, http(s) fetch, or local file path.
|
||||
fn load_bytes(src: &str) -> Result<Vec<u8>, ImageError> {
|
||||
if let Some(rest) = src.strip_prefix("data:") {
|
||||
let (meta, data) = rest
|
||||
.split_once(',')
|
||||
.ok_or_else(|| ImageError::Unsupported("malformed data URL".into()))?;
|
||||
if !meta.ends_with(";base64") {
|
||||
return Err(ImageError::Unsupported(
|
||||
"only base64 data URLs are supported".into(),
|
||||
));
|
||||
}
|
||||
return base64::engine::general_purpose::STANDARD
|
||||
.decode(data)
|
||||
.map_err(|e| ImageError::Decode(e.to_string()));
|
||||
}
|
||||
if src.starts_with("http://") || src.starts_with("https://") {
|
||||
let mut resp = ureq::get(src)
|
||||
.call()
|
||||
.map_err(|e| ImageError::Fetch(e.to_string()))?;
|
||||
return resp
|
||||
.body_mut()
|
||||
.read_to_vec()
|
||||
.map_err(|e| ImageError::Fetch(e.to_string()));
|
||||
}
|
||||
let path = src.strip_prefix("file://").unwrap_or(src);
|
||||
std::fs::read(path).map_err(|e| ImageError::Io(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// Keep JPEG/PNG/BMP/GIF as-is; convert anything else to PNG via the image crate.
|
||||
fn normalize(data: Vec<u8>) -> Result<(Vec<u8>, &'static str), ImageError> {
|
||||
if let Some(ext) = sniff(&data) {
|
||||
return Ok((data, ext));
|
||||
}
|
||||
let img = image::load_from_memory(&data).map_err(|e| ImageError::Decode(e.to_string()))?;
|
||||
let mut buf = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
|
||||
.map_err(|e| ImageError::Decode(e.to_string()))?;
|
||||
Ok((buf, ".png"))
|
||||
}
|
||||
|
||||
/// Magic-byte sniff for the formats the engine reads directly.
|
||||
fn sniff(data: &[u8]) -> Option<&'static str> {
|
||||
if data.starts_with(&[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n']) {
|
||||
Some(".png")
|
||||
} else if data.starts_with(&[0xff, 0xd8, 0xff]) {
|
||||
Some(".jpg")
|
||||
} else if data.starts_with(b"BM") {
|
||||
Some(".bmp")
|
||||
} else if data.starts_with(b"GIF") {
|
||||
Some(".gif")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Inkling-2-Mini model dialect: the output channel state machine.
|
||||
//!
|
||||
//! [`dialect`] ports the streaming reasoning/content/tool translator. The
|
||||
//! tokenizer + chat template (prompt side) land here next, so `InklingFormatter`
|
||||
//! can implement [`crate::api::formatter::Formatter`] end to end.
|
||||
|
||||
pub mod dialect;
|
||||
pub mod formatter;
|
||||
pub mod images;
|
||||
pub mod template;
|
||||
pub mod tokenizer;
|
||||
|
||||
pub use dialect::{InklingDialect, Kind, Out, Tag};
|
||||
pub use formatter::InklingFormatter;
|
||||
pub use template::{finish_prompt, prepare_messages, ChatTemplate, TemplateError};
|
||||
pub use tokenizer::{Detok, InklingTokenizer, TokError};
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Inkling chat template: renders `chat_template.jinja` to the prompt string
|
||||
//! the tokenizer then encodes.
|
||||
//!
|
||||
//! The template is HF-flavoured Jinja: it uses `namespace`, macros, `dictsort`,
|
||||
//! `tojson(sort_keys=…, separators=…)`, a `raise_exception` global, and HF's
|
||||
//! `{% generation %}` blocks. minijinja covers most of it; we supply a `tojson`
|
||||
//! that honours those kwargs, a `raise_exception` that fails the render, and we
|
||||
//! strip the (transparent-for-inference) generation tags before parsing.
|
||||
|
||||
use minijinja::value::{Kwargs, Serde};
|
||||
use minijinja::{Environment, Error, ErrorKind, Value};
|
||||
use serde_json::Value as Json;
|
||||
|
||||
use super::dialect::tag;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TemplateError {
|
||||
#[error("template parse/render failed: {0}")]
|
||||
Render(String),
|
||||
}
|
||||
|
||||
/// A compiled chat template.
|
||||
pub struct ChatTemplate {
|
||||
env: Environment<'static>,
|
||||
}
|
||||
|
||||
impl ChatTemplate {
|
||||
/// Compile from the template source (the contents of chat_template.jinja).
|
||||
pub fn new(source: &str) -> Result<Self, TemplateError> {
|
||||
let cleaned = strip_generation(source);
|
||||
let mut env = Environment::new();
|
||||
env.add_filter("tojson", tojson);
|
||||
env.add_function("raise_exception", raise_exception);
|
||||
env.add_template_owned("chat", cleaned)
|
||||
.map_err(|e| TemplateError::Render(e.to_string()))?;
|
||||
Ok(Self { env })
|
||||
}
|
||||
|
||||
/// Render with the conversation. `messages`/`tools` are OpenAI-shaped JSON
|
||||
/// (see [`prepare_messages`]); `reasoning_effort` is the config string.
|
||||
pub fn render(
|
||||
&self,
|
||||
messages: &Json,
|
||||
tools: Option<&Json>,
|
||||
reasoning_effort: Option<&str>,
|
||||
) -> Result<String, TemplateError> {
|
||||
let ctx = minijinja::context! {
|
||||
messages => Value::from(Serde(messages)),
|
||||
tools => Value::from(Serde(tools.unwrap_or(&Json::Null))),
|
||||
reasoning_effort => reasoning_effort,
|
||||
};
|
||||
self.env
|
||||
.get_template("chat")
|
||||
.and_then(|t| t.render(ctx))
|
||||
.map_err(|e| TemplateError::Render(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// HF `{% generation %}` / `{% endgeneration %}` mark the assistant span for
|
||||
/// training loss; at inference they are transparent, so remove them (keeping
|
||||
/// their inner content) before minijinja parses the source.
|
||||
fn strip_generation(src: &str) -> String {
|
||||
src.replace("{%- generation -%}", "")
|
||||
.replace("{%- endgeneration -%}", "")
|
||||
.replace("{% generation %}", "")
|
||||
.replace("{% endgeneration %}", "")
|
||||
}
|
||||
|
||||
/// `raise_exception(msg)` global: abort the render with the model's own message.
|
||||
fn raise_exception(msg: String) -> Result<Value, Error> {
|
||||
Err(Error::new(ErrorKind::InvalidOperation, msg))
|
||||
}
|
||||
|
||||
/// `tojson` honouring `sort_keys` and `separators` (the template passes
|
||||
/// `separators=(",", ":")`, i.e. compact). Defaults mirror Python json.dumps.
|
||||
fn tojson(value: Value, kwargs: Kwargs) -> Result<Value, Error> {
|
||||
let sort_keys = kwargs.get::<Option<bool>>("sort_keys")?.unwrap_or(false);
|
||||
let separators = kwargs.get::<Option<Value>>("separators")?;
|
||||
let (item_sep, kv_sep) = match separators {
|
||||
Some(seq) => {
|
||||
let a = seq.get_item_by_index(0).ok();
|
||||
let b = seq.get_item_by_index(1).ok();
|
||||
(
|
||||
a.and_then(|v| v.as_str().map(str::to_string))
|
||||
.unwrap_or_else(|| ", ".into()),
|
||||
b.and_then(|v| v.as_str().map(str::to_string))
|
||||
.unwrap_or_else(|| ": ".into()),
|
||||
)
|
||||
}
|
||||
None => (", ".to_string(), ": ".to_string()),
|
||||
};
|
||||
kwargs.assert_all_used()?;
|
||||
|
||||
let json: Json = serde_json::to_value(&value)
|
||||
.map_err(|e| Error::new(ErrorKind::InvalidOperation, e.to_string()))?;
|
||||
let mut out = String::new();
|
||||
write_json(&json, sort_keys, &item_sep, &kv_sep, &mut out);
|
||||
Ok(Value::from_safe_string(out))
|
||||
}
|
||||
|
||||
/// Recursive JSON writer with explicit separators and optional key sorting.
|
||||
fn write_json(v: &Json, sort: bool, item_sep: &str, kv_sep: &str, out: &mut String) {
|
||||
match v {
|
||||
Json::Object(map) => {
|
||||
let mut entries: Vec<(&String, &Json)> = map.iter().collect();
|
||||
if sort {
|
||||
entries.sort_by(|a, b| a.0.cmp(b.0));
|
||||
}
|
||||
out.push('{');
|
||||
for (i, (k, val)) in entries.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(item_sep);
|
||||
}
|
||||
out.push_str(&Json::String((*k).clone()).to_string());
|
||||
out.push_str(kv_sep);
|
||||
write_json(val, sort, item_sep, kv_sep, out);
|
||||
}
|
||||
out.push('}');
|
||||
}
|
||||
Json::Array(arr) => {
|
||||
out.push('[');
|
||||
for (i, val) in arr.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(item_sep);
|
||||
}
|
||||
write_json(val, sort, item_sep, kv_sep, out);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
// scalars: serde_json's own compact spelling (strings escaped, numbers,
|
||||
// booleans, null) is exactly what we want.
|
||||
other => out.push_str(&other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonicalize assistant tool-call arguments from JSON strings to objects, so
|
||||
/// the template's `args is string -> raise` never fires (mirrors
|
||||
/// `inkling_dialect.prepare_messages`). Mutates the messages JSON in place.
|
||||
pub fn prepare_messages(messages: &mut Json) {
|
||||
let Some(arr) = messages.as_array_mut() else {
|
||||
return;
|
||||
};
|
||||
for m in arr.iter_mut() {
|
||||
let Some(calls) = m.get_mut("tool_calls").and_then(|c| c.as_array_mut()) else {
|
||||
continue;
|
||||
};
|
||||
for tc in calls.iter_mut() {
|
||||
let Some(fn_obj) = tc.get_mut("function").and_then(|f| f.as_object_mut()) else {
|
||||
continue;
|
||||
};
|
||||
match fn_obj.get("arguments") {
|
||||
Some(Json::String(s)) => {
|
||||
let parsed = if s.trim().is_empty() {
|
||||
Json::Object(Default::default())
|
||||
} else {
|
||||
match serde_json::from_str::<Json>(s) {
|
||||
Ok(v) if v.is_object() => v,
|
||||
Ok(v) => Json::Object([("value".to_string(), v)].into_iter().collect()),
|
||||
Err(_) => Json::Object(
|
||||
[("raw".to_string(), Json::String(s.clone()))]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
};
|
||||
fn_obj.insert("arguments".to_string(), parsed);
|
||||
}
|
||||
None | Some(Json::Null) => {
|
||||
fn_obj.insert("arguments".to_string(), Json::Object(Default::default()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Append the non-thinking turn opener, **as patched by run_strata_cot.py**:
|
||||
/// only when the prompt carries `Thinking effort level: 0` (effort none). With
|
||||
/// a positive effort the model opens its own thinking, so the prompt is left
|
||||
/// untouched. Idempotent; `forced` (a forced tool opener) is left as-is.
|
||||
pub fn finish_prompt(prompt: &str, has_tools: bool, forced: bool) -> String {
|
||||
if prompt.is_empty() || forced {
|
||||
return prompt.to_string();
|
||||
}
|
||||
if !prompt.contains("Thinking effort level: 0<|end_message|>") {
|
||||
return prompt.to_string();
|
||||
}
|
||||
let empty_think = format!(
|
||||
"{}{}{}",
|
||||
tag::MESSAGE_MODEL,
|
||||
tag::CONTENT_THINKING,
|
||||
tag::END_MESSAGE
|
||||
);
|
||||
if prompt.ends_with(tag::CONTENT_TEXT)
|
||||
|| prompt.ends_with(tag::CONTENT_INVOKE_TOOL_JSON)
|
||||
|| prompt.ends_with(tag::CONTENT_INVOKE_TOOL_TEXT)
|
||||
|| prompt.ends_with(&empty_think)
|
||||
{
|
||||
return prompt.to_string();
|
||||
}
|
||||
if prompt.ends_with(tag::MESSAGE_MODEL) {
|
||||
let tail = if has_tools {
|
||||
format!("{}{}", tag::CONTENT_THINKING, tag::END_MESSAGE)
|
||||
} else {
|
||||
tag::CONTENT_TEXT.to_string()
|
||||
};
|
||||
return format!("{prompt}{tail}");
|
||||
}
|
||||
let tail = if has_tools {
|
||||
empty_think
|
||||
} else {
|
||||
format!("{}{}", tag::MESSAGE_MODEL, tag::CONTENT_TEXT)
|
||||
};
|
||||
format!("{prompt}{tail}")
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Inkling tokenizer: loads the real HF tokenizer (`tokenizer.hf.json`, an
|
||||
//! o200k BPE) via the `tokenizers` crate, and provides the three things the
|
||||
//! formatter needs:
|
||||
//! - encode a rendered prompt string to ids (special channel tokens are matched
|
||||
//! as single ids by the added-token trie);
|
||||
//! - the `id -> Tag` table for the channel tokens (the dialect's `is_special`);
|
||||
//! - incremental, UTF-8-safe detokenization of the engine's output ids.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokenizers::Tokenizer;
|
||||
|
||||
use super::dialect::Tag;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TokError {
|
||||
#[error("cannot load tokenizer {path}: {msg}")]
|
||||
Load { path: String, msg: String },
|
||||
#[error("encode failed: {0}")]
|
||||
Encode(String),
|
||||
#[error("decode failed: {0}")]
|
||||
Decode(String),
|
||||
}
|
||||
|
||||
/// A loaded Inkling tokenizer plus its channel/special id tables.
|
||||
pub struct InklingTokenizer {
|
||||
tok: Tokenizer,
|
||||
/// Channel-token id -> dialect tag (the nine structural tokens).
|
||||
channel: HashMap<u32, Tag>,
|
||||
/// Every added (atomic) token id, special or not.
|
||||
added: HashSet<u32>,
|
||||
}
|
||||
|
||||
impl InklingTokenizer {
|
||||
/// Load `<dir>/tokenizer.hf.json` (the real HF file; `tokenizer.json` in the
|
||||
/// same dir is only a summary and is not loadable).
|
||||
pub fn load_dir(dir: &Path) -> Result<Self, TokError> {
|
||||
Self::from_file(&dir.join("tokenizer.hf.json"))
|
||||
}
|
||||
|
||||
pub fn from_file(path: &Path) -> Result<Self, TokError> {
|
||||
let tok = Tokenizer::from_file(path).map_err(|e| TokError::Load {
|
||||
path: path.display().to_string(),
|
||||
msg: e.to_string(),
|
||||
})?;
|
||||
let mut channel = HashMap::new();
|
||||
let mut added = HashSet::new();
|
||||
for (id, at) in tok.get_added_tokens_decoder() {
|
||||
added.insert(id);
|
||||
if let Some(tag) = Tag::parse(&at.content) {
|
||||
channel.insert(id, tag);
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
tok,
|
||||
channel,
|
||||
added,
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode a prompt string. `add_special_tokens = false`: the rendered chat
|
||||
/// template already carries every structural token explicitly.
|
||||
pub fn encode(&self, text: &str) -> Result<Vec<u32>, TokError> {
|
||||
let enc = self
|
||||
.tok
|
||||
.encode(text, false)
|
||||
.map_err(|e| TokError::Encode(e.to_string()))?;
|
||||
Ok(enc.get_ids().to_vec())
|
||||
}
|
||||
|
||||
/// Decode a whole id slice (specials kept, so channel tokens come back as
|
||||
/// their literal strings).
|
||||
pub fn decode_all(&self, ids: &[u32]) -> Result<String, TokError> {
|
||||
self.tok
|
||||
.decode(ids, false)
|
||||
.map_err(|e| TokError::Decode(e.to_string()))
|
||||
}
|
||||
|
||||
/// The dialect tag for a channel-token id, if any.
|
||||
pub fn channel_tag(&self, id: u32) -> Option<Tag> {
|
||||
self.channel.get(&id).copied()
|
||||
}
|
||||
|
||||
/// Whether an id is an added (atomic) token — the `is_special` flag.
|
||||
pub fn is_special(&self, id: u32) -> bool {
|
||||
self.added.contains(&id)
|
||||
}
|
||||
|
||||
/// The literal string of a token id (for diagnostics / special tokens).
|
||||
pub fn token_str(&self, id: u32) -> Option<String> {
|
||||
self.tok.id_to_token(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Incremental detokenizer over a growing id buffer. Decodes the whole buffer
|
||||
/// each step and emits only the newly-stable suffix, holding back a trailing
|
||||
/// incomplete code point (which the ByteLevel decoder renders as U+FFFD) until
|
||||
/// more bytes arrive. Specials are atomic and emit immediately.
|
||||
pub struct Detok {
|
||||
tok: Arc<InklingTokenizer>,
|
||||
ids: Vec<u32>,
|
||||
emitted: usize,
|
||||
}
|
||||
|
||||
impl Detok {
|
||||
pub fn new(tok: Arc<InklingTokenizer>) -> Self {
|
||||
Self {
|
||||
tok,
|
||||
ids: Vec::new(),
|
||||
emitted: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Feed one id; returns the newly-complete text (possibly empty).
|
||||
pub fn push(&mut self, id: u32) -> String {
|
||||
self.ids.push(id);
|
||||
let full = match self.tok.decode_all(&self.ids) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return String::new(),
|
||||
};
|
||||
let stable = full.len() - trailing_replacement_bytes(&full);
|
||||
if stable > self.emitted && full.is_char_boundary(self.emitted) {
|
||||
let piece = full[self.emitted..stable].to_string();
|
||||
self.emitted = stable;
|
||||
piece
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Flush whatever is left (including any held replacement) at end of stream.
|
||||
pub fn finish(&mut self) -> String {
|
||||
let full = self.tok.decode_all(&self.ids).unwrap_or_default();
|
||||
if full.len() > self.emitted {
|
||||
let piece = full[self.emitted..].to_string();
|
||||
self.emitted = full.len();
|
||||
piece
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte length of a trailing run of U+FFFD (the replacement char), which marks
|
||||
/// an incomplete code point we must not emit yet.
|
||||
fn trailing_replacement_bytes(s: &str) -> usize {
|
||||
let mut n = 0;
|
||||
for c in s.chars().rev() {
|
||||
if c == '\u{FFFD}' {
|
||||
n += c.len_utf8();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
//! strata-ctl: a Rust control layer for the Strata inference engine.
|
||||
//!
|
||||
//! - [`engine`]: spawn `strata --serve` and speak its line protocol.
|
||||
//! - [`api`]: the OpenAI-compatible HTTP surface (types, formatter seam,
|
||||
//! completion service, axum routes).
|
||||
//!
|
||||
//! Next: the Inkling formatter (chat template + tokenizer), then wiring a
|
||||
//! binary that reads the existing `strata-inkling.json` and serves.
|
||||
|
||||
pub mod api;
|
||||
pub mod config;
|
||||
pub mod engine;
|
||||
pub mod inkling;
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
//! strata-ctl CLI.
|
||||
//!
|
||||
//! Resolves the shared JSON config and either reports the launch plan (default)
|
||||
//! or serves the OpenAI-compatible API (`--serve`): config -> Inkling
|
||||
//! tokenizer + chat template -> formatter -> engine supervisor -> axum router.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use strata_ctl::api::{router, ChatService};
|
||||
use strata_ctl::config::{Config, ConfigError};
|
||||
use strata_ctl::engine::Engine;
|
||||
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
|
||||
|
||||
const USAGE: &str = "\
|
||||
strata-ctl — Rust control layer for the Strata engine (OpenAI-compatible API)
|
||||
|
||||
USAGE:
|
||||
strata-ctl [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--config <PATH> model config JSON (default: ~/.config/strata-inkling/strata-inkling.json)
|
||||
--host <HOST> override the bind host from the config
|
||||
--port <PORT> override the bind port from the config
|
||||
--serve start the engine and serve the API (default: print the launch plan)
|
||||
-h, --help show this help
|
||||
";
|
||||
|
||||
struct Args {
|
||||
config: Option<String>,
|
||||
host: Option<String>,
|
||||
port: Option<u16>,
|
||||
serve: bool,
|
||||
help: bool,
|
||||
}
|
||||
|
||||
/// Hand-rolled flag parser: the surface mirrors the Python launcher and is far
|
||||
/// smaller than a dependency on a CLI framework would justify.
|
||||
fn parse_args<I: Iterator<Item = String>>(mut it: I) -> Result<Args, String> {
|
||||
let mut args = Args {
|
||||
config: None,
|
||||
host: None,
|
||||
port: None,
|
||||
serve: false,
|
||||
help: false,
|
||||
};
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"-h" | "--help" => args.help = true,
|
||||
"--serve" => args.serve = true,
|
||||
"--config" => args.config = Some(it.next().ok_or("--config needs a value")?),
|
||||
"--host" => args.host = Some(it.next().ok_or("--host needs a value")?),
|
||||
"--port" => {
|
||||
let v = it.next().ok_or("--port needs a value")?;
|
||||
args.port = Some(v.parse().map_err(|_| format!("invalid --port: {v}"))?);
|
||||
}
|
||||
other if other.starts_with("--config=") => {
|
||||
args.config = Some(other["--config=".len()..].to_string())
|
||||
}
|
||||
other if other.starts_with("--host=") => {
|
||||
args.host = Some(other["--host=".len()..].to_string())
|
||||
}
|
||||
other if other.starts_with("--port=") => {
|
||||
let v = &other["--port=".len()..];
|
||||
args.port = Some(v.parse().map_err(|_| format!("invalid --port: {v}"))?);
|
||||
}
|
||||
other => return Err(format!("unknown argument: {other}")),
|
||||
}
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
let args = match parse_args(std::env::args().skip(1)) {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}\n\n{USAGE}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
if args.help {
|
||||
print!("{USAGE}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
let path = match &args.config {
|
||||
Some(p) => std::path::PathBuf::from(p),
|
||||
None => Config::default_path(),
|
||||
};
|
||||
let cfg = match Config::load(&path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return report_config_error(&path, e),
|
||||
};
|
||||
|
||||
print_plan(&cfg, &path, args.host.as_deref(), args.port);
|
||||
|
||||
if args.serve {
|
||||
serve(&cfg, args.host.as_deref(), args.port).await
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the engine from the config and serve the OpenAI-compatible API.
|
||||
async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> ExitCode {
|
||||
let dir = match &cfg.tokenizer {
|
||||
Some(d) => d.clone(),
|
||||
None => {
|
||||
eprintln!("error: config has no `tokenizer` directory; cannot build the formatter");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let tok = match InklingTokenizer::load_dir(Path::new(&dir)) {
|
||||
Ok(t) => Arc::new(t),
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let tpl_path = Path::new(&dir).join("chat_template.jinja");
|
||||
let src = match std::fs::read_to_string(&tpl_path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("error: cannot read {}: {e}", tpl_path.display());
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let template = match ChatTemplate::new(&src) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
eprintln!("error: chat template: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let fmt = Arc::new(InklingFormatter::new(
|
||||
tok,
|
||||
template,
|
||||
cfg.model_name().to_string(),
|
||||
cfg.reasoning_effort.clone(),
|
||||
));
|
||||
|
||||
let engine = match Engine::start(
|
||||
&cfg.exe,
|
||||
&cfg.engine_argv(),
|
||||
cfg.cwd.as_deref(),
|
||||
Duration::from_secs(600),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(e) => Arc::new(e),
|
||||
Err(e) => {
|
||||
eprintln!("error: the engine failed to start: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!(
|
||||
"\nengine READY (context {} tokens); serving model {}",
|
||||
engine.ready().max_context,
|
||||
cfg.model_name()
|
||||
);
|
||||
|
||||
let svc = ChatService::new(engine.clone(), fmt);
|
||||
let app = router(svc);
|
||||
let addr = format!("{}:{}", cfg.bind_host(cli_host), cfg.bind_port(cli_port));
|
||||
let listener = match tokio::net::TcpListener::bind(&addr).await {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
eprintln!("error: cannot bind {addr}: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("listening on http://{addr} (Ctrl-C to stop)");
|
||||
|
||||
let shutdown_engine = engine.clone();
|
||||
let result = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
println!("\nshutting down");
|
||||
let _ = shutdown_engine.shutdown().await;
|
||||
})
|
||||
.await;
|
||||
if let Err(e) = result {
|
||||
eprintln!("error: server: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn print_plan(cfg: &Config, path: &std::path::Path, cli_host: Option<&str>, cli_port: Option<u16>) {
|
||||
let host = cfg.bind_host(cli_host);
|
||||
let port = cfg.bind_port(cli_port);
|
||||
let ignored = cfg.ignored_keys();
|
||||
|
||||
println!("config: {}", path.display());
|
||||
println!("model: {}", cfg.model_name());
|
||||
println!("bind: {host}:{port}");
|
||||
println!("cwd: {}", cfg.cwd.as_deref().unwrap_or("(process cwd)"));
|
||||
println!(
|
||||
"tokenizer: {}",
|
||||
cfg.tokenizer.as_deref().unwrap_or("(none configured)")
|
||||
);
|
||||
println!(
|
||||
"reasoning_effort: {}",
|
||||
cfg.reasoning_effort.as_deref().unwrap_or("(default)")
|
||||
);
|
||||
println!(
|
||||
"sampling: temp={:?} top_p={:?} min_p={:?} rep_pen={:?}",
|
||||
cfg.sampling.temperature,
|
||||
cfg.sampling.top_p,
|
||||
cfg.sampling.min_p,
|
||||
cfg.sampling.repetition_penalty
|
||||
);
|
||||
println!("\nwould spawn:");
|
||||
println!(" {} {}", cfg.exe, cfg.engine_argv().join(" "));
|
||||
if !ignored.is_empty() {
|
||||
println!("\nignored keys (left for other tools / not yet acted on):");
|
||||
println!(" {}", ignored.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
fn report_config_error(path: &std::path::Path, err: ConfigError) -> ExitCode {
|
||||
eprintln!("error: {err}");
|
||||
if let ConfigError::MissingExe = err {
|
||||
eprintln!(" (check the `exe` field in {})", path.display());
|
||||
}
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! End-to-end tests of the OpenAI surface: HTTP request -> engine (mock) ->
|
||||
//! HTTP response, non-stream and stream, driven through a trivial formatter so
|
||||
//! the whole API layer is exercised without the real tokenizer.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode};
|
||||
use tower::ServiceExt; // for `oneshot`
|
||||
|
||||
use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt};
|
||||
use strata_ctl::api::service::ChatService;
|
||||
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
|
||||
use strata_ctl::engine::Engine;
|
||||
|
||||
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
|
||||
|
||||
/// A formatter with no dialect: the prompt is the last message's bytes; each
|
||||
/// token id < 256 decodes to that byte as a char, always as "content".
|
||||
struct ByteFormatter;
|
||||
|
||||
impl Formatter for ByteFormatter {
|
||||
fn model_name(&self) -> &str {
|
||||
"test-model"
|
||||
}
|
||||
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
|
||||
let text = req
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|m| m.text())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
Ok(Prompt {
|
||||
ids: text.bytes().map(u32::from).collect(),
|
||||
max_new: req.max_new(64),
|
||||
sampling: Default::default(),
|
||||
temp_files: Vec::new(),
|
||||
})
|
||||
}
|
||||
fn decoder(&self) -> Box<dyn Decoder> {
|
||||
Box::new(ByteDecoder)
|
||||
}
|
||||
}
|
||||
|
||||
struct ByteDecoder;
|
||||
impl Decoder for ByteDecoder {
|
||||
fn push(&mut self, id: u32) -> Vec<Piece> {
|
||||
if id < 256 {
|
||||
vec![Piece::Content(char::from(id as u8).to_string())]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
fn finish(&mut self, _reason: Option<&str>) -> Vec<Piece> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Drives the mock's long, STOP-interruptible generation (ids contain 888888).
|
||||
struct LongFormatter;
|
||||
impl Formatter for LongFormatter {
|
||||
fn model_name(&self) -> &str {
|
||||
"test-model"
|
||||
}
|
||||
fn build_prompt(&self, _req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
|
||||
Ok(Prompt {
|
||||
ids: vec![888888],
|
||||
max_new: 100000,
|
||||
sampling: Default::default(),
|
||||
temp_files: Vec::new(),
|
||||
})
|
||||
}
|
||||
fn decoder(&self) -> Box<dyn Decoder> {
|
||||
Box::new(ByteDecoder)
|
||||
}
|
||||
}
|
||||
|
||||
async fn build_app() -> axum::Router {
|
||||
let engine = Arc::new(
|
||||
Engine::start(
|
||||
"python3",
|
||||
&[MOCK.to_string()],
|
||||
None,
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.expect("mock engine starts"),
|
||||
);
|
||||
let svc = ChatService::new(engine, Arc::new(ByteFormatter));
|
||||
strata_ctl::api::router(svc)
|
||||
}
|
||||
|
||||
async fn post_json(app: &axum::Router, body: serde_json::Value) -> (StatusCode, String) {
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/v1/chat/completions")
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap();
|
||||
let resp = app.clone().oneshot(req).await.unwrap();
|
||||
let status = resp.status();
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
(status, String::from_utf8_lossy(&bytes).into_owned())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_lists_the_served_model() {
|
||||
let app = build_app().await;
|
||||
let resp = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/models")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(json["object"], "list");
|
||||
assert_eq!(json["data"][0]["id"], "test-model");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn non_stream_completion() {
|
||||
let app = build_app().await;
|
||||
let (status, text) = post_json(
|
||||
&app,
|
||||
serde_json::json!({
|
||||
"model": "test-model",
|
||||
"messages": [{"role": "user", "content": "hi"}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "body: {text}");
|
||||
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
|
||||
assert_eq!(json["object"], "chat.completion");
|
||||
// the mock's default path emits ids 101..105 -> 'e','f','g','h','i'
|
||||
assert_eq!(json["choices"][0]["message"]["content"], "efghi");
|
||||
assert_eq!(json["choices"][0]["message"]["role"], "assistant");
|
||||
assert_eq!(json["choices"][0]["finish_reason"], "stop");
|
||||
assert_eq!(json["usage"]["completion_tokens"], 5);
|
||||
assert_eq!(
|
||||
json["usage"]["total_tokens"],
|
||||
json["usage"]["prompt_tokens"].as_u64().unwrap() + 5
|
||||
);
|
||||
assert!(json["id"].as_str().unwrap().starts_with("chatcmpl-"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_completion_is_sse() {
|
||||
let app = build_app().await;
|
||||
let (status, text) = post_json(
|
||||
&app,
|
||||
serde_json::json!({
|
||||
"model": "test-model",
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
"stream": true
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "body: {text}");
|
||||
|
||||
// every payload line is `data: ...`; the stream ends with `data: [DONE]`
|
||||
let data_lines: Vec<&str> = text
|
||||
.lines()
|
||||
.filter(|l| l.starts_with("data: "))
|
||||
.map(|l| &l["data: ".len()..])
|
||||
.collect();
|
||||
assert!(
|
||||
data_lines.last().copied() == Some("[DONE]"),
|
||||
"no [DONE]: {text}"
|
||||
);
|
||||
|
||||
// first chunk announces the role, the last (before [DONE]) the finish reason
|
||||
let first: serde_json::Value = serde_json::from_str(data_lines[0]).unwrap();
|
||||
assert_eq!(first["object"], "chat.completion.chunk");
|
||||
assert_eq!(first["choices"][0]["delta"]["role"], "assistant");
|
||||
|
||||
// reassemble content across the middle chunks
|
||||
let mut content = String::new();
|
||||
let mut finish = None;
|
||||
for line in &data_lines[..data_lines.len() - 1] {
|
||||
let v: serde_json::Value = serde_json::from_str(line).unwrap();
|
||||
if let Some(c) = v["choices"][0]["delta"]["content"].as_str() {
|
||||
content.push_str(c);
|
||||
}
|
||||
if let Some(f) = v["choices"][0]["finish_reason"].as_str() {
|
||||
finish = Some(f.to_string());
|
||||
}
|
||||
}
|
||||
assert_eq!(content, "efghi");
|
||||
assert_eq!(finish.as_deref(), Some("stop"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_messages_is_bad_request() {
|
||||
let app = build_app().await;
|
||||
let (status, text) = post_json(
|
||||
&app,
|
||||
serde_json::json!({"model": "test-model", "messages": []}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(json["error"]["type"], "invalid_request_error");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_json_is_openai_error() {
|
||||
let app = build_app().await;
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/v1/chat/completions")
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from("{not json"))
|
||||
.unwrap();
|
||||
let resp = app.oneshot(req).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
assert!(json["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("invalid JSON"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_aborts_on_client_disconnect() {
|
||||
let engine = Arc::new(
|
||||
Engine::start(
|
||||
"python3",
|
||||
&[MOCK.to_string()],
|
||||
None,
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.expect("mock engine starts"),
|
||||
);
|
||||
let svc = ChatService::new(engine.clone(), Arc::new(LongFormatter));
|
||||
let app = strata_ctl::api::router(svc);
|
||||
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/v1/chat/completions")
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(
|
||||
serde_json::json!({
|
||||
"model": "test-model",
|
||||
"messages": [{"role": "user", "content": "go"}],
|
||||
"stream": true
|
||||
})
|
||||
.to_string(),
|
||||
))
|
||||
.unwrap();
|
||||
let resp = app.oneshot(req).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
// Simulate the client vanishing: drop the SSE body without reading it. The
|
||||
// receiver is dropped, the disconnect select fires, the engine is aborted.
|
||||
drop(resp);
|
||||
|
||||
// Poll (non-mutating) until the engine is idle: the long generation must
|
||||
// have been stopped, not left running for the full 100000 tokens. Bounded
|
||||
// wait so the test is robust under parallel load.
|
||||
let mut idle = false;
|
||||
for _ in 0..100 {
|
||||
if engine.is_idle() {
|
||||
idle = true;
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
assert!(idle, "engine still busy after client disconnect");
|
||||
let _ = engine.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_sequence_truncates_content() {
|
||||
let app = build_app().await;
|
||||
// the mock's default answer is "efghi"; stop "gh" cuts it to "ef"
|
||||
let (status, text) = post_json(
|
||||
&app,
|
||||
serde_json::json!({
|
||||
"model": "test-model",
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
"stop": ["gh"]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "body: {text}");
|
||||
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(json["choices"][0]["message"]["content"], "ef");
|
||||
assert_eq!(json["choices"][0]["finish_reason"], "stop");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_sequence_truncates_stream() {
|
||||
let app = build_app().await;
|
||||
let (status, text) = post_json(
|
||||
&app,
|
||||
serde_json::json!({
|
||||
"model": "test-model",
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
"stop": ["gh"],
|
||||
"stream": true
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "body: {text}");
|
||||
let data_lines: Vec<&str> = text
|
||||
.lines()
|
||||
.filter(|l| l.starts_with("data: "))
|
||||
.map(|l| &l["data: ".len()..])
|
||||
.collect();
|
||||
assert_eq!(data_lines.last().copied(), Some("[DONE]"));
|
||||
let mut content = String::new();
|
||||
let mut finish = None;
|
||||
for line in &data_lines[..data_lines.len() - 1] {
|
||||
let v: serde_json::Value = serde_json::from_str(line).unwrap();
|
||||
if let Some(c) = v["choices"][0]["delta"]["content"].as_str() {
|
||||
content.push_str(c);
|
||||
}
|
||||
if let Some(f) = v["choices"][0]["finish_reason"].as_str() {
|
||||
finish = Some(f.to_string());
|
||||
}
|
||||
}
|
||||
assert_eq!(content, "ef");
|
||||
assert_eq!(finish.as_deref(), Some("stop"));
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! End-to-end tests of the supervisor against a scripted mock engine
|
||||
//! (tests/mock_engine.py), which speaks the protocol exactly as `strata
|
||||
//! --serve` prints it.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use strata_ctl::engine::{Engine, EngineError, EngineLine, Sampling};
|
||||
|
||||
fn mock() -> (String, Vec<String>) {
|
||||
let script = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
|
||||
(
|
||||
"python3".into(),
|
||||
vec![script.into(), "--marker".to_string()],
|
||||
)
|
||||
}
|
||||
|
||||
async fn start_mock() -> Engine {
|
||||
let (exe, args) = mock();
|
||||
Engine::start(&exe, &args[0..1], None, Duration::from_secs(10))
|
||||
.await
|
||||
.expect("mock engine starts")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_reads_ready() {
|
||||
let engine = start_mock().await;
|
||||
let ready = engine.ready();
|
||||
assert_eq!(ready.max_context, 8192);
|
||||
assert!(ready.can_stop);
|
||||
assert!(ready.can_hold);
|
||||
assert!(!ready.can_hold_batch);
|
||||
assert_eq!(
|
||||
engine.info().await.get("version").map(String::as_str),
|
||||
Some("0.0.0-mock")
|
||||
);
|
||||
engine.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generate_streams_and_finishes() {
|
||||
let engine = start_mock().await;
|
||||
let mut seen = Vec::new();
|
||||
let out = engine
|
||||
.generate(16, &Sampling::default(), &[1, 2, 3, 4], |line| {
|
||||
if let EngineLine::Prefill { read, total, .. } = line {
|
||||
seen.push((*read, *total));
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.tokens, vec![101, 102, 103, 104, 105]);
|
||||
assert_eq!(out.resumed, 1);
|
||||
assert_eq!(seen, vec![(2, 4)]);
|
||||
let done = out.done.unwrap();
|
||||
assert_eq!((done.generated, done.prompt_tokens), (5, 4));
|
||||
assert_eq!(done.finish, "stop");
|
||||
assert_eq!(done.extra, ["3", "4", "1"]);
|
||||
engine.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refusal_is_reported_and_trailing_done_swallowed() {
|
||||
let engine = start_mock().await;
|
||||
let err = engine
|
||||
.generate(8, &Sampling::default(), &[1, 999999], |_| {})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(&err, EngineError::Refused(m) if m.contains("out of range")));
|
||||
// the mock printed a DONE after the ERR: it must not leak to the next request
|
||||
let out = engine
|
||||
.generate(8, &Sampling::default(), &[1, 2], |_| {})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(out.tokens.len(), 5);
|
||||
engine.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn abort_reaches_a_running_request_and_frees_the_wires() {
|
||||
let exe_mock = mock();
|
||||
let engine = std::sync::Arc::new(
|
||||
Engine::start(
|
||||
&exe_mock.0,
|
||||
&[exe_mock.1[0].clone()],
|
||||
None,
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
let holder = {
|
||||
let engine = engine.clone();
|
||||
tokio::spawn(async move {
|
||||
engine
|
||||
.generate(1000, &Sampling::default(), &[888888], |_| {})
|
||||
.await
|
||||
})
|
||||
};
|
||||
// a second request queues behind the first (FIFO, not a refusal)
|
||||
let waiter = {
|
||||
let engine = engine.clone();
|
||||
tokio::spawn(async move {
|
||||
engine
|
||||
.generate(8, &Sampling::default(), &[1, 2], |_| {})
|
||||
.await
|
||||
})
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert!(engine.abort().await.unwrap(), "a request was running");
|
||||
let held = holder.await.unwrap();
|
||||
assert!(
|
||||
matches!(&held, Err(EngineError::Refused(m)) if m == "aborted"),
|
||||
"the held request should end aborted: {held:?}"
|
||||
);
|
||||
// the queued waiter ran on the same engine and finished normally
|
||||
let waited = waiter.await.unwrap();
|
||||
assert_eq!(waited.unwrap().tokens.len(), 5);
|
||||
// nothing running now: abort is a no-op
|
||||
assert!(!engine.abort().await.unwrap());
|
||||
engine.shutdown().await.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Tests for the Inkling output dialect, driving the public token stream the
|
||||
//! way `server.py` does (one `feed_token` per engine token) and asserting the
|
||||
//! reasoning/content framing the launcher-patched reference produces.
|
||||
|
||||
use strata_ctl::inkling::dialect::{tag, InklingDialect, Kind, Out};
|
||||
|
||||
/// Feed a scripted sequence of tokens; `special` marks channel tokens.
|
||||
fn run(tokens: &[(&str, bool)], finish: Option<&str>) -> Vec<Out> {
|
||||
let mut d = InklingDialect::new();
|
||||
let mut out = Vec::new();
|
||||
for (piece, is_special) in tokens {
|
||||
out.extend(d.feed_token(piece, *is_special));
|
||||
}
|
||||
out.extend(d.finish(finish));
|
||||
out
|
||||
}
|
||||
|
||||
fn content_of(outs: &[Out]) -> String {
|
||||
outs.iter()
|
||||
.filter(|o| o.kind == Kind::Content)
|
||||
.map(|o| o.text.as_str())
|
||||
.collect()
|
||||
}
|
||||
fn reasoning_of(outs: &[Out]) -> String {
|
||||
outs.iter()
|
||||
.filter(|o| o.kind == Kind::Reasoning)
|
||||
.map(|o| o.text.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_answer() {
|
||||
let outs = run(
|
||||
&[
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
(tag::CONTENT_TEXT, true),
|
||||
("Hello world", false),
|
||||
(tag::END_MESSAGE, true),
|
||||
],
|
||||
None,
|
||||
);
|
||||
assert_eq!(content_of(&outs), "Hello world");
|
||||
assert_eq!(reasoning_of(&outs), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thinking_is_streamed_live_then_answers() {
|
||||
let mut d = InklingDialect::new();
|
||||
let mut reasoning = Vec::new();
|
||||
let mut content = Vec::new();
|
||||
let feed = |d: &mut InklingDialect,
|
||||
p: &str,
|
||||
s: bool,
|
||||
reasoning: &mut Vec<String>,
|
||||
content: &mut Vec<String>| {
|
||||
for o in d.feed_token(p, s) {
|
||||
match o.kind {
|
||||
Kind::Reasoning => reasoning.push(o.text),
|
||||
Kind::Content => content.push(o.text),
|
||||
}
|
||||
}
|
||||
};
|
||||
feed(
|
||||
&mut d,
|
||||
tag::MESSAGE_MODEL,
|
||||
true,
|
||||
&mut reasoning,
|
||||
&mut content,
|
||||
);
|
||||
feed(
|
||||
&mut d,
|
||||
tag::CONTENT_THINKING,
|
||||
true,
|
||||
&mut reasoning,
|
||||
&mut content,
|
||||
);
|
||||
feed(&mut d, "Let me ", false, &mut reasoning, &mut content);
|
||||
feed(&mut d, "think. ", false, &mut reasoning, &mut content);
|
||||
feed(&mut d, tag::END_MESSAGE, true, &mut reasoning, &mut content);
|
||||
feed(
|
||||
&mut d,
|
||||
tag::MESSAGE_MODEL,
|
||||
true,
|
||||
&mut reasoning,
|
||||
&mut content,
|
||||
);
|
||||
feed(
|
||||
&mut d,
|
||||
tag::CONTENT_TEXT,
|
||||
true,
|
||||
&mut reasoning,
|
||||
&mut content,
|
||||
);
|
||||
feed(&mut d, "The answer.", false, &mut reasoning, &mut content);
|
||||
feed(&mut d, tag::END_MESSAGE, true, &mut reasoning, &mut content);
|
||||
d.finish(None);
|
||||
|
||||
// reasoning arrived as discrete live deltas, not one blob at the end
|
||||
assert_eq!(reasoning, vec!["Let me ", "think. "]);
|
||||
assert_eq!(content.join(""), "The answer.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_end_message_stays_in_thinking() {
|
||||
// #6675: the model literally writes `<|end_message|>` inside its thinking;
|
||||
// it must not leak to content nor end thinking early.
|
||||
let outs = run(
|
||||
&[
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
(tag::CONTENT_THINKING, true),
|
||||
("before ", false),
|
||||
(tag::END_MESSAGE, true), // quoted, not a real channel end
|
||||
("after", false), // ordinary text proves it was quoted
|
||||
(tag::ENDOFTEXT, true),
|
||||
],
|
||||
None,
|
||||
);
|
||||
assert_eq!(content_of(&outs), "");
|
||||
let r = reasoning_of(&outs);
|
||||
assert!(r.contains("before "), "{r}");
|
||||
assert!(
|
||||
r.contains(tag::END_MESSAGE),
|
||||
"quoted tag kept in reasoning: {r}"
|
||||
);
|
||||
assert!(r.contains("after"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_overflow_becomes_plain_text() {
|
||||
// #6620: no `<|content_text|>`; a newline in the "header" means it is text.
|
||||
let outs = run(
|
||||
&[
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
("Just prose\ncontinued", false),
|
||||
(tag::END_MESSAGE, true),
|
||||
],
|
||||
None,
|
||||
);
|
||||
assert_eq!(content_of(&outs), "Just prose\ncontinued");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_json_renders_a_frame() {
|
||||
let outs = run(
|
||||
&[
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
("get_weather", false),
|
||||
(tag::CONTENT_INVOKE_TOOL_JSON, true),
|
||||
(r#"{"name":"get_weather","args":{"city":"Rome"}}"#, false),
|
||||
(tag::END_MESSAGE, true),
|
||||
],
|
||||
None,
|
||||
);
|
||||
let c = content_of(&outs);
|
||||
assert!(c.contains(tag::TOOL_CALL_OPEN), "{c}");
|
||||
assert!(c.contains(tag::TOOL_CALL_CLOSE), "{c}");
|
||||
// the JSON inside round-trips name + arguments
|
||||
let json_start = c.find('{').unwrap();
|
||||
let json_end = c.rfind('}').unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&c[json_start..=json_end]).unwrap();
|
||||
assert_eq!(v["name"], "get_weather");
|
||||
assert_eq!(v["arguments"]["city"], "Rome");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_json_args_as_json_string_is_parsed() {
|
||||
// arguments shipped as a JSON *string* must be parsed into an object
|
||||
let outs = run(
|
||||
&[
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
(tag::CONTENT_INVOKE_TOOL_JSON, true),
|
||||
(r#"{"name":"f","args":"{\"a\":1}"}"#, false),
|
||||
(tag::END_MESSAGE, true),
|
||||
],
|
||||
None,
|
||||
);
|
||||
let c = content_of(&outs);
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(&c[c.find('{').unwrap()..=c.rfind('}').unwrap()]).unwrap();
|
||||
assert_eq!(v["arguments"]["a"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_tool_falls_back_to_header_name() {
|
||||
let mut d = InklingDialect::new();
|
||||
let mut content = String::new();
|
||||
for (p, s) in [
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
("lookup", false),
|
||||
(tag::CONTENT_INVOKE_TOOL_JSON, true),
|
||||
(
|
||||
"{\"a\":1", // unterminated
|
||||
false,
|
||||
),
|
||||
] {
|
||||
for o in d.feed_token(p, s) {
|
||||
if o.kind == Kind::Content {
|
||||
content.push_str(&o.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
for o in d.finish(Some("length")) {
|
||||
if o.kind == Kind::Content {
|
||||
content.push_str(&o.text);
|
||||
}
|
||||
}
|
||||
assert!(content.contains(tag::TOOL_CALL_OPEN), "{content}");
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(&content[content.find('{').unwrap()..=content.rfind('}').unwrap()])
|
||||
.unwrap();
|
||||
assert_eq!(v["name"], "lookup");
|
||||
assert_eq!(d.calls, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thinking_only_at_length_surfaces_reasoning() {
|
||||
// #6682: budget expires mid-thinking with no answer.
|
||||
let outs = run(
|
||||
&[
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
(tag::CONTENT_THINKING, true),
|
||||
("pondering", false),
|
||||
],
|
||||
Some("length"),
|
||||
);
|
||||
assert!(content_of(&outs).is_empty());
|
||||
// the live delta plus the finish-time accumulation both carry it (faithful
|
||||
// to the reference: patched emit + _finish_typed #6682)
|
||||
assert!(reasoning_of(&outs).contains("pondering"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_sampling_returns_to_idle() {
|
||||
// after END_SAMPLING a new turn can open; ensure a following MessageModel
|
||||
// does not double-emit the prior content.
|
||||
let outs = run(
|
||||
&[
|
||||
(tag::MESSAGE_MODEL, true),
|
||||
(tag::CONTENT_TEXT, true),
|
||||
("first", false),
|
||||
(tag::END_SAMPLING, true),
|
||||
],
|
||||
None,
|
||||
);
|
||||
assert_eq!(content_of(&outs), "first");
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! End-to-end test of the assembled InklingFormatter: prompt build (template +
|
||||
//! encode) and output decode (detok + channel dialect -> API pieces), using a
|
||||
//! host-independent fixture tokenizer whose decoder concatenates without spaces
|
||||
//! (like the real ByteLevel decoder), so channel tags match exactly.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use tokenizers::decoders::fuse::Fuse;
|
||||
use tokenizers::models::wordlevel::WordLevel;
|
||||
use tokenizers::{AddedToken, Tokenizer};
|
||||
|
||||
use strata_ctl::api::formatter::{Formatter, Piece};
|
||||
use strata_ctl::api::types::ChatRequest;
|
||||
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
|
||||
|
||||
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
fn fixture_tokenizer() -> (Arc<InklingTokenizer>, std::path::PathBuf) {
|
||||
let mut vocab = HashMap::new();
|
||||
vocab.insert("think".to_string(), 0u32);
|
||||
vocab.insert("answer".to_string(), 1u32);
|
||||
vocab.insert("hello".to_string(), 2u32);
|
||||
vocab.insert("[UNK]".to_string(), 3u32);
|
||||
vocab.insert(TOOL_BODY.to_string(), 4u32);
|
||||
let model = WordLevel::builder()
|
||||
.vocab(vocab.into_iter().collect())
|
||||
.unk_token("[UNK]".to_string())
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut tok = Tokenizer::new(model);
|
||||
// no pre-tokenizer: each whole segment maps to one vocab word (the JSON tool
|
||||
// body must not be split on punctuation), specials still match via the trie
|
||||
tok.with_pre_tokenizer(None::<tokenizers::pre_tokenizers::PreTokenizerWrapper>);
|
||||
// concatenate without separators, mirroring the real ByteLevel decoder
|
||||
tok.with_decoder(Some(Fuse::new()));
|
||||
let _ = tok.add_special_tokens([
|
||||
AddedToken::from("<|message_model|>", true),
|
||||
AddedToken::from("<|content_thinking|>", true),
|
||||
AddedToken::from("<|content_text|>", true),
|
||||
AddedToken::from("<|end_message|>", true),
|
||||
AddedToken::from("<|content_model_end_sampling|>", true),
|
||||
AddedToken::from("<|content_invoke_tool_json|>", true),
|
||||
]);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"strata-ctl-fmt-{}-{}.json",
|
||||
std::process::id(),
|
||||
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
));
|
||||
tok.save(&path, false).unwrap();
|
||||
(Arc::new(InklingTokenizer::from_file(&path).unwrap()), path)
|
||||
}
|
||||
|
||||
const TEMPLATE: &str =
|
||||
"{%- for m in messages -%}<|content_text|>{{ m.content }}<|end_message|>{%- endfor -%}";
|
||||
|
||||
/// A tool-call body as one whitespace-free word (the fixture is WordLevel).
|
||||
const TOOL_BODY: &str = r#"{"name":"get_weather","args":{"city":"Roma"}}"#;
|
||||
|
||||
fn formatter() -> (InklingFormatter, Arc<InklingTokenizer>, std::path::PathBuf) {
|
||||
let (tok, path) = fixture_tokenizer();
|
||||
let template = ChatTemplate::new(TEMPLATE).unwrap();
|
||||
let fmt = InklingFormatter::new(
|
||||
tok.clone(),
|
||||
template,
|
||||
"test-model".into(),
|
||||
Some("low".into()),
|
||||
);
|
||||
(fmt, tok, path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_prompt_renders_and_encodes() {
|
||||
let (fmt, tok, path) = formatter();
|
||||
let req: ChatRequest = serde_json::from_value(
|
||||
json!({"model": "test-model", "messages": [{"role": "user", "content": "hello"}]}),
|
||||
)
|
||||
.unwrap();
|
||||
let prompt = fmt.build_prompt(&req).unwrap();
|
||||
// the rendered prompt is "<|content_text|>hello<|end_message|>"
|
||||
let text_id = tok.encode("<|content_text|>").unwrap()[0];
|
||||
let end_id = tok.encode("<|end_message|>").unwrap()[0];
|
||||
assert!(prompt.ids.contains(&text_id));
|
||||
assert!(prompt.ids.contains(&2)); // "hello"
|
||||
assert!(prompt.ids.contains(&end_id));
|
||||
assert_eq!(prompt.max_new, 2048); // default
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_splits_reasoning_and_content() {
|
||||
let (fmt, tok, path) = formatter();
|
||||
let mut dec = fmt.decoder();
|
||||
|
||||
// a scripted assistant reply: thinking, then the answer
|
||||
let script = [
|
||||
"<|message_model|>",
|
||||
"<|content_thinking|>",
|
||||
"think",
|
||||
"<|end_message|>",
|
||||
"<|message_model|>",
|
||||
"<|content_text|>",
|
||||
"answer",
|
||||
"<|end_message|>",
|
||||
];
|
||||
let mut reasoning = String::new();
|
||||
let mut content = String::new();
|
||||
for seg in script {
|
||||
for id in tok.encode(seg).unwrap() {
|
||||
for p in dec.push(id) {
|
||||
match p {
|
||||
Piece::Reasoning(s) => reasoning.push_str(&s),
|
||||
Piece::Content(s) => content.push_str(&s),
|
||||
Piece::ToolCall { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for p in dec.finish(None) {
|
||||
match p {
|
||||
Piece::Reasoning(s) => reasoning.push_str(&s),
|
||||
Piece::Content(s) => content.push_str(&s),
|
||||
Piece::ToolCall { .. } => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(reasoning, "think");
|
||||
assert_eq!(content, "answer");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_tokens_override_is_honored() {
|
||||
let (fmt, _tok, path) = formatter();
|
||||
let req: ChatRequest = serde_json::from_value(json!({
|
||||
"model": "test-model",
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"max_tokens": 77
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(fmt.build_prompt(&req).unwrap().max_new, 77);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_emits_structured_tool_call() {
|
||||
let (fmt, tok, path) = formatter();
|
||||
let mut dec = fmt.decoder();
|
||||
|
||||
// assistant opens a JSON tool channel, emits the call body, closes it
|
||||
let script = [
|
||||
"<|message_model|>",
|
||||
"<|content_invoke_tool_json|>",
|
||||
TOOL_BODY,
|
||||
"<|end_message|>",
|
||||
];
|
||||
let mut calls: Vec<(String, String)> = Vec::new();
|
||||
let mut content = String::new();
|
||||
for seg in script {
|
||||
for id in tok.encode(seg).unwrap() {
|
||||
for p in dec.push(id) {
|
||||
match p {
|
||||
Piece::ToolCall { name, arguments } => calls.push((name, arguments)),
|
||||
Piece::Content(s) => content.push_str(&s),
|
||||
Piece::Reasoning(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for p in dec.finish(None) {
|
||||
if let Piece::ToolCall { name, arguments } = p {
|
||||
calls.push((name, arguments));
|
||||
}
|
||||
}
|
||||
assert_eq!(calls.len(), 1, "content was: {content}");
|
||||
assert_eq!(calls[0].0, "get_weather");
|
||||
assert_eq!(calls[0].1, r#"{"city":"Roma"}"#);
|
||||
// the raw frame must NOT leak into content
|
||||
assert!(content.is_empty(), "frame leaked into content: {content}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_choice_forcing_is_rejected() {
|
||||
let (fmt, _tok, path) = formatter();
|
||||
for choice in [
|
||||
json!("required"),
|
||||
json!({"type": "function", "function": {"name": "f"}}),
|
||||
json!("bogus"),
|
||||
] {
|
||||
let req: ChatRequest = serde_json::from_value(json!({
|
||||
"model": "m",
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"tool_choice": choice
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(
|
||||
fmt.build_prompt(&req).is_err(),
|
||||
"choice {choice} should be rejected"
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_choice_none_and_auto_accepted() {
|
||||
let (fmt, _tok, path) = formatter();
|
||||
for choice in [json!("none"), json!("auto")] {
|
||||
let req: ChatRequest = serde_json::from_value(json!({
|
||||
"model": "m",
|
||||
"messages": [{"role": "user", "content": "hello"}],
|
||||
"tools": [{"type": "function", "function": {"name": "f"}}],
|
||||
"tool_choice": choice
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(
|
||||
fmt.build_prompt(&req).is_ok(),
|
||||
"choice {choice} should be accepted"
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Tests for the Inkling image bridge: path encoding, source extraction across
|
||||
//! OpenAI/Responses/Anthropic shapes, and materialization (PNG passthrough,
|
||||
//! WebP->PNG normalization, local path). Host-independent: images are built in
|
||||
//! memory with the image crate.
|
||||
|
||||
use base64::Engine;
|
||||
use serde_json::json;
|
||||
use strata_ctl::inkling::images::{encode_path, extract_sources, materialize};
|
||||
|
||||
fn png_bytes() -> Vec<u8> {
|
||||
let img = image::DynamicImage::ImageRgba8(image::RgbaImage::new(2, 2));
|
||||
let mut buf = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
buf
|
||||
}
|
||||
|
||||
fn webp_bytes() -> Vec<u8> {
|
||||
let img = image::DynamicImage::ImageRgba8(image::RgbaImage::new(2, 2));
|
||||
let mut buf = Vec::new();
|
||||
img.write_to(
|
||||
&mut std::io::Cursor::new(&mut buf),
|
||||
image::ImageFormat::WebP,
|
||||
)
|
||||
.unwrap();
|
||||
buf
|
||||
}
|
||||
|
||||
fn data_url(mime: &str, bytes: &[u8]) -> String {
|
||||
format!(
|
||||
"data:{mime};base64,{}",
|
||||
base64::engine::general_purpose::STANDARD.encode(bytes)
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_path_only_percent_and_space() {
|
||||
assert_eq!(encode_path("/mnt/my pic.png"), "/mnt/my%20pic.png");
|
||||
assert_eq!(encode_path("/a%b.png"), "/a%25b.png");
|
||||
assert_eq!(encode_path("/a %b.png"), "/a%20%25b.png");
|
||||
// slashes stay literal (the engine only decodes %20 and %25)
|
||||
assert_eq!(encode_path("/mnt/x/y.png"), "/mnt/x/y.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_sources_shapes_and_order() {
|
||||
let msgs = json!([
|
||||
{"role": "user", "content": [
|
||||
{"type": "text", "text": "guarda"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAA"}},
|
||||
{"type": "image_url", "image_url": "/local/a.png"}
|
||||
]},
|
||||
{"role": "user", "content": [
|
||||
{"type": "input_image", "image_url": "https://x/b.png"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "BBB"}}
|
||||
]}
|
||||
]);
|
||||
let srcs = extract_sources(&msgs);
|
||||
assert_eq!(
|
||||
srcs,
|
||||
vec![
|
||||
"data:image/png;base64,AAA",
|
||||
"/local/a.png",
|
||||
"https://x/b.png",
|
||||
"data:image/jpeg;base64,BBB",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_ignores_text_only() {
|
||||
let msgs = json!([{"role": "user", "content": "ciao"}]);
|
||||
assert!(extract_sources(&msgs).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialize_png_passthrough() {
|
||||
let png = png_bytes();
|
||||
let paths = materialize(&[data_url("image/png", &png)]).unwrap();
|
||||
assert_eq!(paths.len(), 1);
|
||||
assert_eq!(paths[0].extension().unwrap(), "png");
|
||||
assert_eq!(std::fs::read(&paths[0]).unwrap(), png);
|
||||
let _ = std::fs::remove_file(&paths[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialize_webp_normalizes_to_png() {
|
||||
let webp = webp_bytes();
|
||||
let paths = materialize(&[data_url("image/webp", &webp)]).unwrap();
|
||||
assert_eq!(paths.len(), 1);
|
||||
assert_eq!(paths[0].extension().unwrap(), "png");
|
||||
let out = std::fs::read(&paths[0]).unwrap();
|
||||
assert!(
|
||||
out.starts_with(&[0x89, b'P', b'N', b'G']),
|
||||
"not converted to PNG"
|
||||
);
|
||||
let _ = std::fs::remove_file(&paths[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialize_local_path() {
|
||||
let png = png_bytes();
|
||||
let src = std::env::temp_dir().join(format!("strata-ctl-img-src-{}.png", std::process::id()));
|
||||
std::fs::write(&src, &png).unwrap();
|
||||
let paths = materialize(&[src.to_string_lossy().to_string()]).unwrap();
|
||||
assert_eq!(std::fs::read(&paths[0]).unwrap(), png);
|
||||
let _ = std::fs::remove_file(&paths[0]);
|
||||
let _ = std::fs::remove_file(&src);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Tests for the Inkling chat-template layer: the custom tojson/raise_exception
|
||||
//! and generation-strip (deterministic, inline template), prepare_messages /
|
||||
//! finish_prompt (pure), and an #[ignore] render of the real chat_template.jinja.
|
||||
|
||||
use serde_json::json;
|
||||
use strata_ctl::inkling::dialect::tag;
|
||||
use strata_ctl::inkling::template::{finish_prompt, prepare_messages, ChatTemplate};
|
||||
|
||||
#[test]
|
||||
fn tojson_compact_and_sorted() {
|
||||
let t =
|
||||
ChatTemplate::new("{{ {'b': 1, 'a': 2} | tojson(sort_keys=true, separators=(',', ':')) }}")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
t.render(&json!([]), None, None).unwrap(),
|
||||
"{\"a\":2,\"b\":1}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_blocks_are_transparent() {
|
||||
let t = ChatTemplate::new("A{% generation %}B{% endgeneration %}C").unwrap();
|
||||
assert_eq!(t.render(&json!([]), None, None).unwrap(), "ABC");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_and_dictsort_work() {
|
||||
let src = "{%- set s = namespace(x=[]) -%}\
|
||||
{%- set s.x = s.x + [1, 2] -%}\
|
||||
{{ s.x | tojson(separators=(',', ':')) }}|\
|
||||
{%- for k, v in {'b': 1, 'a': 2} | dictsort(case_sensitive=true) -%}\
|
||||
{{ k }}={{ v }};{%- endfor -%}";
|
||||
let t = ChatTemplate::new(src).unwrap();
|
||||
assert_eq!(t.render(&json!([]), None, None).unwrap(), "[1,2]|a=2;b=1;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raise_exception_fails_render() {
|
||||
let t = ChatTemplate::new("{{ raise_exception('boom') }}").unwrap();
|
||||
let err = t.render(&json!([]), None, None).unwrap_err();
|
||||
assert!(err.to_string().contains("boom"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_messages_parses_string_arguments() {
|
||||
let mut msgs = json!([
|
||||
{"role": "assistant", "tool_calls": [
|
||||
{"id": "c1", "type": "function",
|
||||
"function": {"name": "f", "arguments": "{\"a\": 1}"}}
|
||||
]},
|
||||
{"role": "assistant", "tool_calls": [
|
||||
{"id": "c2", "function": {"name": "g", "arguments": null}}
|
||||
]}
|
||||
]);
|
||||
prepare_messages(&mut msgs);
|
||||
assert_eq!(
|
||||
msgs[0]["tool_calls"][0]["function"]["arguments"],
|
||||
json!({"a": 1})
|
||||
);
|
||||
assert_eq!(msgs[1]["tool_calls"][0]["function"]["arguments"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finish_prompt_only_for_effort_zero() {
|
||||
// positive effort: untouched (model opens its own thinking)
|
||||
let p = "<|message_system|><|content_text|>Thinking effort level: 0.2<|end_message|>";
|
||||
assert_eq!(finish_prompt(p, false, false), p);
|
||||
|
||||
// effort zero, no opener yet: append the text opener (no tools)
|
||||
let z = "<|message_system|><|content_text|>Thinking effort level: 0<|end_message|>";
|
||||
let expect = format!("{z}{}{}", tag::MESSAGE_MODEL, tag::CONTENT_TEXT);
|
||||
assert_eq!(finish_prompt(z, false, false), expect);
|
||||
|
||||
// with tools: the empty-thinking opener
|
||||
let expect_tools = format!(
|
||||
"{z}{}{}{}",
|
||||
tag::MESSAGE_MODEL,
|
||||
tag::CONTENT_THINKING,
|
||||
tag::END_MESSAGE
|
||||
);
|
||||
assert_eq!(finish_prompt(z, true, false), expect_tools);
|
||||
|
||||
// idempotent: already ends with the text opener
|
||||
assert_eq!(finish_prompt(&expect, false, false), expect);
|
||||
}
|
||||
|
||||
/// Render the REAL template (host file). Run with:
|
||||
/// STRATA_TOK_DIR=~/.config/strata-inkling/inkling-tok cargo test -- --ignored
|
||||
#[test]
|
||||
#[ignore = "needs the real Inkling chat_template.jinja"]
|
||||
fn real_template_renders_a_turn() {
|
||||
let dir = std::env::var("STRATA_TOK_DIR")
|
||||
.unwrap_or_else(|_| "/home/federico/.config/strata-inkling/inkling-tok".to_string());
|
||||
let src = std::fs::read_to_string(format!("{dir}/chat_template.jinja")).unwrap();
|
||||
let t = ChatTemplate::new(&src).unwrap();
|
||||
|
||||
let msgs = json!([{"role": "user", "content": "ciao"}]);
|
||||
let out = t.render(&msgs, None, Some("low")).unwrap();
|
||||
assert!(out.contains("Thinking effort level: 0.2"), "{out}");
|
||||
assert!(
|
||||
out.contains("<|message_user|><|content_text|>ciao<|end_message|>"),
|
||||
"{out}"
|
||||
);
|
||||
|
||||
// effort none renders level 0
|
||||
let out0 = t.render(&msgs, None, Some("none")).unwrap();
|
||||
assert!(
|
||||
out0.contains("Thinking effort level: 0<|end_message|>"),
|
||||
"{out0}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Tests for the Inkling tokenizer wrapper.
|
||||
//!
|
||||
//! The deterministic tests build a tiny fixture tokenizer with the `tokenizers`
|
||||
//! crate (no host files), so the suite is green anywhere. A separate `#[ignore]`
|
||||
//! test exercises the REAL o200k tokenizer when STRATA_TOK_DIR is set; run it
|
||||
//! with `cargo test -- --ignored`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokenizers::models::wordlevel::WordLevel;
|
||||
use tokenizers::AddedToken;
|
||||
use tokenizers::Tokenizer;
|
||||
|
||||
use strata_ctl::inkling::dialect::Tag;
|
||||
use strata_ctl::inkling::tokenizer::{Detok, InklingTokenizer};
|
||||
|
||||
/// Unique suffix so parallel tests never share a fixture file.
|
||||
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Build a small WordLevel tokenizer with a few Inkling channel tokens added,
|
||||
/// save it, and load it through our wrapper. Returns (wrapper, path, ids).
|
||||
fn fixture() -> (InklingTokenizer, std::path::PathBuf) {
|
||||
let mut vocab = HashMap::new();
|
||||
vocab.insert("hello".to_string(), 0u32);
|
||||
vocab.insert("world".to_string(), 1u32);
|
||||
vocab.insert("[UNK]".to_string(), 2u32);
|
||||
let model = WordLevel::builder()
|
||||
.vocab(vocab.into_iter().collect())
|
||||
.unk_token("[UNK]".to_string())
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut tok = Tokenizer::new(model);
|
||||
tok.with_pre_tokenizer(Some(tokenizers::pre_tokenizers::whitespace::Whitespace));
|
||||
let _ = tok.add_special_tokens([
|
||||
AddedToken::from("<|message_model|>", true),
|
||||
AddedToken::from("<|content_text|>", true),
|
||||
AddedToken::from("<|content_thinking|>", true),
|
||||
AddedToken::from("<|end_message|>", true),
|
||||
]);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"strata-ctl-tok-{}-{}.json",
|
||||
std::process::id(),
|
||||
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
));
|
||||
tok.save(&path, false).unwrap();
|
||||
let wrapped = InklingTokenizer::from_file(&path).unwrap();
|
||||
(wrapped, path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_decode_roundtrip() {
|
||||
let (t, path) = fixture();
|
||||
let ids = t.encode("hello world").unwrap();
|
||||
assert_eq!(ids, vec![0, 1]);
|
||||
let decoded = t.decode_all(&ids).unwrap();
|
||||
assert!(
|
||||
decoded.contains("hello") && decoded.contains("world"),
|
||||
"{decoded}"
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_tokens_map_to_tags() {
|
||||
let (t, path) = fixture();
|
||||
// a channel token encodes to a single id and maps back to its dialect tag
|
||||
let ids = t.encode("<|content_thinking|>").unwrap();
|
||||
assert_eq!(ids.len(), 1);
|
||||
assert!(t.is_special(ids[0]));
|
||||
assert_eq!(t.channel_tag(ids[0]), Some(Tag::ContentThinking));
|
||||
|
||||
let ids = t.encode("<|end_message|>").unwrap();
|
||||
assert_eq!(t.channel_tag(ids[0]), Some(Tag::EndMessage));
|
||||
// an ordinary word is not special
|
||||
assert!(!t.is_special(0));
|
||||
assert_eq!(t.channel_tag(0), None);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detok_streams_incrementally() {
|
||||
let (t, path) = fixture();
|
||||
let mut d = Detok::new(Arc::new(t));
|
||||
let a = d.push(0);
|
||||
let b = d.push(1);
|
||||
let c = d.finish();
|
||||
// WordLevel decode re-inserts the whitespace between words
|
||||
assert_eq!(format!("{a}{b}{c}"), "hello world");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detok_emits_special_tokens_immediately() {
|
||||
let (t, path) = fixture();
|
||||
let think_id = t.encode("<|content_thinking|>").unwrap()[0];
|
||||
let mut d = Detok::new(Arc::new(t));
|
||||
// ordinary word then a channel token: both surface as text pieces
|
||||
let a = d.push(0);
|
||||
let b = d.push(think_id);
|
||||
assert_eq!(a, "hello");
|
||||
assert!(b.contains("<|content_thinking|>"), "{b}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
/// Real-tokenizer check, ignored by default (host files). Run with:
|
||||
/// STRATA_TOK_DIR=~/.config/strata-inkling/inkling-tok cargo test -- --ignored
|
||||
#[test]
|
||||
#[ignore = "needs the real Inkling tokenizer dir"]
|
||||
fn real_tokenizer_channel_ids() {
|
||||
let dir = std::env::var("STRATA_TOK_DIR")
|
||||
.unwrap_or_else(|_| "/home/federico/.config/strata-inkling/inkling-tok".to_string());
|
||||
let t = InklingTokenizer::load_dir(std::path::Path::new(&dir)).expect("load real tokenizer");
|
||||
|
||||
// the exact ids observed in tokenizer.hf.json's added_tokens
|
||||
assert_eq!(t.channel_tag(200001), Some(Tag::MessageModel));
|
||||
assert_eq!(t.channel_tag(200004), Some(Tag::ContentText));
|
||||
assert_eq!(t.channel_tag(200006), Some(Tag::EndSampling));
|
||||
assert_eq!(t.channel_tag(200008), Some(Tag::ContentThinking));
|
||||
assert_eq!(t.channel_tag(200010), Some(Tag::EndMessage));
|
||||
assert_eq!(t.channel_tag(200024), Some(Tag::ContentXml));
|
||||
assert_eq!(t.channel_tag(200049), Some(Tag::ContentInvokeToolJson));
|
||||
assert_eq!(t.channel_tag(200057), Some(Tag::ContentInvokeToolText));
|
||||
assert_eq!(t.channel_tag(199999), Some(Tag::EndOfText));
|
||||
|
||||
// a channel token in a rendered prompt encodes to its single id
|
||||
let ids = t
|
||||
.encode("<|message_model|><|content_text|>ciao<|end_message|>")
|
||||
.unwrap();
|
||||
assert_eq!(ids.first().copied(), Some(200001));
|
||||
assert_eq!(ids.last().copied(), Some(200010));
|
||||
assert!(t.decode_all(&ids).unwrap().contains("ciao"));
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A scripted stand-in for `strata --serve`, for strata-ctl's integration tests.
|
||||
|
||||
Speaks the line protocol exactly as the engine's parser emits it:
|
||||
READY/INFO at start, then per GEN: optional RESUME, PP lines, T lines, DONE.
|
||||
|
||||
Faithful to the real engine's key invariant: **one DONE per request**. A STOP
|
||||
arriving mid-request ends that request with a single DONE and is not answered
|
||||
again; a STOP arriving while idle is ignored (no request to abort). Stdin is
|
||||
read on a background thread so STOP can interrupt a long generation, exactly
|
||||
as the resident engine's own stdin reader does.
|
||||
|
||||
Scenarios, keyed by the prompt ids sent:
|
||||
* 999999 in ids -> ERR then DONE (a refused id)
|
||||
* 888888 in ids -> long generation (many tokens), interruptible by STOP
|
||||
* 777777 in ids -> total silence (the supervisor's watchdog must fire)
|
||||
* otherwise -> echo five tokens and finish
|
||||
"""
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
def out(line: str) -> None:
|
||||
sys.stdout.write(line + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def reader(cmds: "queue.Queue[str]") -> None:
|
||||
for raw in sys.stdin:
|
||||
cmds.put(raw.strip())
|
||||
cmds.put(None) # EOF
|
||||
|
||||
|
||||
out("INFO version=0.0.0-mock build=test")
|
||||
out("READY 8192 stop hold")
|
||||
|
||||
cmds: "queue.Queue[str | None]" = queue.Queue()
|
||||
threading.Thread(target=reader, args=(cmds,), daemon=True).start()
|
||||
|
||||
while True:
|
||||
cmd = cmds.get()
|
||||
if cmd is None or cmd == "QUIT":
|
||||
break
|
||||
if cmd == "STOP":
|
||||
continue # idle STOP: nothing to abort, no reply (as the real engine)
|
||||
if not cmd.startswith("GEN"):
|
||||
out("ERR unknown command")
|
||||
continue
|
||||
parts = cmd.split()
|
||||
if len(parts) < 3:
|
||||
out("ERR GEN: missing ids")
|
||||
continue
|
||||
try:
|
||||
ids = [int(t) for t in parts[-1].split(",")]
|
||||
except ValueError:
|
||||
out("ERR GEN: bad id")
|
||||
continue
|
||||
keys = " ".join(parts[1:-1])
|
||||
|
||||
if "bad_key" in keys:
|
||||
out("ERR GEN: unknown/unsupported key bad_key")
|
||||
out("DONE 0 0 0.0 0.0 error")
|
||||
continue
|
||||
if 999999 in ids:
|
||||
out("ERR GEN: id out of range")
|
||||
out("DONE 0 0 0.0 0.0 error")
|
||||
continue
|
||||
if 777777 in ids:
|
||||
# total silence for this request: swallow commands until a STOP ends it
|
||||
while True:
|
||||
nxt = cmds.get()
|
||||
if nxt is None or nxt == "QUIT":
|
||||
sys.exit(0)
|
||||
if nxt == "STOP":
|
||||
out("DONE 0 0 0.0 0.0 abort")
|
||||
break
|
||||
continue
|
||||
if 888888 in ids:
|
||||
out("RESUME 3")
|
||||
out("PP 5 5 1.5 3333.3")
|
||||
n = 0
|
||||
stopped = False
|
||||
while n < 100000:
|
||||
nxt = cmds.get_nowait() if not cmds.empty() else None
|
||||
if nxt == "STOP":
|
||||
stopped = True
|
||||
break
|
||||
n += 1
|
||||
out(f"T {n}")
|
||||
if n % 50 == 0:
|
||||
time.sleep(0.001)
|
||||
out(f"DONE {n} {len(ids)} 1.0 2.0 {'abort' if stopped else 'length'}")
|
||||
continue
|
||||
|
||||
out("RESUME 1")
|
||||
out("PP 2 4 0.9 2222.2")
|
||||
for t in (101, 102, 103, 104, 105):
|
||||
out(f"T {t}")
|
||||
out("DONE 5 4 12.5 34.0 stop 3 4 1")
|
||||
Reference in new issue
Block a user