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): enforce parallel_tool_calls=false on non-streaming n>1 candidates (#960)

Krisztian Gajdar1332c10c11cb
diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
index 6c383d6b8..faab053da 100644
--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py
+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
@@ -671,7 +671,22 @@ async def _parse_tool_call_stream_impl(
any_tool_call = False
for cand in chunk.candidates:
cand_text = cand.get("text", "") if isinstance(cand, dict) else ""
- parsed_text, parsed_calls = _parse_candidate_text(cand_text, tool_call_format, schemas)
+ try:
+ parsed_text, parsed_calls = _parse_candidate_text(
+ cand_text,
+ tool_call_format,
+ schemas,
+ parallel_tool_calls=parallel_tool_calls,
+ )
+ except _ParallelToolCallsViolatedError:
+ logger.info(
+ "parallel_tool_calls=false: candidate %d opened a second tool-call block; "
+ "terminating with %s",
+ len(updated_candidates),
+ _PARALLEL_TOOL_CALLS_VIOLATED,
+ )
+ yield _parallel_tool_calls_violation_chunk()
+ return
new_cand = dict(cand) if isinstance(cand, dict) else {}
if parsed_calls:
# OpenAI non-streaming shape: message.content=null,
@@ -783,10 +798,16 @@ async def _parse_tool_call_stream_impl(
yield GenerationChunk(text_delta="", done=True, finish_reason="tool_calls" if any_tool else "stop")
+class _ParallelToolCallsViolatedError(Exception):
+ """A candidate opened a second tool-call block under ``parallel_tool_calls=false``."""
+
+
def _parse_candidate_text(
text: str,
tool_call_format: ToolCallFormat,
schemas: ToolSchemas | None = None,
+ *,
+ parallel_tool_calls: bool = True,
) -> tuple[str, list[dict]]:
"""Parse a single candidate's full text for ``<tool_call>`` blocks.
@@ -801,6 +822,10 @@ def _parse_candidate_text(
candidate's text verbatim: the non-streaming path has no channel for
a per-candidate parse error, and dropping the block would let a
candidate whose only call was malformed finish as an ordinary answer.
+
+ With ``parallel_tool_calls=False``, a block opened after a parsed call
+ raises :class:`_ParallelToolCallsViolatedError`, the rule the streaming
+ path applies to each choice.
"""
open_tag, close_tag = _tool_call_tags(tool_call_format)
if not text or open_tag not in text:
@@ -814,6 +839,8 @@ def _parse_candidate_text(
if open_idx == -1:
out_text_parts.append(text[cursor:])
break
+ if not parallel_tool_calls and tool_calls:
+ raise _ParallelToolCallsViolatedError
out_text_parts.append(text[cursor:open_idx])
body_start = open_idx + len(open_tag)
close_idx = text.find(close_tag, body_start)
diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.py
index 5d299db7e..f312dc84f 100644
--- a/packages/sie_server/tests/processors/test_tool_call_parser.py
+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py
@@ -1088,3 +1088,93 @@ async def test_arguments_too_large_for_one_queue_message_end_with_a_parse_error(
assert out[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
assert "bytes, exceeds" in (out[-1].error_message or "")
assert not _deltas(out)
+
+
+def _hermes_call(name: str, **values: str) -> str:
+ return "<tool_call>" + json.dumps({"name": name, "arguments": values}) + "</tool_call>"
+
+
+_CANDIDATE_FORMATS = [
+ pytest.param("hermes_json", _hermes_call, id="hermes_json"),
+ pytest.param("qwen_xml", _qwen_call, id="qwen_xml"),
+]
+
+
+async def _parse_candidates(
+ texts: list[str], tool_call_format: str, *, parallel_tool_calls: bool
+) -> list[GenerationChunk]:
+ candidates = tuple({"text": text, "finish_reason": "stop", "logprobs": None} for text in texts)
+ return [
+ item
+ async for item in parse_tool_call_stream(
+ _chunks([GenerationChunk(text_delta="", done=True, finish_reason="stop", candidates=candidates)]),
+ tool_call_format=tool_call_format,
+ parallel_tool_calls=parallel_tool_calls,
+ tools=[_EDIT_TOOL],
+ )
+ ]
+
+
[email protected](("tool_call_format", "call"), _CANDIDATE_FORMATS)
+async def test_non_streaming_candidate_with_a_second_call_violates_parallel_tool_calls(
+ tool_call_format: str, call
+) -> None:
+ out = await _parse_candidates(
+ [call("edit_file", path="a"), call("edit_file", path="b") + call("edit_file", path="c")],
+ tool_call_format,
+ parallel_tool_calls=False,
+ )
+
+ terminal = out[-1]
+ assert terminal.done is True
+ assert terminal.finish_reason == "error"
+ assert terminal.error_code == "parallel_tool_calls_violated"
+ assert not terminal.candidates
+
+
[email protected](("tool_call_format", "call"), _CANDIDATE_FORMATS)
+async def test_non_streaming_candidates_with_one_call_each_pass_parallel_tool_calls_false(
+ tool_call_format: str, call
+) -> None:
+ out = await _parse_candidates(
+ [call("edit_file", path="a"), "Calling " + call("edit_file", path="b") + " done"],
+ tool_call_format,
+ parallel_tool_calls=False,
+ )
+
+ terminal = out[-1]
+ assert terminal.error_code is None
+ assert terminal.finish_reason == "tool_calls"
+ assert [len(candidate["tool_calls"]) for candidate in terminal.candidates] == [1, 1]
+
+
[email protected](("tool_call_format", "call"), _CANDIDATE_FORMATS)
+async def test_non_streaming_candidate_keeps_every_call_when_parallel_tool_calls_is_true(
+ tool_call_format: str, call
+) -> None:
+ out = await _parse_candidates(
+ [call("edit_file", path="a") + call("edit_file", path="b")],
+ tool_call_format,
+ parallel_tool_calls=True,
+ )
+
+ (candidate,) = out[-1].candidates
+ assert [json.loads(tc["function"]["arguments"])["path"] for tc in candidate["tool_calls"]] == ["a", "b"]
+
+
+async def test_non_streaming_candidate_with_a_malformed_first_block_keeps_one_call_under_parallel_false() -> None:
+ malformed = "<tool_call>{not json</tool_call>"
+ out = await _parse_candidates(
+ [malformed + _hermes_call("edit_file", path="a")],
+ "hermes_json",
+ parallel_tool_calls=False,
+ )
+
+ (candidate,) = out[-1].candidates
+ assert out[-1].error_code is None
+ assert candidate["text"] == malformed
+ assert [tc["function"]["name"] for tc in candidate["tool_calls"]] == ["edit_file"]