Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/ea7ed621a5149e9f # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#781 (code only) open derived `ea7ed621a5149e9f` #781 Imported from GitHub aien-dev/aien-sovereign-core-mv#781 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `d38411c38f94b02d9e87beea440d01b42cfc5bd8` · Head `bb55d53f077735473057b6f49d036cecff183d20` ### Fetch it A git bundle of the pull request's head, 68972 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/ea7ed621a5149e9f.bundle -o ea7ed621a5149e9f.bundle git fetch ea7ed621a5149e9f.bundle refs/pull/781/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 781 bb55d53f077735473057b6f49d036cecff183d20 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":781,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/781","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:59Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/crates/aien-serve-http/src/codec.rs b/crates/aien-serve-http/src/codec.rs index e1611577..367e4cc1 100644 --- a/crates/aien-serve-http/src/codec.rs +++ b/crates/aien-serve-http/src/codec.rs @@ -79,21 +79,35 @@ pub trait Codec: Send + Sync { /// character must decode with a trailing U+FFFD, never fail. fn decode(&self, tokens: &[u32]) -> Result; fn stop_token_ids(&self) -> Vec; + /// The bytes one token stands for (`/v1/tokenize-text`). The default decodes the token + /// alone, which is exact unless the token is part of a multi-byte character. + fn token_bytes(&self, id: u32) -> Result, CodecError> { + Ok(self.decode(&[id])?.into_bytes()) + } } /// The model's own tokenizer and chat template. pub struct HfCodec { tokenizer: ChatTokenizer, template_name: &'static str, + /// The vocabulary is GPT-2 byte-level (a space is the piece `Ġ`): pieces map to bytes. + byte_level: bool, } impl HfCodec { pub fn from_model_dir(dir: &Path) -> Result { let tokenizer = ChatTokenizer::from_model_dir(dir, None)?; let template_name = tokenizer.template().name(); + let byte_level = match tokenizer.encode(" a").ok().as_deref() { + Some([first, ..]) => tokenizer + .id_to_token(*first) + .is_some_and(|p| p.starts_with('\u{120}')), + _ => false, + }; Ok(Self { tokenizer, template_name, + byte_level, }) } @@ -145,6 +159,43 @@ impl Codec for HfCodec { fn stop_token_ids(&self) -> Vec { self.tokenizer.stop_token_ids().to_vec() } + + /// A byte-level BPE piece (`Ġ` for a space, ...) maps back to its exact bytes, even half a + /// character; a piece outside the byte-level alphabet falls back to decoding the token. + fn token_bytes(&self, id: u32) -> Result, CodecError> { + if let Some(b) = self + .byte_level + .then(|| self.tokenizer.id_to_token(id)) + .flatten() + .and_then(|p| byte_level_bytes(&p)) + { + return Ok(b); + } + Ok(self.decode(&[id])?.into_bytes()) + } +} + +/// Inverts GPT-2's `bytes_to_unicode`: bytes `!`..=`~`, `¡`..=`¬` and `®`..=`ÿ` stand for +/// themselves; the other 68 bytes, in order, are U+0100 onward. +pub fn byte_level_bytes(piece: &str) -> Option> { + let direct = + |b: u32| (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b); + let shifted: Vec = (0u32..=255) + .filter(|&b| !direct(b)) + .map(|b| b as u8) + .collect(); + piece + .chars() + .map(|c| { + let c = c as u32; + if direct(c) { + Some(c as u8) + } else { + c.checked_sub(256) + .and_then(|i| shifted.get(i as usize).copied()) + } + }) + .collect() } /// Test codec: token id = byte value, stop id 256. The chat layout is @@ -185,6 +236,12 @@ impl Codec for ByteCodec { fn stop_token_ids(&self) -> Vec { vec![Self::STOP] } + + fn token_bytes(&self, id: u32) -> Result, CodecError> { + u8::try_from(id) + .map(|b| vec![b]) + .map_err(|_| CodecError::Failed(format!("token {id} has no bytes"))) + } } #[cfg(test)] @@ -211,4 +268,16 @@ mod tests { Err(CodecError::Unrenderable(_)) )); } + + #[test] + fn byte_level_pieces_map_back_to_bytes() { + assert_eq!(byte_level_bytes("\u{120}a"), Some(b" a".to_vec())); + assert_eq!(byte_level_bytes("\u{10A}"), Some(vec![b'\n'])); + assert_eq!(byte_level_bytes("<|im_end|>"), Some(b"<|im_end|>".to_vec())); + // `é` split across two pieces: the high byte alone is exact, no U+FFFD. + assert_eq!(byte_level_bytes("\u{C3}"), Some(vec![0xC3])); + assert_eq!(byte_level_bytes("\u{2581}x"), None); + assert_eq!(ByteCodec.token_bytes(0xC3).unwrap(), vec![0xC3]); + assert!(ByteCodec.token_bytes(ByteCodec::STOP).is_err()); + } } diff --git a/crates/aien-serve-http/src/compat.rs b/crates/aien-serve-http/src/compat.rs new file mode 100644 index 00000000..67ea4e88 --- /dev/null +++ b/crates/aien-serve-http/src/compat.rs @@ -0,0 +1,779 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 Drake Stapleton (AIEN / aien-dev) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The other request shapes xAI's API accepts, as conversions to and from the chat-completions +//! shapes the server already serves: `POST /v1/responses` (OpenAI / xAI Responses), the legacy +//! `POST /v1/completions` and `POST /v1/messages` (Anthropic Messages). A request becomes a chat +//! request, so it passes the same validation; the chat-completion body becomes the reply. Nothing +//! is stored: `previous_response_id` and `background` are refused, never ignored. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde_json::{json, Map, Value}; + +/// The part of a chat id after `chatcmpl-`, shared by the ids of every other surface. +pub fn id_suffix(chat_id: &str) -> &str { + chat_id.strip_prefix("chatcmpl-").unwrap_or(chat_id) +} + +fn copy(from: &Map, to: &mut Map, keys: &[&str]) { + for k in keys { + if let Some(v) = from.get(*k).filter(|v| !v.is_null()) { + to.insert((*k).to_string(), v.clone()); + } + } +} + +fn object(raw: &Value) -> Result<&Map, String> { + raw.as_object() + .ok_or_else(|| "the request must be a JSON object".to_string()) +} + +// --------------------------------------------------------------------------------------------- +// Responses + +/// A Responses request as a chat request, plus what the reply echoes back (`echo`). +pub fn responses_to_chat(raw: &Value) -> Result<(Value, Value), String> { + let o = object(raw)?; + if o.get("previous_response_id").is_some_and(|v| !v.is_null()) { + return Err("previous_response_id is not supported: this server stores no responses; send the whole conversation in input".into()); + } + if o.get("background").and_then(Value::as_bool) == Some(true) { + return Err( + "background responses are not supported: this server stores no responses".into(), + ); + } + if o.get("store").and_then(Value::as_bool) == Some(true) { + return Err("store: true is not supported: this server stores no responses".into()); + } + let mut messages = Vec::new(); + if let Some(i) = o.get("instructions").filter(|v| !v.is_null()) { + let s = i.as_str().ok_or("instructions must be a string")?; + messages.push(json!({"role": "system", "content": s})); + } + match o.get("input") { + Some(Value::String(s)) => messages.push(json!({"role": "user", "content": s})), + Some(Value::Array(items)) => { + for item in items { + input_item(item, &mut messages)?; + } + } + _ => return Err("input must be a string or an array of input items".into()), + } + let mut chat = Map::new(); + chat.insert("messages".into(), Value::Array(messages)); + copy( + o, + &mut chat, + &[ + "model", + "temperature", + "top_p", + "top_k", + "seed", + "stream", + "parallel_tool_calls", + "reasoning_effort", + "chat_template_kwargs", + "aien_test", + "aien_return_token_ids", + ], + ); + if let Some(m) = o.get("max_output_tokens").filter(|v| !v.is_null()) { + chat.insert("max_completion_tokens".into(), m.clone()); + } + if let Some(e) = o + .get("reasoning") + .and_then(|r| r.get("effort")) + .filter(|v| !v.is_null()) + { + chat.insert("reasoning_effort".into(), e.clone()); + } + let tools = match o.get("tools").filter(|v| !v.is_null()) { + None => Vec::new(), + Some(Value::Array(t)) => t.iter().map(response_tool).collect::>()?, + Some(_) => return Err("tools must be an array".into()), + }; + if !tools.is_empty() { + chat.insert("tools".into(), Value::Array(tools)); + } + if let Some(tc) = o.get("tool_choice").filter(|v| !v.is_null()) { + chat.insert("tool_choice".into(), response_tool_choice(tc)); + } + if let Some(f) = o + .get("text") + .and_then(|t| t.get("format")) + .filter(|v| !v.is_null()) + { + chat.insert("response_format".into(), f.clone()); + } + let echo = json!({ + "instructions": o.get("instructions").cloned().unwrap_or(Value::Null), + "max_output_tokens": o.get("max_output_tokens").cloned().unwrap_or(Value::Null), + "temperature": o.get("temperature").cloned().unwrap_or(Value::Null), + "top_p": o.get("top_p").cloned().unwrap_or(Value::Null), + "tools": o.get("tools").filter(|v| v.is_array()).cloned().unwrap_or(json!([])), + "tool_choice": o.get("tool_choice").filter(|v| !v.is_null()).cloned().unwrap_or(json!("auto")), + "parallel_tool_calls": o.get("parallel_tool_calls").and_then(Value::as_bool).unwrap_or(true), + "metadata": o.get("metadata").filter(|v| v.is_object()).cloned().unwrap_or(json!({})), + }); + Ok((Value::Object(chat), echo)) +} + +fn input_item(item: &Value, messages: &mut Vec) -> Result<(), String> { + let kind = item + .get("type") + .and_then(Value::as_str) + .unwrap_or("message"); + match kind { + "message" => { + let role = item + .get("role") + .and_then(Value::as_str) + .ok_or("a message input item needs a role")?; + let content = match item.get("content") { + Some(Value::String(s)) => Value::String(s.clone()), + Some(Value::Array(parts)) => Value::Array( + parts + .iter() + .map(|p| match p.get("type").and_then(Value::as_str) { + Some("input_text" | "output_text" | "text") => { + json!({"type": "text", "text": p.get("text").cloned().unwrap_or(Value::Null)}) + } + // The chat path names the part it refuses. + other => json!({"type": other.unwrap_or("missing")}), + }) + .collect(), + ), + _ => return Err("a message input item needs string or array content".into()), + }; + messages.push(json!({"role": role, "content": content})); + } + "function_call" => { + let call = json!({ + "id": item.get("call_id").cloned().unwrap_or(Value::Null), + "type": "function", + "function": { + "name": item.get("name").cloned().unwrap_or(Value::Null), + "arguments": item.get("arguments").cloned().unwrap_or(json!("{}")), + }, + }); + match messages.last_mut() { + Some(m) if m["role"] == "assistant" => { + if !m["tool_calls"].is_array() { + m["tool_calls"] = json!([]); + } + m["tool_calls"] + .as_array_mut() + .expect("array") + .push(call); + } + _ => messages.push(json!({"role": "assistant", "content": null, "tool_calls": [call]})), + } + } + "function_call_output" => { + let output = match item.get("output") { + Some(Value::String(s)) => s.clone(), + Some(Value::Array(parts)) => parts + .iter() + .filter_map(|p| p.get("text").and_then(Value::as_str)) + .collect(), + _ => return Err("a function_call_output item needs output".into()), + }; + messages.push(json!({ + "role": "tool", + "tool_call_id": item.get("call_id").cloned().unwrap_or(Value::Null), + "content": output, + })); + } + // The model's own earlier reasoning: not re-rendered (the chat template drops it too). + "reasoning" => {} + other => { + return Err(format!( + "input item type '{other}' is not supported: only message, function_call, function_call_output and reasoning items" + )) + } + } + Ok(()) +} + +fn response_tool(t: &Value) -> Result { + match t.get("type").and_then(Value::as_str) { + Some("function") if t.get("function").is_some() => Ok(t.clone()), + Some("function") => { + let mut f = Map::new(); + copy( + t.as_object().expect("tool object"), + &mut f, + &["name", "description", "parameters"], + ); + Ok(json!({"type": "function", "function": f})) + } + other => Err(format!( + "tool type '{}' is not supported: only function tools; server-side tools (web_search, x_search, code_execution, ...) run at xAI, not on this server", + other.unwrap_or("missing") + )), + } +} + +fn response_tool_choice(tc: &Value) -> Value { + match (tc.get("type").and_then(Value::as_str), tc.get("name")) { + (Some("function"), Some(name)) => json!({"type": "function", "function": {"name": name}}), + _ => tc.clone(), + } +} + +pub fn reasoning_item(chat_id: &str, text: &str) -> Value { + json!({ + "type": "reasoning", + "id": format!("rs_{}", id_suffix(chat_id)), + "summary": [], + "content": [{"type": "reasoning_text", "text": text}], + "status": "completed", + }) +} + +pub fn message_item(chat_id: &str, text: &str, status: &str) -> Value { + let content = if status == "in_progress" { + json!([]) + } else { + json!([output_text(text)]) + }; + json!({ + "type": "message", + "id": format!("msg_{}", id_suffix(chat_id)), + "role": "assistant", + "status": status, + "content": content, + }) +} + +pub fn output_text(text: &str) -> Value { + json!({"type": "output_text", "text": text, "annotations": [], "logprobs": []}) +} + +/// A chat `tool_calls` entry as a Responses `function_call` item. +pub fn function_call_item(call: &Value, status: &str) -> Value { + let call_id = call["id"].as_str().unwrap_or("call"); + json!({ + "type": "function_call", + "id": format!("fc_{call_id}"), + "call_id": call_id, + "name": call["function"]["name"], + "arguments": if status == "in_progress" { json!("") } else { call["function"]["arguments"].clone() }, + "status": status, + }) +} + +/// Chat usage as Responses usage (the `aien_*` extras ride along). +pub fn response_usage(u: &Value) -> Value { + let mut v = json!({ + "input_tokens": u["prompt_tokens"], + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens": u["completion_tokens"], + "output_tokens_details": {"reasoning_tokens": u["completion_tokens_details"]["reasoning_tokens"]}, + "total_tokens": u["total_tokens"], + "num_sources_used": 0, + "num_server_side_tools_used": 0, + }); + if let (Some(from), Some(to)) = (u.as_object(), v.as_object_mut()) { + for (k, x) in from.iter().filter(|(k, _)| k.starts_with("aien_")) { + to.insert(k.clone(), x.clone()); + } + } + v +} + +/// The `response` object: `status` `in_progress` (no output, no usage yet), `completed` or +/// `incomplete` (the reply hit `max_output_tokens`). +pub fn response_object( + echo: &Value, + chat_id: &str, + created: u64, + model: &str, + status: &str, + output: Vec, + usage: Option, +) -> Value { + let mut r = json!({ + "id": format!("resp_{}", id_suffix(chat_id)), + "object": "response", + "created_at": created, + "model": model, + "status": status, + "output": output, + "usage": usage, + "error": null, + "incomplete_details": if status == "incomplete" { json!({"reason": "max_output_tokens"}) } else { Value::Null }, + "previous_response_id": null, + "store": false, + "background": false, + "truncation": "disabled", + "text": {"format": {"type": "text"}}, + "reasoning": null, + }); + if status == "completed" || status == "incomplete" { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(created, |d| d.as_secs()); + r["completed_at"] = json!(now); + } + if let (Some(from), Some(to)) = (echo.as_object(), r.as_object_mut()) { + for (k, v) in from { + to.insert(k.clone(), v.clone()); + } + } + r +} + +/// The output items of one chat choice, in order: reasoning, message, function calls. +pub fn output_items(chat_id: &str, message: &Value) -> Vec { + let mut out = Vec::new(); + if let Some(r) = message["reasoning_content"] + .as_str() + .filter(|r| !r.is_empty()) + { + out.push(reasoning_item(chat_id, r)); + } + let calls = message["tool_calls"] + .as_array() + .map_or(&[][..], Vec::as_slice); + let text = message["content"].as_str().unwrap_or(""); + if !text.is_empty() || calls.is_empty() { + out.push(message_item(chat_id, text, "completed")); + } + out.extend(calls.iter().map(|c| function_call_item(c, "completed"))); + out +} + +pub fn status_of(finish: &str) -> &'static str { + if finish == "length" { + "incomplete" + } else { + "completed" + } +} + +/// A chat completion as a `response` object. +pub fn chat_to_response(chat: &Value, echo: &Value) -> Value { + let id = chat["id"].as_str().unwrap_or(""); + let choice = &chat["choices"][0]; + let mut r = response_object( + echo, + id, + chat["created"].as_u64().unwrap_or(0), + chat["model"].as_str().unwrap_or(""), + status_of(choice["finish_reason"].as_str().unwrap_or("stop")), + output_items(id, &choice["message"]), + Some(response_usage(&chat["usage"])), + ); + if let Some(info) = chat.get("aien_readers") { + r["aien_readers"] = info.clone(); + } + r +} + +// --------------------------------------------------------------------------------------------- +// Legacy completions + +/// A legacy completions request as chat fields plus its raw prompt (no chat template). +pub fn completions_to_chat(raw: &Value) -> Result<(Value, String), String> { + let o = object(raw)?; + let prompt = match o.get("prompt") { + Some(Value::String(s)) => s.clone(), + Some(Value::Array(a)) if a.len() == 1 && a[0].is_string() => { + a[0].as_str().expect("string").to_string() + } + Some(Value::Array(_)) => return Err( + "prompt must be a string or an array of one string (batched prompts are not supported)" + .into(), + ), + _ => return Err("prompt must be a string".into()), + }; + if o.get("stream").and_then(Value::as_bool) == Some(true) { + return Err( + "stream is not supported on /v1/completions; use /v1/chat/completions or /v1/responses" + .into(), + ); + } + if o.get("echo").and_then(Value::as_bool) == Some(true) { + return Err("echo is not supported".into()); + } + if o.get("suffix").is_some_and(|v| !v.is_null()) { + return Err("suffix is not supported".into()); + } + if o.get("logprobs") + .is_some_and(|v| !v.is_null() && v != &json!(false) && v != &json!(0)) + { + return Err("logprobs is not supported".into()); + } + if o.get("best_of") + .and_then(Value::as_i64) + .is_some_and(|b| b > 1) + { + return Err("best_of > 1 is not supported".into()); + } + let mut chat = Map::new(); + copy( + o, + &mut chat, + &[ + "model", + "max_tokens", + "temperature", + "top_p", + "top_k", + "seed", + "stop", + "n", + "aien_test", + "aien_return_token_ids", + ], + ); + Ok((Value::Object(chat), prompt)) +} + +pub fn chat_to_text_completion(chat: &Value) -> Value { + let choices: Vec = chat["choices"] + .as_array() + .map_or(&[][..], Vec::as_slice) + .iter() + .map(|c| { + json!({ + "index": c["index"], + "text": c["message"]["content"].as_str().unwrap_or(""), + "finish_reason": c["finish_reason"], + "logprobs": null, + }) + }) + .collect(); + json!({ + "id": format!("cmpl-{}", id_suffix(chat["id"].as_str().unwrap_or(""))), + "object": "text_completion", + "created": chat["created"], + "model": chat["model"], + "choices": choices, + "usage": chat["usage"], + }) +} + +// --------------------------------------------------------------------------------------------- +// Anthropic Messages + +fn block_text(v: &Value) -> Result { + match v { + Value::String(s) => Ok(s.clone()), + Value::Array(blocks) => blocks + .iter() + .map(|b| match b.get("type").and_then(Value::as_str) { + Some("text") => Ok(b["text"].as_str().unwrap_or("").to_string()), + other => Err(format!( + "content block type '{}' is not supported here: only text", + other.unwrap_or("missing") + )), + }) + .collect(), + Value::Null => Ok(String::new()), + _ => Err("content must be a string or an array of blocks".into()), + } +} + +/// A Messages request as a chat request. +pub fn messages_to_chat(raw: &Value) -> Result { + let o = object(raw)?; + if o.get("stream").and_then(Value::as_bool) == Some(true) { + return Err( + "stream is not supported on /v1/messages; use /v1/chat/completions or /v1/responses" + .into(), + ); + } + let max_tokens = o + .get("max_tokens") + .filter(|v| v.is_i64() || v.is_u64()) + .ok_or("max_tokens is required")?; + let mut messages = Vec::new(); + if let Some(s) = o.get("system").filter(|v| !v.is_null()) { + messages.push(json!({"role": "system", "content": block_text(s)?})); + } + let turns = o + .get("messages") + .and_then(Value::as_array) + .ok_or("messages must be an array")?; + for m in turns { + let role = m + .get("role") + .and_then(Value::as_str) + .ok_or("every message needs a role")?; + if role != "user" && role != "assistant" { + return Err(format!("message role '{role}' is not user or assistant")); + } + let blocks = match m.get("content") { + Some(Value::String(s)) => { + messages.push(json!({"role": role, "content": s})); + continue; + } + Some(Value::Array(b)) => b, + _ => return Err("message content must be a string or an array of blocks".into()), + }; + let mut text = String::new(); + let mut calls = Vec::new(); + for b in blocks { + match b.get("type").and_then(Value::as_str) { + Some("text") => text.push_str(b["text"].as_str().unwrap_or("")), + Some("tool_use") if role == "assistant" => calls.push(json!({ + "id": b["id"], + "type": "function", + "function": {"name": b["name"], "arguments": b.get("input").cloned().unwrap_or(json!({})).to_string()}, + })), + Some("tool_result") if role == "user" => messages.push(json!({ + "role": "tool", + "tool_call_id": b["tool_use_id"], + "content": block_text(b.get("content").unwrap_or(&Value::Null))?, + })), + Some("thinking" | "redacted_thinking") => {} + other => { + return Err(format!( + "content block type '{}' is not supported in a {role} message: only text, tool_use (assistant) and tool_result (user)", + other.unwrap_or("missing") + )) + } + } + } + if !calls.is_empty() { + messages.push(json!({"role": role, "content": text, "tool_calls": calls})); + } else if !text.is_empty() { + messages.push(json!({"role": role, "content": text})); + } + } + let mut chat = Map::new(); + chat.insert("messages".into(), Value::Array(messages)); + chat.insert("max_tokens".into(), max_tokens.clone()); + copy( + o, + &mut chat, + &["model", "temperature", "top_p", "top_k", "aien_test"], + ); + if let Some(s) = o.get("stop_sequences").filter(|v| !v.is_null()) { + chat.insert("stop".into(), s.clone()); + } + if let Some(Value::Array(tools)) = o.get("tools") { + let tools = tools + .iter() + .map(|t| match t.get("type").and_then(Value::as_str) { + None | Some("custom") => Ok(json!({"type": "function", "function": { + "name": t["name"], + "description": t.get("description").cloned().unwrap_or(Value::Null), + "parameters": t.get("input_schema").cloned().unwrap_or(json!({})), + }})), + Some(other) => Err(format!( + "tool type '{other}' is not supported: only custom tools with an input_schema" + )), + }) + .collect::, _>>()?; + if !tools.is_empty() { + chat.insert("tools".into(), Value::Array(tools)); + } + } + if let Some(tc) = o.get("tool_choice").filter(|v| !v.is_null()) { + let mapped = match tc.get("type").and_then(Value::as_str) { + Some("auto") => json!("auto"), + Some("none") => json!("none"), + Some("any") => json!("required"), + Some("tool") => json!({"type": "function", "function": {"name": tc["name"]}}), + _ => return Err("tool_choice.type must be auto, none, any or tool".into()), + }; + chat.insert("tool_choice".into(), mapped); + if tc.get("disable_parallel_tool_use").and_then(Value::as_bool) == Some(true) { + chat.insert("parallel_tool_calls".into(), json!(false)); + } + } + Ok(Value::Object(chat)) +} + +/// A chat completion as a Messages reply. +pub fn chat_to_message(chat: &Value) -> Value { + let choice = &chat["choices"][0]; + let msg = &choice["message"]; + let mut content = Vec::new(); + if let Some(r) = msg["reasoning_content"].as_str().filter(|r| !r.is_empty()) { + content.push(json!({"type": "thinking", "thinking": r, "signature": ""})); + } + if let Some(t) = msg["content"].as_str().filter(|t| !t.is_empty()) { + content.push(json!({"type": "text", "text": t})); + } + for c in msg["tool_calls"].as_array().map_or(&[][..], Vec::as_slice) { + let input: Value = c["function"]["arguments"] + .as_str() + .and_then(|a| serde_json::from_str(a).ok()) + .unwrap_or(json!({})); + content.push(json!({"type": "tool_use", "id": c["id"], "name": c["function"]["name"], "input": input})); + } + if content.is_empty() { + content.push(json!({"type": "text", "text": ""})); + } + let stop_reason = match choice["finish_reason"].as_str() { + Some("length") => "max_tokens", + Some("tool_calls") => "tool_use", + _ => "end_turn", + }; + json!({ + "id": format!("msg_{}", id_suffix(chat["id"].as_str().unwrap_or(""))), + "type": "message", + "role": "assistant", + "model": chat["model"], + "content": content, + "stop_reason": stop_reason, + "stop_sequence": null, + "usage": { + "input_tokens": chat["usage"]["prompt_tokens"], + "output_tokens": chat["usage"]["completion_tokens"], + }, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn responses_input_items_become_chat_turns() { + let raw = json!({ + "model": "m", + "instructions": "be brief", + "input": [ + {"role": "user", "content": [{"type": "input_text", "text": "weather?"}]}, + {"type": "reasoning", "id": "rs_1", "summary": []}, + {"type": "function_call", "call_id": "c1", "name": "get", "arguments": "{\"city\":\"x\"}"}, + {"type": "function_call_output", "call_id": "c1", "output": "sunny"}, + ], + "tools": [{"type": "function", "name": "get", "parameters": {"type": "object"}}], + "tool_choice": {"type": "function", "name": "get"}, + "max_output_tokens": 9, + "reasoning": {"effort": "low"}, + "text": {"format": {"type": "text"}}, + }); + let (chat, echo) = responses_to_chat(&raw).unwrap(); + let m = chat["messages"].as_array().unwrap(); + assert_eq!(m.len(), 4); + assert_eq!(m[0], json!({"role": "system", "content": "be brief"})); + assert_eq!( + m[1]["content"][0], + json!({"type": "text", "text": "weather?"}) + ); + assert_eq!(m[2]["tool_calls"][0]["function"]["name"], "get"); + assert_eq!( + m[3], + json!({"role": "tool", "tool_call_id": "c1", "content": "sunny"}) + ); + assert_eq!(chat["tools"][0]["function"]["name"], "get"); + assert_eq!( + chat["tool_choice"], + json!({"type": "function", "function": {"name": "get"}}) + ); + assert_eq!(chat["max_completion_tokens"], 9); + assert_eq!(chat["reasoning_effort"], "low"); + assert_eq!(chat["response_format"], json!({"type": "text"})); + assert_eq!(echo["max_output_tokens"], 9); + } + + #[test] + fn responses_refuses_what_it_cannot_do() { + for raw in [ + json!({"input": "x", "previous_response_id": "resp_1"}), + json!({"input": "x", "background": true}), + json!({"input": "x", "store": true}), + json!({"input": "x", "tools": [{"type": "web_search"}]}), + json!({"input": [{"type": "computer_call"}]}), + json!({"input": 3}), + ] { + assert!(responses_to_chat(&raw).is_err(), "{raw}"); + } + } + + #[test] + fn chat_reply_becomes_a_response() { + let chat = json!({ + "id": "chatcmpl-ab", "created": 5, "model": "m", + "choices": [{"index": 0, "finish_reason": "length", "message": { + "role": "assistant", "content": "hi", "reasoning_content": "think", + "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f", "arguments": "{}"}}], + }}], + "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7, + "completion_tokens_details": {"reasoning_tokens": 2}}, + }); + let r = chat_to_response(&chat, &json!({"tool_choice": "auto"})); + assert_eq!(r["id"], "resp_ab"); + assert_eq!(r["object"], "response"); + assert_eq!(r["status"], "incomplete"); + assert_eq!(r["incomplete_details"]["reason"], "max_output_tokens"); + let out = r["output"].as_array().unwrap(); + assert_eq!(out[0]["type"], "reasoning"); + assert_eq!(out[1]["content"][0]["text"], "hi"); + assert_eq!(out[2]["call_id"], "call_1"); + assert_eq!(r["usage"]["output_tokens_details"]["reasoning_tokens"], 2); + assert_eq!(r["usage"]["total_tokens"], 7); + + let m = chat_to_message(&chat); + assert_eq!(m["id"], "msg_ab"); + assert_eq!(m["stop_reason"], "max_tokens"); + assert_eq!(m["content"][1], json!({"type": "text", "text": "hi"})); + assert_eq!(m["content"][2]["type"], "tool_use"); + + let c = chat_to_text_completion(&chat); + assert_eq!(c["id"], "cmpl-ab"); + assert_eq!(c["choices"][0]["text"], "hi"); + } + + #[test] + fn messages_and_completions_requests_convert_or_refuse() { + let raw = json!({ + "model": "m", "max_tokens": 5, "system": [{"type": "text", "text": "s"}], + "messages": [ + {"role": "user", "content": "q"}, + {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "f", "input": {"a": 1}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "r"}]}, + ], + "tools": [{"name": "f", "input_schema": {"type": "object"}}], + "tool_choice": {"type": "auto"}, + "stop_sequences": ["END"], + }); + let chat = messages_to_chat(&raw).unwrap(); + let m = chat["messages"].as_array().unwrap(); + assert_eq!(m[0]["content"], "s"); + assert_eq!(m[2]["tool_calls"][0]["function"]["arguments"], "{\"a\":1}"); + assert_eq!(m[3]["role"], "tool"); + assert_eq!(chat["stop"], json!(["END"])); + assert_eq!(chat["tool_choice"], "auto"); + assert!( + messages_to_chat(&json!({"messages": [], "max_tokens": 1, "stream": true})).is_err() + ); + assert!(messages_to_chat(&json!({"messages": []})).is_err()); + + let (chat, prompt) = + completions_to_chat(&json!({"prompt": ["once"], "max_tokens": 3})).unwrap(); + assert_eq!(prompt, "once"); + assert_eq!(chat["max_tokens"], 3); + for raw in [ + json!({"prompt": "x", "stream": true}), + json!({"prompt": "x", "echo": true}), + json!({"prompt": "x", "suffix": "y"}), + json!({"prompt": "x", "best_of": 2}), + json!({"prompt": "x", "logprobs": 2}), + json!({"prompt": ["a", "b"]}), + ] { + assert!(completions_to_chat(&raw).is_err(), "{raw}"); + } + } +} diff --git a/crates/aien-serve-http/src/lib.rs b/crates/aien-serve-http/src/lib.rs index 8230304d..46961465 100644 --- a/crates/aien-serve-http/src/lib.rs +++ b/crates/aien-serve-http/src/lib.rs @@ -21,6 +21,7 @@ pub mod chip_reservation; pub mod codec; +pub mod compat; pub mod cpu_engine; pub mod engine; pub mod kv_persist; diff --git a/crates/aien-serve-http/src/main.rs b/crates/aien-serve-http/src/main.rs index 09665337..d5ce5c37 100644 --- a/crates/aien-serve-http/src/main.rs +++ b/crates/aien-serve-http/src/main.rs @@ -21,6 +21,7 @@ //! [--model-dir DIR] [--port 18091] //! [--bind 127.0.0.1] [--model-id ID] [--max-context N] //! [--max-tokens-cap N] [--stub-reply TEXT] [--thinking on|off|template] +//! [--cors-origin https://host[:port]]... [--model-alias NAME]... //! aien-serve-http --version //! //! `--model-dir` defaults to `$HOME/models/qwen3.8-27b-fp8-017b9c7a`. `--version` prints the @@ -44,6 +45,10 @@ //! own default (Qwen3.8-27B and Qwen3.6-35B-A3B: on). Templates without a thinking switch ignore it. //! `stub` replays `--stub-reply` for every request, using the model directory's //! tokenizer when it exists (so Odysseus can be wired before the weights load). +//! `--cors-origin` (repeatable) lets one browser origin call the API: CORS headers for it and +//! its Origin accepted; the bearer token is still required. None by default. `--model-alias` +//! (repeatable) is another name a request may give the model (e.g. `grok-4.7` for a client +//! written for xAI); replies carry `--model-id`. use std::net::IpAddr; use std::path::PathBuf; @@ -124,7 +129,7 @@ fn usage() -> String { "usage: aien-serve-http [--engine cpu|stub|omega] [--weights bf16|fp8-experts|fp8] [--spin-us N] \ [--model-dir DIR] [--port N] [--bind ADDR] [--model-id ID] [--max-context N] \ [--max-tokens-cap N] [--stub-reply TEXT] [--whole-prompt on|off] [--prefill-device-host on|off] \ - [--thinking on|off|template] [--batch-slots N] [--version]" + [--thinking on|off|template] [--batch-slots N] [--cors-origin URL]... [--model-alias NAME]... [--version]" .to_string() } @@ -203,6 +208,26 @@ fn parse_args() -> Result { "--prefill-device-host" => { a.wp_device_host = Some(parse_switch("--prefill-device-host", &val()?)?) } + "--cors-origin" => { + let o = val()?; + let host = o + .strip_prefix("https://") + .or_else(|| o.strip_prefix("http://")) + .unwrap_or(""); + if host.is_empty() || host.contains(['/', '*', ' ', ',']) { + return Err(format!( + "--cors-origin must be one exact origin like https://example.com[:port], got {o}" + )); + } + a.cfg.cors_origins.push(o); + } + "--model-alias" => { + let m = val()?; + if m.is_empty() { + return Err("--model-alias needs a nonempty name".into()); + } + a.cfg.model_aliases.push(m); + } "-h" | "--help" => return Err(usage()), other => return Err(format!("unknown flag {other}\n{}", usage())), } diff --git a/crates/aien-serve-http/src/openai.rs b/crates/aien-serve-http/src/openai.rs index dd5da903..01390997 100644 --- a/crates/aien-serve-http/src/openai.rs +++ b/crates/aien-serve-http/src/openai.rs @@ -52,6 +52,18 @@ pub struct ChatRequest { pub functions: Option>, #[serde(default)] pub stream_options: Option, + /// `"auto"` (default), `"none"` (the tools are not shown to the model), or a forced call + /// (`"required"`, `{"type":"function","function":{"name":..}}`), which is refused with 400: + /// this server has no constrained decoding to force a call. + #[serde(default)] + pub tool_choice: Option, + /// `false`: only the first tool call of a reply is returned. + #[serde(default)] + pub parallel_tool_calls: Option, + /// `{"type":"text"}` only; `json_object` / `json_schema` are refused with 400 (no + /// constrained decoding). + #[serde(default)] + pub response_format: Option, /// Template switches (`{"enable_thinking": bool, "reasoning_effort": "low|medium|xhigh", /// "preserve_thinking": bool}`), read only by templates that define them (Qwen3.8-27B: /// thinking and effort; Qwen3.6-35B-A3B: thinking and preserve). @@ -123,6 +135,8 @@ pub struct Usage { pub prompt_tokens: usize, pub completion_tokens: usize, pub total_tokens: usize, + /// `reasoning_tokens`: the tokens of the thinking block (part of `completion_tokens`). + pub completion_tokens_details: CompletionTokensDetails, /// How the reply was sampled (OWN-8B stage S): an extra field, ignored by OpenAI clients. /// Its `seed` replays the request. Absent for an engine that does not sample. #[serde(skip_serializing_if = "Option::is_none")] @@ -135,6 +149,11 @@ pub struct Usage { pub aien_test: Option, } +#[derive(Debug, Serialize, Clone, Copy, Default)] +pub struct CompletionTokensDetails { + pub reasoning_tokens: usize, +} + #[derive(Debug, Serialize)] pub struct ModelList { pub object: &'static str, diff --git a/crates/aien-serve-http/src/server.rs b/crates/aien-serve-http/src/server.rs index 826b9ad0..03b031aa 100644 --- a/crates/aien-serve-http/src/server.rs +++ b/crates/aien-serve-http/src/server.rs @@ -14,9 +14,13 @@ // limitations under the License. //! The HTTP surface: `GET /v1/models`, `POST /v1/chat/completions` (JSON or SSE), -//! `GET /health`. Every error is OpenAI error JSON. As many generations at a time as the +//! `GET /health`, and the shapes xAI's API also takes (see [`crate::compat`]): +//! `POST /v1/responses` (JSON or SSE), `POST /v1/completions`, `POST /v1/messages`, +//! `GET /v1/language-models` and `POST /v1/tokenize-text`. Every error is OpenAI error JSON +//! (Anthropic error JSON on `/v1/messages`). As many generations at a time as the //! engine says it takes ([`Engine::concurrency`], 1 unless the engine batches): the next -//! request while all those run gets 503 `server_busy` with `Retry-After: 1`. +//! request while all those run gets 503 `server_busy` with `Retry-After: 1`. CORS headers go +//! only to the origins `--cors-origin` lists (none by default). use std::convert::Infallible; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; @@ -26,12 +30,13 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use axum::body::{to_bytes, Body, Bytes}; use axum::extract::{Path, State}; -use axum::http::{header, HeaderMap, HeaderValue, Request, StatusCode}; +use axum::http::{header, HeaderMap, HeaderValue, Method, Request, StatusCode}; +use axum::middleware::{self, Next}; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Json, Router}; -use serde_json::Value; +use serde_json::{json, Value}; use tokio::sync::{mpsc, OwnedSemaphorePermit, Semaphore}; use tokio::task::JoinHandle; use tokio_stream::wrappers::ReceiverStream; @@ -39,10 +44,11 @@ use tokio_stream::wrappers::ReceiverStream; use aien_inference_abi::tokenizer::ChatOptions; use crate::codec::{Codec, CodecError}; +use crate::compat; use crate::engine::{Engine, EngineError, FinishReason, GenerateParams, TestSwitches}; use crate::openai::{ - chunk_json, chunk_json_with, completion_json, ChatRequest, ErrorBody, ModelCard, ModelList, - Usage, + chunk_json, chunk_json_with, completion_json, ChatRequest, CompletionTokensDetails, ErrorBody, + ModelCard, ModelList, Usage, }; use crate::sampling::SamplingRecord; use crate::text::{Push, TextAssembler}; @@ -90,6 +96,12 @@ pub struct ServerConfig { pub header_read_timeout: Duration, /// See [`MAX_CONNECTIONS`]. pub max_connections: usize, + /// Browser origins (`https://host[:port]`) given CORS headers and let past the Origin check. + /// Empty: no CORS header is ever sent and a preflight is 403. + pub cors_origins: Vec, + /// Other names a request may give the model (e.g. `grok-4.7` for a client that names one); + /// replies carry the served id. + pub model_aliases: Vec, /// Tool-calling layout of the model's chat template ([`crate::tools::ToolFormat::from_model_dir`]). pub tool_format: crate::tools::ToolFormat, } @@ -114,6 +126,8 @@ impl Default for ServerConfig { bearer_token: String::new(), header_read_timeout: HEADER_READ_TIMEOUT, max_connections: MAX_CONNECTIONS, + cors_origins: Vec::new(), + model_aliases: Vec::new(), tool_format: crate::tools::ToolFormat::default(), } } @@ -256,6 +270,32 @@ impl IntoResponse for ApiError { } } +impl ApiError { + /// The same error in Anthropic's shape (`/v1/messages`). + fn into_anthropic(self) -> Response { + let kind = match self.status.as_u16() { + 400 | 415 => "invalid_request_error", + 401 => "authentication_error", + 403 => "permission_error", + 404 => "not_found_error", + 413 => "request_too_large", + 503 => "overloaded_error", + _ => "api_error", + }; + let body = + json!({"type": "error", "error": {"type": kind, "message": self.body.error.message}}); + let mut resp = (self.status, Json(body)).into_response(); + if let Some(s) = self.retry_after { + resp.headers_mut().insert( + header::RETRY_AFTER, + HeaderValue::from_str(&s.to_string()).expect("digits"), + ); + } + resp + } +} + +#[derive(Clone)] struct Prepared { prompt_tokens: Vec, params: GenerateParams, @@ -266,10 +306,45 @@ struct Prepared { return_ids: bool, /// The request carried tools: parse `` blocks out of the reply. tools: bool, + /// `parallel_tool_calls` (default true); `false` keeps the first call only. + parallel_tools: bool, + /// `stream_options.include_usage`: a usage-only chunk (`choices: []`) before `[DONE]`. + include_usage: bool, + /// Choices (`n`), generated one after another. + n: usize, /// The merge train's switches for this request (empty: none; `aien_test` absent). test: TestSwitches, } +/// The end of one generation. +struct Done { + finish: &'static str, + completion_tokens: usize, + /// Of `completion_tokens`, the thinking block's (its closing token included). + reasoning_tokens: usize, + sampling: Option, + token_ids: Option>, + /// The `aien_test` switches applied (`usage.aien_test.applied`), when the request set any. + test: Option>, +} + +impl Done { + fn usage(self, prompt_tokens: usize) -> (&'static str, Usage) { + let usage = Usage { + prompt_tokens, + completion_tokens: self.completion_tokens, + total_tokens: prompt_tokens + self.completion_tokens, + completion_tokens_details: CompletionTokensDetails { + reasoning_tokens: self.reasoning_tokens, + }, + aien_sampling: self.sampling, + aien_token_ids: self.token_ids, + aien_test: self.test.map(|n| json!({ "applied": n })), + }; + (self.finish, usage) + } +} + /// What the generation thread sends to the HTTP side. `Done` is sent once per request, so its size /// (past clippy's line since `aien_test` joined it) costs nothing. #[allow(clippy::large_enum_variant)] @@ -277,14 +352,7 @@ enum Ev { Delta(String), /// Text of the thinking block (`reasoning_content`). Reasoning(String), - Done { - finish: &'static str, - completion_tokens: usize, - sampling: Option, - token_ids: Option>, - /// The `aien_test` switches applied (`usage.aien_test.applied`), when the request set any. - test: Option>, - }, + Done(Done), Error(String), /// Memory admission refused a prompt inside the engine: 413 `prompt_exceeds_memory_budget` /// while nothing has been sent, an error event with that code once a stream is open. @@ -311,12 +379,74 @@ pub fn router(state: Arc) -> Router { Router::new() .route("/v1/models", get(list_models)) .route("/v1/models/:id", get(get_model)) + .route("/v1/language-models", get(list_language_models)) + .route("/v1/language-models/:id", get(get_language_model)) .route("/v1/chat/completions", post(chat_completions)) + .route("/v1/responses", post(responses)) + .route("/v1/completions", post(completions)) + .route("/v1/messages", post(messages)) + .route("/v1/tokenize-text", post(tokenize_text)) .route("/health", get(health)) .fallback(not_found) + .layer(middleware::from_fn_with_state(Arc::clone(&state), cors)) .with_state(state) } +fn cors_allowed(state: &AppState, origin: &str) -> bool { + state + .cfg + .cors_origins + .iter() + .any(|o| o.eq_ignore_ascii_case(origin)) +} + +/// CORS for the `--cors-origin` list only. A preflight from a listed origin is 204 with the +/// allowed methods and headers; from any other origin 403. Other responses gain +/// `Access-Control-Allow-Origin` for a listed origin. Every request still passes +/// [`check_headers`] (bearer, Host, Content-Type); CORS only lets a browser read the answer. +async fn cors(State(state): State>, request: Request, next: Next) -> Response { + let origin = request.headers().get(header::ORIGIN).cloned(); + let allowed = origin + .as_ref() + .and_then(|o| o.to_str().ok()) + .is_some_and(|o| cors_allowed(&state, o)); + if request.method() == Method::OPTIONS && origin.is_some() { + if !allowed { + return ApiError::forbidden("CORS: origin not allowed").into_response(); + } + let mut resp = StatusCode::NO_CONTENT.into_response(); + let h = resp.headers_mut(); + h.insert( + header::ACCESS_CONTROL_ALLOW_ORIGIN, + origin.expect("allowed origin"), + ); + h.insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, POST, OPTIONS"), + ); + h.insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("authorization, content-type"), + ); + h.insert( + header::ACCESS_CONTROL_MAX_AGE, + HeaderValue::from_static("600"), + ); + h.insert(header::VARY, HeaderValue::from_static("Origin")); + return resp; + } + let mut resp = next.run(request).await; + if !state.cfg.cors_origins.is_empty() { + resp.headers_mut() + .append(header::VARY, HeaderValue::from_static("Origin")); + } + if let (true, Some(o)) = (allowed, origin) { + resp.headers_mut() + .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, o); + } + resp +} + /// Binds `cfg.bind:cfg.port` (loopback only) and serves in a background task. /// Returns the bound address (useful with port 0) and the task handle. pub async fn serve( @@ -474,13 +604,68 @@ async fn get_model( if let Some(r) = state.cfg.readers.as_ref().filter(|r| r.model_id == id) { return Ok(Json(model_card_for(&state, &r.model_id))); } - if id != state.cfg.model_id { - return Err(ApiError::not_found(format!( - "model '{id}' not found; this server serves '{}'", - state.cfg.model_id - ))); + check_model(&state, &id)?; + Ok(Json(model_card_for(&state, &id))) +} + +/// The served id or one of its `--model-alias` names. +fn serves(state: &AppState, model: &str) -> bool { + model == state.cfg.model_id || state.cfg.model_aliases.iter().any(|a| a == model) +} + +fn check_model(state: &AppState, model: &str) -> Result<(), ApiError> { + if serves(state, model) { + return Ok(()); + } + Err(ApiError::not_found(format!( + "model '{model}' not found; this server serves '{}'", + state.cfg.model_id + ))) +} + +/// xAI's `/v1/language-models` card: prices are 0 (the model runs here), text in and out. +fn language_model(state: &AppState, id: &str) -> Value { + let card = model_card_for(state, id); + let aliases = if id == state.cfg.model_id { + state.cfg.model_aliases.clone() + } else { + Vec::new() + }; + json!({ + "id": id, + "fingerprint": format!("fp_aien_{}", state.engine.kind()), + "created": card.created, + "object": "model", + "owned_by": card.owned_by, + "version": env!("CARGO_PKG_VERSION"), + "input_modalities": ["text"], + "output_modalities": ["text"], + "prompt_text_token_price": 0, + "cached_prompt_text_token_price": 0, + "prompt_image_token_price": 0, + "completion_text_token_price": 0, + "search_price": 0, + "long_context_threshold": 0, + "aliases": aliases, + }) +} + +async fn list_language_models(State(state): State>) -> Json { + let mut models = vec![language_model(&state, &state.cfg.model_id)]; + if let Some(r) = state.cfg.readers.as_ref() { + models.push(language_model(&state, &r.model_id)); + } + Json(json!({ "models": models })) +} + +async fn get_language_model( + State(state): State>, + Path(id): Path, +) -> Result, ApiError> { + if !state.cfg.readers.as_ref().is_some_and(|r| r.model_id == id) { + check_model(&state, &id)?; } - Ok(Json(model_card(&state))) + Ok(Json(language_model(&state, &id))) } async fn health(State(state): State>) -> Json { @@ -523,18 +708,100 @@ async fn health(State(state): State>) -> Json { async fn not_found() -> ApiError { ApiError::not_found( - "no such route; this server exposes /v1/models, /v1/chat/completions and /health", + "no such route; this server exposes /v1/models, /v1/language-models, /v1/chat/completions, /v1/responses, /v1/completions, /v1/messages, /v1/tokenize-text and /health", ) } +#[derive(Clone, Copy, PartialEq, Eq)] +enum Surface { + Chat, + Responses, + Messages, + Completions, +} + +/// How a finished chat reply goes out. +enum Wire { + Chat, + /// The request's fields the `response` object echoes. + Responses(Value), + Messages, + Completions, +} + /// Keep all authorization and slot decisions before the first body poll. async fn chat_completions(State(state): State>, request: Request) -> Response { - match handle_chat(state, request).await { + serve_surface(state, request, Surface::Chat).await +} + +async fn responses(State(state): State>, request: Request) -> Response { + serve_surface(state, request, Surface::Responses).await +} + +async fn completions(State(state): State>, request: Request) -> Response { + serve_surface(state, request, Surface::Completions).await +} + +async fn messages(State(state): State>, request: Request) -> Response { + serve_surface(state, request, Surface::Messages).await +} + +async fn serve_surface(state: Arc, request: Request, surface: Surface) -> Response { + match handle(state, request, surface).await { Ok(r) => r, + Err(e) if surface == Surface::Messages => e.into_anthropic(), Err(e) => e.into_response(), } } +/// `POST /v1/tokenize-text` (xAI): `{text, model?}` to `{token_ids: [{token_id, string_token, +/// token_bytes}]}`. Same header checks as a generation; takes no engine slot. +async fn tokenize_text(State(state): State>, request: Request) -> Response { + match tokenize(state, request).await { + Ok(v) => Json(v).into_response(), + Err(e) => e.into_response(), + } +} + +async fn tokenize(state: Arc, request: Request) -> Result { + let (body, _) = admit(&state, request, false).await?; + tokio::task::spawn_blocking(move || { + let raw: Value = serde_json::from_slice(&body) + .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; + if let Some(m) = raw.get("model").filter(|v| !v.is_null()) { + let m = m + .as_str() + .ok_or_else(|| ApiError::bad_request("model must be a string"))?; + check_model(&state, m)?; + } + let text = raw + .get("text") + .and_then(Value::as_str) + .ok_or_else(|| ApiError::bad_request("text must be a string"))?; + let ids = state + .codec + .encode(text) + .map_err(|e| ApiError::bad_request(format!("could not tokenize: {e}")))?; + let token_ids = ids + .iter() + .map(|&id| { + let bytes = state + .codec + .token_bytes(id) + .map_err(|e| ApiError::internal(e.to_string()))?; + Ok(json!({ + "token_id": id, + "string_token": String::from_utf8_lossy(&bytes), + "token_bytes": bytes, + })) + }) + .collect::, ApiError>>()?; + Ok(json!({ "token_ids": token_ids })) + }) + .await + .map_err(|_| ApiError::internal("tokenizing failed"))? +} + fn authorized(headers: &HeaderMap, token: &str) -> bool { if headers.get_all(header::AUTHORIZATION).iter().count() != 1 { return false; @@ -584,14 +851,16 @@ fn check_headers(state: &AppState, headers: &HeaderMap) -> Result<(), ApiError> let origin = origin .to_str() .map_err(|_| ApiError::forbidden("unrecognized Origin"))?; - let origin_host = origin - .strip_prefix("http://") - .ok_or_else(|| ApiError::forbidden("unrecognized Origin"))?; - if !state.allowed_hosts[1..] - .iter() - .any(|h| origin_host.eq_ignore_ascii_case(h)) - { - return Err(ApiError::forbidden("unrecognized Origin")); + if !cors_allowed(state, origin) { + let origin_host = origin + .strip_prefix("http://") + .ok_or_else(|| ApiError::forbidden("unrecognized Origin"))?; + if !state.allowed_hosts[1..] + .iter() + .any(|h| origin_host.eq_ignore_ascii_case(h)) + { + return Err(ApiError::forbidden("unrecognized Origin")); + } } } if headers.get_all(header::CONTENT_TYPE).iter().count() != 1 { @@ -611,13 +880,24 @@ fn check_headers(state: &AppState, headers: &HeaderMap) -> Result<(), ApiError> Ok(()) } -async fn handle_chat(state: Arc, request: Request) -> Result { - check_headers(&state, request.headers())?; +/// Headers, then (with `slot`) an engine slot, then the bounded body: all before parsing. +async fn admit( + state: &Arc, + request: Request, + slot: bool, +) -> Result<(Bytes, Option), ApiError> { + check_headers(state, request.headers())?; // A request owns its engine slot while the bounded body is read and while parsing or // tokenizing. Readers may reserve additional slots only after their initial admission. - let guard = Arc::clone(&state.gate) - .try_acquire_owned() - .map_err(|_| ApiError::busy())?; + let guard = if slot { + Some( + Arc::clone(&state.gate) + .try_acquire_owned() + .map_err(|_| ApiError::busy())?, + ) + } else { + None + }; if request .headers() .get(header::CONTENT_LENGTH) @@ -635,39 +915,78 @@ async fn handle_chat(state: Arc, request: Request) -> Result, - stream: bool, +async fn handle( + state: Arc, + request: Request, + surface: Surface, +) -> Result { + let (body, guard) = admit(&state, request, true).await?; + let guard = guard.expect("admit took a slot"); + let (pending, wire) = + tokio::task::spawn_blocking(move || prepare_surface(state, surface, body, guard)) + .await + .map_err(|_| ApiError::internal("request preparation failed"))??; + respond(pending, wire).await +} + +/// A request of any surface as a chat request on its way to the engine. +fn prepare_surface( + state: Arc, + surface: Surface, + body: Bytes, + guard: OwnedSemaphorePermit, +) -> Result<(PendingResponse, Wire), ApiError> { + let raw: Value = serde_json::from_slice(&body) + .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; + match surface { + Surface::Chat => Ok((prepare_chat(state, raw, guard)?, Wire::Chat)), + Surface::Responses => { + let (chat, echo) = compat::responses_to_chat(&raw).map_err(ApiError::bad_request)?; + Ok((prepare_chat(state, chat, guard)?, Wire::Responses(echo))) + } + Surface::Messages => { + let chat = compat::messages_to_chat(&raw).map_err(ApiError::bad_request)?; + Ok((prepare_chat(state, chat, guard)?, Wire::Messages)) + } + Surface::Completions => { + let (chat, prompt) = + compat::completions_to_chat(&raw).map_err(ApiError::bad_request)?; + let req: ChatRequest = serde_json::from_value(chat) + .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; + let prepared = prepare_raw(&state, req, prompt)?; + let model = state.cfg.model_id.clone(); + Ok((start(&state, prepared, guard, model), Wire::Completions)) + } + } +} + +/// What every reply of a request shares. +struct Meta { id: String, created: u64, model: String, prompt_tokens: usize, tools: bool, + parallel_tools: bool, + include_usage: bool, +} + +struct PendingResponse { + /// One per choice (`n`), generated in order. + rxs: Vec>, + stream: bool, + meta: Meta, } fn prepare_chat( state: Arc, - body: Bytes, + mut raw: Value, guard: OwnedSemaphorePermit, ) -> Result { let mut guard = Some(guard); - let mut raw: Value = serde_json::from_slice(&body) - .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; let mut model = state.cfg.model_id.clone(); if let Some(rc) = state.cfg.readers.as_ref() { if raw.get("model").and_then(Value::as_str) == Some(rc.model_id.as_str()) { @@ -681,33 +1000,72 @@ fn prepare_chat( let req: ChatRequest = serde_json::from_value(raw) .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; let prepared = prepare(&state, req)?; - let (created, id) = new_id(&state); - let prompt_tokens = prepared.prompt_tokens.len(); + Ok(start( + &state, + prepared, + guard.expect("admitted slot"), + model, + )) +} + +fn start( + state: &Arc, + prepared: Prepared, + guard: OwnedSemaphorePermit, + model: String, +) -> PendingResponse { + let (created, id) = new_id(state); + let meta = Meta { + id, + created, + model, + prompt_tokens: prepared.prompt_tokens.len(), + tools: prepared.tools, + parallel_tools: prepared.parallel_tools, + include_usage: prepared.include_usage, + }; let stream = prepared.stream; - let tools = prepared.tools; - let (tx, rx) = mpsc::channel::(64); + let rxs = launch(state, prepared, guard, &meta.id); + PendingResponse { rxs, stream, meta } +} + +/// The `n` choices one after another on one blocking thread holding the slot; choice `i` samples +/// with seed + i. A client that leaves stops the choices not yet started. +fn launch( + state: &AppState, + prepared: Prepared, + guard: OwnedSemaphorePermit, + id: &str, +) -> Vec> { + let n = prepared.n.max(1); + let (txs, rxs): (Vec<_>, Vec<_>) = (0..n).map(|_| mpsc::channel::(64)).unzip(); let engine = Arc::clone(&state.engine); let codec = Arc::clone(&state.codec); - let log_id = id.clone(); + let id = id.to_string(); tokio::task::spawn_blocking(move || { - run_generation( - engine, - codec, - prepared, - tx, - guard.expect("admitted slot"), - &log_id, - ); + let mut guard = Some(guard); + let mut prepared = Some(prepared); + for (i, tx) in txs.into_iter().enumerate() { + if i > 0 && tx.is_closed() { + return; + } + let last = i + 1 == n; + let mut p = if last { + prepared.take().expect("the last choice") + } else { + prepared.as_ref().expect("choices left").clone() + }; + p.params.seed = p.params.seed.wrapping_add(i as u64); + let g = if last { guard.take() } else { None }; + let log_id = if n > 1 { + format!("{id}/{i}") + } else { + id.clone() + }; + run_generation(Arc::clone(&engine), Arc::clone(&codec), p, tx, g, &log_id); + } }); - Ok(PendingResponse { - rx, - stream, - id, - created, - model, - prompt_tokens, - tools, - }) + rxs } fn new_id(state: &AppState) -> (u64, String) { @@ -735,6 +1093,11 @@ fn handle_readers( let Some(mut plan) = readers::plan(msgs, rc, &count) else { return Ok(None); }; + if raw.get("n").is_some_and(|n| !n.is_null() && n != &json!(1)) { + return Err(ApiError::bad_request( + "n > 1 is not supported on the readers model", + )); + } let slots = state.engine.concurrency().max(1); let want = plan.parts.len().min(slots); let (extra, got) = (1..want) @@ -776,7 +1139,12 @@ fn handle_readers( // The connect request must be valid before any row reads (same checks, notes not yet known). let blank = vec![String::new(); plan.parts.len()]; let check = from(readers::connect_body(raw, &plan, &blank, base))?; - let (stream, tools) = (check.stream, check.tools); + let (stream, tools, parallel_tools, include_usage) = ( + check.stream, + check.tools, + check.parallel_tools, + check.include_usage, + ); let show_notes = raw .get("aien_show_notes") .and_then(Value::as_bool) @@ -794,13 +1162,17 @@ fn handle_readers( run_readers(st, raw, plan, maps, permit, tx, stream, show_notes, &log_id); }); Ok(Some(PendingResponse { - rx, + rxs: vec![rx], stream, - id, - created, - model: rc.model_id.clone(), - prompt_tokens: 0, - tools, + meta: Meta { + id, + created, + model: rc.model_id.clone(), + prompt_tokens: 0, + tools, + parallel_tools, + include_usage, + }, })) } @@ -988,55 +1360,63 @@ fn run_readers( Arc::clone(&state.codec), connect, tx, - one, + Some(one), id, ); } +/// A generation's events, the first one already read. +struct Events { + first: Option, + rx: mpsc::Receiver, +} + +impl Events { + async fn recv(&mut self) -> Option { + match self.first.take() { + Some(ev) => Some(ev), + None => self.rx.recv().await, + } + } +} + /// The response for a generation's events: the first decides the status (a busy chip is 503). -async fn respond( - mut rx: mpsc::Receiver, - stream: bool, - id: String, - created: u64, - model: String, - prompt_tokens: usize, - tools: bool, -) -> Result { +async fn respond(pending: PendingResponse, wire: Wire) -> Result { // The first event decides the status: a busy chip is a 503 in the OpenAI error envelope, // before any headers go out (streaming included). Everything else is forwarded unchanged. + let mut rxs = pending.rxs.into_iter(); + let mut rx = rxs + .next() + .ok_or_else(|| ApiError::internal("no generation started"))?; let first = rx.recv().await; match &first { Some(Ev::Busy(m)) => return Err(ApiError::gpu_busy(m)), Some(Ev::MemoryExceeded(m)) => return Err(ApiError::memory_exceeded(m.clone())), _ => {} } - let (ftx, frx) = mpsc::channel::(64); - tokio::spawn(async move { - if let Some(ev) = first { - if ftx.send(ev).await.is_err() { - return; - } - } - while let Some(ev) = rx.recv().await { - if ftx.send(ev).await.is_err() { - return; - } - } - }); - let rx = frx; - if stream { - Ok(stream_response( - id, - created, - model, - prompt_tokens, - rx, - tools, - )) - } else { - collect_response(id, created, &model, prompt_tokens, rx, tools).await + let mut events: Vec = std::iter::once(Events { first, rx }) + .chain(rxs.map(|rx| Events { first: None, rx })) + .collect(); + let meta = pending.meta; + if pending.stream { + // `n > 1` is refused for streams, so there is one generation. + let ev = events.swap_remove(0); + return Ok(match wire { + Wire::Responses(echo) => stream_responses(meta, ev, echo), + _ => stream_response(meta, ev), + }); } + let chat = match collect_chat(&meta, events).await? { + Ok(chat) => chat, + Err(busy) => return Ok(busy), + }; + let body = match wire { + Wire::Chat => chat, + Wire::Responses(echo) => compat::chat_to_response(&chat, &echo), + Wire::Messages => compat::chat_to_message(&chat), + Wire::Completions => compat::chat_to_text_completion(&chat), + }; + Ok(Json(body).into_response()) } fn text_of_content(content: &Value) -> Result { @@ -1071,15 +1451,7 @@ fn text_of_content(content: &Value) -> Result { fn prepare(state: &AppState, req: ChatRequest) -> Result { let cfg = &state.cfg; if let Some(m) = req.model.as_deref() { - if m != cfg.model_id { - return Err(ApiError::not_found(format!( - "model '{m}' not found; this server serves '{}'", - cfg.model_id - ))); - } - } - if matches!(req.n, Some(n) if n != 1) { - return Err(ApiError::bad_request("n must be 1")); + check_model(state, m)?; } // Tool calling in the model's own format (`cfg.tool_format`, read from its chat template at // load): legacy `functions` are accepted as tools. @@ -1091,6 +1463,7 @@ fn prepare(state: &AppState, req: ChatRequest) -> Result { .collect(), _ => Vec::new(), }; + let has_tools = tool_mode(&req, &tool_defs)?; if req.messages.is_empty() { return Err(ApiError::bad_request("messages must be a non-empty array")); } @@ -1132,9 +1505,91 @@ fn prepare(state: &AppState, req: ChatRequest) -> Result { CodecError::Unrenderable(m) => ApiError::bad_request(m), CodecError::Failed(m) => ApiError::internal(m), })?; + prepare_params(state, req, &prompt_text, has_tools) +} + +/// `tool_choice`: whether the tools are shown to the model. A forced call (`"required"`, a named +/// function) is a 400: nothing here can make the model call a tool, and pretending would let a +/// client trust a reply that may carry no call. +fn tool_mode(req: &ChatRequest, tools: &[Value]) -> Result { + const NO_FORCE: &str = + "this server cannot force a tool call (no constrained decoding); use \"auto\" or \"none\""; + match req.tool_choice.as_ref() { + None | Some(Value::Null) => Ok(!tools.is_empty()), + Some(Value::String(s)) if s == "auto" => Ok(!tools.is_empty()), + Some(Value::String(s)) if s == "none" => Ok(false), + Some(Value::String(s)) if s == "required" => Err(ApiError::bad_request(format!( + "tool_choice \"required\" is not supported: {NO_FORCE}" + ))), + Some(v) if v["type"] == "function" && v["function"]["name"].is_string() => { + let name = v["function"]["name"].as_str().expect("string"); + if tools.iter().any(|t| t["function"]["name"] == name) { + Err(ApiError::bad_request(format!( + "tool_choice forcing function '{name}' is not supported: {NO_FORCE}" + ))) + } else { + Err(ApiError::bad_request(format!( + "tool_choice names function '{name}', which is not in tools" + ))) + } + } + Some(v) => Err(ApiError::bad_request(format!( + "tool_choice must be \"auto\", \"none\", \"required\" or {{\"type\":\"function\",\"function\":{{\"name\":...}}}}; got {v}" + ))), + } +} + +/// A legacy completion: the prompt as given, no chat template. +fn prepare_raw(state: &AppState, req: ChatRequest, prompt: String) -> Result { + if let Some(m) = req.model.as_deref() { + check_model(state, m)?; + } + if prompt.is_empty() { + return Err(ApiError::bad_request("prompt must be non-empty")); + } + prepare_params(state, req, &prompt, false) +} + +fn prepare_params( + state: &AppState, + req: ChatRequest, + prompt_text: &str, + has_tools: bool, +) -> Result { + let cfg = &state.cfg; + if let Some(f) = req.response_format.as_ref().filter(|v| !v.is_null()) { + match f.get("type").and_then(Value::as_str) { + Some("text") => {} + Some(k @ ("json_object" | "json_schema")) => { + return Err(ApiError::bad_request(format!( + "response_format {k} is not supported: this server has no constrained decoding, so it cannot guarantee JSON" + ))) + } + _ => { + return Err(ApiError::bad_request( + "response_format must be {\"type\":\"text\"}", + )) + } + } + } + let n = match req.n { + None => 1, + Some(n) if (1..=8).contains(&n) => n as usize, + Some(_) => return Err(ApiError::bad_request("n must be between 1 and 8")), + }; + if n > 1 && req.stream { + return Err(ApiError::bad_request( + "n > 1 is not supported with stream: true", + )); + } + if n > 1 && req.aien_return_token_ids { + return Err(ApiError::bad_request("aien_return_token_ids needs n = 1")); + } + let include_usage = req.stream_options.as_ref().is_some_and(|o| o.include_usage); + let parallel_tools = req.parallel_tool_calls != Some(false); let prompt_tokens = state .codec - .encode(&prompt_text) + .encode(prompt_text) .map_err(|e| ApiError::context_exceeded(format!("could not tokenize prompt: {e}")))?; if prompt_tokens.is_empty() { return Err(ApiError::bad_request("the rendered prompt is empty")); @@ -1228,7 +1683,10 @@ fn prepare(state: &AppState, req: ChatRequest) -> Result { None }, return_ids: req.aien_return_token_ids, - tools: !tool_defs.is_empty(), + tools: has_tools, + parallel_tools, + include_usage, + n, test: test_switches(state, req.aien_test.as_ref())?, }) } @@ -1304,15 +1762,16 @@ fn chat_options(req: &ChatRequest) -> Result { Ok(o) } -/// Runs on a blocking thread holding the generation lock (`guard`). The lock is released as soon -/// as the engine returns, before the final event is sent, so a client that sends its next request -/// the moment it has the reply never meets a stale 503 `server_busy`. +/// Runs on a blocking thread holding the generation lock (`guard`, absent for all but the last of +/// several choices, which run under it). The lock is released as soon as the engine returns, +/// before the final event is sent, so a client that sends its next request the moment it has the +/// reply never meets a stale 503 `server_busy`. fn run_generation( engine: Arc, codec: Arc, prepared: Prepared, tx: mpsc::Sender, - guard: OwnedSemaphorePermit, + guard: Option, id: &str, ) { let mut asm = TextAssembler::new(Arc::clone(&codec), prepared.stop_strings); @@ -1326,6 +1785,7 @@ fn run_generation( let mut ids = prepared.return_ids.then(Vec::new); let mut stopped_by_string = false; let mut client_gone = false; + let mut reasoning_tokens = 0usize; let test_report = (!prepared.test.is_empty()).then(|| prepared.test.names()); let result = engine.generate_with_test( &prepared.prompt_tokens, @@ -1336,6 +1796,7 @@ fn run_generation( ids.push(tok); } if let Some((end, rasm)) = thinking.as_mut() { + reasoning_tokens += 1; let ev = if tok == *end { let rest = rasm.finish(); thinking = None; @@ -1449,30 +1910,105 @@ fn run_generation( out.prefill_ms, out.decode_ms ); - let _ = tx.blocking_send(Ev::Done { + let _ = tx.blocking_send(Ev::Done(Done { finish, completion_tokens: out.emitted_tokens, + reasoning_tokens: reasoning_tokens.min(out.emitted_tokens), sampling: out.sampling, token_ids: ids, test: test_report, - }); + })); } } } -async fn collect_response( - id: String, - created: u64, - model: &str, - mut prompt_tokens: usize, - mut rx: mpsc::Receiver, - tools: bool, -) -> Result { +/// The reply's text and its tool calls (`parallel: false` keeps the first call). +fn split_calls(text: &str, id: &str, parallel: bool) -> (String, Vec) { + let (text, mut calls) = crate::tools::parse_reply(text, id); + if !parallel { + calls.truncate(1); + } + (text, calls) +} + +/// Streamed tool requests: text goes out until a `` opens (a possible split tag is +/// held back); from there the reply is held and parsed at the end. +#[derive(Default)] +struct ToolSplit { + held: String, + in_call: bool, +} + +impl ToolSplit { + /// The text of `d` that can go out now. + fn push(&mut self, d: &str) -> String { + self.held.push_str(d); + if self.in_call { + return String::new(); + } + let cut = match self.held.find(crate::tools::OPEN) { + Some(p) => { + self.in_call = true; + p + } + None => self.held.len() - crate::tools::partial_open_len(&self.held), + }; + self.held.drain(..cut).collect() + } + + /// The held text and calls at the end of the reply. + fn finish(&mut self, id: &str, parallel: bool) -> (String, Vec) { + if self.held.is_empty() { + return (String::new(), Vec::new()); + } + split_calls(&std::mem::take(&mut self.held), id, parallel) + } +} + +/// All choices as one `chat.completion`: the prompt counted once, the replies' tokens summed. +/// `Ok(Err(_))` is the busy-chip 503. +async fn collect_chat( + meta: &Meta, + events: Vec, +) -> Result, ApiError> { + let mut body: Option = None; + for (i, mut ev) in events.into_iter().enumerate() { + let one = match collect_choice(meta, &mut ev).await? { + Ok(v) => v, + Err(busy) => return Ok(Err(busy)), + }; + let Some(b) = body.as_mut() else { + body = Some(one); + continue; + }; + let mut choice = one["choices"][0].clone(); + choice["index"] = json!(i); + b["choices"].as_array_mut().expect("choices").push(choice); + for k in ["completion_tokens", "total_tokens"] { + let sum = b["usage"][k].as_u64().unwrap_or(0) + + one["usage"]["completion_tokens"].as_u64().unwrap_or(0); + b["usage"][k] = json!(sum); + } + let r = &mut b["usage"]["completion_tokens_details"]["reasoning_tokens"]; + *r = json!( + r.as_u64().unwrap_or(0) + + one["usage"]["completion_tokens_details"]["reasoning_tokens"] + .as_u64() + .unwrap_or(0) + ); + } + body.map(Ok) + .ok_or_else(|| ApiError::internal("generation ended without a result")) +} + +async fn collect_choice(meta: &Meta, ev: &mut Events) -> Result, ApiError> { + let (id, created, model) = (meta.id.as_str(), meta.created, meta.model.as_str()); + let mut prompt_tokens = meta.prompt_tokens; let mut content = String::new(); let mut reasoning: Option = None; let mut readers: Option = None; - while let Some(ev) = rx.recv().await { - match ev { + while let Some(e) = ev.recv().await { + match e { Ev::Delta(d) => content.push_str(&d), Ev::Reading => {} Ev::Readers { @@ -1483,29 +2019,16 @@ async fn collect_response( prompt_tokens = p; } Ev::Reasoning(d) => reasoning.get_or_insert_with(String::new).push_str(&d), - Ev::Done { - finish, - completion_tokens, - sampling, - token_ids, - test, - } => { - let usage = Usage { - prompt_tokens, - completion_tokens, - total_tokens: prompt_tokens + completion_tokens, - aien_sampling: sampling, - aien_token_ids: token_ids, - aien_test: test.map(|n| serde_json::json!({ "applied": n })), - }; + Ev::Done(done) => { + let (finish, usage) = done.usage(prompt_tokens); let reasoning = reasoning.as_deref().map(str::trim); - let (text, calls) = if tools { - crate::tools::parse_reply(&content, &id) + let (text, calls) = if meta.tools { + split_calls(&content, id, meta.parallel_tools) } else { (content.clone(), Vec::new()) }; let mut body = - completion_json(&id, created, model, &text, reasoning, finish, &usage); + completion_json(id, created, model, &text, reasoning, finish, &usage); if !calls.is_empty() { let msg = &mut body["choices"][0]["message"]; msg["tool_calls"] = Value::Array(calls); @@ -1517,7 +2040,7 @@ async fn collect_response( if let Some(info) = readers { body["aien_readers"] = info; } - return Ok(Json(body).into_response()); + return Ok(Ok(body)); } Ev::Error(m) => return Err(ApiError::internal(m)), // Not the first event on the readers' path (`Ev::Readers` goes before the connect @@ -1529,142 +2052,100 @@ async fn collect_response( Err(ApiError::internal("generation ended without a result")) } -fn stream_response( - id: String, - created: u64, - model: String, - mut prompt_tokens: usize, - mut rx: mpsc::Receiver, - tools: bool, -) -> Response { +fn sse(erx: mpsc::Receiver>) -> Response { + Sse::new(ReceiverStream::new(erx)) + .keep_alive( + KeepAlive::new() + .interval(Duration::from_secs(15)) + .text("keep-alive"), + ) + .into_response() +} + +fn stream_response(meta: Meta, mut ev: Events) -> Response { let (etx, erx) = mpsc::channel::>(64); tokio::spawn(async move { - // Tool requests: content streams until a `` opens (a possible split tag is held - // back); from there the reply is buffered and sent as one `tool_calls` delta at the end. - let mut held = String::new(); - let mut in_call = false; + let (id, created, model) = (meta.id.as_str(), meta.created, meta.model.as_str()); + let mut prompt_tokens = meta.prompt_tokens; + let mut split = ToolSplit::default(); let data = |v: Value| Ok(Event::default().data(v.to_string())); - let first = chunk_json( - &id, - created, - &model, - Some("assistant"), - Some(""), - None, - None, - ); + let text_chunk = |t: &str| chunk_json(id, created, model, None, Some(t), None, None); + let first = chunk_json(id, created, model, Some("assistant"), Some(""), None, None); if etx.send(data(first)).await.is_err() { return; } - while let Some(ev) = rx.recv().await { - let item = match ev { + while let Some(e) = ev.recv().await { + let item = match e { Ev::Reading => continue, Ev::Readers { info, prompt_tokens: p, } => { prompt_tokens = p; - let mut v = chunk_json(&id, created, &model, None, None, None, None); + let mut v = chunk_json(id, created, model, None, None, None, None); v["aien_readers"] = info; data(v) } - Ev::Delta(d) if tools => { - held.push_str(&d); - if in_call { - continue; - } - let out = if let Some(p) = held.find(crate::tools::OPEN) { - in_call = true; - let out = held[..p].to_string(); - held = held[p..].to_string(); - out - } else { - let keep = crate::tools::partial_open_len(&held); - let cut = held.len() - keep; - let out = held[..cut].to_string(); - held = held[cut..].to_string(); - out - }; + Ev::Delta(d) if meta.tools => { + let out = split.push(&d); if out.is_empty() { continue; } - data(chunk_json( - &id, - created, - &model, - None, - Some(&out), - None, - None, - )) + data(text_chunk(&out)) } - Ev::Delta(d) => data(chunk_json(&id, created, &model, None, Some(&d), None, None)), + Ev::Delta(d) => data(text_chunk(&d)), Ev::Reasoning(d) => data(chunk_json_with( - &id, + id, created, - &model, + model, None, None, Some(&d), None, None, )), - Ev::Done { - finish, - completion_tokens, - sampling, - token_ids, - test, - } => { - let usage = Usage { - prompt_tokens, - completion_tokens, - total_tokens: prompt_tokens + completion_tokens, - aien_sampling: sampling, - aien_token_ids: token_ids, - aien_test: test.map(|n| serde_json::json!({ "applied": n })), - }; - let mut finish = finish; - if tools && !held.is_empty() { - let (text, calls) = crate::tools::parse_reply(&held, &id); - if !text.is_empty() - && etx - .send(data(chunk_json( - &id, - created, - &model, - None, - Some(&text), - None, - None, - ))) - .await - .is_err() - { + Ev::Done(done) => { + let (mut finish, usage) = done.usage(prompt_tokens); + let (text, calls) = split.finish(id, meta.parallel_tools); + if !text.is_empty() && etx.send(data(text_chunk(&text))).await.is_err() { + return; + } + if !calls.is_empty() { + let deltas: Vec = calls + .into_iter() + .enumerate() + .map(|(i, mut c)| { + c["index"] = Value::from(i); + c + }) + .collect(); + let mut ch = chunk_json(id, created, model, None, None, None, None); + ch["choices"][0]["delta"]["tool_calls"] = Value::Array(deltas); + if etx.send(data(ch)).await.is_err() { return; } - if !calls.is_empty() { - let deltas: Vec = calls - .into_iter() - .enumerate() - .map(|(i, mut c)| { - c["index"] = Value::from(i); - c - }) - .collect(); - let mut ch = chunk_json(&id, created, &model, None, None, None, None); - ch["choices"][0]["delta"]["tool_calls"] = Value::Array(deltas); - if etx.send(data(ch)).await.is_err() { - return; - } - finish = "tool_calls"; - } + finish = "tool_calls"; } let last = - chunk_json(&id, created, &model, None, None, Some(finish), Some(&usage)); + chunk_json(id, created, model, None, None, Some(finish), Some(&usage)); if etx.send(data(last)).await.is_err() { return; } + // `stream_options.include_usage`: the usage again in a chunk of its own with + // no choices, as OpenAI and xAI send it. + if meta.include_usage { + let u = json!({ + "id": id, + "object": "chat.completion.chunk", + "created": created, + "model": model, + "choices": [], + "usage": usage, + }); + if etx.send(data(u)).await.is_err() { + return; + } + } let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; return; } @@ -1693,13 +2174,186 @@ fn stream_response( } } }); - Sse::new(ReceiverStream::new(erx)) - .keep_alive( - KeepAlive::new() - .interval(Duration::from_secs(15)) - .text("keep-alive"), - ) - .into_response() + sse(erx) +} + +/// A Responses stream: named events with a running `sequence_number`, from `response.created` to +/// `response.completed` (or `.incomplete`), then `data: [DONE]`. The reasoning item goes out +/// whole when the answer starts; text streams as `response.output_text.delta`; tool calls go out +/// at the end, each as its item plus one arguments delta. +fn stream_responses(meta: Meta, mut ev: Events, echo: Value) -> Response { + let (etx, erx) = mpsc::channel::>(64); + tokio::spawn(async move { + let id = meta.id.as_str(); + let base = |status: &str, output: Vec, usage: Option| { + compat::response_object(&echo, id, meta.created, &meta.model, status, output, usage) + }; + let msg_id = format!("msg_{}", compat::id_suffix(id)); + let mut seq = 0u64..; + let mut prompt_tokens = meta.prompt_tokens; + let mut reasoning = String::new(); + let mut reasoning_done = false; + let mut text = String::new(); + let mut msg_index: Option = None; + let mut split = ToolSplit::default(); + let mut output: Vec = Vec::new(); + macro_rules! emit { + ($kind:expr, $v:expr) => {{ + let mut v: Value = $v; + v["type"] = json!($kind); + v["sequence_number"] = json!(seq.next()); + let event = Event::default().event($kind).data(v.to_string()); + if etx.send(Ok(event)).await.is_err() { + return; + } + }}; + } + macro_rules! close_reasoning { + () => { + if !std::mem::replace(&mut reasoning_done, true) && !reasoning.trim().is_empty() { + let idx = output.len(); + let item = compat::reasoning_item(id, reasoning.trim()); + let mut added = item.clone(); + added["status"] = json!("in_progress"); + emit!( + "response.output_item.added", + json!({"output_index": idx, "item": added}) + ); + emit!( + "response.output_item.done", + json!({"output_index": idx, "item": item.clone()}) + ); + output.push(item); + } + }; + } + macro_rules! open_message { + () => { + if msg_index.is_none() { + let idx = output.len(); + msg_index = Some(idx); + emit!( + "response.output_item.added", + json!({"output_index": idx, "item": compat::message_item(id, "", "in_progress")}) + ); + emit!( + "response.content_part.added", + json!({"item_id": msg_id, "output_index": idx, "content_index": 0, "part": compat::output_text("")}) + ); + } + }; + } + macro_rules! text_delta { + ($d:expr) => {{ + let d: String = $d; + close_reasoning!(); + open_message!(); + text.push_str(&d); + emit!( + "response.output_text.delta", + json!({"item_id": msg_id, "output_index": msg_index, "content_index": 0, "delta": d, "logprobs": []}) + ); + }}; + } + emit!( + "response.created", + json!({"response": base("in_progress", Vec::new(), None)}) + ); + emit!( + "response.in_progress", + json!({"response": base("in_progress", Vec::new(), None)}) + ); + while let Some(e) = ev.recv().await { + match e { + Ev::Reading => {} + Ev::Readers { + prompt_tokens: p, .. + } => prompt_tokens = p, + Ev::Reasoning(d) => reasoning.push_str(&d), + Ev::Delta(d) => { + let out = if meta.tools { split.push(&d) } else { d }; + if !out.is_empty() { + text_delta!(out); + } + } + Ev::Done(done) => { + let (finish, usage) = done.usage(prompt_tokens); + let (rest, calls) = split.finish(id, meta.parallel_tools); + if !rest.is_empty() { + text_delta!(rest); + } + close_reasoning!(); + if calls.is_empty() { + open_message!(); + } + if let Some(idx) = msg_index { + emit!( + "response.output_text.done", + json!({"item_id": msg_id, "output_index": idx, "content_index": 0, "text": text, "logprobs": []}) + ); + emit!( + "response.content_part.done", + json!({"item_id": msg_id, "output_index": idx, "content_index": 0, "part": compat::output_text(&text)}) + ); + let item = compat::message_item(id, &text, "completed"); + emit!( + "response.output_item.done", + json!({"output_index": idx, "item": item.clone()}) + ); + output.push(item); + } + for c in &calls { + let idx = output.len(); + let item = compat::function_call_item(c, "completed"); + emit!( + "response.output_item.added", + json!({"output_index": idx, "item": compat::function_call_item(c, "in_progress")}) + ); + emit!( + "response.function_call_arguments.delta", + json!({"item_id": item["id"], "output_index": idx, "delta": item["arguments"]}) + ); + emit!( + "response.function_call_arguments.done", + json!({"item_id": item["id"], "output_index": idx, "name": item["name"], "arguments": item["arguments"]}) + ); + emit!( + "response.output_item.done", + json!({"output_index": idx, "item": item.clone()}) + ); + output.push(item); + } + let status = compat::status_of(finish); + let usage = compat::response_usage(&json!(usage)); + let kind = if status == "incomplete" { + "response.incomplete" + } else { + "response.completed" + }; + emit!(kind, json!({"response": base(status, output, Some(usage))})); + let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; + return; + } + Ev::Error(m) | Ev::Busy(m) => { + emit!( + "error", + json!({"code": "server_error", "message": m, "param": null}) + ); + let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; + return; + } + Ev::MemoryExceeded(m) => { + emit!( + "error", + json!({"code": "prompt_exceeds_memory_budget", "message": m, "param": null}) + ); + let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; + return; + } + } + } + }); + sse(erx) } #[cfg(test)] @@ -1712,7 +2366,21 @@ mod tests { tx.send(ev).await.expect("room for every event"); } drop(tx); - respond(rx, stream, "id".into(), 0, "m".into(), 3, false) + let meta = Meta { + id: "id".into(), + created: 0, + model: "m".into(), + prompt_tokens: 3, + tools: false, + parallel_tools: true, + include_usage: false, + }; + let pending = PendingResponse { + rxs: vec![rx], + stream, + meta, + }; + respond(pending, Wire::Chat) .await .unwrap_or_else(IntoResponse::into_response) } @@ -1747,4 +2415,194 @@ mod tests { ]; assert_chip_busy(&answer(events, false).await); } + + fn done(completion_tokens: usize, reasoning_tokens: usize) -> Ev { + Ev::Done(Done { + finish: "stop", + completion_tokens, + reasoning_tokens, + sampling: Default::default(), + token_ids: None, + test: None, + }) + } + + async fn body_json(resp: Response) -> Value { + let b = to_bytes(resp.into_body(), 1 << 20).await.expect("body"); + serde_json::from_slice(&b).expect("json") + } + + async fn body_text(resp: Response) -> String { + let b = to_bytes(resp.into_body(), 1 << 20).await.expect("body"); + String::from_utf8(b.to_vec()).expect("utf8") + } + + fn meta(include_usage: bool) -> Meta { + Meta { + id: "chatcmpl-1".into(), + created: 0, + model: "m".into(), + prompt_tokens: 3, + tools: false, + parallel_tools: true, + include_usage, + } + } + + async fn channel(events: Vec) -> mpsc::Receiver { + let (tx, rx) = mpsc::channel(events.len().max(1)); + for ev in events { + tx.send(ev).await.expect("room"); + } + rx + } + + /// Reasoning tokens are reported under `completion_tokens_details`. + #[tokio::test] + async fn usage_carries_reasoning_tokens() { + let events = vec![ + Ev::Reasoning("think".into()), + Ev::Delta("hi".into()), + done(5, 2), + ]; + let v = body_json(answer(events, false).await).await; + assert_eq!(v["usage"]["completion_tokens"], 5); + assert_eq!( + v["usage"]["completion_tokens_details"]["reasoning_tokens"], + 2 + ); + assert_eq!(v["usage"]["total_tokens"], 8); + } + + /// `n = 2`: two choices with indexes 0 and 1, the prompt counted once. + #[tokio::test] + async fn two_choices_merge_into_one_reply() { + let pending = PendingResponse { + rxs: vec![ + channel(vec![Ev::Delta("a".into()), done(2, 1)]).await, + channel(vec![Ev::Delta("b".into()), done(4, 0)]).await, + ], + stream: false, + meta: meta(false), + }; + let v = body_json(respond(pending, Wire::Chat).await.expect("reply")).await; + assert_eq!(v["choices"][0]["message"]["content"], "a"); + assert_eq!(v["choices"][1]["index"], 1); + assert_eq!(v["choices"][1]["message"]["content"], "b"); + assert_eq!(v["usage"]["prompt_tokens"], 3); + assert_eq!(v["usage"]["completion_tokens"], 6); + assert_eq!(v["usage"]["total_tokens"], 9); + assert_eq!( + v["usage"]["completion_tokens_details"]["reasoning_tokens"], + 1 + ); + } + + /// `stream_options.include_usage`: a last chunk with no choices and the usage, before `[DONE]`. + #[tokio::test] + async fn include_usage_adds_a_usage_chunk() { + let rx = channel(vec![Ev::Delta("hi".into()), done(1, 0)]).await; + let pending = PendingResponse { + rxs: vec![rx], + stream: true, + meta: meta(true), + }; + let text = body_text(respond(pending, Wire::Chat).await.expect("reply")).await; + let data: Vec<&str> = text + .lines() + .filter_map(|l| l.strip_prefix("data: ")) + .collect(); + assert_eq!(data.last(), Some(&"[DONE]")); + let u: Value = serde_json::from_str(data[data.len() - 2]).expect("usage chunk"); + assert_eq!(u["choices"], json!([])); + assert_eq!(u["usage"]["total_tokens"], 4); + let rx = channel(vec![Ev::Delta("hi".into()), done(1, 0)]).await; + let pending = PendingResponse { + rxs: vec![rx], + stream: true, + meta: meta(false), + }; + let text = body_text(respond(pending, Wire::Chat).await.expect("reply")).await; + assert!(!text.contains("\"choices\":[]"), "{text}"); + } + + /// A Responses stream runs created .. completed with rising sequence numbers, then `[DONE]`. + #[tokio::test] + async fn responses_stream_events_in_order() { + let rx = channel(vec![ + Ev::Delta("he".into()), + Ev::Delta("llo".into()), + done(2, 0), + ]) + .await; + let pending = PendingResponse { + rxs: vec![rx], + stream: true, + meta: meta(false), + }; + let (_, echo) = compat::responses_to_chat(&json!({"input": "x"})).expect("maps"); + let text = body_text( + respond(pending, Wire::Responses(echo)) + .await + .expect("reply"), + ) + .await; + let kinds: Vec<&str> = text + .lines() + .filter_map(|l| l.strip_prefix("event: ")) + .collect(); + assert_eq!( + kinds, + [ + "response.created", + "response.in_progress", + "response.output_item.added", + "response.content_part.added", + "response.output_text.delta", + "response.output_text.delta", + "response.output_text.done", + "response.content_part.done", + "response.output_item.done", + "response.completed", + ] + ); + let seqs: Vec = text + .lines() + .filter_map(|l| l.strip_prefix("data: ")) + .filter_map(|d| serde_json::from_str::(d).ok()) + .filter_map(|v| v["sequence_number"].as_u64()) + .collect(); + assert_eq!(seqs, (0..10).collect::>()); + assert!(text.contains("\"text\":\"hello\""), "{text}"); + assert!(text.trim_end().ends_with("data: [DONE]"), "{text}"); + } + + fn req(v: Value) -> ChatRequest { + serde_json::from_value(v).expect("request") + } + + /// `tool_choice`: auto and none are honoured; a forced call is a 400, never ignored. + #[test] + fn tool_choice_is_honoured_or_refused() { + let tools = vec![json!({"type":"function","function":{"name":"f"}})]; + let base = json!({"messages":[{"role":"user","content":"x"}]}); + let with = |tc: Value| { + let mut v = base.clone(); + v["tool_choice"] = tc; + tool_mode(&req(v), &tools) + }; + assert!(tool_mode(&req(base.clone()), &tools).unwrap()); + assert!(!tool_mode(&req(base.clone()), &[]).unwrap()); + assert!(with(json!("auto")).unwrap()); + assert!(!with(json!("none")).unwrap()); + for tc in [ + json!("required"), + json!({"type":"function","function":{"name":"f"}}), + json!({"type":"function","function":{"name":"g"}}), + json!("sometimes"), + ] { + let e = with(tc.clone()).expect_err("refused"); + assert_eq!(e.status, StatusCode::BAD_REQUEST, "{tc}"); + } + } } diff --git a/crates/aien-serve-http/tests/loopback.rs b/crates/aien-serve-http/tests/loopback.rs index 8b9cb176..4e951860 100644 --- a/crates/aien-serve-http/tests/loopback.rs +++ b/crates/aien-serve-http/tests/loopback.rs @@ -863,3 +863,206 @@ mod sampling_gate { assert!(picks.len() >= 2, "{picks:?}"); } } + +fn post(addr: SocketAddr, path: &str, body: &str) -> Reply { + request(addr, "POST", path, Some(body)) +} + +/// `--cors-origin`: a listed origin gets a preflight and `Access-Control-Allow-Origin`, and still +/// needs the bearer; any other origin gets neither. Off by default. +#[test] +fn cors_only_for_listed_origins() { + let preflight = |addr, origin: &str| { + raw_request(addr, &format!( + "OPTIONS /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nOrigin: {origin}\r\nAccess-Control-Request-Method: POST\r\nAccess-Control-Request-Headers: authorization,content-type\r\n\r\n" + )) + }; + let acao = |r: &Reply| { + r.headers + .to_ascii_lowercase() + .contains("access-control-allow-origin:") + }; + let off = start(stub("x"), ServerConfig::default()); + let r = preflight(off.addr, "https://app.example"); + assert_eq!(r.status, 403); + assert!(!acao(&r)); + + let srv = start( + stub("x"), + ServerConfig { + cors_origins: vec!["https://app.example".into()], + ..ServerConfig::default() + }, + ); + let r = preflight(srv.addr, "https://app.example"); + assert_eq!(r.status, 204, "{}", r.headers); + assert!(r + .headers + .to_ascii_lowercase() + .contains("access-control-allow-origin: https://app.example")); + let r = preflight(srv.addr, "https://evil.example"); + assert_eq!(r.status, 403); + assert!(!acao(&r)); + + let body = r#"{"messages":[{"role":"user","content":"hi"}]}"#; + let r = raw_post( + srv.addr, + &format!("Origin: https://app.example\r\nAuthorization: Bearer {TOKEN}\r\nContent-Type: application/json\r\n"), + body, + ); + assert_eq!(r.status, 200, "{}", r.body); + assert!(acao(&r)); + let r = raw_post( + srv.addr, + "Origin: https://app.example\r\nContent-Type: application/json\r\n", + body, + ); + assert_eq!(r.status, 401, "a listed origin still needs the bearer"); + let r = raw_post( + srv.addr, + &format!("Origin: https://evil.example\r\nAuthorization: Bearer {TOKEN}\r\nContent-Type: application/json\r\n"), + body, + ); + assert_eq!(r.status, 403); + assert!(!acao(&r)); +} + +/// `tool_choice` forcing a call and `response_format` JSON modes are 400s, never ignored. +#[test] +fn unsupported_controls_are_400() { + let srv = start(stub("x"), ServerConfig::default()); + let tools = r#"[{"type":"function","function":{"name":"f","parameters":{"type":"object"}}}]"#; + for extra in [ + format!(r#""tools":{tools},"tool_choice":"required""#), + format!(r#""tools":{tools},"tool_choice":{{"type":"function","function":{{"name":"f"}}}}"#), + r#""response_format":{"type":"json_object"}"#.to_string(), + r#""response_format":{"type":"json_schema","json_schema":{"name":"s","schema":{}}}"# + .to_string(), + r#""n":9"#.to_string(), + r#""n":2,"stream":true"#.to_string(), + ] { + let body = format!(r#"{{"messages":[{{"role":"user","content":"hi"}}],{extra}}}"#); + let r = chat(srv.addr, &body); + assert_eq!(r.status, 400, "{extra}: {}", r.body); + assert!(json(&r)["error"]["message"].is_string()); + } + let r = chat( + srv.addr, + &format!( + r#"{{"messages":[{{"role":"user","content":"hi"}}],"tools":{tools},"tool_choice":"none","response_format":{{"type":"text"}}}}"# + ), + ); + assert_eq!(r.status, 200, "{}", r.body); +} + +/// `n = 2` gives two choices; the stream's `include_usage` chunk has no choices. +#[test] +fn n_and_include_usage() { + let srv = start(stub("ab"), ServerConfig::default()); + let r = chat( + srv.addr, + r#"{"messages":[{"role":"user","content":"hi"}],"n":2}"#, + ); + assert_eq!(r.status, 200, "{}", r.body); + let v = json(&r); + assert_eq!(v["choices"].as_array().unwrap().len(), 2); + assert_eq!(v["choices"][1]["index"], 1); + assert_eq!(v["usage"]["completion_tokens"], 4); + assert!(v["usage"]["completion_tokens_details"]["reasoning_tokens"].is_number()); + let r = chat( + srv.addr, + r#"{"messages":[{"role":"user","content":"hi"}],"stream":true,"stream_options":{"include_usage":true}}"#, + ); + let data = sse_data(&r.body); + assert_eq!(data.last().map(String::as_str), Some("[DONE]")); + let u: Value = serde_json::from_str(&data[data.len() - 2]).unwrap(); + assert_eq!(u["choices"], serde_json::json!([])); + assert!(u["usage"]["total_tokens"].is_number()); +} + +/// The xAI and legacy surfaces on the stub: Responses, language models, tokenize, completions, +/// messages, and a model alias. +#[test] +fn xai_and_legacy_surfaces() { + let srv = start( + stub("hello"), + ServerConfig { + model_aliases: vec!["grok-4.7".into()], + ..ServerConfig::default() + }, + ); + let r = post( + srv.addr, + "/v1/responses", + r#"{"model":"grok-4.7","input":"hi"}"#, + ); + assert_eq!(r.status, 200, "{}", r.body); + let v = json(&r); + assert_eq!(v["object"], "response"); + assert_eq!(v["status"], "completed"); + assert_eq!(v["output"][0]["content"][0]["type"], "output_text"); + assert_eq!(v["output"][0]["content"][0]["text"], "hello"); + assert!(v["usage"]["output_tokens"].is_number()); + + let r = post(srv.addr, "/v1/responses", r#"{"input":"hi","stream":true}"#); + assert_eq!(r.status, 200, "{}", r.body); + assert!(r.body.contains("event: response.completed"), "{}", r.body); + assert!(r.body.contains("event: response.output_text.delta")); + + let r = post( + srv.addr, + "/v1/responses", + r#"{"input":"hi","previous_response_id":"resp_1"}"#, + ); + assert_eq!(r.status, 400, "stateless server refuses chaining"); + + let r = request(srv.addr, "GET", "/v1/language-models", None); + assert_eq!(r.status, 200, "{}", r.body); + let v = json(&r); + assert_eq!(v["models"][0]["id"], "test-model"); + assert_eq!(v["models"][0]["aliases"][0], "grok-4.7"); + let r = request(srv.addr, "GET", "/v1/models/grok-4.7", None); + assert_eq!(r.status, 200, "{}", r.body); + let r = request(srv.addr, "GET", "/v1/models/grok-9", None); + assert_eq!(r.status, 404); + + let r = post( + srv.addr, + "/v1/tokenize-text", + r#"{"text":"ab","model":"grok-4.7"}"#, + ); + assert_eq!(r.status, 200, "{}", r.body); + let v = json(&r); + assert_eq!(v["token_ids"][0]["token_id"], 97); + assert_eq!(v["token_ids"][1]["string_token"], "b"); + + let r = post( + srv.addr, + "/v1/completions", + r#"{"prompt":"hi","max_tokens":8}"#, + ); + assert_eq!(r.status, 200, "{}", r.body); + let v = json(&r); + assert_eq!(v["object"], "text_completion"); + assert_eq!(v["choices"][0]["text"], "hello"); + + let r = post( + srv.addr, + "/v1/messages", + r#"{"max_tokens":8,"messages":[{"role":"user","content":"hi"}]}"#, + ); + assert_eq!(r.status, 200, "{}", r.body); + let v = json(&r); + assert_eq!(v["type"], "message"); + assert_eq!(v["content"][0]["text"], "hello"); + let r = post(srv.addr, "/v1/messages", r#"{"messages":[]}"#); + assert_eq!(r.status, 400); + assert_eq!(json(&r)["type"], "error", "Anthropic error shape"); + + let r = chat( + srv.addr, + r#"{"model":"grok-4.7","messages":[{"role":"user","content":"hi"}]}"#, + ); + assert_eq!(r.status, 200, "{}", r.body); + assert_eq!(json(&r)["model"], "test-model"); +} diff --git a/scripts/xai-compat-probe.sh b/scripts/xai-compat-probe.sh new file mode 100755 index 00000000..ada19dd5 --- /dev/null +++ b/scripts/xai-compat-probe.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Drake Stapleton (AIEN / aien-dev) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# xAI / OpenAI API compatibility probe for aien-serve-http (or any OpenAI-shaped server). +# +# scripts/xai-compat-probe.sh [model] +# base-url e.g. http://127.0.0.1:18291/v1 (a SIDE-PORT copy; port 18091 is refused) +# model model id to request; default: the first id from GET /models +# env XAI_COMPAT_BEARER token to send as "Authorization: Bearer"; default "aien-compat-probe" +# env XAI_COMPAT_OUT keep raw responses in this directory; default: a temp dir, deleted +# env XAI_COMPAT_ORIGIN Origin sent by the CORS preflight; default "https://example.invalid" +# +# Sends request shapes taken from the xAI REST reference (docs.x.ai/developers/rest-api-reference, +# fetched 2026-10-26) and prints one line per check: +# VERDICTTIERCHECKHTTPDETAIL +# VERDICT is PASS or FAIL. TIER says what a FAIL costs: +# CORE an OpenAI/xAI SDK pointed at this base_url breaks +# EXT a common optional field is ignored or refused +# XAI an xAI-only endpoint or shape is missing +# LEGACY an endpoint xAI itself lists as legacy or deprecated +# Every check is engine independent: it tests what the HTTP layer must do whatever the model says, +# so a stub engine is a valid target. Exit: 0 all PASS, 1 any FAIL, 2 refused or unreachable. +set -uo pipefail +base=${1:?usage: xai-compat-probe.sh [model]} +base=${base%/} +case $base in +*:18091 | *:18091/*) echo "refused: port 18091 is the live server; probe a side-port copy" >&2; exit 2 ;; +esac +for t in curl jq; do command -v "$t" >/dev/null || { echo "missing $t" >&2; exit 2; }; done +tok=${XAI_COMPAT_BEARER:-aien-compat-probe} +origin=${XAI_COMPAT_ORIGIN:-https://example.invalid} +if [ -n "${XAI_COMPAT_OUT:-}" ]; then out=$XAI_COMPAT_OUT; mkdir -p "$out"; else + out=$(mktemp -d); trap 'rm -rf "$out"' EXIT +fi +fails=0 passes=0 + +# req NAME METHOD PATH [BODY] [extra curl args...] -> $out/NAME.body, $out/NAME.hdr; prints status. +# PROBE_AUTH overrides the Authorization value for one call; PROBE_AUTH= sends none. +req() { + local name=$1 method=$2 path=$3 body=${4:-} auth=${PROBE_AUTH-"Bearer $tok"} + shift 4 2>/dev/null || shift $# + local args=(-sS -m 30 -X "$method" -o "$out/$name.body" -D "$out/$name.hdr" -w '%{http_code}') + [ -n "$auth" ] && args+=(-H "Authorization: $auth") + [ -n "$body" ] && args+=(-H 'content-type: application/json' --data-binary "$body") + curl "${args[@]}" "$@" "$base$path" 2>/dev/null || true +} +verdict() { # PASS|FAIL tier check http detail + printf '%s\t%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$4" "$5" + if [ "$1" = PASS ]; then passes=$((passes + 1)); else fails=$((fails + 1)); fi +} +# check TIER NAME HTTP JQ-PREDICATE DETAIL: PASS when the body satisfies the predicate +check() { + local tier=$1 name=$2 code=$3 pred=$4 detail=$5 + if jq -e "$pred" "$out/$name.body" >/dev/null 2>&1; then verdict PASS "$tier" "$name" "$code" "$detail" + else verdict FAIL "$tier" "$name" "$code" "$detail; body: $(head -c 160 "$out/$name.body" 2>/dev/null | tr '\n\t' ' ')"; fi +} + +# models +c=$(req models.list GET /models) +[ "$c" = 000 ] && { echo "unreachable: $base" >&2; exit 2; } +model=${2:-$(jq -r '.data[0].id // empty' "$out/models.list.body" 2>/dev/null)} +[ -n "$model" ] || model=unknown-model +check CORE models.list "$c" "$c == 200 and .object == \"list\" and (.data[0].id | type == \"string\")" \ + "GET /models lists ids" +c=$(req models.get GET "/models/$model") +check CORE models.get "$c" "$c == 200 and .id == \"$model\" and .object == \"model\"" "GET /models/{id}" +c=$(req models.language GET /language-models) +check XAI models.language "$c" "$c == 200 and (.models | type == \"array\")" "GET /language-models (xAI)" + +user='{"role":"user","content":"Say hello."}' +sys='{"role":"system","content":"You are a test assistant."}' + +# chat: the xAI quick-start request (OpenAI SDK with base_url swapped) +c=$(req chat.basic POST /chat/completions "{\"model\":\"$model\",\"messages\":[$sys,$user]}") +check CORE chat.basic "$c" '. as $r | '"$c"' == 200 and .object == "chat.completion" and (.id | type == "string") + and .choices[0].message.role == "assistant" and (.choices[0].message.content | type == "string") + and (.choices[0].finish_reason | IN("stop","length","tool_calls")) + and (.usage.prompt_tokens | type == "number") and (.usage.completion_tokens | type == "number")' \ + "POST /chat/completions plain" + +# xAI documents max_tokens as deprecated in favour of max_completion_tokens +c=$(req chat.max_completion_tokens POST /chat/completions \ + "{\"model\":\"$model\",\"messages\":[$user],\"max_completion_tokens\":1}") +check CORE chat.max_completion_tokens "$c" "$c == 200 and .usage.completion_tokens <= 1" "max_completion_tokens=1 bounds output" + +# streaming: every data line is a chunk, text arrives, stream ends with [DONE] +c=$(req chat.stream POST /chat/completions "{\"model\":\"$model\",\"messages\":[$user],\"stream\":true}" -N) +if [ "$c" = 200 ] && [ "$(grep '^data: ' "$out/chat.stream.body" | tail -1)" = 'data: [DONE]' ] && + grep '^data: {' "$out/chat.stream.body" | sed 's/^data: //' | + jq -se 'length > 0 and all(.object == "chat.completion.chunk") and any(.choices[0].delta.content // "" | length > 0)' >/dev/null 2>&1; then + verdict PASS CORE chat.stream "$c" "SSE chunks, content deltas, data: [DONE]" +else verdict FAIL CORE chat.stream "$c" "SSE shape; first line: $(head -c 120 "$out/chat.stream.body" | tr '\n' ' ')"; fi + +# stream_options.include_usage: xAI sends usage in an extra chunk before [DONE] (choices empty) +c=$(req chat.stream_usage POST /chat/completions \ + "{\"model\":\"$model\",\"messages\":[$user],\"stream\":true,\"stream_options\":{\"include_usage\":true}}" -N) +grep '^data: {' "$out/chat.stream_usage.body" | sed 's/^data: //' | jq -s . >"$out/chat.stream_usage.json" 2>/dev/null +if [ "$c" = 200 ] && jq -e 'any(.usage.total_tokens? | type == "number")' "$out/chat.stream_usage.json" >/dev/null 2>&1; then + verdict PASS CORE chat.stream_usage "$c" "usage reaches the client in the stream" +else verdict FAIL CORE chat.stream_usage "$c" "no usage chunk in stream"; fi +if jq -e 'any(.usage != null and (.choices | length == 0))' "$out/chat.stream_usage.json" >/dev/null 2>&1; then + verdict PASS XAI chat.stream_usage_chunk "$c" "usage in its own chunk with empty choices" +else verdict FAIL XAI chat.stream_usage_chunk "$c" "usage not sent as a separate choices:[] chunk"; fi + +# tools: accepted with tool_choice auto; a tool_choice naming an unknown function must be refused +tools='[{"type":"function","function":{"name":"get_weather","description":"Weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]' +c=$(req chat.tools POST /chat/completions "{\"model\":\"$model\",\"messages\":[$user],\"tools\":$tools,\"tool_choice\":\"auto\"}") +check CORE chat.tools "$c" "$c == 200 and .object == \"chat.completion\"" "tools + tool_choice auto accepted" +c=$(req chat.tool_choice_checked POST /chat/completions \ + "{\"model\":\"$model\",\"messages\":[$user],\"tools\":$tools,\"tool_choice\":{\"type\":\"function\",\"function\":{\"name\":\"no_such_tool\"}}}") +check EXT chat.tool_choice_checked "$c" "$c == 400 and (.error.message | type == \"string\")" \ + "tool_choice naming an absent function -> 400 (else tool_choice is ignored)" + +# response_format: a bogus type must be refused if the field is read at all +c=$(req chat.response_format_checked POST /chat/completions \ + "{\"model\":\"$model\",\"messages\":[$user],\"response_format\":{\"type\":\"no_such_format\"}}") +check EXT chat.response_format_checked "$c" "$c == 400" "response_format type no_such_format -> 400 (else field is ignored)" + +c=$(req chat.reasoning_effort POST /chat/completions "{\"model\":\"$model\",\"messages\":[$user],\"reasoning_effort\":\"low\"}") +check EXT chat.reasoning_effort "$c" "$c == 200" "reasoning_effort low accepted" +cp "$out/chat.basic.body" "$out/chat.usage_reasoning_tokens.body" +check XAI chat.usage_reasoning_tokens 200 '(.usage.completion_tokens_details.reasoning_tokens | type == "number")' \ + "usage.completion_tokens_details.reasoning_tokens present" +c=$(req chat.n2 POST /chat/completions "{\"model\":\"$model\",\"messages\":[$user],\"n\":2}") +check EXT chat.n2 "$c" "$c == 200 and (.choices | length == 2)" "n=2 returns two choices" +png='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' +c=$(req chat.image_part POST /chat/completions \ + "{\"model\":\"$model\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"What is this?\"},{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:image/png;base64,$png\"}}]}]}") +check EXT chat.image_part "$c" "$c == 200" "image_url content part accepted" + +# a client written for api.x.ai sends grok model ids +c=$(req chat.grok_model_id POST /chat/completions "{\"model\":\"grok-4.7\",\"messages\":[$user]}") +check XAI chat.grok_model_id "$c" "$c == 200" "model grok-4.7 accepted (alias)" + +# errors: OpenAI/xAI error object +c=$(req error.empty_messages POST /chat/completions "{\"model\":\"$model\",\"messages\":[]}") +check CORE error.empty_messages "$c" "$c == 400 and (.error.message | type == \"string\")" "messages [] -> 400 {error:{message}}" +c=$(req error.unknown_route GET /no-such-route) +check CORE error.unknown_route "$c" "$c == 404 and (.error.message | type == \"string\")" "unknown route -> 404 {error:{message}}" + +# auth: a missing or wrong bearer must be refused +c=$(PROBE_AUTH= req auth.missing POST /chat/completions "{\"model\":\"$model\",\"messages\":[$user]}") +check EXT auth.missing "$c" "$c == 401" "no Authorization -> 401" +c=$(PROBE_AUTH="Bearer wrong-$tok" req auth.wrong POST /chat/completions "{\"model\":\"$model\",\"messages\":[$user]}") +check EXT auth.wrong "$c" "$c == 401" "wrong bearer -> 401" + +# CORS preflight, needed by browser clients +c=$(req cors.preflight OPTIONS /chat/completions '' -H "Origin: $origin" \ + -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: authorization,content-type') +if [ "${c:0:1}" = 2 ] && grep -qi '^access-control-allow-origin:' "$out/cors.preflight.hdr"; then + verdict PASS EXT cors.preflight "$c" "OPTIONS preflight answered" +else verdict FAIL EXT cors.preflight "$c" "no CORS preflight answer"; fi + +# xAI Responses API (the primary xAI inference endpoint) +c=$(req responses.basic POST /responses "{\"model\":\"$model\",\"input\":\"Say hello.\"}") +check XAI responses.basic "$c" "$c == 200 and .object == \"response\" and + any(.output[]?; .type == \"message\" and any(.content[]?; .type == \"output_text\" and (.text | type == \"string\")))" \ + "POST /responses input string" +c=$(req tokenize POST /tokenize-text "{\"model\":\"$model\",\"text\":\"Hello world\"}") +check XAI tokenize "$c" "$c == 200 and (.token_ids[0].token_id | type == \"number\")" "POST /tokenize-text" +c=$(req completions POST /completions "{\"model\":\"$model\",\"prompt\":\"Hello\",\"max_tokens\":4}") +check LEGACY completions "$c" "$c == 200 and .object == \"text_completion\" and (.choices[0].text | type == \"string\")" \ + "POST /completions (legacy)" +c=$(req messages POST /messages "{\"model\":\"$model\",\"max_tokens\":16,\"messages\":[$user]}" -H 'anthropic-version: 2023-06-01') +check LEGACY messages "$c" "$c == 200 and .type == \"message\" and (.content[0].text | type == \"string\")" \ + "POST /messages Anthropic shape (xAI: deprecated)" + +printf 'SUMMARY\tbase=%s\tmodel=%s\tpass=%d\tfail=%d\n' "$base" "$model" "$passes" "$fails" +[ "$fails" -eq 0 ] ```