From e7c2edb8573cdea1ac842efbb650130e089895f8 Mon Sep 17 00:00:00 2001 From: Zuraiz Anjum Date: Fri, 2 Oct 2026 05:33:27 +0500 Subject: [PATCH] serve: honor stop and stop_sequences, cut the answer before the stop string and stop the engine there --- docs/DETAILS.md | 4 +- serve/server.py | 113 +++++++++++++++++++++++++++++++++++--- serve/test_server.py | 127 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 236 insertions(+), 8 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 78390cef..a1aa466b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -686,7 +686,9 @@ persisted across restarts. **Current limits (v1):** one request at a time unless `"parallel": N` is set (opt-in batch slots, up to N requests decoded together: [BATCHING.md](BATCHING.md)), and one conversation cached at a time (switching between two chats re-reads the other one unless the opt-in cache above is enabled, or each conversation keeps its own batch slot); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / -seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result +seed** are honored per request (OpenAI and Anthropic fields), and so are stop strings (OpenAI `stop`, a string or up +to 4; Anthropic `stop_sequences`): the answer ends before the first one, which is not sent, and the engine stops +there (`finish_reason` "stop"; `stop_reason` "stop_sequence" with `stop_sequence` set to the one found); with the default adaptive expert tier a sampled result is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out (`"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20}`); a request's own fields always win, and with no diff --git a/serve/server.py b/serve/server.py index 838068bd..496f6f80 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1713,6 +1713,63 @@ class Detokenizer: return delta +OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop` + + +def stop_strings(req: dict) -> list[str]: + """The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences` + (a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated.""" + req = req or {} + if req.get("stop") is not None: + stop = req["stop"] + stop = [stop] if isinstance(stop, str) else stop + if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop): + raise ValueError("stop must be a string or a list of strings") + if len(stop) > OPENAI_MAX_STOP: + raise ValueError(f"stop takes at most {OPENAI_MAX_STOP} strings") + elif req.get("stop_sequences") is not None: + stop = req["stop_sequences"] + if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop): + raise ValueError("stop_sequences must be a list of strings") + else: + return [] + return [x for x in stop if x] + + +class StopMatcher: + """Cuts the answer's text at the first stop string. Text that could still be the start of a stop string is held + back (only that tail, never more), so a stop string split across tokens or chunks is still found and never sent.""" + + def __init__(self, stops: list[str]): + self.stops, self.held, self.hit = stops, "", None + + def push(self, text: str) -> str: + """-> the text that is safe to send now; after a match, self.hit is the stop string and nothing more comes.""" + if self.hit is not None: + return "" + buf = self.held + text + first = None + for s in self.stops: + i = buf.find(s) + if i >= 0 and (first is None or i < first[0]): + first = (i, s) + if first is not None: + self.held, self.hit = "", first[1] + return buf[:first[0]] + keep = 0 # the longest end of buf that a stop string starts with + for s in self.stops: + for k in range(min(len(s) - 1, len(buf)), keep, -1): + if buf.endswith(s[:k]): + keep = k + break + self.held = buf[len(buf) - keep:] if keep else "" + return buf[:len(buf) - keep] + + def flush(self) -> str: + held, self.held = self.held, "" + return held + + class Service: def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", vision: Vision | None = None, sampling_defaults: dict | None = None, @@ -2321,6 +2378,27 @@ class Service: detok, n, finish = Detokenizer(self.tok), 0, "length" run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) + stop_list = stop_strings(sampling) + stops = StopMatcher(stop_list) if stop_list else None + + def cut(evs): + """The events with the answer's text cut at a stop string (OpenAI stop, Anthropic stop_sequences).""" + if stops is None: + return evs + out = [] + for ev in evs: + if stops.hit is not None: + break # nothing after the stop string is sent + if ev.kind == "content": + text = stops.push(ev.text or "") + if text: + out.append(Event("content", text)) + continue + held = stops.flush() # a stop string does not run across a tool call or thinking + if held: + out.append(Event("content", held)) + out.append(ev) + return out timings, before = None, None # this request's timings; the engine's `last` before it raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb = getattr(self.embeddings, "path", None) @@ -2387,11 +2465,14 @@ 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 here break - evs = parser.feed(detok.push(t)) + evs = cut(parser.feed(detok.push(t))) self._note(n, evs, st, rate) last_print = self._progress(last_print, st=st) for ev in evs: yield "event", ev + if stops is not None and stops.hit is not None: + finish = "stop" # gen.close() below STOPs the engine, as for a stop token + break if budget and parser.state == "reasoning": thought += 1 # at a clean point: no tag held back, no character split across tokens @@ -2434,10 +2515,13 @@ class Service: n += 1 raw_ids.append(t) thinking_n += parser.state in ("reasoning", "rcall") - evs = parser.feed(detok.push(t)) + evs = cut(parser.feed(detok.push(t))) self._note(n, evs, st, rate) for ev in evs: yield "event", ev + if stops is not None and stops.hit is not None: + finish = "stop" + break prompt = prompt + seg + extra if cancel.is_set(): finish = "cancel" @@ -2527,10 +2611,15 @@ class Service: finally: if emb: Path(emb).unlink(missing_ok=True) - for ev in parser.finish(): + for ev in cut(parser.finish()): yield "event", ev - yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), - "timings": timings, "reasoning_tokens": thinking_n} + if stops is not None and stops.hit is None and stops.held: + yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all + done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), + "timings": timings, "reasoning_tokens": thinking_n} + if stops is not None and stops.hit is not None: + done["stop_sequence"] = stops.hit + yield "done", done def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int: @@ -2848,12 +2937,14 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can else: if open_kind is not None: yield close() - stop = "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ + stop = "stop_sequence" if x.get("stop_sequence") is not None else \ + "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] # the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held, # which is cache_read_input_tokens (message_start could only say the whole prompt) reused = min(x.get("reused") or 0, len(ids)) - yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, + yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, + "stop_sequence": x.get("stop_sequence")}, "usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}} yield "message_stop", {"type": "message_stop"} @@ -2885,6 +2976,7 @@ def anthropic_collect(events) -> dict: blocks.pop() elif name == "message_delta": msg["stop_reason"] = e["delta"]["stop_reason"] + msg["stop_sequence"] = e["delta"].get("stop_sequence") msg["usage"].update(e["usage"]) msg["content"] = blocks return msg @@ -3462,6 +3554,7 @@ def make_handler(svc: Service): use_mcp = bool(extra) tools = (tools or []) + extra or None svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + stop_strings(req) # ... and so is a bad stop / stop_sequences ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() @@ -3610,6 +3703,10 @@ def make_handler(svc: Service): svc.reasoning_budget(req) # a bad value is a 400 before anything is sent except ValueError as e: raise ResponsesError(str(e), "reasoning_budget_tokens") from None + try: + stop_strings(req) + except ValueError as e: + raise ResponsesError(str(e), "stop") from None svc.load() try: ids, thinking, max_new = svc.prepare(messages, tools, kw, req.get("max_output_tokens") or 0) @@ -3630,6 +3727,7 @@ def make_handler(svc: Service): read for the same request, rendered and tokenized - the model does not run.""" req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + stop_strings(req) # the same 400 as the request itself would get self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))}) def _anthropic(self, req): @@ -3639,6 +3737,7 @@ def make_handler(svc: Service): self._no_local_images(messages) max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + stop_strings(req) # ... and so is a bad stop / stop_sequences ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) cancel = threading.Event() diff --git a/serve/test_server.py b/serve/test_server.py index e5c9e2c0..266df8e9 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2874,5 +2874,132 @@ class ImageSources(unittest.TestCase): httpd.server_close() +class CountingEngine(MockEngine): + """Counts the tokens the engine was asked for, so a test can see it stopped early.""" + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.yielded = 0 + for t in super().generate(ids, max_new, sampling, cancel, embeddings): + self.yielded += 1 + yield t + + +class StopStrings(unittest.TestCase): + """OpenAI `stop` and Anthropic `stop_sequences`: the answer ends before the first stop string, which is not sent, + and the engine stops there. The byte tokenizer gives one token per byte, so every stop string here is split + across tokens (and across streamed chunks).""" + ANSWER = "alpha END beta STOP gamma" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = CountingEngine(tok, "\n\n" + cls.ANSWER, max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def post(self, api, stream, **extra): + """-> (status, text, finish or stop_reason, stop_sequence, the streamed text pieces)""" + path = "/v1/chat/completions" if api == "openai" else "/v1/messages" + body = {"model": "x", "max_tokens": 200, "stream": stream, "messages": [{"role": "user", "content": "hi"}], + **extra} + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={ + "Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()), None, None, None + if not stream: + b = json.loads(raw) + if api == "openai": + c = b["choices"][0] + return 200, c["message"]["content"] or "", c["finish_reason"], None, None + text = "".join(x.get("text", "") for x in b["content"] if x["type"] == "text") + return 200, text, b["stop_reason"], b["stop_sequence"], None + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + if api == "openai": + pieces = [e["choices"][0]["delta"].get("content") or "" for e in evs] + return 200, "".join(pieces), evs[-1]["choices"][0]["finish_reason"], None, [p for p in pieces if p] + pieces = [e["delta"]["text"] for e in evs if e["type"] == "content_block_delta" + and e["delta"]["type"] == "text_delta"] + delta = [e for e in evs if e["type"] == "message_delta"][0]["delta"] + return 200, "".join(pieces), delta["stop_reason"], delta["stop_sequence"], pieces + + def stop_field(self, api, stops): + return {"stop": stops} if api == "openai" else {"stop_sequences": stops} + + def test_cut_at_the_stop_string(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + code, text, finish, seq, pieces = self.post(api, stream, **self.stop_field(api, ["END"])) + self.assertEqual(code, 200, text) + self.assertEqual(text, "alpha ") + if api == "openai": + self.assertEqual(finish, "stop") + else: + self.assertEqual((finish, seq), ("stop_sequence", "END")) + if stream: + self.assertFalse(any("E" in p for p in pieces), pieces) # no part of it was sent + # the engine stopped at the stop string, it did not run to the end of the answer + self.assertLess(self.engine.yielded, len("\n\n" + self.ANSWER)) + + def test_the_first_of_several(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + _, text, finish, seq, _ = self.post(api, stream, **self.stop_field(api, ["STOP", "beta", "zzz"])) + self.assertEqual(text, "alpha END ") + if api == "anthropic": + self.assertEqual((finish, seq), ("stop_sequence", "beta")) + + def test_openai_takes_a_string(self): + _, text, finish, _, _ = self.post("openai", False, stop="STOP") + self.assertEqual((text, finish), ("alpha END beta ", "stop")) + + def test_a_prefix_that_is_not_a_stop_is_sent(self): + """"ENDX" begins like the answer's "END" but is not in it: the held tail goes out and nothing is lost.""" + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + _, text, finish, seq, _ = self.post(api, stream, **self.stop_field(api, ["ENDX", "gammaZ"])) + self.assertEqual(text, self.ANSWER) + self.assertEqual(finish, "stop" if api == "openai" else "end_turn") + self.assertIsNone(seq) + + def test_no_stop_and_an_empty_list(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + for extra in ({}, self.stop_field(api, []), self.stop_field(api, ["nowhere"])): + with self.subTest(api=api, stream=stream, extra=extra): + _, text, finish, seq, _ = self.post(api, stream, **extra) + self.assertEqual(text, self.ANSWER) + self.assertEqual(finish, "stop" if api == "openai" else "end_turn") + self.assertIsNone(seq) + + def test_bad_values_are_a_400(self): + for api, extra in (("openai", {"stop": ["a", "b", "c", "d", "e"]}), ("openai", {"stop": 5}), + ("anthropic", {"stop_sequences": "END"}), ("anthropic", {"stop_sequences": [1]})): + with self.subTest(api=api, extra=extra): + code, *_ = self.post(api, False, **extra) + self.assertEqual(code, 400) + + def test_matcher_holds_back_only_a_possible_prefix(self): + from serve.server import StopMatcher + m = StopMatcher([""]) + self.assertEqual(m.push("a <"), "a ") # "<" may start "" + self.assertEqual(m.push("b"), " d"), "") + self.assertEqual(m.hit, "") + self.assertEqual(m.push("more"), "") + + if __name__ == "__main__": unittest.main()