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:
1 parent
b6619d30de
commit
9e6d44fa1a
7 files changed
+758
-24
No files matched your search
@@ -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"));
|
||||
}
|
||||
Reference in new issue
Block a user