bots-garden/razorbillpublic Fork
⑂ 7cdd37d
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

v0.2 step 7 — reasoning over the API (#37)

The model's thinking is returned apart from the answer as
reasoning_content (message and stream deltas); blank reasoning is left
out. Requests turn thinking on or off with
chat_template_kwargs.enable_thinking or reasoning_effort, and may set a
thinking_budget; configuration defaults and locks still apply. Engine
errors caused by a request setting become 400s naming the field.
usage.completion_tokens_details.reasoning_tokens is reported.

Tests: Linux 120, Mac 131 (real Qwen3 thinking and budget).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-25T13:51:42+01:00 Browse files
7cdd37d parent: d8981f3
modified .memory/handoffs/2026-11-25-v0-2-server-foundation.md +9 -9
@@ -1,24 +1,24 @@
1-# Handoff — 2026-11-25 — v0.2: server (#32), config (#33), models (#34), chat (#35), streaming (#36)
1+# Handoff — 2026-11-25 — v0.2: server, config, models, chat, streaming, reasoning (#32–#37)
22
33 ## State
44 Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78).
55 Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94).
66 Update after #35: non-streaming chat completions done (Linux 106, Mac 114, real-model smoke tests).
77 Update after #36: streaming done (Linux 113, Mac 122).
8+Update after #37: reasoning_content + switches done (Linux 120, Mac 131). Its design choices were
9+made by Claude on a plain "go": mention them to the user if reasoning comes up.
810 Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP
911 server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket
1012 closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task
1113 closed. Nothing pushed.
1214
1315 ## Next steps
14-1. #37 reasoning over the API: `CompletionPiece.reasoning` is produced and dropped in
15- `ChatCompletionRoute.complete` and `ChunkBuilder.chunks` — map it to `reasoning_content`
16- (message and `delta`); decide how a request turns thinking on/off (`reasoning_effort`?) on top of
17- the config's `thinking` default.
18-2. Then by milestone order: #38 spike constrained decoding, #39 structured output, #40/#41 tools,
19- #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; the agent docs
20- are still in docs/).
21-3. User check on the Mac: `rzb serve` + a real model over HTTP (streaming with `curl -N`).
16+1. #38 spike: constrained decoding with MLXGuidedGeneration (XGrammar) in the resolved
17+ mlx-swift-lm 3.32.3 — Mac only; read the API from the SwiftPM checkout, not `main`. It gates
18+ #39 (response_format) and #41 (forced tool choice).
19+2. Then #40 tools, #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs
20+ (EN+FR; the agent docs are still in docs/).
21+3. User check on the Mac: `rzb serve` + a real model over HTTP (`curl -N`, reasoning_effort).
2222 4. Open point: a network-exposed server accepting any HF id lets callers trigger downloads.
2323
2424 ## Watch out for
@@ -1,24 +1,24 @@
1-# Handoff — 2026-11-25 — v0.2: server (#32), config (#33), models (#34), chat (#35), streaming (#36)1+# Handoff — 2026-11-25 — v0.2: server, config, models, chat, streaming, reasoning (#32–#37)
2 2
3 ## State3 ## 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).
5 Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94).5 Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94).
6 Update after #35: non-streaming chat completions done (Linux 106, Mac 114, real-model smoke tests).6 Update after #35: non-streaming chat completions done (Linux 106, Mac 114, real-model smoke tests).
7 Update after #36: streaming done (Linux 113, Mac 122).7 Update after #36: streaming done (Linux 113, Mac 122).
8+Update after #37: reasoning_content + switches done (Linux 120, Mac 131). Its design choices were
9+made by Claude on a plain "go": mention them to the user if reasoning comes up.
8 Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP10 Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP
9 server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket11 server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket
10 closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task12 closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task
11 closed. Nothing pushed.13 closed. Nothing pushed.
12 14
13 ## Next steps15 ## Next steps
14-1. #37 reasoning over the API: `CompletionPiece.reasoning` is produced and dropped in16+1. #38 spike: constrained decoding with MLXGuidedGeneration (XGrammar) in the resolved
15- `ChatCompletionRoute.complete` and `ChunkBuilder.chunks` — map it to `reasoning_content`17+ mlx-swift-lm 3.32.3 — Mac only; read the API from the SwiftPM checkout, not `main`. It gates
16- (message and `delta`); decide how a request turns thinking on/off (`reasoning_effort`?) on top of18+ #39 (response_format) and #41 (forced tool choice).
17- the config's `thinking` default.19+2. Then #40 tools, #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs
18-2. Then by milestone order: #38 spike constrained decoding, #39 structured output, #40/#41 tools,20+ (EN+FR; the agent docs are still in docs/).
19- #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; the agent docs21+3. User check on the Mac: `rzb serve` + a real model over HTTP (`curl -N`, reasoning_effort).
20- are still in docs/).
21-3. User check on the Mac: `rzb serve` + a real model over HTTP (streaming with `curl -N`).
22 4. Open point: a network-exposed server accepting any HF id lets callers trigger downloads.22 4. Open point: a network-exposed server accepting any HF id lets callers trigger downloads.
23 23
24 ## Watch out for24 ## Watch out for
modified .memory/history.md +8 -0
@@ -175,3 +175,11 @@
175175 SDK `stream=True` and `curl -N` checked. Gate PASS (run #11). #36 closed.
176176 - Trap: the privacy hook refuses a command whose text holds the account e-mail (e.g. a ticket
177177 author block written inline); copy the author block from the ticket file instead.
178+- #37: reasoning over the API. Decision asked by the ticket taken by Claude on the user's "go" (field
179+ `reasoning_content`; switches `chat_template_kwargs.enable_thinking` then `reasoning_effort`;
180+ budget only via `thinking_budget`; reasoning always returned when the model thought, blank
181+ reasoning dropped; `reasoning_tokens` ≈ reasoning pieces). Rejected: budgets derived from
182+ `reasoning_effort` (would 400 on models without a thinking protocol). `RequestSettingError`
183+ protocol so engine-side setting errors become 400s. Mac smoke tests with real Qwen3 thinking
184+ (budget 16 → 37 reasoning tokens: Qwen3's transition sentence counts). Linux 120, Mac 131, gate
185+ PASS (run #12). #37 closed (`needs-decision` label removed).
@@ -175,3 +175,11 @@
175 SDK `stream=True` and `curl -N` checked. Gate PASS (run #11). #36 closed.175 SDK `stream=True` and `curl -N` checked. Gate PASS (run #11). #36 closed.
176 - Trap: the privacy hook refuses a command whose text holds the account e-mail (e.g. a ticket176 - Trap: the privacy hook refuses a command whose text holds the account e-mail (e.g. a ticket
177 author block written inline); copy the author block from the ticket file instead.177 author block written inline); copy the author block from the ticket file instead.
178+- #37: reasoning over the API. Decision asked by the ticket taken by Claude on the user's "go" (field
179+ `reasoning_content`; switches `chat_template_kwargs.enable_thinking` then `reasoning_effort`;
180+ budget only via `thinking_budget`; reasoning always returned when the model thought, blank
181+ reasoning dropped; `reasoning_tokens` ≈ reasoning pieces). Rejected: budgets derived from
182+ `reasoning_effort` (would 400 on models without a thinking protocol). `RequestSettingError`
183+ protocol so engine-side setting errors become 400s. Mac smoke tests with real Qwen3 thinking
184+ (budget 16 → 37 reasoning tokens: Qwen3's transition sentence counts). Linux 120, Mac 131, gate
185+ PASS (run #12). #37 closed (`needs-decision` label removed).
modified .memory/summary.md +9 -3
@@ -7,7 +7,7 @@
77 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in
88 tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code
99 removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33,
10-model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35 and its streaming #36 (see
10+model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37 (see
1111 Architecture). Decided by the user (#31): the
1212 agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore,
1313 MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb`
@@ -57,7 +57,10 @@ whole conversation each time, system messages through the template); stop sequen
5757 server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer
5858 (`Connection: close`) because it watches for client hang-ups. Streams hold the model lease until the
5959 stream ends; a vanished streaming client is noticed by a failed write, so SSE sends a `: keep-alive`
60-comment every 5 s. Next: reasoning over the API (#37).
60+comment every 5 s. Reasoning (#37): `reasoning_content` on message and deltas; per request
61+`chat_template_kwargs.enable_thinking` > `reasoning_effort` (none/minimal off) > config default;
62+budget only via the `thinking_budget` extension field; engine errors caused by a request setting
63+adopt `RequestSettingError` (Core) → 400. Next: #38 constrained-decoding spike.
6164
6265 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
6366
@@ -71,6 +74,9 @@ parser commands, `CLIEnvironment` task-local for tests), executable `rzb`. Engin
7174
7275 ## Decisions in force
7376
77+- #37 reasoning switches were chosen by Claude after the user's plain "go" (see the ticket's
78+ comment); the user may still revisit them.
79+
7480 - v0.2 (#33, user 2026-11-25): any Hugging Face id in MLX format is accepted as `model`, declared
7581 or not (cached GGUF-only repos refused; uncached ones checked at download, #34). Nothing is locked
7682 unless listed in a `locked:` block; temperature/top_p/thinking imposed, max_tokens and
@@ -145,7 +151,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes
145151 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).
146152 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped
147153 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).
148-Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #36): Linux 113, Mac 122 (incl. `ChatSmokeTests`: real
154+Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #37): Linux 120, Mac 131 (incl. `ChatSmokeTests`: real
149155 Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache).
150156 Server tests start the real server on a random port (`HummingbirdTesting` `.live`).
151157
@@ -7,7 +7,7 @@
7 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in7 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 code8 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 and its streaming #36 (see10+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): the11 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`
@@ -57,7 +57,10 @@ whole conversation each time, system messages through the template); stop sequen
57 server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer57 server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer
58 (`Connection: close`) because it watches for client hang-ups. Streams hold the model lease until the58 (`Connection: close`) because it watches for client hang-ups. Streams hold the model lease until the
59 stream ends; a vanished streaming client is noticed by a failed write, so SSE sends a `: keep-alive`59 stream ends; a vanished streaming client is noticed by a failed write, so SSE sends a `: keep-alive`
60-comment every 5 s. Next: reasoning over the API (#37).60+comment every 5 s. Reasoning (#37): `reasoning_content` on message and deltas; per request
61+`chat_template_kwargs.enable_thinking` > `reasoning_effort` (none/minimal off) > config default;
62+budget only via the `thinking_budget` extension field; engine errors caused by a request setting
63+adopt `RequestSettingError` (Core) → 400. Next: #38 constrained-decoding spike.
61 64
62 ## Architecture of v0.1 (agent, removed on the v0.2 branch)65 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
63 66
@@ -71,6 +74,9 @@ parser commands, `CLIEnvironment` task-local for tests), executable `rzb`. Engin
71 74
72 ## Decisions in force75 ## Decisions in force
73 76
77+- #37 reasoning switches were chosen by Claude after the user's plain "go" (see the ticket's
78+ comment); the user may still revisit them.
79+
74 - v0.2 (#33, user 2026-11-25): any Hugging Face id in MLX format is accepted as `model`, declared80 - v0.2 (#33, user 2026-11-25): any Hugging Face id in MLX format is accepted as `model`, declared
75 or not (cached GGUF-only repos refused; uncached ones checked at download, #34). Nothing is locked81 or not (cached GGUF-only repos refused; uncached ones checked at download, #34). Nothing is locked
76 unless listed in a `locked:` block; temperature/top_p/thinking imposed, max_tokens and82 unless listed in a `locked:` block; temperature/top_p/thinking imposed, max_tokens and
@@ -145,7 +151,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes
145 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).151 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).
146 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped152 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped
147 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).153 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).
148-Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #36): Linux 113, Mac 122 (incl. `ChatSmokeTests`: real154+Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #37): Linux 120, Mac 131 (incl. `ChatSmokeTests`: real
149 Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache).155 Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache).
150 Server tests start the real server on a random port (`HummingbirdTesting` `.live`).156 Server tests start the real server on a random port (`HummingbirdTesting` `.live`).
151 157
modified .quality/history.jsonl +1 -0
@@ -9,3 +9,4 @@
99 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 9, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:03Z"}
1010 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 10, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:06Z"}
1111 {"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"}
@@ -9,3 +9,4 @@
9 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 9, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:03Z"}9 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 9, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:03Z"}
10 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 10, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:06Z"}10 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 10, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:06Z"}
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"}
added .quality/report-20261125T124822Z.md +73 -0
new file mode 100644
@@ -0,0 +1,73 @@
1+# Quality report — 2026-11-25T12:48:22Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `d8981f3` 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**: #12 (previous: 2026-11-25T12:38:59Z)
8+
9+## Lint issues (`qlty check`)
10+
11+_none_
12+
13+### Top rules
14+
15+_none_
16+
17+### Most affected files
18+
19+_none_
20+
21+## Code smells (`qlty smells`)
22+
23+Total: **0** (vs previous: ±0)
24+
25+_none_
26+
27+## Metrics (`qlty metrics`)
28+
29+| metric | total | vs previous |
30+|---|---|---|
31+| funcs | 384 | +12 |
32+| classes | 171 | +2 |
33+| fields | 758 | +33 |
34+| cyclo | 395 | +5 |
35+| complex | 329 | +4 |
36+| lcom | 76 | +1 |
37+| lines | 6999 | +228 |
38+| loc | 5488 | +189 |
39+
40+### Most complex files
41+
42+| file | complex | cyclo | loc |
43+|---|---|---|---|
44+| Sources/RazorbillServer/Chat/CompletionStream.swift | 25 | 16 | 106 |
45+| 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 | 214 |
48+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 |
49+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
50+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 264 |
51+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
52+| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 132 |
53+| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 |
54+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
55+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
56+| 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+
60+## Trend
61+
62+| run | timestamp | error | warning | smells | complex | gate |
63+|---|---|---|---|---|---|---|
64+| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
65+| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
66+| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS |
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 |
new file mode 100644
@@ -0,0 +1,73 @@
1+# Quality report — 2026-11-25T12:48:22Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `d8981f3` 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**: #12 (previous: 2026-11-25T12:38:59Z)
8+
9+## Lint issues (`qlty check`)
10+
11+_none_
12+
13+### Top rules
14+
15+_none_
16+
17+### Most affected files
18+
19+_none_
20+
21+## Code smells (`qlty smells`)
22+
23+Total: **0** (vs previous: ±0)
24+
25+_none_
26+
27+## Metrics (`qlty metrics`)
28+
29+| metric | total | vs previous |
30+|---|---|---|
31+| funcs | 384 | +12 |
32+| classes | 171 | +2 |
33+| fields | 758 | +33 |
34+| cyclo | 395 | +5 |
35+| complex | 329 | +4 |
36+| lcom | 76 | +1 |
37+| lines | 6999 | +228 |
38+| loc | 5488 | +189 |
39+
40+### Most complex files
41+
42+| file | complex | cyclo | loc |
43+|---|---|---|---|
44+| Sources/RazorbillServer/Chat/CompletionStream.swift | 25 | 16 | 106 |
45+| 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 | 214 |
48+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 |
49+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
50+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 264 |
51+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
52+| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 132 |
53+| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 |
54+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
55+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
56+| 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+
60+## Trend
61+
62+| run | timestamp | error | warning | smells | complex | gate |
63+|---|---|---|---|---|---|---|
64+| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
65+| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
66+| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS |
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 |
modified .quality/report-latest.md +17 -17
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-25T12:38:59Z
1+# Quality report — 2026-11-25T12:48:22Z
22
33 - **Gate**: ✅ **PASS**
4-- **Commit**: `6a3f52a` on `feature/v0.2-openai-server`
4+- **Commit**: `d8981f3` on `feature/v0.2-openai-server`
55 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
66 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #11 (previous: 2026-11-25T12:29:06Z)
7+- **Run**: #12 (previous: 2026-11-25T12:38:59Z)
88
99 ## Lint issues (`qlty check`)
1010
@@ -28,40 +28,39 @@ _none_
2828
2929 | metric | total | vs previous |
3030 |---|---|---|
31-| funcs | 372 | +23 |
32-| classes | 169 | +13 |
33-| fields | 725 | +55 |
34-| cyclo | 390 | +21 |
35-| complex | 325 | +29 |
36-| lcom | 75 | +2 |
37-| lines | 6771 | +426 |
38-| loc | 5299 | +351 |
31+| funcs | 384 | +12 |
32+| classes | 171 | +2 |
33+| fields | 758 | +33 |
34+| cyclo | 395 | +5 |
35+| complex | 329 | +4 |
36+| lcom | 76 | +1 |
37+| lines | 6999 | +228 |
38+| loc | 5488 | +189 |
3939
4040 ### Most complex files
4141
4242 | file | complex | cyclo | loc |
4343 |---|---|---|---|
44-| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 |
44+| Sources/RazorbillServer/Chat/CompletionStream.swift | 25 | 16 | 106 |
4545 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
46-| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 |
46+| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 206 |
4747 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |
48-| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 131 |
48+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 |
4949 | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
50+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 264 |
5051 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
51-| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 241 |
52+| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 132 |
5253 | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 |
5354 | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
5455 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
5556 | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
5657 | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
5758 | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 |
58-| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 9 | 11 | 127 |
5959
6060 ## Trend
6161
6262 | run | timestamp | error | warning | smells | complex | gate |
6363 |---|---|---|---|---|---|---|
64-| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |
6564 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
6665 | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
6766 | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS |
@@ -71,3 +70,4 @@ _none_
7170 | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS |
7271 | 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS |
7372 | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS |
73+| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-25T12:38:59Z1+# Quality report — 2026-11-25T12:48:22Z
2 2
3 - **Gate**: ✅ **PASS**3 - **Gate**: ✅ **PASS**
4-- **Commit**: `6a3f52a` on `feature/v0.2-openai-server`4+- **Commit**: `d8981f3` 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**: #11 (previous: 2026-11-25T12:29:06Z)7+- **Run**: #12 (previous: 2026-11-25T12:38:59Z)
8 8
9 ## Lint issues (`qlty check`)9 ## Lint issues (`qlty check`)
10 10
@@ -28,40 +28,39 @@ _none_
28 28
29 | metric | total | vs previous |29 | metric | total | vs previous |
30 |---|---|---|30 |---|---|---|
31-| funcs | 372 | +23 |31+| funcs | 384 | +12 |
32-| classes | 169 | +13 |32+| classes | 171 | +2 |
33-| fields | 725 | +55 |33+| fields | 758 | +33 |
34-| cyclo | 390 | +21 |34+| cyclo | 395 | +5 |
35-| complex | 325 | +29 |35+| complex | 329 | +4 |
36-| lcom | 75 | +2 |36+| lcom | 76 | +1 |
37-| lines | 6771 | +426 |37+| lines | 6999 | +228 |
38-| loc | 5299 | +351 |38+| loc | 5488 | +189 |
39 39
40 ### Most complex files40 ### Most complex files
41 41
42 | file | complex | cyclo | loc |42 | file | complex | cyclo | loc |
43 |---|---|---|---|43 |---|---|---|---|
44-| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 |44+| Sources/RazorbillServer/Chat/CompletionStream.swift | 25 | 16 | 106 |
45 | tools/host-runner/host_runner.py | 22 | 22 | 141 |45 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
46-| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 |46+| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 206 |
47 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |47 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |
48-| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 131 |48+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 |
49 | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |49 | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
50+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 264 |
50 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |51 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
51-| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 241 |52+| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 132 |
52 | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 |53 | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 |
53 | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |54 | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
54 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |55 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
55 | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |56 | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
56 | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |57 | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
57 | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 |58 | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 |
58-| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 9 | 11 | 127 |
59 59
60 ## Trend60 ## Trend
61 61
62 | run | timestamp | error | warning | smells | complex | gate |62 | run | timestamp | error | warning | smells | complex | gate |
63 |---|---|---|---|---|---|---|63 |---|---|---|---|---|---|---|
64-| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |
65 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |64 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
66 | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |65 | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
67 | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS |66 | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS |
@@ -71,3 +70,4 @@ _none_
71 | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS |70 | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS |
72 | 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS |71 | 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS |
73 | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | 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 |
modified .tickets/issues/0037-reasoning-models-over-the-api-reasoning-content.yaml +32 -9
@@ -1,17 +1,16 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 37
33 title: "Reasoning models over the API: reasoning_content, enable_thinking, budget"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z
9+updatedAt: 2026-11-25T12:55:00.000Z
1010 labels:
1111 - "kind::feature"
1212 - "area::engine"
1313 - "priority::high"
14- - "needs-decision"
1514 milestone: "v0.2 — OpenAI-compatible MLX server"
1615 epic: "Chat completions"
1716 related:
@@ -33,42 +32,66 @@ body: |
3332 tasks:
3433 - id: 1
3534 title: "Decide the reasoning field and switches"
36- state: open
35+ state: closed
3736 priority: high
3837 author:
3938 name: k33g
4039 email: ph.charriere@gmail.com
4140 createdAt: 2026-11-24T21:17:08.000Z
41+ updatedAt: 2026-11-25T12:55:00.000Z
42+ closedAt: 2026-11-25T12:55:00.000Z
4243 - id: 2
4344 title: "Separate reasoning in non-streaming responses"
44- state: open
45+ state: closed
4546 priority: high
4647 author:
4748 name: k33g
4849 email: ph.charriere@gmail.com
4950 createdAt: 2026-11-24T21:17:08.000Z
51+ updatedAt: 2026-11-25T12:55:00.000Z
52+ closedAt: 2026-11-25T12:55:00.000Z
5053 - id: 3
5154 title: "reasoning deltas in streams"
52- state: open
55+ state: closed
5356 priority: high
5457 author:
5558 name: k33g
5659 email: ph.charriere@gmail.com
5760 createdAt: 2026-11-24T21:17:08.000Z
61+ updatedAt: 2026-11-25T12:55:00.000Z
62+ closedAt: 2026-11-25T12:55:00.000Z
5863 - id: 4
5964 title: "Per-request on/off and budget"
60- state: open
65+ state: closed
6166 priority: medium
6267 author:
6368 name: k33g
6469 email: ph.charriere@gmail.com
6570 createdAt: 2026-11-24T21:17:08.000Z
71+ updatedAt: 2026-11-25T12:55:00.000Z
72+ closedAt: 2026-11-25T12:55:00.000Z
6673 - id: 5
6774 title: "reasoning_tokens in usage"
68- state: open
75+ state: closed
6976 priority: low
7077 author:
7178 name: k33g
7279 email: ph.charriere@gmail.com
7380 createdAt: 2026-11-24T21:17:08.000Z
74-comments: []
81+ updatedAt: 2026-11-25T12:55:00.000Z
82+ closedAt: 2026-11-25T12:55:00.000Z
83+comments:
84+ - id: 1
85+ author:
86+ name: k33g
87+ email: ph.charriere@gmail.com
88+ createdAt: 2026-11-25T12:55:00.000Z
89+ body: |
90+ Decided (user said "go"; defaults chosen by Claude, open to change) and done:
91+ - Output field: `reasoning_content` on the message and on stream deltas (DeepSeek / vLLM / llama-server convention). Returned whenever the model thought; reasoning that is only blank (Qwen3's empty `<think></think>` when thinking is off) is left out.
92+ - On/off per request: `chat_template_kwargs.enable_thinking` (bool, other keys ignored) first, then `reasoning_effort` (`none`/`minimal` → off, `low`/`medium`/`high` → on); otherwise the configuration's `defaults.thinking`. `locked.thinking` still wins.
93+ - Budget: only the explicit extension field `thinking_budget` (≥ 0), capped by `locked.thinking_budget`. Not derived from `reasoning_effort`: a model with no known thinking protocol would then fail on a plain `low`. Such a model given a budget answers 400 `param: thinking_budget` (new `RequestSettingError` protocol in Core, adopted by `MLXEngine.NoThinkingProtocol`).
94+ - `usage.completion_tokens_details.reasoning_tokens`: number of reasoning pieces (≈ tokens; MLX gives no separate count), written only when > 0.
95+ Note: with Qwen3, mlx-swift-lm closes a budget with a ~20-token transition sentence that is part of the reasoning (budget 16 → 37 reasoning tokens observed).
96+ Tests: 13 server tests + 2 Mac smoke tests with Qwen3-0.6B (reasoning apart from the answer; budget shortens it). Linux 120, Mac 131, gate PASS.
97+
@@ -1,17 +1,16 @@
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: 372 id: 37
3 title: "Reasoning models over the API: reasoning_content, enable_thinking, budget"3 title: "Reasoning models over the API: reasoning_content, enable_thinking, budget"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-24T21:17:08.000Z8 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z9+updatedAt: 2026-11-25T12:55:00.000Z
10 labels:10 labels:
11 - "kind::feature"11 - "kind::feature"
12 - "area::engine"12 - "area::engine"
13 - "priority::high"13 - "priority::high"
14- - "needs-decision"
15 milestone: "v0.2 — OpenAI-compatible MLX server"14 milestone: "v0.2 — OpenAI-compatible MLX server"
16 epic: "Chat completions"15 epic: "Chat completions"
17 related:16 related:
@@ -33,42 +32,66 @@ body: |
33 tasks:32 tasks:
34 - id: 133 - id: 1
35 title: "Decide the reasoning field and switches"34 title: "Decide the reasoning field and switches"
36- state: open35+ state: closed
37 priority: high36 priority: high
38 author:37 author:
39 name: k33g38 name: k33g
40 email: ph.charriere@gmail.com39 email: ph.charriere@gmail.com
41 createdAt: 2026-11-24T21:17:08.000Z40 createdAt: 2026-11-24T21:17:08.000Z
41+ updatedAt: 2026-11-25T12:55:00.000Z
42+ closedAt: 2026-11-25T12:55:00.000Z
42 - id: 243 - id: 2
43 title: "Separate reasoning in non-streaming responses"44 title: "Separate reasoning in non-streaming responses"
44- state: open45+ state: closed
45 priority: high46 priority: high
46 author:47 author:
47 name: k33g48 name: k33g
48 email: ph.charriere@gmail.com49 email: ph.charriere@gmail.com
49 createdAt: 2026-11-24T21:17:08.000Z50 createdAt: 2026-11-24T21:17:08.000Z
51+ updatedAt: 2026-11-25T12:55:00.000Z
52+ closedAt: 2026-11-25T12:55:00.000Z
50 - id: 353 - id: 3
51 title: "reasoning deltas in streams"54 title: "reasoning deltas in streams"
52- state: open55+ state: closed
53 priority: high56 priority: high
54 author:57 author:
55 name: k33g58 name: k33g
56 email: ph.charriere@gmail.com59 email: ph.charriere@gmail.com
57 createdAt: 2026-11-24T21:17:08.000Z60 createdAt: 2026-11-24T21:17:08.000Z
61+ updatedAt: 2026-11-25T12:55:00.000Z
62+ closedAt: 2026-11-25T12:55:00.000Z
58 - id: 463 - id: 4
59 title: "Per-request on/off and budget"64 title: "Per-request on/off and budget"
60- state: open65+ state: closed
61 priority: medium66 priority: medium
62 author:67 author:
63 name: k33g68 name: k33g
64 email: ph.charriere@gmail.com69 email: ph.charriere@gmail.com
65 createdAt: 2026-11-24T21:17:08.000Z70 createdAt: 2026-11-24T21:17:08.000Z
71+ updatedAt: 2026-11-25T12:55:00.000Z
72+ closedAt: 2026-11-25T12:55:00.000Z
66 - id: 573 - id: 5
67 title: "reasoning_tokens in usage"74 title: "reasoning_tokens in usage"
68- state: open75+ state: closed
69 priority: low76 priority: low
70 author:77 author:
71 name: k33g78 name: k33g
72 email: ph.charriere@gmail.com79 email: ph.charriere@gmail.com
73 createdAt: 2026-11-24T21:17:08.000Z80 createdAt: 2026-11-24T21:17:08.000Z
74-comments: []81+ updatedAt: 2026-11-25T12:55:00.000Z
82+ closedAt: 2026-11-25T12:55:00.000Z
83+comments:
84+ - id: 1
85+ author:
86+ name: k33g
87+ email: ph.charriere@gmail.com
88+ createdAt: 2026-11-25T12:55:00.000Z
89+ body: |
90+ Decided (user said "go"; defaults chosen by Claude, open to change) and done:
91+ - Output field: `reasoning_content` on the message and on stream deltas (DeepSeek / vLLM / llama-server convention). Returned whenever the model thought; reasoning that is only blank (Qwen3's empty `<think></think>` when thinking is off) is left out.
92+ - On/off per request: `chat_template_kwargs.enable_thinking` (bool, other keys ignored) first, then `reasoning_effort` (`none`/`minimal` → off, `low`/`medium`/`high` → on); otherwise the configuration's `defaults.thinking`. `locked.thinking` still wins.
93+ - Budget: only the explicit extension field `thinking_budget` (≥ 0), capped by `locked.thinking_budget`. Not derived from `reasoning_effort`: a model with no known thinking protocol would then fail on a plain `low`. Such a model given a budget answers 400 `param: thinking_budget` (new `RequestSettingError` protocol in Core, adopted by `MLXEngine.NoThinkingProtocol`).
94+ - `usage.completion_tokens_details.reasoning_tokens`: number of reasoning pieces (≈ tokens; MLX gives no separate count), written only when > 0.
95+ Note: with Qwen3, mlx-swift-lm closes a budget with a ~20-token transition sentence that is part of the reasoning (budget 16 → 37 reasoning tokens observed).
96+ Tests: 13 server tests + 2 Mac smoke tests with Qwen3-0.6B (reasoning apart from the answer; budget shortens it). Linux 120, Mac 131, gate PASS.
97+
modified Sources/RazorbillCore/Engine/InferenceEngine.swift +7 -0
@@ -10,6 +10,13 @@ public enum EngineEvent: Sendable, Equatable {
1010 case stats(GenerationStats)
1111 }
1212
13+/// An engine error caused by what the request asked for (the server answers it with a 400 naming
14+/// `parameter`), not by the server.
15+public protocol RequestSettingError: Error, CustomStringConvertible {
16+ /// The request field at fault, e.g. `thinking_budget`.
17+ var parameter: String { get }
18+}
19+
1320 /// Everything a session needs to know before the first message.
1421 public struct SessionSetup: Sendable, Equatable {
1522 public var system: String
@@ -10,6 +10,13 @@ public enum EngineEvent: Sendable, Equatable {
10 case stats(GenerationStats)10 case stats(GenerationStats)
11 }11 }
12 12
13+/// An engine error caused by what the request asked for (the server answers it with a 400 naming
14+/// `parameter`), not by the server.
15+public protocol RequestSettingError: Error, CustomStringConvertible {
16+ /// The request field at fault, e.g. `thinking_budget`.
17+ var parameter: String { get }
18+}
19+
13 /// Everything a session needs to know before the first message.20 /// Everything a session needs to know before the first message.
14 public struct SessionSetup: Sendable, Equatable {21 public struct SessionSetup: Sendable, Equatable {
15 public var system: String22 public var system: String
modified Sources/RazorbillMLX/MLXEngine.swift +4 -2
@@ -32,10 +32,12 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable {
3232 }
3333
3434 /// `thinking_budget` is set but mlx-swift-lm does not know how this model thinks.
35- public struct NoThinkingProtocol: Error, CustomStringConvertible {
35+ public struct NoThinkingProtocol: RequestSettingError {
3636 public let model: String
37+ public var parameter: String { "thinking_budget" }
3738 public var description: String {
38- "\(model) has no known thinking protocol: remove generation.thinking_budget"
39+ "\(model) has no known thinking protocol, so a thinking budget cannot be enforced: "
40+ + "remove thinking_budget"
3941 }
4042 }
4143
@@ -32,10 +32,12 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable {
32 }32 }
33 33
34 /// `thinking_budget` is set but mlx-swift-lm does not know how this model thinks.34 /// `thinking_budget` is set but mlx-swift-lm does not know how this model thinks.
35- public struct NoThinkingProtocol: Error, CustomStringConvertible {35+ public struct NoThinkingProtocol: RequestSettingError {
36 public let model: String36 public let model: String
37+ public var parameter: String { "thinking_budget" }
37 public var description: String {38 public var description: String {
38- "\(model) has no known thinking protocol: remove generation.thinking_budget"39+ "\(model) has no known thinking protocol, so a thinking budget cannot be enforced: "
40+ + "remove thinking_budget"
39 }41 }
40 }42 }
41 43
modified Sources/RazorbillServer/Chat/ChatCompletionChunk.swift +4 -2
@@ -55,10 +55,12 @@ struct ChunkChoice: Encodable, Sendable {
5555 struct ChunkDelta: Encodable, Sendable {
5656 var role: String?
5757 var content: String?
58+ var reasoningContent: String?
5859 var toolCalls: [IndexedToolCall]?
5960
6061 enum CodingKeys: String, CodingKey {
6162 case role, content
63+ case reasoningContent = "reasoning_content"
6264 case toolCalls = "tool_calls"
6365 }
6466 }
@@ -103,8 +105,8 @@ struct ChunkBuilder: Sendable {
103105 switch piece {
104106 case .content(let text):
105107 return [chunk(ChunkDelta(content: text))]
106- case .reasoning:
107- return [] // reasoning_content comes with ticket #37
108+ case .reasoning(let text):
109+ return [chunk(ChunkDelta(reasoningContent: text))]
108110 case .toolCall(let call):
109111 defer { toolCallCount += 1 }
110112 let indexed = IndexedToolCall(index: toolCallCount, call: WireToolCall(call))
@@ -55,10 +55,12 @@ struct ChunkChoice: Encodable, Sendable {
55 struct ChunkDelta: Encodable, Sendable {55 struct ChunkDelta: Encodable, Sendable {
56 var role: String?56 var role: String?
57 var content: String?57 var content: String?
58+ var reasoningContent: String?
58 var toolCalls: [IndexedToolCall]?59 var toolCalls: [IndexedToolCall]?
59 60
60 enum CodingKeys: String, CodingKey {61 enum CodingKeys: String, CodingKey {
61 case role, content62 case role, content
63+ case reasoningContent = "reasoning_content"
62 case toolCalls = "tool_calls"64 case toolCalls = "tool_calls"
63 }65 }
64 }66 }
@@ -103,8 +105,8 @@ struct ChunkBuilder: Sendable {
103 switch piece {105 switch piece {
104 case .content(let text):106 case .content(let text):
105 return [chunk(ChunkDelta(content: text))]107 return [chunk(ChunkDelta(content: text))]
106- case .reasoning:108+ case .reasoning(let text):
107- return [] // reasoning_content comes with ticket #37109+ return [chunk(ChunkDelta(reasoningContent: text))]
108 case .toolCall(let call):110 case .toolCall(let call):
109 defer { toolCallCount += 1 }111 defer { toolCallCount += 1 }
110 let indexed = IndexedToolCall(index: toolCallCount, call: WireToolCall(call))112 let indexed = IndexedToolCall(index: toolCallCount, call: WireToolCall(call))
modified Sources/RazorbillServer/Chat/ChatCompletionRequest.swift +32 -1
@@ -21,6 +21,12 @@ struct ChatCompletionRequest: Decodable, Sendable {
2121 var logprobs: Bool?
2222 var tools: ConfigValue?
2323 var responseFormat: ConfigValue?
24+ /// `none` / `minimal` turn thinking off; `low` / `medium` / `high` turn it on.
25+ var reasoningEffort: String?
26+ /// vLLM's convention: `{"enable_thinking": false}`. Other keys are ignored.
27+ var chatTemplateKwargs: ConfigValue?
28+ /// razorbill extension: most tokens the model may think before it must answer.
29+ var thinkingBudget: Int?
2430
2531 enum CodingKeys: String, CodingKey {
2632 case model, messages, temperature, stop, seed, stream, logprobs, tools
@@ -32,6 +38,9 @@ struct ChatCompletionRequest: Decodable, Sendable {
3238 case frequencyPenalty = "frequency_penalty"
3339 case responseFormat = "response_format"
3440 case streamOptions = "stream_options"
41+ case reasoningEffort = "reasoning_effort"
42+ case chatTemplateKwargs = "chat_template_kwargs"
43+ case thinkingBudget = "thinking_budget"
3544 }
3645
3746 /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field.
@@ -157,16 +166,38 @@ extension ChatCompletionRequest {
157166 try check(frequencyPenalty, "frequency_penalty", "must be between -2 and 2") {
158167 abs($0) <= 2
159168 }
169+ try checkReasoningSwitches()
160170 return ChatPlan(
161171 model: model,
162172 messages: try messages.enumerated().map { try Self.message($1, at: $0) },
163- client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit),
173+ client: GenerationOverrides(
174+ temperature: temperature, topP: topP, maxTokens: limit, thinking: requestedThinking,
175+ thinkingBudget: thinkingBudget),
164176 seed: seed.map { UInt64(bitPattern: $0) },
165177 presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty,
166178 stops: stops, stream: stream ?? false,
167179 includeUsage: streamOptions?.includeUsage ?? false)
168180 }
169181
182+ /// Whether the request turns thinking on or off: `chat_template_kwargs.enable_thinking` first,
183+ /// then `reasoning_effort`; `nil` leaves the configuration's choice.
184+ var requestedThinking: Bool? {
185+ if let enabled = chatTemplateKwargs?["enable_thinking"]?.boolValue { return enabled }
186+ return reasoningEffort.map { !["none", "minimal"].contains($0) }
187+ }
188+
189+ /// `thinking_budget`, `reasoning_effort` and `chat_template_kwargs.enable_thinking`.
190+ private func checkReasoningSwitches() throws {
191+ try check(thinkingBudget, "thinking_budget", "must be 0 or more") { $0 >= 0 }
192+ let efforts = ["none", "minimal", "low", "medium", "high"]
193+ let effortRule = "must be one of: \(efforts.joined(separator: ", "))"
194+ try check(reasoningEffort, "reasoning_effort", effortRule) { efforts.contains($0) }
195+ let enableThinking = chatTemplateKwargs?["enable_thinking"]
196+ try require(
197+ enableThinking == nil || enableThinking?.boolValue != nil, "chat_template_kwargs",
198+ "enable_thinking must be true or false")
199+ }
200+
170201 /// Fields razorbill does not handle yet: refused rather than silently ignored.
171202 private func checkUnsupported() throws {
172203 try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)")
@@ -21,6 +21,12 @@ struct ChatCompletionRequest: Decodable, Sendable {
21 var logprobs: Bool?21 var logprobs: Bool?
22 var tools: ConfigValue?22 var tools: ConfigValue?
23 var responseFormat: ConfigValue?23 var responseFormat: ConfigValue?
24+ /// `none` / `minimal` turn thinking off; `low` / `medium` / `high` turn it on.
25+ var reasoningEffort: String?
26+ /// vLLM's convention: `{"enable_thinking": false}`. Other keys are ignored.
27+ var chatTemplateKwargs: ConfigValue?
28+ /// razorbill extension: most tokens the model may think before it must answer.
29+ var thinkingBudget: Int?
24 30
25 enum CodingKeys: String, CodingKey {31 enum CodingKeys: String, CodingKey {
26 case model, messages, temperature, stop, seed, stream, logprobs, tools32 case model, messages, temperature, stop, seed, stream, logprobs, tools
@@ -32,6 +38,9 @@ struct ChatCompletionRequest: Decodable, Sendable {
32 case frequencyPenalty = "frequency_penalty"38 case frequencyPenalty = "frequency_penalty"
33 case responseFormat = "response_format"39 case responseFormat = "response_format"
34 case streamOptions = "stream_options"40 case streamOptions = "stream_options"
41+ case reasoningEffort = "reasoning_effort"
42+ case chatTemplateKwargs = "chat_template_kwargs"
43+ case thinkingBudget = "thinking_budget"
35 }44 }
36 45
37 /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field.46 /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field.
@@ -157,16 +166,38 @@ extension ChatCompletionRequest {
157 try check(frequencyPenalty, "frequency_penalty", "must be between -2 and 2") {166 try check(frequencyPenalty, "frequency_penalty", "must be between -2 and 2") {
158 abs($0) <= 2167 abs($0) <= 2
159 }168 }
169+ try checkReasoningSwitches()
160 return ChatPlan(170 return ChatPlan(
161 model: model,171 model: model,
162 messages: try messages.enumerated().map { try Self.message($1, at: $0) },172 messages: try messages.enumerated().map { try Self.message($1, at: $0) },
163- client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit),173+ client: GenerationOverrides(
174+ temperature: temperature, topP: topP, maxTokens: limit, thinking: requestedThinking,
175+ thinkingBudget: thinkingBudget),
164 seed: seed.map { UInt64(bitPattern: $0) },176 seed: seed.map { UInt64(bitPattern: $0) },
165 presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty,177 presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty,
166 stops: stops, stream: stream ?? false,178 stops: stops, stream: stream ?? false,
167 includeUsage: streamOptions?.includeUsage ?? false)179 includeUsage: streamOptions?.includeUsage ?? false)
168 }180 }
169 181
182+ /// Whether the request turns thinking on or off: `chat_template_kwargs.enable_thinking` first,
183+ /// then `reasoning_effort`; `nil` leaves the configuration's choice.
184+ var requestedThinking: Bool? {
185+ if let enabled = chatTemplateKwargs?["enable_thinking"]?.boolValue { return enabled }
186+ return reasoningEffort.map { !["none", "minimal"].contains($0) }
187+ }
188+
189+ /// `thinking_budget`, `reasoning_effort` and `chat_template_kwargs.enable_thinking`.
190+ private func checkReasoningSwitches() throws {
191+ try check(thinkingBudget, "thinking_budget", "must be 0 or more") { $0 >= 0 }
192+ let efforts = ["none", "minimal", "low", "medium", "high"]
193+ let effortRule = "must be one of: \(efforts.joined(separator: ", "))"
194+ try check(reasoningEffort, "reasoning_effort", effortRule) { efforts.contains($0) }
195+ let enableThinking = chatTemplateKwargs?["enable_thinking"]
196+ try require(
197+ enableThinking == nil || enableThinking?.boolValue != nil, "chat_template_kwargs",
198+ "enable_thinking must be true or false")
199+ }
200+
170 /// Fields razorbill does not handle yet: refused rather than silently ignored.201 /// Fields razorbill does not handle yet: refused rather than silently ignored.
171 private func checkUnsupported() throws {202 private func checkUnsupported() throws {
172 try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)")203 try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)")
modified Sources/RazorbillServer/Chat/ChatCompletionRoute.swift +8 -2
@@ -36,10 +36,13 @@ struct CompletionChoice: Encodable, Sendable {
3636 struct AssistantMessage: Encodable, Sendable {
3737 var role = "assistant"
3838 let content: String?
39+ /// The model's thinking, apart from the answer; not written when the model did not think.
40+ var reasoningContent: String?
3941 let toolCalls: [WireToolCall]
4042
4143 enum CodingKeys: String, CodingKey {
4244 case role, content
45+ case reasoningContent = "reasoning_content"
4346 case toolCalls = "tool_calls"
4447 }
4548
@@ -47,6 +50,7 @@ struct AssistantMessage: Encodable, Sendable {
4750 var container = encoder.container(keyedBy: CodingKeys.self)
4851 try container.encode(role, forKey: .role)
4952 try container.encode(content, forKey: .content)
53+ try container.encodeIfPresent(reasoningContent, forKey: .reasoningContent)
5054 if !toolCalls.isEmpty { try container.encode(toolCalls, forKey: .toolCalls) }
5155 }
5256 }
@@ -120,18 +124,20 @@ struct ChatCompletionRoute {
120124 let pieces = CompletionStream.pieces(
121125 from: session.send(plan.messages), stops: plan.stops)
122126 var content = ""
127+ var reasoning = ""
123128 var calls: [WireToolCall] = []
124129 var ending = (FinishReason.stop, Usage(promptTokens: 0, completionTokens: 0))
125130 for try await piece in pieces {
126131 switch piece {
127132 case .content(let text): content += text
128- case .reasoning: break // reasoning_content comes with ticket #37
133+ case .reasoning(let text): reasoning += text
129134 case .toolCall(let call): calls.append(WireToolCall(call))
130135 case .finished(let reason, let usage): ending = (reason, usage)
131136 }
132137 }
133138 let message = AssistantMessage(
134- content: calls.isEmpty || !content.isEmpty ? content : nil, toolCalls: calls)
139+ content: calls.isEmpty || !content.isEmpty ? content : nil,
140+ reasoningContent: reasoning.isEmpty ? nil : reasoning, toolCalls: calls)
135141 let choice = CompletionChoice(message: message, finishReason: ending.0)
136142 return ChatCompletionResponse(
137143 id: Self.newID(), created: Int(Date().timeIntervalSince1970), model: plan.model,
@@ -36,10 +36,13 @@ struct CompletionChoice: Encodable, Sendable {
36 struct AssistantMessage: Encodable, Sendable {36 struct AssistantMessage: Encodable, Sendable {
37 var role = "assistant"37 var role = "assistant"
38 let content: String?38 let content: String?
39+ /// The model's thinking, apart from the answer; not written when the model did not think.
40+ var reasoningContent: String?
39 let toolCalls: [WireToolCall]41 let toolCalls: [WireToolCall]
40 42
41 enum CodingKeys: String, CodingKey {43 enum CodingKeys: String, CodingKey {
42 case role, content44 case role, content
45+ case reasoningContent = "reasoning_content"
43 case toolCalls = "tool_calls"46 case toolCalls = "tool_calls"
44 }47 }
45 48
@@ -47,6 +50,7 @@ struct AssistantMessage: Encodable, Sendable {
47 var container = encoder.container(keyedBy: CodingKeys.self)50 var container = encoder.container(keyedBy: CodingKeys.self)
48 try container.encode(role, forKey: .role)51 try container.encode(role, forKey: .role)
49 try container.encode(content, forKey: .content)52 try container.encode(content, forKey: .content)
53+ try container.encodeIfPresent(reasoningContent, forKey: .reasoningContent)
50 if !toolCalls.isEmpty { try container.encode(toolCalls, forKey: .toolCalls) }54 if !toolCalls.isEmpty { try container.encode(toolCalls, forKey: .toolCalls) }
51 }55 }
52 }56 }
@@ -120,18 +124,20 @@ struct ChatCompletionRoute {
120 let pieces = CompletionStream.pieces(124 let pieces = CompletionStream.pieces(
121 from: session.send(plan.messages), stops: plan.stops)125 from: session.send(plan.messages), stops: plan.stops)
122 var content = ""126 var content = ""
127+ var reasoning = ""
123 var calls: [WireToolCall] = []128 var calls: [WireToolCall] = []
124 var ending = (FinishReason.stop, Usage(promptTokens: 0, completionTokens: 0))129 var ending = (FinishReason.stop, Usage(promptTokens: 0, completionTokens: 0))
125 for try await piece in pieces {130 for try await piece in pieces {
126 switch piece {131 switch piece {
127 case .content(let text): content += text132 case .content(let text): content += text
128- case .reasoning: break // reasoning_content comes with ticket #37133+ case .reasoning(let text): reasoning += text
129 case .toolCall(let call): calls.append(WireToolCall(call))134 case .toolCall(let call): calls.append(WireToolCall(call))
130 case .finished(let reason, let usage): ending = (reason, usage)135 case .finished(let reason, let usage): ending = (reason, usage)
131 }136 }
132 }137 }
133 let message = AssistantMessage(138 let message = AssistantMessage(
134- content: calls.isEmpty || !content.isEmpty ? content : nil, toolCalls: calls)139+ content: calls.isEmpty || !content.isEmpty ? content : nil,
140+ reasoningContent: reasoning.isEmpty ? nil : reasoning, toolCalls: calls)
135 let choice = CompletionChoice(message: message, finishReason: ending.0)141 let choice = CompletionChoice(message: message, finishReason: ending.0)
136 return ChatCompletionResponse(142 return ChatCompletionResponse(
137 id: Self.newID(), created: Int(Date().timeIntervalSince1970), model: plan.model,143 id: Self.newID(), created: Int(Date().timeIntervalSince1970), model: plan.model,
modified Sources/RazorbillServer/Chat/CompletionStream.swift +19 -1
@@ -1,3 +1,4 @@
1+import Foundation
12 import RazorbillCore
23
34 /// Why an answer ended, in OpenAI's words.
@@ -8,15 +9,19 @@ enum FinishReason: String, Encodable, Sendable {
89 }
910
1011 /// Token counts of one answer.
12+/// `completion_tokens_details.reasoning_tokens` is written only when the model thought; it counts
13+/// the pieces of reasoning received (about one per token), since MLX reports no separate count.
1114 struct Usage: Encodable, Equatable, Sendable {
1215 let promptTokens: Int
1316 let completionTokens: Int
17+ var reasoningTokens = 0
1418 var totalTokens: Int { promptTokens + completionTokens }
1519
1620 enum CodingKeys: String, CodingKey {
1721 case promptTokens = "prompt_tokens"
1822 case completionTokens = "completion_tokens"
1923 case totalTokens = "total_tokens"
24+ case details = "completion_tokens_details"
2025 }
2126
2227 func encode(to encoder: any Encoder) throws {
@@ -24,6 +29,9 @@ struct Usage: Encodable, Equatable, Sendable {
2429 try container.encode(promptTokens, forKey: .promptTokens)
2530 try container.encode(completionTokens, forKey: .completionTokens)
2631 try container.encode(totalTokens, forKey: .totalTokens)
32+ if reasoningTokens > 0 {
33+ try container.encode(["reasoning_tokens": reasoningTokens], forKey: .details)
34+ }
2735 }
2836 }
2937
@@ -69,6 +77,10 @@ enum CompletionStream {
6977 var stats: GenerationStats?
7078 var calledTools = false
7179 var textPieces = 0
80+ var reasoningPieces = 0
81+ /// Reasoning seen so far is only blank (Qwen3 writes an empty `<think></think>` when told
82+ /// not to think): such pieces are not passed on.
83+ var reasoningStarted = false
7284
7385 mutating func consume(_ event: EngineEvent) -> [CompletionPiece] {
7486 switch event {
@@ -78,6 +90,11 @@ enum CompletionStream {
7890 return shown.isEmpty ? [] : [.content(shown)]
7991 case .thinking(let text):
8092 textPieces += 1
93+ reasoningStarted =
94+ reasoningStarted
95+ || !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
96+ guard reasoningStarted else { return [] }
97+ reasoningPieces += 1
8198 return [.reasoning(text)]
8299 case .toolCall(let call):
83100 calledTools = true
@@ -100,11 +117,12 @@ enum CompletionStream {
100117 } else {
101118 .stop
102119 }
103- let usage =
120+ var usage =
104121 stats.map {
105122 Usage(promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens)
106123 }
107124 ?? Usage(promptTokens: 0, completionTokens: textPieces)
125+ usage.reasoningTokens = reasoningPieces
108126 return (rest.isEmpty ? [] : [.content(rest)]) + [.finished(reason, usage)]
109127 }
110128 }
@@ -1,3 +1,4 @@
1+import Foundation
1 import RazorbillCore2 import RazorbillCore
2 3
3 /// Why an answer ended, in OpenAI's words.4 /// Why an answer ended, in OpenAI's words.
@@ -8,15 +9,19 @@ enum FinishReason: String, Encodable, Sendable {
8 }9 }
9 10
10 /// Token counts of one answer.11 /// Token counts of one answer.
12+/// `completion_tokens_details.reasoning_tokens` is written only when the model thought; it counts
13+/// the pieces of reasoning received (about one per token), since MLX reports no separate count.
11 struct Usage: Encodable, Equatable, Sendable {14 struct Usage: Encodable, Equatable, Sendable {
12 let promptTokens: Int15 let promptTokens: Int
13 let completionTokens: Int16 let completionTokens: Int
17+ var reasoningTokens = 0
14 var totalTokens: Int { promptTokens + completionTokens }18 var totalTokens: Int { promptTokens + completionTokens }
15 19
16 enum CodingKeys: String, CodingKey {20 enum CodingKeys: String, CodingKey {
17 case promptTokens = "prompt_tokens"21 case promptTokens = "prompt_tokens"
18 case completionTokens = "completion_tokens"22 case completionTokens = "completion_tokens"
19 case totalTokens = "total_tokens"23 case totalTokens = "total_tokens"
24+ case details = "completion_tokens_details"
20 }25 }
21 26
22 func encode(to encoder: any Encoder) throws {27 func encode(to encoder: any Encoder) throws {
@@ -24,6 +29,9 @@ struct Usage: Encodable, Equatable, Sendable {
24 try container.encode(promptTokens, forKey: .promptTokens)29 try container.encode(promptTokens, forKey: .promptTokens)
25 try container.encode(completionTokens, forKey: .completionTokens)30 try container.encode(completionTokens, forKey: .completionTokens)
26 try container.encode(totalTokens, forKey: .totalTokens)31 try container.encode(totalTokens, forKey: .totalTokens)
32+ if reasoningTokens > 0 {
33+ try container.encode(["reasoning_tokens": reasoningTokens], forKey: .details)
34+ }
27 }35 }
28 }36 }
29 37
@@ -69,6 +77,10 @@ enum CompletionStream {
69 var stats: GenerationStats?77 var stats: GenerationStats?
70 var calledTools = false78 var calledTools = false
71 var textPieces = 079 var textPieces = 0
80+ var reasoningPieces = 0
81+ /// Reasoning seen so far is only blank (Qwen3 writes an empty `<think></think>` when told
82+ /// not to think): such pieces are not passed on.
83+ var reasoningStarted = false
72 84
73 mutating func consume(_ event: EngineEvent) -> [CompletionPiece] {85 mutating func consume(_ event: EngineEvent) -> [CompletionPiece] {
74 switch event {86 switch event {
@@ -78,6 +90,11 @@ enum CompletionStream {
78 return shown.isEmpty ? [] : [.content(shown)]90 return shown.isEmpty ? [] : [.content(shown)]
79 case .thinking(let text):91 case .thinking(let text):
80 textPieces += 192 textPieces += 1
93+ reasoningStarted =
94+ reasoningStarted
95+ || !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
96+ guard reasoningStarted else { return [] }
97+ reasoningPieces += 1
81 return [.reasoning(text)]98 return [.reasoning(text)]
82 case .toolCall(let call):99 case .toolCall(let call):
83 calledTools = true100 calledTools = true
@@ -100,11 +117,12 @@ enum CompletionStream {
100 } else {117 } else {
101 .stop118 .stop
102 }119 }
103- let usage =120+ var usage =
104 stats.map {121 stats.map {
105 Usage(promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens)122 Usage(promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens)
106 }123 }
107 ?? Usage(promptTokens: 0, completionTokens: textPieces)124 ?? Usage(promptTokens: 0, completionTokens: textPieces)
125+ usage.reasoningTokens = reasoningPieces
108 return (rest.isEmpty ? [] : [.content(rest)]) + [.finished(reason, usage)]126 return (rest.isEmpty ? [] : [.content(rest)]) + [.finished(reason, usage)]
109 }127 }
110 }128 }
modified Sources/RazorbillServer/OpenAIError.swift +2 -0
@@ -130,6 +130,8 @@ extension OpenAIError {
130130 return OpenAIError(model: error)
131131 case let error as ModelManagerError:
132132 return OpenAIError(manager: error)
133+ case let error as any RequestSettingError:
134+ return OpenAIError(.badRequest, message: error.description, param: error.parameter)
133135 case let error as HTTPError:
134136 return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)
135137 case let error as any HTTPResponseError where error.status == .contentTooLarge:
@@ -130,6 +130,8 @@ extension OpenAIError {
130 return OpenAIError(model: error)130 return OpenAIError(model: error)
131 case let error as ModelManagerError:131 case let error as ModelManagerError:
132 return OpenAIError(manager: error)132 return OpenAIError(manager: error)
133+ case let error as any RequestSettingError:
134+ return OpenAIError(.badRequest, message: error.description, param: error.parameter)
133 case let error as HTTPError:135 case let error as HTTPError:
134 return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)136 return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)
135 case let error as any HTTPResponseError where error.status == .contentTooLarge:137 case let error as any HTTPResponseError where error.status == .contentTooLarge:
modified Tests/RazorbillMLXTests/ChatSmokeTests.swift +23 -0
@@ -44,6 +44,29 @@ struct ChatSmokeTests {
4444 #expect(response.usage.promptTokens > 10 && response.usage.completionTokens > 0)
4545 }
4646
47+ @Test func reasoningIsReturnedApart() async throws {
48+ var thinking = plan("What is the capital of France?", maxTokens: 600)
49+ thinking.client.thinking = true
50+ let response = try await route().complete(thinking)
51+ let message = try #require(response.choices.first?.message)
52+ #expect((message.reasoningContent?.count ?? 0) > 20)
53+ #expect(message.content?.contains("Paris") == true)
54+ #expect(message.content?.contains("think>") == false)
55+ #expect(response.usage.reasoningTokens > 0)
56+ }
57+
58+ @Test func thinkingBudgetShortensTheReasoning() async throws {
59+ var thinking = plan("Is 391 a prime number?", maxTokens: 600)
60+ thinking.client.thinking = true
61+ let free = try await route().complete(thinking)
62+ thinking.client.thinkingBudget = 16
63+ let budgeted = try await route().complete(thinking)
64+ // Qwen3's budget ends with a ~20-token transition sentence, counted as reasoning.
65+ #expect(budgeted.usage.reasoningTokens <= 16 + 30)
66+ #expect(budgeted.usage.reasoningTokens < free.usage.reasoningTokens)
67+ #expect(budgeted.choices.first?.message.content?.isEmpty == false)
68+ }
69+
4770 @Test func tokenLimitGivesLength() async throws {
4871 let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8))
4972 #expect(response.choices.first?.finishReason == .length)
@@ -44,6 +44,29 @@ struct ChatSmokeTests {
44 #expect(response.usage.promptTokens > 10 && response.usage.completionTokens > 0)44 #expect(response.usage.promptTokens > 10 && response.usage.completionTokens > 0)
45 }45 }
46 46
47+ @Test func reasoningIsReturnedApart() async throws {
48+ var thinking = plan("What is the capital of France?", maxTokens: 600)
49+ thinking.client.thinking = true
50+ let response = try await route().complete(thinking)
51+ let message = try #require(response.choices.first?.message)
52+ #expect((message.reasoningContent?.count ?? 0) > 20)
53+ #expect(message.content?.contains("Paris") == true)
54+ #expect(message.content?.contains("think>") == false)
55+ #expect(response.usage.reasoningTokens > 0)
56+ }
57+
58+ @Test func thinkingBudgetShortensTheReasoning() async throws {
59+ var thinking = plan("Is 391 a prime number?", maxTokens: 600)
60+ thinking.client.thinking = true
61+ let free = try await route().complete(thinking)
62+ thinking.client.thinkingBudget = 16
63+ let budgeted = try await route().complete(thinking)
64+ // Qwen3's budget ends with a ~20-token transition sentence, counted as reasoning.
65+ #expect(budgeted.usage.reasoningTokens <= 16 + 30)
66+ #expect(budgeted.usage.reasoningTokens < free.usage.reasoningTokens)
67+ #expect(budgeted.choices.first?.message.content?.isEmpty == false)
68+ }
69+
47 @Test func tokenLimitGivesLength() async throws {70 @Test func tokenLimitGivesLength() async throws {
48 let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8))71 let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8))
49 #expect(response.choices.first?.finishReason == .length)72 #expect(response.choices.first?.finishReason == .length)
modified Tests/RazorbillServerTests/ChatCompletionTests.swift +2 -2
@@ -146,10 +146,10 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri
146146 @Test func tokenLimitEndsWithLength() async throws {
147147 let stats = GenerationStats(
148148 promptTokens: 7, generatedTokens: 16, tokensPerSecond: 1, hitTokenLimit: true)
149- let engines = TestEngines(script: [[.thinking("hmm"), .text("partial"), .stats(stats)]])
149+ let engines = TestEngines(script: [[.text("partial"), .stats(stats)]])
150150 try await withLiveServer(engines: engines) { client in
151151 let body = try CompletionBody(try await post(client, simpleRequest()))
152- #expect(body.first.message.content == "partial") // reasoning is not content
152+ #expect(body.first.message.content == "partial")
153153 #expect(body.first.finishReason == "length")
154154 #expect(
155155 body.usage == ["prompt_tokens": 7, "completion_tokens": 16, "total_tokens": 23])
@@ -146,10 +146,10 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri
146 @Test func tokenLimitEndsWithLength() async throws {146 @Test func tokenLimitEndsWithLength() async throws {
147 let stats = GenerationStats(147 let stats = GenerationStats(
148 promptTokens: 7, generatedTokens: 16, tokensPerSecond: 1, hitTokenLimit: true)148 promptTokens: 7, generatedTokens: 16, tokensPerSecond: 1, hitTokenLimit: true)
149- let engines = TestEngines(script: [[.thinking("hmm"), .text("partial"), .stats(stats)]])149+ let engines = TestEngines(script: [[.text("partial"), .stats(stats)]])
150 try await withLiveServer(engines: engines) { client in150 try await withLiveServer(engines: engines) { client in
151 let body = try CompletionBody(try await post(client, simpleRequest()))151 let body = try CompletionBody(try await post(client, simpleRequest()))
152- #expect(body.first.message.content == "partial") // reasoning is not content152+ #expect(body.first.message.content == "partial")
153 #expect(body.first.finishReason == "length")153 #expect(body.first.finishReason == "length")
154 #expect(154 #expect(
155 body.usage == ["prompt_tokens": 7, "completion_tokens": 16, "total_tokens": 23])155 body.usage == ["prompt_tokens": 7, "completion_tokens": 16, "total_tokens": 23])
added Tests/RazorbillServerTests/ReasoningTests.swift +137 -0
new file mode 100644
@@ -0,0 +1,137 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import RazorbillCore
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+/// The body of a response as loose JSON.
10+func json(_ response: TestResponse) throws -> [String: Any] {
11+ try #require(
12+ try JSONSerialization.jsonObject(with: Data(buffer: response.body)) as? [String: Any])
13+}
14+
15+/// `choices[0].message` of a `chat.completion`.
16+func message(_ body: [String: Any]) -> [String: Any]? {
17+ ((body["choices"] as? [[String: Any]])?.first)?["message"] as? [String: Any]
18+}
19+
20+struct BadBudget: RequestSettingError {
21+ var parameter: String { "thinking_budget" }
22+ var description: String { "no thinking protocol" }
23+}
24+
25+@Suite struct ReasoningTests {
26+ let stats = GenerationStats(promptTokens: 4, generatedTokens: 9, tokensPerSecond: 1)
27+
28+ @Test func reasoningComesApartFromTheAnswer() async throws {
29+ let script: [EngineEvent] = [
30+ .thinking("\n"), .thinking("Six times"), .thinking(" seven."), .text("42"),
31+ .stats(stats),
32+ ]
33+ let engines = TestEngines(script: [script])
34+ try await withLiveServer(engines: engines) { client in
35+ let body = try json(try await post(client, simpleRequest()))
36+ let answer = try #require(message(body))
37+ #expect(answer["content"] as? String == "42")
38+ #expect(answer["reasoning_content"] as? String == "Six times seven.")
39+ let usage = try #require(body["usage"] as? [String: Any])
40+ #expect(usage["completion_tokens"] as? Int == 9)
41+ #expect(
42+ (usage["completion_tokens_details"] as? [String: Int]) == ["reasoning_tokens": 2])
43+ }
44+ }
45+
46+ @Test func blankReasoningIsLeftOut() async throws {
47+ // Qwen3 writes an empty <think></think> when told not to think.
48+ let engines = TestEngines(script: [[.thinking("\n\n"), .text("Hi"), .stats(stats)]])
49+ try await withLiveServer(engines: engines) { client in
50+ let body = try json(try await post(client, simpleRequest()))
51+ #expect(message(body)?["reasoning_content"] == nil)
52+ #expect((body["usage"] as? [String: Any])?["completion_tokens_details"] == nil)
53+ }
54+ }
55+
56+ @Test func reasoningStreamsAsDeltas() async throws {
57+ let engines = TestEngines(script: [[.thinking("Hmm."), .text("Yes")]])
58+ try await withLiveServer(engines: engines) { client in
59+ let all = try chunks(try await post(client, simpleRequest(extra: #","stream":true"#)))
60+ #expect(delta(all[1])?["reasoning_content"] as? String == "Hmm.")
61+ #expect(delta(all[1])?["content"] == nil)
62+ #expect(delta(all[2])?["content"] as? String == "Yes")
63+ }
64+ }
65+
66+ static let switches: [(extra: String, thinking: Bool)] = [
67+ (#","reasoning_effort":"high""#, true),
68+ (#","reasoning_effort":"low""#, true),
69+ (#","reasoning_effort":"none""#, false),
70+ (#","reasoning_effort":"minimal""#, false),
71+ (#","chat_template_kwargs":{"enable_thinking":false}"#, false),
72+ (
73+ #","chat_template_kwargs":{"enable_thinking":true,"other":1},"reasoning_effort":"none""#,
74+ true
75+ ),
76+ ]
77+
78+ @Test(arguments: switches)
79+ func requestsTurnThinkingOnOrOff(extra: String, thinking: Bool) async throws {
80+ let engines = TestEngines()
81+ try await withLiveServer(engines: engines) { client in
82+ let response = try await post(client, simpleRequest(extra: extra))
83+ #expect(response.status == .ok)
84+ }
85+ #expect(engines.fake.sessionSetups.first?.generation.thinking == thinking)
86+ }
87+
88+ @Test func configurationDefaultsAndLocksStillApply() async throws {
89+ var settings = testSettings
90+ settings.config = ServerConfig(
91+ defaults: GenerationOverrides(thinking: true),
92+ locked: GenerationOverrides(thinkingBudget: 256))
93+ let engines = TestEngines()
94+ try await withLiveServer(settings, engines: engines) { client in
95+ _ = try await post(client, simpleRequest())
96+ }
97+ try await withLiveServer(settings, engines: engines) { client in
98+ _ = try await post(client, simpleRequest(extra: #","thinking_budget":1000"#))
99+ }
100+ let setups = engines.fake.sessionSetups.map(\.generation)
101+ // The default applies when the request says nothing.
102+ #expect(setups.map(\.thinking) == [true, true])
103+ #expect(setups.map(\.thinkingBudget) == [256, 256]) // the lock is a ceiling
104+
105+ settings.config.locked = GenerationOverrides(thinking: false)
106+ try await withLiveServer(settings, engines: engines) { client in
107+ _ = try await post(client, simpleRequest(extra: #","reasoning_effort":"high""#))
108+ }
109+ #expect(engines.fake.sessionSetups.last?.generation.thinking == false)
110+ }
111+
112+ static let invalid: [(extra: String, param: String)] = [
113+ (#","reasoning_effort":"extreme""#, "reasoning_effort"),
114+ (#","thinking_budget":-1"#, "thinking_budget"),
115+ (#","chat_template_kwargs":{"enable_thinking":"yes"}"#, "chat_template_kwargs"),
116+ ]
117+
118+ @Test(arguments: invalid)
119+ func invalidSwitchesAre400s(extra: String, param: String) async throws {
120+ try await withLiveServer { client in
121+ let response = try await post(client, simpleRequest(extra: extra))
122+ #expect(response.status == .badRequest)
123+ let error = try ErrorBody(response).error
124+ #expect(error.param == param)
125+ }
126+ }
127+
128+ @Test func engineRefusingASettingIsA400() async throws {
129+ let engines = TestEngines(failure: ([], BadBudget()))
130+ try await withLiveServer(engines: engines) { client in
131+ let response = try await post(client, simpleRequest())
132+ #expect(response.status == .badRequest)
133+ let error = try ErrorBody(response).error
134+ #expect(error.param == "thinking_budget" && error.message == "no thinking protocol")
135+ }
136+ }
137+}
new file mode 100644
@@ -0,0 +1,137 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import RazorbillCore
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+/// The body of a response as loose JSON.
10+func json(_ response: TestResponse) throws -> [String: Any] {
11+ try #require(
12+ try JSONSerialization.jsonObject(with: Data(buffer: response.body)) as? [String: Any])
13+}
14+
15+/// `choices[0].message` of a `chat.completion`.
16+func message(_ body: [String: Any]) -> [String: Any]? {
17+ ((body["choices"] as? [[String: Any]])?.first)?["message"] as? [String: Any]
18+}
19+
20+struct BadBudget: RequestSettingError {
21+ var parameter: String { "thinking_budget" }
22+ var description: String { "no thinking protocol" }
23+}
24+
25+@Suite struct ReasoningTests {
26+ let stats = GenerationStats(promptTokens: 4, generatedTokens: 9, tokensPerSecond: 1)
27+
28+ @Test func reasoningComesApartFromTheAnswer() async throws {
29+ let script: [EngineEvent] = [
30+ .thinking("\n"), .thinking("Six times"), .thinking(" seven."), .text("42"),
31+ .stats(stats),
32+ ]
33+ let engines = TestEngines(script: [script])
34+ try await withLiveServer(engines: engines) { client in
35+ let body = try json(try await post(client, simpleRequest()))
36+ let answer = try #require(message(body))
37+ #expect(answer["content"] as? String == "42")
38+ #expect(answer["reasoning_content"] as? String == "Six times seven.")
39+ let usage = try #require(body["usage"] as? [String: Any])
40+ #expect(usage["completion_tokens"] as? Int == 9)
41+ #expect(
42+ (usage["completion_tokens_details"] as? [String: Int]) == ["reasoning_tokens": 2])
43+ }
44+ }
45+
46+ @Test func blankReasoningIsLeftOut() async throws {
47+ // Qwen3 writes an empty <think></think> when told not to think.
48+ let engines = TestEngines(script: [[.thinking("\n\n"), .text("Hi"), .stats(stats)]])
49+ try await withLiveServer(engines: engines) { client in
50+ let body = try json(try await post(client, simpleRequest()))
51+ #expect(message(body)?["reasoning_content"] == nil)
52+ #expect((body["usage"] as? [String: Any])?["completion_tokens_details"] == nil)
53+ }
54+ }
55+
56+ @Test func reasoningStreamsAsDeltas() async throws {
57+ let engines = TestEngines(script: [[.thinking("Hmm."), .text("Yes")]])
58+ try await withLiveServer(engines: engines) { client in
59+ let all = try chunks(try await post(client, simpleRequest(extra: #","stream":true"#)))
60+ #expect(delta(all[1])?["reasoning_content"] as? String == "Hmm.")
61+ #expect(delta(all[1])?["content"] == nil)
62+ #expect(delta(all[2])?["content"] as? String == "Yes")
63+ }
64+ }
65+
66+ static let switches: [(extra: String, thinking: Bool)] = [
67+ (#","reasoning_effort":"high""#, true),
68+ (#","reasoning_effort":"low""#, true),
69+ (#","reasoning_effort":"none""#, false),
70+ (#","reasoning_effort":"minimal""#, false),
71+ (#","chat_template_kwargs":{"enable_thinking":false}"#, false),
72+ (
73+ #","chat_template_kwargs":{"enable_thinking":true,"other":1},"reasoning_effort":"none""#,
74+ true
75+ ),
76+ ]
77+
78+ @Test(arguments: switches)
79+ func requestsTurnThinkingOnOrOff(extra: String, thinking: Bool) async throws {
80+ let engines = TestEngines()
81+ try await withLiveServer(engines: engines) { client in
82+ let response = try await post(client, simpleRequest(extra: extra))
83+ #expect(response.status == .ok)
84+ }
85+ #expect(engines.fake.sessionSetups.first?.generation.thinking == thinking)
86+ }
87+
88+ @Test func configurationDefaultsAndLocksStillApply() async throws {
89+ var settings = testSettings
90+ settings.config = ServerConfig(
91+ defaults: GenerationOverrides(thinking: true),
92+ locked: GenerationOverrides(thinkingBudget: 256))
93+ let engines = TestEngines()
94+ try await withLiveServer(settings, engines: engines) { client in
95+ _ = try await post(client, simpleRequest())
96+ }
97+ try await withLiveServer(settings, engines: engines) { client in
98+ _ = try await post(client, simpleRequest(extra: #","thinking_budget":1000"#))
99+ }
100+ let setups = engines.fake.sessionSetups.map(\.generation)
101+ // The default applies when the request says nothing.
102+ #expect(setups.map(\.thinking) == [true, true])
103+ #expect(setups.map(\.thinkingBudget) == [256, 256]) // the lock is a ceiling
104+
105+ settings.config.locked = GenerationOverrides(thinking: false)
106+ try await withLiveServer(settings, engines: engines) { client in
107+ _ = try await post(client, simpleRequest(extra: #","reasoning_effort":"high""#))
108+ }
109+ #expect(engines.fake.sessionSetups.last?.generation.thinking == false)
110+ }
111+
112+ static let invalid: [(extra: String, param: String)] = [
113+ (#","reasoning_effort":"extreme""#, "reasoning_effort"),
114+ (#","thinking_budget":-1"#, "thinking_budget"),
115+ (#","chat_template_kwargs":{"enable_thinking":"yes"}"#, "chat_template_kwargs"),
116+ ]
117+
118+ @Test(arguments: invalid)
119+ func invalidSwitchesAre400s(extra: String, param: String) async throws {
120+ try await withLiveServer { client in
121+ let response = try await post(client, simpleRequest(extra: extra))
122+ #expect(response.status == .badRequest)
123+ let error = try ErrorBody(response).error
124+ #expect(error.param == param)
125+ }
126+ }
127+
128+ @Test func engineRefusingASettingIsA400() async throws {
129+ let engines = TestEngines(failure: ([], BadBudget()))
130+ try await withLiveServer(engines: engines) { client in
131+ let response = try await post(client, simpleRequest())
132+ #expect(response.status == .badRequest)
133+ let error = try ErrorBody(response).error
134+ #expect(error.param == "thinking_budget" && error.message == "no thinking protocol")
135+ }
136+ }
137+}