//! 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, fmt: Arc, } impl ChatService { pub fn new(engine: Arc, fmt: Arc) -> 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 { 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 = 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 + 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::(); 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, id: &str, created: u64, model: &str, piece: &Piece, st: &mut EmitState, abort_engine: &Arc, ) { 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, id: &str, created: u64, model: &str, delta: Delta, finish: Option, ) { 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 }