Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: honour OpenAI tool_choice "required" and a named function
Amir Guindehib3c63f7e0be3
diff --git a/serve/frontend.py b/serve/frontend.pyindex 4d2310ce2..13fa735fc 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -449,6 +449,48 @@ def call_end(text: str) -> int:return text.find(CALL_END, pos)+def tool_choice_of(tool_choice) -> tuple[str, str | None]:+ """A client's `tool_choice` in either API's shape -> ("auto" | "none" | "required" | "named", name). OpenAI:+ "auto" / "none" / "required", {"type": "function", "function": {"name": N}} or the flat {"type": "function",+ "name": N}; Anthropic: {"type": "auto" | "any" | "none"} and {"type": "tool", "name": N}. A value it does not+ know is ("unknown", None)."""+ if tool_choice is None:+ return "auto", None+ if isinstance(tool_choice, str):+ return (tool_choice, None) if tool_choice in ("auto", "none", "required") else ("unknown", None)+ if isinstance(tool_choice, dict):+ kind = tool_choice.get("type")+ if kind in ("auto", "none"):+ return kind, None+ if kind in ("any", "required"):+ return "required", None+ if kind in ("function", "tool"):+ fn = tool_choice.get("function")+ name = (fn.get("name") if isinstance(fn, dict) else None) or tool_choice.get("name")+ if isinstance(name, str) and name:+ return "named", name+ return "unknown", None+++def forced_call(tool_choice, tools: list[dict] | None) -> str | None:+ """`tool_choice` -> the text that opens the call the reply must make, or None (the model decides).+ There is no grammar here: the server writes this opening itself, so the model can only go on with a call.+ "required" / Anthropic "any": any of the tools; a named function: that one. A value it cannot honour (an+ unknown shape, a name that is not one of the tools, "required" with no tools) is logged and acts as "auto",+ not a 400: a client's odd choice must not stop its request. "none" is handled by the caller (no tools)."""+ kind, name = tool_choice_of(tool_choice)+ names = {t.get("name") for t in tools or [] if isinstance(t, dict)}+ if kind in ("auto", "none"):+ return None+ if kind == "required" and names:+ return CALL_START + "\n<function="+ if kind == "named" and name in names:+ return CALL_START + f"\n<function={name}>\n"+ print(f"[strata] tool_choice {json.dumps(tool_choice)[:200]} is not supported here (or names no tool of the "+ "request): the model decides, as with \"auto\"", flush=True)+ return None++def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:"""`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> ToolCall. Values are JSON-decodedwhen the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSONdiff --git a/serve/server.py b/serve/server.pyindex b8067f15c..22ebeabd7 100644--- a/serve/server.py+++ b/serve/server.py@@ -53,7 +53,8 @@ ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "tools"))sys.path.insert(0, str(ROOT)) # run as a script (run-<model>.bat) as well as a modulefrom serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402- images_of, mark_think_literals, openai_to_messages, unmark_think_literals)+ forced_call, images_of, mark_think_literals, openai_to_messages, tool_choice_of,+ unmark_think_literals)from serve.mcp import McpCancelled, hub_from_config # noqa: E402from serve import runconfig # noqa: E402from serve.winjob import contain # noqa: E402@@ -2265,10 +2266,13 @@ class Service:prompt, plain = unmark_think_literals(prompt)return self.tok.encode(prompt, parse_special=True, plain=plain)- def prepare(self, messages, tools, kwargs, max_new=None):+ def prepare(self, messages, tools, kwargs, max_new=None, force=None):"""-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited":- the rest of the context."""+ the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the+ prompt; with thinking, Service.run writes it once the thinking is over."""ids = self.encode_prompt(messages, tools, kwargs)+ if force and kwargs.get("enable_thinking", True) is False:+ ids = ids + self.tok.encode(force, parse_special=True)self.embeddings.path = Noneimages = images_of(messages)if images:@@ -2367,8 +2371,9 @@ class Service:f"{el:.0f} s", flush=True)return now- def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]:- """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..})."""+ def run(self, ids, thinking, tools, max_new, sampling, cancel, force=None) -> Iterator[tuple[str, object]]:+ """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).+ `force` (forced_call): the opening of the call the reply must make - see prepare()."""budget = self.reasoning_budget(sampling) if thinking else None # #123: opt-in, off by defaultdefaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with appsif defaults: # the request's own fields win (explicit 0 stays greedy)@@ -2399,6 +2404,10 @@ class Service:out.append(Event("content", held))out.append(ev)return out+ opening = [] # without thinking the prompt ends with the forced opening:+ if force and not thinking: # the parser reads it as if the model had written it+ opening, force = parser.feed(force), None+ tail = "" # the last characters written (the newlines before a call)timings, before = None, None # this request's timings; the engine's `last` before itraw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text)emb = getattr(self.embeddings, "path", None)@@ -2439,10 +2448,13 @@ class Service:before = getattr(self.engine, "last", None)last_print = time.time()prompt, thought = ids, 0 # thought: the reasoning tokens so far (the budget's count)+ for ev in opening:+ yield "event", evwhile True:gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \else self.engine.generate(prompt, max_new - n, sampling, cancel)seg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closed+ opens = False # the thinking is over: write the forced call's openingtry:for t in gen:if t is None: # heartbeat while the engine is quiet@@ -2465,7 +2477,9 @@ class Service:if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens:repeated = True # #606: a degenerate output, not an answer: end it herebreak- evs = cut(parser.feed(detok.push(t)))+ piece = detok.push(t)+ tail = (tail + piece)[-2:]+ evs = cut(parser.feed(piece))self._note(n, evs, st, rate)last_print = self._progress(last_print, st=st)for ev in evs:@@ -2479,6 +2493,12 @@ class Service:if thought >= budget and not parser.buf and not detok.pending():wrap = Truebreak+ if force:+ if any(ev.kind in ("tool_start", "tool_call") for ev in evs):+ force = None # the model is writing a call of its own+ elif parser.state == "content" and not parser.buf and not detok.pending():+ opens = True+ breakexcept EngineDied as e:finish = "error"self._say_died(e)@@ -2500,17 +2520,25 @@ class Service:self._say_died(e)if not leaving and not cancel.is_set():raise- if not wrap or cancel.is_set():+ if not (wrap or opens) or cancel.is_set():break# #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a# short wrap-up and </think>) and let it answer: the next pass's prompt is this one plus what# was generated plus the wrap-up, so the engine continues from the prefix it already holds.- budget = None- extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True)+ # A forced call (tool_choice) is opened the same way: after the wrap-up, or where the+ # thinking ended, after the blank line the template puts before a call.+ if wrap:+ budget = None+ text = REASONING_WRAP_UP + (force or "")+ else:+ text = "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force+ force = None+ extra = self.tok.encode(text, parse_special=True)if max_new - n - len(extra) < 1:break # no room left to answer: "length", as without a budget- print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking",- flush=True)+ if wrap:+ print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking",+ flush=True)for t in extra:n += 1raw_ids.append(t)@@ -2757,9 +2785,9 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new,# ------------------------------------------------------------------------------------------------ OpenAI-def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None):+def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None, force=None):"""`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with- an empty delta and a `strata_mcp` field, which only the web app reads."""+ an empty delta and a `strata_mcp` field, which only the web app reads. `force`: see Service.run."""cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time())model = svc.model_for(req)@@ -2771,7 +2799,7 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancelcalls = 0streamed = {} # tool call id -> index, for calls sent piece by piecefinished = set() # ... and the ones whose final tool_call came (#211)- for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel):+ for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force):if kind == "ping":yield Noneelif kind == "mcp":@@ -2882,7 +2910,7 @@ def structured_chunks(chunks, validator):# ------------------------------------------------------------------------------------------------ Anthropic-def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel):+def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, force=None):mid = "msg_" + uuid.uuid4().hex[:24]yield "message_start", {"type": "message_start", "message": {"id": mid, "type": "message", "role": "assistant", "model": svc.model_for(req), "content": [],@@ -2893,7 +2921,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, canreturn ("content_block_stop", {"type": "content_block_stop", "index": index})streamed, finished = set(), set() # calls sent piece by piece; those whose final tool_call came (#211)- for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel):+ for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel, force=force):if kind == "ping":yield Nonecontinue@@ -3577,6 +3605,9 @@ def make_handler(svc: Service):req = svc.with_shared(req, "openai")messages, tools, kw = openai_to_messages(req)self._no_local_images(messages)+ if tool_choice_of(req.get("tool_choice"))[0] == "none": # as the Responses route: no tools are offered+ tools = None+ force = forced_call(req.get("tool_choice"), tools) # a bad value is a 400 before anything is sentmessages, validator = prepare_format(req.get("response_format"), messages)if validator is not None and (tools or req.get("strata_mcp")):raise ValueError("structured response_format with tools/MCP is not supported")@@ -3591,15 +3622,17 @@ def make_handler(svc: Service):extra = svc.mcp.template_tools(exclude=own) # the request's own tools win a name clashuse_mcp = bool(extra)tools = (tools or []) + extra or None+ if force and use_mcp:+ raise ValueError("a forced tool_choice with MCP tools is not supported")svc.reasoning_budget(req) # a bad value is a 400 before anything is sentstop_strings(req) # ... and so is a bad stop / stop_sequences- ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new)+ ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force)_debug_req("openai", req, messages, tools, max_new, thinking, len(ids))cancel = threading.Event()self._watch_client(cancel) # #430 #431run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel,{t["name"] for t in extra}) if use_mcp else None- chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run)+ chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force)if validator is not None:chunks = structured_chunks(chunks, validator)chunks = self._capture(chunks, "openai")@@ -3773,14 +3806,17 @@ def make_handler(svc: Service):req = svc.with_shared(req, "anthropic")messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked)self._no_local_images(messages)+ if tool_choice_of(req.get("tool_choice"))[0] == "none": # Anthropic's {"type": "none"}: no tools offered+ tools = None+ force = forced_call(req.get("tool_choice"), tools) # "any" / {"type": "tool", "name": N}max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the contextsvc.reasoning_budget(req) # a bad value is a 400 before anything is sentstop_strings(req) # ... and so is a bad stop / stop_sequences- ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new)+ ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force)_debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids))cancel = threading.Event()self._watch_client(cancel) # #430 #431- events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel)+ events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel, force=force)events = self._capture(events, "anthropic")if not req.get("stream"):return self._json(200, anthropic_collect(events))diff --git a/serve/test_server.py b/serve/test_server.pyindex f1d70a285..778e8f4f7 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -2204,6 +2204,183 @@ class ThinkingBudget(unittest.TestCase):self.assertEqual(self.engine.prompts, [])+class CallingEngine(MockEngine):+ """Thinks, then answers in text - unless its prompt already opens a call (a forced tool_choice): then it finishes+ that call. Records every prompt it is given."""+ THOUGHT = "I could look this up. " * 8 # 176 reasoning tokens (one per byte)+ ANSWER = "The answer is 4."+ ARGS = "<parameter=q>\n2+2\n</parameter>\n</function>\n</tool_call>"++ def __init__(self, tok):+ super().__init__(tok, "x", max_context=CTX)+ self.prompts = []++ def generate(self, ids, max_new, sampling, cancel, embeddings=None):+ self.prompts.append(list(ids))+ prompt = self.tok.decode(ids)+ if prompt.endswith("<function="):+ text = "search>\n" + self.ARGS+ elif prompt.endswith("<function=search>\n"):+ text = self.ARGS+ elif prompt.endswith("</think>\n\n"):+ text = self.ANSWER+ else:+ text = self.THOUGHT + "</think>\n\n" + self.ANSWER+ for t in (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]:+ if cancel.is_set():+ return+ yield t+++class ForcedToolChoice(unittest.TestCase):+ """tool_choice "required" or a named function: the server writes the call's opening - after the thinking, or at+ the end of the prompt without thinking - so the model can only go on with a call."""+ TOOLS = [{"type": "function", "function": {"name": "search", "description": "search the web",+ "parameters": {"type": "object",+ "properties": {"q": {"type": "string"}}}}},+ {"type": "function", "function": {"name": "done", "parameters": {"type": "object", "properties": {}}}}]+ NAMED = {"type": "function", "function": {"name": "search"}}+ NO_THINKING = {"chat_template_kwargs": {"enable_thinking": False}}++ def setUp(self):+ self.tok = ByteTokenizer()+ self.engine = CallingEngine(self.tok)+ self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ self.httpd = serve(self.svc, port=0)+ self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"++ def tearDown(self):+ self.httpd.shutdown()+ self.httpd.server_close()++ def openai(self, **extra):+ body = {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], "max_tokens": 400,+ "tools": self.TOOLS, **extra}+ req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=30) as r:+ raw = r.read().decode()+ return r.status, (json.loads(raw) if not body.get("stream") else raw)+ except urllib.error.HTTPError as e:+ with e:+ return e.code, json.loads(e.read())++ def call_of(self, code, b, stream):+ """-> (finish_reason, [(name, arguments)], reasoning) of a whole or a streamed reply."""+ self.assertEqual(code, 200, b)+ if not stream:+ choice = b["choices"][0]+ calls = [(c["function"]["name"], json.loads(c["function"]["arguments"]))+ for c in choice["message"].get("tool_calls") or []]+ return choice["finish_reason"], calls, choice["message"].get("reasoning_content") or ""+ chunks = [json.loads(line[6:]) for line in b.splitlines() if line.startswith("data: {")]+ names, args, reasoning, finish = {}, {}, "", None+ for c in chunks:+ d = c["choices"][0]["delta"]+ reasoning += d.get("reasoning_content") or ""+ for tc in d.get("tool_calls") or []:+ names.setdefault(tc["index"], tc["function"].get("name"))+ args[tc["index"]] = args.get(tc["index"], "") + tc["function"].get("arguments", "")+ finish = c["choices"][0]["finish_reason"] or finish+ return finish, [(names[i], json.loads(args[i])) for i in sorted(names)], reasoning++ def test_required_and_named_after_the_thinking(self):+ for choice in ("required", self.NAMED):+ for stream in (False, True):+ with self.subTest(choice=choice, stream=stream):+ self.engine.prompts = []+ code, b = self.openai(tool_choice=choice, stream=stream)+ finish, calls, reasoning = self.call_of(code, b, stream)+ self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})]))+ self.assertEqual(reasoning, CallingEngine.THOUGHT)+ first, second = self.engine.prompts+ opening = "<tool_call>\n<function=" + ("search>\n" if choice == self.NAMED else "")+ # where the thinking ended, after the blank line the template puts before a call+ self.assertEqual(second, first + self.tok.encode(CallingEngine.THOUGHT + "</think>\n\n" + opening))++ def test_without_thinking_the_prompt_ends_with_the_opening(self):+ for choice in ("required", self.NAMED):+ for stream in (False, True):+ with self.subTest(choice=choice, stream=stream):+ self.engine.prompts = []+ code, b = self.openai(tool_choice=choice, stream=stream, **self.NO_THINKING)+ finish, calls, reasoning = self.call_of(code, b, stream)+ self.assertEqual((finish, calls, reasoning), ("tool_calls", [("search", {"q": "2+2"})], ""))+ self.assertEqual(len(self.engine.prompts), 1)+ opening = "<tool_call>\n<function=" + ("search>\n" if choice == self.NAMED else "")+ self.assertTrue(self.tok.decode(self.engine.prompts[0]).endswith("</think>\n\n" + opening))++ def test_the_budget_wrap_up_opens_the_call(self):+ from serve.server import REASONING_WRAP_UP+ code, b = self.openai(tool_choice="required", reasoning_budget_tokens=20)+ finish, calls, reasoning = self.call_of(code, b, False)+ self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})]))+ self.assertEqual(reasoning, CallingEngine.THOUGHT[:20] + REASONING_WRAP_UP.split("</think>")[0])+ first, second = self.engine.prompts+ extra = self.tok.encode(REASONING_WRAP_UP + "<tool_call>\n<function=", parse_special=True)+ self.assertEqual(second, first + self.tok.encode(CallingEngine.THOUGHT[:20]) + extra)++ def test_auto_absent_and_none_leave_the_tools_to_the_model(self):+ for extra in ({}, {"tool_choice": "auto"}, {"tool_choice": "none"}):+ with self.subTest(extra=extra):+ self.engine.prompts = []+ code, b = self.openai(**extra)+ self.assertEqual(code, 200, b)+ self.assertEqual(b["choices"][0]["message"]["content"], CallingEngine.ANSWER)+ self.assertEqual(b["choices"][0]["finish_reason"], "stop")+ self.assertEqual(len(self.engine.prompts), 1)+ offered = "search the web" in self.tok.decode(self.engine.prompts[0])+ self.assertEqual(offered, extra.get("tool_choice") != "none") # "none": no tools in the prompt++ def test_a_call_cut_by_max_tokens_is_not_a_tool_call(self):+ code, b = self.openai(tool_choice="required", max_tokens=5, **self.NO_THINKING)+ finish, calls, _ = self.call_of(code, b, False)+ self.assertEqual((finish, calls), ("length", []))++ def test_values_it_cannot_honour_act_as_auto(self):+ """Not a 400: an odd tool_choice is logged and the model decides."""+ named = lambda n: {"type": "function", "function": {"name": n}} # noqa: E731+ for choice, tools in ((named("nope"), self.TOOLS), ({"type": "function"}, self.TOOLS),+ ("required", None), ({"type": "banana"}, self.TOOLS), ("sometimes", self.TOOLS)):+ with self.subTest(choice=choice, tools=bool(tools)):+ self.engine.prompts = []+ code, b = self.openai(tool_choice=choice, tools=tools)+ self.assertEqual(code, 200, b)+ self.assertEqual(b["choices"][0]["message"]["content"], CallingEngine.ANSWER)+ self.assertEqual(len(self.engine.prompts), 1)++ def test_the_flat_shape_names_a_function(self):+ code, b = self.openai(tool_choice={"type": "function", "name": "search"})+ finish, calls, _ = self.call_of(code, b, False)+ self.assertEqual((finish, calls), ("tool_calls", [("search", {"q": "2+2"})]))++ def test_anthropic_any_tool_none(self):+ tools = [{"name": "search", "description": "search the web", "input_schema": {+ "type": "object", "properties": {"q": {"type": "string"}}}}, {"name": "done", "input_schema": {+ "type": "object", "properties": {}}}]+ for choice, want in (({"type": "any"}, "tool_use"), ({"type": "tool", "name": "search"}, "tool_use"),+ ({"type": "auto"}, "end_turn"), ({"type": "none"}, "end_turn"),+ ({"type": "tool", "name": "nope"}, "end_turn")):+ for stream in (False, True):+ with self.subTest(choice=choice, stream=stream):+ self.engine.prompts = []+ body = {"model": "m", "max_tokens": 400, "stream": stream, "tools": tools, "tool_choice": choice,+ "messages": [{"role": "user", "content": "2+2?"}]}+ req = urllib.request.Request(self.base + "/v1/messages", data=json.dumps(body).encode(), headers={+ "Content-Type": "application/json", "anthropic-version": "2023-06-01"})+ with urllib.request.urlopen(req, timeout=30) as r:+ raw = r.read().decode()+ if stream:+ evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]+ stop = [e for e in evs if e["type"] == "message_delta"][0]["delta"]["stop_reason"]+ else:+ stop = json.loads(raw)["stop_reason"]+ self.assertEqual(stop, want)+ offered = "search the web" in self.tok.decode(self.engine.prompts[0])+ self.assertEqual(offered, choice["type"] != "none")++class StatusHandover(unittest.TestCase):"""#266: a stream aborted mid-way and the next request, which was waiting for the fifo. The aborted request'sstatus/history block ran after the fifo was released, so the waiting request could start in that gap: the old