Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(server): refuse more choices than an OpenAI upstream's max_choices (#1041)

Krisztian Gajdar938f8b5f38ae
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.md
index 5690b2ad0..7a2541b49 100644
--- a/deploy/helm/sie-cluster/README.md
+++ b/deploy/helm/sie-cluster/README.md
@@ -978,7 +978,8 @@ Below, `<fullname>` is the chart's full name: `<release>-sie-cluster`, or
`proxy_url`. An upstream of kind `openai` also declares the `endpoints` it
offers (`completions`, `chat`, `embeddings`, `rerank`) and may name request
fields to add to every call (`set_params`) or remove from it
- (`strip_params`). `api_key_secret` names a Kubernetes Secret and key that you
+ (`strip_params`), and the most choices (`n`) one call may ask for
+ (`max_choices`, 1 to 128), for an upstream that refuses `n`. `api_key_secret` names a Kubernetes Secret and key that you
create; the chart rejects a plain string, so a credential cannot be written
into values. The chart checks these fields as the server does when it
renders, and a test sends the same URLs and definitions through the chart
diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tpl
index 1e1019bc3..323948bea 100644
--- a/deploy/helm/sie-cluster/templates/_helpers.tpl
+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl
@@ -2202,6 +2202,9 @@ the upstream's Secret.
{{- with $upstream.equivalence -}}
{{- $_ := set $entry "equivalence" (dict "max_age_s" (int64 .max_age_s) "record_files" .record_files) -}}
{{- end -}}
+{{- if not (kindIs "invalid" $upstream.max_choices) -}}
+{{- $_ := set $entry "max_choices" (int64 $upstream.max_choices) -}}
+{{- end -}}
{{- if $upstream.api_key_secret -}}
{{- $_ := set $entry "api_key_secret" (include "sie-cluster.upstream.keyEnvName" $name) -}}
{{- end -}}
@@ -2330,12 +2333,22 @@ Args (dict): url, field, requireTls.
{{/*
Check the fields of an upstream of kind openai the way the server does: the
-endpoints it offers, and the request fields set or stripped on every call.
+endpoints it offers, the request fields set or stripped on every call, and the
+most choices one call may ask for.
Names that fail the pattern are not repeated. Args (dict): upstream, path.
*/}}
{{- define "sie-cluster.upstreams.validateOpenaiFields" -}}
{{- $upstream := .upstream -}}
{{- $path := .path -}}
+{{- $maxChoices := $upstream.max_choices -}}
+{{- if not (kindIs "invalid" $maxChoices) -}}
+{{- if eq $upstream.kind "sie" -}}
+{{- fail (printf "%s: kind sie takes no max_choices" $path) -}}
+{{- end -}}
+{{- if not (and (or (kindIs "int" $maxChoices) (kindIs "int64" $maxChoices) (kindIs "float64" $maxChoices)) (eq (float64 $maxChoices) (floor (float64 $maxChoices))) (ge (float64 $maxChoices) 1.0) (le (float64 $maxChoices) 128.0)) -}}
+{{- fail (printf "%s.max_choices must be an integer from 1 to 128" $path) -}}
+{{- end -}}
+{{- end -}}
{{- $reserved := list "documents" "encoding_format" "input" "messages" "model" "n" "prompt" "query" "stream" "stream_options" "top_n" -}}
{{- $namePattern := "^[A-Za-z_][A-Za-z0-9_]{0,63}$" -}}
{{- if eq $upstream.kind "sie" -}}
@@ -2469,8 +2482,8 @@ credential pasted as a key would otherwise be printed.
{{- $fieldPosition := 0 -}}
{{- range $field, $_ := $upstream -}}
{{- $fieldPosition = add1 $fieldPosition -}}
-{{- if not (has $field (list "kind" "base_url" "api_key_secret" "rate_cap" "proxy_url" "endpoints" "set_params" "strip_params" "breaker" "equivalence")) -}}
-{{- fail (printf "%s: field %d, counting in name order, is not an upstream field; use kind, base_url, api_key_secret, rate_cap, proxy_url, endpoints, set_params, strip_params, breaker and equivalence" $path $fieldPosition) -}}
+{{- if not (has $field (list "kind" "base_url" "api_key_secret" "rate_cap" "proxy_url" "endpoints" "set_params" "strip_params" "max_choices" "breaker" "equivalence")) -}}
+{{- fail (printf "%s: field %d, counting in name order, is not an upstream field; use kind, base_url, api_key_secret, rate_cap, proxy_url, endpoints, set_params, strip_params, max_choices, breaker and equivalence" $path $fieldPosition) -}}
{{- end -}}
{{- end -}}
{{- if not (has $upstream.kind (list "sie" "openai")) -}}
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 98ce0c984..c635fceee 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -202,6 +202,12 @@ The operator may add `set_params` and `strip_params` on the upstream. Reserved
input and response-shaping fields, including `model`, cannot be overridden or
stripped. Callers cannot pass additional upstream fields or credentials.
+Some OpenAI-compatible upstreams refuse the `n` field, so they return a single
+choice per call. Set `max_choices: 1` on such an upstream (it takes 1 to 128). A chat or raw
+completion request asking for more choices than `max_choices` is then refused
+with `400 unsupported_field` (param `n`) before anything is sent upstream.
+Without `max_choices`, the server sets no limit.
+
## Context window of a remote profile
A generation model with local weights can declare a different window for its
diff --git a/packages/sie_server/src/sie_server/adapters/remote/openai.py b/packages/sie_server/src/sie_server/adapters/remote/openai.py
index 285c6ce67..9dc17b8c6 100644
--- a/packages/sie_server/src/sie_server/adapters/remote/openai.py
+++ b/packages/sie_server/src/sie_server/adapters/remote/openai.py
@@ -196,6 +196,11 @@ class OpenAIUpstreamAdapter(BaseAdapter, GenerationAdapter):
self, body: dict[str, Any], *, chat: bool, stream: bool
) -> tuple[httpx.AsyncClient, httpx.Request]:
upstream = self._generation_upstream(UpstreamEndpoint.CHAT if chat else UpstreamEndpoint.COMPLETIONS)
+ choices = body.get("n")
+ if upstream.max_choices is not None and type(choices) is int and choices > upstream.max_choices:
+ raise GenerationUnsupportedFieldError(
+ "n", f"'n' above {upstream.max_choices} is not supported by this model"
+ )
sent = upstream.apply_params({**body, "model": self._upstream_model, "stream": stream})
if not chat:
sent["echo"] = False
diff --git a/packages/sie_server/src/sie_server/config/upstreams.py b/packages/sie_server/src/sie_server/config/upstreams.py
index 49008fe79..971481bfe 100644
--- a/packages/sie_server/src/sie_server/config/upstreams.py
+++ b/packages/sie_server/src/sie_server/config/upstreams.py
@@ -296,6 +296,8 @@ class Upstream(BaseModel):
"""For kind ``openai``: request fields added to every call, in place of any value the server sends."""
strip_params: frozenset[str] = frozenset()
"""For kind ``openai``: request fields removed from every call."""
+ max_choices: int | None = Field(default=None, ge=1, le=128, strict=True)
+ """For kind ``openai``: the most choices (``n``), 1 to 128, one generation call may ask for. ``None`` sets no limit."""
equivalence: EquivalencePolicy | None = Field(default=None, repr=False)
"""For kind ``openai``: local files containing exact-model measured evidence."""
@@ -311,6 +313,14 @@ class Upstream(BaseModel):
_refuse_repeats(value, field=str(info.field_name))
return value
+ @field_validator("max_choices", mode="before")
+ @classmethod
+ def _whole_number_choices(cls, value: object) -> object:
+ # Helm decodes 1 and 1.0 alike, so the chart cannot refuse 1.0.
+ if type(value) is float and value.is_integer():
+ return int(value)
+ return value
+
@field_validator("set_params")
@classmethod
def _set_params(cls, value: dict[str, Any]) -> dict[str, Any]:
@@ -361,7 +371,9 @@ class Upstream(BaseModel):
if self.kind is UpstreamKind.SIE:
if self.equivalence is not None:
raise UpstreamConfigError("kind sie uses immutable identity, not OpenAI equivalence records")
- declared = [name for name in ("endpoints", "set_params", "strip_params") if getattr(self, name)]
+ declared = [
+ name for name in ("endpoints", "set_params", "strip_params", "max_choices") if getattr(self, name)
+ ]
if declared:
raise UpstreamConfigError(f"kind sie takes no {' or '.join(declared)}")
elif not self.endpoints:
diff --git a/packages/sie_server/tests/adapters/test_remote_openai_generation.py b/packages/sie_server/tests/adapters/test_remote_openai_generation.py
index eafcc428b..68a06b9c9 100644
--- a/packages/sie_server/tests/adapters/test_remote_openai_generation.py
+++ b/packages/sie_server/tests/adapters/test_remote_openai_generation.py
@@ -176,6 +176,43 @@ def test_non_integer_sample_counts_are_not_reinterpreted(adapter: OpenAIUpstream
assert sent["n"] == samples
[email protected]("chat", [False, True])
[email protected]("streaming", [False, True])
[email protected](("samples", "refused"), [(None, False), (1, False), (2, True)])
+async def test_choices_above_the_upstream_limit_refuse_without_dispatch(
+ adapter: OpenAIUpstreamAdapter, chat: bool, streaming: bool, samples: int | None, refused: bool
+) -> None:
+ assert adapter._upstream is not None
+ adapter._upstream = adapter._upstream.model_copy(update={"max_choices": 1})
+ body: dict[str, Any] = {"max_tokens": 9}
+ body.update({"messages": [{"role": "user", "content": "Hi."}]} if chat else {"prompt": "Hi."})
+ if samples is not None:
+ body["n"] = samples
+ if not refused:
+ _, request = adapter._generation_request(body, chat=chat, stream=streaming)
+ assert "n" not in json.loads(request.content)
+ return
+ with pytest.raises(GenerationUnsupportedFieldError) as raised:
+ adapter._generation_request(body, chat=chat, stream=streaming)
+ assert raised.value.param == "n"
+ assert raised.value.code == "unsupported_field"
+
+
+async def test_chat_choices_above_the_upstream_limit_never_reach_the_upstream(
+ adapter: OpenAIUpstreamAdapter,
+) -> None:
+ assert adapter._upstream is not None
+ adapter._upstream = adapter._upstream.model_copy(update={"max_choices": 1})
+ calls = []
+ answer_with(adapter, lambda request: calls.append(request) or httpx.Response(200))
+ body = {"messages": [{"role": "user", "content": "Hi."}], "max_tokens": 9, "n": 2}
+ with pytest.raises(GenerationUnsupportedFieldError):
+ await adapter.chat_completion(body, requested_model="caller/model")
+ with pytest.raises(GenerationUnsupportedFieldError):
+ adapter.chat_completion_stream(body, requested_model="caller/model")
+ assert calls == []
+
+
@pytest.mark.parametrize("streaming", [False, True])
async def test_missing_chat_endpoint_refuses_without_dispatch(adapter: OpenAIUpstreamAdapter, streaming: bool) -> None:
assert adapter._upstream is not None
diff --git a/packages/sie_server/tests/api/test_remote_chat.py b/packages/sie_server/tests/api/test_remote_chat.py
index 9ad8155de..eb33e68ab 100644
--- a/packages/sie_server/tests/api/test_remote_chat.py
+++ b/packages/sie_server/tests/api/test_remote_chat.py
@@ -148,6 +148,23 @@ def answer_with(
adapter._async_client = upstream_client(adapter._upstream, transport=httpx.MockTransport(respond))
[email protected]("stream", [False, True])
+def test_choices_above_the_upstream_limit_are_refused_before_dispatch(remote_chat: tuple, stream: bool) -> None:
+ client, adapter, _, requests = remote_chat
+ if isinstance(adapter, SieUpstreamAdapter):
+ pytest.skip("max_choices is an openai upstream field")
+ adapter._upstream = adapter._upstream.model_copy(update={"max_choices": 1})
+ answer_with(remote_chat, json_response(200, completion()))
+ response = client.post("/v1/chat/completions", json={**BODY, "n": 2, "stream": stream})
+ assert response.status_code == 400, response.text
+ error = response.json()["error"]
+ assert (error["code"], error["param"]) == ("unsupported_field", "n")
+ assert not requests
+ response = client.post("/v1/chat/completions", json={**BODY, "n": 1, "stream": False})
+ assert response.status_code == 200, response.text
+ assert "n" not in json.loads(requests[0].content)
+
+
def test_cpu_chat_preserves_identity_exact_usage_and_operator_defaults(remote_chat: tuple) -> None:
client, _, _, requests = remote_chat
answer_with(remote_chat, json_response(200, completion(model="private", id="private-id")))
diff --git a/packages/sie_server/tests/config/test_openai_upstream_endpoints.py b/packages/sie_server/tests/config/test_openai_upstream_endpoints.py
index 07560e6fe..27a373999 100644
--- a/packages/sie_server/tests/config/test_openai_upstream_endpoints.py
+++ b/packages/sie_server/tests/config/test_openai_upstream_endpoints.py
@@ -131,8 +131,13 @@ def test_a_list_is_never_silently_shortened_or_widened(tmp_path: Path, fields: d
@pytest.mark.parametrize(
"field",
- [{"endpoints": ["chat"]}, {"set_params": {"provider": {"zdr": True}}}, {"strip_params": ["user"]}],
- ids=["endpoints", "set_params", "strip_params"],
+ [
+ {"endpoints": ["chat"]},
+ {"set_params": {"provider": {"zdr": True}}},
+ {"strip_params": ["user"]},
+ {"max_choices": 1},
+ ],
+ ids=["endpoints", "set_params", "strip_params", "max_choices"],
)
def test_kind_sie_takes_no_openai_field(field: dict[str, Any]) -> None:
with pytest.raises(ValidationError, match=f"kind sie takes no {next(iter(field))}"):
@@ -141,6 +146,35 @@ def test_kind_sie_takes_no_openai_field(field: dict[str, Any]) -> None:
)
[email protected]("value", [0, -1, 129, 1.5, 0.0, True, "1"])
+def test_max_choices_is_an_integer_from_1_to_128(value: object) -> None:
+ with pytest.raises(ValidationError, match="max_choices"):
+ Upstream.model_validate(
+ {
+ "kind": "openai",
+ "base_url": "https://api.example.com/v1",
+ "endpoints": ["chat"],
+ "rate_cap": RATE_CAP,
+ "max_choices": value,
+ }
+ )
+
+
+def test_a_whole_number_max_choices_is_read_as_an_integer() -> None:
+ upstream = Upstream.model_validate(
+ {
+ "kind": "openai",
+ "base_url": "https://api.example.com/v1",
+ "endpoints": ["chat"],
+ "rate_cap": RATE_CAP,
+ "max_choices": 1.0,
+ }
+ )
+
+ assert type(upstream.max_choices) is int
+ assert upstream.max_choices == 1
+
+
def test_the_model_and_the_caller_input_are_reserved() -> None:
assert {"model", "input", "messages", "prompt", "query", "documents", "stream"} <= RESERVED_UPSTREAM_PARAMS
diff --git a/tools/ci/fixtures/helm-upstreams.yaml b/tools/ci/fixtures/helm-upstreams.yaml
index 4faeb20da..992cccb11 100644
--- a/tools/ci/fixtures/helm-upstreams.yaml
+++ b/tools/ci/fixtures/helm-upstreams.yaml
@@ -25,6 +25,7 @@ values:
set_params:
provider: {data_collection: deny}
strip_params: [user]
+ max_choices: 1
equivalence:
max_age_s: 300
record_files: {local/model: /proofs/local-model.json}
@@ -49,6 +50,7 @@ rendered:
set_params:
provider: {data_collection: deny}
strip_params: [user]
+ max_choices: 1
equivalence:
max_age_s: 300
record_files: {local/model: /proofs/local-model.json}
@@ -109,6 +111,20 @@ definitions:
- {accepted: false, upstream: {kind: openai, endpoints: [chat], strip_params: [user, user]}}
- {accepted: false, upstream: {kind: openai, endpoints: [chat], strip_params: [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31, p32]}}
- {accepted: false, upstream: {kind: openai, endpoints: [chat], set_params: {user: x}, strip_params: [user]}}
+ - {accepted: true, upstream: {kind: openai, endpoints: [chat], max_choices: 1}}
+ - {accepted: true, upstream: {kind: openai, endpoints: [chat], max_choices: 8}}
+ - {accepted: true, upstream: {kind: openai, endpoints: [chat], max_choices: 128}}
+ - {accepted: true, upstream: {kind: openai, endpoints: [chat], max_choices: 1.0}}
+ - {accepted: false, upstream: {kind: openai, endpoints: [chat], max_choices: 129}}
+ - {accepted: false, upstream: {kind: openai, endpoints: [chat], max_choices: 9223372036854775808}}
+ - {accepted: true, upstream: {kind: openai, endpoints: [chat], max_choices: null}}
+ - {accepted: true, upstream: {kind: sie, max_choices: null}}
+ - {accepted: false, upstream: {kind: sie, max_choices: 1}}
+ - {accepted: false, upstream: {kind: openai, endpoints: [chat], max_choices: 0}}
+ - {accepted: false, upstream: {kind: openai, endpoints: [chat], max_choices: -1}}
+ - {accepted: false, upstream: {kind: openai, endpoints: [chat], max_choices: 1.5}}
+ - {accepted: false, upstream: {kind: openai, endpoints: [chat], max_choices: true}}
+ - {accepted: false, upstream: {kind: openai, endpoints: [chat], max_choices: "1"}}
- {accepted: true, upstream: {kind: sie, breaker: {failures: 3, window_s: 12.5, cooldown_s: 45}}}
- {accepted: true, upstream: {kind: sie, breaker: {}}}