v0.2 step 10 — OpenAI compatibility suite (#43, Mac re-run pending)
Tests/Compatibility + scripts/compat.sh: openai SDK, LangChain and the docs' curl examples against a real rzb serve (fake engine on Linux, MLX on the Mac). Its first Mac run found two structured-output problems, fixed here: - JSON Schemas reached the grammar with keys sorted; ConfigValue maps are now ordered (ConfigMap) and request schemas are read with an order-keeping parser. - response_format json_object/json_schema now adds an instruction with the schema to the system message; without it a reasoning model planned prose and filled the forced JSON with garbage. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e69a810 parent: a61fd30 modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +11 -0 | @@ -71,3 +71,14 @@ closed. Nothing pushed. | ||
| 71 | 71 | ## Update — manual test plan |
| 72 | 72 | `TEST-PLAN-v0.2.md` (root) is what the user is running on the Mac. Wait for their report (grid at |
| 73 | 73 | the end of the file) before starting #43; fix the ❌ first. Delete the file once v0.2 is validated. |
| 74 | + | |
| 75 | +## Update — #43 in progress | |
| 76 | +- Manual plan validated by the user and deleted. Suite: `scripts/compat.sh` (see summary). | |
| 77 | +- Pending: re-run on the Mac after the ConfigMap / format-instruction fixes (Mac build + XCTest + | |
| 78 | + `scripts/compat.sh` on the Mac, or `RZB_URL=http://host.docker.internal:8080/v1 scripts/compat.sh` | |
| 79 | + against a server the user starts). Task 3 (a chat UI, e.g. Open WebUI) is manual, open. | |
| 80 | +- **Trap**: `host.sh run . rzb serve …` never ends; killing the sandbox client does NOT stop it (the | |
| 81 | + sbx proxy keeps the upstream connection, so the runner's writes never fail) and the runner then | |
| 82 | + answers 409 to everything. The user must stop `rzb serve` on the Mac. Don't serve through the | |
| 83 | + host-runner without a way to stop it (idea: a `stop` action in host_runner.py). | |
| 84 | +- Model-produced tool-call arguments still come out key-sorted (mlx-swift-lm gives a Dictionary). | |
| @@ -71,3 +71,14 @@ closed. Nothing pushed. | |||
| 71 | ## Update — manual test plan | 71 | ## Update — manual test plan |
| 72 | `TEST-PLAN-v0.2.md` (root) is what the user is running on the Mac. Wait for their report (grid at | 72 | `TEST-PLAN-v0.2.md` (root) is what the user is running on the Mac. Wait for their report (grid at |
| 73 | the end of the file) before starting #43; fix the ❌ first. Delete the file once v0.2 is validated. | 73 | the end of the file) before starting #43; fix the ❌ first. Delete the file once v0.2 is validated. |
| 74 | + | ||
| 75 | +## Update — #43 in progress | ||
| 76 | +- Manual plan validated by the user and deleted. Suite: `scripts/compat.sh` (see summary). | ||
| 77 | +- Pending: re-run on the Mac after the ConfigMap / format-instruction fixes (Mac build + XCTest + | ||
| 78 | + `scripts/compat.sh` on the Mac, or `RZB_URL=http://host.docker.internal:8080/v1 scripts/compat.sh` | ||
| 79 | + against a server the user starts). Task 3 (a chat UI, e.g. Open WebUI) is manual, open. | ||
| 80 | +- **Trap**: `host.sh run . rzb serve …` never ends; killing the sandbox client does NOT stop it (the | ||
| 81 | + sbx proxy keeps the upstream connection, so the runner's writes never fail) and the runner then | ||
| 82 | + answers 409 to everything. The user must stop `rzb serve` on the Mac. Don't serve through the | ||
| 83 | + host-runner without a way to stop it (idea: a `stop` action in host_runner.py). | ||
| 84 | +- Model-produced tool-call arguments still come out key-sorted (mlx-swift-lm gives a Dictionary). | ||
modified
.memory/history.md +14 -0 | @@ -216,3 +216,17 @@ output, constrained-decoding speed, tools (auto/required/named/none/parallel, Ll | ||
| 216 | 216 | (SDK, dimensions, base64, LangChain, Matryoshka, wrong kind, too long), known limits, report grid. |
| 217 | 217 | Correction: the server does not log tok/s (an earlier answer said it did); the plan computes it |
| 218 | 218 | from `usage`. No code change, no tests run. |
| 219 | + | |
| 220 | +## 2026-11-25 — #43 compatibility suite (in progress) + two fixes it found | |
| 221 | + | |
| 222 | +User validated the manual plan ("tout est ok"); `TEST-PLAN-v0.2.md` deleted (replaced by the suite). | |
| 223 | +Added `Tests/Compatibility/` (pytest: chat, streaming, structured output, tools, embeddings, | |
| 224 | +LangChain, docs curl examples) and `scripts/compat.sh`. Linux/fake: 28 pass, 19 skip. Ran it against | |
| 225 | +MLX on the Mac (server started through host-runner, suite from the sandbox via | |
| 226 | +host.docker.internal:8080): 45 pass, 1 fail — `parse()` with `reasoning_effort: low` hit max_tokens | |
| 227 | +with garbage JSON. Root causes: (1) schema keys reached XGrammar sorted alphabetically | |
| 228 | +(`ConfigValue.map` was a Dictionary + `.sortedKeys`) — fixed with `ConfigMap` + an order-keeping JSON | |
| 229 | +reader; (2) the model did not know JSON was expected and planned prose while thinking — fixed by | |
| 230 | +adding the schema instruction to the system message (measured 3/3 correct with vs prose in fields | |
| 231 | +without). Decision taken without asking (strong evidence); flagged to the user. Linux tests 155, | |
| 232 | +gate PASS (run #18). Mac re-run pending: the host-runner stayed busy with the server (see handoff). | |
| @@ -216,3 +216,17 @@ output, constrained-decoding speed, tools (auto/required/named/none/parallel, Ll | |||
| 216 | (SDK, dimensions, base64, LangChain, Matryoshka, wrong kind, too long), known limits, report grid. | 216 | (SDK, dimensions, base64, LangChain, Matryoshka, wrong kind, too long), known limits, report grid. |
| 217 | Correction: the server does not log tok/s (an earlier answer said it did); the plan computes it | 217 | Correction: the server does not log tok/s (an earlier answer said it did); the plan computes it |
| 218 | from `usage`. No code change, no tests run. | 218 | from `usage`. No code change, no tests run. |
| 219 | + | ||
| 220 | +## 2026-11-25 — #43 compatibility suite (in progress) + two fixes it found | ||
| 221 | + | ||
| 222 | +User validated the manual plan ("tout est ok"); `TEST-PLAN-v0.2.md` deleted (replaced by the suite). | ||
| 223 | +Added `Tests/Compatibility/` (pytest: chat, streaming, structured output, tools, embeddings, | ||
| 224 | +LangChain, docs curl examples) and `scripts/compat.sh`. Linux/fake: 28 pass, 19 skip. Ran it against | ||
| 225 | +MLX on the Mac (server started through host-runner, suite from the sandbox via | ||
| 226 | +host.docker.internal:8080): 45 pass, 1 fail — `parse()` with `reasoning_effort: low` hit max_tokens | ||
| 227 | +with garbage JSON. Root causes: (1) schema keys reached XGrammar sorted alphabetically | ||
| 228 | +(`ConfigValue.map` was a Dictionary + `.sortedKeys`) — fixed with `ConfigMap` + an order-keeping JSON | ||
| 229 | +reader; (2) the model did not know JSON was expected and planned prose while thinking — fixed by | ||
| 230 | +adding the schema instruction to the system message (measured 3/3 correct with vs prose in fields | ||
| 231 | +without). Decision taken without asking (strong evidence); flagged to the user. Linux tests 155, | ||
| 232 | +gate PASS (run #18). Mac re-run pending: the host-runner stayed busy with the server (see handoff). | ||
modified
.memory/summary.md +12 -1 | @@ -73,7 +73,13 @@ tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). E | ||
| 73 | 73 | `InferenceEngine.embed`, `EngineRegistry` factories take a `ModelKind` (`mlx` → `MLXEngine` or |
| 74 | 74 | `MLXEmbedder`), `ModelManager` slots keyed `org/name` (chat) or `org/name#embedding`, |
| 75 | 75 | `POST /v1/embeddings` in `EmbeddingsRoute.swift`; sentence-transformers CLS pooling mapped to |
| 76 | -`.first` (MLXEmbedders' `.cls` = BERT pooler output, wrong). Next: #43 compatibility suite. | |
| 76 | +`.first` (MLXEmbedders' `.cls` = BERT pooler output, wrong). JSON key order (#43): `ConfigValue.map` | |
| 77 | +holds a `ConfigMap` (insertion-ordered, order-insensitive `==`); `JSONDecoder` loses order, so | |
| 78 | +`ChatCompletionRequest.decode` re-reads the body with `ConfigValue(orderedJSON:)` | |
| 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 | |
| 81 | +system message (`formatInstruction`): without it Qwen3-4B with reasoning filled fields with prose / | |
| 82 | +looped on digits. Next: #43 Mac run, then #44, #45. | |
| 77 | 83 | |
| 78 | 84 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 79 | 85 | |
| @@ -168,6 +174,11 @@ Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #42): | ||
| 168 | 174 | sentence-transformers reference cosines, which need the two models pulled; `ConstrainedSmokeTests`, `ChatSmokeTests`: real |
| 169 | 175 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 170 | 176 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 177 | +**Compatibility suite** (#43): `scripts/compat.sh [pytest args]` — pytest + openai SDK + LangChain + | |
| 178 | +the docs' curl examples (`Tests/Compatibility/`, deps via `uv`). It starts `rzb serve` with ids | |
| 179 | +`chat` / `embed` / `unforced` (Llama, if cached) and stops it; `RZB_URL=…/v1` targets a running | |
| 180 | +server instead. Linux = fake engine (protocol only, `real_model` tests skipped): 28 pass, 19 skip. | |
| 181 | +Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes. | |
| 171 | 182 | |
| 172 | 183 | ## mlx-swift-lm API version trap |
| 173 | 184 | |
| @@ -73,7 +73,13 @@ tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). E | |||
| 73 | `InferenceEngine.embed`, `EngineRegistry` factories take a `ModelKind` (`mlx` → `MLXEngine` or | 73 | `InferenceEngine.embed`, `EngineRegistry` factories take a `ModelKind` (`mlx` → `MLXEngine` or |
| 74 | `MLXEmbedder`), `ModelManager` slots keyed `org/name` (chat) or `org/name#embedding`, | 74 | `MLXEmbedder`), `ModelManager` slots keyed `org/name` (chat) or `org/name#embedding`, |
| 75 | `POST /v1/embeddings` in `EmbeddingsRoute.swift`; sentence-transformers CLS pooling mapped to | 75 | `POST /v1/embeddings` in `EmbeddingsRoute.swift`; sentence-transformers CLS pooling mapped to |
| 76 | -`.first` (MLXEmbedders' `.cls` = BERT pooler output, wrong). Next: #43 compatibility suite. | 76 | +`.first` (MLXEmbedders' `.cls` = BERT pooler output, wrong). JSON key order (#43): `ConfigValue.map` |
| 77 | +holds a `ConfigMap` (insertion-ordered, order-insensitive `==`); `JSONDecoder` loses order, so | ||
| 78 | +`ChatCompletionRequest.decode` re-reads the body with `ConfigValue(orderedJSON:)` | ||
| 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 | ||
| 81 | +system message (`formatInstruction`): without it Qwen3-4B with reasoning filled fields with prose / | ||
| 82 | +looped on digits. Next: #43 Mac run, then #44, #45. | ||
| 77 | 83 | ||
| 78 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 84 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 79 | 85 | ||
| @@ -168,6 +174,11 @@ Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #42): | |||
| 168 | sentence-transformers reference cosines, which need the two models pulled; `ConstrainedSmokeTests`, `ChatSmokeTests`: real | 174 | sentence-transformers reference cosines, which need the two models pulled; `ConstrainedSmokeTests`, `ChatSmokeTests`: real |
| 169 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). | 175 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 170 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). | 176 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 177 | +**Compatibility suite** (#43): `scripts/compat.sh [pytest args]` — pytest + openai SDK + LangChain + | ||
| 178 | +the docs' curl examples (`Tests/Compatibility/`, deps via `uv`). It starts `rzb serve` with ids | ||
| 179 | +`chat` / `embed` / `unforced` (Llama, if cached) and stops it; `RZB_URL=…/v1` targets a running | ||
| 180 | +server instead. Linux = fake engine (protocol only, `real_model` tests skipped): 28 pass, 19 skip. | ||
| 181 | +Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes. | ||
| 171 | 182 | ||
| 172 | ## mlx-swift-lm API version trap | 183 | ## mlx-swift-lm API version trap |
| 173 | 184 | ||
modified
.quality/history.jsonl +2 -0 | @@ -14,3 +14,5 @@ | ||
| 14 | 14 | {"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} |
| 15 | 15 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} |
| 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 | +{"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"} | |
| @@ -14,3 +14,5 @@ | |||
| 14 | {"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} | 14 | {"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} |
| 15 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} | 15 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} |
| 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"} | ||
| 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"} | ||
added
.quality/report-20261125T175515Z.md +83 -0 | new file mode 100644 | ||
| @@ -0,0 +1,83 @@ | ||
| 1 | +# Quality report — 2026-11-25T17:55:15Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `a61fd30` 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**: #17 (previous: 2026-11-25T13:38:25Z) | |
| 8 | + | |
| 9 | +## Gate violations | |
| 10 | + | |
| 11 | +- warning-level issues: 3 (max 0) | |
| 12 | + | |
| 13 | +## Lint issues (`qlty check`) | |
| 14 | + | |
| 15 | +| level | count | vs previous | | |
| 16 | +|---|---|---| | |
| 17 | +| warning | 3 | — | | |
| 18 | + | |
| 19 | +### Top rules | |
| 20 | + | |
| 21 | +| rule | count | | |
| 22 | +|---|---| | |
| 23 | +| swiftlint:optional_data_string_conversion | 3 | | |
| 24 | + | |
| 25 | +### Most affected files | |
| 26 | + | |
| 27 | +| file | issues | | |
| 28 | +|---|---| | |
| 29 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 3 | | |
| 30 | + | |
| 31 | +## Code smells (`qlty smells`) | |
| 32 | + | |
| 33 | +Total: **0** (vs previous: ±0) | |
| 34 | + | |
| 35 | +_none_ | |
| 36 | + | |
| 37 | +## Metrics (`qlty metrics`) | |
| 38 | + | |
| 39 | +| metric | total | vs previous | | |
| 40 | +|---|---|---| | |
| 41 | +| funcs | 517 | +39 | | |
| 42 | +| classes | 213 | +5 | | |
| 43 | +| fields | 1021 | +38 | | |
| 44 | +| cyclo | 538 | +51 | | |
| 45 | +| complex | 449 | +41 | | |
| 46 | +| lcom | 102 | +3 | | |
| 47 | +| lines | 9261 | +505 | | |
| 48 | +| loc | 7339 | +406 | | |
| 49 | + | |
| 50 | +### Most complex files | |
| 51 | + | |
| 52 | +| file | complex | cyclo | loc | | |
| 53 | +|---|---|---|---| | |
| 54 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 35 | 48 | 205 | | |
| 55 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | |
| 56 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | |
| 57 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 58 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 59 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 18 | 25 | 284 | | |
| 60 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 169 | | |
| 61 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | |
| 62 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 63 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 64 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 65 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 66 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | |
| 67 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | |
| 68 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 69 | + | |
| 70 | +## Trend | |
| 71 | + | |
| 72 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 73 | +|---|---|---|---|---|---|---| | |
| 74 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 75 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 76 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| 77 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| 78 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | |
| 79 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | |
| 80 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| 81 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| 82 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| 83 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,83 @@ | |||
| 1 | +# Quality report — 2026-11-25T17:55:15Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `a61fd30` 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**: #17 (previous: 2026-11-25T13:38:25Z) | ||
| 8 | + | ||
| 9 | +## Gate violations | ||
| 10 | + | ||
| 11 | +- warning-level issues: 3 (max 0) | ||
| 12 | + | ||
| 13 | +## Lint issues (`qlty check`) | ||
| 14 | + | ||
| 15 | +| level | count | vs previous | | ||
| 16 | +|---|---|---| | ||
| 17 | +| warning | 3 | — | | ||
| 18 | + | ||
| 19 | +### Top rules | ||
| 20 | + | ||
| 21 | +| rule | count | | ||
| 22 | +|---|---| | ||
| 23 | +| swiftlint:optional_data_string_conversion | 3 | | ||
| 24 | + | ||
| 25 | +### Most affected files | ||
| 26 | + | ||
| 27 | +| file | issues | | ||
| 28 | +|---|---| | ||
| 29 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 3 | | ||
| 30 | + | ||
| 31 | +## Code smells (`qlty smells`) | ||
| 32 | + | ||
| 33 | +Total: **0** (vs previous: ±0) | ||
| 34 | + | ||
| 35 | +_none_ | ||
| 36 | + | ||
| 37 | +## Metrics (`qlty metrics`) | ||
| 38 | + | ||
| 39 | +| metric | total | vs previous | | ||
| 40 | +|---|---|---| | ||
| 41 | +| funcs | 517 | +39 | | ||
| 42 | +| classes | 213 | +5 | | ||
| 43 | +| fields | 1021 | +38 | | ||
| 44 | +| cyclo | 538 | +51 | | ||
| 45 | +| complex | 449 | +41 | | ||
| 46 | +| lcom | 102 | +3 | | ||
| 47 | +| lines | 9261 | +505 | | ||
| 48 | +| loc | 7339 | +406 | | ||
| 49 | + | ||
| 50 | +### Most complex files | ||
| 51 | + | ||
| 52 | +| file | complex | cyclo | loc | | ||
| 53 | +|---|---|---|---| | ||
| 54 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 35 | 48 | 205 | | ||
| 55 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | ||
| 56 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | ||
| 57 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 58 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 59 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 18 | 25 | 284 | | ||
| 60 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 169 | | ||
| 61 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | ||
| 62 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 63 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 64 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 65 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 66 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | ||
| 67 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | ||
| 68 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 69 | + | ||
| 70 | +## Trend | ||
| 71 | + | ||
| 72 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 73 | +|---|---|---|---|---|---|---| | ||
| 74 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 75 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 76 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
| 77 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
| 78 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | ||
| 79 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | ||
| 80 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
| 81 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
| 82 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
| 83 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
added
.quality/report-20261125T175549Z.md +75 -0 | new file mode 100644 | ||
| @@ -0,0 +1,75 @@ | ||
| 1 | +# Quality report — 2026-11-25T17:55:49Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `a61fd30` 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**: #18 (previous: 2026-11-25T17:55:15Z) | |
| 8 | + | |
| 9 | +## Lint issues (`qlty check`) | |
| 10 | + | |
| 11 | +| level | count | vs previous | | |
| 12 | +|---|---|---| | |
| 13 | +| warning | 0 | -3 | | |
| 14 | + | |
| 15 | +### Top rules | |
| 16 | + | |
| 17 | +_none_ | |
| 18 | + | |
| 19 | +### Most affected files | |
| 20 | + | |
| 21 | +_none_ | |
| 22 | + | |
| 23 | +## Code smells (`qlty smells`) | |
| 24 | + | |
| 25 | +Total: **0** (vs previous: ±0) | |
| 26 | + | |
| 27 | +_none_ | |
| 28 | + | |
| 29 | +## Metrics (`qlty metrics`) | |
| 30 | + | |
| 31 | +| metric | total | vs previous | | |
| 32 | +|---|---|---| | |
| 33 | +| funcs | 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 | | |
| 41 | + | |
| 42 | +### Most complex files | |
| 43 | + | |
| 44 | +| file | complex | cyclo | loc | | |
| 45 | +|---|---|---|---| | |
| 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 | | |
| 49 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | |
| 50 | +| 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 | | |
| 53 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | |
| 54 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 55 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | |
| 56 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 57 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 58 | +| 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 | | |
| 61 | + | |
| 62 | +## Trend | |
| 63 | + | |
| 64 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 65 | +|---|---|---|---|---|---|---| | |
| 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 | | |
| 69 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | |
| 70 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | |
| 71 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| 72 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| 73 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| 74 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| 75 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,75 @@ | |||
| 1 | +# Quality report — 2026-11-25T17:55:49Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `a61fd30` 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**: #18 (previous: 2026-11-25T17:55:15Z) | ||
| 8 | + | ||
| 9 | +## Lint issues (`qlty check`) | ||
| 10 | + | ||
| 11 | +| level | count | vs previous | | ||
| 12 | +|---|---|---| | ||
| 13 | +| warning | 0 | -3 | | ||
| 14 | + | ||
| 15 | +### Top rules | ||
| 16 | + | ||
| 17 | +_none_ | ||
| 18 | + | ||
| 19 | +### Most affected files | ||
| 20 | + | ||
| 21 | +_none_ | ||
| 22 | + | ||
| 23 | +## Code smells (`qlty smells`) | ||
| 24 | + | ||
| 25 | +Total: **0** (vs previous: ±0) | ||
| 26 | + | ||
| 27 | +_none_ | ||
| 28 | + | ||
| 29 | +## Metrics (`qlty metrics`) | ||
| 30 | + | ||
| 31 | +| metric | total | vs previous | | ||
| 32 | +|---|---|---| | ||
| 33 | +| funcs | 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 | | ||
| 41 | + | ||
| 42 | +### Most complex files | ||
| 43 | + | ||
| 44 | +| file | complex | cyclo | loc | | ||
| 45 | +|---|---|---|---| | ||
| 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 | | ||
| 49 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | ||
| 50 | +| 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 | | ||
| 53 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | ||
| 54 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 55 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | ||
| 56 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 57 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 58 | +| 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 | | ||
| 61 | + | ||
| 62 | +## Trend | ||
| 63 | + | ||
| 64 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 65 | +|---|---|---|---|---|---|---| | ||
| 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 | | ||
| 69 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | ||
| 70 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | ||
| 71 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
| 72 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
| 73 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
| 74 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
| 75 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | ||
modified
.quality/report-latest.md +20 -18 | @@ -1,14 +1,16 @@ | ||
| 1 | -# Quality report — 2026-11-25T13:38:25Z | |
| 1 | +# Quality report — 2026-11-25T17:55:49Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `53d6eb7` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `a61fd30` 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**: #16 (previous: 2026-11-25T13:26:02Z) | |
| 7 | +- **Run**: #18 (previous: 2026-11-25T17:55:15Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| 11 | -_none_ | |
| 11 | +| level | count | vs previous | | |
| 12 | +|---|---|---| | |
| 13 | +| warning | 0 | -3 | | |
| 12 | 14 | |
| 13 | 15 | ### Top rules |
| 14 | 16 | |
| @@ -28,14 +30,14 @@ _none_ | ||
| 28 | 30 | |
| 29 | 31 | | metric | total | vs previous | |
| 30 | 32 | |---|---|---| |
| 31 | -| funcs | 478 | +36 | | |
| 32 | -| classes | 208 | +17 | | |
| 33 | -| fields | 983 | +92 | | |
| 34 | -| cyclo | 487 | +30 | | |
| 35 | -| complex | 408 | +31 | | |
| 36 | -| lcom | 99 | +15 | | |
| 37 | -| lines | 8756 | +669 | | |
| 38 | -| loc | 6933 | +549 | | |
| 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 | | |
| 39 | 41 | |
| 40 | 42 | ### Most complex files |
| 41 | 43 | |
| @@ -44,25 +46,23 @@ _none_ | ||
| 44 | 46 | | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | |
| 45 | 47 | | Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | |
| 46 | 48 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 49 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | |
| 47 | 50 | | 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 | | |
| 48 | 53 | | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | |
| 49 | 54 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 50 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | |
| 51 | -| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | |
| 55 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | |
| 52 | 56 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 53 | 57 | | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | |
| 54 | 58 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 55 | 59 | | Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | |
| 56 | 60 | | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | |
| 57 | -| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 58 | -| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | |
| 59 | 61 | |
| 60 | 62 | ## Trend |
| 61 | 63 | |
| 62 | 64 | | run | timestamp | error | warning | smells | complex | gate | |
| 63 | 65 | |---|---|---|---|---|---|---| |
| 64 | -| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 65 | -| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 66 | 66 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | |
| 67 | 67 | | 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | |
| 68 | 68 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | |
| @@ -71,3 +71,5 @@ _none_ | ||
| 71 | 71 | | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | |
| 72 | 72 | | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | |
| 73 | 73 | | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | |
| 74 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| 75 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | |
| @@ -1,14 +1,16 @@ | |||
| 1 | -# Quality report — 2026-11-25T13:38:25Z | 1 | +# Quality report — 2026-11-25T17:55:49Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `53d6eb7` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `a61fd30` 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**: #16 (previous: 2026-11-25T13:26:02Z) | 7 | +- **Run**: #18 (previous: 2026-11-25T17:55:15Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| 11 | -_none_ | 11 | +| level | count | vs previous | |
| 12 | +|---|---|---| | ||
| 13 | +| warning | 0 | -3 | | ||
| 12 | 14 | ||
| 13 | ### Top rules | 15 | ### Top rules |
| 14 | 16 | ||
| @@ -28,14 +30,14 @@ _none_ | |||
| 28 | 30 | ||
| 29 | | metric | total | vs previous | | 31 | | metric | total | vs previous | |
| 30 | |---|---|---| | 32 | |---|---|---| |
| 31 | -| funcs | 478 | +36 | | 33 | +| funcs | 517 | ±0 | |
| 32 | -| classes | 208 | +17 | | 34 | +| classes | 213 | ±0 | |
| 33 | -| fields | 983 | +92 | | 35 | +| fields | 1021 | ±0 | |
| 34 | -| cyclo | 487 | +30 | | 36 | +| cyclo | 539 | +1 | |
| 35 | -| complex | 408 | +31 | | 37 | +| complex | 449 | ±0 | |
| 36 | -| lcom | 99 | +15 | | 38 | +| lcom | 102 | ±0 | |
| 37 | -| lines | 8756 | +669 | | 39 | +| lines | 9274 | +13 | |
| 38 | -| loc | 6933 | +549 | | 40 | +| loc | 7353 | +14 | |
| 39 | 41 | ||
| 40 | ### Most complex files | 42 | ### Most complex files |
| 41 | 43 | ||
| @@ -44,25 +46,23 @@ _none_ | |||
| 44 | | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | 46 | | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | |
| 45 | | Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | 47 | | Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | |
| 46 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | | 48 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 49 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | ||
| 47 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | 50 | | 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 | | ||
| 48 | | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | 53 | | Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | |
| 49 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | 54 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 50 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | 55 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | |
| 51 | -| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | ||
| 52 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 56 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 53 | | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | 57 | | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | |
| 54 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | 58 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 55 | | Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | 59 | | Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | |
| 56 | | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | 60 | | Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | |
| 57 | -| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 58 | -| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | ||
| 59 | 61 | ||
| 60 | ## Trend | 62 | ## Trend |
| 61 | 63 | ||
| 62 | | run | timestamp | error | warning | smells | complex | gate | | 64 | | run | timestamp | error | warning | smells | complex | gate | |
| 63 | |---|---|---|---|---|---|---| | 65 | |---|---|---|---|---|---|---| |
| 64 | -| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 65 | -| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 66 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | 66 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | |
| 67 | | 10 | 2026-11-25T12:29:06Z | 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 | | 68 | | 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | |
| @@ -71,3 +71,5 @@ _none_ | |||
| 71 | | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | 71 | | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | |
| 72 | | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | 72 | | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | |
| 73 | | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | 73 | | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | |
| 74 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
| 75 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | ||
modified
.tickets/issues/0043-openai-compatibility-test-suite-with-official-cl.yaml +16 -4 | @@ -6,7 +6,7 @@ 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-25T18:00:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::chore" |
| 12 | 12 | - "area::server" |
| @@ -29,7 +29,7 @@ body: | | ||
| 29 | 29 | tasks: |
| 30 | 30 | - id: 1 |
| 31 | 31 | title: "Python SDK compatibility script (uv)" |
| 32 | - state: open | |
| 32 | + state: closed | |
| 33 | 33 | priority: medium |
| 34 | 34 | author: |
| 35 | 35 | name: k33g |
| @@ -37,7 +37,7 @@ tasks: | ||
| 37 | 37 | createdAt: 2026-11-24T21:17:08.000Z |
| 38 | 38 | - id: 2 |
| 39 | 39 | title: "Hook it into scripts/test.sh / host-runner for the Mac" |
| 40 | - state: open | |
| 40 | + state: closed | |
| 41 | 41 | priority: medium |
| 42 | 42 | author: |
| 43 | 43 | name: k33g |
| @@ -51,4 +51,16 @@ tasks: | ||
| 51 | 51 | name: k33g |
| 52 | 52 | email: ph.charriere@gmail.com |
| 53 | 53 | createdAt: 2026-11-24T21:17:08.000Z |
| 54 | -comments: [] | |
| 54 | +comments: | |
| 55 | + - id: 1 | |
| 56 | + author: | |
| 57 | + name: k33g | |
| 58 | + email: ph.charriere@gmail.com | |
| 59 | + createdAt: 2026-11-25T18:00:00.000Z | |
| 60 | + body: | | |
| 61 | + Suite in Tests/Compatibility (pytest: openai SDK, LangChain, docs curl examples), run by | |
| 62 | + scripts/compat.sh (starts rzb serve, or RZB_URL for a running server). Kept out of | |
| 63 | + scripts/test.sh: on the Mac it needs pulled models and minutes of generation. | |
| 64 | + Linux/fake: 28 pass, 19 skip. Mac/MLX first run: 45/46; the failure (parse() with reasoning) | |
| 65 | + led to two fixes: schema key order kept (ConfigMap + ordered JSON reader) and a schema | |
| 66 | + instruction added to the system message. Mac re-run pending. | |
| @@ -6,7 +6,7 @@ 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-25T18:00:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::chore" | 11 | - "kind::chore" |
| 12 | - "area::server" | 12 | - "area::server" |
| @@ -29,7 +29,7 @@ body: | | |||
| 29 | tasks: | 29 | tasks: |
| 30 | - id: 1 | 30 | - id: 1 |
| 31 | title: "Python SDK compatibility script (uv)" | 31 | title: "Python SDK compatibility script (uv)" |
| 32 | - state: open | 32 | + state: closed |
| 33 | priority: medium | 33 | priority: medium |
| 34 | author: | 34 | author: |
| 35 | name: k33g | 35 | name: k33g |
| @@ -37,7 +37,7 @@ tasks: | |||
| 37 | createdAt: 2026-11-24T21:17:08.000Z | 37 | createdAt: 2026-11-24T21:17:08.000Z |
| 38 | - id: 2 | 38 | - id: 2 |
| 39 | title: "Hook it into scripts/test.sh / host-runner for the Mac" | 39 | title: "Hook it into scripts/test.sh / host-runner for the Mac" |
| 40 | - state: open | 40 | + state: closed |
| 41 | priority: medium | 41 | priority: medium |
| 42 | author: | 42 | author: |
| 43 | name: k33g | 43 | name: k33g |
| @@ -51,4 +51,16 @@ tasks: | |||
| 51 | name: k33g | 51 | name: k33g |
| 52 | email: ph.charriere@gmail.com | 52 | email: ph.charriere@gmail.com |
| 53 | createdAt: 2026-11-24T21:17:08.000Z | 53 | createdAt: 2026-11-24T21:17:08.000Z |
| 54 | -comments: [] | 54 | +comments: |
| 55 | + - id: 1 | ||
| 56 | + author: | ||
| 57 | + name: k33g | ||
| 58 | + email: ph.charriere@gmail.com | ||
| 59 | + createdAt: 2026-11-25T18:00:00.000Z | ||
| 60 | + body: | | ||
| 61 | + Suite in Tests/Compatibility (pytest: openai SDK, LangChain, docs curl examples), run by | ||
| 62 | + scripts/compat.sh (starts rzb serve, or RZB_URL for a running server). Kept out of | ||
| 63 | + scripts/test.sh: on the Mac it needs pulled models and minutes of generation. | ||
| 64 | + Linux/fake: 28 pass, 19 skip. Mac/MLX first run: 45/46; the failure (parse() with reasoning) | ||
| 65 | + led to two fixes: schema key order kept (ConfigMap + ordered JSON reader) and a schema | ||
| 66 | + instruction added to the system message. Mac re-run pending. | ||
added
Sources/RazorbillCore/Config/ConfigMap.swift +58 -0 | new file mode 100644 | ||
| @@ -0,0 +1,58 @@ | ||
| 1 | +/// The entries of a ``ConfigValue/map(_:)``, in the order they were written. | |
| 2 | +/// | |
| 3 | +/// Order matters for JSON Schemas sent over the API: a constrained decoder writes an object's | |
| 4 | +/// properties in schema order, and clients rely on it (a `reasoning` field before `answer`). | |
| 5 | +/// Equality ignores the order, like JSON object equality. | |
| 6 | +/// | |
| 7 | +/// ```swift | |
| 8 | +/// var schema: ConfigMap = ["type": .string("object"), "required": .list([])] | |
| 9 | +/// schema["title"] = .string("City") | |
| 10 | +/// schema.keys // ["type", "required", "title"] | |
| 11 | +/// ``` | |
| 12 | +public struct ConfigMap: Sendable, Equatable, ExpressibleByDictionaryLiteral, Sequence { | |
| 13 | + /// The keys, in order. | |
| 14 | + public private(set) var keys: [String] = [] | |
| 15 | + private var storage: [String: ConfigValue] = [:] | |
| 16 | + | |
| 17 | + public init() {} | |
| 18 | + | |
| 19 | + /// Entries in this order; a repeated key keeps its first place and its last value. | |
| 20 | + public init(_ entries: [(String, ConfigValue)]) { | |
| 21 | + for (key, value) in entries { self[key] = value } | |
| 22 | + } | |
| 23 | + | |
| 24 | + /// A dictionary has no order: its keys are sorted, so the result is the same every time. | |
| 25 | + public init(_ dictionary: [String: ConfigValue]) { | |
| 26 | + self.init(dictionary.sorted { $0.key < $1.key }.map { ($0.key, $0.value) }) | |
| 27 | + } | |
| 28 | + | |
| 29 | + public init(dictionaryLiteral elements: (String, ConfigValue)...) { | |
| 30 | + self.init(elements) | |
| 31 | + } | |
| 32 | + | |
| 33 | + public subscript(key: String) -> ConfigValue? { | |
| 34 | + get { storage[key] } | |
| 35 | + set { | |
| 36 | + if storage[key] == nil, newValue != nil { keys.append(key) } | |
| 37 | + if newValue == nil { keys.removeAll { $0 == key } } | |
| 38 | + storage[key] = newValue | |
| 39 | + } | |
| 40 | + } | |
| 41 | + | |
| 42 | + public var count: Int { keys.count } | |
| 43 | + public var isEmpty: Bool { keys.isEmpty } | |
| 44 | + /// The entries as a dictionary (order lost). | |
| 45 | + public var dictionary: [String: ConfigValue] { storage } | |
| 46 | + | |
| 47 | + public func mapValues<T>(_ transform: (ConfigValue) throws -> T) rethrows -> [String: T] { | |
| 48 | + try storage.mapValues(transform) | |
| 49 | + } | |
| 50 | + | |
| 51 | + public func makeIterator() -> some IteratorProtocol<(key: String, value: ConfigValue)> { | |
| 52 | + keys.lazy.map { (key: $0, value: storage[$0] ?? .null) }.makeIterator() | |
| 53 | + } | |
| 54 | + | |
| 55 | + public static func == (left: ConfigMap, right: ConfigMap) -> Bool { | |
| 56 | + left.storage == right.storage | |
| 57 | + } | |
| 58 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | +/// The entries of a ``ConfigValue/map(_:)``, in the order they were written. | ||
| 2 | +/// | ||
| 3 | +/// Order matters for JSON Schemas sent over the API: a constrained decoder writes an object's | ||
| 4 | +/// properties in schema order, and clients rely on it (a `reasoning` field before `answer`). | ||
| 5 | +/// Equality ignores the order, like JSON object equality. | ||
| 6 | +/// | ||
| 7 | +/// ```swift | ||
| 8 | +/// var schema: ConfigMap = ["type": .string("object"), "required": .list([])] | ||
| 9 | +/// schema["title"] = .string("City") | ||
| 10 | +/// schema.keys // ["type", "required", "title"] | ||
| 11 | +/// ``` | ||
| 12 | +public struct ConfigMap: Sendable, Equatable, ExpressibleByDictionaryLiteral, Sequence { | ||
| 13 | + /// The keys, in order. | ||
| 14 | + public private(set) var keys: [String] = [] | ||
| 15 | + private var storage: [String: ConfigValue] = [:] | ||
| 16 | + | ||
| 17 | + public init() {} | ||
| 18 | + | ||
| 19 | + /// Entries in this order; a repeated key keeps its first place and its last value. | ||
| 20 | + public init(_ entries: [(String, ConfigValue)]) { | ||
| 21 | + for (key, value) in entries { self[key] = value } | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + /// A dictionary has no order: its keys are sorted, so the result is the same every time. | ||
| 25 | + public init(_ dictionary: [String: ConfigValue]) { | ||
| 26 | + self.init(dictionary.sorted { $0.key < $1.key }.map { ($0.key, $0.value) }) | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + public init(dictionaryLiteral elements: (String, ConfigValue)...) { | ||
| 30 | + self.init(elements) | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + public subscript(key: String) -> ConfigValue? { | ||
| 34 | + get { storage[key] } | ||
| 35 | + set { | ||
| 36 | + if storage[key] == nil, newValue != nil { keys.append(key) } | ||
| 37 | + if newValue == nil { keys.removeAll { $0 == key } } | ||
| 38 | + storage[key] = newValue | ||
| 39 | + } | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + public var count: Int { keys.count } | ||
| 43 | + public var isEmpty: Bool { keys.isEmpty } | ||
| 44 | + /// The entries as a dictionary (order lost). | ||
| 45 | + public var dictionary: [String: ConfigValue] { storage } | ||
| 46 | + | ||
| 47 | + public func mapValues<T>(_ transform: (ConfigValue) throws -> T) rethrows -> [String: T] { | ||
| 48 | + try storage.mapValues(transform) | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + public func makeIterator() -> some IteratorProtocol<(key: String, value: ConfigValue)> { | ||
| 52 | + keys.lazy.map { (key: $0, value: storage[$0] ?? .null) }.makeIterator() | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + public static func == (left: ConfigMap, right: ConfigMap) -> Bool { | ||
| 56 | + left.storage == right.storage | ||
| 57 | + } | ||
| 58 | +} | ||
modified
Sources/RazorbillCore/Config/ConfigReader.swift +1 -5 | @@ -85,11 +85,7 @@ final class ConfigReader { | ||
| 85 | 85 | case .sequence(let sequence): |
| 86 | 86 | return .list(sequence.map(value)) |
| 87 | 87 | case .mapping(let mapping): |
| 88 | - var entries: [String: ConfigValue] = [:] | |
| 89 | - for (key, child) in mapping { | |
| 90 | - entries[key.string ?? ""] = value(child) | |
| 91 | - } | |
| 92 | - return .map(entries) | |
| 88 | + return .map(ConfigMap(mapping.map { ($0.key.string ?? "", value($0.value)) })) | |
| 93 | 89 | case .alias: |
| 94 | 90 | return .null |
| 95 | 91 | } |
| @@ -85,11 +85,7 @@ final class ConfigReader { | |||
| 85 | case .sequence(let sequence): | 85 | case .sequence(let sequence): |
| 86 | return .list(sequence.map(value)) | 86 | return .list(sequence.map(value)) |
| 87 | case .mapping(let mapping): | 87 | case .mapping(let mapping): |
| 88 | - var entries: [String: ConfigValue] = [:] | 88 | + return .map(ConfigMap(mapping.map { ($0.key.string ?? "", value($0.value)) })) |
| 89 | - for (key, child) in mapping { | ||
| 90 | - entries[key.string ?? ""] = value(child) | ||
| 91 | - } | ||
| 92 | - return .map(entries) | ||
| 93 | case .alias: | 89 | case .alias: |
| 94 | return .null | 90 | return .null |
| 95 | } | 91 | } |
modified
Sources/RazorbillCore/Config/ConfigValue+JSON.swift +47 -7 | @@ -2,9 +2,12 @@ import Foundation | ||
| 2 | 2 | |
| 3 | 3 | /// JSON in and out, for tool-call arguments and JSON schemas sent over the API. |
| 4 | 4 | /// |
| 5 | +/// `JSONDecoder` loses the order of object keys (its maps come out sorted); | |
| 6 | +/// ``init(orderedJSON:)`` keeps it, and ``jsonString`` writes keys in map order. | |
| 7 | +/// | |
| 5 | 8 | /// ```swift |
| 6 | -/// let value = try JSONDecoder().decode(ConfigValue.self, from: Data(#"{"a": [1, true]}"#.utf8)) | |
| 7 | -/// let text = value.jsonString // {"a":[1,true]} | |
| 9 | +/// let value = try ConfigValue(orderedJSON: Data(#"{"b": [1, true], "a": null}"#.utf8)) | |
| 10 | +/// let text = value.jsonString // {"b":[1,true],"a":null} | |
| 8 | 11 | /// ``` |
| 9 | 12 | extension ConfigValue: Codable { |
| 10 | 13 | public init(from decoder: any Decoder) throws { |
| @@ -27,7 +30,7 @@ extension ConfigValue: Codable { | ||
| 27 | 30 | in container: any SingleValueDecodingContainer |
| 28 | 31 | ) throws -> ConfigValue { |
| 29 | 32 | if let items = try? container.decode([ConfigValue].self) { return .list(items) } |
| 30 | - return .map(try container.decode([String: ConfigValue].self)) | |
| 33 | + return .map(ConfigMap(try container.decode([String: ConfigValue].self))) | |
| 31 | 34 | } |
| 32 | 35 | |
| 33 | 36 | public func encode(to encoder: any Encoder) throws { |
| @@ -39,15 +42,52 @@ extension ConfigValue: Codable { | ||
| 39 | 42 | case .double(let number): try container.encode(number) |
| 40 | 43 | case .string(let text): try container.encode(text) |
| 41 | 44 | case .list(let items): try container.encode(items) |
| 42 | - case .map(let entries): try container.encode(entries) | |
| 45 | + case .map(let entries): try container.encode(entries.dictionary) | |
| 43 | 46 | } |
| 44 | 47 | } |
| 45 | 48 | |
| 46 | - /// Compact JSON with sorted keys. | |
| 49 | + /// Compact JSON, object keys in map order. | |
| 47 | 50 | public var jsonString: String { |
| 51 | + var output = "" | |
| 52 | + write(to: &output) | |
| 53 | + return output | |
| 54 | + } | |
| 55 | + | |
| 56 | + private func write(to output: inout String) { | |
| 57 | + switch self { | |
| 58 | + case .null: output += "null" | |
| 59 | + case .bool(let flag): output += flag ? "true" : "false" | |
| 60 | + case .int(let number): output += String(number) | |
| 61 | + case .double, .string: output += Self.scalarJSON(self) | |
| 62 | + case .list(let items): | |
| 63 | + output += "[" | |
| 64 | + for (index, item) in items.enumerated() { | |
| 65 | + if index > 0 { output += "," } | |
| 66 | + item.write(to: &output) | |
| 67 | + } | |
| 68 | + output += "]" | |
| 69 | + case .map(let entries): | |
| 70 | + output += "{" | |
| 71 | + for (index, entry) in entries.enumerated() { | |
| 72 | + if index > 0 { output += "," } | |
| 73 | + output += Self.scalarJSON(.string(entry.key)) + ":" | |
| 74 | + entry.value.write(to: &output) | |
| 75 | + } | |
| 76 | + output += "}" | |
| 77 | + } | |
| 78 | + } | |
| 79 | + | |
| 80 | + /// A number or a string written by `JSONEncoder` (escapes, number format). | |
| 81 | + private static func scalarJSON(_ value: ConfigValue) -> String { | |
| 48 | 82 | let encoder = JSONEncoder() |
| 49 | - encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] | |
| 50 | - let data = (try? encoder.encode(self)) ?? Data("null".utf8) | |
| 83 | + encoder.outputFormatting = .withoutEscapingSlashes | |
| 84 | + let data = (try? encoder.encode(value)) ?? Data("null".utf8) | |
| 51 | 85 | return String(bytes: data, encoding: .utf8) ?? "null" |
| 52 | 86 | } |
| 87 | + | |
| 88 | + /// Parses JSON text, keeping the order of object keys. | |
| 89 | + public init(orderedJSON data: Data) throws { | |
| 90 | + var reader = OrderedJSONReader(bytes: Array(data)) | |
| 91 | + self = try reader.document() | |
| 92 | + } | |
| 53 | 93 | } |
| @@ -2,9 +2,12 @@ import Foundation | |||
| 2 | 2 | ||
| 3 | /// JSON in and out, for tool-call arguments and JSON schemas sent over the API. | 3 | /// JSON in and out, for tool-call arguments and JSON schemas sent over the API. |
| 4 | /// | 4 | /// |
| 5 | +/// `JSONDecoder` loses the order of object keys (its maps come out sorted); | ||
| 6 | +/// ``init(orderedJSON:)`` keeps it, and ``jsonString`` writes keys in map order. | ||
| 7 | +/// | ||
| 5 | /// ```swift | 8 | /// ```swift |
| 6 | -/// let value = try JSONDecoder().decode(ConfigValue.self, from: Data(#"{"a": [1, true]}"#.utf8)) | 9 | +/// let value = try ConfigValue(orderedJSON: Data(#"{"b": [1, true], "a": null}"#.utf8)) |
| 7 | -/// let text = value.jsonString // {"a":[1,true]} | 10 | +/// let text = value.jsonString // {"b":[1,true],"a":null} |
| 8 | /// ``` | 11 | /// ``` |
| 9 | extension ConfigValue: Codable { | 12 | extension ConfigValue: Codable { |
| 10 | public init(from decoder: any Decoder) throws { | 13 | public init(from decoder: any Decoder) throws { |
| @@ -27,7 +30,7 @@ extension ConfigValue: Codable { | |||
| 27 | in container: any SingleValueDecodingContainer | 30 | in container: any SingleValueDecodingContainer |
| 28 | ) throws -> ConfigValue { | 31 | ) throws -> ConfigValue { |
| 29 | if let items = try? container.decode([ConfigValue].self) { return .list(items) } | 32 | if let items = try? container.decode([ConfigValue].self) { return .list(items) } |
| 30 | - return .map(try container.decode([String: ConfigValue].self)) | 33 | + return .map(ConfigMap(try container.decode([String: ConfigValue].self))) |
| 31 | } | 34 | } |
| 32 | 35 | ||
| 33 | public func encode(to encoder: any Encoder) throws { | 36 | public func encode(to encoder: any Encoder) throws { |
| @@ -39,15 +42,52 @@ extension ConfigValue: Codable { | |||
| 39 | case .double(let number): try container.encode(number) | 42 | case .double(let number): try container.encode(number) |
| 40 | case .string(let text): try container.encode(text) | 43 | case .string(let text): try container.encode(text) |
| 41 | case .list(let items): try container.encode(items) | 44 | case .list(let items): try container.encode(items) |
| 42 | - case .map(let entries): try container.encode(entries) | 45 | + case .map(let entries): try container.encode(entries.dictionary) |
| 43 | } | 46 | } |
| 44 | } | 47 | } |
| 45 | 48 | ||
| 46 | - /// Compact JSON with sorted keys. | 49 | + /// Compact JSON, object keys in map order. |
| 47 | public var jsonString: String { | 50 | public var jsonString: String { |
| 51 | + var output = "" | ||
| 52 | + write(to: &output) | ||
| 53 | + return output | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + private func write(to output: inout String) { | ||
| 57 | + switch self { | ||
| 58 | + case .null: output += "null" | ||
| 59 | + case .bool(let flag): output += flag ? "true" : "false" | ||
| 60 | + case .int(let number): output += String(number) | ||
| 61 | + case .double, .string: output += Self.scalarJSON(self) | ||
| 62 | + case .list(let items): | ||
| 63 | + output += "[" | ||
| 64 | + for (index, item) in items.enumerated() { | ||
| 65 | + if index > 0 { output += "," } | ||
| 66 | + item.write(to: &output) | ||
| 67 | + } | ||
| 68 | + output += "]" | ||
| 69 | + case .map(let entries): | ||
| 70 | + output += "{" | ||
| 71 | + for (index, entry) in entries.enumerated() { | ||
| 72 | + if index > 0 { output += "," } | ||
| 73 | + output += Self.scalarJSON(.string(entry.key)) + ":" | ||
| 74 | + entry.value.write(to: &output) | ||
| 75 | + } | ||
| 76 | + output += "}" | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + /// A number or a string written by `JSONEncoder` (escapes, number format). | ||
| 81 | + private static func scalarJSON(_ value: ConfigValue) -> String { | ||
| 48 | let encoder = JSONEncoder() | 82 | let encoder = JSONEncoder() |
| 49 | - encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] | 83 | + encoder.outputFormatting = .withoutEscapingSlashes |
| 50 | - let data = (try? encoder.encode(self)) ?? Data("null".utf8) | 84 | + let data = (try? encoder.encode(value)) ?? Data("null".utf8) |
| 51 | return String(bytes: data, encoding: .utf8) ?? "null" | 85 | return String(bytes: data, encoding: .utf8) ?? "null" |
| 52 | } | 86 | } |
| 87 | + | ||
| 88 | + /// Parses JSON text, keeping the order of object keys. | ||
| 89 | + public init(orderedJSON data: Data) throws { | ||
| 90 | + var reader = OrderedJSONReader(bytes: Array(data)) | ||
| 91 | + self = try reader.document() | ||
| 92 | + } | ||
| 53 | } | 93 | } |
modified
Sources/RazorbillCore/Config/ConfigValue.swift +1 -1 | @@ -11,7 +11,7 @@ public indirect enum ConfigValue: Sendable, Equatable { | ||
| 11 | 11 | case double(Double) |
| 12 | 12 | case string(String) |
| 13 | 13 | case list([ConfigValue]) |
| 14 | - case map([String: ConfigValue]) | |
| 14 | + case map(ConfigMap) | |
| 15 | 15 | |
| 16 | 16 | /// The value for `key` when this is a map. |
| 17 | 17 | public subscript(key: String) -> ConfigValue? { |
| @@ -11,7 +11,7 @@ public indirect enum ConfigValue: Sendable, Equatable { | |||
| 11 | case double(Double) | 11 | case double(Double) |
| 12 | case string(String) | 12 | case string(String) |
| 13 | case list([ConfigValue]) | 13 | case list([ConfigValue]) |
| 14 | - case map([String: ConfigValue]) | 14 | + case map(ConfigMap) |
| 15 | 15 | ||
| 16 | /// The value for `key` when this is a map. | 16 | /// The value for `key` when this is a map. |
| 17 | public subscript(key: String) -> ConfigValue? { | 17 | public subscript(key: String) -> ConfigValue? { |
added
Sources/RazorbillCore/Config/OrderedJSONReader.swift +159 -0 | new file mode 100644 | ||
| @@ -0,0 +1,159 @@ | ||
| 1 | +/// JSON text that ``ConfigValue/init(orderedJSON:)`` cannot read. | |
| 2 | +public struct InvalidJSON: Error, Equatable, CustomStringConvertible { | |
| 3 | + public let offset: Int | |
| 4 | + public var description: String { "invalid JSON at byte \(offset)" } | |
| 5 | +} | |
| 6 | + | |
| 7 | +/// A small recursive-descent JSON parser (RFC 8259) that keeps object keys in order. | |
| 8 | +struct OrderedJSONReader { | |
| 9 | + let bytes: [UInt8] | |
| 10 | + var index = 0 | |
| 11 | + | |
| 12 | + mutating func document() throws -> ConfigValue { | |
| 13 | + let value = try self.value() | |
| 14 | + skipWhitespace() | |
| 15 | + guard index == bytes.count else { throw InvalidJSON(offset: index) } | |
| 16 | + return value | |
| 17 | + } | |
| 18 | + | |
| 19 | + private mutating func value() throws -> ConfigValue { | |
| 20 | + skipWhitespace() | |
| 21 | + switch peek() { | |
| 22 | + case UInt8(ascii: "{"): return try object() | |
| 23 | + case UInt8(ascii: "["): return try array() | |
| 24 | + case UInt8(ascii: "\""): return .string(try string()) | |
| 25 | + case UInt8(ascii: "t"): return try literal("true", .bool(true)) | |
| 26 | + case UInt8(ascii: "f"): return try literal("false", .bool(false)) | |
| 27 | + case UInt8(ascii: "n"): return try literal("null", .null) | |
| 28 | + default: return try number() | |
| 29 | + } | |
| 30 | + } | |
| 31 | + | |
| 32 | + private mutating func object() throws -> ConfigValue { | |
| 33 | + index += 1 | |
| 34 | + var entries: [(String, ConfigValue)] = [] | |
| 35 | + if try consumeClosing(UInt8(ascii: "}")) { return .map(ConfigMap(entries)) } | |
| 36 | + repeat { | |
| 37 | + skipWhitespace() | |
| 38 | + guard peek() == UInt8(ascii: "\"") else { throw InvalidJSON(offset: index) } | |
| 39 | + let key = try string() | |
| 40 | + skipWhitespace() | |
| 41 | + try expect(UInt8(ascii: ":")) | |
| 42 | + entries.append((key, try value())) | |
| 43 | + } while try separatorOrClosing(UInt8(ascii: "}")) | |
| 44 | + return .map(ConfigMap(entries)) | |
| 45 | + } | |
| 46 | + | |
| 47 | + private mutating func array() throws -> ConfigValue { | |
| 48 | + index += 1 | |
| 49 | + var items: [ConfigValue] = [] | |
| 50 | + if try consumeClosing(UInt8(ascii: "]")) { return .list(items) } | |
| 51 | + repeat { | |
| 52 | + items.append(try value()) | |
| 53 | + } while try separatorOrClosing(UInt8(ascii: "]")) | |
| 54 | + return .list(items) | |
| 55 | + } | |
| 56 | + | |
| 57 | + /// After an element: `true` on a comma (more to come), `false` on `closing`. | |
| 58 | + private mutating func separatorOrClosing(_ closing: UInt8) throws -> Bool { | |
| 59 | + skipWhitespace() | |
| 60 | + if peek() == UInt8(ascii: ",") { | |
| 61 | + index += 1 | |
| 62 | + return true | |
| 63 | + } | |
| 64 | + try expect(closing) | |
| 65 | + return false | |
| 66 | + } | |
| 67 | + | |
| 68 | + private mutating func consumeClosing(_ closing: UInt8) throws -> Bool { | |
| 69 | + skipWhitespace() | |
| 70 | + guard peek() == closing else { return false } | |
| 71 | + index += 1 | |
| 72 | + return true | |
| 73 | + } | |
| 74 | + | |
| 75 | + private mutating func string() throws -> String { | |
| 76 | + index += 1 | |
| 77 | + var utf8: [UInt8] = [] | |
| 78 | + while let byte = peek() { | |
| 79 | + index += 1 | |
| 80 | + switch byte { | |
| 81 | + case UInt8(ascii: "\""): | |
| 82 | + guard let text = String(bytes: utf8, encoding: .utf8) else { | |
| 83 | + throw InvalidJSON(offset: index - 1) | |
| 84 | + } | |
| 85 | + return text | |
| 86 | + case UInt8(ascii: "\\"): | |
| 87 | + utf8 += try escape() | |
| 88 | + case 0 ..< 0x20: | |
| 89 | + throw InvalidJSON(offset: index - 1) | |
| 90 | + default: | |
| 91 | + utf8.append(byte) | |
| 92 | + } | |
| 93 | + } | |
| 94 | + throw InvalidJSON(offset: index) | |
| 95 | + } | |
| 96 | + | |
| 97 | + /// The UTF-8 bytes of the escape after a backslash. | |
| 98 | + private mutating func escape() throws -> [UInt8] { | |
| 99 | + guard let byte = peek() else { throw InvalidJSON(offset: index) } | |
| 100 | + index += 1 | |
| 101 | + let simple: [UInt8: UInt8] = [ | |
| 102 | + UInt8(ascii: "\""): 0x22, UInt8(ascii: "\\"): 0x5C, UInt8(ascii: "/"): 0x2F, | |
| 103 | + UInt8(ascii: "b"): 0x08, UInt8(ascii: "f"): 0x0C, UInt8(ascii: "n"): 0x0A, | |
| 104 | + UInt8(ascii: "r"): 0x0D, UInt8(ascii: "t"): 0x09, | |
| 105 | + ] | |
| 106 | + if let plain = simple[byte] { return [plain] } | |
| 107 | + guard byte == UInt8(ascii: "u") else { throw InvalidJSON(offset: index - 1) } | |
| 108 | + var scalar = try hexQuad() | |
| 109 | + if (0xD800 ..< 0xDC00).contains(scalar), bytes[index...].starts(with: Array("\\u".utf8)) { | |
| 110 | + index += 2 | |
| 111 | + let low = try hexQuad() | |
| 112 | + guard (0xDC00 ..< 0xE000).contains(low) else { throw InvalidJSON(offset: index) } | |
| 113 | + scalar = 0x10000 + ((scalar - 0xD800) << 10) + (low - 0xDC00) | |
| 114 | + } | |
| 115 | + let character = Unicode.Scalar(scalar) ?? "\u{FFFD}" | |
| 116 | + return Array(String(Character(character)).utf8) | |
| 117 | + } | |
| 118 | + | |
| 119 | + private mutating func hexQuad() throws -> UInt32 { | |
| 120 | + guard index + 4 <= bytes.count, | |
| 121 | + let hex = String(bytes: bytes[index ..< index + 4], encoding: .utf8), | |
| 122 | + let value = UInt32(hex, radix: 16) | |
| 123 | + else { throw InvalidJSON(offset: index) } | |
| 124 | + index += 4 | |
| 125 | + return value | |
| 126 | + } | |
| 127 | + | |
| 128 | + private mutating func number() throws -> ConfigValue { | |
| 129 | + let start = index | |
| 130 | + let allowed = Set("+-0123456789.eE".utf8) | |
| 131 | + while let byte = peek(), allowed.contains(byte) { index += 1 } | |
| 132 | + let text = String(bytes: bytes[start ..< index], encoding: .utf8) ?? "" | |
| 133 | + let isInteger = !text.contains { ".eE".contains($0) } | |
| 134 | + if isInteger, let integer = Int(text) { return .int(integer) } | |
| 135 | + guard !text.isEmpty, let double = Double(text) else { throw InvalidJSON(offset: start) } | |
| 136 | + return .double(double) | |
| 137 | + } | |
| 138 | + | |
| 139 | + private mutating func literal(_ word: String, _ value: ConfigValue) throws -> ConfigValue { | |
| 140 | + guard bytes[index...].starts(with: Array(word.utf8)) else { | |
| 141 | + throw InvalidJSON(offset: index) | |
| 142 | + } | |
| 143 | + index += word.utf8.count | |
| 144 | + return value | |
| 145 | + } | |
| 146 | + | |
| 147 | + private mutating func expect(_ byte: UInt8) throws { | |
| 148 | + guard peek() == byte else { throw InvalidJSON(offset: index) } | |
| 149 | + index += 1 | |
| 150 | + } | |
| 151 | + | |
| 152 | + private func peek() -> UInt8? { | |
| 153 | + index < bytes.count ? bytes[index] : nil | |
| 154 | + } | |
| 155 | + | |
| 156 | + private mutating func skipWhitespace() { | |
| 157 | + while let byte = peek(), [0x20, 0x09, 0x0A, 0x0D].contains(byte) { index += 1 } | |
| 158 | + } | |
| 159 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,159 @@ | |||
| 1 | +/// JSON text that ``ConfigValue/init(orderedJSON:)`` cannot read. | ||
| 2 | +public struct InvalidJSON: Error, Equatable, CustomStringConvertible { | ||
| 3 | + public let offset: Int | ||
| 4 | + public var description: String { "invalid JSON at byte \(offset)" } | ||
| 5 | +} | ||
| 6 | + | ||
| 7 | +/// A small recursive-descent JSON parser (RFC 8259) that keeps object keys in order. | ||
| 8 | +struct OrderedJSONReader { | ||
| 9 | + let bytes: [UInt8] | ||
| 10 | + var index = 0 | ||
| 11 | + | ||
| 12 | + mutating func document() throws -> ConfigValue { | ||
| 13 | + let value = try self.value() | ||
| 14 | + skipWhitespace() | ||
| 15 | + guard index == bytes.count else { throw InvalidJSON(offset: index) } | ||
| 16 | + return value | ||
| 17 | + } | ||
| 18 | + | ||
| 19 | + private mutating func value() throws -> ConfigValue { | ||
| 20 | + skipWhitespace() | ||
| 21 | + switch peek() { | ||
| 22 | + case UInt8(ascii: "{"): return try object() | ||
| 23 | + case UInt8(ascii: "["): return try array() | ||
| 24 | + case UInt8(ascii: "\""): return .string(try string()) | ||
| 25 | + case UInt8(ascii: "t"): return try literal("true", .bool(true)) | ||
| 26 | + case UInt8(ascii: "f"): return try literal("false", .bool(false)) | ||
| 27 | + case UInt8(ascii: "n"): return try literal("null", .null) | ||
| 28 | + default: return try number() | ||
| 29 | + } | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + private mutating func object() throws -> ConfigValue { | ||
| 33 | + index += 1 | ||
| 34 | + var entries: [(String, ConfigValue)] = [] | ||
| 35 | + if try consumeClosing(UInt8(ascii: "}")) { return .map(ConfigMap(entries)) } | ||
| 36 | + repeat { | ||
| 37 | + skipWhitespace() | ||
| 38 | + guard peek() == UInt8(ascii: "\"") else { throw InvalidJSON(offset: index) } | ||
| 39 | + let key = try string() | ||
| 40 | + skipWhitespace() | ||
| 41 | + try expect(UInt8(ascii: ":")) | ||
| 42 | + entries.append((key, try value())) | ||
| 43 | + } while try separatorOrClosing(UInt8(ascii: "}")) | ||
| 44 | + return .map(ConfigMap(entries)) | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + private mutating func array() throws -> ConfigValue { | ||
| 48 | + index += 1 | ||
| 49 | + var items: [ConfigValue] = [] | ||
| 50 | + if try consumeClosing(UInt8(ascii: "]")) { return .list(items) } | ||
| 51 | + repeat { | ||
| 52 | + items.append(try value()) | ||
| 53 | + } while try separatorOrClosing(UInt8(ascii: "]")) | ||
| 54 | + return .list(items) | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + /// After an element: `true` on a comma (more to come), `false` on `closing`. | ||
| 58 | + private mutating func separatorOrClosing(_ closing: UInt8) throws -> Bool { | ||
| 59 | + skipWhitespace() | ||
| 60 | + if peek() == UInt8(ascii: ",") { | ||
| 61 | + index += 1 | ||
| 62 | + return true | ||
| 63 | + } | ||
| 64 | + try expect(closing) | ||
| 65 | + return false | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + private mutating func consumeClosing(_ closing: UInt8) throws -> Bool { | ||
| 69 | + skipWhitespace() | ||
| 70 | + guard peek() == closing else { return false } | ||
| 71 | + index += 1 | ||
| 72 | + return true | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + private mutating func string() throws -> String { | ||
| 76 | + index += 1 | ||
| 77 | + var utf8: [UInt8] = [] | ||
| 78 | + while let byte = peek() { | ||
| 79 | + index += 1 | ||
| 80 | + switch byte { | ||
| 81 | + case UInt8(ascii: "\""): | ||
| 82 | + guard let text = String(bytes: utf8, encoding: .utf8) else { | ||
| 83 | + throw InvalidJSON(offset: index - 1) | ||
| 84 | + } | ||
| 85 | + return text | ||
| 86 | + case UInt8(ascii: "\\"): | ||
| 87 | + utf8 += try escape() | ||
| 88 | + case 0 ..< 0x20: | ||
| 89 | + throw InvalidJSON(offset: index - 1) | ||
| 90 | + default: | ||
| 91 | + utf8.append(byte) | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | + throw InvalidJSON(offset: index) | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + /// The UTF-8 bytes of the escape after a backslash. | ||
| 98 | + private mutating func escape() throws -> [UInt8] { | ||
| 99 | + guard let byte = peek() else { throw InvalidJSON(offset: index) } | ||
| 100 | + index += 1 | ||
| 101 | + let simple: [UInt8: UInt8] = [ | ||
| 102 | + UInt8(ascii: "\""): 0x22, UInt8(ascii: "\\"): 0x5C, UInt8(ascii: "/"): 0x2F, | ||
| 103 | + UInt8(ascii: "b"): 0x08, UInt8(ascii: "f"): 0x0C, UInt8(ascii: "n"): 0x0A, | ||
| 104 | + UInt8(ascii: "r"): 0x0D, UInt8(ascii: "t"): 0x09, | ||
| 105 | + ] | ||
| 106 | + if let plain = simple[byte] { return [plain] } | ||
| 107 | + guard byte == UInt8(ascii: "u") else { throw InvalidJSON(offset: index - 1) } | ||
| 108 | + var scalar = try hexQuad() | ||
| 109 | + if (0xD800 ..< 0xDC00).contains(scalar), bytes[index...].starts(with: Array("\\u".utf8)) { | ||
| 110 | + index += 2 | ||
| 111 | + let low = try hexQuad() | ||
| 112 | + guard (0xDC00 ..< 0xE000).contains(low) else { throw InvalidJSON(offset: index) } | ||
| 113 | + scalar = 0x10000 + ((scalar - 0xD800) << 10) + (low - 0xDC00) | ||
| 114 | + } | ||
| 115 | + let character = Unicode.Scalar(scalar) ?? "\u{FFFD}" | ||
| 116 | + return Array(String(Character(character)).utf8) | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + private mutating func hexQuad() throws -> UInt32 { | ||
| 120 | + guard index + 4 <= bytes.count, | ||
| 121 | + let hex = String(bytes: bytes[index ..< index + 4], encoding: .utf8), | ||
| 122 | + let value = UInt32(hex, radix: 16) | ||
| 123 | + else { throw InvalidJSON(offset: index) } | ||
| 124 | + index += 4 | ||
| 125 | + return value | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + private mutating func number() throws -> ConfigValue { | ||
| 129 | + let start = index | ||
| 130 | + let allowed = Set("+-0123456789.eE".utf8) | ||
| 131 | + while let byte = peek(), allowed.contains(byte) { index += 1 } | ||
| 132 | + let text = String(bytes: bytes[start ..< index], encoding: .utf8) ?? "" | ||
| 133 | + let isInteger = !text.contains { ".eE".contains($0) } | ||
| 134 | + if isInteger, let integer = Int(text) { return .int(integer) } | ||
| 135 | + guard !text.isEmpty, let double = Double(text) else { throw InvalidJSON(offset: start) } | ||
| 136 | + return .double(double) | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + private mutating func literal(_ word: String, _ value: ConfigValue) throws -> ConfigValue { | ||
| 140 | + guard bytes[index...].starts(with: Array(word.utf8)) else { | ||
| 141 | + throw InvalidJSON(offset: index) | ||
| 142 | + } | ||
| 143 | + index += word.utf8.count | ||
| 144 | + return value | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + private mutating func expect(_ byte: UInt8) throws { | ||
| 148 | + guard peek() == byte else { throw InvalidJSON(offset: index) } | ||
| 149 | + index += 1 | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + private func peek() -> UInt8? { | ||
| 153 | + index < bytes.count ? bytes[index] : nil | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + private mutating func skipWhitespace() { | ||
| 157 | + while let byte = peek(), [0x20, 0x09, 0x0A, 0x0D].contains(byte) { index += 1 } | ||
| 158 | + } | ||
| 159 | +} | ||
modified
Sources/RazorbillCore/Engine/Messages.swift +1 -1 | @@ -43,7 +43,7 @@ public struct ChatMessage: Sendable, Equatable { | ||
| 43 | 43 | } |
| 44 | 44 | |
| 45 | 45 | /// Arguments of a tool call: a JSON object, decoded into ``ConfigValue``s. |
| 46 | -public typealias ToolArguments = [String: ConfigValue] | |
| 46 | +public typealias ToolArguments = ConfigMap | |
| 47 | 47 | |
| 48 | 48 | /// A request from the model to run a tool. |
| 49 | 49 | /// |
| @@ -43,7 +43,7 @@ public struct ChatMessage: Sendable, Equatable { | |||
| 43 | } | 43 | } |
| 44 | 44 | ||
| 45 | /// Arguments of a tool call: a JSON object, decoded into ``ConfigValue``s. | 45 | /// Arguments of a tool call: a JSON object, decoded into ``ConfigValue``s. |
| 46 | -public typealias ToolArguments = [String: ConfigValue] | 46 | +public typealias ToolArguments = ConfigMap |
| 47 | 47 | ||
| 48 | /// A request from the model to run a tool. | 48 | /// A request from the model to run a tool. |
| 49 | /// | 49 | /// |
modified
Sources/RazorbillCore/Engine/OutputConstraint.swift +1 -1 | @@ -86,7 +86,7 @@ public enum JSONSchemaSupport { | ||
| 86 | 86 | /// The sub-schemas of a schema object, with their paths. Under `properties`, `$defs`… the |
| 87 | 87 | /// keys are names, not keywords: their values are the sub-schemas. |
| 88 | 88 | private static func children( |
| 89 | - of entries: [String: ConfigValue], path: String | |
| 89 | + of entries: ConfigMap, path: String | |
| 90 | 90 | ) -> [(String, ConfigValue)] { |
| 91 | 91 | entries.keys.sorted().flatMap { key -> [(String, ConfigValue)] in |
| 92 | 92 | let childPath = path.isEmpty ? key : "\(path).\(key)" |
| @@ -86,7 +86,7 @@ public enum JSONSchemaSupport { | |||
| 86 | /// The sub-schemas of a schema object, with their paths. Under `properties`, `$defs`… the | 86 | /// The sub-schemas of a schema object, with their paths. Under `properties`, `$defs`… the |
| 87 | /// keys are names, not keywords: their values are the sub-schemas. | 87 | /// keys are names, not keywords: their values are the sub-schemas. |
| 88 | private static func children( | 88 | private static func children( |
| 89 | - of entries: [String: ConfigValue], path: String | 89 | + of entries: ConfigMap, path: String |
| 90 | ) -> [(String, ConfigValue)] { | 90 | ) -> [(String, ConfigValue)] { |
| 91 | entries.keys.sorted().flatMap { key -> [(String, ConfigValue)] in | 91 | entries.keys.sorted().flatMap { key -> [(String, ConfigValue)] in |
| 92 | let childPath = path.isEmpty ? key : "\(path).\(key)" | 92 | let childPath = path.isEmpty ? key : "\(path).\(key)" |
modified
Sources/RazorbillMLX/MLXEngine.swift +2 -2 | @@ -234,7 +234,7 @@ enum MLXConversion { | ||
| 234 | 234 | case .chunk(let text): |
| 235 | 235 | return splitter.feed(text) |
| 236 | 236 | case .toolCall(let call): |
| 237 | - let arguments = call.function.arguments.mapValues(value) | |
| 237 | + let arguments = ConfigMap(call.function.arguments.mapValues(value)) | |
| 238 | 238 | let toolCall = RazorbillCore.ToolCall( |
| 239 | 239 | id: call.id, name: call.function.name, arguments: arguments) |
| 240 | 240 | return splitter.finish() + [.toolCall(toolCall)] |
| @@ -280,7 +280,7 @@ enum MLXConversion { | ||
| 280 | 280 | case .double(let number): .double(number) |
| 281 | 281 | case .string(let text): .string(text) |
| 282 | 282 | case .array(let items): .list(items.map(value)) |
| 283 | - case .object(let entries): .map(entries.mapValues(value)) | |
| 283 | + case .object(let entries): .map(ConfigMap(entries.mapValues(value))) | |
| 284 | 284 | } |
| 285 | 285 | } |
| 286 | 286 | } |
| @@ -234,7 +234,7 @@ enum MLXConversion { | |||
| 234 | case .chunk(let text): | 234 | case .chunk(let text): |
| 235 | return splitter.feed(text) | 235 | return splitter.feed(text) |
| 236 | case .toolCall(let call): | 236 | case .toolCall(let call): |
| 237 | - let arguments = call.function.arguments.mapValues(value) | 237 | + let arguments = ConfigMap(call.function.arguments.mapValues(value)) |
| 238 | let toolCall = RazorbillCore.ToolCall( | 238 | let toolCall = RazorbillCore.ToolCall( |
| 239 | id: call.id, name: call.function.name, arguments: arguments) | 239 | id: call.id, name: call.function.name, arguments: arguments) |
| 240 | return splitter.finish() + [.toolCall(toolCall)] | 240 | return splitter.finish() + [.toolCall(toolCall)] |
| @@ -280,7 +280,7 @@ enum MLXConversion { | |||
| 280 | case .double(let number): .double(number) | 280 | case .double(let number): .double(number) |
| 281 | case .string(let text): .string(text) | 281 | case .string(let text): .string(text) |
| 282 | case .array(let items): .list(items.map(value)) | 282 | case .array(let items): .list(items.map(value)) |
| 283 | - case .object(let entries): .map(entries.mapValues(value)) | 283 | + case .object(let entries): .map(ConfigMap(entries.mapValues(value))) |
| 284 | } | 284 | } |
| 285 | } | 285 | } |
| 286 | } | 286 | } |
modified
Sources/RazorbillServer/Chat/ChatCompletionRequest.swift +22 -3 | @@ -52,15 +52,33 @@ struct ChatCompletionRequest: Decodable, Sendable { | ||
| 52 | 52 | } |
| 53 | 53 | |
| 54 | 54 | /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. |
| 55 | + /// JSON Schemas (`response_format`, tool parameters) keep the key order the client wrote. | |
| 55 | 56 | static func decode(_ data: Data) throws -> ChatCompletionRequest { |
| 56 | 57 | do { |
| 57 | - return try JSONDecoder().decode(ChatCompletionRequest.self, from: data) | |
| 58 | + var request = try JSONDecoder().decode(ChatCompletionRequest.self, from: data) | |
| 59 | + if let ordered = try? ConfigValue(orderedJSON: data) { | |
| 60 | + request.keepSchemaOrder(from: ordered) | |
| 61 | + } | |
| 62 | + return request | |
| 58 | 63 | } catch let error as DecodingError { |
| 59 | 64 | throw OpenAIError.invalidBody(error) |
| 60 | 65 | } catch { |
| 61 | 66 | throw OpenAIError(.badRequest, message: "The body is not valid JSON.") |
| 62 | 67 | } |
| 63 | 68 | } |
| 69 | + | |
| 70 | + /// `JSONDecoder` sorts object keys: take the schemas from the order-keeping parse instead. | |
| 71 | + private mutating func keepSchemaOrder(from body: ConfigValue) { | |
| 72 | + responseFormat = body["response_format"] ?? responseFormat | |
| 73 | + guard case .list(let wireTools)? = body["tools"], wireTools.count == tools?.count else { | |
| 74 | + return | |
| 75 | + } | |
| 76 | + for (index, wire) in wireTools.enumerated() { | |
| 77 | + if let parameters = wire["function"]?["parameters"] { | |
| 78 | + tools?[index].function.parameters = parameters | |
| 79 | + } | |
| 80 | + } | |
| 81 | + } | |
| 64 | 82 | } |
| 65 | 83 | |
| 66 | 84 | /// `stream_options`. |
| @@ -178,9 +196,10 @@ extension ChatCompletionRequest { | ||
| 178 | 196 | } |
| 179 | 197 | try checkReasoningSwitches() |
| 180 | 198 | let output = try outputPlan() |
| 199 | + let mapped = try messages.enumerated().map { try Self.message($1, at: $0) } | |
| 181 | 200 | return ChatPlan( |
| 182 | 201 | model: model, |
| 183 | - messages: try messages.enumerated().map { try Self.message($1, at: $0) }, | |
| 202 | + messages: Self.adding(formatInstruction(), to: mapped), | |
| 184 | 203 | client: GenerationOverrides( |
| 185 | 204 | temperature: temperature, topP: topP, maxTokens: limit, thinking: requestedThinking, |
| 186 | 205 | thinkingBudget: thinkingBudget, showReasoning: includeReasoning), |
| @@ -270,7 +289,7 @@ extension ChatCompletionRequest { | ||
| 270 | 289 | |
| 271 | 290 | private static func toolCall(_ wire: WireToolCall, path: String) throws -> ToolCall { |
| 272 | 291 | let data = Data(wire.function.arguments.utf8) |
| 273 | - guard case .map(let arguments)? = try? JSONDecoder().decode(ConfigValue.self, from: data) | |
| 292 | + guard case .map(let arguments)? = try? ConfigValue(orderedJSON: data) | |
| 274 | 293 | else { |
| 275 | 294 | throw OpenAIError( |
| 276 | 295 | .badRequest, message: "Tool call arguments must be a JSON object.", |
| @@ -52,15 +52,33 @@ struct ChatCompletionRequest: Decodable, Sendable { | |||
| 52 | } | 52 | } |
| 53 | 53 | ||
| 54 | /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. | 54 | /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. |
| 55 | + /// JSON Schemas (`response_format`, tool parameters) keep the key order the client wrote. | ||
| 55 | static func decode(_ data: Data) throws -> ChatCompletionRequest { | 56 | static func decode(_ data: Data) throws -> ChatCompletionRequest { |
| 56 | do { | 57 | do { |
| 57 | - return try JSONDecoder().decode(ChatCompletionRequest.self, from: data) | 58 | + var request = try JSONDecoder().decode(ChatCompletionRequest.self, from: data) |
| 59 | + if let ordered = try? ConfigValue(orderedJSON: data) { | ||
| 60 | + request.keepSchemaOrder(from: ordered) | ||
| 61 | + } | ||
| 62 | + return request | ||
| 58 | } catch let error as DecodingError { | 63 | } catch let error as DecodingError { |
| 59 | throw OpenAIError.invalidBody(error) | 64 | throw OpenAIError.invalidBody(error) |
| 60 | } catch { | 65 | } catch { |
| 61 | throw OpenAIError(.badRequest, message: "The body is not valid JSON.") | 66 | throw OpenAIError(.badRequest, message: "The body is not valid JSON.") |
| 62 | } | 67 | } |
| 63 | } | 68 | } |
| 69 | + | ||
| 70 | + /// `JSONDecoder` sorts object keys: take the schemas from the order-keeping parse instead. | ||
| 71 | + private mutating func keepSchemaOrder(from body: ConfigValue) { | ||
| 72 | + responseFormat = body["response_format"] ?? responseFormat | ||
| 73 | + guard case .list(let wireTools)? = body["tools"], wireTools.count == tools?.count else { | ||
| 74 | + return | ||
| 75 | + } | ||
| 76 | + for (index, wire) in wireTools.enumerated() { | ||
| 77 | + if let parameters = wire["function"]?["parameters"] { | ||
| 78 | + tools?[index].function.parameters = parameters | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | + } | ||
| 64 | } | 82 | } |
| 65 | 83 | ||
| 66 | /// `stream_options`. | 84 | /// `stream_options`. |
| @@ -178,9 +196,10 @@ extension ChatCompletionRequest { | |||
| 178 | } | 196 | } |
| 179 | try checkReasoningSwitches() | 197 | try checkReasoningSwitches() |
| 180 | let output = try outputPlan() | 198 | let output = try outputPlan() |
| 199 | + let mapped = try messages.enumerated().map { try Self.message($1, at: $0) } | ||
| 181 | return ChatPlan( | 200 | return ChatPlan( |
| 182 | model: model, | 201 | model: model, |
| 183 | - messages: try messages.enumerated().map { try Self.message($1, at: $0) }, | 202 | + messages: Self.adding(formatInstruction(), to: mapped), |
| 184 | client: GenerationOverrides( | 203 | client: GenerationOverrides( |
| 185 | temperature: temperature, topP: topP, maxTokens: limit, thinking: requestedThinking, | 204 | temperature: temperature, topP: topP, maxTokens: limit, thinking: requestedThinking, |
| 186 | thinkingBudget: thinkingBudget, showReasoning: includeReasoning), | 205 | thinkingBudget: thinkingBudget, showReasoning: includeReasoning), |
| @@ -270,7 +289,7 @@ extension ChatCompletionRequest { | |||
| 270 | 289 | ||
| 271 | private static func toolCall(_ wire: WireToolCall, path: String) throws -> ToolCall { | 290 | private static func toolCall(_ wire: WireToolCall, path: String) throws -> ToolCall { |
| 272 | let data = Data(wire.function.arguments.utf8) | 291 | let data = Data(wire.function.arguments.utf8) |
| 273 | - guard case .map(let arguments)? = try? JSONDecoder().decode(ConfigValue.self, from: data) | 292 | + guard case .map(let arguments)? = try? ConfigValue(orderedJSON: data) |
| 274 | else { | 293 | else { |
| 275 | throw OpenAIError( | 294 | throw OpenAIError( |
| 276 | .badRequest, message: "Tool call arguments must be a JSON object.", | 295 | .badRequest, message: "Tool call arguments must be a JSON object.", |
modified
Sources/RazorbillServer/Chat/ToolsAndFormats.swift +34 -1 | @@ -4,7 +4,7 @@ import RazorbillCore | ||
| 4 | 4 | /// One entry of `tools`. |
| 5 | 5 | struct WireTool: Decodable, Sendable { |
| 6 | 6 | let type: String |
| 7 | - let function: WireFunction | |
| 7 | + var function: WireFunction | |
| 8 | 8 | } |
| 9 | 9 | |
| 10 | 10 | /// A function the model may call. |
| @@ -147,6 +147,39 @@ extension ChatCompletionRequest { | ||
| 147 | 147 | } |
| 148 | 148 | } |
| 149 | 149 | |
| 150 | + /// What the model is told when `response_format` asks for JSON. The grammar alone keeps the | |
| 151 | + /// syntax valid but not the content: a model that does not know JSON is expected (a reasoning | |
| 152 | + /// model plans a prose answer while it thinks) fills the forced fields with prose or loops on | |
| 153 | + /// digits. Measured with Qwen3-4B (#43): 3 of 3 answers right with the schema in the prompt, | |
| 154 | + /// prose in the fields without it. | |
| 155 | + func formatInstruction() -> String? { | |
| 156 | + switch responseFormat?["type"]?.stringValue { | |
| 157 | + case "json_object": | |
| 158 | + return "Answer with a single JSON object." | |
| 159 | + case "json_schema": | |
| 160 | + guard let schema = responseFormat?["json_schema"]?["schema"] else { return nil } | |
| 161 | + return "Answer with a single JSON object that follows this JSON Schema:\n" | |
| 162 | + + schema.jsonString | |
| 163 | + default: | |
| 164 | + return nil | |
| 165 | + } | |
| 166 | + } | |
| 167 | + | |
| 168 | + /// `messages` with `instruction` appended to the system message (one is added first when | |
| 169 | + /// the conversation has none). | |
| 170 | + static func adding(_ instruction: String?, to messages: [ChatMessage]) -> [ChatMessage] { | |
| 171 | + guard let instruction else { return messages } | |
| 172 | + var result = messages | |
| 173 | + if let first = result.first, first.role == .system { | |
| 174 | + result[0].content = | |
| 175 | + first.content.isEmpty | |
| 176 | + ? instruction : first.content + "\n\n" + instruction | |
| 177 | + } else { | |
| 178 | + result.insert(ChatMessage(role: .system, content: instruction), at: 0) | |
| 179 | + } | |
| 180 | + return result | |
| 181 | + } | |
| 182 | + | |
| 150 | 183 | /// A strict schema must not rely on keywords the decoder cannot enforce. |
| 151 | 184 | private func checkEnforceable(_ schema: ConfigValue, param: String) throws { |
| 152 | 185 | if let found = JSONSchemaSupport.firstUnenforcedKeyword(in: schema) { |
| @@ -4,7 +4,7 @@ import RazorbillCore | |||
| 4 | /// One entry of `tools`. | 4 | /// One entry of `tools`. |
| 5 | struct WireTool: Decodable, Sendable { | 5 | struct WireTool: Decodable, Sendable { |
| 6 | let type: String | 6 | let type: String |
| 7 | - let function: WireFunction | 7 | + var function: WireFunction |
| 8 | } | 8 | } |
| 9 | 9 | ||
| 10 | /// A function the model may call. | 10 | /// A function the model may call. |
| @@ -147,6 +147,39 @@ extension ChatCompletionRequest { | |||
| 147 | } | 147 | } |
| 148 | } | 148 | } |
| 149 | 149 | ||
| 150 | + /// What the model is told when `response_format` asks for JSON. The grammar alone keeps the | ||
| 151 | + /// syntax valid but not the content: a model that does not know JSON is expected (a reasoning | ||
| 152 | + /// model plans a prose answer while it thinks) fills the forced fields with prose or loops on | ||
| 153 | + /// digits. Measured with Qwen3-4B (#43): 3 of 3 answers right with the schema in the prompt, | ||
| 154 | + /// prose in the fields without it. | ||
| 155 | + func formatInstruction() -> String? { | ||
| 156 | + switch responseFormat?["type"]?.stringValue { | ||
| 157 | + case "json_object": | ||
| 158 | + return "Answer with a single JSON object." | ||
| 159 | + case "json_schema": | ||
| 160 | + guard let schema = responseFormat?["json_schema"]?["schema"] else { return nil } | ||
| 161 | + return "Answer with a single JSON object that follows this JSON Schema:\n" | ||
| 162 | + + schema.jsonString | ||
| 163 | + default: | ||
| 164 | + return nil | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + /// `messages` with `instruction` appended to the system message (one is added first when | ||
| 169 | + /// the conversation has none). | ||
| 170 | + static func adding(_ instruction: String?, to messages: [ChatMessage]) -> [ChatMessage] { | ||
| 171 | + guard let instruction else { return messages } | ||
| 172 | + var result = messages | ||
| 173 | + if let first = result.first, first.role == .system { | ||
| 174 | + result[0].content = | ||
| 175 | + first.content.isEmpty | ||
| 176 | + ? instruction : first.content + "\n\n" + instruction | ||
| 177 | + } else { | ||
| 178 | + result.insert(ChatMessage(role: .system, content: instruction), at: 0) | ||
| 179 | + } | ||
| 180 | + return result | ||
| 181 | + } | ||
| 182 | + | ||
| 150 | /// A strict schema must not rely on keywords the decoder cannot enforce. | 183 | /// A strict schema must not rely on keywords the decoder cannot enforce. |
| 151 | private func checkEnforceable(_ schema: ConfigValue, param: String) throws { | 184 | private func checkEnforceable(_ schema: ConfigValue, param: String) throws { |
| 152 | if let found = JSONSchemaSupport.firstUnenforcedKeyword(in: schema) { | 185 | if let found = JSONSchemaSupport.firstUnenforcedKeyword(in: schema) { |
deleted
TEST-PLAN-v0.2.md +0 -669 | deleted file mode 100644 | ||
| @@ -1,669 +0,0 @@ | ||
| 1 | -# Plan de test manuel — rzb serve v0.2 (#38 → #42) | |
| 2 | - | |
| 3 | -Ce document liste ce qu'il reste à vérifier **à la main, sur le Mac**, après les tickets #38 à #42 | |
| 4 | -(sorties structurées, appels d'outils, embeddings). Les tests automatiques passent déjà (Linux 144, | |
| 5 | -Mac 167) : ici, on vérifie ce qu'ils ne couvrent pas — de vrais clients, de plus gros modèles, | |
| 6 | -d'autres familles de modèles, et la vitesse en Release. | |
| 7 | - | |
| 8 | -Chaque test a : la commande à lancer, **le résultat attendu**, et une case à cocher. Notez ce qui | |
| 9 | -échoue (commande + sortie) dans la section [Rapport](#rapport) à la fin. | |
| 10 | - | |
| 11 | -Durée estimée : 1 h à 1 h 30, dont l'essentiel en téléchargements de modèles. | |
| 12 | - | |
| 13 | ---- | |
| 14 | - | |
| 15 | -## 0. Préparation | |
| 16 | - | |
| 17 | -### 0.1 Compiler en Release | |
| 18 | - | |
| 19 | -```bash | |
| 20 | -cd ~/kDrive/Rickub/bots-garden/razorbill | |
| 21 | -xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \ | |
| 22 | - -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation | |
| 23 | -alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb" | |
| 24 | -rzb version | |
| 25 | -``` | |
| 26 | - | |
| 27 | -- [ ] `rzb version` affiche la version et `engines: mlx`. | |
| 28 | - | |
| 29 | -### 0.2 Télécharger les modèles | |
| 30 | - | |
| 31 | -```bash | |
| 32 | -rzb models pull mlx-community/Qwen3-4B-4bit # ~2,3 Go — chat, outils, JSON | |
| 33 | -rzb models pull mlx-community/Llama-3.2-3B-Instruct-4bit # ~1,8 Go — 2e famille d'outils | |
| 34 | -rzb models pull BAAI/bge-small-en-v1.5 # déjà en cache normalement | |
| 35 | -rzb models list | |
| 36 | -``` | |
| 37 | - | |
| 38 | -Optionnel (test Matryoshka, §4.4) : un modèle d'embedding Qwen3 au format MLX, par exemple | |
| 39 | -`mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ` (vérifiez le nom exact sur Hugging Face). | |
| 40 | - | |
| 41 | -### 0.3 Configuration de test | |
| 42 | - | |
| 43 | -Enregistrez ceci dans `/tmp/rzb-test.yaml` : | |
| 44 | - | |
| 45 | -```yaml | |
| 46 | -server: | |
| 47 | - host: 127.0.0.1 | |
| 48 | - port: 8080 | |
| 49 | - | |
| 50 | -models: | |
| 51 | - - id: qwen4b | |
| 52 | - source: mlx-community/Qwen3-4B-4bit | |
| 53 | - kind: chat | |
| 54 | - - id: llama3b | |
| 55 | - source: mlx-community/Llama-3.2-3B-Instruct-4bit | |
| 56 | - kind: chat | |
| 57 | - - id: embed | |
| 58 | - source: BAAI/bge-small-en-v1.5 | |
| 59 | - kind: embedding | |
| 60 | - preload: true | |
| 61 | - | |
| 62 | -limits: | |
| 63 | - max_loaded_models: 2 | |
| 64 | - keep_alive: 10m | |
| 65 | -``` | |
| 66 | - | |
| 67 | -```bash | |
| 68 | -rzb config validate /tmp/rzb-test.yaml | |
| 69 | -rzb serve --config /tmp/rzb-test.yaml | |
| 70 | -``` | |
| 71 | - | |
| 72 | -- [ ] `config validate` ne signale aucune erreur. | |
| 73 | -- [ ] Le serveur démarre, affiche `serving http://127.0.0.1:8080`, et le log indique que `embed` | |
| 74 | - est chargé au démarrage (`preload: true`). | |
| 75 | - | |
| 76 | -Laissez ce terminal ouvert (les logs serviront) et ouvrez-en un second pour la suite. | |
| 77 | - | |
| 78 | -> Pas de clé d'API dans cette config : les clients peuvent envoyer n'importe quelle valeur | |
| 79 | -> (`api_key="x"`). Si `RZB_API_KEY` est définie dans votre shell **et** déclarée via | |
| 80 | -> `api_key_env`, utilisez sa valeur. | |
| 81 | - | |
| 82 | -### 0.4 Outils côté client | |
| 83 | - | |
| 84 | -Les exemples Python utilisent `uv` (pas d'environnement à créer) : | |
| 85 | - | |
| 86 | -```bash | |
| 87 | -uv --version # sinon : brew install uv | |
| 88 | -``` | |
| 89 | - | |
| 90 | -### 0.5 Premier contact | |
| 91 | - | |
| 92 | -```bash | |
| 93 | -curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool | |
| 94 | -``` | |
| 95 | - | |
| 96 | -- [ ] La liste contient `qwen4b`, `llama3b` (`"kind": "chat"`) et `embed` (`"kind": "embedding"`), | |
| 97 | - plus les modèles du cache. | |
| 98 | - | |
| 99 | ---- | |
| 100 | - | |
| 101 | -## 1. Sorties structurées — `response_format` (#39) | |
| 102 | - | |
| 103 | -### 1.1 `parse()` du SDK openai avec une classe Pydantic — **critère d'acceptation de #39** | |
| 104 | - | |
| 105 | -```bash | |
| 106 | -uv run --with openai --with pydantic python - <<'EOF' | |
| 107 | -from openai import OpenAI | |
| 108 | -from pydantic import BaseModel | |
| 109 | - | |
| 110 | -class City(BaseModel): | |
| 111 | - name: str | |
| 112 | - country: str | |
| 113 | - population: int | |
| 114 | - landmarks: list[str] | |
| 115 | - | |
| 116 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 117 | -completion = client.beta.chat.completions.parse( | |
| 118 | - model="qwen4b", | |
| 119 | - messages=[{"role": "user", "content": "Describe Lyon, France."}], | |
| 120 | - response_format=City, | |
| 121 | - extra_body={"reasoning_effort": "high"}, | |
| 122 | -) | |
| 123 | -message = completion.choices[0].message | |
| 124 | -print("parsed :", message.parsed) | |
| 125 | -print("raison :", (getattr(message, "reasoning_content", None) or "")[:200]) | |
| 126 | -EOF | |
| 127 | -``` | |
| 128 | - | |
| 129 | -- [ ] `parsed` est un objet `City` rempli (pas `None`), sans exception de validation. | |
| 130 | -- [ ] Recommencez 3 fois : toujours un JSON valide. | |
| 131 | - | |
| 132 | -> Selon la version du SDK, `client.chat.completions.parse(...)` (sans `beta`) existe aussi : | |
| 133 | -> testez celle que vous avez. | |
| 134 | - | |
| 135 | -### 1.2 Avec réflexion activée | |
| 136 | - | |
| 137 | -```bash | |
| 138 | -uv run --with openai --with pydantic python - <<'EOF' | |
| 139 | -from openai import OpenAI | |
| 140 | -from pydantic import BaseModel | |
| 141 | - | |
| 142 | -class City(BaseModel): | |
| 143 | - name: str | |
| 144 | - country: str | |
| 145 | - population: int | |
| 146 | - landmarks: list[str] | |
| 147 | - | |
| 148 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 149 | -completion = client.beta.chat.completions.parse( | |
| 150 | - model="qwen4b", | |
| 151 | - messages=[{"role": "user", "content": "Describe Lyon, France."}], | |
| 152 | - response_format=City, | |
| 153 | - extra_body={"reasoning_effort": "high"}, | |
| 154 | -) | |
| 155 | -message = completion.choices[0].message | |
| 156 | -print("parsed :", message.parsed) | |
| 157 | -print("raison :", (getattr(message, "reasoning_content", None) or "")[:500]) | |
| 158 | -EOF | |
| 159 | -``` | |
| 160 | - | |
| 161 | -- [ ] `reasoning_content` contient la réflexion (texte libre, pas du JSON). | |
| 162 | -- [ ] `parsed` reste un objet `City` valide : la contrainte ne s'applique qu'après `</think>`. | |
| 163 | - | |
| 164 | -### 1.3 `json_object` avec curl | |
| 165 | - | |
| 166 | -```bash | |
| 167 | -curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | |
| 168 | - "model": "qwen4b", | |
| 169 | - "messages": [{"role": "user", "content": "Give me 3 French cheeses with their region, as JSON."}], | |
| 170 | - "response_format": {"type": "json_object"}, | |
| 171 | - "reasoning_effort": "none" | |
| 172 | -}' | python3 -c 'import json,sys; c=json.load(sys.stdin)["choices"][0]["message"]["content"]; print(json.dumps(json.loads(c), indent=2, ensure_ascii=False))' | |
| 173 | -``` | |
| 174 | - | |
| 175 | -- [ ] La commande affiche un objet JSON (le `json.loads` ne lève pas d'erreur). | |
| 176 | - | |
| 177 | -### 1.4 Streaming d'un `json_schema` | |
| 178 | - | |
| 179 | -```bash | |
| 180 | -curl -sN http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | |
| 181 | - "model": "qwen4b", "stream": true, "reasoning_effort": "none", | |
| 182 | - "messages": [{"role": "user", "content": "List 5 planets with their diameter in km."}], | |
| 183 | - "response_format": {"type": "json_schema", "json_schema": {"name": "planets", "strict": true, | |
| 184 | - "schema": {"type": "object", "additionalProperties": false, "required": ["planets"], | |
| 185 | - "properties": {"planets": {"type": "array", "items": {"type": "object", | |
| 186 | - "additionalProperties": false, "required": ["name", "diameter_km"], | |
| 187 | - "properties": {"name": {"type": "string"}, "diameter_km": {"type": "number"}}}}}}}} | |
| 188 | -}' | |
| 189 | -``` | |
| 190 | - | |
| 191 | -- [ ] Les lignes `data: {...}` arrivent **au fil de l'eau**, chacune avec un petit morceau de JSON | |
| 192 | - dans `delta.content` (pas un seul bloc à la fin). | |
| 193 | -- [ ] Le flux se termine par `finish_reason: "stop"` puis `data: [DONE]`. | |
| 194 | -- [ ] En recollant les `content`, on obtient un JSON qui respecte le schéma. | |
| 195 | - | |
| 196 | -### 1.5 Schéma strict avec un mot-clé non appliqué → 400 | |
| 197 | - | |
| 198 | -```bash | |
| 199 | -curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | |
| 200 | - "model": "qwen4b", | |
| 201 | - "messages": [{"role": "user", "content": "3 tags"}], | |
| 202 | - "response_format": {"type": "json_schema", "json_schema": {"name": "tags", "strict": true, | |
| 203 | - "schema": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}}} | |
| 204 | -}' | |
| 205 | -``` | |
| 206 | - | |
| 207 | -- [ ] Réponse **400** `{"error": {...}}` dont le message nomme `uniqueItems`. | |
| 208 | -- [ ] Le même appel avec `"strict": false` est accepté (le mot-clé est simplement ignoré). | |
| 209 | - | |
| 210 | ---- | |
| 211 | - | |
| 212 | -## 2. Vitesse du décodage contraint (Release) | |
| 213 | - | |
| 214 | -Mes mesures (build **Debug**, Qwen3-0.6B) : ~90 tok/s en libre, ~49 tok/s sous contrainte. Le | |
| 215 | -serveur ne logue pas les tok/s : ce script les calcule à partir de `usage`. | |
| 216 | - | |
| 217 | -```bash | |
| 218 | -uv run --with openai python - <<'EOF' | |
| 219 | -import time | |
| 220 | -from openai import OpenAI | |
| 221 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 222 | -prompt = [{"role": "user", "content": "Describe 10 European capitals: name, country, population, one fact each."}] | |
| 223 | -schema = {"type": "json_schema", "json_schema": {"name": "capitals", "schema": { | |
| 224 | - "type": "object", "properties": {"capitals": {"type": "array", "items": {"type": "object", | |
| 225 | - "properties": {"name": {"type": "string"}, "country": {"type": "string"}, | |
| 226 | - "population": {"type": "integer"}, "fact": {"type": "string"}}, | |
| 227 | - "required": ["name", "country", "population", "fact"]}}}, "required": ["capitals"]}}} | |
| 228 | -client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=5) # chauffe | |
| 229 | -for label, extra in [("libre", {}), ("json_object", {"response_format": {"type": "json_object"}}), | |
| 230 | - ("json_schema", {"response_format": schema})]: | |
| 231 | - start = time.time() | |
| 232 | - r = client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=800, | |
| 233 | - extra_body={"reasoning_effort": "none"}, **extra) | |
| 234 | - elapsed = time.time() - start | |
| 235 | - n = r.usage.completion_tokens | |
| 236 | - print(f"{label:12} {n:4} tokens {elapsed:5.1f} s {n / elapsed:5.1f} tok/s") | |
| 237 | -EOF | |
| 238 | -``` | |
| 239 | - | |
| 240 | -- [ ] Notez les trois débits dans le rapport. **Attendu** : le contraint reste dans le même ordre | |
| 241 | - de grandeur que le libre (au pire ~2× plus lent). Un écart de 5× ou plus est un problème. | |
| 242 | -- [ ] Optionnel : relancez avec `model="mlx-community/Qwen3-0.6B-4bit"` pour comparer à mes chiffres Debug. | |
| 243 | - | |
| 244 | ---- | |
| 245 | - | |
| 246 | -## 3. Appels d'outils (#40, #41) | |
| 247 | - | |
| 248 | -### 3.1 Aller-retour complet en `auto` avec Qwen3-4B | |
| 249 | - | |
| 250 | -```bash | |
| 251 | -uv run --with openai python - <<'EOF' | |
| 252 | -import json | |
| 253 | -from openai import OpenAI | |
| 254 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 255 | -MODEL = "qwen4b" | |
| 256 | -tools = [{"type": "function", "function": { | |
| 257 | - "name": "get_weather", "description": "Current weather for a city", | |
| 258 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 259 | - "required": ["city"]}}}] | |
| 260 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | |
| 261 | - | |
| 262 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | |
| 263 | -msg = r.choices[0].message | |
| 264 | -print("1) finish_reason:", r.choices[0].finish_reason) | |
| 265 | -print(" tool_calls :", msg.tool_calls) | |
| 266 | -assert msg.tool_calls, "aucun appel d'outil" | |
| 267 | - | |
| 268 | -messages.append(msg.model_dump(exclude_none=True)) | |
| 269 | -for call in msg.tool_calls: | |
| 270 | - args = json.loads(call.function.arguments) | |
| 271 | - messages.append({"role": "tool", "tool_call_id": call.id, | |
| 272 | - "content": json.dumps({"city": args["city"], "temp_c": 7, "sky": "rain"})}) | |
| 273 | - | |
| 274 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | |
| 275 | -print("2) réponse finale:", r.choices[0].message.content) | |
| 276 | -EOF | |
| 277 | -``` | |
| 278 | - | |
| 279 | -- [ ] Étape 1 : `finish_reason` vaut `tool_calls`, avec un appel `get_weather` dont les | |
| 280 | - `arguments` sont un JSON valide (`{"city": "Lyon"}`). | |
| 281 | -- [ ] Étape 2 : la réponse finale parle de 7 °C et de pluie à Lyon. | |
| 282 | - | |
| 283 | -### 3.2 Appel d'outil en streaming | |
| 284 | - | |
| 285 | -```bash | |
| 286 | -uv run --with openai python - <<'EOF' | |
| 287 | -from openai import OpenAI | |
| 288 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 289 | -MODEL = "qwen4b" | |
| 290 | -tools = [{"type": "function", "function": { | |
| 291 | - "name": "get_weather", "description": "Current weather for a city", | |
| 292 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 293 | - "required": ["city"]}}}] | |
| 294 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | |
| 295 | - | |
| 296 | -stream = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, stream=True) | |
| 297 | -for chunk in stream: | |
| 298 | - if chunk.choices: | |
| 299 | - choice = chunk.choices[0] | |
| 300 | - print(choice.delta.model_dump(exclude_none=True), "| finish:", choice.finish_reason) | |
| 301 | -EOF | |
| 302 | -``` | |
| 303 | - | |
| 304 | -- [ ] Un delta contient `tool_calls` avec `index: 0`, un `id`, `type: "function"` et le nom et les | |
| 305 | - arguments ; le dernier chunk a `finish: tool_calls`. | |
| 306 | - | |
| 307 | -### 3.3 Deuxième famille (Llama 3.2) en `auto` — **critère de #40, non vérifié** | |
| 308 | - | |
| 309 | -```bash | |
| 310 | -uv run --with openai python - <<'EOF' | |
| 311 | -import json | |
| 312 | -from openai import OpenAI | |
| 313 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 314 | -MODEL = "llama3b" | |
| 315 | -tools = [{"type": "function", "function": { | |
| 316 | - "name": "get_weather", "description": "Current weather for a city", | |
| 317 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 318 | - "required": ["city"]}}}] | |
| 319 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | |
| 320 | - | |
| 321 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | |
| 322 | -msg = r.choices[0].message | |
| 323 | -print("1) finish_reason:", r.choices[0].finish_reason) | |
| 324 | -print(" tool_calls :", msg.tool_calls) | |
| 325 | -print(" content :", msg.content) | |
| 326 | -assert msg.tool_calls, "aucun appel d'outil" | |
| 327 | - | |
| 328 | -messages.append(msg.model_dump(exclude_none=True)) | |
| 329 | -for call in msg.tool_calls: | |
| 330 | - args = json.loads(call.function.arguments) | |
| 331 | - messages.append({"role": "tool", "tool_call_id": call.id, | |
| 332 | - "content": json.dumps({"city": args["city"], "temp_c": 7, "sky": "rain"})}) | |
| 333 | - | |
| 334 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | |
| 335 | -print("2) réponse finale:", r.choices[0].message.content) | |
| 336 | -EOF | |
| 337 | -``` | |
| 338 | - | |
| 339 | -- [ ] `tool_calls` est rempli correctement (nom + arguments JSON), **pas** du texte brut du genre | |
| 340 | - `{"name": "get_weather", ...}` dans `content`. | |
| 341 | -- [ ] La réponse finale utilise le résultat de l'outil. | |
| 342 | - | |
| 343 | -Si vous avez un Mistral au format MLX (ex. `mlx-community/Mistral-7B-Instruct-v0.3-4bit`), relancez | |
| 344 | -ce script en remplaçant `MODEL = "llama3b"` par l'id du modèle. | |
| 345 | - | |
| 346 | -### 3.4 Appels forcés sur Qwen : `required` et fonction nommée | |
| 347 | - | |
| 348 | -La question n'a **rien à voir** avec la météo : seule la grammaire peut produire l'appel. | |
| 349 | - | |
| 350 | -```bash | |
| 351 | -uv run --with openai python - <<'EOF' | |
| 352 | -from openai import OpenAI | |
| 353 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 354 | -MODEL = "qwen4b" | |
| 355 | -tools = [{"type": "function", "function": { | |
| 356 | - "name": "get_weather", "description": "Current weather for a city", | |
| 357 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 358 | - "required": ["city"]}}}] | |
| 359 | -messages = [{"role": "user", "content": "Tell me a joke."}] | |
| 360 | - | |
| 361 | -for label, choice in [("required", "required"), | |
| 362 | - ("nommée", {"type": "function", "function": {"name": "get_weather"}})]: | |
| 363 | - r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | |
| 364 | - tool_choice=choice) | |
| 365 | - calls = r.choices[0].message.tool_calls or [] | |
| 366 | - print(f"{label:9} finish={r.choices[0].finish_reason} {len(calls)} appel(s)") | |
| 367 | - for call in calls: | |
| 368 | - print(" ", call.function.name, call.function.arguments) | |
| 369 | -EOF | |
| 370 | -``` | |
| 371 | - | |
| 372 | -- [ ] Pour `required` comme pour la fonction nommée : `finish=tool_calls` et **exactement un** | |
| 373 | - appel `get_weather` avec des arguments JSON valides. | |
| 374 | - | |
| 375 | -### 3.5 Appel forcé sur Llama → 400 attendu | |
| 376 | - | |
| 377 | -```bash | |
| 378 | -uv run --with openai python - <<'EOF' | |
| 379 | -import openai | |
| 380 | -from openai import OpenAI | |
| 381 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 382 | -MODEL = "llama3b" | |
| 383 | -tools = [{"type": "function", "function": { | |
| 384 | - "name": "get_weather", "description": "Current weather for a city", | |
| 385 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 386 | - "required": ["city"]}}}] | |
| 387 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | |
| 388 | - | |
| 389 | -for choice in ["required", "auto"]: | |
| 390 | - try: | |
| 391 | - r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | |
| 392 | - tool_choice=choice) | |
| 393 | - print(f"{choice:8} OK finish={r.choices[0].finish_reason}", | |
| 394 | - r.choices[0].message.tool_calls) | |
| 395 | - except openai.BadRequestError as error: | |
| 396 | - print(f"{choice:8} 400 ", error.body) | |
| 397 | -EOF | |
| 398 | -``` | |
| 399 | - | |
| 400 | -- [ ] `required` : **400** avec un message expliquant que la syntaxe d'appel de ce modèle ne permet | |
| 401 | - pas de forcer un outil. C'est le comportement voulu. | |
| 402 | -- [ ] `auto` : OK, avec un appel `get_weather` (cf. 3.3). | |
| 403 | - | |
| 404 | -### 3.6 `tool_choice: "none"` | |
| 405 | - | |
| 406 | -```bash | |
| 407 | -uv run --with openai python - <<'EOF' | |
| 408 | -from openai import OpenAI | |
| 409 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 410 | -MODEL = "qwen4b" | |
| 411 | -tools = [{"type": "function", "function": { | |
| 412 | - "name": "get_weather", "description": "Current weather for a city", | |
| 413 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 414 | - "required": ["city"]}}}] | |
| 415 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | |
| 416 | - | |
| 417 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, tool_choice="none") | |
| 418 | -msg = r.choices[0].message | |
| 419 | -print("finish_reason:", r.choices[0].finish_reason) | |
| 420 | -print("tool_calls :", msg.tool_calls) | |
| 421 | -print("content :", msg.content) | |
| 422 | -EOF | |
| 423 | -``` | |
| 424 | - | |
| 425 | -- [ ] `finish_reason: stop`, `tool_calls: None`, et une réponse en texte. | |
| 426 | - | |
| 427 | -### 3.7 Appels parallèles | |
| 428 | - | |
| 429 | -```bash | |
| 430 | -uv run --with openai python - <<'EOF' | |
| 431 | -from openai import OpenAI | |
| 432 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 433 | -MODEL = "qwen4b" | |
| 434 | -tools = [ | |
| 435 | - {"type": "function", "function": { | |
| 436 | - "name": "get_weather", "description": "Current weather for a city", | |
| 437 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 438 | - "required": ["city"]}}}, | |
| 439 | - {"type": "function", "function": { | |
| 440 | - "name": "get_time", "description": "Current local time in a city", | |
| 441 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 442 | - "required": ["city"]}}}, | |
| 443 | -] | |
| 444 | -messages = [{"role": "user", "content": "What's the weather and the local time in Tokyo?"}] | |
| 445 | - | |
| 446 | -for parallel in [True, False]: | |
| 447 | - r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | |
| 448 | - tool_choice="required", parallel_tool_calls=parallel) | |
| 449 | - calls = r.choices[0].message.tool_calls or [] | |
| 450 | - print(f"parallel_tool_calls={parallel}: {len(calls)} appel(s)") | |
| 451 | - for call in calls: | |
| 452 | - print(" ", call.id, call.function.name, call.function.arguments) | |
| 453 | -EOF | |
| 454 | -``` | |
| 455 | - | |
| 456 | -- [ ] `parallel_tool_calls=True` : deux appels (`get_weather` et `get_time`), avec des `id` différents. | |
| 457 | -- [ ] `parallel_tool_calls=False` : un seul appel (comportement voulu des appels forcés). | |
| 458 | - | |
| 459 | -### 3.8 Un vrai client agent (optionnel, mais très parlant) | |
| 460 | - | |
| 461 | -Par exemple LangChain : | |
| 462 | - | |
| 463 | -```bash | |
| 464 | -uv run --with langchain-openai python - <<'EOF' | |
| 465 | -from langchain_openai import ChatOpenAI | |
| 466 | -from langchain_core.tools import tool | |
| 467 | - | |
| 468 | -@tool | |
| 469 | -def add(a: int, b: int) -> int: | |
| 470 | - """Add two integers.""" | |
| 471 | - return a + b | |
| 472 | - | |
| 473 | -llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x", model="qwen4b") | |
| 474 | -msg = llm.bind_tools([add]).invoke("What is 1234 + 4321? Use the tool.") | |
| 475 | -print(msg.tool_calls) | |
| 476 | -EOF | |
| 477 | -``` | |
| 478 | - | |
| 479 | -- [ ] `msg.tool_calls` contient un appel `add` avec `{"a": 1234, "b": 4321}`. | |
| 480 | - | |
| 481 | ---- | |
| 482 | - | |
| 483 | -## 4. Embeddings (#42) | |
| 484 | - | |
| 485 | -### 4.1 SDK openai | |
| 486 | - | |
| 487 | -```bash | |
| 488 | -uv run --with openai --with numpy python - <<'EOF' | |
| 489 | -import numpy as np | |
| 490 | -from openai import OpenAI | |
| 491 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 492 | -texts = ["The cat sits on the mat.", "A feline is resting on a rug.", "Stock markets fell sharply today."] | |
| 493 | -for model in ["qembed", "BAAI/bge-small-en-v1.5"]: | |
| 494 | - r = client.embeddings.create(model=model, input=texts) | |
| 495 | - v = np.array([d.embedding for d in r.data]) | |
| 496 | - print(model, v.shape, "usage:", r.usage) | |
| 497 | - print(" cos(chat, félin) =", round(float(v[0] @ v[1]), 4), " cos(chat, bourse) =", round(float(v[0] @ v[2]), 4)) | |
| 498 | -EOF | |
| 499 | -``` | |
| 500 | - | |
| 501 | -- [ ] Forme `(3, 384)` pour les deux noms (alias de config et id Hugging Face). | |
| 502 | -- [ ] cos(chat, félin) ≈ **0,755**, cos(chat, bourse) ≈ **0,324** (valeurs de sentence-transformers). | |
| 503 | -- [ ] `usage.prompt_tokens` > 0. | |
| 504 | - | |
| 505 | -### 4.2 `dimensions` et `encoding_format: base64` | |
| 506 | - | |
| 507 | -```bash | |
| 508 | -curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | |
| 509 | - -d '{"model": "embed", "input": "bonjour", "dimensions": 64}' \ | |
| 510 | - | python3 -c 'import json,sys; e=json.load(sys.stdin)["data"][0]["embedding"]; print(len(e), sum(x*x for x in e))' | |
| 511 | - | |
| 512 | -curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | |
| 513 | - -d '{"model": "embed", "input": "bonjour", "encoding_format": "base64"}' \ | |
| 514 | - | python3 -c 'import json,sys,base64,struct; b=base64.b64decode(json.load(sys.stdin)["data"][0]["embedding"]); print(len(b)//4, struct.unpack("<3f", b[:12]))' | |
| 515 | -``` | |
| 516 | - | |
| 517 | -- [ ] Premier appel : `64` et une norme au carré ≈ `1.0` (vecteur tronqué puis renormalisé). | |
| 518 | -- [ ] Second appel : `384` et trois nombres flottants plausibles (entre -1 et 1). | |
| 519 | -- [ ] `"dimensions": 1000` → **400** qui indique la dimension native (384). | |
| 520 | - | |
| 521 | -> Le SDK openai demande lui-même `base64` par défaut quand on n'impose rien : le test 4.1 couvre | |
| 522 | -> donc déjà ce chemin côté SDK. | |
| 523 | - | |
| 524 | -### 4.3 LangChain `OpenAIEmbeddings` | |
| 525 | - | |
| 526 | -```bash | |
| 527 | -uv run --with langchain-openai python - <<'EOF' | |
| 528 | -from langchain_openai import OpenAIEmbeddings | |
| 529 | -emb = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="x", model="embed", | |
| 530 | - check_embedding_ctx_length=False) | |
| 531 | -v = emb.embed_documents(["hello world", "bonjour le monde"]) | |
| 532 | -print(len(v), len(v[0])) | |
| 533 | -print(len(emb.embed_query("hi"))) | |
| 534 | -EOF | |
| 535 | -``` | |
| 536 | - | |
| 537 | -- [ ] `2 384` puis `384`. | |
| 538 | -- [ ] Sans `check_embedding_ctx_length=False` : **400** « token arrays are not supported yet ». | |
| 539 | - C'est une limite connue (LangChain envoie alors des tokens tiktoken) ; dites-moi si vous | |
| 540 | - voulez qu'elle soit levée. | |
| 541 | - | |
| 542 | -### 4.4 Modèle Matryoshka (optionnel) | |
| 543 | - | |
| 544 | -Ajoutez ce modèle sous `models:` dans `/tmp/rzb-test.yaml`, puis redémarrez le serveur | |
| 545 | -(Ctrl-C, puis `rzb serve --config /tmp/rzb-test.yaml`) : | |
| 546 | - | |
| 547 | -```yaml | |
| 548 | - - id: qembed | |
| 549 | - source: mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ # nom exact à vérifier | |
| 550 | - kind: embedding | |
| 551 | -``` | |
| 552 | - | |
| 553 | -```bash | |
| 554 | -uv run --with openai --with numpy python - <<'EOF' | |
| 555 | -import numpy as np | |
| 556 | -from openai import OpenAI | |
| 557 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 558 | -texts = ["The cat sits on the mat.", "A feline is resting on a rug.", "Stock markets fell sharply today."] | |
| 559 | -for dimensions in [None, 256]: | |
| 560 | - extra = {} if dimensions is None else {"dimensions": dimensions} | |
| 561 | - r = client.embeddings.create(model="qembed", input=texts, **extra) | |
| 562 | - v = np.array([d.embedding for d in r.data]) | |
| 563 | - print(f"dimensions={dimensions}: forme {v.shape}, normes {np.round(np.linalg.norm(v, axis=1), 4)}") | |
| 564 | - print(" cos(chat, félin) =", round(float(v[0] @ v[1]), 4), | |
| 565 | - " cos(chat, bourse) =", round(float(v[0] @ v[2]), 4)) | |
| 566 | -EOF | |
| 567 | -``` | |
| 568 | - | |
| 569 | -- [ ] Le modèle se charge (sinon, notez l'erreur exacte : ce modèle n'a jamais été essayé). | |
| 570 | -- [ ] Forme `(3, 1024)` puis `(3, 256)`, normes ≈ 1. | |
| 571 | -- [ ] cos(chat, félin) > cos(chat, bourse), en pleine dimension comme en 256. | |
| 572 | - | |
| 573 | -### 4.5 Chat et embedding chargés ensemble | |
| 574 | - | |
| 575 | -Avec `max_loaded_models: 2`, en gardant un œil sur les logs du serveur : | |
| 576 | - | |
| 577 | -```bash | |
| 578 | -uv run --with openai python - <<'EOF' | |
| 579 | -import time | |
| 580 | -from openai import OpenAI | |
| 581 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 582 | - | |
| 583 | -def chat(label): | |
| 584 | - start = time.time() | |
| 585 | - r = client.chat.completions.create(model="qwen4b", max_tokens=20, | |
| 586 | - messages=[{"role": "user", "content": "Say hello."}], | |
| 587 | - extra_body={"reasoning_effort": "none"}) | |
| 588 | - print(f"{label:10} {time.time() - start:5.2f} s {r.choices[0].message.content!r}") | |
| 589 | - | |
| 590 | -def embed(label): | |
| 591 | - start = time.time() | |
| 592 | - r = client.embeddings.create(model="embed", input=["hello"]) | |
| 593 | - print(f"{label:10} {time.time() - start:5.2f} s {len(r.data[0].embedding)} dimensions") | |
| 594 | - | |
| 595 | -chat("chat 1") # charge qwen4b si besoin | |
| 596 | -embed("embed") # embed est déjà chargé (preload) | |
| 597 | -chat("chat 2") # doit être immédiat : qwen4b est resté chargé | |
| 598 | -embed("embed 2") | |
| 599 | -EOF | |
| 600 | -``` | |
| 601 | - | |
| 602 | -- [ ] `chat 2` et `embed 2` répondent en une fraction de seconde (pas de rechargement). | |
| 603 | -- [ ] Les logs du serveur ne montrent **aucun** `unloaded` pendant le script. | |
| 604 | - | |
| 605 | -### 4.6 Mauvais type de modèle | |
| 606 | - | |
| 607 | -```bash | |
| 608 | -curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | |
| 609 | - -d '{"model": "qwen4b", "input": "x"}' | |
| 610 | -curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' \ | |
| 611 | - -d '{"model": "embed", "messages": [{"role": "user", "content": "hi"}]}' | |
| 612 | -``` | |
| 613 | - | |
| 614 | -- [ ] Les deux renvoient une erreur JSON claire (400) qui dit que le modèle n'est pas du bon type, | |
| 615 | - sans planter ni charger un modèle pour rien. | |
| 616 | - | |
| 617 | -### 4.7 Texte trop long | |
| 618 | - | |
| 619 | -```bash | |
| 620 | -python3 -c 'import json; print(json.dumps({"model": "embed", "input": ["court", "mot " * 3000]}))' \ | |
| 621 | - | curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' -d @- | |
| 622 | -``` | |
| 623 | - | |
| 624 | -- [ ] **400** qui désigne `input[1]` et la limite du modèle (512 tokens pour bge-small). | |
| 625 | - | |
| 626 | ---- | |
| 627 | - | |
| 628 | -## 5. Limites connues (pas des bugs) | |
| 629 | - | |
| 630 | -- `/v1/models` affiche `"kind": "chat"` pour un modèle d'embedding **non déclaré** présent dans le | |
| 631 | - cache (le cache ne connaît pas le type). Les modèles déclarés avec `kind:` sont justes. | |
| 632 | -- Pas d'option de troncature des textes trop longs : 400 (cf. 4.7). | |
| 633 | -- `input` sous forme de tokens (listes d'entiers) refusé (cf. 4.3). | |
| 634 | -- Les préfixes d'instruction (`search_query:`, `Instruct: …`) sont à ajouter côté client. | |
| 635 | -- Appels d'outils **forcés** (`required`, fonction nommée, outil `strict`) : uniquement pour les | |
| 636 | - modèles à syntaxe `<tool_call>` JSON (Qwen, Hermes). Les autres familles → 400 (cf. 3.5). | |
| 637 | -- Les grammaires sont recompilées à chaque requête (~0,2 s), la version de XGrammar embarquée ne | |
| 638 | - permettant pas de les mettre en cache. | |
| 639 | - | |
| 640 | ---- | |
| 641 | - | |
| 642 | -## Rapport | |
| 643 | - | |
| 644 | -Copiez ce bloc et remplissez-le ; envoyez-moi les lignes en ❌ avec la commande et la sortie. | |
| 645 | - | |
| 646 | -```text | |
| 647 | -0. Préparation : ✅ / ❌ | |
| 648 | -1.1 parse() Pydantic : | |
| 649 | -1.2 + reasoning : | |
| 650 | -1.3 json_object : | |
| 651 | -1.4 json_schema stream : | |
| 652 | -1.5 uniqueItems → 400 : | |
| 653 | -2. débits (tok/s) : libre=… json_object=… json_schema=… | |
| 654 | -3.1 outils auto Qwen : | |
| 655 | -3.2 outils en stream : | |
| 656 | -3.3 outils auto Llama : | |
| 657 | -3.4 forcés Qwen : | |
| 658 | -3.5 forcé Llama → 400 : | |
| 659 | -3.6 tool_choice none : | |
| 660 | -3.7 parallèles : | |
| 661 | -3.8 LangChain agent : | |
| 662 | -4.1 embeddings SDK : cos=… | |
| 663 | -4.2 dimensions/base64 : | |
| 664 | -4.3 LangChain embed : | |
| 665 | -4.4 Matryoshka : | |
| 666 | -4.5 chat + embed : | |
| 667 | -4.6 mauvais type : | |
| 668 | -4.7 texte trop long : | |
| 669 | -``` | |
| deleted file mode 100644 | |||
| @@ -1,669 +0,0 @@ | |||
| 1 | -# Plan de test manuel — rzb serve v0.2 (#38 → #42) | ||
| 2 | - | ||
| 3 | -Ce document liste ce qu'il reste à vérifier **à la main, sur le Mac**, après les tickets #38 à #42 | ||
| 4 | -(sorties structurées, appels d'outils, embeddings). Les tests automatiques passent déjà (Linux 144, | ||
| 5 | -Mac 167) : ici, on vérifie ce qu'ils ne couvrent pas — de vrais clients, de plus gros modèles, | ||
| 6 | -d'autres familles de modèles, et la vitesse en Release. | ||
| 7 | - | ||
| 8 | -Chaque test a : la commande à lancer, **le résultat attendu**, et une case à cocher. Notez ce qui | ||
| 9 | -échoue (commande + sortie) dans la section [Rapport](#rapport) à la fin. | ||
| 10 | - | ||
| 11 | -Durée estimée : 1 h à 1 h 30, dont l'essentiel en téléchargements de modèles. | ||
| 12 | - | ||
| 13 | ---- | ||
| 14 | - | ||
| 15 | -## 0. Préparation | ||
| 16 | - | ||
| 17 | -### 0.1 Compiler en Release | ||
| 18 | - | ||
| 19 | -```bash | ||
| 20 | -cd ~/kDrive/Rickub/bots-garden/razorbill | ||
| 21 | -xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \ | ||
| 22 | - -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation | ||
| 23 | -alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb" | ||
| 24 | -rzb version | ||
| 25 | -``` | ||
| 26 | - | ||
| 27 | -- [ ] `rzb version` affiche la version et `engines: mlx`. | ||
| 28 | - | ||
| 29 | -### 0.2 Télécharger les modèles | ||
| 30 | - | ||
| 31 | -```bash | ||
| 32 | -rzb models pull mlx-community/Qwen3-4B-4bit # ~2,3 Go — chat, outils, JSON | ||
| 33 | -rzb models pull mlx-community/Llama-3.2-3B-Instruct-4bit # ~1,8 Go — 2e famille d'outils | ||
| 34 | -rzb models pull BAAI/bge-small-en-v1.5 # déjà en cache normalement | ||
| 35 | -rzb models list | ||
| 36 | -``` | ||
| 37 | - | ||
| 38 | -Optionnel (test Matryoshka, §4.4) : un modèle d'embedding Qwen3 au format MLX, par exemple | ||
| 39 | -`mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ` (vérifiez le nom exact sur Hugging Face). | ||
| 40 | - | ||
| 41 | -### 0.3 Configuration de test | ||
| 42 | - | ||
| 43 | -Enregistrez ceci dans `/tmp/rzb-test.yaml` : | ||
| 44 | - | ||
| 45 | -```yaml | ||
| 46 | -server: | ||
| 47 | - host: 127.0.0.1 | ||
| 48 | - port: 8080 | ||
| 49 | - | ||
| 50 | -models: | ||
| 51 | - - id: qwen4b | ||
| 52 | - source: mlx-community/Qwen3-4B-4bit | ||
| 53 | - kind: chat | ||
| 54 | - - id: llama3b | ||
| 55 | - source: mlx-community/Llama-3.2-3B-Instruct-4bit | ||
| 56 | - kind: chat | ||
| 57 | - - id: embed | ||
| 58 | - source: BAAI/bge-small-en-v1.5 | ||
| 59 | - kind: embedding | ||
| 60 | - preload: true | ||
| 61 | - | ||
| 62 | -limits: | ||
| 63 | - max_loaded_models: 2 | ||
| 64 | - keep_alive: 10m | ||
| 65 | -``` | ||
| 66 | - | ||
| 67 | -```bash | ||
| 68 | -rzb config validate /tmp/rzb-test.yaml | ||
| 69 | -rzb serve --config /tmp/rzb-test.yaml | ||
| 70 | -``` | ||
| 71 | - | ||
| 72 | -- [ ] `config validate` ne signale aucune erreur. | ||
| 73 | -- [ ] Le serveur démarre, affiche `serving http://127.0.0.1:8080`, et le log indique que `embed` | ||
| 74 | - est chargé au démarrage (`preload: true`). | ||
| 75 | - | ||
| 76 | -Laissez ce terminal ouvert (les logs serviront) et ouvrez-en un second pour la suite. | ||
| 77 | - | ||
| 78 | -> Pas de clé d'API dans cette config : les clients peuvent envoyer n'importe quelle valeur | ||
| 79 | -> (`api_key="x"`). Si `RZB_API_KEY` est définie dans votre shell **et** déclarée via | ||
| 80 | -> `api_key_env`, utilisez sa valeur. | ||
| 81 | - | ||
| 82 | -### 0.4 Outils côté client | ||
| 83 | - | ||
| 84 | -Les exemples Python utilisent `uv` (pas d'environnement à créer) : | ||
| 85 | - | ||
| 86 | -```bash | ||
| 87 | -uv --version # sinon : brew install uv | ||
| 88 | -``` | ||
| 89 | - | ||
| 90 | -### 0.5 Premier contact | ||
| 91 | - | ||
| 92 | -```bash | ||
| 93 | -curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool | ||
| 94 | -``` | ||
| 95 | - | ||
| 96 | -- [ ] La liste contient `qwen4b`, `llama3b` (`"kind": "chat"`) et `embed` (`"kind": "embedding"`), | ||
| 97 | - plus les modèles du cache. | ||
| 98 | - | ||
| 99 | ---- | ||
| 100 | - | ||
| 101 | -## 1. Sorties structurées — `response_format` (#39) | ||
| 102 | - | ||
| 103 | -### 1.1 `parse()` du SDK openai avec une classe Pydantic — **critère d'acceptation de #39** | ||
| 104 | - | ||
| 105 | -```bash | ||
| 106 | -uv run --with openai --with pydantic python - <<'EOF' | ||
| 107 | -from openai import OpenAI | ||
| 108 | -from pydantic import BaseModel | ||
| 109 | - | ||
| 110 | -class City(BaseModel): | ||
| 111 | - name: str | ||
| 112 | - country: str | ||
| 113 | - population: int | ||
| 114 | - landmarks: list[str] | ||
| 115 | - | ||
| 116 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 117 | -completion = client.beta.chat.completions.parse( | ||
| 118 | - model="qwen4b", | ||
| 119 | - messages=[{"role": "user", "content": "Describe Lyon, France."}], | ||
| 120 | - response_format=City, | ||
| 121 | - extra_body={"reasoning_effort": "high"}, | ||
| 122 | -) | ||
| 123 | -message = completion.choices[0].message | ||
| 124 | -print("parsed :", message.parsed) | ||
| 125 | -print("raison :", (getattr(message, "reasoning_content", None) or "")[:200]) | ||
| 126 | -EOF | ||
| 127 | -``` | ||
| 128 | - | ||
| 129 | -- [ ] `parsed` est un objet `City` rempli (pas `None`), sans exception de validation. | ||
| 130 | -- [ ] Recommencez 3 fois : toujours un JSON valide. | ||
| 131 | - | ||
| 132 | -> Selon la version du SDK, `client.chat.completions.parse(...)` (sans `beta`) existe aussi : | ||
| 133 | -> testez celle que vous avez. | ||
| 134 | - | ||
| 135 | -### 1.2 Avec réflexion activée | ||
| 136 | - | ||
| 137 | -```bash | ||
| 138 | -uv run --with openai --with pydantic python - <<'EOF' | ||
| 139 | -from openai import OpenAI | ||
| 140 | -from pydantic import BaseModel | ||
| 141 | - | ||
| 142 | -class City(BaseModel): | ||
| 143 | - name: str | ||
| 144 | - country: str | ||
| 145 | - population: int | ||
| 146 | - landmarks: list[str] | ||
| 147 | - | ||
| 148 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 149 | -completion = client.beta.chat.completions.parse( | ||
| 150 | - model="qwen4b", | ||
| 151 | - messages=[{"role": "user", "content": "Describe Lyon, France."}], | ||
| 152 | - response_format=City, | ||
| 153 | - extra_body={"reasoning_effort": "high"}, | ||
| 154 | -) | ||
| 155 | -message = completion.choices[0].message | ||
| 156 | -print("parsed :", message.parsed) | ||
| 157 | -print("raison :", (getattr(message, "reasoning_content", None) or "")[:500]) | ||
| 158 | -EOF | ||
| 159 | -``` | ||
| 160 | - | ||
| 161 | -- [ ] `reasoning_content` contient la réflexion (texte libre, pas du JSON). | ||
| 162 | -- [ ] `parsed` reste un objet `City` valide : la contrainte ne s'applique qu'après `</think>`. | ||
| 163 | - | ||
| 164 | -### 1.3 `json_object` avec curl | ||
| 165 | - | ||
| 166 | -```bash | ||
| 167 | -curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | ||
| 168 | - "model": "qwen4b", | ||
| 169 | - "messages": [{"role": "user", "content": "Give me 3 French cheeses with their region, as JSON."}], | ||
| 170 | - "response_format": {"type": "json_object"}, | ||
| 171 | - "reasoning_effort": "none" | ||
| 172 | -}' | python3 -c 'import json,sys; c=json.load(sys.stdin)["choices"][0]["message"]["content"]; print(json.dumps(json.loads(c), indent=2, ensure_ascii=False))' | ||
| 173 | -``` | ||
| 174 | - | ||
| 175 | -- [ ] La commande affiche un objet JSON (le `json.loads` ne lève pas d'erreur). | ||
| 176 | - | ||
| 177 | -### 1.4 Streaming d'un `json_schema` | ||
| 178 | - | ||
| 179 | -```bash | ||
| 180 | -curl -sN http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | ||
| 181 | - "model": "qwen4b", "stream": true, "reasoning_effort": "none", | ||
| 182 | - "messages": [{"role": "user", "content": "List 5 planets with their diameter in km."}], | ||
| 183 | - "response_format": {"type": "json_schema", "json_schema": {"name": "planets", "strict": true, | ||
| 184 | - "schema": {"type": "object", "additionalProperties": false, "required": ["planets"], | ||
| 185 | - "properties": {"planets": {"type": "array", "items": {"type": "object", | ||
| 186 | - "additionalProperties": false, "required": ["name", "diameter_km"], | ||
| 187 | - "properties": {"name": {"type": "string"}, "diameter_km": {"type": "number"}}}}}}}} | ||
| 188 | -}' | ||
| 189 | -``` | ||
| 190 | - | ||
| 191 | -- [ ] Les lignes `data: {...}` arrivent **au fil de l'eau**, chacune avec un petit morceau de JSON | ||
| 192 | - dans `delta.content` (pas un seul bloc à la fin). | ||
| 193 | -- [ ] Le flux se termine par `finish_reason: "stop"` puis `data: [DONE]`. | ||
| 194 | -- [ ] En recollant les `content`, on obtient un JSON qui respecte le schéma. | ||
| 195 | - | ||
| 196 | -### 1.5 Schéma strict avec un mot-clé non appliqué → 400 | ||
| 197 | - | ||
| 198 | -```bash | ||
| 199 | -curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | ||
| 200 | - "model": "qwen4b", | ||
| 201 | - "messages": [{"role": "user", "content": "3 tags"}], | ||
| 202 | - "response_format": {"type": "json_schema", "json_schema": {"name": "tags", "strict": true, | ||
| 203 | - "schema": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}}} | ||
| 204 | -}' | ||
| 205 | -``` | ||
| 206 | - | ||
| 207 | -- [ ] Réponse **400** `{"error": {...}}` dont le message nomme `uniqueItems`. | ||
| 208 | -- [ ] Le même appel avec `"strict": false` est accepté (le mot-clé est simplement ignoré). | ||
| 209 | - | ||
| 210 | ---- | ||
| 211 | - | ||
| 212 | -## 2. Vitesse du décodage contraint (Release) | ||
| 213 | - | ||
| 214 | -Mes mesures (build **Debug**, Qwen3-0.6B) : ~90 tok/s en libre, ~49 tok/s sous contrainte. Le | ||
| 215 | -serveur ne logue pas les tok/s : ce script les calcule à partir de `usage`. | ||
| 216 | - | ||
| 217 | -```bash | ||
| 218 | -uv run --with openai python - <<'EOF' | ||
| 219 | -import time | ||
| 220 | -from openai import OpenAI | ||
| 221 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 222 | -prompt = [{"role": "user", "content": "Describe 10 European capitals: name, country, population, one fact each."}] | ||
| 223 | -schema = {"type": "json_schema", "json_schema": {"name": "capitals", "schema": { | ||
| 224 | - "type": "object", "properties": {"capitals": {"type": "array", "items": {"type": "object", | ||
| 225 | - "properties": {"name": {"type": "string"}, "country": {"type": "string"}, | ||
| 226 | - "population": {"type": "integer"}, "fact": {"type": "string"}}, | ||
| 227 | - "required": ["name", "country", "population", "fact"]}}}, "required": ["capitals"]}}} | ||
| 228 | -client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=5) # chauffe | ||
| 229 | -for label, extra in [("libre", {}), ("json_object", {"response_format": {"type": "json_object"}}), | ||
| 230 | - ("json_schema", {"response_format": schema})]: | ||
| 231 | - start = time.time() | ||
| 232 | - r = client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=800, | ||
| 233 | - extra_body={"reasoning_effort": "none"}, **extra) | ||
| 234 | - elapsed = time.time() - start | ||
| 235 | - n = r.usage.completion_tokens | ||
| 236 | - print(f"{label:12} {n:4} tokens {elapsed:5.1f} s {n / elapsed:5.1f} tok/s") | ||
| 237 | -EOF | ||
| 238 | -``` | ||
| 239 | - | ||
| 240 | -- [ ] Notez les trois débits dans le rapport. **Attendu** : le contraint reste dans le même ordre | ||
| 241 | - de grandeur que le libre (au pire ~2× plus lent). Un écart de 5× ou plus est un problème. | ||
| 242 | -- [ ] Optionnel : relancez avec `model="mlx-community/Qwen3-0.6B-4bit"` pour comparer à mes chiffres Debug. | ||
| 243 | - | ||
| 244 | ---- | ||
| 245 | - | ||
| 246 | -## 3. Appels d'outils (#40, #41) | ||
| 247 | - | ||
| 248 | -### 3.1 Aller-retour complet en `auto` avec Qwen3-4B | ||
| 249 | - | ||
| 250 | -```bash | ||
| 251 | -uv run --with openai python - <<'EOF' | ||
| 252 | -import json | ||
| 253 | -from openai import OpenAI | ||
| 254 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 255 | -MODEL = "qwen4b" | ||
| 256 | -tools = [{"type": "function", "function": { | ||
| 257 | - "name": "get_weather", "description": "Current weather for a city", | ||
| 258 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 259 | - "required": ["city"]}}}] | ||
| 260 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | ||
| 261 | - | ||
| 262 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | ||
| 263 | -msg = r.choices[0].message | ||
| 264 | -print("1) finish_reason:", r.choices[0].finish_reason) | ||
| 265 | -print(" tool_calls :", msg.tool_calls) | ||
| 266 | -assert msg.tool_calls, "aucun appel d'outil" | ||
| 267 | - | ||
| 268 | -messages.append(msg.model_dump(exclude_none=True)) | ||
| 269 | -for call in msg.tool_calls: | ||
| 270 | - args = json.loads(call.function.arguments) | ||
| 271 | - messages.append({"role": "tool", "tool_call_id": call.id, | ||
| 272 | - "content": json.dumps({"city": args["city"], "temp_c": 7, "sky": "rain"})}) | ||
| 273 | - | ||
| 274 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | ||
| 275 | -print("2) réponse finale:", r.choices[0].message.content) | ||
| 276 | -EOF | ||
| 277 | -``` | ||
| 278 | - | ||
| 279 | -- [ ] Étape 1 : `finish_reason` vaut `tool_calls`, avec un appel `get_weather` dont les | ||
| 280 | - `arguments` sont un JSON valide (`{"city": "Lyon"}`). | ||
| 281 | -- [ ] Étape 2 : la réponse finale parle de 7 °C et de pluie à Lyon. | ||
| 282 | - | ||
| 283 | -### 3.2 Appel d'outil en streaming | ||
| 284 | - | ||
| 285 | -```bash | ||
| 286 | -uv run --with openai python - <<'EOF' | ||
| 287 | -from openai import OpenAI | ||
| 288 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 289 | -MODEL = "qwen4b" | ||
| 290 | -tools = [{"type": "function", "function": { | ||
| 291 | - "name": "get_weather", "description": "Current weather for a city", | ||
| 292 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 293 | - "required": ["city"]}}}] | ||
| 294 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | ||
| 295 | - | ||
| 296 | -stream = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, stream=True) | ||
| 297 | -for chunk in stream: | ||
| 298 | - if chunk.choices: | ||
| 299 | - choice = chunk.choices[0] | ||
| 300 | - print(choice.delta.model_dump(exclude_none=True), "| finish:", choice.finish_reason) | ||
| 301 | -EOF | ||
| 302 | -``` | ||
| 303 | - | ||
| 304 | -- [ ] Un delta contient `tool_calls` avec `index: 0`, un `id`, `type: "function"` et le nom et les | ||
| 305 | - arguments ; le dernier chunk a `finish: tool_calls`. | ||
| 306 | - | ||
| 307 | -### 3.3 Deuxième famille (Llama 3.2) en `auto` — **critère de #40, non vérifié** | ||
| 308 | - | ||
| 309 | -```bash | ||
| 310 | -uv run --with openai python - <<'EOF' | ||
| 311 | -import json | ||
| 312 | -from openai import OpenAI | ||
| 313 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 314 | -MODEL = "llama3b" | ||
| 315 | -tools = [{"type": "function", "function": { | ||
| 316 | - "name": "get_weather", "description": "Current weather for a city", | ||
| 317 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 318 | - "required": ["city"]}}}] | ||
| 319 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | ||
| 320 | - | ||
| 321 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | ||
| 322 | -msg = r.choices[0].message | ||
| 323 | -print("1) finish_reason:", r.choices[0].finish_reason) | ||
| 324 | -print(" tool_calls :", msg.tool_calls) | ||
| 325 | -print(" content :", msg.content) | ||
| 326 | -assert msg.tool_calls, "aucun appel d'outil" | ||
| 327 | - | ||
| 328 | -messages.append(msg.model_dump(exclude_none=True)) | ||
| 329 | -for call in msg.tool_calls: | ||
| 330 | - args = json.loads(call.function.arguments) | ||
| 331 | - messages.append({"role": "tool", "tool_call_id": call.id, | ||
| 332 | - "content": json.dumps({"city": args["city"], "temp_c": 7, "sky": "rain"})}) | ||
| 333 | - | ||
| 334 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | ||
| 335 | -print("2) réponse finale:", r.choices[0].message.content) | ||
| 336 | -EOF | ||
| 337 | -``` | ||
| 338 | - | ||
| 339 | -- [ ] `tool_calls` est rempli correctement (nom + arguments JSON), **pas** du texte brut du genre | ||
| 340 | - `{"name": "get_weather", ...}` dans `content`. | ||
| 341 | -- [ ] La réponse finale utilise le résultat de l'outil. | ||
| 342 | - | ||
| 343 | -Si vous avez un Mistral au format MLX (ex. `mlx-community/Mistral-7B-Instruct-v0.3-4bit`), relancez | ||
| 344 | -ce script en remplaçant `MODEL = "llama3b"` par l'id du modèle. | ||
| 345 | - | ||
| 346 | -### 3.4 Appels forcés sur Qwen : `required` et fonction nommée | ||
| 347 | - | ||
| 348 | -La question n'a **rien à voir** avec la météo : seule la grammaire peut produire l'appel. | ||
| 349 | - | ||
| 350 | -```bash | ||
| 351 | -uv run --with openai python - <<'EOF' | ||
| 352 | -from openai import OpenAI | ||
| 353 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 354 | -MODEL = "qwen4b" | ||
| 355 | -tools = [{"type": "function", "function": { | ||
| 356 | - "name": "get_weather", "description": "Current weather for a city", | ||
| 357 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 358 | - "required": ["city"]}}}] | ||
| 359 | -messages = [{"role": "user", "content": "Tell me a joke."}] | ||
| 360 | - | ||
| 361 | -for label, choice in [("required", "required"), | ||
| 362 | - ("nommée", {"type": "function", "function": {"name": "get_weather"}})]: | ||
| 363 | - r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | ||
| 364 | - tool_choice=choice) | ||
| 365 | - calls = r.choices[0].message.tool_calls or [] | ||
| 366 | - print(f"{label:9} finish={r.choices[0].finish_reason} {len(calls)} appel(s)") | ||
| 367 | - for call in calls: | ||
| 368 | - print(" ", call.function.name, call.function.arguments) | ||
| 369 | -EOF | ||
| 370 | -``` | ||
| 371 | - | ||
| 372 | -- [ ] Pour `required` comme pour la fonction nommée : `finish=tool_calls` et **exactement un** | ||
| 373 | - appel `get_weather` avec des arguments JSON valides. | ||
| 374 | - | ||
| 375 | -### 3.5 Appel forcé sur Llama → 400 attendu | ||
| 376 | - | ||
| 377 | -```bash | ||
| 378 | -uv run --with openai python - <<'EOF' | ||
| 379 | -import openai | ||
| 380 | -from openai import OpenAI | ||
| 381 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 382 | -MODEL = "llama3b" | ||
| 383 | -tools = [{"type": "function", "function": { | ||
| 384 | - "name": "get_weather", "description": "Current weather for a city", | ||
| 385 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 386 | - "required": ["city"]}}}] | ||
| 387 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | ||
| 388 | - | ||
| 389 | -for choice in ["required", "auto"]: | ||
| 390 | - try: | ||
| 391 | - r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | ||
| 392 | - tool_choice=choice) | ||
| 393 | - print(f"{choice:8} OK finish={r.choices[0].finish_reason}", | ||
| 394 | - r.choices[0].message.tool_calls) | ||
| 395 | - except openai.BadRequestError as error: | ||
| 396 | - print(f"{choice:8} 400 ", error.body) | ||
| 397 | -EOF | ||
| 398 | -``` | ||
| 399 | - | ||
| 400 | -- [ ] `required` : **400** avec un message expliquant que la syntaxe d'appel de ce modèle ne permet | ||
| 401 | - pas de forcer un outil. C'est le comportement voulu. | ||
| 402 | -- [ ] `auto` : OK, avec un appel `get_weather` (cf. 3.3). | ||
| 403 | - | ||
| 404 | -### 3.6 `tool_choice: "none"` | ||
| 405 | - | ||
| 406 | -```bash | ||
| 407 | -uv run --with openai python - <<'EOF' | ||
| 408 | -from openai import OpenAI | ||
| 409 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 410 | -MODEL = "qwen4b" | ||
| 411 | -tools = [{"type": "function", "function": { | ||
| 412 | - "name": "get_weather", "description": "Current weather for a city", | ||
| 413 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 414 | - "required": ["city"]}}}] | ||
| 415 | -messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | ||
| 416 | - | ||
| 417 | -r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, tool_choice="none") | ||
| 418 | -msg = r.choices[0].message | ||
| 419 | -print("finish_reason:", r.choices[0].finish_reason) | ||
| 420 | -print("tool_calls :", msg.tool_calls) | ||
| 421 | -print("content :", msg.content) | ||
| 422 | -EOF | ||
| 423 | -``` | ||
| 424 | - | ||
| 425 | -- [ ] `finish_reason: stop`, `tool_calls: None`, et une réponse en texte. | ||
| 426 | - | ||
| 427 | -### 3.7 Appels parallèles | ||
| 428 | - | ||
| 429 | -```bash | ||
| 430 | -uv run --with openai python - <<'EOF' | ||
| 431 | -from openai import OpenAI | ||
| 432 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 433 | -MODEL = "qwen4b" | ||
| 434 | -tools = [ | ||
| 435 | - {"type": "function", "function": { | ||
| 436 | - "name": "get_weather", "description": "Current weather for a city", | ||
| 437 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 438 | - "required": ["city"]}}}, | ||
| 439 | - {"type": "function", "function": { | ||
| 440 | - "name": "get_time", "description": "Current local time in a city", | ||
| 441 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 442 | - "required": ["city"]}}}, | ||
| 443 | -] | ||
| 444 | -messages = [{"role": "user", "content": "What's the weather and the local time in Tokyo?"}] | ||
| 445 | - | ||
| 446 | -for parallel in [True, False]: | ||
| 447 | - r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | ||
| 448 | - tool_choice="required", parallel_tool_calls=parallel) | ||
| 449 | - calls = r.choices[0].message.tool_calls or [] | ||
| 450 | - print(f"parallel_tool_calls={parallel}: {len(calls)} appel(s)") | ||
| 451 | - for call in calls: | ||
| 452 | - print(" ", call.id, call.function.name, call.function.arguments) | ||
| 453 | -EOF | ||
| 454 | -``` | ||
| 455 | - | ||
| 456 | -- [ ] `parallel_tool_calls=True` : deux appels (`get_weather` et `get_time`), avec des `id` différents. | ||
| 457 | -- [ ] `parallel_tool_calls=False` : un seul appel (comportement voulu des appels forcés). | ||
| 458 | - | ||
| 459 | -### 3.8 Un vrai client agent (optionnel, mais très parlant) | ||
| 460 | - | ||
| 461 | -Par exemple LangChain : | ||
| 462 | - | ||
| 463 | -```bash | ||
| 464 | -uv run --with langchain-openai python - <<'EOF' | ||
| 465 | -from langchain_openai import ChatOpenAI | ||
| 466 | -from langchain_core.tools import tool | ||
| 467 | - | ||
| 468 | -@tool | ||
| 469 | -def add(a: int, b: int) -> int: | ||
| 470 | - """Add two integers.""" | ||
| 471 | - return a + b | ||
| 472 | - | ||
| 473 | -llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x", model="qwen4b") | ||
| 474 | -msg = llm.bind_tools([add]).invoke("What is 1234 + 4321? Use the tool.") | ||
| 475 | -print(msg.tool_calls) | ||
| 476 | -EOF | ||
| 477 | -``` | ||
| 478 | - | ||
| 479 | -- [ ] `msg.tool_calls` contient un appel `add` avec `{"a": 1234, "b": 4321}`. | ||
| 480 | - | ||
| 481 | ---- | ||
| 482 | - | ||
| 483 | -## 4. Embeddings (#42) | ||
| 484 | - | ||
| 485 | -### 4.1 SDK openai | ||
| 486 | - | ||
| 487 | -```bash | ||
| 488 | -uv run --with openai --with numpy python - <<'EOF' | ||
| 489 | -import numpy as np | ||
| 490 | -from openai import OpenAI | ||
| 491 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 492 | -texts = ["The cat sits on the mat.", "A feline is resting on a rug.", "Stock markets fell sharply today."] | ||
| 493 | -for model in ["qembed", "BAAI/bge-small-en-v1.5"]: | ||
| 494 | - r = client.embeddings.create(model=model, input=texts) | ||
| 495 | - v = np.array([d.embedding for d in r.data]) | ||
| 496 | - print(model, v.shape, "usage:", r.usage) | ||
| 497 | - print(" cos(chat, félin) =", round(float(v[0] @ v[1]), 4), " cos(chat, bourse) =", round(float(v[0] @ v[2]), 4)) | ||
| 498 | -EOF | ||
| 499 | -``` | ||
| 500 | - | ||
| 501 | -- [ ] Forme `(3, 384)` pour les deux noms (alias de config et id Hugging Face). | ||
| 502 | -- [ ] cos(chat, félin) ≈ **0,755**, cos(chat, bourse) ≈ **0,324** (valeurs de sentence-transformers). | ||
| 503 | -- [ ] `usage.prompt_tokens` > 0. | ||
| 504 | - | ||
| 505 | -### 4.2 `dimensions` et `encoding_format: base64` | ||
| 506 | - | ||
| 507 | -```bash | ||
| 508 | -curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | ||
| 509 | - -d '{"model": "embed", "input": "bonjour", "dimensions": 64}' \ | ||
| 510 | - | python3 -c 'import json,sys; e=json.load(sys.stdin)["data"][0]["embedding"]; print(len(e), sum(x*x for x in e))' | ||
| 511 | - | ||
| 512 | -curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | ||
| 513 | - -d '{"model": "embed", "input": "bonjour", "encoding_format": "base64"}' \ | ||
| 514 | - | python3 -c 'import json,sys,base64,struct; b=base64.b64decode(json.load(sys.stdin)["data"][0]["embedding"]); print(len(b)//4, struct.unpack("<3f", b[:12]))' | ||
| 515 | -``` | ||
| 516 | - | ||
| 517 | -- [ ] Premier appel : `64` et une norme au carré ≈ `1.0` (vecteur tronqué puis renormalisé). | ||
| 518 | -- [ ] Second appel : `384` et trois nombres flottants plausibles (entre -1 et 1). | ||
| 519 | -- [ ] `"dimensions": 1000` → **400** qui indique la dimension native (384). | ||
| 520 | - | ||
| 521 | -> Le SDK openai demande lui-même `base64` par défaut quand on n'impose rien : le test 4.1 couvre | ||
| 522 | -> donc déjà ce chemin côté SDK. | ||
| 523 | - | ||
| 524 | -### 4.3 LangChain `OpenAIEmbeddings` | ||
| 525 | - | ||
| 526 | -```bash | ||
| 527 | -uv run --with langchain-openai python - <<'EOF' | ||
| 528 | -from langchain_openai import OpenAIEmbeddings | ||
| 529 | -emb = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="x", model="embed", | ||
| 530 | - check_embedding_ctx_length=False) | ||
| 531 | -v = emb.embed_documents(["hello world", "bonjour le monde"]) | ||
| 532 | -print(len(v), len(v[0])) | ||
| 533 | -print(len(emb.embed_query("hi"))) | ||
| 534 | -EOF | ||
| 535 | -``` | ||
| 536 | - | ||
| 537 | -- [ ] `2 384` puis `384`. | ||
| 538 | -- [ ] Sans `check_embedding_ctx_length=False` : **400** « token arrays are not supported yet ». | ||
| 539 | - C'est une limite connue (LangChain envoie alors des tokens tiktoken) ; dites-moi si vous | ||
| 540 | - voulez qu'elle soit levée. | ||
| 541 | - | ||
| 542 | -### 4.4 Modèle Matryoshka (optionnel) | ||
| 543 | - | ||
| 544 | -Ajoutez ce modèle sous `models:` dans `/tmp/rzb-test.yaml`, puis redémarrez le serveur | ||
| 545 | -(Ctrl-C, puis `rzb serve --config /tmp/rzb-test.yaml`) : | ||
| 546 | - | ||
| 547 | -```yaml | ||
| 548 | - - id: qembed | ||
| 549 | - source: mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ # nom exact à vérifier | ||
| 550 | - kind: embedding | ||
| 551 | -``` | ||
| 552 | - | ||
| 553 | -```bash | ||
| 554 | -uv run --with openai --with numpy python - <<'EOF' | ||
| 555 | -import numpy as np | ||
| 556 | -from openai import OpenAI | ||
| 557 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 558 | -texts = ["The cat sits on the mat.", "A feline is resting on a rug.", "Stock markets fell sharply today."] | ||
| 559 | -for dimensions in [None, 256]: | ||
| 560 | - extra = {} if dimensions is None else {"dimensions": dimensions} | ||
| 561 | - r = client.embeddings.create(model="qembed", input=texts, **extra) | ||
| 562 | - v = np.array([d.embedding for d in r.data]) | ||
| 563 | - print(f"dimensions={dimensions}: forme {v.shape}, normes {np.round(np.linalg.norm(v, axis=1), 4)}") | ||
| 564 | - print(" cos(chat, félin) =", round(float(v[0] @ v[1]), 4), | ||
| 565 | - " cos(chat, bourse) =", round(float(v[0] @ v[2]), 4)) | ||
| 566 | -EOF | ||
| 567 | -``` | ||
| 568 | - | ||
| 569 | -- [ ] Le modèle se charge (sinon, notez l'erreur exacte : ce modèle n'a jamais été essayé). | ||
| 570 | -- [ ] Forme `(3, 1024)` puis `(3, 256)`, normes ≈ 1. | ||
| 571 | -- [ ] cos(chat, félin) > cos(chat, bourse), en pleine dimension comme en 256. | ||
| 572 | - | ||
| 573 | -### 4.5 Chat et embedding chargés ensemble | ||
| 574 | - | ||
| 575 | -Avec `max_loaded_models: 2`, en gardant un œil sur les logs du serveur : | ||
| 576 | - | ||
| 577 | -```bash | ||
| 578 | -uv run --with openai python - <<'EOF' | ||
| 579 | -import time | ||
| 580 | -from openai import OpenAI | ||
| 581 | -client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 582 | - | ||
| 583 | -def chat(label): | ||
| 584 | - start = time.time() | ||
| 585 | - r = client.chat.completions.create(model="qwen4b", max_tokens=20, | ||
| 586 | - messages=[{"role": "user", "content": "Say hello."}], | ||
| 587 | - extra_body={"reasoning_effort": "none"}) | ||
| 588 | - print(f"{label:10} {time.time() - start:5.2f} s {r.choices[0].message.content!r}") | ||
| 589 | - | ||
| 590 | -def embed(label): | ||
| 591 | - start = time.time() | ||
| 592 | - r = client.embeddings.create(model="embed", input=["hello"]) | ||
| 593 | - print(f"{label:10} {time.time() - start:5.2f} s {len(r.data[0].embedding)} dimensions") | ||
| 594 | - | ||
| 595 | -chat("chat 1") # charge qwen4b si besoin | ||
| 596 | -embed("embed") # embed est déjà chargé (preload) | ||
| 597 | -chat("chat 2") # doit être immédiat : qwen4b est resté chargé | ||
| 598 | -embed("embed 2") | ||
| 599 | -EOF | ||
| 600 | -``` | ||
| 601 | - | ||
| 602 | -- [ ] `chat 2` et `embed 2` répondent en une fraction de seconde (pas de rechargement). | ||
| 603 | -- [ ] Les logs du serveur ne montrent **aucun** `unloaded` pendant le script. | ||
| 604 | - | ||
| 605 | -### 4.6 Mauvais type de modèle | ||
| 606 | - | ||
| 607 | -```bash | ||
| 608 | -curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | ||
| 609 | - -d '{"model": "qwen4b", "input": "x"}' | ||
| 610 | -curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' \ | ||
| 611 | - -d '{"model": "embed", "messages": [{"role": "user", "content": "hi"}]}' | ||
| 612 | -``` | ||
| 613 | - | ||
| 614 | -- [ ] Les deux renvoient une erreur JSON claire (400) qui dit que le modèle n'est pas du bon type, | ||
| 615 | - sans planter ni charger un modèle pour rien. | ||
| 616 | - | ||
| 617 | -### 4.7 Texte trop long | ||
| 618 | - | ||
| 619 | -```bash | ||
| 620 | -python3 -c 'import json; print(json.dumps({"model": "embed", "input": ["court", "mot " * 3000]}))' \ | ||
| 621 | - | curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' -d @- | ||
| 622 | -``` | ||
| 623 | - | ||
| 624 | -- [ ] **400** qui désigne `input[1]` et la limite du modèle (512 tokens pour bge-small). | ||
| 625 | - | ||
| 626 | ---- | ||
| 627 | - | ||
| 628 | -## 5. Limites connues (pas des bugs) | ||
| 629 | - | ||
| 630 | -- `/v1/models` affiche `"kind": "chat"` pour un modèle d'embedding **non déclaré** présent dans le | ||
| 631 | - cache (le cache ne connaît pas le type). Les modèles déclarés avec `kind:` sont justes. | ||
| 632 | -- Pas d'option de troncature des textes trop longs : 400 (cf. 4.7). | ||
| 633 | -- `input` sous forme de tokens (listes d'entiers) refusé (cf. 4.3). | ||
| 634 | -- Les préfixes d'instruction (`search_query:`, `Instruct: …`) sont à ajouter côté client. | ||
| 635 | -- Appels d'outils **forcés** (`required`, fonction nommée, outil `strict`) : uniquement pour les | ||
| 636 | - modèles à syntaxe `<tool_call>` JSON (Qwen, Hermes). Les autres familles → 400 (cf. 3.5). | ||
| 637 | -- Les grammaires sont recompilées à chaque requête (~0,2 s), la version de XGrammar embarquée ne | ||
| 638 | - permettant pas de les mettre en cache. | ||
| 639 | - | ||
| 640 | ---- | ||
| 641 | - | ||
| 642 | -## Rapport | ||
| 643 | - | ||
| 644 | -Copiez ce bloc et remplissez-le ; envoyez-moi les lignes en ❌ avec la commande et la sortie. | ||
| 645 | - | ||
| 646 | -```text | ||
| 647 | -0. Préparation : ✅ / ❌ | ||
| 648 | -1.1 parse() Pydantic : | ||
| 649 | -1.2 + reasoning : | ||
| 650 | -1.3 json_object : | ||
| 651 | -1.4 json_schema stream : | ||
| 652 | -1.5 uniqueItems → 400 : | ||
| 653 | -2. débits (tok/s) : libre=… json_object=… json_schema=… | ||
| 654 | -3.1 outils auto Qwen : | ||
| 655 | -3.2 outils en stream : | ||
| 656 | -3.3 outils auto Llama : | ||
| 657 | -3.4 forcés Qwen : | ||
| 658 | -3.5 forcé Llama → 400 : | ||
| 659 | -3.6 tool_choice none : | ||
| 660 | -3.7 parallèles : | ||
| 661 | -3.8 LangChain agent : | ||
| 662 | -4.1 embeddings SDK : cos=… | ||
| 663 | -4.2 dimensions/base64 : | ||
| 664 | -4.3 LangChain embed : | ||
| 665 | -4.4 Matryoshka : | ||
| 666 | -4.5 chat + embed : | ||
| 667 | -4.6 mauvais type : | ||
| 668 | -4.7 texte trop long : | ||
| 669 | -``` | ||
added
Tests/Compatibility/conftest.py +98 -0 | new file mode 100644 | ||
| @@ -0,0 +1,98 @@ | ||
| 1 | +"""Shared fixtures of the OpenAI compatibility suite (ticket #43). | |
| 2 | + | |
| 3 | +The suite talks to a running `rzb serve` through the official clients. `scripts/compat.sh` starts | |
| 4 | +one with the configuration it expects; to test a server you started yourself, set `RZB_URL`. | |
| 5 | + | |
| 6 | +The server must declare these ids (see `scripts/compat.sh`): | |
| 7 | + chat a chat model with the `<tool_call>` syntax (Qwen3) | |
| 8 | + embed an embedding model (BAAI/bge-small-en-v1.5 for the reference values) | |
| 9 | + unforced optional: a chat model of another tool syntax (Llama 3.x) | |
| 10 | + | |
| 11 | +With the fake engine (Linux), only the protocol is checked; tests that need a real model are | |
| 12 | +marked `real_model` and skipped. | |
| 13 | +""" | |
| 14 | + | |
| 15 | +import os | |
| 16 | + | |
| 17 | +import httpx | |
| 18 | +import pytest | |
| 19 | +from openai import OpenAI | |
| 20 | + | |
| 21 | +BASE_URL = os.environ.get("RZB_URL", "http://127.0.0.1:8080/v1") | |
| 22 | +API_KEY = os.environ.get("RZB_API_KEY", "unused") | |
| 23 | +# What `embed` is (scripts/compat.sh exports it): reference values exist for bge-small only. | |
| 24 | +EMBED_SOURCE = os.environ.get("RZB_COMPAT_EMBED_SOURCE", "BAAI/bge-small-en-v1.5") | |
| 25 | + | |
| 26 | + | |
| 27 | +def pytest_configure(config): | |
| 28 | + config.addinivalue_line("markers", "real_model: needs a real model (skipped on the fake engine)") | |
| 29 | + | |
| 30 | + | |
| 31 | +@pytest.fixture(scope="session") | |
| 32 | +def client(): | |
| 33 | + return OpenAI(base_url=BASE_URL, api_key=API_KEY, max_retries=0, timeout=600) | |
| 34 | + | |
| 35 | + | |
| 36 | +@pytest.fixture(scope="session") | |
| 37 | +def http(): | |
| 38 | + """A raw HTTP client, for what the SDK hides (status codes, SSE lines).""" | |
| 39 | + with httpx.Client( | |
| 40 | + base_url=BASE_URL, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=600 | |
| 41 | + ) as raw: | |
| 42 | + yield raw | |
| 43 | + | |
| 44 | + | |
| 45 | +@pytest.fixture(scope="session") | |
| 46 | +def declared_ids(client): | |
| 47 | + return {model.id for model in client.models.list()} | |
| 48 | + | |
| 49 | + | |
| 50 | +@pytest.fixture(scope="session") | |
| 51 | +def fake_engine(client): | |
| 52 | + """True when the server runs the fake engine: it answers `echo: <last message>`.""" | |
| 53 | + answer = client.chat.completions.create( | |
| 54 | + model="chat", messages=[{"role": "user", "content": "ping"}], max_tokens=4 | |
| 55 | + ) | |
| 56 | + return (answer.choices[0].message.content or "").startswith("echo: ") | |
| 57 | + | |
| 58 | + | |
| 59 | +@pytest.fixture(autouse=True) | |
| 60 | +def _skip_real_model_tests(request, fake_engine): | |
| 61 | + if fake_engine and request.node.get_closest_marker("real_model"): | |
| 62 | + pytest.skip("needs a real model (the server runs the fake engine)") | |
| 63 | + | |
| 64 | + | |
| 65 | +@pytest.fixture(scope="session") | |
| 66 | +def unforced_model(declared_ids): | |
| 67 | + if "unforced" not in declared_ids: | |
| 68 | + pytest.skip("no 'unforced' model declared (a Llama 3.x model, see scripts/compat.sh)") | |
| 69 | + return "unforced" | |
| 70 | + | |
| 71 | + | |
| 72 | +WEATHER_TOOL = { | |
| 73 | + "type": "function", | |
| 74 | + "function": { | |
| 75 | + "name": "get_weather", | |
| 76 | + "description": "Current weather for a city", | |
| 77 | + "parameters": { | |
| 78 | + "type": "object", | |
| 79 | + "properties": {"city": {"type": "string"}}, | |
| 80 | + "required": ["city"], | |
| 81 | + }, | |
| 82 | + }, | |
| 83 | +} | |
| 84 | + | |
| 85 | +TIME_TOOL = { | |
| 86 | + "type": "function", | |
| 87 | + "function": { | |
| 88 | + "name": "get_time", | |
| 89 | + "description": "Current local time in a city", | |
| 90 | + "parameters": { | |
| 91 | + "type": "object", | |
| 92 | + "properties": {"city": {"type": "string"}}, | |
| 93 | + "required": ["city"], | |
| 94 | + }, | |
| 95 | + }, | |
| 96 | +} | |
| 97 | + | |
| 98 | +NO_THINKING = {"reasoning_effort": "none"} | |
| new file mode 100644 | |||
| @@ -0,0 +1,98 @@ | |||
| 1 | +"""Shared fixtures of the OpenAI compatibility suite (ticket #43). | ||
| 2 | + | ||
| 3 | +The suite talks to a running `rzb serve` through the official clients. `scripts/compat.sh` starts | ||
| 4 | +one with the configuration it expects; to test a server you started yourself, set `RZB_URL`. | ||
| 5 | + | ||
| 6 | +The server must declare these ids (see `scripts/compat.sh`): | ||
| 7 | + chat a chat model with the `<tool_call>` syntax (Qwen3) | ||
| 8 | + embed an embedding model (BAAI/bge-small-en-v1.5 for the reference values) | ||
| 9 | + unforced optional: a chat model of another tool syntax (Llama 3.x) | ||
| 10 | + | ||
| 11 | +With the fake engine (Linux), only the protocol is checked; tests that need a real model are | ||
| 12 | +marked `real_model` and skipped. | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +import os | ||
| 16 | + | ||
| 17 | +import httpx | ||
| 18 | +import pytest | ||
| 19 | +from openai import OpenAI | ||
| 20 | + | ||
| 21 | +BASE_URL = os.environ.get("RZB_URL", "http://127.0.0.1:8080/v1") | ||
| 22 | +API_KEY = os.environ.get("RZB_API_KEY", "unused") | ||
| 23 | +# What `embed` is (scripts/compat.sh exports it): reference values exist for bge-small only. | ||
| 24 | +EMBED_SOURCE = os.environ.get("RZB_COMPAT_EMBED_SOURCE", "BAAI/bge-small-en-v1.5") | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def pytest_configure(config): | ||
| 28 | + config.addinivalue_line("markers", "real_model: needs a real model (skipped on the fake engine)") | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +@pytest.fixture(scope="session") | ||
| 32 | +def client(): | ||
| 33 | + return OpenAI(base_url=BASE_URL, api_key=API_KEY, max_retries=0, timeout=600) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +@pytest.fixture(scope="session") | ||
| 37 | +def http(): | ||
| 38 | + """A raw HTTP client, for what the SDK hides (status codes, SSE lines).""" | ||
| 39 | + with httpx.Client( | ||
| 40 | + base_url=BASE_URL, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=600 | ||
| 41 | + ) as raw: | ||
| 42 | + yield raw | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +@pytest.fixture(scope="session") | ||
| 46 | +def declared_ids(client): | ||
| 47 | + return {model.id for model in client.models.list()} | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +@pytest.fixture(scope="session") | ||
| 51 | +def fake_engine(client): | ||
| 52 | + """True when the server runs the fake engine: it answers `echo: <last message>`.""" | ||
| 53 | + answer = client.chat.completions.create( | ||
| 54 | + model="chat", messages=[{"role": "user", "content": "ping"}], max_tokens=4 | ||
| 55 | + ) | ||
| 56 | + return (answer.choices[0].message.content or "").startswith("echo: ") | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +@pytest.fixture(autouse=True) | ||
| 60 | +def _skip_real_model_tests(request, fake_engine): | ||
| 61 | + if fake_engine and request.node.get_closest_marker("real_model"): | ||
| 62 | + pytest.skip("needs a real model (the server runs the fake engine)") | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +@pytest.fixture(scope="session") | ||
| 66 | +def unforced_model(declared_ids): | ||
| 67 | + if "unforced" not in declared_ids: | ||
| 68 | + pytest.skip("no 'unforced' model declared (a Llama 3.x model, see scripts/compat.sh)") | ||
| 69 | + return "unforced" | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +WEATHER_TOOL = { | ||
| 73 | + "type": "function", | ||
| 74 | + "function": { | ||
| 75 | + "name": "get_weather", | ||
| 76 | + "description": "Current weather for a city", | ||
| 77 | + "parameters": { | ||
| 78 | + "type": "object", | ||
| 79 | + "properties": {"city": {"type": "string"}}, | ||
| 80 | + "required": ["city"], | ||
| 81 | + }, | ||
| 82 | + }, | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +TIME_TOOL = { | ||
| 86 | + "type": "function", | ||
| 87 | + "function": { | ||
| 88 | + "name": "get_time", | ||
| 89 | + "description": "Current local time in a city", | ||
| 90 | + "parameters": { | ||
| 91 | + "type": "object", | ||
| 92 | + "properties": {"city": {"type": "string"}}, | ||
| 93 | + "required": ["city"], | ||
| 94 | + }, | ||
| 95 | + }, | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +NO_THINKING = {"reasoning_effort": "none"} | ||
added
Tests/Compatibility/pytest.ini +4 -0 | new file mode 100644 | ||
| @@ -0,0 +1,4 @@ | ||
| 1 | +[pytest] | |
| 2 | +# langsmith (pulled in by langchain-openai) uses an asyncio API that Python 3.14 deprecates. | |
| 3 | +filterwarnings = | |
| 4 | + ignore::DeprecationWarning:langsmith.* | |
| new file mode 100644 | |||
| @@ -0,0 +1,4 @@ | |||
| 1 | +[pytest] | ||
| 2 | +# langsmith (pulled in by langchain-openai) uses an asyncio API that Python 3.14 deprecates. | ||
| 3 | +filterwarnings = | ||
| 4 | + ignore::DeprecationWarning:langsmith.* | ||
added
Tests/Compatibility/requirements.txt +6 -0 | new file mode 100644 | ||
| @@ -0,0 +1,6 @@ | ||
| 1 | +# The clients the compatibility suite checks (run with: scripts/compat.sh). | |
| 2 | +openai>=1.40 | |
| 3 | +pydantic>=2 | |
| 4 | +httpx | |
| 5 | +langchain-openai>=0.2 | |
| 6 | +pytest>=8 | |
| new file mode 100644 | |||
| @@ -0,0 +1,6 @@ | |||
| 1 | +# The clients the compatibility suite checks (run with: scripts/compat.sh). | ||
| 2 | +openai>=1.40 | ||
| 3 | +pydantic>=2 | ||
| 4 | +httpx | ||
| 5 | +langchain-openai>=0.2 | ||
| 6 | +pytest>=8 | ||
added
Tests/Compatibility/test_chat.py +127 -0 | new file mode 100644 | ||
| @@ -0,0 +1,127 @@ | ||
| 1 | +"""Chat completions through the openai SDK: models, answers, streaming, errors.""" | |
| 2 | + | |
| 3 | +import json | |
| 4 | + | |
| 5 | +import openai | |
| 6 | +import pytest | |
| 7 | + | |
| 8 | +from conftest import NO_THINKING | |
| 9 | + | |
| 10 | + | |
| 11 | +def test_models_list_declared_ids_with_their_kind(http): | |
| 12 | + body = http.get("/models").json() | |
| 13 | + kinds = {model["id"]: model.get("kind") for model in body["data"]} | |
| 14 | + assert body["object"] == "list" | |
| 15 | + assert kinds["chat"] == "chat" | |
| 16 | + assert kinds["embed"] == "embedding" | |
| 17 | + | |
| 18 | + | |
| 19 | +def test_model_retrieve(client): | |
| 20 | + assert client.models.retrieve("chat").id == "chat" | |
| 21 | + | |
| 22 | + | |
| 23 | +def test_unknown_model_is_a_404(client): | |
| 24 | + with pytest.raises(openai.NotFoundError) as error: | |
| 25 | + client.chat.completions.create( | |
| 26 | + model="no-such-model", messages=[{"role": "user", "content": "hi"}] | |
| 27 | + ) | |
| 28 | + assert error.value.body["param"] == "model" | |
| 29 | + | |
| 30 | + | |
| 31 | +def test_answer_has_openai_shape(client): | |
| 32 | + answer = client.chat.completions.create( | |
| 33 | + model="chat", | |
| 34 | + messages=[ | |
| 35 | + {"role": "system", "content": "Answer in one word."}, | |
| 36 | + {"role": "user", "content": "Say hello."}, | |
| 37 | + ], | |
| 38 | + max_tokens=50, | |
| 39 | + extra_body=NO_THINKING, | |
| 40 | + ) | |
| 41 | + choice = answer.choices[0] | |
| 42 | + assert answer.object == "chat.completion" | |
| 43 | + assert answer.id.startswith("chatcmpl-") | |
| 44 | + assert answer.model == "chat" | |
| 45 | + assert choice.message.role == "assistant" | |
| 46 | + assert choice.message.content | |
| 47 | + assert choice.finish_reason in ("stop", "length") | |
| 48 | + assert answer.usage.prompt_tokens > 0 | |
| 49 | + assert answer.usage.total_tokens == answer.usage.prompt_tokens + answer.usage.completion_tokens | |
| 50 | + | |
| 51 | + | |
| 52 | +def test_streaming_with_usage(client): | |
| 53 | + stream = client.chat.completions.create( | |
| 54 | + model="chat", | |
| 55 | + messages=[{"role": "user", "content": "Count from 1 to 5."}], | |
| 56 | + max_tokens=60, | |
| 57 | + stream=True, | |
| 58 | + stream_options={"include_usage": True}, | |
| 59 | + extra_body=NO_THINKING, | |
| 60 | + ) | |
| 61 | + chunks = list(stream) | |
| 62 | + with_choices = [chunk for chunk in chunks if chunk.choices] | |
| 63 | + assert with_choices[0].choices[0].delta.role == "assistant" | |
| 64 | + assert "".join(chunk.choices[0].delta.content or "" for chunk in with_choices) | |
| 65 | + assert with_choices[-1].choices[0].finish_reason in ("stop", "length") | |
| 66 | + assert chunks[-1].choices == [] | |
| 67 | + assert chunks[-1].usage.completion_tokens > 0 | |
| 68 | + | |
| 69 | + | |
| 70 | +def test_raw_stream_ends_with_done(http): | |
| 71 | + request = { | |
| 72 | + "model": "chat", | |
| 73 | + "messages": [{"role": "user", "content": "hi"}], | |
| 74 | + "max_tokens": 10, | |
| 75 | + "stream": True, | |
| 76 | + **NO_THINKING, | |
| 77 | + } | |
| 78 | + with http.stream("POST", "/chat/completions", json=request) as response: | |
| 79 | + assert response.headers["content-type"].startswith("text/event-stream") | |
| 80 | + events = [line[6:] for line in response.iter_lines() if line.startswith("data: ")] | |
| 81 | + assert events[-1] == "[DONE]" | |
| 82 | + assert all(json.loads(event)["object"] == "chat.completion.chunk" for event in events[:-1]) | |
| 83 | + | |
| 84 | + | |
| 85 | +@pytest.mark.parametrize( | |
| 86 | + ("field", "value"), | |
| 87 | + [("n", 2), ("logprobs", True), ("temperature", -1), ("reasoning_effort", "huge")], | |
| 88 | +) | |
| 89 | +def test_unsupported_or_invalid_fields_are_400(client, field, value): | |
| 90 | + with pytest.raises(openai.BadRequestError) as error: | |
| 91 | + client.chat.completions.create( | |
| 92 | + model="chat", messages=[{"role": "user", "content": "hi"}], extra_body={field: value} | |
| 93 | + ) | |
| 94 | + assert error.value.body["param"] == field | |
| 95 | + | |
| 96 | + | |
| 97 | +def test_embedding_model_cannot_chat(client): | |
| 98 | + with pytest.raises(openai.BadRequestError) as error: | |
| 99 | + client.chat.completions.create(model="embed", messages=[{"role": "user", "content": "hi"}]) | |
| 100 | + assert error.value.body["param"] == "model" | |
| 101 | + | |
| 102 | + | |
| 103 | +@pytest.mark.real_model | |
| 104 | +def test_reasoning_is_separate_from_the_answer(client): | |
| 105 | + answer = client.chat.completions.create( | |
| 106 | + model="chat", | |
| 107 | + messages=[{"role": "user", "content": "What is 17 * 3?"}], | |
| 108 | + max_tokens=1500, | |
| 109 | + extra_body={"reasoning_effort": "low"}, | |
| 110 | + ) | |
| 111 | + message = answer.choices[0].message | |
| 112 | + assert getattr(message, "reasoning_content", None) | |
| 113 | + assert "<think>" not in (message.content or "") | |
| 114 | + assert "51" in message.content | |
| 115 | + | |
| 116 | + | |
| 117 | +@pytest.mark.real_model | |
| 118 | +def test_stop_sequence(client): | |
| 119 | + answer = client.chat.completions.create( | |
| 120 | + model="chat", | |
| 121 | + messages=[{"role": "user", "content": "Write the numbers from 1 to 10, comma separated."}], | |
| 122 | + stop=["5"], | |
| 123 | + max_tokens=100, | |
| 124 | + extra_body=NO_THINKING, | |
| 125 | + ) | |
| 126 | + assert "5" not in answer.choices[0].message.content | |
| 127 | + assert answer.choices[0].finish_reason == "stop" | |
| new file mode 100644 | |||
| @@ -0,0 +1,127 @@ | |||
| 1 | +"""Chat completions through the openai SDK: models, answers, streaming, errors.""" | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | + | ||
| 5 | +import openai | ||
| 6 | +import pytest | ||
| 7 | + | ||
| 8 | +from conftest import NO_THINKING | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def test_models_list_declared_ids_with_their_kind(http): | ||
| 12 | + body = http.get("/models").json() | ||
| 13 | + kinds = {model["id"]: model.get("kind") for model in body["data"]} | ||
| 14 | + assert body["object"] == "list" | ||
| 15 | + assert kinds["chat"] == "chat" | ||
| 16 | + assert kinds["embed"] == "embedding" | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def test_model_retrieve(client): | ||
| 20 | + assert client.models.retrieve("chat").id == "chat" | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def test_unknown_model_is_a_404(client): | ||
| 24 | + with pytest.raises(openai.NotFoundError) as error: | ||
| 25 | + client.chat.completions.create( | ||
| 26 | + model="no-such-model", messages=[{"role": "user", "content": "hi"}] | ||
| 27 | + ) | ||
| 28 | + assert error.value.body["param"] == "model" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def test_answer_has_openai_shape(client): | ||
| 32 | + answer = client.chat.completions.create( | ||
| 33 | + model="chat", | ||
| 34 | + messages=[ | ||
| 35 | + {"role": "system", "content": "Answer in one word."}, | ||
| 36 | + {"role": "user", "content": "Say hello."}, | ||
| 37 | + ], | ||
| 38 | + max_tokens=50, | ||
| 39 | + extra_body=NO_THINKING, | ||
| 40 | + ) | ||
| 41 | + choice = answer.choices[0] | ||
| 42 | + assert answer.object == "chat.completion" | ||
| 43 | + assert answer.id.startswith("chatcmpl-") | ||
| 44 | + assert answer.model == "chat" | ||
| 45 | + assert choice.message.role == "assistant" | ||
| 46 | + assert choice.message.content | ||
| 47 | + assert choice.finish_reason in ("stop", "length") | ||
| 48 | + assert answer.usage.prompt_tokens > 0 | ||
| 49 | + assert answer.usage.total_tokens == answer.usage.prompt_tokens + answer.usage.completion_tokens | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def test_streaming_with_usage(client): | ||
| 53 | + stream = client.chat.completions.create( | ||
| 54 | + model="chat", | ||
| 55 | + messages=[{"role": "user", "content": "Count from 1 to 5."}], | ||
| 56 | + max_tokens=60, | ||
| 57 | + stream=True, | ||
| 58 | + stream_options={"include_usage": True}, | ||
| 59 | + extra_body=NO_THINKING, | ||
| 60 | + ) | ||
| 61 | + chunks = list(stream) | ||
| 62 | + with_choices = [chunk for chunk in chunks if chunk.choices] | ||
| 63 | + assert with_choices[0].choices[0].delta.role == "assistant" | ||
| 64 | + assert "".join(chunk.choices[0].delta.content or "" for chunk in with_choices) | ||
| 65 | + assert with_choices[-1].choices[0].finish_reason in ("stop", "length") | ||
| 66 | + assert chunks[-1].choices == [] | ||
| 67 | + assert chunks[-1].usage.completion_tokens > 0 | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def test_raw_stream_ends_with_done(http): | ||
| 71 | + request = { | ||
| 72 | + "model": "chat", | ||
| 73 | + "messages": [{"role": "user", "content": "hi"}], | ||
| 74 | + "max_tokens": 10, | ||
| 75 | + "stream": True, | ||
| 76 | + **NO_THINKING, | ||
| 77 | + } | ||
| 78 | + with http.stream("POST", "/chat/completions", json=request) as response: | ||
| 79 | + assert response.headers["content-type"].startswith("text/event-stream") | ||
| 80 | + events = [line[6:] for line in response.iter_lines() if line.startswith("data: ")] | ||
| 81 | + assert events[-1] == "[DONE]" | ||
| 82 | + assert all(json.loads(event)["object"] == "chat.completion.chunk" for event in events[:-1]) | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +@pytest.mark.parametrize( | ||
| 86 | + ("field", "value"), | ||
| 87 | + [("n", 2), ("logprobs", True), ("temperature", -1), ("reasoning_effort", "huge")], | ||
| 88 | +) | ||
| 89 | +def test_unsupported_or_invalid_fields_are_400(client, field, value): | ||
| 90 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 91 | + client.chat.completions.create( | ||
| 92 | + model="chat", messages=[{"role": "user", "content": "hi"}], extra_body={field: value} | ||
| 93 | + ) | ||
| 94 | + assert error.value.body["param"] == field | ||
| 95 | + | ||
| 96 | + | ||
| 97 | +def test_embedding_model_cannot_chat(client): | ||
| 98 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 99 | + client.chat.completions.create(model="embed", messages=[{"role": "user", "content": "hi"}]) | ||
| 100 | + assert error.value.body["param"] == "model" | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +@pytest.mark.real_model | ||
| 104 | +def test_reasoning_is_separate_from_the_answer(client): | ||
| 105 | + answer = client.chat.completions.create( | ||
| 106 | + model="chat", | ||
| 107 | + messages=[{"role": "user", "content": "What is 17 * 3?"}], | ||
| 108 | + max_tokens=1500, | ||
| 109 | + extra_body={"reasoning_effort": "low"}, | ||
| 110 | + ) | ||
| 111 | + message = answer.choices[0].message | ||
| 112 | + assert getattr(message, "reasoning_content", None) | ||
| 113 | + assert "<think>" not in (message.content or "") | ||
| 114 | + assert "51" in message.content | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +@pytest.mark.real_model | ||
| 118 | +def test_stop_sequence(client): | ||
| 119 | + answer = client.chat.completions.create( | ||
| 120 | + model="chat", | ||
| 121 | + messages=[{"role": "user", "content": "Write the numbers from 1 to 10, comma separated."}], | ||
| 122 | + stop=["5"], | ||
| 123 | + max_tokens=100, | ||
| 124 | + extra_body=NO_THINKING, | ||
| 125 | + ) | ||
| 126 | + assert "5" not in answer.choices[0].message.content | ||
| 127 | + assert answer.choices[0].finish_reason == "stop" | ||
added
Tests/Compatibility/test_docs_curl.py +51 -0 | new file mode 100644 | ||
| @@ -0,0 +1,51 @@ | ||
| 1 | +"""The `curl` examples of the API reference run against the server and answer without error. | |
| 2 | + | |
| 3 | +Every fenced `bash` block of `docs/*/reference/*.md` that calls `http://127.0.0.1:8080/v1` is | |
| 4 | +run, with the address replaced by the server under test. An example that needs a real model | |
| 5 | +says so with a `# real model` comment in its block. | |
| 6 | +""" | |
| 7 | + | |
| 8 | +import json | |
| 9 | +import os | |
| 10 | +import re | |
| 11 | +import subprocess | |
| 12 | +from pathlib import Path | |
| 13 | + | |
| 14 | +import pytest | |
| 15 | + | |
| 16 | +from conftest import BASE_URL | |
| 17 | + | |
| 18 | +ROOT = Path(__file__).resolve().parents[2] | |
| 19 | +DOCS_ADDRESS = "http://127.0.0.1:8080/v1" | |
| 20 | +BLOCK = re.compile(r"```bash\n(.*?)```", re.DOTALL) | |
| 21 | + | |
| 22 | + | |
| 23 | +def examples(): | |
| 24 | + found = [] | |
| 25 | + for page in sorted(ROOT.glob("docs/*/reference/*.md")): | |
| 26 | + for number, block in enumerate(BLOCK.findall(page.read_text())): | |
| 27 | + if "curl" in block and DOCS_ADDRESS in block: | |
| 28 | + found.append(pytest.param(block, id=f"{page.relative_to(ROOT)}#{number}")) | |
| 29 | + return found or [pytest.param("", marks=pytest.mark.skip("no curl example in the docs yet"))] | |
| 30 | + | |
| 31 | + | |
| 32 | +def outputs_are_valid(output): | |
| 33 | + """A JSON body without `error`, or SSE events ending with `[DONE]`.""" | |
| 34 | + if output.lstrip().startswith("data: "): | |
| 35 | + events = [line[6:] for line in output.splitlines() if line.startswith("data: ")] | |
| 36 | + return events[-1] == "[DONE]" | |
| 37 | + return "error" not in json.loads(output) | |
| 38 | + | |
| 39 | + | |
| 40 | +@pytest.mark.parametrize("block", examples()) | |
| 41 | +def test_curl_example(block, fake_engine): | |
| 42 | + if fake_engine and "# real model" in block: | |
| 43 | + pytest.skip("needs a real model (the server runs the fake engine)") | |
| 44 | + script = block.replace(DOCS_ADDRESS, BASE_URL) | |
| 45 | + env = {**os.environ, "RZB_API_KEY": os.environ.get("RZB_API_KEY", "unused")} | |
| 46 | + done = subprocess.run( | |
| 47 | + ["bash", "-euo", "pipefail", "-c", script], | |
| 48 | + capture_output=True, text=True, timeout=600, env=env, check=False, | |
| 49 | + ) | |
| 50 | + assert done.returncode == 0, done.stderr | |
| 51 | + assert outputs_are_valid(done.stdout), done.stdout | |
| new file mode 100644 | |||
| @@ -0,0 +1,51 @@ | |||
| 1 | +"""The `curl` examples of the API reference run against the server and answer without error. | ||
| 2 | + | ||
| 3 | +Every fenced `bash` block of `docs/*/reference/*.md` that calls `http://127.0.0.1:8080/v1` is | ||
| 4 | +run, with the address replaced by the server under test. An example that needs a real model | ||
| 5 | +says so with a `# real model` comment in its block. | ||
| 6 | +""" | ||
| 7 | + | ||
| 8 | +import json | ||
| 9 | +import os | ||
| 10 | +import re | ||
| 11 | +import subprocess | ||
| 12 | +from pathlib import Path | ||
| 13 | + | ||
| 14 | +import pytest | ||
| 15 | + | ||
| 16 | +from conftest import BASE_URL | ||
| 17 | + | ||
| 18 | +ROOT = Path(__file__).resolve().parents[2] | ||
| 19 | +DOCS_ADDRESS = "http://127.0.0.1:8080/v1" | ||
| 20 | +BLOCK = re.compile(r"```bash\n(.*?)```", re.DOTALL) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def examples(): | ||
| 24 | + found = [] | ||
| 25 | + for page in sorted(ROOT.glob("docs/*/reference/*.md")): | ||
| 26 | + for number, block in enumerate(BLOCK.findall(page.read_text())): | ||
| 27 | + if "curl" in block and DOCS_ADDRESS in block: | ||
| 28 | + found.append(pytest.param(block, id=f"{page.relative_to(ROOT)}#{number}")) | ||
| 29 | + return found or [pytest.param("", marks=pytest.mark.skip("no curl example in the docs yet"))] | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def outputs_are_valid(output): | ||
| 33 | + """A JSON body without `error`, or SSE events ending with `[DONE]`.""" | ||
| 34 | + if output.lstrip().startswith("data: "): | ||
| 35 | + events = [line[6:] for line in output.splitlines() if line.startswith("data: ")] | ||
| 36 | + return events[-1] == "[DONE]" | ||
| 37 | + return "error" not in json.loads(output) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +@pytest.mark.parametrize("block", examples()) | ||
| 41 | +def test_curl_example(block, fake_engine): | ||
| 42 | + if fake_engine and "# real model" in block: | ||
| 43 | + pytest.skip("needs a real model (the server runs the fake engine)") | ||
| 44 | + script = block.replace(DOCS_ADDRESS, BASE_URL) | ||
| 45 | + env = {**os.environ, "RZB_API_KEY": os.environ.get("RZB_API_KEY", "unused")} | ||
| 46 | + done = subprocess.run( | ||
| 47 | + ["bash", "-euo", "pipefail", "-c", script], | ||
| 48 | + capture_output=True, text=True, timeout=600, env=env, check=False, | ||
| 49 | + ) | ||
| 50 | + assert done.returncode == 0, done.stderr | ||
| 51 | + assert outputs_are_valid(done.stdout), done.stdout | ||
added
Tests/Compatibility/test_embeddings.py +90 -0 | new file mode 100644 | ||
| @@ -0,0 +1,90 @@ | ||
| 1 | +"""`/v1/embeddings` through the openai SDK (ticket #42).""" | |
| 2 | + | |
| 3 | +import base64 | |
| 4 | +import math | |
| 5 | +import struct | |
| 6 | + | |
| 7 | +import openai | |
| 8 | +import pytest | |
| 9 | + | |
| 10 | +from conftest import EMBED_SOURCE | |
| 11 | + | |
| 12 | +SENTENCES = [ | |
| 13 | + "The cat sits on the mat.", | |
| 14 | + "A feline is resting on a rug.", | |
| 15 | + "Stock markets fell sharply today.", | |
| 16 | +] | |
| 17 | + | |
| 18 | +# sentence-transformers values for BAAI/bge-small-en-v1.5 (see EmbeddingSmokeTests.swift). | |
| 19 | +BGE_COSINES = {(0, 1): 0.754619, (0, 2): 0.324302, (1, 2): 0.313784} | |
| 20 | + | |
| 21 | + | |
| 22 | +def dot(left, right): | |
| 23 | + return sum(a * b for a, b in zip(left, right)) | |
| 24 | + | |
| 25 | + | |
| 26 | +def test_list_of_texts(client): | |
| 27 | + result = client.embeddings.create(model="embed", input=SENTENCES) | |
| 28 | + assert result.object == "list" | |
| 29 | + assert [item.index for item in result.data] == [0, 1, 2] | |
| 30 | + assert len({len(item.embedding) for item in result.data}) == 1 | |
| 31 | + assert all(math.isclose(dot(v.embedding, v.embedding), 1, abs_tol=1e-3) for v in result.data) | |
| 32 | + assert result.usage.prompt_tokens > 0 | |
| 33 | + | |
| 34 | + | |
| 35 | +def test_single_text_as_floats(http): | |
| 36 | + body = http.post( | |
| 37 | + "/embeddings", json={"model": "embed", "input": "hello", "encoding_format": "float"} | |
| 38 | + ).json() | |
| 39 | + assert isinstance(body["data"][0]["embedding"][0], float) | |
| 40 | + | |
| 41 | + | |
| 42 | +def test_base64_is_little_endian_float32(http): | |
| 43 | + request = {"model": "embed", "input": "hello"} | |
| 44 | + floats = http.post("/embeddings", json=request).json()["data"][0]["embedding"] | |
| 45 | + encoded = http.post("/embeddings", json={**request, "encoding_format": "base64"}).json() | |
| 46 | + raw = base64.b64decode(encoded["data"][0]["embedding"]) | |
| 47 | + decoded = struct.unpack(f"<{len(raw) // 4}f", raw) | |
| 48 | + assert len(decoded) == len(floats) | |
| 49 | + assert all(math.isclose(a, b, abs_tol=1e-6) for a, b in zip(decoded, floats)) | |
| 50 | + | |
| 51 | + | |
| 52 | +def test_dimensions_truncates_and_renormalises(client): | |
| 53 | + vector = client.embeddings.create(model="embed", input="hello", dimensions=4).data[0].embedding | |
| 54 | + assert len(vector) == 4 | |
| 55 | + assert math.isclose(dot(vector, vector), 1, abs_tol=1e-3) | |
| 56 | + | |
| 57 | + | |
| 58 | +def test_too_many_dimensions_is_400(client): | |
| 59 | + with pytest.raises(openai.BadRequestError) as error: | |
| 60 | + client.embeddings.create(model="embed", input="hello", dimensions=100_000) | |
| 61 | + assert error.value.body["param"] == "dimensions" | |
| 62 | + | |
| 63 | + | |
| 64 | +@pytest.mark.parametrize("bad_input", [[], [""], [1, 2, 3]]) | |
| 65 | +def test_bad_input_is_400(client, bad_input): | |
| 66 | + with pytest.raises(openai.BadRequestError): | |
| 67 | + client.embeddings.create(model="embed", input=bad_input) | |
| 68 | + | |
| 69 | + | |
| 70 | +def test_chat_model_cannot_embed(client): | |
| 71 | + with pytest.raises(openai.BadRequestError) as error: | |
| 72 | + client.embeddings.create(model="chat", input="hello") | |
| 73 | + assert error.value.body["param"] == "model" | |
| 74 | + | |
| 75 | + | |
| 76 | +@pytest.mark.real_model | |
| 77 | +def test_cosines_match_sentence_transformers(client): | |
| 78 | + if EMBED_SOURCE != "BAAI/bge-small-en-v1.5": | |
| 79 | + pytest.skip(f"reference values are for BAAI/bge-small-en-v1.5, not {EMBED_SOURCE}") | |
| 80 | + result = client.embeddings.create(model="embed", input=SENTENCES) | |
| 81 | + vectors = [item.embedding for item in result.data] | |
| 82 | + for (left, right), expected in BGE_COSINES.items(): | |
| 83 | + assert math.isclose(dot(vectors[left], vectors[right]), expected, abs_tol=1e-3) | |
| 84 | + | |
| 85 | + | |
| 86 | +@pytest.mark.real_model | |
| 87 | +def test_too_long_input_is_400(client): | |
| 88 | + with pytest.raises(openai.BadRequestError) as error: | |
| 89 | + client.embeddings.create(model="embed", input=["short", "word " * 3000]) | |
| 90 | + assert "input[1]" in error.value.body["message"] | |
| new file mode 100644 | |||
| @@ -0,0 +1,90 @@ | |||
| 1 | +"""`/v1/embeddings` through the openai SDK (ticket #42).""" | ||
| 2 | + | ||
| 3 | +import base64 | ||
| 4 | +import math | ||
| 5 | +import struct | ||
| 6 | + | ||
| 7 | +import openai | ||
| 8 | +import pytest | ||
| 9 | + | ||
| 10 | +from conftest import EMBED_SOURCE | ||
| 11 | + | ||
| 12 | +SENTENCES = [ | ||
| 13 | + "The cat sits on the mat.", | ||
| 14 | + "A feline is resting on a rug.", | ||
| 15 | + "Stock markets fell sharply today.", | ||
| 16 | +] | ||
| 17 | + | ||
| 18 | +# sentence-transformers values for BAAI/bge-small-en-v1.5 (see EmbeddingSmokeTests.swift). | ||
| 19 | +BGE_COSINES = {(0, 1): 0.754619, (0, 2): 0.324302, (1, 2): 0.313784} | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def dot(left, right): | ||
| 23 | + return sum(a * b for a, b in zip(left, right)) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def test_list_of_texts(client): | ||
| 27 | + result = client.embeddings.create(model="embed", input=SENTENCES) | ||
| 28 | + assert result.object == "list" | ||
| 29 | + assert [item.index for item in result.data] == [0, 1, 2] | ||
| 30 | + assert len({len(item.embedding) for item in result.data}) == 1 | ||
| 31 | + assert all(math.isclose(dot(v.embedding, v.embedding), 1, abs_tol=1e-3) for v in result.data) | ||
| 32 | + assert result.usage.prompt_tokens > 0 | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def test_single_text_as_floats(http): | ||
| 36 | + body = http.post( | ||
| 37 | + "/embeddings", json={"model": "embed", "input": "hello", "encoding_format": "float"} | ||
| 38 | + ).json() | ||
| 39 | + assert isinstance(body["data"][0]["embedding"][0], float) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def test_base64_is_little_endian_float32(http): | ||
| 43 | + request = {"model": "embed", "input": "hello"} | ||
| 44 | + floats = http.post("/embeddings", json=request).json()["data"][0]["embedding"] | ||
| 45 | + encoded = http.post("/embeddings", json={**request, "encoding_format": "base64"}).json() | ||
| 46 | + raw = base64.b64decode(encoded["data"][0]["embedding"]) | ||
| 47 | + decoded = struct.unpack(f"<{len(raw) // 4}f", raw) | ||
| 48 | + assert len(decoded) == len(floats) | ||
| 49 | + assert all(math.isclose(a, b, abs_tol=1e-6) for a, b in zip(decoded, floats)) | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def test_dimensions_truncates_and_renormalises(client): | ||
| 53 | + vector = client.embeddings.create(model="embed", input="hello", dimensions=4).data[0].embedding | ||
| 54 | + assert len(vector) == 4 | ||
| 55 | + assert math.isclose(dot(vector, vector), 1, abs_tol=1e-3) | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +def test_too_many_dimensions_is_400(client): | ||
| 59 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 60 | + client.embeddings.create(model="embed", input="hello", dimensions=100_000) | ||
| 61 | + assert error.value.body["param"] == "dimensions" | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +@pytest.mark.parametrize("bad_input", [[], [""], [1, 2, 3]]) | ||
| 65 | +def test_bad_input_is_400(client, bad_input): | ||
| 66 | + with pytest.raises(openai.BadRequestError): | ||
| 67 | + client.embeddings.create(model="embed", input=bad_input) | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def test_chat_model_cannot_embed(client): | ||
| 71 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 72 | + client.embeddings.create(model="chat", input="hello") | ||
| 73 | + assert error.value.body["param"] == "model" | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +@pytest.mark.real_model | ||
| 77 | +def test_cosines_match_sentence_transformers(client): | ||
| 78 | + if EMBED_SOURCE != "BAAI/bge-small-en-v1.5": | ||
| 79 | + pytest.skip(f"reference values are for BAAI/bge-small-en-v1.5, not {EMBED_SOURCE}") | ||
| 80 | + result = client.embeddings.create(model="embed", input=SENTENCES) | ||
| 81 | + vectors = [item.embedding for item in result.data] | ||
| 82 | + for (left, right), expected in BGE_COSINES.items(): | ||
| 83 | + assert math.isclose(dot(vectors[left], vectors[right]), expected, abs_tol=1e-3) | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +@pytest.mark.real_model | ||
| 87 | +def test_too_long_input_is_400(client): | ||
| 88 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 89 | + client.embeddings.create(model="embed", input=["short", "word " * 3000]) | ||
| 90 | + assert "input[1]" in error.value.body["message"] | ||
added
Tests/Compatibility/test_langchain.py +46 -0 | new file mode 100644 | ||
| @@ -0,0 +1,46 @@ | ||
| 1 | +"""LangChain's OpenAI integration (`langchain-openai`), the most common client after the SDK.""" | |
| 2 | + | |
| 3 | +import pytest | |
| 4 | +from langchain_core.tools import tool | |
| 5 | +from langchain_openai import ChatOpenAI, OpenAIEmbeddings | |
| 6 | + | |
| 7 | +from conftest import API_KEY, BASE_URL | |
| 8 | + | |
| 9 | + | |
| 10 | +@tool | |
| 11 | +def add(a: int, b: int) -> int: | |
| 12 | + """Add two integers.""" | |
| 13 | + return a + b | |
| 14 | + | |
| 15 | + | |
| 16 | +def chat_model(**options): | |
| 17 | + return ChatOpenAI( | |
| 18 | + base_url=BASE_URL, api_key=API_KEY, model="chat", max_tokens=200, | |
| 19 | + reasoning_effort="none", **options, | |
| 20 | + ) | |
| 21 | + | |
| 22 | + | |
| 23 | +def test_invoke(): | |
| 24 | + assert chat_model().invoke("Say hello.").content | |
| 25 | + | |
| 26 | + | |
| 27 | +def test_stream(): | |
| 28 | + assert "".join(piece.content for piece in chat_model().stream("Count from 1 to 5.")) | |
| 29 | + | |
| 30 | + | |
| 31 | +def test_embeddings(): | |
| 32 | + # check_embedding_ctx_length=False: otherwise LangChain sends tiktoken token arrays, which | |
| 33 | + # razorbill refuses for now. | |
| 34 | + embeddings = OpenAIEmbeddings( | |
| 35 | + base_url=BASE_URL, api_key=API_KEY, model="embed", check_embedding_ctx_length=False | |
| 36 | + ) | |
| 37 | + documents = embeddings.embed_documents(["hello world", "bonjour le monde"]) | |
| 38 | + assert len(documents) == 2 | |
| 39 | + assert len(embeddings.embed_query("hi")) == len(documents[0]) | |
| 40 | + | |
| 41 | + | |
| 42 | +@pytest.mark.real_model | |
| 43 | +def test_bind_tools(): | |
| 44 | + message = chat_model().bind_tools([add]).invoke("What is 1234 + 4321? Use the tool.") | |
| 45 | + assert message.tool_calls[0]["name"] == "add" | |
| 46 | + assert message.tool_calls[0]["args"] == {"a": 1234, "b": 4321} | |
| new file mode 100644 | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | +"""LangChain's OpenAI integration (`langchain-openai`), the most common client after the SDK.""" | ||
| 2 | + | ||
| 3 | +import pytest | ||
| 4 | +from langchain_core.tools import tool | ||
| 5 | +from langchain_openai import ChatOpenAI, OpenAIEmbeddings | ||
| 6 | + | ||
| 7 | +from conftest import API_KEY, BASE_URL | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +@tool | ||
| 11 | +def add(a: int, b: int) -> int: | ||
| 12 | + """Add two integers.""" | ||
| 13 | + return a + b | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def chat_model(**options): | ||
| 17 | + return ChatOpenAI( | ||
| 18 | + base_url=BASE_URL, api_key=API_KEY, model="chat", max_tokens=200, | ||
| 19 | + reasoning_effort="none", **options, | ||
| 20 | + ) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def test_invoke(): | ||
| 24 | + assert chat_model().invoke("Say hello.").content | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def test_stream(): | ||
| 28 | + assert "".join(piece.content for piece in chat_model().stream("Count from 1 to 5.")) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def test_embeddings(): | ||
| 32 | + # check_embedding_ctx_length=False: otherwise LangChain sends tiktoken token arrays, which | ||
| 33 | + # razorbill refuses for now. | ||
| 34 | + embeddings = OpenAIEmbeddings( | ||
| 35 | + base_url=BASE_URL, api_key=API_KEY, model="embed", check_embedding_ctx_length=False | ||
| 36 | + ) | ||
| 37 | + documents = embeddings.embed_documents(["hello world", "bonjour le monde"]) | ||
| 38 | + assert len(documents) == 2 | ||
| 39 | + assert len(embeddings.embed_query("hi")) == len(documents[0]) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +@pytest.mark.real_model | ||
| 43 | +def test_bind_tools(): | ||
| 44 | + message = chat_model().bind_tools([add]).invoke("What is 1234 + 4321? Use the tool.") | ||
| 45 | + assert message.tool_calls[0]["name"] == "add" | ||
| 46 | + assert message.tool_calls[0]["args"] == {"a": 1234, "b": 4321} | ||
added
Tests/Compatibility/test_structured_output.py +112 -0 | new file mode 100644 | ||
| @@ -0,0 +1,112 @@ | ||
| 1 | +"""`response_format` through the openai SDK, `parse()` included (ticket #39).""" | |
| 2 | + | |
| 3 | +import json | |
| 4 | + | |
| 5 | +import openai | |
| 6 | +import pytest | |
| 7 | +from pydantic import BaseModel | |
| 8 | + | |
| 9 | +from conftest import NO_THINKING | |
| 10 | + | |
| 11 | + | |
| 12 | +class City(BaseModel): | |
| 13 | + name: str | |
| 14 | + country: str | |
| 15 | + population: int | |
| 16 | + landmarks: list[str] | |
| 17 | + | |
| 18 | + | |
| 19 | +PLANETS_SCHEMA = { | |
| 20 | + "type": "json_schema", | |
| 21 | + "json_schema": { | |
| 22 | + "name": "planets", | |
| 23 | + "strict": True, | |
| 24 | + "schema": { | |
| 25 | + "type": "object", | |
| 26 | + "additionalProperties": False, | |
| 27 | + "required": ["planets"], | |
| 28 | + "properties": { | |
| 29 | + "planets": { | |
| 30 | + "type": "array", | |
| 31 | + "items": { | |
| 32 | + "type": "object", | |
| 33 | + "additionalProperties": False, | |
| 34 | + "required": ["name", "diameter_km"], | |
| 35 | + "properties": { | |
| 36 | + "name": {"type": "string"}, | |
| 37 | + "diameter_km": {"type": "number"}, | |
| 38 | + }, | |
| 39 | + }, | |
| 40 | + } | |
| 41 | + }, | |
| 42 | + }, | |
| 43 | + }, | |
| 44 | +} | |
| 45 | + | |
| 46 | + | |
| 47 | +def test_strict_schema_with_unenforced_keyword_is_400(client): | |
| 48 | + format_ = { | |
| 49 | + "type": "json_schema", | |
| 50 | + "json_schema": { | |
| 51 | + "name": "tags", | |
| 52 | + "strict": True, | |
| 53 | + "schema": {"type": "array", "items": {"type": "string"}, "uniqueItems": True}, | |
| 54 | + }, | |
| 55 | + } | |
| 56 | + with pytest.raises(openai.BadRequestError) as error: | |
| 57 | + client.chat.completions.create( | |
| 58 | + model="chat", messages=[{"role": "user", "content": "3 tags"}], response_format=format_ | |
| 59 | + ) | |
| 60 | + assert "uniqueItems" in error.value.body["message"] | |
| 61 | + | |
| 62 | + | |
| 63 | +def test_unknown_format_type_is_400(client): | |
| 64 | + with pytest.raises(openai.BadRequestError): | |
| 65 | + client.chat.completions.create( | |
| 66 | + model="chat", | |
| 67 | + messages=[{"role": "user", "content": "hi"}], | |
| 68 | + response_format={"type": "yaml"}, | |
| 69 | + ) | |
| 70 | + | |
| 71 | + | |
| 72 | +@pytest.mark.real_model | |
| 73 | +@pytest.mark.parametrize("effort", ["none", "low"]) | |
| 74 | +def test_parse_with_a_pydantic_class(client, effort): | |
| 75 | + completion = client.beta.chat.completions.parse( | |
| 76 | + model="chat", | |
| 77 | + messages=[{"role": "user", "content": "Describe Lyon, France."}], | |
| 78 | + response_format=City, | |
| 79 | + max_tokens=2000, | |
| 80 | + extra_body={"reasoning_effort": effort}, | |
| 81 | + ) | |
| 82 | + city = completion.choices[0].message.parsed | |
| 83 | + assert isinstance(city, City) | |
| 84 | + assert city.name | |
| 85 | + | |
| 86 | + | |
| 87 | +@pytest.mark.real_model | |
| 88 | +def test_json_object(client): | |
| 89 | + answer = client.chat.completions.create( | |
| 90 | + model="chat", | |
| 91 | + messages=[{"role": "user", "content": "Give me 3 French cheeses with their region."}], | |
| 92 | + response_format={"type": "json_object"}, | |
| 93 | + max_tokens=400, | |
| 94 | + extra_body=NO_THINKING, | |
| 95 | + ) | |
| 96 | + assert isinstance(json.loads(answer.choices[0].message.content), dict) | |
| 97 | + | |
| 98 | + | |
| 99 | +@pytest.mark.real_model | |
| 100 | +def test_streamed_json_schema_arrives_in_pieces(client): | |
| 101 | + stream = client.chat.completions.create( | |
| 102 | + model="chat", | |
| 103 | + messages=[{"role": "user", "content": "List 5 planets with their diameter in km."}], | |
| 104 | + response_format=PLANETS_SCHEMA, | |
| 105 | + max_tokens=400, | |
| 106 | + stream=True, | |
| 107 | + extra_body=NO_THINKING, | |
| 108 | + ) | |
| 109 | + pieces = [c.choices[0].delta.content for c in stream if c.choices and c.choices[0].delta.content] | |
| 110 | + assert len(pieces) > 5 | |
| 111 | + planets = json.loads("".join(pieces))["planets"] | |
| 112 | + assert all(set(planet) == {"name", "diameter_km"} for planet in planets) | |
| new file mode 100644 | |||
| @@ -0,0 +1,112 @@ | |||
| 1 | +"""`response_format` through the openai SDK, `parse()` included (ticket #39).""" | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | + | ||
| 5 | +import openai | ||
| 6 | +import pytest | ||
| 7 | +from pydantic import BaseModel | ||
| 8 | + | ||
| 9 | +from conftest import NO_THINKING | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +class City(BaseModel): | ||
| 13 | + name: str | ||
| 14 | + country: str | ||
| 15 | + population: int | ||
| 16 | + landmarks: list[str] | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +PLANETS_SCHEMA = { | ||
| 20 | + "type": "json_schema", | ||
| 21 | + "json_schema": { | ||
| 22 | + "name": "planets", | ||
| 23 | + "strict": True, | ||
| 24 | + "schema": { | ||
| 25 | + "type": "object", | ||
| 26 | + "additionalProperties": False, | ||
| 27 | + "required": ["planets"], | ||
| 28 | + "properties": { | ||
| 29 | + "planets": { | ||
| 30 | + "type": "array", | ||
| 31 | + "items": { | ||
| 32 | + "type": "object", | ||
| 33 | + "additionalProperties": False, | ||
| 34 | + "required": ["name", "diameter_km"], | ||
| 35 | + "properties": { | ||
| 36 | + "name": {"type": "string"}, | ||
| 37 | + "diameter_km": {"type": "number"}, | ||
| 38 | + }, | ||
| 39 | + }, | ||
| 40 | + } | ||
| 41 | + }, | ||
| 42 | + }, | ||
| 43 | + }, | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def test_strict_schema_with_unenforced_keyword_is_400(client): | ||
| 48 | + format_ = { | ||
| 49 | + "type": "json_schema", | ||
| 50 | + "json_schema": { | ||
| 51 | + "name": "tags", | ||
| 52 | + "strict": True, | ||
| 53 | + "schema": {"type": "array", "items": {"type": "string"}, "uniqueItems": True}, | ||
| 54 | + }, | ||
| 55 | + } | ||
| 56 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 57 | + client.chat.completions.create( | ||
| 58 | + model="chat", messages=[{"role": "user", "content": "3 tags"}], response_format=format_ | ||
| 59 | + ) | ||
| 60 | + assert "uniqueItems" in error.value.body["message"] | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def test_unknown_format_type_is_400(client): | ||
| 64 | + with pytest.raises(openai.BadRequestError): | ||
| 65 | + client.chat.completions.create( | ||
| 66 | + model="chat", | ||
| 67 | + messages=[{"role": "user", "content": "hi"}], | ||
| 68 | + response_format={"type": "yaml"}, | ||
| 69 | + ) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +@pytest.mark.real_model | ||
| 73 | +@pytest.mark.parametrize("effort", ["none", "low"]) | ||
| 74 | +def test_parse_with_a_pydantic_class(client, effort): | ||
| 75 | + completion = client.beta.chat.completions.parse( | ||
| 76 | + model="chat", | ||
| 77 | + messages=[{"role": "user", "content": "Describe Lyon, France."}], | ||
| 78 | + response_format=City, | ||
| 79 | + max_tokens=2000, | ||
| 80 | + extra_body={"reasoning_effort": effort}, | ||
| 81 | + ) | ||
| 82 | + city = completion.choices[0].message.parsed | ||
| 83 | + assert isinstance(city, City) | ||
| 84 | + assert city.name | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +@pytest.mark.real_model | ||
| 88 | +def test_json_object(client): | ||
| 89 | + answer = client.chat.completions.create( | ||
| 90 | + model="chat", | ||
| 91 | + messages=[{"role": "user", "content": "Give me 3 French cheeses with their region."}], | ||
| 92 | + response_format={"type": "json_object"}, | ||
| 93 | + max_tokens=400, | ||
| 94 | + extra_body=NO_THINKING, | ||
| 95 | + ) | ||
| 96 | + assert isinstance(json.loads(answer.choices[0].message.content), dict) | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +@pytest.mark.real_model | ||
| 100 | +def test_streamed_json_schema_arrives_in_pieces(client): | ||
| 101 | + stream = client.chat.completions.create( | ||
| 102 | + model="chat", | ||
| 103 | + messages=[{"role": "user", "content": "List 5 planets with their diameter in km."}], | ||
| 104 | + response_format=PLANETS_SCHEMA, | ||
| 105 | + max_tokens=400, | ||
| 106 | + stream=True, | ||
| 107 | + extra_body=NO_THINKING, | ||
| 108 | + ) | ||
| 109 | + pieces = [c.choices[0].delta.content for c in stream if c.choices and c.choices[0].delta.content] | ||
| 110 | + assert len(pieces) > 5 | ||
| 111 | + planets = json.loads("".join(pieces))["planets"] | ||
| 112 | + assert all(set(planet) == {"name", "diameter_km"} for planet in planets) | ||
added
Tests/Compatibility/test_tools.py +114 -0 | new file mode 100644 | ||
| @@ -0,0 +1,114 @@ | ||
| 1 | +"""Function calling through the openai SDK (tickets #40, #41).""" | |
| 2 | + | |
| 3 | +import json | |
| 4 | + | |
| 5 | +import openai | |
| 6 | +import pytest | |
| 7 | + | |
| 8 | +from conftest import NO_THINKING, TIME_TOOL, WEATHER_TOOL | |
| 9 | + | |
| 10 | +WEATHER_QUESTION = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | |
| 11 | + | |
| 12 | + | |
| 13 | +def ask(client, model="chat", messages=WEATHER_QUESTION, tools=(WEATHER_TOOL,), **options): | |
| 14 | + return client.chat.completions.create( | |
| 15 | + model=model, messages=messages, tools=list(tools), extra_body=NO_THINKING, **options | |
| 16 | + ) | |
| 17 | + | |
| 18 | + | |
| 19 | +def test_tool_choice_naming_an_unknown_tool_is_400(client): | |
| 20 | + with pytest.raises(openai.BadRequestError) as error: | |
| 21 | + ask(client, tool_choice={"type": "function", "function": {"name": "nope"}}) | |
| 22 | + assert error.value.body["param"] == "tool_choice" | |
| 23 | + | |
| 24 | + | |
| 25 | +def test_required_without_tools_is_400(client): | |
| 26 | + with pytest.raises(openai.BadRequestError): | |
| 27 | + client.chat.completions.create( | |
| 28 | + model="chat", messages=WEATHER_QUESTION, tool_choice="required" | |
| 29 | + ) | |
| 30 | + | |
| 31 | + | |
| 32 | +def test_invalid_tool_name_is_400(client): | |
| 33 | + tool = {"type": "function", "function": {"name": "get weather", "parameters": {}}} | |
| 34 | + with pytest.raises(openai.BadRequestError): | |
| 35 | + ask(client, tools=[tool]) | |
| 36 | + | |
| 37 | + | |
| 38 | +@pytest.mark.real_model | |
| 39 | +def test_round_trip_in_auto_mode(client): | |
| 40 | + first = ask(client) | |
| 41 | + message = first.choices[0].message | |
| 42 | + assert first.choices[0].finish_reason == "tool_calls" | |
| 43 | + call = message.tool_calls[0] | |
| 44 | + assert call.function.name == "get_weather" | |
| 45 | + assert "lyon" in json.loads(call.function.arguments)["city"].lower() | |
| 46 | + | |
| 47 | + result = {"city": "Lyon", "temp_c": 7, "sky": "rain"} | |
| 48 | + messages = [ | |
| 49 | + *WEATHER_QUESTION, | |
| 50 | + message.model_dump(exclude_none=True), | |
| 51 | + {"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}, | |
| 52 | + ] | |
| 53 | + final = ask(client, messages=messages).choices[0] | |
| 54 | + assert final.finish_reason == "stop" | |
| 55 | + assert "7" in final.message.content | |
| 56 | + | |
| 57 | + | |
| 58 | +@pytest.mark.real_model | |
| 59 | +def test_streamed_tool_call(client): | |
| 60 | + chunks = [chunk for chunk in ask(client, stream=True) if chunk.choices] | |
| 61 | + calls = [call for chunk in chunks for call in chunk.choices[0].delta.tool_calls or []] | |
| 62 | + assert calls[0].index == 0 | |
| 63 | + assert calls[0].id | |
| 64 | + assert calls[0].function.name == "get_weather" | |
| 65 | + assert chunks[-1].choices[0].finish_reason == "tool_calls" | |
| 66 | + | |
| 67 | + | |
| 68 | +@pytest.mark.real_model | |
| 69 | +@pytest.mark.parametrize( | |
| 70 | + "choice", ["required", {"type": "function", "function": {"name": "get_weather"}}] | |
| 71 | +) | |
| 72 | +def test_forced_call_even_off_topic(client, choice): | |
| 73 | + joke = [{"role": "user", "content": "Tell me a joke."}] | |
| 74 | + answer = ask(client, messages=joke, tool_choice=choice).choices[0] | |
| 75 | + assert answer.finish_reason == "tool_calls" | |
| 76 | + assert len(answer.message.tool_calls) == 1 | |
| 77 | + json.loads(answer.message.tool_calls[0].function.arguments) | |
| 78 | + | |
| 79 | + | |
| 80 | +@pytest.mark.real_model | |
| 81 | +def test_tool_choice_none_answers_in_text(client): | |
| 82 | + answer = ask(client, tool_choice="none").choices[0] | |
| 83 | + assert answer.finish_reason == "stop" | |
| 84 | + assert not answer.message.tool_calls | |
| 85 | + assert answer.message.content | |
| 86 | + | |
| 87 | + | |
| 88 | +@pytest.mark.real_model | |
| 89 | +@pytest.mark.parametrize(("parallel", "count"), [(True, 2), (False, 1)]) | |
| 90 | +def test_parallel_forced_calls(client, parallel, count): | |
| 91 | + question = [{"role": "user", "content": "What's the weather and the local time in Tokyo?"}] | |
| 92 | + answer = ask( | |
| 93 | + client, | |
| 94 | + messages=question, | |
| 95 | + tools=(WEATHER_TOOL, TIME_TOOL), | |
| 96 | + tool_choice="required", | |
| 97 | + parallel_tool_calls=parallel, | |
| 98 | + ) | |
| 99 | + calls = answer.choices[0].message.tool_calls | |
| 100 | + assert len(calls) == count | |
| 101 | + assert len({call.id for call in calls}) == count | |
| 102 | + | |
| 103 | + | |
| 104 | +@pytest.mark.real_model | |
| 105 | +def test_other_family_in_auto_mode(client, unforced_model): | |
| 106 | + message = ask(client, model=unforced_model).choices[0].message | |
| 107 | + assert message.tool_calls, f"no tool call; content: {message.content!r}" | |
| 108 | + assert message.tool_calls[0].function.name == "get_weather" | |
| 109 | + | |
| 110 | + | |
| 111 | +@pytest.mark.real_model | |
| 112 | +def test_other_family_cannot_be_forced(client, unforced_model): | |
| 113 | + with pytest.raises(openai.BadRequestError): | |
| 114 | + ask(client, model=unforced_model, tool_choice="required") | |
| new file mode 100644 | |||
| @@ -0,0 +1,114 @@ | |||
| 1 | +"""Function calling through the openai SDK (tickets #40, #41).""" | ||
| 2 | + | ||
| 3 | +import json | ||
| 4 | + | ||
| 5 | +import openai | ||
| 6 | +import pytest | ||
| 7 | + | ||
| 8 | +from conftest import NO_THINKING, TIME_TOOL, WEATHER_TOOL | ||
| 9 | + | ||
| 10 | +WEATHER_QUESTION = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def ask(client, model="chat", messages=WEATHER_QUESTION, tools=(WEATHER_TOOL,), **options): | ||
| 14 | + return client.chat.completions.create( | ||
| 15 | + model=model, messages=messages, tools=list(tools), extra_body=NO_THINKING, **options | ||
| 16 | + ) | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def test_tool_choice_naming_an_unknown_tool_is_400(client): | ||
| 20 | + with pytest.raises(openai.BadRequestError) as error: | ||
| 21 | + ask(client, tool_choice={"type": "function", "function": {"name": "nope"}}) | ||
| 22 | + assert error.value.body["param"] == "tool_choice" | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def test_required_without_tools_is_400(client): | ||
| 26 | + with pytest.raises(openai.BadRequestError): | ||
| 27 | + client.chat.completions.create( | ||
| 28 | + model="chat", messages=WEATHER_QUESTION, tool_choice="required" | ||
| 29 | + ) | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def test_invalid_tool_name_is_400(client): | ||
| 33 | + tool = {"type": "function", "function": {"name": "get weather", "parameters": {}}} | ||
| 34 | + with pytest.raises(openai.BadRequestError): | ||
| 35 | + ask(client, tools=[tool]) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +@pytest.mark.real_model | ||
| 39 | +def test_round_trip_in_auto_mode(client): | ||
| 40 | + first = ask(client) | ||
| 41 | + message = first.choices[0].message | ||
| 42 | + assert first.choices[0].finish_reason == "tool_calls" | ||
| 43 | + call = message.tool_calls[0] | ||
| 44 | + assert call.function.name == "get_weather" | ||
| 45 | + assert "lyon" in json.loads(call.function.arguments)["city"].lower() | ||
| 46 | + | ||
| 47 | + result = {"city": "Lyon", "temp_c": 7, "sky": "rain"} | ||
| 48 | + messages = [ | ||
| 49 | + *WEATHER_QUESTION, | ||
| 50 | + message.model_dump(exclude_none=True), | ||
| 51 | + {"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}, | ||
| 52 | + ] | ||
| 53 | + final = ask(client, messages=messages).choices[0] | ||
| 54 | + assert final.finish_reason == "stop" | ||
| 55 | + assert "7" in final.message.content | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +@pytest.mark.real_model | ||
| 59 | +def test_streamed_tool_call(client): | ||
| 60 | + chunks = [chunk for chunk in ask(client, stream=True) if chunk.choices] | ||
| 61 | + calls = [call for chunk in chunks for call in chunk.choices[0].delta.tool_calls or []] | ||
| 62 | + assert calls[0].index == 0 | ||
| 63 | + assert calls[0].id | ||
| 64 | + assert calls[0].function.name == "get_weather" | ||
| 65 | + assert chunks[-1].choices[0].finish_reason == "tool_calls" | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +@pytest.mark.real_model | ||
| 69 | +@pytest.mark.parametrize( | ||
| 70 | + "choice", ["required", {"type": "function", "function": {"name": "get_weather"}}] | ||
| 71 | +) | ||
| 72 | +def test_forced_call_even_off_topic(client, choice): | ||
| 73 | + joke = [{"role": "user", "content": "Tell me a joke."}] | ||
| 74 | + answer = ask(client, messages=joke, tool_choice=choice).choices[0] | ||
| 75 | + assert answer.finish_reason == "tool_calls" | ||
| 76 | + assert len(answer.message.tool_calls) == 1 | ||
| 77 | + json.loads(answer.message.tool_calls[0].function.arguments) | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +@pytest.mark.real_model | ||
| 81 | +def test_tool_choice_none_answers_in_text(client): | ||
| 82 | + answer = ask(client, tool_choice="none").choices[0] | ||
| 83 | + assert answer.finish_reason == "stop" | ||
| 84 | + assert not answer.message.tool_calls | ||
| 85 | + assert answer.message.content | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +@pytest.mark.real_model | ||
| 89 | +@pytest.mark.parametrize(("parallel", "count"), [(True, 2), (False, 1)]) | ||
| 90 | +def test_parallel_forced_calls(client, parallel, count): | ||
| 91 | + question = [{"role": "user", "content": "What's the weather and the local time in Tokyo?"}] | ||
| 92 | + answer = ask( | ||
| 93 | + client, | ||
| 94 | + messages=question, | ||
| 95 | + tools=(WEATHER_TOOL, TIME_TOOL), | ||
| 96 | + tool_choice="required", | ||
| 97 | + parallel_tool_calls=parallel, | ||
| 98 | + ) | ||
| 99 | + calls = answer.choices[0].message.tool_calls | ||
| 100 | + assert len(calls) == count | ||
| 101 | + assert len({call.id for call in calls}) == count | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +@pytest.mark.real_model | ||
| 105 | +def test_other_family_in_auto_mode(client, unforced_model): | ||
| 106 | + message = ask(client, model=unforced_model).choices[0].message | ||
| 107 | + assert message.tool_calls, f"no tool call; content: {message.content!r}" | ||
| 108 | + assert message.tool_calls[0].function.name == "get_weather" | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +@pytest.mark.real_model | ||
| 112 | +def test_other_family_cannot_be_forced(client, unforced_model): | ||
| 113 | + with pytest.raises(openai.BadRequestError): | ||
| 114 | + ask(client, model=unforced_model, tool_choice="required") | ||
added
Tests/RazorbillCoreTests/OrderedJSONTests.swift +61 -0 | new file mode 100644 | ||
| @@ -0,0 +1,61 @@ | ||
| 1 | +import Foundation | |
| 2 | +import RazorbillCore | |
| 3 | +import Testing | |
| 4 | + | |
| 5 | +@Suite struct OrderedJSONTests { | |
| 6 | + @Test func objectKeysKeepTheirOrder() throws { | |
| 7 | + let text = #"{"name":"x","country":"y","population":1,"landmarks":[],"a":{"z":1,"b":2}}"# | |
| 8 | + let value = try ConfigValue(orderedJSON: Data(text.utf8)) | |
| 9 | + guard case .map(let entries) = value else { | |
| 10 | + Issue.record("not a map") | |
| 11 | + return | |
| 12 | + } | |
| 13 | + #expect(entries.keys == ["name", "country", "population", "landmarks", "a"]) | |
| 14 | + #expect(value.jsonString == text) | |
| 15 | + } | |
| 16 | + | |
| 17 | + @Test func scalarsAndEscapes() throws { | |
| 18 | + let text = #"[null, true, false, -12, 2.5, 1e3, "a\"b\\c\/d\n\té😀", ""]"# | |
| 19 | + let value = try ConfigValue(orderedJSON: Data(text.utf8)) | |
| 20 | + #expect( | |
| 21 | + value | |
| 22 | + == .list([ | |
| 23 | + .null, .bool(true), .bool(false), .int(-12), .double(2.5), .double(1000), | |
| 24 | + .string("a\"b\\c/d\n\té😀"), .string(""), | |
| 25 | + ])) | |
| 26 | + } | |
| 27 | + | |
| 28 | + @Test func agreesWithJSONDecoderButForOrder() throws { | |
| 29 | + let text = #"{"b":[1,{"y":null,"x":"é"}],"a":{"nested":[true,0.25]},"c":"A"}"# | |
| 30 | + let ordered = try ConfigValue(orderedJSON: Data(text.utf8)) | |
| 31 | + let decoded = try JSONDecoder().decode(ConfigValue.self, from: Data(text.utf8)) | |
| 32 | + #expect(ordered == decoded) | |
| 33 | + #expect( | |
| 34 | + decoded.jsonString | |
| 35 | + == #"{"a":{"nested":[true,0.25]},"b":[1,{"x":"é","y":null}],"c":"A"}"#) | |
| 36 | + } | |
| 37 | + | |
| 38 | + @Test(arguments: ["", "{", #"{"a" 1}"#, "[1,]", "[1 2]", "tru", #""abc"#, "1 2", #"{"a":1,}"#]) | |
| 39 | + func malformedTextThrows(_ text: String) { | |
| 40 | + #expect(throws: InvalidJSON.self) { try ConfigValue(orderedJSON: Data(text.utf8)) } | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +@Suite struct ConfigMapTests { | |
| 45 | + @Test func insertionOrderAndRemoval() { | |
| 46 | + var map: ConfigMap = ["b": .int(1), "a": .int(2)] | |
| 47 | + map["c"] = .int(3) | |
| 48 | + map["b"] = .int(4) | |
| 49 | + #expect(map.keys == ["b", "a", "c"]) | |
| 50 | + map["a"] = nil | |
| 51 | + #expect(map.keys == ["b", "c"] && map.count == 2) | |
| 52 | + #expect(map.map(\.key) == ["b", "c"]) | |
| 53 | + } | |
| 54 | + | |
| 55 | + @Test func equalityIgnoresOrder() { | |
| 56 | + let left: ConfigMap = ["a": .int(1), "b": .int(2)] | |
| 57 | + let right: ConfigMap = ["b": .int(2), "a": .int(1)] | |
| 58 | + #expect(left == right) | |
| 59 | + #expect(ConfigMap(["z": .null, "m": .null]).keys == ["m", "z"]) | |
| 60 | + } | |
| 61 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import RazorbillCore | ||
| 3 | +import Testing | ||
| 4 | + | ||
| 5 | +@Suite struct OrderedJSONTests { | ||
| 6 | + @Test func objectKeysKeepTheirOrder() throws { | ||
| 7 | + let text = #"{"name":"x","country":"y","population":1,"landmarks":[],"a":{"z":1,"b":2}}"# | ||
| 8 | + let value = try ConfigValue(orderedJSON: Data(text.utf8)) | ||
| 9 | + guard case .map(let entries) = value else { | ||
| 10 | + Issue.record("not a map") | ||
| 11 | + return | ||
| 12 | + } | ||
| 13 | + #expect(entries.keys == ["name", "country", "population", "landmarks", "a"]) | ||
| 14 | + #expect(value.jsonString == text) | ||
| 15 | + } | ||
| 16 | + | ||
| 17 | + @Test func scalarsAndEscapes() throws { | ||
| 18 | + let text = #"[null, true, false, -12, 2.5, 1e3, "a\"b\\c\/d\n\té😀", ""]"# | ||
| 19 | + let value = try ConfigValue(orderedJSON: Data(text.utf8)) | ||
| 20 | + #expect( | ||
| 21 | + value | ||
| 22 | + == .list([ | ||
| 23 | + .null, .bool(true), .bool(false), .int(-12), .double(2.5), .double(1000), | ||
| 24 | + .string("a\"b\\c/d\n\té😀"), .string(""), | ||
| 25 | + ])) | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + @Test func agreesWithJSONDecoderButForOrder() throws { | ||
| 29 | + let text = #"{"b":[1,{"y":null,"x":"é"}],"a":{"nested":[true,0.25]},"c":"A"}"# | ||
| 30 | + let ordered = try ConfigValue(orderedJSON: Data(text.utf8)) | ||
| 31 | + let decoded = try JSONDecoder().decode(ConfigValue.self, from: Data(text.utf8)) | ||
| 32 | + #expect(ordered == decoded) | ||
| 33 | + #expect( | ||
| 34 | + decoded.jsonString | ||
| 35 | + == #"{"a":{"nested":[true,0.25]},"b":[1,{"x":"é","y":null}],"c":"A"}"#) | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + @Test(arguments: ["", "{", #"{"a" 1}"#, "[1,]", "[1 2]", "tru", #""abc"#, "1 2", #"{"a":1,}"#]) | ||
| 39 | + func malformedTextThrows(_ text: String) { | ||
| 40 | + #expect(throws: InvalidJSON.self) { try ConfigValue(orderedJSON: Data(text.utf8)) } | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +@Suite struct ConfigMapTests { | ||
| 45 | + @Test func insertionOrderAndRemoval() { | ||
| 46 | + var map: ConfigMap = ["b": .int(1), "a": .int(2)] | ||
| 47 | + map["c"] = .int(3) | ||
| 48 | + map["b"] = .int(4) | ||
| 49 | + #expect(map.keys == ["b", "a", "c"]) | ||
| 50 | + map["a"] = nil | ||
| 51 | + #expect(map.keys == ["b", "c"] && map.count == 2) | ||
| 52 | + #expect(map.map(\.key) == ["b", "c"]) | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + @Test func equalityIgnoresOrder() { | ||
| 56 | + let left: ConfigMap = ["a": .int(1), "b": .int(2)] | ||
| 57 | + let right: ConfigMap = ["b": .int(2), "a": .int(1)] | ||
| 58 | + #expect(left == right) | ||
| 59 | + #expect(ConfigMap(["z": .null, "m": .null]).keys == ["m", "z"]) | ||
| 60 | + } | ||
| 61 | +} | ||
modified
Tests/RazorbillServerTests/ToolsAndFormatsTests.swift +57 -3 | @@ -42,10 +42,42 @@ let timeTool = #"{"type":"function","function":{"name":"time"}}"# | ||
| 42 | 42 | let format = |
| 43 | 43 | #","response_format":{"type":"json_schema","json_schema":{"name":"x","strict":true,"schema":"# |
| 44 | 44 | + schema + "}}" |
| 45 | + // The schema reaches the decoder with the client's key order (#43). | |
| 46 | + #expect(try plan(format).output.constraint == .jsonSchema(schema)) | |
| 47 | + } | |
| 48 | + | |
| 49 | + @Test func schemaKeyOrderIsKept() throws { | |
| 50 | + let schema = | |
| 51 | + #"{"type":"object","properties":{"reasoning":{"type":"string"},"answer":{"type":"string"}},"# | |
| 52 | + + #""required":["reasoning","answer"]}"# | |
| 53 | + let format = | |
| 54 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","schema":"# | |
| 55 | + + schema + "}}" | |
| 56 | + #expect(try plan(format).output.constraint == .jsonSchema(schema)) | |
| 57 | + } | |
| 58 | + | |
| 59 | + @Test func jsonFormatsTellTheModelWhatToWrite() throws { | |
| 60 | + let schema = | |
| 61 | + #"{"type":"object","properties":{"b":{"type":"integer"},"a":{"type":"string"}}}"# | |
| 62 | + let format = | |
| 63 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","schema":"# | |
| 64 | + + schema + "}}" | |
| 65 | + let added = try plan(format).messages | |
| 66 | + #expect(added.count == 2 && added[0].role == .system) | |
| 67 | + #expect(added[0].content.hasSuffix("follows this JSON Schema:\n" + schema)) | |
| 68 | + | |
| 69 | + let object = try plan(#","response_format":{"type":"json_object"}"#).messages | |
| 45 | 70 | #expect( |
| 46 | - try plan(format).output.constraint | |
| 47 | - == .jsonSchema( | |
| 48 | - #"{"properties":{"n":{"type":"integer"}},"required":["n"],"type":"object"}"#)) | |
| 71 | + object[0] == ChatMessage(role: .system, content: "Answer with a single JSON object.")) | |
| 72 | + #expect(try plan(#","response_format":{"type":"text"}"#).messages.count == 1) | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Test func instructionIsAppendedToAnExistingSystemMessage() { | |
| 76 | + let messages = [ChatMessage(role: .system, content: "Be brief."), .user("hi")] | |
| 77 | + let result = ChatCompletionRequest.adding("Answer in JSON.", to: messages) | |
| 78 | + #expect(result.count == 2) | |
| 79 | + #expect(result[0].content == "Be brief.\n\nAnswer in JSON.") | |
| 80 | + #expect(ChatCompletionRequest.adding(nil, to: messages) == messages) | |
| 49 | 81 | } |
| 50 | 82 | |
| 51 | 83 | @Test func strictSchemasWithUnenforcedKeywordsAre400s() throws { |
| @@ -231,3 +263,25 @@ let timeTool = #"{"type":"function","function":{"name":"time"}}"# | ||
| 231 | 263 | == nil) |
| 232 | 264 | } |
| 233 | 265 | } |
| 266 | + | |
| 267 | +@Test func toolParametersKeepTheirKeyOrder() throws { | |
| 268 | + let tool = | |
| 269 | + #"{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":"# | |
| 270 | + + #"{"zeta":{"type":"string"},"alpha":{"type":"integer"}}}}}"# | |
| 271 | + let output = try plan(#","tools":["# + tool + "]").output | |
| 272 | + guard case .map(let properties)? = output.tools[0].parameters["properties"] else { | |
| 273 | + Issue.record("no properties") | |
| 274 | + return | |
| 275 | + } | |
| 276 | + #expect(properties.keys == ["zeta", "alpha"]) | |
| 277 | +} | |
| 278 | + | |
| 279 | +@Test func assistantToolCallArgumentsKeepTheirOrder() throws { | |
| 280 | + let body = | |
| 281 | + #"{"model":"m","messages":[{"role":"user","content":"hi"},"# | |
| 282 | + + #"{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","# | |
| 283 | + + #""function":{"name":"f","arguments":"{\"b\":1,\"a\":2}"}}]},"# | |
| 284 | + + #"{"role":"tool","tool_call_id":"c1","content":"ok"}]}"# | |
| 285 | + let messages = try ChatCompletionRequest.decode(Data(body.utf8)).validated().messages | |
| 286 | + #expect(messages[1].toolCalls[0].arguments.keys == ["b", "a"]) | |
| 287 | +} | |
| @@ -42,10 +42,42 @@ let timeTool = #"{"type":"function","function":{"name":"time"}}"# | |||
| 42 | let format = | 42 | let format = |
| 43 | #","response_format":{"type":"json_schema","json_schema":{"name":"x","strict":true,"schema":"# | 43 | #","response_format":{"type":"json_schema","json_schema":{"name":"x","strict":true,"schema":"# |
| 44 | + schema + "}}" | 44 | + schema + "}}" |
| 45 | + // The schema reaches the decoder with the client's key order (#43). | ||
| 46 | + #expect(try plan(format).output.constraint == .jsonSchema(schema)) | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + @Test func schemaKeyOrderIsKept() throws { | ||
| 50 | + let schema = | ||
| 51 | + #"{"type":"object","properties":{"reasoning":{"type":"string"},"answer":{"type":"string"}},"# | ||
| 52 | + + #""required":["reasoning","answer"]}"# | ||
| 53 | + let format = | ||
| 54 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","schema":"# | ||
| 55 | + + schema + "}}" | ||
| 56 | + #expect(try plan(format).output.constraint == .jsonSchema(schema)) | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + @Test func jsonFormatsTellTheModelWhatToWrite() throws { | ||
| 60 | + let schema = | ||
| 61 | + #"{"type":"object","properties":{"b":{"type":"integer"},"a":{"type":"string"}}}"# | ||
| 62 | + let format = | ||
| 63 | + #","response_format":{"type":"json_schema","json_schema":{"name":"x","schema":"# | ||
| 64 | + + schema + "}}" | ||
| 65 | + let added = try plan(format).messages | ||
| 66 | + #expect(added.count == 2 && added[0].role == .system) | ||
| 67 | + #expect(added[0].content.hasSuffix("follows this JSON Schema:\n" + schema)) | ||
| 68 | + | ||
| 69 | + let object = try plan(#","response_format":{"type":"json_object"}"#).messages | ||
| 45 | #expect( | 70 | #expect( |
| 46 | - try plan(format).output.constraint | 71 | + object[0] == ChatMessage(role: .system, content: "Answer with a single JSON object.")) |
| 47 | - == .jsonSchema( | 72 | + #expect(try plan(#","response_format":{"type":"text"}"#).messages.count == 1) |
| 48 | - #"{"properties":{"n":{"type":"integer"}},"required":["n"],"type":"object"}"#)) | 73 | + } |
| 74 | + | ||
| 75 | + @Test func instructionIsAppendedToAnExistingSystemMessage() { | ||
| 76 | + let messages = [ChatMessage(role: .system, content: "Be brief."), .user("hi")] | ||
| 77 | + let result = ChatCompletionRequest.adding("Answer in JSON.", to: messages) | ||
| 78 | + #expect(result.count == 2) | ||
| 79 | + #expect(result[0].content == "Be brief.\n\nAnswer in JSON.") | ||
| 80 | + #expect(ChatCompletionRequest.adding(nil, to: messages) == messages) | ||
| 49 | } | 81 | } |
| 50 | 82 | ||
| 51 | @Test func strictSchemasWithUnenforcedKeywordsAre400s() throws { | 83 | @Test func strictSchemasWithUnenforcedKeywordsAre400s() throws { |
| @@ -231,3 +263,25 @@ let timeTool = #"{"type":"function","function":{"name":"time"}}"# | |||
| 231 | == nil) | 263 | == nil) |
| 232 | } | 264 | } |
| 233 | } | 265 | } |
| 266 | + | ||
| 267 | +@Test func toolParametersKeepTheirKeyOrder() throws { | ||
| 268 | + let tool = | ||
| 269 | + #"{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":"# | ||
| 270 | + + #"{"zeta":{"type":"string"},"alpha":{"type":"integer"}}}}}"# | ||
| 271 | + let output = try plan(#","tools":["# + tool + "]").output | ||
| 272 | + guard case .map(let properties)? = output.tools[0].parameters["properties"] else { | ||
| 273 | + Issue.record("no properties") | ||
| 274 | + return | ||
| 275 | + } | ||
| 276 | + #expect(properties.keys == ["zeta", "alpha"]) | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +@Test func assistantToolCallArgumentsKeepTheirOrder() throws { | ||
| 280 | + let body = | ||
| 281 | + #"{"model":"m","messages":[{"role":"user","content":"hi"},"# | ||
| 282 | + + #"{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","# | ||
| 283 | + + #""function":{"name":"f","arguments":"{\"b\":1,\"a\":2}"}}]},"# | ||
| 284 | + + #"{"role":"tool","tool_call_id":"c1","content":"ok"}]}"# | ||
| 285 | + let messages = try ChatCompletionRequest.decode(Data(body.utf8)).validated().messages | ||
| 286 | + #expect(messages[1].toolCalls[0].arguments.keys == ["b", "a"]) | ||
| 287 | +} | ||
added
scripts/compat.sh +80 -0 | new file mode 100755 | ||
| @@ -0,0 +1,80 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# OpenAI compatibility suite (ticket #43): official clients (openai SDK, LangChain, curl examples | |
| 3 | +# of the docs) against a real `rzb serve`. | |
| 4 | +# | |
| 5 | +# scripts/compat.sh start a server, run the suite, stop the server | |
| 6 | +# scripts/compat.sh -k tools extra arguments go to pytest | |
| 7 | +# RZB_URL=http://host:8080/v1 scripts/compat.sh use a server already running | |
| 8 | +# | |
| 9 | +# On Linux the server runs the fake engine: the protocol is checked, real-model tests are skipped. | |
| 10 | +# On the Mac it runs MLX with these models (pull them first with `rzb models pull`): | |
| 11 | +# RZB_COMPAT_CHAT_SOURCE default mlx-community/Qwen3-4B-4bit | |
| 12 | +# RZB_COMPAT_EMBED_SOURCE default BAAI/bge-small-en-v1.5 | |
| 13 | +# RZB_COMPAT_UNFORCED_SOURCE default mlx-community/Llama-3.2-3B-Instruct-4bit (used if cached) | |
| 14 | +# Other knobs: RZB_BIN (the rzb binary), RZB_COMPAT_PORT (default 18080). | |
| 15 | +set -euo pipefail | |
| 16 | +cd "$(dirname "$0")/.." | |
| 17 | + | |
| 18 | +export RZB_COMPAT_CHAT_SOURCE="${RZB_COMPAT_CHAT_SOURCE:-mlx-community/Qwen3-4B-4bit}" | |
| 19 | +export RZB_COMPAT_EMBED_SOURCE="${RZB_COMPAT_EMBED_SOURCE:-BAAI/bge-small-en-v1.5}" | |
| 20 | +UNFORCED_SOURCE="${RZB_COMPAT_UNFORCED_SOURCE:-mlx-community/Llama-3.2-3B-Instruct-4bit}" | |
| 21 | +PORT="${RZB_COMPAT_PORT:-18080}" | |
| 22 | +HUB="${HF_HUB_CACHE:-${HF_HOME:-$HOME/.cache/huggingface}/hub}" | |
| 23 | + | |
| 24 | +run_suite() { | |
| 25 | + uv run --quiet --with-requirements Tests/Compatibility/requirements.txt \ | |
| 26 | + pytest Tests/Compatibility -q -p no:cacheprovider "$@" | |
| 27 | +} | |
| 28 | + | |
| 29 | +if [[ -n "${RZB_URL:-}" ]]; then | |
| 30 | + run_suite "$@" | |
| 31 | + exit | |
| 32 | +fi | |
| 33 | + | |
| 34 | +is_cached() { [[ -d "$HUB/models--${1//\//--}" ]]; } | |
| 35 | + | |
| 36 | +if [[ "$(uname)" == "Darwin" ]]; then | |
| 37 | + RZB_BIN="${RZB_BIN:-.build/xcode/Build/Products/Release/rzb}" | |
| 38 | + if [[ ! -x "$RZB_BIN" ]]; then | |
| 39 | + xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \ | |
| 40 | + -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation -quiet | |
| 41 | + fi | |
| 42 | + for model in "$RZB_COMPAT_CHAT_SOURCE" "$RZB_COMPAT_EMBED_SOURCE"; do | |
| 43 | + is_cached "$model" || { echo "missing model: run rzb models pull $model" >&2; exit 1; } | |
| 44 | + done | |
| 45 | +else | |
| 46 | + RZB_BIN="${RZB_BIN:-.build/linux/debug/rzb}" | |
| 47 | + swift build --scratch-path .build/linux --product rzb >&2 | |
| 48 | +fi | |
| 49 | + | |
| 50 | +work="$(mktemp -d)" | |
| 51 | +config="$work/server.yaml" | |
| 52 | +cat > "$config" <<YAML | |
| 53 | +server: { host: 127.0.0.1, port: $PORT } | |
| 54 | +models: | |
| 55 | + - { id: chat, source: $RZB_COMPAT_CHAT_SOURCE, kind: chat } | |
| 56 | + - { id: embed, source: $RZB_COMPAT_EMBED_SOURCE, kind: embedding } | |
| 57 | +YAML | |
| 58 | +if [[ "$(uname)" == "Darwin" ]] && is_cached "$UNFORCED_SOURCE"; then | |
| 59 | + echo " - { id: unforced, source: $UNFORCED_SOURCE, kind: chat }" >> "$config" | |
| 60 | +fi | |
| 61 | +printf 'limits: { max_loaded_models: 2, keep_alive: 10m }\n' >> "$config" | |
| 62 | + | |
| 63 | +"$RZB_BIN" serve --config "$config" > "$work/server.log" 2>&1 & | |
| 64 | +server=$! | |
| 65 | +trap 'kill $server 2>/dev/null; wait $server 2>/dev/null; rm -rf "$work"' EXIT | |
| 66 | + | |
| 67 | +for _ in $(seq 100); do | |
| 68 | + curl -sf "http://127.0.0.1:$PORT/health" > /dev/null && break | |
| 69 | + kill -0 "$server" 2>/dev/null || { cat "$work/server.log" >&2; exit 1; } | |
| 70 | + sleep 0.2 | |
| 71 | +done | |
| 72 | + | |
| 73 | +export RZB_URL="http://127.0.0.1:$PORT/v1" | |
| 74 | +status=0 | |
| 75 | +run_suite "$@" || status=$? | |
| 76 | +if (( status != 0 )); then | |
| 77 | + echo "--- server log (last 40 lines) ---" >&2 | |
| 78 | + tail -n 40 "$work/server.log" >&2 | |
| 79 | +fi | |
| 80 | +exit "$status" | |
| new file mode 100755 | |||
| @@ -0,0 +1,80 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# OpenAI compatibility suite (ticket #43): official clients (openai SDK, LangChain, curl examples | ||
| 3 | +# of the docs) against a real `rzb serve`. | ||
| 4 | +# | ||
| 5 | +# scripts/compat.sh start a server, run the suite, stop the server | ||
| 6 | +# scripts/compat.sh -k tools extra arguments go to pytest | ||
| 7 | +# RZB_URL=http://host:8080/v1 scripts/compat.sh use a server already running | ||
| 8 | +# | ||
| 9 | +# On Linux the server runs the fake engine: the protocol is checked, real-model tests are skipped. | ||
| 10 | +# On the Mac it runs MLX with these models (pull them first with `rzb models pull`): | ||
| 11 | +# RZB_COMPAT_CHAT_SOURCE default mlx-community/Qwen3-4B-4bit | ||
| 12 | +# RZB_COMPAT_EMBED_SOURCE default BAAI/bge-small-en-v1.5 | ||
| 13 | +# RZB_COMPAT_UNFORCED_SOURCE default mlx-community/Llama-3.2-3B-Instruct-4bit (used if cached) | ||
| 14 | +# Other knobs: RZB_BIN (the rzb binary), RZB_COMPAT_PORT (default 18080). | ||
| 15 | +set -euo pipefail | ||
| 16 | +cd "$(dirname "$0")/.." | ||
| 17 | + | ||
| 18 | +export RZB_COMPAT_CHAT_SOURCE="${RZB_COMPAT_CHAT_SOURCE:-mlx-community/Qwen3-4B-4bit}" | ||
| 19 | +export RZB_COMPAT_EMBED_SOURCE="${RZB_COMPAT_EMBED_SOURCE:-BAAI/bge-small-en-v1.5}" | ||
| 20 | +UNFORCED_SOURCE="${RZB_COMPAT_UNFORCED_SOURCE:-mlx-community/Llama-3.2-3B-Instruct-4bit}" | ||
| 21 | +PORT="${RZB_COMPAT_PORT:-18080}" | ||
| 22 | +HUB="${HF_HUB_CACHE:-${HF_HOME:-$HOME/.cache/huggingface}/hub}" | ||
| 23 | + | ||
| 24 | +run_suite() { | ||
| 25 | + uv run --quiet --with-requirements Tests/Compatibility/requirements.txt \ | ||
| 26 | + pytest Tests/Compatibility -q -p no:cacheprovider "$@" | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +if [[ -n "${RZB_URL:-}" ]]; then | ||
| 30 | + run_suite "$@" | ||
| 31 | + exit | ||
| 32 | +fi | ||
| 33 | + | ||
| 34 | +is_cached() { [[ -d "$HUB/models--${1//\//--}" ]]; } | ||
| 35 | + | ||
| 36 | +if [[ "$(uname)" == "Darwin" ]]; then | ||
| 37 | + RZB_BIN="${RZB_BIN:-.build/xcode/Build/Products/Release/rzb}" | ||
| 38 | + if [[ ! -x "$RZB_BIN" ]]; then | ||
| 39 | + xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \ | ||
| 40 | + -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation -quiet | ||
| 41 | + fi | ||
| 42 | + for model in "$RZB_COMPAT_CHAT_SOURCE" "$RZB_COMPAT_EMBED_SOURCE"; do | ||
| 43 | + is_cached "$model" || { echo "missing model: run rzb models pull $model" >&2; exit 1; } | ||
| 44 | + done | ||
| 45 | +else | ||
| 46 | + RZB_BIN="${RZB_BIN:-.build/linux/debug/rzb}" | ||
| 47 | + swift build --scratch-path .build/linux --product rzb >&2 | ||
| 48 | +fi | ||
| 49 | + | ||
| 50 | +work="$(mktemp -d)" | ||
| 51 | +config="$work/server.yaml" | ||
| 52 | +cat > "$config" <<YAML | ||
| 53 | +server: { host: 127.0.0.1, port: $PORT } | ||
| 54 | +models: | ||
| 55 | + - { id: chat, source: $RZB_COMPAT_CHAT_SOURCE, kind: chat } | ||
| 56 | + - { id: embed, source: $RZB_COMPAT_EMBED_SOURCE, kind: embedding } | ||
| 57 | +YAML | ||
| 58 | +if [[ "$(uname)" == "Darwin" ]] && is_cached "$UNFORCED_SOURCE"; then | ||
| 59 | + echo " - { id: unforced, source: $UNFORCED_SOURCE, kind: chat }" >> "$config" | ||
| 60 | +fi | ||
| 61 | +printf 'limits: { max_loaded_models: 2, keep_alive: 10m }\n' >> "$config" | ||
| 62 | + | ||
| 63 | +"$RZB_BIN" serve --config "$config" > "$work/server.log" 2>&1 & | ||
| 64 | +server=$! | ||
| 65 | +trap 'kill $server 2>/dev/null; wait $server 2>/dev/null; rm -rf "$work"' EXIT | ||
| 66 | + | ||
| 67 | +for _ in $(seq 100); do | ||
| 68 | + curl -sf "http://127.0.0.1:$PORT/health" > /dev/null && break | ||
| 69 | + kill -0 "$server" 2>/dev/null || { cat "$work/server.log" >&2; exit 1; } | ||
| 70 | + sleep 0.2 | ||
| 71 | +done | ||
| 72 | + | ||
| 73 | +export RZB_URL="http://127.0.0.1:$PORT/v1" | ||
| 74 | +status=0 | ||
| 75 | +run_suite "$@" || status=$? | ||
| 76 | +if (( status != 0 )); then | ||
| 77 | + echo "--- server log (last 40 lines) ---" >&2 | ||
| 78 | + tail -n 40 "$work/server.log" >&2 | ||
| 79 | +fi | ||
| 80 | +exit "$status" | ||