mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #4222] [Engine] Chat takes tools and a JSON format while the masks are live: the grammar answers with the call, the schema binds the answer #4959
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#4959
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/Niko1221/Strata/pull/4222
Author: @ncphri
Created: 10/26/2026
Status: 🔄 Open
Base:
main← Head:f-tool-call-serve📝 Commits (10+)
6cb9538serve + engine: constrained decoding for JSON response formats: a token mask per window (mask=1, MQ/MF/MK) on the chat routed851324Merge branch 'main' into f-json-mask52922efserve + engine: MTP drafts under the token mask: multi-row MKN windows, MQ/MF/MK round-trip, consume-based lookahead on the server (no validate_tokens); mask stats behind STRATA_MASK_STATS=1a79dd4dMerge remote-tracking branch 'origin/main' into json_mtp8fc68d7Merge branch 'main' into f-json-maskeb4e23cMerge remote-tracking branch 'origin/main' into f-json-maskc4c8323Merge origin/main (0.1.48.x) into f-json-mask: keep both sides — token_mask INFO beside the new prefill keys, mask=1 key parser beside pipe=, mk_take inside the !merged draft gate, sycl mask-cut before the follow-logprobs dump, include union, PY_PACKAGES keeps llguidance3766738Merge remote-tracking branch 'origin/main' into f-json-mask-merged8979f87Merge origin/main (0.2.3) into f-json-mask: keep-both on the draft-window head - the mask-exchange comments ride above main's spec_cost chain_rows clamp5ff40a5serve: bare tool calls are grammar-constrained under STRATA_TOOL_MASK=1 (opt-in)📊 Changes
17 files changed (+2209 additions, -20 deletions)
View changed files
📝
docs/DETAILS.md(+34 -2)➕
include/strata/core/token_mask.hpp(+162 -0)📝
include/strata/core/verify.hpp(+18 -0)📝
requirements.txt(+1 -0)➕
serve/constrain.py(+550 -0)➕
serve/fake_mask_engine.py(+89 -0)📝
serve/responses.py(+23 -2)📝
serve/server.py(+108 -4)📝
serve/structured.py(+8 -0)➕
serve/test_constrain.py(+951 -0)📝
serve/test_structured.py(+44 -0)📝
setup.py(+2 -1)📝
src/core/verify.cpp(+64 -0)📝
src/program/generate.cpp(+91 -6)📝
sycl/include/strata/core/verify.hpp(+11 -0)📝
sycl/src/core/verify.cpp(+24 -0)📝
sycl/src/program/generate.cpp(+29 -5)📄 Description
Problem and result
A request that sends
toolstogether with a JSONresponse_formaton/v1/chat/completionswas refusedwith 400 (the prompt directive cannot tell a call turn from an answer turn), so clients that always send
tools — every agentic CLI does — fell back to prompt-only instruction and post-turn validation, and the
schema held only as well as the model's own compliance: the missing-required-key failures that come back
to a client that re-validates. When the engine takes token masks and
llguidanceis installed, the grammarnow has two branches (
answer: json | calls), so the same request answers with the tool call (read by theparser as it always did, unchecked against the schema) or with the final answer masked to the schema and
validated after the turn.
On top of that answer|calls grammar, this PR adds three serve-side pieces, all opt-in:
by a capability gate: without the mask the old 400 stays).
STRATA_TOOL_NAME_ENUM=1: the call's name sits behind a literalsingle-choice regex of the request's declared tool names, so a hallucinated tool name is stopped at
decode time, not at validation. llguidance 1.9.1 rejects look-around in a regex literal (grammar-build
error, measured), so the rule is a longest-first alternation with a mandatory
[\s<]delimiter afterthe name — a prefix pair like exec/exec_command stays on the longer branch after
exec, pinning thelongest name.
A byte-vocabulary release fix measured in this branch: the free-REST release (
_all_free()) cannever fire on a byte vocabulary — REST compiles to the valid-UTF-8 character set and 82/263 invalid
single-byte tokens stay masked forever (probe-measured) — so the release now fires at the separator
after the name, one token later than the tag-only release, with the body free from there.
STRATA_TOOL_MASK=1: with no JSON format but tools offered, the choice is thecall or prose (
answer: calls | PROSE,PROSE: /[^<][\s\S]*/): prose cannot START with<, so a<tool_call>tag — special token or plain text — can only arrive through the calls branch, where thename sits behind the enumeration and the separator frees the turn for the body; a
<later in theprose stays free. One wiring point covers all three APIs (they share one generation loop):
/v1/chat/completions,/v1/responses(withouttext.format) and/v1/messages(Anthropic carriesno format equivalent, so bare calls are the only calls its grammar can see).
Everything is opt-in and off by default; without the engine's
token_maskINFO key or thellguidancepackage every request behaves exactly as before (prompt directive + validation after the turn). A forced
tool_choicenever arms the mask.Related discussion
Stacked on #3800 (the engine half: the per-window token mask, MQ/MF/MK handshake, MTP drafts surviving
the mask), whose head this branch is based on — this PR adds no engine lines of its own. Since
2026-10-28 the branch also merges
origin/main(0.2.7.x, merge headd4bf1fac), so the diff of thisbranch against #3800's head now carries upstream's engine lines as well; the meaningful split is
against the FILED base — measured at
d4bf1fac, the engine lines in the filed diff (basemain) areexactly #3800's mask machinery (8 files, +407/−12) plus the serve files
mainlacks because #3800carries them (
constrain.py,fake_mask_engine.py); nothing else insrc/include/syclmoves.Scope was agreed in the #3800 thread; no separate issue was opened.
Note on filing: a fork PR cannot target the fork's branch, so this PR's base is
mainand the shownfile list carries #3800's engine files as well until that PR merges. This PR's own change on top of
#3800's head is serve/doc-only —
5ff40a54(bare tool calls under the mask),80f76218(the toolgrammar chain) and the two merge resolutions; the engine build that the filed diff shows is #3800's
half.
Approach
serve/constrain.py: theanswer | callstwo-branch grammar; the name-enum rule (longest-firstalternation + mandatory delimiter, no look-around); the PROSE branch for the bare-call grammar; the
separator-release in
Constraint.feed()(thename_lencounter; the_all_free()fallback path iskept for non-byte vocabularies); the bare-call grammar as an explicit
{"type": "bare"}request formatsentinel so a plain
format_of() == Nonecan never arm it by accident.80f76218):response_format: {"type": "lark", "grammar": ...}passes a Larkgrammar through untouched — llguidance reads Lark natively, so the string is the whole constraint; a
grammar that cannot build drops to free decoding under HTTP 200 (never a 500), and a lark without a
non-empty grammar string is not a format (400). Custom tool grammars bind the call envelope via
vocab.literal(the special tokens come from the frontend constants, never text literals) so bothpack shapes consume, with the body binding gated on the call opener being ONE token
(
vocab.single(TOOL_CALL)), the name-enum/REST fallback behind that gate;responses.pywires thesame custom grammar into the Responses API. llguidance stays optional (nothing vendored).
serve/server.py: the chat route's 400 replaced by themask_available()gate;_with_constraintgains the
forcecapture (a forced call appends the opening tag to the prompt, so the grammar muststay unarmed), the name-enum flag, and the bare-call wiring;
tools_with_jsonadvertised on/v1/status; the forced-call keep-unarmed flag on the generation loop; the MockEngine records thesampling's constraint key for tests.
serve/test_constrain.py: the new fixtures live here (not test_server.py) and reuse theHttpbase,MockEngine+supports_mask = True, the sharedTOOLS/CALL/FMTconstants and the@needllguidance guard.
docs/DETAILS.md: the structured-output section names the two-branch grammar, the enumeration flagand the three bare-call routes.
main 0.2.7.x (measured: the filed diff's engine lines are #3800's 8 files, +407/−12).
setup.py/requirements.txtcarry llguidance for #3800's half; this PR adds no dependency.Validation
Passed (all on the same revision, commit
5ff40a54, unless named):python -m unittest serve.test_constrain serve.test_structured serve.test_responses serve.test_server— 437 tests OK (~136 s, miniforge python 3.12, llguidance 1.9.1, WSL Ubuntu, no GPU), zero skips, env
unset. Also 44-test subset OK after every intermediate edit.
The opt-in paths are covered with the flag ON, not only the default: 28 constrain tests with the enum
fixtures (TagTokenizer Vocab), 6
ChatBareToolMasktests withSTRATA_TOOL_MASK=1(default off /prose turn / bare call / enum+separator release / responses bare / anthropic bare).
Hardware run — a separate machine, engine build at merge f2aff0d6 of this PR's branch with
origin/main (engine 0.1.51, same serve code), Windows, RTX 4090-class, swift-1.5-iq3_s,
STRATA_TOOL_MASK=1:turn / forced tool_choice / responses bare call / responses tools+text.format / chat schema
round-trip (client-side jsonschema validation) / chat tools+schema / anthropic tool_use;
nested-required-arrays / enum+range / Japanese prompt / no-markdown-fence trap / 15-word enum
stress / json_object / tools+schema strict. Serve log carries the
"constrained decoding on" line (the mask was armed for every probe).
/v1/status:constrained_decoding: true,tools_with_json: true, engine 0.1.51.Re-validated after the main-0.2.6 merge (head
8822e7df, the merge that brings main'sset_family/force_textand the new DETAILS structure): the same 4-test suite, 437 tests OK(~135 s, same environment), and the diff against #3800's head is still serve/doc-only (four files,
zero engine lines).
Hardware re-run at the merged head
8822e7df(same machine, CUDA 13, engine 0.1.51,STRATA_TOOL_MASK=1): the same 15 probes again 15/15 first-pass (8 route + 7 schema-shape);/v1/status=constrained_decoding: true,tools_with_json: true; the serve log carries theconstrained decoding online and the error log shows zero 502/structured_output_failed.(One probe-harness bug — the json_object case passing a
Noneschema to the validator — was fixedin the harness itself; the server had answered 200 with valid JSON from the first attempt.)
Re-validated after the main-0.2.7.x merge (head
d4bf1fac, 2026-10-28:server.pytakes main'sprefill_onlyhead rewrite beside the mask block and the LP-line capture besidec.feed(t);generate.cpptakes main's window-T refactor at the mask-comment hunks, so the engine lines inthe filed diff stay #3800's half —
git diff origin/main <head> -- src include sycl= 8 files,+407/−12): the same suite plus
serve.test_mcp, 496 tests OK (~158 s, same environment).Hardware re-run at the same head (same machine, CUDA 13, engine 0.1.53,
STRATA_TOOL_MASK=1):the same 15 probes again 15/15 first-pass (8 route + 7 schema-shape);
/v1/status=constrained_decoding: true,tools_with_json: true; the serve log carries theconstrained decoding online and the error log shows zero 502/structured_output_failed.Re-validated after the main-0.2.10 merge (head
ed7f0d1e, 2026-11-04:server.pykeeps the mask gatebeside main's
rid/pen_frommachinery — themask=1append rides after main's rid head;verify.cpptakes main'sSTRATA_VERIFY_HGLguard beside the token_mask include;generate.cpptakes main's DFlash2/window-rule restructure with the MQ exchange beside main's
keep_sync, beforewindow adoption; SYCL's bare-MQ block keeps the window rule's result one row under the mask) — the
engine lines in the filed diff stay #3800's half (
git diff origin/main <head> -- src include sycl= 7 files, +399/−11): the same suite, 498 tests OK (~159 s, same environment).
Hardware re-run at the same head (same machine, CUDA 13, engine 0.1.56,
STRATA_TOOL_MASK=1):the same 15 probes again 15/15 first-pass (8 route + 7 schema-shape);
/v1/status=constrained_decoding: true,tools_with_json: true; the serve log carries theconstrained decoding online and the error log shows zero 502/structured_output_failed.Failed: none observed.
Not run:
the filed diff (base
main) also carries.filed diff belong to #3800, which built
sycl/tools/build.shclean at its merge8979f87f(oneAPI2026.1, 232/232 steps, compilation only); since the branch also merges main (latest 0.2.10,
ed7f0d1e), aSYCL rebuild of the current head would no longer be binary-identical to #3800's build — the wider
engine state is what the CUDA hardware run above covers (170/170 steps, 0 errors, same head).
Limits
STRATA_TOOL_MASK=1keeps the mask live for the whole turn: on a byte vocabularythe invalid single-byte tokens (82/263 measured on the 263-token mock vocabulary) stay masked until the
EOS. Real Qwen vocabularies are byte-level too, so the cost is real; the MTP draft-acceptance
interaction in prose turns is not measured yet (the JSON branch is where #3800 measured 82% accepted).
<degrades to free decoding at that token (the existing give-the-mask-uppath; the turn is validated after, never a 502).
tag-only release; the body after the name stays free REST (the parser reads it).
STRATA_TOOL_NAME_ENUM=1with a name outside[A-Za-z0-9_-]+masks that name OUT of the grammar(the enumeration is a strict filter); such a request should not turn the flag on.
/v1/messagesthinking turns are unarmed until</think>, as with every other route.🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.