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): finish a tool call cut by the token limit as length (#971)

Shai Shmuel8959a350a281
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index 636460085..fc2959388 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -248,7 +248,9 @@ produces `Yes` (unsafe) or `No` (safe). A missing or invalid verdict returns
`invalid_guard_verdict`; never treat an error or an empty response as safe.
Private reasoning is hidden on both input surfaces. If it consumes the entire
generation budget, the answer is empty with `finish_reason` `"length"`; raise
-`max_tokens` to leave room for the answer. A model that stops without usable
+`max_tokens` to leave room for the answer. A tool call the budget cuts short is
+dropped the same way: the choice ends with `finish_reason` `"length"` and
+carries only the calls that completed. A model that stops without usable
output fails with `empty_model_output`.
## Connecting to SIE Serverless or a managed gateway
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 faab053da..7091393c2 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
@@ -383,6 +383,9 @@ class _ChoiceState:
# Set once the choice's terminal closure has been emitted so the
# global terminal does not double-emit.
closed: bool = False
+ # Set when the token limit ended generation inside an open tool-call
+ # block; the choice then finishes as ``length``.
+ truncated: bool = False
# Tool-call deltas observed so far (for parallel_tool_calls=false
# enforcement, currently sufficient as the boolean
# ``emitted_tool_call`` flag). Reserved field kept implicit.
@@ -513,6 +516,27 @@ def _process_text(
return out, False
+def _drop_call_cut_by_length(state: _ChoiceState, finish: str | None) -> bool:
+ """Drop a tool-call block the token limit cut short.
+
+ Returns True when ``state`` was inside an open block and the upstream
+ finish reason is ``length``. The partial call is discarded, not
+ surfaced: its arguments are incomplete, so a client could not run it.
+ The choice finishes as ``length`` so the client knows the output was
+ truncated. An open block under any other finish reason stays a parse
+ error.
+ """
+ if not state.in_tool_call or finish != "length":
+ return False
+ state.in_tool_call = False
+ state.tool_buffer = ""
+ # While a block is open ``text_buffer`` only holds the tail kept back
+ # for a close tag split across deltas; it is part of the dropped call.
+ state.text_buffer = ""
+ state.truncated = True
+ return True
+
+
def _close_choice(state: _ChoiceState, choice_index: int, fallback_finish: str | None) -> list[GenerationChunk]:
"""Emit the per-choice closure chunk for one candidate.
@@ -522,7 +546,7 @@ def _close_choice(state: _ChoiceState, choice_index: int, fallback_finish: str |
or any choice that did not see a per-choice finish event).
"""
out: list[GenerationChunk] = []
- if state.in_tool_call:
+ if state.in_tool_call and not _drop_call_cut_by_length(state, state.pending_finish or fallback_finish):
out.append(_parse_error_chunk("unterminated <tool_call> block"))
return out
if state.text_buffer:
@@ -536,7 +560,9 @@ def _close_choice(state: _ChoiceState, choice_index: int, fallback_finish: str |
)
state.text_buffer = ""
finish: FinishReason = (
- "tool_calls"
+ "length"
+ if state.truncated
+ else "tool_calls"
if state.emitted_tool_call
else cast("FinishReason", state.pending_finish or fallback_finish or "stop")
)
@@ -657,6 +683,10 @@ async def _parse_tool_call_stream_impl(
state.pending_completion_tokens = chunk.completion_tokens
for ev in _close_choice(state, idx, chunk.finish_reason):
yield ev
+ if ev.done:
+ # Parse error: terminal for the whole stream, so the
+ # global terminal must not close this choice again.
+ return
if chunk.done:
# Non-streaming ``n>1`` + tools (H5 non-streaming side): the
@@ -671,12 +701,14 @@ 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 ""
+ cut_by_length = isinstance(cand, dict) and cand.get("finish_reason") == "length"
try:
- parsed_text, parsed_calls = _parse_candidate_text(
+ parsed_text, parsed_calls, truncated = _parse_candidate_text(
cand_text,
tool_call_format,
schemas,
parallel_tool_calls=parallel_tool_calls,
+ drop_unterminated=cut_by_length,
)
except _ParallelToolCallsViolatedError:
logger.info(
@@ -688,7 +720,14 @@ async def _parse_tool_call_stream_impl(
yield _parallel_tool_calls_violation_chunk()
return
new_cand = dict(cand) if isinstance(cand, dict) else {}
- if parsed_calls:
+ if truncated:
+ # The token limit cut a later block short: keep
+ # the complete calls and the candidate's own
+ # ``length`` so the truncation stays visible.
+ new_cand["text"] = parsed_text
+ if parsed_calls:
+ new_cand["tool_calls"] = parsed_calls
+ elif parsed_calls:
# OpenAI non-streaming shape: message.content=null,
# message.tool_calls=[{id, type, function:{name, arguments}}].
# The gateway candidate builder surfaces this as
@@ -735,8 +774,10 @@ async def _parse_tool_call_stream_impl(
for cidx, st in list(states.items()):
if st.closed:
continue
- # Mid-tool-call at terminal → error (mirrors prior impl).
- if st.in_tool_call:
+ # Mid-tool-call at terminal → error, unless the token
+ # limit cut the block: then the stream finishes as
+ # ``length`` without the partial call.
+ if st.in_tool_call and not _drop_call_cut_by_length(st, chunk.finish_reason):
yield _parse_error_chunk("unterminated <tool_call> block")
return
if st.text_buffer:
@@ -756,7 +797,7 @@ async def _parse_tool_call_stream_impl(
# Single-candidate emitted a tool call? Surface tool_calls
# on the global terminal too so n=1 behaviour matches the
# original wrapper exactly.
- if len(states) == 1 and 0 in states and states[0].emitted_tool_call:
+ if len(states) == 1 and 0 in states and states[0].emitted_tool_call and not states[0].truncated:
global_finish = "tool_calls"
elif global_finish is None:
global_finish = "tool_calls" if any(s.emitted_tool_call for s in states.values()) else "stop"
@@ -808,12 +849,17 @@ def _parse_candidate_text(
schemas: ToolSchemas | None = None,
*,
parallel_tool_calls: bool = True,
-) -> tuple[str, list[dict]]:
+ drop_unterminated: bool = False,
+) -> tuple[str, list[dict], bool]:
"""Parse a single candidate's full text for ``<tool_call>`` blocks.
- Returns ``(text_outside_tool_blocks, tool_calls)`` where
+ Returns ``(text_outside_tool_blocks, tool_calls, truncated)`` where
``tool_calls`` is the OpenAI non-streaming wire shape:
- ``[{id, type, function: {name, arguments}}, ...]``.
+ ``[{id, type, function: {name, arguments}}, ...]``. ``truncated`` is
+ True when ``drop_unterminated`` is set (the candidate finished as
+ ``length``) and an unterminated block within the buffer cap was dropped
+ from the text, the rule the streaming path applies to a call the token
+ limit cut short.
Used by the non-streaming ``n>1`` + tools path: the worker's
multi-candidate adapter ships one terminal carrying the full text
@@ -829,9 +875,10 @@ def _parse_candidate_text(
"""
open_tag, close_tag = _tool_call_tags(tool_call_format)
if not text or open_tag not in text:
- return text, []
+ return text, [], False
out_text_parts: list[str] = []
tool_calls: list[dict] = []
+ truncated = False
cursor = 0
tool_index = 0
while cursor < len(text):
@@ -845,6 +892,12 @@ def _parse_candidate_text(
body_start = open_idx + len(open_tag)
close_idx = text.find(close_tag, body_start)
if close_idx == -1:
+ # A block past the buffer cap is not a call the token limit cut
+ # short: the streaming path fails it before the terminal. It
+ # stays in the text like any other malformed block.
+ if drop_unterminated and len(text) - body_start <= _MAX_TOOL_BUFFER_CHARS:
+ truncated = True
+ break
# Unterminated block: bail; surface the rest as text so the
# candidate's prose isn't silently lost.
out_text_parts.append(text[open_idx:])
@@ -873,7 +926,7 @@ def _parse_candidate_text(
)
tool_index += 1
cursor = close_idx + len(close_tag)
- return "".join(out_text_parts), tool_calls
+ return "".join(out_text_parts), tool_calls, truncated
def _tool_call_deltas(
diff --git a/packages/sie_server/tests/processors/test_tool_call_grammar_gemma4.py b/packages/sie_server/tests/processors/test_tool_call_grammar_gemma4.py
index 5e916cf67..a48e79336 100644
--- a/packages/sie_server/tests/processors/test_tool_call_grammar_gemma4.py
+++ b/packages/sie_server/tests/processors/test_tool_call_grammar_gemma4.py
@@ -29,7 +29,7 @@ def _accepts(pattern: str, text: str) -> bool:
accepted = re.fullmatch(pattern, text) is not None
if accepted:
# Everything the forcing grammar admits in these tests is a well-formed call.
- remaining, calls = _parse_candidate_text(text, "gemma4")
+ remaining, calls, _ = _parse_candidate_text(text, "gemma4")
assert remaining == ""
assert calls
return accepted
diff --git a/packages/sie_server/tests/processors/test_tool_call_parser_length.py b/packages/sie_server/tests/processors/test_tool_call_parser_length.py
new file mode 100644
index 000000000..174ad355a
--- /dev/null
+++ b/packages/sie_server/tests/processors/test_tool_call_parser_length.py
@@ -0,0 +1,219 @@
+"""A tool call cut short by the token limit finishes as ``length``, not as a parse error."""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+
+import pytest
+from sie_server.adapters._generation_base import GenerationChunk
+from sie_server.processors import tool_call_parser
+from sie_server.processors.tool_call_parser import parse_tool_call_stream
+
+_CALL = '<tool_call>{"name":"get_weather","arguments":{"city":"Tokyo"}}</tool_call>'
+# Ends on a prefix of the close tag, which the parser holds back in its text buffer.
+_CUT_CALL = '<tool_call>{"name":"get_weather","arguments":{"city":"To</tool_c'
+
+
+async def _chunks(items: list[GenerationChunk]) -> AsyncIterator[GenerationChunk]:
+ for item in items:
+ yield item
+
+
+async def _parse(items: list[GenerationChunk], **kwargs: object) -> list[GenerationChunk]:
+ return [item async for item in parse_tool_call_stream(_chunks(items), **kwargs)] # type: ignore[arg-type]
+
+
+def _text(out: list[GenerationChunk], choice: int = 0) -> str:
+ return "".join(chunk.text_delta for chunk in out if chunk.choice_index == choice)
+
+
+def _names(out: list[GenerationChunk], choice: int = 0) -> list[str]:
+ return [
+ chunk.tool_call_delta.function_name
+ for chunk in out
+ if chunk.choice_index == choice and chunk.tool_call_delta is not None and chunk.tool_call_delta.function_name
+ ]
+
+
+def _closures(out: list[GenerationChunk]) -> dict[int, str | None]:
+ return {chunk.choice_index: chunk.finish_reason for chunk in out if not chunk.done and chunk.finish_reason}
+
+
+def _assert_parse_error(out: list[GenerationChunk]) -> None:
+ assert out[-1].done is True
+ assert out[-1].finish_reason == "error"
+ assert out[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
+ assert out[-1].error_message == "unterminated <tool_call> block"
+
+
+async def test_single_choice_cut_by_length_finishes_as_length() -> None:
+ out = await _parse(
+ [
+ GenerationChunk(text_delta="Sure. "),
+ GenerationChunk(text_delta=_CUT_CALL),
+ GenerationChunk(text_delta="", done=True, finish_reason="length", prompt_tokens=7, completion_tokens=16),
+ ]
+ )
+
+ assert [chunk.done for chunk in out].count(True) == 1
+ terminal = out[-1]
+ assert terminal.finish_reason == "length"
+ assert terminal.error_code is None
+ assert (terminal.prompt_tokens, terminal.completion_tokens) == (7, 16)
+ # The partial call is dropped whole: no delta, and none of its text leaks.
+ assert all(chunk.tool_call_delta is None for chunk in out)
+ assert _text(out) == "Sure. "
+
+
[email protected]("finish_reason", ["stop", None])
+async def test_single_choice_unterminated_for_another_reason_stays_a_parse_error(finish_reason: str | None) -> None:
+ out = await _parse(
+ [
+ GenerationChunk(text_delta="Sure. " + _CUT_CALL),
+ GenerationChunk(text_delta="", done=True, finish_reason=finish_reason), # type: ignore[arg-type]
+ ]
+ )
+
+ _assert_parse_error(out)
+
+
+async def test_stream_ending_without_a_terminal_stays_a_parse_error() -> None:
+ out = await _parse([GenerationChunk(text_delta=_CUT_CALL)])
+
+ _assert_parse_error(out)
+
+
+async def test_complete_call_then_cut_call_keeps_the_first_and_finishes_as_length() -> None:
+ out = await _parse(
+ [
+ GenerationChunk(text_delta=_CALL + _CUT_CALL),
+ GenerationChunk(text_delta="", done=True, finish_reason="length"),
+ ]
+ )
+
+ assert _names(out) == ["get_weather"]
+ assert out[-1].done is True
+ assert out[-1].finish_reason == "length"
+ assert _text(out) == ""
+
+
+async def test_native_format_cut_by_length_finishes_as_length() -> None:
+ out = await _parse(
+ [
+ GenerationChunk(text_delta="Sure. <|tool_call>call:f{a:1"),
+ GenerationChunk(text_delta="", done=True, finish_reason="length"),
+ ],
+ tool_call_format="gemma4",
+ )
+
+ assert out[-1].finish_reason == "length"
+ assert all(chunk.tool_call_delta is None for chunk in out)
+ assert _text(out) == "Sure. "
+
+
+async def test_streamed_choices_close_independently_when_one_is_cut_by_length() -> None:
+ out = await _parse(
+ [
+ GenerationChunk(text_delta="A " + _CUT_CALL, choice_index=0),
+ GenerationChunk(text_delta="B " + _CALL + _CUT_CALL, choice_index=1),
+ GenerationChunk(text_delta="C " + _CALL, choice_index=2),
+ GenerationChunk(text_delta="", choice_index=0, finish_reason="length", completion_tokens=5),
+ GenerationChunk(text_delta="", choice_index=1, finish_reason="length"),
+ GenerationChunk(text_delta="", choice_index=2, finish_reason="length"),
+ GenerationChunk(text_delta="", done=True, finish_reason="length", prompt_tokens=3, completion_tokens=30),
+ ]
+ )
+
+ # Choice 2 was cut after a complete call, so it keeps ``tool_calls``.
+ assert _closures(out) == {0: "length", 1: "length", 2: "tool_calls"}
+ assert [_names(out, choice) for choice in range(3)] == [[], ["get_weather"], ["get_weather"]]
+ assert [_text(out, choice) for choice in range(3)] == ["A ", "B ", "C "]
+ closure_0 = next(chunk for chunk in out if chunk.choice_index == 0 and chunk.finish_reason == "length")
+ assert closure_0.completion_tokens == 5
+ assert out[-1].done is True
+ assert out[-1].error_code is None
+ assert (out[-1].prompt_tokens, out[-1].completion_tokens) == (3, 30)
+
+
+async def test_streamed_choice_unterminated_at_stop_stays_a_parse_error() -> None:
+ out = await _parse(
+ [
+ GenerationChunk(text_delta=_CUT_CALL, choice_index=0),
+ GenerationChunk(text_delta="fine", choice_index=1),
+ GenerationChunk(text_delta="", choice_index=0, finish_reason="stop"),
+ GenerationChunk(text_delta="", choice_index=1, finish_reason="length"),
+ GenerationChunk(text_delta="", done=True, finish_reason="length"),
+ ]
+ )
+
+ _assert_parse_error(out)
+
+
+async def test_streamed_choice_without_its_own_finish_uses_the_terminal_length() -> None:
+ out = await _parse(
+ [
+ GenerationChunk(text_delta="A " + _CUT_CALL, choice_index=0),
+ GenerationChunk(text_delta="B", choice_index=1),
+ GenerationChunk(text_delta="", done=True, finish_reason="length"),
+ ]
+ )
+
+ assert out[-1].done is True
+ assert out[-1].finish_reason == "length"
+ assert [_text(out, choice) for choice in range(2)] == ["A ", "B"]
+ assert all(chunk.tool_call_delta is None for chunk in out)
+
+
+async def test_buffered_candidates_cut_by_length_drop_the_partial_call() -> None:
+ candidates = (
+ {"text": "A " + _CUT_CALL, "finish_reason": "length", "logprobs": None},
+ {"text": "B " + _CALL + _CUT_CALL, "finish_reason": "length", "logprobs": None},
+ {"text": "C " + _CUT_CALL, "finish_reason": "stop", "logprobs": None},
+ {"text": "D " + _CALL, "finish_reason": "length", "logprobs": None},
+ )
+ out = await _parse([GenerationChunk(text_delta="", done=True, finish_reason="length", candidates=candidates)])
+
+ assert out[-1].done is True
+ assert out[-1].error_code is None
+ cut, call_then_cut, unterminated_at_stop, complete = out[-1].candidates or ()
+ assert cut == {"text": "A ", "finish_reason": "length", "logprobs": None}
+ assert call_then_cut["text"] == "B "
+ assert call_then_cut["finish_reason"] == "length"
+ assert [call["function"]["name"] for call in call_then_cut["tool_calls"]] == ["get_weather"]
+ # Not cut by the token limit: the malformed block stays in the text verbatim.
+ assert unterminated_at_stop == {"text": "C " + _CUT_CALL, "finish_reason": "stop", "logprobs": None}
+ assert complete["finish_reason"] == "tool_calls"
+
+
+async def test_open_block_past_the_buffer_cap_is_not_treated_as_cut_by_length(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(tool_call_parser, "_MAX_TOOL_BUFFER_CHARS", 64)
+ at_cap = "<tool_call>" + "x" * 64
+ over_cap = "<tool_call>" + "x" * 65
+
+ # Streaming: the cap fails the block before the ``length`` terminal arrives.
+ streamed = await _parse(
+ [GenerationChunk(text_delta=over_cap), GenerationChunk(text_delta="", done=True, finish_reason="length")]
+ )
+ assert streamed[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
+ assert "exceeded 64 chars" in (streamed[-1].error_message or "")
+
+ # Buffered: there is no per-candidate error channel, so the oversized block
+ # stays in the text verbatim, as it did before ``length`` handling existed.
+ candidates = (
+ {"text": "A " + at_cap, "finish_reason": "length", "logprobs": None},
+ {"text": "B " + over_cap, "finish_reason": "length", "logprobs": None},
+ )
+ out = await _parse([GenerationChunk(text_delta="", done=True, finish_reason="length", candidates=candidates)])
+ within, oversized = out[-1].candidates or ()
+ assert within["text"] == "A "
+ assert oversized == {"text": "B " + over_cap, "finish_reason": "length", "logprobs": None}