Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix: answer /v1/rerank without usage when the score has none (#569)

Krisztian Gajdar3459946f282c
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index 590a03f76..756a6409c 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -3498,13 +3498,20 @@
"type": "array"
},
"usage": {
- "$ref": "#/components/schemas/ScoreUsage"
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ScoreUsage",
+ "description": "Omitted when the serving path could not count, as on `/v1/score`."
+ }
+ ]
}
},
"required": [
"model",
- "results",
- "usage"
+ "results"
],
"type": "object"
},
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index cc60f4cb9..48b463712 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -14858,24 +14858,27 @@ fn rerank_response_from_score(
ranked.truncate(limit);
}
- let usage = native
- .get("usage")
- .and_then(Value::as_object)
- .ok_or_else(|| "score response missing authoritative usage".to_string())?;
- let input_tokens = usage
- .get("input_tokens")
- .and_then(Value::as_u64)
- .ok_or_else(|| "score response usage missing input_tokens".to_string())?;
- let images = usage.get("images").map(|value| {
- value
- .as_u64()
- .ok_or_else(|| "score response usage has an invalid images count".to_string())
- });
- let mut output_usage = Map::new();
- output_usage.insert("input_tokens".to_string(), json!(input_tokens));
- if let Some(images) = images {
- output_usage.insert("images".to_string(), json!(images?));
- }
+ let output_usage = match native.get("usage") {
+ None | Some(Value::Null) => None,
+ Some(usage) => {
+ let usage = usage
+ .as_object()
+ .ok_or_else(|| "score response usage is not an object".to_string())?;
+ let input_tokens = usage
+ .get("input_tokens")
+ .and_then(Value::as_u64)
+ .ok_or_else(|| "score response usage missing input_tokens".to_string())?;
+ let mut output_usage = Map::new();
+ output_usage.insert("input_tokens".to_string(), json!(input_tokens));
+ if let Some(images) = usage.get("images") {
+ let images = images.as_u64().ok_or_else(|| {
+ "score response usage has an invalid images count".to_string()
+ })?;
+ output_usage.insert("images".to_string(), json!(images));
+ }
+ Some(output_usage)
+ }
+ };
let results = ranked
.into_iter()
@@ -14890,11 +14893,13 @@ fn rerank_response_from_score(
})
.collect::<Vec<_>>();
- Ok(json!({
- "model": model,
- "results": results,
- "usage": output_usage,
- }))
+ let mut response = Map::new();
+ response.insert("model".to_string(), json!(model));
+ response.insert("results".to_string(), Value::Array(results));
+ if let Some(usage) = output_usage {
+ response.insert("usage".to_string(), Value::Object(usage));
+ }
+ Ok(Value::Object(response))
}
fn rerank_error(status: StatusCode, message: impl Into<String>) -> Response {
@@ -27923,10 +27928,38 @@ mod tests {
}
#[test]
- fn test_rerank_response_rejects_missing_or_malformed_usage() {
+ fn test_rerank_response_omits_usage_when_the_score_reports_none() {
+ let scores = json!([
+ {"item_id": "1", "score": 0.9, "rank": 0},
+ {"item_id": "0", "score": 0.2, "rank": 1}
+ ]);
+ for native in [
+ json!({"model": "m", "scores": scores.clone()}),
+ json!({"model": "m", "scores": scores.clone(), "usage": null}),
+ ] {
+ let response = rerank_response_from_score(
+ &native,
+ &["first".to_string(), "second".to_string()],
+ None,
+ false,
+ )
+ .unwrap();
+ assert!(response.get("usage").is_none(), "{response}");
+ let indexes = response["results"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|result| result["index"].as_u64().unwrap())
+ .collect::<Vec<_>>();
+ assert_eq!(indexes, vec![1, 0]);
+ }
+ }
+
+ #[test]
+ fn test_rerank_response_rejects_malformed_usage() {
let scores = json!([{"item_id": "0", "score": 0.5, "rank": 0}]);
for (usage, expected) in [
- (Value::Null, "missing authoritative usage"),
+ (json!([4]), "usage is not an object"),
(json!({"images": 1}), "missing input_tokens"),
(
json!({"input_tokens": 4, "images": -1}),
diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs
index 643105a0e..f8c92fe91 100644
--- a/packages/sie_gateway/src/openapi.rs
+++ b/packages/sie_gateway/src/openapi.rs
@@ -3134,7 +3134,9 @@ pub struct Usage {
pub struct RerankResponse {
pub model: String,
pub results: Vec<RerankResult>,
- pub usage: ScoreUsage,
+ /// Omitted when the serving path could not count, as on `/v1/score`.
+ #[serde(default)]
+ pub usage: Option<ScoreUsage>,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 2e5a0ebbf..928a18d9c 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -123,12 +123,12 @@ with SIEClient(base_url="http://localhost:8080") as client:
Usage counts come from the upstream. When an upstream reports no usage, a
native `encode`, `score` or `extract` request still succeeds, and the response
-omits `usage` instead of estimating it. This holds for every operation an
-upstream kind supports, on a single node and in a cluster. Two
-OpenAI-compatible routes differ. `/v1/embeddings` always returns a `usage`
-object, so it reports a character-based estimate instead, which the gateway
-marks with `sie_token_source: character_estimate`. `/v1/rerank` requires usage
-and answers `500` when the score carries none. For an OpenAI-compatible
+omits `usage` instead of estimating it. This holds for the `encode`, `score`
+and `extract` operations each upstream kind supports, on a single node and in a
+cluster. The OpenAI-compatible `/v1/rerank` route also omits `usage`. The
+OpenAI-compatible `/v1/embeddings` route always returns a `usage` object, so it
+reports a character-based estimate instead, which the gateway marks with
+`sie_token_source: character_estimate`. For an OpenAI-compatible
upstream, a `usage` object with no count in it counts as no usage. Malformed
usage fails the request: a value of the wrong type, an invalid count, or an SIE
upstream's `usage` without `input_tokens`. Generation fails closed: a
@@ -146,7 +146,7 @@ set `upstream_model` to the provider's model id.
OpenAI-compatible embedding profiles support dense text only. Sparse,
multivector, image input and extraction are rejected before dispatch. A rerank
upstream must accept the Cohere-shaped request. Without upstream usage,
-`/v1/score` omits `usage` and `/v1/rerank` answers `500`, as described above.
+`/v1/score` and `/v1/rerank` both omit `usage`, as described above.
SIE restores scores to document order rather than exposing the provider's
ranked order.
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index b9f36a297..b182c4f67 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -1565,8 +1565,9 @@ async def rerank(
"""Cohere/OpenAI-style reranking backed by the in-process score adapter.
Request: ``{model, query, documents: [str], top_n?, return_documents?}``.
- Response: ``{model, results: [{index, relevance_score, document?}], usage}``
- sorted by descending relevance.
+ Response: ``{model, results: [{index, relevance_score, document?}], usage?}``
+ sorted by descending relevance. ``usage`` is omitted when the score output
+ carries no counts, as on ``/v1/score``.
Errors are emitted as top-level OpenAI ``{"error": {...}}`` envelopes
(never FastAPI's ``{"detail": ...}`` wrapper), matching ``/v1/completions``.
@@ -1685,11 +1686,6 @@ async def _rerank(
# the HTTPException is re-emitted as the OpenAI error envelope by rerank().
ensure_finite_scores(scores, model)
usage = score_usage_from_output(score_output)
- if usage is None:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail={"code": "inference_error", "message": "score response missing authoritative usage"},
- )
ranked = sorted(enumerate(scores), key=lambda pair: pair[1], reverse=True)
if top_n is not None:
@@ -1701,11 +1697,7 @@ async def _rerank(
entry["document"] = {"text": documents[index]}
results.append(entry)
- return JSONResponse(
- content={
- "model": getattr(config, "name", None) or registry_key,
- "results": results,
- "usage": usage,
- },
- headers=route.headers(),
- )
+ content: dict[str, Any] = {"model": getattr(config, "name", None) or registry_key, "results": results}
+ if usage is not None:
+ content["usage"] = usage
+ return JSONResponse(content=content, headers=route.headers())
diff --git a/packages/sie_server/tests/adapters/test_remote_openai_adapter.py b/packages/sie_server/tests/adapters/test_remote_openai_adapter.py
index 3ad71f7aa..56662b559 100644
--- a/packages/sie_server/tests/adapters/test_remote_openai_adapter.py
+++ b/packages/sie_server/tests/adapters/test_remote_openai_adapter.py
@@ -63,13 +63,15 @@ class FakeOpenAI:
"""An OpenAI-compatible upstream that records each call and answers from a queue first.
``delays`` holds seconds to wait before answering an embeddings input, so
- concurrent calls can finish out of order.
+ concurrent calls can finish out of order. With ``rerank_usage`` off, rerank
+ answers carry no usage.
"""
url: str = ""
calls: list[dict[str, Any]] = field(default_factory=list)
queued: list[Response] = field(default_factory=list)
delays: dict[str, float] = field(default_factory=dict)
+ rerank_usage: bool = True
def app(self) -> FastAPI:
app = FastAPI()
@@ -102,8 +104,10 @@ class FakeOpenAI:
({"index": i, "relevance_score": relevance(body["query"], doc)} for i, doc in enumerate(documents)),
key=lambda result: -result["relevance_score"],
)
- usage = {"total_tokens": word_count(body["query"], *documents)}
- return JSONResponse({"results": results[: body["top_n"]], "usage": usage})
+ answer: dict[str, Any] = {"results": results[: body["top_n"]]}
+ if self.rerank_usage:
+ answer["usage"] = {"total_tokens": word_count(body["query"], *documents)}
+ return JSONResponse(answer)
return app
@@ -343,6 +347,32 @@ def test_the_openai_rerank_route_asks_the_upstream_for_every_score(
assert [call["body"]["top_n"] for call in fake_openai.calls] == [3]
+def test_an_upstream_without_usage_is_served_on_score_and_rerank_without_usage(
+ fake_openai: FakeOpenAI, openai_app: Callable[..., FastAPI]
+) -> None:
+ fake_openai.rerank_usage = False
+ documents = ["a green pear", "a red apple pie", "red wine"]
+ with TestClient(openai_app(fake_openai.url)) as client:
+ scored = post(
+ client,
+ fake_openai,
+ f"/v1/score/{MODEL}",
+ {"query": {"text": "red apple"}, "items": [{"id": str(i), "text": doc} for i, doc in enumerate(documents)]},
+ )
+ reranked = post(
+ client, fake_openai, "/v1/rerank", {"model": MODEL, "query": "red apple", "documents": documents}
+ )
+
+ assert scored.status_code == 200, scored.text
+ assert "usage" not in scored.json()
+ assert reranked.status_code == 200, reranked.text
+ assert [result["index"] for result in reranked.json()["results"]] == sorted(
+ range(len(documents)), key=lambda index: -relevance("red apple", documents[index])
+ )
+ assert "usage" not in reranked.json()
+ assert reranked.headers["x-sie-served-by"] == "remote"
+
+
def test_an_operation_the_upstream_does_not_declare_is_refused_before_sending(
fake_openai: FakeOpenAI, openai_app: Callable[..., FastAPI]
) -> None: