Files
strata-ctl/src/api/formatter.rs
T

156 lines
6.1 KiB
Rust

//! 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.
/// Matches the project-wide generation budget (CoT + answer share it); a
/// dialect with a real tokenizer overrides this from its config.
fn default_max_new(&self) -> u32 {
16384
}
/// Token count of a text, used to route uploads (small-text inline threshold).
/// Default is a byte-length estimate; dialects with a real tokenizer override.
fn count_tokens(&self, text: &str) -> usize {
text.len()
}
/// 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>;
/// Render only the conversation prefix to prompt ids, for cache pre-warming
/// (`GEN 0`): the same messages/tools/effort as the real turn but WITHOUT the
/// generation opener, so the ids are a byte-exact token prefix of the real
/// prompt and the engine's `RESUME` hits. Default: a dialect with no
/// generation suffix already yields the prefix from `build_prompt`; dialects
/// that append an opener (Inkling's `finish_prompt`) override this to skip it.
fn build_prefix_ids(&self, req: &ChatRequest) -> Result<Vec<u32>, ApiErrorEnvelope> {
Ok(self.build_prompt(req)?.ids)
}
/// 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)
}