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): convert queued tool-call arguments by the declared schema (#609)
Krisztian Gajdar5f0047091c90
diff --git a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.pyindex 5084dff0a..3c5db183b 100644--- a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py+++ b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py@@ -165,6 +165,7 @@ async def prepare_rendered_chat(chunks,tool_call_format=_tool_format(config),parallel_tool_calls=body.get("parallel_tool_calls") is not False,+ tools=tools,)chunks = bound_generation(chunks, resolve_generation_timeouts(config, None))return _events(chunks, body, requested_model)diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 4dc6d1985..df8037711 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -2336,6 +2336,7 @@ class StreamingProcessor:chunks_iter,tool_call_format=tool_call_format,parallel_tool_calls=parallel_tool_calls,+ tools=tools,)chunks_iter = enforce_strict_grammar(chunks_iter, grammar)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.pyindex 44081969e..4f0d786fa 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@@ -9,6 +9,11 @@ This first implementation emits arguments atomically when the closing tag arriveIt is intentionally strict: malformed JSON or missing ``name``/``arguments``turns into a terminal ``MODEL_OUTPUT_PARSE_ERROR`` chunk.+The XML forms carry every argument value as text. Each value is converted by+the JSON-schema type its parameter declares in the request's ``tools``: a+string parameter keeps its exact text, and a value that does not convert, or+that belongs to an undeclared tool or parameter, stays a string.+For streaming ``n>1`` the parser maintains independent per-candidate statekeyed by ``chunk.choice_index`` (H5): each candidate's tool-call deltassurface tagged with the same ``choice_index`` they came in on, so the@@ -17,13 +22,15 @@ gateway can fan tool calls out per candidate.from __future__ import annotations+import astimport jsonimport logging+import mathimport reimport uuid-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mapping, Sequencefrom dataclasses import dataclass, field-from typing import Literal, cast+from typing import Any, Literal, castfrom sie_server.adapters._generation_base import (FinishReason,@@ -71,12 +78,204 @@ _MAX_TEXT_BUFFER_CHARS = 256 * 1024# to ``json.dumps`` back out._MAX_TOOL_ARGUMENTS_CHARS = 64 * 1024+ToolSchemas = Mapping[str, Mapping[str, Any]]++_STRING_TYPES = frozenset({"string", "str", "text", "varchar", "char", "enum"})+_INTEGER_TYPE_PREFIXES = ("int", "uint", "long", "short", "unsigned")+_NUMBER_TYPE_PREFIXES = ("num", "float")+_CONTAINER_TYPES = frozenset({"object", "array", "arr"})+_CONTAINER_TYPE_PREFIXES = ("dict", "list")+_MAX_SCHEMA_DEPTH = 32+++def tool_parameter_schemas(tools: Sequence[Mapping[str, Any]] | None) -> dict[str, Mapping[str, Any]]:+ """Map each declared function name in an OpenAI ``tools`` array to its ``parameters`` schema."""+ schemas: dict[str, Mapping[str, Any]] = {}+ for tool in tools or ():+ if not isinstance(tool, Mapping):+ continue+ function = tool.get("function")+ if not isinstance(function, Mapping):+ continue+ name = function.get("name")+ if not isinstance(name, str) or not name:+ continue+ parameters = function.get("parameters")+ schemas[name] = parameters if isinstance(parameters, Mapping) else {}+ return schemas+++def _resolve_ref(schema: Any, root: Mapping[str, Any]) -> Any:+ """Follow local ``#/...`` JSON pointers. An unresolvable reference yields ``None``."""+ for _ in range(_MAX_SCHEMA_DEPTH):+ if not isinstance(schema, Mapping):+ return schema+ ref = schema.get("$ref")+ if not isinstance(ref, str):+ return schema+ if ref == "#":+ schema = root+ continue+ if not ref.startswith("#/"):+ return None+ node: Any = root+ for part in ref[2:].split("/"):+ part = part.replace("~1", "/").replace("~0", "~")+ if not isinstance(node, Mapping) or part not in node:+ return None+ node = node[part]+ schema = node+ return None+++def _enum_type(values: list[object]) -> str:+ kinds: set[str] = set()+ for value in values:+ if value is None:+ kinds.add("null")+ elif isinstance(value, bool):+ kinds.add("boolean")+ elif isinstance(value, int):+ kinds.add("integer")+ elif isinstance(value, float):+ kinds.add("number")+ elif isinstance(value, str):+ kinds.add("string")+ elif isinstance(value, list):+ kinds.add("array")+ elif isinstance(value, dict):+ kinds.add("object")+ return kinds.pop() if len(kinds) == 1 else "string"+++def _schema_type(schema: Any, root: Mapping[str, Any], depth: int = 0) -> str | None:+ """Infer one conversion type from a parameter schema, as SGLang's ``infer_type_from_json_schema`` does."""+ schema = _resolve_ref(schema, root)+ if not isinstance(schema, Mapping) or depth > _MAX_SCHEMA_DEPTH:+ return None+ declared = schema.get("type")+ if isinstance(declared, str):+ return declared.strip().lower()+ if isinstance(declared, list) and declared:+ non_null = [str(kind) for kind in declared if kind != "null"]+ return non_null[0].strip().lower() if non_null else "string"+ variants = schema.get("anyOf") or schema.get("oneOf")+ if isinstance(variants, list):+ kinds = [kind for kind in (_schema_type(variant, root, depth + 1) for variant in variants) if kind]+ if kinds:+ distinct = set(kinds)+ if len(distinct) == 1:+ return kinds[0]+ if len(distinct) == 2 and "null" in distinct: # noqa: PLR2004 - optional type pair+ return next(kind for kind in kinds if kind != "null")+ return "string" if "string" in distinct else kinds[0]+ enum = schema.get("enum")+ if isinstance(enum, list):+ return _enum_type(enum) if enum else "string"+ all_of = schema.get("allOf")+ if isinstance(all_of, list):+ for variant in all_of:+ kind = _schema_type(variant, root, depth + 1)+ if kind and kind != "string":+ return kind+ return "string"+ if "properties" in schema:+ return "object"+ if "items" in schema:+ return "array"+ return None+++def _schema_allows_null(schema: Any, root: Mapping[str, Any], depth: int = 0) -> bool:+ schema = _resolve_ref(schema, root)+ if not isinstance(schema, Mapping) or depth > _MAX_SCHEMA_DEPTH:+ return False+ declared = schema.get("type")+ if schema.get("nullable") is True or declared == "null" or (isinstance(declared, list) and "null" in declared):+ return True+ enum = schema.get("enum")+ if isinstance(enum, list) and None in enum:+ return True+ return any(+ isinstance(variants, list) and any(_schema_allows_null(variant, root, depth + 1) for variant in variants)+ for variants in (schema.get("anyOf"), schema.get("oneOf"))+ )+++def _reject_constant(constant: str) -> object:+ raise ValueError(f"non-finite JSON constant {constant}")+++def _loads_json(text: str) -> object:+ return json.loads(text, parse_constant=_reject_constant)+++def _convert_argument(raw: str, schema: Any, root: Mapping[str, Any]) -> object:+ """Convert one XML argument value by its declared type.++ ``schema is None`` marks an undeclared tool or parameter, which keeps the raw+ text. A value that does not convert to its declared type also keeps the raw+ text, so the client's own validation can report it to the model.+ """+ if schema is None:+ return raw+ kind = _schema_type(schema, root) or "string"+ text = raw.strip()+ if text.lower() == "null" and (kind not in _STRING_TYPES or _schema_allows_null(schema, root)):+ return None+ if kind in _STRING_TYPES:+ return raw+ if kind.startswith(_INTEGER_TYPE_PREFIXES):+ try:+ return int(text)+ except ValueError:+ return raw+ if kind.startswith(_NUMBER_TYPE_PREFIXES):+ if "." not in text and "e" not in text.lower():+ try:+ return int(text)+ except ValueError:+ pass+ try:+ number = float(text)+ except ValueError:+ return raw+ return number if math.isfinite(number) else raw+ if kind in ("boolean", "bool", "binary"):+ lowered = text.lower()+ return lowered == "true" if lowered in ("true", "false") else raw+ try:+ return _loads_json(text)+ except (ValueError, RecursionError):+ pass+ if kind in _CONTAINER_TYPES or kind.startswith(_CONTAINER_TYPE_PREFIXES):+ try:+ value = ast.literal_eval(text)+ if isinstance(value, dict | list):+ json.dumps(value, allow_nan=False)+ return value+ except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):+ pass+ return raw+++def _parameter_schema(schemas: ToolSchemas, name: str, key: str) -> tuple[Any, Mapping[str, Any]]:+ """Return ``(parameter schema or None, tool parameters root)`` for one argument."""+ root = schemas.get(name)+ if root is None:+ return None, {}+ properties = root.get("properties")+ if not isinstance(properties, Mapping):+ return None, root+ return properties.get(key), root+async def parse_tool_call_stream(chunks: AsyncIterator[GenerationChunk],*,tool_call_format: ToolCallFormat = "auto",parallel_tool_calls: bool = True,+ tools: Sequence[Mapping[str, Any]] | None = None,) -> AsyncIterator[GenerationChunk]:"""Tool-call parsing wrapper that guarantees the upstream is closed.@@ -94,6 +293,7 @@ async def parse_tool_call_stream(chunks,tool_call_format=tool_call_format,parallel_tool_calls=parallel_tool_calls,+ schemas=tool_parameter_schemas(tools),):if out.done:terminal_outcome_selected = True@@ -157,6 +357,7 @@ def _process_text(choice_index: int,tool_call_format: ToolCallFormat,parallel_tool_calls: bool,+ schemas: ToolSchemas,) -> tuple[list[GenerationChunk], bool]:"""Run one text delta through the per-choice parser.@@ -193,7 +394,7 @@ def _process_text(continuestate.tool_buffer += incoming[cursor:close_idx]try:- deltas = _tool_call_deltas(state.tool_buffer, state.tool_index, tool_call_format)+ deltas = _tool_call_deltas(state.tool_buffer, state.tool_index, tool_call_format, schemas)except ValueError as exc:out.append(_parse_error_chunk(str(exc)))return out, True@@ -314,6 +515,7 @@ async def _parse_tool_call_stream_impl(*,tool_call_format: ToolCallFormat = "auto",parallel_tool_calls: bool = True,+ schemas: ToolSchemas | None = None,) -> AsyncIterator[GenerationChunk]:"""Convert tagged text chunks into OpenAI-compatible tool-call deltas.@@ -342,6 +544,7 @@ async def _parse_tool_call_stream_impl(terminal then closes any choices that did not see a per-choiceclosure and surfaces aggregate usage."""+ schemas = schemas or {}states: dict[int, _ChoiceState] = {}def _state(idx: int) -> _ChoiceState:@@ -375,6 +578,7 @@ async def _parse_tool_call_stream_impl(choice_index=idx,tool_call_format=tool_call_format,parallel_tool_calls=parallel_tool_calls,+ schemas=schemas,)for ev in emitted:yield ev@@ -414,7 +618,7 @@ async def _parse_tool_call_stream_impl(any_tool_call = Falsefor 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)+ parsed_text, parsed_calls = _parse_candidate_text(cand_text, tool_call_format, schemas)new_cand = dict(cand) if isinstance(cand, dict) else {}if parsed_calls:# OpenAI non-streaming shape: message.content=null,@@ -522,7 +726,11 @@ async def _parse_tool_call_stream_impl(yield GenerationChunk(text_delta="", done=True, finish_reason="tool_calls" if any_tool else "stop")-def _parse_candidate_text(text: str, tool_call_format: ToolCallFormat) -> tuple[str, list[dict]]:+def _parse_candidate_text(+ text: str,+ tool_call_format: ToolCallFormat,+ schemas: ToolSchemas | None = None,+) -> tuple[str, list[dict]]:"""Parse a single candidate's full text for ``<tool_call>`` blocks.Returns ``(text_outside_tool_blocks, tool_calls)`` where@@ -532,11 +740,10 @@ def _parse_candidate_text(text: str, tool_call_format: ToolCallFormat) -> tuple[Used by the non-streaming ``n>1`` + tools path: the worker'smulti-candidate adapter ships one terminal carrying the full textof each candidate, and each candidate needs its own tool-call- aggregation (H5 non-streaming side). On malformed blocks the- candidate's surrounding text is preserved verbatim and the- malformed block is skipped — the non-streaming path doesn't have a- natural channel for a per-candidate parse error, so we degrade- gracefully rather than failing the whole multi-candidate batch.+ aggregation (H5 non-streaming side). A malformed block stays in the+ 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."""if not text or _OPEN not in text:return text, []@@ -559,11 +766,9 @@ def _parse_candidate_text(text: str, tool_call_format: ToolCallFormat) -> tuple[breakbody = text[body_start:close_idx]try:- deltas = _tool_call_deltas(body, tool_index, tool_call_format)+ deltas = _tool_call_deltas(body, tool_index, tool_call_format, schemas)except ValueError:- # Malformed tool body — drop it and keep going. The candidate- # batch is non-streaming, so partial failure of one block in- # one candidate must not poison the rest.+ out_text_parts.append(text[open_idx : close_idx + len(_CLOSE)])cursor = close_idx + len(_CLOSE)continue# ``_tool_call_deltas`` returns two deltas per call: announcement@@ -586,7 +791,12 @@ def _parse_candidate_text(text: str, tool_call_format: ToolCallFormat) -> tuple[return "".join(out_text_parts), tool_calls-def _tool_call_deltas(raw: str, index: int, tool_call_format: ToolCallFormat = "auto") -> list[ToolCallDelta]:+def _tool_call_deltas(+ raw: str,+ index: int,+ tool_call_format: ToolCallFormat = "auto",+ schemas: ToolSchemas | None = None,+) -> list[ToolCallDelta]:raw = raw.strip()# Two on-the-wire formats appear inside <tool_call>…</tool_call>:# 1. Hermes JSON: {"name": "...", "arguments": {...}}@@ -595,13 +805,13 @@ def _tool_call_deltas(raw: str, index: int, tool_call_format: ToolCallFormat = "# ``tool_call_format`` makes the choice explicit (config-driven);# ``"auto"`` falls back to the original "starts-with-<function=" heuristic.if tool_call_format == "qwen_xml":- name, arguments = _parse_xml_tool_call(raw)+ name, arguments = _parse_xml_tool_call(raw, schemas)elif tool_call_format == "hermes_json":name, arguments = _parse_hermes_tool_call(raw)elif tool_call_format == "glm_xml":- name, arguments = _parse_glm_tool_call(raw)+ name, arguments = _parse_glm_tool_call(raw, schemas)elif raw.startswith("<function="):- name, arguments = _parse_xml_tool_call(raw)+ name, arguments = _parse_xml_tool_call(raw, schemas)else:name, arguments = _parse_hermes_tool_call(raw)if not isinstance(name, str) or not name:@@ -651,7 +861,7 @@ _XML_PARAM_CLOSE = "</parameter>"_MAX_XML_PARAMS = 256-def _parse_xml_tool_call(raw: str) -> tuple[str, dict[str, object]]:+def _parse_xml_tool_call(raw: str, schemas: ToolSchemas | None = None) -> tuple[str, dict[str, object]]:"""Parse the Qwen3(-Coder) XML tool-call form.Example::@@ -662,10 +872,10 @@ def _parse_xml_tool_call(raw: str) -> tuple[str, dict[str, object]]:</parameter></function>- Returns ``(name, arguments)``. Parameter values are coerced from text to- JSON scalars where possible (so ``"5"`` → ``5``, ``"true"`` → ``True``),- falling back to the trimmed string — which matches how OpenAI clients- expect typed function arguments.+ Returns ``(name, arguments)``. The chat template wraps every value in one+ newline on each side, so exactly one is removed from each end and the rest+ of the text is kept. Values are then converted by their declared parameter+ type in ``schemas``."""fm = _XML_FUNC_RE.search(raw)if not fm:@@ -686,11 +896,9 @@ def _parse_xml_tool_call(raw: str) -> tuple[str, dict[str, object]]:if close_idx == -1:# Unterminated parameter — stop; well-formed input always closes.break- val = raw[val_start:close_idx].strip()- try:- arguments[key] = json.loads(val)- except (json.JSONDecodeError, ValueError):- arguments[key] = val+ val = raw[val_start:close_idx].removeprefix("\n").removesuffix("\n")+ schema, root = _parameter_schema(schemas or {}, name, key)+ arguments[key] = _convert_argument(val, schema, root)pos = close_idx + len(_XML_PARAM_CLOSE)count += 1return name, arguments@@ -708,7 +916,7 @@ def _skip_whitespace(raw: str, pos: int) -> int:return pos-def _parse_glm_tool_call(raw: str) -> tuple[str, dict[str, object]]:+def _parse_glm_tool_call(raw: str, schemas: ToolSchemas | None = None) -> tuple[str, dict[str, object]]:"""Parse the GLM tool-call form.Example::@@ -719,9 +927,10 @@ def _parse_glm_tool_call(raw: str) -> tuple[str, dict[str, object]]:``<arg_key>``. Only whitespace may separate the name and the argumentpairs, and a name or key carrying a tag is rejected, so an unpaired ormisplaced tag is a parse error rather than part of the call. The chat- template writes string values raw and every other value as JSON, so values- are coerced as in the Qwen XML form. The scan is linear, and a call with- more than ``_MAX_XML_PARAMS`` pairs is rejected rather than truncated.+ template writes ``<arg_value>{value}</arg_value>`` with nothing around the+ value, so the text is kept verbatim and converted by its declared parameter+ type in ``schemas``. The scan is linear, and a call with more than+ ``_MAX_XML_PARAMS`` pairs is rejected rather than truncated."""first_key = raw.find(_GLM_KEY_OPEN)name = (raw if first_key == -1 else raw[:first_key]).strip()@@ -745,11 +954,9 @@ def _parse_glm_tool_call(raw: str) -> tuple[str, dict[str, object]]:key = raw[pos + len(_GLM_KEY_OPEN) : key_close].strip()if "<" in key or ">" in key:raise ValueError("malformed GLM tool-call: invalid argument key")- value = raw[value_open + len(_GLM_VALUE_OPEN) : value_close].strip()- try:- arguments[key] = json.loads(value)- except (json.JSONDecodeError, ValueError):- arguments[key] = value+ value = raw[value_open + len(_GLM_VALUE_OPEN) : value_close]+ schema, root = _parameter_schema(schemas or {}, name, key)+ arguments[key] = _convert_argument(value, schema, root)pos = value_close + len(_GLM_VALUE_CLOSE)count += 1if _skip_whitespace(raw, pos) < len(raw):diff --git a/packages/sie_server/tests/processors/test_remote_chat_prompt.py b/packages/sie_server/tests/processors/test_remote_chat_prompt.pyindex 1e95c902a..86974570d 100644--- a/packages/sie_server/tests/processors/test_remote_chat_prompt.py+++ b/packages/sie_server/tests/processors/test_remote_chat_prompt.py@@ -40,7 +40,7 @@ class RawAdapter(OpenAIUpstreamAdapter):self.closed = True-def model() -> ModelConfig:+def model(tool_call_parser: str = "hermes") -> ModelConfig:return ModelConfig.model_validate({"sie_id": "local/model",@@ -58,7 +58,7 @@ def model() -> ModelConfig:"adapter_path": "sie_server.adapters.sglang:SGLangGenerationAdapter","max_batch_tokens": 8192,"kv_budget_tokens": 8192,- "adapter_options": {"loadtime": {"tool_call_parser": "hermes"}},+ "adapter_options": {"loadtime": {"tool_call_parser": tool_call_parser}},}},}@@ -173,6 +173,31 @@ async def test_local_tool_parser_and_prior_arguments(template) -> None:assert payload["choices"][0]["finish_reason"] == "tool_calls"+async def test_rendered_chat_tool_arguments_follow_the_request_schema(template) -> None:+ tool = {+ "type": "function",+ "function": {+ "name": "edit",+ "parameters": {"type": "object", "properties": {"old": {"type": "string"}, "line": {"type": "integer"}}},+ },+ }+ adapter = RawAdapter(+ [+ GenerationChunk(+ text_delta="</think><tool_call>\n<function=edit>\n<parameter=old>\n return 1.10\n</parameter>\n"+ "<parameter=line>\n7\n</parameter>\n</function>\n</tool_call>"+ ),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=12, completion_tokens=3),+ ]+ )+ events = await prepare(adapter, body(tools=[tool]), config=model("qwen3_coder"))+ assert events is not None+ payload = await remote_chat_prompt.collect_rendered_chat(events)+ call = payload["choices"][0]["message"]["tool_calls"][0]+ assert json.loads(call["function"]["arguments"]) == {"old": " return 1.10", "line": 7}++@pytest.mark.asyncioasync def test_none_choice_hides_tools_from_template(template) -> None:adapter = RawAdapter(diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex 2facaef4b..74e8fbc66 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport asyncioimport base64+import jsonimport reimport threadingimport time@@ -2884,6 +2885,100 @@ async def test_streaming_tool_call_is_forced_and_parsed_in_the_configured_formatassert decoded[-1]["finish_reason"] == "tool_calls"+_EDIT_FILE_TOOL = {+ "type": "function",+ "function": {+ "name": "edit_file",+ "parameters": {+ "type": "object",+ "$defs": {"Mode": {"type": "string", "enum": ["replace", "append"]}},+ "properties": {+ "path": {"type": "string"},+ "old_str": {"type": "string"},+ "new_str": {"type": "string"},+ "content": {"type": "string"},+ "mode": {"$ref": "#/$defs/Mode"},+ "line": {"type": "integer"},+ "dry_run": {"type": "boolean"},+ "tags": {"type": "array", "items": {"type": "string"}},+ "options": {"type": "object"},+ "note": {"type": ["string", "null"]},+ },+ "required": ["path"],+ },+ },+}++_EDIT_FILE_ARGUMENTS = {+ "path": "src/app.py",+ "old_str": " return x",+ "new_str": " return y\n",+ "content": '{"version": "1.10", "html": "<b> <i>"}',+ "mode": "replace",+ "line": 42,+ "dry_run": False,+ "tags": ["a", "b"],+ "options": {"indent": 4},+ "note": None,+}+++def _template_value(value: object) -> str:+ return value if isinstance(value, str) else json.dumps(value)+++def _qwen_xml_call(name: str, arguments: dict[str, object]) -> str:+ body = "".join(f"<parameter={key}>\n{_template_value(value)}\n</parameter>\n" for key, value in arguments.items())+ return f"<tool_call>\n<function={name}>\n{body}</function>\n</tool_call>"+++def _glm_xml_call(name: str, arguments: dict[str, object]) -> str:+ body = "".join(+ f"<arg_key>{key}</arg_key><arg_value>{_template_value(value)}</arg_value>" for key, value in arguments.items()+ )+ return f"<tool_call>{name}{body}</tool_call>"+++async def _stream_tool_call(parser: str, text: str, tools: list[dict[str, Any]]) -> list[dict[str, Any]]:+ nc = AsyncMock()+ script = [GenerationChunk(text_delta=text[i : i + 5], is_first=i == 0) for i in range(0, len(text), 5)]+ script.append(GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=5, completion_tokens=9))+ registry = _make_registry(_FakeGenAdapter(script))+ resolved = MagicMock()+ resolved.loadtime = {"tool_call_parser": parser}+ registry.get_config.return_value.resolve_profile.return_value = resolved+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ wi = _make_work_item(generate={"prompt": "edit", "max_new_tokens": 512, "tools": tools})++ await proc.process(_make_msg(wi), "test/model")++ return _decode_chunks(nc)++[email protected](("parser", "render"), [("qwen3_coder", _qwen_xml_call), ("glm47", _glm_xml_call)])+async def test_streamed_tool_call_arguments_match_what_the_model_wrote(parser: str, render: Any) -> None:+ decoded = await _stream_tool_call(parser, render("edit_file", _EDIT_FILE_ARGUMENTS), [_EDIT_FILE_TOOL])++ tcs = _tool_call_deltas(decoded)+ assert tcs[0]["function"]["name"] == "edit_file"+ assert json.loads(tcs[1]["function"]["arguments"]) == _EDIT_FILE_ARGUMENTS+ assert decoded[-1]["finish_reason"] == "tool_calls"++[email protected](("parser", "render"), [("qwen3_coder", _qwen_xml_call), ("glm47", _glm_xml_call)])+async def test_streamed_call_to_an_undeclared_tool_keeps_string_values(parser: str, render: Any) -> None:+ arguments = {"count": "5", "flag": "true", "payload": '{"a": 1}'}++ decoded = await _stream_tool_call(parser, render("delete_branch", arguments), [_EDIT_FILE_TOOL])++ tcs = _tool_call_deltas(decoded)+ assert tcs[0]["function"]["name"] == "delete_branch"+ assert json.loads(tcs[1]["function"]["arguments"]) == arguments+ assert decoded[-1]["finish_reason"] == "tool_calls"++@pytest.mark.asyncioasync def test_streaming_tool_choice_none_hides_tools_from_chat_template(monkeypatch) -> None:"""``tool_choice='none'`` must prevent the model from ever seeing thediff --git a/packages/sie_server/tests/processors/test_tool_call_grammar.py b/packages/sie_server/tests/processors/test_tool_call_grammar.pyindex 4b00923db..6ad36d9d0 100644--- a/packages/sie_server/tests/processors/test_tool_call_grammar.py+++ b/packages/sie_server/tests/processors/test_tool_call_grammar.py@@ -143,7 +143,8 @@ def test_glm_xml_regex_accepts_only_complete_argument_pairs() -> None:"\n<arg_key>days</arg_key>\n<arg_value>3</arg_value></tool_call>")assert pat.fullmatch(two)- assert _parse_glm_tool_call(two.removeprefix("<tool_call>").removesuffix("</tool_call>")) == (+ schemas = {"get_weather": {"properties": {"city": {"type": "string"}, "days": {"type": "integer"}}}}+ assert _parse_glm_tool_call(two.removeprefix("<tool_call>").removesuffix("</tool_call>"), schemas) == ("get_weather",{"city": "Tokyo", "days": 3},)diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.pyindex 9b377409b..572b7a612 100644--- a/packages/sie_server/tests/processors/test_tool_call_parser.py+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py@@ -320,6 +320,13 @@ def _deltas(out: list[GenerationChunk]) -> list:return [c.tool_call_delta for c in out if c.tool_call_delta is not None]+def _tool(name: str, **properties: dict) -> dict:+ return {+ "type": "function",+ "function": {"name": name, "parameters": {"type": "object", "properties": properties}},+ }++def _args_for(out: list[GenerationChunk], index: int = 0) -> str:"""Concatenate the arguments_delta for a given tool-call index."""return "".join(d.arguments_delta for d in _deltas(out) if d.index == index and d.arguments_delta)@@ -344,6 +351,7 @@ async def test_explicit_qwen_xml_format() -> None:out = await _collect("<tool_call><function=f><parameter=a>\n1\n</parameter></function></tool_call>",tool_call_format="qwen_xml",+ tools=[_tool("f", a={"type": "integer"})],)import json@@ -362,8 +370,8 @@ async def test_explicit_hermes_json_format() -> None:@pytest.mark.asyncio-async def test_xml_argument_coercion_edge_cases() -> None:- """XML parameter values coerce to typed JSON where possible, else string."""+async def test_xml_argument_values_follow_declared_types() -> None:+ """XML parameter values convert by declared type; a value that does not convert stays a string."""import jsonraw = (@@ -377,7 +385,17 @@ async def test_xml_argument_coercion_edge_cases() -> None:"<parameter=multiline>\nline1\nline2\n</parameter>""</function></tool_call>")- out = await _collect(raw, tool_call_format="qwen_xml")+ tool = _tool(+ "f",+ num={"type": "integer"},+ flag={"type": "boolean"},+ nested={"type": "object"},+ jsonish={"type": "object"},+ empty={"type": "string"},+ unicode={"type": "string"},+ multiline={"type": "string"},+ )+ out = await _collect(raw, tool_call_format="qwen_xml", tools=[tool])args = json.loads(_args_for(out))assert args["num"] == 5assert args["flag"] is True@@ -460,7 +478,7 @@ async def test_parallel_tool_calls_true_keeps_all_calls() -> None:def test_xml_param_scan_matches_well_formed_input() -> None:"""The linear ``str.find`` scan reproduces the old regex behavior for- well-formed input — multiple params, typed coercion preserved.+ well-formed input — multiple params, each converted by its declared type."""from sie_server.processors.tool_call_parser import _parse_xml_tool_call@@ -471,7 +489,8 @@ def test_xml_param_scan_matches_well_formed_input() -> None:'<parameter=c>\n{"k":[1,2]}\n</parameter>'"</function>")- name, args = _parse_xml_tool_call(raw)+ schemas = {"f": {"properties": {"a": {"type": "integer"}, "b": {"type": "string"}, "c": {"type": "object"}}}}+ name, args = _parse_xml_tool_call(raw, schemas)assert name == "f"assert args == {"a": 1, "b": "hello", "c": {"k": [1, 2]}}@@ -548,7 +567,11 @@ def test_xml_param_scan_garbled_openers_no_close_is_fast() -> None:async def test_explicit_glm_xml_format(raw: str) -> None:import json- out = await _collect("Checking. " + raw, tool_call_format="glm_xml")+ out = await _collect(+ "Checking. " + raw,+ tool_call_format="glm_xml",+ tools=[_tool("get_weather", city={"type": "string"}, days={"type": "integer"})],+ )assert out[0].text_delta == "Checking. "assert _deltas(out)[0].function_name == "get_weather"@@ -565,7 +588,7 @@ async def test_glm_xml_call_without_arguments() -> None:@pytest.mark.asyncio-async def test_glm_xml_argument_values_coerce_like_qwen_xml() -> None:+async def test_glm_xml_argument_values_follow_declared_types() -> None:import jsonraw = (@@ -577,7 +600,15 @@ async def test_glm_xml_argument_values_coerce_like_qwen_xml() -> None:"<arg_key>multiline</arg_key><arg_value>line1\nline2</arg_value>""</tool_call>")- out = await _collect(raw, tool_call_format="glm_xml")+ tool = _tool(+ "f",+ num={"type": "integer"},+ flag={"type": "boolean"},+ nested={"type": "object"},+ text={"type": "string"},+ multiline={"type": "string"},+ )+ out = await _collect(raw, tool_call_format="glm_xml", tools=[tool])assert json.loads(_args_for(out)) == {"num": 5,@@ -773,3 +804,187 @@ async def test_parse_tool_call_stream_non_streaming_per_candidate_tool_calls() -assert cands[0]["finish_reason"] == "tool_calls"assert "tool_calls" not in cands[1] or not cands[1].get("tool_calls")assert cands[1]["finish_reason"] == "stop"+++# ── schema-driven argument values ──────────────────────────────────+++def _qwen_call(name: str, **values: str) -> str:+ body = "".join(f"<parameter={key}>\n{value}\n</parameter>\n" for key, value in values.items())+ return f"<tool_call>\n<function={name}>\n{body}</function>\n</tool_call>"+++def _glm_call(name: str, **values: str) -> str:+ body = "".join(f"<arg_key>{key}</arg_key><arg_value>{value}</arg_value>" for key, value in values.items())+ return f"<tool_call>{name}{body}</tool_call>"+++_EDIT_TOOL = _tool(+ "edit_file",+ path={"type": "string"},+ old_str={"type": "string"},+ new_str={"type": "string"},+ content={"type": "string"},+ version={"type": "string"},+ pattern={"type": "string"},+ query={"type": "string"},+)++_EXACT_STRINGS = {+ "old_str": " return x",+ "new_str": " return y",+ "content": '{"version": "1.10"}',+ "version": "1.10",+ "pattern": "true",+ "query": "null",+}+++ ("raw", "tool_call_format"),+ [+ (_qwen_call("edit_file", **_EXACT_STRINGS), "qwen_xml"),+ (_glm_call("edit_file", **_EXACT_STRINGS), "glm_xml"),+ ],+)+async def test_string_parameters_keep_their_exact_text(raw: str, tool_call_format: str) -> None:+ import json++ out = await _collect(raw, tool_call_format=tool_call_format, tools=[_EDIT_TOOL])++ assert json.loads(_args_for(out)) == _EXACT_STRINGS+++async def test_qwen_xml_removes_only_the_template_newlines() -> None:+ import json++ raw = "<tool_call><function=edit_file><parameter=content>\nline\n\n</parameter></function></tool_call>"+ out = await _collect(raw, tool_call_format="qwen_xml", tools=[_EDIT_TOOL])++ assert json.loads(_args_for(out)) == {"content": "line\n"}+++async def test_glm_xml_string_values_are_not_json_unquoted() -> None:+ import json++ out = await _collect(_glm_call("edit_file", new_str='"hello"'), tool_call_format="glm_xml", tools=[_EDIT_TOOL])++ assert json.loads(_args_for(out)) == {"new_str": '"hello"'}++[email protected]("tool_call_format", ["qwen_xml", "glm_xml"])+async def test_undeclared_tool_and_parameter_values_stay_strings(tool_call_format: str) -> None:+ import json++ values = {"count": "5", "flag": "true", "data": '{"a": 1}'}+ raw = (_qwen_call if tool_call_format == "qwen_xml" else _glm_call)("unknown_tool", **values)+ out = await _collect(raw, tool_call_format=tool_call_format, tools=[_EDIT_TOOL])+ assert _deltas(out)[0].function_name == "unknown_tool"+ assert json.loads(_args_for(out)) == values++ raw = (_qwen_call if tool_call_format == "qwen_xml" else _glm_call)("edit_file", path="a.py", extra="5")+ out = await _collect(raw, tool_call_format=tool_call_format, tools=[_EDIT_TOOL])+ assert json.loads(_args_for(out)) == {"path": "a.py", "extra": "5"}+++async def test_values_without_tools_stay_strings() -> None:+ import json++ out = await _collect(_qwen_call("f", n="5"), tool_call_format="qwen_xml")++ assert json.loads(_args_for(out)) == {"n": "5"}+++ ("schema", "text", "expected"),+ [+ ({"type": "integer"}, "42", 42),+ ({"type": "integer"}, "forty", "forty"),+ ({"type": "integer"}, "null", None),+ ({"type": "number"}, "1.5", 1.5),+ ({"type": "number"}, "2", 2),+ ({"type": "number"}, "nan", "nan"),+ ({"type": "number"}, "1e400", "1e400"),+ ({"type": "boolean"}, "False", False),+ ({"type": "boolean"}, "yes", "yes"),+ ({"type": "array"}, "[1, 2]", [1, 2]),+ ({"type": "object"}, "{'a': 1}", {"a": 1}),+ ({"type": "object"}, "{'a': {1, 2}}", "{'a': {1, 2}}"),+ ({"type": "object"}, '{"a": NaN}', '{"a": NaN}'),+ ({"type": "string"}, "null", "null"),+ ({"type": ["string", "null"]}, "null", None),+ ({"type": "string", "nullable": True}, "null", None),+ ({"type": ["integer", "null"]}, "7", 7),+ ({"anyOf": [{"type": "integer"}, {"type": "null"}]}, "7", 7),+ ({"anyOf": [{"type": "integer"}, {"type": "string"}]}, "7", "7"),+ ({"oneOf": [{"type": "integer"}, {"type": "boolean"}]}, "7", 7),+ ({"enum": [1, 2, 3]}, "2", 2),+ ({"enum": ["1", "2"]}, "2", "2"),+ ({"enum": [1, "a"]}, "1", "1"),+ ({"allOf": [{"type": "integer"}, {"minimum": 0}]}, "3", 3),+ ({"properties": {"a": {"type": "integer"}}}, '{"a": 1}', {"a": 1}),+ ({"items": {"type": "integer"}}, "[1]", [1]),+ ({"$ref": "#/$defs/Count"}, "9", 9),+ ({"$ref": "#/$defs/Missing"}, "9", "9"),+ ({"$ref": "https://example.com/schema"}, "9", "9"),+ ({"description": "no type"}, "9", "9"),+ ],+)+def test_argument_conversion_follows_the_declared_schema(schema: dict, text: str, expected: object) -> None:+ from sie_server.processors.tool_call_parser import _parse_xml_tool_call++ schemas = {"f": {"$defs": {"Count": {"type": "integer"}}, "properties": {"v": schema}}}+ _, args = _parse_xml_tool_call(f"<function=f><parameter=v>\n{text}\n</parameter></function>", schemas)++ assert args == {"v": expected}+ assert type(args["v"]) is type(expected)+++def test_self_referencing_schema_does_not_loop() -> None:+ from sie_server.processors.tool_call_parser import _parse_xml_tool_call++ schemas = {"f": {"$defs": {"A": {"$ref": "#/$defs/A"}}, "properties": {"v": {"$ref": "#/$defs/A"}}}}++ assert _parse_xml_tool_call("<function=f><parameter=v>\n1\n</parameter></function>", schemas) == ("f", {"v": "1"})+++async def test_non_streaming_candidates_keep_a_malformed_block_as_text() -> None:+ import json++ malformed = "<tool_call>{not json</tool_call>"+ candidates = (+ {"text": "Calling " + malformed, "finish_reason": "stop", "logprobs": None},+ {"text": _qwen_call("edit_file", old_str=" a"), "finish_reason": "stop", "logprobs": None},+ )+ out = [+ item+ async for item in parse_tool_call_stream(+ _chunks([GenerationChunk(text_delta="", done=True, finish_reason="stop", candidates=candidates)]),+ tool_call_format="hermes_json",+ tools=[_EDIT_TOOL],+ )+ ]+ first, second = out[-1].candidates++ assert first["text"] == "Calling " + malformed+ assert not first.get("tool_calls")+ assert first["finish_reason"] == "stop"+ assert second["finish_reason"] == "stop"++ out = [+ item+ async for item in parse_tool_call_stream(+ _chunks([GenerationChunk(text_delta="", done=True, finish_reason="stop", candidates=candidates[1:])]),+ tool_call_format="qwen_xml",+ tools=[_EDIT_TOOL],+ )+ ]+ (parsed,) = out[-1].candidates+ assert json.loads(parsed["tool_calls"][0]["function"]["arguments"]) == {"old_str": " a"}+ assert parsed["finish_reason"] == "tool_calls"