Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
10 changes: 6 additions & 4 deletions src/embedding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
20 changes: 16 additions & 4 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -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}"
),
}
}
}
Expand Down
42 changes: 30 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -55,23 +61,35 @@ async fn embed(
Json(req): Json<EmbedRequest>,
) -> Result<Json<EmbedResponse>, 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,
Expand Down
4 changes: 2 additions & 2 deletions tests/embed_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -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")]
Expand Down
Loading