v0.2 step 5 — chat completions, non-streaming (#35)
POST /v1/chat/completions: tolerant OpenAI request decoding with 400s naming the field, roles system/developer/user/assistant/tool, text content parts, temperature/top_p/max(_completion)_tokens through the configuration defaults and locks, seed and presence/frequency penalties passed to MLX, stop sequences applied server side without leaking, finish_reason stop/length/tool_calls and usage. The generation is cancelled when the client disconnects (the connection is then closed: Connection: close). Fields not handled yet (n, logprobs, stream, tools, response_format) are refused with a clear 400. Tests: Linux 106, Mac 114 including smoke tests with a real Qwen3-0.6B model; the openai Python SDK works against the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6a3f52a parent: 4d3623e modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +18 -8 | @@ -1,21 +1,23 @@ | ||
| 1 | -# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config (#33), models (#34) | |
| 1 | +# Handoff — 2026-11-25 — v0.2: server foundation (#32), config (#33), models (#34), chat (#35) | |
| 2 | 2 | |
| 3 | 3 | ## State |
| 4 | 4 | Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78). |
| 5 | 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 | 7 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 7 | 8 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 8 | 9 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 9 | 10 | closed. Nothing pushed. |
| 10 | 11 | |
| 11 | 12 | ## Next steps |
| 12 | -1. #35 — `POST /v1/chat/completions` (non-streaming): `models.acquire(name)` → lease → | |
| 13 | - `engine.makeSession(SessionSetup(system:…, generation: lease.model.generation(client: …)))`, | |
| 14 | - release the lease when the answer is complete (for streaming #36: when the stream ends or is | |
| 15 | - cancelled). Task 7 (moved from #34): cancel generation when the client disconnects. | |
| 16 | -2. User check on the Mac: a config with `preload: true` for an MLX model → `rzb serve --config …` | |
| 17 | - → `curl /v1/models` should show `"loaded": true` (never run with a real model yet). | |
| 18 | -3. Open point: a network-exposed server accepting any HF id lets clients trigger downloads. | |
| 13 | +1. #36 streaming: in `ChatCompletionRoute.answer`, when `plan.stream`, return | |
| 14 | + `ServerSentEvents.response(...)` over `CompletionStream.pieces` mapped to `chat.completion.chunk` | |
| 15 | + (first chunk `delta.role`, then `delta.content`, last with `finish_reason`, optional usage chunk | |
| 16 | + with `stream_options.include_usage`). The lease must be released when the stream ends or is | |
| 17 | + cancelled — `withModel` cannot wrap a streamed body: acquire, and release in the body writer. | |
| 18 | +2. #37 reasoning: `CompletionPiece.reasoning` is already produced and dropped in `complete`. | |
| 19 | +3. User check on the Mac: `rzb serve` + openai SDK or curl against a real model over HTTP. | |
| 20 | +4. Open point: a network-exposed server accepting any HF id lets clients trigger downloads. | |
| 19 | 21 | |
| 20 | 22 | ## Watch out for |
| 21 | 23 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -37,6 +39,14 @@ closed. Nothing pushed. | ||
| 37 | 39 | (`$!`, `kill -0`), not by pattern — a false "still running after SIGINT" cost time here. |
| 38 | 40 | - Swift 6.2 crashed ("failed to produce diagnostic") on an untyped `withCheckedThrowingContinuation` |
| 39 | 41 | closure that mutated actor state inline: type the continuation and call an isolated method. |
| 42 | +- Hummingbird's inbound-close helpers need the *original* request body: read the body inside | |
| 43 | + `consumeWithCancellationOnInboundClose`, never `request.decode`/`collectBody` before it | |
| 44 | + (precondition failure). The connection is closed after the response; HummingbirdTesting's | |
| 45 | + client does not reconnect, so tests needing several requests start one server per request. | |
| 46 | +- HummingbirdTesting's live server listens on `localhost` (IPv6 here): raw sockets must resolve | |
| 47 | + `localhost` (getaddrinfo), not hard-code 127.0.0.1. | |
| 48 | +- `@Suite(.enabled(if: Type.member))` referencing its own type is a "circular reference" error: | |
| 49 | + use a file-level constant. | |
| 40 | 50 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 41 | 51 | the requested name. |
| 42 | 52 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
| @@ -1,21 +1,23 @@ | |||
| 1 | -# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config (#33), models (#34) | 1 | +# Handoff — 2026-11-25 — v0.2: server foundation (#32), config (#33), models (#34), chat (#35) |
| 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). |
| 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 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP | 7 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 7 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket | 8 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 8 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task | 9 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 9 | closed. Nothing pushed. | 10 | closed. Nothing pushed. |
| 10 | 11 | ||
| 11 | ## Next steps | 12 | ## Next steps |
| 12 | -1. #35 — `POST /v1/chat/completions` (non-streaming): `models.acquire(name)` → lease → | 13 | +1. #36 streaming: in `ChatCompletionRoute.answer`, when `plan.stream`, return |
| 13 | - `engine.makeSession(SessionSetup(system:…, generation: lease.model.generation(client: …)))`, | 14 | + `ServerSentEvents.response(...)` over `CompletionStream.pieces` mapped to `chat.completion.chunk` |
| 14 | - release the lease when the answer is complete (for streaming #36: when the stream ends or is | 15 | + (first chunk `delta.role`, then `delta.content`, last with `finish_reason`, optional usage chunk |
| 15 | - cancelled). Task 7 (moved from #34): cancel generation when the client disconnects. | 16 | + with `stream_options.include_usage`). The lease must be released when the stream ends or is |
| 16 | -2. User check on the Mac: a config with `preload: true` for an MLX model → `rzb serve --config …` | 17 | + cancelled — `withModel` cannot wrap a streamed body: acquire, and release in the body writer. |
| 17 | - → `curl /v1/models` should show `"loaded": true` (never run with a real model yet). | 18 | +2. #37 reasoning: `CompletionPiece.reasoning` is already produced and dropped in `complete`. |
| 18 | -3. Open point: a network-exposed server accepting any HF id lets clients trigger downloads. | 19 | +3. User check on the Mac: `rzb serve` + openai SDK or curl against a real model over HTTP. |
| 20 | +4. Open point: a network-exposed server accepting any HF id lets clients trigger downloads. | ||
| 19 | 21 | ||
| 20 | ## Watch out for | 22 | ## Watch out for |
| 21 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns | 23 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -37,6 +39,14 @@ closed. Nothing pushed. | |||
| 37 | (`$!`, `kill -0`), not by pattern — a false "still running after SIGINT" cost time here. | 39 | (`$!`, `kill -0`), not by pattern — a false "still running after SIGINT" cost time here. |
| 38 | - Swift 6.2 crashed ("failed to produce diagnostic") on an untyped `withCheckedThrowingContinuation` | 40 | - Swift 6.2 crashed ("failed to produce diagnostic") on an untyped `withCheckedThrowingContinuation` |
| 39 | closure that mutated actor state inline: type the continuation and call an isolated method. | 41 | closure that mutated actor state inline: type the continuation and call an isolated method. |
| 42 | +- Hummingbird's inbound-close helpers need the *original* request body: read the body inside | ||
| 43 | + `consumeWithCancellationOnInboundClose`, never `request.decode`/`collectBody` before it | ||
| 44 | + (precondition failure). The connection is closed after the response; HummingbirdTesting's | ||
| 45 | + client does not reconnect, so tests needing several requests start one server per request. | ||
| 46 | +- HummingbirdTesting's live server listens on `localhost` (IPv6 here): raw sockets must resolve | ||
| 47 | + `localhost` (getaddrinfo), not hard-code 127.0.0.1. | ||
| 48 | +- `@Suite(.enabled(if: Type.member))` referencing its own type is a "circular reference" error: | ||
| 49 | + use a file-level constant. | ||
| 40 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by | 50 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 41 | the requested name. | 51 | the requested name. |
| 42 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. | 52 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
modified
.memory/history.md +10 -0 | @@ -156,3 +156,13 @@ | ||
| 156 | 156 | for a busy model to free a slot (503 instead), batching across requests. A route test caught a |
| 157 | 157 | duplicate listing of loaded declared models (fixed). Linux 89, Mac 94, gate PASS (run #6). #34 |
| 158 | 158 | closed; its "cancel on disconnect" task moved to #35. |
| 159 | +- #35: `POST /v1/chat/completions` (non-streaming). Request DTOs with tolerant decoding and 400s | |
| 160 | + naming the field; developer → system; text parts; seed + presence/frequency penalties passed to | |
| 161 | + mlx-swift-lm (native in 3.32.3); stop sequences server side; finish_reason from | |
| 162 | + `GenerationStats.hitTokenLimit`; cancel on client disconnect via Hummingbird's | |
| 163 | + `consumeWithCancellationOnInboundClose` (forces `Connection: close`; kept because a long | |
| 164 | + generation for a gone client would block the model's queue). Refused until their tickets: n≠1, | |
| 165 | + logprobs, stream, tools, response_format≠text. Rejected: per-request stop strings in the MLX | |
| 166 | + model configuration (shared container). Tests Linux 106, Mac 114 incl. real-model smoke tests; | |
| 167 | + openai Python SDK verified against the Linux binary. Quality gate PASS (run #9, after splitting a | |
| 168 | + nested if-chain in ConfigValue decoding). #35 closed. | |
| @@ -156,3 +156,13 @@ | |||
| 156 | for a busy model to free a slot (503 instead), batching across requests. A route test caught a | 156 | for a busy model to free a slot (503 instead), batching across requests. A route test caught a |
| 157 | duplicate listing of loaded declared models (fixed). Linux 89, Mac 94, gate PASS (run #6). #34 | 157 | duplicate listing of loaded declared models (fixed). Linux 89, Mac 94, gate PASS (run #6). #34 |
| 158 | closed; its "cancel on disconnect" task moved to #35. | 158 | closed; its "cancel on disconnect" task moved to #35. |
| 159 | +- #35: `POST /v1/chat/completions` (non-streaming). Request DTOs with tolerant decoding and 400s | ||
| 160 | + naming the field; developer → system; text parts; seed + presence/frequency penalties passed to | ||
| 161 | + mlx-swift-lm (native in 3.32.3); stop sequences server side; finish_reason from | ||
| 162 | + `GenerationStats.hitTokenLimit`; cancel on client disconnect via Hummingbird's | ||
| 163 | + `consumeWithCancellationOnInboundClose` (forces `Connection: close`; kept because a long | ||
| 164 | + generation for a gone client would block the model's queue). Refused until their tickets: n≠1, | ||
| 165 | + logprobs, stream, tools, response_format≠text. Rejected: per-request stop strings in the MLX | ||
| 166 | + model configuration (shared container). Tests Linux 106, Mac 114 incl. real-model smoke tests; | ||
| 167 | + openai Python SDK verified against the Linux binary. Quality gate PASS (run #9, after splitting a | ||
| 168 | + nested if-chain in ConfigValue decoding). #35 closed. | ||
modified
.memory/summary.md +13 -6 | @@ -7,7 +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 (see Architecture). Decided by the user (#31): the | |
| 10 | +model lifecycle + `/v1/models` #34, non-streaming `POST /v1/chat/completions` #35 (see | |
| 11 | +Architecture). Decided by the user (#31): the | |
| 11 | 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 12 | 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| 13 | 14 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by |
| @@ -41,14 +42,19 @@ Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `Thin | ||
| 41 | 42 | and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS → |
| 42 | 43 | error envelope → API key, `GET /health`, `ServerSentEvents` helper; `ModelManager` actor = load on |
| 43 | 44 | demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService` |
| 44 | -for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`), `RazorbillCLI` (`serve`, | |
| 45 | +for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`; `Chat/`: | |
| 46 | +`ChatCompletionRequest` → `ChatPlan`, `CompletionStream` (engine events → content / reasoning / | |
| 47 | +tool calls / finish + usage, stop sequences), `ChatCompletionRoute`), `RazorbillCLI` (`serve`, | |
| 45 | 48 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` |
| 46 | 49 | runner for tests; `ServerSettings.config` carries the loaded file to the server). |
| 47 | 50 | `rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` |
| 48 | 51 | (options win over the file's `server:` section); `rzb config validate <file>`; example |
| 49 | 52 | `examples/server.yaml`. The API key is read only from the environment (`server.api_key_env` names |
| 50 | 53 | the variable). One engine instance per loaded model (`InferenceEngine.unload()`); the engine is the |
| 51 | -registry's default (`mlx` on the Mac, `fake` on Linux). Next: chat completions (#35). | |
| 54 | +registry's default (`mlx` on the Mac, `fake` on Linux). Chat requests are stateless (fresh session, | |
| 55 | +whole conversation each time, system messages through the template); stop sequences are applied | |
| 56 | +server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer | |
| 57 | +(`Connection: close`) because it watches for client hang-ups. Next: streaming (#36). | |
| 52 | 58 | |
| 53 | 59 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 54 | 60 | |
| @@ -136,7 +142,8 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | ||
| 136 | 142 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 137 | 143 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 138 | 144 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 139 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #34): Linux 89, Mac 94. | |
| 145 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #35): Linux 106, Mac 114 (incl. `ChatSmokeTests`: real | |
| 146 | +Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). | |
| 140 | 147 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 141 | 148 | |
| 142 | 149 | ## mlx-swift-lm API version trap |
| @@ -148,8 +155,8 @@ of the resolved version. | ||
| 148 | 155 | |
| 149 | 156 | ## Not yet established |
| 150 | 157 | |
| 151 | -- A real MLX model loaded through the server (`ModelManager` + `MLXEngine`, e.g. with `preload: true`) | |
| 152 | - on the Mac: not run yet. Whether dropping `MLXEngine`'s container frees GPU memory promptly (no | |
| 158 | +- A real MLX model answers through `ModelManager` + `MLXEngine` (Mac smoke tests, 2026-11-25), but | |
| 159 | + not yet over HTTP with `rzb serve` on the Mac. Whether dropping `MLXEngine`'s container frees GPU memory promptly (no | |
| 153 | 160 | `MLX.GPU.clearCache` call) is unverified. |
| 154 | 161 | |
| 155 | 162 | - Behaviour of the quality skill on macOS (qlty running swiftlint via its plugin) — untested. |
| @@ -7,7 +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 (see Architecture). Decided by the user (#31): the | 10 | +model lifecycle + `/v1/models` #34, non-streaming `POST /v1/chat/completions` #35 (see |
| 11 | +Architecture). Decided by the user (#31): the | ||
| 11 | 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, |
| 12 | 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` |
| 13 | (`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 |
| @@ -41,14 +42,19 @@ Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `Thin | |||
| 41 | and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS → | 42 | and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS → |
| 42 | error envelope → API key, `GET /health`, `ServerSentEvents` helper; `ModelManager` actor = load on | 43 | error envelope → API key, `GET /health`, `ServerSentEvents` helper; `ModelManager` actor = load on |
| 43 | demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService` | 44 | demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService` |
| 44 | -for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`), `RazorbillCLI` (`serve`, | 45 | +for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`; `Chat/`: |
| 46 | +`ChatCompletionRequest` → `ChatPlan`, `CompletionStream` (engine events → content / reasoning / | ||
| 47 | +tool calls / finish + usage, stop sequences), `ChatCompletionRoute`), `RazorbillCLI` (`serve`, | ||
| 45 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` | 48 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` |
| 46 | runner for tests; `ServerSettings.config` carries the loaded file to the server). | 49 | runner for tests; `ServerSettings.config` carries the loaded file to the server). |
| 47 | `rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` | 50 | `rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` |
| 48 | (options win over the file's `server:` section); `rzb config validate <file>`; example | 51 | (options win over the file's `server:` section); `rzb config validate <file>`; example |
| 49 | `examples/server.yaml`. The API key is read only from the environment (`server.api_key_env` names | 52 | `examples/server.yaml`. The API key is read only from the environment (`server.api_key_env` names |
| 50 | the variable). One engine instance per loaded model (`InferenceEngine.unload()`); the engine is the | 53 | the variable). One engine instance per loaded model (`InferenceEngine.unload()`); the engine is the |
| 51 | -registry's default (`mlx` on the Mac, `fake` on Linux). Next: chat completions (#35). | 54 | +registry's default (`mlx` on the Mac, `fake` on Linux). Chat requests are stateless (fresh session, |
| 55 | +whole conversation each time, system messages through the template); stop sequences are applied | ||
| 56 | +server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer | ||
| 57 | +(`Connection: close`) because it watches for client hang-ups. Next: streaming (#36). | ||
| 52 | 58 | ||
| 53 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 59 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 54 | 60 | ||
| @@ -136,7 +142,8 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | |||
| 136 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). | 142 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 137 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped | 143 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 138 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). | 144 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 139 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #34): Linux 89, Mac 94. | 145 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #35): Linux 106, Mac 114 (incl. `ChatSmokeTests`: real |
| 146 | +Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). | ||
| 140 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). | 147 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 141 | 148 | ||
| 142 | ## mlx-swift-lm API version trap | 149 | ## mlx-swift-lm API version trap |
| @@ -148,8 +155,8 @@ of the resolved version. | |||
| 148 | 155 | ||
| 149 | ## Not yet established | 156 | ## Not yet established |
| 150 | 157 | ||
| 151 | -- A real MLX model loaded through the server (`ModelManager` + `MLXEngine`, e.g. with `preload: true`) | 158 | +- A real MLX model answers through `ModelManager` + `MLXEngine` (Mac smoke tests, 2026-11-25), but |
| 152 | - on the Mac: not run yet. Whether dropping `MLXEngine`'s container frees GPU memory promptly (no | 159 | + not yet over HTTP with `rzb serve` on the Mac. Whether dropping `MLXEngine`'s container frees GPU memory promptly (no |
| 153 | `MLX.GPU.clearCache` call) is unverified. | 160 | `MLX.GPU.clearCache` call) is unverified. |
| 154 | 161 | ||
| 155 | - Behaviour of the quality skill on macOS (qlty running swiftlint via its plugin) — untested. | 162 | - Behaviour of the quality skill on macOS (qlty running swiftlint via its plugin) — untested. |
modified
.quality/history.jsonl +4 -0 | @@ -4,3 +4,7 @@ | ||
| 4 | 4 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"} |
| 5 | 5 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "efa10e1", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 105, "complex": 198, "cyclo": 251, "fields": 436, "funcs": 235, "lcom": 56, "lines": 4348, "loc": 3305}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 5, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T08:05:17Z"} |
| 6 | 6 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "b48915d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 122, "complex": 228, "cyclo": 296, "fields": 531, "funcs": 290, "lcom": 63, "lines": 5247, "loc": 4035}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 6, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:12:54Z"} |
| 7 | +{"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 1 (max 0)"], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 156, "complex": 311, "cyclo": 369, "fields": 670, "funcs": 347, "lcom": 73, "lines": 6341, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 7, "smells": 1, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:28:23Z"} | |
| 8 | +{"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)"], "commit": "4d3623e", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "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": 8, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:28:48Z"} | |
| 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"} | |
| @@ -4,3 +4,7 @@ | |||
| 4 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"} | 4 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"} |
| 5 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "efa10e1", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 105, "complex": 198, "cyclo": 251, "fields": 436, "funcs": 235, "lcom": 56, "lines": 4348, "loc": 3305}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 5, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T08:05:17Z"} | 5 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "efa10e1", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 105, "complex": 198, "cyclo": 251, "fields": 436, "funcs": 235, "lcom": 56, "lines": 4348, "loc": 3305}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 5, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T08:05:17Z"} |
| 6 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "b48915d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 122, "complex": 228, "cyclo": 296, "fields": 531, "funcs": 290, "lcom": 63, "lines": 5247, "loc": 4035}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 6, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:12:54Z"} | 6 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "b48915d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 122, "complex": 228, "cyclo": 296, "fields": 531, "funcs": 290, "lcom": 63, "lines": 5247, "loc": 4035}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 6, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:12:54Z"} |
| 7 | +{"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 1 (max 0)"], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 156, "complex": 311, "cyclo": 369, "fields": 670, "funcs": 347, "lcom": 73, "lines": 6341, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 7, "smells": 1, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:28:23Z"} | ||
| 8 | +{"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)"], "commit": "4d3623e", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "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": 8, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:28:48Z"} | ||
| 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"} | ||
added
.quality/report-20261125T122823Z.md +76 -0 | new file mode 100644 | ||
| @@ -0,0 +1,76 @@ | ||
| 1 | +# Quality report — 2026-11-25T12:28:23Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `4d3623e` 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**: #7 (previous: 2026-11-25T12:12:54Z) | |
| 8 | + | |
| 9 | +## Gate violations | |
| 10 | + | |
| 11 | +- code smells: 1 (max 0) | |
| 12 | + | |
| 13 | +## Lint issues (`qlty check`) | |
| 14 | + | |
| 15 | +_none_ | |
| 16 | + | |
| 17 | +### Top rules | |
| 18 | + | |
| 19 | +_none_ | |
| 20 | + | |
| 21 | +### Most affected files | |
| 22 | + | |
| 23 | +_none_ | |
| 24 | + | |
| 25 | +## Code smells (`qlty smells`) | |
| 26 | + | |
| 27 | +Total: **1** (vs previous: +1) | |
| 28 | + | |
| 29 | +| smell | file | line | detail | | |
| 30 | +|---|---|---|---| | |
| 31 | +| qlty:nested-control-flow | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | Deeply nested control flow (level = 5) | | |
| 32 | + | |
| 33 | +## Metrics (`qlty metrics`) | |
| 34 | + | |
| 35 | +| metric | total | vs previous | | |
| 36 | +|---|---|---| | |
| 37 | +| funcs | 347 | +57 | | |
| 38 | +| classes | 156 | +34 | | |
| 39 | +| fields | 670 | +139 | | |
| 40 | +| cyclo | 369 | +73 | | |
| 41 | +| complex | 311 | +83 | | |
| 42 | +| lcom | 73 | +10 | | |
| 43 | +| lines | 6341 | +1094 | | |
| 44 | +| loc | 4948 | +913 | | |
| 45 | + | |
| 46 | +### Most complex files | |
| 47 | + | |
| 48 | +| file | complex | cyclo | loc | | |
| 49 | +|---|---|---|---| | |
| 50 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | |
| 51 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 22 | 14 | 39 | | |
| 52 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 53 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | |
| 54 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | |
| 55 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | |
| 56 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 57 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | |
| 58 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 59 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | |
| 60 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 61 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | |
| 62 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 63 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | |
| 64 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | |
| 65 | + | |
| 66 | +## Trend | |
| 67 | + | |
| 68 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 69 | +|---|---|---|---|---|---|---| | |
| 70 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | |
| 71 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | |
| 72 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | |
| 73 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | |
| 74 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| 75 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 76 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,76 @@ | |||
| 1 | +# Quality report — 2026-11-25T12:28:23Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `4d3623e` 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**: #7 (previous: 2026-11-25T12:12:54Z) | ||
| 8 | + | ||
| 9 | +## Gate violations | ||
| 10 | + | ||
| 11 | +- code smells: 1 (max 0) | ||
| 12 | + | ||
| 13 | +## Lint issues (`qlty check`) | ||
| 14 | + | ||
| 15 | +_none_ | ||
| 16 | + | ||
| 17 | +### Top rules | ||
| 18 | + | ||
| 19 | +_none_ | ||
| 20 | + | ||
| 21 | +### Most affected files | ||
| 22 | + | ||
| 23 | +_none_ | ||
| 24 | + | ||
| 25 | +## Code smells (`qlty smells`) | ||
| 26 | + | ||
| 27 | +Total: **1** (vs previous: +1) | ||
| 28 | + | ||
| 29 | +| smell | file | line | detail | | ||
| 30 | +|---|---|---|---| | ||
| 31 | +| qlty:nested-control-flow | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | Deeply nested control flow (level = 5) | | ||
| 32 | + | ||
| 33 | +## Metrics (`qlty metrics`) | ||
| 34 | + | ||
| 35 | +| metric | total | vs previous | | ||
| 36 | +|---|---|---| | ||
| 37 | +| funcs | 347 | +57 | | ||
| 38 | +| classes | 156 | +34 | | ||
| 39 | +| fields | 670 | +139 | | ||
| 40 | +| cyclo | 369 | +73 | | ||
| 41 | +| complex | 311 | +83 | | ||
| 42 | +| lcom | 73 | +10 | | ||
| 43 | +| lines | 6341 | +1094 | | ||
| 44 | +| loc | 4948 | +913 | | ||
| 45 | + | ||
| 46 | +### Most complex files | ||
| 47 | + | ||
| 48 | +| file | complex | cyclo | loc | | ||
| 49 | +|---|---|---|---| | ||
| 50 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | ||
| 51 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 22 | 14 | 39 | | ||
| 52 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 53 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | ||
| 54 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | ||
| 55 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | ||
| 56 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 57 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | ||
| 58 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 59 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | ||
| 60 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 61 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | ||
| 62 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 63 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | ||
| 64 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | ||
| 65 | + | ||
| 66 | +## Trend | ||
| 67 | + | ||
| 68 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 69 | +|---|---|---|---|---|---|---| | ||
| 70 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | ||
| 71 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | ||
| 72 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | ||
| 73 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | ||
| 74 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
| 75 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 76 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
added
.quality/report-20261125T122848Z.md +81 -0 | new file mode 100644 | ||
| @@ -0,0 +1,81 @@ | ||
| 1 | +# Quality report — 2026-11-25T12:28:48Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `4d3623e` 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**: #8 (previous: 2026-11-25T12:28:23Z) | |
| 8 | + | |
| 9 | +## Gate violations | |
| 10 | + | |
| 11 | +- warning-level issues: 1 (max 0) | |
| 12 | + | |
| 13 | +## Lint issues (`qlty check`) | |
| 14 | + | |
| 15 | +| level | count | vs previous | | |
| 16 | +|---|---|---| | |
| 17 | +| warning | 1 | — | | |
| 18 | + | |
| 19 | +### Top rules | |
| 20 | + | |
| 21 | +| rule | count | | |
| 22 | +|---|---| | |
| 23 | +| swiftlint:opening_brace | 1 | | |
| 24 | + | |
| 25 | +### Most affected files | |
| 26 | + | |
| 27 | +| file | issues | | |
| 28 | +|---|---| | |
| 29 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 1 | | |
| 30 | + | |
| 31 | +## Code smells (`qlty smells`) | |
| 32 | + | |
| 33 | +Total: **0** (vs previous: -1) | |
| 34 | + | |
| 35 | +_none_ | |
| 36 | + | |
| 37 | +## Metrics (`qlty metrics`) | |
| 38 | + | |
| 39 | +| metric | total | vs previous | | |
| 40 | +|---|---|---| | |
| 41 | +| funcs | 349 | +2 | | |
| 42 | +| classes | 156 | ±0 | | |
| 43 | +| fields | 670 | ±0 | | |
| 44 | +| cyclo | 369 | ±0 | | |
| 45 | +| complex | 296 | -15 | | |
| 46 | +| lcom | 73 | ±0 | | |
| 47 | +| lines | 6345 | +4 | | |
| 48 | +| loc | 4948 | ±0 | | |
| 49 | + | |
| 50 | +### Most complex files | |
| 51 | + | |
| 52 | +| file | complex | cyclo | loc | | |
| 53 | +|---|---|---|---| | |
| 54 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | |
| 55 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 56 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | |
| 57 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | |
| 58 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | |
| 59 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 60 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | |
| 61 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 62 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | |
| 63 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 64 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | |
| 65 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 66 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | |
| 67 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | |
| 68 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | |
| 69 | + | |
| 70 | +## Trend | |
| 71 | + | |
| 72 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 73 | +|---|---|---|---|---|---|---| | |
| 74 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | |
| 75 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | |
| 76 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | |
| 77 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | |
| 78 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| 79 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 80 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 81 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,81 @@ | |||
| 1 | +# Quality report — 2026-11-25T12:28:48Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `4d3623e` 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**: #8 (previous: 2026-11-25T12:28:23Z) | ||
| 8 | + | ||
| 9 | +## Gate violations | ||
| 10 | + | ||
| 11 | +- warning-level issues: 1 (max 0) | ||
| 12 | + | ||
| 13 | +## Lint issues (`qlty check`) | ||
| 14 | + | ||
| 15 | +| level | count | vs previous | | ||
| 16 | +|---|---|---| | ||
| 17 | +| warning | 1 | — | | ||
| 18 | + | ||
| 19 | +### Top rules | ||
| 20 | + | ||
| 21 | +| rule | count | | ||
| 22 | +|---|---| | ||
| 23 | +| swiftlint:opening_brace | 1 | | ||
| 24 | + | ||
| 25 | +### Most affected files | ||
| 26 | + | ||
| 27 | +| file | issues | | ||
| 28 | +|---|---| | ||
| 29 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 1 | | ||
| 30 | + | ||
| 31 | +## Code smells (`qlty smells`) | ||
| 32 | + | ||
| 33 | +Total: **0** (vs previous: -1) | ||
| 34 | + | ||
| 35 | +_none_ | ||
| 36 | + | ||
| 37 | +## Metrics (`qlty metrics`) | ||
| 38 | + | ||
| 39 | +| metric | total | vs previous | | ||
| 40 | +|---|---|---| | ||
| 41 | +| funcs | 349 | +2 | | ||
| 42 | +| classes | 156 | ±0 | | ||
| 43 | +| fields | 670 | ±0 | | ||
| 44 | +| cyclo | 369 | ±0 | | ||
| 45 | +| complex | 296 | -15 | | ||
| 46 | +| lcom | 73 | ±0 | | ||
| 47 | +| lines | 6345 | +4 | | ||
| 48 | +| loc | 4948 | ±0 | | ||
| 49 | + | ||
| 50 | +### Most complex files | ||
| 51 | + | ||
| 52 | +| file | complex | cyclo | loc | | ||
| 53 | +|---|---|---|---| | ||
| 54 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | ||
| 55 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 56 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | ||
| 57 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | ||
| 58 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | ||
| 59 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 60 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | ||
| 61 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 62 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | ||
| 63 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 64 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | ||
| 65 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 66 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | ||
| 67 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | ||
| 68 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | ||
| 69 | + | ||
| 70 | +## Trend | ||
| 71 | + | ||
| 72 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 73 | +|---|---|---|---|---|---|---| | ||
| 74 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | ||
| 75 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | ||
| 76 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | ||
| 77 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | ||
| 78 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
| 79 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 80 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 81 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
added
.quality/report-20261125T122903Z.md +74 -0 | new file mode 100644 | ||
| @@ -0,0 +1,74 @@ | ||
| 1 | +# Quality report — 2026-11-25T12:29:03Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `4d3623e` 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**: #9 (previous: 2026-11-25T12:28:48Z) | |
| 8 | + | |
| 9 | +## Lint issues (`qlty check`) | |
| 10 | + | |
| 11 | +| level | count | vs previous | | |
| 12 | +|---|---|---| | |
| 13 | +| warning | 0 | -1 | | |
| 14 | + | |
| 15 | +### Top rules | |
| 16 | + | |
| 17 | +_none_ | |
| 18 | + | |
| 19 | +### Most affected files | |
| 20 | + | |
| 21 | +_none_ | |
| 22 | + | |
| 23 | +## Code smells (`qlty smells`) | |
| 24 | + | |
| 25 | +Total: **0** (vs previous: ±0) | |
| 26 | + | |
| 27 | +_none_ | |
| 28 | + | |
| 29 | +## Metrics (`qlty metrics`) | |
| 30 | + | |
| 31 | +| metric | total | vs previous | | |
| 32 | +|---|---|---| | |
| 33 | +| funcs | 349 | ±0 | | |
| 34 | +| classes | 156 | ±0 | | |
| 35 | +| fields | 670 | ±0 | | |
| 36 | +| cyclo | 369 | ±0 | | |
| 37 | +| complex | 296 | ±0 | | |
| 38 | +| lcom | 73 | ±0 | | |
| 39 | +| lines | 6345 | ±0 | | |
| 40 | +| loc | 4948 | ±0 | | |
| 41 | + | |
| 42 | +### Most complex files | |
| 43 | + | |
| 44 | +| file | complex | cyclo | loc | | |
| 45 | +|---|---|---|---| | |
| 46 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | |
| 47 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 48 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | |
| 49 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | |
| 50 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | |
| 51 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 52 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | |
| 53 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 54 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | |
| 55 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 56 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | |
| 57 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | |
| 59 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | |
| 60 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | |
| 61 | + | |
| 62 | +## Trend | |
| 63 | + | |
| 64 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 65 | +|---|---|---|---|---|---|---| | |
| 66 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | |
| 67 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | |
| 68 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | |
| 69 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | |
| 70 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| 71 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 72 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 73 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 74 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,74 @@ | |||
| 1 | +# Quality report — 2026-11-25T12:29:03Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `4d3623e` 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**: #9 (previous: 2026-11-25T12:28:48Z) | ||
| 8 | + | ||
| 9 | +## Lint issues (`qlty check`) | ||
| 10 | + | ||
| 11 | +| level | count | vs previous | | ||
| 12 | +|---|---|---| | ||
| 13 | +| warning | 0 | -1 | | ||
| 14 | + | ||
| 15 | +### Top rules | ||
| 16 | + | ||
| 17 | +_none_ | ||
| 18 | + | ||
| 19 | +### Most affected files | ||
| 20 | + | ||
| 21 | +_none_ | ||
| 22 | + | ||
| 23 | +## Code smells (`qlty smells`) | ||
| 24 | + | ||
| 25 | +Total: **0** (vs previous: ±0) | ||
| 26 | + | ||
| 27 | +_none_ | ||
| 28 | + | ||
| 29 | +## Metrics (`qlty metrics`) | ||
| 30 | + | ||
| 31 | +| metric | total | vs previous | | ||
| 32 | +|---|---|---| | ||
| 33 | +| funcs | 349 | ±0 | | ||
| 34 | +| classes | 156 | ±0 | | ||
| 35 | +| fields | 670 | ±0 | | ||
| 36 | +| cyclo | 369 | ±0 | | ||
| 37 | +| complex | 296 | ±0 | | ||
| 38 | +| lcom | 73 | ±0 | | ||
| 39 | +| lines | 6345 | ±0 | | ||
| 40 | +| loc | 4948 | ±0 | | ||
| 41 | + | ||
| 42 | +### Most complex files | ||
| 43 | + | ||
| 44 | +| file | complex | cyclo | loc | | ||
| 45 | +|---|---|---|---| | ||
| 46 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | ||
| 47 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 48 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | ||
| 49 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | ||
| 50 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | ||
| 51 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 52 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | ||
| 53 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 54 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | ||
| 55 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 56 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | ||
| 57 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | ||
| 59 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | ||
| 60 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | ||
| 61 | + | ||
| 62 | +## Trend | ||
| 63 | + | ||
| 64 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 65 | +|---|---|---|---|---|---|---| | ||
| 66 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | ||
| 67 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | ||
| 68 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | ||
| 69 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | ||
| 70 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
| 71 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 72 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 73 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 74 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
added
.quality/report-20261125T122906Z.md +73 -0 | new file mode 100644 | ||
| @@ -0,0 +1,73 @@ | ||
| 1 | +# Quality report — 2026-11-25T12:29:06Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `4d3623e` 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**: #10 (previous: 2026-11-25T12:29:03Z) | |
| 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 | 349 | ±0 | | |
| 32 | +| classes | 156 | ±0 | | |
| 33 | +| fields | 670 | ±0 | | |
| 34 | +| cyclo | 369 | ±0 | | |
| 35 | +| complex | 296 | ±0 | | |
| 36 | +| lcom | 73 | ±0 | | |
| 37 | +| lines | 6345 | ±0 | | |
| 38 | +| loc | 4948 | ±0 | | |
| 39 | + | |
| 40 | +### Most complex files | |
| 41 | + | |
| 42 | +| file | complex | cyclo | loc | | |
| 43 | +|---|---|---|---| | |
| 44 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | |
| 45 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 46 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | |
| 47 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | |
| 48 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | |
| 49 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 50 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | |
| 51 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 52 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | |
| 53 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 54 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | |
| 55 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 56 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | |
| 57 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | |
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | |
| 59 | + | |
| 60 | +## Trend | |
| 61 | + | |
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 63 | +|---|---|---|---|---|---|---| | |
| 64 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | |
| 65 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | |
| 66 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | |
| 67 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | |
| 68 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| 69 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 70 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 71 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 72 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 73 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,73 @@ | |||
| 1 | +# Quality report — 2026-11-25T12:29:06Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `4d3623e` 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**: #10 (previous: 2026-11-25T12:29:03Z) | ||
| 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 | 349 | ±0 | | ||
| 32 | +| classes | 156 | ±0 | | ||
| 33 | +| fields | 670 | ±0 | | ||
| 34 | +| cyclo | 369 | ±0 | | ||
| 35 | +| complex | 296 | ±0 | | ||
| 36 | +| lcom | 73 | ±0 | | ||
| 37 | +| lines | 6345 | ±0 | | ||
| 38 | +| loc | 4948 | ±0 | | ||
| 39 | + | ||
| 40 | +### Most complex files | ||
| 41 | + | ||
| 42 | +| file | complex | cyclo | loc | | ||
| 43 | +|---|---|---|---| | ||
| 44 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | ||
| 45 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 46 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | ||
| 47 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | ||
| 48 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | ||
| 49 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 50 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | ||
| 51 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 52 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | ||
| 53 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 54 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | ||
| 55 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 56 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | ||
| 57 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | ||
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | ||
| 59 | + | ||
| 60 | +## Trend | ||
| 61 | + | ||
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 63 | +|---|---|---|---|---|---|---| | ||
| 64 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | ||
| 65 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | ||
| 66 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | ||
| 67 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | ||
| 68 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
| 69 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 70 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 71 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 72 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 73 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
modified
.quality/report-latest.md +21 -17 | @@ -1,10 +1,10 @@ | ||
| 1 | -# Quality report — 2026-11-25T12:12:54Z | |
| 1 | +# Quality report — 2026-11-25T12:29:06Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `b48915d` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `4d3623e` 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**: #6 (previous: 2026-11-25T08:05:17Z) | |
| 7 | +- **Run**: #10 (previous: 2026-11-25T12:29:03Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| @@ -28,34 +28,34 @@ _none_ | ||
| 28 | 28 | |
| 29 | 29 | | metric | total | vs previous | |
| 30 | 30 | |---|---|---| |
| 31 | -| funcs | 290 | +55 | | |
| 32 | -| classes | 122 | +17 | | |
| 33 | -| fields | 531 | +95 | | |
| 34 | -| cyclo | 296 | +45 | | |
| 35 | -| complex | 228 | +30 | | |
| 36 | -| lcom | 63 | +7 | | |
| 37 | -| lines | 5247 | +899 | | |
| 38 | -| loc | 4035 | +730 | | |
| 31 | +| funcs | 349 | ±0 | | |
| 32 | +| classes | 156 | ±0 | | |
| 33 | +| fields | 670 | ±0 | | |
| 34 | +| cyclo | 369 | ±0 | | |
| 35 | +| complex | 296 | ±0 | | |
| 36 | +| lcom | 73 | ±0 | | |
| 37 | +| lines | 6345 | ±0 | | |
| 38 | +| loc | 4948 | ±0 | | |
| 39 | 39 | |
| 40 | 40 | ### Most complex files |
| 41 | 41 | |
| 42 | 42 | | file | complex | cyclo | loc | |
| 43 | 43 | |---|---|---|---| |
| 44 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | |
| 44 | 45 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 45 | -| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 201 | | |
| 46 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | |
| 46 | 47 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | |
| 47 | 48 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | |
| 48 | 49 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 50 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | |
| 49 | 51 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 50 | 52 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | |
| 51 | 53 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 52 | 54 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | |
| 53 | 55 | | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | |
| 54 | -| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 | | |
| 55 | -| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 | | |
| 56 | -| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 | | |
| 57 | -| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 | | |
| 58 | -| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 | | |
| 56 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | |
| 57 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | |
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | |
| 59 | 59 | |
| 60 | 60 | ## Trend |
| 61 | 61 | |
| @@ -67,3 +67,7 @@ _none_ | ||
| 67 | 67 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | |
| 68 | 68 | | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | |
| 69 | 69 | | 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | |
| 70 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 71 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 72 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 73 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| @@ -1,10 +1,10 @@ | |||
| 1 | -# Quality report — 2026-11-25T12:12:54Z | 1 | +# Quality report — 2026-11-25T12:29:06Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `b48915d` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `4d3623e` 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**: #6 (previous: 2026-11-25T08:05:17Z) | 7 | +- **Run**: #10 (previous: 2026-11-25T12:29:03Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| @@ -28,34 +28,34 @@ _none_ | |||
| 28 | 28 | ||
| 29 | | metric | total | vs previous | | 29 | | metric | total | vs previous | |
| 30 | |---|---|---| | 30 | |---|---|---| |
| 31 | -| funcs | 290 | +55 | | 31 | +| funcs | 349 | ±0 | |
| 32 | -| classes | 122 | +17 | | 32 | +| classes | 156 | ±0 | |
| 33 | -| fields | 531 | +95 | | 33 | +| fields | 670 | ±0 | |
| 34 | -| cyclo | 296 | +45 | | 34 | +| cyclo | 369 | ±0 | |
| 35 | -| complex | 228 | +30 | | 35 | +| complex | 296 | ±0 | |
| 36 | -| lcom | 63 | +7 | | 36 | +| lcom | 73 | ±0 | |
| 37 | -| lines | 5247 | +899 | | 37 | +| lines | 6345 | ±0 | |
| 38 | -| loc | 4035 | +730 | | 38 | +| loc | 4948 | ±0 | |
| 39 | 39 | ||
| 40 | ### Most complex files | 40 | ### 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 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | | 45 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 45 | -| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 201 | | 46 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | |
| 46 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | 47 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | |
| 47 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | 48 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | |
| 48 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 49 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 50 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | ||
| 49 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | 51 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 50 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | 52 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | |
| 51 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | 53 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 52 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | 54 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | |
| 53 | | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | 55 | | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | |
| 54 | -| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 | | 56 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | |
| 55 | -| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 | | 57 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | |
| 56 | -| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 | | 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | |
| 57 | -| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 | | ||
| 58 | -| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 | | ||
| 59 | 59 | ||
| 60 | ## Trend | 60 | ## Trend |
| 61 | 61 | ||
| @@ -67,3 +67,7 @@ _none_ | |||
| 67 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | 67 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | |
| 68 | | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | 68 | | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | |
| 69 | | 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | 69 | | 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | |
| 70 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 71 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 72 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 73 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
modified
.tickets/issues/0035-chat-completions-post-v1-chat-completions-non-st.yaml +39 -10 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 35 |
| 3 | 3 | title: "Chat completions: POST /v1/chat/completions (non-streaming)" |
| 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-25T12:20:00.000Z | |
| 9 | +updatedAt: 2026-11-25T12:35:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::server" |
| @@ -34,58 +34,87 @@ body: | | ||
| 34 | 34 | tasks: |
| 35 | 35 | - id: 1 |
| 36 | 36 | title: "OpenAI DTOs for chat requests/responses (Codable, tolerant decoding)" |
| 37 | - state: open | |
| 37 | + state: closed | |
| 38 | 38 | priority: urgent |
| 39 | 39 | author: |
| 40 | 40 | name: k33g |
| 41 | 41 | email: ph.charriere@gmail.com |
| 42 | 42 | createdAt: 2026-11-24T21:17:08.000Z |
| 43 | + updatedAt: 2026-11-25T12:35:00.000Z | |
| 44 | + closedAt: 2026-11-25T12:35:00.000Z | |
| 43 | 45 | - id: 2 |
| 44 | 46 | title: "Map messages to the chat template; content parts; developer role" |
| 45 | - state: open | |
| 47 | + state: closed | |
| 46 | 48 | priority: high |
| 47 | 49 | author: |
| 48 | 50 | name: k33g |
| 49 | 51 | email: ph.charriere@gmail.com |
| 50 | 52 | createdAt: 2026-11-24T21:17:08.000Z |
| 53 | + updatedAt: 2026-11-25T12:35:00.000Z | |
| 54 | + closedAt: 2026-11-25T12:35:00.000Z | |
| 51 | 55 | - id: 3 |
| 52 | 56 | title: "Generation parameters mapping and validation errors" |
| 53 | - state: open | |
| 57 | + state: closed | |
| 54 | 58 | priority: high |
| 55 | 59 | author: |
| 56 | 60 | name: k33g |
| 57 | 61 | email: ph.charriere@gmail.com |
| 58 | 62 | createdAt: 2026-11-24T21:17:08.000Z |
| 63 | + updatedAt: 2026-11-25T12:35:00.000Z | |
| 64 | + closedAt: 2026-11-25T12:35:00.000Z | |
| 59 | 65 | - id: 4 |
| 60 | 66 | title: "Stop sequences without partial leaks" |
| 61 | - state: open | |
| 67 | + state: closed | |
| 62 | 68 | priority: medium |
| 63 | 69 | author: |
| 64 | 70 | name: k33g |
| 65 | 71 | email: ph.charriere@gmail.com |
| 66 | 72 | createdAt: 2026-11-24T21:17:08.000Z |
| 73 | + updatedAt: 2026-11-25T12:35:00.000Z | |
| 74 | + closedAt: 2026-11-25T12:35:00.000Z | |
| 67 | 75 | - id: 5 |
| 68 | 76 | title: "usage and finish_reason" |
| 69 | - state: open | |
| 77 | + state: closed | |
| 70 | 78 | priority: high |
| 71 | 79 | author: |
| 72 | 80 | name: k33g |
| 73 | 81 | email: ph.charriere@gmail.com |
| 74 | 82 | createdAt: 2026-11-24T21:17:08.000Z |
| 83 | + updatedAt: 2026-11-25T12:35:00.000Z | |
| 84 | + closedAt: 2026-11-25T12:35:00.000Z | |
| 75 | 85 | - id: 6 |
| 76 | 86 | title: "Tests with FakeEngine + a Mac smoke test with a real model" |
| 77 | - state: open | |
| 87 | + state: closed | |
| 78 | 88 | priority: high |
| 79 | 89 | author: |
| 80 | 90 | name: k33g |
| 81 | 91 | email: ph.charriere@gmail.com |
| 82 | 92 | createdAt: 2026-11-24T21:17:08.000Z |
| 93 | + updatedAt: 2026-11-25T12:35:00.000Z | |
| 94 | + closedAt: 2026-11-25T12:35:00.000Z | |
| 83 | 95 | - id: 7 |
| 84 | 96 | title: "Cancel generation when the client disconnects (moved from #34)" |
| 85 | - state: open | |
| 97 | + state: closed | |
| 86 | 98 | priority: high |
| 87 | 99 | author: |
| 88 | 100 | name: k33g |
| 89 | 101 | email: ph.charriere@gmail.com |
| 90 | 102 | createdAt: 2026-11-25T12:20:00.000Z |
| 91 | -comments: [] | |
| 103 | + updatedAt: 2026-11-25T12:35:00.000Z | |
| 104 | + closedAt: 2026-11-25T12:35:00.000Z | |
| 105 | +comments: | |
| 106 | + - id: 1 | |
| 107 | + author: | |
| 108 | + name: k33g | |
| 109 | + email: ph.charriere@gmail.com | |
| 110 | + createdAt: 2026-11-25T12:35:00.000Z | |
| 111 | + body: | | |
| 112 | + Done: `POST /v1/chat/completions` (non-streaming). | |
| 113 | + - Request: tolerant decoding (unknown fields ignored), errors are 400s naming the field (`messages[0].role`…). Roles system/developer/user/assistant (with `tool_calls` history)/tool; text content parts joined with a newline, other parts refused. `temperature`, `top_p`, `max_tokens` / `max_completion_tokens` (the latter wins), `seed`, `presence_penalty`, `frequency_penalty` (mlx-swift-lm has all three natively), `stop` (≤ 4). Refused with a clear 400 until their tickets: `n` ≠ 1, `logprobs`, `stream: true` (#36), `tools` (#40), `response_format` other than text (#39). | |
| 114 | + - Settings: configuration defaults → client values → locks (`ChatPlan.settings(for:)`). | |
| 115 | + - Stateless: a fresh engine session per request with the whole conversation (system messages go through the chat template, not `instructions`). | |
| 116 | + - Stop sequences: server side on the decoded text (`StopSequenceFilter`, nothing of a stop leaks); the generation is cancelled at the first match. MLX then reports no counts, so `usage` is approximate in that case (one token per text piece, prompt 0). | |
| 117 | + - `finish_reason`: stop / length (from mlx-swift-lm's `stopReason == .length`, new `GenerationStats.hitTokenLimit`) / tool_calls. Reasoning is not put in `content` (reasoning_content: #37). | |
| 118 | + - Client disconnect cancels the generation (`consumeWithCancellationOnInboundClose`). Side effect: Hummingbird closes the connection after each answer, so the route sends `Connection: close`; the openai Python SDK handles it (3 calls in a row checked). | |
| 119 | + Tests: 14 route tests (incl. a real TCP hang-up), stop filter, JSON; Mac smoke tests with Qwen3-0.6B-4bit (answer, length, stop) — run only when the model is cached. Linux 106, Mac 114. openai SDK checked against the Linux binary (FakeEngine). Quality gate PASS. | |
| 120 | + | |
| @@ -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: 35 | 2 | id: 35 |
| 3 | title: "Chat completions: POST /v1/chat/completions (non-streaming)" | 3 | title: "Chat completions: POST /v1/chat/completions (non-streaming)" |
| 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-25T12:20:00.000Z | 9 | +updatedAt: 2026-11-25T12:35:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::server" | 12 | - "area::server" |
| @@ -34,58 +34,87 @@ body: | | |||
| 34 | tasks: | 34 | tasks: |
| 35 | - id: 1 | 35 | - id: 1 |
| 36 | title: "OpenAI DTOs for chat requests/responses (Codable, tolerant decoding)" | 36 | title: "OpenAI DTOs for chat requests/responses (Codable, tolerant decoding)" |
| 37 | - state: open | 37 | + state: closed |
| 38 | priority: urgent | 38 | priority: urgent |
| 39 | author: | 39 | author: |
| 40 | name: k33g | 40 | name: k33g |
| 41 | email: ph.charriere@gmail.com | 41 | email: ph.charriere@gmail.com |
| 42 | createdAt: 2026-11-24T21:17:08.000Z | 42 | createdAt: 2026-11-24T21:17:08.000Z |
| 43 | + updatedAt: 2026-11-25T12:35:00.000Z | ||
| 44 | + closedAt: 2026-11-25T12:35:00.000Z | ||
| 43 | - id: 2 | 45 | - id: 2 |
| 44 | title: "Map messages to the chat template; content parts; developer role" | 46 | title: "Map messages to the chat template; content parts; developer role" |
| 45 | - state: open | 47 | + state: closed |
| 46 | priority: high | 48 | priority: high |
| 47 | author: | 49 | author: |
| 48 | name: k33g | 50 | name: k33g |
| 49 | email: ph.charriere@gmail.com | 51 | email: ph.charriere@gmail.com |
| 50 | createdAt: 2026-11-24T21:17:08.000Z | 52 | createdAt: 2026-11-24T21:17:08.000Z |
| 53 | + updatedAt: 2026-11-25T12:35:00.000Z | ||
| 54 | + closedAt: 2026-11-25T12:35:00.000Z | ||
| 51 | - id: 3 | 55 | - id: 3 |
| 52 | title: "Generation parameters mapping and validation errors" | 56 | title: "Generation parameters mapping and validation errors" |
| 53 | - state: open | 57 | + state: closed |
| 54 | priority: high | 58 | priority: high |
| 55 | author: | 59 | author: |
| 56 | name: k33g | 60 | name: k33g |
| 57 | email: ph.charriere@gmail.com | 61 | email: ph.charriere@gmail.com |
| 58 | createdAt: 2026-11-24T21:17:08.000Z | 62 | createdAt: 2026-11-24T21:17:08.000Z |
| 63 | + updatedAt: 2026-11-25T12:35:00.000Z | ||
| 64 | + closedAt: 2026-11-25T12:35:00.000Z | ||
| 59 | - id: 4 | 65 | - id: 4 |
| 60 | title: "Stop sequences without partial leaks" | 66 | title: "Stop sequences without partial leaks" |
| 61 | - state: open | 67 | + state: closed |
| 62 | priority: medium | 68 | priority: medium |
| 63 | author: | 69 | author: |
| 64 | name: k33g | 70 | name: k33g |
| 65 | email: ph.charriere@gmail.com | 71 | email: ph.charriere@gmail.com |
| 66 | createdAt: 2026-11-24T21:17:08.000Z | 72 | createdAt: 2026-11-24T21:17:08.000Z |
| 73 | + updatedAt: 2026-11-25T12:35:00.000Z | ||
| 74 | + closedAt: 2026-11-25T12:35:00.000Z | ||
| 67 | - id: 5 | 75 | - id: 5 |
| 68 | title: "usage and finish_reason" | 76 | title: "usage and finish_reason" |
| 69 | - state: open | 77 | + state: closed |
| 70 | priority: high | 78 | priority: high |
| 71 | author: | 79 | author: |
| 72 | name: k33g | 80 | name: k33g |
| 73 | email: ph.charriere@gmail.com | 81 | email: ph.charriere@gmail.com |
| 74 | createdAt: 2026-11-24T21:17:08.000Z | 82 | createdAt: 2026-11-24T21:17:08.000Z |
| 83 | + updatedAt: 2026-11-25T12:35:00.000Z | ||
| 84 | + closedAt: 2026-11-25T12:35:00.000Z | ||
| 75 | - id: 6 | 85 | - id: 6 |
| 76 | title: "Tests with FakeEngine + a Mac smoke test with a real model" | 86 | title: "Tests with FakeEngine + a Mac smoke test with a real model" |
| 77 | - state: open | 87 | + state: closed |
| 78 | priority: high | 88 | priority: high |
| 79 | author: | 89 | author: |
| 80 | name: k33g | 90 | name: k33g |
| 81 | email: ph.charriere@gmail.com | 91 | email: ph.charriere@gmail.com |
| 82 | createdAt: 2026-11-24T21:17:08.000Z | 92 | createdAt: 2026-11-24T21:17:08.000Z |
| 93 | + updatedAt: 2026-11-25T12:35:00.000Z | ||
| 94 | + closedAt: 2026-11-25T12:35:00.000Z | ||
| 83 | - id: 7 | 95 | - id: 7 |
| 84 | title: "Cancel generation when the client disconnects (moved from #34)" | 96 | title: "Cancel generation when the client disconnects (moved from #34)" |
| 85 | - state: open | 97 | + state: closed |
| 86 | priority: high | 98 | priority: high |
| 87 | author: | 99 | author: |
| 88 | name: k33g | 100 | name: k33g |
| 89 | email: ph.charriere@gmail.com | 101 | email: ph.charriere@gmail.com |
| 90 | createdAt: 2026-11-25T12:20:00.000Z | 102 | createdAt: 2026-11-25T12:20:00.000Z |
| 91 | -comments: [] | 103 | + updatedAt: 2026-11-25T12:35:00.000Z |
| 104 | + closedAt: 2026-11-25T12:35:00.000Z | ||
| 105 | +comments: | ||
| 106 | + - id: 1 | ||
| 107 | + author: | ||
| 108 | + name: k33g | ||
| 109 | + email: ph.charriere@gmail.com | ||
| 110 | + createdAt: 2026-11-25T12:35:00.000Z | ||
| 111 | + body: | | ||
| 112 | + Done: `POST /v1/chat/completions` (non-streaming). | ||
| 113 | + - Request: tolerant decoding (unknown fields ignored), errors are 400s naming the field (`messages[0].role`…). Roles system/developer/user/assistant (with `tool_calls` history)/tool; text content parts joined with a newline, other parts refused. `temperature`, `top_p`, `max_tokens` / `max_completion_tokens` (the latter wins), `seed`, `presence_penalty`, `frequency_penalty` (mlx-swift-lm has all three natively), `stop` (≤ 4). Refused with a clear 400 until their tickets: `n` ≠ 1, `logprobs`, `stream: true` (#36), `tools` (#40), `response_format` other than text (#39). | ||
| 114 | + - Settings: configuration defaults → client values → locks (`ChatPlan.settings(for:)`). | ||
| 115 | + - Stateless: a fresh engine session per request with the whole conversation (system messages go through the chat template, not `instructions`). | ||
| 116 | + - Stop sequences: server side on the decoded text (`StopSequenceFilter`, nothing of a stop leaks); the generation is cancelled at the first match. MLX then reports no counts, so `usage` is approximate in that case (one token per text piece, prompt 0). | ||
| 117 | + - `finish_reason`: stop / length (from mlx-swift-lm's `stopReason == .length`, new `GenerationStats.hitTokenLimit`) / tool_calls. Reasoning is not put in `content` (reasoning_content: #37). | ||
| 118 | + - Client disconnect cancels the generation (`consumeWithCancellationOnInboundClose`). Side effect: Hummingbird closes the connection after each answer, so the route sends `Connection: close`; the openai Python SDK handles it (3 calls in a row checked). | ||
| 119 | + Tests: 14 route tests (incl. a real TCP hang-up), stop filter, JSON; Mac smoke tests with Qwen3-0.6B-4bit (answer, length, stop) — run only when the model is cached. Linux 106, Mac 114. openai SDK checked against the Linux binary (FakeEngine). Quality gate PASS. | ||
| 120 | + | ||
modified
Package.swift +3 -1 | @@ -89,7 +89,9 @@ let package = Package( | ||
| 89 | 89 | // Empty on Linux: the MLX engine only exists on macOS. |
| 90 | 90 | .testTarget( |
| 91 | 91 | name: "RazorbillMLXTests", |
| 92 | - dependencies: ["RazorbillMLX", macOnly("MLXLMCommon", "mlx-swift-lm")] | |
| 92 | + dependencies: [ | |
| 93 | + "RazorbillMLX", "RazorbillServer", macOnly("MLXLMCommon", "mlx-swift-lm"), | |
| 94 | + ] | |
| 93 | 95 | ), |
| 94 | 96 | ] |
| 95 | 97 | ) |
| @@ -89,7 +89,9 @@ let package = Package( | |||
| 89 | // Empty on Linux: the MLX engine only exists on macOS. | 89 | // Empty on Linux: the MLX engine only exists on macOS. |
| 90 | .testTarget( | 90 | .testTarget( |
| 91 | name: "RazorbillMLXTests", | 91 | name: "RazorbillMLXTests", |
| 92 | - dependencies: ["RazorbillMLX", macOnly("MLXLMCommon", "mlx-swift-lm")] | 92 | + dependencies: [ |
| 93 | + "RazorbillMLX", "RazorbillServer", macOnly("MLXLMCommon", "mlx-swift-lm"), | ||
| 94 | + ] | ||
| 93 | ), | 95 | ), |
| 94 | ] | 96 | ] |
| 95 | ) | 97 | ) |
added
Sources/RazorbillCore/Config/ConfigValue+JSON.swift +53 -0 | new file mode 100644 | ||
| @@ -0,0 +1,53 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// JSON in and out, for tool-call arguments and JSON schemas sent over the API. | |
| 4 | +/// | |
| 5 | +/// ```swift | |
| 6 | +/// let value = try JSONDecoder().decode(ConfigValue.self, from: Data(#"{"a": [1, true]}"#.utf8)) | |
| 7 | +/// let text = value.jsonString // {"a":[1,true]} | |
| 8 | +/// ``` | |
| 9 | +extension ConfigValue: Codable { | |
| 10 | + public init(from decoder: any Decoder) throws { | |
| 11 | + let container = try decoder.singleValueContainer() | |
| 12 | + self = try Self.scalar(in: container) ?? Self.collection(in: container) | |
| 13 | + } | |
| 14 | + | |
| 15 | + /// `null`, a boolean, a number or a string; `nil` for anything else. | |
| 16 | + private static func scalar(in container: any SingleValueDecodingContainer) -> ConfigValue? { | |
| 17 | + if container.decodeNil() { return .null } | |
| 18 | + if let flag = try? container.decode(Bool.self) { return .bool(flag) } | |
| 19 | + if let number = try? container.decode(Int.self) { return .int(number) } | |
| 20 | + if let number = try? container.decode(Double.self) { return .double(number) } | |
| 21 | + if let text = try? container.decode(String.self) { return .string(text) } | |
| 22 | + return nil | |
| 23 | + } | |
| 24 | + | |
| 25 | + /// An array or an object. | |
| 26 | + private static func collection( | |
| 27 | + in container: any SingleValueDecodingContainer | |
| 28 | + ) throws -> ConfigValue { | |
| 29 | + if let items = try? container.decode([ConfigValue].self) { return .list(items) } | |
| 30 | + return .map(try container.decode([String: ConfigValue].self)) | |
| 31 | + } | |
| 32 | + | |
| 33 | + public func encode(to encoder: any Encoder) throws { | |
| 34 | + var container = encoder.singleValueContainer() | |
| 35 | + switch self { | |
| 36 | + case .null: try container.encodeNil() | |
| 37 | + case .bool(let flag): try container.encode(flag) | |
| 38 | + case .int(let number): try container.encode(number) | |
| 39 | + case .double(let number): try container.encode(number) | |
| 40 | + case .string(let text): try container.encode(text) | |
| 41 | + case .list(let items): try container.encode(items) | |
| 42 | + case .map(let entries): try container.encode(entries) | |
| 43 | + } | |
| 44 | + } | |
| 45 | + | |
| 46 | + /// Compact JSON with sorted keys. | |
| 47 | + public var jsonString: String { | |
| 48 | + let encoder = JSONEncoder() | |
| 49 | + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] | |
| 50 | + let data = (try? encoder.encode(self)) ?? Data("null".utf8) | |
| 51 | + return String(bytes: data, encoding: .utf8) ?? "null" | |
| 52 | + } | |
| 53 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,53 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// JSON in and out, for tool-call arguments and JSON schemas sent over the API. | ||
| 4 | +/// | ||
| 5 | +/// ```swift | ||
| 6 | +/// let value = try JSONDecoder().decode(ConfigValue.self, from: Data(#"{"a": [1, true]}"#.utf8)) | ||
| 7 | +/// let text = value.jsonString // {"a":[1,true]} | ||
| 8 | +/// ``` | ||
| 9 | +extension ConfigValue: Codable { | ||
| 10 | + public init(from decoder: any Decoder) throws { | ||
| 11 | + let container = try decoder.singleValueContainer() | ||
| 12 | + self = try Self.scalar(in: container) ?? Self.collection(in: container) | ||
| 13 | + } | ||
| 14 | + | ||
| 15 | + /// `null`, a boolean, a number or a string; `nil` for anything else. | ||
| 16 | + private static func scalar(in container: any SingleValueDecodingContainer) -> ConfigValue? { | ||
| 17 | + if container.decodeNil() { return .null } | ||
| 18 | + if let flag = try? container.decode(Bool.self) { return .bool(flag) } | ||
| 19 | + if let number = try? container.decode(Int.self) { return .int(number) } | ||
| 20 | + if let number = try? container.decode(Double.self) { return .double(number) } | ||
| 21 | + if let text = try? container.decode(String.self) { return .string(text) } | ||
| 22 | + return nil | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + /// An array or an object. | ||
| 26 | + private static func collection( | ||
| 27 | + in container: any SingleValueDecodingContainer | ||
| 28 | + ) throws -> ConfigValue { | ||
| 29 | + if let items = try? container.decode([ConfigValue].self) { return .list(items) } | ||
| 30 | + return .map(try container.decode([String: ConfigValue].self)) | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + public func encode(to encoder: any Encoder) throws { | ||
| 34 | + var container = encoder.singleValueContainer() | ||
| 35 | + switch self { | ||
| 36 | + case .null: try container.encodeNil() | ||
| 37 | + case .bool(let flag): try container.encode(flag) | ||
| 38 | + case .int(let number): try container.encode(number) | ||
| 39 | + case .double(let number): try container.encode(number) | ||
| 40 | + case .string(let text): try container.encode(text) | ||
| 41 | + case .list(let items): try container.encode(items) | ||
| 42 | + case .map(let entries): try container.encode(entries) | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// Compact JSON with sorted keys. | ||
| 47 | + public var jsonString: String { | ||
| 48 | + let encoder = JSONEncoder() | ||
| 49 | + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] | ||
| 50 | + let data = (try? encoder.encode(self)) ?? Data("null".utf8) | ||
| 51 | + return String(bytes: data, encoding: .utf8) ?? "null" | ||
| 52 | + } | ||
| 53 | +} | ||
modified
Sources/RazorbillCore/Engine/GenerationSettings.swift +11 -1 | @@ -15,15 +15,25 @@ public struct GenerationSettings: Sendable, Equatable { | ||
| 15 | 15 | /// Most tokens a model may spend thinking before it is made to answer; `nil` = no limit. |
| 16 | 16 | /// Counted inside ``maxTokens``, so it must be smaller. Default `nil`. |
| 17 | 17 | public var thinkingBudget: Int? |
| 18 | + /// Seed of the sampler, for reproducible answers at the same settings; `nil` = random. | |
| 19 | + public var seed: UInt64? | |
| 20 | + /// Additive penalty for tokens already present in the answer (OpenAI's `presence_penalty`). | |
| 21 | + public var presencePenalty: Double? | |
| 22 | + /// Penalty growing with how often a token already appeared (OpenAI's `frequency_penalty`). | |
| 23 | + public var frequencyPenalty: Double? | |
| 18 | 24 | |
| 19 | 25 | public init( |
| 20 | 26 | temperature: Double = 0.6, topP: Double = 1.0, maxTokens: Int = 1024, |
| 21 | - thinking: Bool = false, thinkingBudget: Int? = nil | |
| 27 | + thinking: Bool = false, thinkingBudget: Int? = nil, seed: UInt64? = nil, | |
| 28 | + presencePenalty: Double? = nil, frequencyPenalty: Double? = nil | |
| 22 | 29 | ) { |
| 23 | 30 | self.temperature = temperature |
| 24 | 31 | self.topP = topP |
| 25 | 32 | self.maxTokens = maxTokens |
| 26 | 33 | self.thinking = thinking |
| 27 | 34 | self.thinkingBudget = thinkingBudget |
| 35 | + self.seed = seed | |
| 36 | + self.presencePenalty = presencePenalty | |
| 37 | + self.frequencyPenalty = frequencyPenalty | |
| 28 | 38 | } |
| 29 | 39 | } |
| @@ -15,15 +15,25 @@ public struct GenerationSettings: Sendable, Equatable { | |||
| 15 | /// Most tokens a model may spend thinking before it is made to answer; `nil` = no limit. | 15 | /// Most tokens a model may spend thinking before it is made to answer; `nil` = no limit. |
| 16 | /// Counted inside ``maxTokens``, so it must be smaller. Default `nil`. | 16 | /// Counted inside ``maxTokens``, so it must be smaller. Default `nil`. |
| 17 | public var thinkingBudget: Int? | 17 | public var thinkingBudget: Int? |
| 18 | + /// Seed of the sampler, for reproducible answers at the same settings; `nil` = random. | ||
| 19 | + public var seed: UInt64? | ||
| 20 | + /// Additive penalty for tokens already present in the answer (OpenAI's `presence_penalty`). | ||
| 21 | + public var presencePenalty: Double? | ||
| 22 | + /// Penalty growing with how often a token already appeared (OpenAI's `frequency_penalty`). | ||
| 23 | + public var frequencyPenalty: Double? | ||
| 18 | 24 | ||
| 19 | public init( | 25 | public init( |
| 20 | temperature: Double = 0.6, topP: Double = 1.0, maxTokens: Int = 1024, | 26 | temperature: Double = 0.6, topP: Double = 1.0, maxTokens: Int = 1024, |
| 21 | - thinking: Bool = false, thinkingBudget: Int? = nil | 27 | + thinking: Bool = false, thinkingBudget: Int? = nil, seed: UInt64? = nil, |
| 28 | + presencePenalty: Double? = nil, frequencyPenalty: Double? = nil | ||
| 22 | ) { | 29 | ) { |
| 23 | self.temperature = temperature | 30 | self.temperature = temperature |
| 24 | self.topP = topP | 31 | self.topP = topP |
| 25 | self.maxTokens = maxTokens | 32 | self.maxTokens = maxTokens |
| 26 | self.thinking = thinking | 33 | self.thinking = thinking |
| 27 | self.thinkingBudget = thinkingBudget | 34 | self.thinkingBudget = thinkingBudget |
| 35 | + self.seed = seed | ||
| 36 | + self.presencePenalty = presencePenalty | ||
| 37 | + self.frequencyPenalty = frequencyPenalty | ||
| 28 | } | 38 | } |
| 29 | } | 39 | } |
modified
Sources/RazorbillCore/Engine/Messages.swift +7 -1 | @@ -89,10 +89,16 @@ public struct GenerationStats: Sendable, Equatable { | ||
| 89 | 89 | public var promptTokens: Int |
| 90 | 90 | public var generatedTokens: Int |
| 91 | 91 | public var tokensPerSecond: Double |
| 92 | + /// The answer was cut because it reached `maxTokens`. | |
| 93 | + public var hitTokenLimit: Bool | |
| 92 | 94 | |
| 93 | - public init(promptTokens: Int, generatedTokens: Int, tokensPerSecond: Double) { | |
| 95 | + public init( | |
| 96 | + promptTokens: Int, generatedTokens: Int, tokensPerSecond: Double, | |
| 97 | + hitTokenLimit: Bool = false | |
| 98 | + ) { | |
| 94 | 99 | self.promptTokens = promptTokens |
| 95 | 100 | self.generatedTokens = generatedTokens |
| 96 | 101 | self.tokensPerSecond = tokensPerSecond |
| 102 | + self.hitTokenLimit = hitTokenLimit | |
| 97 | 103 | } |
| 98 | 104 | } |
| @@ -89,10 +89,16 @@ public struct GenerationStats: Sendable, Equatable { | |||
| 89 | public var promptTokens: Int | 89 | public var promptTokens: Int |
| 90 | public var generatedTokens: Int | 90 | public var generatedTokens: Int |
| 91 | public var tokensPerSecond: Double | 91 | public var tokensPerSecond: Double |
| 92 | + /// The answer was cut because it reached `maxTokens`. | ||
| 93 | + public var hitTokenLimit: Bool | ||
| 92 | 94 | ||
| 93 | - public init(promptTokens: Int, generatedTokens: Int, tokensPerSecond: Double) { | 95 | + public init( |
| 96 | + promptTokens: Int, generatedTokens: Int, tokensPerSecond: Double, | ||
| 97 | + hitTokenLimit: Bool = false | ||
| 98 | + ) { | ||
| 94 | self.promptTokens = promptTokens | 99 | self.promptTokens = promptTokens |
| 95 | self.generatedTokens = generatedTokens | 100 | self.generatedTokens = generatedTokens |
| 96 | self.tokensPerSecond = tokensPerSecond | 101 | self.tokensPerSecond = tokensPerSecond |
| 102 | + self.hitTokenLimit = hitTokenLimit | ||
| 97 | } | 103 | } |
| 98 | } | 104 | } |
added
Sources/RazorbillCore/Engine/StopSequenceFilter.swift +59 -0 | new file mode 100644 | ||
| @@ -0,0 +1,59 @@ | ||
| 1 | +/// Cuts an answer at the first stop sequence, as the text streams in, without ever letting part | |
| 2 | +/// of a stop sequence through: text that might be the start of one is held back until the next | |
| 3 | +/// piece shows whether it is. | |
| 4 | +/// | |
| 5 | +/// ```swift | |
| 6 | +/// var filter = StopSequenceFilter(["END"]) | |
| 7 | +/// filter.feed("Hello E") // "Hello " ("E" held back) | |
| 8 | +/// filter.feed("ND more") // "" — stopped | |
| 9 | +/// filter.isStopped // true | |
| 10 | +/// ``` | |
| 11 | +public struct StopSequenceFilter: Sendable { | |
| 12 | + public let stops: [String] | |
| 13 | + private var pending = "" | |
| 14 | + /// A stop sequence was found; nothing more comes out. | |
| 15 | + public private(set) var isStopped = false | |
| 16 | + | |
| 17 | + /// Empty strings are ignored. | |
| 18 | + public init(_ stops: [String]) { | |
| 19 | + self.stops = stops.filter { !$0.isEmpty } | |
| 20 | + } | |
| 21 | + | |
| 22 | + /// The part of `text` that can be shown now. | |
| 23 | + public mutating func feed(_ text: String) -> String { | |
| 24 | + guard !isStopped else { return "" } | |
| 25 | + guard !stops.isEmpty else { return text } | |
| 26 | + pending += text | |
| 27 | + if let cut = firstStop(in: pending) { | |
| 28 | + isStopped = true | |
| 29 | + let shown = String(pending[..<cut]) | |
| 30 | + pending = "" | |
| 31 | + return shown | |
| 32 | + } | |
| 33 | + let held = heldBackCount(pending) | |
| 34 | + let shown = String(pending.dropLast(held)) | |
| 35 | + pending = String(pending.suffix(held)) | |
| 36 | + return shown | |
| 37 | + } | |
| 38 | + | |
| 39 | + /// What was held back, once the answer ended without a stop sequence. | |
| 40 | + public mutating func finish() -> String { | |
| 41 | + defer { pending = "" } | |
| 42 | + return isStopped ? "" : pending | |
| 43 | + } | |
| 44 | + | |
| 45 | + /// Start of the earliest stop sequence in `text`. | |
| 46 | + private func firstStop(in text: String) -> String.Index? { | |
| 47 | + stops.compactMap { text.range(of: $0)?.lowerBound }.min() | |
| 48 | + } | |
| 49 | + | |
| 50 | + /// Length of the longest end of `text` that begins a stop sequence. | |
| 51 | + private func heldBackCount(_ text: String) -> Int { | |
| 52 | + let longest = min(text.count, (stops.map(\.count).max() ?? 1) - 1) | |
| 53 | + for length in stride(from: longest, to: 0, by: -1) { | |
| 54 | + let tail = text.suffix(length) | |
| 55 | + if stops.contains(where: { $0.hasPrefix(tail) }) { return length } | |
| 56 | + } | |
| 57 | + return 0 | |
| 58 | + } | |
| 59 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | +/// Cuts an answer at the first stop sequence, as the text streams in, without ever letting part | ||
| 2 | +/// of a stop sequence through: text that might be the start of one is held back until the next | ||
| 3 | +/// piece shows whether it is. | ||
| 4 | +/// | ||
| 5 | +/// ```swift | ||
| 6 | +/// var filter = StopSequenceFilter(["END"]) | ||
| 7 | +/// filter.feed("Hello E") // "Hello " ("E" held back) | ||
| 8 | +/// filter.feed("ND more") // "" — stopped | ||
| 9 | +/// filter.isStopped // true | ||
| 10 | +/// ``` | ||
| 11 | +public struct StopSequenceFilter: Sendable { | ||
| 12 | + public let stops: [String] | ||
| 13 | + private var pending = "" | ||
| 14 | + /// A stop sequence was found; nothing more comes out. | ||
| 15 | + public private(set) var isStopped = false | ||
| 16 | + | ||
| 17 | + /// Empty strings are ignored. | ||
| 18 | + public init(_ stops: [String]) { | ||
| 19 | + self.stops = stops.filter { !$0.isEmpty } | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + /// The part of `text` that can be shown now. | ||
| 23 | + public mutating func feed(_ text: String) -> String { | ||
| 24 | + guard !isStopped else { return "" } | ||
| 25 | + guard !stops.isEmpty else { return text } | ||
| 26 | + pending += text | ||
| 27 | + if let cut = firstStop(in: pending) { | ||
| 28 | + isStopped = true | ||
| 29 | + let shown = String(pending[..<cut]) | ||
| 30 | + pending = "" | ||
| 31 | + return shown | ||
| 32 | + } | ||
| 33 | + let held = heldBackCount(pending) | ||
| 34 | + let shown = String(pending.dropLast(held)) | ||
| 35 | + pending = String(pending.suffix(held)) | ||
| 36 | + return shown | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + /// What was held back, once the answer ended without a stop sequence. | ||
| 40 | + public mutating func finish() -> String { | ||
| 41 | + defer { pending = "" } | ||
| 42 | + return isStopped ? "" : pending | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + /// Start of the earliest stop sequence in `text`. | ||
| 46 | + private func firstStop(in text: String) -> String.Index? { | ||
| 47 | + stops.compactMap { text.range(of: $0)?.lowerBound }.min() | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + /// Length of the longest end of `text` that begins a stop sequence. | ||
| 51 | + private func heldBackCount(_ text: String) -> Int { | ||
| 52 | + let longest = min(text.count, (stops.map(\.count).max() ?? 1) - 1) | ||
| 53 | + for length in stride(from: longest, to: 0, by: -1) { | ||
| 54 | + let tail = text.suffix(length) | ||
| 55 | + if stops.contains(where: { $0.hasPrefix(tail) }) { return length } | ||
| 56 | + } | ||
| 57 | + return 0 | ||
| 58 | + } | ||
| 59 | +} | ||
modified
Sources/RazorbillMLX/MLXEngine.swift +5 -2 | @@ -63,10 +63,13 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 63 | 63 | |
| 64 | 64 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 65 | 65 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } |
| 66 | - let parameters = GenerateParameters( | |
| 66 | + var parameters = GenerateParameters( | |
| 67 | 67 | maxTokens: setup.generation.maxTokens, |
| 68 | 68 | temperature: Float(setup.generation.temperature), |
| 69 | 69 | topP: Float(setup.generation.topP)) |
| 70 | + parameters.seed = setup.generation.seed | |
| 71 | + parameters.presencePenalty = setup.generation.presencePenalty.map(Float.init) | |
| 72 | + parameters.frequencyPenalty = setup.generation.frequencyPenalty.map(Float.init) | |
| 70 | 73 | let session = ChatSession( |
| 71 | 74 | container, |
| 72 | 75 | instructions: setup.system.isEmpty ? nil : setup.system, |
| @@ -200,7 +203,7 @@ enum MLXConversion { | ||
| 200 | 203 | case .info(let info): |
| 201 | 204 | let stats = GenerationStats( |
| 202 | 205 | promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, |
| 203 | - tokensPerSecond: info.tokensPerSecond) | |
| 206 | + tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) | |
| 204 | 207 | return splitter.finish() + [.stats(stats)] |
| 205 | 208 | default: |
| 206 | 209 | return [] |
| @@ -63,10 +63,13 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 63 | 63 | ||
| 64 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 64 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 65 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } | 65 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } |
| 66 | - let parameters = GenerateParameters( | 66 | + var parameters = GenerateParameters( |
| 67 | maxTokens: setup.generation.maxTokens, | 67 | maxTokens: setup.generation.maxTokens, |
| 68 | temperature: Float(setup.generation.temperature), | 68 | temperature: Float(setup.generation.temperature), |
| 69 | topP: Float(setup.generation.topP)) | 69 | topP: Float(setup.generation.topP)) |
| 70 | + parameters.seed = setup.generation.seed | ||
| 71 | + parameters.presencePenalty = setup.generation.presencePenalty.map(Float.init) | ||
| 72 | + parameters.frequencyPenalty = setup.generation.frequencyPenalty.map(Float.init) | ||
| 70 | let session = ChatSession( | 73 | let session = ChatSession( |
| 71 | container, | 74 | container, |
| 72 | instructions: setup.system.isEmpty ? nil : setup.system, | 75 | instructions: setup.system.isEmpty ? nil : setup.system, |
| @@ -200,7 +203,7 @@ enum MLXConversion { | |||
| 200 | case .info(let info): | 203 | case .info(let info): |
| 201 | let stats = GenerationStats( | 204 | let stats = GenerationStats( |
| 202 | promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, | 205 | promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, |
| 203 | - tokensPerSecond: info.tokensPerSecond) | 206 | + tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) |
| 204 | return splitter.finish() + [.stats(stats)] | 207 | return splitter.finish() + [.stats(stats)] |
| 205 | default: | 208 | default: |
| 206 | return [] | 209 | return [] |
added
Sources/RazorbillServer/Chat/ChatCompletionRequest.swift +269 -0 | new file mode 100644 | ||
| @@ -0,0 +1,269 @@ | ||
| 1 | +import Foundation | |
| 2 | +import RazorbillCore | |
| 3 | + | |
| 4 | +/// The body of `POST /v1/chat/completions`, as OpenAI clients send it. Unknown fields are | |
| 5 | +/// ignored, like OpenAI does; ``validated()`` turns it into a ``ChatPlan`` or a 400. | |
| 6 | +struct ChatCompletionRequest: Decodable, Sendable { | |
| 7 | + var model: String | |
| 8 | + var messages: [WireMessage] | |
| 9 | + var temperature: Double? | |
| 10 | + var topP: Double? | |
| 11 | + var maxTokens: Int? | |
| 12 | + var maxCompletionTokens: Int? | |
| 13 | + var stop: StopField? | |
| 14 | + var seed: Int64? | |
| 15 | + /// OpenAI's `n`: how many answers to generate. | |
| 16 | + var choiceCount: Int? | |
| 17 | + var presencePenalty: Double? | |
| 18 | + var frequencyPenalty: Double? | |
| 19 | + var stream: Bool? | |
| 20 | + var logprobs: Bool? | |
| 21 | + var tools: ConfigValue? | |
| 22 | + var responseFormat: ConfigValue? | |
| 23 | + | |
| 24 | + enum CodingKeys: String, CodingKey { | |
| 25 | + case model, messages, temperature, stop, seed, stream, logprobs, tools | |
| 26 | + case choiceCount = "n" | |
| 27 | + case topP = "top_p" | |
| 28 | + case maxTokens = "max_tokens" | |
| 29 | + case maxCompletionTokens = "max_completion_tokens" | |
| 30 | + case presencePenalty = "presence_penalty" | |
| 31 | + case frequencyPenalty = "frequency_penalty" | |
| 32 | + case responseFormat = "response_format" | |
| 33 | + } | |
| 34 | + | |
| 35 | + /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. | |
| 36 | + static func decode(_ data: Data) throws -> ChatCompletionRequest { | |
| 37 | + do { | |
| 38 | + return try JSONDecoder().decode(ChatCompletionRequest.self, from: data) | |
| 39 | + } catch let error as DecodingError { | |
| 40 | + throw OpenAIError.invalidBody(error) | |
| 41 | + } catch { | |
| 42 | + throw OpenAIError(.badRequest, message: "The body is not valid JSON.") | |
| 43 | + } | |
| 44 | + } | |
| 45 | +} | |
| 46 | + | |
| 47 | +/// `stop`: one string or a list of strings. | |
| 48 | +struct StopField: Decodable, Sendable { | |
| 49 | + let values: [String] | |
| 50 | + | |
| 51 | + init(from decoder: any Decoder) throws { | |
| 52 | + let container = try decoder.singleValueContainer() | |
| 53 | + if let single = try? container.decode(String.self) { | |
| 54 | + values = [single] | |
| 55 | + } else { | |
| 56 | + values = try container.decode([String].self) | |
| 57 | + } | |
| 58 | + } | |
| 59 | +} | |
| 60 | + | |
| 61 | +/// One message of `messages`. | |
| 62 | +struct WireMessage: Decodable, Sendable { | |
| 63 | + var role: String | |
| 64 | + var content: WireContent? | |
| 65 | + var toolCalls: [WireToolCall]? | |
| 66 | + var toolCallID: String? | |
| 67 | + var name: String? | |
| 68 | + | |
| 69 | + enum CodingKeys: String, CodingKey { | |
| 70 | + case role, content, name | |
| 71 | + case toolCalls = "tool_calls" | |
| 72 | + case toolCallID = "tool_call_id" | |
| 73 | + } | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// `content`: a string, or a list of parts (`{"type": "text", "text": …}`, images…). | |
| 77 | +enum WireContent: Decodable, Sendable { | |
| 78 | + case text(String) | |
| 79 | + case parts([Part]) | |
| 80 | + | |
| 81 | + struct Part: Decodable, Sendable { | |
| 82 | + let type: String | |
| 83 | + let text: String? | |
| 84 | + } | |
| 85 | + | |
| 86 | + init(from decoder: any Decoder) throws { | |
| 87 | + let container = try decoder.singleValueContainer() | |
| 88 | + if let text = try? container.decode(String.self) { | |
| 89 | + self = .text(text) | |
| 90 | + } else { | |
| 91 | + self = .parts(try container.decode([Part].self)) | |
| 92 | + } | |
| 93 | + } | |
| 94 | +} | |
| 95 | + | |
| 96 | +/// A tool call of an assistant message in the history. | |
| 97 | +struct WireToolCall: Codable, Sendable { | |
| 98 | + struct Function: Codable, Sendable { | |
| 99 | + let name: String | |
| 100 | + /// JSON text, as OpenAI sends it. | |
| 101 | + let arguments: String | |
| 102 | + } | |
| 103 | + | |
| 104 | + var id: String? | |
| 105 | + var type: String? = "function" | |
| 106 | + let function: Function | |
| 107 | +} | |
| 108 | + | |
| 109 | +/// A validated request, ready to run. | |
| 110 | +struct ChatPlan: Sendable { | |
| 111 | + var model: String | |
| 112 | + var messages: [ChatMessage] | |
| 113 | + /// Sampling values the client sent (configuration `defaults` / `locked` still apply). | |
| 114 | + var client: GenerationOverrides | |
| 115 | + var seed: UInt64? | |
| 116 | + var presencePenalty: Double? | |
| 117 | + var frequencyPenalty: Double? | |
| 118 | + var stops: [String] | |
| 119 | + var stream: Bool | |
| 120 | + | |
| 121 | + /// The settings for `model`: its defaults, then the client's values, then its locks. | |
| 122 | + func settings(for model: ResolvedModel) -> GenerationSettings { | |
| 123 | + var settings = model.generation(client: client) | |
| 124 | + settings.seed = seed | |
| 125 | + settings.presencePenalty = presencePenalty | |
| 126 | + settings.frequencyPenalty = frequencyPenalty | |
| 127 | + return settings | |
| 128 | + } | |
| 129 | +} | |
| 130 | + | |
| 131 | +extension ChatCompletionRequest { | |
| 132 | + /// Checks every field and maps the messages; the first problem is a 400 naming its field. | |
| 133 | + func validated() throws -> ChatPlan { | |
| 134 | + try checkUnsupported() | |
| 135 | + let stops = stop?.values ?? [] | |
| 136 | + try require(stops.count <= 4, "stop", "can hold at most 4 sequences") | |
| 137 | + try require(!messages.isEmpty, "messages", "must hold at least one message") | |
| 138 | + try check(temperature, "temperature", "must be between 0 and 2") { (0 ... 2).contains($0) } | |
| 139 | + try check(topP, "top_p", "must be above 0 and at most 1") { $0 > 0 && $0 <= 1 } | |
| 140 | + let limit = maxCompletionTokens ?? maxTokens | |
| 141 | + let limitName = maxCompletionTokens == nil ? "max_tokens" : "max_completion_tokens" | |
| 142 | + try check(limit, limitName, "must be 1 or more") { $0 >= 1 } | |
| 143 | + try check(presencePenalty, "presence_penalty", "must be between -2 and 2") { abs($0) <= 2 } | |
| 144 | + try check(frequencyPenalty, "frequency_penalty", "must be between -2 and 2") { | |
| 145 | + abs($0) <= 2 | |
| 146 | + } | |
| 147 | + return ChatPlan( | |
| 148 | + model: model, | |
| 149 | + messages: try messages.enumerated().map { try Self.message($1, at: $0) }, | |
| 150 | + client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit), | |
| 151 | + seed: seed.map { UInt64(bitPattern: $0) }, | |
| 152 | + presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, | |
| 153 | + stops: stops, stream: stream ?? false) | |
| 154 | + } | |
| 155 | + | |
| 156 | + /// Fields razorbill does not handle yet: refused rather than silently ignored. | |
| 157 | + private func checkUnsupported() throws { | |
| 158 | + try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)") | |
| 159 | + try require(logprobs != true, "logprobs", "is not supported yet") | |
| 160 | + try require(tools == nil, "tools", "is not supported yet (function calling)") | |
| 161 | + let format = responseFormat?["type"]?.stringValue ?? "text" | |
| 162 | + try require( | |
| 163 | + format == "text", "response_format", "only accepts {\"type\": \"text\"} for now") | |
| 164 | + } | |
| 165 | + | |
| 166 | + static func message(_ wire: WireMessage, at index: Int) throws -> ChatMessage { | |
| 167 | + let path = "messages[\(index)]" | |
| 168 | + let text = try content(wire.content, path: path) | |
| 169 | + switch wire.role { | |
| 170 | + case "system", "developer": | |
| 171 | + return ChatMessage(role: .system, content: try required(text, path)) | |
| 172 | + case "user": | |
| 173 | + return ChatMessage(role: .user, content: try required(text, path)) | |
| 174 | + case "assistant": | |
| 175 | + let calls = try (wire.toolCalls ?? []).map { try toolCall($0, path: path) } | |
| 176 | + if calls.isEmpty { _ = try required(text, path) } | |
| 177 | + return ChatMessage(role: .assistant, content: text ?? "", toolCalls: calls) | |
| 178 | + case "tool": | |
| 179 | + return ChatMessage( | |
| 180 | + role: .tool, content: try required(text, path), toolName: wire.name, | |
| 181 | + toolCallID: wire.toolCallID) | |
| 182 | + default: | |
| 183 | + throw OpenAIError( | |
| 184 | + .badRequest, | |
| 185 | + message: "'\(wire.role)' is not a supported role " | |
| 186 | + + "(system, developer, user, assistant, tool).", | |
| 187 | + param: "\(path).role") | |
| 188 | + } | |
| 189 | + } | |
| 190 | + | |
| 191 | + private static func content(_ content: WireContent?, path: String) throws -> String? { | |
| 192 | + switch content { | |
| 193 | + case nil: | |
| 194 | + return nil | |
| 195 | + case .text(let text): | |
| 196 | + return text | |
| 197 | + case .parts(let parts): | |
| 198 | + return try parts.map { part in | |
| 199 | + guard part.type == "text", let text = part.text else { | |
| 200 | + throw OpenAIError( | |
| 201 | + .badRequest, | |
| 202 | + message: "Content parts of type '\(part.type)' are not supported " | |
| 203 | + + "(only text, this model takes no images).", | |
| 204 | + param: "\(path).content") | |
| 205 | + } | |
| 206 | + return text | |
| 207 | + }.joined(separator: "\n") | |
| 208 | + } | |
| 209 | + } | |
| 210 | + | |
| 211 | + private static func required(_ text: String?, _ path: String) throws -> String { | |
| 212 | + guard let text else { | |
| 213 | + throw OpenAIError( | |
| 214 | + .badRequest, message: "This message needs a content.", param: "\(path).content") | |
| 215 | + } | |
| 216 | + return text | |
| 217 | + } | |
| 218 | + | |
| 219 | + private static func toolCall(_ wire: WireToolCall, path: String) throws -> ToolCall { | |
| 220 | + let data = Data(wire.function.arguments.utf8) | |
| 221 | + guard case .map(let arguments)? = try? JSONDecoder().decode(ConfigValue.self, from: data) | |
| 222 | + else { | |
| 223 | + throw OpenAIError( | |
| 224 | + .badRequest, message: "Tool call arguments must be a JSON object.", | |
| 225 | + param: "\(path).tool_calls") | |
| 226 | + } | |
| 227 | + return ToolCall(id: wire.id, name: wire.function.name, arguments: arguments) | |
| 228 | + } | |
| 229 | + | |
| 230 | + private func require(_ condition: Bool, _ param: String, _ message: String) throws { | |
| 231 | + guard condition else { | |
| 232 | + throw OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | |
| 233 | + } | |
| 234 | + } | |
| 235 | + | |
| 236 | + private func check<T>( | |
| 237 | + _ value: T?, _ param: String, _ message: String, _ isValid: (T) -> Bool | |
| 238 | + ) throws { | |
| 239 | + if let value { try require(isValid(value), param, message) } | |
| 240 | + } | |
| 241 | +} | |
| 242 | + | |
| 243 | +extension OpenAIError { | |
| 244 | + /// A 400 for a body that does not match the expected shape, naming the field. | |
| 245 | + static func invalidBody(_ error: DecodingError) -> OpenAIError { | |
| 246 | + func path(_ context: DecodingError.Context) -> String { | |
| 247 | + context.codingPath.map { key in | |
| 248 | + key.intValue.map { "[\($0)]" } ?? ".\(key.stringValue)" | |
| 249 | + }.joined().trimmingCharacters(in: CharacterSet(charactersIn: ".")) | |
| 250 | + } | |
| 251 | + switch error { | |
| 252 | + case .keyNotFound(let key, let context): | |
| 253 | + let field = [path(context), key.stringValue].filter { !$0.isEmpty }.joined( | |
| 254 | + separator: ".") | |
| 255 | + return OpenAIError( | |
| 256 | + .badRequest, message: "Missing required parameter: '\(field)'.", param: field) | |
| 257 | + case .typeMismatch(_, let context), .valueNotFound(_, let context): | |
| 258 | + let field = path(context) | |
| 259 | + return OpenAIError(.badRequest, message: "Invalid type for '\(field)'.", param: field) | |
| 260 | + case .dataCorrupted(let context): | |
| 261 | + let field = path(context) | |
| 262 | + let message = | |
| 263 | + field.isEmpty ? "The body is not valid JSON." : "Invalid value for '\(field)'." | |
| 264 | + return OpenAIError(.badRequest, message: message, param: field.isEmpty ? nil : field) | |
| 265 | + @unknown default: | |
| 266 | + return OpenAIError(.badRequest, message: "Invalid request body.") | |
| 267 | + } | |
| 268 | + } | |
| 269 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,269 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import RazorbillCore | ||
| 3 | + | ||
| 4 | +/// The body of `POST /v1/chat/completions`, as OpenAI clients send it. Unknown fields are | ||
| 5 | +/// ignored, like OpenAI does; ``validated()`` turns it into a ``ChatPlan`` or a 400. | ||
| 6 | +struct ChatCompletionRequest: Decodable, Sendable { | ||
| 7 | + var model: String | ||
| 8 | + var messages: [WireMessage] | ||
| 9 | + var temperature: Double? | ||
| 10 | + var topP: Double? | ||
| 11 | + var maxTokens: Int? | ||
| 12 | + var maxCompletionTokens: Int? | ||
| 13 | + var stop: StopField? | ||
| 14 | + var seed: Int64? | ||
| 15 | + /// OpenAI's `n`: how many answers to generate. | ||
| 16 | + var choiceCount: Int? | ||
| 17 | + var presencePenalty: Double? | ||
| 18 | + var frequencyPenalty: Double? | ||
| 19 | + var stream: Bool? | ||
| 20 | + var logprobs: Bool? | ||
| 21 | + var tools: ConfigValue? | ||
| 22 | + var responseFormat: ConfigValue? | ||
| 23 | + | ||
| 24 | + enum CodingKeys: String, CodingKey { | ||
| 25 | + case model, messages, temperature, stop, seed, stream, logprobs, tools | ||
| 26 | + case choiceCount = "n" | ||
| 27 | + case topP = "top_p" | ||
| 28 | + case maxTokens = "max_tokens" | ||
| 29 | + case maxCompletionTokens = "max_completion_tokens" | ||
| 30 | + case presencePenalty = "presence_penalty" | ||
| 31 | + case frequencyPenalty = "frequency_penalty" | ||
| 32 | + case responseFormat = "response_format" | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. | ||
| 36 | + static func decode(_ data: Data) throws -> ChatCompletionRequest { | ||
| 37 | + do { | ||
| 38 | + return try JSONDecoder().decode(ChatCompletionRequest.self, from: data) | ||
| 39 | + } catch let error as DecodingError { | ||
| 40 | + throw OpenAIError.invalidBody(error) | ||
| 41 | + } catch { | ||
| 42 | + throw OpenAIError(.badRequest, message: "The body is not valid JSON.") | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// `stop`: one string or a list of strings. | ||
| 48 | +struct StopField: Decodable, Sendable { | ||
| 49 | + let values: [String] | ||
| 50 | + | ||
| 51 | + init(from decoder: any Decoder) throws { | ||
| 52 | + let container = try decoder.singleValueContainer() | ||
| 53 | + if let single = try? container.decode(String.self) { | ||
| 54 | + values = [single] | ||
| 55 | + } else { | ||
| 56 | + values = try container.decode([String].self) | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// One message of `messages`. | ||
| 62 | +struct WireMessage: Decodable, Sendable { | ||
| 63 | + var role: String | ||
| 64 | + var content: WireContent? | ||
| 65 | + var toolCalls: [WireToolCall]? | ||
| 66 | + var toolCallID: String? | ||
| 67 | + var name: String? | ||
| 68 | + | ||
| 69 | + enum CodingKeys: String, CodingKey { | ||
| 70 | + case role, content, name | ||
| 71 | + case toolCalls = "tool_calls" | ||
| 72 | + case toolCallID = "tool_call_id" | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// `content`: a string, or a list of parts (`{"type": "text", "text": …}`, images…). | ||
| 77 | +enum WireContent: Decodable, Sendable { | ||
| 78 | + case text(String) | ||
| 79 | + case parts([Part]) | ||
| 80 | + | ||
| 81 | + struct Part: Decodable, Sendable { | ||
| 82 | + let type: String | ||
| 83 | + let text: String? | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + init(from decoder: any Decoder) throws { | ||
| 87 | + let container = try decoder.singleValueContainer() | ||
| 88 | + if let text = try? container.decode(String.self) { | ||
| 89 | + self = .text(text) | ||
| 90 | + } else { | ||
| 91 | + self = .parts(try container.decode([Part].self)) | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// A tool call of an assistant message in the history. | ||
| 97 | +struct WireToolCall: Codable, Sendable { | ||
| 98 | + struct Function: Codable, Sendable { | ||
| 99 | + let name: String | ||
| 100 | + /// JSON text, as OpenAI sends it. | ||
| 101 | + let arguments: String | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + var id: String? | ||
| 105 | + var type: String? = "function" | ||
| 106 | + let function: Function | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// A validated request, ready to run. | ||
| 110 | +struct ChatPlan: Sendable { | ||
| 111 | + var model: String | ||
| 112 | + var messages: [ChatMessage] | ||
| 113 | + /// Sampling values the client sent (configuration `defaults` / `locked` still apply). | ||
| 114 | + var client: GenerationOverrides | ||
| 115 | + var seed: UInt64? | ||
| 116 | + var presencePenalty: Double? | ||
| 117 | + var frequencyPenalty: Double? | ||
| 118 | + var stops: [String] | ||
| 119 | + var stream: Bool | ||
| 120 | + | ||
| 121 | + /// The settings for `model`: its defaults, then the client's values, then its locks. | ||
| 122 | + func settings(for model: ResolvedModel) -> GenerationSettings { | ||
| 123 | + var settings = model.generation(client: client) | ||
| 124 | + settings.seed = seed | ||
| 125 | + settings.presencePenalty = presencePenalty | ||
| 126 | + settings.frequencyPenalty = frequencyPenalty | ||
| 127 | + return settings | ||
| 128 | + } | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +extension ChatCompletionRequest { | ||
| 132 | + /// Checks every field and maps the messages; the first problem is a 400 naming its field. | ||
| 133 | + func validated() throws -> ChatPlan { | ||
| 134 | + try checkUnsupported() | ||
| 135 | + let stops = stop?.values ?? [] | ||
| 136 | + try require(stops.count <= 4, "stop", "can hold at most 4 sequences") | ||
| 137 | + try require(!messages.isEmpty, "messages", "must hold at least one message") | ||
| 138 | + try check(temperature, "temperature", "must be between 0 and 2") { (0 ... 2).contains($0) } | ||
| 139 | + try check(topP, "top_p", "must be above 0 and at most 1") { $0 > 0 && $0 <= 1 } | ||
| 140 | + let limit = maxCompletionTokens ?? maxTokens | ||
| 141 | + let limitName = maxCompletionTokens == nil ? "max_tokens" : "max_completion_tokens" | ||
| 142 | + try check(limit, limitName, "must be 1 or more") { $0 >= 1 } | ||
| 143 | + try check(presencePenalty, "presence_penalty", "must be between -2 and 2") { abs($0) <= 2 } | ||
| 144 | + try check(frequencyPenalty, "frequency_penalty", "must be between -2 and 2") { | ||
| 145 | + abs($0) <= 2 | ||
| 146 | + } | ||
| 147 | + return ChatPlan( | ||
| 148 | + model: model, | ||
| 149 | + messages: try messages.enumerated().map { try Self.message($1, at: $0) }, | ||
| 150 | + client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit), | ||
| 151 | + seed: seed.map { UInt64(bitPattern: $0) }, | ||
| 152 | + presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, | ||
| 153 | + stops: stops, stream: stream ?? false) | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + /// Fields razorbill does not handle yet: refused rather than silently ignored. | ||
| 157 | + private func checkUnsupported() throws { | ||
| 158 | + try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)") | ||
| 159 | + try require(logprobs != true, "logprobs", "is not supported yet") | ||
| 160 | + try require(tools == nil, "tools", "is not supported yet (function calling)") | ||
| 161 | + let format = responseFormat?["type"]?.stringValue ?? "text" | ||
| 162 | + try require( | ||
| 163 | + format == "text", "response_format", "only accepts {\"type\": \"text\"} for now") | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + static func message(_ wire: WireMessage, at index: Int) throws -> ChatMessage { | ||
| 167 | + let path = "messages[\(index)]" | ||
| 168 | + let text = try content(wire.content, path: path) | ||
| 169 | + switch wire.role { | ||
| 170 | + case "system", "developer": | ||
| 171 | + return ChatMessage(role: .system, content: try required(text, path)) | ||
| 172 | + case "user": | ||
| 173 | + return ChatMessage(role: .user, content: try required(text, path)) | ||
| 174 | + case "assistant": | ||
| 175 | + let calls = try (wire.toolCalls ?? []).map { try toolCall($0, path: path) } | ||
| 176 | + if calls.isEmpty { _ = try required(text, path) } | ||
| 177 | + return ChatMessage(role: .assistant, content: text ?? "", toolCalls: calls) | ||
| 178 | + case "tool": | ||
| 179 | + return ChatMessage( | ||
| 180 | + role: .tool, content: try required(text, path), toolName: wire.name, | ||
| 181 | + toolCallID: wire.toolCallID) | ||
| 182 | + default: | ||
| 183 | + throw OpenAIError( | ||
| 184 | + .badRequest, | ||
| 185 | + message: "'\(wire.role)' is not a supported role " | ||
| 186 | + + "(system, developer, user, assistant, tool).", | ||
| 187 | + param: "\(path).role") | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + private static func content(_ content: WireContent?, path: String) throws -> String? { | ||
| 192 | + switch content { | ||
| 193 | + case nil: | ||
| 194 | + return nil | ||
| 195 | + case .text(let text): | ||
| 196 | + return text | ||
| 197 | + case .parts(let parts): | ||
| 198 | + return try parts.map { part in | ||
| 199 | + guard part.type == "text", let text = part.text else { | ||
| 200 | + throw OpenAIError( | ||
| 201 | + .badRequest, | ||
| 202 | + message: "Content parts of type '\(part.type)' are not supported " | ||
| 203 | + + "(only text, this model takes no images).", | ||
| 204 | + param: "\(path).content") | ||
| 205 | + } | ||
| 206 | + return text | ||
| 207 | + }.joined(separator: "\n") | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + private static func required(_ text: String?, _ path: String) throws -> String { | ||
| 212 | + guard let text else { | ||
| 213 | + throw OpenAIError( | ||
| 214 | + .badRequest, message: "This message needs a content.", param: "\(path).content") | ||
| 215 | + } | ||
| 216 | + return text | ||
| 217 | + } | ||
| 218 | + | ||
| 219 | + private static func toolCall(_ wire: WireToolCall, path: String) throws -> ToolCall { | ||
| 220 | + let data = Data(wire.function.arguments.utf8) | ||
| 221 | + guard case .map(let arguments)? = try? JSONDecoder().decode(ConfigValue.self, from: data) | ||
| 222 | + else { | ||
| 223 | + throw OpenAIError( | ||
| 224 | + .badRequest, message: "Tool call arguments must be a JSON object.", | ||
| 225 | + param: "\(path).tool_calls") | ||
| 226 | + } | ||
| 227 | + return ToolCall(id: wire.id, name: wire.function.name, arguments: arguments) | ||
| 228 | + } | ||
| 229 | + | ||
| 230 | + private func require(_ condition: Bool, _ param: String, _ message: String) throws { | ||
| 231 | + guard condition else { | ||
| 232 | + throw OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | ||
| 233 | + } | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + private func check<T>( | ||
| 237 | + _ value: T?, _ param: String, _ message: String, _ isValid: (T) -> Bool | ||
| 238 | + ) throws { | ||
| 239 | + if let value { try require(isValid(value), param, message) } | ||
| 240 | + } | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +extension OpenAIError { | ||
| 244 | + /// A 400 for a body that does not match the expected shape, naming the field. | ||
| 245 | + static func invalidBody(_ error: DecodingError) -> OpenAIError { | ||
| 246 | + func path(_ context: DecodingError.Context) -> String { | ||
| 247 | + context.codingPath.map { key in | ||
| 248 | + key.intValue.map { "[\($0)]" } ?? ".\(key.stringValue)" | ||
| 249 | + }.joined().trimmingCharacters(in: CharacterSet(charactersIn: ".")) | ||
| 250 | + } | ||
| 251 | + switch error { | ||
| 252 | + case .keyNotFound(let key, let context): | ||
| 253 | + let field = [path(context), key.stringValue].filter { !$0.isEmpty }.joined( | ||
| 254 | + separator: ".") | ||
| 255 | + return OpenAIError( | ||
| 256 | + .badRequest, message: "Missing required parameter: '\(field)'.", param: field) | ||
| 257 | + case .typeMismatch(_, let context), .valueNotFound(_, let context): | ||
| 258 | + let field = path(context) | ||
| 259 | + return OpenAIError(.badRequest, message: "Invalid type for '\(field)'.", param: field) | ||
| 260 | + case .dataCorrupted(let context): | ||
| 261 | + let field = path(context) | ||
| 262 | + let message = | ||
| 263 | + field.isEmpty ? "The body is not valid JSON." : "Invalid value for '\(field)'." | ||
| 264 | + return OpenAIError(.badRequest, message: message, param: field.isEmpty ? nil : field) | ||
| 265 | + @unknown default: | ||
| 266 | + return OpenAIError(.badRequest, message: "Invalid request body.") | ||
| 267 | + } | ||
| 268 | + } | ||
| 269 | +} | ||
added
Sources/RazorbillServer/Chat/ChatCompletionRoute.swift +137 -0 | new file mode 100644 | ||
| @@ -0,0 +1,137 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import RazorbillCore | |
| 4 | + | |
| 5 | +/// `chat.completion`: the answer to a non-streamed request. | |
| 6 | +struct ChatCompletionResponse: Encodable, Sendable { | |
| 7 | + let id: String | |
| 8 | + var object = "chat.completion" | |
| 9 | + let created: Int | |
| 10 | + let model: String | |
| 11 | + let choices: [CompletionChoice] | |
| 12 | + let usage: Usage | |
| 13 | +} | |
| 14 | + | |
| 15 | +/// The one choice of a ``ChatCompletionResponse`` (razorbill answers `n = 1` only). | |
| 16 | +struct CompletionChoice: Encodable, Sendable { | |
| 17 | + var index = 0 | |
| 18 | + let message: AssistantMessage | |
| 19 | + let finishReason: FinishReason | |
| 20 | + | |
| 21 | + enum CodingKeys: String, CodingKey { | |
| 22 | + case index, message, logprobs | |
| 23 | + case finishReason = "finish_reason" | |
| 24 | + } | |
| 25 | + | |
| 26 | + func encode(to encoder: any Encoder) throws { | |
| 27 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 28 | + try container.encode(index, forKey: .index) | |
| 29 | + try container.encode(message, forKey: .message) | |
| 30 | + try container.encodeNil(forKey: .logprobs) | |
| 31 | + try container.encode(finishReason, forKey: .finishReason) | |
| 32 | + } | |
| 33 | +} | |
| 34 | + | |
| 35 | +/// The model's message. `content` is `null` when the model only called tools, like OpenAI. | |
| 36 | +struct AssistantMessage: Encodable, Sendable { | |
| 37 | + var role = "assistant" | |
| 38 | + let content: String? | |
| 39 | + let toolCalls: [WireToolCall] | |
| 40 | + | |
| 41 | + enum CodingKeys: String, CodingKey { | |
| 42 | + case role, content | |
| 43 | + case toolCalls = "tool_calls" | |
| 44 | + } | |
| 45 | + | |
| 46 | + func encode(to encoder: any Encoder) throws { | |
| 47 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 48 | + try container.encode(role, forKey: .role) | |
| 49 | + try container.encode(content, forKey: .content) | |
| 50 | + if !toolCalls.isEmpty { try container.encode(toolCalls, forKey: .toolCalls) } | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// `POST /v1/chat/completions`. | |
| 55 | +/// | |
| 56 | +/// The request is stateless: every call carries the whole conversation, which is rendered with | |
| 57 | +/// the model's chat template in a fresh session. The model is held (other requests for it wait) | |
| 58 | +/// until the answer is complete. If the client disconnects, the generation is cancelled. | |
| 59 | +struct ChatCompletionRoute { | |
| 60 | + let models: ModelManager | |
| 61 | + | |
| 62 | + func add(to router: Router<ServerContext>) { | |
| 63 | + router.post("/v1/chat/completions") { request, context in | |
| 64 | + // Watching for the client hanging up consumes the connection's input, so Hummingbird | |
| 65 | + // closes the connection after the answer: say so, for clients that reuse connections. | |
| 66 | + var response = try await request.body.consumeWithCancellationOnInboundClose { body in | |
| 67 | + do { | |
| 68 | + return try await answer(body, context: context) | |
| 69 | + } catch is CancellationError { | |
| 70 | + throw CancellationError() | |
| 71 | + } catch { | |
| 72 | + return try OpenAIError.converting(error, for: request) | |
| 73 | + .response(from: request, context: context) | |
| 74 | + } | |
| 75 | + } | |
| 76 | + response.headers[.connection] = "close" | |
| 77 | + return response | |
| 78 | + } | |
| 79 | + } | |
| 80 | + | |
| 81 | + func answer(_ body: RequestBody, context: ServerContext) async throws -> Response { | |
| 82 | + let buffer = try await body.collect(upTo: context.maxUploadSize) | |
| 83 | + let plan = try ChatCompletionRequest.decode(Data(buffer: buffer)).validated() | |
| 84 | + guard !plan.stream else { | |
| 85 | + throw OpenAIError( | |
| 86 | + .badRequest, message: "stream: true is not supported yet.", param: "stream") | |
| 87 | + } | |
| 88 | + let response = try await complete(plan) | |
| 89 | + context.usage.record( | |
| 90 | + model: plan.model, promptTokens: response.usage.promptTokens, | |
| 91 | + completionTokens: response.usage.completionTokens) | |
| 92 | + return try jsonResponse(response) | |
| 93 | + } | |
| 94 | + | |
| 95 | + func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse { | |
| 96 | + try await models.withModel(plan.model) { lease in | |
| 97 | + let setup = SessionSetup( | |
| 98 | + system: "", tools: [], generation: plan.settings(for: lease.model)) | |
| 99 | + let session = try await lease.engine.makeSession(setup) | |
| 100 | + let pieces = CompletionStream.pieces( | |
| 101 | + from: session.send(plan.messages), stops: plan.stops) | |
| 102 | + var content = "" | |
| 103 | + var calls: [WireToolCall] = [] | |
| 104 | + var ending = (FinishReason.stop, Usage(promptTokens: 0, completionTokens: 0)) | |
| 105 | + for try await piece in pieces { | |
| 106 | + switch piece { | |
| 107 | + case .content(let text): content += text | |
| 108 | + case .reasoning: break // reasoning_content comes with ticket #37 | |
| 109 | + case .toolCall(let call): calls.append(WireToolCall(call)) | |
| 110 | + case .finished(let reason, let usage): ending = (reason, usage) | |
| 111 | + } | |
| 112 | + } | |
| 113 | + let message = AssistantMessage( | |
| 114 | + content: calls.isEmpty || !content.isEmpty ? content : nil, toolCalls: calls) | |
| 115 | + let choice = CompletionChoice(message: message, finishReason: ending.0) | |
| 116 | + return ChatCompletionResponse( | |
| 117 | + id: Self.newID(), created: Int(Date().timeIntervalSince1970), model: plan.model, | |
| 118 | + choices: [choice], usage: ending.1) | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + /// `chatcmpl-` followed by 24 random hexadecimal digits. | |
| 123 | + static func newID() -> String { | |
| 124 | + "chatcmpl-" | |
| 125 | + + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased().prefix(24) | |
| 126 | + } | |
| 127 | +} | |
| 128 | + | |
| 129 | +extension WireToolCall { | |
| 130 | + /// A call made by the model, with its arguments as JSON text. | |
| 131 | + init(_ call: ToolCall) { | |
| 132 | + self.init( | |
| 133 | + id: call.id ?? "call_" + UUID().uuidString.prefix(8).lowercased(), type: "function", | |
| 134 | + function: Function( | |
| 135 | + name: call.name, arguments: ConfigValue.map(call.arguments).jsonString)) | |
| 136 | + } | |
| 137 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,137 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import RazorbillCore | ||
| 4 | + | ||
| 5 | +/// `chat.completion`: the answer to a non-streamed request. | ||
| 6 | +struct ChatCompletionResponse: Encodable, Sendable { | ||
| 7 | + let id: String | ||
| 8 | + var object = "chat.completion" | ||
| 9 | + let created: Int | ||
| 10 | + let model: String | ||
| 11 | + let choices: [CompletionChoice] | ||
| 12 | + let usage: Usage | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +/// The one choice of a ``ChatCompletionResponse`` (razorbill answers `n = 1` only). | ||
| 16 | +struct CompletionChoice: Encodable, Sendable { | ||
| 17 | + var index = 0 | ||
| 18 | + let message: AssistantMessage | ||
| 19 | + let finishReason: FinishReason | ||
| 20 | + | ||
| 21 | + enum CodingKeys: String, CodingKey { | ||
| 22 | + case index, message, logprobs | ||
| 23 | + case finishReason = "finish_reason" | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + func encode(to encoder: any Encoder) throws { | ||
| 27 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 28 | + try container.encode(index, forKey: .index) | ||
| 29 | + try container.encode(message, forKey: .message) | ||
| 30 | + try container.encodeNil(forKey: .logprobs) | ||
| 31 | + try container.encode(finishReason, forKey: .finishReason) | ||
| 32 | + } | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// The model's message. `content` is `null` when the model only called tools, like OpenAI. | ||
| 36 | +struct AssistantMessage: Encodable, Sendable { | ||
| 37 | + var role = "assistant" | ||
| 38 | + let content: String? | ||
| 39 | + let toolCalls: [WireToolCall] | ||
| 40 | + | ||
| 41 | + enum CodingKeys: String, CodingKey { | ||
| 42 | + case role, content | ||
| 43 | + case toolCalls = "tool_calls" | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + func encode(to encoder: any Encoder) throws { | ||
| 47 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 48 | + try container.encode(role, forKey: .role) | ||
| 49 | + try container.encode(content, forKey: .content) | ||
| 50 | + if !toolCalls.isEmpty { try container.encode(toolCalls, forKey: .toolCalls) } | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// `POST /v1/chat/completions`. | ||
| 55 | +/// | ||
| 56 | +/// The request is stateless: every call carries the whole conversation, which is rendered with | ||
| 57 | +/// the model's chat template in a fresh session. The model is held (other requests for it wait) | ||
| 58 | +/// until the answer is complete. If the client disconnects, the generation is cancelled. | ||
| 59 | +struct ChatCompletionRoute { | ||
| 60 | + let models: ModelManager | ||
| 61 | + | ||
| 62 | + func add(to router: Router<ServerContext>) { | ||
| 63 | + router.post("/v1/chat/completions") { request, context in | ||
| 64 | + // Watching for the client hanging up consumes the connection's input, so Hummingbird | ||
| 65 | + // closes the connection after the answer: say so, for clients that reuse connections. | ||
| 66 | + var response = try await request.body.consumeWithCancellationOnInboundClose { body in | ||
| 67 | + do { | ||
| 68 | + return try await answer(body, context: context) | ||
| 69 | + } catch is CancellationError { | ||
| 70 | + throw CancellationError() | ||
| 71 | + } catch { | ||
| 72 | + return try OpenAIError.converting(error, for: request) | ||
| 73 | + .response(from: request, context: context) | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | + response.headers[.connection] = "close" | ||
| 77 | + return response | ||
| 78 | + } | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + func answer(_ body: RequestBody, context: ServerContext) async throws -> Response { | ||
| 82 | + let buffer = try await body.collect(upTo: context.maxUploadSize) | ||
| 83 | + let plan = try ChatCompletionRequest.decode(Data(buffer: buffer)).validated() | ||
| 84 | + guard !plan.stream else { | ||
| 85 | + throw OpenAIError( | ||
| 86 | + .badRequest, message: "stream: true is not supported yet.", param: "stream") | ||
| 87 | + } | ||
| 88 | + let response = try await complete(plan) | ||
| 89 | + context.usage.record( | ||
| 90 | + model: plan.model, promptTokens: response.usage.promptTokens, | ||
| 91 | + completionTokens: response.usage.completionTokens) | ||
| 92 | + return try jsonResponse(response) | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse { | ||
| 96 | + try await models.withModel(plan.model) { lease in | ||
| 97 | + let setup = SessionSetup( | ||
| 98 | + system: "", tools: [], generation: plan.settings(for: lease.model)) | ||
| 99 | + let session = try await lease.engine.makeSession(setup) | ||
| 100 | + let pieces = CompletionStream.pieces( | ||
| 101 | + from: session.send(plan.messages), stops: plan.stops) | ||
| 102 | + var content = "" | ||
| 103 | + var calls: [WireToolCall] = [] | ||
| 104 | + var ending = (FinishReason.stop, Usage(promptTokens: 0, completionTokens: 0)) | ||
| 105 | + for try await piece in pieces { | ||
| 106 | + switch piece { | ||
| 107 | + case .content(let text): content += text | ||
| 108 | + case .reasoning: break // reasoning_content comes with ticket #37 | ||
| 109 | + case .toolCall(let call): calls.append(WireToolCall(call)) | ||
| 110 | + case .finished(let reason, let usage): ending = (reason, usage) | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + let message = AssistantMessage( | ||
| 114 | + content: calls.isEmpty || !content.isEmpty ? content : nil, toolCalls: calls) | ||
| 115 | + let choice = CompletionChoice(message: message, finishReason: ending.0) | ||
| 116 | + return ChatCompletionResponse( | ||
| 117 | + id: Self.newID(), created: Int(Date().timeIntervalSince1970), model: plan.model, | ||
| 118 | + choices: [choice], usage: ending.1) | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + /// `chatcmpl-` followed by 24 random hexadecimal digits. | ||
| 123 | + static func newID() -> String { | ||
| 124 | + "chatcmpl-" | ||
| 125 | + + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased().prefix(24) | ||
| 126 | + } | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +extension WireToolCall { | ||
| 130 | + /// A call made by the model, with its arguments as JSON text. | ||
| 131 | + init(_ call: ToolCall) { | ||
| 132 | + self.init( | ||
| 133 | + id: call.id ?? "call_" + UUID().uuidString.prefix(8).lowercased(), type: "function", | ||
| 134 | + function: Function( | ||
| 135 | + name: call.name, arguments: ConfigValue.map(call.arguments).jsonString)) | ||
| 136 | + } | ||
| 137 | +} | ||
added
Sources/RazorbillServer/Chat/CompletionStream.swift +111 -0 | new file mode 100644 | ||
| @@ -0,0 +1,111 @@ | ||
| 1 | +import RazorbillCore | |
| 2 | + | |
| 3 | +/// Why an answer ended, in OpenAI's words. | |
| 4 | +enum FinishReason: String, Encodable, Sendable { | |
| 5 | + case stop | |
| 6 | + case length | |
| 7 | + case toolCalls = "tool_calls" | |
| 8 | +} | |
| 9 | + | |
| 10 | +/// Token counts of one answer. | |
| 11 | +struct Usage: Encodable, Equatable, Sendable { | |
| 12 | + let promptTokens: Int | |
| 13 | + let completionTokens: Int | |
| 14 | + var totalTokens: Int { promptTokens + completionTokens } | |
| 15 | + | |
| 16 | + enum CodingKeys: String, CodingKey { | |
| 17 | + case promptTokens = "prompt_tokens" | |
| 18 | + case completionTokens = "completion_tokens" | |
| 19 | + case totalTokens = "total_tokens" | |
| 20 | + } | |
| 21 | + | |
| 22 | + func encode(to encoder: any Encoder) throws { | |
| 23 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 24 | + try container.encode(promptTokens, forKey: .promptTokens) | |
| 25 | + try container.encode(completionTokens, forKey: .completionTokens) | |
| 26 | + try container.encode(totalTokens, forKey: .totalTokens) | |
| 27 | + } | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// What a chat completion produces, piece by piece. Shared by the plain and streamed answers. | |
| 31 | +enum CompletionPiece: Sendable, Equatable { | |
| 32 | + case content(String) | |
| 33 | + case reasoning(String) | |
| 34 | + case toolCall(ToolCall) | |
| 35 | + /// Always the last piece. | |
| 36 | + case finished(FinishReason, Usage) | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// Turns the engine's events into ``CompletionPiece``s: applies the stop sequences (ending the | |
| 40 | +/// generation at the first one), and works out `finish_reason` and `usage`. | |
| 41 | +/// | |
| 42 | +/// When a stop sequence ends the answer, the engine is interrupted before it reports its token | |
| 43 | +/// counts: `usage` then counts one token per piece of text received, and no prompt tokens. | |
| 44 | +enum CompletionStream { | |
| 45 | + static func pieces( | |
| 46 | + from events: AsyncThrowingStream<EngineEvent, Error>, stops: [String] | |
| 47 | + ) -> AsyncThrowingStream<CompletionPiece, Error> { | |
| 48 | + AsyncThrowingStream { continuation in | |
| 49 | + let task = Task { | |
| 50 | + do { | |
| 51 | + var state = State(filter: StopSequenceFilter(stops)) | |
| 52 | + events: for try await event in events { | |
| 53 | + for piece in state.consume(event) { continuation.yield(piece) } | |
| 54 | + if state.filter.isStopped { break events } | |
| 55 | + } | |
| 56 | + for piece in state.finish() { continuation.yield(piece) } | |
| 57 | + continuation.finish() | |
| 58 | + } catch { | |
| 59 | + continuation.finish(throwing: error) | |
| 60 | + } | |
| 61 | + } | |
| 62 | + continuation.onTermination = { _ in task.cancel() } | |
| 63 | + } | |
| 64 | + } | |
| 65 | + | |
| 66 | + /// What has been seen so far. | |
| 67 | + struct State { | |
| 68 | + var filter: StopSequenceFilter | |
| 69 | + var stats: GenerationStats? | |
| 70 | + var calledTools = false | |
| 71 | + var textPieces = 0 | |
| 72 | + | |
| 73 | + mutating func consume(_ event: EngineEvent) -> [CompletionPiece] { | |
| 74 | + switch event { | |
| 75 | + case .text(let text): | |
| 76 | + textPieces += 1 | |
| 77 | + let shown = filter.feed(text) | |
| 78 | + return shown.isEmpty ? [] : [.content(shown)] | |
| 79 | + case .thinking(let text): | |
| 80 | + textPieces += 1 | |
| 81 | + return [.reasoning(text)] | |
| 82 | + case .toolCall(let call): | |
| 83 | + calledTools = true | |
| 84 | + return [.toolCall(call)] | |
| 85 | + case .stats(let stats): | |
| 86 | + self.stats = stats | |
| 87 | + return [] | |
| 88 | + } | |
| 89 | + } | |
| 90 | + | |
| 91 | + mutating func finish() -> [CompletionPiece] { | |
| 92 | + let rest = filter.finish() | |
| 93 | + let reason: FinishReason = | |
| 94 | + if filter.isStopped { | |
| 95 | + .stop | |
| 96 | + } else if calledTools { | |
| 97 | + .toolCalls | |
| 98 | + } else if stats?.hitTokenLimit == true { | |
| 99 | + .length | |
| 100 | + } else { | |
| 101 | + .stop | |
| 102 | + } | |
| 103 | + let usage = | |
| 104 | + stats.map { | |
| 105 | + Usage(promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens) | |
| 106 | + } | |
| 107 | + ?? Usage(promptTokens: 0, completionTokens: textPieces) | |
| 108 | + return (rest.isEmpty ? [] : [.content(rest)]) + [.finished(reason, usage)] | |
| 109 | + } | |
| 110 | + } | |
| 111 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,111 @@ | |||
| 1 | +import RazorbillCore | ||
| 2 | + | ||
| 3 | +/// Why an answer ended, in OpenAI's words. | ||
| 4 | +enum FinishReason: String, Encodable, Sendable { | ||
| 5 | + case stop | ||
| 6 | + case length | ||
| 7 | + case toolCalls = "tool_calls" | ||
| 8 | +} | ||
| 9 | + | ||
| 10 | +/// Token counts of one answer. | ||
| 11 | +struct Usage: Encodable, Equatable, Sendable { | ||
| 12 | + let promptTokens: Int | ||
| 13 | + let completionTokens: Int | ||
| 14 | + var totalTokens: Int { promptTokens + completionTokens } | ||
| 15 | + | ||
| 16 | + enum CodingKeys: String, CodingKey { | ||
| 17 | + case promptTokens = "prompt_tokens" | ||
| 18 | + case completionTokens = "completion_tokens" | ||
| 19 | + case totalTokens = "total_tokens" | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + func encode(to encoder: any Encoder) throws { | ||
| 23 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 24 | + try container.encode(promptTokens, forKey: .promptTokens) | ||
| 25 | + try container.encode(completionTokens, forKey: .completionTokens) | ||
| 26 | + try container.encode(totalTokens, forKey: .totalTokens) | ||
| 27 | + } | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// What a chat completion produces, piece by piece. Shared by the plain and streamed answers. | ||
| 31 | +enum CompletionPiece: Sendable, Equatable { | ||
| 32 | + case content(String) | ||
| 33 | + case reasoning(String) | ||
| 34 | + case toolCall(ToolCall) | ||
| 35 | + /// Always the last piece. | ||
| 36 | + case finished(FinishReason, Usage) | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// Turns the engine's events into ``CompletionPiece``s: applies the stop sequences (ending the | ||
| 40 | +/// generation at the first one), and works out `finish_reason` and `usage`. | ||
| 41 | +/// | ||
| 42 | +/// When a stop sequence ends the answer, the engine is interrupted before it reports its token | ||
| 43 | +/// counts: `usage` then counts one token per piece of text received, and no prompt tokens. | ||
| 44 | +enum CompletionStream { | ||
| 45 | + static func pieces( | ||
| 46 | + from events: AsyncThrowingStream<EngineEvent, Error>, stops: [String] | ||
| 47 | + ) -> AsyncThrowingStream<CompletionPiece, Error> { | ||
| 48 | + AsyncThrowingStream { continuation in | ||
| 49 | + let task = Task { | ||
| 50 | + do { | ||
| 51 | + var state = State(filter: StopSequenceFilter(stops)) | ||
| 52 | + events: for try await event in events { | ||
| 53 | + for piece in state.consume(event) { continuation.yield(piece) } | ||
| 54 | + if state.filter.isStopped { break events } | ||
| 55 | + } | ||
| 56 | + for piece in state.finish() { continuation.yield(piece) } | ||
| 57 | + continuation.finish() | ||
| 58 | + } catch { | ||
| 59 | + continuation.finish(throwing: error) | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + continuation.onTermination = { _ in task.cancel() } | ||
| 63 | + } | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + /// What has been seen so far. | ||
| 67 | + struct State { | ||
| 68 | + var filter: StopSequenceFilter | ||
| 69 | + var stats: GenerationStats? | ||
| 70 | + var calledTools = false | ||
| 71 | + var textPieces = 0 | ||
| 72 | + | ||
| 73 | + mutating func consume(_ event: EngineEvent) -> [CompletionPiece] { | ||
| 74 | + switch event { | ||
| 75 | + case .text(let text): | ||
| 76 | + textPieces += 1 | ||
| 77 | + let shown = filter.feed(text) | ||
| 78 | + return shown.isEmpty ? [] : [.content(shown)] | ||
| 79 | + case .thinking(let text): | ||
| 80 | + textPieces += 1 | ||
| 81 | + return [.reasoning(text)] | ||
| 82 | + case .toolCall(let call): | ||
| 83 | + calledTools = true | ||
| 84 | + return [.toolCall(call)] | ||
| 85 | + case .stats(let stats): | ||
| 86 | + self.stats = stats | ||
| 87 | + return [] | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + mutating func finish() -> [CompletionPiece] { | ||
| 92 | + let rest = filter.finish() | ||
| 93 | + let reason: FinishReason = | ||
| 94 | + if filter.isStopped { | ||
| 95 | + .stop | ||
| 96 | + } else if calledTools { | ||
| 97 | + .toolCalls | ||
| 98 | + } else if stats?.hitTokenLimit == true { | ||
| 99 | + .length | ||
| 100 | + } else { | ||
| 101 | + .stop | ||
| 102 | + } | ||
| 103 | + let usage = | ||
| 104 | + stats.map { | ||
| 105 | + Usage(promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens) | ||
| 106 | + } | ||
| 107 | + ?? Usage(promptTokens: 0, completionTokens: textPieces) | ||
| 108 | + return (rest.isEmpty ? [] : [.content(rest)]) + [.finished(reason, usage)] | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | +} | ||
modified
Sources/RazorbillServer/Middlewares.swift +4 -0 | @@ -11,6 +11,10 @@ struct ErrorEnvelopeMiddleware: RouterMiddleware { | ||
| 11 | 11 | ) async throws -> Response { |
| 12 | 12 | do { |
| 13 | 13 | return try await next(request, context) |
| 14 | + } catch is CancellationError { | |
| 15 | + // The client went away (or the server is stopping): nobody reads this answer. | |
| 16 | + context.logger.info("\(request.method) \(request.uri.path) cancelled") | |
| 17 | + return Response(status: .init(code: 499, reasonPhrase: "Client Closed Request")) | |
| 14 | 18 | } catch { |
| 15 | 19 | if !(error is any HTTPResponseError) { |
| 16 | 20 | context.logger.error("\(request.method) \(request.uri.path) failed: \(error)") |
| @@ -11,6 +11,10 @@ struct ErrorEnvelopeMiddleware: RouterMiddleware { | |||
| 11 | ) async throws -> Response { | 11 | ) async throws -> Response { |
| 12 | do { | 12 | do { |
| 13 | return try await next(request, context) | 13 | return try await next(request, context) |
| 14 | + } catch is CancellationError { | ||
| 15 | + // The client went away (or the server is stopping): nobody reads this answer. | ||
| 16 | + context.logger.info("\(request.method) \(request.uri.path) cancelled") | ||
| 17 | + return Response(status: .init(code: 499, reasonPhrase: "Client Closed Request")) | ||
| 14 | } catch { | 18 | } catch { |
| 15 | if !(error is any HTTPResponseError) { | 19 | if !(error is any HTTPResponseError) { |
| 16 | context.logger.error("\(request.method) \(request.uri.path) failed: \(error)") | 20 | context.logger.error("\(request.method) \(request.uri.path) failed: \(error)") |
modified
Sources/RazorbillServer/RazorbillServer.swift +1 -0 | @@ -39,6 +39,7 @@ public enum RazorbillServer { | ||
| 39 | 39 | } |
| 40 | 40 | addHealthRoute(to: router) |
| 41 | 41 | ModelRoutes(models: models).add(to: router) |
| 42 | + ChatCompletionRoute(models: models).add(to: router) | |
| 42 | 43 | return router |
| 43 | 44 | } |
| 44 | 45 | |
| @@ -39,6 +39,7 @@ public enum RazorbillServer { | |||
| 39 | } | 39 | } |
| 40 | addHealthRoute(to: router) | 40 | addHealthRoute(to: router) |
| 41 | ModelRoutes(models: models).add(to: router) | 41 | ModelRoutes(models: models).add(to: router) |
| 42 | + ChatCompletionRoute(models: models).add(to: router) | ||
| 42 | return router | 43 | return router |
| 43 | } | 44 | } |
| 44 | 45 | ||
added
Tests/RazorbillCoreTests/StopSequenceFilterTests.swift +54 -0 | new file mode 100644 | ||
| @@ -0,0 +1,54 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Testing | |
| 3 | + | |
| 4 | +@testable import RazorbillCore | |
| 5 | + | |
| 6 | +@Suite struct StopSequenceFilterTests { | |
| 7 | + func run(_ stops: [String], _ pieces: [String]) -> (shown: [String], stopped: Bool) { | |
| 8 | + var filter = StopSequenceFilter(stops) | |
| 9 | + var shown = pieces.map { filter.feed($0) } | |
| 10 | + shown.append(filter.finish()) | |
| 11 | + return (shown, filter.isStopped) | |
| 12 | + } | |
| 13 | + | |
| 14 | + @Test func withoutStopsEverythingPasses() { | |
| 15 | + #expect(run([], ["a", "b"]).shown == ["a", "b", ""]) | |
| 16 | + #expect(run([""], ["a"]).shown == ["a", ""]) | |
| 17 | + } | |
| 18 | + | |
| 19 | + @Test func holdsBackAPossibleStartThenCuts() { | |
| 20 | + let result = run(["END"], ["Hello E", "N", "D more", "ignored"]) | |
| 21 | + #expect(result.shown == ["Hello ", "", "", "", ""]) | |
| 22 | + #expect(result.stopped) | |
| 23 | + } | |
| 24 | + | |
| 25 | + @Test func releasesWhatTurnsOutNotToBeAStop() { | |
| 26 | + // "ELSE" ends with "E", which could start "END": it waits for the next piece. | |
| 27 | + let result = run(["END"], ["Hello E", "LSE", " EN"]) | |
| 28 | + #expect(result.shown == ["Hello ", "ELS", "E ", "EN"]) | |
| 29 | + #expect(!result.stopped) | |
| 30 | + } | |
| 31 | + | |
| 32 | + @Test func earliestOfSeveralStopsWins() { | |
| 33 | + #expect(run(["b", "zzz"], ["a zzz b"]).shown == ["a ", ""]) | |
| 34 | + #expect(run(["\n\n", "User:"], ["one\n", "\nUser: two"]).shown == ["one", "", ""]) | |
| 35 | + } | |
| 36 | + | |
| 37 | + @Test func stopInsideOnePiece() { | |
| 38 | + #expect(run(["<|end|>"], ["done<|end|>junk"]).shown == ["done", ""]) | |
| 39 | + } | |
| 40 | +} | |
| 41 | + | |
| 42 | +@Suite struct ConfigValueJSONTests { | |
| 43 | + @Test func roundTrips() throws { | |
| 44 | + let json = #"{"a":[1,2.5,true,null,"x"],"b":{"c":"d"}}"# | |
| 45 | + let value = try JSONDecoder().decode(ConfigValue.self, from: Data(json.utf8)) | |
| 46 | + #expect( | |
| 47 | + value | |
| 48 | + == .map([ | |
| 49 | + "a": .list([.int(1), .double(2.5), .bool(true), .null, .string("x")]), | |
| 50 | + "b": .map(["c": .string("d")]), | |
| 51 | + ])) | |
| 52 | + #expect(value.jsonString == json) | |
| 53 | + } | |
| 54 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,54 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Testing | ||
| 3 | + | ||
| 4 | +@testable import RazorbillCore | ||
| 5 | + | ||
| 6 | +@Suite struct StopSequenceFilterTests { | ||
| 7 | + func run(_ stops: [String], _ pieces: [String]) -> (shown: [String], stopped: Bool) { | ||
| 8 | + var filter = StopSequenceFilter(stops) | ||
| 9 | + var shown = pieces.map { filter.feed($0) } | ||
| 10 | + shown.append(filter.finish()) | ||
| 11 | + return (shown, filter.isStopped) | ||
| 12 | + } | ||
| 13 | + | ||
| 14 | + @Test func withoutStopsEverythingPasses() { | ||
| 15 | + #expect(run([], ["a", "b"]).shown == ["a", "b", ""]) | ||
| 16 | + #expect(run([""], ["a"]).shown == ["a", ""]) | ||
| 17 | + } | ||
| 18 | + | ||
| 19 | + @Test func holdsBackAPossibleStartThenCuts() { | ||
| 20 | + let result = run(["END"], ["Hello E", "N", "D more", "ignored"]) | ||
| 21 | + #expect(result.shown == ["Hello ", "", "", "", ""]) | ||
| 22 | + #expect(result.stopped) | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + @Test func releasesWhatTurnsOutNotToBeAStop() { | ||
| 26 | + // "ELSE" ends with "E", which could start "END": it waits for the next piece. | ||
| 27 | + let result = run(["END"], ["Hello E", "LSE", " EN"]) | ||
| 28 | + #expect(result.shown == ["Hello ", "ELS", "E ", "EN"]) | ||
| 29 | + #expect(!result.stopped) | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + @Test func earliestOfSeveralStopsWins() { | ||
| 33 | + #expect(run(["b", "zzz"], ["a zzz b"]).shown == ["a ", ""]) | ||
| 34 | + #expect(run(["\n\n", "User:"], ["one\n", "\nUser: two"]).shown == ["one", "", ""]) | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + @Test func stopInsideOnePiece() { | ||
| 38 | + #expect(run(["<|end|>"], ["done<|end|>junk"]).shown == ["done", ""]) | ||
| 39 | + } | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +@Suite struct ConfigValueJSONTests { | ||
| 43 | + @Test func roundTrips() throws { | ||
| 44 | + let json = #"{"a":[1,2.5,true,null,"x"],"b":{"c":"d"}}"# | ||
| 45 | + let value = try JSONDecoder().decode(ConfigValue.self, from: Data(json.utf8)) | ||
| 46 | + #expect( | ||
| 47 | + value | ||
| 48 | + == .map([ | ||
| 49 | + "a": .list([.int(1), .double(2.5), .bool(true), .null, .string("x")]), | ||
| 50 | + "b": .map(["c": .string("d")]), | ||
| 51 | + ])) | ||
| 52 | + #expect(value.jsonString == json) | ||
| 53 | + } | ||
| 54 | +} | ||
added
Tests/RazorbillMLXTests/ChatSmokeTests.swift +59 -0 | new file mode 100644 | ||
| @@ -0,0 +1,59 @@ | ||
| 1 | +#if canImport(MLXLLM) | |
| 2 | +import Foundation | |
| 3 | +import RazorbillCore | |
| 4 | +import Testing | |
| 5 | + | |
| 6 | +@testable import RazorbillMLX | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +/// The small model the smoke tests use, when it is already in the Hugging Face cache. | |
| 10 | +let smokeModel = "mlx-community/Qwen3-0.6B-4bit" | |
| 11 | +let smokeModelIsCached = ModelStore().isAvailableLocally( | |
| 12 | + .huggingFace(id: smokeModel, revision: "main")) | |
| 13 | + | |
| 14 | +/// End to end on the Mac with a real model: model manager → MLX engine → chat completion. | |
| 15 | +/// Runs only when the model is already in the Hugging Face cache (no download in tests). | |
| 16 | +@Suite(.serialized, .enabled(if: smokeModelIsCached)) | |
| 17 | +struct ChatSmokeTests { | |
| 18 | + | |
| 19 | + func route() -> ChatCompletionRoute { | |
| 20 | + let catalog = ModelCatalog(config: ServerConfig(), store: ModelStore()) | |
| 21 | + let models = ModelManager(catalog: catalog, limits: ServerLimits()) { MLXEngine() } | |
| 22 | + return ChatCompletionRoute(models: models) | |
| 23 | + } | |
| 24 | + | |
| 25 | + func plan(_ prompt: String, maxTokens: Int = 64, stops: [String] = []) -> ChatPlan { | |
| 26 | + ChatPlan( | |
| 27 | + model: smokeModel, | |
| 28 | + messages: [ | |
| 29 | + ChatMessage(role: .system, content: "Answer in one short sentence."), | |
| 30 | + .user(prompt), | |
| 31 | + ], | |
| 32 | + client: GenerationOverrides(temperature: 0, maxTokens: maxTokens), stops: stops, | |
| 33 | + stream: false) | |
| 34 | + } | |
| 35 | + | |
| 36 | + @Test func answersWithRealUsage() async throws { | |
| 37 | + let response = try await route().complete(plan("What is the capital of France?")) | |
| 38 | + let answer = try #require(response.choices.first) | |
| 39 | + #expect(answer.message.content?.contains("Paris") == true) | |
| 40 | + #expect(answer.message.content?.contains("<think>") == false) | |
| 41 | + #expect(answer.finishReason == .stop) | |
| 42 | + #expect(response.usage.promptTokens > 10 && response.usage.completionTokens > 0) | |
| 43 | + } | |
| 44 | + | |
| 45 | + @Test func tokenLimitGivesLength() async throws { | |
| 46 | + let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8)) | |
| 47 | + #expect(response.choices.first?.finishReason == .length) | |
| 48 | + #expect(response.usage.completionTokens == 8) | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Test func stopSequenceCutsTheAnswer() async throws { | |
| 52 | + let response = try await route().complete( | |
| 53 | + plan("List the numbers from 1 to 10, separated by commas.", stops: ["5"])) | |
| 54 | + let content = try #require(response.choices.first?.message.content) | |
| 55 | + #expect(!content.contains("5") && !content.contains("6")) | |
| 56 | + #expect(content.contains("4")) | |
| 57 | + } | |
| 58 | +} | |
| 59 | +#endif | |
| new file mode 100644 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | +#if canImport(MLXLLM) | ||
| 2 | +import Foundation | ||
| 3 | +import RazorbillCore | ||
| 4 | +import Testing | ||
| 5 | + | ||
| 6 | +@testable import RazorbillMLX | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +/// The small model the smoke tests use, when it is already in the Hugging Face cache. | ||
| 10 | +let smokeModel = "mlx-community/Qwen3-0.6B-4bit" | ||
| 11 | +let smokeModelIsCached = ModelStore().isAvailableLocally( | ||
| 12 | + .huggingFace(id: smokeModel, revision: "main")) | ||
| 13 | + | ||
| 14 | +/// End to end on the Mac with a real model: model manager → MLX engine → chat completion. | ||
| 15 | +/// Runs only when the model is already in the Hugging Face cache (no download in tests). | ||
| 16 | +@Suite(.serialized, .enabled(if: smokeModelIsCached)) | ||
| 17 | +struct ChatSmokeTests { | ||
| 18 | + | ||
| 19 | + func route() -> ChatCompletionRoute { | ||
| 20 | + let catalog = ModelCatalog(config: ServerConfig(), store: ModelStore()) | ||
| 21 | + let models = ModelManager(catalog: catalog, limits: ServerLimits()) { MLXEngine() } | ||
| 22 | + return ChatCompletionRoute(models: models) | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + func plan(_ prompt: String, maxTokens: Int = 64, stops: [String] = []) -> ChatPlan { | ||
| 26 | + ChatPlan( | ||
| 27 | + model: smokeModel, | ||
| 28 | + messages: [ | ||
| 29 | + ChatMessage(role: .system, content: "Answer in one short sentence."), | ||
| 30 | + .user(prompt), | ||
| 31 | + ], | ||
| 32 | + client: GenerationOverrides(temperature: 0, maxTokens: maxTokens), stops: stops, | ||
| 33 | + stream: false) | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + @Test func answersWithRealUsage() async throws { | ||
| 37 | + let response = try await route().complete(plan("What is the capital of France?")) | ||
| 38 | + let answer = try #require(response.choices.first) | ||
| 39 | + #expect(answer.message.content?.contains("Paris") == true) | ||
| 40 | + #expect(answer.message.content?.contains("<think>") == false) | ||
| 41 | + #expect(answer.finishReason == .stop) | ||
| 42 | + #expect(response.usage.promptTokens > 10 && response.usage.completionTokens > 0) | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + @Test func tokenLimitGivesLength() async throws { | ||
| 46 | + let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8)) | ||
| 47 | + #expect(response.choices.first?.finishReason == .length) | ||
| 48 | + #expect(response.usage.completionTokens == 8) | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + @Test func stopSequenceCutsTheAnswer() async throws { | ||
| 52 | + let response = try await route().complete( | ||
| 53 | + plan("List the numbers from 1 to 10, separated by commas.", stops: ["5"])) | ||
| 54 | + let content = try #require(response.choices.first?.message.content) | ||
| 55 | + #expect(!content.contains("5") && !content.contains("6")) | ||
| 56 | + #expect(content.contains("4")) | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | +#endif | ||
added
Tests/RazorbillServerTests/ChatCompletionTests.swift +303 -0 | new file mode 100644 | ||
| @@ -0,0 +1,303 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import HummingbirdTesting | |
| 4 | +import RazorbillCore | |
| 5 | +import Testing | |
| 6 | + | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +#if canImport(Glibc) | |
| 10 | +import Glibc | |
| 11 | +#else | |
| 12 | +import Darwin | |
| 13 | +#endif | |
| 14 | + | |
| 15 | +/// The message of a `chat.completion` choice, decoded. | |
| 16 | +struct CompletionMessage: Decodable { | |
| 17 | + let role: String | |
| 18 | + let content: String? | |
| 19 | + let toolCalls: [WireToolCall]? | |
| 20 | + | |
| 21 | + enum CodingKeys: String, CodingKey { | |
| 22 | + case role, content | |
| 23 | + case toolCalls = "tool_calls" | |
| 24 | + } | |
| 25 | +} | |
| 26 | + | |
| 27 | +/// A `chat.completion` choice, decoded. | |
| 28 | +struct DecodedChoice: Decodable { | |
| 29 | + let index: Int | |
| 30 | + let message: CompletionMessage | |
| 31 | + let finishReason: String | |
| 32 | + | |
| 33 | + enum CodingKeys: String, CodingKey { | |
| 34 | + case index, message | |
| 35 | + case finishReason = "finish_reason" | |
| 36 | + } | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// The parts of a `chat.completion` the tests look at. | |
| 40 | +struct CompletionBody: Decodable { | |
| 41 | + let id: String | |
| 42 | + let object: String | |
| 43 | + let model: String | |
| 44 | + let choices: [DecodedChoice] | |
| 45 | + let usage: [String: Int] | |
| 46 | + | |
| 47 | + init(_ response: TestResponse) throws { | |
| 48 | + self = try JSONDecoder().decode(CompletionBody.self, from: Data(buffer: response.body)) | |
| 49 | + } | |
| 50 | + | |
| 51 | + var first: DecodedChoice { choices[0] } | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// POSTs `json` to `/v1/chat/completions`. | |
| 55 | +func post(_ client: any TestClientProtocol, _ json: String) async throws -> TestResponse { | |
| 56 | + try await client.execute( | |
| 57 | + uri: "/v1/chat/completions", method: .post, headers: [.contentType: "application/json"], | |
| 58 | + body: ByteBuffer(string: json)) | |
| 59 | +} | |
| 60 | + | |
| 61 | +/// A request with one user message. | |
| 62 | +func simpleRequest(_ model: String = "org/m", content: String = "x", extra: String = "") -> String { | |
| 63 | + #"{"model":"\#(model)","messages":[{"role":"user","content":"\#(content)"}]\#(extra)}"# | |
| 64 | +} | |
| 65 | + | |
| 66 | +@Suite struct ChatCompletionTests { | |
| 67 | + @Test func answersInOpenAIShape() async throws { | |
| 68 | + let engines = TestEngines() | |
| 69 | + try await withLiveServer(engines: engines) { client in | |
| 70 | + let response = try await post(client, simpleRequest(content: "Hi")) | |
| 71 | + #expect(response.status == .ok) | |
| 72 | + #expect(response.headers[.connection] == "close") | |
| 73 | + let body = try CompletionBody(response) | |
| 74 | + #expect(body.id.hasPrefix("chatcmpl-") && body.object == "chat.completion") | |
| 75 | + #expect(body.model == "org/m") | |
| 76 | + #expect(body.choices.count == 1 && body.first.index == 0) | |
| 77 | + #expect(body.first.message.role == "assistant") | |
| 78 | + #expect(body.first.message.content == "echo: Hi") | |
| 79 | + #expect(body.first.finishReason == "stop") | |
| 80 | + #expect(body.usage == ["prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2]) | |
| 81 | + } | |
| 82 | + #expect(engines.loads == 1) | |
| 83 | + } | |
| 84 | + | |
| 85 | + @Test func messagesAreMappedForTheChatTemplate() async throws { | |
| 86 | + let engines = TestEngines() | |
| 87 | + let request = """ | |
| 88 | + {"model": "org/m", "user": "ignored", "messages": [ | |
| 89 | + {"role": "developer", "content": "Be brief."}, | |
| 90 | + {"role": "user", "content": [ | |
| 91 | + {"type": "text", "text": "Weather"}, {"type": "text", "text": "in Lyon?"}]}, | |
| 92 | + {"role": "assistant", "content": null, "tool_calls": [{"id": "c1", "type": "function", | |
| 93 | + "function": {"name": "weather", "arguments": "{\\"city\\":\\"Lyon\\"}"}}]}, | |
| 94 | + {"role": "tool", "tool_call_id": "c1", "content": "12°C"} | |
| 95 | + ]} | |
| 96 | + """ | |
| 97 | + try await withLiveServer(engines: engines) { client in | |
| 98 | + let response = try await post(client, request) | |
| 99 | + #expect(response.status == .ok) | |
| 100 | + } | |
| 101 | + let call = ToolCall(id: "c1", name: "weather", arguments: ["city": .string("Lyon")]) | |
| 102 | + let expected: [ChatMessage] = [ | |
| 103 | + ChatMessage(role: .system, content: "Be brief."), | |
| 104 | + .user("Weather\nin Lyon?"), | |
| 105 | + .assistant("", toolCalls: [call]), | |
| 106 | + ChatMessage(role: .tool, content: "12°C", toolCallID: "c1"), | |
| 107 | + ] | |
| 108 | + #expect(engines.fake.receivedMessages == [expected]) | |
| 109 | + #expect(engines.fake.sessionSetups.first?.system == "") | |
| 110 | + } | |
| 111 | + | |
| 112 | + @Test func clientSettingsMeetConfigurationDefaultsAndLocks() async throws { | |
| 113 | + let engines = TestEngines() | |
| 114 | + var settings = testSettings | |
| 115 | + settings.config = ServerConfig( | |
| 116 | + defaults: GenerationOverrides(temperature: 0.1, topP: 0.5), | |
| 117 | + locked: GenerationOverrides(maxTokens: 300)) | |
| 118 | + let extra = | |
| 119 | + #","temperature":0.9,"max_tokens":50,"max_completion_tokens":900,"seed":42,"# | |
| 120 | + + #""presence_penalty":0.5,"frequency_penalty":-0.5"# | |
| 121 | + try await withLiveServer(settings, engines: engines) { client in | |
| 122 | + let response = try await post(client, simpleRequest(extra: extra)) | |
| 123 | + #expect(response.status == .ok) | |
| 124 | + } | |
| 125 | + let generation = try #require(engines.fake.sessionSetups.first?.generation) | |
| 126 | + #expect(generation.temperature == 0.9 && generation.topP == 0.5) | |
| 127 | + #expect(generation.maxTokens == 300) // max_completion_tokens wins, then the lock caps it | |
| 128 | + #expect(generation.seed == 42) | |
| 129 | + #expect(generation.presencePenalty == 0.5 && generation.frequencyPenalty == -0.5) | |
| 130 | + } | |
| 131 | + | |
| 132 | + @Test func stopSequencesCutTheAnswerWithoutLeaking() async throws { | |
| 133 | + let engines = TestEngines(script: [ | |
| 134 | + [.text("Hello wo"), .text("rld EN"), .text("D and more")] | |
| 135 | + ]) | |
| 136 | + try await withLiveServer(engines: engines) { client in | |
| 137 | + let body = try CompletionBody( | |
| 138 | + try await post(client, simpleRequest(extra: #","stop":"END""#))) | |
| 139 | + #expect(body.first.message.content == "Hello world ") | |
| 140 | + #expect(body.first.finishReason == "stop") | |
| 141 | + // Interrupted before the engine's counts: one token per piece of text. | |
| 142 | + #expect(body.usage["completion_tokens"] == 3) | |
| 143 | + } | |
| 144 | + } | |
| 145 | + | |
| 146 | + @Test func tokenLimitEndsWithLength() async throws { | |
| 147 | + let stats = GenerationStats( | |
| 148 | + promptTokens: 7, generatedTokens: 16, tokensPerSecond: 1, hitTokenLimit: true) | |
| 149 | + let engines = TestEngines(script: [[.thinking("hmm"), .text("partial"), .stats(stats)]]) | |
| 150 | + try await withLiveServer(engines: engines) { client in | |
| 151 | + let body = try CompletionBody(try await post(client, simpleRequest())) | |
| 152 | + #expect(body.first.message.content == "partial") // reasoning is not content | |
| 153 | + #expect(body.first.finishReason == "length") | |
| 154 | + #expect( | |
| 155 | + body.usage == ["prompt_tokens": 7, "completion_tokens": 16, "total_tokens": 23]) | |
| 156 | + } | |
| 157 | + } | |
| 158 | + | |
| 159 | + @Test func toolCallsComeBackWithNullContent() async throws { | |
| 160 | + let call = ToolCall(id: "call_1", name: "weather", arguments: ["city": .string("Lyon")]) | |
| 161 | + let engines = TestEngines(script: [[.toolCall(call)]]) | |
| 162 | + try await withLiveServer(engines: engines) { client in | |
| 163 | + let body = try CompletionBody(try await post(client, simpleRequest())) | |
| 164 | + #expect(body.first.message.content == nil) | |
| 165 | + #expect(body.first.finishReason == "tool_calls") | |
| 166 | + let wire = try #require(body.first.message.toolCalls?.first) | |
| 167 | + #expect(wire.id == "call_1" && wire.type == "function") | |
| 168 | + #expect(wire.function.name == "weather") | |
| 169 | + #expect(wire.function.arguments == #"{"city":"Lyon"}"#) | |
| 170 | + } | |
| 171 | + } | |
| 172 | + | |
| 173 | + static let invalidRequests: [(json: String, param: String)] = [ | |
| 174 | + (#"{"messages":[{"role":"user","content":"x"}]}"#, "model"), | |
| 175 | + (#"{"model":"org/m","messages":[]}"#, "messages"), | |
| 176 | + (simpleRequest(extra: #","temperature":3"#), "temperature"), | |
| 177 | + (simpleRequest(extra: #","top_p":"high""#), "top_p"), | |
| 178 | + (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), | |
| 179 | + (simpleRequest(extra: #","n":2"#), "n"), | |
| 180 | + (simpleRequest(extra: #","stream":true"#), "stream"), | |
| 181 | + (simpleRequest(extra: #","tools":[]"#), "tools"), | |
| 182 | + (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), | |
| 183 | + (simpleRequest(extra: #","response_format":{"type":"json_object"}"#), "response_format"), | |
| 184 | + (#"{"model":"org/m","messages":[{"role":"robot","content":"x"}]}"#, "messages[0].role"), | |
| 185 | + (#"{"model":"org/m","messages":[{"role":"user"}]}"#, "messages[0].content"), | |
| 186 | + ( | |
| 187 | + #"{"model":"org/m","messages":[{"role":"user","content":[{"type":"image_url"}]}]}"#, | |
| 188 | + "messages[0].content" | |
| 189 | + ), | |
| 190 | + ] | |
| 191 | + | |
| 192 | + @Test(arguments: invalidRequests) | |
| 193 | + func invalidRequestsAre400sNamingTheField(json: String, param: String) async throws { | |
| 194 | + let engines = TestEngines() | |
| 195 | + try await withLiveServer(engines: engines) { client in | |
| 196 | + let response = try await post(client, json) | |
| 197 | + #expect(response.status == .badRequest) | |
| 198 | + #expect(response.headers[.connection] == "close") | |
| 199 | + let error = try ErrorBody(response).error | |
| 200 | + #expect(error.param == param) | |
| 201 | + #expect(error.type == "invalid_request_error") | |
| 202 | + } | |
| 203 | + #expect(engines.loads == 0) | |
| 204 | + } | |
| 205 | + | |
| 206 | + @Test func malformedJSONIs400() async throws { | |
| 207 | + try await withLiveServer { client in | |
| 208 | + let response = try await post(client, "{nope") | |
| 209 | + #expect(response.status == .badRequest) | |
| 210 | + let error = try ErrorBody(response).error | |
| 211 | + #expect(error.message == "The body is not valid JSON.") | |
| 212 | + } | |
| 213 | + } | |
| 214 | + | |
| 215 | + @Test func unknownModelIs404() async throws { | |
| 216 | + try await withLiveServer { client in | |
| 217 | + let response = try await post(client, simpleRequest("gpt-4o")) | |
| 218 | + #expect(response.status == .notFound) | |
| 219 | + let error = try ErrorBody(response).error | |
| 220 | + #expect(error.code == "model_not_found") | |
| 221 | + } | |
| 222 | + } | |
| 223 | + | |
| 224 | + @Test func requestLogShowsModelAndTokensButNotTheMessages() async throws { | |
| 225 | + let logs = LogCapture() | |
| 226 | + try await withLiveServer(logs: logs) { client in | |
| 227 | + _ = try await post(client, simpleRequest(content: "secret")) | |
| 228 | + } | |
| 229 | + #expect( | |
| 230 | + logs.messages.contains { | |
| 231 | + $0.contains("POST /v1/chat/completions 200") | |
| 232 | + && $0.hasSuffix("model=org/m tokens=1+1") | |
| 233 | + }) | |
| 234 | + #expect(!logs.messages.contains { $0.contains("secret") }) | |
| 235 | + } | |
| 236 | + | |
| 237 | + @Test func clientDisconnectCancelsTheGeneration() async throws { | |
| 238 | + let engines = TestEngines(hang: true) | |
| 239 | + try await withLiveServer(engines: engines) { client in | |
| 240 | + let port = try #require(client.port) | |
| 241 | + let body = simpleRequest() | |
| 242 | + let socket = try RawConnection(port: port) | |
| 243 | + socket.send( | |
| 244 | + "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n" | |
| 245 | + + "Content-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)" | |
| 246 | + ) | |
| 247 | + try await Task.sleep(for: .milliseconds(200)) // the generation has started | |
| 248 | + socket.close() | |
| 249 | + for _ in 0 ..< 200 where engines.cancelledGenerations == 0 { | |
| 250 | + try await Task.sleep(for: .milliseconds(10)) | |
| 251 | + } | |
| 252 | + } | |
| 253 | + #expect(engines.cancelledGenerations == 1) | |
| 254 | + } | |
| 255 | +} | |
| 256 | + | |
| 257 | +/// A bare TCP connection, to hang up in the middle of a request. | |
| 258 | +struct RawConnection { | |
| 259 | + private(set) var descriptor: Int32 = -1 | |
| 260 | + | |
| 261 | + /// Connects to `localhost:port` (IPv4 or IPv6, whichever the test server listens on). | |
| 262 | + init(port: Int) throws { | |
| 263 | + var hints = addrinfo() | |
| 264 | + hints.ai_family = AF_UNSPEC | |
| 265 | + #if canImport(Glibc) | |
| 266 | + hints.ai_socktype = Int32(SOCK_STREAM.rawValue) | |
| 267 | + #else | |
| 268 | + hints.ai_socktype = SOCK_STREAM | |
| 269 | + #endif | |
| 270 | + var list: UnsafeMutablePointer<addrinfo>? | |
| 271 | + guard getaddrinfo("localhost", String(port), &hints, &list) == 0 else { | |
| 272 | + throw POSIXError(.EADDRNOTAVAIL) | |
| 273 | + } | |
| 274 | + defer { freeaddrinfo(list) } | |
| 275 | + var entry = list | |
| 276 | + while let info = entry?.pointee { | |
| 277 | + let candidate = socket(info.ai_family, info.ai_socktype, info.ai_protocol) | |
| 278 | + if candidate >= 0, connect(candidate, info.ai_addr, info.ai_addrlen) == 0 { | |
| 279 | + descriptor = candidate | |
| 280 | + return | |
| 281 | + } | |
| 282 | + if candidate >= 0 { Self.close(candidate) } | |
| 283 | + entry = info.ai_next | |
| 284 | + } | |
| 285 | + throw POSIXError(.ECONNREFUSED) | |
| 286 | + } | |
| 287 | + | |
| 288 | + func send(_ text: String) { | |
| 289 | + _ = text.utf8CString.withUnsafeBufferPointer { buffer in | |
| 290 | + write(descriptor, buffer.baseAddress, buffer.count - 1) | |
| 291 | + } | |
| 292 | + } | |
| 293 | + | |
| 294 | + func close() { Self.close(descriptor) } | |
| 295 | + | |
| 296 | + static func close(_ descriptor: Int32) { | |
| 297 | + #if canImport(Glibc) | |
| 298 | + _ = Glibc.close(descriptor) | |
| 299 | + #else | |
| 300 | + _ = Darwin.close(descriptor) | |
| 301 | + #endif | |
| 302 | + } | |
| 303 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,303 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import HummingbirdTesting | ||
| 4 | +import RazorbillCore | ||
| 5 | +import Testing | ||
| 6 | + | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +#if canImport(Glibc) | ||
| 10 | +import Glibc | ||
| 11 | +#else | ||
| 12 | +import Darwin | ||
| 13 | +#endif | ||
| 14 | + | ||
| 15 | +/// The message of a `chat.completion` choice, decoded. | ||
| 16 | +struct CompletionMessage: Decodable { | ||
| 17 | + let role: String | ||
| 18 | + let content: String? | ||
| 19 | + let toolCalls: [WireToolCall]? | ||
| 20 | + | ||
| 21 | + enum CodingKeys: String, CodingKey { | ||
| 22 | + case role, content | ||
| 23 | + case toolCalls = "tool_calls" | ||
| 24 | + } | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// A `chat.completion` choice, decoded. | ||
| 28 | +struct DecodedChoice: Decodable { | ||
| 29 | + let index: Int | ||
| 30 | + let message: CompletionMessage | ||
| 31 | + let finishReason: String | ||
| 32 | + | ||
| 33 | + enum CodingKeys: String, CodingKey { | ||
| 34 | + case index, message | ||
| 35 | + case finishReason = "finish_reason" | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// The parts of a `chat.completion` the tests look at. | ||
| 40 | +struct CompletionBody: Decodable { | ||
| 41 | + let id: String | ||
| 42 | + let object: String | ||
| 43 | + let model: String | ||
| 44 | + let choices: [DecodedChoice] | ||
| 45 | + let usage: [String: Int] | ||
| 46 | + | ||
| 47 | + init(_ response: TestResponse) throws { | ||
| 48 | + self = try JSONDecoder().decode(CompletionBody.self, from: Data(buffer: response.body)) | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + var first: DecodedChoice { choices[0] } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// POSTs `json` to `/v1/chat/completions`. | ||
| 55 | +func post(_ client: any TestClientProtocol, _ json: String) async throws -> TestResponse { | ||
| 56 | + try await client.execute( | ||
| 57 | + uri: "/v1/chat/completions", method: .post, headers: [.contentType: "application/json"], | ||
| 58 | + body: ByteBuffer(string: json)) | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// A request with one user message. | ||
| 62 | +func simpleRequest(_ model: String = "org/m", content: String = "x", extra: String = "") -> String { | ||
| 63 | + #"{"model":"\#(model)","messages":[{"role":"user","content":"\#(content)"}]\#(extra)}"# | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +@Suite struct ChatCompletionTests { | ||
| 67 | + @Test func answersInOpenAIShape() async throws { | ||
| 68 | + let engines = TestEngines() | ||
| 69 | + try await withLiveServer(engines: engines) { client in | ||
| 70 | + let response = try await post(client, simpleRequest(content: "Hi")) | ||
| 71 | + #expect(response.status == .ok) | ||
| 72 | + #expect(response.headers[.connection] == "close") | ||
| 73 | + let body = try CompletionBody(response) | ||
| 74 | + #expect(body.id.hasPrefix("chatcmpl-") && body.object == "chat.completion") | ||
| 75 | + #expect(body.model == "org/m") | ||
| 76 | + #expect(body.choices.count == 1 && body.first.index == 0) | ||
| 77 | + #expect(body.first.message.role == "assistant") | ||
| 78 | + #expect(body.first.message.content == "echo: Hi") | ||
| 79 | + #expect(body.first.finishReason == "stop") | ||
| 80 | + #expect(body.usage == ["prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2]) | ||
| 81 | + } | ||
| 82 | + #expect(engines.loads == 1) | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + @Test func messagesAreMappedForTheChatTemplate() async throws { | ||
| 86 | + let engines = TestEngines() | ||
| 87 | + let request = """ | ||
| 88 | + {"model": "org/m", "user": "ignored", "messages": [ | ||
| 89 | + {"role": "developer", "content": "Be brief."}, | ||
| 90 | + {"role": "user", "content": [ | ||
| 91 | + {"type": "text", "text": "Weather"}, {"type": "text", "text": "in Lyon?"}]}, | ||
| 92 | + {"role": "assistant", "content": null, "tool_calls": [{"id": "c1", "type": "function", | ||
| 93 | + "function": {"name": "weather", "arguments": "{\\"city\\":\\"Lyon\\"}"}}]}, | ||
| 94 | + {"role": "tool", "tool_call_id": "c1", "content": "12°C"} | ||
| 95 | + ]} | ||
| 96 | + """ | ||
| 97 | + try await withLiveServer(engines: engines) { client in | ||
| 98 | + let response = try await post(client, request) | ||
| 99 | + #expect(response.status == .ok) | ||
| 100 | + } | ||
| 101 | + let call = ToolCall(id: "c1", name: "weather", arguments: ["city": .string("Lyon")]) | ||
| 102 | + let expected: [ChatMessage] = [ | ||
| 103 | + ChatMessage(role: .system, content: "Be brief."), | ||
| 104 | + .user("Weather\nin Lyon?"), | ||
| 105 | + .assistant("", toolCalls: [call]), | ||
| 106 | + ChatMessage(role: .tool, content: "12°C", toolCallID: "c1"), | ||
| 107 | + ] | ||
| 108 | + #expect(engines.fake.receivedMessages == [expected]) | ||
| 109 | + #expect(engines.fake.sessionSetups.first?.system == "") | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + @Test func clientSettingsMeetConfigurationDefaultsAndLocks() async throws { | ||
| 113 | + let engines = TestEngines() | ||
| 114 | + var settings = testSettings | ||
| 115 | + settings.config = ServerConfig( | ||
| 116 | + defaults: GenerationOverrides(temperature: 0.1, topP: 0.5), | ||
| 117 | + locked: GenerationOverrides(maxTokens: 300)) | ||
| 118 | + let extra = | ||
| 119 | + #","temperature":0.9,"max_tokens":50,"max_completion_tokens":900,"seed":42,"# | ||
| 120 | + + #""presence_penalty":0.5,"frequency_penalty":-0.5"# | ||
| 121 | + try await withLiveServer(settings, engines: engines) { client in | ||
| 122 | + let response = try await post(client, simpleRequest(extra: extra)) | ||
| 123 | + #expect(response.status == .ok) | ||
| 124 | + } | ||
| 125 | + let generation = try #require(engines.fake.sessionSetups.first?.generation) | ||
| 126 | + #expect(generation.temperature == 0.9 && generation.topP == 0.5) | ||
| 127 | + #expect(generation.maxTokens == 300) // max_completion_tokens wins, then the lock caps it | ||
| 128 | + #expect(generation.seed == 42) | ||
| 129 | + #expect(generation.presencePenalty == 0.5 && generation.frequencyPenalty == -0.5) | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + @Test func stopSequencesCutTheAnswerWithoutLeaking() async throws { | ||
| 133 | + let engines = TestEngines(script: [ | ||
| 134 | + [.text("Hello wo"), .text("rld EN"), .text("D and more")] | ||
| 135 | + ]) | ||
| 136 | + try await withLiveServer(engines: engines) { client in | ||
| 137 | + let body = try CompletionBody( | ||
| 138 | + try await post(client, simpleRequest(extra: #","stop":"END""#))) | ||
| 139 | + #expect(body.first.message.content == "Hello world ") | ||
| 140 | + #expect(body.first.finishReason == "stop") | ||
| 141 | + // Interrupted before the engine's counts: one token per piece of text. | ||
| 142 | + #expect(body.usage["completion_tokens"] == 3) | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + @Test func tokenLimitEndsWithLength() async throws { | ||
| 147 | + let stats = GenerationStats( | ||
| 148 | + promptTokens: 7, generatedTokens: 16, tokensPerSecond: 1, hitTokenLimit: true) | ||
| 149 | + let engines = TestEngines(script: [[.thinking("hmm"), .text("partial"), .stats(stats)]]) | ||
| 150 | + try await withLiveServer(engines: engines) { client in | ||
| 151 | + let body = try CompletionBody(try await post(client, simpleRequest())) | ||
| 152 | + #expect(body.first.message.content == "partial") // reasoning is not content | ||
| 153 | + #expect(body.first.finishReason == "length") | ||
| 154 | + #expect( | ||
| 155 | + body.usage == ["prompt_tokens": 7, "completion_tokens": 16, "total_tokens": 23]) | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + @Test func toolCallsComeBackWithNullContent() async throws { | ||
| 160 | + let call = ToolCall(id: "call_1", name: "weather", arguments: ["city": .string("Lyon")]) | ||
| 161 | + let engines = TestEngines(script: [[.toolCall(call)]]) | ||
| 162 | + try await withLiveServer(engines: engines) { client in | ||
| 163 | + let body = try CompletionBody(try await post(client, simpleRequest())) | ||
| 164 | + #expect(body.first.message.content == nil) | ||
| 165 | + #expect(body.first.finishReason == "tool_calls") | ||
| 166 | + let wire = try #require(body.first.message.toolCalls?.first) | ||
| 167 | + #expect(wire.id == "call_1" && wire.type == "function") | ||
| 168 | + #expect(wire.function.name == "weather") | ||
| 169 | + #expect(wire.function.arguments == #"{"city":"Lyon"}"#) | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + static let invalidRequests: [(json: String, param: String)] = [ | ||
| 174 | + (#"{"messages":[{"role":"user","content":"x"}]}"#, "model"), | ||
| 175 | + (#"{"model":"org/m","messages":[]}"#, "messages"), | ||
| 176 | + (simpleRequest(extra: #","temperature":3"#), "temperature"), | ||
| 177 | + (simpleRequest(extra: #","top_p":"high""#), "top_p"), | ||
| 178 | + (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), | ||
| 179 | + (simpleRequest(extra: #","n":2"#), "n"), | ||
| 180 | + (simpleRequest(extra: #","stream":true"#), "stream"), | ||
| 181 | + (simpleRequest(extra: #","tools":[]"#), "tools"), | ||
| 182 | + (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), | ||
| 183 | + (simpleRequest(extra: #","response_format":{"type":"json_object"}"#), "response_format"), | ||
| 184 | + (#"{"model":"org/m","messages":[{"role":"robot","content":"x"}]}"#, "messages[0].role"), | ||
| 185 | + (#"{"model":"org/m","messages":[{"role":"user"}]}"#, "messages[0].content"), | ||
| 186 | + ( | ||
| 187 | + #"{"model":"org/m","messages":[{"role":"user","content":[{"type":"image_url"}]}]}"#, | ||
| 188 | + "messages[0].content" | ||
| 189 | + ), | ||
| 190 | + ] | ||
| 191 | + | ||
| 192 | + @Test(arguments: invalidRequests) | ||
| 193 | + func invalidRequestsAre400sNamingTheField(json: String, param: String) async throws { | ||
| 194 | + let engines = TestEngines() | ||
| 195 | + try await withLiveServer(engines: engines) { client in | ||
| 196 | + let response = try await post(client, json) | ||
| 197 | + #expect(response.status == .badRequest) | ||
| 198 | + #expect(response.headers[.connection] == "close") | ||
| 199 | + let error = try ErrorBody(response).error | ||
| 200 | + #expect(error.param == param) | ||
| 201 | + #expect(error.type == "invalid_request_error") | ||
| 202 | + } | ||
| 203 | + #expect(engines.loads == 0) | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + @Test func malformedJSONIs400() async throws { | ||
| 207 | + try await withLiveServer { client in | ||
| 208 | + let response = try await post(client, "{nope") | ||
| 209 | + #expect(response.status == .badRequest) | ||
| 210 | + let error = try ErrorBody(response).error | ||
| 211 | + #expect(error.message == "The body is not valid JSON.") | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + @Test func unknownModelIs404() async throws { | ||
| 216 | + try await withLiveServer { client in | ||
| 217 | + let response = try await post(client, simpleRequest("gpt-4o")) | ||
| 218 | + #expect(response.status == .notFound) | ||
| 219 | + let error = try ErrorBody(response).error | ||
| 220 | + #expect(error.code == "model_not_found") | ||
| 221 | + } | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + @Test func requestLogShowsModelAndTokensButNotTheMessages() async throws { | ||
| 225 | + let logs = LogCapture() | ||
| 226 | + try await withLiveServer(logs: logs) { client in | ||
| 227 | + _ = try await post(client, simpleRequest(content: "secret")) | ||
| 228 | + } | ||
| 229 | + #expect( | ||
| 230 | + logs.messages.contains { | ||
| 231 | + $0.contains("POST /v1/chat/completions 200") | ||
| 232 | + && $0.hasSuffix("model=org/m tokens=1+1") | ||
| 233 | + }) | ||
| 234 | + #expect(!logs.messages.contains { $0.contains("secret") }) | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + @Test func clientDisconnectCancelsTheGeneration() async throws { | ||
| 238 | + let engines = TestEngines(hang: true) | ||
| 239 | + try await withLiveServer(engines: engines) { client in | ||
| 240 | + let port = try #require(client.port) | ||
| 241 | + let body = simpleRequest() | ||
| 242 | + let socket = try RawConnection(port: port) | ||
| 243 | + socket.send( | ||
| 244 | + "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n" | ||
| 245 | + + "Content-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)" | ||
| 246 | + ) | ||
| 247 | + try await Task.sleep(for: .milliseconds(200)) // the generation has started | ||
| 248 | + socket.close() | ||
| 249 | + for _ in 0 ..< 200 where engines.cancelledGenerations == 0 { | ||
| 250 | + try await Task.sleep(for: .milliseconds(10)) | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + #expect(engines.cancelledGenerations == 1) | ||
| 254 | + } | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// A bare TCP connection, to hang up in the middle of a request. | ||
| 258 | +struct RawConnection { | ||
| 259 | + private(set) var descriptor: Int32 = -1 | ||
| 260 | + | ||
| 261 | + /// Connects to `localhost:port` (IPv4 or IPv6, whichever the test server listens on). | ||
| 262 | + init(port: Int) throws { | ||
| 263 | + var hints = addrinfo() | ||
| 264 | + hints.ai_family = AF_UNSPEC | ||
| 265 | + #if canImport(Glibc) | ||
| 266 | + hints.ai_socktype = Int32(SOCK_STREAM.rawValue) | ||
| 267 | + #else | ||
| 268 | + hints.ai_socktype = SOCK_STREAM | ||
| 269 | + #endif | ||
| 270 | + var list: UnsafeMutablePointer<addrinfo>? | ||
| 271 | + guard getaddrinfo("localhost", String(port), &hints, &list) == 0 else { | ||
| 272 | + throw POSIXError(.EADDRNOTAVAIL) | ||
| 273 | + } | ||
| 274 | + defer { freeaddrinfo(list) } | ||
| 275 | + var entry = list | ||
| 276 | + while let info = entry?.pointee { | ||
| 277 | + let candidate = socket(info.ai_family, info.ai_socktype, info.ai_protocol) | ||
| 278 | + if candidate >= 0, connect(candidate, info.ai_addr, info.ai_addrlen) == 0 { | ||
| 279 | + descriptor = candidate | ||
| 280 | + return | ||
| 281 | + } | ||
| 282 | + if candidate >= 0 { Self.close(candidate) } | ||
| 283 | + entry = info.ai_next | ||
| 284 | + } | ||
| 285 | + throw POSIXError(.ECONNREFUSED) | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + func send(_ text: String) { | ||
| 289 | + _ = text.utf8CString.withUnsafeBufferPointer { buffer in | ||
| 290 | + write(descriptor, buffer.baseAddress, buffer.count - 1) | ||
| 291 | + } | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + func close() { Self.close(descriptor) } | ||
| 295 | + | ||
| 296 | + static func close(_ descriptor: Int32) { | ||
| 297 | + #if canImport(Glibc) | ||
| 298 | + _ = Glibc.close(descriptor) | ||
| 299 | + #else | ||
| 300 | + _ = Darwin.close(descriptor) | ||
| 301 | + #endif | ||
| 302 | + } | ||
| 303 | +} | ||
modified
Tests/RazorbillServerTests/ModelManagerTests.swift +28 -2 | @@ -4,11 +4,24 @@ import Testing | ||
| 4 | 4 | |
| 5 | 5 | @testable import RazorbillServer |
| 6 | 6 | |
| 7 | -/// Engines that record what they load and unload, and can be told to fail. | |
| 7 | +/// Engines that record what they load and unload, and can be told to fail. Sessions play | |
| 8 | +/// `script` through a shared ``FakeEngine`` (inspect it with `fake`), or never end with `hang`. | |
| 8 | 9 | final class TestEngines: @unchecked Sendable { |
| 9 | 10 | private let lock = NSLock() |
| 10 | 11 | private var storedEvents: [String] = [] |
| 11 | 12 | private var failures: [String: any Error] = [:] |
| 13 | + let fake: FakeEngine | |
| 14 | + /// Sessions stream nothing and never finish; `cancelledGenerations` counts the cancelled ones. | |
| 15 | + let hang: Bool | |
| 16 | + private var cancelled = 0 | |
| 17 | + | |
| 18 | + init(script: [[EngineEvent]] = [], hang: Bool = false) { | |
| 19 | + fake = FakeEngine(script: script) | |
| 20 | + self.hang = hang | |
| 21 | + } | |
| 22 | + | |
| 23 | + var cancelledGenerations: Int { lock.withLock { cancelled } } | |
| 24 | + func recordCancellation() { lock.withLock { cancelled += 1 } } | |
| 12 | 25 | |
| 13 | 26 | /// `load <model>` / `unload <model>`, in order. |
| 14 | 27 | var events: [String] { lock.withLock { storedEvents } } |
| @@ -48,7 +61,7 @@ final class TestEngines: @unchecked Sendable { | ||
| 48 | 61 | ) async throws {} |
| 49 | 62 | |
| 50 | 63 | func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 51 | - try await FakeEngine().makeSession(setup) | |
| 64 | + owner.hang ? HangingSession(owner: owner) : try await owner.fake.makeSession(setup) | |
| 52 | 65 | } |
| 53 | 66 | |
| 54 | 67 | func unload() async { |
| @@ -57,6 +70,19 @@ final class TestEngines: @unchecked Sendable { | ||
| 57 | 70 | } |
| 58 | 71 | } |
| 59 | 72 | |
| 73 | +/// A generation that never ends until it is cancelled. | |
| 74 | +struct HangingSession: EngineSession { | |
| 75 | + let owner: TestEngines | |
| 76 | + | |
| 77 | + func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | |
| 78 | + AsyncThrowingStream { continuation in | |
| 79 | + continuation.onTermination = { reason in | |
| 80 | + if case .cancelled = reason { owner.recordCancellation() } | |
| 81 | + } | |
| 82 | + } | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 60 | 86 | struct LoadBroke: Error, CustomStringConvertible { |
| 61 | 87 | var description: String { "disk on fire" } |
| 62 | 88 | } |
| @@ -4,11 +4,24 @@ import Testing | |||
| 4 | 4 | ||
| 5 | @testable import RazorbillServer | 5 | @testable import RazorbillServer |
| 6 | 6 | ||
| 7 | -/// Engines that record what they load and unload, and can be told to fail. | 7 | +/// Engines that record what they load and unload, and can be told to fail. Sessions play |
| 8 | +/// `script` through a shared ``FakeEngine`` (inspect it with `fake`), or never end with `hang`. | ||
| 8 | final class TestEngines: @unchecked Sendable { | 9 | final class TestEngines: @unchecked Sendable { |
| 9 | private let lock = NSLock() | 10 | private let lock = NSLock() |
| 10 | private var storedEvents: [String] = [] | 11 | private var storedEvents: [String] = [] |
| 11 | private var failures: [String: any Error] = [:] | 12 | private var failures: [String: any Error] = [:] |
| 13 | + let fake: FakeEngine | ||
| 14 | + /// Sessions stream nothing and never finish; `cancelledGenerations` counts the cancelled ones. | ||
| 15 | + let hang: Bool | ||
| 16 | + private var cancelled = 0 | ||
| 17 | + | ||
| 18 | + init(script: [[EngineEvent]] = [], hang: Bool = false) { | ||
| 19 | + fake = FakeEngine(script: script) | ||
| 20 | + self.hang = hang | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + var cancelledGenerations: Int { lock.withLock { cancelled } } | ||
| 24 | + func recordCancellation() { lock.withLock { cancelled += 1 } } | ||
| 12 | 25 | ||
| 13 | /// `load <model>` / `unload <model>`, in order. | 26 | /// `load <model>` / `unload <model>`, in order. |
| 14 | var events: [String] { lock.withLock { storedEvents } } | 27 | var events: [String] { lock.withLock { storedEvents } } |
| @@ -48,7 +61,7 @@ final class TestEngines: @unchecked Sendable { | |||
| 48 | ) async throws {} | 61 | ) async throws {} |
| 49 | 62 | ||
| 50 | func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 63 | func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 51 | - try await FakeEngine().makeSession(setup) | 64 | + owner.hang ? HangingSession(owner: owner) : try await owner.fake.makeSession(setup) |
| 52 | } | 65 | } |
| 53 | 66 | ||
| 54 | func unload() async { | 67 | func unload() async { |
| @@ -57,6 +70,19 @@ final class TestEngines: @unchecked Sendable { | |||
| 57 | } | 70 | } |
| 58 | } | 71 | } |
| 59 | 72 | ||
| 73 | +/// A generation that never ends until it is cancelled. | ||
| 74 | +struct HangingSession: EngineSession { | ||
| 75 | + let owner: TestEngines | ||
| 76 | + | ||
| 77 | + func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 78 | + AsyncThrowingStream { continuation in | ||
| 79 | + continuation.onTermination = { reason in | ||
| 80 | + if case .cancelled = reason { owner.recordCancellation() } | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 60 | struct LoadBroke: Error, CustomStringConvertible { | 86 | struct LoadBroke: Error, CustomStringConvertible { |
| 61 | var description: String { "disk on fire" } | 87 | var description: String { "disk on fire" } |
| 62 | } | 88 | } |
modified
Tests/RazorbillServerTests/ServerTests.swift +2 -1 | @@ -31,9 +31,10 @@ func withLiveServer( | ||
| 31 | 31 | _ settings: ServerSettings = testSettings, |
| 32 | 32 | router: Router<ServerContext>? = nil, |
| 33 | 33 | logs: LogCapture = LogCapture(), |
| 34 | + engines: TestEngines = TestEngines(), | |
| 34 | 35 | _ test: @Sendable (any TestClientProtocol) async throws -> Void |
| 35 | 36 | ) async throws { |
| 36 | - let models = testModels(settings) | |
| 37 | + let models = testModels(settings, engines: engines) | |
| 37 | 38 | let router = router ?? RazorbillServer.makeRouter(settings, models: models) |
| 38 | 39 | let app = RazorbillServer.makeApplication( |
| 39 | 40 | router: router, settings: settings, models: models, logger: logs.logger) |
| @@ -31,9 +31,10 @@ func withLiveServer( | |||
| 31 | _ settings: ServerSettings = testSettings, | 31 | _ settings: ServerSettings = testSettings, |
| 32 | router: Router<ServerContext>? = nil, | 32 | router: Router<ServerContext>? = nil, |
| 33 | logs: LogCapture = LogCapture(), | 33 | logs: LogCapture = LogCapture(), |
| 34 | + engines: TestEngines = TestEngines(), | ||
| 34 | _ test: @Sendable (any TestClientProtocol) async throws -> Void | 35 | _ test: @Sendable (any TestClientProtocol) async throws -> Void |
| 35 | ) async throws { | 36 | ) async throws { |
| 36 | - let models = testModels(settings) | 37 | + let models = testModels(settings, engines: engines) |
| 37 | let router = router ?? RazorbillServer.makeRouter(settings, models: models) | 38 | let router = router ?? RazorbillServer.makeRouter(settings, models: models) |
| 38 | let app = RazorbillServer.makeApplication( | 39 | let app = RazorbillServer.makeApplication( |
| 39 | router: router, settings: settings, models: models, logger: logs.logger) | 40 | router: router, settings: settings, models: models, logger: logs.logger) |