[GH-ISSUE #5] the engine reported an error: malformed tool call: web_search<arg_key>limit</arg_key><arg_value>8</arg_value><arg_key>query</arg_ke #1

Closed
opened 2026-10-29 21:18:56 +07:00 by bsakaguchi · 3 comments
Owner

Originally created by @xldistance on GitHub (Oct 8, 2026).
Original GitHub issue: https://github.com/mw00/project-maya/issues/5

When running glm5.3-flash-iq2_xxs in Maya on Windows, the model is unable to call tools and reports the following errors:

[strata] the engine reported an error: malformed tool call: mcp--tavily--tavily-search<arg_key>max_results</arg_key><arg_value>10</arg_value>

[strata] the engine reported an error: malformed tool call: web_search<arg_key>limit</arg_key><arg_value>8</arg_value><arg_key>query</arg_ke

Originally created by @xldistance on GitHub (Oct 8, 2026). Original GitHub issue: https://github.com/mw00/project-maya/issues/5 When running glm5.3-flash-iq2_xxs in Maya on Windows, the model is unable to call tools and reports the following errors: [strata] the engine reported an error: malformed tool call: mcp--tavily--tavily-search<arg_key>max_results</arg_key><arg_value>10</arg_value> [strata] the engine reported an error: malformed tool call: web_search<arg_key>limit</arg_key><arg_value>8</arg_value><arg_key>query</arg_ke
Author
Owner

@xldistance commented on GitHub (Oct 8, 2026):

{ "exe": "G:\\models\\project-maya\\build\\strata.exe", "args": [ "--glm-pack", "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\pack", "--max-context", "131072", "--kv", "int8" ], "cwd": "G:\\models\\project-maya", "tokenizer": "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\pack\\tokenizer", "model_name": "glm-5.3-flash", "gpu": [ 0 ], "sampling": { "temperature": 0.6, "top_p": 0.95 }, "reasoning_effort": "xhigh", "lib_dirs": [ "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v13.2\\bin", "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v13.2\\bin\\x64" ], "host": "0.0.0.0", "port": 5001, "vision": { "exe": "G:\\models\\project-maya\\build-vision\\bin\\strata-vision.exe", "mmproj": "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\vision\\mmproj-GLM-5.3-Flash-F16.gguf", "model": "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\vision\\GLM-5.3-Flash-vocab.gguf", "gpu": true }, "log": "G:\\models\\project-maya\\maya-maya-s-v2-iq2_xxs.log", "installer": { "data_dir": "G:\\models\\Maya-data", "quant": "Maya-S-v2-IQ2_XXS", "gguf_dir": null, "written": "2026-10-08 09:29" } }

<!-- gh-comment-id:6050910885 --> @xldistance commented on GitHub (Oct 8, 2026): ` { "exe": "G:\\models\\project-maya\\build\\strata.exe", "args": [ "--glm-pack", "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\pack", "--max-context", "131072", "--kv", "int8" ], "cwd": "G:\\models\\project-maya", "tokenizer": "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\pack\\tokenizer", "model_name": "glm-5.3-flash", "gpu": [ 0 ], "sampling": { "temperature": 0.6, "top_p": 0.95 }, "reasoning_effort": "xhigh", "lib_dirs": [ "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v13.2\\bin", "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v13.2\\bin\\x64" ], "host": "0.0.0.0", "port": 5001, "vision": { "exe": "G:\\models\\project-maya\\build-vision\\bin\\strata-vision.exe", "mmproj": "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\vision\\mmproj-GLM-5.3-Flash-F16.gguf", "model": "G:\\models\\Maya-data\\models\\glm-5.3-flash-maya-s-v2-iq2_xxs\\vision\\GLM-5.3-Flash-vocab.gguf", "gpu": true }, "log": "G:\\models\\project-maya\\maya-maya-s-v2-iq2_xxs.log", "installer": { "data_dir": "G:\\models\\Maya-data", "quant": "Maya-S-v2-IQ2_XXS", "gguf_dir": null, "written": "2026-10-08 09:29" } } `
Author
Owner

@xldistance commented on GitHub (Oct 8, 2026):

project-maya\serve\frontend.py needs to be modified.

"""serve/frontend.py - plan v0.3 P8: the request/response layer between API clients and the engine.

Everything here is text: no model, no GPU. The engine consumes token ids and produces text deltas; this module

  * normalizes OpenAI Chat Completions and Anthropic Messages requests into the chat template's message form,
  * renders the model's own Jinja chat template (pack `tokenizer/chat_template.jinja`) exactly as Hugging Face
    does (checked against the pack's `chat_golden.json`, 10 cases incl. thinking and tools),
  * parses the streamed output incrementally into reasoning (`<think>...</think>`), content and tool calls in
    Qwen's function/parameter XML or GLM's tool-name/arg_key/arg_value XML,
    never emitting a partial tag to the client.

Design note: plan v0.3 describes a single C++ process. The frontend is Python first because the template is Jinja
and the formats change often; the engine boundary is token ids in, text deltas out, which keeps a later C++ port
(or a pybind wrapper) a local change.
"""
from __future__ import annotations

import json
import uuid
from dataclasses import dataclass, field
from pathlib import Path

import jinja2
from jinja2.sandbox import ImmutableSandboxedEnvironment


# ------------------------------------------------------------------------------------------------ template
class ChatTemplate:
    """The model's chat template, rendered with the same Jinja settings as transformers' apply_chat_template."""

    def __init__(self, path: str | Path):
        def raise_exception(message):
            raise jinja2.exceptions.TemplateError(message)

        def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
            return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)

        env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=["jinja2.ext.loopcontrols"])
        env.filters["tojson"] = tojson
        env.globals["raise_exception"] = raise_exception
        self.source = Path(path).read_text(encoding="utf-8")
        self.template = env.from_string(self.source)
        # GLM-5.x: the template knows reasoning_effort "low" and "high" only - anything else, an absent one included,
        # is "Max", its most verbose - and it always opens <think> (no enable_thinking).  The levels the server speaks
        # (low / medium / xhigh, or thinking off) map onto low / high / max, and off closes the think block the way
        # the template writes a turn without reasoning.
        self.glm_effort = "reasoning_effort in ['low', 'high']" in self.source

    def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True,
               **kwargs) -> str:
        off = False
        if self.glm_effort:
            off = kwargs.pop("enable_thinking", True) is False
            level = kwargs.pop("reasoning_effort", None)
            kwargs["reasoning_effort"] = "low" if off else {"low": "low", "medium": "high", "high": "high"}.get(level, "max")
        out = self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt,
                                   **kwargs)
        if off and add_generation_prompt and out.endswith("<think>"):
            out += "</think>"
        return out


# ------------------------------------------------------------------------------------------------ requests
def _text_of(content) -> str:
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    return "".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in
                   ("text", "input_text", None))


IMAGE_PARTS = ("image_url", "input_image", "image")

# Thinking levels.  The model's template knows low, medium and xhigh (its default; "high" means xhigh), and
# enable_thinking=false for none.  Clients spell these many ways; everything maps onto those four.
EFFORT = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None,
          "low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh", "max": "xhigh", "maximum": "xhigh"}


def effort_kwargs(value) -> dict:
    """A reasoning effort as given by a client -> the template's kwargs.  Unknown values are a 400, not a crash."""
    if value is None or value == "":
        return {}
    if value is False:
        return {"enable_thinking": False}
    key = str(value).strip().lower()
    if key not in EFFORT:
        raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium or high")
    level = EFFORT[key]
    return {"enable_thinking": False} if level is None else {"reasoning_effort": level}


def budget_effort(tokens) -> dict:
    """Anthropic's thinking budget (budget_tokens) -> a level: under 2K low, under 8K medium, else high."""
    try:
        n = int(tokens)
    except (TypeError, ValueError):
        return {}
    return {"reasoning_effort": "low" if n < 2048 else "medium" if n < 8192 else "xhigh"}


def _has_image(content) -> bool:
    return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in IMAGE_PARTS for p in content)


def _image_source(part: dict) -> str:
    """An image part's source as one string: a data: URL, an http(s) URL or a local file path.
    OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style
    {"type": "input_image", "image_url": ...}; Anthropic: {"type": "image", "source": {"type": "base64",
    "media_type": ..., "data": ...}} or {"source": {"type": "url", "url": ...}}."""
    if part.get("type") == "image":
        src = part.get("source") or {}
        if src.get("type") == "base64":
            return f"data:{src.get('media_type', 'image/png')};base64,{src.get('data', '')}"
        return src.get("url") or src.get("path") or ""
    url = part.get("image_url")
    if isinstance(url, dict):
        url = url.get("url")
    return url or ""


def _parts_of(content):
    """Message content for the template: a string when there is no image (unchanged behaviour), otherwise the
    template's list form - text items and image items, in order - whose image items carry their source."""
    if not _has_image(content):
        return _text_of(content)
    items = []
    for part in content:
        if not isinstance(part, dict):
            continue
        if part.get("type") in IMAGE_PARTS:
            items.append({"type": "image", "source": _image_source(part)})
        elif part.get("type") in ("text", "input_text", None) and "text" in part:
            items.append({"type": "text", "text": part.get("text", "")})
    return items


def images_of(messages: list[dict]) -> list[str]:
    """The image sources of the rendered conversation, in prompt order (the template renders one
    <|vision_start|><|image_pad|><|vision_end|> per image item, message by message)."""
    return [item["source"] for m in messages if isinstance(m.get("content"), list)
            for item in m["content"] if item.get("type") == "image"]


def _late_system_to_user(messages: list[dict]) -> list[dict]:
    """The chat template takes a system message only at the start ("System message must be at the beginning").
    Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user
    turn, some OpenAI clients a late "developer" message (issue #56) - so those become user messages, in place:
    merging them into the first one would change the prompt's start and cost the conversation cache every turn."""
    return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)]


def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
    """OpenAI Chat Completions -> (template messages, template tools, template kwargs)."""
    messages = []
    for m in req.get("messages", []):
        role = m.get("role")
        if role == "developer":
            role = "system"
        out = {"role": role, "content": _parts_of(m.get("content")) if role in ("user", "tool", "assistant") else _text_of(m.get("content"))}
        if m.get("reasoning_content"):
            out["reasoning_content"] = m["reasoning_content"]
        if m.get("tool_calls"):
            calls = []
            for c in m["tool_calls"]:
                fn = c.get("function", c)
                args = fn.get("arguments")
                if isinstance(args, str):               # the template requires a mapping, not a JSON string
                    args = json.loads(args) if args.strip() else {}
                calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}})
            out["tool_calls"] = calls
        messages.append(out)
    tools = [t.get("function", t) if isinstance(t, dict) and t.get("type") == "function" else t
             for t in req.get("tools") or []] or None
    kwargs = {}
    # OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...}
    reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {}
    kwargs.update(effort_kwargs(req.get("reasoning_effort") or reasoning.get("effort")))
    # the vLLM / llama.cpp convention: {"chat_template_kwargs": {"enable_thinking": false, "reasoning_effort": "low"}}
    for k, v in (req.get("chat_template_kwargs") or {}).items():
        if k == "enable_thinking" and not v:
            kwargs = {"enable_thinking": False}
        elif k == "reasoning_effort" and "enable_thinking" not in kwargs:
            kwargs.update(effort_kwargs(v))
    return _late_system_to_user(messages), tools, kwargs


def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
    """Anthropic Messages -> (template messages, template tools, template kwargs)."""
    messages = []
    system = req.get("system")
    if system:
        messages.append({"role": "system", "content": _text_of(system)})
    for m in req.get("messages", []):
        content = m.get("content")
        if isinstance(content, str):
            messages.append({"role": m["role"], "content": content})
            continue
        if m.get("role") == "user" and _has_image(content) and not any(
                isinstance(b, dict) and b.get("type") == "tool_result" for b in content):
            messages.append({"role": "user", "content": _parts_of(content)})
            continue
        text, reasoning, calls = [], [], []
        for block in content or []:
            kind = block.get("type")
            if kind == "text":
                text.append(block.get("text", ""))
            elif kind == "thinking":
                reasoning.append(block.get("thinking", ""))
            elif kind == "tool_use":
                calls.append({"function": {"name": block.get("name"), "arguments": block.get("input") or {}}})
            elif kind == "tool_result":
                messages.append({"role": "tool", "content": _text_of(block.get("content"))})
        if text or calls or reasoning:
            out = {"role": m["role"], "content": "".join(text)}
            if reasoning:
                out["reasoning_content"] = "".join(reasoning)
            if calls:
                out["tool_calls"] = calls
            messages.append(out)
    tools = [{"name": t["name"], "description": t.get("description", ""), "parameters": t.get("input_schema", {})}
             for t in req.get("tools") or []] or None
    kwargs = {}
    # Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N};
    # "output_config": {"effort": "low" | "medium" | "high"}
    thinking = req.get("thinking")
    effort = (req.get("output_config") or {}).get("effort") if isinstance(req.get("output_config"), dict) else None
    if isinstance(thinking, dict) and thinking.get("type") == "disabled":
        kwargs["enable_thinking"] = False
    elif effort:
        kwargs.update(effort_kwargs(effort))
    elif isinstance(thinking, dict) and thinking.get("budget_tokens"):
        kwargs.update(budget_effort(thinking["budget_tokens"]))
    return _late_system_to_user(messages), tools, kwargs


# ------------------------------------------------------------------------------------------------ output parser
@dataclass
class ToolCall:
    name: str
    arguments: dict
    id: str = field(default_factory=lambda: "call_" + uuid.uuid4().hex[:24])


@dataclass
class Event:
    kind: str                     # "reasoning" | "content" | "tool_call"
    text: str = ""
    call: ToolCall | None = None


THINK_END = "</think>"
CALL_START = "<tool_call>"
CALL_END = "</tool_call>"


def _tool_header(body: str, complete: bool = False) -> tuple[str, int, bool] | None:
    """Return (name, body offset, is GLM), or wait for an incomplete streamed header."""
    stripped = body.lstrip()
    lead = len(body) - len(stripped)
    if stripped.startswith("<function="):
        end = stripped.find(">")
        if end >= 0:
            return stripped[10:end], lead + end + 1, False
    elif stripped and not stripped.startswith("<"):
        end = stripped.find("<")
        if end >= 0 or complete:
            end = end if end >= 0 else len(stripped)
            name = stripped[:end].strip()
            if name and not any(c.isspace() for c in name):
                return name, lead + end, True
    return None


def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:
    """Qwen function/parameter or GLM name/arg_key/arg_value XML -> ToolCall.
    Values are JSON-decoded unless the schema declares a string; GLM string whitespace is literal."""
    body = body.strip()
    header = _tool_header(body, complete=True)
    if header is None:
        raise ValueError("malformed tool call: " + body[:80])
    name, offset, glm = header
    rest = body[offset:]
    props = ((schema or {}).get("parameters") or {}).get("properties") or {}
    args = {}
    key_start, key_end = ("<arg_key>", "</arg_key>") if glm else ("<parameter=", ">")
    value_end = "</arg_value>" if glm else "</parameter>"
    while key_start in rest:
        rest = rest[rest.index(key_start) + len(key_start):]
        pname = rest[:rest.index(key_end)]
        rest = rest[rest.index(key_end) + len(key_end):]
        if glm:
            rest = rest.lstrip()
            if not rest.startswith("<arg_value>"):
                raise ValueError("malformed tool argument: " + pname)
            rest = rest[len("<arg_value>"):]
        end = rest.find(value_end)
        value = rest[:end] if end >= 0 else rest
        rest = rest[end + len(value_end):] if end >= 0 else ""
        if not glm:
            if value.startswith("\n"):
                value = value[1:]
            if value.endswith("\n"):
                value = value[:-1]
        declared = (props.get(pname) or {}).get("type")
        if declared == "string":
            args[pname] = value
        else:
            try:
                args[pname] = json.loads(value)
            except ValueError:
                args[pname] = value
    return ToolCall(name=name, arguments=args)


class OutputParser:
    """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back
    until it is complete, so clients never see `<tool_` or `</thi`."""

    def __init__(self, thinking: bool = True, tools: list[dict] | None = None, stream_tools: bool = False):
        self.state = "reasoning" if thinking else "content"
        self.buf = ""
        self.lead = False
        self.schemas = {t.get("name"): t for t in tools or []}
        # stream_tools: a tool call is also reported while it is being written - "tool_start" (its name and id) as
        # soon as the name is known, then "tool_args" pieces of its JSON arguments (string parameters character by
        # character; other types whole, once complete) - before the final "tool_call".  Without it, a client sees
        # nothing until the call is complete, which for a large file write can be many minutes.
        self.stream_tools = stream_tools
        self._reset_scan()

    def _reset_scan(self):
        self.sp = 0                  # how much of self.buf (the call body) the scanner has consumed
        self.ss = "name"             # name -> between -> str|raw -> ... -> done
        self.scall = None            # the ToolCall being streamed (its id is reused by the final event)
        self.sfirst = True
        self.sval_started = False
        self.sdeclared = {}
        self.sglm = False
        self.send = "</parameter>"

    def _scan(self, complete: bool = False) -> list[Event]:
        """Advance the streaming view of the call body in self.buf (see stream_tools)."""
        out = []

        def args(s):
            if s:
                out.append(Event("tool_args", s, call=self.scall))
        while True:
            rest = self.buf[self.sp:]
            if self.ss == "name":
                header = _tool_header(rest, complete=complete)
                if header is None:
                    return out
                name, offset, self.sglm = header
                self.send = "</arg_value>" if self.sglm else "</parameter>"
                self.scall = ToolCall(name=name, arguments={})
                props = ((self.schemas.get(name) or {}).get("parameters") or {}).get("properties") or {}
                self.sdeclared = {k: (v or {}).get("type") for k, v in props.items()}
                out.append(Event("tool_start", call=self.scall))
                args("{")
                self.sp += offset
                self.ss = "between"
            elif self.ss == "between":
                stripped = rest.lstrip()
                self.sp += len(rest) - len(stripped)
                key_start, key_end = ("<arg_key>", "</arg_key>") if self.sglm else ("<parameter=", ">")
                if stripped.startswith(key_start):
                    b = stripped.find(key_end)
                    if b < 0:
                        return out
                    pname = stripped[len(key_start):b]
                    args(("" if self.sfirst else ",") + json.dumps(pname) + ":")
                    self.sfirst = False
                    self.sp += b + len(key_end)
                    if self.sglm:
                        self.snext = "str" if self.sdeclared.get(pname) == "string" else "raw"
                        self.ss = "value"
                        continue
                    if self.sdeclared.get(pname) == "string":
                        args('"')
                        self.ss, self.sval_started = "str", False
                    else:
                        self.ss = "raw"
                elif stripped.startswith("</function>") or (self.sglm and complete and not stripped):
                    args("}")
                    if not self.sglm:
                        self.sp += len("</function>")
                    self.ss = "done"
                else:
                    return out          # a tag still arriving (or trailing text): wait
            elif self.ss == "value":
                stripped = rest.lstrip()
                if not stripped.startswith("<arg_value>"):
                    return out
                self.sp += len(rest) - len(stripped) + len("<arg_value>")
                self.ss, self.sval_started = self.snext, False
                if self.ss == "str":
                    args('"')
            elif self.ss == "str":
                if not self.sval_started:
                    if not rest:
                        return out
                    if not self.sglm and rest[0] == "\n":   # Qwen's delimiter newline is not part of the value
                        self.sp += 1
                        rest = rest[1:]
                    self.sval_started = True
                end = rest.find(self.send)
                if end >= 0:
                    value = rest[:end]
                    if not self.sglm and value.endswith("\n"):
                        value = value[:-1]
                    args(json.dumps(value)[1:-1] + '"')
                    self.sp += end + len(self.send)
                    self.ss = "between"
                    continue
                safe = len(rest) - self._hold(rest, (self.send,))
                if not self.sglm and safe > 0 and rest[safe - 1] == "\n":   # Qwen's trailing delimiter newline
                    safe -= 1
                if safe > 0:
                    args(json.dumps(rest[:safe])[1:-1])
                    self.sp += safe
                return out
            elif self.ss == "raw":
                end = rest.find(self.send)
                if end < 0:
                    return out
                value = rest[:end]
                if not self.sglm:
                    if value.startswith("\n"):
                        value = value[1:]
                    if value.endswith("\n"):
                        value = value[:-1]
                try:
                    v = json.loads(value)
                except ValueError:
                    v = value
                args(json.dumps(v, ensure_ascii=False))
                self.sp += end + len(self.send)
                self.ss = "between"
            else:
                return out

    def _close_scan(self) -> list[Event]:
        """A streamed call that ended without a clean </function>: close its JSON so clients can still parse it."""
        out = []
        if self.scall is None or self.ss == "done":
            return out
        tail = ""
        if self.ss == "str":
            tail += '"'
        elif self.ss == "raw":
            value = self.buf[self.sp:]
            tail += json.dumps(value if self.sglm else value.strip("\n"))
        elif self.ss == "value":
            tail += "null"            # generation stopped before the GLM value tag arrived
        tail += "}"
        out.append(Event("tool_args", tail, call=self.scall))
        self.ss = "done"
        return out

    def _hold(self, text: str, tags: tuple[str, ...]) -> int:
        """Length of the longest suffix of `text` that is a proper prefix of one of `tags`."""
        best = 0
        for tag in tags:
            for n in range(1, len(tag)):
                if text.endswith(tag[:n]):
                    best = max(best, n)
        return best

    def feed(self, delta: str) -> list[Event]:
        self.buf += delta
        out: list[Event] = []
        while True:
            if self.state == "reasoning":
                i = self.buf.find(THINK_END)
                if i < 0:
                    keep = self._hold(self.buf, (THINK_END,))
                    if len(self.buf) > keep:
                        out.append(Event("reasoning", self.buf[:len(self.buf) - keep]))
                        self.buf = self.buf[len(self.buf) - keep:]
                    return out
                if i:
                    out.append(Event("reasoning", self.buf[:i]))
                self.buf = self.buf[i + len(THINK_END):]
                self.state, self.lead = "content", True
            elif self.state == "content":
                if self.lead:                                   # newlines right after </think> or a call
                    stripped = self.buf.lstrip("\n")
                    if not stripped:
                        self.buf = ""
                        return out
                    self.buf, self.lead = stripped, False
                i = self.buf.find(CALL_START)
                if i < 0:
                    # Hold a partial tag AND the newlines before it: if a tool call follows, they are dropped,
                    # so emitting them early would make streamed and whole outputs differ.
                    j = len(self.buf) - self._hold(self.buf, (CALL_START,))
                    while j > 0 and self.buf[j - 1] == "\n":
                        j -= 1
                    if j > 0:
                        out.append(Event("content", self.buf[:j]))
                        self.buf = self.buf[j:]
                    return out
                if i and self.buf[:i].strip():
                    out.append(Event("content", self.buf[:i].rstrip("\n")))
                self.buf = self.buf[i + len(CALL_START):]
                self.state = "call"
            else:
                i = self.buf.find(CALL_END)
                if self.stream_tools:
                    if i >= 0:
                        whole, self.buf = self.buf, self.buf[:i]     # scan only the body
                        out += self._scan(complete=True)
                        out += self._close_scan()
                        self.buf = whole
                    else:
                        out += self._scan()
                if i < 0:
                    return out
                body = self.buf[:i]
                self.buf = self.buf[i + len(CALL_END):]
                header = _tool_header(body, complete=True)
                name = header[0] if header else None
                call = parse_tool_call(body, self.schemas.get(name))
                if self.scall is not None:
                    call.id = self.scall.id
                out.append(Event("tool_call", call=call))
                self._reset_scan()
                self.state, self.lead = "content", True

    def finish(self) -> list[Event]:
        """End of generation: flush whatever is held (an unterminated tool call is returned as content)."""
        out = []
        if self.state == "call" and self.stream_tools and self.scall is not None:
            out += self._scan()                 # the output ended inside a call that was already announced
            out += self._close_scan()
            out.append(Event("tool_call", call=self.scall))
            self.buf = ""
            self._reset_scan()
            return out
        if self.buf:
            kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content")
            text = self.buf if self.state != "call" else CALL_START + self.buf
            out.append(Event(kind, text))
            self.buf = ""
        return out

<!-- gh-comment-id:6051305655 --> @xldistance commented on GitHub (Oct 8, 2026): project-maya\serve\frontend.py needs to be modified. ``` """serve/frontend.py - plan v0.3 P8: the request/response layer between API clients and the engine. Everything here is text: no model, no GPU. The engine consumes token ids and produces text deltas; this module * normalizes OpenAI Chat Completions and Anthropic Messages requests into the chat template's message form, * renders the model's own Jinja chat template (pack `tokenizer/chat_template.jinja`) exactly as Hugging Face does (checked against the pack's `chat_golden.json`, 10 cases incl. thinking and tools), * parses the streamed output incrementally into reasoning (`<think>...</think>`), content and tool calls in Qwen's function/parameter XML or GLM's tool-name/arg_key/arg_value XML, never emitting a partial tag to the client. Design note: plan v0.3 describes a single C++ process. The frontend is Python first because the template is Jinja and the formats change often; the engine boundary is token ids in, text deltas out, which keeps a later C++ port (or a pybind wrapper) a local change. """ from __future__ import annotations import json import uuid from dataclasses import dataclass, field from pathlib import Path import jinja2 from jinja2.sandbox import ImmutableSandboxedEnvironment # ------------------------------------------------------------------------------------------------ template class ChatTemplate: """The model's chat template, rendered with the same Jinja settings as transformers' apply_chat_template.""" def __init__(self, path: str | Path): def raise_exception(message): raise jinja2.exceptions.TemplateError(message) def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False): return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys) env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=["jinja2.ext.loopcontrols"]) env.filters["tojson"] = tojson env.globals["raise_exception"] = raise_exception self.source = Path(path).read_text(encoding="utf-8") self.template = env.from_string(self.source) # GLM-5.x: the template knows reasoning_effort "low" and "high" only - anything else, an absent one included, # is "Max", its most verbose - and it always opens <think> (no enable_thinking). The levels the server speaks # (low / medium / xhigh, or thinking off) map onto low / high / max, and off closes the think block the way # the template writes a turn without reasoning. self.glm_effort = "reasoning_effort in ['low', 'high']" in self.source def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True, **kwargs) -> str: off = False if self.glm_effort: off = kwargs.pop("enable_thinking", True) is False level = kwargs.pop("reasoning_effort", None) kwargs["reasoning_effort"] = "low" if off else {"low": "low", "medium": "high", "high": "high"}.get(level, "max") out = self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs) if off and add_generation_prompt and out.endswith("<think>"): out += "</think>" return out # ------------------------------------------------------------------------------------------------ requests def _text_of(content) -> str: if content is None: return "" if isinstance(content, str): return content return "".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in ("text", "input_text", None)) IMAGE_PARTS = ("image_url", "input_image", "image") # Thinking levels. The model's template knows low, medium and xhigh (its default; "high" means xhigh), and # enable_thinking=false for none. Clients spell these many ways; everything maps onto those four. EFFORT = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None, "low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh", "max": "xhigh", "maximum": "xhigh"} def effort_kwargs(value) -> dict: """A reasoning effort as given by a client -> the template's kwargs. Unknown values are a 400, not a crash.""" if value is None or value == "": return {} if value is False: return {"enable_thinking": False} key = str(value).strip().lower() if key not in EFFORT: raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium or high") level = EFFORT[key] return {"enable_thinking": False} if level is None else {"reasoning_effort": level} def budget_effort(tokens) -> dict: """Anthropic's thinking budget (budget_tokens) -> a level: under 2K low, under 8K medium, else high.""" try: n = int(tokens) except (TypeError, ValueError): return {} return {"reasoning_effort": "low" if n < 2048 else "medium" if n < 8192 else "xhigh"} def _has_image(content) -> bool: return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in IMAGE_PARTS for p in content) def _image_source(part: dict) -> str: """An image part's source as one string: a data: URL, an http(s) URL or a local file path. OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style {"type": "input_image", "image_url": ...}; Anthropic: {"type": "image", "source": {"type": "base64", "media_type": ..., "data": ...}} or {"source": {"type": "url", "url": ...}}.""" if part.get("type") == "image": src = part.get("source") or {} if src.get("type") == "base64": return f"data:{src.get('media_type', 'image/png')};base64,{src.get('data', '')}" return src.get("url") or src.get("path") or "" url = part.get("image_url") if isinstance(url, dict): url = url.get("url") return url or "" def _parts_of(content): """Message content for the template: a string when there is no image (unchanged behaviour), otherwise the template's list form - text items and image items, in order - whose image items carry their source.""" if not _has_image(content): return _text_of(content) items = [] for part in content: if not isinstance(part, dict): continue if part.get("type") in IMAGE_PARTS: items.append({"type": "image", "source": _image_source(part)}) elif part.get("type") in ("text", "input_text", None) and "text" in part: items.append({"type": "text", "text": part.get("text", "")}) return items def images_of(messages: list[dict]) -> list[str]: """The image sources of the rendered conversation, in prompt order (the template renders one <|vision_start|><|image_pad|><|vision_end|> per image item, message by message).""" return [item["source"] for m in messages if isinstance(m.get("content"), list) for item in m["content"] if item.get("type") == "image"] def _late_system_to_user(messages: list[dict]) -> list[dict]: """The chat template takes a system message only at the start ("System message must be at the beginning"). Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user turn, some OpenAI clients a late "developer" message (issue #56) - so those become user messages, in place: merging them into the first one would change the prompt's start and cost the conversation cache every turn.""" return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)] def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] for m in req.get("messages", []): role = m.get("role") if role == "developer": role = "system" out = {"role": role, "content": _parts_of(m.get("content")) if role in ("user", "tool", "assistant") else _text_of(m.get("content"))} if m.get("reasoning_content"): out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): calls = [] for c in m["tool_calls"]: fn = c.get("function", c) args = fn.get("arguments") if isinstance(args, str): # the template requires a mapping, not a JSON string args = json.loads(args) if args.strip() else {} calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}}) out["tool_calls"] = calls messages.append(out) tools = [t.get("function", t) if isinstance(t, dict) and t.get("type") == "function" else t for t in req.get("tools") or []] or None kwargs = {} # OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...} reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {} kwargs.update(effort_kwargs(req.get("reasoning_effort") or reasoning.get("effort"))) # the vLLM / llama.cpp convention: {"chat_template_kwargs": {"enable_thinking": false, "reasoning_effort": "low"}} for k, v in (req.get("chat_template_kwargs") or {}).items(): if k == "enable_thinking" and not v: kwargs = {"enable_thinking": False} elif k == "reasoning_effort" and "enable_thinking" not in kwargs: kwargs.update(effort_kwargs(v)) return _late_system_to_user(messages), tools, kwargs def anthropic_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """Anthropic Messages -> (template messages, template tools, template kwargs).""" messages = [] system = req.get("system") if system: messages.append({"role": "system", "content": _text_of(system)}) for m in req.get("messages", []): content = m.get("content") if isinstance(content, str): messages.append({"role": m["role"], "content": content}) continue if m.get("role") == "user" and _has_image(content) and not any( isinstance(b, dict) and b.get("type") == "tool_result" for b in content): messages.append({"role": "user", "content": _parts_of(content)}) continue text, reasoning, calls = [], [], [] for block in content or []: kind = block.get("type") if kind == "text": text.append(block.get("text", "")) elif kind == "thinking": reasoning.append(block.get("thinking", "")) elif kind == "tool_use": calls.append({"function": {"name": block.get("name"), "arguments": block.get("input") or {}}}) elif kind == "tool_result": messages.append({"role": "tool", "content": _text_of(block.get("content"))}) if text or calls or reasoning: out = {"role": m["role"], "content": "".join(text)} if reasoning: out["reasoning_content"] = "".join(reasoning) if calls: out["tool_calls"] = calls messages.append(out) tools = [{"name": t["name"], "description": t.get("description", ""), "parameters": t.get("input_schema", {})} for t in req.get("tools") or []] or None kwargs = {} # Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N}; # "output_config": {"effort": "low" | "medium" | "high"} thinking = req.get("thinking") effort = (req.get("output_config") or {}).get("effort") if isinstance(req.get("output_config"), dict) else None if isinstance(thinking, dict) and thinking.get("type") == "disabled": kwargs["enable_thinking"] = False elif effort: kwargs.update(effort_kwargs(effort)) elif isinstance(thinking, dict) and thinking.get("budget_tokens"): kwargs.update(budget_effort(thinking["budget_tokens"])) return _late_system_to_user(messages), tools, kwargs # ------------------------------------------------------------------------------------------------ output parser @dataclass class ToolCall: name: str arguments: dict id: str = field(default_factory=lambda: "call_" + uuid.uuid4().hex[:24]) @dataclass class Event: kind: str # "reasoning" | "content" | "tool_call" text: str = "" call: ToolCall | None = None THINK_END = "</think>" CALL_START = "<tool_call>" CALL_END = "</tool_call>" def _tool_header(body: str, complete: bool = False) -> tuple[str, int, bool] | None: """Return (name, body offset, is GLM), or wait for an incomplete streamed header.""" stripped = body.lstrip() lead = len(body) - len(stripped) if stripped.startswith("<function="): end = stripped.find(">") if end >= 0: return stripped[10:end], lead + end + 1, False elif stripped and not stripped.startswith("<"): end = stripped.find("<") if end >= 0 or complete: end = end if end >= 0 else len(stripped) name = stripped[:end].strip() if name and not any(c.isspace() for c in name): return name, lead + end, True return None def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall: """Qwen function/parameter or GLM name/arg_key/arg_value XML -> ToolCall. Values are JSON-decoded unless the schema declares a string; GLM string whitespace is literal.""" body = body.strip() header = _tool_header(body, complete=True) if header is None: raise ValueError("malformed tool call: " + body[:80]) name, offset, glm = header rest = body[offset:] props = ((schema or {}).get("parameters") or {}).get("properties") or {} args = {} key_start, key_end = ("<arg_key>", "</arg_key>") if glm else ("<parameter=", ">") value_end = "</arg_value>" if glm else "</parameter>" while key_start in rest: rest = rest[rest.index(key_start) + len(key_start):] pname = rest[:rest.index(key_end)] rest = rest[rest.index(key_end) + len(key_end):] if glm: rest = rest.lstrip() if not rest.startswith("<arg_value>"): raise ValueError("malformed tool argument: " + pname) rest = rest[len("<arg_value>"):] end = rest.find(value_end) value = rest[:end] if end >= 0 else rest rest = rest[end + len(value_end):] if end >= 0 else "" if not glm: if value.startswith("\n"): value = value[1:] if value.endswith("\n"): value = value[:-1] declared = (props.get(pname) or {}).get("type") if declared == "string": args[pname] = value else: try: args[pname] = json.loads(value) except ValueError: args[pname] = value return ToolCall(name=name, arguments=args) class OutputParser: """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back until it is complete, so clients never see `<tool_` or `</thi`.""" def __init__(self, thinking: bool = True, tools: list[dict] | None = None, stream_tools: bool = False): self.state = "reasoning" if thinking else "content" self.buf = "" self.lead = False self.schemas = {t.get("name"): t for t in tools or []} # stream_tools: a tool call is also reported while it is being written - "tool_start" (its name and id) as # soon as the name is known, then "tool_args" pieces of its JSON arguments (string parameters character by # character; other types whole, once complete) - before the final "tool_call". Without it, a client sees # nothing until the call is complete, which for a large file write can be many minutes. self.stream_tools = stream_tools self._reset_scan() def _reset_scan(self): self.sp = 0 # how much of self.buf (the call body) the scanner has consumed self.ss = "name" # name -> between -> str|raw -> ... -> done self.scall = None # the ToolCall being streamed (its id is reused by the final event) self.sfirst = True self.sval_started = False self.sdeclared = {} self.sglm = False self.send = "</parameter>" def _scan(self, complete: bool = False) -> list[Event]: """Advance the streaming view of the call body in self.buf (see stream_tools).""" out = [] def args(s): if s: out.append(Event("tool_args", s, call=self.scall)) while True: rest = self.buf[self.sp:] if self.ss == "name": header = _tool_header(rest, complete=complete) if header is None: return out name, offset, self.sglm = header self.send = "</arg_value>" if self.sglm else "</parameter>" self.scall = ToolCall(name=name, arguments={}) props = ((self.schemas.get(name) or {}).get("parameters") or {}).get("properties") or {} self.sdeclared = {k: (v or {}).get("type") for k, v in props.items()} out.append(Event("tool_start", call=self.scall)) args("{") self.sp += offset self.ss = "between" elif self.ss == "between": stripped = rest.lstrip() self.sp += len(rest) - len(stripped) key_start, key_end = ("<arg_key>", "</arg_key>") if self.sglm else ("<parameter=", ">") if stripped.startswith(key_start): b = stripped.find(key_end) if b < 0: return out pname = stripped[len(key_start):b] args(("" if self.sfirst else ",") + json.dumps(pname) + ":") self.sfirst = False self.sp += b + len(key_end) if self.sglm: self.snext = "str" if self.sdeclared.get(pname) == "string" else "raw" self.ss = "value" continue if self.sdeclared.get(pname) == "string": args('"') self.ss, self.sval_started = "str", False else: self.ss = "raw" elif stripped.startswith("</function>") or (self.sglm and complete and not stripped): args("}") if not self.sglm: self.sp += len("</function>") self.ss = "done" else: return out # a tag still arriving (or trailing text): wait elif self.ss == "value": stripped = rest.lstrip() if not stripped.startswith("<arg_value>"): return out self.sp += len(rest) - len(stripped) + len("<arg_value>") self.ss, self.sval_started = self.snext, False if self.ss == "str": args('"') elif self.ss == "str": if not self.sval_started: if not rest: return out if not self.sglm and rest[0] == "\n": # Qwen's delimiter newline is not part of the value self.sp += 1 rest = rest[1:] self.sval_started = True end = rest.find(self.send) if end >= 0: value = rest[:end] if not self.sglm and value.endswith("\n"): value = value[:-1] args(json.dumps(value)[1:-1] + '"') self.sp += end + len(self.send) self.ss = "between" continue safe = len(rest) - self._hold(rest, (self.send,)) if not self.sglm and safe > 0 and rest[safe - 1] == "\n": # Qwen's trailing delimiter newline safe -= 1 if safe > 0: args(json.dumps(rest[:safe])[1:-1]) self.sp += safe return out elif self.ss == "raw": end = rest.find(self.send) if end < 0: return out value = rest[:end] if not self.sglm: if value.startswith("\n"): value = value[1:] if value.endswith("\n"): value = value[:-1] try: v = json.loads(value) except ValueError: v = value args(json.dumps(v, ensure_ascii=False)) self.sp += end + len(self.send) self.ss = "between" else: return out def _close_scan(self) -> list[Event]: """A streamed call that ended without a clean </function>: close its JSON so clients can still parse it.""" out = [] if self.scall is None or self.ss == "done": return out tail = "" if self.ss == "str": tail += '"' elif self.ss == "raw": value = self.buf[self.sp:] tail += json.dumps(value if self.sglm else value.strip("\n")) elif self.ss == "value": tail += "null" # generation stopped before the GLM value tag arrived tail += "}" out.append(Event("tool_args", tail, call=self.scall)) self.ss = "done" return out def _hold(self, text: str, tags: tuple[str, ...]) -> int: """Length of the longest suffix of `text` that is a proper prefix of one of `tags`.""" best = 0 for tag in tags: for n in range(1, len(tag)): if text.endswith(tag[:n]): best = max(best, n) return best def feed(self, delta: str) -> list[Event]: self.buf += delta out: list[Event] = [] while True: if self.state == "reasoning": i = self.buf.find(THINK_END) if i < 0: keep = self._hold(self.buf, (THINK_END,)) if len(self.buf) > keep: out.append(Event("reasoning", self.buf[:len(self.buf) - keep])) self.buf = self.buf[len(self.buf) - keep:] return out if i: out.append(Event("reasoning", self.buf[:i])) self.buf = self.buf[i + len(THINK_END):] self.state, self.lead = "content", True elif self.state == "content": if self.lead: # newlines right after </think> or a call stripped = self.buf.lstrip("\n") if not stripped: self.buf = "" return out self.buf, self.lead = stripped, False i = self.buf.find(CALL_START) if i < 0: # Hold a partial tag AND the newlines before it: if a tool call follows, they are dropped, # so emitting them early would make streamed and whole outputs differ. j = len(self.buf) - self._hold(self.buf, (CALL_START,)) while j > 0 and self.buf[j - 1] == "\n": j -= 1 if j > 0: out.append(Event("content", self.buf[:j])) self.buf = self.buf[j:] return out if i and self.buf[:i].strip(): out.append(Event("content", self.buf[:i].rstrip("\n"))) self.buf = self.buf[i + len(CALL_START):] self.state = "call" else: i = self.buf.find(CALL_END) if self.stream_tools: if i >= 0: whole, self.buf = self.buf, self.buf[:i] # scan only the body out += self._scan(complete=True) out += self._close_scan() self.buf = whole else: out += self._scan() if i < 0: return out body = self.buf[:i] self.buf = self.buf[i + len(CALL_END):] header = _tool_header(body, complete=True) name = header[0] if header else None call = parse_tool_call(body, self.schemas.get(name)) if self.scall is not None: call.id = self.scall.id out.append(Event("tool_call", call=call)) self._reset_scan() self.state, self.lead = "content", True def finish(self) -> list[Event]: """End of generation: flush whatever is held (an unterminated tool call is returned as content).""" out = [] if self.state == "call" and self.stream_tools and self.scall is not None: out += self._scan() # the output ended inside a call that was already announced out += self._close_scan() out.append(Event("tool_call", call=self.scall)) self.buf = "" self._reset_scan() return out if self.buf: kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content") text = self.buf if self.state != "call" else CALL_START + self.buf out.append(Event(kind, text)) self.buf = "" return out ```
Author
Owner

@mw00 commented on GitHub (Oct 8, 2026):

Thanks for the report, and sorry it took this long. It is fixed in v1.0.13.

GLM-5.x writes its calls as <tool_call>NAME<arg_key>…</arg_key><arg_value>…</arg_value></tool_call>, and the server only read the <function=…> form. The parser now reads both:

  • whole, and streamed (the name first, then the arguments piece by piece);
  • with values typed from the tool's schema.

I checked the call and its result in the next turn with the model's own template, for both the OpenAI and Anthropic APIs. A call the model only quotes inside a code block now stays text.

Update with git pull, then start as usual. If a tool call still fails for you (MCP / Tavily included), please post the server line here.

<!-- gh-comment-id:6064342565 --> @mw00 commented on GitHub (Oct 8, 2026): Thanks for the report, and sorry it took this long. It is fixed in [v1.0.13](https://github.com/mw00/project-maya/releases/tag/v1.0.13). GLM-5.x writes its calls as `<tool_call>NAME<arg_key>…</arg_key><arg_value>…</arg_value></tool_call>`, and the server only read the `<function=…>` form. The parser now reads both: - whole, and streamed (the name first, then the arguments piece by piece); - with values typed from the tool's schema. I checked the call and its result in the next turn with the model's own template, for both the OpenAI and Anthropic APIs. A call the model only quotes inside a code block now stays text. Update with `git pull`, then start as usual. If a tool call still fails for you (MCP / Tavily included), please post the server line here.
Sign in to join this conversation.
No labels
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
mw00/project-maya#1
No description provided.