messages/request.rs (the Messages request types and Request::into_responses, CountRequest, text and block helpers) and messages/reply.rs (message, stop reason, tool_use block, usage, the error type table and envelope as functions of the status number) are in crates/gateway-domain. strata-control keeps the route layers, the SSE adaptation and the HTTP errors; error_value(StatusCode, ..) is a wrapper over the domain function. The adapter tests stay where they are and pass on the moved code (same test ids). The long functions are added to docs/architecture/tech-debt.md, the continuation is recorded in docs/experiments/stra-338-gateway-track.md (90 golden cases; an earlier commit message says 96, which was a miscount).
35 lines
1.3 KiB
Rust
35 lines
1.3 KiB
Rust
//! `POST /v1/messages/count_tokens`: the Messages request counted through the native token counter.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
pub async fn count_tokens(
|
|
State(state): State<AppState>,
|
|
body: Result<Json<Value>, JsonRejection>,
|
|
) -> Response {
|
|
let value = match body {
|
|
Ok(Json(value)) => value,
|
|
Err(e) => return error(e.status(), &e.body_text()),
|
|
};
|
|
let request: CountRequest = match serde_json::from_value(value) {
|
|
Ok(request) => request,
|
|
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
|
|
};
|
|
let native = match request.into_responses() {
|
|
Ok(value) => value,
|
|
Err(e) => return error(StatusCode::BAD_REQUEST, &e),
|
|
};
|
|
let response = responses::count_input_tokens(State(state), Ok(Json(native))).await;
|
|
if !response.status().is_success() {
|
|
return response; // Route middleware normalizes native errors.
|
|
}
|
|
let bytes = to_bytes(response.into_body(), 1024).await;
|
|
if let Ok(bytes) = bytes
|
|
&& let Ok(value) = serde_json::from_slice::<Value>(&bytes)
|
|
&& let Some(count) = value["input_tokens"].as_u64()
|
|
{
|
|
return Json(json!({"input_tokens":count})).into_response();
|
|
}
|
|
error(StatusCode::BAD_GATEWAY, "invalid native token count")
|
|
}
|