v0.2 step 11 — legacy text completions (#44)
POST /v1/completions: the prompt is continued as raw text through the new InferenceEngine.complete (no chat template, thinking or tool parsing), with streaming, echo, stop sequences and usage. suffix, logprobs, n/best_of and several prompts are refused with a 400. Chunks and text completions share CompletionEnvelope; field checks shared by both request types (FieldChecking). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
c1a7231 parent: 9be357d modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +5 -0 | @@ -87,3 +87,8 @@ the end of the file) before starting #43; fix the ❌ first. Delete the file onc | ||
| 87 | 87 | Mac compat run green (46 pass, 1 skip). Next: #44 (`/v1/completions`), then #45 (docs EN+FR; write |
| 88 | 88 | curl examples in `docs/*/reference/*.md` as ```bash blocks hitting http://127.0.0.1:8080/v1 so |
| 89 | 89 | `test_docs_curl.py` runs them; tag model-dependent ones `# real model`). |
| 90 | + | |
| 91 | +## Update — #44 closed | |
| 92 | +`/v1/completions` done. Only #45 (docs EN+FR) remains in v0.2; also document: the JSON instruction | |
| 93 | +added to the system prompt (#43), schema key order kept, max_tokens default for completions, | |
| 94 | +completions refusals. Mac compat suite not re-run since #44 (Linux green; Mac XCTest green). | |
| @@ -87,3 +87,8 @@ the end of the file) before starting #43; fix the ❌ first. Delete the file onc | |||
| 87 | Mac compat run green (46 pass, 1 skip). Next: #44 (`/v1/completions`), then #45 (docs EN+FR; write | 87 | Mac compat run green (46 pass, 1 skip). Next: #44 (`/v1/completions`), then #45 (docs EN+FR; write |
| 88 | curl examples in `docs/*/reference/*.md` as ```bash blocks hitting http://127.0.0.1:8080/v1 so | 88 | curl examples in `docs/*/reference/*.md` as ```bash blocks hitting http://127.0.0.1:8080/v1 so |
| 89 | `test_docs_curl.py` runs them; tag model-dependent ones `# real model`). | 89 | `test_docs_curl.py` runs them; tag model-dependent ones `# real model`). |
| 90 | + | ||
| 91 | +## Update — #44 closed | ||
| 92 | +`/v1/completions` done. Only #45 (docs EN+FR) remains in v0.2; also document: the JSON instruction | ||
| 93 | +added to the system prompt (#43), schema key order kept, max_tokens default for completions, | ||
| 94 | +completions refusals. Mac compat suite not re-run since #44 (Linux green; Mac XCTest green). | ||
modified
.memory/history.md +11 -0 | @@ -237,3 +237,14 @@ checks finish_reason == stop first (readable failure). Mac 178 pass. compat.sh f | ||
| 237 | 237 | (it would have tested a stale Release binary). Compat run on the Mac handed to the user. |
| 238 | 238 | User ran `scripts/compat.sh` on the Mac: 46 passed, 1 skipped (docs curl, until #45), 80 s. #43 |
| 239 | 239 | closed; its task 3 (manual check with a chat UI) left open as a manual follow-up. |
| 240 | + | |
| 241 | +## 2026-11-25 — #44 legacy text completions | |
| 242 | + | |
| 243 | +User: "vas y" for #44 (the ticket said "only if a real client needs it"; the user chose to do it). | |
| 244 | +Added `POST /v1/completions` (raw prompt, no chat template) with `InferenceEngine.complete` | |
| 245 | +(MLX: tokenizer.encode + container.generate; Fake: echo/script). Refused: suffix (no FIM), | |
| 246 | +logprobs, n/best_of > 1, several prompts, token arrays. Decision: max_tokens default = server config, | |
| 247 | +not OpenAI's 16 (to document in #45). Gate first failed on duplicated envelope code between | |
| 248 | +`TextCompletion` and `ChatCompletionChunk` → generic `CompletionEnvelope<Choice: EnvelopeChoice>`. | |
| 249 | +Field checks shared via `FieldChecking`. Tests: Linux 161, Mac 185 (real Qwen3-0.6B: "The capital of | |
| 250 | +France is" → Paris), compat Linux 34 pass / 21 skip. Gate PASS (run #20). Mac compat run not redone. | |
| @@ -237,3 +237,14 @@ checks finish_reason == stop first (readable failure). Mac 178 pass. compat.sh f | |||
| 237 | (it would have tested a stale Release binary). Compat run on the Mac handed to the user. | 237 | (it would have tested a stale Release binary). Compat run on the Mac handed to the user. |
| 238 | User ran `scripts/compat.sh` on the Mac: 46 passed, 1 skipped (docs curl, until #45), 80 s. #43 | 238 | User ran `scripts/compat.sh` on the Mac: 46 passed, 1 skipped (docs curl, until #45), 80 s. #43 |
| 239 | closed; its task 3 (manual check with a chat UI) left open as a manual follow-up. | 239 | closed; its task 3 (manual check with a chat UI) left open as a manual follow-up. |
| 240 | + | ||
| 241 | +## 2026-11-25 — #44 legacy text completions | ||
| 242 | + | ||
| 243 | +User: "vas y" for #44 (the ticket said "only if a real client needs it"; the user chose to do it). | ||
| 244 | +Added `POST /v1/completions` (raw prompt, no chat template) with `InferenceEngine.complete` | ||
| 245 | +(MLX: tokenizer.encode + container.generate; Fake: echo/script). Refused: suffix (no FIM), | ||
| 246 | +logprobs, n/best_of > 1, several prompts, token arrays. Decision: max_tokens default = server config, | ||
| 247 | +not OpenAI's 16 (to document in #45). Gate first failed on duplicated envelope code between | ||
| 248 | +`TextCompletion` and `ChatCompletionChunk` → generic `CompletionEnvelope<Choice: EnvelopeChoice>`. | ||
| 249 | +Field checks shared via `FieldChecking`. Tests: Linux 161, Mac 185 (real Qwen3-0.6B: "The capital of | ||
| 250 | +France is" → Paris), compat Linux 34 pass / 21 skip. Gate PASS (run #20). Mac compat run not redone. | ||
modified
.memory/summary.md +9 -3 | @@ -79,8 +79,13 @@ holds a `ConfigMap` (insertion-ordered, order-insensitive `==`); `JSONDecoder` l | ||
| 79 | 79 | (`OrderedJSONReader.swift`) for `response_format` and tool `parameters`; `jsonString` writes map |
| 80 | 80 | order. `response_format` json_object/json_schema also adds an instruction (with the schema) to the |
| 81 | 81 | system message (`formatInstruction`): without it Qwen3-4B with reasoning filled fields with prose / |
| 82 | -looped on digits. #43 closed. Next: #44 legacy completions, #45 docs (EN+FR, with curl examples | |
| 83 | -the compat suite runs). | |
| 82 | +looped on digits. #43 closed. Legacy completions (#44): `POST /v1/completions` in | |
| 83 | +`CompletionsRoute.swift` → `InferenceEngine.complete(prompt, generation:)` (raw tokens via | |
| 84 | +`container.encode` + `container.generate`, no template/thinking/tools; default implementation | |
| 85 | +throws WrongModelKind); reuses `CompletionStream`, SSE and `CompletionEnvelope<Choice>` (shared with | |
| 86 | +chat chunks); suffix/logprobs/n/best_of/multi-prompt/token arrays → 400; max_tokens defaults to the | |
| 87 | +config (not OpenAI's 16). Shared field checks in `FieldChecking.swift`. Next: #45 docs (EN+FR, | |
| 88 | +with curl examples the compat suite runs). | |
| 84 | 89 | |
| 85 | 90 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 86 | 91 | |
| @@ -181,7 +186,8 @@ the docs' curl examples (`Tests/Compatibility/`, deps via `uv`). It starts `rzb | ||
| 181 | 186 | server instead. Linux = fake engine (protocol only, `real_model` tests skipped): 28 pass, 19 skip. |
| 182 | 187 | Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes; re-run after them: |
| 183 | 188 | 46 pass, 1 skip (docs curl, until #45), 80 s. compat.sh always rebuilds rzb (incremental) unless RZB_BIN is set. |
| 184 | -Tests 2026-11-25 after #43 fixes: Linux 155, Mac 178. | |
| 189 | +Tests 2026-11-25 after #43 fixes: Linux 155, Mac 178. After #44: Linux 161, Mac 185, compat on | |
| 190 | +Linux 34 pass / 21 skip (Mac compat not re-run after #44). | |
| 185 | 191 | |
| 186 | 192 | ## mlx-swift-lm API version trap |
| 187 | 193 | |
| @@ -79,8 +79,13 @@ holds a `ConfigMap` (insertion-ordered, order-insensitive `==`); `JSONDecoder` l | |||
| 79 | (`OrderedJSONReader.swift`) for `response_format` and tool `parameters`; `jsonString` writes map | 79 | (`OrderedJSONReader.swift`) for `response_format` and tool `parameters`; `jsonString` writes map |
| 80 | order. `response_format` json_object/json_schema also adds an instruction (with the schema) to the | 80 | order. `response_format` json_object/json_schema also adds an instruction (with the schema) to the |
| 81 | system message (`formatInstruction`): without it Qwen3-4B with reasoning filled fields with prose / | 81 | system message (`formatInstruction`): without it Qwen3-4B with reasoning filled fields with prose / |
| 82 | -looped on digits. #43 closed. Next: #44 legacy completions, #45 docs (EN+FR, with curl examples | 82 | +looped on digits. #43 closed. Legacy completions (#44): `POST /v1/completions` in |
| 83 | -the compat suite runs). | 83 | +`CompletionsRoute.swift` → `InferenceEngine.complete(prompt, generation:)` (raw tokens via |
| 84 | +`container.encode` + `container.generate`, no template/thinking/tools; default implementation | ||
| 85 | +throws WrongModelKind); reuses `CompletionStream`, SSE and `CompletionEnvelope<Choice>` (shared with | ||
| 86 | +chat chunks); suffix/logprobs/n/best_of/multi-prompt/token arrays → 400; max_tokens defaults to the | ||
| 87 | +config (not OpenAI's 16). Shared field checks in `FieldChecking.swift`. Next: #45 docs (EN+FR, | ||
| 88 | +with curl examples the compat suite runs). | ||
| 84 | 89 | ||
| 85 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 90 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 86 | 91 | ||
| @@ -181,7 +186,8 @@ the docs' curl examples (`Tests/Compatibility/`, deps via `uv`). It starts `rzb | |||
| 181 | server instead. Linux = fake engine (protocol only, `real_model` tests skipped): 28 pass, 19 skip. | 186 | server instead. Linux = fake engine (protocol only, `real_model` tests skipped): 28 pass, 19 skip. |
| 182 | Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes; re-run after them: | 187 | Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes; re-run after them: |
| 183 | 46 pass, 1 skip (docs curl, until #45), 80 s. compat.sh always rebuilds rzb (incremental) unless RZB_BIN is set. | 188 | 46 pass, 1 skip (docs curl, until #45), 80 s. compat.sh always rebuilds rzb (incremental) unless RZB_BIN is set. |
| 184 | -Tests 2026-11-25 after #43 fixes: Linux 155, Mac 178. | 189 | +Tests 2026-11-25 after #43 fixes: Linux 155, Mac 178. After #44: Linux 161, Mac 185, compat on |
| 190 | +Linux 34 pass / 21 skip (Mac compat not re-run after #44). | ||
| 185 | 191 | ||
| 186 | ## mlx-swift-lm API version trap | 192 | ## mlx-swift-lm API version trap |
| 187 | 193 | ||
modified
.quality/history.jsonl +2 -0 | @@ -16,3 +16,5 @@ | ||
| 16 | 16 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "53d6eb7", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 208, "complex": 408, "cyclo": 487, "fields": 983, "funcs": 478, "lcom": 99, "lines": 8756, "loc": 6933}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 16, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:38:25Z"} |
| 17 | 17 | {"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 3 (max 0)"], "commit": "a61fd30", "counts": {"warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 213, "complex": 449, "cyclo": 538, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9261, "loc": 7339}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 17, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:15Z"} |
| 18 | 18 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "a61fd30", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 213, "complex": 449, "cyclo": 539, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9274, "loc": 7353}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 18, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:49Z"} |
| 19 | +{"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"} | |
| 20 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"} | |
| @@ -16,3 +16,5 @@ | |||
| 16 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "53d6eb7", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 208, "complex": 408, "cyclo": 487, "fields": 983, "funcs": 478, "lcom": 99, "lines": 8756, "loc": 6933}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 16, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:38:25Z"} | 16 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "53d6eb7", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 208, "complex": 408, "cyclo": 487, "fields": 983, "funcs": 478, "lcom": 99, "lines": 8756, "loc": 6933}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 16, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:38:25Z"} |
| 17 | {"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 3 (max 0)"], "commit": "a61fd30", "counts": {"warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 213, "complex": 449, "cyclo": 538, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9261, "loc": 7339}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 17, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:15Z"} | 17 | {"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 3 (max 0)"], "commit": "a61fd30", "counts": {"warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 213, "complex": 449, "cyclo": 538, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9261, "loc": 7339}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 17, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:15Z"} |
| 18 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "a61fd30", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 213, "complex": 449, "cyclo": 539, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9274, "loc": 7353}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 18, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:49Z"} | 18 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "a61fd30", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 213, "complex": 449, "cyclo": 539, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9274, "loc": 7353}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 18, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:49Z"} |
| 19 | +{"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"} | ||
| 20 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"} | ||
added
.quality/report-20261125T184420Z.md +80 -0 | new file mode 100644 | ||
| @@ -0,0 +1,80 @@ | ||
| 1 | +# Quality report — 2026-11-25T18:44:20Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `9be357d` 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**: #19 (previous: 2026-11-25T17:55:49Z) | |
| 8 | + | |
| 9 | +## Gate violations | |
| 10 | + | |
| 11 | +- code smells: 2 (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: **2** (vs previous: +2) | |
| 28 | + | |
| 29 | +| smell | file | line | detail | | |
| 30 | +|---|---|---|---| | |
| 31 | +| qlty:similar-code | Sources/RazorbillServer/CompletionsRoute.swift | 133 | Found 23 lines of similar code in 2 locations (mass = 199) | | |
| 32 | +| qlty:similar-code | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 11 | Found 23 lines of similar code in 2 locations (mass = 199) | | |
| 33 | + | |
| 34 | +## Metrics (`qlty metrics`) | |
| 35 | + | |
| 36 | +| metric | total | vs previous | | |
| 37 | +|---|---|---| | |
| 38 | +| funcs | 542 | +25 | | |
| 39 | +| classes | 223 | +10 | | |
| 40 | +| fields | 1087 | +66 | | |
| 41 | +| cyclo | 570 | +31 | | |
| 42 | +| complex | 513 | +64 | | |
| 43 | +| lcom | 106 | +4 | | |
| 44 | +| lines | 9809 | +535 | | |
| 45 | +| loc | 7811 | +458 | | |
| 46 | + | |
| 47 | +### Most complex files | |
| 48 | + | |
| 49 | +| file | complex | cyclo | loc | | |
| 50 | +|---|---|---|---| | |
| 51 | +| Sources/RazorbillServer/CompletionsRoute.swift | 48 | 21 | 257 | | |
| 52 | +| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 | | |
| 53 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | |
| 54 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 55 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | |
| 56 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 57 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | |
| 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | |
| 59 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | |
| 60 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 61 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | |
| 62 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 63 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 64 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 65 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 | | |
| 66 | + | |
| 67 | +## Trend | |
| 68 | + | |
| 69 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 70 | +|---|---|---|---|---|---|---| | |
| 71 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| 72 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| 73 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | |
| 74 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | |
| 75 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| 76 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| 77 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| 78 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| 79 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | |
| 80 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,80 @@ | |||
| 1 | +# Quality report — 2026-11-25T18:44:20Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `9be357d` 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**: #19 (previous: 2026-11-25T17:55:49Z) | ||
| 8 | + | ||
| 9 | +## Gate violations | ||
| 10 | + | ||
| 11 | +- code smells: 2 (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: **2** (vs previous: +2) | ||
| 28 | + | ||
| 29 | +| smell | file | line | detail | | ||
| 30 | +|---|---|---|---| | ||
| 31 | +| qlty:similar-code | Sources/RazorbillServer/CompletionsRoute.swift | 133 | Found 23 lines of similar code in 2 locations (mass = 199) | | ||
| 32 | +| qlty:similar-code | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 11 | Found 23 lines of similar code in 2 locations (mass = 199) | | ||
| 33 | + | ||
| 34 | +## Metrics (`qlty metrics`) | ||
| 35 | + | ||
| 36 | +| metric | total | vs previous | | ||
| 37 | +|---|---|---| | ||
| 38 | +| funcs | 542 | +25 | | ||
| 39 | +| classes | 223 | +10 | | ||
| 40 | +| fields | 1087 | +66 | | ||
| 41 | +| cyclo | 570 | +31 | | ||
| 42 | +| complex | 513 | +64 | | ||
| 43 | +| lcom | 106 | +4 | | ||
| 44 | +| lines | 9809 | +535 | | ||
| 45 | +| loc | 7811 | +458 | | ||
| 46 | + | ||
| 47 | +### Most complex files | ||
| 48 | + | ||
| 49 | +| file | complex | cyclo | loc | | ||
| 50 | +|---|---|---|---| | ||
| 51 | +| Sources/RazorbillServer/CompletionsRoute.swift | 48 | 21 | 257 | | ||
| 52 | +| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 | | ||
| 53 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | ||
| 54 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 55 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | ||
| 56 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 57 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | ||
| 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | ||
| 59 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | ||
| 60 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 61 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | ||
| 62 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 63 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 64 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 65 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 | | ||
| 66 | + | ||
| 67 | +## Trend | ||
| 68 | + | ||
| 69 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 70 | +|---|---|---|---|---|---|---| | ||
| 71 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
| 72 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
| 73 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | ||
| 74 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | ||
| 75 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
| 76 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
| 77 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
| 78 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
| 79 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | ||
| 80 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | ||
added
.quality/report-20261125T184458Z.md +73 -0 | new file mode 100644 | ||
| @@ -0,0 +1,73 @@ | ||
| 1 | +# Quality report — 2026-11-25T18:44:58Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `9be357d` 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**: #20 (previous: 2026-11-25T18:44:20Z) | |
| 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: -2) | |
| 24 | + | |
| 25 | +_none_ | |
| 26 | + | |
| 27 | +## Metrics (`qlty metrics`) | |
| 28 | + | |
| 29 | +| metric | total | vs previous | | |
| 30 | +|---|---|---| | |
| 31 | +| funcs | 541 | -1 | | |
| 32 | +| classes | 221 | -2 | | |
| 33 | +| fields | 1086 | -1 | | |
| 34 | +| cyclo | 569 | -1 | | |
| 35 | +| complex | 512 | -1 | | |
| 36 | +| lcom | 106 | ±0 | | |
| 37 | +| lines | 9798 | -11 | | |
| 38 | +| loc | 7798 | -13 | | |
| 39 | + | |
| 40 | +### Most complex files | |
| 41 | + | |
| 42 | +| file | complex | cyclo | loc | | |
| 43 | +|---|---|---|---| | |
| 44 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 | | |
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 | | |
| 46 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | |
| 47 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 48 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | |
| 49 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 50 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | |
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | |
| 52 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 | | |
| 53 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 54 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | |
| 55 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 56 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 57 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 | | |
| 59 | + | |
| 60 | +## Trend | |
| 61 | + | |
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 63 | +|---|---|---|---|---|---|---| | |
| 64 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| 65 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | |
| 66 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | |
| 67 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| 68 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| 69 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| 70 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| 71 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | |
| 72 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | |
| 73 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,73 @@ | |||
| 1 | +# Quality report — 2026-11-25T18:44:58Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `9be357d` 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**: #20 (previous: 2026-11-25T18:44:20Z) | ||
| 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: -2) | ||
| 24 | + | ||
| 25 | +_none_ | ||
| 26 | + | ||
| 27 | +## Metrics (`qlty metrics`) | ||
| 28 | + | ||
| 29 | +| metric | total | vs previous | | ||
| 30 | +|---|---|---| | ||
| 31 | +| funcs | 541 | -1 | | ||
| 32 | +| classes | 221 | -2 | | ||
| 33 | +| fields | 1086 | -1 | | ||
| 34 | +| cyclo | 569 | -1 | | ||
| 35 | +| complex | 512 | -1 | | ||
| 36 | +| lcom | 106 | ±0 | | ||
| 37 | +| lines | 9798 | -11 | | ||
| 38 | +| loc | 7798 | -13 | | ||
| 39 | + | ||
| 40 | +### Most complex files | ||
| 41 | + | ||
| 42 | +| file | complex | cyclo | loc | | ||
| 43 | +|---|---|---|---| | ||
| 44 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 | | ||
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 | | ||
| 46 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | ||
| 47 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 48 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | ||
| 49 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 50 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | ||
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | ||
| 52 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 | | ||
| 53 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 54 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | ||
| 55 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 56 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 57 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 | | ||
| 59 | + | ||
| 60 | +## Trend | ||
| 61 | + | ||
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 63 | +|---|---|---|---|---|---|---| | ||
| 64 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
| 65 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | ||
| 66 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | ||
| 67 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
| 68 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
| 69 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
| 70 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
| 71 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | ||
| 72 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | ||
| 73 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | ||
modified
.quality/report-latest.md +20 -22 | @@ -1,16 +1,14 @@ | ||
| 1 | -# Quality report — 2026-11-25T17:55:49Z | |
| 1 | +# Quality report — 2026-11-25T18:44:58Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `a61fd30` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `9be357d` 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**: #18 (previous: 2026-11-25T17:55:15Z) | |
| 7 | +- **Run**: #20 (previous: 2026-11-25T18:44:20Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| 11 | -| level | count | vs previous | | |
| 12 | -|---|---|---| | |
| 13 | -| warning | 0 | -3 | | |
| 11 | +_none_ | |
| 14 | 12 | |
| 15 | 13 | ### Top rules |
| 16 | 14 | |
| @@ -22,7 +20,7 @@ _none_ | ||
| 22 | 20 | |
| 23 | 21 | ## Code smells (`qlty smells`) |
| 24 | 22 | |
| 25 | -Total: **0** (vs previous: ±0) | |
| 23 | +Total: **0** (vs previous: -2) | |
| 26 | 24 | |
| 27 | 25 | _none_ |
| 28 | 26 | |
| @@ -30,41 +28,39 @@ _none_ | ||
| 30 | 28 | |
| 31 | 29 | | metric | total | vs previous | |
| 32 | 30 | |---|---|---| |
| 33 | -| funcs | 517 | ±0 | | |
| 34 | -| classes | 213 | ±0 | | |
| 35 | -| fields | 1021 | ±0 | | |
| 36 | -| cyclo | 539 | +1 | | |
| 37 | -| complex | 449 | ±0 | | |
| 38 | -| lcom | 102 | ±0 | | |
| 39 | -| lines | 9274 | +13 | | |
| 40 | -| loc | 7353 | +14 | | |
| 31 | +| funcs | 541 | -1 | | |
| 32 | +| classes | 221 | -2 | | |
| 33 | +| fields | 1086 | -1 | | |
| 34 | +| cyclo | 569 | -1 | | |
| 35 | +| complex | 512 | -1 | | |
| 36 | +| lcom | 106 | ±0 | | |
| 37 | +| lines | 9798 | -11 | | |
| 38 | +| loc | 7798 | -13 | | |
| 41 | 39 | |
| 42 | 40 | ### Most complex files |
| 43 | 41 | |
| 44 | 42 | | file | complex | cyclo | loc | |
| 45 | 43 | |---|---|---|---| |
| 44 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 | | |
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 | | |
| 46 | 46 | | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | |
| 47 | -| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | |
| 48 | 47 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 49 | 48 | | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | |
| 50 | 49 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | |
| 51 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 18 | 25 | 284 | | |
| 52 | 50 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | |
| 53 | -| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | |
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | |
| 52 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 | | |
| 54 | 53 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 55 | 54 | | Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | |
| 56 | 55 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 57 | 56 | | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | |
| 58 | 57 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 59 | -| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | |
| 60 | -| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | |
| 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 | | |
| 61 | 59 | |
| 62 | 60 | ## Trend |
| 63 | 61 | |
| 64 | 62 | | run | timestamp | error | warning | smells | complex | gate | |
| 65 | 63 | |---|---|---|---|---|---|---| |
| 66 | -| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 67 | -| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| 68 | 64 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | |
| 69 | 65 | | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | |
| 70 | 66 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | |
| @@ -73,3 +69,5 @@ _none_ | ||
| 73 | 69 | | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | |
| 74 | 70 | | 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | |
| 75 | 71 | | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | |
| 72 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | |
| 73 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | |
| @@ -1,16 +1,14 @@ | |||
| 1 | -# Quality report — 2026-11-25T17:55:49Z | 1 | +# Quality report — 2026-11-25T18:44:58Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `a61fd30` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `9be357d` 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**: #18 (previous: 2026-11-25T17:55:15Z) | 7 | +- **Run**: #20 (previous: 2026-11-25T18:44:20Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| 11 | -| level | count | vs previous | | 11 | +_none_ |
| 12 | -|---|---|---| | ||
| 13 | -| warning | 0 | -3 | | ||
| 14 | 12 | ||
| 15 | ### Top rules | 13 | ### Top rules |
| 16 | 14 | ||
| @@ -22,7 +20,7 @@ _none_ | |||
| 22 | 20 | ||
| 23 | ## Code smells (`qlty smells`) | 21 | ## Code smells (`qlty smells`) |
| 24 | 22 | ||
| 25 | -Total: **0** (vs previous: ±0) | 23 | +Total: **0** (vs previous: -2) |
| 26 | 24 | ||
| 27 | _none_ | 25 | _none_ |
| 28 | 26 | ||
| @@ -30,41 +28,39 @@ _none_ | |||
| 30 | 28 | ||
| 31 | | metric | total | vs previous | | 29 | | metric | total | vs previous | |
| 32 | |---|---|---| | 30 | |---|---|---| |
| 33 | -| funcs | 517 | ±0 | | 31 | +| funcs | 541 | -1 | |
| 34 | -| classes | 213 | ±0 | | 32 | +| classes | 221 | -2 | |
| 35 | -| fields | 1021 | ±0 | | 33 | +| fields | 1086 | -1 | |
| 36 | -| cyclo | 539 | +1 | | 34 | +| cyclo | 569 | -1 | |
| 37 | -| complex | 449 | ±0 | | 35 | +| complex | 512 | -1 | |
| 38 | -| lcom | 102 | ±0 | | 36 | +| lcom | 106 | ±0 | |
| 39 | -| lines | 9274 | +13 | | 37 | +| lines | 9798 | -11 | |
| 40 | -| loc | 7353 | +14 | | 38 | +| loc | 7798 | -13 | |
| 41 | 39 | ||
| 42 | ### Most complex files | 40 | ### Most complex files |
| 43 | 41 | ||
| 44 | | file | complex | cyclo | loc | | 42 | | file | complex | cyclo | loc | |
| 45 | |---|---|---|---| | 43 | |---|---|---|---| |
| 44 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 | | ||
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 | | ||
| 46 | | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | 46 | | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | |
| 47 | -| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | ||
| 48 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | | 47 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 49 | | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | 48 | | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | |
| 50 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | 49 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | |
| 51 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 18 | 25 | 284 | | ||
| 52 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | 50 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | |
| 53 | -| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | |
| 52 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 | | ||
| 54 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | 53 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 55 | | Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | 54 | | Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | |
| 56 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 55 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 57 | | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | 56 | | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | |
| 58 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | 57 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 59 | -| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | 58 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 | |
| 60 | -| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | ||
| 61 | 59 | ||
| 62 | ## Trend | 60 | ## Trend |
| 63 | 61 | ||
| 64 | | run | timestamp | error | warning | smells | complex | gate | | 62 | | run | timestamp | error | warning | smells | complex | gate | |
| 65 | |---|---|---|---|---|---|---| | 63 | |---|---|---|---|---|---|---| |
| 66 | -| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 67 | -| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
| 68 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | 64 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | |
| 69 | | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | 65 | | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | |
| 70 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | 66 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | |
| @@ -73,3 +69,5 @@ _none_ | |||
| 73 | | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | 69 | | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | |
| 74 | | 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | 70 | | 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | |
| 75 | | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | 71 | | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | |
| 72 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | ||
| 73 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | ||
modified
.tickets/issues/0044-legacy-text-completions-post-v1-completions.yaml +23 -5 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 44 |
| 3 | 3 | title: "Legacy text completions: POST /v1/completions" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T19:50:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::server" |
| @@ -20,18 +20,36 @@ body: | | ||
| 20 | 20 | tasks: |
| 21 | 21 | - id: 1 |
| 22 | 22 | title: "Decide whether v0.2 needs it" |
| 23 | - state: open | |
| 23 | + state: closed | |
| 24 | 24 | priority: low |
| 25 | 25 | author: |
| 26 | 26 | name: k33g |
| 27 | 27 | email: ph.charriere@gmail.com |
| 28 | 28 | createdAt: 2026-11-24T21:17:08.000Z |
| 29 | + updatedAt: 2026-11-25T19:50:00.000Z | |
| 30 | + closedAt: 2026-11-25T19:50:00.000Z | |
| 29 | 31 | - id: 2 |
| 30 | 32 | title: "Implement prompt-only completion + streaming" |
| 31 | - state: open | |
| 33 | + state: closed | |
| 32 | 34 | priority: low |
| 33 | 35 | author: |
| 34 | 36 | name: k33g |
| 35 | 37 | email: ph.charriere@gmail.com |
| 36 | 38 | createdAt: 2026-11-24T21:17:08.000Z |
| 37 | -comments: [] | |
| 39 | + updatedAt: 2026-11-25T19:50:00.000Z | |
| 40 | + closedAt: 2026-11-25T19:50:00.000Z | |
| 41 | +comments: | |
| 42 | + - id: 1 | |
| 43 | + author: | |
| 44 | + name: k33g | |
| 45 | + email: ph.charriere@gmail.com | |
| 46 | + createdAt: 2026-11-25T19:50:00.000Z | |
| 47 | + body: | | |
| 48 | + Done (user asked for it, 2026-11-25). POST /v1/completions: prompt (string or one-element | |
| 49 | + list) continued as raw text (InferenceEngine.complete: no chat template, no thinking, no tool | |
| 50 | + parsing), max_tokens, temperature, top_p, stop, seed, penalties, echo, stream (+ include_usage), | |
| 51 | + cancellation on disconnect. Refused with a 400: suffix (no FIM), logprobs > 0, n / best_of > 1, | |
| 52 | + several prompts, token arrays. max_tokens defaults to the server configuration, not OpenAI's 16. | |
| 53 | + Tests: Linux 161 (CompletionsTests), Mac 185 (real Qwen3-0.6B continuation), compat suite 34/21 on | |
| 54 | + Linux (test_completions.py). Gate PASS (run #20). | |
| 55 | + | |
| @@ -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: 44 | 2 | id: 44 |
| 3 | title: "Legacy text completions: POST /v1/completions" | 3 | title: "Legacy text completions: POST /v1/completions" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T19:50:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::server" | 12 | - "area::server" |
| @@ -20,18 +20,36 @@ body: | | |||
| 20 | tasks: | 20 | tasks: |
| 21 | - id: 1 | 21 | - id: 1 |
| 22 | title: "Decide whether v0.2 needs it" | 22 | title: "Decide whether v0.2 needs it" |
| 23 | - state: open | 23 | + state: closed |
| 24 | priority: low | 24 | priority: low |
| 25 | author: | 25 | author: |
| 26 | name: k33g | 26 | name: k33g |
| 27 | email: ph.charriere@gmail.com | 27 | email: ph.charriere@gmail.com |
| 28 | createdAt: 2026-11-24T21:17:08.000Z | 28 | createdAt: 2026-11-24T21:17:08.000Z |
| 29 | + updatedAt: 2026-11-25T19:50:00.000Z | ||
| 30 | + closedAt: 2026-11-25T19:50:00.000Z | ||
| 29 | - id: 2 | 31 | - id: 2 |
| 30 | title: "Implement prompt-only completion + streaming" | 32 | title: "Implement prompt-only completion + streaming" |
| 31 | - state: open | 33 | + state: closed |
| 32 | priority: low | 34 | priority: low |
| 33 | author: | 35 | author: |
| 34 | name: k33g | 36 | name: k33g |
| 35 | email: ph.charriere@gmail.com | 37 | email: ph.charriere@gmail.com |
| 36 | createdAt: 2026-11-24T21:17:08.000Z | 38 | createdAt: 2026-11-24T21:17:08.000Z |
| 37 | -comments: [] | 39 | + updatedAt: 2026-11-25T19:50:00.000Z |
| 40 | + closedAt: 2026-11-25T19:50:00.000Z | ||
| 41 | +comments: | ||
| 42 | + - id: 1 | ||
| 43 | + author: | ||
| 44 | + name: k33g | ||
| 45 | + email: ph.charriere@gmail.com | ||
| 46 | + createdAt: 2026-11-25T19:50:00.000Z | ||
| 47 | + body: | | ||
| 48 | + Done (user asked for it, 2026-11-25). POST /v1/completions: prompt (string or one-element | ||
| 49 | + list) continued as raw text (InferenceEngine.complete: no chat template, no thinking, no tool | ||
| 50 | + parsing), max_tokens, temperature, top_p, stop, seed, penalties, echo, stream (+ include_usage), | ||
| 51 | + cancellation on disconnect. Refused with a 400: suffix (no FIM), logprobs > 0, n / best_of > 1, | ||
| 52 | + several prompts, token arrays. max_tokens defaults to the server configuration, not OpenAI's 16. | ||
| 53 | + Tests: Linux 161 (CompletionsTests), Mac 185 (real Qwen3-0.6B continuation), compat suite 34/21 on | ||
| 54 | + Linux (test_completions.py). Gate PASS (run #20). | ||
| 55 | + | ||
modified
Sources/RazorbillCore/Engine/FakeEngine.swift +12 -0 | @@ -63,6 +63,18 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable { | ||
| 63 | 63 | return Embeddings(vectors: vectors, promptTokens: tokens) |
| 64 | 64 | } |
| 65 | 65 | |
| 66 | + /// Plays the next scripted turn, else answers `echo: <prompt>`; the prompt is recorded as a | |
| 67 | + /// user message in ``receivedMessages``. | |
| 68 | + public func complete( | |
| 69 | + _ prompt: String, generation: GenerationSettings | |
| 70 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | |
| 71 | + let events = nextTurn(for: [.user(prompt)]) | |
| 72 | + return AsyncThrowingStream { continuation in | |
| 73 | + for event in events { continuation.yield(event) } | |
| 74 | + continuation.finish() | |
| 75 | + } | |
| 76 | + } | |
| 77 | + | |
| 66 | 78 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 67 | 79 | lock.withLock { setups.append(setup) } |
| 68 | 80 | return Session(engine: self) |
| @@ -63,6 +63,18 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable { | |||
| 63 | return Embeddings(vectors: vectors, promptTokens: tokens) | 63 | return Embeddings(vectors: vectors, promptTokens: tokens) |
| 64 | } | 64 | } |
| 65 | 65 | ||
| 66 | + /// Plays the next scripted turn, else answers `echo: <prompt>`; the prompt is recorded as a | ||
| 67 | + /// user message in ``receivedMessages``. | ||
| 68 | + public func complete( | ||
| 69 | + _ prompt: String, generation: GenerationSettings | ||
| 70 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 71 | + let events = nextTurn(for: [.user(prompt)]) | ||
| 72 | + return AsyncThrowingStream { continuation in | ||
| 73 | + for event in events { continuation.yield(event) } | ||
| 74 | + continuation.finish() | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + | ||
| 66 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 78 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 67 | lock.withLock { setups.append(setup) } | 79 | lock.withLock { setups.append(setup) } |
| 68 | return Session(engine: self) | 80 | return Session(engine: self) |
modified
Sources/RazorbillCore/Engine/InferenceEngine.swift +13 -0 | @@ -68,6 +68,12 @@ public protocol InferenceEngine: Sendable { | ||
| 68 | 68 | |
| 69 | 69 | /// Embeds `texts` with a loaded embedding model, one vector per text. |
| 70 | 70 | func embed(_ texts: [String]) async throws -> Embeddings |
| 71 | + | |
| 72 | + /// Continues `prompt` as raw text: no chat template, no thinking, no tools | |
| 73 | + /// (`/v1/completions`). Streams `.text` pieces then `.stats`; cancelling stops it. | |
| 74 | + func complete( | |
| 75 | + _ prompt: String, generation: GenerationSettings | |
| 76 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> | |
| 71 | 77 | } |
| 72 | 78 | |
| 73 | 79 | extension InferenceEngine { |
| @@ -78,6 +84,13 @@ extension InferenceEngine { | ||
| 78 | 84 | public func embed(_ texts: [String]) async throws -> Embeddings { |
| 79 | 85 | throw WrongModelKind(model: name, kind: .chat, wanted: .embedding) |
| 80 | 86 | } |
| 87 | + | |
| 88 | + /// Engines without a raw-text path (embedding engines) cannot complete a prompt. | |
| 89 | + public func complete( | |
| 90 | + _ prompt: String, generation: GenerationSettings | |
| 91 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | |
| 92 | + throw WrongModelKind(model: name, kind: .embedding, wanted: .chat) | |
| 93 | + } | |
| 81 | 94 | } |
| 82 | 95 | |
| 83 | 96 | /// One conversation with a loaded model. It keeps the history (and the model's cache), so each |
| @@ -68,6 +68,12 @@ public protocol InferenceEngine: Sendable { | |||
| 68 | 68 | ||
| 69 | /// Embeds `texts` with a loaded embedding model, one vector per text. | 69 | /// Embeds `texts` with a loaded embedding model, one vector per text. |
| 70 | func embed(_ texts: [String]) async throws -> Embeddings | 70 | func embed(_ texts: [String]) async throws -> Embeddings |
| 71 | + | ||
| 72 | + /// Continues `prompt` as raw text: no chat template, no thinking, no tools | ||
| 73 | + /// (`/v1/completions`). Streams `.text` pieces then `.stats`; cancelling stops it. | ||
| 74 | + func complete( | ||
| 75 | + _ prompt: String, generation: GenerationSettings | ||
| 76 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> | ||
| 71 | } | 77 | } |
| 72 | 78 | ||
| 73 | extension InferenceEngine { | 79 | extension InferenceEngine { |
| @@ -78,6 +84,13 @@ extension InferenceEngine { | |||
| 78 | public func embed(_ texts: [String]) async throws -> Embeddings { | 84 | public func embed(_ texts: [String]) async throws -> Embeddings { |
| 79 | throw WrongModelKind(model: name, kind: .chat, wanted: .embedding) | 85 | throw WrongModelKind(model: name, kind: .chat, wanted: .embedding) |
| 80 | } | 86 | } |
| 87 | + | ||
| 88 | + /// Engines without a raw-text path (embedding engines) cannot complete a prompt. | ||
| 89 | + public func complete( | ||
| 90 | + _ prompt: String, generation: GenerationSettings | ||
| 91 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 92 | + throw WrongModelKind(model: name, kind: .embedding, wanted: .chat) | ||
| 93 | + } | ||
| 81 | } | 94 | } |
| 82 | 95 | ||
| 83 | /// One conversation with a loaded model. It keeps the history (and the model's cache), so each | 96 | /// One conversation with a loaded model. It keeps the history (and the model's cache), so each |
modified
Sources/RazorbillMLX/MLXEngine.swift +49 -11 | @@ -1,6 +1,7 @@ | ||
| 1 | 1 | #if canImport(MLXLLM) |
| 2 | 2 | import Foundation |
| 3 | 3 | import HuggingFace |
| 4 | +import MLX | |
| 4 | 5 | import MLXHuggingFace |
| 5 | 6 | import MLXLLM |
| 6 | 7 | import MLXLMCommon |
| @@ -74,13 +75,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 74 | 75 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 75 | 76 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } |
| 76 | 77 | await useToolCallFormat(for: setup, in: container) |
| 77 | - var parameters = GenerateParameters( | |
| 78 | - maxTokens: setup.generation.maxTokens, | |
| 79 | - temperature: Float(setup.generation.temperature), | |
| 80 | - topP: Float(setup.generation.topP)) | |
| 81 | - parameters.seed = setup.generation.seed | |
| 82 | - parameters.presencePenalty = setup.generation.presencePenalty.map(Float.init) | |
| 83 | - parameters.frequencyPenalty = setup.generation.frequencyPenalty.map(Float.init) | |
| 78 | + var parameters = Self.parameters(setup.generation) | |
| 84 | 79 | if setup.tools.isEmpty { |
| 85 | 80 | // No tools offered: nothing to recover, and the recovery scanner would hold back any |
| 86 | 81 | // answer starting with "{" (a JSON answer would then arrive in one piece). |
| @@ -99,6 +94,46 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 99 | 94 | return MLXSession(session: session, startsInsideThinking: opensThinking) |
| 100 | 95 | } |
| 101 | 96 | |
| 97 | + /// The prompt's tokens as they are (the tokenizer may add its BOS token, as for any raw | |
| 98 | + /// completion), generated without chat template, thinking split or tool calls. | |
| 99 | + public func complete( | |
| 100 | + _ prompt: String, generation: GenerationSettings | |
| 101 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | |
| 102 | + guard let container = lock.withLock({ container }) else { throw NotLoaded() } | |
| 103 | + let noTools = SessionSetup(system: "", tools: [], generation: generation) | |
| 104 | + await useToolCallFormat(for: noTools, in: container) | |
| 105 | + var parameters = Self.parameters(generation) | |
| 106 | + parameters.toolCallPolicy.recovery = .disabled | |
| 107 | + let tokens = await container.encode(prompt) | |
| 108 | + let input = LMInput(tokens: MLXArray(tokens)) | |
| 109 | + let generations = try await container.generate(input: input, parameters: parameters) | |
| 110 | + return AsyncThrowingStream { continuation in | |
| 111 | + let task = Task { | |
| 112 | + for await generation in generations { | |
| 113 | + if Task.isCancelled { break } | |
| 114 | + switch generation { | |
| 115 | + case .chunk(let text): continuation.yield(.text(text)) | |
| 116 | + case .info(let info): continuation.yield(.stats(MLXConversion.stats(info))) | |
| 117 | + default: break | |
| 118 | + } | |
| 119 | + } | |
| 120 | + continuation.finish() | |
| 121 | + } | |
| 122 | + continuation.onTermination = { _ in task.cancel() } | |
| 123 | + } | |
| 124 | + } | |
| 125 | + | |
| 126 | + /// mlx-swift-lm's sampling settings for `generation`. | |
| 127 | + static func parameters(_ generation: GenerationSettings) -> GenerateParameters { | |
| 128 | + var parameters = GenerateParameters( | |
| 129 | + maxTokens: generation.maxTokens, temperature: Float(generation.temperature), | |
| 130 | + topP: Float(generation.topP)) | |
| 131 | + parameters.seed = generation.seed | |
| 132 | + parameters.presencePenalty = generation.presencePenalty.map(Float.init) | |
| 133 | + parameters.frequencyPenalty = generation.frequencyPenalty.map(Float.init) | |
| 134 | + return parameters | |
| 135 | + } | |
| 136 | + | |
| 102 | 137 | /// The `.json` tool-call parser (Qwen, Hermes…) holds back any answer starting with "{" in case |
| 103 | 138 | /// it is a bare-JSON tool call, so a JSON answer would stream in one piece. Without tools there |
| 104 | 139 | /// is no call to find: use `.gptOSS`, the same `<tool_call>` parser without that fallback. The |
| @@ -239,10 +274,7 @@ enum MLXConversion { | ||
| 239 | 274 | id: call.id, name: call.function.name, arguments: arguments) |
| 240 | 275 | return splitter.finish() + [.toolCall(toolCall)] |
| 241 | 276 | case .info(let info): |
| 242 | - let stats = GenerationStats( | |
| 243 | - promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, | |
| 244 | - tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) | |
| 245 | - return splitter.finish() + [.stats(stats)] | |
| 277 | + return splitter.finish() + [.stats(stats(info))] | |
| 246 | 278 | default: |
| 247 | 279 | return [] |
| 248 | 280 | } |
| @@ -272,6 +304,12 @@ enum MLXConversion { | ||
| 272 | 304 | } |
| 273 | 305 | } |
| 274 | 306 | |
| 307 | + static func stats(_ info: GenerateCompletionInfo) -> GenerationStats { | |
| 308 | + GenerationStats( | |
| 309 | + promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, | |
| 310 | + tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) | |
| 311 | + } | |
| 312 | + | |
| 275 | 313 | static func value(_ json: JSONValue) -> ConfigValue { |
| 276 | 314 | switch json { |
| 277 | 315 | case .null: .null |
| @@ -1,6 +1,7 @@ | |||
| 1 | #if canImport(MLXLLM) | 1 | #if canImport(MLXLLM) |
| 2 | import Foundation | 2 | import Foundation |
| 3 | import HuggingFace | 3 | import HuggingFace |
| 4 | +import MLX | ||
| 4 | import MLXHuggingFace | 5 | import MLXHuggingFace |
| 5 | import MLXLLM | 6 | import MLXLLM |
| 6 | import MLXLMCommon | 7 | import MLXLMCommon |
| @@ -74,13 +75,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 74 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 75 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 75 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } | 76 | guard let container = lock.withLock({ container }) else { throw NotLoaded() } |
| 76 | await useToolCallFormat(for: setup, in: container) | 77 | await useToolCallFormat(for: setup, in: container) |
| 77 | - var parameters = GenerateParameters( | 78 | + var parameters = Self.parameters(setup.generation) |
| 78 | - maxTokens: setup.generation.maxTokens, | ||
| 79 | - temperature: Float(setup.generation.temperature), | ||
| 80 | - topP: Float(setup.generation.topP)) | ||
| 81 | - parameters.seed = setup.generation.seed | ||
| 82 | - parameters.presencePenalty = setup.generation.presencePenalty.map(Float.init) | ||
| 83 | - parameters.frequencyPenalty = setup.generation.frequencyPenalty.map(Float.init) | ||
| 84 | if setup.tools.isEmpty { | 79 | if setup.tools.isEmpty { |
| 85 | // No tools offered: nothing to recover, and the recovery scanner would hold back any | 80 | // No tools offered: nothing to recover, and the recovery scanner would hold back any |
| 86 | // answer starting with "{" (a JSON answer would then arrive in one piece). | 81 | // answer starting with "{" (a JSON answer would then arrive in one piece). |
| @@ -99,6 +94,46 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 99 | return MLXSession(session: session, startsInsideThinking: opensThinking) | 94 | return MLXSession(session: session, startsInsideThinking: opensThinking) |
| 100 | } | 95 | } |
| 101 | 96 | ||
| 97 | + /// The prompt's tokens as they are (the tokenizer may add its BOS token, as for any raw | ||
| 98 | + /// completion), generated without chat template, thinking split or tool calls. | ||
| 99 | + public func complete( | ||
| 100 | + _ prompt: String, generation: GenerationSettings | ||
| 101 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 102 | + guard let container = lock.withLock({ container }) else { throw NotLoaded() } | ||
| 103 | + let noTools = SessionSetup(system: "", tools: [], generation: generation) | ||
| 104 | + await useToolCallFormat(for: noTools, in: container) | ||
| 105 | + var parameters = Self.parameters(generation) | ||
| 106 | + parameters.toolCallPolicy.recovery = .disabled | ||
| 107 | + let tokens = await container.encode(prompt) | ||
| 108 | + let input = LMInput(tokens: MLXArray(tokens)) | ||
| 109 | + let generations = try await container.generate(input: input, parameters: parameters) | ||
| 110 | + return AsyncThrowingStream { continuation in | ||
| 111 | + let task = Task { | ||
| 112 | + for await generation in generations { | ||
| 113 | + if Task.isCancelled { break } | ||
| 114 | + switch generation { | ||
| 115 | + case .chunk(let text): continuation.yield(.text(text)) | ||
| 116 | + case .info(let info): continuation.yield(.stats(MLXConversion.stats(info))) | ||
| 117 | + default: break | ||
| 118 | + } | ||
| 119 | + } | ||
| 120 | + continuation.finish() | ||
| 121 | + } | ||
| 122 | + continuation.onTermination = { _ in task.cancel() } | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + /// mlx-swift-lm's sampling settings for `generation`. | ||
| 127 | + static func parameters(_ generation: GenerationSettings) -> GenerateParameters { | ||
| 128 | + var parameters = GenerateParameters( | ||
| 129 | + maxTokens: generation.maxTokens, temperature: Float(generation.temperature), | ||
| 130 | + topP: Float(generation.topP)) | ||
| 131 | + parameters.seed = generation.seed | ||
| 132 | + parameters.presencePenalty = generation.presencePenalty.map(Float.init) | ||
| 133 | + parameters.frequencyPenalty = generation.frequencyPenalty.map(Float.init) | ||
| 134 | + return parameters | ||
| 135 | + } | ||
| 136 | + | ||
| 102 | /// The `.json` tool-call parser (Qwen, Hermes…) holds back any answer starting with "{" in case | 137 | /// The `.json` tool-call parser (Qwen, Hermes…) holds back any answer starting with "{" in case |
| 103 | /// it is a bare-JSON tool call, so a JSON answer would stream in one piece. Without tools there | 138 | /// it is a bare-JSON tool call, so a JSON answer would stream in one piece. Without tools there |
| 104 | /// is no call to find: use `.gptOSS`, the same `<tool_call>` parser without that fallback. The | 139 | /// is no call to find: use `.gptOSS`, the same `<tool_call>` parser without that fallback. The |
| @@ -239,10 +274,7 @@ enum MLXConversion { | |||
| 239 | id: call.id, name: call.function.name, arguments: arguments) | 274 | id: call.id, name: call.function.name, arguments: arguments) |
| 240 | return splitter.finish() + [.toolCall(toolCall)] | 275 | return splitter.finish() + [.toolCall(toolCall)] |
| 241 | case .info(let info): | 276 | case .info(let info): |
| 242 | - let stats = GenerationStats( | 277 | + return splitter.finish() + [.stats(stats(info))] |
| 243 | - promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, | ||
| 244 | - tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) | ||
| 245 | - return splitter.finish() + [.stats(stats)] | ||
| 246 | default: | 278 | default: |
| 247 | return [] | 279 | return [] |
| 248 | } | 280 | } |
| @@ -272,6 +304,12 @@ enum MLXConversion { | |||
| 272 | } | 304 | } |
| 273 | } | 305 | } |
| 274 | 306 | ||
| 307 | + static func stats(_ info: GenerateCompletionInfo) -> GenerationStats { | ||
| 308 | + GenerationStats( | ||
| 309 | + promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, | ||
| 310 | + tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) | ||
| 311 | + } | ||
| 312 | + | ||
| 275 | static func value(_ json: JSONValue) -> ConfigValue { | 313 | static func value(_ json: JSONValue) -> ConfigValue { |
| 276 | switch json { | 314 | switch json { |
| 277 | case .null: .null | 315 | case .null: .null |
modified
Sources/RazorbillServer/Chat/ChatCompletionChunk.swift +14 -4 | @@ -8,11 +8,20 @@ import RazorbillCore | ||
| 8 | 8 | /// `delta.tool_calls`) pieces, then a chunk with an empty delta and `finish_reason`; with |
| 9 | 9 | /// `stream_options.include_usage`, a last chunk with empty `choices` and the `usage` (every other |
| 10 | 10 | /// chunk then carries `"usage": null`). |
| 11 | -struct ChatCompletionChunk: Encodable, Sendable { | |
| 11 | +typealias ChatCompletionChunk = CompletionEnvelope<ChunkChoice> | |
| 12 | + | |
| 13 | +/// The choice type of a ``CompletionEnvelope`` names the envelope's `object`. | |
| 14 | +protocol EnvelopeChoice: Encodable, Sendable { | |
| 15 | + static var object: String { get } | |
| 16 | +} | |
| 17 | + | |
| 18 | +/// `{"id", "object", "created", "model", "choices", "usage"}`: the outer shape shared by stream | |
| 19 | +/// chunks and legacy text completions. | |
| 20 | +struct CompletionEnvelope<Choice: EnvelopeChoice>: Encodable, Sendable { | |
| 12 | 21 | let id: String |
| 13 | 22 | let created: Int |
| 14 | 23 | let model: String |
| 15 | - let choices: [ChunkChoice] | |
| 24 | + let choices: [Choice] | |
| 16 | 25 | /// `nil` and not written unless usage was requested; then `null` until the last chunk. |
| 17 | 26 | let usage: Usage? |
| 18 | 27 | let includesUsage: Bool |
| @@ -24,7 +33,7 @@ struct ChatCompletionChunk: Encodable, Sendable { | ||
| 24 | 33 | func encode(to encoder: any Encoder) throws { |
| 25 | 34 | var container = encoder.container(keyedBy: CodingKeys.self) |
| 26 | 35 | try container.encode(id, forKey: .id) |
| 27 | - try container.encode("chat.completion.chunk", forKey: .object) | |
| 36 | + try container.encode(Choice.object, forKey: .object) | |
| 28 | 37 | try container.encode(created, forKey: .created) |
| 29 | 38 | try container.encode(model, forKey: .model) |
| 30 | 39 | try container.encode(choices, forKey: .choices) |
| @@ -33,7 +42,8 @@ struct ChatCompletionChunk: Encodable, Sendable { | ||
| 33 | 42 | } |
| 34 | 43 | |
| 35 | 44 | /// The one choice of a chunk. |
| 36 | -struct ChunkChoice: Encodable, Sendable { | |
| 45 | +struct ChunkChoice: EnvelopeChoice { | |
| 46 | + static let object = "chat.completion.chunk" | |
| 37 | 47 | let delta: ChunkDelta |
| 38 | 48 | let finishReason: FinishReason? |
| 39 | 49 | |
| @@ -8,11 +8,20 @@ import RazorbillCore | |||
| 8 | /// `delta.tool_calls`) pieces, then a chunk with an empty delta and `finish_reason`; with | 8 | /// `delta.tool_calls`) pieces, then a chunk with an empty delta and `finish_reason`; with |
| 9 | /// `stream_options.include_usage`, a last chunk with empty `choices` and the `usage` (every other | 9 | /// `stream_options.include_usage`, a last chunk with empty `choices` and the `usage` (every other |
| 10 | /// chunk then carries `"usage": null`). | 10 | /// chunk then carries `"usage": null`). |
| 11 | -struct ChatCompletionChunk: Encodable, Sendable { | 11 | +typealias ChatCompletionChunk = CompletionEnvelope<ChunkChoice> |
| 12 | + | ||
| 13 | +/// The choice type of a ``CompletionEnvelope`` names the envelope's `object`. | ||
| 14 | +protocol EnvelopeChoice: Encodable, Sendable { | ||
| 15 | + static var object: String { get } | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +/// `{"id", "object", "created", "model", "choices", "usage"}`: the outer shape shared by stream | ||
| 19 | +/// chunks and legacy text completions. | ||
| 20 | +struct CompletionEnvelope<Choice: EnvelopeChoice>: Encodable, Sendable { | ||
| 12 | let id: String | 21 | let id: String |
| 13 | let created: Int | 22 | let created: Int |
| 14 | let model: String | 23 | let model: String |
| 15 | - let choices: [ChunkChoice] | 24 | + let choices: [Choice] |
| 16 | /// `nil` and not written unless usage was requested; then `null` until the last chunk. | 25 | /// `nil` and not written unless usage was requested; then `null` until the last chunk. |
| 17 | let usage: Usage? | 26 | let usage: Usage? |
| 18 | let includesUsage: Bool | 27 | let includesUsage: Bool |
| @@ -24,7 +33,7 @@ struct ChatCompletionChunk: Encodable, Sendable { | |||
| 24 | func encode(to encoder: any Encoder) throws { | 33 | func encode(to encoder: any Encoder) throws { |
| 25 | var container = encoder.container(keyedBy: CodingKeys.self) | 34 | var container = encoder.container(keyedBy: CodingKeys.self) |
| 26 | try container.encode(id, forKey: .id) | 35 | try container.encode(id, forKey: .id) |
| 27 | - try container.encode("chat.completion.chunk", forKey: .object) | 36 | + try container.encode(Choice.object, forKey: .object) |
| 28 | try container.encode(created, forKey: .created) | 37 | try container.encode(created, forKey: .created) |
| 29 | try container.encode(model, forKey: .model) | 38 | try container.encode(model, forKey: .model) |
| 30 | try container.encode(choices, forKey: .choices) | 39 | try container.encode(choices, forKey: .choices) |
| @@ -33,7 +42,8 @@ struct ChatCompletionChunk: Encodable, Sendable { | |||
| 33 | } | 42 | } |
| 34 | 43 | ||
| 35 | /// The one choice of a chunk. | 44 | /// The one choice of a chunk. |
| 36 | -struct ChunkChoice: Encodable, Sendable { | 45 | +struct ChunkChoice: EnvelopeChoice { |
| 46 | + static let object = "chat.completion.chunk" | ||
| 37 | let delta: ChunkDelta | 47 | let delta: ChunkDelta |
| 38 | let finishReason: FinishReason? | 48 | let finishReason: FinishReason? |
| 39 | 49 | ||
modified
Sources/RazorbillServer/Chat/ChatCompletionRequest.swift +7 -21 | @@ -3,7 +3,7 @@ import RazorbillCore | ||
| 3 | 3 | |
| 4 | 4 | /// The body of `POST /v1/chat/completions`, as OpenAI clients send it. Unknown fields are |
| 5 | 5 | /// ignored, like OpenAI does; ``validated()`` turns it into a ``ChatPlan`` or a 400. |
| 6 | -struct ChatCompletionRequest: Decodable, Sendable { | |
| 6 | +struct ChatCompletionRequest: Decodable, Sendable, FieldChecking { | |
| 7 | 7 | var model: String |
| 8 | 8 | var messages: [WireMessage] |
| 9 | 9 | var temperature: Double? |
| @@ -183,17 +183,14 @@ extension ChatCompletionRequest { | ||
| 183 | 183 | func validated() throws -> ChatPlan { |
| 184 | 184 | try checkUnsupported() |
| 185 | 185 | let stops = stop?.values ?? [] |
| 186 | - try require(stops.count <= 4, "stop", "can hold at most 4 sequences") | |
| 187 | 186 | try require(!messages.isEmpty, "messages", "must hold at least one message") |
| 188 | - try check(temperature, "temperature", "must be between 0 and 2") { (0 ... 2).contains($0) } | |
| 189 | - try check(topP, "top_p", "must be above 0 and at most 1") { $0 > 0 && $0 <= 1 } | |
| 190 | 187 | let limit = maxCompletionTokens ?? maxTokens |
| 191 | - let limitName = maxCompletionTokens == nil ? "max_tokens" : "max_completion_tokens" | |
| 192 | - try check(limit, limitName, "must be 1 or more") { $0 >= 1 } | |
| 193 | - try check(presencePenalty, "presence_penalty", "must be between -2 and 2") { abs($0) <= 2 } | |
| 194 | - try check(frequencyPenalty, "frequency_penalty", "must be between -2 and 2") { | |
| 195 | - abs($0) <= 2 | |
| 196 | - } | |
| 188 | + try checkSampling( | |
| 189 | + SamplingFields( | |
| 190 | + temperature: temperature, topP: topP, limit: limit, | |
| 191 | + limitName: maxCompletionTokens == nil ? "max_tokens" : "max_completion_tokens", | |
| 192 | + presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, | |
| 193 | + stops: stops)) | |
| 197 | 194 | try checkReasoningSwitches() |
| 198 | 195 | let output = try outputPlan() |
| 199 | 196 | let mapped = try messages.enumerated().map { try Self.message($1, at: $0) } |
| @@ -298,17 +295,6 @@ extension ChatCompletionRequest { | ||
| 298 | 295 | return ToolCall(id: wire.id, name: wire.function.name, arguments: arguments) |
| 299 | 296 | } |
| 300 | 297 | |
| 301 | - private func require(_ condition: Bool, _ param: String, _ message: String) throws { | |
| 302 | - guard condition else { | |
| 303 | - throw OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | |
| 304 | - } | |
| 305 | - } | |
| 306 | - | |
| 307 | - private func check<T>( | |
| 308 | - _ value: T?, _ param: String, _ message: String, _ isValid: (T) -> Bool | |
| 309 | - ) throws { | |
| 310 | - if let value { try require(isValid(value), param, message) } | |
| 311 | - } | |
| 312 | 298 | } |
| 313 | 299 | |
| 314 | 300 | extension OpenAIError { |
| @@ -3,7 +3,7 @@ import RazorbillCore | |||
| 3 | 3 | ||
| 4 | /// The body of `POST /v1/chat/completions`, as OpenAI clients send it. Unknown fields are | 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. | 5 | /// ignored, like OpenAI does; ``validated()`` turns it into a ``ChatPlan`` or a 400. |
| 6 | -struct ChatCompletionRequest: Decodable, Sendable { | 6 | +struct ChatCompletionRequest: Decodable, Sendable, FieldChecking { |
| 7 | var model: String | 7 | var model: String |
| 8 | var messages: [WireMessage] | 8 | var messages: [WireMessage] |
| 9 | var temperature: Double? | 9 | var temperature: Double? |
| @@ -183,17 +183,14 @@ extension ChatCompletionRequest { | |||
| 183 | func validated() throws -> ChatPlan { | 183 | func validated() throws -> ChatPlan { |
| 184 | try checkUnsupported() | 184 | try checkUnsupported() |
| 185 | let stops = stop?.values ?? [] | 185 | let stops = stop?.values ?? [] |
| 186 | - try require(stops.count <= 4, "stop", "can hold at most 4 sequences") | ||
| 187 | try require(!messages.isEmpty, "messages", "must hold at least one message") | 186 | try require(!messages.isEmpty, "messages", "must hold at least one message") |
| 188 | - try check(temperature, "temperature", "must be between 0 and 2") { (0 ... 2).contains($0) } | ||
| 189 | - try check(topP, "top_p", "must be above 0 and at most 1") { $0 > 0 && $0 <= 1 } | ||
| 190 | let limit = maxCompletionTokens ?? maxTokens | 187 | let limit = maxCompletionTokens ?? maxTokens |
| 191 | - let limitName = maxCompletionTokens == nil ? "max_tokens" : "max_completion_tokens" | 188 | + try checkSampling( |
| 192 | - try check(limit, limitName, "must be 1 or more") { $0 >= 1 } | 189 | + SamplingFields( |
| 193 | - try check(presencePenalty, "presence_penalty", "must be between -2 and 2") { abs($0) <= 2 } | 190 | + temperature: temperature, topP: topP, limit: limit, |
| 194 | - try check(frequencyPenalty, "frequency_penalty", "must be between -2 and 2") { | 191 | + limitName: maxCompletionTokens == nil ? "max_tokens" : "max_completion_tokens", |
| 195 | - abs($0) <= 2 | 192 | + presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, |
| 196 | - } | 193 | + stops: stops)) |
| 197 | try checkReasoningSwitches() | 194 | try checkReasoningSwitches() |
| 198 | let output = try outputPlan() | 195 | let output = try outputPlan() |
| 199 | let mapped = try messages.enumerated().map { try Self.message($1, at: $0) } | 196 | let mapped = try messages.enumerated().map { try Self.message($1, at: $0) } |
| @@ -298,17 +295,6 @@ extension ChatCompletionRequest { | |||
| 298 | return ToolCall(id: wire.id, name: wire.function.name, arguments: arguments) | 295 | return ToolCall(id: wire.id, name: wire.function.name, arguments: arguments) |
| 299 | } | 296 | } |
| 300 | 297 | ||
| 301 | - private func require(_ condition: Bool, _ param: String, _ message: String) throws { | ||
| 302 | - guard condition else { | ||
| 303 | - throw OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | ||
| 304 | - } | ||
| 305 | - } | ||
| 306 | - | ||
| 307 | - private func check<T>( | ||
| 308 | - _ value: T?, _ param: String, _ message: String, _ isValid: (T) -> Bool | ||
| 309 | - ) throws { | ||
| 310 | - if let value { try require(isValid(value), param, message) } | ||
| 311 | - } | ||
| 312 | } | 298 | } |
| 313 | 299 | ||
| 314 | extension OpenAIError { | 300 | extension OpenAIError { |
added
Sources/RazorbillServer/CompletionsRoute.swift +276 -0 | new file mode 100644 | ||
| @@ -0,0 +1,276 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import Logging | |
| 4 | +import RazorbillCore | |
| 5 | + | |
| 6 | +/// The body of `POST /v1/completions`, OpenAI's legacy text completion: the prompt is continued | |
| 7 | +/// as raw text, without chat template (ticket #44). | |
| 8 | +struct CompletionRequest: Decodable, Sendable, FieldChecking { | |
| 9 | + var model: String | |
| 10 | + var prompt: PromptField | |
| 11 | + var maxTokens: Int? | |
| 12 | + var temperature: Double? | |
| 13 | + var topP: Double? | |
| 14 | + var stop: StopField? | |
| 15 | + var seed: Int64? | |
| 16 | + var presencePenalty: Double? | |
| 17 | + var frequencyPenalty: Double? | |
| 18 | + var stream: Bool? | |
| 19 | + var streamOptions: StreamOptions? | |
| 20 | + /// Write the prompt before the completion. | |
| 21 | + var echo: Bool? | |
| 22 | + /// Fill-in-the-middle text after the completion: refused (no model-independent way to do it). | |
| 23 | + var suffix: String? | |
| 24 | + /// The legacy API's number of log-probabilities per token: refused above 0. | |
| 25 | + var logprobs: Int? | |
| 26 | + var choiceCount: Int? | |
| 27 | + var bestOf: Int? | |
| 28 | + | |
| 29 | + enum CodingKeys: String, CodingKey { | |
| 30 | + case model, prompt, temperature, stop, seed, stream, echo, suffix, logprobs | |
| 31 | + case maxTokens = "max_tokens" | |
| 32 | + case topP = "top_p" | |
| 33 | + case presencePenalty = "presence_penalty" | |
| 34 | + case frequencyPenalty = "frequency_penalty" | |
| 35 | + case streamOptions = "stream_options" | |
| 36 | + case choiceCount = "n" | |
| 37 | + case bestOf = "best_of" | |
| 38 | + } | |
| 39 | + | |
| 40 | + static func decode(_ data: Data) throws -> CompletionRequest { | |
| 41 | + do { | |
| 42 | + return try JSONDecoder().decode(CompletionRequest.self, from: data) | |
| 43 | + } catch let error as DecodingError { | |
| 44 | + throw OpenAIError.invalidBody(error) | |
| 45 | + } catch { | |
| 46 | + throw OpenAIError(.badRequest, message: "The body is not valid JSON.") | |
| 47 | + } | |
| 48 | + } | |
| 49 | + | |
| 50 | + func validated() throws -> CompletionPlan { | |
| 51 | + try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)") | |
| 52 | + try require((bestOf ?? 1) == 1, "best_of", "must be 1") | |
| 53 | + try require((logprobs ?? 0) == 0, "logprobs", "is not supported yet") | |
| 54 | + try require(suffix?.isEmpty ?? true, "suffix", "is not supported (no fill-in-the-middle)") | |
| 55 | + let stops = stop?.values ?? [] | |
| 56 | + try checkSampling( | |
| 57 | + SamplingFields( | |
| 58 | + temperature: temperature, topP: topP, limit: maxTokens, | |
| 59 | + presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, stops: stops)) | |
| 60 | + return CompletionPlan( | |
| 61 | + model: model, prompt: try prompt.single(), | |
| 62 | + client: GenerationOverrides( | |
| 63 | + temperature: temperature, topP: topP, maxTokens: maxTokens, thinking: false), | |
| 64 | + seed: seed.map { UInt64(bitPattern: $0) }, presencePenalty: presencePenalty, | |
| 65 | + frequencyPenalty: frequencyPenalty, stops: stops, stream: stream ?? false, | |
| 66 | + includeUsage: streamOptions?.includeUsage ?? false, echo: echo ?? false) | |
| 67 | + } | |
| 68 | +} | |
| 69 | + | |
| 70 | +/// `prompt`: a string, or a list holding one string. Several prompts (several choices) and token | |
| 71 | +/// arrays are refused. | |
| 72 | +enum PromptField: Decodable, Sendable { | |
| 73 | + case texts([String]) | |
| 74 | + case tokens | |
| 75 | + | |
| 76 | + init(from decoder: any Decoder) throws { | |
| 77 | + let container = try decoder.singleValueContainer() | |
| 78 | + if let text = try? container.decode(String.self) { | |
| 79 | + self = .texts([text]) | |
| 80 | + } else if let texts = try? container.decode([String].self) { | |
| 81 | + self = .texts(texts) | |
| 82 | + } else if EmbeddingInput.isTokenArray(container) { | |
| 83 | + self = .tokens | |
| 84 | + } else { | |
| 85 | + throw DecodingError.typeMismatch( | |
| 86 | + String.self, | |
| 87 | + .init( | |
| 88 | + codingPath: decoder.codingPath, | |
| 89 | + debugDescription: "a string or a list of strings")) | |
| 90 | + } | |
| 91 | + } | |
| 92 | + | |
| 93 | + func single() throws -> String { | |
| 94 | + guard case .texts(let texts) = self else { | |
| 95 | + throw OpenAIError( | |
| 96 | + .badRequest, message: "prompt token arrays are not supported yet; send text.", | |
| 97 | + param: "prompt") | |
| 98 | + } | |
| 99 | + guard texts.count == 1 else { | |
| 100 | + throw OpenAIError( | |
| 101 | + .badRequest, message: "prompt must hold one text (one choice per request).", | |
| 102 | + param: "prompt") | |
| 103 | + } | |
| 104 | + return texts[0] | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 108 | +/// A validated `/v1/completions` request. | |
| 109 | +struct CompletionPlan: Sendable { | |
| 110 | + var model: String | |
| 111 | + var prompt: String | |
| 112 | + var client: GenerationOverrides | |
| 113 | + var seed: UInt64? | |
| 114 | + var presencePenalty: Double? | |
| 115 | + var frequencyPenalty: Double? | |
| 116 | + var stops: [String] | |
| 117 | + var stream: Bool | |
| 118 | + var includeUsage: Bool | |
| 119 | + var echo: Bool | |
| 120 | + | |
| 121 | + /// The model's defaults, then the client's values, then its locks; never thinking. | |
| 122 | + func settings(for model: ResolvedModel) -> GenerationSettings { | |
| 123 | + var settings = model.generation(client: client) | |
| 124 | + settings.thinking = false | |
| 125 | + settings.seed = seed | |
| 126 | + settings.presencePenalty = presencePenalty | |
| 127 | + settings.frequencyPenalty = frequencyPenalty | |
| 128 | + return settings | |
| 129 | + } | |
| 130 | +} | |
| 131 | + | |
| 132 | +/// `text_completion`, whole or as one chunk of a stream (same shape, as OpenAI). | |
| 133 | +typealias TextCompletion = CompletionEnvelope<TextChoice> | |
| 134 | + | |
| 135 | +struct TextChoice: EnvelopeChoice { | |
| 136 | + static let object = "text_completion" | |
| 137 | + let text: String | |
| 138 | + let finishReason: FinishReason? | |
| 139 | + | |
| 140 | + enum CodingKeys: String, CodingKey { | |
| 141 | + case text, index, logprobs | |
| 142 | + case finishReason = "finish_reason" | |
| 143 | + } | |
| 144 | + | |
| 145 | + func encode(to encoder: any Encoder) throws { | |
| 146 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 147 | + try container.encode(text, forKey: .text) | |
| 148 | + try container.encode(0, forKey: .index) | |
| 149 | + try container.encodeNil(forKey: .logprobs) | |
| 150 | + try container.encode(finishReason, forKey: .finishReason) | |
| 151 | + } | |
| 152 | +} | |
| 153 | + | |
| 154 | +/// `POST /v1/completions` (ticket #44). Held like a chat answer; cancelled if the client leaves. | |
| 155 | +struct CompletionsRoute { | |
| 156 | + let models: ModelManager | |
| 157 | + var streamKeepAlive: Duration = .seconds(5) | |
| 158 | + | |
| 159 | + func add(to router: Router<ServerContext>) { | |
| 160 | + router.post("/v1/completions") { request, context in | |
| 161 | + var response = try await request.body.consumeWithCancellationOnInboundClose { body in | |
| 162 | + do { | |
| 163 | + return try await answer(body, context: context) | |
| 164 | + } catch is CancellationError { | |
| 165 | + throw CancellationError() | |
| 166 | + } catch { | |
| 167 | + return try OpenAIError.converting(error, for: request) | |
| 168 | + .response(from: request, context: context) | |
| 169 | + } | |
| 170 | + } | |
| 171 | + response.headers[.connection] = "close" | |
| 172 | + return response | |
| 173 | + } | |
| 174 | + } | |
| 175 | + | |
| 176 | + func answer(_ body: RequestBody, context: ServerContext) async throws -> Response { | |
| 177 | + let buffer = try await body.collect(upTo: context.maxUploadSize) | |
| 178 | + let plan = try CompletionRequest.decode(Data(buffer: buffer)).validated() | |
| 179 | + guard plan.stream else { | |
| 180 | + let completion = try await complete(plan) | |
| 181 | + context.usage.record( | |
| 182 | + model: plan.model, promptTokens: completion.usage?.promptTokens ?? 0, | |
| 183 | + completionTokens: completion.usage?.completionTokens ?? 0) | |
| 184 | + return try jsonResponse(completion) | |
| 185 | + } | |
| 186 | + let lease = try await models.acquire(plan.model) | |
| 187 | + let pieces: AsyncThrowingStream<CompletionPiece, Error> | |
| 188 | + do { | |
| 189 | + pieces = try await Self.generate(plan, with: lease) | |
| 190 | + } catch { | |
| 191 | + await lease.release() | |
| 192 | + throw error | |
| 193 | + } | |
| 194 | + context.usage.record(model: plan.model) | |
| 195 | + let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger) | |
| 196 | + return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive) | |
| 197 | + } | |
| 198 | + | |
| 199 | + func complete(_ plan: CompletionPlan) async throws -> TextCompletion { | |
| 200 | + try await models.withModel(plan.model) { lease in | |
| 201 | + var text = plan.echo ? plan.prompt : "" | |
| 202 | + var ending = (FinishReason.stop, Usage(promptTokens: 0, completionTokens: 0)) | |
| 203 | + for try await piece in try await Self.generate(plan, with: lease) { | |
| 204 | + switch piece { | |
| 205 | + case .content(let content): text += content | |
| 206 | + case .finished(let reason, let usage): ending = (reason, usage) | |
| 207 | + default: break | |
| 208 | + } | |
| 209 | + } | |
| 210 | + return TextCompletion( | |
| 211 | + id: Self.newID(), created: Int(Date().timeIntervalSince1970), model: plan.model, | |
| 212 | + choices: [TextChoice(text: text, finishReason: ending.0)], usage: ending.1, | |
| 213 | + includesUsage: true) | |
| 214 | + } | |
| 215 | + } | |
| 216 | + | |
| 217 | + static func generate( | |
| 218 | + _ plan: CompletionPlan, with lease: ModelLease | |
| 219 | + ) async throws -> AsyncThrowingStream<CompletionPiece, Error> { | |
| 220 | + let events = try await lease.engine.complete( | |
| 221 | + plan.prompt, generation: plan.settings(for: lease.model)) | |
| 222 | + return CompletionStream.pieces(from: events, stops: plan.stops) | |
| 223 | + } | |
| 224 | + | |
| 225 | + /// The stream's chunks: the prompt first with `echo`, the text pieces, a last chunk with | |
| 226 | + /// `finish_reason`, then the usage chunk if asked. The lease is released at the end. | |
| 227 | + static func chunks( | |
| 228 | + _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease, | |
| 229 | + plan: CompletionPlan, logger: Logger | |
| 230 | + ) -> AsyncThrowingStream<TextCompletion, Error> { | |
| 231 | + let id = newID() | |
| 232 | + let created = Int(Date().timeIntervalSince1970) | |
| 233 | + func chunk(_ text: String, _ reason: FinishReason? = nil) -> TextCompletion { | |
| 234 | + TextCompletion( | |
| 235 | + id: id, created: created, model: plan.model, | |
| 236 | + choices: [TextChoice(text: text, finishReason: reason)], usage: nil, | |
| 237 | + includesUsage: plan.includeUsage) | |
| 238 | + } | |
| 239 | + return AsyncThrowingStream { continuation in | |
| 240 | + let task = Task { | |
| 241 | + var outcome = "cancelled" | |
| 242 | + if plan.echo { continuation.yield(chunk(plan.prompt)) } | |
| 243 | + do { | |
| 244 | + for try await piece in pieces { | |
| 245 | + switch piece { | |
| 246 | + case .content(let text): continuation.yield(chunk(text)) | |
| 247 | + case .finished(let reason, let usage): | |
| 248 | + outcome = | |
| 249 | + "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | |
| 250 | + continuation.yield(chunk("", reason)) | |
| 251 | + if plan.includeUsage { | |
| 252 | + continuation.yield( | |
| 253 | + TextCompletion( | |
| 254 | + id: id, created: created, model: plan.model, choices: [], | |
| 255 | + usage: usage, includesUsage: true)) | |
| 256 | + } | |
| 257 | + default: break | |
| 258 | + } | |
| 259 | + } | |
| 260 | + continuation.finish() | |
| 261 | + } catch { | |
| 262 | + if !(error is CancellationError) { outcome = "failed: \(error)" } | |
| 263 | + continuation.finish(throwing: error) | |
| 264 | + } | |
| 265 | + await lease.release() | |
| 266 | + logger.info("stream \(id) model=\(plan.model) \(outcome)") | |
| 267 | + } | |
| 268 | + continuation.onTermination = { _ in task.cancel() } | |
| 269 | + } | |
| 270 | + } | |
| 271 | + | |
| 272 | + /// `cmpl-` followed by 24 random hexadecimal digits. | |
| 273 | + static func newID() -> String { | |
| 274 | + "cmpl-" + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased().prefix(24) | |
| 275 | + } | |
| 276 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,276 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import Logging | ||
| 4 | +import RazorbillCore | ||
| 5 | + | ||
| 6 | +/// The body of `POST /v1/completions`, OpenAI's legacy text completion: the prompt is continued | ||
| 7 | +/// as raw text, without chat template (ticket #44). | ||
| 8 | +struct CompletionRequest: Decodable, Sendable, FieldChecking { | ||
| 9 | + var model: String | ||
| 10 | + var prompt: PromptField | ||
| 11 | + var maxTokens: Int? | ||
| 12 | + var temperature: Double? | ||
| 13 | + var topP: Double? | ||
| 14 | + var stop: StopField? | ||
| 15 | + var seed: Int64? | ||
| 16 | + var presencePenalty: Double? | ||
| 17 | + var frequencyPenalty: Double? | ||
| 18 | + var stream: Bool? | ||
| 19 | + var streamOptions: StreamOptions? | ||
| 20 | + /// Write the prompt before the completion. | ||
| 21 | + var echo: Bool? | ||
| 22 | + /// Fill-in-the-middle text after the completion: refused (no model-independent way to do it). | ||
| 23 | + var suffix: String? | ||
| 24 | + /// The legacy API's number of log-probabilities per token: refused above 0. | ||
| 25 | + var logprobs: Int? | ||
| 26 | + var choiceCount: Int? | ||
| 27 | + var bestOf: Int? | ||
| 28 | + | ||
| 29 | + enum CodingKeys: String, CodingKey { | ||
| 30 | + case model, prompt, temperature, stop, seed, stream, echo, suffix, logprobs | ||
| 31 | + case maxTokens = "max_tokens" | ||
| 32 | + case topP = "top_p" | ||
| 33 | + case presencePenalty = "presence_penalty" | ||
| 34 | + case frequencyPenalty = "frequency_penalty" | ||
| 35 | + case streamOptions = "stream_options" | ||
| 36 | + case choiceCount = "n" | ||
| 37 | + case bestOf = "best_of" | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + static func decode(_ data: Data) throws -> CompletionRequest { | ||
| 41 | + do { | ||
| 42 | + return try JSONDecoder().decode(CompletionRequest.self, from: data) | ||
| 43 | + } catch let error as DecodingError { | ||
| 44 | + throw OpenAIError.invalidBody(error) | ||
| 45 | + } catch { | ||
| 46 | + throw OpenAIError(.badRequest, message: "The body is not valid JSON.") | ||
| 47 | + } | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + func validated() throws -> CompletionPlan { | ||
| 51 | + try require((choiceCount ?? 1) == 1, "n", "must be 1 (one choice per request)") | ||
| 52 | + try require((bestOf ?? 1) == 1, "best_of", "must be 1") | ||
| 53 | + try require((logprobs ?? 0) == 0, "logprobs", "is not supported yet") | ||
| 54 | + try require(suffix?.isEmpty ?? true, "suffix", "is not supported (no fill-in-the-middle)") | ||
| 55 | + let stops = stop?.values ?? [] | ||
| 56 | + try checkSampling( | ||
| 57 | + SamplingFields( | ||
| 58 | + temperature: temperature, topP: topP, limit: maxTokens, | ||
| 59 | + presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, stops: stops)) | ||
| 60 | + return CompletionPlan( | ||
| 61 | + model: model, prompt: try prompt.single(), | ||
| 62 | + client: GenerationOverrides( | ||
| 63 | + temperature: temperature, topP: topP, maxTokens: maxTokens, thinking: false), | ||
| 64 | + seed: seed.map { UInt64(bitPattern: $0) }, presencePenalty: presencePenalty, | ||
| 65 | + frequencyPenalty: frequencyPenalty, stops: stops, stream: stream ?? false, | ||
| 66 | + includeUsage: streamOptions?.includeUsage ?? false, echo: echo ?? false) | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// `prompt`: a string, or a list holding one string. Several prompts (several choices) and token | ||
| 71 | +/// arrays are refused. | ||
| 72 | +enum PromptField: Decodable, Sendable { | ||
| 73 | + case texts([String]) | ||
| 74 | + case tokens | ||
| 75 | + | ||
| 76 | + init(from decoder: any Decoder) throws { | ||
| 77 | + let container = try decoder.singleValueContainer() | ||
| 78 | + if let text = try? container.decode(String.self) { | ||
| 79 | + self = .texts([text]) | ||
| 80 | + } else if let texts = try? container.decode([String].self) { | ||
| 81 | + self = .texts(texts) | ||
| 82 | + } else if EmbeddingInput.isTokenArray(container) { | ||
| 83 | + self = .tokens | ||
| 84 | + } else { | ||
| 85 | + throw DecodingError.typeMismatch( | ||
| 86 | + String.self, | ||
| 87 | + .init( | ||
| 88 | + codingPath: decoder.codingPath, | ||
| 89 | + debugDescription: "a string or a list of strings")) | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + func single() throws -> String { | ||
| 94 | + guard case .texts(let texts) = self else { | ||
| 95 | + throw OpenAIError( | ||
| 96 | + .badRequest, message: "prompt token arrays are not supported yet; send text.", | ||
| 97 | + param: "prompt") | ||
| 98 | + } | ||
| 99 | + guard texts.count == 1 else { | ||
| 100 | + throw OpenAIError( | ||
| 101 | + .badRequest, message: "prompt must hold one text (one choice per request).", | ||
| 102 | + param: "prompt") | ||
| 103 | + } | ||
| 104 | + return texts[0] | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// A validated `/v1/completions` request. | ||
| 109 | +struct CompletionPlan: Sendable { | ||
| 110 | + var model: String | ||
| 111 | + var prompt: String | ||
| 112 | + var client: GenerationOverrides | ||
| 113 | + var seed: UInt64? | ||
| 114 | + var presencePenalty: Double? | ||
| 115 | + var frequencyPenalty: Double? | ||
| 116 | + var stops: [String] | ||
| 117 | + var stream: Bool | ||
| 118 | + var includeUsage: Bool | ||
| 119 | + var echo: Bool | ||
| 120 | + | ||
| 121 | + /// The model's defaults, then the client's values, then its locks; never thinking. | ||
| 122 | + func settings(for model: ResolvedModel) -> GenerationSettings { | ||
| 123 | + var settings = model.generation(client: client) | ||
| 124 | + settings.thinking = false | ||
| 125 | + settings.seed = seed | ||
| 126 | + settings.presencePenalty = presencePenalty | ||
| 127 | + settings.frequencyPenalty = frequencyPenalty | ||
| 128 | + return settings | ||
| 129 | + } | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +/// `text_completion`, whole or as one chunk of a stream (same shape, as OpenAI). | ||
| 133 | +typealias TextCompletion = CompletionEnvelope<TextChoice> | ||
| 134 | + | ||
| 135 | +struct TextChoice: EnvelopeChoice { | ||
| 136 | + static let object = "text_completion" | ||
| 137 | + let text: String | ||
| 138 | + let finishReason: FinishReason? | ||
| 139 | + | ||
| 140 | + enum CodingKeys: String, CodingKey { | ||
| 141 | + case text, index, logprobs | ||
| 142 | + case finishReason = "finish_reason" | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + func encode(to encoder: any Encoder) throws { | ||
| 146 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 147 | + try container.encode(text, forKey: .text) | ||
| 148 | + try container.encode(0, forKey: .index) | ||
| 149 | + try container.encodeNil(forKey: .logprobs) | ||
| 150 | + try container.encode(finishReason, forKey: .finishReason) | ||
| 151 | + } | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +/// `POST /v1/completions` (ticket #44). Held like a chat answer; cancelled if the client leaves. | ||
| 155 | +struct CompletionsRoute { | ||
| 156 | + let models: ModelManager | ||
| 157 | + var streamKeepAlive: Duration = .seconds(5) | ||
| 158 | + | ||
| 159 | + func add(to router: Router<ServerContext>) { | ||
| 160 | + router.post("/v1/completions") { request, context in | ||
| 161 | + var response = try await request.body.consumeWithCancellationOnInboundClose { body in | ||
| 162 | + do { | ||
| 163 | + return try await answer(body, context: context) | ||
| 164 | + } catch is CancellationError { | ||
| 165 | + throw CancellationError() | ||
| 166 | + } catch { | ||
| 167 | + return try OpenAIError.converting(error, for: request) | ||
| 168 | + .response(from: request, context: context) | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + response.headers[.connection] = "close" | ||
| 172 | + return response | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | + | ||
| 176 | + func answer(_ body: RequestBody, context: ServerContext) async throws -> Response { | ||
| 177 | + let buffer = try await body.collect(upTo: context.maxUploadSize) | ||
| 178 | + let plan = try CompletionRequest.decode(Data(buffer: buffer)).validated() | ||
| 179 | + guard plan.stream else { | ||
| 180 | + let completion = try await complete(plan) | ||
| 181 | + context.usage.record( | ||
| 182 | + model: plan.model, promptTokens: completion.usage?.promptTokens ?? 0, | ||
| 183 | + completionTokens: completion.usage?.completionTokens ?? 0) | ||
| 184 | + return try jsonResponse(completion) | ||
| 185 | + } | ||
| 186 | + let lease = try await models.acquire(plan.model) | ||
| 187 | + let pieces: AsyncThrowingStream<CompletionPiece, Error> | ||
| 188 | + do { | ||
| 189 | + pieces = try await Self.generate(plan, with: lease) | ||
| 190 | + } catch { | ||
| 191 | + await lease.release() | ||
| 192 | + throw error | ||
| 193 | + } | ||
| 194 | + context.usage.record(model: plan.model) | ||
| 195 | + let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger) | ||
| 196 | + return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive) | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + func complete(_ plan: CompletionPlan) async throws -> TextCompletion { | ||
| 200 | + try await models.withModel(plan.model) { lease in | ||
| 201 | + var text = plan.echo ? plan.prompt : "" | ||
| 202 | + var ending = (FinishReason.stop, Usage(promptTokens: 0, completionTokens: 0)) | ||
| 203 | + for try await piece in try await Self.generate(plan, with: lease) { | ||
| 204 | + switch piece { | ||
| 205 | + case .content(let content): text += content | ||
| 206 | + case .finished(let reason, let usage): ending = (reason, usage) | ||
| 207 | + default: break | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | + return TextCompletion( | ||
| 211 | + id: Self.newID(), created: Int(Date().timeIntervalSince1970), model: plan.model, | ||
| 212 | + choices: [TextChoice(text: text, finishReason: ending.0)], usage: ending.1, | ||
| 213 | + includesUsage: true) | ||
| 214 | + } | ||
| 215 | + } | ||
| 216 | + | ||
| 217 | + static func generate( | ||
| 218 | + _ plan: CompletionPlan, with lease: ModelLease | ||
| 219 | + ) async throws -> AsyncThrowingStream<CompletionPiece, Error> { | ||
| 220 | + let events = try await lease.engine.complete( | ||
| 221 | + plan.prompt, generation: plan.settings(for: lease.model)) | ||
| 222 | + return CompletionStream.pieces(from: events, stops: plan.stops) | ||
| 223 | + } | ||
| 224 | + | ||
| 225 | + /// The stream's chunks: the prompt first with `echo`, the text pieces, a last chunk with | ||
| 226 | + /// `finish_reason`, then the usage chunk if asked. The lease is released at the end. | ||
| 227 | + static func chunks( | ||
| 228 | + _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease, | ||
| 229 | + plan: CompletionPlan, logger: Logger | ||
| 230 | + ) -> AsyncThrowingStream<TextCompletion, Error> { | ||
| 231 | + let id = newID() | ||
| 232 | + let created = Int(Date().timeIntervalSince1970) | ||
| 233 | + func chunk(_ text: String, _ reason: FinishReason? = nil) -> TextCompletion { | ||
| 234 | + TextCompletion( | ||
| 235 | + id: id, created: created, model: plan.model, | ||
| 236 | + choices: [TextChoice(text: text, finishReason: reason)], usage: nil, | ||
| 237 | + includesUsage: plan.includeUsage) | ||
| 238 | + } | ||
| 239 | + return AsyncThrowingStream { continuation in | ||
| 240 | + let task = Task { | ||
| 241 | + var outcome = "cancelled" | ||
| 242 | + if plan.echo { continuation.yield(chunk(plan.prompt)) } | ||
| 243 | + do { | ||
| 244 | + for try await piece in pieces { | ||
| 245 | + switch piece { | ||
| 246 | + case .content(let text): continuation.yield(chunk(text)) | ||
| 247 | + case .finished(let reason, let usage): | ||
| 248 | + outcome = | ||
| 249 | + "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | ||
| 250 | + continuation.yield(chunk("", reason)) | ||
| 251 | + if plan.includeUsage { | ||
| 252 | + continuation.yield( | ||
| 253 | + TextCompletion( | ||
| 254 | + id: id, created: created, model: plan.model, choices: [], | ||
| 255 | + usage: usage, includesUsage: true)) | ||
| 256 | + } | ||
| 257 | + default: break | ||
| 258 | + } | ||
| 259 | + } | ||
| 260 | + continuation.finish() | ||
| 261 | + } catch { | ||
| 262 | + if !(error is CancellationError) { outcome = "failed: \(error)" } | ||
| 263 | + continuation.finish(throwing: error) | ||
| 264 | + } | ||
| 265 | + await lease.release() | ||
| 266 | + logger.info("stream \(id) model=\(plan.model) \(outcome)") | ||
| 267 | + } | ||
| 268 | + continuation.onTermination = { _ in task.cancel() } | ||
| 269 | + } | ||
| 270 | + } | ||
| 271 | + | ||
| 272 | + /// `cmpl-` followed by 24 random hexadecimal digits. | ||
| 273 | + static func newID() -> String { | ||
| 274 | + "cmpl-" + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased().prefix(24) | ||
| 275 | + } | ||
| 276 | +} | ||
added
Sources/RazorbillServer/FieldChecking.swift +41 -0 | new file mode 100644 | ||
| @@ -0,0 +1,41 @@ | ||
| 1 | +import RazorbillCore | |
| 2 | + | |
| 3 | +/// A request body whose fields are checked one by one: the first problem is a 400 naming it. | |
| 4 | +protocol FieldChecking {} | |
| 5 | + | |
| 6 | +/// The sampling fields shared by `/v1/chat/completions` and `/v1/completions`. | |
| 7 | +struct SamplingFields { | |
| 8 | + var temperature: Double? | |
| 9 | + var topP: Double? | |
| 10 | + var limit: Int? | |
| 11 | + var limitName = "max_tokens" | |
| 12 | + var presencePenalty: Double? | |
| 13 | + var frequencyPenalty: Double? | |
| 14 | + var stops: [String] = [] | |
| 15 | +} | |
| 16 | + | |
| 17 | +extension FieldChecking { | |
| 18 | + func require(_ condition: Bool, _ param: String, _ message: String) throws { | |
| 19 | + guard condition else { | |
| 20 | + throw OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | |
| 21 | + } | |
| 22 | + } | |
| 23 | + | |
| 24 | + func check<T>( | |
| 25 | + _ value: T?, _ param: String, _ message: String, _ isValid: (T) -> Bool | |
| 26 | + ) throws { | |
| 27 | + if let value { try require(isValid(value), param, message) } | |
| 28 | + } | |
| 29 | + | |
| 30 | + func checkSampling(_ fields: SamplingFields) throws { | |
| 31 | + try require(fields.stops.count <= 4, "stop", "can hold at most 4 sequences") | |
| 32 | + try check(fields.temperature, "temperature", "must be between 0 and 2") { | |
| 33 | + (0 ... 2).contains($0) | |
| 34 | + } | |
| 35 | + try check(fields.topP, "top_p", "must be above 0 and at most 1") { $0 > 0 && $0 <= 1 } | |
| 36 | + try check(fields.limit, fields.limitName, "must be 1 or more") { $0 >= 1 } | |
| 37 | + let penalty = "must be between -2 and 2" | |
| 38 | + try check(fields.presencePenalty, "presence_penalty", penalty) { abs($0) <= 2 } | |
| 39 | + try check(fields.frequencyPenalty, "frequency_penalty", penalty) { abs($0) <= 2 } | |
| 40 | + } | |
| 41 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,41 @@ | |||
| 1 | +import RazorbillCore | ||
| 2 | + | ||
| 3 | +/// A request body whose fields are checked one by one: the first problem is a 400 naming it. | ||
| 4 | +protocol FieldChecking {} | ||
| 5 | + | ||
| 6 | +/// The sampling fields shared by `/v1/chat/completions` and `/v1/completions`. | ||
| 7 | +struct SamplingFields { | ||
| 8 | + var temperature: Double? | ||
| 9 | + var topP: Double? | ||
| 10 | + var limit: Int? | ||
| 11 | + var limitName = "max_tokens" | ||
| 12 | + var presencePenalty: Double? | ||
| 13 | + var frequencyPenalty: Double? | ||
| 14 | + var stops: [String] = [] | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +extension FieldChecking { | ||
| 18 | + func require(_ condition: Bool, _ param: String, _ message: String) throws { | ||
| 19 | + guard condition else { | ||
| 20 | + throw OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | ||
| 21 | + } | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + func check<T>( | ||
| 25 | + _ value: T?, _ param: String, _ message: String, _ isValid: (T) -> Bool | ||
| 26 | + ) throws { | ||
| 27 | + if let value { try require(isValid(value), param, message) } | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + func checkSampling(_ fields: SamplingFields) throws { | ||
| 31 | + try require(fields.stops.count <= 4, "stop", "can hold at most 4 sequences") | ||
| 32 | + try check(fields.temperature, "temperature", "must be between 0 and 2") { | ||
| 33 | + (0 ... 2).contains($0) | ||
| 34 | + } | ||
| 35 | + try check(fields.topP, "top_p", "must be above 0 and at most 1") { $0 > 0 && $0 <= 1 } | ||
| 36 | + try check(fields.limit, fields.limitName, "must be 1 or more") { $0 >= 1 } | ||
| 37 | + let penalty = "must be between -2 and 2" | ||
| 38 | + try check(fields.presencePenalty, "presence_penalty", penalty) { abs($0) <= 2 } | ||
| 39 | + try check(fields.frequencyPenalty, "frequency_penalty", penalty) { abs($0) <= 2 } | ||
| 40 | + } | ||
| 41 | +} | ||
modified
Sources/RazorbillServer/RazorbillServer.swift +1 -0 | @@ -42,6 +42,7 @@ public enum RazorbillServer { | ||
| 42 | 42 | addHealthRoute(to: router) |
| 43 | 43 | ModelRoutes(models: models).add(to: router) |
| 44 | 44 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 45 | + CompletionsRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) | |
| 45 | 46 | EmbeddingsRoute(models: models).add(to: router) |
| 46 | 47 | return router |
| 47 | 48 | } |
| @@ -42,6 +42,7 @@ public enum RazorbillServer { | |||
| 42 | addHealthRoute(to: router) | 42 | addHealthRoute(to: router) |
| 43 | ModelRoutes(models: models).add(to: router) | 43 | ModelRoutes(models: models).add(to: router) |
| 44 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) | 44 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 45 | + CompletionsRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) | ||
| 45 | EmbeddingsRoute(models: models).add(to: router) | 46 | EmbeddingsRoute(models: models).add(to: router) |
| 46 | return router | 47 | return router |
| 47 | } | 48 | } |
added
Tests/Compatibility/test_completions.py +59 -0 | new file mode 100644 | ||
| @@ -0,0 +1,59 @@ | ||
| 1 | +"""Legacy `/v1/completions` through the openai SDK (ticket #44).""" | |
| 2 | + | |
| 3 | +import openai | |
| 4 | +import pytest | |
| 5 | + | |
| 6 | + | |
| 7 | +def test_completion_shape(client): | |
| 8 | + answer = client.completions.create(model="chat", prompt="The capital of France is", max_tokens=8) | |
| 9 | + choice = answer.choices[0] | |
| 10 | + assert answer.object == "text_completion" | |
| 11 | + assert answer.id.startswith("cmpl-") | |
| 12 | + assert choice.index == 0 | |
| 13 | + assert choice.text | |
| 14 | + assert choice.finish_reason in ("stop", "length") | |
| 15 | + assert answer.usage.completion_tokens > 0 | |
| 16 | + | |
| 17 | + | |
| 18 | +def test_streaming_with_echo_and_usage(client): | |
| 19 | + prompt = "One, two, three," | |
| 20 | + stream = client.completions.create( | |
| 21 | + model="chat", prompt=prompt, max_tokens=8, echo=True, stream=True, | |
| 22 | + stream_options={"include_usage": True}, | |
| 23 | + ) | |
| 24 | + chunks = list(stream) | |
| 25 | + text = "".join(chunk.choices[0].text for chunk in chunks if chunk.choices) | |
| 26 | + assert text.startswith(prompt) | |
| 27 | + assert chunks[-1].choices == [] | |
| 28 | + assert chunks[-1].usage.completion_tokens > 0 | |
| 29 | + | |
| 30 | + | |
| 31 | +@pytest.mark.parametrize(("field", "value"), [("suffix", "}"), ("n", 2), ("logprobs", 3)]) | |
| 32 | +def test_unsupported_fields_are_400(client, field, value): | |
| 33 | + with pytest.raises(openai.BadRequestError) as error: | |
| 34 | + client.completions.create(model="chat", prompt="x", **{field: value}) | |
| 35 | + assert error.value.body["param"] == field | |
| 36 | + | |
| 37 | + | |
| 38 | +def test_embedding_model_cannot_complete(client): | |
| 39 | + with pytest.raises(openai.BadRequestError): | |
| 40 | + client.completions.create(model="embed", prompt="x") | |
| 41 | + | |
| 42 | + | |
| 43 | +@pytest.mark.real_model | |
| 44 | +def test_raw_prompt_is_continued(client): | |
| 45 | + answer = client.completions.create( | |
| 46 | + model="chat", prompt="The capital of France is", max_tokens=8, temperature=0 | |
| 47 | + ) | |
| 48 | + assert "Paris" in answer.choices[0].text | |
| 49 | + | |
| 50 | + | |
| 51 | +@pytest.mark.real_model | |
| 52 | +def test_stop_sequence(client): | |
| 53 | + answer = client.completions.create( | |
| 54 | + model="chat", prompt="1, 2, 3, 4,", max_tokens=30, temperature=0, stop=["7"] | |
| 55 | + ) | |
| 56 | + choice = answer.choices[0] | |
| 57 | + assert "7" not in choice.text | |
| 58 | + assert "6" in choice.text | |
| 59 | + assert choice.finish_reason == "stop" | |
| new file mode 100644 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | +"""Legacy `/v1/completions` through the openai SDK (ticket #44).""" | ||
| 2 | + | ||
| 3 | +import openai | ||
| 4 | +import pytest | ||
| 5 | + | ||
| 6 | + | ||
| 7 | +def test_completion_shape(client): | ||
| 8 | + answer = client.completions.create(model="chat", prompt="The capital of France is", max_tokens=8) | ||
| 9 | + choice = answer.choices[0] | ||
| 10 | + assert answer.object == "text_completion" | ||
| 11 | + assert answer.id.startswith("cmpl-") | ||
| 12 | + assert choice.index == 0 | ||
| 13 | + assert choice.text | ||
| 14 | + assert choice.finish_reason in ("stop", "length") | ||
| 15 | + assert answer.usage.completion_tokens > 0 | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def test_streaming_with_echo_and_usage(client): | ||
| 19 | + prompt = "One, two, three," | ||
| 20 | + stream = client.completions.create( | ||
| 21 | + model="chat", prompt=prompt, max_tokens=8, echo=True, stream=True, | ||
| 22 | + stream_options={"include_usage": True}, | ||
| 23 | + ) | ||
| 24 | + chunks = list(stream) | ||
| 25 | + text = "".join(chunk.choices[0].text for chunk in chunks if chunk.choices) | ||
| 26 | + assert text.startswith(prompt) | ||
| 27 | + assert chunks[-1].choices == [] | ||
| 28 | + assert chunks[-1].usage.completion_tokens > 0 | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +@pytest.mark.parametrize(("field", "value"), [("suffix", "}"), ("n", 2), ("logprobs", 3)]) | ||
| 32 | +def test_unsupported_fields_are_400(client, field, value): | ||
| 33 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 34 | + client.completions.create(model="chat", prompt="x", **{field: value}) | ||
| 35 | + assert error.value.body["param"] == field | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def test_embedding_model_cannot_complete(client): | ||
| 39 | + with pytest.raises(openai.BadRequestError): | ||
| 40 | + client.completions.create(model="embed", prompt="x") | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +@pytest.mark.real_model | ||
| 44 | +def test_raw_prompt_is_continued(client): | ||
| 45 | + answer = client.completions.create( | ||
| 46 | + model="chat", prompt="The capital of France is", max_tokens=8, temperature=0 | ||
| 47 | + ) | ||
| 48 | + assert "Paris" in answer.choices[0].text | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +@pytest.mark.real_model | ||
| 52 | +def test_stop_sequence(client): | ||
| 53 | + answer = client.completions.create( | ||
| 54 | + model="chat", prompt="1, 2, 3, 4,", max_tokens=30, temperature=0, stop=["7"] | ||
| 55 | + ) | ||
| 56 | + choice = answer.choices[0] | ||
| 57 | + assert "7" not in choice.text | ||
| 58 | + assert "6" in choice.text | ||
| 59 | + assert choice.finish_reason == "stop" | ||
modified
Tests/RazorbillMLXTests/ChatSmokeTests.swift +12 -0 | @@ -133,5 +133,17 @@ struct ChatSmokeTests { | ||
| 133 | 133 | #expect(!content.contains("5") && !content.contains("6")) |
| 134 | 134 | #expect(content.contains("4")) |
| 135 | 135 | } |
| 136 | + | |
| 137 | + @Test func rawCompletionContinuesThePrompt() async throws { | |
| 138 | + let body = | |
| 139 | + #"{"model":"\#(smokeModel)","prompt":"The capital of France is","max_tokens":8,"# | |
| 140 | + + #""temperature":0,"echo":true}"# | |
| 141 | + let plan = try CompletionRequest.decode(Data(body.utf8)).validated() | |
| 142 | + let completion = try await CompletionsRoute(models: models).complete(plan) | |
| 143 | + let text = try #require(completion.choices.first?.text) | |
| 144 | + #expect(text.hasPrefix("The capital of France is")) | |
| 145 | + #expect(text.contains("Paris"), "\(text)") | |
| 146 | + #expect((completion.usage?.promptTokens ?? 0) >= 5) | |
| 147 | + } | |
| 136 | 148 | } |
| 137 | 149 | #endif |
| @@ -133,5 +133,17 @@ struct ChatSmokeTests { | |||
| 133 | #expect(!content.contains("5") && !content.contains("6")) | 133 | #expect(!content.contains("5") && !content.contains("6")) |
| 134 | #expect(content.contains("4")) | 134 | #expect(content.contains("4")) |
| 135 | } | 135 | } |
| 136 | + | ||
| 137 | + @Test func rawCompletionContinuesThePrompt() async throws { | ||
| 138 | + let body = | ||
| 139 | + #"{"model":"\#(smokeModel)","prompt":"The capital of France is","max_tokens":8,"# | ||
| 140 | + + #""temperature":0,"echo":true}"# | ||
| 141 | + let plan = try CompletionRequest.decode(Data(body.utf8)).validated() | ||
| 142 | + let completion = try await CompletionsRoute(models: models).complete(plan) | ||
| 143 | + let text = try #require(completion.choices.first?.text) | ||
| 144 | + #expect(text.hasPrefix("The capital of France is")) | ||
| 145 | + #expect(text.contains("Paris"), "\(text)") | ||
| 146 | + #expect((completion.usage?.promptTokens ?? 0) >= 5) | ||
| 147 | + } | ||
| 136 | } | 148 | } |
| 137 | #endif | 149 | #endif |
added
Tests/RazorbillServerTests/CompletionsTests.swift +121 -0 | new file mode 100644 | ||
| @@ -0,0 +1,121 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import HummingbirdTesting | |
| 4 | +import RazorbillCore | |
| 5 | +import Testing | |
| 6 | + | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +/// POSTs `json` to `/v1/completions`. | |
| 10 | +func postCompletion(_ client: any TestClientProtocol, _ json: String) async throws -> TestResponse { | |
| 11 | + try await client.execute( | |
| 12 | + uri: "/v1/completions", method: .post, headers: [.contentType: "application/json"], | |
| 13 | + body: ByteBuffer(string: json)) | |
| 14 | +} | |
| 15 | + | |
| 16 | +/// `choices[0].text` of a `text_completion` (whole or chunk). | |
| 17 | +func choiceText(_ body: [String: Any]) -> String? { | |
| 18 | + ((body["choices"] as? [[String: Any]])?.first)?["text"] as? String | |
| 19 | +} | |
| 20 | + | |
| 21 | +@Suite struct CompletionsTests { | |
| 22 | + @Test func answersInOpenAIShape() async throws { | |
| 23 | + let engines = TestEngines() | |
| 24 | + try await withLiveServer(engines: engines) { client in | |
| 25 | + let response = try await postCompletion( | |
| 26 | + client, #"{"model":"org/m","prompt":"def add(a, b):","max_tokens":7}"#) | |
| 27 | + #expect(response.status == .ok) | |
| 28 | + let body = try json(response) | |
| 29 | + #expect(body["object"] as? String == "text_completion") | |
| 30 | + #expect((body["id"] as? String)?.hasPrefix("cmpl-") == true) | |
| 31 | + #expect(choiceText(body) == "echo: def add(a, b):") | |
| 32 | + let choice = try #require((body["choices"] as? [[String: Any]])?.first) | |
| 33 | + #expect(choice["finish_reason"] as? String == "stop" && choice["index"] as? Int == 0) | |
| 34 | + #expect(choice.keys.contains("logprobs")) | |
| 35 | + #expect((body["usage"] as? [String: Int])?["total_tokens"] == 2) | |
| 36 | + } | |
| 37 | + // The raw prompt reaches the engine, with the client's limit and no thinking. | |
| 38 | + #expect(engines.events.contains("complete 7 thinking=false")) | |
| 39 | + #expect(engines.fake.receivedMessages.last == [.user("def add(a, b):")]) | |
| 40 | + } | |
| 41 | + | |
| 42 | + @Test func echoAndStopSequences() async throws { | |
| 43 | + let engines = TestEngines(script: [[.text("one, two"), .text(", three")]]) | |
| 44 | + try await withLiveServer(engines: engines) { client in | |
| 45 | + let body = try json( | |
| 46 | + try await postCompletion( | |
| 47 | + client, #"{"model":"org/m","prompt":["Count: "],"echo":true,"stop":", t"}"#)) | |
| 48 | + #expect(choiceText(body) == "Count: one") | |
| 49 | + } | |
| 50 | + } | |
| 51 | + | |
| 52 | + @Test func streamsTextChunksThenUsage() async throws { | |
| 53 | + let stats = GenerationStats(promptTokens: 3, generatedTokens: 2, tokensPerSecond: 1) | |
| 54 | + let engines = TestEngines(script: [[.text("Hel"), .text("lo"), .stats(stats)]]) | |
| 55 | + try await withLiveServer(engines: engines) { client in | |
| 56 | + let response = try await postCompletion( | |
| 57 | + client, | |
| 58 | + #"{"model":"org/m","prompt":"Say","stream":true,"echo":true,"# | |
| 59 | + + #""stream_options":{"include_usage":true}}"#) | |
| 60 | + let all = try chunks(response) | |
| 61 | + #expect(events(response).last == "[DONE]") | |
| 62 | + #expect(all.allSatisfy { $0["object"] as? String == "text_completion" }) | |
| 63 | + #expect(all.prefix(3).compactMap(choiceText) == ["Say", "Hel", "lo"]) | |
| 64 | + #expect(finishReason(all[3]) == "stop") | |
| 65 | + #expect((all[4]["choices"] as? [Any])?.isEmpty == true) | |
| 66 | + #expect((all[4]["usage"] as? [String: Int])?["completion_tokens"] == 2) | |
| 67 | + #expect(all[0]["usage"] is NSNull) | |
| 68 | + } | |
| 69 | + } | |
| 70 | + | |
| 71 | + static let invalid: [(json: String, param: String)] = [ | |
| 72 | + (#"{"model":"org/m","prompt":"x","n":2}"#, "n"), | |
| 73 | + (#"{"model":"org/m","prompt":"x","best_of":3}"#, "best_of"), | |
| 74 | + (#"{"model":"org/m","prompt":"x","logprobs":5}"#, "logprobs"), | |
| 75 | + (#"{"model":"org/m","prompt":"x","suffix":"}"}"#, "suffix"), | |
| 76 | + (#"{"model":"org/m","prompt":["a","b"]}"#, "prompt"), | |
| 77 | + (#"{"model":"org/m","prompt":[1,2,3]}"#, "prompt"), | |
| 78 | + (#"{"model":"org/m","prompt":"x","temperature":3}"#, "temperature"), | |
| 79 | + (#"{"model":"org/m","prompt":"x","max_tokens":0}"#, "max_tokens"), | |
| 80 | + (#"{"model":"org/m","prompt":"x","stop":["a","b","c","d","e"]}"#, "stop"), | |
| 81 | + (#"{"model":"org/m"}"#, "prompt"), | |
| 82 | + ] | |
| 83 | + | |
| 84 | + @Test(arguments: invalid) | |
| 85 | + func invalidRequestsAre400s(_ invalid: (json: String, param: String)) async throws { | |
| 86 | + try await withLiveServer { client in | |
| 87 | + let response = try await postCompletion(client, invalid.json) | |
| 88 | + #expect(response.status == .badRequest) | |
| 89 | + let error = try #require(try json(response)["error"] as? [String: Any]) | |
| 90 | + #expect(error["param"] as? String == invalid.param) | |
| 91 | + } | |
| 92 | + } | |
| 93 | + | |
| 94 | + @Test func unknownModelIs404() async throws { | |
| 95 | + try await withLiveServer { client in | |
| 96 | + let response = try await postCompletion(client, #"{"model":"nope","prompt":"x"}"#) | |
| 97 | + #expect(response.status == .notFound) | |
| 98 | + } | |
| 99 | + } | |
| 100 | + | |
| 101 | + @Test func vanishedClientCancelsTheGeneration() async throws { | |
| 102 | + let engines = TestEngines(hang: true) | |
| 103 | + let models = testModels(engines: engines) | |
| 104 | + let router = RazorbillServer.makeRouter( | |
| 105 | + testSettings, models: models, streamKeepAlive: .milliseconds(20)) | |
| 106 | + try await withLiveServer(router: router, engines: engines) { client in | |
| 107 | + let body = #"{"model":"org/m","prompt":"x","stream":true}"# | |
| 108 | + let socket = try RawConnection(port: try #require(client.port)) | |
| 109 | + socket.send( | |
| 110 | + "POST /v1/completions HTTP/1.1\r\nHost: localhost\r\n" | |
| 111 | + + "Content-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)" | |
| 112 | + ) | |
| 113 | + try await Task.sleep(for: .milliseconds(200)) | |
| 114 | + socket.close() | |
| 115 | + for _ in 0 ..< 300 where engines.cancelledGenerations == 0 { | |
| 116 | + try await Task.sleep(for: .milliseconds(10)) | |
| 117 | + } | |
| 118 | + } | |
| 119 | + #expect(engines.cancelledGenerations == 1) | |
| 120 | + } | |
| 121 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,121 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import HummingbirdTesting | ||
| 4 | +import RazorbillCore | ||
| 5 | +import Testing | ||
| 6 | + | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +/// POSTs `json` to `/v1/completions`. | ||
| 10 | +func postCompletion(_ client: any TestClientProtocol, _ json: String) async throws -> TestResponse { | ||
| 11 | + try await client.execute( | ||
| 12 | + uri: "/v1/completions", method: .post, headers: [.contentType: "application/json"], | ||
| 13 | + body: ByteBuffer(string: json)) | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +/// `choices[0].text` of a `text_completion` (whole or chunk). | ||
| 17 | +func choiceText(_ body: [String: Any]) -> String? { | ||
| 18 | + ((body["choices"] as? [[String: Any]])?.first)?["text"] as? String | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +@Suite struct CompletionsTests { | ||
| 22 | + @Test func answersInOpenAIShape() async throws { | ||
| 23 | + let engines = TestEngines() | ||
| 24 | + try await withLiveServer(engines: engines) { client in | ||
| 25 | + let response = try await postCompletion( | ||
| 26 | + client, #"{"model":"org/m","prompt":"def add(a, b):","max_tokens":7}"#) | ||
| 27 | + #expect(response.status == .ok) | ||
| 28 | + let body = try json(response) | ||
| 29 | + #expect(body["object"] as? String == "text_completion") | ||
| 30 | + #expect((body["id"] as? String)?.hasPrefix("cmpl-") == true) | ||
| 31 | + #expect(choiceText(body) == "echo: def add(a, b):") | ||
| 32 | + let choice = try #require((body["choices"] as? [[String: Any]])?.first) | ||
| 33 | + #expect(choice["finish_reason"] as? String == "stop" && choice["index"] as? Int == 0) | ||
| 34 | + #expect(choice.keys.contains("logprobs")) | ||
| 35 | + #expect((body["usage"] as? [String: Int])?["total_tokens"] == 2) | ||
| 36 | + } | ||
| 37 | + // The raw prompt reaches the engine, with the client's limit and no thinking. | ||
| 38 | + #expect(engines.events.contains("complete 7 thinking=false")) | ||
| 39 | + #expect(engines.fake.receivedMessages.last == [.user("def add(a, b):")]) | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + @Test func echoAndStopSequences() async throws { | ||
| 43 | + let engines = TestEngines(script: [[.text("one, two"), .text(", three")]]) | ||
| 44 | + try await withLiveServer(engines: engines) { client in | ||
| 45 | + let body = try json( | ||
| 46 | + try await postCompletion( | ||
| 47 | + client, #"{"model":"org/m","prompt":["Count: "],"echo":true,"stop":", t"}"#)) | ||
| 48 | + #expect(choiceText(body) == "Count: one") | ||
| 49 | + } | ||
| 50 | + } | ||
| 51 | + | ||
| 52 | + @Test func streamsTextChunksThenUsage() async throws { | ||
| 53 | + let stats = GenerationStats(promptTokens: 3, generatedTokens: 2, tokensPerSecond: 1) | ||
| 54 | + let engines = TestEngines(script: [[.text("Hel"), .text("lo"), .stats(stats)]]) | ||
| 55 | + try await withLiveServer(engines: engines) { client in | ||
| 56 | + let response = try await postCompletion( | ||
| 57 | + client, | ||
| 58 | + #"{"model":"org/m","prompt":"Say","stream":true,"echo":true,"# | ||
| 59 | + + #""stream_options":{"include_usage":true}}"#) | ||
| 60 | + let all = try chunks(response) | ||
| 61 | + #expect(events(response).last == "[DONE]") | ||
| 62 | + #expect(all.allSatisfy { $0["object"] as? String == "text_completion" }) | ||
| 63 | + #expect(all.prefix(3).compactMap(choiceText) == ["Say", "Hel", "lo"]) | ||
| 64 | + #expect(finishReason(all[3]) == "stop") | ||
| 65 | + #expect((all[4]["choices"] as? [Any])?.isEmpty == true) | ||
| 66 | + #expect((all[4]["usage"] as? [String: Int])?["completion_tokens"] == 2) | ||
| 67 | + #expect(all[0]["usage"] is NSNull) | ||
| 68 | + } | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + static let invalid: [(json: String, param: String)] = [ | ||
| 72 | + (#"{"model":"org/m","prompt":"x","n":2}"#, "n"), | ||
| 73 | + (#"{"model":"org/m","prompt":"x","best_of":3}"#, "best_of"), | ||
| 74 | + (#"{"model":"org/m","prompt":"x","logprobs":5}"#, "logprobs"), | ||
| 75 | + (#"{"model":"org/m","prompt":"x","suffix":"}"}"#, "suffix"), | ||
| 76 | + (#"{"model":"org/m","prompt":["a","b"]}"#, "prompt"), | ||
| 77 | + (#"{"model":"org/m","prompt":[1,2,3]}"#, "prompt"), | ||
| 78 | + (#"{"model":"org/m","prompt":"x","temperature":3}"#, "temperature"), | ||
| 79 | + (#"{"model":"org/m","prompt":"x","max_tokens":0}"#, "max_tokens"), | ||
| 80 | + (#"{"model":"org/m","prompt":"x","stop":["a","b","c","d","e"]}"#, "stop"), | ||
| 81 | + (#"{"model":"org/m"}"#, "prompt"), | ||
| 82 | + ] | ||
| 83 | + | ||
| 84 | + @Test(arguments: invalid) | ||
| 85 | + func invalidRequestsAre400s(_ invalid: (json: String, param: String)) async throws { | ||
| 86 | + try await withLiveServer { client in | ||
| 87 | + let response = try await postCompletion(client, invalid.json) | ||
| 88 | + #expect(response.status == .badRequest) | ||
| 89 | + let error = try #require(try json(response)["error"] as? [String: Any]) | ||
| 90 | + #expect(error["param"] as? String == invalid.param) | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + @Test func unknownModelIs404() async throws { | ||
| 95 | + try await withLiveServer { client in | ||
| 96 | + let response = try await postCompletion(client, #"{"model":"nope","prompt":"x"}"#) | ||
| 97 | + #expect(response.status == .notFound) | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + @Test func vanishedClientCancelsTheGeneration() async throws { | ||
| 102 | + let engines = TestEngines(hang: true) | ||
| 103 | + let models = testModels(engines: engines) | ||
| 104 | + let router = RazorbillServer.makeRouter( | ||
| 105 | + testSettings, models: models, streamKeepAlive: .milliseconds(20)) | ||
| 106 | + try await withLiveServer(router: router, engines: engines) { client in | ||
| 107 | + let body = #"{"model":"org/m","prompt":"x","stream":true}"# | ||
| 108 | + let socket = try RawConnection(port: try #require(client.port)) | ||
| 109 | + socket.send( | ||
| 110 | + "POST /v1/completions HTTP/1.1\r\nHost: localhost\r\n" | ||
| 111 | + + "Content-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)" | ||
| 112 | + ) | ||
| 113 | + try await Task.sleep(for: .milliseconds(200)) | ||
| 114 | + socket.close() | ||
| 115 | + for _ in 0 ..< 300 where engines.cancelledGenerations == 0 { | ||
| 116 | + try await Task.sleep(for: .milliseconds(10)) | ||
| 117 | + } | ||
| 118 | + } | ||
| 119 | + #expect(engines.cancelledGenerations == 1) | ||
| 120 | + } | ||
| 121 | +} | ||
modified
Tests/RazorbillServerTests/ModelManagerTests.swift +8 -0 | @@ -82,6 +82,14 @@ final class TestEngines: @unchecked Sendable { | ||
| 82 | 82 | func embed(_ texts: [String]) async throws -> Embeddings { |
| 83 | 83 | try await owner.fake.embed(texts) |
| 84 | 84 | } |
| 85 | + | |
| 86 | + func complete( | |
| 87 | + _ prompt: String, generation: GenerationSettings | |
| 88 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | |
| 89 | + owner.record("complete \(generation.maxTokens) thinking=\(generation.thinking)") | |
| 90 | + if owner.hang { return HangingSession(owner: owner).send([]) } | |
| 91 | + return try await owner.fake.complete(prompt, generation: generation) | |
| 92 | + } | |
| 85 | 93 | } |
| 86 | 94 | } |
| 87 | 95 | |
| @@ -82,6 +82,14 @@ final class TestEngines: @unchecked Sendable { | |||
| 82 | func embed(_ texts: [String]) async throws -> Embeddings { | 82 | func embed(_ texts: [String]) async throws -> Embeddings { |
| 83 | try await owner.fake.embed(texts) | 83 | try await owner.fake.embed(texts) |
| 84 | } | 84 | } |
| 85 | + | ||
| 86 | + func complete( | ||
| 87 | + _ prompt: String, generation: GenerationSettings | ||
| 88 | + ) async throws -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 89 | + owner.record("complete \(generation.maxTokens) thinking=\(generation.thinking)") | ||
| 90 | + if owner.hang { return HangingSession(owner: owner).send([]) } | ||
| 91 | + return try await owner.fake.complete(prompt, generation: generation) | ||
| 92 | + } | ||
| 85 | } | 93 | } |
| 86 | } | 94 | } |
| 87 | 95 | ||