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(server): accept tool_choice and parallel_tool_calls on the MLX chat path (#729)

Krisztian Gajdara50706cb2090
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 78856291b..f15b2219d 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -172,8 +172,9 @@ _CUDA_CHAT_FIELDS = frozenset(
)
# mlx_lm's public chat request fields, excluding child process controls such as
-# model adapters and speculative-decoding configuration. Validate this boundary
-# before a potentially expensive MLX model download.
+# model adapters and speculative-decoding configuration, plus the tool-choice
+# fields this route resolves itself because mlx_lm reads neither. Validate this
+# boundary before a potentially expensive MLX model download.
_MLX_CHAT_FIELDS = frozenset(
{
"model",
@@ -195,6 +196,8 @@ _MLX_CHAT_FIELDS = frozenset(
"stream",
"stream_options",
"tools",
+ "tool_choice",
+ "parallel_tool_calls",
"role_mapping",
}
)
@@ -385,6 +388,47 @@ def _strict_output_error_response(message: str) -> JSONResponse:
)
+def _mlx_tool_call_limit(body: dict[str, Any], proxied: dict[str, Any]) -> int | None:
+ """Most tool calls one choice may carry, or ``None`` for no limit.
+
+ ``mlx_lm`` parses tool calls out of the model's output whether or not the
+ request offered tools, and never limits how many it returns.
+ """
+ if not proxied.get("tools"):
+ return 0
+ if body.get("parallel_tool_calls") is False:
+ return 1
+ return None
+
+
+def _excess_tool_call(payload: dict[str, Any], limit: int, calls: dict[int, set[object]]) -> str | None:
+ """Record each choice's distinct tool calls and describe the first over ``limit``."""
+ choices = payload.get("choices")
+ if not isinstance(choices, list):
+ return None
+ for position, choice in enumerate(choices):
+ if not isinstance(choice, dict):
+ continue
+ choice_obj = cast("dict[str, Any]", choice)
+ raw_index = choice_obj.get("index", position)
+ index = raw_index if isinstance(raw_index, int) and not isinstance(raw_index, bool) else position
+ delta = choice_obj.get("delta")
+ message = choice_obj.get("message")
+ container = message if isinstance(message, dict) else delta if isinstance(delta, dict) else None
+ tool_calls = container.get("tool_calls") if container is not None else None
+ if not isinstance(tool_calls, list) or not tool_calls:
+ continue
+ seen = calls.setdefault(index, set())
+ for call in tool_calls:
+ key = call.get("index") if container is delta and isinstance(call, dict) else None
+ seen.add(key if isinstance(key, int) and not isinstance(key, bool) else object())
+ if len(seen) > limit:
+ if limit == 0:
+ return "generation child returned a tool call the request did not offer"
+ return "generation child returned more than one tool call with parallel_tool_calls=false"
+ return None
+
+
def _validate_optional_positive_int(body: dict[str, Any], field: str) -> int | None:
value = body.get(field)
if value is None:
@@ -590,6 +634,13 @@ def _validate_mlx_chat_body(body: dict[str, Any]) -> None:
raise _bad_request(f"field '{unknown}' is not supported", param=unknown, code="unsupported_field")
_validate_common_chat_body(body)
+ choice = body.get("tool_choice")
+ if choice is not None and choice not in ("auto", "none"):
+ raise _bad_request(
+ "'tool_choice' must be 'auto' or 'none' on this device, which cannot force a tool call",
+ param="tool_choice",
+ code="unsupported_field",
+ )
min_p = body.get("min_p")
if min_p is not None and (isinstance(min_p, bool) or not isinstance(min_p, int | float) or not 0 <= min_p <= 1):
@@ -905,6 +956,9 @@ def _prepare_mlx_body(
proxied["max_tokens"] = requested_cap if requested_cap is not None else cap
# mlx_lm versions used by the Mac bundle consume the legacy field.
proxied.pop("max_completion_tokens", None)
+ proxied.pop("parallel_tool_calls", None)
+ if proxied.pop("tool_choice", None) == "none":
+ proxied.pop("tools", None)
if seed is not None:
proxied["seed"] = seed
@@ -1021,11 +1075,13 @@ async def _sanitize_sse_stream(
initial_inside_thinking: bool,
reasoning_format: ReasoningFormat,
slot: asyncio.Semaphore | None,
+ tool_call_limit: int | None = None,
strict_grammar: GrammarSpec | None = None,
) -> AsyncIterator[bytes]:
states: dict[int, ThinkingBlockStripper] = {}
strict_contents: dict[int, list[str]] = {}
strict_tool_choices: set[int] = set()
+ tool_calls: dict[int, set[object]] = {}
buffered = bytearray()
received = 0
saw_done = False
@@ -1082,6 +1138,12 @@ async def _sanitize_sse_stream(
error_type="server_error",
)
return
+ if tool_call_limit is not None:
+ excess = _excess_tool_call(sanitized, tool_call_limit, tool_calls)
+ if excess is not None:
+ terminal_outcome_selected = True
+ yield _upstream_error_event(excess)
+ return
encoded = json.dumps(sanitized, separators=(",", ":"), ensure_ascii=False).encode()
yield b"data: " + encoded + b"\n"
@@ -1460,6 +1522,7 @@ async def _chat_completions(
)
slot: asyncio.Semaphore | None = None
reasoning_parser: str | None = None
+ tool_call_limit: int | None = None
if isinstance(adapter, MLXGenerationAdapter) and not str(device).startswith("cuda"):
if adapter.mlx_repo is None:
raise _unsupported_chat(model, device)
@@ -1473,6 +1536,7 @@ async def _chat_completions(
max_tokens=max_tokens,
seed=seed,
)
+ tool_call_limit = _mlx_tool_call_limit(body, proxied)
slot = adapter.generation_slot()
elif isinstance(adapter, SGLangGenerationAdapter) and str(device).startswith("cuda"):
server_url = adapter.server_url
@@ -1566,6 +1630,7 @@ async def _chat_completions(
initial_inside_thinking=initial_inside_thinking,
reasoning_format=reasoning_format,
slot=slot,
+ tool_call_limit=tool_call_limit,
strict_grammar=strict_grammar,
),
media_type="text/event-stream",
@@ -1611,6 +1676,8 @@ async def _chat_completions(
violation = await _strict_output_violation(strict_grammar, _completed_choice_contents(payload))
if violation is not None:
return _strict_output_error_response(violation)
+ if tool_call_limit is not None and (excess := _excess_tool_call(payload, tool_call_limit, {})) is not None:
+ return _upstream_error_response(excess)
return JSONResponse(content=payload, headers=route.headers())
diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.py
index 607cfad63..e7df2eb5e 100644
--- a/packages/sie_server/tests/api/test_openai_local.py
+++ b/packages/sie_server/tests/api/test_openai_local.py
@@ -422,6 +422,299 @@ def test_mlx_chat_rejects_child_process_controls_before_model_load(
registry.get.assert_not_called()
+_WEATHER_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+ },
+}
+_PARIS_CALL = {
+ "id": "call_paris",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},
+}
+_TOKYO_CALL = {
+ "id": "call_tokyo",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Tokyo"}'},
+}
+_AFTER_A_TOOL_TURN = [
+ {"role": "user", "content": "Weather in Paris?"},
+ {"role": "assistant", "content": None, "tool_calls": [_PARIS_CALL]},
+ {"role": "tool", "tool_call_id": "call_paris", "content": "18C, clear"},
+ {"role": "user", "content": "And in Tokyo?"},
+]
+
+
+def _mlx_tool_call_stream(*calls: dict[str, Any]) -> _ChunkedAsyncStream:
+ """An mlx_lm.server chat stream: one delta per completed call, then the finish event."""
+ events = [
+ {
+ "id": "chatcmpl-mlx",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "mlx-community/Qwen3.5-4B-4bit",
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": None,
+ "delta": {"role": "assistant", "tool_calls": [{**call, "index": i}]},
+ }
+ ],
+ }
+ for i, call in enumerate(calls)
+ ]
+ events.append(
+ {
+ "id": "chatcmpl-mlx",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "mlx-community/Qwen3.5-4B-4bit",
+ "choices": [{"index": 0, "finish_reason": "tool_calls", "delta": {"role": "assistant"}}],
+ }
+ )
+ return _ChunkedAsyncStream([f"data: {json.dumps(event)}\n\n".encode() for event in events] + [b"data: [DONE]\n\n"])
+
+
+def _sse_events(response_text: str) -> list[dict[str, Any]]:
+ lines = [line.removeprefix("data: ") for line in response_text.splitlines() if line.startswith("data: ")]
+ assert lines[-1] == "[DONE]"
+ return [json.loads(line) for line in lines[:-1]]
+
+
+ "tool_fields",
+ [
+ {"tool_choice": "auto"},
+ {"tool_choice": "auto", "parallel_tool_calls": True},
+ {"parallel_tool_calls": True},
+ ],
+)
+def test_mlx_chat_accepts_auto_tool_choice_and_returns_every_call(
+ monkeypatch: pytest.MonkeyPatch,
+ tool_fields: dict[str, Any],
+) -> None:
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(
+ 200, json=_chat_completion(None, finish_reason="tool_calls", tool_calls=[_PARIS_CALL, _TOKYO_CALL])
+ )
+
+ client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "Qwen/Qwen3.5-4B",
+ "messages": [{"role": "user", "content": "Weather in Paris and Tokyo?"}],
+ "tools": [_WEATHER_TOOL],
+ **tool_fields,
+ },
+ )
+
+ assert response.status_code == 200
+ assert seen["body"]["tools"] == [_WEATHER_TOOL]
+ assert "tool_choice" not in seen["body"]
+ assert "parallel_tool_calls" not in seen["body"]
+ completion = ChatCompletion.model_validate(response.json())
+ assert completion.choices[0].finish_reason == "tool_calls"
+ assert [call.id for call in completion.choices[0].message.tool_calls or []] == ["call_paris", "call_tokyo"]
+
+
+def test_mlx_chat_streams_every_tool_call_under_auto(monkeypatch: pytest.MonkeyPatch) -> None:
+ seen: dict[str, Any] = {}
+ upstream_stream = _mlx_tool_call_stream(_PARIS_CALL, _TOKYO_CALL)
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(200, stream=upstream_stream, headers={"content-type": "text/event-stream"})
+
+ client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "Qwen/Qwen3.5-4B",
+ "messages": [{"role": "user", "content": "Weather in Paris and Tokyo?"}],
+ "tools": [_WEATHER_TOOL],
+ "tool_choice": "auto",
+ "stream": True,
+ },
+ )
+
+ assert response.status_code == 200
+ assert seen["body"]["tools"] == [_WEATHER_TOOL]
+ assert "tool_choice" not in seen["body"]
+ chunks = [ChatCompletionChunk.model_validate(event) for event in _sse_events(response.text)]
+ streamed = [call for chunk in chunks for call in chunk.choices[0].delta.tool_calls or []]
+ assert [(call.index, call.id) for call in streamed] == [(0, "call_paris"), (1, "call_tokyo")]
+ assert chunks[-1].choices[0].finish_reason == "tool_calls"
+ assert upstream_stream.closed is True
+
+
[email protected]("stream", [False, True])
+def test_mlx_chat_parallel_tool_calls_false_returns_a_single_call(
+ monkeypatch: pytest.MonkeyPatch, stream: bool
+) -> None:
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ if stream:
+ return httpx.Response(
+ 200, stream=_mlx_tool_call_stream(_PARIS_CALL), headers={"content-type": "text/event-stream"}
+ )
+ return httpx.Response(200, json=_chat_completion(None, finish_reason="tool_calls", tool_calls=[_PARIS_CALL]))
+
+ client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "Qwen/Qwen3.5-4B",
+ "messages": [{"role": "user", "content": "Weather in Paris?"}],
+ "tools": [_WEATHER_TOOL],
+ "tool_choice": "auto",
+ "parallel_tool_calls": False,
+ "stream": stream,
+ },
+ )
+
+ assert response.status_code == 200
+ assert seen["body"]["tools"] == [_WEATHER_TOOL]
+ assert "parallel_tool_calls" not in seen["body"]
+ if stream:
+ events = _sse_events(response.text)
+ assert [call["id"] for event in events for call in event["choices"][0]["delta"].get("tool_calls", [])] == [
+ "call_paris"
+ ]
+ assert events[-1]["choices"][0]["finish_reason"] == "tool_calls"
+ else:
+ assert [call["id"] for call in response.json()["choices"][0]["message"]["tool_calls"]] == ["call_paris"]
+
+
+def test_mlx_chat_tool_choice_none_withholds_tools_from_the_child(monkeypatch: pytest.MonkeyPatch) -> None:
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(200, json=_chat_completion("It is sunny."))
+
+ client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "Qwen/Qwen3.5-4B",
+ "messages": [{"role": "user", "content": "Weather in Paris?"}],
+ "tools": [_WEATHER_TOOL],
+ "tool_choice": "none",
+ },
+ )
+
+ assert response.status_code == 200
+ assert "tools" not in seen["body"]
+ assert "tool_choice" not in seen["body"]
+ assert response.json()["choices"][0]["message"]["content"] == "It is sunny."
+
+
[email protected]("stream", [False, True])
+ ("tool_fields", "calls", "delivered", "message"),
+ [
+ (
+ {"tools": [_WEATHER_TOOL], "parallel_tool_calls": False},
+ [_PARIS_CALL, _TOKYO_CALL],
+ ["call_paris"],
+ "generation child returned more than one tool call with parallel_tool_calls=false",
+ ),
+ (
+ {"tools": [_WEATHER_TOOL], "tool_choice": "none"},
+ [_TOKYO_CALL],
+ [],
+ "generation child returned a tool call the request did not offer",
+ ),
+ (
+ {},
+ [_TOKYO_CALL],
+ [],
+ "generation child returned a tool call the request did not offer",
+ ),
+ ],
+ ids=["parallel_tool_calls_false", "tool_choice_none", "no_tools"],
+)
+def test_mlx_chat_fails_closed_on_tool_calls_the_request_ruled_out(
+ monkeypatch: pytest.MonkeyPatch,
+ stream: bool,
+ tool_fields: dict[str, Any],
+ calls: list[dict[str, Any]],
+ delivered: list[str],
+ message: str,
+) -> None:
+ upstream_stream = _mlx_tool_call_stream(*calls)
+
+ def _handler(_request: httpx.Request) -> httpx.Response:
+ if stream:
+ return httpx.Response(200, stream=upstream_stream, headers={"content-type": "text/event-stream"})
+ return httpx.Response(200, json=_chat_completion(None, finish_reason="tool_calls", tool_calls=calls))
+
+ client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _AFTER_A_TOOL_TURN, "stream": stream, **tool_fields},
+ )
+
+ error = {"error": {"message": message, "type": "upstream_error", "param": None, "code": "upstream_error"}}
+ if not stream:
+ assert response.status_code == 502
+ assert response.json() == error
+ return
+ assert response.status_code == 200
+ events = _sse_events(response.text)
+ assert events[-1] == error
+ streamed = [call["id"] for event in events[:-1] for call in event["choices"][0]["delta"].get("tool_calls", [])]
+ assert streamed == delivered
+ assert all(event["choices"][0]["finish_reason"] is None for event in events[:-1])
+ assert upstream_stream.closed is True
+
+
[email protected]("device", ["mps", "cpu"])
+ "tool_choice",
+ ["required", {"type": "function", "function": {"name": "get_weather"}}],
+)
+def test_mlx_chat_refuses_a_forced_tool_choice_before_model_load(
+ monkeypatch: pytest.MonkeyPatch,
+ device: str,
+ tool_choice: Any,
+) -> None:
+ client, registry = _mlx_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("refused request must not reach upstream"),
+ chat_template_kwargs={"enable_thinking": False},
+ )
+ registry.device = device
+
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "Qwen/Qwen3.5-4B",
+ "messages": [{"role": "user", "content": "Weather in Paris?"}],
+ "tools": [_WEATHER_TOOL],
+ "tool_choice": tool_choice,
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"] == {
+ "code": "unsupported_field",
+ "message": "'tool_choice' must be 'auto' or 'none' on this device, which cannot force a tool call",
+ "param": "tool_choice",
+ "type": "invalid_request_error",
+ }
+ registry.is_loaded.assert_not_called()
+ registry.get.assert_not_called()
+
+
@pytest.mark.parametrize(
("chat_template_kwargs", "code"),
[