From a028fdcfd9262c9ff3786d0e6791504206bd716b Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 16:01:42 +0530 Subject: [PATCH 1/2] feat(embedding): return token limit details in the error --- src/embedding.rs | 10 ++++++---- src/error.rs | 20 ++++++++++++++++---- src/main.rs | 42 ++++++++++++++++++++++++++++++------------ tests/embed_e2e.rs | 4 ++-- 4 files changed, 54 insertions(+), 22 deletions(-) diff --git a/src/embedding.rs b/src/embedding.rs index 4217405..423e1cf 100644 --- a/src/embedding.rs +++ b/src/embedding.rs @@ -699,10 +699,12 @@ impl EmbeddingClient { .map_err(|e| format!("Failed to join tokenizer task: {}", e))??; if let Some((index, count)) = first_over_limit(&counts, loaded.max_length) { - return Err(EmbedError::TooLong(format!( - "text at index {} has {} tokens, the limit for {} is {}", - index, count, model_name, loaded.max_length - ))); + return Err(EmbedError::TooLong { + model: model_name.to_owned(), + index, + tokens: count, + limit: loaded.max_length, + }); } let tokens = counts.iter().sum(); diff --git a/src/error.rs b/src/error.rs index b228177..3b99e5f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,16 +1,28 @@ #[derive(Debug)] pub enum EmbedError { UnknownModel(String), - TooLong(String), + TooLong { + model: String, + index: usize, + tokens: usize, + limit: usize, + }, Internal(String), } impl std::fmt::Display for EmbedError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - EmbedError::UnknownModel(m) | EmbedError::TooLong(m) | EmbedError::Internal(m) => { - write!(f, "{}", m) - } + EmbedError::UnknownModel(m) | EmbedError::Internal(m) => write!(f, "{}", m), + EmbedError::TooLong { + model, + index, + tokens, + limit, + } => write!( + f, + "text at index {index} has {tokens} tokens, the limit for {model} is {limit}" + ), } } } diff --git a/src/main.rs b/src/main.rs index db3323b..821847e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,7 +31,13 @@ struct EmbedResponse { total_duration: u64, } -struct AppError(StatusCode, String); +struct AppError(StatusCode, serde_json::Value); + +impl AppError { + fn new(status: StatusCode, message: String) -> Self { + Self(status, message.into()) + } +} impl IntoResponse for AppError { fn into_response(self) -> Response { @@ -55,23 +61,35 @@ async fn embed( Json(req): Json, ) -> Result, AppError> { if req.texts.is_empty() { - return Err(AppError( + return Err(AppError::new( StatusCode::BAD_REQUEST, "texts must not be empty".to_string(), )); } let refs: Vec<&str> = req.texts.iter().map(|s| s.as_str()).collect(); - let result = state - .client - .embed(&req.model, &refs) - .await - .map_err(|e| match e { - EmbedError::UnknownModel(msg) | EmbedError::TooLong(msg) => { - AppError(StatusCode::BAD_REQUEST, msg) - } - EmbedError::Internal(msg) => AppError(StatusCode::INTERNAL_SERVER_ERROR, msg), - })?; + let result = state.client.embed(&req.model, &refs).await.map_err(|e| { + let message = e.to_string(); + match e { + EmbedError::UnknownModel(msg) => AppError::new(StatusCode::BAD_REQUEST, msg), + EmbedError::TooLong { + index, + tokens, + limit, + .. + } => AppError( + StatusCode::BAD_REQUEST, + serde_json::json!({ + "type": "text_too_long", + "message": message, + "index": index, + "tokens": tokens, + "limit": limit, + }), + ), + EmbedError::Internal(msg) => AppError::new(StatusCode::INTERNAL_SERVER_ERROR, msg), + } + })?; Ok(Json(EmbedResponse { model: result.model, diff --git a/tests/embed_e2e.rs b/tests/embed_e2e.rs index 6249ff3..69b9fd7 100644 --- a/tests/embed_e2e.rs +++ b/tests/embed_e2e.rs @@ -217,7 +217,7 @@ async fn nomic_rejects_text_over_max_length() { .await .expect_err("text over the limit should be rejected"); - assert!(matches!(err, EmbedError::TooLong(_))); + assert!(matches!(err, EmbedError::TooLong { .. })); } #[tokio::test(flavor = "multi_thread")] @@ -230,7 +230,7 @@ async fn minilm_rejects_text_over_its_context() { .await .expect_err("text over the model context should be rejected"); - assert!(matches!(err, EmbedError::TooLong(_))); + assert!(matches!(err, EmbedError::TooLong { .. })); } #[tokio::test(flavor = "multi_thread")] From e98bbfd898b9da2c5e6ec357a48093a0afa897a7 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 16:01:42 +0530 Subject: [PATCH 2/2] docs: document the token limit error body --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 05f23f0..d564770 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,6 @@ Response: Errors: -- `400 Bad Request` — `texts` is empty, the model alias is not in `EMBEDDING_MODELS`, or a text is over the token limit. Split long input before sending it. +- `400 Bad Request` — `texts` is empty, the model alias is not in `EMBEDDING_MODELS`, or a text is over the token limit. Split long input before sending it. Over the limit, `error` is an object: `{"type":"text_too_long","message":"...","index":1,"tokens":20002,"limit":2048}`. - `500 Internal Server Error` — embedding or tokenizer failure (message in `error` field). - `503 Service Unavailable` — `GET /health` for 30 seconds after a model load has failed (message in `error` field).