Streaming - tool calls stream as they are written (OpenAI tool_calls deltas, Anthropic input_json_delta) - keep-alives while a long prompt is read, progress in the server window, GET /status - closing the connection or pressing stop really stops the engine (STOP) Stalled requests (mostly image turns) - the expert cache is sized after its slots are written (Windows only counts GPU memory once it is touched), so the reserve really stays free instead of the card running at 0 MiB and paging - the prompt chunk shrinks when its buffers do not fit in the cache, instead of allocating on top - the image encoder warms up before the engine starts; images are encoded in request order - the log shows the VRAM left once everything is loaded setup.py now requires engine 0.1.2 (downloaded automatically on the next START-HERE.bat).
480 lines
22 KiB
Python
480 lines
22 KiB
Python
"""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
|
|
the template's XML form (`<tool_call><function=NAME><parameter=P>VALUE</parameter>...</function></tool_call>`),
|
|
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.template = env.from_string(Path(path).read_text(encoding="utf-8"))
|
|
|
|
def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True,
|
|
**kwargs) -> str:
|
|
return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt,
|
|
**kwargs)
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ 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 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 == "user" 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 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 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 parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:
|
|
"""`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> ToolCall. Values are JSON-decoded
|
|
when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON
|
|
objects/arrays/numbers/booleans)."""
|
|
body = body.strip()
|
|
if not body.startswith("<function=") or ">" not in body:
|
|
raise ValueError("malformed tool call: " + body[:80])
|
|
name = body[len("<function="):body.index(">")]
|
|
rest = body[body.index(">") + 1:]
|
|
props = ((schema or {}).get("parameters") or {}).get("properties") or {}
|
|
args = {}
|
|
while "<parameter=" in rest:
|
|
rest = rest[rest.index("<parameter=") + len("<parameter="):]
|
|
pname = rest[:rest.index(">")]
|
|
rest = rest[rest.index(">") + 1:]
|
|
end = rest.find("</parameter>")
|
|
value = rest[:end] if end >= 0 else rest
|
|
rest = rest[end + len("</parameter>"):] if end >= 0 else ""
|
|
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 = {}
|
|
|
|
def _scan(self) -> 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":
|
|
a = rest.find("<function=")
|
|
b = rest.find(">", a + 10) if a >= 0 else -1
|
|
if b < 0:
|
|
return out
|
|
name = rest[a + 10:b]
|
|
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 += b + 1
|
|
self.ss = "between"
|
|
elif self.ss == "between":
|
|
stripped = rest.lstrip()
|
|
self.sp += len(rest) - len(stripped)
|
|
if stripped.startswith("<parameter="):
|
|
b = stripped.find(">")
|
|
if b < 0:
|
|
return out
|
|
pname = stripped[11:b]
|
|
args(("" if self.sfirst else ",") + json.dumps(pname) + ":")
|
|
self.sfirst = False
|
|
self.sp += b + 1
|
|
if self.sdeclared.get(pname) == "string":
|
|
args('"')
|
|
self.ss, self.sval_started = "str", False
|
|
else:
|
|
self.ss = "raw"
|
|
elif stripped.startswith("</function>"):
|
|
args("}")
|
|
self.sp += len("</function>")
|
|
self.ss = "done"
|
|
else:
|
|
return out # a tag still arriving (or trailing text): wait
|
|
elif self.ss == "str":
|
|
if not self.sval_started:
|
|
if not rest:
|
|
return out
|
|
if rest[0] == "\n": # the value's leading newline is not part of it
|
|
self.sp += 1
|
|
rest = rest[1:]
|
|
self.sval_started = True
|
|
end = rest.find("</parameter>")
|
|
if end >= 0:
|
|
value = rest[:end]
|
|
if value.endswith("\n"):
|
|
value = value[:-1]
|
|
args(json.dumps(value)[1:-1] + '"')
|
|
self.sp += end + len("</parameter>")
|
|
self.ss = "between"
|
|
continue
|
|
safe = len(rest) - self._hold(rest, ("</parameter>",))
|
|
if safe > 0 and rest[safe - 1] == "\n": # may be the trailing newline before </parameter>
|
|
safe -= 1
|
|
if safe > 0:
|
|
args(json.dumps(rest[:safe])[1:-1])
|
|
self.sp += safe
|
|
return out
|
|
elif self.ss == "raw":
|
|
end = rest.find("</parameter>")
|
|
if end < 0:
|
|
return out
|
|
value = rest[:end]
|
|
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("</parameter>")
|
|
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":
|
|
tail += json.dumps(self.buf[self.sp:].strip("\n"))
|
|
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()
|
|
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):]
|
|
name = body.strip()[len("<function="):].split(">", 1)[0]
|
|
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
|