Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): name the context window when the generation child refuses a chat request (#1021)
Krisztian Gajdar17f744388087
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_window.py b/packages/sie_server/src/sie_server/adapters/sglang/_window.pyindex 2af2fec80..ca9acb901 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/_window.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/_window.py@@ -18,19 +18,26 @@ from sie_server.types.inputs import InvalidInputError# Identical in the SGLang 0.5.10 and 0.5.20 the bundles pin: the first two come from# its tokenizer process, the last two from its scheduler, which also counts image# tokens and keeps a small margin.-_WINDOW_REFUSALS = tuple(- re.compile(pattern)- for pattern in (- r"The input \((?P<tokens>\d+) tokens\) is longer than the model's context length \((?P<limit>\d+) tokens\)\.",- r"Requested token count exceeds the model's maximum context length of (?P<limit>\d+) tokens\. "- r"You requested a total of (?P<tokens>\d+) tokens: \d+ tokens from the input messages and \d+ tokens "- r"for the completion\. Please reduce the number of tokens in the input messages or the completion "- r"to fit within the limit\.",+_INPUT_OVER_WINDOW = re.compile(+ r"The input \((?P<tokens>\d+) tokens\) is longer than the model's context length \((?P<limit>\d+) tokens\)\."+)+_TOTAL_OVER_WINDOW = re.compile(+ r"Requested token count exceeds the model's maximum context length of (?P<limit>\d+) tokens\. "+ r"You requested a total of (?P<tokens>\d+) tokens: (?P<input>\d+) tokens from the input messages and "+ r"(?P<output>\d+) tokens for the completion\. Please reduce the number of tokens in the input messages or the "+ r"completion to fit within the limit\."+)+_WINDOW_REFUSALS = (+ _INPUT_OVER_WINDOW,+ _TOTAL_OVER_WINDOW,+ re.compile(r"Input length \((?P<tokens>\d+) tokens\) exceeds the maximum allowed length \((?P<limit>\d+) tokens\)\. "- r"Use a shorter input or enable --allow-auto-truncate\.",+ r"Use a shorter input or enable --allow-auto-truncate\."+ ),+ re.compile(r"Multimodal prompt is too long after expanding multimodal tokens\. "- r"After expanding len\(req\.origin_input_ids_unpadded\)=\d+ => (?P<tokens>\d+) >= (?P<limit>\d+)\.",- )+ r"After expanding len\(req\.origin_input_ids_unpadded\)=\d+ => (?P<tokens>\d+) >= (?P<limit>\d+)\."+ ),)@@ -46,3 +53,23 @@ def window_refusal_message(message: object) -> str | None:if (match := pattern.fullmatch(message)) is not None:return f"The request needs {match['tokens']} tokens, at or over this model's limit of {match['limit']}"return None+++def chat_window_refusal_message(message: object, *, model: str) -> str | None:+ """The chat route's text for a window refusal, else ``None``.++ The tokenizer's two refusals measure against the model's window, so they are+ worded as the chat route words a window it checks itself: the prompt tokens,+ the output cap and the window. The scheduler's limit is not the window, so+ its refusals keep the generic text.+ """+ if not isinstance(message, str):+ return None+ if (match := _TOTAL_OVER_WINDOW.fullmatch(message)) is not None:+ return (+ f"prompt_tokens ({match['input']}) + max_new_tokens ({match['output']}) = {match['tokens']} "+ f"exceeds context_length ({match['limit']}) for model '{model}'"+ )+ if (match := _INPUT_OVER_WINDOW.fullmatch(message)) is not None:+ return f"prompt_tokens ({match['tokens']}) exceeds context_length ({match['limit']}) for model '{model}'"+ return window_refusal_message(message)diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 37bb82563..15a95ac7f 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -68,6 +68,7 @@ from sie_server.adapters.errors import (from sie_server.adapters.fake.adapter import FakeAdapterfrom sie_server.adapters.mlx.generation import MLXGenerationAdapter, normalize_mlx_seedfrom sie_server.adapters.remote._http import RemoteUpstreamError+from sie_server.adapters.sglang._window import chat_window_refusal_messagefrom sie_server.adapters.sglang.generation import SGLangGenerationAdapterfrom sie_server.api.generate import (_generation_http_exception,@@ -348,6 +349,24 @@ def _upstream_error_response(return JSONResponse(status_code=response_status, content={"error": error})+def _raise_for_child_window_refusal(upstream_status: int, body: bytes, *, requested_model: str) -> None:+ """Raise the route's too-long refusal when the child's 400 is a window refusal.++ Raises:+ HTTPException: The child's 400 carries one of its window refusals.+ """+ if upstream_status != status.HTTP_400_BAD_REQUEST:+ return+ try:+ payload = json.loads(body)+ except (ValueError, RecursionError):+ return+ message = payload.get("message") if isinstance(payload, dict) else None+ refusal = chat_window_refusal_message(message, model=requested_model)+ if refusal is not None:+ raise _generation_http_exception(GenerationInputTooLongError(refusal))++def _translated_upstream_status(upstream_status: int) -> int:"""Preserve child request errors; collapse engine failures to 502."""if status.HTTP_400_BAD_REQUEST <= upstream_status < status.HTTP_500_INTERNAL_SERVER_ERROR:@@ -1936,12 +1955,14 @@ async def _chat_completions(context="generation child SSE response",)if upstream.status_code != status.HTTP_200_OK:+ error_body = b""try:- await _read_upstream_body(upstream)+ error_body = await _read_upstream_body(upstream)except (httpx.HTTPError, ValueError):- # The body is intentionally discarded; never log child- # validation details because they can include user input.+ # Never log child validation details because they can+ # include user input.pass+ _raise_for_child_window_refusal(upstream.status_code, error_body, requested_model=model)logger.error("generation child chat error status=%d", upstream.status_code)return _upstream_error_response(response_status=_translated_upstream_status(upstream.status_code),@@ -2000,6 +2021,7 @@ async def _chat_completions(slot.release()if upstream_status != status.HTTP_200_OK:+ _raise_for_child_window_refusal(upstream_status, raw, requested_model=model)logger.error("generation child chat error status=%d", upstream_status)return _upstream_error_response(response_status=_translated_upstream_status(upstream_status),diff --git a/packages/sie_server/tests/adapters/test_sglang_window_refusal.py b/packages/sie_server/tests/adapters/test_sglang_window_refusal.pyindex 21d737eee..60f43070b 100644--- a/packages/sie_server/tests/adapters/test_sglang_window_refusal.py+++ b/packages/sie_server/tests/adapters/test_sglang_window_refusal.py@@ -17,7 +17,11 @@ from sie_server.adapters._generation_base import (GenerationInvalidRequestError,)from sie_server.adapters.errors import InputTooLongError-from sie_server.adapters.sglang._window import SGLangInputTooLongError, window_refusal_message+from sie_server.adapters.sglang._window import (+ SGLangInputTooLongError,+ chat_window_refusal_message,+ window_refusal_message,+)from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapterfrom sie_server.adapters.sglang.generation import (SGLangGenerationAdapter,@@ -87,6 +91,33 @@ def test_other_engine_messages_are_not_window_refusals(message: object) -> None:assert window_refusal_message(message) is None+# Chat: the tokenizer measures against the window, so its refusals name the prompt, output cap and window.+CHAT_REFUSALS = [+ pytest.param(+ REFUSALS[0].values[0],+ "prompt_tokens (30042) exceeds context_length (24576) for model 'org/model:long'",+ id="tokenizer-input",+ ),+ pytest.param(+ REFUSALS[1].values[0],+ "prompt_tokens (8176) + max_new_tokens (16) = 8192 exceeds context_length (8192) for model 'org/model:long'",+ id="tokenizer-total",+ ),+ pytest.param(REFUSALS[2].values[0], _expected("8189", "8186"), id="scheduler-input"),+ pytest.param(REFUSALS[3].values[0], _expected("16454", "16378"), id="scheduler-multimodal"),+]++[email protected](("message", "expected"), CHAT_REFUSALS)+def test_chat_refusals_name_the_prompt_output_cap_and_window(message: str, expected: str) -> None:+ assert chat_window_refusal_message(message, model="org/model:long") == expected++[email protected]("message", OTHER_MESSAGES)+def test_other_engine_messages_are_not_chat_window_refusals(message: object) -> None:+ assert chat_window_refusal_message(message, model="org/model") is None++# Generation: where the engine reports the refusal depends on where it noticed.diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pyindex 98f871445..30be4b94b 100644--- a/packages/sie_server/tests/api/test_openai_local.py+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -29,7 +29,7 @@ from openai.types.chat import ChatCompletion, ChatCompletionChunkfrom sie_server.adapters.mlx import generation as mlx_generationfrom sie_server.adapters.mlx.generation import MLXGenerationAdapterfrom sie_server.adapters.sglang.generation import SGLangGenerationAdapter-from sie_server.api import anthropic_messages, openai_local+from sie_server.api import anthropic_messages, openai_local, openai_responsesfrom sie_server.api.openai_local import _validate_mlx_seed, routerfrom sie_server.config.model import ModelConfigfrom sie_server.core import video_frames@@ -1239,6 +1239,103 @@ def test_cuda_chat_does_not_log_upstream_error_body(assert private_marker not in caplog.text+# SGLang's chat surface refusing a request whose input plus output cap does not fit its window.+_SGLANG_WINDOW_REFUSAL = {+ "object": "error",+ "message": (+ "Requested token count exceeds the model's maximum context length of 32768 tokens. You requested a total "+ "of 32898 tokens: 28802 tokens from the input messages and 4096 tokens for the completion. Please reduce "+ "the number of tokens in the input messages or the completion to fit within the limit."+ ),+ "type": "BadRequestError",+ "param": None,+ "code": 400,+}+_WINDOW_REFUSAL_ERROR = {+ "message": (+ "prompt_tokens (28802) + max_new_tokens (4096) = 32898 exceeds context_length (32768) "+ "for model 'Qwen/Qwen3.5-4B'"+ ),+ "type": "invalid_request_error",+ "param": "prompt",+ "code": "INPUT_TOO_LONG",+}++[email protected]("stream", [False, True])+def test_cuda_chat_names_the_window_the_child_refused(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ stream: bool,+) -> None:+ client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(400, json=_SGLANG_WINDOW_REFUSAL))+ with caplog.at_level("ERROR", logger="sie_server.api.openai_local"):+ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}], "stream": stream},+ )++ assert response.status_code == 400, response.text+ assert response.json() == {"error": _WINDOW_REFUSAL_ERROR}+ assert "generation child chat error" not in caplog.text+++ ("path", "body", "error"),+ [+ (+ "/v1/responses",+ {"model": "Qwen/Qwen3.5-4B", "input": "Hello"},+ {"error": _WINDOW_REFUSAL_ERROR},+ ),+ (+ "/v1/messages",+ {"model": "Qwen/Qwen3.5-4B", "max_tokens": 32, "messages": [{"role": "user", "content": "Hello"}]},+ {+ "type": "error",+ "error": {+ "type": "invalid_request_error",+ "message": "prompt is too long: 32898 tokens > 32768 maximum",+ },+ },+ ),+ ],+ ids=["responses", "messages"],+)+def test_cuda_chat_window_refusal_reaches_the_translated_routes(+ monkeypatch: pytest.MonkeyPatch, path: str, body: dict[str, Any], error: dict[str, Any]+) -> None:+ client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(400, json=_SGLANG_WINDOW_REFUSAL))+ client.app.include_router(openai_responses.router)+ client.app.include_router(anthropic_messages.router)++ response = client.post(path, json=body)++ assert response.status_code == 400, response.text+ assert {key: response.json()[key] for key in error} == error+++ ("upstream_status", "body"),+ [+ (500, _SGLANG_WINDOW_REFUSAL),+ (400, {**_SGLANG_WINDOW_REFUSAL, "message": f"{_SGLANG_WINDOW_REFUSAL['message']} secret"}),+ ],+ ids=["engine failure status", "longer text"],+)+def test_cuda_chat_keeps_other_child_errors_opaque(+ monkeypatch: pytest.MonkeyPatch, upstream_status: int, body: dict[str, Any]+) -> None:+ client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(upstream_status, json=body))+ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}]},+ )++ assert response.json()["error"]["code"] == "upstream_error"+ assert "secret" not in response.text++def test_cuda_chat_rejects_engine_control_and_output_above_model_cap(monkeypatch: pytest.MonkeyPatch,) -> None: