Add Anthropic Messages endpoint (/v1/messages), stream + non-stream

- api::anthropic: AnthropicRequest -> internal ChatRequest (system, text/image/
  thinking/tool_use/tool_result blocks, tools input_schema->parameters,
  tool_choice, sampling, stop_sequences); ChatResponse -> Anthropic message
  (thinking/text/tool_use blocks, stop_reason end_turn/max_tokens/tool_use, usage).
- AnthropicStream translator: message_start / content_block_start/delta/stop /
  message_delta / message_stop, with block-index state.
- Refactor service.stream to yield semantic ChatChunk (+ prompt_len); SSE
  serialization and the terminal [DONE] moved to the OpenAI route. ChatChunk
  carries a #[serde(skip)] usage field for presenters (invisible on the OpenAI
  wire). The same engine-driving (abort/stop/disconnect) feeds both formats.
- Route POST /v1/messages; the OpenAI wire is unchanged.

7 new tests (5 conversion unit + 2 HTTP end-to-end); 87 green + 2 ignored;
clippy clean; cargo fmt applied. README updated.
Core cases faithful; deferred: defer_loading/tool_addition/tool_reference,
thinking budget_tokens, prompt-cache token accounting.
This commit is contained in:
adm committed 2026-11-24 19:58:29 +01:00
1 parent b6619d30de
commit 9e6d44fa1a
7 files changed
+758 -24

No files matched your search

+13 -2
View File
@@ -47,6 +47,15 @@ OpenAI-compatible endpoints:
- `POST /v1/chat/completions` — streaming (SSE) and non-streaming.
- `GET /v1/models`, `GET /health`.
Anthropic-compatible endpoint:
- `POST /v1/messages` — the Anthropic Messages API (streaming + non-streaming),
translated onto the same engine: `system`, text/image/thinking/tool_use/
tool_result content blocks, tools (`input_schema`), `tool_choice`, sampling and
`stop_sequences`. Responses use Anthropic content blocks and `stop_reason`
(`end_turn` / `max_tokens` / `tool_use`); streaming emits the
`message_start` / `content_block_*` / `message_delta` / `message_stop` sequence.
Behavior implemented and validated against the real Inkling engine:
- **Chain-of-thought separation** — thinking is streamed live as
@@ -121,14 +130,16 @@ is preserved untouched and reported as ignored — unknown keys never break star
## Status
Working and tested (80 tests, plus 2 real-file tests run on demand). Text, images
Working and tested (87 tests, plus 2 real-file tests run on demand). Text, images
and the full client-side tool loop have been validated live against the real
Inkling engine.
Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function
returns a clear 400), multi-slot batching, logprobs / structured output, automatic
engine restart after a crash, a full SSRF guard against DNS rebinding, and the
Anthropic / Responses native endpoints.
OpenAI Responses native endpoint. The Anthropic adapter covers the core cases but
not yet the `defer_loading` / `tool_addition` / `tool_reference` tool machinery, the
thinking `budget_tokens` mapping, or prompt-cache token accounting.
## License and credits
+553
View File
@@ -0,0 +1,553 @@
//! The Anthropic Messages surface (`POST /v1/messages`).
//!
//! A translation layer over the same [`ChatService`] the OpenAI route uses: an
//! Anthropic request is converted to the internal [`ChatRequest`], and the
//! engine's output is presented back as Anthropic content blocks (thinking /
//! text / tool_use) — non-streaming as one message, streaming as the
//! `message_start` / `content_block_*` / `message_delta` / `message_stop` event
//! sequence. Faithful to `serve/frontend.py:anthropic_to_messages` and
//! `serve/server.py:anthropic_events` for the core cases.
//!
//! Not yet ported (documented gaps): `defer_loading` / `tool_addition` /
//! `tool_reference` tool machinery, the thinking `budget_tokens` -> hold-budget
//! mapping, and the prompt-cache token accounting (`cache_creation/read`).
use axum::response::sse::Event;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value as Json};
use super::types::{
ApiErrorEnvelope, ChatChunk, ChatMessage, ChatRequest, ChatResponse, FinishReason,
FunctionCall, Role, Stop, ToolCall,
};
/// `POST /v1/messages` body (the fields we recognise).
#[derive(Debug, Clone, Deserialize)]
pub struct AnthropicRequest {
#[serde(default)]
pub model: String,
#[serde(default)]
pub messages: Vec<AnthropicMessage>,
/// A string, or an array of text blocks.
#[serde(default)]
pub system: Option<Json>,
#[serde(default)]
pub max_tokens: Option<u32>,
#[serde(default)]
pub stream: bool,
#[serde(default)]
pub temperature: Option<f64>,
#[serde(default)]
pub top_p: Option<f64>,
#[serde(default)]
pub top_k: Option<u32>,
#[serde(default)]
pub stop_sequences: Option<Vec<String>>,
#[serde(default)]
pub tools: Option<Json>,
#[serde(default)]
pub tool_choice: Option<Json>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AnthropicMessage {
pub role: String,
/// A string, or an array of content blocks.
#[serde(default)]
pub content: Json,
}
impl AnthropicRequest {
/// Convert to the internal OpenAI-shaped request the service drives.
pub fn to_chat_request(&self) -> Result<ChatRequest, ApiErrorEnvelope> {
let mut messages = Vec::new();
if let Some(sys) = &self.system {
let text = text_of(sys);
if !text.is_empty() {
messages.push(msg(Role::System, Json::String(text)));
}
}
for m in &self.messages {
convert_message(m, &mut messages)?;
}
let tools = self.tools.as_ref().map(tools_to_openai);
let tool_choice = match &self.tool_choice {
None => None,
Some(c) => Some(tool_choice_to_openai(c)?),
};
Ok(ChatRequest {
model: self.model.clone(),
messages,
stream: self.stream,
temperature: self.temperature,
top_p: self.top_p,
max_tokens: self.max_tokens,
max_completion_tokens: None,
frequency_penalty: None,
presence_penalty: None,
seed: None,
top_k: self.top_k,
min_p: None,
repetition_penalty: None,
stop: self.stop_sequences.clone().map(Stop::Many),
tools,
tool_choice,
})
}
}
fn msg(role: Role, content: Json) -> ChatMessage {
ChatMessage {
role,
content: Some(content),
tool_call_id: None,
tool_calls: None,
name: None,
reasoning_content: None,
}
}
/// The plain text of a string-or-text-blocks value (system, tool_result, ...).
fn text_of(v: &Json) -> String {
if let Some(s) = v.as_str() {
return s.to_string();
}
let mut out = String::new();
if let Some(arr) = v.as_array() {
for b in arr {
if b.get("type").and_then(|t| t.as_str()) == Some("text") {
out.push_str(b.get("text").and_then(|t| t.as_str()).unwrap_or(""));
}
}
}
out
}
fn convert_message(
m: &AnthropicMessage,
out: &mut Vec<ChatMessage>,
) -> Result<(), ApiErrorEnvelope> {
let role = match m.role.as_str() {
"user" => Role::User,
"assistant" => Role::Assistant,
other => {
return Err(ApiErrorEnvelope::new(
format!("unsupported Anthropic role: {other}"),
"invalid_request_error",
None,
))
}
};
if let Some(s) = m.content.as_str() {
out.push(msg(role, Json::String(s.to_string())));
return Ok(());
}
let blocks = m.content.as_array().cloned().unwrap_or_default();
let mut text = String::new();
let mut reasoning = String::new();
let mut calls: Vec<ToolCall> = Vec::new();
let mut parts: Vec<Json> = Vec::new();
let mut has_image = false;
for b in &blocks {
match b.get("type").and_then(|t| t.as_str()).unwrap_or("") {
"text" => {
let t = b.get("text").and_then(|t| t.as_str()).unwrap_or("");
text.push_str(t);
parts.push(json!({"type": "text", "text": t}));
}
"image" => {
if let Some(part) = image_to_openai(b) {
parts.push(part);
has_image = true;
}
}
"thinking" => {
reasoning.push_str(b.get("thinking").and_then(|t| t.as_str()).unwrap_or(""));
}
"tool_use" => {
let name = b
.get("name")
.and_then(|n| n.as_str())
.unwrap_or("")
.to_string();
let id = b
.get("id")
.and_then(|i| i.as_str())
.unwrap_or("")
.to_string();
let input = b.get("input").cloned().unwrap_or_else(|| json!({}));
calls.push(ToolCall {
id,
kind: "function".to_string(),
function: FunctionCall {
name,
arguments: input.to_string(),
},
});
}
"tool_result" => {
let tid = b
.get("tool_use_id")
.and_then(|i| i.as_str())
.unwrap_or("")
.to_string();
let content = Json::String(text_of(b.get("content").unwrap_or(&Json::Null)));
let mut tm = msg(Role::Tool, content);
tm.tool_call_id = Some(tid);
out.push(tm);
}
_ => {}
}
}
if !text.is_empty() || !calls.is_empty() || !reasoning.is_empty() || !parts.is_empty() {
let content = if has_image {
Json::Array(parts)
} else {
Json::String(text)
};
let mut message = msg(role, content);
if !reasoning.is_empty() {
message.reasoning_content = Some(reasoning);
}
if !calls.is_empty() {
message.tool_calls = Some(calls);
}
out.push(message);
}
Ok(())
}
/// Anthropic image block -> an OpenAI `image_url` part (base64 folded to a data
/// URL), which the formatter's image bridge already materializes.
fn image_to_openai(b: &Json) -> Option<Json> {
let src = b.get("source")?;
if src.get("type").and_then(|t| t.as_str()) == Some("base64") {
let mt = src
.get("media_type")
.and_then(|m| m.as_str())
.unwrap_or("image/png");
let data = src.get("data").and_then(|d| d.as_str())?;
Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mt};base64,{data}")}}))
} else {
let url = src.get("url").and_then(|u| u.as_str())?;
Some(json!({"type": "image_url", "image_url": {"url": url}}))
}
}
/// Anthropic tools (`input_schema`) -> OpenAI function tools (`parameters`).
fn tools_to_openai(tools: &Json) -> Json {
let arr = tools.as_array().cloned().unwrap_or_default();
Json::Array(
arr.iter()
.map(|t| {
json!({
"type": "function",
"function": {
"name": t.get("name").and_then(|n| n.as_str()).unwrap_or(""),
"description": t.get("description").and_then(|d| d.as_str()).unwrap_or(""),
"parameters": t.get("input_schema").cloned().unwrap_or_else(|| json!({})),
}
})
})
.collect(),
)
}
/// Anthropic `tool_choice` -> OpenAI's. `any`/`tool` map to `required`/named,
/// which the Inkling formatter rejects honestly (no native forcing yet).
fn tool_choice_to_openai(c: &Json) -> Result<Json, ApiErrorEnvelope> {
match c.get("type").and_then(|t| t.as_str()).unwrap_or("auto") {
"auto" => Ok(Json::String("auto".into())),
"none" => Ok(Json::String("none".into())),
"any" => Ok(Json::String("required".into())),
"tool" => {
let name = c.get("name").and_then(|n| n.as_str()).unwrap_or("");
Ok(json!({"type": "function", "function": {"name": name}}))
}
other => Err(ApiErrorEnvelope::new(
format!("unknown tool_choice type: {other}"),
"invalid_request_error",
None,
)),
}
}
/// Non-streaming Anthropic response (`type: "message"`).
#[derive(Debug, Clone, Serialize)]
pub struct AnthropicResponse {
pub id: String,
#[serde(rename = "type")]
pub kind: &'static str,
pub role: &'static str,
pub model: String,
pub content: Vec<Json>,
pub stop_reason: Option<&'static str>,
pub stop_sequence: Option<String>,
pub usage: AnthropicUsage,
}
#[derive(Debug, Clone, Serialize)]
pub struct AnthropicUsage {
pub input_tokens: u32,
pub output_tokens: u32,
}
/// Build an Anthropic message from the internal completion response.
pub fn from_chat_response(resp: &ChatResponse) -> AnthropicResponse {
let mut content = Vec::new();
let mut stop_reason = "end_turn";
if let Some(choice) = resp.choices.first() {
let m = &choice.message;
if let Some(r) = &m.reasoning_content {
if !r.is_empty() {
content.push(json!({"type": "thinking", "thinking": r, "signature": ""}));
}
}
if let Some(Some(s)) = m.content.as_ref().map(|c| c.as_str()) {
if !s.is_empty() {
content.push(json!({"type": "text", "text": s}));
}
}
if let Some(calls) = &m.tool_calls {
for tc in calls {
let input: Json =
serde_json::from_str(&tc.function.arguments).unwrap_or_else(|_| json!({}));
content.push(json!({"type": "tool_use", "id": tc.id, "name": tc.function.name, "input": input}));
}
}
stop_reason = stop_reason_of(choice.finish_reason);
}
AnthropicResponse {
id: message_id(),
kind: "message",
role: "assistant",
model: resp.model.clone(),
content,
stop_reason: Some(stop_reason),
stop_sequence: None,
usage: AnthropicUsage {
input_tokens: resp.usage.prompt_tokens,
output_tokens: resp.usage.completion_tokens,
},
}
}
fn stop_reason_of(f: FinishReason) -> &'static str {
match f {
FinishReason::ToolCalls => "tool_use",
FinishReason::Length => "max_tokens",
_ => "end_turn",
}
}
fn message_id() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
let n = SEQ.fetch_add(1, Ordering::Relaxed);
format!("msg_{nanos:016x}{n:08x}")
}
/// Stateful translator: internal stream chunks -> Anthropic SSE events. Blocks
/// are opened on the first piece of a kind and closed when the kind changes (or
/// the turn finishes); each tool call is its own `tool_use` block.
pub struct AnthropicStream {
id: String,
model: String,
input_tokens: u32,
index: i32,
open: Option<&'static str>,
}
impl AnthropicStream {
pub fn new(model: String, input_tokens: u32) -> Self {
Self {
id: message_id(),
model,
input_tokens,
index: -1,
open: None,
}
}
/// The opening `message_start` event.
pub fn start(&self) -> Event {
let message = json!({
"type": "message", "id": self.id, "role": "assistant", "model": self.model,
"content": [], "stop_reason": null, "stop_sequence": null,
"usage": {"input_tokens": self.input_tokens, "output_tokens": 0},
});
sse(
"message_start",
json!({"type": "message_start", "message": message}),
)
}
/// Translate one chunk into zero or more events.
pub fn on_chunk(&mut self, chunk: &ChatChunk) -> Vec<Event> {
let mut evs = Vec::new();
let Some(choice) = chunk.choices.first() else {
return evs;
};
let d = &choice.delta;
if let Some(r) = &d.reasoning_content {
if !r.is_empty() {
self.switch(
&mut evs,
"thinking",
json!({"type": "thinking", "thinking": "", "signature": ""}),
);
evs.push(sse("content_block_delta", json!({"type": "content_block_delta", "index": self.index, "delta": {"type": "thinking_delta", "thinking": r}})));
}
}
if let Some(c) = &d.content {
if !c.is_empty() {
self.switch(&mut evs, "text", json!({"type": "text", "text": ""}));
evs.push(sse("content_block_delta", json!({"type": "content_block_delta", "index": self.index, "delta": {"type": "text_delta", "text": c}})));
}
}
if let Some(arr) = d.tool_calls.as_ref().and_then(|t| t.as_array()) {
for call in arr {
let id = call.get("id").and_then(|i| i.as_str()).unwrap_or("");
let func = call.get("function");
let name = func
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.unwrap_or("");
let args = func
.and_then(|f| f.get("arguments"))
.and_then(|a| a.as_str())
.unwrap_or("{}");
self.close(&mut evs);
self.index += 1;
self.open = Some("tool_use");
evs.push(sse("content_block_start", json!({"type": "content_block_start", "index": self.index, "content_block": {"type": "tool_use", "id": id, "name": name, "input": {}}})));
evs.push(sse("content_block_delta", json!({"type": "content_block_delta", "index": self.index, "delta": {"type": "input_json_delta", "partial_json": args}})));
}
}
if let Some(finish) = choice.finish_reason {
self.close(&mut evs);
let out = chunk
.usage
.as_ref()
.map(|u| u.completion_tokens)
.unwrap_or(0);
evs.push(sse("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": stop_reason_of(finish), "stop_sequence": null}, "usage": {"output_tokens": out}})));
evs.push(sse("message_stop", json!({"type": "message_stop"})));
}
evs
}
fn switch(&mut self, evs: &mut Vec<Event>, kind: &'static str, block: Json) {
if self.open != Some(kind) {
self.close(evs);
self.index += 1;
self.open = Some(kind);
evs.push(sse(
"content_block_start",
json!({"type": "content_block_start", "index": self.index, "content_block": block}),
));
}
}
fn close(&mut self, evs: &mut Vec<Event>) {
if self.open.is_some() {
evs.push(sse(
"content_block_stop",
json!({"type": "content_block_stop", "index": self.index}),
));
self.open = None;
}
}
}
fn sse(name: &str, data: Json) -> Event {
Event::default()
.event(name)
.json_data(data)
.unwrap_or_else(|_| Event::default().event(name).data("{}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn req(v: Json) -> AnthropicRequest {
serde_json::from_value(v).unwrap()
}
#[test]
fn system_and_text_convert() {
let r = req(json!({
"model": "m", "max_tokens": 100,
"system": "be brief",
"messages": [{"role": "user", "content": "hi"}]
}));
let c = r.to_chat_request().unwrap();
assert_eq!(c.messages[0].role, Role::System);
assert_eq!(c.messages[0].text(), Some("be brief"));
assert_eq!(c.messages[1].role, Role::User);
assert_eq!(c.messages[1].text(), Some("hi"));
assert_eq!(c.max_tokens, Some(100));
}
#[test]
fn tool_use_and_result_convert() {
let r = req(json!({
"model": "m", "max_tokens": 10,
"messages": [
{"role": "assistant", "content": [
{"type": "tool_use", "id": "t1", "name": "get_weather", "input": {"city": "Roma"}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "t1", "content": "sunny"}
]}
]
}));
let c = r.to_chat_request().unwrap();
let calls = c.messages[0].tool_calls.as_ref().unwrap();
assert_eq!(calls[0].function.name, "get_weather");
assert_eq!(calls[0].function.arguments, r#"{"city":"Roma"}"#);
assert_eq!(c.messages[1].role, Role::Tool);
assert_eq!(c.messages[1].tool_call_id.as_deref(), Some("t1"));
assert_eq!(c.messages[1].text(), Some("sunny"));
}
#[test]
fn tools_and_choice_convert() {
let r = req(json!({
"model": "m", "max_tokens": 10,
"messages": [{"role": "user", "content": "hi"}],
"tools": [{"name": "f", "description": "d", "input_schema": {"type": "object"}}],
"tool_choice": {"type": "auto"}
}));
let c = r.to_chat_request().unwrap();
let tools = c.tools.unwrap();
assert_eq!(tools[0]["function"]["name"], "f");
assert_eq!(tools[0]["function"]["parameters"]["type"], "object");
assert_eq!(c.tool_choice.unwrap(), json!("auto"));
}
#[test]
fn image_block_becomes_data_url() {
let r = req(json!({
"model": "m", "max_tokens": 10,
"messages": [{"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "QUJD"}}
]}]
}));
let c = r.to_chat_request().unwrap();
let parts = c.messages[0].content.as_ref().unwrap().as_array().unwrap();
assert_eq!(parts[0]["image_url"]["url"], "data:image/png;base64,QUJD");
}
#[test]
fn stop_reason_mapping() {
assert_eq!(stop_reason_of(FinishReason::ToolCalls), "tool_use");
assert_eq!(stop_reason_of(FinishReason::Length), "max_tokens");
assert_eq!(stop_reason_of(FinishReason::Stop), "end_turn");
}
}
+1
View File
@@ -4,6 +4,7 @@
//! [`formatter`] the token<->text seam, [`service`] the completion logic, and
//! [`routes`] the axum router.
pub mod anthropic;
pub mod formatter;
pub mod routes;
pub mod service;
+69 -6
View File
@@ -6,11 +6,12 @@
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{sse::Sse, IntoResponse, Json};
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
use axum::routing::{get, post};
use axum::Router;
use serde::de::DeserializeOwned;
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
use super::service::ChatService;
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
@@ -25,6 +26,7 @@ pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router {
.route("/health", get(health))
.route("/v1/models", get(models))
.route("/v1/chat/completions", post(chat_completions))
.route("/v1/messages", post(messages))
.with_state(AppState { service })
.layer(axum::middleware::from_fn_with_state(auth, auth_middleware))
}
@@ -181,12 +183,22 @@ async fn chat_completions(
if req.stream {
match st.service.stream(&req).await {
Ok(stream) => {
Ok((stream, _prompt_len)) => {
use futures::StreamExt;
// Sse wants Stream<Item = Result<Event, E>>; our channel yields
// plain Events, so lift them (errors are infallible here).
let stream = stream.map(Ok::<_, std::convert::Infallible>);
Sse::new(stream)
// Serialize each semantic chunk to an SSE event, then append the
// terminal [DONE] the OpenAI wire expects.
let events = stream
.map(|chunk| match Event::default().json_data(&chunk) {
Ok(ev) => Ok::<_, std::convert::Infallible>(ev),
Err(e) => {
tracing::error!(error = %e, "failed to serialize SSE chunk");
Ok(Event::default().data("{}"))
}
})
.chain(futures::stream::once(async {
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
}));
Sse::new(events)
.keep_alive(
axum::response::sse::KeepAlive::new()
.interval(std::time::Duration::from_secs(10))
@@ -204,6 +216,57 @@ async fn chat_completions(
}
}
/// `POST /v1/messages` — the Anthropic Messages surface, translated onto the
/// same service. Non-streaming returns one message; streaming emits the
/// Anthropic event sequence.
async fn messages(
State(st): State<AppState>,
raw: axum::extract::Request,
) -> axum::response::Response {
let areq: AnthropicRequest = match json_body(raw).await {
Ok(r) => r,
Err(e) => return e.into_response(),
};
let req = match areq.to_chat_request() {
Ok(r) => r,
Err(env) => return Error::from_envelope(env).into_response(),
};
if req.messages.is_empty() {
return Error::bad_request("`messages` must not be empty").into_response();
}
if req.stream {
match st.service.stream(&req).await {
Ok((stream, prompt_len)) => {
use futures::StreamExt;
let mut tr = AnthropicStream::new(req.model.clone(), prompt_len);
let start = tr.start();
let events =
futures::stream::once(async move { Ok::<_, std::convert::Infallible>(start) })
.chain(stream.flat_map(move |chunk| {
let evs = tr.on_chunk(&chunk);
futures::stream::iter(
evs.into_iter().map(Ok::<_, std::convert::Infallible>),
)
}));
Sse::new(events)
.keep_alive(
axum::response::sse::KeepAlive::new()
.interval(std::time::Duration::from_secs(10))
.text("ping"),
)
.into_response()
}
Err(env) => Error::from_envelope(env).into_response(),
}
} else {
match st.service.complete(&req).await {
Ok(resp) => Json(anthropic::from_chat_response(&resp)).into_response(),
Err(env) => Error::from_envelope(env).into_response(),
}
}
}
/// Read and deserialize a JSON body, mapping any failure to our error type.
async fn json_body<T: DeserializeOwned>(req: axum::extract::Request) -> Result<T, Error> {
let bytes = axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024)
+32 -16
View File
@@ -9,7 +9,6 @@
use std::sync::Arc;
use axum::response::sse::Event;
use futures::Stream;
use tokio::sync::mpsc::UnboundedSender;
use tokio_stream::wrappers::UnboundedReceiverStream;
@@ -111,8 +110,9 @@ impl ChatService {
pub async fn stream(
&self,
req: &ChatRequest,
) -> Result<impl Stream<Item = Event> + Send + 'static, ApiErrorEnvelope> {
) -> Result<(impl Stream<Item = ChatChunk> + Send + 'static, u32), ApiErrorEnvelope> {
let prompt = self.build_prompt_blocking(req).await?;
let prompt_len = prompt.ids.len() as u32;
let id = completion_id();
let created = now_unix();
@@ -120,7 +120,7 @@ impl ChatService {
// Unbounded: the token callback is synchronous and must never block on
// (or lose events to) backpressure; a request is bounded by max_new.
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<ChatChunk>();
let engine = self.engine.clone();
let fmt = self.fmt.clone();
@@ -145,6 +145,7 @@ impl ChatService {
..Default::default()
},
None,
None,
);
let mut dec = fmt.decoder();
@@ -201,6 +202,7 @@ impl ChatService {
..Default::default()
},
None,
None,
);
}
@@ -214,15 +216,30 @@ impl ChatService {
Err(_) => FinishReason::Stop,
}
};
send(&tx, &id, created, &model, Delta::default(), Some(finish));
let _ = tx.send(Event::default().data("[DONE]"));
let completion = match &gen {
Ok(out) => out
.done
.as_ref()
.map(|d| d.generated)
.unwrap_or(out.tokens.len() as u32),
Err(_) => 0,
};
send(
&tx,
&id,
created,
&model,
Delta::default(),
Some(finish),
Some(Usage::new(prompt_len, completion)),
);
if let Err(e) = gen {
tracing::warn!(error = %e, "streaming generation ended in error");
}
});
Ok(UnboundedReceiverStream::new(rx))
Ok((UnboundedReceiverStream::new(rx), prompt_len))
}
/// Run `build_prompt` off the async worker: image materialization does
@@ -265,7 +282,7 @@ impl Drop for TempFilesGuard {
}
fn send_piece(
tx: &UnboundedSender<Event>,
tx: &UnboundedSender<ChatChunk>,
id: &str,
created: u64,
model: &str,
@@ -314,17 +331,20 @@ fn send_piece(
}
_ => return,
};
send(tx, id, created, model, delta, None);
send(tx, id, created, model, delta, None, None);
}
/// Push one SSE `data:` event holding a `chat.completion.chunk`.
/// Push one semantic `chat.completion.chunk` onto the stream. Serialization to
/// SSE (and the terminal `[DONE]`) is the presenter's job (OpenAI route or the
/// Anthropic adapter), so the same chunks feed both wire formats.
fn send(
tx: &UnboundedSender<Event>,
tx: &UnboundedSender<ChatChunk>,
id: &str,
created: u64,
model: &str,
delta: Delta,
finish: Option<FinishReason>,
usage: Option<Usage>,
) {
let body = ChatChunk {
id: id.to_string(),
@@ -336,13 +356,9 @@ fn send(
delta,
finish_reason: finish,
}],
usage,
};
match Event::default().json_data(&body) {
Ok(ev) => {
let _ = tx.send(ev);
}
Err(e) => tracing::error!(error = %e, "failed to serialize SSE chunk"),
}
let _ = tx.send(body);
}
fn finish_reason(outcome: &Outcome, max_new: u32) -> FinishReason {
+4
View File
@@ -238,6 +238,10 @@ pub struct ChatChunk {
pub created: u64,
pub model: String,
pub choices: Vec<StreamChoice>,
/// Carried internally for presenters that need final counts (e.g. the
/// Anthropic adapter); never serialized on the OpenAI wire.
#[serde(skip)]
pub usage: Option<Usage>,
}
/// `GET /v1/models` element and envelope.
+86
View File
@@ -431,3 +431,89 @@ async fn allowed_hosts_is_enforced() {
let (status, _) = post_with_headers(&app, &[("host", "evil.example")]).await;
assert_eq!(status, StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn anthropic_non_stream_message() {
let app = build_app().await;
let req = Request::builder()
.method(Method::POST)
.uri("/v1/messages")
.header(CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({"model":"test-model","max_tokens":64,"messages":[{"role":"user","content":"hi"}]})
.to_string(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["type"], "message");
assert_eq!(v["role"], "assistant");
assert_eq!(v["content"][0]["type"], "text");
assert_eq!(v["content"][0]["text"], "efghi");
assert_eq!(v["stop_reason"], "end_turn");
assert_eq!(v["usage"]["output_tokens"], 5);
}
#[tokio::test]
async fn anthropic_stream_event_sequence() {
let app = build_app().await;
let req = Request::builder()
.method(Method::POST)
.uri("/v1/messages")
.header(CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({"model":"test-model","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]})
.to_string(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let text = String::from_utf8_lossy(&bytes);
for name in [
"message_start",
"content_block_start",
"content_block_delta",
"content_block_stop",
"message_delta",
"message_stop",
] {
assert!(
text.contains(&format!("event: {name}")),
"missing {name}: {text}"
);
}
// reassemble the text deltas and read the final stop_reason
let mut content = String::new();
let mut stop = None;
for block in text.split("\n\n") {
let mut event = "";
let mut data = "";
for line in block.lines() {
if let Some(e) = line.strip_prefix("event: ") {
event = e;
}
if let Some(d) = line.strip_prefix("data: ") {
data = d;
}
}
if data.is_empty() {
continue;
}
let v: serde_json::Value = serde_json::from_str(data).unwrap();
if event == "content_block_delta" && v["delta"]["type"] == "text_delta" {
content.push_str(v["delta"]["text"].as_str().unwrap_or(""));
}
if event == "message_delta" {
stop = v["delta"]["stop_reason"].as_str().map(str::to_string);
}
}
assert_eq!(content, "efghi");
assert_eq!(stop.as_deref(), Some("end_turn"));
}