mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 23:08:36 +00:00
serve: a reply with tools that ends in tool-call markup that is no call is written again once; strata_unread_tool_markup
A user's report of agent turns that stopped (499 turns, 63 sessions) had 43 replies that ended in tool-call markup the
server did not run: 30 named a tool the request did not declare, 13 were
cut before their end or did not read as a call. The agent took the text for an answer and stopped.
Now, for a request that declared tools (chat completions, messages and responses alike), the answer's text from a
`<tool_call>` (or a bare `<function=`) opener at a line start is held back until the reply goes on past the block (then
it is sent as written) or the model stops in it. At that natural stop the rest of the output is read as before; when
the reply ends in markup that is no call and no call came out, it is written again once inside the same request:
the prompt goes on with the reply, a short user-turn note (why the call was not run, the declared tools, the closest
declared name for an undeclared one) and an assistant turn without thinking. The new reply takes the held markup's
place; words written before it stay. Nothing runs under a guessed name: the strict parser reads the new reply as it
reads any other. One retry only, and only when at least 64 output tokens are left after the note (the note counts
against max_tokens, so the reply stays inside the context). Not for a JSON-form template or another model family.
- /metrics/prometheus: strata:tool_markup_retries_total; one log line per retry (reason, names, hint, held length).
- strata_unread_tool_markup {"reason": "cut_off" | "unreadable", "chars": n}: the reply the client got still ends
in such markup and it is not in strata_rejected_tool_calls; at the same places as that list (chat: the last stream
chunk / the body; messages: message_delta / the body). /v1/responses now carries both fields at the top level of
the response object.
- Off: config "tool_markup_retry": false, or STRATA_TOOL_MARKUP_RETRY=0 (the server's own switch; the settings
register lists only names the engine reads, so it is documented in docs/DETAILS.md's config table).
Test: serve/test_tool_markup_retry.py: the 43 stops' shapes rewritten with neutral text (the report holds private
paths and content), whole and per character: 42 held and written again (30 rejected with the expected hints, 7 cut
off, 5 unreadable), the 43rd (prose without markup) not; the server path with a scripted engine: an undeclared name
written again as a declared call, the hint in the note, one retry only then the text with the markers (stream and
not), the rollback switch, no room, no tools, the streamed markup never sent when the retry calls, messages and
responses markers.
Live (l620, the shared BASE-05 Qwen set; a system prompt that shows an `exec` tool the request does not declare,
only `read` declared; 12 requests per arm): retry off, 12 of 12 replies ended in `exec` markup; on, 12 retries, then
6 replies called `read`, 5 answered in text, 1 still ended in `exec` (sent as text, in the rejected list). An
ordinary request (pwsh declared): a pwsh call and no retry in both arms.
This commit is contained in:
1 parent
3e1efe7fde
commit
e05e6e0ccc
4 files changed
+539
-5
No files matched your search
@@ -510,6 +510,7 @@ applies at the next start. Network, key, MCP and program keys are not editable t
|
||||
| `anthropic_thinking` | as the template | `"on_request"` renders a `/v1/messages` request that asks for no thinking without thinking, as Anthropic does. Claude Code's short helper calls need it. |
|
||||
| `tool_call_recovery` | on (since 0.2.8; off in 0.2.7 and before) | Also reads a declared tool's call written as `<parameter=NAME>`, as JSON inside `<tool_call>`, as a `<function=NAME>` block without `<tool_call>`, or as a second call inside one `<tool_call>`. On 1,462 agent turns 98.3% read as intended with it and 92.9% without; the 49 specimens of the test corpus read the same with it on or off. Only a declared tool's call is ever recovered; anything else stays text. `"tool_call_recovery": false` turns it off. |
|
||||
| `undeclared_tool_calls` | `"text"` | A well-formed call of a tool the request did not declare stays the text the model wrote, with `strata_rejected_tool_calls` beside it (the default, as since 0.2.2). `"call"` returns it as a tool call instead, for a client with its own policy for unknown names: it can answer the model with the tool names it has and ask again, which a call kept as text never lets it do. The environment variable `STRATA_UNDECLARED_TOOL_CALLS` sets the same; the config wins. Only a call the parser reads as a whole call is returned; prose and quoted examples stay text (#4622). |
|
||||
| `tool_markup_retry` | on | A reply to a request with tools that ends in tool-call markup the server does not run (a tool name the request did not declare, a call cut off before its end, a block that reads as no call) is written again once, inside the same request: the markup is held back, the model reads a short note naming the declared tools (and the closest one to the name it wrote), and its new reply takes the markup's place. Nothing is run under a guessed name. `/metrics` counts the retries (`strata:tool_markup_retries_total`). A reply that still ends in such markup carries `strata_unread_tool_markup` (`reason`: `cut_off` or `unreadable`, `chars`). `false`, or `STRATA_TOOL_MARKUP_RETRY=0` in the environment, sends the markup as text, as before. |
|
||||
| `env_to_user` | off | Moves opencode's `<env>` block (working directory, date) to the first user message so the system turn is the same for every session and the disk prefix cache restores it. |
|
||||
| `return_progress` | off | Per request `"return_progress": true` adds llama.cpp's `prompt_progress` (`total`, `cache`, `processed`, `time_ms`) to the stream, one update per `--prefill` chunk. A prompt shorter than one chunk sends nothing. |
|
||||
| `prevent_sleep` | off | Windows only: keeps the PC awake while a request runs or waits (`SetThreadExecutionState`). On Linux and macOS one startup line says it does nothing. |
|
||||
|
||||
@@ -837,6 +837,11 @@ class Assembler:
|
||||
"input_tokens": prompt, "input_tokens_details": {"cached_tokens": min(done.get("reused") or 0, prompt)},
|
||||
"output_tokens": n, "output_tokens_details": {"reasoning_tokens": done.get("reasoning_tokens", 0)},
|
||||
"total_tokens": prompt + n}
|
||||
# #3796 / (a): the markers /v1/chat/completions carries, at the top level of the response object
|
||||
if done.get("rejected_tool_calls"):
|
||||
self.response["strata_rejected_tool_calls"] = done["rejected_tool_calls"]
|
||||
if done.get("unread_tool_markup"):
|
||||
self.response["strata_unread_tool_markup"] = done["unread_tool_markup"]
|
||||
if length:
|
||||
self.response["status"] = "incomplete"
|
||||
self.response["incomplete_details"] = {"reason": "max_output_tokens"}
|
||||
|
||||
+223
-5
@@ -62,7 +62,8 @@ from urllib.parse import parse_qs, urlsplit
|
||||
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 module
|
||||
from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, parser_for_template, anthropic_to_messages, anthropic_tools, # noqa: E402
|
||||
from serve.frontend import (CALL_END, CALL_START, FUNC_END, FUNC_START, THINK_END, ChatTemplate, Event, OutputParser, # noqa: E402
|
||||
parser_for_template, anthropic_to_messages, anthropic_tools,
|
||||
forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages, require_messages,
|
||||
tool_choice_of, unmark_think_literals)
|
||||
from serve.mcp import McpCancelled, hub_from_config, resolve_image_results # noqa: E402
|
||||
@@ -5090,6 +5091,9 @@ class Service:
|
||||
self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False
|
||||
self.undeclared_tool_calls = "text" # #4622: config "undeclared_tool_calls": "call" hands a call of an undeclared name to the client
|
||||
self.tool_call_recovery = True # default on (0.2.8): tool calls in forms next to the template's; config "tool_call_recovery": false turns it off
|
||||
# (a): a reply to a request with tools that ends in tool-call markup that is no call is written again once (default
|
||||
# on; STRATA_TOOL_MARKUP_RETRY=0 is the way back to sending it as text)
|
||||
self.tool_markup_retry = os.environ.get("STRATA_TOOL_MARKUP_RETRY", "1").strip().lower() not in ("0", "off", "false", "no")
|
||||
self.images = None # serve/images.py's ImageGen when the config has "images"
|
||||
self.restore_after_load = None # a session file an image job saved before it unloaded
|
||||
self.stop_ids = end_token_ids(tokenizer)
|
||||
@@ -5966,6 +5970,8 @@ class Service:
|
||||
("strata:drafts_accepted_total", "counter", "Speculative draft tokens accepted", t["drafts_accepted"]),
|
||||
("strata:tool_calls_unread_total", "counter", "<tool_call> blocks returned as text (an undeclared name or a form the template does not use)",
|
||||
t.get("tool_calls_unread", 0)),
|
||||
("strata:tool_markup_retries_total", "counter", "Replies that ended in tool-call markup that is no call and were written again once (STRATA_TOOL_MARKUP_RETRY)",
|
||||
t.get("tool_markup_retries", 0)),
|
||||
("strata:tool_args_repaired_total", "counter", "Tool call arguments (a JSON array or object) that were damaged and read as written",
|
||||
t.get("tool_args_repaired", 0)),
|
||||
("strata:model_loaded", "gauge", "1 while the model is loaded", int(self.loaded())),
|
||||
@@ -6425,8 +6431,21 @@ class Service:
|
||||
stop_list = stop_strings(sampling)
|
||||
stops = StopMatcher(stop_list) if stop_list else None
|
||||
|
||||
# the names the parser takes as declared: the request's tools and those its history called (#4663)
|
||||
declared = [t.get("name") for t in with_history_tools(tools, sampling) or []
|
||||
if isinstance(t, dict) and isinstance(t.get("name"), str)]
|
||||
# (a): armed for a request with tools, on the template's own call form (the Qwen form; a JSON-form parser or another
|
||||
# family keeps sending the text as it is)
|
||||
hold = ToolMarkupHold(bool(self.tool_markup_retry and declared and self.family is None
|
||||
and self.parser_cls is OutputParser))
|
||||
parser_done, markup_retried = False, None
|
||||
|
||||
def cut(evs):
|
||||
"""The events with the answer's text cut at a stop string (OpenAI stop, Anthropic stop_sequences)."""
|
||||
"""The events with the answer's text cut at a stop string (OpenAI stop, Anthropic stop_sequences), then
|
||||
through the tool-markup hold (a)."""
|
||||
return hold.push(_cut(evs))
|
||||
|
||||
def _cut(evs):
|
||||
if stops is None:
|
||||
return evs
|
||||
out = []
|
||||
@@ -6443,6 +6462,7 @@ class Service:
|
||||
out.append(Event("content", held))
|
||||
out.append(ev)
|
||||
return out
|
||||
forced_text = force # (a): the retry opens a forced call again (tool_choice)
|
||||
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
|
||||
@@ -6770,6 +6790,50 @@ class Service:
|
||||
# tokens, a tag held back) or the reasoning count is short: on from the live session
|
||||
prompt = prompt + seg
|
||||
continue
|
||||
if (hold.armed and not hold.calls and finish == "stop" and not (wrap or opens)
|
||||
and not cancel.is_set() and not repeated and not looped and parser.state != "reasoning"
|
||||
and (stops is None or (stops.hit is None and not stops.held))):
|
||||
# (a): the model stopped (a request with tools). Read the rest of its output here, as the
|
||||
# end would: a call that is whole there goes out as one; when the reply ends in tool-call
|
||||
# markup that is no call (held back, not sent), it is written again once
|
||||
for ev in cut(parser.finish("stop")):
|
||||
yield "event", ev
|
||||
parser_done = True
|
||||
dead = dead_markup_tail(hold.text) if hold.held and not hold.calls else None
|
||||
if dead is not None:
|
||||
names = [x for x in markup_names(hold.text) if x not in declared]
|
||||
kind = "rejected" if names else dead[1]
|
||||
near = closest_declared(names[0], declared) if names else None
|
||||
note = tool_retry_note(kind, names[:3], declared, near)
|
||||
extra = self.tok.encode(IM_END + "\n<|im_start|>user\n" + note + IM_END
|
||||
+ "\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
|
||||
+ (forced_text or ""), parse_special=True)
|
||||
if max_new - n - len(extra) >= TOOL_RETRY_MIN_ROOM:
|
||||
dropped = hold.drop()
|
||||
hold.armed = False # one retry: its own reply goes out as it is written
|
||||
markup_retried = {"reason": kind, "chars": len(dropped), "names": names[:3]}
|
||||
with self.status_lock:
|
||||
t = self.totals
|
||||
t["tool_markup_retries"] = t.get("tool_markup_retries", 0) + 1
|
||||
t["tool_calls_unread"] = t.get("tool_calls_unread", 0) + parser.unread
|
||||
print(f"[strata] the reply ended in tool-call markup that is no call ({kind}"
|
||||
+ (f": {', '.join(names[:3])}" if names else "") + (f", closest declared "
|
||||
f"{near}" if near else "") + f"; {len(dropped)} characters held back): writing "
|
||||
"the reply's end again once (STRATA_TOOL_MARKUP_RETRY=0 turns this off)",
|
||||
flush=True)
|
||||
max_new -= len(extra) # the note is prompt: the reply keeps inside the context
|
||||
prompt = prompt + seg + extra
|
||||
parser = self.parser_cls(thinking=False, tools=with_history_tools(tools, sampling),
|
||||
stream_tools=True, recover=self.tool_call_recovery,
|
||||
declared_only=declared_only,
|
||||
deferred=deferred or self.undeclared_tool_calls == "call")
|
||||
detok, tail, parser_done, force, budget = Detokenizer(self.tok), "", False, None, None
|
||||
if forced_text: # a forced call (tool_choice): its opening again, read as
|
||||
for ev in cut(parser.feed(forced_text)): # if the model had written it
|
||||
yield "event", ev
|
||||
finish = "length"
|
||||
continue
|
||||
break
|
||||
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
|
||||
@@ -6928,8 +6992,12 @@ class Service:
|
||||
self._terminal_event_locked(request_id, event, finish)
|
||||
if emb:
|
||||
Path(emb).unlink(missing_ok=True)
|
||||
for ev in cut(parser.finish(finish)):
|
||||
if not parser_done:
|
||||
for ev in cut(parser.finish(finish)):
|
||||
yield "event", ev
|
||||
for ev in hold.release(): # no retry (or its reply): the held text goes out as it is
|
||||
yield "event", ev
|
||||
hold.armed = False
|
||||
if parser.rescued or parser.refused:
|
||||
self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued
|
||||
print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as "
|
||||
@@ -6955,7 +7023,6 @@ class Service:
|
||||
# #5904 / #5933 / #4622: plus the declared tool the name comes closest to, as a hint for the client or the
|
||||
# model's next turn. Only a hint: the call is not run under that name (a guessed tool is a safety risk;
|
||||
# "undeclared_tool_calls": "call" stays the only way to run an undeclared call)
|
||||
declared = [t.get("name") for t in tools or [] if isinstance(t, dict) and isinstance(t.get("name"), str)]
|
||||
rejected = []
|
||||
for nm in named or []:
|
||||
entry = {"name": nm, "reason": "undeclared"}
|
||||
@@ -6964,7 +7031,9 @@ class Service:
|
||||
entry["closest_declared"] = near
|
||||
rejected.append(entry)
|
||||
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
|
||||
# the held tail was not a stop string after all
|
||||
for ev in hold.push([Event("content", stops.flush())]):
|
||||
yield "event", ev
|
||||
done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0),
|
||||
"timings": timings, "reasoning_tokens": thinking_n,
|
||||
"reasoning_recoveries": recovery_count}
|
||||
@@ -6972,6 +7041,17 @@ class Service:
|
||||
done["stop_sequence"] = stops.hit
|
||||
if rejected:
|
||||
done["rejected_tool_calls"] = rejected
|
||||
if markup_retried is not None:
|
||||
done["tool_markup_retry"] = markup_retried
|
||||
if declared:
|
||||
# strata_unread_tool_markup (GUI-C-1116 reads it): the reply the client got ends in tool-call markup that is
|
||||
# no call and is not one of strata_rejected_tool_calls' (a declared name's block that does not read, a cut one)
|
||||
text = hold.reply_text()
|
||||
tail_markup = dead_markup_tail(text)
|
||||
if tail_markup is not None:
|
||||
said = {e["name"] for e in rejected}
|
||||
if not said.intersection(markup_names(text[tail_markup[0]:])):
|
||||
done["unread_tool_markup"] = {"reason": tail_markup[1], "chars": len(text) - tail_markup[0]}
|
||||
yield "done", done
|
||||
|
||||
|
||||
@@ -6993,6 +7073,132 @@ def closest_declared(name: str, declared: list[str]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
TOOL_RETRY_MIN_ROOM = 64 # (a): the retry runs only with this many output tokens left after its note
|
||||
_MARKUP_OPENER = re.compile(r"<tool_call>|<function=")
|
||||
|
||||
|
||||
def _line_start(s: str, i: int) -> bool:
|
||||
head = s[:i].rstrip(" \t")
|
||||
return not head or head.endswith("\n")
|
||||
|
||||
|
||||
def dead_markup_tail(text: str) -> tuple[int, str] | None:
|
||||
"""The tool-call markup a reply's text ends in: (where the run of blocks at the end starts, "cut_off" | "unreadable"),
|
||||
or None when the text does not end in one. A block opens with `<tool_call>` (or a bare `<function=`) at a line
|
||||
start, outside a ``` fence; "cut_off": the last block has no closer (`</tool_call>`, or `</function>` for a bare one),
|
||||
"unreadable": it closed (the parser read it as no call). Text after a block's closer means the reply went on: None."""
|
||||
s = text.rstrip()
|
||||
start, reason, end = None, None, len(s)
|
||||
while True:
|
||||
part = s[:end]
|
||||
iw = max((m.start() for m in re.finditer(re.escape(CALL_START), part) if _line_start(part, m.start())), default=-1)
|
||||
ib = max((m.start() for m in re.finditer(re.escape(FUNC_START), part) if _line_start(part, m.start())), default=-1)
|
||||
bare = ib > iw and (iw < 0 or CALL_END in part[iw:ib])
|
||||
i = ib if bare else iw
|
||||
if i < 0:
|
||||
break
|
||||
body = part[i:]
|
||||
closer = FUNC_END if bare else CALL_END
|
||||
k = body.find(closer)
|
||||
if k >= 0 and body[k + len(closer):].strip():
|
||||
break # the block closed and text follows it: not the reply's end
|
||||
closed = k >= 0
|
||||
if reason is None:
|
||||
reason = "unreadable" if closed or body.endswith(FUNC_END) else "cut_off"
|
||||
elif not closed:
|
||||
break # an unclosed block before the last one: the run starts after it
|
||||
start, end = i, len(part[:i].rstrip())
|
||||
if start is None or s[:start].count("```") % 2:
|
||||
return None
|
||||
return start, reason
|
||||
|
||||
|
||||
def markup_names(text: str) -> list[str]:
|
||||
"""The names written in the `<function=NAME>` openers of a piece of text."""
|
||||
return [m.group(1).strip() for m in re.finditer(r"<function=([^<>\n]+?)>", text)]
|
||||
|
||||
|
||||
def tool_retry_note(reason: str, names: list[str], declared: list[str], near: str | None) -> str:
|
||||
"""(a): the user-turn note the one retry reads: why the call was not run, the declared tools, the hint."""
|
||||
what = {"rejected": "it names " + ", ".join(f"`{x}`" for x in names) + ", which is not one of the tools you can call",
|
||||
"cut_off": "it was cut off before its end",
|
||||
"unreadable": "it is not in a form that can be read"}[reason]
|
||||
listed = ", ".join(declared[:40]) + (f" and {len(declared) - 40} more" if len(declared) > 40 else "")
|
||||
hint = f" Did you mean `{near}`?" if near else ""
|
||||
return (f"[Strata server] Your last reply ended with a tool call that was not run: {what}.{hint} The tools you can "
|
||||
f"call are: {listed}. Write the call again in this form, with a tool from that list:\n"
|
||||
f"{CALL_START}\n{FUNC_START}TOOL_NAME>\n<parameter=PARAMETER_NAME>\nvalue\n</parameter>\n{FUNC_END}\n{CALL_END}\n"
|
||||
"or answer in plain text if no tool is needed.")
|
||||
|
||||
|
||||
class ToolMarkupHold:
|
||||
"""(a) The answer's text from a tool-call opener at a line start is held back until the reply goes on past the block
|
||||
(then it is sent as it is) or ends in it (then the server may write the reply's end again, once, in place of it).
|
||||
Unarmed it holds nothing; it always keeps the text it sent, for strata_unread_tool_markup."""
|
||||
|
||||
def __init__(self, armed: bool):
|
||||
self.armed = armed
|
||||
self.held: list[Event] = []
|
||||
self.text = ""
|
||||
self.closed = False # a closer (`</tool_call>` / `</function>`) is in the held text
|
||||
self.sent: list[str] = []
|
||||
self.prev = "" # the last characters sent (a line start at the reply's start)
|
||||
self.fences = 0 # ``` marks sent so far
|
||||
self.calls = False # a tool call came out: the reply does not end in dead markup
|
||||
|
||||
def _send(self, ev: Event) -> Event:
|
||||
if ev.text:
|
||||
self.sent.append(ev.text)
|
||||
self.prev = (self.prev + ev.text)[-16:]
|
||||
self.fences += ev.text.count("```")
|
||||
return ev
|
||||
|
||||
def _opener(self, text: str) -> int:
|
||||
for m in _MARKUP_OPENER.finditer(text):
|
||||
seen = self.prev + text[:m.start()]
|
||||
if _line_start(seen, len(seen)) and (self.fences + text[:m.start()].count("```")) % 2 == 0:
|
||||
return m.start()
|
||||
return -1
|
||||
|
||||
def push(self, evs: list) -> list:
|
||||
out = []
|
||||
for ev in evs:
|
||||
if ev.kind != "content":
|
||||
if ev.kind in ("tool_start", "tool_call"):
|
||||
self.calls = True
|
||||
out += self.release()
|
||||
out.append(ev)
|
||||
continue
|
||||
text = ev.text or ""
|
||||
if not self.held:
|
||||
p = self._opener(text) if self.armed and text else -1
|
||||
if p < 0:
|
||||
out.append(self._send(ev))
|
||||
continue
|
||||
if p:
|
||||
out.append(self._send(Event("content", text[:p])))
|
||||
ev, text = Event("content", text[p:]), text[p:]
|
||||
self.held.append(ev)
|
||||
self.text += text
|
||||
if not self.closed: # (until a closer arrives the block is open: held, no scan)
|
||||
near = self.text[-(len(text) + len(CALL_END)):]
|
||||
self.closed = CALL_END in near or FUNC_END in near
|
||||
if self.closed and text.strip() and dead_markup_tail(self.text) is None:
|
||||
out += self.release() # text after the block: the reply goes on
|
||||
return out
|
||||
|
||||
def release(self) -> list:
|
||||
evs, self.held, self.text, self.closed = self.held, [], "", False
|
||||
return [self._send(ev) for ev in evs]
|
||||
|
||||
def drop(self) -> str:
|
||||
text, self.held, self.text, self.closed = self.text, [], "", False
|
||||
return text
|
||||
|
||||
def reply_text(self) -> str:
|
||||
return "".join(self.sent)
|
||||
|
||||
|
||||
def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int:
|
||||
"""#471: the prompt tokens a request got through - all of them, unless the engine's DONE line says a cancel stopped
|
||||
its prompt read part-way (then the reused ones plus those read). /metrics' history and totals count these, so a
|
||||
@@ -7467,6 +7673,8 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel
|
||||
last["timings"] = x["timings"] # llama.cpp's field: the speed its clients show
|
||||
if x.get("rejected_tool_calls"):
|
||||
last["strata_rejected_tool_calls"] = x["rejected_tool_calls"] # #3796: only when a call was refused as undeclared
|
||||
if x.get("unread_tool_markup"):
|
||||
last["strata_unread_tool_markup"] = x["unread_tool_markup"]
|
||||
yield last
|
||||
if not answered_done and not cancel.is_set():
|
||||
# Every admitted request ends with a "done" event that carries its finish reason. A run that simply stopped (a 200 with one chunk and no
|
||||
@@ -7532,6 +7740,8 @@ def openai_collect(chunks) -> dict:
|
||||
out["timings"] = last["timings"]
|
||||
if last.get("strata_rejected_tool_calls"):
|
||||
out["strata_rejected_tool_calls"] = last["strata_rejected_tool_calls"]
|
||||
if last.get("strata_unread_tool_markup"):
|
||||
out["strata_unread_tool_markup"] = last["strata_unread_tool_markup"]
|
||||
return out
|
||||
|
||||
|
||||
@@ -7718,6 +7928,8 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can
|
||||
"cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}}
|
||||
if x.get("rejected_tool_calls"):
|
||||
delta_event["strata_rejected_tool_calls"] = x["rejected_tool_calls"] # #3796
|
||||
if x.get("unread_tool_markup"):
|
||||
delta_event["strata_unread_tool_markup"] = x["unread_tool_markup"]
|
||||
yield "message_delta", delta_event
|
||||
yield "message_stop", {"type": "message_stop"}
|
||||
|
||||
@@ -7752,6 +7964,8 @@ def anthropic_collect(events) -> dict:
|
||||
msg["usage"].update(e["usage"])
|
||||
if e.get("strata_rejected_tool_calls"):
|
||||
msg["strata_rejected_tool_calls"] = e["strata_rejected_tool_calls"]
|
||||
if e.get("strata_unread_tool_markup"):
|
||||
msg["strata_unread_tool_markup"] = e["strata_unread_tool_markup"]
|
||||
for i in range(len(blocks) - 1): # a turn with no </think>: the text is the answer; it is not also a thinking block
|
||||
a, b = blocks[i], blocks[i + 1]
|
||||
if a.get("type") == "thinking" and b.get("type") == "text" and a.get("thinking", "").strip() == b.get("text", "").strip():
|
||||
@@ -10807,6 +11021,10 @@ def _main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> i
|
||||
svc.anthropic_think_unasked = mode == "model"
|
||||
svc.tool_call_recovery = tool_call_recovery_setting(cfg)
|
||||
svc.undeclared_tool_calls = undeclared_tool_calls_setting(cfg)
|
||||
retry = cfg.get("tool_markup_retry", True) # (a): false (or STRATA_TOOL_MARKUP_RETRY=0) sends the markup as text
|
||||
if not isinstance(retry, bool):
|
||||
raise SystemExit(f"[strata] config \"tool_markup_retry\" must be true or false, not {retry!r}")
|
||||
svc.tool_markup_retry = svc.tool_markup_retry and retry
|
||||
etu = cfg.get("env_to_user", False) # opt-in: see frontend._env_to_user
|
||||
if not isinstance(etu, bool):
|
||||
raise SystemExit(f"[strata] config \"env_to_user\" must be true or false, not {etu!r}")
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
"""serve/test_tool_markup_retry.py - (a): a reply to a request with tools that ends in tool-call markup that is no call (a
|
||||
name the request did not declare, a call cut before its end, a block that reads as no call) is written again once, inside
|
||||
the same request; strata_unread_tool_markup marks a reply that still ends in such markup. The 43 forms are the shapes of a
|
||||
user's report of agent turns that stopped (499 turns, 63 sessions): its 30 undeclared names and 13 cut or unreadable blocks,
|
||||
rewritten with neutral text. Against a scripted engine (no GPU, no pack).
|
||||
|
||||
python -m unittest serve.test_tool_markup_retry -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from serve.frontend import ChatTemplate, OutputParser # noqa: E402
|
||||
from serve.server import (ByteTokenizer, MockEngine, Service, ToolMarkupHold, closest_declared, # noqa: E402
|
||||
dead_markup_tail, markup_names, serve)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DECLARED = ["pwsh", "read", "write", "edit", "glob", "grep", "background_jobs", "ask_user_question", "todo_write",
|
||||
"web_fetch", "web_search"]
|
||||
P = {"type": "object", "properties": {"command": {"type": "string"}, "description": {"type": "string"},
|
||||
"file_path": {"type": "string"}, "content": {"type": "string"}}}
|
||||
TOOLS = [{"name": n, "parameters": P} for n in DECLARED]
|
||||
|
||||
|
||||
def call(name, **params):
|
||||
body = "".join(f"<parameter={k}>\n{v}\n</parameter>\n" for k, v in params.items())
|
||||
return f"<tool_call>\n<function={name}>\n{body}</function>\n</tool_call>"
|
||||
|
||||
|
||||
# The report's 30 undeclared names (the name the model wrote, the declared one the hint should give, if any)
|
||||
REJECTED = [("delete", None), ("delete", None), ("delete", None), ("psh", "pwsh"), ("psh:", "pwsh"),
|
||||
("read_file", "read"), ("read_file", "read"), ("pash", "pwsh"), ("exec", None), ("exec", None),
|
||||
("exec", None), ("exec", None), ("exec", None), ("Bash", None), ("PowerShell", None), ("exec", None),
|
||||
("background_job", "background_jobs"), ("background_job", "background_jobs"), ("task", None),
|
||||
("task", None), ("powrsh_placeholder", None), ("write_file", "write"), ("write_file", "write"),
|
||||
("psn", None), ("psh", "pwsh"), ("pash", "pwsh"), ("ask_user_questions", "ask_user_question"),
|
||||
("gread", "read"), ("run", None), ("pwash", "pwsh")]
|
||||
# The report's cut and unreadable blocks, as shapes (the reason the server gives)
|
||||
CUT_OR_GARBAGE = [
|
||||
("Let me look at the folder first.\n<tool_call>", "cut_off"), # bare opener
|
||||
("<tool_call>\n<parameter name=\"command\">ls\n</parameter>\n<parameter=description>\nlist the", "cut_off"),
|
||||
("<tool_call>\n<function=pw", "cut_off"),
|
||||
("<tool_call>\n<=>\n</parameter>\n<parameter=command>\nls\n</parameter>\n</function>\n</tool_call>", "unreadable"),
|
||||
("I will run it now.\n<tool_call>\n<=true>\n</invoke>\n</function>\n</tool_call>", "unreadable"),
|
||||
("<tool_call>", "cut_off"),
|
||||
("<tool_call>\n<=>\n</function>\n</tool_call>", "unreadable"),
|
||||
("Next step.\n\n<tool_call>", "cut_off"),
|
||||
("<tool_call>\n", "cut_off"),
|
||||
("<tool_call>\n</function>\n</tool_call>", "unreadable"),
|
||||
("<tool_call>\n<=command>\n</function>\n</tool_call>", "unreadable"),
|
||||
("<tool_call>\n<function=", "cut_off"),
|
||||
]
|
||||
PROSE_ONLY = "I will read the file and then edit the line that sets the port." # the report's 13th: no markup at all
|
||||
|
||||
|
||||
def rejected_text(i, name):
|
||||
lead = "Checking the log.\n" if i % 4 == 1 else ""
|
||||
return lead + call(name, command="Get-ChildItem .\\logs", description="list the logs")
|
||||
|
||||
|
||||
def run_hold(raw, step=0):
|
||||
"""-> (events sent, the hold) after the parser and the hold read `raw` and the model stopped, as Service._run does."""
|
||||
p = OutputParser(thinking=False, tools=TOOLS, stream_tools=True, recover=True, declared_only=True)
|
||||
hold, out = ToolMarkupHold(True), []
|
||||
w = step or len(raw) or 1
|
||||
for i in range(0, len(raw), w):
|
||||
out += hold.push(p.feed(raw[i:i + w]))
|
||||
out += hold.push(p.finish("stop"))
|
||||
return out, hold
|
||||
|
||||
|
||||
class DeadMarkupTail(unittest.TestCase):
|
||||
def test_ends(self):
|
||||
for text, want in [("<tool_call>", "cut_off"), ("ok\n<tool_call>\n<function=x>\n", "cut_off"),
|
||||
("ok\n" + call("x", a=1), "unreadable"), ("ok\n<function=x>\n</function>", "unreadable"),
|
||||
("ok\n<function=x>\n<parameter=a>", "cut_off"),
|
||||
("<tool_call>\n</function>\n</tool_call>\n\n", "unreadable")]:
|
||||
with self.subTest(text=text):
|
||||
got = dead_markup_tail(text)
|
||||
self.assertIsNotNone(got)
|
||||
self.assertEqual(got[1], want)
|
||||
self.assertTrue(text[got[0]:].startswith(("<tool_call>", "<function=")))
|
||||
|
||||
def test_not_an_end(self):
|
||||
for text in ["plain answer", call("x", a=1) + "\n\nDone: the file is fixed.",
|
||||
"Write `<tool_call>` to call a tool.", "```\n<tool_call>\n<function=x>\n```",
|
||||
"```xml\n" + call("x", a=1), "see <function=x> in the doc"]:
|
||||
with self.subTest(text=text):
|
||||
self.assertIsNone(dead_markup_tail(text))
|
||||
|
||||
def test_a_run_of_blocks_starts_at_the_first(self):
|
||||
text = "Two tries.\n" + call("a", q=1) + "\n" + call("b", q=2) + "\n"
|
||||
start, reason = dead_markup_tail(text)
|
||||
self.assertEqual((text[start:start + 11], reason), ("<tool_call>", "unreadable"))
|
||||
self.assertEqual(text[:start], "Two tries.\n")
|
||||
|
||||
|
||||
class ReportShapes(unittest.TestCase):
|
||||
"""The parser and the hold over the report's 43 stops: 42 end in markup the server writes again; prose does not."""
|
||||
|
||||
def test_all_43(self):
|
||||
verdicts = []
|
||||
for step in (0, 1):
|
||||
seen = []
|
||||
for i, (name, near) in enumerate(REJECTED):
|
||||
raw = rejected_text(i, name)
|
||||
out, hold = run_hold(raw, step)
|
||||
dead = dead_markup_tail(hold.text) if hold.held and not hold.calls else None
|
||||
with self.subTest(case=i, step=step):
|
||||
self.assertIsNotNone(dead, raw)
|
||||
names = [x for x in markup_names(hold.text) if x not in DECLARED]
|
||||
self.assertEqual(names, [name.strip()])
|
||||
self.assertEqual(closest_declared(names[0], DECLARED), near)
|
||||
sent = "".join(e.text for e in out if e.kind == "content")
|
||||
self.assertEqual(sent, raw[:raw.index("<tool_call>")]) # the words before it went out
|
||||
seen.append("rejected")
|
||||
for raw, reason in CUT_OR_GARBAGE:
|
||||
out, hold = run_hold(raw, step)
|
||||
dead = dead_markup_tail(hold.text) if hold.held and not hold.calls else None
|
||||
with self.subTest(raw=raw, step=step):
|
||||
self.assertIsNotNone(dead)
|
||||
self.assertEqual(dead[1], reason)
|
||||
self.assertFalse(any(e.kind in ("tool_call", "tool_start") for e in out))
|
||||
seen.append(reason)
|
||||
out, hold = run_hold(PROSE_ONLY, step)
|
||||
self.assertFalse(hold.held)
|
||||
self.assertEqual("".join(e.text for e in out), PROSE_ONLY)
|
||||
verdicts.append(seen)
|
||||
self.assertEqual(verdicts[0], verdicts[1])
|
||||
self.assertEqual(len(verdicts[0]), 42)
|
||||
|
||||
def test_a_declared_call_is_never_held(self):
|
||||
raw = "Reading it.\n" + call("read", file_path="a.txt")
|
||||
out, hold = run_hold(raw, 1)
|
||||
self.assertTrue(hold.calls)
|
||||
self.assertEqual([e.call.name for e in out if e.kind == "tool_call"], ["read"])
|
||||
|
||||
def test_prose_after_the_block_releases_it(self):
|
||||
raw = call("exec", command="ls") + "\n\nThat tool does not exist here, so here is the answer: 4."
|
||||
out, hold = run_hold(raw, 1)
|
||||
self.assertFalse(hold.held)
|
||||
self.assertEqual("".join(e.text for e in out if e.kind == "content"), raw)
|
||||
|
||||
|
||||
class Scripted(MockEngine):
|
||||
"""Each generate() call (a pass, the retry included) gets the next text; the last one repeats."""
|
||||
|
||||
def __init__(self, tok, texts):
|
||||
super().__init__(tok, "x", max_context=32768)
|
||||
self.texts, self.prompts = list(texts), []
|
||||
|
||||
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
|
||||
self.prompts.append(list(ids))
|
||||
text = self.texts[min(len(self.prompts) - 1, len(self.texts) - 1)]
|
||||
yield from (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]
|
||||
|
||||
|
||||
OPENAI_TOOLS = [{"type": "function", "function": {"name": n, "parameters": P}} for n in DECLARED]
|
||||
|
||||
|
||||
class ServerRetry(unittest.TestCase):
|
||||
def start(self, texts, env=None):
|
||||
self.tok = ByteTokenizer()
|
||||
self.engine = Scripted(self.tok, texts)
|
||||
with mock.patch.dict(os.environ, env or {}):
|
||||
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]}"
|
||||
self.addCleanup(self.httpd.server_close)
|
||||
self.addCleanup(self.httpd.shutdown)
|
||||
|
||||
def post(self, path, body):
|
||||
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
raw = r.read().decode()
|
||||
return json.loads(raw) if not body.get("stream") else raw
|
||||
|
||||
def chat(self, tools=OPENAI_TOOLS, **extra):
|
||||
return self.post("/v1/chat/completions", {"model": "m", "max_tokens": 4000, "tools": tools,
|
||||
"messages": [{"role": "user", "content": "list the logs"}], **extra})
|
||||
|
||||
def metric(self, name):
|
||||
with urllib.request.urlopen(self.base + "/metrics/prometheus", timeout=30) as r:
|
||||
for line in r.read().decode().splitlines():
|
||||
if line.startswith(name + " "):
|
||||
return float(line.split()[1])
|
||||
return None
|
||||
|
||||
def test_an_undeclared_name_is_written_again_as_a_declared_call(self):
|
||||
good = call("pwsh", command="Get-ChildItem .\\logs")
|
||||
self.start(["</think>\n\nChecking.\n" + call("exec", command="Get-ChildItem .\\logs"), good])
|
||||
b = self.chat()
|
||||
msg = b["choices"][0]["message"]
|
||||
self.assertEqual(b["choices"][0]["finish_reason"], "tool_calls")
|
||||
self.assertEqual([c["function"]["name"] for c in msg["tool_calls"]], ["pwsh"])
|
||||
self.assertNotIn("exec", msg.get("content") or "")
|
||||
self.assertEqual((msg.get("content") or "").strip(), "Checking.")
|
||||
self.assertNotIn("strata_rejected_tool_calls", b)
|
||||
self.assertNotIn("strata_unread_tool_markup", b)
|
||||
self.assertEqual(len(self.engine.prompts), 2)
|
||||
retry = self.tok.decode(self.engine.prompts[1])
|
||||
note = retry[len(self.tok.decode(self.engine.prompts[0])):]
|
||||
self.assertIn("`exec`, which is not one of the tools you can call", note)
|
||||
for n in DECLARED:
|
||||
self.assertIn(n, note)
|
||||
self.assertTrue(note.endswith("<|im_start|>assistant\n<think>\n\n</think>\n\n"))
|
||||
self.assertEqual(self.metric("strata:tool_markup_retries_total"), 1)
|
||||
|
||||
def test_the_hint_names_the_closest_declared_tool(self):
|
||||
self.start(["</think>\n\n" + call("read_file", file_path="a.txt"), call("read", file_path="a.txt")])
|
||||
b = self.chat()
|
||||
self.assertEqual([c["function"]["name"] for c in b["choices"][0]["message"]["tool_calls"]], ["read"])
|
||||
self.assertIn("Did you mean `read`?", self.tok.decode(self.engine.prompts[1]))
|
||||
|
||||
def test_a_forced_call_is_opened_again(self):
|
||||
"""tool_choice "required": the retry's reply opens with the call's opening too, as the first one did."""
|
||||
self.start([call("exec", command="ls")[len("<tool_call>\n"):], call("pwsh", command="ls")[len("<tool_call>\n"):]])
|
||||
b = self.chat(tool_choice="required", chat_template_kwargs={"enable_thinking": False})
|
||||
self.assertEqual(b["choices"][0]["finish_reason"], "tool_calls")
|
||||
self.assertEqual([c["function"]["name"] for c in b["choices"][0]["message"]["tool_calls"]], ["pwsh"])
|
||||
self.assertTrue(self.tok.decode(self.engine.prompts[1]).endswith("</think>\n\n<tool_call>\n"))
|
||||
self.assertFalse((b["choices"][0]["message"].get("content") or "").strip())
|
||||
|
||||
def test_one_retry_only_then_the_text_and_the_markers(self):
|
||||
for first, again, field, want in [
|
||||
(call("exec", command="ls"), call("exec", command="ls"), "strata_rejected_tool_calls",
|
||||
[{"name": "exec", "reason": "undeclared"}]),
|
||||
("<tool_call>", "<tool_call>\n<=>\n</function>\n</tool_call>", "strata_unread_tool_markup",
|
||||
{"reason": "unreadable", "chars": len("<tool_call>\n<=>\n</function>\n</tool_call>")}),
|
||||
("<tool_call>\n</function>\n</tool_call>", "Sure.\n<tool_call>", "strata_unread_tool_markup",
|
||||
{"reason": "cut_off", "chars": len("<tool_call>")})]:
|
||||
with self.subTest(first=first):
|
||||
self.start(["</think>\n\n" + first, again])
|
||||
for stream in (False, True):
|
||||
self.engine.prompts.clear()
|
||||
b = self.chat(stream=stream)
|
||||
self.assertEqual(len(self.engine.prompts), 2, "one retry, never a second")
|
||||
if stream:
|
||||
chunks = [json.loads(x[6:]) for x in b.splitlines() if x.startswith("data: {")]
|
||||
text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c["choices"])
|
||||
got = [c[field] for c in chunks if field in c]
|
||||
self.assertEqual(len(got), 1)
|
||||
got = got[0]
|
||||
else:
|
||||
text = b["choices"][0]["message"]["content"]
|
||||
got = b.get(field)
|
||||
self.assertEqual(text.strip(), again.strip())
|
||||
self.assertEqual(got, want)
|
||||
if field == "strata_unread_tool_markup":
|
||||
self.assertEqual(text[len(text) - got["chars"]:].strip(), text[text.index("<tool_call>"):].strip())
|
||||
|
||||
def test_the_rollback_switch_sends_the_text_as_before(self):
|
||||
dead = "<tool_call>\n<=>\n</function>\n</tool_call>"
|
||||
self.start(["</think>\n\nOne moment.\n" + dead, call("pwsh", command="ls")],
|
||||
env={"STRATA_TOOL_MARKUP_RETRY": "0"})
|
||||
b = self.chat()
|
||||
self.assertEqual(len(self.engine.prompts), 1)
|
||||
self.assertEqual(b["choices"][0]["message"]["content"], "One moment.\n" + dead)
|
||||
self.assertEqual(b["strata_unread_tool_markup"], {"reason": "unreadable", "chars": len(dead)})
|
||||
self.assertEqual(self.metric("strata:tool_markup_retries_total"), 0)
|
||||
|
||||
def test_no_room_left_no_retry(self):
|
||||
"""The note is prompt: with too few output tokens left after it, the reply goes out as written."""
|
||||
dead = "<tool_call>\n<=>\n</function>\n</tool_call>"
|
||||
self.start(["</think>\n\n" + dead, call("pwsh", command="ls")])
|
||||
b = self.chat(max_tokens=400) # one token per byte here: the note alone is longer
|
||||
self.assertEqual(len(self.engine.prompts), 1)
|
||||
self.assertEqual(b["strata_unread_tool_markup"], {"reason": "unreadable", "chars": len(dead)})
|
||||
|
||||
def test_no_tools_no_retry_and_no_marker(self):
|
||||
self.start(["</think>\n\nHere: <tool_call>", call("pwsh", command="ls")])
|
||||
b = self.post("/v1/chat/completions", {"model": "m", "max_tokens": 300,
|
||||
"messages": [{"role": "user", "content": "hi"}]})
|
||||
self.assertEqual(len(self.engine.prompts), 1)
|
||||
self.assertNotIn("strata_unread_tool_markup", b)
|
||||
|
||||
def test_streamed_markup_never_reaches_the_client_when_the_retry_calls(self):
|
||||
self.start(["</think>\n\nChecking.\n" + call("Bash", command="ls"), call("pwsh", command="ls")])
|
||||
raw = self.chat(stream=True)
|
||||
self.assertNotIn("Bash", raw)
|
||||
self.assertIn('"pwsh"', raw)
|
||||
|
||||
def test_messages_and_responses_carry_the_marker(self):
|
||||
dead = "<tool_call>\n<=>\n</function>\n</tool_call>"
|
||||
want = {"reason": "unreadable", "chars": len(dead)}
|
||||
self.start(["</think>\n\n" + dead])
|
||||
a = self.post("/v1/messages", {"model": "m", "max_tokens": 4000, "messages": [{"role": "user", "content": "x"}],
|
||||
"tools": [{"name": n, "input_schema": P} for n in DECLARED]})
|
||||
self.assertEqual(a.get("strata_unread_tool_markup"), want)
|
||||
s = self.post("/v1/messages", {"model": "m", "max_tokens": 4000, "stream": True,
|
||||
"messages": [{"role": "user", "content": "x"}],
|
||||
"tools": [{"name": n, "input_schema": P} for n in DECLARED]})
|
||||
deltas = [json.loads(x[6:]) for x in s.splitlines() if x.startswith("data: {") and "message_delta" in x]
|
||||
self.assertEqual(deltas[-1].get("strata_unread_tool_markup"), want)
|
||||
r = self.post("/v1/responses", {"model": "m", "max_output_tokens": 4000, "input": "x",
|
||||
"tools": [{"type": "function", "name": n, "parameters": P} for n in DECLARED]})
|
||||
self.assertEqual(r.get("strata_unread_tool_markup"), want)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user