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
+69
-6
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user