v0.2 step 8 — constrained decoding, structured output, function calling (#38-#41)
Constrained decoding on mlx-swift-lm's XGrammar bridge, as a logit processor inside the normal generation path: temperature, the thinking budget, tool-call parsing and streaming keep working, and reasoning models think freely before the constrained answer. A whitespace-run bias stops small models looping inside JSON. response_format json_object / json_schema (strict schemas using keywords the decoder cannot enforce are refused with a 400 naming them). tools, tool_choice (none, auto, required, named) and parallel_tool_calls; required, named and strict tools are enforced with XGrammar structural tags for the <tool_call> JSON syntax (Qwen, Hermes). JSON answers now stream piece by piece: sessions without tools no longer use the tool parser's bare-JSON fallback, which held them back. Spike report in ticket #38. Tests: Linux 136, Mac 156 (constrained generation with a real Qwen3 model). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
53d6eb7 parent: 1f0e95f modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +12 -8 | @@ -1,4 +1,4 @@ | ||
| 1 | -# Handoff — 2026-11-25 — v0.2: server, config, models, chat, streaming, reasoning (#32–#37) | |
| 1 | +# Handoff — 2026-11-25 — v0.2: server … tools (#32–#41), embeddings (#42) | |
| 2 | 2 | |
| 3 | 3 | ## State |
| 4 | 4 | Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78). |
| @@ -9,19 +9,17 @@ Update after #37: reasoning_content + switches done (Linux 120, Mac 131). Its de | ||
| 9 | 9 | made by Claude on a plain "go": mention them to the user if reasoning comes up. The user then asked |
| 10 | 10 | for a way to hide it (`show_reasoning` / `include_reasoning`, done) and for it to stream (it did; |
| 11 | 11 | now verified on the Mac). |
| 12 | +Update after #41: constrained decoding, response_format, tools done (Linux 136, Mac 156). | |
| 12 | 13 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 13 | 14 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 14 | 15 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 15 | 16 | closed. Nothing pushed. |
| 16 | 17 | |
| 17 | 18 | ## Next steps |
| 18 | -1. #38 spike: constrained decoding with MLXGuidedGeneration (XGrammar) in the resolved | |
| 19 | - mlx-swift-lm 3.32.3 — Mac only; read the API from the SwiftPM checkout, not `main`. It gates | |
| 20 | - #39 (response_format) and #41 (forced tool choice). | |
| 21 | -2. Then #40 tools, #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs | |
| 22 | - (EN+FR; the agent docs are still in docs/). | |
| 23 | -3. User check on the Mac: `rzb serve` + a real model over HTTP (`curl -N`, reasoning_effort). | |
| 24 | -4. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. | |
| 19 | +1. #42 embeddings (in progress in this session), then give the user the testing checklist they | |
| 20 | + asked for (end of the #38–#42 request). | |
| 21 | +2. Then #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; agent docs still in docs/). | |
| 22 | +3. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. | |
| 25 | 23 | |
| 26 | 24 | ## Watch out for |
| 27 | 25 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -53,6 +51,12 @@ closed. Nothing pushed. | ||
| 53 | 51 | use a file-level constant. |
| 54 | 52 | - Ticket comments: build the author block from the ticket file's own `author:` (the privacy hook |
| 55 | 53 | refuses commands that contain the account e-mail). |
| 54 | +- XGrammar in mlx-swift-lm 3.32.3 is v0.1.30: `GrammarConstraint.clone()` throws (no Fork), and | |
| 55 | + JSON whitespace is unconstrained (`any_whitespace=true` hard-coded in the C shim). | |
| 56 | +- mlx-swift-lm's token iterator samples one token ahead: a LogitProcessor sees a token after the | |
| 57 | + end token; `GrammarProcessor` stops committing once the grammar has terminated. | |
| 58 | +- Debugging a constrained generation: print the raw `EngineEvent`s of a session — when the tool | |
| 59 | + parser swallows a truncated call, the API shows only an empty answer with finish_reason length. | |
| 56 | 60 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 57 | 61 | the requested name. |
| 58 | 62 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
| @@ -1,4 +1,4 @@ | |||
| 1 | -# Handoff — 2026-11-25 — v0.2: server, config, models, chat, streaming, reasoning (#32–#37) | 1 | +# Handoff — 2026-11-25 — v0.2: server … tools (#32–#41), embeddings (#42) |
| 2 | 2 | ||
| 3 | ## State | 3 | ## State |
| 4 | Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78). | 4 | Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78). |
| @@ -9,19 +9,17 @@ Update after #37: reasoning_content + switches done (Linux 120, Mac 131). Its de | |||
| 9 | made by Claude on a plain "go": mention them to the user if reasoning comes up. The user then asked | 9 | made by Claude on a plain "go": mention them to the user if reasoning comes up. The user then asked |
| 10 | for a way to hide it (`show_reasoning` / `include_reasoning`, done) and for it to stream (it did; | 10 | for a way to hide it (`show_reasoning` / `include_reasoning`, done) and for it to stream (it did; |
| 11 | now verified on the Mac). | 11 | now verified on the Mac). |
| 12 | +Update after #41: constrained decoding, response_format, tools done (Linux 136, Mac 156). | ||
| 12 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP | 13 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 13 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket | 14 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 14 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task | 15 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 15 | closed. Nothing pushed. | 16 | closed. Nothing pushed. |
| 16 | 17 | ||
| 17 | ## Next steps | 18 | ## Next steps |
| 18 | -1. #38 spike: constrained decoding with MLXGuidedGeneration (XGrammar) in the resolved | 19 | +1. #42 embeddings (in progress in this session), then give the user the testing checklist they |
| 19 | - mlx-swift-lm 3.32.3 — Mac only; read the API from the SwiftPM checkout, not `main`. It gates | 20 | + asked for (end of the #38–#42 request). |
| 20 | - #39 (response_format) and #41 (forced tool choice). | 21 | +2. Then #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; agent docs still in docs/). |
| 21 | -2. Then #40 tools, #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs | 22 | +3. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. |
| 22 | - (EN+FR; the agent docs are still in docs/). | ||
| 23 | -3. User check on the Mac: `rzb serve` + a real model over HTTP (`curl -N`, reasoning_effort). | ||
| 24 | -4. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. | ||
| 25 | 23 | ||
| 26 | ## Watch out for | 24 | ## Watch out for |
| 27 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns | 25 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -53,6 +51,12 @@ closed. Nothing pushed. | |||
| 53 | use a file-level constant. | 51 | use a file-level constant. |
| 54 | - Ticket comments: build the author block from the ticket file's own `author:` (the privacy hook | 52 | - Ticket comments: build the author block from the ticket file's own `author:` (the privacy hook |
| 55 | refuses commands that contain the account e-mail). | 53 | refuses commands that contain the account e-mail). |
| 54 | +- XGrammar in mlx-swift-lm 3.32.3 is v0.1.30: `GrammarConstraint.clone()` throws (no Fork), and | ||
| 55 | + JSON whitespace is unconstrained (`any_whitespace=true` hard-coded in the C shim). | ||
| 56 | +- mlx-swift-lm's token iterator samples one token ahead: a LogitProcessor sees a token after the | ||
| 57 | + end token; `GrammarProcessor` stops committing once the grammar has terminated. | ||
| 58 | +- Debugging a constrained generation: print the raw `EngineEvent`s of a session — when the tool | ||
| 59 | + parser swallows a truncated call, the API shows only an empty answer with finish_reason length. | ||
| 56 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by | 60 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 57 | the requested name. | 61 | the requested name. |
| 58 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. | 62 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
modified
.memory/history.md +9 -0 | @@ -189,3 +189,12 @@ | ||
| 189 | 189 | on), shared by plain and streamed answers through `ChatCompletionRoute.generate`. Streaming of |
| 190 | 190 | reasoning already existed; now verified with real Qwen3 on the Mac. Linux 123, Mac 135, gate PASS |
| 191 | 191 | (run #13). Comment #2 on #37. |
| 192 | +- User asked for #38 through #42 in one go, plus a list of what they should test. #38–#41 done: | |
| 193 | + spike report in #38 (LogitProcessor integration instead of GuidedGenerationLoop; no matcher fork | |
| 194 | + in vendored XGrammar v0.1.30 → per-request compile; unenforced-keyword list read from XGrammar's | |
| 195 | + source; whitespace loops of Qwen3-0.6B in forced calls fixed with mlx-swift-lm's whitespace bias; | |
| 196 | + GPU bitmask expansion; Debug numbers ~90 vs ~49 tok/s). #39 response_format; #40 tools / | |
| 197 | + tool_choice / parallel_tool_calls; #41 structural tags (`<tool_call>` JSON syntax only — others | |
| 198 | + 400, rejected the ticket's retry-then-500 fallback). Found and fixed: JSON answers streamed in one | |
| 199 | + piece because mlx-swift-lm's `.json` parser holds back a leading brace (switch to `.gptOSS` parser | |
| 200 | + when no tools). Linux 136, Mac 156 (8 constrained smoke tests with real Qwen3), gate PASS (run #15). | |
| @@ -189,3 +189,12 @@ | |||
| 189 | on), shared by plain and streamed answers through `ChatCompletionRoute.generate`. Streaming of | 189 | on), shared by plain and streamed answers through `ChatCompletionRoute.generate`. Streaming of |
| 190 | reasoning already existed; now verified with real Qwen3 on the Mac. Linux 123, Mac 135, gate PASS | 190 | reasoning already existed; now verified with real Qwen3 on the Mac. Linux 123, Mac 135, gate PASS |
| 191 | (run #13). Comment #2 on #37. | 191 | (run #13). Comment #2 on #37. |
| 192 | +- User asked for #38 through #42 in one go, plus a list of what they should test. #38–#41 done: | ||
| 193 | + spike report in #38 (LogitProcessor integration instead of GuidedGenerationLoop; no matcher fork | ||
| 194 | + in vendored XGrammar v0.1.30 → per-request compile; unenforced-keyword list read from XGrammar's | ||
| 195 | + source; whitespace loops of Qwen3-0.6B in forced calls fixed with mlx-swift-lm's whitespace bias; | ||
| 196 | + GPU bitmask expansion; Debug numbers ~90 vs ~49 tok/s). #39 response_format; #40 tools / | ||
| 197 | + tool_choice / parallel_tool_calls; #41 structural tags (`<tool_call>` JSON syntax only — others | ||
| 198 | + 400, rejected the ticket's retry-then-500 fallback). Found and fixed: JSON answers streamed in one | ||
| 199 | + piece because mlx-swift-lm's `.json` parser holds back a leading brace (switch to `.gptOSS` parser | ||
| 200 | + when no tools). Linux 136, Mac 156 (8 constrained smoke tests with real Qwen3), gate PASS (run #15). | ||
modified
.memory/summary.md +11 -4 | @@ -7,8 +7,8 @@ | ||
| 7 | 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in |
| 8 | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, |
| 10 | -model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37 (see | |
| 11 | -Architecture). Decided by the user (#31): the | |
| 10 | +model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37, constrained | |
| 11 | +decoding #38, structured output #39, function calling #40/#41 (see Architecture). Decided by the user (#31): the | |
| 12 | 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 13 | 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| 14 | 14 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by |
| @@ -62,7 +62,14 @@ comment every 5 s. Reasoning (#37): `reasoning_content` on message and deltas; p | ||
| 62 | 62 | budget only via the `thinking_budget` extension field; hidden with `show_reasoning: false` |
| 63 | 63 | (config `defaults`/`locked`) or `include_reasoning: false` (request) — the model still thinks and |
| 64 | 64 | `reasoning_tokens` still counts; engine errors caused by a request setting |
| 65 | -adopt `RequestSettingError` (Core) → 400. Next: #38 constrained-decoding spike. | |
| 65 | +adopt `RequestSettingError` (Core) → 400. Constrained decoding (#38–#41): `SessionSetup.constraint` | |
| 66 | +(`OutputConstraint`: `.jsonSchema` or `.toolCalls`), enforced in `RazorbillMLX/GrammarSupport.swift` | |
| 67 | +by a `GrammarProcessor` (LogitProcessor on mlx-swift-lm's XGrammar bridge, inactive until | |
| 68 | +`</think>`, whitespace-run bias, grammar compiled per request because XGrammar v0.1.30 cannot fork); | |
| 69 | +`response_format` → `.jsonSchema` (strict + unenforced keyword → 400); tools/tool_choice in | |
| 70 | +`Chat/ToolsAndFormats.swift`; forced tool calls via structural tags for the `<tool_call>` JSON syntax | |
| 71 | +only (others → 400); forced calls are single unless `parallel_tool_calls: true`. Sessions without | |
| 72 | +tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). Next: embeddings (#42). | |
| 66 | 73 | |
| 67 | 74 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 68 | 75 | |
| @@ -153,7 +160,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | ||
| 153 | 160 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 154 | 161 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 155 | 162 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 156 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #37): Linux 123, Mac 135 (incl. `ChatSmokeTests`: real | |
| 163 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #41): Linux 136, Mac 156 (incl. `ConstrainedSmokeTests`, `ChatSmokeTests`: real | |
| 157 | 164 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 158 | 165 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 159 | 166 | |
| @@ -7,8 +7,8 @@ | |||
| 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in | 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in |
| 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, | 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, |
| 10 | -model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37 (see | 10 | +model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37, constrained |
| 11 | -Architecture). Decided by the user (#31): the | 11 | +decoding #38, structured output #39, function calling #40/#41 (see Architecture). Decided by the user (#31): the |
| 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, | 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` | 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| 14 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by | 14 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by |
| @@ -62,7 +62,14 @@ comment every 5 s. Reasoning (#37): `reasoning_content` on message and deltas; p | |||
| 62 | budget only via the `thinking_budget` extension field; hidden with `show_reasoning: false` | 62 | budget only via the `thinking_budget` extension field; hidden with `show_reasoning: false` |
| 63 | (config `defaults`/`locked`) or `include_reasoning: false` (request) — the model still thinks and | 63 | (config `defaults`/`locked`) or `include_reasoning: false` (request) — the model still thinks and |
| 64 | `reasoning_tokens` still counts; engine errors caused by a request setting | 64 | `reasoning_tokens` still counts; engine errors caused by a request setting |
| 65 | -adopt `RequestSettingError` (Core) → 400. Next: #38 constrained-decoding spike. | 65 | +adopt `RequestSettingError` (Core) → 400. Constrained decoding (#38–#41): `SessionSetup.constraint` |
| 66 | +(`OutputConstraint`: `.jsonSchema` or `.toolCalls`), enforced in `RazorbillMLX/GrammarSupport.swift` | ||
| 67 | +by a `GrammarProcessor` (LogitProcessor on mlx-swift-lm's XGrammar bridge, inactive until | ||
| 68 | +`</think>`, whitespace-run bias, grammar compiled per request because XGrammar v0.1.30 cannot fork); | ||
| 69 | +`response_format` → `.jsonSchema` (strict + unenforced keyword → 400); tools/tool_choice in | ||
| 70 | +`Chat/ToolsAndFormats.swift`; forced tool calls via structural tags for the `<tool_call>` JSON syntax | ||
| 71 | +only (others → 400); forced calls are single unless `parallel_tool_calls: true`. Sessions without | ||
| 72 | +tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). Next: embeddings (#42). | ||
| 66 | 73 | ||
| 67 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 74 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 68 | 75 | ||
| @@ -153,7 +160,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | |||
| 153 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). | 160 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 154 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped | 161 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 155 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). | 162 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 156 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #37): Linux 123, Mac 135 (incl. `ChatSmokeTests`: real | 163 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #41): Linux 136, Mac 156 (incl. `ConstrainedSmokeTests`, `ChatSmokeTests`: real |
| 157 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). | 164 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 158 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). | 165 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 159 | 166 | ||
modified
.quality/history.jsonl +2 -0 | @@ -11,3 +11,5 @@ | ||
| 11 | 11 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "6a3f52a", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 169, "complex": 325, "cyclo": 390, "fields": 725, "funcs": 372, "lcom": 75, "lines": 6771, "loc": 5299}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 11, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:38:59Z"} |
| 12 | 12 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "d8981f3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 329, "cyclo": 395, "fields": 758, "funcs": 384, "lcom": 76, "lines": 6999, "loc": 5488}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 12, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:48:22Z"} |
| 13 | 13 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "7cdd37d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 338, "cyclo": 401, "fields": 770, "funcs": 390, "lcom": 77, "lines": 7106, "loc": 5580}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 13, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:55:33Z"} |
| 14 | +{"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} | |
| 15 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} | |
| @@ -11,3 +11,5 @@ | |||
| 11 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "6a3f52a", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 169, "complex": 325, "cyclo": 390, "fields": 725, "funcs": 372, "lcom": 75, "lines": 6771, "loc": 5299}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 11, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:38:59Z"} | 11 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "6a3f52a", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 169, "complex": 325, "cyclo": 390, "fields": 725, "funcs": 372, "lcom": 75, "lines": 6771, "loc": 5299}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 11, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:38:59Z"} |
| 12 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "d8981f3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 329, "cyclo": 395, "fields": 758, "funcs": 384, "lcom": 76, "lines": 6999, "loc": 5488}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 12, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:48:22Z"} | 12 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "d8981f3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 329, "cyclo": 395, "fields": 758, "funcs": 384, "lcom": 76, "lines": 6999, "loc": 5488}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 12, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:48:22Z"} |
| 13 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "7cdd37d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 338, "cyclo": 401, "fields": 770, "funcs": 390, "lcom": 77, "lines": 7106, "loc": 5580}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 13, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:55:33Z"} | 13 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "7cdd37d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 338, "cyclo": 401, "fields": 770, "funcs": 390, "lcom": 77, "lines": 7106, "loc": 5580}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 13, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:55:33Z"} |
| 14 | +{"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} | ||
| 15 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} | ||
added
.quality/report-20261125T132534Z.md +93 -0 | new file mode 100644 | ||
| @@ -0,0 +1,93 @@ | ||
| 1 | +# Quality report — 2026-11-25T13:25:34Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` | |
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | |
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | |
| 7 | +- **Run**: #14 (previous: 2026-11-25T12:55:33Z) | |
| 8 | + | |
| 9 | +## Gate violations | |
| 10 | + | |
| 11 | +- error-level issues: 1 (max 0) | |
| 12 | +- warning-level issues: 3 (max 0) | |
| 13 | +- code smells: 2 (max 0) | |
| 14 | + | |
| 15 | +## Lint issues (`qlty check`) | |
| 16 | + | |
| 17 | +| level | count | vs previous | | |
| 18 | +|---|---|---| | |
| 19 | +| error | 1 | — | | |
| 20 | +| warning | 3 | — | | |
| 21 | + | |
| 22 | +### Top rules | |
| 23 | + | |
| 24 | +| rule | count | | |
| 25 | +|---|---| | |
| 26 | +| swiftlint:cyclomatic_complexity | 1 | | |
| 27 | +| swiftlint:for_where | 1 | | |
| 28 | +| swiftlint:opening_brace | 1 | | |
| 29 | +| swiftlint:shorthand_operator | 1 | | |
| 30 | + | |
| 31 | +### Most affected files | |
| 32 | + | |
| 33 | +| file | issues | | |
| 34 | +|---|---| | |
| 35 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 3 | | |
| 36 | +| Sources/RazorbillMLX/GrammarSupport.swift | 1 | | |
| 37 | + | |
| 38 | +## Code smells (`qlty smells`) | |
| 39 | + | |
| 40 | +Total: **2** (vs previous: +2) | |
| 41 | + | |
| 42 | +| smell | file | line | detail | | |
| 43 | +|---|---|---|---| | |
| 44 | +| qlty:nested-control-flow | Sources/RazorbillCore/Engine/OutputConstraint.swift | 83 | Deeply nested control flow (level = 5) | | |
| 45 | +| qlty:function-complexity | Sources/RazorbillCore/Engine/OutputConstraint.swift | 71 | Function with high complexity (count = 39): find | | |
| 46 | + | |
| 47 | +## Metrics (`qlty metrics`) | |
| 48 | + | |
| 49 | +| metric | total | vs previous | | |
| 50 | +|---|---|---| | |
| 51 | +| funcs | 440 | +50 | | |
| 52 | +| classes | 191 | +20 | | |
| 53 | +| fields | 891 | +121 | | |
| 54 | +| cyclo | 464 | +63 | | |
| 55 | +| complex | 406 | +68 | | |
| 56 | +| lcom | 84 | +7 | | |
| 57 | +| lines | 8086 | +980 | | |
| 58 | +| loc | 6388 | +808 | | |
| 59 | + | |
| 60 | +### Most complex files | |
| 61 | + | |
| 62 | +| file | complex | cyclo | loc | | |
| 63 | +|---|---|---|---| | |
| 64 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 39 | 15 | 68 | | |
| 65 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | |
| 66 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | |
| 67 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 68 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 69 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | |
| 70 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 71 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | |
| 72 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | |
| 73 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 74 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 75 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | |
| 76 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | |
| 77 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 78 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 79 | + | |
| 80 | +## Trend | |
| 81 | + | |
| 82 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 83 | +|---|---|---|---|---|---|---| | |
| 84 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| 85 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 86 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 87 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 88 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 89 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| 90 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| 91 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | |
| 92 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | |
| 93 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# Quality report — 2026-11-25T13:25:34Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` | ||
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | ||
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | ||
| 7 | +- **Run**: #14 (previous: 2026-11-25T12:55:33Z) | ||
| 8 | + | ||
| 9 | +## Gate violations | ||
| 10 | + | ||
| 11 | +- error-level issues: 1 (max 0) | ||
| 12 | +- warning-level issues: 3 (max 0) | ||
| 13 | +- code smells: 2 (max 0) | ||
| 14 | + | ||
| 15 | +## Lint issues (`qlty check`) | ||
| 16 | + | ||
| 17 | +| level | count | vs previous | | ||
| 18 | +|---|---|---| | ||
| 19 | +| error | 1 | — | | ||
| 20 | +| warning | 3 | — | | ||
| 21 | + | ||
| 22 | +### Top rules | ||
| 23 | + | ||
| 24 | +| rule | count | | ||
| 25 | +|---|---| | ||
| 26 | +| swiftlint:cyclomatic_complexity | 1 | | ||
| 27 | +| swiftlint:for_where | 1 | | ||
| 28 | +| swiftlint:opening_brace | 1 | | ||
| 29 | +| swiftlint:shorthand_operator | 1 | | ||
| 30 | + | ||
| 31 | +### Most affected files | ||
| 32 | + | ||
| 33 | +| file | issues | | ||
| 34 | +|---|---| | ||
| 35 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 3 | | ||
| 36 | +| Sources/RazorbillMLX/GrammarSupport.swift | 1 | | ||
| 37 | + | ||
| 38 | +## Code smells (`qlty smells`) | ||
| 39 | + | ||
| 40 | +Total: **2** (vs previous: +2) | ||
| 41 | + | ||
| 42 | +| smell | file | line | detail | | ||
| 43 | +|---|---|---|---| | ||
| 44 | +| qlty:nested-control-flow | Sources/RazorbillCore/Engine/OutputConstraint.swift | 83 | Deeply nested control flow (level = 5) | | ||
| 45 | +| qlty:function-complexity | Sources/RazorbillCore/Engine/OutputConstraint.swift | 71 | Function with high complexity (count = 39): find | | ||
| 46 | + | ||
| 47 | +## Metrics (`qlty metrics`) | ||
| 48 | + | ||
| 49 | +| metric | total | vs previous | | ||
| 50 | +|---|---|---| | ||
| 51 | +| funcs | 440 | +50 | | ||
| 52 | +| classes | 191 | +20 | | ||
| 53 | +| fields | 891 | +121 | | ||
| 54 | +| cyclo | 464 | +63 | | ||
| 55 | +| complex | 406 | +68 | | ||
| 56 | +| lcom | 84 | +7 | | ||
| 57 | +| lines | 8086 | +980 | | ||
| 58 | +| loc | 6388 | +808 | | ||
| 59 | + | ||
| 60 | +### Most complex files | ||
| 61 | + | ||
| 62 | +| file | complex | cyclo | loc | | ||
| 63 | +|---|---|---|---| | ||
| 64 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 39 | 15 | 68 | | ||
| 65 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | ||
| 66 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | ||
| 67 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 68 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 69 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | ||
| 70 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 71 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | ||
| 72 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | ||
| 73 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 74 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 75 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | ||
| 76 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | ||
| 77 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 78 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 79 | + | ||
| 80 | +## Trend | ||
| 81 | + | ||
| 82 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 83 | +|---|---|---|---|---|---|---| | ||
| 84 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
| 85 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 86 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 87 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 88 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 89 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
| 90 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
| 91 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | ||
| 92 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | ||
| 93 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
added
.quality/report-20261125T132602Z.md +76 -0 | new file mode 100644 | ||
| @@ -0,0 +1,76 @@ | ||
| 1 | +# Quality report — 2026-11-25T13:26:02Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` | |
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | |
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | |
| 7 | +- **Run**: #15 (previous: 2026-11-25T13:25:34Z) | |
| 8 | + | |
| 9 | +## Lint issues (`qlty check`) | |
| 10 | + | |
| 11 | +| level | count | vs previous | | |
| 12 | +|---|---|---| | |
| 13 | +| error | 0 | -1 | | |
| 14 | +| warning | 0 | -3 | | |
| 15 | + | |
| 16 | +### Top rules | |
| 17 | + | |
| 18 | +_none_ | |
| 19 | + | |
| 20 | +### Most affected files | |
| 21 | + | |
| 22 | +_none_ | |
| 23 | + | |
| 24 | +## Code smells (`qlty smells`) | |
| 25 | + | |
| 26 | +Total: **0** (vs previous: -2) | |
| 27 | + | |
| 28 | +_none_ | |
| 29 | + | |
| 30 | +## Metrics (`qlty metrics`) | |
| 31 | + | |
| 32 | +| metric | total | vs previous | | |
| 33 | +|---|---|---| | |
| 34 | +| funcs | 442 | +2 | | |
| 35 | +| classes | 191 | ±0 | | |
| 36 | +| fields | 891 | ±0 | | |
| 37 | +| cyclo | 457 | -7 | | |
| 38 | +| complex | 377 | -29 | | |
| 39 | +| lcom | 84 | ±0 | | |
| 40 | +| lines | 8087 | +1 | | |
| 41 | +| loc | 6384 | -4 | | |
| 42 | + | |
| 43 | +### Most complex files | |
| 44 | + | |
| 45 | +| file | complex | cyclo | loc | | |
| 46 | +|---|---|---|---| | |
| 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | |
| 48 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | |
| 49 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 50 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | |
| 52 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 53 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | |
| 54 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | |
| 55 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 56 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 57 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | |
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | |
| 59 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 60 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | |
| 61 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 62 | + | |
| 63 | +## Trend | |
| 64 | + | |
| 65 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 66 | +|---|---|---|---|---|---|---| | |
| 67 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 68 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 69 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 70 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 71 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| 72 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| 73 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | |
| 74 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | |
| 75 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| 76 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,76 @@ | |||
| 1 | +# Quality report — 2026-11-25T13:26:02Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` | ||
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | ||
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | ||
| 7 | +- **Run**: #15 (previous: 2026-11-25T13:25:34Z) | ||
| 8 | + | ||
| 9 | +## Lint issues (`qlty check`) | ||
| 10 | + | ||
| 11 | +| level | count | vs previous | | ||
| 12 | +|---|---|---| | ||
| 13 | +| error | 0 | -1 | | ||
| 14 | +| warning | 0 | -3 | | ||
| 15 | + | ||
| 16 | +### Top rules | ||
| 17 | + | ||
| 18 | +_none_ | ||
| 19 | + | ||
| 20 | +### Most affected files | ||
| 21 | + | ||
| 22 | +_none_ | ||
| 23 | + | ||
| 24 | +## Code smells (`qlty smells`) | ||
| 25 | + | ||
| 26 | +Total: **0** (vs previous: -2) | ||
| 27 | + | ||
| 28 | +_none_ | ||
| 29 | + | ||
| 30 | +## Metrics (`qlty metrics`) | ||
| 31 | + | ||
| 32 | +| metric | total | vs previous | | ||
| 33 | +|---|---|---| | ||
| 34 | +| funcs | 442 | +2 | | ||
| 35 | +| classes | 191 | ±0 | | ||
| 36 | +| fields | 891 | ±0 | | ||
| 37 | +| cyclo | 457 | -7 | | ||
| 38 | +| complex | 377 | -29 | | ||
| 39 | +| lcom | 84 | ±0 | | ||
| 40 | +| lines | 8087 | +1 | | ||
| 41 | +| loc | 6384 | -4 | | ||
| 42 | + | ||
| 43 | +### Most complex files | ||
| 44 | + | ||
| 45 | +| file | complex | cyclo | loc | | ||
| 46 | +|---|---|---|---| | ||
| 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | ||
| 48 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | ||
| 49 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 50 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | ||
| 52 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 53 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | ||
| 54 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | ||
| 55 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 56 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 57 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | ||
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | ||
| 59 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 60 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | ||
| 61 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 62 | + | ||
| 63 | +## Trend | ||
| 64 | + | ||
| 65 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 66 | +|---|---|---|---|---|---|---| | ||
| 67 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 68 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 69 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 70 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 71 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
| 72 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
| 73 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | ||
| 74 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | ||
| 75 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
| 76 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
modified
.quality/report-latest.md +24 -21 | @@ -1,14 +1,17 @@ | ||
| 1 | -# Quality report — 2026-11-25T12:55:33Z | |
| 1 | +# Quality report — 2026-11-25T13:26:02Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `7cdd37d` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` | |
| 5 | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #13 (previous: 2026-11-25T12:48:22Z) | |
| 7 | +- **Run**: #15 (previous: 2026-11-25T13:25:34Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| 11 | -_none_ | |
| 11 | +| level | count | vs previous | | |
| 12 | +|---|---|---| | |
| 13 | +| error | 0 | -1 | | |
| 14 | +| warning | 0 | -3 | | |
| 12 | 15 | |
| 13 | 16 | ### Top rules |
| 14 | 17 | |
| @@ -20,7 +23,7 @@ _none_ | ||
| 20 | 23 | |
| 21 | 24 | ## Code smells (`qlty smells`) |
| 22 | 25 | |
| 23 | -Total: **0** (vs previous: ±0) | |
| 26 | +Total: **0** (vs previous: -2) | |
| 24 | 27 | |
| 25 | 28 | _none_ |
| 26 | 29 | |
| @@ -28,41 +31,39 @@ _none_ | ||
| 28 | 31 | |
| 29 | 32 | | metric | total | vs previous | |
| 30 | 33 | |---|---|---| |
| 31 | -| funcs | 390 | +6 | | |
| 32 | -| classes | 171 | ±0 | | |
| 33 | -| fields | 770 | +12 | | |
| 34 | -| cyclo | 401 | +6 | | |
| 35 | -| complex | 338 | +9 | | |
| 36 | -| lcom | 77 | +1 | | |
| 37 | -| lines | 7106 | +107 | | |
| 38 | -| loc | 5580 | +92 | | |
| 34 | +| funcs | 442 | +2 | | |
| 35 | +| classes | 191 | ±0 | | |
| 36 | +| fields | 891 | ±0 | | |
| 37 | +| cyclo | 457 | -7 | | |
| 38 | +| complex | 377 | -29 | | |
| 39 | +| lcom | 84 | ±0 | | |
| 40 | +| lines | 8087 | +1 | | |
| 41 | +| loc | 6384 | -4 | | |
| 39 | 42 | |
| 40 | 43 | ### Most complex files |
| 41 | 44 | |
| 42 | 45 | | file | complex | cyclo | loc | |
| 43 | 46 | |---|---|---|---| |
| 44 | -| Sources/RazorbillServer/Chat/CompletionStream.swift | 27 | 17 | 109 | | |
| 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | |
| 48 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | |
| 45 | 49 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 46 | -| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 206 | | |
| 47 | 50 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | |
| 48 | 51 | | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | |
| 49 | 52 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 50 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 266 | | |
| 53 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | |
| 54 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | |
| 51 | 55 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 52 | 56 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 53 | -| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 135 | | |
| 57 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | |
| 54 | 58 | | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | |
| 55 | 59 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 60 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | |
| 56 | 61 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 57 | -| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | |
| 58 | -| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 59 | 62 | |
| 60 | 63 | ## Trend |
| 61 | 64 | |
| 62 | 65 | | run | timestamp | error | warning | smells | complex | gate | |
| 63 | 66 | |---|---|---|---|---|---|---| |
| 64 | -| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | |
| 65 | -| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| 66 | 67 | | 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | |
| 67 | 68 | | 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | |
| 68 | 69 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | |
| @@ -71,3 +72,5 @@ _none_ | ||
| 71 | 72 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | |
| 72 | 73 | | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | |
| 73 | 74 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | |
| 75 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| 76 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| @@ -1,14 +1,17 @@ | |||
| 1 | -# Quality report — 2026-11-25T12:55:33Z | 1 | +# Quality report — 2026-11-25T13:26:02Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `7cdd37d` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` |
| 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #13 (previous: 2026-11-25T12:48:22Z) | 7 | +- **Run**: #15 (previous: 2026-11-25T13:25:34Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| 11 | -_none_ | 11 | +| level | count | vs previous | |
| 12 | +|---|---|---| | ||
| 13 | +| error | 0 | -1 | | ||
| 14 | +| warning | 0 | -3 | | ||
| 12 | 15 | ||
| 13 | ### Top rules | 16 | ### Top rules |
| 14 | 17 | ||
| @@ -20,7 +23,7 @@ _none_ | |||
| 20 | 23 | ||
| 21 | ## Code smells (`qlty smells`) | 24 | ## Code smells (`qlty smells`) |
| 22 | 25 | ||
| 23 | -Total: **0** (vs previous: ±0) | 26 | +Total: **0** (vs previous: -2) |
| 24 | 27 | ||
| 25 | _none_ | 28 | _none_ |
| 26 | 29 | ||
| @@ -28,41 +31,39 @@ _none_ | |||
| 28 | 31 | ||
| 29 | | metric | total | vs previous | | 32 | | metric | total | vs previous | |
| 30 | |---|---|---| | 33 | |---|---|---| |
| 31 | -| funcs | 390 | +6 | | 34 | +| funcs | 442 | +2 | |
| 32 | -| classes | 171 | ±0 | | 35 | +| classes | 191 | ±0 | |
| 33 | -| fields | 770 | +12 | | 36 | +| fields | 891 | ±0 | |
| 34 | -| cyclo | 401 | +6 | | 37 | +| cyclo | 457 | -7 | |
| 35 | -| complex | 338 | +9 | | 38 | +| complex | 377 | -29 | |
| 36 | -| lcom | 77 | +1 | | 39 | +| lcom | 84 | ±0 | |
| 37 | -| lines | 7106 | +107 | | 40 | +| lines | 8087 | +1 | |
| 38 | -| loc | 5580 | +92 | | 41 | +| loc | 6384 | -4 | |
| 39 | 42 | ||
| 40 | ### Most complex files | 43 | ### Most complex files |
| 41 | 44 | ||
| 42 | | file | complex | cyclo | loc | | 45 | | file | complex | cyclo | loc | |
| 43 | |---|---|---|---| | 46 | |---|---|---|---| |
| 44 | -| Sources/RazorbillServer/Chat/CompletionStream.swift | 27 | 17 | 109 | | 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | |
| 48 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | ||
| 45 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | | 49 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 46 | -| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 206 | | ||
| 47 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | 50 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | |
| 48 | | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | 51 | | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | |
| 49 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | 52 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 50 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 266 | | 53 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | |
| 54 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | ||
| 51 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 55 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 52 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | 56 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 53 | -| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 135 | | 57 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | |
| 54 | | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | 58 | | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | |
| 55 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | 59 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 60 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | ||
| 56 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | 61 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 57 | -| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | ||
| 58 | -| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 59 | 62 | ||
| 60 | ## Trend | 63 | ## Trend |
| 61 | 64 | ||
| 62 | | run | timestamp | error | warning | smells | complex | gate | | 65 | | run | timestamp | error | warning | smells | complex | gate | |
| 63 | |---|---|---|---|---|---|---| | 66 | |---|---|---|---|---|---|---| |
| 64 | -| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | ||
| 65 | -| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
| 66 | | 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | 67 | | 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | |
| 67 | | 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | 68 | | 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | |
| 68 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | 69 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | |
| @@ -71,3 +72,5 @@ _none_ | |||
| 71 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | 72 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | |
| 72 | | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | 73 | | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | |
| 73 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | 74 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | |
| 75 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
| 76 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
modified
.tickets/issues/0038-spike-constrained-decoding-with-mlxguidedgenerat.yaml +35 -8 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 38 |
| 3 | 3 | title: "Spike: constrained decoding with MLXGuidedGeneration (XGrammar)" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T13:40:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "spike" |
| 12 | 12 | - "area::engine" |
| @@ -32,42 +32,69 @@ body: | | ||
| 32 | 32 | tasks: |
| 33 | 33 | - id: 1 |
| 34 | 34 | title: "Minimal Mac prototype: JSON Schema-constrained output with Qwen3" |
| 35 | - state: open | |
| 35 | + state: closed | |
| 36 | 36 | priority: high |
| 37 | 37 | author: |
| 38 | 38 | name: k33g |
| 39 | 39 | email: ph.charriere@gmail.com |
| 40 | 40 | createdAt: 2026-11-24T21:17:08.000Z |
| 41 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 42 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 41 | 43 | - id: 2 |
| 42 | 44 | title: "Composition with thinking and the thinking budget" |
| 43 | - state: open | |
| 45 | + state: closed | |
| 44 | 46 | priority: high |
| 45 | 47 | author: |
| 46 | 48 | name: k33g |
| 47 | 49 | email: ph.charriere@gmail.com |
| 48 | 50 | createdAt: 2026-11-24T21:17:08.000Z |
| 51 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 52 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 49 | 53 | - id: 3 |
| 50 | 54 | title: "Supported JSON Schema subset and error behaviour" |
| 51 | - state: open | |
| 55 | + state: closed | |
| 52 | 56 | priority: medium |
| 53 | 57 | author: |
| 54 | 58 | name: k33g |
| 55 | 59 | email: ph.charriere@gmail.com |
| 56 | 60 | createdAt: 2026-11-24T21:17:08.000Z |
| 61 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 62 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 57 | 63 | - id: 4 |
| 58 | 64 | title: "Measure compile time and tokens/s overhead" |
| 59 | - state: open | |
| 65 | + state: closed | |
| 60 | 66 | priority: medium |
| 61 | 67 | author: |
| 62 | 68 | name: k33g |
| 63 | 69 | email: ph.charriere@gmail.com |
| 64 | 70 | createdAt: 2026-11-24T21:17:08.000Z |
| 71 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 72 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 65 | 73 | - id: 5 |
| 66 | 74 | title: "Write the report and the decision" |
| 67 | - state: open | |
| 75 | + state: closed | |
| 68 | 76 | priority: high |
| 69 | 77 | author: |
| 70 | 78 | name: k33g |
| 71 | 79 | email: ph.charriere@gmail.com |
| 72 | 80 | createdAt: 2026-11-24T21:17:08.000Z |
| 73 | -comments: [] | |
| 81 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 82 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 83 | +comments: | |
| 84 | + - id: 1 | |
| 85 | + author: | |
| 86 | + name: k33g | |
| 87 | + email: ph.charriere@gmail.com | |
| 88 | + createdAt: 2026-11-25T13:40:00.000Z | |
| 89 | + body: | | |
| 90 | + Spike report (Mac, mlx-swift-lm 3.32.3, Qwen3-0.6B-4bit). | |
| 91 | + - **Integration**: not `GuidedGenerationLoop` (its own loop, greedy, no thinking budget, no tool parsing) but a `LogitProcessor` (`GrammarProcessor` in RazorbillMLX) appended to `GenerationComponents`, so it works inside `ChatSession` with temperature/top-p, the thinking budget, tool-call parsing and streaming. It masks logits from XGrammar's bitmask (bits expanded on the GPU: a Swift loop over 150k tokens per step halved throughput) and commits each sampled token. | |
| 92 | + - **Thinking**: the processor stays inactive until `</think>` when thinking is on, so the model reasons freely and only the answer is constrained (checked: reasoning + schema-valid JSON). Composes with the thinking-budget processor (budget first in the chain). | |
| 93 | + - **No grammar cache**: the XGrammar v0.1.30 vendored by mlx-swift-lm has no matcher Fork (`clone()` fails: "Fork() not available in xgrammar v0.1.30"), so a grammar is compiled per request. The grammar tokenizer (vocabulary) is built once per loaded model. | |
| 94 | + - **Unenforced JSON Schema keywords** (json_schema_converter.cc only warns): not, if/then/else, dependentRequired, dependentSchemas, multipleOf, uniqueItems, contains, minContains, maxContains. They give a 400 under `strict: true` (`JSONSchemaSupport`) and are ignored otherwise. Whitespace is free (`any_whitespace=true`, not exposed by the bridge). | |
| 95 | + - **Whitespace loops**: Qwen3-0.6B inside a forced tool call looped on whitespace until max_tokens (the truncated call then lost everything). Fix as in mlx-swift-lm's own loop: after 3 whitespace tokens in a row, a -200 bias on whitespace-only tokens. | |
| 96 | + - **Cost** (Debug build, so pessimistic): free 41 tok in 0.45 s (~90 tok/s); constrained 31 tok in 0.63 s (~49 tok/s) including the per-request grammar compile; the first constrained request of a model adds ~0.6 s (vocabulary extraction). | |
| 97 | + - **Builds** with xcodebuild (the C++ compiles in the package); macOS 14+ per mlx-swift-lm. | |
| 98 | + - **Streaming side issue found**: the `.json` tool-call parser holds back any answer starting with a brace (bare-JSON fallback), so JSON answers streamed in one piece; sessions without tools now use `.gptOSS` (same `<tool_call>` parser without the fallback). | |
| 99 | + Decision for #39/#41: constrained decoding through `OutputConstraint` (Core) and `GrammarProcessor` (MLX); structural tags for tool calls. | |
| 100 | + | |
| @@ -1,12 +1,12 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 38 | 2 | id: 38 |
| 3 | title: "Spike: constrained decoding with MLXGuidedGeneration (XGrammar)" | 3 | title: "Spike: constrained decoding with MLXGuidedGeneration (XGrammar)" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T13:40:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "spike" | 11 | - "spike" |
| 12 | - "area::engine" | 12 | - "area::engine" |
| @@ -32,42 +32,69 @@ body: | | |||
| 32 | tasks: | 32 | tasks: |
| 33 | - id: 1 | 33 | - id: 1 |
| 34 | title: "Minimal Mac prototype: JSON Schema-constrained output with Qwen3" | 34 | title: "Minimal Mac prototype: JSON Schema-constrained output with Qwen3" |
| 35 | - state: open | 35 | + state: closed |
| 36 | priority: high | 36 | priority: high |
| 37 | author: | 37 | author: |
| 38 | name: k33g | 38 | name: k33g |
| 39 | email: ph.charriere@gmail.com | 39 | email: ph.charriere@gmail.com |
| 40 | createdAt: 2026-11-24T21:17:08.000Z | 40 | createdAt: 2026-11-24T21:17:08.000Z |
| 41 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 42 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 41 | - id: 2 | 43 | - id: 2 |
| 42 | title: "Composition with thinking and the thinking budget" | 44 | title: "Composition with thinking and the thinking budget" |
| 43 | - state: open | 45 | + state: closed |
| 44 | priority: high | 46 | priority: high |
| 45 | author: | 47 | author: |
| 46 | name: k33g | 48 | name: k33g |
| 47 | email: ph.charriere@gmail.com | 49 | email: ph.charriere@gmail.com |
| 48 | createdAt: 2026-11-24T21:17:08.000Z | 50 | createdAt: 2026-11-24T21:17:08.000Z |
| 51 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 52 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 49 | - id: 3 | 53 | - id: 3 |
| 50 | title: "Supported JSON Schema subset and error behaviour" | 54 | title: "Supported JSON Schema subset and error behaviour" |
| 51 | - state: open | 55 | + state: closed |
| 52 | priority: medium | 56 | priority: medium |
| 53 | author: | 57 | author: |
| 54 | name: k33g | 58 | name: k33g |
| 55 | email: ph.charriere@gmail.com | 59 | email: ph.charriere@gmail.com |
| 56 | createdAt: 2026-11-24T21:17:08.000Z | 60 | createdAt: 2026-11-24T21:17:08.000Z |
| 61 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 62 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 57 | - id: 4 | 63 | - id: 4 |
| 58 | title: "Measure compile time and tokens/s overhead" | 64 | title: "Measure compile time and tokens/s overhead" |
| 59 | - state: open | 65 | + state: closed |
| 60 | priority: medium | 66 | priority: medium |
| 61 | author: | 67 | author: |
| 62 | name: k33g | 68 | name: k33g |
| 63 | email: ph.charriere@gmail.com | 69 | email: ph.charriere@gmail.com |
| 64 | createdAt: 2026-11-24T21:17:08.000Z | 70 | createdAt: 2026-11-24T21:17:08.000Z |
| 71 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 72 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 65 | - id: 5 | 73 | - id: 5 |
| 66 | title: "Write the report and the decision" | 74 | title: "Write the report and the decision" |
| 67 | - state: open | 75 | + state: closed |
| 68 | priority: high | 76 | priority: high |
| 69 | author: | 77 | author: |
| 70 | name: k33g | 78 | name: k33g |
| 71 | email: ph.charriere@gmail.com | 79 | email: ph.charriere@gmail.com |
| 72 | createdAt: 2026-11-24T21:17:08.000Z | 80 | createdAt: 2026-11-24T21:17:08.000Z |
| 73 | -comments: [] | 81 | + updatedAt: 2026-11-25T13:40:00.000Z |
| 82 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 83 | +comments: | ||
| 84 | + - id: 1 | ||
| 85 | + author: | ||
| 86 | + name: k33g | ||
| 87 | + email: ph.charriere@gmail.com | ||
| 88 | + createdAt: 2026-11-25T13:40:00.000Z | ||
| 89 | + body: | | ||
| 90 | + Spike report (Mac, mlx-swift-lm 3.32.3, Qwen3-0.6B-4bit). | ||
| 91 | + - **Integration**: not `GuidedGenerationLoop` (its own loop, greedy, no thinking budget, no tool parsing) but a `LogitProcessor` (`GrammarProcessor` in RazorbillMLX) appended to `GenerationComponents`, so it works inside `ChatSession` with temperature/top-p, the thinking budget, tool-call parsing and streaming. It masks logits from XGrammar's bitmask (bits expanded on the GPU: a Swift loop over 150k tokens per step halved throughput) and commits each sampled token. | ||
| 92 | + - **Thinking**: the processor stays inactive until `</think>` when thinking is on, so the model reasons freely and only the answer is constrained (checked: reasoning + schema-valid JSON). Composes with the thinking-budget processor (budget first in the chain). | ||
| 93 | + - **No grammar cache**: the XGrammar v0.1.30 vendored by mlx-swift-lm has no matcher Fork (`clone()` fails: "Fork() not available in xgrammar v0.1.30"), so a grammar is compiled per request. The grammar tokenizer (vocabulary) is built once per loaded model. | ||
| 94 | + - **Unenforced JSON Schema keywords** (json_schema_converter.cc only warns): not, if/then/else, dependentRequired, dependentSchemas, multipleOf, uniqueItems, contains, minContains, maxContains. They give a 400 under `strict: true` (`JSONSchemaSupport`) and are ignored otherwise. Whitespace is free (`any_whitespace=true`, not exposed by the bridge). | ||
| 95 | + - **Whitespace loops**: Qwen3-0.6B inside a forced tool call looped on whitespace until max_tokens (the truncated call then lost everything). Fix as in mlx-swift-lm's own loop: after 3 whitespace tokens in a row, a -200 bias on whitespace-only tokens. | ||
| 96 | + - **Cost** (Debug build, so pessimistic): free 41 tok in 0.45 s (~90 tok/s); constrained 31 tok in 0.63 s (~49 tok/s) including the per-request grammar compile; the first constrained request of a model adds ~0.6 s (vocabulary extraction). | ||
| 97 | + - **Builds** with xcodebuild (the C++ compiles in the package); macOS 14+ per mlx-swift-lm. | ||
| 98 | + - **Streaming side issue found**: the `.json` tool-call parser holds back any answer starting with a brace (bare-JSON fallback), so JSON answers streamed in one piece; sessions without tools now use `.gptOSS` (same `<tool_call>` parser without the fallback). | ||
| 99 | + Decision for #39/#41: constrained decoding through `OutputConstraint` (Core) and `GrammarProcessor` (MLX); structural tags for tool calls. | ||
| 100 | + | ||
modified
.tickets/issues/0039-structured-output-response-format-json-object-an.yaml +29 -9 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 39 |
| 3 | 3 | title: "Structured output: response_format json_object and json_schema" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T13:40:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::server" |
| @@ -31,50 +31,70 @@ body: | | ||
| 31 | 31 | tasks: |
| 32 | 32 | - id: 1 |
| 33 | 33 | title: "Parse and validate response_format" |
| 34 | - state: open | |
| 34 | + state: closed | |
| 35 | 35 | priority: high |
| 36 | 36 | author: |
| 37 | 37 | name: k33g |
| 38 | 38 | email: ph.charriere@gmail.com |
| 39 | 39 | createdAt: 2026-11-24T21:17:08.000Z |
| 40 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 41 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 40 | 42 | - id: 2 |
| 41 | 43 | title: "json_object via a generic JSON grammar" |
| 42 | - state: open | |
| 44 | + state: closed | |
| 43 | 45 | priority: high |
| 44 | 46 | author: |
| 45 | 47 | name: k33g |
| 46 | 48 | email: ph.charriere@gmail.com |
| 47 | 49 | createdAt: 2026-11-24T21:17:08.000Z |
| 50 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 51 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 48 | 52 | - id: 3 |
| 49 | 53 | title: "json_schema strict via the guided processor" |
| 50 | - state: open | |
| 54 | + state: closed | |
| 51 | 55 | priority: high |
| 52 | 56 | author: |
| 53 | 57 | name: k33g |
| 54 | 58 | email: ph.charriere@gmail.com |
| 55 | 59 | createdAt: 2026-11-24T21:17:08.000Z |
| 60 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 61 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 56 | 62 | - id: 4 |
| 57 | 63 | title: "Clear 400 for unsupported schema keywords" |
| 58 | - state: open | |
| 64 | + state: closed | |
| 59 | 65 | priority: medium |
| 60 | 66 | author: |
| 61 | 67 | name: k33g |
| 62 | 68 | email: ph.charriere@gmail.com |
| 63 | 69 | createdAt: 2026-11-24T21:17:08.000Z |
| 70 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 71 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 64 | 72 | - id: 5 |
| 65 | 73 | title: "Streaming + reasoning interaction" |
| 66 | - state: open | |
| 74 | + state: closed | |
| 67 | 75 | priority: medium |
| 68 | 76 | author: |
| 69 | 77 | name: k33g |
| 70 | 78 | email: ph.charriere@gmail.com |
| 71 | 79 | createdAt: 2026-11-24T21:17:08.000Z |
| 80 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 81 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 72 | 82 | - id: 6 |
| 73 | 83 | title: "Compiled-grammar cache" |
| 74 | - state: open | |
| 84 | + state: closed | |
| 75 | 85 | priority: low |
| 76 | 86 | author: |
| 77 | 87 | name: k33g |
| 78 | 88 | email: ph.charriere@gmail.com |
| 79 | 89 | createdAt: 2026-11-24T21:17:08.000Z |
| 80 | -comments: [] | |
| 90 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 91 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 92 | +comments: | |
| 93 | + - id: 1 | |
| 94 | + author: | |
| 95 | + name: k33g | |
| 96 | + email: ph.charriere@gmail.com | |
| 97 | + createdAt: 2026-11-25T13:40:00.000Z | |
| 98 | + body: | | |
| 99 | + Done: `response_format` `text` / `json_object` (schema `{"type":"object"}`) / `json_schema` (`schema` required; constrained whether strict or not; `strict: true` with an unenforced keyword gives a 400 naming it and its path). Streaming gives the JSON piece by piece (Mac test reassembles and parses it); reasoning models think first then answer under the schema; `finish_reason: length` when max_tokens cuts the JSON (output then invalid, documented). Grammar cache: not possible (see #38). Mac tests: schema output decodes into a Swift type (enum, minItems, minimum, required, additionalProperties), json_object parses, reasoning + schema, streamed JSON. The openai SDK `.parse(...)` acceptance with a 4B model is on the user's checklist. | |
| 100 | + | |
| @@ -1,12 +1,12 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 39 | 2 | id: 39 |
| 3 | title: "Structured output: response_format json_object and json_schema" | 3 | title: "Structured output: response_format json_object and json_schema" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T13:40:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::server" | 12 | - "area::server" |
| @@ -31,50 +31,70 @@ body: | | |||
| 31 | tasks: | 31 | tasks: |
| 32 | - id: 1 | 32 | - id: 1 |
| 33 | title: "Parse and validate response_format" | 33 | title: "Parse and validate response_format" |
| 34 | - state: open | 34 | + state: closed |
| 35 | priority: high | 35 | priority: high |
| 36 | author: | 36 | author: |
| 37 | name: k33g | 37 | name: k33g |
| 38 | email: ph.charriere@gmail.com | 38 | email: ph.charriere@gmail.com |
| 39 | createdAt: 2026-11-24T21:17:08.000Z | 39 | createdAt: 2026-11-24T21:17:08.000Z |
| 40 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 41 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 40 | - id: 2 | 42 | - id: 2 |
| 41 | title: "json_object via a generic JSON grammar" | 43 | title: "json_object via a generic JSON grammar" |
| 42 | - state: open | 44 | + state: closed |
| 43 | priority: high | 45 | priority: high |
| 44 | author: | 46 | author: |
| 45 | name: k33g | 47 | name: k33g |
| 46 | email: ph.charriere@gmail.com | 48 | email: ph.charriere@gmail.com |
| 47 | createdAt: 2026-11-24T21:17:08.000Z | 49 | createdAt: 2026-11-24T21:17:08.000Z |
| 50 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 51 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 48 | - id: 3 | 52 | - id: 3 |
| 49 | title: "json_schema strict via the guided processor" | 53 | title: "json_schema strict via the guided processor" |
| 50 | - state: open | 54 | + state: closed |
| 51 | priority: high | 55 | priority: high |
| 52 | author: | 56 | author: |
| 53 | name: k33g | 57 | name: k33g |
| 54 | email: ph.charriere@gmail.com | 58 | email: ph.charriere@gmail.com |
| 55 | createdAt: 2026-11-24T21:17:08.000Z | 59 | createdAt: 2026-11-24T21:17:08.000Z |
| 60 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 61 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 56 | - id: 4 | 62 | - id: 4 |
| 57 | title: "Clear 400 for unsupported schema keywords" | 63 | title: "Clear 400 for unsupported schema keywords" |
| 58 | - state: open | 64 | + state: closed |
| 59 | priority: medium | 65 | priority: medium |
| 60 | author: | 66 | author: |
| 61 | name: k33g | 67 | name: k33g |
| 62 | email: ph.charriere@gmail.com | 68 | email: ph.charriere@gmail.com |
| 63 | createdAt: 2026-11-24T21:17:08.000Z | 69 | createdAt: 2026-11-24T21:17:08.000Z |
| 70 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 71 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 64 | - id: 5 | 72 | - id: 5 |
| 65 | title: "Streaming + reasoning interaction" | 73 | title: "Streaming + reasoning interaction" |
| 66 | - state: open | 74 | + state: closed |
| 67 | priority: medium | 75 | priority: medium |
| 68 | author: | 76 | author: |
| 69 | name: k33g | 77 | name: k33g |
| 70 | email: ph.charriere@gmail.com | 78 | email: ph.charriere@gmail.com |
| 71 | createdAt: 2026-11-24T21:17:08.000Z | 79 | createdAt: 2026-11-24T21:17:08.000Z |
| 80 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 81 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 72 | - id: 6 | 82 | - id: 6 |
| 73 | title: "Compiled-grammar cache" | 83 | title: "Compiled-grammar cache" |
| 74 | - state: open | 84 | + state: closed |
| 75 | priority: low | 85 | priority: low |
| 76 | author: | 86 | author: |
| 77 | name: k33g | 87 | name: k33g |
| 78 | email: ph.charriere@gmail.com | 88 | email: ph.charriere@gmail.com |
| 79 | createdAt: 2026-11-24T21:17:08.000Z | 89 | createdAt: 2026-11-24T21:17:08.000Z |
| 80 | -comments: [] | 90 | + updatedAt: 2026-11-25T13:40:00.000Z |
| 91 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 92 | +comments: | ||
| 93 | + - id: 1 | ||
| 94 | + author: | ||
| 95 | + name: k33g | ||
| 96 | + email: ph.charriere@gmail.com | ||
| 97 | + createdAt: 2026-11-25T13:40:00.000Z | ||
| 98 | + body: | | ||
| 99 | + Done: `response_format` `text` / `json_object` (schema `{"type":"object"}`) / `json_schema` (`schema` required; constrained whether strict or not; `strict: true` with an unenforced keyword gives a 400 naming it and its path). Streaming gives the JSON piece by piece (Mac test reassembles and parses it); reasoning models think first then answer under the schema; `finish_reason: length` when max_tokens cuts the JSON (output then invalid, documented). Grammar cache: not possible (see #38). Mac tests: schema output decodes into a Swift type (enum, minItems, minimum, required, additionalProperties), json_object parses, reasoning + schema, streamed JSON. The openai SDK `.parse(...)` acceptance with a 4B model is on the user's checklist. | ||
| 100 | + | ||
modified
.tickets/issues/0040-function-calling-tools-tool-choice-and-tool-call.yaml +32 -10 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 40 |
| 3 | 3 | title: "Function calling: tools, tool_choice and tool_calls responses" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T13:40:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::server" |
| @@ -37,58 +37,80 @@ body: | | ||
| 37 | 37 | tasks: |
| 38 | 38 | - id: 1 |
| 39 | 39 | title: "Tool DTOs and rendering through the chat template" |
| 40 | - state: open | |
| 40 | + state: closed | |
| 41 | 41 | priority: high |
| 42 | 42 | author: |
| 43 | 43 | name: k33g |
| 44 | 44 | email: ph.charriere@gmail.com |
| 45 | 45 | createdAt: 2026-11-24T21:17:08.000Z |
| 46 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 47 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 46 | 48 | - id: 2 |
| 47 | 49 | title: "Parse tool calls with ToolCallFormat per family" |
| 48 | - state: open | |
| 50 | + state: closed | |
| 49 | 51 | priority: high |
| 50 | 52 | author: |
| 51 | 53 | name: k33g |
| 52 | 54 | email: ph.charriere@gmail.com |
| 53 | 55 | createdAt: 2026-11-24T21:17:08.000Z |
| 56 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 57 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 54 | 58 | - id: 3 |
| 55 | 59 | title: "tool_calls in non-streaming responses" |
| 56 | - state: open | |
| 60 | + state: closed | |
| 57 | 61 | priority: high |
| 58 | 62 | author: |
| 59 | 63 | name: k33g |
| 60 | 64 | email: ph.charriere@gmail.com |
| 61 | 65 | createdAt: 2026-11-24T21:17:08.000Z |
| 66 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 67 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 62 | 68 | - id: 4 |
| 63 | 69 | title: "Streaming tool_call deltas" |
| 64 | - state: open | |
| 70 | + state: closed | |
| 65 | 71 | priority: high |
| 66 | 72 | author: |
| 67 | 73 | name: k33g |
| 68 | 74 | email: ph.charriere@gmail.com |
| 69 | 75 | createdAt: 2026-11-24T21:17:08.000Z |
| 76 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 77 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 70 | 78 | - id: 5 |
| 71 | 79 | title: "tool / assistant.tool_calls history messages" |
| 72 | - state: open | |
| 80 | + state: closed | |
| 73 | 81 | priority: high |
| 74 | 82 | author: |
| 75 | 83 | name: k33g |
| 76 | 84 | email: ph.charriere@gmail.com |
| 77 | 85 | createdAt: 2026-11-24T21:17:08.000Z |
| 86 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 87 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 78 | 88 | - id: 6 |
| 79 | 89 | title: "tool_choice none / auto" |
| 80 | - state: open | |
| 90 | + state: closed | |
| 81 | 91 | priority: medium |
| 82 | 92 | author: |
| 83 | 93 | name: k33g |
| 84 | 94 | email: ph.charriere@gmail.com |
| 85 | 95 | createdAt: 2026-11-24T21:17:08.000Z |
| 96 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 97 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 86 | 98 | - id: 7 |
| 87 | 99 | title: "Tests per family with recorded model outputs" |
| 88 | - state: open | |
| 100 | + state: closed | |
| 89 | 101 | priority: high |
| 90 | 102 | author: |
| 91 | 103 | name: k33g |
| 92 | 104 | email: ph.charriere@gmail.com |
| 93 | 105 | createdAt: 2026-11-24T21:17:08.000Z |
| 94 | -comments: [] | |
| 106 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 107 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 108 | +comments: | |
| 109 | + - id: 1 | |
| 110 | + author: | |
| 111 | + name: k33g | |
| 112 | + email: ph.charriere@gmail.com | |
| 113 | + createdAt: 2026-11-25T13:40:00.000Z | |
| 114 | + body: | | |
| 115 | + Done: `tools` (functions only, names 1-64 [A-Za-z0-9_-], unique, `parameters` default `{type: object, properties: {}}`) passed to the chat template; `tool_choice` none (tools not offered) / auto / required / named; `parallel_tool_calls`; history with `assistant.tool_calls` + `role: tool` + `tool_call_id` (since #35). Parsing by mlx-swift-lm's `ToolCallFormat` (model config); non-streaming `tool_calls` with JSON-string arguments and null content; streaming `delta.tool_calls` with `index` (one delta per complete call). `parallel_tool_calls: false` keeps the first call. Mac round trip with Qwen3-0.6B: forced call, tool result, answer using it. Qwen3-0.6B often answers in prose under `auto` (hence #41). Second model family (Llama 3.x / Mistral) not tested here: user checklist. | |
| 116 | + | |
| @@ -1,12 +1,12 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 40 | 2 | id: 40 |
| 3 | title: "Function calling: tools, tool_choice and tool_calls responses" | 3 | title: "Function calling: tools, tool_choice and tool_calls responses" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T13:40:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::server" | 12 | - "area::server" |
| @@ -37,58 +37,80 @@ body: | | |||
| 37 | tasks: | 37 | tasks: |
| 38 | - id: 1 | 38 | - id: 1 |
| 39 | title: "Tool DTOs and rendering through the chat template" | 39 | title: "Tool DTOs and rendering through the chat template" |
| 40 | - state: open | 40 | + state: closed |
| 41 | priority: high | 41 | priority: high |
| 42 | author: | 42 | author: |
| 43 | name: k33g | 43 | name: k33g |
| 44 | email: ph.charriere@gmail.com | 44 | email: ph.charriere@gmail.com |
| 45 | createdAt: 2026-11-24T21:17:08.000Z | 45 | createdAt: 2026-11-24T21:17:08.000Z |
| 46 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 47 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 46 | - id: 2 | 48 | - id: 2 |
| 47 | title: "Parse tool calls with ToolCallFormat per family" | 49 | title: "Parse tool calls with ToolCallFormat per family" |
| 48 | - state: open | 50 | + state: closed |
| 49 | priority: high | 51 | priority: high |
| 50 | author: | 52 | author: |
| 51 | name: k33g | 53 | name: k33g |
| 52 | email: ph.charriere@gmail.com | 54 | email: ph.charriere@gmail.com |
| 53 | createdAt: 2026-11-24T21:17:08.000Z | 55 | createdAt: 2026-11-24T21:17:08.000Z |
| 56 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 57 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 54 | - id: 3 | 58 | - id: 3 |
| 55 | title: "tool_calls in non-streaming responses" | 59 | title: "tool_calls in non-streaming responses" |
| 56 | - state: open | 60 | + state: closed |
| 57 | priority: high | 61 | priority: high |
| 58 | author: | 62 | author: |
| 59 | name: k33g | 63 | name: k33g |
| 60 | email: ph.charriere@gmail.com | 64 | email: ph.charriere@gmail.com |
| 61 | createdAt: 2026-11-24T21:17:08.000Z | 65 | createdAt: 2026-11-24T21:17:08.000Z |
| 66 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 67 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 62 | - id: 4 | 68 | - id: 4 |
| 63 | title: "Streaming tool_call deltas" | 69 | title: "Streaming tool_call deltas" |
| 64 | - state: open | 70 | + state: closed |
| 65 | priority: high | 71 | priority: high |
| 66 | author: | 72 | author: |
| 67 | name: k33g | 73 | name: k33g |
| 68 | email: ph.charriere@gmail.com | 74 | email: ph.charriere@gmail.com |
| 69 | createdAt: 2026-11-24T21:17:08.000Z | 75 | createdAt: 2026-11-24T21:17:08.000Z |
| 76 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 77 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 70 | - id: 5 | 78 | - id: 5 |
| 71 | title: "tool / assistant.tool_calls history messages" | 79 | title: "tool / assistant.tool_calls history messages" |
| 72 | - state: open | 80 | + state: closed |
| 73 | priority: high | 81 | priority: high |
| 74 | author: | 82 | author: |
| 75 | name: k33g | 83 | name: k33g |
| 76 | email: ph.charriere@gmail.com | 84 | email: ph.charriere@gmail.com |
| 77 | createdAt: 2026-11-24T21:17:08.000Z | 85 | createdAt: 2026-11-24T21:17:08.000Z |
| 86 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 87 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 78 | - id: 6 | 88 | - id: 6 |
| 79 | title: "tool_choice none / auto" | 89 | title: "tool_choice none / auto" |
| 80 | - state: open | 90 | + state: closed |
| 81 | priority: medium | 91 | priority: medium |
| 82 | author: | 92 | author: |
| 83 | name: k33g | 93 | name: k33g |
| 84 | email: ph.charriere@gmail.com | 94 | email: ph.charriere@gmail.com |
| 85 | createdAt: 2026-11-24T21:17:08.000Z | 95 | createdAt: 2026-11-24T21:17:08.000Z |
| 96 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 97 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 86 | - id: 7 | 98 | - id: 7 |
| 87 | title: "Tests per family with recorded model outputs" | 99 | title: "Tests per family with recorded model outputs" |
| 88 | - state: open | 100 | + state: closed |
| 89 | priority: high | 101 | priority: high |
| 90 | author: | 102 | author: |
| 91 | name: k33g | 103 | name: k33g |
| 92 | email: ph.charriere@gmail.com | 104 | email: ph.charriere@gmail.com |
| 93 | createdAt: 2026-11-24T21:17:08.000Z | 105 | createdAt: 2026-11-24T21:17:08.000Z |
| 94 | -comments: [] | 106 | + updatedAt: 2026-11-25T13:40:00.000Z |
| 107 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 108 | +comments: | ||
| 109 | + - id: 1 | ||
| 110 | + author: | ||
| 111 | + name: k33g | ||
| 112 | + email: ph.charriere@gmail.com | ||
| 113 | + createdAt: 2026-11-25T13:40:00.000Z | ||
| 114 | + body: | | ||
| 115 | + Done: `tools` (functions only, names 1-64 [A-Za-z0-9_-], unique, `parameters` default `{type: object, properties: {}}`) passed to the chat template; `tool_choice` none (tools not offered) / auto / required / named; `parallel_tool_calls`; history with `assistant.tool_calls` + `role: tool` + `tool_call_id` (since #35). Parsing by mlx-swift-lm's `ToolCallFormat` (model config); non-streaming `tool_calls` with JSON-string arguments and null content; streaming `delta.tool_calls` with `index` (one delta per complete call). `parallel_tool_calls: false` keeps the first call. Mac round trip with Qwen3-0.6B: forced call, tool result, answer using it. Qwen3-0.6B often answers in prose under `auto` (hence #41). Second model family (Llama 3.x / Mistral) not tested here: user checklist. | ||
| 116 | + | ||
modified
.tickets/issues/0041-function-calling-enforce-tool-choice-required-na.yaml +23 -7 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 41 |
| 3 | 3 | title: "Function calling: enforce tool_choice required / named with constrained decoding" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T13:40:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::engine" |
| @@ -28,34 +28,50 @@ body: | | ||
| 28 | 28 | tasks: |
| 29 | 29 | - id: 1 |
| 30 | 30 | title: "Grammar for the tool-call syntax of each supported family" |
| 31 | - state: open | |
| 31 | + state: closed | |
| 32 | 32 | priority: medium |
| 33 | 33 | author: |
| 34 | 34 | name: k33g |
| 35 | 35 | email: ph.charriere@gmail.com |
| 36 | 36 | createdAt: 2026-11-24T21:17:08.000Z |
| 37 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 38 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 37 | 39 | - id: 2 |
| 38 | 40 | title: "required / named tool_choice" |
| 39 | - state: open | |
| 41 | + state: closed | |
| 40 | 42 | priority: medium |
| 41 | 43 | author: |
| 42 | 44 | name: k33g |
| 43 | 45 | email: ph.charriere@gmail.com |
| 44 | 46 | createdAt: 2026-11-24T21:17:08.000Z |
| 47 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 48 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 45 | 49 | - id: 3 |
| 46 | 50 | title: "strict function arguments" |
| 47 | - state: open | |
| 51 | + state: closed | |
| 48 | 52 | priority: medium |
| 49 | 53 | author: |
| 50 | 54 | name: k33g |
| 51 | 55 | email: ph.charriere@gmail.com |
| 52 | 56 | createdAt: 2026-11-24T21:17:08.000Z |
| 57 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 58 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 53 | 59 | - id: 4 |
| 54 | 60 | title: "Tests with a small model that otherwise answers in prose" |
| 55 | - state: open | |
| 61 | + state: closed | |
| 56 | 62 | priority: medium |
| 57 | 63 | author: |
| 58 | 64 | name: k33g |
| 59 | 65 | email: ph.charriere@gmail.com |
| 60 | 66 | createdAt: 2026-11-24T21:17:08.000Z |
| 61 | -comments: [] | |
| 67 | + updatedAt: 2026-11-25T13:40:00.000Z | |
| 68 | + closedAt: 2026-11-25T13:40:00.000Z | |
| 69 | +comments: | |
| 70 | + - id: 1 | |
| 71 | + author: | |
| 72 | + name: k33g | |
| 73 | + email: ph.charriere@gmail.com | |
| 74 | + createdAt: 2026-11-25T13:40:00.000Z | |
| 75 | + body: | | |
| 76 | + Done with XGrammar structural tags for the `<tool_call>` + JSON + `</tool_call>` syntax (`.json` format: Qwen, Hermes…): `required` / named use `tags_with_separator` (at least one); `strict` functions under `auto` use `triggered_tags` on `<tool_call>`; arguments constrained by each function's schema (`anyOf` over functions, `name` as const). Forced calls are a single call unless `parallel_tool_calls: true` is sent (small models otherwise repeat the call until max_tokens). Other syntaxes (Mistral, Llama 3, Gemma, GLM…) give a 400 `param: tool_choice` instead of the retry-then-500 fallback the ticket proposed (explicit and cheaper; can be revisited). Mac tests: required on small talk gives a valid call; named function called with enum-valid arguments. | |
| 77 | + | |
| @@ -1,12 +1,12 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 41 | 2 | id: 41 |
| 3 | title: "Function calling: enforce tool_choice required / named with constrained decoding" | 3 | title: "Function calling: enforce tool_choice required / named with constrained decoding" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T13:40:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::engine" | 12 | - "area::engine" |
| @@ -28,34 +28,50 @@ body: | | |||
| 28 | tasks: | 28 | tasks: |
| 29 | - id: 1 | 29 | - id: 1 |
| 30 | title: "Grammar for the tool-call syntax of each supported family" | 30 | title: "Grammar for the tool-call syntax of each supported family" |
| 31 | - state: open | 31 | + state: closed |
| 32 | priority: medium | 32 | priority: medium |
| 33 | author: | 33 | author: |
| 34 | name: k33g | 34 | name: k33g |
| 35 | email: ph.charriere@gmail.com | 35 | email: ph.charriere@gmail.com |
| 36 | createdAt: 2026-11-24T21:17:08.000Z | 36 | createdAt: 2026-11-24T21:17:08.000Z |
| 37 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 38 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 37 | - id: 2 | 39 | - id: 2 |
| 38 | title: "required / named tool_choice" | 40 | title: "required / named tool_choice" |
| 39 | - state: open | 41 | + state: closed |
| 40 | priority: medium | 42 | priority: medium |
| 41 | author: | 43 | author: |
| 42 | name: k33g | 44 | name: k33g |
| 43 | email: ph.charriere@gmail.com | 45 | email: ph.charriere@gmail.com |
| 44 | createdAt: 2026-11-24T21:17:08.000Z | 46 | createdAt: 2026-11-24T21:17:08.000Z |
| 47 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 48 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 45 | - id: 3 | 49 | - id: 3 |
| 46 | title: "strict function arguments" | 50 | title: "strict function arguments" |
| 47 | - state: open | 51 | + state: closed |
| 48 | priority: medium | 52 | priority: medium |
| 49 | author: | 53 | author: |
| 50 | name: k33g | 54 | name: k33g |
| 51 | email: ph.charriere@gmail.com | 55 | email: ph.charriere@gmail.com |
| 52 | createdAt: 2026-11-24T21:17:08.000Z | 56 | createdAt: 2026-11-24T21:17:08.000Z |
| 57 | + updatedAt: 2026-11-25T13:40:00.000Z | ||
| 58 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 53 | - id: 4 | 59 | - id: 4 |
| 54 | title: "Tests with a small model that otherwise answers in prose" | 60 | title: "Tests with a small model that otherwise answers in prose" |
| 55 | - state: open | 61 | + state: closed |
| 56 | priority: medium | 62 | priority: medium |
| 57 | author: | 63 | author: |
| 58 | name: k33g | 64 | name: k33g |
| 59 | email: ph.charriere@gmail.com | 65 | email: ph.charriere@gmail.com |
| 60 | createdAt: 2026-11-24T21:17:08.000Z | 66 | createdAt: 2026-11-24T21:17:08.000Z |
| 61 | -comments: [] | 67 | + updatedAt: 2026-11-25T13:40:00.000Z |
| 68 | + closedAt: 2026-11-25T13:40:00.000Z | ||
| 69 | +comments: | ||
| 70 | + - id: 1 | ||
| 71 | + author: | ||
| 72 | + name: k33g | ||
| 73 | + email: ph.charriere@gmail.com | ||
| 74 | + createdAt: 2026-11-25T13:40:00.000Z | ||
| 75 | + body: | | ||
| 76 | + Done with XGrammar structural tags for the `<tool_call>` + JSON + `</tool_call>` syntax (`.json` format: Qwen, Hermes…): `required` / named use `tags_with_separator` (at least one); `strict` functions under `auto` use `triggered_tags` on `<tool_call>`; arguments constrained by each function's schema (`anyOf` over functions, `name` as const). Forced calls are a single call unless `parallel_tool_calls: true` is sent (small models otherwise repeat the call until max_tokens). Other syntaxes (Mistral, Llama 3, Gemma, GLM…) give a 400 `param: tool_choice` instead of the retry-then-500 fallback the ticket proposed (explicit and cheaper; can be revisited). Mac tests: required on small talk gives a valid call; named function called with enum-valid arguments. | ||
| 77 | + | ||
modified
Package.swift +4 -0 | @@ -25,6 +25,7 @@ let package = Package( | ||
| 25 | 25 | .upToNextMinor(from: "3.32.3"), |
| 26 | 26 | traits: [] |
| 27 | 27 | ), |
| 28 | + .package(url: "https://github.com/ml-explore/mlx-swift", from: "0.32.0"), | |
| 28 | 29 | .package(url: "https://github.com/huggingface/swift-huggingface", from: "0.9.0"), |
| 29 | 30 | .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"), |
| 30 | 31 | .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"), |
| @@ -49,6 +50,9 @@ let package = Package( | ||
| 49 | 50 | macOnly("MLXLLM", "mlx-swift-lm"), |
| 50 | 51 | macOnly("MLXLMCommon", "mlx-swift-lm"), |
| 51 | 52 | macOnly("MLXHuggingFace", "mlx-swift-lm"), |
| 53 | + // Constrained decoding (XGrammar, C++): structured output and forced tool calls. | |
| 54 | + macOnly("MLXGuidedGeneration", "mlx-swift-lm"), | |
| 55 | + macOnly("MLX", "mlx-swift"), | |
| 52 | 56 | macOnly("HuggingFace", "swift-huggingface"), |
| 53 | 57 | macOnly("Tokenizers", "swift-transformers"), |
| 54 | 58 | ] |
| @@ -25,6 +25,7 @@ let package = Package( | |||
| 25 | .upToNextMinor(from: "3.32.3"), | 25 | .upToNextMinor(from: "3.32.3"), |
| 26 | traits: [] | 26 | traits: [] |
| 27 | ), | 27 | ), |
| 28 | + .package(url: "https://github.com/ml-explore/mlx-swift", from: "0.32.0"), | ||
| 28 | .package(url: "https://github.com/huggingface/swift-huggingface", from: "0.9.0"), | 29 | .package(url: "https://github.com/huggingface/swift-huggingface", from: "0.9.0"), |
| 29 | .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"), | 30 | .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"), |
| 30 | .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"), | 31 | .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"), |
| @@ -49,6 +50,9 @@ let package = Package( | |||
| 49 | macOnly("MLXLLM", "mlx-swift-lm"), | 50 | macOnly("MLXLLM", "mlx-swift-lm"), |
| 50 | macOnly("MLXLMCommon", "mlx-swift-lm"), | 51 | macOnly("MLXLMCommon", "mlx-swift-lm"), |
| 51 | macOnly("MLXHuggingFace", "mlx-swift-lm"), | 52 | macOnly("MLXHuggingFace", "mlx-swift-lm"), |
| 53 | + // Constrained decoding (XGrammar, C++): structured output and forced tool calls. | ||
| 54 | + macOnly("MLXGuidedGeneration", "mlx-swift-lm"), | ||
| 55 | + macOnly("MLX", "mlx-swift"), | ||
| 52 | macOnly("HuggingFace", "swift-huggingface"), | 56 | macOnly("HuggingFace", "swift-huggingface"), |
| 53 | macOnly("Tokenizers", "swift-transformers"), | 57 | macOnly("Tokenizers", "swift-transformers"), |
| 54 | ] | 58 | ] |
modified
Sources/RazorbillCore/Engine/InferenceEngine.swift +8 -1 | @@ -20,13 +20,20 @@ public protocol RequestSettingError: Error, CustomStringConvertible { | ||
| 20 | 20 | /// Everything a session needs to know before the first message. |
| 21 | 21 | public struct SessionSetup: Sendable, Equatable { |
| 22 | 22 | public var system: String |
| 23 | + /// Tools offered to the model through its chat template. | |
| 23 | 24 | public var tools: [ToolSpec] |
| 24 | 25 | public var generation: GenerationSettings |
| 26 | + /// What the answer must look like, enforced by constrained decoding; `nil` = free text. | |
| 27 | + public var constraint: OutputConstraint? | |
| 25 | 28 | |
| 26 | - public init(system: String, tools: [ToolSpec], generation: GenerationSettings) { | |
| 29 | + public init( | |
| 30 | + system: String, tools: [ToolSpec], generation: GenerationSettings, | |
| 31 | + constraint: OutputConstraint? = nil | |
| 32 | + ) { | |
| 27 | 33 | self.system = system |
| 28 | 34 | self.tools = tools |
| 29 | 35 | self.generation = generation |
| 36 | + self.constraint = constraint | |
| 30 | 37 | } |
| 31 | 38 | } |
| 32 | 39 | |
| @@ -20,13 +20,20 @@ public protocol RequestSettingError: Error, CustomStringConvertible { | |||
| 20 | /// Everything a session needs to know before the first message. | 20 | /// Everything a session needs to know before the first message. |
| 21 | public struct SessionSetup: Sendable, Equatable { | 21 | public struct SessionSetup: Sendable, Equatable { |
| 22 | public var system: String | 22 | public var system: String |
| 23 | + /// Tools offered to the model through its chat template. | ||
| 23 | public var tools: [ToolSpec] | 24 | public var tools: [ToolSpec] |
| 24 | public var generation: GenerationSettings | 25 | public var generation: GenerationSettings |
| 26 | + /// What the answer must look like, enforced by constrained decoding; `nil` = free text. | ||
| 27 | + public var constraint: OutputConstraint? | ||
| 25 | 28 | ||
| 26 | - public init(system: String, tools: [ToolSpec], generation: GenerationSettings) { | 29 | + public init( |
| 30 | + system: String, tools: [ToolSpec], generation: GenerationSettings, | ||
| 31 | + constraint: OutputConstraint? = nil | ||
| 32 | + ) { | ||
| 27 | self.system = system | 33 | self.system = system |
| 28 | self.tools = tools | 34 | self.tools = tools |
| 29 | self.generation = generation | 35 | self.generation = generation |
| 36 | + self.constraint = constraint | ||
| 30 | } | 37 | } |
| 31 | } | 38 | } |
| 32 | 39 | ||
added
Sources/RazorbillCore/Engine/OutputConstraint.swift +103 -0 | new file mode 100644 | ||
| @@ -0,0 +1,103 @@ | ||
| 1 | +/// What an answer must look like. Engines enforce it with constrained decoding: at each step only | |
| 2 | +/// the tokens that keep the output valid can be sampled. Reasoning models think freely first; the | |
| 3 | +/// constraint applies to the answer after their reasoning. | |
| 4 | +/// | |
| 5 | +/// ```swift | |
| 6 | +/// let json = OutputConstraint.jsonSchema(#"{"type": "object"}"#) | |
| 7 | +/// let call = OutputConstraint.toolCalls(ToolCallConstraint(tools: [weather], required: true)) | |
| 8 | +/// ``` | |
| 9 | +public enum OutputConstraint: Sendable, Equatable { | |
| 10 | + /// One JSON value matching this JSON Schema (as JSON text). | |
| 11 | + case jsonSchema(String) | |
| 12 | + /// Tool calls written in the model's own syntax, with arguments matching each tool's schema. | |
| 13 | + case toolCalls(ToolCallConstraint) | |
| 14 | + | |
| 15 | + /// The schema that accepts any JSON object (`response_format: json_object`). | |
| 16 | + public static let anyJSONObject = OutputConstraint.jsonSchema(#"{"type":"object"}"#) | |
| 17 | +} | |
| 18 | + | |
| 19 | +/// How tool calls are constrained. | |
| 20 | +public struct ToolCallConstraint: Sendable, Equatable { | |
| 21 | + /// The functions a call may use. | |
| 22 | + public var tools: [ToolSpec] | |
| 23 | + /// `true`: the answer is only tool calls (`tool_choice: required` or a named function). | |
| 24 | + /// `false`: the model may write text, but a call it starts must be valid (`strict` tools). | |
| 25 | + public var required: Bool | |
| 26 | + /// More than one call allowed. | |
| 27 | + public var parallel: Bool | |
| 28 | + | |
| 29 | + public init(tools: [ToolSpec], required: Bool, parallel: Bool = true) { | |
| 30 | + self.tools = tools | |
| 31 | + self.required = required | |
| 32 | + self.parallel = parallel | |
| 33 | + } | |
| 34 | +} | |
| 35 | + | |
| 36 | +/// The engine cannot enforce what the request asked (unsupported schema, tool-call syntax it | |
| 37 | +/// cannot express…): a 400 naming `parameter`. | |
| 38 | +public struct UnsupportedConstraint: RequestSettingError, Equatable { | |
| 39 | + public let parameter: String | |
| 40 | + public let reason: String | |
| 41 | + | |
| 42 | + public init(parameter: String, reason: String) { | |
| 43 | + self.parameter = parameter | |
| 44 | + self.reason = reason | |
| 45 | + } | |
| 46 | + | |
| 47 | + public var description: String { reason } | |
| 48 | +} | |
| 49 | + | |
| 50 | +/// JSON Schema keywords the constrained decoder (XGrammar) accepts but does not enforce; it only | |
| 51 | +/// logs a warning. Read from its `json_schema_converter.cc` (mlx-swift-lm 3.32.3). | |
| 52 | +public enum JSONSchemaSupport { | |
| 53 | + public static let unenforcedKeywords: Set<String> = [ | |
| 54 | + "not", "if", "then", "else", "dependentRequired", "dependentSchemas", "multipleOf", | |
| 55 | + "uniqueItems", "contains", "minContains", "maxContains", | |
| 56 | + ] | |
| 57 | + | |
| 58 | + /// Keys whose value maps names to schemas (the names themselves are not keywords). | |
| 59 | + static let schemaMaps: Set<String> = [ | |
| 60 | + "properties", "patternProperties", "$defs", "definitions", "dependentSchemas", | |
| 61 | + ] | |
| 62 | + | |
| 63 | + /// An unenforced keyword and where it was found. | |
| 64 | + public typealias Finding = (keyword: String, path: String) | |
| 65 | + | |
| 66 | + /// The first unenforced keyword in `schema` and where it is, e.g. `("uniqueItems", | |
| 67 | + /// "properties.tags")`; `nil` when the whole schema can be enforced. | |
| 68 | + public static func firstUnenforcedKeyword(in schema: ConfigValue) -> Finding? { | |
| 69 | + find(in: schema, path: "") | |
| 70 | + } | |
| 71 | + | |
| 72 | + private static func find(in value: ConfigValue, path: String) -> Finding? { | |
| 73 | + switch value { | |
| 74 | + case .map(let entries): | |
| 75 | + if let keyword = entries.keys.sorted().first(where: unenforcedKeywords.contains) { | |
| 76 | + return (keyword, path.isEmpty ? "(root)" : path) | |
| 77 | + } | |
| 78 | + return firstFinding(in: children(of: entries, path: path)) | |
| 79 | + case .list(let items): | |
| 80 | + return firstFinding(in: items.enumerated().map { ("\(path)[\($0)]", $1) }) | |
| 81 | + default: | |
| 82 | + return nil | |
| 83 | + } | |
| 84 | + } | |
| 85 | + | |
| 86 | + /// The sub-schemas of a schema object, with their paths. Under `properties`, `$defs`… the | |
| 87 | + /// keys are names, not keywords: their values are the sub-schemas. | |
| 88 | + private static func children( | |
| 89 | + of entries: [String: ConfigValue], path: String | |
| 90 | + ) -> [(String, ConfigValue)] { | |
| 91 | + entries.keys.sorted().flatMap { key -> [(String, ConfigValue)] in | |
| 92 | + let childPath = path.isEmpty ? key : "\(path).\(key)" | |
| 93 | + if schemaMaps.contains(key), case .map(let named)? = entries[key] { | |
| 94 | + return named.keys.sorted().map { ("\(childPath).\($0)", named[$0] ?? .null) } | |
| 95 | + } | |
| 96 | + return [(childPath, entries[key] ?? .null)] | |
| 97 | + } | |
| 98 | + } | |
| 99 | + | |
| 100 | + private static func firstFinding(in children: [(String, ConfigValue)]) -> Finding? { | |
| 101 | + children.lazy.compactMap { find(in: $0.1, path: $0.0) }.first | |
| 102 | + } | |
| 103 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | +/// What an answer must look like. Engines enforce it with constrained decoding: at each step only | ||
| 2 | +/// the tokens that keep the output valid can be sampled. Reasoning models think freely first; the | ||
| 3 | +/// constraint applies to the answer after their reasoning. | ||
| 4 | +/// | ||
| 5 | +/// ```swift | ||
| 6 | +/// let json = OutputConstraint.jsonSchema(#"{"type": "object"}"#) | ||
| 7 | +/// let call = OutputConstraint.toolCalls(ToolCallConstraint(tools: [weather], required: true)) | ||
| 8 | +/// ``` | ||
| 9 | +public enum OutputConstraint: Sendable, Equatable { | ||
| 10 | + /// One JSON value matching this JSON Schema (as JSON text). | ||
| 11 | + case jsonSchema(String) | ||
| 12 | + /// Tool calls written in the model's own syntax, with arguments matching each tool's schema. | ||
| 13 | + case toolCalls(ToolCallConstraint) | ||
| 14 | + | ||
| 15 | + /// The schema that accepts any JSON object (`response_format: json_object`). | ||
| 16 | + public static let anyJSONObject = OutputConstraint.jsonSchema(#"{"type":"object"}"#) | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +/// How tool calls are constrained. | ||
| 20 | +public struct ToolCallConstraint: Sendable, Equatable { | ||
| 21 | + /// The functions a call may use. | ||
| 22 | + public var tools: [ToolSpec] | ||
| 23 | + /// `true`: the answer is only tool calls (`tool_choice: required` or a named function). | ||
| 24 | + /// `false`: the model may write text, but a call it starts must be valid (`strict` tools). | ||
| 25 | + public var required: Bool | ||
| 26 | + /// More than one call allowed. | ||
| 27 | + public var parallel: Bool | ||
| 28 | + | ||
| 29 | + public init(tools: [ToolSpec], required: Bool, parallel: Bool = true) { | ||
| 30 | + self.tools = tools | ||
| 31 | + self.required = required | ||
| 32 | + self.parallel = parallel | ||
| 33 | + } | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/// The engine cannot enforce what the request asked (unsupported schema, tool-call syntax it | ||
| 37 | +/// cannot express…): a 400 naming `parameter`. | ||
| 38 | +public struct UnsupportedConstraint: RequestSettingError, Equatable { | ||
| 39 | + public let parameter: String | ||
| 40 | + public let reason: String | ||
| 41 | + | ||
| 42 | + public init(parameter: String, reason: String) { | ||
| 43 | + self.parameter = parameter | ||
| 44 | + self.reason = reason | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + public var description: String { reason } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// JSON Schema keywords the constrained decoder (XGrammar) accepts but does not enforce; it only | ||
| 51 | +/// logs a warning. Read from its `json_schema_converter.cc` (mlx-swift-lm 3.32.3). | ||
| 52 | +public enum JSONSchemaSupport { | ||
| 53 | + public static let unenforcedKeywords: Set<String> = [ | ||
| 54 | + "not", "if", "then", "else", "dependentRequired", "dependentSchemas", "multipleOf", | ||
| 55 | + "uniqueItems", "contains", "minContains", "maxContains", | ||
| 56 | + ] | ||
| 57 | + | ||
| 58 | + /// Keys whose value maps names to schemas (the names themselves are not keywords). | ||
| 59 | + static let schemaMaps: Set<String> = [ | ||
| 60 | + "properties", "patternProperties", "$defs", "definitions", "dependentSchemas", | ||
| 61 | + ] | ||
| 62 | + | ||
| 63 | + /// An unenforced keyword and where it was found. | ||
| 64 | + public typealias Finding = (keyword: String, path: String) | ||
| 65 | + | ||
| 66 | + /// The first unenforced keyword in `schema` and where it is, e.g. `("uniqueItems", | ||
| 67 | + /// "properties.tags")`; `nil` when the whole schema can be enforced. | ||
| 68 | + public static func firstUnenforcedKeyword(in schema: ConfigValue) -> Finding? { | ||
| 69 | + find(in: schema, path: "") | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + private static func find(in value: ConfigValue, path: String) -> Finding? { | ||
| 73 | + switch value { | ||
| 74 | + case .map(let entries): | ||
| 75 | + if let keyword = entries.keys.sorted().first(where: unenforcedKeywords.contains) { | ||
| 76 | + return (keyword, path.isEmpty ? "(root)" : path) | ||
| 77 | + } | ||
| 78 | + return firstFinding(in: children(of: entries, path: path)) | ||
| 79 | + case .list(let items): | ||
| 80 | + return firstFinding(in: items.enumerated().map { ("\(path)[\($0)]", $1) }) | ||
| 81 | + default: | ||
| 82 | + return nil | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + /// The sub-schemas of a schema object, with their paths. Under `properties`, `$defs`… the | ||
| 87 | + /// keys are names, not keywords: their values are the sub-schemas. | ||
| 88 | + private static func children( | ||
| 89 | + of entries: [String: ConfigValue], path: String | ||
| 90 | + ) -> [(String, ConfigValue)] { | ||
| 91 | + entries.keys.sorted().flatMap { key -> [(String, ConfigValue)] in | ||
| 92 | + let childPath = path.isEmpty ? key : "\(path).\(key)" | ||
| 93 | + if schemaMaps.contains(key), case .map(let named)? = entries[key] { | ||
| 94 | + return named.keys.sorted().map { ("\(childPath).\($0)", named[$0] ?? .null) } | ||
| 95 | + } | ||
| 96 | + return [(childPath, entries[key] ?? .null)] | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + private static func firstFinding(in children: [(String, ConfigValue)]) -> Finding? { | ||
| 101 | + children.lazy.compactMap { find(in: $0.1, path: $0.0) }.first | ||
| 102 | + } | ||
| 103 | +} | ||
added
Sources/RazorbillMLX/GrammarSupport.swift +246 -0 | new file mode 100644 | ||
| @@ -0,0 +1,246 @@ | ||
| 1 | +#if canImport(MLXGuidedGeneration) | |
| 2 | +import Foundation | |
| 3 | +import MLX | |
| 4 | +import MLXGuidedGeneration | |
| 5 | +import MLXLMCommon | |
| 6 | +import RazorbillCore | |
| 7 | + | |
| 8 | +/// Constrained decoding for one loaded model, on mlx-swift-lm's XGrammar bridge (ticket #38). | |
| 9 | +/// | |
| 10 | +/// The grammar is applied as a ``LogitProcessor`` inside the normal generation path, so sampling | |
| 11 | +/// (temperature, top-p), the thinking budget and tool-call parsing keep working. The grammar | |
| 12 | +/// tokenizer is built once per model. Grammars are compiled for each generation: the XGrammar | |
| 13 | +/// vendored by mlx-swift-lm 3.32.3 (v0.1.30) cannot fork a matcher, so a compiled grammar cannot be | |
| 14 | +/// shared between generations. | |
| 15 | +final class GrammarSupport: @unchecked Sendable { | |
| 16 | + private let lock = NSLock() | |
| 17 | + private var vocabulary: Vocabulary? | |
| 18 | + | |
| 19 | + /// What the grammar needs from the model's tokenizer. | |
| 20 | + struct Vocabulary: @unchecked Sendable { | |
| 21 | + let tokenizer: GrammarTokenizer | |
| 22 | + let size: Int | |
| 23 | + /// `</think>`'s id, when the model has one: the grammar starts after it. | |
| 24 | + let thinkEnd: Int? | |
| 25 | + /// -200 on whitespace-only tokens, 0 elsewhere, and their ids (see ``GrammarProcessor``). | |
| 26 | + let whitespaceBias: MLXArray | |
| 27 | + let whitespaceIDs: Set<Int> | |
| 28 | + } | |
| 29 | + | |
| 30 | + /// A processor factory enforcing `constraint` for one generation of `container`'s model. The | |
| 31 | + /// grammar is compiled here, so an invalid one fails before generation starts. | |
| 32 | + func processorFactory( | |
| 33 | + for constraint: OutputConstraint, container: ModelContainer, thinking: Bool | |
| 34 | + ) async throws -> @Sendable () -> any LogitProcessor { | |
| 35 | + let vocabulary = try await vocabulary(for: container) | |
| 36 | + let format = await container.configuration.toolCallFormat ?? .json | |
| 37 | + // `.gptOSS` stands in for `.json` in sessions without tools (see MLXEngine). | |
| 38 | + let (source, parameter) = try Self.grammarSource(constraint, toolCallFormat: format) | |
| 39 | + let compiled = try Self.compile(source, vocabulary: vocabulary, parameter: parameter) | |
| 40 | + let startsActive = !(thinking && vocabulary.thinkEnd != nil) | |
| 41 | + let first = OneShot(compiled) | |
| 42 | + return { | |
| 43 | + // Normally called once per generation; a second call compiles again. | |
| 44 | + let constraint = | |
| 45 | + first.take() | |
| 46 | + ?? (try? Self.compile(source, vocabulary: vocabulary, parameter: parameter)) | |
| 47 | + return GrammarProcessor( | |
| 48 | + constraint: constraint, vocabulary: vocabulary, active: startsActive) | |
| 49 | + } | |
| 50 | + } | |
| 51 | + | |
| 52 | + private func vocabulary(for container: ModelContainer) async throws -> Vocabulary { | |
| 53 | + if let vocabulary = lock.withLock({ self.vocabulary }) { return vocabulary } | |
| 54 | + let tokenizer = await container.tokenizer | |
| 55 | + let extracted = TokenizerVocabExtractor.extractForGrammar(from: tokenizer) | |
| 56 | + let eos = tokenizer.eosTokenId ?? 0 | |
| 57 | + let whitespace = WhitespaceTokenBias.compute(tokenizer: tokenizer) | |
| 58 | + let vocabulary = Vocabulary( | |
| 59 | + tokenizer: try GrammarTokenizer( | |
| 60 | + vocab: extracted.vocab, vocabType: extracted.vocabType, eosTokenId: Int32(eos)), | |
| 61 | + size: extracted.vocab.count, thinkEnd: tokenizer.convertTokenToId("</think>"), | |
| 62 | + whitespaceBias: whitespace.bias, whitespaceIDs: whitespace.tokenIDs) | |
| 63 | + lock.withLock { self.vocabulary = vocabulary } | |
| 64 | + return vocabulary | |
| 65 | + } | |
| 66 | + | |
| 67 | + static func compile( | |
| 68 | + _ source: GrammarSource, vocabulary: Vocabulary, parameter: String | |
| 69 | + ) throws -> GrammarConstraint { | |
| 70 | + do { | |
| 71 | + switch source { | |
| 72 | + case .jsonSchema(let schema): | |
| 73 | + return try GrammarConstraint(tokenizer: vocabulary.tokenizer, jsonSchema: schema) | |
| 74 | + case .structuralTag(let tag): | |
| 75 | + return try GrammarConstraint(tokenizer: vocabulary.tokenizer, structuralTag: tag) | |
| 76 | + } | |
| 77 | + } catch { | |
| 78 | + throw UnsupportedConstraint( | |
| 79 | + parameter: parameter, reason: "the constrained decoder rejected it: \(error)") | |
| 80 | + } | |
| 81 | + } | |
| 82 | + | |
| 83 | + enum GrammarSource: Sendable { | |
| 84 | + case jsonSchema(String) | |
| 85 | + case structuralTag(String) | |
| 86 | + } | |
| 87 | + | |
| 88 | + /// The grammar for a constraint and the request field to blame when it fails. | |
| 89 | + static func grammarSource( | |
| 90 | + _ constraint: OutputConstraint, toolCallFormat: ToolCallFormat | |
| 91 | + ) throws -> (GrammarSource, String) { | |
| 92 | + switch constraint { | |
| 93 | + case .jsonSchema(let schema): | |
| 94 | + return (.jsonSchema(schema), "response_format") | |
| 95 | + case .toolCalls(let calls): | |
| 96 | + guard toolCallFormat == .json || toolCallFormat == .gptOSS else { | |
| 97 | + throw UnsupportedConstraint( | |
| 98 | + parameter: "tool_choice", | |
| 99 | + reason: "constrained tool calls are not supported for this model's tool-call " | |
| 100 | + + "syntax (\(toolCallFormat.rawValue)); only the <tool_call> JSON syntax " | |
| 101 | + + "(Qwen, Hermes…) is") | |
| 102 | + } | |
| 103 | + return (.structuralTag(ToolCallGrammar.structuralTag(calls)), "tools") | |
| 104 | + } | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 108 | +/// A value handed out once. | |
| 109 | +private final class OneShot<Value>: @unchecked Sendable { | |
| 110 | + private let lock = NSLock() | |
| 111 | + private var value: Value? | |
| 112 | + | |
| 113 | + init(_ value: Value) { self.value = value } | |
| 114 | + | |
| 115 | + func take() -> Value? { | |
| 116 | + lock.withLock { | |
| 117 | + defer { value = nil } | |
| 118 | + return value | |
| 119 | + } | |
| 120 | + } | |
| 121 | +} | |
| 122 | + | |
| 123 | +/// XGrammar structural tags for tool calls written as `<tool_call>\n{"name": …, "arguments": …}\n</tool_call>`. | |
| 124 | +enum ToolCallGrammar { | |
| 125 | + static func structuralTag(_ calls: ToolCallConstraint) -> String { | |
| 126 | + let schemas: [ConfigValue] = calls.tools.map { tool in | |
| 127 | + .map([ | |
| 128 | + "type": .string("object"), | |
| 129 | + "properties": .map([ | |
| 130 | + "name": .map(["const": .string(tool.name)]), | |
| 131 | + "arguments": tool.parameters, | |
| 132 | + ]), | |
| 133 | + "required": .list([.string("name"), .string("arguments")]), | |
| 134 | + "additionalProperties": .bool(false), | |
| 135 | + ]) | |
| 136 | + } | |
| 137 | + let schema = schemas.count == 1 ? schemas[0] : .map(["anyOf": .list(schemas)]) | |
| 138 | + let tag: ConfigValue = .map([ | |
| 139 | + "type": .string("tag"), "begin": .string("<tool_call>\n"), | |
| 140 | + "content": .map(["type": .string("json_schema"), "json_schema": schema]), | |
| 141 | + "end": .string("\n</tool_call>"), | |
| 142 | + ]) | |
| 143 | + let format: ConfigValue = | |
| 144 | + calls.required | |
| 145 | + ? .map([ | |
| 146 | + "type": .string("tags_with_separator"), "tags": .list([tag]), | |
| 147 | + "separator": .string("\n"), "at_least_one": .bool(true), | |
| 148 | + "stop_after_first": .bool(!calls.parallel), | |
| 149 | + ]) | |
| 150 | + : .map([ | |
| 151 | + "type": .string("triggered_tags"), "triggers": .list([.string("<tool_call>")]), | |
| 152 | + "tags": .list([tag]), "at_least_one": .bool(false), | |
| 153 | + "stop_after_first": .bool(!calls.parallel), | |
| 154 | + ]) | |
| 155 | + return ConfigValue.map(["type": .string("structural_tag"), "format": format]).jsonString | |
| 156 | + } | |
| 157 | +} | |
| 158 | + | |
| 159 | +/// Masks the logits to what the grammar accepts and advances it with each sampled token. Inactive | |
| 160 | +/// until `</think>` when the model thinks first. | |
| 161 | +/// | |
| 162 | +/// JSON grammars accept any amount of whitespace, and small models can loop on it until | |
| 163 | +/// `max_tokens` (seen with Qwen3-0.6B inside a forced tool call). After 3 whitespace tokens in a | |
| 164 | +/// row, whitespace gets a -200 bias for the rest of the generation; finite, so a place where the | |
| 165 | +/// grammar allows only whitespace still gets it. | |
| 166 | +final class GrammarProcessor: LogitProcessor, @unchecked Sendable { | |
| 167 | + /// `nil` when a recompilation failed: nothing is constrained. | |
| 168 | + let constraint: GrammarConstraint? | |
| 169 | + let vocabulary: GrammarSupport.Vocabulary | |
| 170 | + private(set) var active: Bool | |
| 171 | + private var whitespaceRun: WhitespaceRunTracker | |
| 172 | + /// The grammar refused a token (should not happen): stop constraining rather than crash. | |
| 173 | + private(set) var broken = false | |
| 174 | + /// The grammar is complete (its end token was sampled). The generator samples one token | |
| 175 | + /// ahead, so it may still pass tokens after this: they are not the grammar's business. | |
| 176 | + private(set) var finished = false | |
| 177 | + | |
| 178 | + init(constraint: GrammarConstraint?, vocabulary: GrammarSupport.Vocabulary, active: Bool) { | |
| 179 | + self.constraint = constraint | |
| 180 | + self.vocabulary = vocabulary | |
| 181 | + self.active = active | |
| 182 | + whitespaceRun = WhitespaceRunTracker(whitespaceTokenIDs: vocabulary.whitespaceIDs) | |
| 183 | + } | |
| 184 | + | |
| 185 | + func prompt(_ prompt: MLXArray) {} | |
| 186 | + | |
| 187 | + func process(logits: MLXArray) -> MLXArray { | |
| 188 | + guard active, !broken, !finished, let mask = try? constraint?.computeMask(), mask.needsApply | |
| 189 | + else { | |
| 190 | + return logits | |
| 191 | + } | |
| 192 | + let dimension = logits.dim(-1) | |
| 193 | + var masked = | |
| 194 | + logits + Self.additiveMask(mask.mask, vocabSize: vocabulary.size, dimension: dimension) | |
| 195 | + if whitespaceRun.isActive { | |
| 196 | + masked += Self.fitted(vocabulary.whitespaceBias, to: dimension) | |
| 197 | + } | |
| 198 | + return masked | |
| 199 | + } | |
| 200 | + | |
| 201 | + /// `array` cut or zero-padded to `dimension` (the model may have more logits than tokens). | |
| 202 | + static func fitted(_ array: MLXArray, to dimension: Int) -> MLXArray { | |
| 203 | + let count = array.dim(0) | |
| 204 | + if count == dimension { return array } | |
| 205 | + if count > dimension { return array[0 ..< dimension] } | |
| 206 | + return concatenated([array, MLXArray.zeros([dimension - count])]) | |
| 207 | + } | |
| 208 | + | |
| 209 | + /// The packed bitmask (one bit per token) as 0 / -inf, built on the GPU: a Swift loop over a | |
| 210 | + /// 150k-token vocabulary at every step costs more than the forward pass of a small model. | |
| 211 | + static func additiveMask(_ words: [Int32], vocabSize: Int, dimension: Int) -> MLXArray { | |
| 212 | + let packed = MLXArray(words.map { UInt32(bitPattern: $0) }) | |
| 213 | + let shifts = MLXArray((0 ..< 32).map { UInt32($0) }) | |
| 214 | + let bits = ((packed.expandedDimensions(axis: 1) >> shifts) & UInt32(1)).flattened() | |
| 215 | + let count = min(vocabSize, dimension, bits.dim(0)) | |
| 216 | + var additive = MLX.where(bits[0 ..< count] .== UInt32(1), Float(0), -Float.infinity) | |
| 217 | + if count < dimension { | |
| 218 | + additive = concatenated([ | |
| 219 | + additive, MLXArray.full([dimension - count], values: MLXArray(-Float.infinity)), | |
| 220 | + ]) | |
| 221 | + } | |
| 222 | + return additive | |
| 223 | + } | |
| 224 | + | |
| 225 | + func didSample(token: MLXArray) { | |
| 226 | + let id = token.item(Int.self) | |
| 227 | + guard active else { | |
| 228 | + if id == vocabulary.thinkEnd { active = true } | |
| 229 | + return | |
| 230 | + } | |
| 231 | + guard !broken, !finished, let constraint else { return } | |
| 232 | + _ = whitespaceRun.record(tokenID: id) | |
| 233 | + do { | |
| 234 | + finished = try constraint.commitToken(Int32(id)).isTerminated | |
| 235 | + } catch { | |
| 236 | + broken = true | |
| 237 | + } | |
| 238 | + } | |
| 239 | + | |
| 240 | + /// Only speculative decoding copies processors, and razorbill does not use it. XGrammar | |
| 241 | + /// v0.1.30 cannot fork a matcher, so the copy shares this one's grammar state. | |
| 242 | + func copy() -> GrammarProcessor { | |
| 243 | + GrammarProcessor(constraint: constraint, vocabulary: vocabulary, active: active) | |
| 244 | + } | |
| 245 | +} | |
| 246 | +#endif | |
| new file mode 100644 | |||
| @@ -0,0 +1,246 @@ | |||
| 1 | +#if canImport(MLXGuidedGeneration) | ||
| 2 | +import Foundation | ||
| 3 | +import MLX | ||
| 4 | +import MLXGuidedGeneration | ||
| 5 | +import MLXLMCommon | ||
| 6 | +import RazorbillCore | ||
| 7 | + | ||
| 8 | +/// Constrained decoding for one loaded model, on mlx-swift-lm's XGrammar bridge (ticket #38). | ||
| 9 | +/// | ||
| 10 | +/// The grammar is applied as a ``LogitProcessor`` inside the normal generation path, so sampling | ||
| 11 | +/// (temperature, top-p), the thinking budget and tool-call parsing keep working. The grammar | ||
| 12 | +/// tokenizer is built once per model. Grammars are compiled for each generation: the XGrammar | ||
| 13 | +/// vendored by mlx-swift-lm 3.32.3 (v0.1.30) cannot fork a matcher, so a compiled grammar cannot be | ||
| 14 | +/// shared between generations. | ||
| 15 | +final class GrammarSupport: @unchecked Sendable { | ||
| 16 | + private let lock = NSLock() | ||
| 17 | + private var vocabulary: Vocabulary? | ||
| 18 | + | ||
| 19 | + /// What the grammar needs from the model's tokenizer. | ||
| 20 | + struct Vocabulary: @unchecked Sendable { | ||
| 21 | + let tokenizer: GrammarTokenizer | ||
| 22 | + let size: Int | ||
| 23 | + /// `</think>`'s id, when the model has one: the grammar starts after it. | ||
| 24 | + let thinkEnd: Int? | ||
| 25 | + /// -200 on whitespace-only tokens, 0 elsewhere, and their ids (see ``GrammarProcessor``). | ||
| 26 | + let whitespaceBias: MLXArray | ||
| 27 | + let whitespaceIDs: Set<Int> | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + /// A processor factory enforcing `constraint` for one generation of `container`'s model. The | ||
| 31 | + /// grammar is compiled here, so an invalid one fails before generation starts. | ||
| 32 | + func processorFactory( | ||
| 33 | + for constraint: OutputConstraint, container: ModelContainer, thinking: Bool | ||
| 34 | + ) async throws -> @Sendable () -> any LogitProcessor { | ||
| 35 | + let vocabulary = try await vocabulary(for: container) | ||
| 36 | + let format = await container.configuration.toolCallFormat ?? .json | ||
| 37 | + // `.gptOSS` stands in for `.json` in sessions without tools (see MLXEngine). | ||
| 38 | + let (source, parameter) = try Self.grammarSource(constraint, toolCallFormat: format) | ||
| 39 | + let compiled = try Self.compile(source, vocabulary: vocabulary, parameter: parameter) | ||
| 40 | + let startsActive = !(thinking && vocabulary.thinkEnd != nil) | ||
| 41 | + let first = OneShot(compiled) | ||
| 42 | + return { | ||
| 43 | + // Normally called once per generation; a second call compiles again. | ||
| 44 | + let constraint = | ||
| 45 | + first.take() | ||
| 46 | + ?? (try? Self.compile(source, vocabulary: vocabulary, parameter: parameter)) | ||
| 47 | + return GrammarProcessor( | ||
| 48 | + constraint: constraint, vocabulary: vocabulary, active: startsActive) | ||
| 49 | + } | ||
| 50 | + } | ||
| 51 | + | ||
| 52 | + private func vocabulary(for container: ModelContainer) async throws -> Vocabulary { | ||
| 53 | + if let vocabulary = lock.withLock({ self.vocabulary }) { return vocabulary } | ||
| 54 | + let tokenizer = await container.tokenizer | ||
| 55 | + let extracted = TokenizerVocabExtractor.extractForGrammar(from: tokenizer) | ||
| 56 | + let eos = tokenizer.eosTokenId ?? 0 | ||
| 57 | + let whitespace = WhitespaceTokenBias.compute(tokenizer: tokenizer) | ||
| 58 | + let vocabulary = Vocabulary( | ||
| 59 | + tokenizer: try GrammarTokenizer( | ||
| 60 | + vocab: extracted.vocab, vocabType: extracted.vocabType, eosTokenId: Int32(eos)), | ||
| 61 | + size: extracted.vocab.count, thinkEnd: tokenizer.convertTokenToId("</think>"), | ||
| 62 | + whitespaceBias: whitespace.bias, whitespaceIDs: whitespace.tokenIDs) | ||
| 63 | + lock.withLock { self.vocabulary = vocabulary } | ||
| 64 | + return vocabulary | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + static func compile( | ||
| 68 | + _ source: GrammarSource, vocabulary: Vocabulary, parameter: String | ||
| 69 | + ) throws -> GrammarConstraint { | ||
| 70 | + do { | ||
| 71 | + switch source { | ||
| 72 | + case .jsonSchema(let schema): | ||
| 73 | + return try GrammarConstraint(tokenizer: vocabulary.tokenizer, jsonSchema: schema) | ||
| 74 | + case .structuralTag(let tag): | ||
| 75 | + return try GrammarConstraint(tokenizer: vocabulary.tokenizer, structuralTag: tag) | ||
| 76 | + } | ||
| 77 | + } catch { | ||
| 78 | + throw UnsupportedConstraint( | ||
| 79 | + parameter: parameter, reason: "the constrained decoder rejected it: \(error)") | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + enum GrammarSource: Sendable { | ||
| 84 | + case jsonSchema(String) | ||
| 85 | + case structuralTag(String) | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + /// The grammar for a constraint and the request field to blame when it fails. | ||
| 89 | + static func grammarSource( | ||
| 90 | + _ constraint: OutputConstraint, toolCallFormat: ToolCallFormat | ||
| 91 | + ) throws -> (GrammarSource, String) { | ||
| 92 | + switch constraint { | ||
| 93 | + case .jsonSchema(let schema): | ||
| 94 | + return (.jsonSchema(schema), "response_format") | ||
| 95 | + case .toolCalls(let calls): | ||
| 96 | + guard toolCallFormat == .json || toolCallFormat == .gptOSS else { | ||
| 97 | + throw UnsupportedConstraint( | ||
| 98 | + parameter: "tool_choice", | ||
| 99 | + reason: "constrained tool calls are not supported for this model's tool-call " | ||
| 100 | + + "syntax (\(toolCallFormat.rawValue)); only the <tool_call> JSON syntax " | ||
| 101 | + + "(Qwen, Hermes…) is") | ||
| 102 | + } | ||
| 103 | + return (.structuralTag(ToolCallGrammar.structuralTag(calls)), "tools") | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// A value handed out once. | ||
| 109 | +private final class OneShot<Value>: @unchecked Sendable { | ||
| 110 | + private let lock = NSLock() | ||
| 111 | + private var value: Value? | ||
| 112 | + | ||
| 113 | + init(_ value: Value) { self.value = value } | ||
| 114 | + | ||
| 115 | + func take() -> Value? { | ||
| 116 | + lock.withLock { | ||
| 117 | + defer { value = nil } | ||
| 118 | + return value | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// XGrammar structural tags for tool calls written as `<tool_call>\n{"name": …, "arguments": …}\n</tool_call>`. | ||
| 124 | +enum ToolCallGrammar { | ||
| 125 | + static func structuralTag(_ calls: ToolCallConstraint) -> String { | ||
| 126 | + let schemas: [ConfigValue] = calls.tools.map { tool in | ||
| 127 | + .map([ | ||
| 128 | + "type": .string("object"), | ||
| 129 | + "properties": .map([ | ||
| 130 | + "name": .map(["const": .string(tool.name)]), | ||
| 131 | + "arguments": tool.parameters, | ||
| 132 | + ]), | ||
| 133 | + "required": .list([.string("name"), .string("arguments")]), | ||
| 134 | + "additionalProperties": .bool(false), | ||
| 135 | + ]) | ||
| 136 | + } | ||
| 137 | + let schema = schemas.count == 1 ? schemas[0] : .map(["anyOf": .list(schemas)]) | ||
| 138 | + let tag: ConfigValue = .map([ | ||
| 139 | + "type": .string("tag"), "begin": .string("<tool_call>\n"), | ||
| 140 | + "content": .map(["type": .string("json_schema"), "json_schema": schema]), | ||
| 141 | + "end": .string("\n</tool_call>"), | ||
| 142 | + ]) | ||
| 143 | + let format: ConfigValue = | ||
| 144 | + calls.required | ||
| 145 | + ? .map([ | ||
| 146 | + "type": .string("tags_with_separator"), "tags": .list([tag]), | ||
| 147 | + "separator": .string("\n"), "at_least_one": .bool(true), | ||
| 148 | + "stop_after_first": .bool(!calls.parallel), | ||
| 149 | + ]) | ||
| 150 | + : .map([ | ||
| 151 | + "type": .string("triggered_tags"), "triggers": .list([.string("<tool_call>")]), | ||
| 152 | + "tags": .list([tag]), "at_least_one": .bool(false), | ||
| 153 | + "stop_after_first": .bool(!calls.parallel), | ||
| 154 | + ]) | ||
| 155 | + return ConfigValue.map(["type": .string("structural_tag"), "format": format]).jsonString | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/// Masks the logits to what the grammar accepts and advances it with each sampled token. Inactive | ||
| 160 | +/// until `</think>` when the model thinks first. | ||
| 161 | +/// | ||
| 162 | +/// JSON grammars accept any amount of whitespace, and small models can loop on it until | ||
| 163 | +/// `max_tokens` (seen with Qwen3-0.6B inside a forced tool call). After 3 whitespace tokens in a | ||
| 164 | +/// row, whitespace gets a -200 bias for the rest of the generation; finite, so a place where the | ||
| 165 | +/// grammar allows only whitespace still gets it. | ||
| 166 | +final class GrammarProcessor: LogitProcessor, @unchecked Sendable { | ||
| 167 | + /// `nil` when a recompilation failed: nothing is constrained. | ||
| 168 | + let constraint: GrammarConstraint? | ||
| 169 | + let vocabulary: GrammarSupport.Vocabulary | ||
| 170 | + private(set) var active: Bool | ||
| 171 | + private var whitespaceRun: WhitespaceRunTracker | ||
| 172 | + /// The grammar refused a token (should not happen): stop constraining rather than crash. | ||
| 173 | + private(set) var broken = false | ||
| 174 | + /// The grammar is complete (its end token was sampled). The generator samples one token | ||
| 175 | + /// ahead, so it may still pass tokens after this: they are not the grammar's business. | ||
| 176 | + private(set) var finished = false | ||
| 177 | + | ||
| 178 | + init(constraint: GrammarConstraint?, vocabulary: GrammarSupport.Vocabulary, active: Bool) { | ||
| 179 | + self.constraint = constraint | ||
| 180 | + self.vocabulary = vocabulary | ||
| 181 | + self.active = active | ||
| 182 | + whitespaceRun = WhitespaceRunTracker(whitespaceTokenIDs: vocabulary.whitespaceIDs) | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + func prompt(_ prompt: MLXArray) {} | ||
| 186 | + | ||
| 187 | + func process(logits: MLXArray) -> MLXArray { | ||
| 188 | + guard active, !broken, !finished, let mask = try? constraint?.computeMask(), mask.needsApply | ||
| 189 | + else { | ||
| 190 | + return logits | ||
| 191 | + } | ||
| 192 | + let dimension = logits.dim(-1) | ||
| 193 | + var masked = | ||
| 194 | + logits + Self.additiveMask(mask.mask, vocabSize: vocabulary.size, dimension: dimension) | ||
| 195 | + if whitespaceRun.isActive { | ||
| 196 | + masked += Self.fitted(vocabulary.whitespaceBias, to: dimension) | ||
| 197 | + } | ||
| 198 | + return masked | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + /// `array` cut or zero-padded to `dimension` (the model may have more logits than tokens). | ||
| 202 | + static func fitted(_ array: MLXArray, to dimension: Int) -> MLXArray { | ||
| 203 | + let count = array.dim(0) | ||
| 204 | + if count == dimension { return array } | ||
| 205 | + if count > dimension { return array[0 ..< dimension] } | ||
| 206 | + return concatenated([array, MLXArray.zeros([dimension - count])]) | ||
| 207 | + } | ||
| 208 | + | ||
| 209 | + /// The packed bitmask (one bit per token) as 0 / -inf, built on the GPU: a Swift loop over a | ||
| 210 | + /// 150k-token vocabulary at every step costs more than the forward pass of a small model. | ||
| 211 | + static func additiveMask(_ words: [Int32], vocabSize: Int, dimension: Int) -> MLXArray { | ||
| 212 | + let packed = MLXArray(words.map { UInt32(bitPattern: $0) }) | ||
| 213 | + let shifts = MLXArray((0 ..< 32).map { UInt32($0) }) | ||
| 214 | + let bits = ((packed.expandedDimensions(axis: 1) >> shifts) & UInt32(1)).flattened() | ||
| 215 | + let count = min(vocabSize, dimension, bits.dim(0)) | ||
| 216 | + var additive = MLX.where(bits[0 ..< count] .== UInt32(1), Float(0), -Float.infinity) | ||
| 217 | + if count < dimension { | ||
| 218 | + additive = concatenated([ | ||
| 219 | + additive, MLXArray.full([dimension - count], values: MLXArray(-Float.infinity)), | ||
| 220 | + ]) | ||
| 221 | + } | ||
| 222 | + return additive | ||
| 223 | + } | ||
| 224 | + | ||
| 225 | + func didSample(token: MLXArray) { | ||
| 226 | + let id = token.item(Int.self) | ||
| 227 | + guard active else { | ||
| 228 | + if id == vocabulary.thinkEnd { active = true } | ||
| 229 | + return | ||
| 230 | + } | ||
| 231 | + guard !broken, !finished, let constraint else { return } | ||
| 232 | + _ = whitespaceRun.record(tokenID: id) | ||
| 233 | + do { | ||
| 234 | + finished = try constraint.commitToken(Int32(id)).isTerminated | ||
| 235 | + } catch { | ||
| 236 | + broken = true | ||
| 237 | + } | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + /// Only speculative decoding copies processors, and razorbill does not use it. XGrammar | ||
| 241 | + /// v0.1.30 cannot fork a matcher, so the copy shares this one's grammar state. | ||
| 242 | + func copy() -> GrammarProcessor { | ||
| 243 | + GrammarProcessor(constraint: constraint, vocabulary: vocabulary, active: active) | ||
| 244 | + } | ||
| 245 | +} | ||
| 246 | +#endif | ||
modified
Sources/RazorbillMLX/MLXEngine.swift +38 -2 | @@ -22,6 +22,9 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 22 | 22 | private let store: ModelStore |
| 23 | 23 | private let lock = NSLock() |
| 24 | 24 | private var container: ModelContainer? |
| 25 | + private var grammars = GrammarSupport() | |
| 26 | + /// The model's own tool-call format, read at load time (see ``makeSession(_:)``). | |
| 27 | + private var nativeToolCallFormat: ToolCallFormat? | |
| 25 | 28 | |
| 26 | 29 | public init(store: ModelStore = ModelStore()) { |
| 27 | 30 | self.store = store |
| @@ -45,7 +48,12 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 45 | 48 | _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void |
| 46 | 49 | ) async throws { |
| 47 | 50 | let loaded = try await loadContainer(model, offline: offline, progress: progress) |
| 48 | - lock.withLock { container = loaded } | |
| 51 | + let format = await loaded.configuration.toolCallFormat | |
| 52 | + lock.withLock { | |
| 53 | + container = loaded | |
| 54 | + nativeToolCallFormat = format | |
| 55 | + grammars = GrammarSupport() // built for this model's tokenizer | |
| 56 | + } | |
| 49 | 57 | } |
| 50 | 58 | |
| 51 | 59 | public func download( |
| @@ -65,6 +73,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 65 | 73 | |
| 66 | 74 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 67 | 75 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } |
| 76 | + await useToolCallFormat(for: setup, in: container) | |
| 68 | 77 | var parameters = GenerateParameters( |
| 69 | 78 | maxTokens: setup.generation.maxTokens, |
| 70 | 79 | temperature: Float(setup.generation.temperature), |
| @@ -72,11 +81,16 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 72 | 81 | parameters.seed = setup.generation.seed |
| 73 | 82 | parameters.presencePenalty = setup.generation.presencePenalty.map(Float.init) |
| 74 | 83 | parameters.frequencyPenalty = setup.generation.frequencyPenalty.map(Float.init) |
| 84 | + if setup.tools.isEmpty { | |
| 85 | + // No tools offered: nothing to recover, and the recovery scanner would hold back any | |
| 86 | + // answer starting with "{" (a JSON answer would then arrive in one piece). | |
| 87 | + parameters.toolCallPolicy.recovery = .disabled | |
| 88 | + } | |
| 75 | 89 | let session = ChatSession( |
| 76 | 90 | container, |
| 77 | 91 | instructions: setup.system.isEmpty ? nil : setup.system, |
| 78 | 92 | generateParameters: parameters, |
| 79 | - components: try await Self.components(container, generation: setup.generation), | |
| 93 | + components: try await components(container, setup: setup), | |
| 80 | 94 | // Read by Qwen3-style chat templates; ignored by the others. |
| 81 | 95 | additionalContext: ["enable_thinking": setup.generation.thinking], |
| 82 | 96 | tools: setup.tools.isEmpty ? nil : setup.tools.map(MLXConversion.toolSpec)) |
| @@ -85,6 +99,28 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 85 | 99 | return MLXSession(session: session, startsInsideThinking: opensThinking) |
| 86 | 100 | } |
| 87 | 101 | |
| 102 | + /// The `.json` tool-call parser (Qwen, Hermes…) holds back any answer starting with "{" in case | |
| 103 | + /// it is a bare-JSON tool call, so a JSON answer would stream in one piece. Without tools there | |
| 104 | + /// is no call to find: use `.gptOSS`, the same `<tool_call>` parser without that fallback. The | |
| 105 | + /// server runs one generation per model at a time, so switching per session is safe. | |
| 106 | + private func useToolCallFormat(for setup: SessionSetup, in container: ModelContainer) async { | |
| 107 | + let native = lock.withLock { nativeToolCallFormat } | |
| 108 | + let format: ToolCallFormat? = | |
| 109 | + setup.tools.isEmpty && (native ?? .json) == .json ? .gptOSS : native | |
| 110 | + await container.update { $0.configuration.toolCallFormat = format } | |
| 111 | + } | |
| 112 | + | |
| 113 | + /// The thinking budget, then the output constraint, when the setup asks for them. | |
| 114 | + private func components( | |
| 115 | + _ container: ModelContainer, setup: SessionSetup | |
| 116 | + ) async throws -> GenerationComponents { | |
| 117 | + let components = try await Self.components(container, generation: setup.generation) | |
| 118 | + guard let constraint = setup.constraint else { return components } | |
| 119 | + let factory = try await lock.withLock { grammars }.processorFactory( | |
| 120 | + for: constraint, container: container, thinking: setup.generation.thinking) | |
| 121 | + return components.appendingLogitProcessor(factory) | |
| 122 | + } | |
| 123 | + | |
| 88 | 124 | /// The thinking budget, when one is set and the model thinks. |
| 89 | 125 | static func components( |
| 90 | 126 | _ container: ModelContainer, generation: GenerationSettings |
| @@ -22,6 +22,9 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 22 | private let store: ModelStore | 22 | private let store: ModelStore |
| 23 | private let lock = NSLock() | 23 | private let lock = NSLock() |
| 24 | private var container: ModelContainer? | 24 | private var container: ModelContainer? |
| 25 | + private var grammars = GrammarSupport() | ||
| 26 | + /// The model's own tool-call format, read at load time (see ``makeSession(_:)``). | ||
| 27 | + private var nativeToolCallFormat: ToolCallFormat? | ||
| 25 | 28 | ||
| 26 | public init(store: ModelStore = ModelStore()) { | 29 | public init(store: ModelStore = ModelStore()) { |
| 27 | self.store = store | 30 | self.store = store |
| @@ -45,7 +48,12 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 45 | _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void | 48 | _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void |
| 46 | ) async throws { | 49 | ) async throws { |
| 47 | let loaded = try await loadContainer(model, offline: offline, progress: progress) | 50 | let loaded = try await loadContainer(model, offline: offline, progress: progress) |
| 48 | - lock.withLock { container = loaded } | 51 | + let format = await loaded.configuration.toolCallFormat |
| 52 | + lock.withLock { | ||
| 53 | + container = loaded | ||
| 54 | + nativeToolCallFormat = format | ||
| 55 | + grammars = GrammarSupport() // built for this model's tokenizer | ||
| 56 | + } | ||
| 49 | } | 57 | } |
| 50 | 58 | ||
| 51 | public func download( | 59 | public func download( |
| @@ -65,6 +73,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 65 | 73 | ||
| 66 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 74 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 67 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } | 75 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } |
| 76 | + await useToolCallFormat(for: setup, in: container) | ||
| 68 | var parameters = GenerateParameters( | 77 | var parameters = GenerateParameters( |
| 69 | maxTokens: setup.generation.maxTokens, | 78 | maxTokens: setup.generation.maxTokens, |
| 70 | temperature: Float(setup.generation.temperature), | 79 | temperature: Float(setup.generation.temperature), |
| @@ -72,11 +81,16 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 72 | parameters.seed = setup.generation.seed | 81 | parameters.seed = setup.generation.seed |
| 73 | parameters.presencePenalty = setup.generation.presencePenalty.map(Float.init) | 82 | parameters.presencePenalty = setup.generation.presencePenalty.map(Float.init) |
| 74 | parameters.frequencyPenalty = setup.generation.frequencyPenalty.map(Float.init) | 83 | parameters.frequencyPenalty = setup.generation.frequencyPenalty.map(Float.init) |
| 84 | + if setup.tools.isEmpty { | ||
| 85 | + // No tools offered: nothing to recover, and the recovery scanner would hold back any | ||
| 86 | + // answer starting with "{" (a JSON answer would then arrive in one piece). | ||
| 87 | + parameters.toolCallPolicy.recovery = .disabled | ||
| 88 | + } | ||
| 75 | let session = ChatSession( | 89 | let session = ChatSession( |
| 76 | container, | 90 | container, |
| 77 | instructions: setup.system.isEmpty ? nil : setup.system, | 91 | instructions: setup.system.isEmpty ? nil : setup.system, |
| 78 | generateParameters: parameters, | 92 | generateParameters: parameters, |
| 79 | - components: try await Self.components(container, generation: setup.generation), | 93 | + components: try await components(container, setup: setup), |
| 80 | // Read by Qwen3-style chat templates; ignored by the others. | 94 | // Read by Qwen3-style chat templates; ignored by the others. |
| 81 | additionalContext: ["enable_thinking": setup.generation.thinking], | 95 | additionalContext: ["enable_thinking": setup.generation.thinking], |
| 82 | tools: setup.tools.isEmpty ? nil : setup.tools.map(MLXConversion.toolSpec)) | 96 | tools: setup.tools.isEmpty ? nil : setup.tools.map(MLXConversion.toolSpec)) |
| @@ -85,6 +99,28 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 85 | return MLXSession(session: session, startsInsideThinking: opensThinking) | 99 | return MLXSession(session: session, startsInsideThinking: opensThinking) |
| 86 | } | 100 | } |
| 87 | 101 | ||
| 102 | + /// The `.json` tool-call parser (Qwen, Hermes…) holds back any answer starting with "{" in case | ||
| 103 | + /// it is a bare-JSON tool call, so a JSON answer would stream in one piece. Without tools there | ||
| 104 | + /// is no call to find: use `.gptOSS`, the same `<tool_call>` parser without that fallback. The | ||
| 105 | + /// server runs one generation per model at a time, so switching per session is safe. | ||
| 106 | + private func useToolCallFormat(for setup: SessionSetup, in container: ModelContainer) async { | ||
| 107 | + let native = lock.withLock { nativeToolCallFormat } | ||
| 108 | + let format: ToolCallFormat? = | ||
| 109 | + setup.tools.isEmpty && (native ?? .json) == .json ? .gptOSS : native | ||
| 110 | + await container.update { $0.configuration.toolCallFormat = format } | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + /// The thinking budget, then the output constraint, when the setup asks for them. | ||
| 114 | + private func components( | ||
| 115 | + _ container: ModelContainer, setup: SessionSetup | ||
| 116 | + ) async throws -> GenerationComponents { | ||
| 117 | + let components = try await Self.components(container, generation: setup.generation) | ||
| 118 | + guard let constraint = setup.constraint else { return components } | ||
| 119 | + let factory = try await lock.withLock { grammars }.processorFactory( | ||
| 120 | + for: constraint, container: container, thinking: setup.generation.thinking) | ||
| 121 | + return components.appendingLogitProcessor(factory) | ||
| 122 | + } | ||
| 123 | + | ||
| 88 | /// The thinking budget, when one is set and the model thinks. | 124 | /// The thinking budget, when one is set and the model thinks. |
| 89 | static func components( | 125 | static func components( |
| 90 | _ container: ModelContainer, generation: GenerationSettings | 126 | _ container: ModelContainer, generation: GenerationSettings |
modified
Sources/RazorbillServer/Chat/ChatCompletionRequest.swift +10 -6 | @@ -19,7 +19,10 @@ struct ChatCompletionRequest: Decodable, Sendable { | ||
| 19 | 19 | var stream: Bool? |
| 20 | 20 | var streamOptions: StreamOptions? |
| 21 | 21 | var logprobs: Bool? |
| 22 | - var tools: ConfigValue? | |
| 22 | + var tools: [WireTool]? | |
| 23 | + /// `"none"`, `"auto"`, `"required"` or `{"type": "function", "function": {"name": …}}`. | |
| 24 | + var toolChoice: ConfigValue? | |
| 25 | + var parallelToolCalls: Bool? | |
| 23 | 26 | var responseFormat: ConfigValue? |
| 24 | 27 | /// `none` / `minimal` turn thinking off; `low` / `medium` / `high` turn it on. |
| 25 | 28 | var reasoningEffort: String? |
| @@ -39,6 +42,8 @@ struct ChatCompletionRequest: Decodable, Sendable { | ||
| 39 | 42 | case presencePenalty = "presence_penalty" |
| 40 | 43 | case frequencyPenalty = "frequency_penalty" |
| 41 | 44 | case responseFormat = "response_format" |
| 45 | + case toolChoice = "tool_choice" | |
| 46 | + case parallelToolCalls = "parallel_tool_calls" | |
| 42 | 47 | case streamOptions = "stream_options" |
| 43 | 48 | case reasoningEffort = "reasoning_effort" |
| 44 | 49 | case chatTemplateKwargs = "chat_template_kwargs" |
| @@ -142,6 +147,8 @@ struct ChatPlan: Sendable { | ||
| 142 | 147 | var stream: Bool |
| 143 | 148 | /// `stream_options.include_usage`: a last chunk with the token counts. |
| 144 | 149 | var includeUsage = false |
| 150 | + /// Tools offered to the model, the output constraint and the call limit. | |
| 151 | + var output = OutputPlan() | |
| 145 | 152 | |
| 146 | 153 | /// The settings for `model`: its defaults, then the client's values, then its locks. |
| 147 | 154 | func settings(for model: ResolvedModel) -> GenerationSettings { |
| @@ -170,6 +177,7 @@ extension ChatCompletionRequest { | ||
| 170 | 177 | abs($0) <= 2 |
| 171 | 178 | } |
| 172 | 179 | try checkReasoningSwitches() |
| 180 | + let output = try outputPlan() | |
| 173 | 181 | return ChatPlan( |
| 174 | 182 | model: model, |
| 175 | 183 | messages: try messages.enumerated().map { try Self.message($1, at: $0) }, |
| @@ -179,7 +187,7 @@ extension ChatCompletionRequest { | ||
| 179 | 187 | seed: seed.map { UInt64(bitPattern: $0) }, |
| 180 | 188 | presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, |
| 181 | 189 | stops: stops, stream: stream ?? false, |
| 182 | - includeUsage: streamOptions?.includeUsage ?? false) | |
| 190 | + includeUsage: streamOptions?.includeUsage ?? false, output: output) | |
| 183 | 191 | } |
| 184 | 192 | |
| 185 | 193 | /// Whether the request turns thinking on or off: `chat_template_kwargs.enable_thinking` first, |
| @@ -205,10 +213,6 @@ extension ChatCompletionRequest { | ||
| 205 | 213 | private func checkUnsupported() throws { |
| 206 | 214 | try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)") |
| 207 | 215 | try require(logprobs != true, "logprobs", "is not supported yet") |
| 208 | - try require(tools == nil, "tools", "is not supported yet (function calling)") | |
| 209 | - let format = responseFormat?["type"]?.stringValue ?? "text" | |
| 210 | - try require( | |
| 211 | - format == "text", "response_format", "only accepts {\"type\": \"text\"} for now") | |
| 212 | 216 | } |
| 213 | 217 | |
| 214 | 218 | static func message(_ wire: WireMessage, at index: Int) throws -> ChatMessage { |
| @@ -19,7 +19,10 @@ struct ChatCompletionRequest: Decodable, Sendable { | |||
| 19 | var stream: Bool? | 19 | var stream: Bool? |
| 20 | var streamOptions: StreamOptions? | 20 | var streamOptions: StreamOptions? |
| 21 | var logprobs: Bool? | 21 | var logprobs: Bool? |
| 22 | - var tools: ConfigValue? | 22 | + var tools: [WireTool]? |
| 23 | + /// `"none"`, `"auto"`, `"required"` or `{"type": "function", "function": {"name": …}}`. | ||
| 24 | + var toolChoice: ConfigValue? | ||
| 25 | + var parallelToolCalls: Bool? | ||
| 23 | var responseFormat: ConfigValue? | 26 | var responseFormat: ConfigValue? |
| 24 | /// `none` / `minimal` turn thinking off; `low` / `medium` / `high` turn it on. | 27 | /// `none` / `minimal` turn thinking off; `low` / `medium` / `high` turn it on. |
| 25 | var reasoningEffort: String? | 28 | var reasoningEffort: String? |
| @@ -39,6 +42,8 @@ struct ChatCompletionRequest: Decodable, Sendable { | |||
| 39 | case presencePenalty = "presence_penalty" | 42 | case presencePenalty = "presence_penalty" |
| 40 | case frequencyPenalty = "frequency_penalty" | 43 | case frequencyPenalty = "frequency_penalty" |
| 41 | case responseFormat = "response_format" | 44 | case responseFormat = "response_format" |
| 45 | + case toolChoice = "tool_choice" | ||
| 46 | + case parallelToolCalls = "parallel_tool_calls" | ||
| 42 | case streamOptions = "stream_options" | 47 | case streamOptions = "stream_options" |
| 43 | case reasoningEffort = "reasoning_effort" | 48 | case reasoningEffort = "reasoning_effort" |
| 44 | case chatTemplateKwargs = "chat_template_kwargs" | 49 | case chatTemplateKwargs = "chat_template_kwargs" |
| @@ -142,6 +147,8 @@ struct ChatPlan: Sendable { | |||
| 142 | var stream: Bool | 147 | var stream: Bool |
| 143 | /// `stream_options.include_usage`: a last chunk with the token counts. | 148 | /// `stream_options.include_usage`: a last chunk with the token counts. |
| 144 | var includeUsage = false | 149 | var includeUsage = false |
| 150 | + /// Tools offered to the model, the output constraint and the call limit. | ||
| 151 | + var output = OutputPlan() | ||
| 145 | 152 | ||
| 146 | /// The settings for `model`: its defaults, then the client's values, then its locks. | 153 | /// The settings for `model`: its defaults, then the client's values, then its locks. |
| 147 | func settings(for model: ResolvedModel) -> GenerationSettings { | 154 | func settings(for model: ResolvedModel) -> GenerationSettings { |
| @@ -170,6 +177,7 @@ extension ChatCompletionRequest { | |||
| 170 | abs($0) <= 2 | 177 | abs($0) <= 2 |
| 171 | } | 178 | } |
| 172 | try checkReasoningSwitches() | 179 | try checkReasoningSwitches() |
| 180 | + let output = try outputPlan() | ||
| 173 | return ChatPlan( | 181 | return ChatPlan( |
| 174 | model: model, | 182 | model: model, |
| 175 | messages: try messages.enumerated().map { try Self.message($1, at: $0) }, | 183 | messages: try messages.enumerated().map { try Self.message($1, at: $0) }, |
| @@ -179,7 +187,7 @@ extension ChatCompletionRequest { | |||
| 179 | seed: seed.map { UInt64(bitPattern: $0) }, | 187 | seed: seed.map { UInt64(bitPattern: $0) }, |
| 180 | presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, | 188 | presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, |
| 181 | stops: stops, stream: stream ?? false, | 189 | stops: stops, stream: stream ?? false, |
| 182 | - includeUsage: streamOptions?.includeUsage ?? false) | 190 | + includeUsage: streamOptions?.includeUsage ?? false, output: output) |
| 183 | } | 191 | } |
| 184 | 192 | ||
| 185 | /// Whether the request turns thinking on or off: `chat_template_kwargs.enable_thinking` first, | 193 | /// Whether the request turns thinking on or off: `chat_template_kwargs.enable_thinking` first, |
| @@ -205,10 +213,6 @@ extension ChatCompletionRequest { | |||
| 205 | private func checkUnsupported() throws { | 213 | private func checkUnsupported() throws { |
| 206 | try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)") | 214 | try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)") |
| 207 | try require(logprobs != true, "logprobs", "is not supported yet") | 215 | try require(logprobs != true, "logprobs", "is not supported yet") |
| 208 | - try require(tools == nil, "tools", "is not supported yet (function calling)") | ||
| 209 | - let format = responseFormat?["type"]?.stringValue ?? "text" | ||
| 210 | - try require( | ||
| 211 | - format == "text", "response_format", "only accepts {\"type\": \"text\"} for now") | ||
| 212 | } | 216 | } |
| 213 | 217 | ||
| 214 | static func message(_ wire: WireMessage, at index: Int) throws -> ChatMessage { | 218 | static func message(_ wire: WireMessage, at index: Int) throws -> ChatMessage { |
modified
Sources/RazorbillServer/Chat/ChatCompletionRoute.swift +4 -2 | @@ -145,10 +145,12 @@ struct ChatCompletionRoute { | ||
| 145 | 145 | ) async throws -> AsyncThrowingStream<CompletionPiece, Error> { |
| 146 | 146 | let settings = plan.settings(for: lease.model) |
| 147 | 147 | let session = try await lease.engine.makeSession( |
| 148 | - SessionSetup(system: "", tools: [], generation: settings)) | |
| 148 | + SessionSetup( | |
| 149 | + system: "", tools: plan.output.tools, generation: settings, | |
| 150 | + constraint: plan.output.constraint)) | |
| 149 | 151 | return CompletionStream.pieces( |
| 150 | 152 | from: session.send(plan.messages), stops: plan.stops, |
| 151 | - showReasoning: settings.showReasoning) | |
| 153 | + showReasoning: settings.showReasoning, maxToolCalls: plan.output.maxToolCalls) | |
| 152 | 154 | } |
| 153 | 155 | |
| 154 | 156 | /// `chatcmpl-` followed by 24 random hexadecimal digits. |
| @@ -145,10 +145,12 @@ struct ChatCompletionRoute { | |||
| 145 | ) async throws -> AsyncThrowingStream<CompletionPiece, Error> { | 145 | ) async throws -> AsyncThrowingStream<CompletionPiece, Error> { |
| 146 | let settings = plan.settings(for: lease.model) | 146 | let settings = plan.settings(for: lease.model) |
| 147 | let session = try await lease.engine.makeSession( | 147 | let session = try await lease.engine.makeSession( |
| 148 | - SessionSetup(system: "", tools: [], generation: settings)) | 148 | + SessionSetup( |
| 149 | + system: "", tools: plan.output.tools, generation: settings, | ||
| 150 | + constraint: plan.output.constraint)) | ||
| 149 | return CompletionStream.pieces( | 151 | return CompletionStream.pieces( |
| 150 | from: session.send(plan.messages), stops: plan.stops, | 152 | from: session.send(plan.messages), stops: plan.stops, |
| 151 | - showReasoning: settings.showReasoning) | 153 | + showReasoning: settings.showReasoning, maxToolCalls: plan.output.maxToolCalls) |
| 152 | } | 154 | } |
| 153 | 155 | ||
| 154 | /// `chatcmpl-` followed by 24 random hexadecimal digits. | 156 | /// `chatcmpl-` followed by 24 random hexadecimal digits. |
modified
Sources/RazorbillServer/Chat/CompletionStream.swift +8 -2 | @@ -53,13 +53,14 @@ enum CompletionStream { | ||
| 53 | 53 | /// With `showReasoning` false, reasoning is counted in `usage` but not passed on. |
| 54 | 54 | static func pieces( |
| 55 | 55 | from events: AsyncThrowingStream<EngineEvent, Error>, stops: [String], |
| 56 | - showReasoning: Bool = true | |
| 56 | + showReasoning: Bool = true, maxToolCalls: Int? = nil | |
| 57 | 57 | ) -> AsyncThrowingStream<CompletionPiece, Error> { |
| 58 | 58 | AsyncThrowingStream { continuation in |
| 59 | 59 | let task = Task { |
| 60 | 60 | do { |
| 61 | 61 | var state = State( |
| 62 | - filter: StopSequenceFilter(stops), showReasoning: showReasoning) | |
| 62 | + filter: StopSequenceFilter(stops), showReasoning: showReasoning, | |
| 63 | + maxToolCalls: maxToolCalls) | |
| 63 | 64 | events: for try await event in events { |
| 64 | 65 | for piece in state.consume(event) { continuation.yield(piece) } |
| 65 | 66 | if state.filter.isStopped { break events } |
| @@ -78,6 +79,9 @@ enum CompletionStream { | ||
| 78 | 79 | struct State { |
| 79 | 80 | var filter: StopSequenceFilter |
| 80 | 81 | var showReasoning = true |
| 82 | + /// Calls beyond this are dropped (`parallel_tool_calls: false`). | |
| 83 | + var maxToolCalls: Int? | |
| 84 | + var toolCallCount = 0 | |
| 81 | 85 | var stats: GenerationStats? |
| 82 | 86 | var calledTools = false |
| 83 | 87 | var textPieces = 0 |
| @@ -102,6 +106,8 @@ enum CompletionStream { | ||
| 102 | 106 | return showReasoning ? [.reasoning(text)] : [] |
| 103 | 107 | case .toolCall(let call): |
| 104 | 108 | calledTools = true |
| 109 | + toolCallCount += 1 | |
| 110 | + if let maxToolCalls, toolCallCount > maxToolCalls { return [] } | |
| 105 | 111 | return [.toolCall(call)] |
| 106 | 112 | case .stats(let stats): |
| 107 | 113 | self.stats = stats |
| @@ -53,13 +53,14 @@ enum CompletionStream { | |||
| 53 | /// With `showReasoning` false, reasoning is counted in `usage` but not passed on. | 53 | /// With `showReasoning` false, reasoning is counted in `usage` but not passed on. |
| 54 | static func pieces( | 54 | static func pieces( |
| 55 | from events: AsyncThrowingStream<EngineEvent, Error>, stops: [String], | 55 | from events: AsyncThrowingStream<EngineEvent, Error>, stops: [String], |
| 56 | - showReasoning: Bool = true | 56 | + showReasoning: Bool = true, maxToolCalls: Int? = nil |
| 57 | ) -> AsyncThrowingStream<CompletionPiece, Error> { | 57 | ) -> AsyncThrowingStream<CompletionPiece, Error> { |
| 58 | AsyncThrowingStream { continuation in | 58 | AsyncThrowingStream { continuation in |
| 59 | let task = Task { | 59 | let task = Task { |
| 60 | do { | 60 | do { |
| 61 | var state = State( | 61 | var state = State( |
| 62 | - filter: StopSequenceFilter(stops), showReasoning: showReasoning) | 62 | + filter: StopSequenceFilter(stops), showReasoning: showReasoning, |
| 63 | + maxToolCalls: maxToolCalls) | ||
| 63 | events: for try await event in events { | 64 | events: for try await event in events { |
| 64 | for piece in state.consume(event) { continuation.yield(piece) } | 65 | for piece in state.consume(event) { continuation.yield(piece) } |
| 65 | if state.filter.isStopped { break events } | 66 | if state.filter.isStopped { break events } |
| @@ -78,6 +79,9 @@ enum CompletionStream { | |||
| 78 | struct State { | 79 | struct State { |
| 79 | var filter: StopSequenceFilter | 80 | var filter: StopSequenceFilter |
| 80 | var showReasoning = true | 81 | var showReasoning = true |
| 82 | + /// Calls beyond this are dropped (`parallel_tool_calls: false`). | ||
| 83 | + var maxToolCalls: Int? | ||
| 84 | + var toolCallCount = 0 | ||
| 81 | var stats: GenerationStats? | 85 | var stats: GenerationStats? |
| 82 | var calledTools = false | 86 | var calledTools = false |
| 83 | var textPieces = 0 | 87 | var textPieces = 0 |
| @@ -102,6 +106,8 @@ enum CompletionStream { | |||
| 102 | return showReasoning ? [.reasoning(text)] : [] | 106 | return showReasoning ? [.reasoning(text)] : [] |
| 103 | case .toolCall(let call): | 107 | case .toolCall(let call): |
| 104 | calledTools = true | 108 | calledTools = true |
| 109 | + toolCallCount += 1 | ||
| 110 | + if let maxToolCalls, toolCallCount > maxToolCalls { return [] } | ||
| 105 | return [.toolCall(call)] | 111 | return [.toolCall(call)] |
| 106 | case .stats(let stats): | 112 | case .stats(let stats): |
| 107 | self.stats = stats | 113 | self.stats = stats |
added
Sources/RazorbillServer/Chat/ToolsAndFormats.swift +170 -0 | new file mode 100644 | ||
| @@ -0,0 +1,170 @@ | ||
| 1 | +import Foundation | |
| 2 | +import RazorbillCore | |
| 3 | + | |
| 4 | +/// One entry of `tools`. | |
| 5 | +struct WireTool: Decodable, Sendable { | |
| 6 | + let type: String | |
| 7 | + let function: WireFunction | |
| 8 | +} | |
| 9 | + | |
| 10 | +/// A function the model may call. | |
| 11 | +struct WireFunction: Decodable, Sendable { | |
| 12 | + let name: String | |
| 13 | + var description: String? | |
| 14 | + /// JSON Schema of the arguments; an empty object schema when absent. | |
| 15 | + var parameters: ConfigValue? | |
| 16 | + /// The arguments must match `parameters` exactly (constrained decoding). | |
| 17 | + var strict: Bool? | |
| 18 | +} | |
| 19 | + | |
| 20 | +/// What the request asks of the answer's form: tools offered, constraint, call limit. | |
| 21 | +struct OutputPlan: Sendable, Equatable { | |
| 22 | + var tools: [ToolSpec] = [] | |
| 23 | + var constraint: OutputConstraint? | |
| 24 | + /// `parallel_tool_calls: false` keeps only the first call. | |
| 25 | + var maxToolCalls: Int? | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// `tool_choice`, decoded. | |
| 29 | +enum ToolChoice: Equatable { | |
| 30 | + case none, auto, required | |
| 31 | + case named(String) | |
| 32 | +} | |
| 33 | + | |
| 34 | +extension ChatCompletionRequest { | |
| 35 | + /// Tools (#40, #41) and `response_format` (#39) turned into an ``OutputPlan``. | |
| 36 | + func outputPlan() throws -> OutputPlan { | |
| 37 | + let tools = try toolSpecs() | |
| 38 | + let choice = try toolChoiceValue(tools: tools) | |
| 39 | + // Forced calls are one call unless parallel calls are asked for explicitly: small models | |
| 40 | + // otherwise repeat the call until max_tokens, and the truncated last call loses them all. | |
| 41 | + let parallel = | |
| 42 | + switch choice { | |
| 43 | + case .named: false | |
| 44 | + case .required: parallelToolCalls ?? false | |
| 45 | + default: parallelToolCalls ?? true | |
| 46 | + } | |
| 47 | + var plan = OutputPlan(maxToolCalls: parallel ? nil : 1) | |
| 48 | + guard choice != .none else { | |
| 49 | + plan.constraint = try formatConstraint() | |
| 50 | + return plan | |
| 51 | + } | |
| 52 | + plan.tools = tools | |
| 53 | + let strict = (self.tools ?? []).contains { $0.function.strict == true } | |
| 54 | + let toolConstraint: OutputConstraint? = | |
| 55 | + switch choice { | |
| 56 | + case .required: | |
| 57 | + .toolCalls(ToolCallConstraint(tools: tools, required: true, parallel: parallel)) | |
| 58 | + case .named(let name): | |
| 59 | + .toolCalls( | |
| 60 | + ToolCallConstraint( | |
| 61 | + tools: tools.filter { $0.name == name }, required: true, parallel: parallel) | |
| 62 | + ) | |
| 63 | + case .auto where strict: | |
| 64 | + .toolCalls(ToolCallConstraint(tools: tools, required: false, parallel: parallel)) | |
| 65 | + default: nil | |
| 66 | + } | |
| 67 | + let format = try formatConstraint() | |
| 68 | + if toolConstraint != nil && format != nil { | |
| 69 | + throw invalid( | |
| 70 | + "response_format", | |
| 71 | + "cannot be combined with tool_choice required, a named tool or strict tools") | |
| 72 | + } | |
| 73 | + plan.constraint = toolConstraint ?? format | |
| 74 | + return plan | |
| 75 | + } | |
| 76 | + | |
| 77 | + /// `tools` checked and converted: functions only, valid unique names, object schemas. | |
| 78 | + func toolSpecs() throws -> [ToolSpec] { | |
| 79 | + var names: Set<String> = [] | |
| 80 | + return try (tools ?? []).enumerated().map { index, tool in | |
| 81 | + let path = "tools[\(index)]" | |
| 82 | + guard tool.type == "function" else { | |
| 83 | + throw invalid("\(path).type", "must be \"function\"") | |
| 84 | + } | |
| 85 | + let name = tool.function.name | |
| 86 | + guard Self.isValidToolName(name) else { | |
| 87 | + throw invalid("\(path).function.name", "must be 1-64 letters, digits, _ or -") | |
| 88 | + } | |
| 89 | + guard names.insert(name).inserted else { | |
| 90 | + throw invalid("\(path).function.name", "duplicate tool name \(name)") | |
| 91 | + } | |
| 92 | + let parameters = | |
| 93 | + tool.function.parameters | |
| 94 | + ?? .map(["type": .string("object"), "properties": .map([:])]) | |
| 95 | + guard case .map = parameters else { | |
| 96 | + throw invalid("\(path).function.parameters", "must be a JSON Schema object") | |
| 97 | + } | |
| 98 | + if tool.function.strict == true { | |
| 99 | + try checkEnforceable(parameters, param: "\(path).function.parameters") | |
| 100 | + } | |
| 101 | + return ToolSpec( | |
| 102 | + name: name, description: tool.function.description ?? "", parameters: parameters) | |
| 103 | + } | |
| 104 | + } | |
| 105 | + | |
| 106 | + func toolChoiceValue(tools: [ToolSpec]) throws -> ToolChoice { | |
| 107 | + let choice: ToolChoice | |
| 108 | + switch toolChoice { | |
| 109 | + case nil: choice = tools.isEmpty ? .none : .auto | |
| 110 | + case .string("none")?: choice = .none | |
| 111 | + case .string("auto")?: choice = .auto | |
| 112 | + case .string("required")?: choice = .required | |
| 113 | + case let value? where value["type"]?.stringValue == "function": | |
| 114 | + guard let name = value["function"]?["name"]?.stringValue else { | |
| 115 | + throw invalid("tool_choice", "needs function.name") | |
| 116 | + } | |
| 117 | + guard tools.contains(where: { $0.name == name }) else { | |
| 118 | + throw invalid("tool_choice", "names \(name), which is not in tools") | |
| 119 | + } | |
| 120 | + choice = .named(name) | |
| 121 | + default: | |
| 122 | + throw invalid( | |
| 123 | + "tool_choice", "must be none, auto, required or {\"type\": \"function\", …}") | |
| 124 | + } | |
| 125 | + if tools.isEmpty, choice == .required { | |
| 126 | + throw invalid("tool_choice", "is required but no tools were given") | |
| 127 | + } | |
| 128 | + return choice | |
| 129 | + } | |
| 130 | + | |
| 131 | + /// `response_format`: `text` (no constraint), `json_object`, or `json_schema`. | |
| 132 | + func formatConstraint() throws -> OutputConstraint? { | |
| 133 | + guard let format = responseFormat else { return nil } | |
| 134 | + switch format["type"]?.stringValue { | |
| 135 | + case "text": return nil | |
| 136 | + case "json_object": return .anyJSONObject | |
| 137 | + case "json_schema": | |
| 138 | + guard case .map(let schema)? = format["json_schema"]?["schema"] else { | |
| 139 | + throw invalid("response_format.json_schema.schema", "must be a JSON Schema object") | |
| 140 | + } | |
| 141 | + if format["json_schema"]?["strict"]?.boolValue == true { | |
| 142 | + try checkEnforceable(.map(schema), param: "response_format.json_schema.schema") | |
| 143 | + } | |
| 144 | + return .jsonSchema(ConfigValue.map(schema).jsonString) | |
| 145 | + default: | |
| 146 | + throw invalid("response_format", "type must be text, json_object or json_schema") | |
| 147 | + } | |
| 148 | + } | |
| 149 | + | |
| 150 | + /// A strict schema must not rely on keywords the decoder cannot enforce. | |
| 151 | + private func checkEnforceable(_ schema: ConfigValue, param: String) throws { | |
| 152 | + if let found = JSONSchemaSupport.firstUnenforcedKeyword(in: schema) { | |
| 153 | + throw invalid( | |
| 154 | + param, | |
| 155 | + "uses '\(found.keyword)' (at \(found.path)), which strict mode cannot enforce; " | |
| 156 | + + "remove it or set strict to false") | |
| 157 | + } | |
| 158 | + } | |
| 159 | + | |
| 160 | + static func isValidToolName(_ name: String) -> Bool { | |
| 161 | + (1 ... 64).contains(name.count) | |
| 162 | + && name.allSatisfy { | |
| 163 | + $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_" || $0 == "-") | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + private func invalid(_ param: String, _ message: String) -> OpenAIError { | |
| 168 | + OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | |
| 169 | + } | |
| 170 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,170 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import RazorbillCore | ||
| 3 | + | ||
| 4 | +/// One entry of `tools`. | ||
| 5 | +struct WireTool: Decodable, Sendable { | ||
| 6 | + let type: String | ||
| 7 | + let function: WireFunction | ||
| 8 | +} | ||
| 9 | + | ||
| 10 | +/// A function the model may call. | ||
| 11 | +struct WireFunction: Decodable, Sendable { | ||
| 12 | + let name: String | ||
| 13 | + var description: String? | ||
| 14 | + /// JSON Schema of the arguments; an empty object schema when absent. | ||
| 15 | + var parameters: ConfigValue? | ||
| 16 | + /// The arguments must match `parameters` exactly (constrained decoding). | ||
| 17 | + var strict: Bool? | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// What the request asks of the answer's form: tools offered, constraint, call limit. | ||
| 21 | +struct OutputPlan: Sendable, Equatable { | ||
| 22 | + var tools: [ToolSpec] = [] | ||
| 23 | + var constraint: OutputConstraint? | ||
| 24 | + /// `parallel_tool_calls: false` keeps only the first call. | ||
| 25 | + var maxToolCalls: Int? | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +/// `tool_choice`, decoded. | ||
| 29 | +enum ToolChoice: Equatable { | ||
| 30 | + case none, auto, required | ||
| 31 | + case named(String) | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +extension ChatCompletionRequest { | ||
| 35 | + /// Tools (#40, #41) and `response_format` (#39) turned into an ``OutputPlan``. | ||
| 36 | + func outputPlan() throws -> OutputPlan { | ||
| 37 | + let tools = try toolSpecs() | ||
| 38 | + let choice = try toolChoiceValue(tools: tools) | ||
| 39 | + // Forced calls are one call unless parallel calls are asked for explicitly: small models | ||
| 40 | + // otherwise repeat the call until max_tokens, and the truncated last call loses them all. | ||
| 41 | + let parallel = | ||
| 42 | + switch choice { | ||
| 43 | + case .named: false | ||
| 44 | + case .required: parallelToolCalls ?? false | ||
| 45 | + default: parallelToolCalls ?? true | ||
| 46 | + } | ||
| 47 | + var plan = OutputPlan(maxToolCalls: parallel ? nil : 1) | ||
| 48 | + guard choice != .none else { | ||
| 49 | + plan.constraint = try formatConstraint() | ||
| 50 | + return plan | ||
| 51 | + } | ||
| 52 | + plan.tools = tools | ||
| 53 | + let strict = (self.tools ?? []).contains { $0.function.strict == true } | ||
| 54 | + let toolConstraint: OutputConstraint? = | ||
| 55 | + switch choice { | ||
| 56 | + case .required: | ||
| 57 | + .toolCalls(ToolCallConstraint(tools: tools, required: true, parallel: parallel)) | ||
| 58 | + case .named(let name): | ||
| 59 | + .toolCalls( | ||
| 60 | + ToolCallConstraint( | ||
| 61 | + tools: tools.filter { $0.name == name }, required: true, parallel: parallel) | ||
| 62 | + ) | ||
| 63 | + case .auto where strict: | ||
| 64 | + .toolCalls(ToolCallConstraint(tools: tools, required: false, parallel: parallel)) | ||
| 65 | + default: nil | ||
| 66 | + } | ||
| 67 | + let format = try formatConstraint() | ||
| 68 | + if toolConstraint != nil && format != nil { | ||
| 69 | + throw invalid( | ||
| 70 | + "response_format", | ||
| 71 | + "cannot be combined with tool_choice required, a named tool or strict tools") | ||
| 72 | + } | ||
| 73 | + plan.constraint = toolConstraint ?? format | ||
| 74 | + return plan | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + /// `tools` checked and converted: functions only, valid unique names, object schemas. | ||
| 78 | + func toolSpecs() throws -> [ToolSpec] { | ||
| 79 | + var names: Set<String> = [] | ||
| 80 | + return try (tools ?? []).enumerated().map { index, tool in | ||
| 81 | + let path = "tools[\(index)]" | ||
| 82 | + guard tool.type == "function" else { | ||
| 83 | + throw invalid("\(path).type", "must be \"function\"") | ||
| 84 | + } | ||
| 85 | + let name = tool.function.name | ||
| 86 | + guard Self.isValidToolName(name) else { | ||
| 87 | + throw invalid("\(path).function.name", "must be 1-64 letters, digits, _ or -") | ||
| 88 | + } | ||
| 89 | + guard names.insert(name).inserted else { | ||
| 90 | + throw invalid("\(path).function.name", "duplicate tool name \(name)") | ||
| 91 | + } | ||
| 92 | + let parameters = | ||
| 93 | + tool.function.parameters | ||
| 94 | + ?? .map(["type": .string("object"), "properties": .map([:])]) | ||
| 95 | + guard case .map = parameters else { | ||
| 96 | + throw invalid("\(path).function.parameters", "must be a JSON Schema object") | ||
| 97 | + } | ||
| 98 | + if tool.function.strict == true { | ||
| 99 | + try checkEnforceable(parameters, param: "\(path).function.parameters") | ||
| 100 | + } | ||
| 101 | + return ToolSpec( | ||
| 102 | + name: name, description: tool.function.description ?? "", parameters: parameters) | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + func toolChoiceValue(tools: [ToolSpec]) throws -> ToolChoice { | ||
| 107 | + let choice: ToolChoice | ||
| 108 | + switch toolChoice { | ||
| 109 | + case nil: choice = tools.isEmpty ? .none : .auto | ||
| 110 | + case .string("none")?: choice = .none | ||
| 111 | + case .string("auto")?: choice = .auto | ||
| 112 | + case .string("required")?: choice = .required | ||
| 113 | + case let value? where value["type"]?.stringValue == "function": | ||
| 114 | + guard let name = value["function"]?["name"]?.stringValue else { | ||
| 115 | + throw invalid("tool_choice", "needs function.name") | ||
| 116 | + } | ||
| 117 | + guard tools.contains(where: { $0.name == name }) else { | ||
| 118 | + throw invalid("tool_choice", "names \(name), which is not in tools") | ||
| 119 | + } | ||
| 120 | + choice = .named(name) | ||
| 121 | + default: | ||
| 122 | + throw invalid( | ||
| 123 | + "tool_choice", "must be none, auto, required or {\"type\": \"function\", …}") | ||
| 124 | + } | ||
| 125 | + if tools.isEmpty, choice == .required { | ||
| 126 | + throw invalid("tool_choice", "is required but no tools were given") | ||
| 127 | + } | ||
| 128 | + return choice | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + /// `response_format`: `text` (no constraint), `json_object`, or `json_schema`. | ||
| 132 | + func formatConstraint() throws -> OutputConstraint? { | ||
| 133 | + guard let format = responseFormat else { return nil } | ||
| 134 | + switch format["type"]?.stringValue { | ||
| 135 | + case "text": return nil | ||
| 136 | + case "json_object": return .anyJSONObject | ||
| 137 | + case "json_schema": | ||
| 138 | + guard case .map(let schema)? = format["json_schema"]?["schema"] else { | ||
| 139 | + throw invalid("response_format.json_schema.schema", "must be a JSON Schema object") | ||
| 140 | + } | ||
| 141 | + if format["json_schema"]?["strict"]?.boolValue == true { | ||
| 142 | + try checkEnforceable(.map(schema), param: "response_format.json_schema.schema") | ||
| 143 | + } | ||
| 144 | + return .jsonSchema(ConfigValue.map(schema).jsonString) | ||
| 145 | + default: | ||
| 146 | + throw invalid("response_format", "type must be text, json_object or json_schema") | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + | ||
| 150 | + /// A strict schema must not rely on keywords the decoder cannot enforce. | ||
| 151 | + private func checkEnforceable(_ schema: ConfigValue, param: String) throws { | ||
| 152 | + if let found = JSONSchemaSupport.firstUnenforcedKeyword(in: schema) { | ||
| 153 | + throw invalid( | ||
| 154 | + param, | ||
| 155 | + "uses '\(found.keyword)' (at \(found.path)), which strict mode cannot enforce; " | ||
| 156 | + + "remove it or set strict to false") | ||
| 157 | + } | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + static func isValidToolName(_ name: String) -> Bool { | ||
| 161 | + (1 ... 64).contains(name.count) | ||
| 162 | + && name.allSatisfy { | ||
| 163 | + $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_" || $0 == "-") | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + private func invalid(_ param: String, _ message: String) -> OpenAIError { | ||
| 168 | + OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | ||
| 169 | + } | ||
| 170 | +} | ||
added
Tests/RazorbillMLXTests/ConstrainedSmokeTests.swift +167 -0 | new file mode 100644 | ||
| @@ -0,0 +1,167 @@ | ||
| 1 | +#if canImport(MLXLLM) | |
| 2 | +import Foundation | |
| 3 | +import RazorbillCore | |
| 4 | +import Testing | |
| 5 | + | |
| 6 | +@testable import RazorbillMLX | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +/// Constrained decoding with a real model (tickets #38–#41): the output must parse whatever the | |
| 10 | +/// small model would have written on its own. Runs only when the model is in the HF cache. | |
| 11 | +@Suite(.serialized, .enabled(if: smokeModelIsCached)) | |
| 12 | +struct ConstrainedSmokeTests { | |
| 13 | + let models = ModelManager( | |
| 14 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() | |
| 15 | + ) { MLXEngine() } | |
| 16 | + | |
| 17 | + struct Person: Decodable { | |
| 18 | + let name: String | |
| 19 | + let age: Int | |
| 20 | + let languages: [String] | |
| 21 | + } | |
| 22 | + | |
| 23 | + static let personSchema = """ | |
| 24 | + {"type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer","minimum":0}, | |
| 25 | + "languages":{"type":"array","items":{"type":"string","enum":["French","English","Spanish"]}, | |
| 26 | + "minItems":1}},"required":["name","age","languages"],"additionalProperties":false} | |
| 27 | + """ | |
| 28 | + | |
| 29 | + func plan( | |
| 30 | + _ prompt: String, extra: String = "", maxTokens: Int = 200, stream: Bool = false | |
| 31 | + ) throws -> ChatPlan { | |
| 32 | + let escaped = prompt.replacingOccurrences(of: "\"", with: "\\\"") | |
| 33 | + let json = | |
| 34 | + #"{"model":"\#(smokeModel)","temperature":0,"max_tokens":\#(maxTokens),"# | |
| 35 | + + #""messages":[{"role":"user","content":"\#(escaped)"}]\#(extra)}"# | |
| 36 | + var plan = try ChatCompletionRequest.decode(Data(json.utf8)).validated() | |
| 37 | + plan.stream = stream | |
| 38 | + return plan | |
| 39 | + } | |
| 40 | + | |
| 41 | + func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse { | |
| 42 | + try await ChatCompletionRoute(models: models).complete(plan) | |
| 43 | + } | |
| 44 | + | |
| 45 | + static var schemaFormat: String { | |
| 46 | + #","response_format":{"type":"json_schema","json_schema":{"name":"person","strict":true,"schema":"# | |
| 47 | + + personSchema + "}}" | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Test func jsonSchemaOutputParses() async throws { | |
| 51 | + let response = try await complete( | |
| 52 | + try plan("Invent a person who speaks two languages.", extra: Self.schemaFormat)) | |
| 53 | + let content = try #require(response.choices.first?.message.content) | |
| 54 | + let person = try JSONDecoder().decode(Person.self, from: Data(content.utf8)) | |
| 55 | + #expect(!person.name.isEmpty && person.age >= 0 && !person.languages.isEmpty) | |
| 56 | + #expect(person.languages.allSatisfy { ["French", "English", "Spanish"].contains($0) }) | |
| 57 | + } | |
| 58 | + | |
| 59 | + @Test func jsonObjectOutputIsAnObject() async throws { | |
| 60 | + let response = try await complete( | |
| 61 | + try plan("Tell me a joke.", extra: #","response_format":{"type":"json_object"}"#)) | |
| 62 | + let content = try #require(response.choices.first?.message.content) | |
| 63 | + #expect(try JSONSerialization.jsonObject(with: Data(content.utf8)) is [String: Any]) | |
| 64 | + } | |
| 65 | + | |
| 66 | + @Test func reasoningModelThinksThenAnswersUnderTheSchema() async throws { | |
| 67 | + let response = try await complete( | |
| 68 | + try plan( | |
| 69 | + "Invent a person who speaks two languages.", | |
| 70 | + extra: Self.schemaFormat + #","reasoning_effort":"high""#, maxTokens: 1200)) | |
| 71 | + let message = try #require(response.choices.first?.message) | |
| 72 | + #expect((message.reasoningContent?.count ?? 0) > 20) | |
| 73 | + _ = try JSONDecoder().decode(Person.self, from: Data((message.content ?? "").utf8)) | |
| 74 | + } | |
| 75 | + | |
| 76 | + @Test func streamedJSONReassembles() async throws { | |
| 77 | + let streaming = try plan( | |
| 78 | + "Invent a person who speaks two languages.", extra: Self.schemaFormat, stream: true) | |
| 79 | + let lease = try await models.acquire(smokeModel) | |
| 80 | + let pieces = try await ChatCompletionRoute.generate(streaming, with: lease) | |
| 81 | + let chunks = ChatCompletionRoute.chunks( | |
| 82 | + pieces, lease: lease, plan: streaming, logger: .init(label: "test")) | |
| 83 | + var parts: [String] = [] | |
| 84 | + for try await chunk in chunks { | |
| 85 | + parts += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty } | |
| 86 | + } | |
| 87 | + #expect(parts.count > 5) | |
| 88 | + _ = try JSONDecoder().decode(Person.self, from: Data(parts.joined().utf8)) | |
| 89 | + } | |
| 90 | + | |
| 91 | + static let tools = | |
| 92 | + #","tools":[{"type":"function","function":{"name":"get_weather","description":"Current weather","# | |
| 93 | + + #""parameters":{"type":"object","properties":{"city":{"type":"string"},"# | |
| 94 | + + #""unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["city","unit"]}}},"# | |
| 95 | + + #"{"type":"function","function":{"name":"get_time","parameters":{"type":"object","# | |
| 96 | + + #""properties":{"timezone":{"type":"string"}},"required":["timezone"]}}}]"# | |
| 97 | + | |
| 98 | + @Test func requiredForcesAValidCallEvenForSmallTalk() async throws { | |
| 99 | + let response = try await complete( | |
| 100 | + try plan("Hello! How are you?", extra: Self.tools + #","tool_choice":"required""#)) | |
| 101 | + let choice = try #require(response.choices.first) | |
| 102 | + #expect(choice.finishReason == .toolCalls) | |
| 103 | + let call = try #require(choice.message.toolCalls.first) | |
| 104 | + #expect(["get_weather", "get_time"].contains(call.function.name)) | |
| 105 | + _ = try JSONSerialization.jsonObject(with: Data(call.function.arguments.utf8)) | |
| 106 | + } | |
| 107 | + | |
| 108 | + @Test func namedToolIsTheOneCalledWithValidArguments() async throws { | |
| 109 | + let named = #","tool_choice":{"type":"function","function":{"name":"get_weather"}}"# | |
| 110 | + let response = try await complete( | |
| 111 | + try plan("What time is it in Tokyo?", extra: Self.tools + named)) | |
| 112 | + let call = try #require(response.choices.first?.message.toolCalls.first) | |
| 113 | + #expect(call.function.name == "get_weather") | |
| 114 | + let arguments = try #require( | |
| 115 | + try JSONSerialization.jsonObject(with: Data(call.function.arguments.utf8)) | |
| 116 | + as? [String: String]) | |
| 117 | + #expect( | |
| 118 | + arguments["city"] != nil && ["celsius", "fahrenheit"].contains(arguments["unit"] ?? "")) | |
| 119 | + } | |
| 120 | + | |
| 121 | + @Test func autoRoundTripWithAToolResult() async throws { | |
| 122 | + // Qwen3-0.6B often answers in prose under "auto": force the first call (as #41 allows), | |
| 123 | + // then check that the tool result comes back through the template. | |
| 124 | + let first = try await complete( | |
| 125 | + try plan( | |
| 126 | + "What is the weather in Paris, in celsius?", | |
| 127 | + extra: Self.tools + #","tool_choice":"required""#)) | |
| 128 | + let message = try #require(first.choices.first?.message) | |
| 129 | + let call = try #require(message.toolCalls.first, "content: \(message.content ?? "nil")") | |
| 130 | + #expect(call.function.name == "get_weather") | |
| 131 | + let history = | |
| 132 | + #"{"role":"user","content":"What is the weather in Paris, in celsius?"},"# | |
| 133 | + + #"{"role":"assistant","content":null,"tool_calls":[{"id":"\#(call.id ?? "c1")","# | |
| 134 | + + #""type":"function","function":{"name":"get_weather","arguments":"# | |
| 135 | + + String(data: try JSONEncoder().encode(call.function.arguments), encoding: .utf8)! | |
| 136 | + + #"}}]},{"role":"tool","tool_call_id":"\#(call.id ?? "c1")","content":"18 degrees, sunny"}"# | |
| 137 | + let json = | |
| 138 | + #"{"model":"\#(smokeModel)","temperature":0,"max_tokens":200,"messages":[\#(history)]"# | |
| 139 | + + Self.tools + "}" | |
| 140 | + let second = try await complete( | |
| 141 | + try ChatCompletionRequest.decode(Data(json.utf8)).validated()) | |
| 142 | + let answer = try #require(second.choices.first?.message.content) | |
| 143 | + #expect(answer.contains("18")) | |
| 144 | + } | |
| 145 | + | |
| 146 | + /// Spike #38 measurements, printed for the report. | |
| 147 | + @Test func measureConstraintCost() async throws { | |
| 148 | + let prompt = "Describe a person in JSON with name, age and languages." | |
| 149 | + func timed(_ plan: ChatPlan) async throws -> (seconds: Double, tokens: Int) { | |
| 150 | + let start = ContinuousClock.now | |
| 151 | + let response = try await complete(plan) | |
| 152 | + let elapsed = ContinuousClock.now - start | |
| 153 | + let seconds = | |
| 154 | + Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18 | |
| 155 | + return (seconds, response.usage.completionTokens) | |
| 156 | + } | |
| 157 | + _ = try await timed(try plan("Hi", maxTokens: 4)) // load the model | |
| 158 | + let free = try await timed(try plan(prompt, maxTokens: 120)) | |
| 159 | + let cold = try await timed(try plan(prompt, extra: Self.schemaFormat, maxTokens: 120)) | |
| 160 | + let warm = try await timed(try plan(prompt, extra: Self.schemaFormat, maxTokens: 120)) | |
| 161 | + print( | |
| 162 | + "SPIKE38 free: \(free.tokens) tok in \(free.seconds)s; constrained cold: \(cold.tokens) tok in " | |
| 163 | + + "\(cold.seconds)s; constrained warm: \(warm.tokens) tok in \(warm.seconds)s") | |
| 164 | + #expect(warm.tokens > 0) | |
| 165 | + } | |
| 166 | +} | |
| 167 | +#endif | |
| new file mode 100644 | |||
| @@ -0,0 +1,167 @@ | |||
| 1 | +#if canImport(MLXLLM) | ||
| 2 | +import Foundation | ||
| 3 | +import RazorbillCore | ||
| 4 | +import Testing | ||
| 5 | + | ||
| 6 | +@testable import RazorbillMLX | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +/// Constrained decoding with a real model (tickets #38–#41): the output must parse whatever the | ||
| 10 | +/// small model would have written on its own. Runs only when the model is in the HF cache. | ||
| 11 | +@Suite(.serialized, .enabled(if: smokeModelIsCached)) | ||
| 12 | +struct ConstrainedSmokeTests { | ||
| 13 | + let models = ModelManager( | ||
| 14 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() | ||
| 15 | + ) { MLXEngine() } | ||
| 16 | + | ||
| 17 | + struct Person: Decodable { | ||
| 18 | + let name: String | ||
| 19 | + let age: Int | ||
| 20 | + let languages: [String] | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + static let personSchema = """ | ||
| 24 | + {"type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer","minimum":0}, | ||
| 25 | + "languages":{"type":"array","items":{"type":"string","enum":["French","English","Spanish"]}, | ||
| 26 | + "minItems":1}},"required":["name","age","languages"],"additionalProperties":false} | ||
| 27 | + """ | ||
| 28 | + | ||
| 29 | + func plan( | ||
| 30 | + _ prompt: String, extra: String = "", maxTokens: Int = 200, stream: Bool = false | ||
| 31 | + ) throws -> ChatPlan { | ||
| 32 | + let escaped = prompt.replacingOccurrences(of: "\"", with: "\\\"") | ||
| 33 | + let json = | ||
| 34 | + #"{"model":"\#(smokeModel)","temperature":0,"max_tokens":\#(maxTokens),"# | ||
| 35 | + + #""messages":[{"role":"user","content":"\#(escaped)"}]\#(extra)}"# | ||
| 36 | + var plan = try ChatCompletionRequest.decode(Data(json.utf8)).validated() | ||
| 37 | + plan.stream = stream | ||
| 38 | + return plan | ||
| 39 | + } | ||
| 40 | + | ||
| 41 | + func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse { | ||
| 42 | + try await ChatCompletionRoute(models: models).complete(plan) | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + static var schemaFormat: String { | ||
| 46 | + #","response_format":{"type":"json_schema","json_schema":{"name":"person","strict":true,"schema":"# | ||
| 47 | + + personSchema + "}}" | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + @Test func jsonSchemaOutputParses() async throws { | ||
| 51 | + let response = try await complete( | ||
| 52 | + try plan("Invent a person who speaks two languages.", extra: Self.schemaFormat)) | ||
| 53 | + let content = try #require(response.choices.first?.message.content) | ||
| 54 | + let person = try JSONDecoder().decode(Person.self, from: Data(content.utf8)) | ||
| 55 | + #expect(!person.name.isEmpty && person.age >= 0 && !person.languages.isEmpty) | ||
| 56 | + #expect(person.languages.allSatisfy { ["French", "English", "Spanish"].contains($0) }) | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + @Test func jsonObjectOutputIsAnObject() async throws { | ||
| 60 | + let response = try await complete( | ||
| 61 | + try plan("Tell me a joke.", extra: #","response_format":{"type":"json_object"}"#)) | ||
| 62 | + let content = try #require(response.choices.first?.message.content) | ||
| 63 | + #expect(try JSONSerialization.jsonObject(with: Data(content.utf8)) is [String: Any]) | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + @Test func reasoningModelThinksThenAnswersUnderTheSchema() async throws { | ||
| 67 | + let response = try await complete( | ||
| 68 | + try plan( | ||
| 69 | + "Invent a person who speaks two languages.", | ||
| 70 | + extra: Self.schemaFormat + #","reasoning_effort":"high""#, maxTokens: 1200)) | ||
| 71 | + let message = try #require(response.choices.first?.message) | ||
| 72 | + #expect((message.reasoningContent?.count ?? 0) > 20) | ||
| 73 | + _ = try JSONDecoder().decode(Person.self, from: Data((message.content ?? "").utf8)) | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + @Test func streamedJSONReassembles() async throws { | ||
| 77 | + let streaming = try plan( | ||
| 78 | + "Invent a person who speaks two languages.", extra: Self.schemaFormat, stream: true) | ||
| 79 | + let lease = try await models.acquire(smokeModel) | ||
| 80 | + let pieces = try await ChatCompletionRoute.generate(streaming, with: lease) | ||
| 81 | + let chunks = ChatCompletionRoute.chunks( | ||
| 82 | + pieces, lease: lease, plan: streaming, logger: .init(label: "test")) | ||
| 83 | + var parts: [String] = [] | ||
| 84 | + for try await chunk in chunks { | ||
| 85 | + parts += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty } | ||
| 86 | + } | ||
| 87 | + #expect(parts.count > 5) | ||
| 88 | + _ = try JSONDecoder().decode(Person.self, from: Data(parts.joined().utf8)) | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + static let tools = | ||
| 92 | + #","tools":[{"type":"function","function":{"name":"get_weather","description":"Current weather","# | ||
| 93 | + + #""parameters":{"type":"object","properties":{"city":{"type":"string"},"# | ||
| 94 | + + #""unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["city","unit"]}}},"# | ||
| 95 | + + #"{"type":"function","function":{"name":"get_time","parameters":{"type":"object","# | ||
| 96 | + + #""properties":{"timezone":{"type":"string"}},"required":["timezone"]}}}]"# | ||
| 97 | + | ||
| 98 | + @Test func requiredForcesAValidCallEvenForSmallTalk() async throws { | ||
| 99 | + let response = try await complete( | ||
| 100 | + try plan("Hello! How are you?", extra: Self.tools + #","tool_choice":"required""#)) | ||
| 101 | + let choice = try #require(response.choices.first) | ||
| 102 | + #expect(choice.finishReason == .toolCalls) | ||
| 103 | + let call = try #require(choice.message.toolCalls.first) | ||
| 104 | + #expect(["get_weather", "get_time"].contains(call.function.name)) | ||
| 105 | + _ = try JSONSerialization.jsonObject(with: Data(call.function.arguments.utf8)) | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + @Test func namedToolIsTheOneCalledWithValidArguments() async throws { | ||
| 109 | + let named = #","tool_choice":{"type":"function","function":{"name":"get_weather"}}"# | ||
| 110 | + let response = try await complete( | ||
| 111 | + try plan("What time is it in Tokyo?", extra: Self.tools + named)) | ||
| 112 | + let call = try #require(response.choices.first?.message.toolCalls.first) | ||
| 113 | + #expect(call.function.name == "get_weather") | ||
| 114 | + let arguments = try #require( | ||
| 115 | + try JSONSerialization.jsonObject(with: Data(call.function.arguments.utf8)) | ||
| 116 | + as? [String: String]) | ||
| 117 | + #expect( | ||
| 118 | + arguments["city"] != nil && ["celsius", "fahrenheit"].contains(arguments["unit"] ?? "")) | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + @Test func autoRoundTripWithAToolResult() async throws { | ||
| 122 | + // Qwen3-0.6B often answers in prose under "auto": force the first call (as #41 allows), | ||
| 123 | + // then check that the tool result comes back through the template. | ||
| 124 | + let first = try await complete( | ||
| 125 | + try plan( | ||
| 126 | + "What is the weather in Paris, in celsius?", | ||
| 127 | + extra: Self.tools + #","tool_choice":"required""#)) | ||
| 128 | + let message = try #require(first.choices.first?.message) | ||
| 129 | + let call = try #require(message.toolCalls.first, "content: \(message.content ?? "nil")") | ||
| 130 | + #expect(call.function.name == "get_weather") | ||
| 131 | + let history = | ||
| 132 | + #"{"role":"user","content":"What is the weather in Paris, in celsius?"},"# | ||
| 133 | + + #"{"role":"assistant","content":null,"tool_calls":[{"id":"\#(call.id ?? "c1")","# | ||
| 134 | + + #""type":"function","function":{"name":"get_weather","arguments":"# | ||
| 135 | + + String(data: try JSONEncoder().encode(call.function.arguments), encoding: .utf8)! | ||
| 136 | + + #"}}]},{"role":"tool","tool_call_id":"\#(call.id ?? "c1")","content":"18 degrees, sunny"}"# | ||
| 137 | + let json = | ||
| 138 | + #"{"model":"\#(smokeModel)","temperature":0,"max_tokens":200,"messages":[\#(history)]"# | ||
| 139 | + + Self.tools + "}" | ||
| 140 | + let second = try await complete( | ||
| 141 | + try ChatCompletionRequest.decode(Data(json.utf8)).validated()) | ||
| 142 | + let answer = try #require(second.choices.first?.message.content) | ||
| 143 | + #expect(answer.contains("18")) | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + /// Spike #38 measurements, printed for the report. | ||
| 147 | + @Test func measureConstraintCost() async throws { | ||
| 148 | + let prompt = "Describe a person in JSON with name, age and languages." | ||
| 149 | + func timed(_ plan: ChatPlan) async throws -> (seconds: Double, tokens: Int) { | ||
| 150 | + let start = ContinuousClock.now | ||
| 151 | + let response = try await complete(plan) | ||
| 152 | + let elapsed = ContinuousClock.now - start | ||
| 153 | + let seconds = | ||
| 154 | + Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18 | ||
| 155 | + return (seconds, response.usage.completionTokens) | ||
| 156 | + } | ||
| 157 | + _ = try await timed(try plan("Hi", maxTokens: 4)) // load the model | ||
| 158 | + let free = try await timed(try plan(prompt, maxTokens: 120)) | ||
| 159 | + let cold = try await timed(try plan(prompt, extra: Self.schemaFormat, maxTokens: 120)) | ||
| 160 | + let warm = try await timed(try plan(prompt, extra: Self.schemaFormat, maxTokens: 120)) | ||
| 161 | + print( | ||
| 162 | + "SPIKE38 free: \(free.tokens) tok in \(free.seconds)s; constrained cold: \(cold.tokens) tok in " | ||
| 163 | + + "\(cold.seconds)s; constrained warm: \(warm.tokens) tok in \(warm.seconds)s") | ||
| 164 | + #expect(warm.tokens > 0) | ||
| 165 | + } | ||
| 166 | +} | ||
| 167 | +#endif | ||
modified
Tests/RazorbillServerTests/ChatCompletionTests.swift +5 -2 | @@ -177,9 +177,12 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri | ||
| 177 | 177 | (simpleRequest(extra: #","top_p":"high""#), "top_p"), |
| 178 | 178 | (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), |
| 179 | 179 | (simpleRequest(extra: #","n":2"#), "n"), |
| 180 | - (simpleRequest(extra: #","tools":[]"#), "tools"), | |
| 180 | + ( | |
| 181 | + simpleRequest(extra: #","tools":[{"type":"web","function":{"name":"f"}}]"#), | |
| 182 | + "tools[0].type" | |
| 183 | + ), | |
| 181 | 184 | (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), |
| 182 | - (simpleRequest(extra: #","response_format":{"type":"json_object"}"#), "response_format"), | |
| 185 | + (simpleRequest(extra: #","response_format":{"type":"xml"}"#), "response_format"), | |
| 183 | 186 | (#"{"model":"org/m","messages":[{"role":"robot","content":"x"}]}"#, "messages[0].role"), |
| 184 | 187 | (#"{"model":"org/m","messages":[{"role":"user"}]}"#, "messages[0].content"), |
| 185 | 188 | ( |
| @@ -177,9 +177,12 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri | |||
| 177 | (simpleRequest(extra: #","top_p":"high""#), "top_p"), | 177 | (simpleRequest(extra: #","top_p":"high""#), "top_p"), |
| 178 | (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), | 178 | (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), |
| 179 | (simpleRequest(extra: #","n":2"#), "n"), | 179 | (simpleRequest(extra: #","n":2"#), "n"), |
| 180 | - (simpleRequest(extra: #","tools":[]"#), "tools"), | 180 | + ( |
| 181 | + simpleRequest(extra: #","tools":[{"type":"web","function":{"name":"f"}}]"#), | ||
| 182 | + "tools[0].type" | ||
| 183 | + ), | ||
| 181 | (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), | 184 | (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), |
| 182 | - (simpleRequest(extra: #","response_format":{"type":"json_object"}"#), "response_format"), | 185 | + (simpleRequest(extra: #","response_format":{"type":"xml"}"#), "response_format"), |
| 183 | (#"{"model":"org/m","messages":[{"role":"robot","content":"x"}]}"#, "messages[0].role"), | 186 | (#"{"model":"org/m","messages":[{"role":"robot","content":"x"}]}"#, "messages[0].role"), |
| 184 | (#"{"model":"org/m","messages":[{"role":"user"}]}"#, "messages[0].content"), | 187 | (#"{"model":"org/m","messages":[{"role":"user"}]}"#, "messages[0].content"), |
| 185 | ( | 188 | ( |
added
Tests/RazorbillServerTests/ToolsAndFormatsTests.swift +233 -0 | new file mode 100644 | ||
| @@ -0,0 +1,233 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import HummingbirdTesting | |
| 4 | +import RazorbillCore | |
| 5 | +import Testing | |
| 6 | + | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +/// A request with one user message and `extra` fields, decoded and validated. | |
| 10 | +func plan(_ extra: String) throws -> ChatPlan { | |
| 11 | + try ChatCompletionRequest.decode(Data(simpleRequest(extra: extra).utf8)).validated() | |
| 12 | +} | |
| 13 | + | |
| 14 | +/// The 400's `param` for a request with `extra` fields. | |
| 15 | +func rejectedParam(_ extra: String) -> String? { | |
| 16 | + do { | |
| 17 | + _ = try plan(extra) | |
| 18 | + return nil | |
| 19 | + } catch let error as OpenAIError { | |
| 20 | + return error.param | |
| 21 | + } catch { | |
| 22 | + return "unexpected \(error)" | |
| 23 | + } | |
| 24 | +} | |
| 25 | + | |
| 26 | +let weatherTool = | |
| 27 | + #"{"type":"function","function":{"name":"weather","description":"Weather in a city","# | |
| 28 | + + #""parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}"# | |
| 29 | +let timeTool = #"{"type":"function","function":{"name":"time"}}"# | |
| 30 | + | |
| 31 | +@Suite struct ResponseFormatTests { | |
| 32 | + @Test func textIsNoConstraint() throws { | |
| 33 | + #expect(try plan("").output.constraint == nil) | |
| 34 | + #expect(try plan(#","response_format":{"type":"text"}"#).output.constraint == nil) | |
| 35 | + } | |
| 36 | + | |
| 37 | + @Test func jsonObjectAndJSONSchemaBecomeConstraints() throws { | |
| 38 | + #expect( | |
| 39 | + try plan(#","response_format":{"type":"json_object"}"#).output.constraint | |
| 40 | + == .anyJSONObject) | |
| 41 | + let schema = #"{"type":"object","properties":{"n":{"type":"integer"}},"required":["n"]}"# | |
| 42 | + let format = | |
| 43 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","strict":true,"schema":"# | |
| 44 | + + schema + "}}" | |
| 45 | + #expect( | |
| 46 | + try plan(format).output.constraint | |
| 47 | + == .jsonSchema( | |
| 48 | + #"{"properties":{"n":{"type":"integer"}},"required":["n"],"type":"object"}"#)) | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Test func strictSchemasWithUnenforcedKeywordsAre400s() throws { | |
| 52 | + let unique = #"{"type":"object","properties":{"tags":{"type":"array","uniqueItems":true}}}"# | |
| 53 | + let strict = | |
| 54 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","strict":true,"schema":"# | |
| 55 | + + unique + "}}" | |
| 56 | + #expect(rejectedParam(strict) == "response_format.json_schema.schema") | |
| 57 | + do { | |
| 58 | + _ = try plan(strict) | |
| 59 | + } catch let error as OpenAIError { | |
| 60 | + #expect(error.message.contains("'uniqueItems' (at properties.tags)")) | |
| 61 | + } | |
| 62 | + // Not strict: best effort, the keyword is ignored. | |
| 63 | + #expect( | |
| 64 | + rejectedParam( | |
| 65 | + strict.replacingOccurrences(of: #""strict":true"#, with: #""strict":false"#)) == nil | |
| 66 | + ) | |
| 67 | + // A property merely *named* like a keyword is fine. | |
| 68 | + let named = #"{"type":"object","properties":{"not":{"type":"string"}}}"# | |
| 69 | + #expect(rejectedParam(strict.replacingOccurrences(of: unique, with: named)) == nil) | |
| 70 | + } | |
| 71 | + | |
| 72 | + @Test func malformedFormatsAre400s() { | |
| 73 | + #expect(rejectedParam(#","response_format":{"type":"yaml"}"#) == "response_format") | |
| 74 | + #expect( | |
| 75 | + rejectedParam(#","response_format":{"type":"json_schema","json_schema":{"name":"x"}}"#) | |
| 76 | + == "response_format.json_schema.schema") | |
| 77 | + } | |
| 78 | +} | |
| 79 | + | |
| 80 | +@Suite struct ToolChoiceTests { | |
| 81 | + @Test func autoOffersToolsWithoutConstraint() throws { | |
| 82 | + let output = try plan(#","tools":[\#(weatherTool),\#(timeTool)]"#).output | |
| 83 | + #expect(output.tools.map(\.name) == ["weather", "time"]) | |
| 84 | + #expect(output.tools[0].description == "Weather in a city") | |
| 85 | + #expect( | |
| 86 | + output.tools[1].parameters | |
| 87 | + == .map(["type": .string("object"), "properties": .map([:])])) | |
| 88 | + #expect(output.constraint == nil && output.maxToolCalls == nil) | |
| 89 | + } | |
| 90 | + | |
| 91 | + @Test func noneHidesTheTools() throws { | |
| 92 | + let output = try plan(#","tools":[\#(weatherTool)],"tool_choice":"none""#).output | |
| 93 | + #expect(output.tools.isEmpty && output.constraint == nil) | |
| 94 | + } | |
| 95 | + | |
| 96 | + @Test func requiredAndNamedConstrainTheCalls() throws { | |
| 97 | + let required = try plan( | |
| 98 | + #","tools":[\#(weatherTool),\#(timeTool)],"tool_choice":"required""#) | |
| 99 | + guard case .toolCalls(let calls)? = required.output.constraint else { | |
| 100 | + Issue.record("no tool-call constraint") | |
| 101 | + return | |
| 102 | + } | |
| 103 | + #expect(calls.required && !calls.parallel && calls.tools.count == 2) | |
| 104 | + let parallel = try plan( | |
| 105 | + #","tools":[\#(weatherTool),\#(timeTool)],"tool_choice":"required","parallel_tool_calls":true"# | |
| 106 | + ) | |
| 107 | + guard case .toolCalls(let many)? = parallel.output.constraint else { | |
| 108 | + Issue.record("no tool-call constraint") | |
| 109 | + return | |
| 110 | + } | |
| 111 | + #expect(many.parallel && parallel.output.maxToolCalls == nil) | |
| 112 | + | |
| 113 | + let named = try plan( | |
| 114 | + #","tools":[\#(weatherTool),\#(timeTool)],"parallel_tool_calls":false,"# | |
| 115 | + + #""tool_choice":{"type":"function","function":{"name":"time"}}"#) | |
| 116 | + guard case .toolCalls(let one)? = named.output.constraint else { | |
| 117 | + Issue.record("no tool-call constraint") | |
| 118 | + return | |
| 119 | + } | |
| 120 | + #expect(one.tools.map(\.name) == ["time"] && one.required && !one.parallel) | |
| 121 | + #expect(named.output.tools.count == 2) // the template still sees every tool | |
| 122 | + #expect(named.output.maxToolCalls == 1) | |
| 123 | + } | |
| 124 | + | |
| 125 | + @Test func strictToolsConstrainCallsUnderAuto() throws { | |
| 126 | + let strict = weatherTool.replacingOccurrences( | |
| 127 | + of: #""name":"weather","#, with: #""name":"weather","strict":true,"#) | |
| 128 | + guard case .toolCalls(let calls)? = try plan(#","tools":[\#(strict)]"#).output.constraint | |
| 129 | + else { | |
| 130 | + Issue.record("no tool-call constraint") | |
| 131 | + return | |
| 132 | + } | |
| 133 | + #expect(!calls.required) | |
| 134 | + } | |
| 135 | + | |
| 136 | + static let invalid: [(extra: String, param: String)] = [ | |
| 137 | + ( | |
| 138 | + #","tools":[{"type":"function","function":{"name":"bad name"}}]"#, | |
| 139 | + "tools[0].function.name" | |
| 140 | + ), | |
| 141 | + (#","tools":[\#(timeTool),\#(timeTool)]"#, "tools[1].function.name"), | |
| 142 | + ( | |
| 143 | + #","tools":[{"type":"function","function":{"name":"f","parameters":[1]}}]"#, | |
| 144 | + "tools[0].function.parameters" | |
| 145 | + ), | |
| 146 | + (#","tool_choice":"required""#, "tool_choice"), | |
| 147 | + (#","tools":[\#(timeTool)],"tool_choice":"sometimes""#, "tool_choice"), | |
| 148 | + ( | |
| 149 | + #","tools":[\#(timeTool)],"tool_choice":{"type":"function","function":{"name":"nope"}}"#, | |
| 150 | + "tool_choice" | |
| 151 | + ), | |
| 152 | + ( | |
| 153 | + #","tools":[\#(timeTool)],"tool_choice":"required","response_format":{"type":"json_object"}"#, | |
| 154 | + "response_format" | |
| 155 | + ), | |
| 156 | + ] | |
| 157 | + | |
| 158 | + @Test(arguments: invalid) | |
| 159 | + func invalidToolRequestsAre400s(extra: String, param: String) { | |
| 160 | + #expect(rejectedParam(extra) == param) | |
| 161 | + } | |
| 162 | +} | |
| 163 | + | |
| 164 | +@Suite struct ToolsOverHTTPTests { | |
| 165 | + @Test func toolsAndConstraintReachTheEngine() async throws { | |
| 166 | + let engines = TestEngines() | |
| 167 | + try await withLiveServer(engines: engines) { client in | |
| 168 | + let response = try await post( | |
| 169 | + client, | |
| 170 | + simpleRequest(extra: #","tools":[\#(weatherTool)],"tool_choice":"required""#)) | |
| 171 | + #expect(response.status == .ok) | |
| 172 | + } | |
| 173 | + let setup = try #require(engines.fake.sessionSetups.first) | |
| 174 | + #expect(setup.tools.map(\.name) == ["weather"]) | |
| 175 | + guard case .toolCalls(let calls)? = setup.constraint else { | |
| 176 | + Issue.record("no constraint") | |
| 177 | + return | |
| 178 | + } | |
| 179 | + #expect(calls.required) | |
| 180 | + } | |
| 181 | + | |
| 182 | + @Test func parallelFalseKeepsTheFirstCall() async throws { | |
| 183 | + let calls: [EngineEvent] = [ | |
| 184 | + .toolCall(ToolCall(id: "a", name: "time")), .toolCall(ToolCall(id: "b", name: "time")), | |
| 185 | + ] | |
| 186 | + let engines = TestEngines(script: [calls, calls]) | |
| 187 | + try await withLiveServer(engines: engines) { client in | |
| 188 | + let body = try CompletionBody( | |
| 189 | + try await post( | |
| 190 | + client, | |
| 191 | + simpleRequest(extra: #","tools":[\#(timeTool)],"parallel_tool_calls":false"#))) | |
| 192 | + #expect(body.first.message.toolCalls?.map(\.id) == ["a"]) | |
| 193 | + } | |
| 194 | + try await withLiveServer(engines: engines) { client in | |
| 195 | + let body = try CompletionBody( | |
| 196 | + try await post(client, simpleRequest(extra: #","tools":[\#(timeTool)]"#))) | |
| 197 | + #expect(body.first.message.toolCalls?.map(\.id) == ["a", "b"]) | |
| 198 | + } | |
| 199 | + } | |
| 200 | + | |
| 201 | + @Test func unsupportedConstraintFromTheEngineIsA400() async throws { | |
| 202 | + let engines = TestEngines( | |
| 203 | + failure: ( | |
| 204 | + [], UnsupportedConstraint(parameter: "tool_choice", reason: "syntax not supported") | |
| 205 | + )) | |
| 206 | + try await withLiveServer(engines: engines) { client in | |
| 207 | + let response = try await post(client, simpleRequest()) | |
| 208 | + #expect(response.status == .badRequest) | |
| 209 | + let error = try ErrorBody(response).error | |
| 210 | + #expect(error.param == "tool_choice") | |
| 211 | + } | |
| 212 | + } | |
| 213 | +} | |
| 214 | + | |
| 215 | +@Suite struct JSONSchemaSupportTests { | |
| 216 | + @Test func findsUnenforcedKeywordsButNotPropertyNames() throws { | |
| 217 | + func find(_ json: String) throws -> String? { | |
| 218 | + let value = try JSONDecoder().decode(ConfigValue.self, from: Data(json.utf8)) | |
| 219 | + return JSONSchemaSupport.firstUnenforcedKeyword(in: value).map { | |
| 220 | + "\($0.keyword)@\($0.path)" | |
| 221 | + } | |
| 222 | + } | |
| 223 | + #expect(try find(#"{"type":"integer","multipleOf":2}"#) == "multipleOf@(root)") | |
| 224 | + #expect( | |
| 225 | + try find(#"{"anyOf":[{"type":"string"},{"not":{"type":"null"}}]}"#) == "not@anyOf[1]") | |
| 226 | + #expect( | |
| 227 | + try find(#"{"$defs":{"if":{"type":"object","properties":{"then":{"type":"string"}}}}}"#) | |
| 228 | + == nil) | |
| 229 | + #expect( | |
| 230 | + try find(#"{"type":"object","properties":{"a":{"type":"string","pattern":"^x"}}}"#) | |
| 231 | + == nil) | |
| 232 | + } | |
| 233 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,233 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import HummingbirdTesting | ||
| 4 | +import RazorbillCore | ||
| 5 | +import Testing | ||
| 6 | + | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +/// A request with one user message and `extra` fields, decoded and validated. | ||
| 10 | +func plan(_ extra: String) throws -> ChatPlan { | ||
| 11 | + try ChatCompletionRequest.decode(Data(simpleRequest(extra: extra).utf8)).validated() | ||
| 12 | +} | ||
| 13 | + | ||
| 14 | +/// The 400's `param` for a request with `extra` fields. | ||
| 15 | +func rejectedParam(_ extra: String) -> String? { | ||
| 16 | + do { | ||
| 17 | + _ = try plan(extra) | ||
| 18 | + return nil | ||
| 19 | + } catch let error as OpenAIError { | ||
| 20 | + return error.param | ||
| 21 | + } catch { | ||
| 22 | + return "unexpected \(error)" | ||
| 23 | + } | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +let weatherTool = | ||
| 27 | + #"{"type":"function","function":{"name":"weather","description":"Weather in a city","# | ||
| 28 | + + #""parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}"# | ||
| 29 | +let timeTool = #"{"type":"function","function":{"name":"time"}}"# | ||
| 30 | + | ||
| 31 | +@Suite struct ResponseFormatTests { | ||
| 32 | + @Test func textIsNoConstraint() throws { | ||
| 33 | + #expect(try plan("").output.constraint == nil) | ||
| 34 | + #expect(try plan(#","response_format":{"type":"text"}"#).output.constraint == nil) | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + @Test func jsonObjectAndJSONSchemaBecomeConstraints() throws { | ||
| 38 | + #expect( | ||
| 39 | + try plan(#","response_format":{"type":"json_object"}"#).output.constraint | ||
| 40 | + == .anyJSONObject) | ||
| 41 | + let schema = #"{"type":"object","properties":{"n":{"type":"integer"}},"required":["n"]}"# | ||
| 42 | + let format = | ||
| 43 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","strict":true,"schema":"# | ||
| 44 | + + schema + "}}" | ||
| 45 | + #expect( | ||
| 46 | + try plan(format).output.constraint | ||
| 47 | + == .jsonSchema( | ||
| 48 | + #"{"properties":{"n":{"type":"integer"}},"required":["n"],"type":"object"}"#)) | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + @Test func strictSchemasWithUnenforcedKeywordsAre400s() throws { | ||
| 52 | + let unique = #"{"type":"object","properties":{"tags":{"type":"array","uniqueItems":true}}}"# | ||
| 53 | + let strict = | ||
| 54 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","strict":true,"schema":"# | ||
| 55 | + + unique + "}}" | ||
| 56 | + #expect(rejectedParam(strict) == "response_format.json_schema.schema") | ||
| 57 | + do { | ||
| 58 | + _ = try plan(strict) | ||
| 59 | + } catch let error as OpenAIError { | ||
| 60 | + #expect(error.message.contains("'uniqueItems' (at properties.tags)")) | ||
| 61 | + } | ||
| 62 | + // Not strict: best effort, the keyword is ignored. | ||
| 63 | + #expect( | ||
| 64 | + rejectedParam( | ||
| 65 | + strict.replacingOccurrences(of: #""strict":true"#, with: #""strict":false"#)) == nil | ||
| 66 | + ) | ||
| 67 | + // A property merely *named* like a keyword is fine. | ||
| 68 | + let named = #"{"type":"object","properties":{"not":{"type":"string"}}}"# | ||
| 69 | + #expect(rejectedParam(strict.replacingOccurrences(of: unique, with: named)) == nil) | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + @Test func malformedFormatsAre400s() { | ||
| 73 | + #expect(rejectedParam(#","response_format":{"type":"yaml"}"#) == "response_format") | ||
| 74 | + #expect( | ||
| 75 | + rejectedParam(#","response_format":{"type":"json_schema","json_schema":{"name":"x"}}"#) | ||
| 76 | + == "response_format.json_schema.schema") | ||
| 77 | + } | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +@Suite struct ToolChoiceTests { | ||
| 81 | + @Test func autoOffersToolsWithoutConstraint() throws { | ||
| 82 | + let output = try plan(#","tools":[\#(weatherTool),\#(timeTool)]"#).output | ||
| 83 | + #expect(output.tools.map(\.name) == ["weather", "time"]) | ||
| 84 | + #expect(output.tools[0].description == "Weather in a city") | ||
| 85 | + #expect( | ||
| 86 | + output.tools[1].parameters | ||
| 87 | + == .map(["type": .string("object"), "properties": .map([:])])) | ||
| 88 | + #expect(output.constraint == nil && output.maxToolCalls == nil) | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + @Test func noneHidesTheTools() throws { | ||
| 92 | + let output = try plan(#","tools":[\#(weatherTool)],"tool_choice":"none""#).output | ||
| 93 | + #expect(output.tools.isEmpty && output.constraint == nil) | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + @Test func requiredAndNamedConstrainTheCalls() throws { | ||
| 97 | + let required = try plan( | ||
| 98 | + #","tools":[\#(weatherTool),\#(timeTool)],"tool_choice":"required""#) | ||
| 99 | + guard case .toolCalls(let calls)? = required.output.constraint else { | ||
| 100 | + Issue.record("no tool-call constraint") | ||
| 101 | + return | ||
| 102 | + } | ||
| 103 | + #expect(calls.required && !calls.parallel && calls.tools.count == 2) | ||
| 104 | + let parallel = try plan( | ||
| 105 | + #","tools":[\#(weatherTool),\#(timeTool)],"tool_choice":"required","parallel_tool_calls":true"# | ||
| 106 | + ) | ||
| 107 | + guard case .toolCalls(let many)? = parallel.output.constraint else { | ||
| 108 | + Issue.record("no tool-call constraint") | ||
| 109 | + return | ||
| 110 | + } | ||
| 111 | + #expect(many.parallel && parallel.output.maxToolCalls == nil) | ||
| 112 | + | ||
| 113 | + let named = try plan( | ||
| 114 | + #","tools":[\#(weatherTool),\#(timeTool)],"parallel_tool_calls":false,"# | ||
| 115 | + + #""tool_choice":{"type":"function","function":{"name":"time"}}"#) | ||
| 116 | + guard case .toolCalls(let one)? = named.output.constraint else { | ||
| 117 | + Issue.record("no tool-call constraint") | ||
| 118 | + return | ||
| 119 | + } | ||
| 120 | + #expect(one.tools.map(\.name) == ["time"] && one.required && !one.parallel) | ||
| 121 | + #expect(named.output.tools.count == 2) // the template still sees every tool | ||
| 122 | + #expect(named.output.maxToolCalls == 1) | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + @Test func strictToolsConstrainCallsUnderAuto() throws { | ||
| 126 | + let strict = weatherTool.replacingOccurrences( | ||
| 127 | + of: #""name":"weather","#, with: #""name":"weather","strict":true,"#) | ||
| 128 | + guard case .toolCalls(let calls)? = try plan(#","tools":[\#(strict)]"#).output.constraint | ||
| 129 | + else { | ||
| 130 | + Issue.record("no tool-call constraint") | ||
| 131 | + return | ||
| 132 | + } | ||
| 133 | + #expect(!calls.required) | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + static let invalid: [(extra: String, param: String)] = [ | ||
| 137 | + ( | ||
| 138 | + #","tools":[{"type":"function","function":{"name":"bad name"}}]"#, | ||
| 139 | + "tools[0].function.name" | ||
| 140 | + ), | ||
| 141 | + (#","tools":[\#(timeTool),\#(timeTool)]"#, "tools[1].function.name"), | ||
| 142 | + ( | ||
| 143 | + #","tools":[{"type":"function","function":{"name":"f","parameters":[1]}}]"#, | ||
| 144 | + "tools[0].function.parameters" | ||
| 145 | + ), | ||
| 146 | + (#","tool_choice":"required""#, "tool_choice"), | ||
| 147 | + (#","tools":[\#(timeTool)],"tool_choice":"sometimes""#, "tool_choice"), | ||
| 148 | + ( | ||
| 149 | + #","tools":[\#(timeTool)],"tool_choice":{"type":"function","function":{"name":"nope"}}"#, | ||
| 150 | + "tool_choice" | ||
| 151 | + ), | ||
| 152 | + ( | ||
| 153 | + #","tools":[\#(timeTool)],"tool_choice":"required","response_format":{"type":"json_object"}"#, | ||
| 154 | + "response_format" | ||
| 155 | + ), | ||
| 156 | + ] | ||
| 157 | + | ||
| 158 | + @Test(arguments: invalid) | ||
| 159 | + func invalidToolRequestsAre400s(extra: String, param: String) { | ||
| 160 | + #expect(rejectedParam(extra) == param) | ||
| 161 | + } | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +@Suite struct ToolsOverHTTPTests { | ||
| 165 | + @Test func toolsAndConstraintReachTheEngine() async throws { | ||
| 166 | + let engines = TestEngines() | ||
| 167 | + try await withLiveServer(engines: engines) { client in | ||
| 168 | + let response = try await post( | ||
| 169 | + client, | ||
| 170 | + simpleRequest(extra: #","tools":[\#(weatherTool)],"tool_choice":"required""#)) | ||
| 171 | + #expect(response.status == .ok) | ||
| 172 | + } | ||
| 173 | + let setup = try #require(engines.fake.sessionSetups.first) | ||
| 174 | + #expect(setup.tools.map(\.name) == ["weather"]) | ||
| 175 | + guard case .toolCalls(let calls)? = setup.constraint else { | ||
| 176 | + Issue.record("no constraint") | ||
| 177 | + return | ||
| 178 | + } | ||
| 179 | + #expect(calls.required) | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + @Test func parallelFalseKeepsTheFirstCall() async throws { | ||
| 183 | + let calls: [EngineEvent] = [ | ||
| 184 | + .toolCall(ToolCall(id: "a", name: "time")), .toolCall(ToolCall(id: "b", name: "time")), | ||
| 185 | + ] | ||
| 186 | + let engines = TestEngines(script: [calls, calls]) | ||
| 187 | + try await withLiveServer(engines: engines) { client in | ||
| 188 | + let body = try CompletionBody( | ||
| 189 | + try await post( | ||
| 190 | + client, | ||
| 191 | + simpleRequest(extra: #","tools":[\#(timeTool)],"parallel_tool_calls":false"#))) | ||
| 192 | + #expect(body.first.message.toolCalls?.map(\.id) == ["a"]) | ||
| 193 | + } | ||
| 194 | + try await withLiveServer(engines: engines) { client in | ||
| 195 | + let body = try CompletionBody( | ||
| 196 | + try await post(client, simpleRequest(extra: #","tools":[\#(timeTool)]"#))) | ||
| 197 | + #expect(body.first.message.toolCalls?.map(\.id) == ["a", "b"]) | ||
| 198 | + } | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + @Test func unsupportedConstraintFromTheEngineIsA400() async throws { | ||
| 202 | + let engines = TestEngines( | ||
| 203 | + failure: ( | ||
| 204 | + [], UnsupportedConstraint(parameter: "tool_choice", reason: "syntax not supported") | ||
| 205 | + )) | ||
| 206 | + try await withLiveServer(engines: engines) { client in | ||
| 207 | + let response = try await post(client, simpleRequest()) | ||
| 208 | + #expect(response.status == .badRequest) | ||
| 209 | + let error = try ErrorBody(response).error | ||
| 210 | + #expect(error.param == "tool_choice") | ||
| 211 | + } | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +@Suite struct JSONSchemaSupportTests { | ||
| 216 | + @Test func findsUnenforcedKeywordsButNotPropertyNames() throws { | ||
| 217 | + func find(_ json: String) throws -> String? { | ||
| 218 | + let value = try JSONDecoder().decode(ConfigValue.self, from: Data(json.utf8)) | ||
| 219 | + return JSONSchemaSupport.firstUnenforcedKeyword(in: value).map { | ||
| 220 | + "\($0.keyword)@\($0.path)" | ||
| 221 | + } | ||
| 222 | + } | ||
| 223 | + #expect(try find(#"{"type":"integer","multipleOf":2}"#) == "multipleOf@(root)") | ||
| 224 | + #expect( | ||
| 225 | + try find(#"{"anyOf":[{"type":"string"},{"not":{"type":"null"}}]}"#) == "not@anyOf[1]") | ||
| 226 | + #expect( | ||
| 227 | + try find(#"{"$defs":{"if":{"type":"object","properties":{"then":{"type":"string"}}}}}"#) | ||
| 228 | + == nil) | ||
| 229 | + #expect( | ||
| 230 | + try find(#"{"type":"object","properties":{"a":{"type":"string","pattern":"^x"}}}"#) | ||
| 231 | + == nil) | ||
| 232 | + } | ||
| 233 | +} | ||