Files
adm 9e6d44fa1a 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.
2026-11-24 19:58:29 +01:00

520 lines
17 KiB
Rust

//! End-to-end tests of the OpenAI surface: HTTP request -> engine (mock) ->
//! HTTP response, non-stream and stream, driven through a trivial formatter so
//! the whole API layer is exercised without the real tokenizer.
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode};
use tower::ServiceExt; // for `oneshot`
use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt};
use strata_ctl::api::service::ChatService;
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
use strata_ctl::engine::Engine;
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
/// A formatter with no dialect: the prompt is the last message's bytes; each
/// token id < 256 decodes to that byte as a char, always as "content".
struct ByteFormatter;
impl Formatter for ByteFormatter {
fn model_name(&self) -> &str {
"test-model"
}
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
let text = req
.messages
.iter()
.rev()
.find_map(|m| m.text())
.unwrap_or("")
.to_string();
Ok(Prompt {
ids: text.bytes().map(u32::from).collect(),
max_new: req.max_new(64),
sampling: Default::default(),
temp_files: Vec::new(),
})
}
fn decoder(&self) -> Box<dyn Decoder> {
Box::new(ByteDecoder)
}
}
struct ByteDecoder;
impl Decoder for ByteDecoder {
fn push(&mut self, id: u32) -> Vec<Piece> {
if id < 256 {
vec![Piece::Content(char::from(id as u8).to_string())]
} else {
Vec::new()
}
}
fn finish(&mut self, _reason: Option<&str>) -> Vec<Piece> {
Vec::new()
}
}
/// Drives the mock's long, STOP-interruptible generation (ids contain 888888).
struct LongFormatter;
impl Formatter for LongFormatter {
fn model_name(&self) -> &str {
"test-model"
}
fn build_prompt(&self, _req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
Ok(Prompt {
ids: vec![888888],
max_new: 100000,
sampling: Default::default(),
temp_files: Vec::new(),
})
}
fn decoder(&self) -> Box<dyn Decoder> {
Box::new(ByteDecoder)
}
}
async fn build_app() -> axum::Router {
let engine = Arc::new(
Engine::start(
"python3",
&[MOCK.to_string()],
None,
Duration::from_secs(10),
)
.await
.expect("mock engine starts"),
);
let svc = ChatService::new(engine, Arc::new(ByteFormatter));
strata_ctl::api::router(svc)
}
async fn post_json(app: &axum::Router, body: serde_json::Value) -> (StatusCode, String) {
let req = Request::builder()
.method(Method::POST)
.uri("/v1/chat/completions")
.header(CONTENT_TYPE, "application/json")
.body(Body::from(body.to_string()))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
(status, String::from_utf8_lossy(&bytes).into_owned())
}
#[tokio::test]
async fn models_lists_the_served_model() {
let app = build_app().await;
let resp = app
.oneshot(
Request::builder()
.uri("/v1/models")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["object"], "list");
assert_eq!(json["data"][0]["id"], "test-model");
}
#[tokio::test]
async fn non_stream_completion() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}]
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(json["object"], "chat.completion");
// the mock's default path emits ids 101..105 -> 'e','f','g','h','i'
assert_eq!(json["choices"][0]["message"]["content"], "efghi");
assert_eq!(json["choices"][0]["message"]["role"], "assistant");
assert_eq!(json["choices"][0]["finish_reason"], "stop");
assert_eq!(json["usage"]["completion_tokens"], 5);
assert_eq!(
json["usage"]["total_tokens"],
json["usage"]["prompt_tokens"].as_u64().unwrap() + 5
);
assert!(json["id"].as_str().unwrap().starts_with("chatcmpl-"));
}
#[tokio::test]
async fn stream_completion_is_sse() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}],
"stream": true
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
// every payload line is `data: ...`; the stream ends with `data: [DONE]`
let data_lines: Vec<&str> = text
.lines()
.filter(|l| l.starts_with("data: "))
.map(|l| &l["data: ".len()..])
.collect();
assert!(
data_lines.last().copied() == Some("[DONE]"),
"no [DONE]: {text}"
);
// first chunk announces the role, the last (before [DONE]) the finish reason
let first: serde_json::Value = serde_json::from_str(data_lines[0]).unwrap();
assert_eq!(first["object"], "chat.completion.chunk");
assert_eq!(first["choices"][0]["delta"]["role"], "assistant");
// reassemble content across the middle chunks
let mut content = String::new();
let mut finish = None;
for line in &data_lines[..data_lines.len() - 1] {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
if let Some(c) = v["choices"][0]["delta"]["content"].as_str() {
content.push_str(c);
}
if let Some(f) = v["choices"][0]["finish_reason"].as_str() {
finish = Some(f.to_string());
}
}
assert_eq!(content, "efghi");
assert_eq!(finish.as_deref(), Some("stop"));
}
#[tokio::test]
async fn empty_messages_is_bad_request() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({"model": "test-model", "messages": []}),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(json["error"]["type"], "invalid_request_error");
}
#[tokio::test]
async fn malformed_json_is_openai_error() {
let app = build_app().await;
let req = Request::builder()
.method(Method::POST)
.uri("/v1/chat/completions")
.header(CONTENT_TYPE, "application/json")
.body(Body::from("{not json"))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert!(json["error"]["message"]
.as_str()
.unwrap()
.contains("invalid JSON"));
}
#[tokio::test]
async fn stream_aborts_on_client_disconnect() {
let engine = Arc::new(
Engine::start(
"python3",
&[MOCK.to_string()],
None,
Duration::from_secs(10),
)
.await
.expect("mock engine starts"),
);
let svc = ChatService::new(engine.clone(), Arc::new(LongFormatter));
let app = strata_ctl::api::router(svc);
let req = Request::builder()
.method(Method::POST)
.uri("/v1/chat/completions")
.header(CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "go"}],
"stream": true
})
.to_string(),
))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// Simulate the client vanishing: drop the SSE body without reading it. The
// receiver is dropped, the disconnect select fires, the engine is aborted.
drop(resp);
// Poll (non-mutating) until the engine is idle: the long generation must
// have been stopped, not left running for the full 100000 tokens. Bounded
// wait so the test is robust under parallel load.
let mut idle = false;
for _ in 0..100 {
if engine.is_idle() {
idle = true;
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
assert!(idle, "engine still busy after client disconnect");
let _ = engine.shutdown().await;
}
#[tokio::test]
async fn stop_sequence_truncates_content() {
let app = build_app().await;
// the mock's default answer is "efghi"; stop "gh" cuts it to "ef"
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}],
"stop": ["gh"]
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(json["choices"][0]["message"]["content"], "ef");
assert_eq!(json["choices"][0]["finish_reason"], "stop");
}
#[tokio::test]
async fn stop_sequence_truncates_stream() {
let app = build_app().await;
let (status, text) = post_json(
&app,
serde_json::json!({
"model": "test-model",
"messages": [{"role": "user", "content": "hi"}],
"stop": ["gh"],
"stream": true
}),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {text}");
let data_lines: Vec<&str> = text
.lines()
.filter(|l| l.starts_with("data: "))
.map(|l| &l["data: ".len()..])
.collect();
assert_eq!(data_lines.last().copied(), Some("[DONE]"));
let mut content = String::new();
let mut finish = None;
for line in &data_lines[..data_lines.len() - 1] {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
if let Some(c) = v["choices"][0]["delta"]["content"].as_str() {
content.push_str(c);
}
if let Some(f) = v["choices"][0]["finish_reason"].as_str() {
finish = Some(f.to_string());
}
}
assert_eq!(content, "ef");
assert_eq!(finish.as_deref(), Some("stop"));
}
async fn build_app_auth(auth: strata_ctl::api::AuthConfig) -> axum::Router {
let engine = Arc::new(
Engine::start(
"python3",
&[MOCK.to_string()],
None,
Duration::from_secs(10),
)
.await
.expect("mock engine starts"),
);
let svc = ChatService::new(engine, Arc::new(ByteFormatter));
strata_ctl::api::router_with_auth(svc, auth)
}
/// POST a completion with extra headers; returns (status, body).
async fn post_with_headers(app: &axum::Router, headers: &[(&str, &str)]) -> (StatusCode, String) {
let mut builder = Request::builder()
.method(Method::POST)
.uri("/v1/chat/completions")
.header(CONTENT_TYPE, "application/json");
for (k, v) in headers {
builder = builder.header(*k, *v);
}
let req = builder
.body(Body::from(
serde_json::json!({"model":"test-model","messages":[{"role":"user","content":"hi"}]})
.to_string(),
))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
(status, String::from_utf8_lossy(&bytes).into_owned())
}
#[tokio::test]
async fn api_key_is_enforced_when_configured() {
let auth = strata_ctl::api::AuthConfig {
api_key: Some("secret".into()),
allowed_hosts: vec![],
};
let app = build_app_auth(auth).await;
// no key -> 401
let (status, _) = post_with_headers(&app, &[]).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
// wrong key -> 401
let (status, _) = post_with_headers(&app, &[("authorization", "Bearer wrong")]).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
// correct bearer -> 200
let (status, text) = post_with_headers(&app, &[("authorization", "Bearer secret")]).await;
assert_eq!(status, StatusCode::OK, "body: {text}");
// x-api-key (Anthropic style) also accepted
let (status, _) = post_with_headers(&app, &[("x-api-key", "secret")]).await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn health_is_open_even_with_api_key() {
let auth = strata_ctl::api::AuthConfig {
api_key: Some("secret".into()),
allowed_hosts: vec![],
};
let app = build_app_auth(auth).await;
let resp = app
.oneshot(
Request::builder()
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn allowed_hosts_is_enforced() {
let auth = strata_ctl::api::AuthConfig {
api_key: None,
allowed_hosts: vec!["good.example".into()],
};
let app = build_app_auth(auth).await;
// matching Host (port stripped) -> 200
let (status, text) = post_with_headers(&app, &[("host", "good.example:8095")]).await;
assert_eq!(status, StatusCode::OK, "body: {text}");
// wrong Host -> 403
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"));
}