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

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

Download ZIP

v0.2 step 12 — server documentation, EN + FR (#45)

Diátaxis docs rewritten around the server: tutorial (first requests with
curl and the openai SDK), how-to guides (configuration, OpenAI clients,
structured output, function calling, embeddings, reasoning), reference (HTTP
API, errors, configuration file, command line) and explanations
(architecture, model lifecycle, constrained decoding, OpenAI compatibility,
reasoning). Agent-era pages removed; README and module diagram updated.

The curl examples of the API reference are run by the compatibility suite.
Closes #45 and #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-25T20:13:15+01:00 Browse files
f2a20f5 parent: c1a7231
modified .memory/handoffs/2026-11-25-v0-2-server-foundation.md +6 -0
@@ -92,3 +92,9 @@ curl examples in `docs/*/reference/*.md` as ```bash blocks hitting http://127.0.
9292 `/v1/completions` done. Only #45 (docs EN+FR) remains in v0.2; also document: the JSON instruction
9393 added to the system prompt (#43), schema key order kept, max_tokens default for completions,
9494 completions refusals. Mac compat suite not re-run since #44 (Linux green; Mac XCTest green).
95+
96+## Update — #45 closed, v0.2 work done
97+Docs EN+FR rewritten (see summary). Remaining in the v0.2 milestone: #47 (KV-cache spike, open,
98+priority high). Release not started: version string is still 0.1.0, milestone not closed — use the
99+release skill only when the user asks. Mac run of `scripts/compat.sh` (now 14 doc curl examples) not
100+done since #44.
@@ -92,3 +92,9 @@ curl examples in `docs/*/reference/*.md` as ```bash blocks hitting http://127.0.
92 `/v1/completions` done. Only #45 (docs EN+FR) remains in v0.2; also document: the JSON instruction92 `/v1/completions` done. Only #45 (docs EN+FR) remains in v0.2; also document: the JSON instruction
93 added to the system prompt (#43), schema key order kept, max_tokens default for completions,93 added to the system prompt (#43), schema key order kept, max_tokens default for completions,
94 completions refusals. Mac compat suite not re-run since #44 (Linux green; Mac XCTest green).94 completions refusals. Mac compat suite not re-run since #44 (Linux green; Mac XCTest green).
95+
96+## Update — #45 closed, v0.2 work done
97+Docs EN+FR rewritten (see summary). Remaining in the v0.2 milestone: #47 (KV-cache spike, open,
98+priority high). Release not started: version string is still 0.1.0, milestone not closed — use the
99+release skill only when the user asks. Mac run of `scripts/compat.sh` (now 14 doc curl examples) not
100+done since #44.
modified .memory/history.md +15 -0
@@ -248,3 +248,18 @@ not OpenAI's 16 (to document in #45). Gate first failed on duplicated envelope c
248248 `TextCompletion` and `ChatCompletionChunk` → generic `CompletionEnvelope<Choice: EnvelopeChoice>`.
249249 Field checks shared via `FieldChecking`. Tests: Linux 161, Mac 185 (real Qwen3-0.6B: "The capital of
250250 France is" → Paris), compat Linux 34 pass / 21 skip. Gate PASS (run #20). Mac compat run not redone.
251+
252+## 2026-11-25 — #45 server documentation (EN + FR)
253+
254+User: "vas y". Rewrote docs/en and docs/fr (Diátaxis) around the server; removed the agent pages
255+(add-a-tool, bash tool, rzb in scripts, tool safety; FR equivalents). New: tutorial (first requests
256+with curl + openai SDK), how-to configure-the-server / use-openai-clients / get-structured-output /
257+use-function-calling / compute-embeddings, configure-thinking rewritten as "control reasoning";
258+reference http-api, errors, configuration and cli rewritten; explanation architecture,
259+model-lifecycle, constrained-decoding, openai-compatibility, thinking updated. Facts taken from the
260+code (CLI options, config keys and messages, error codes/messages, defaults: temperature 0.6, top_p
261+1.0, max_tokens 1024, thinking false). README rewritten; packages.drawio: TUI → RazorbillServer,
262+Hummingbird box. test_docs_curl.py maps doc model ids to the suite's ids: 14 curl examples pass
263+(Linux/fake). Link/anchor check script: 0 broken. Gate PASS (run #21). Closed #45 and #31 (its last
264+task was the architecture doc). Not done: Mac run of the doc curl examples (needs the user), version
265+bump to 0.2.0 (release step), milestone still has #47 open.
@@ -248,3 +248,18 @@ not OpenAI's 16 (to document in #45). Gate first failed on duplicated envelope c
248 `TextCompletion` and `ChatCompletionChunk` → generic `CompletionEnvelope<Choice: EnvelopeChoice>`.248 `TextCompletion` and `ChatCompletionChunk` → generic `CompletionEnvelope<Choice: EnvelopeChoice>`.
249 Field checks shared via `FieldChecking`. Tests: Linux 161, Mac 185 (real Qwen3-0.6B: "The capital of249 Field checks shared via `FieldChecking`. Tests: Linux 161, Mac 185 (real Qwen3-0.6B: "The capital of
250 France is" → Paris), compat Linux 34 pass / 21 skip. Gate PASS (run #20). Mac compat run not redone.250 France is" → Paris), compat Linux 34 pass / 21 skip. Gate PASS (run #20). Mac compat run not redone.
251+
252+## 2026-11-25 — #45 server documentation (EN + FR)
253+
254+User: "vas y". Rewrote docs/en and docs/fr (Diátaxis) around the server; removed the agent pages
255+(add-a-tool, bash tool, rzb in scripts, tool safety; FR equivalents). New: tutorial (first requests
256+with curl + openai SDK), how-to configure-the-server / use-openai-clients / get-structured-output /
257+use-function-calling / compute-embeddings, configure-thinking rewritten as "control reasoning";
258+reference http-api, errors, configuration and cli rewritten; explanation architecture,
259+model-lifecycle, constrained-decoding, openai-compatibility, thinking updated. Facts taken from the
260+code (CLI options, config keys and messages, error codes/messages, defaults: temperature 0.6, top_p
261+1.0, max_tokens 1024, thinking false). README rewritten; packages.drawio: TUI → RazorbillServer,
262+Hummingbird box. test_docs_curl.py maps doc model ids to the suite's ids: 14 curl examples pass
263+(Linux/fake). Link/anchor check script: 0 broken. Gate PASS (run #21). Closed #45 and #31 (its last
264+task was the architecture doc). Not done: Mac run of the doc curl examples (needs the user), version
265+bump to 0.2.0 (release step), milestone still has #47 open.
modified .memory/summary.md +7 -2
@@ -84,8 +84,13 @@ looped on digits. #43 closed. Legacy completions (#44): `POST /v1/completions` i
8484 `container.encode` + `container.generate`, no template/thinking/tools; default implementation
8585 throws WrongModelKind); reuses `CompletionStream`, SSE and `CompletionEnvelope<Choice>` (shared with
8686 chat chunks); suffix/logprobs/n/best_of/multi-prompt/token arrays → 400; max_tokens defaults to the
87-config (not OpenAI's 16). Shared field checks in `FieldChecking.swift`. Next: #45 docs (EN+FR,
88-with curl examples the compat suite runs).
87+config (not OpenAI's 16). Shared field checks in `FieldChecking.swift`. Docs (#45): Diátaxis EN+FR rewritten around the
88+server (tutorial, 10 how-to, 4 reference incl. `http-api.md` / `api-http.md`, 5 explanation); the
89+`curl` blocks of `docs/*/reference/*.md` that hit `http://127.0.0.1:8080/v1` are run by
90+`Tests/Compatibility/test_docs_curl.py` (doc models `mlx-community/Qwen3-4B-4bit` /
91+`BAAI/bge-small-en-v1.5` are mapped to `chat` / `embed`): keep reference examples in that form, and
92+only successful calls in ```bash blocks. v0.2 tickets #31–#45 closed; #47 (KV-cache spike) still
93+open in the milestone; version string still `0.1.0` (bump at release).
8994
9095 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
9196
@@ -84,8 +84,13 @@ looped on digits. #43 closed. Legacy completions (#44): `POST /v1/completions` i
84 `container.encode` + `container.generate`, no template/thinking/tools; default implementation84 `container.encode` + `container.generate`, no template/thinking/tools; default implementation
85 throws WrongModelKind); reuses `CompletionStream`, SSE and `CompletionEnvelope<Choice>` (shared with85 throws WrongModelKind); reuses `CompletionStream`, SSE and `CompletionEnvelope<Choice>` (shared with
86 chat chunks); suffix/logprobs/n/best_of/multi-prompt/token arrays → 400; max_tokens defaults to the86 chat chunks); suffix/logprobs/n/best_of/multi-prompt/token arrays → 400; max_tokens defaults to the
87-config (not OpenAI's 16). Shared field checks in `FieldChecking.swift`. Next: #45 docs (EN+FR,87+config (not OpenAI's 16). Shared field checks in `FieldChecking.swift`. Docs (#45): Diátaxis EN+FR rewritten around the
88-with curl examples the compat suite runs).88+server (tutorial, 10 how-to, 4 reference incl. `http-api.md` / `api-http.md`, 5 explanation); the
89+`curl` blocks of `docs/*/reference/*.md` that hit `http://127.0.0.1:8080/v1` are run by
90+`Tests/Compatibility/test_docs_curl.py` (doc models `mlx-community/Qwen3-4B-4bit` /
91+`BAAI/bge-small-en-v1.5` are mapped to `chat` / `embed`): keep reference examples in that form, and
92+only successful calls in ```bash blocks. v0.2 tickets #31–#45 closed; #47 (KV-cache spike) still
93+open in the milestone; version string still `0.1.0` (bump at release).
89 94
90 ## Architecture of v0.1 (agent, removed on the v0.2 branch)95 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
91 96
modified .quality/history.jsonl +1 -0
@@ -18,3 +18,4 @@
1818 {"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"}
1919 {"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"}
2020 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"}
21+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "c1a7231", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 21, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T19:12:45Z"}
@@ -18,3 +18,4 @@
18 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "a61fd30", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 213, "complex": 449, "cyclo": 539, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9274, "loc": 7353}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 18, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:49Z"}18 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "a61fd30", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 213, "complex": 449, "cyclo": 539, "fields": 1021, "funcs": 517, "lcom": 102, "lines": 9274, "loc": 7353}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 18, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T17:55:49Z"}
19 {"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"}19 {"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"}
20 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"}20 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"}
21+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "c1a7231", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 21, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T19:12:45Z"}
added .quality/report-20261125T191245Z.md +73 -0
new file mode 100644
@@ -0,0 +1,73 @@
1+# Quality report — 2026-11-25T19:12:45Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `c1a7231` 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**: #21 (previous: 2026-11-25T18:44:58Z)
8+
9+## Lint issues (`qlty check`)
10+
11+_none_
12+
13+### Top rules
14+
15+_none_
16+
17+### Most affected files
18+
19+_none_
20+
21+## Code smells (`qlty smells`)
22+
23+Total: **0** (vs previous: ±0)
24+
25+_none_
26+
27+## Metrics (`qlty metrics`)
28+
29+| metric | total | vs previous |
30+|---|---|---|
31+| funcs | 541 | ±0 |
32+| classes | 221 | ±0 |
33+| fields | 1086 | ±0 |
34+| cyclo | 569 | ±0 |
35+| complex | 512 | ±0 |
36+| lcom | 106 | ±0 |
37+| lines | 9798 | ±0 |
38+| loc | 7798 | ±0 |
39+
40+### Most complex files
41+
42+| file | complex | cyclo | loc |
43+|---|---|---|---|
44+| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
45+| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
46+| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
47+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
48+| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
49+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
50+| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 |
51+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 |
52+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 |
53+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
54+| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 |
55+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
56+| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
57+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
58+| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 |
59+
60+## Trend
61+
62+| run | timestamp | error | warning | smells | complex | gate |
63+|---|---|---|---|---|---|---|
64+| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |
65+| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
66+| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
67+| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
68+| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
69+| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL |
70+| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
71+| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
72+| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
73+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
new file mode 100644
@@ -0,0 +1,73 @@
1+# Quality report — 2026-11-25T19:12:45Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `c1a7231` 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**: #21 (previous: 2026-11-25T18:44:58Z)
8+
9+## Lint issues (`qlty check`)
10+
11+_none_
12+
13+### Top rules
14+
15+_none_
16+
17+### Most affected files
18+
19+_none_
20+
21+## Code smells (`qlty smells`)
22+
23+Total: **0** (vs previous: ±0)
24+
25+_none_
26+
27+## Metrics (`qlty metrics`)
28+
29+| metric | total | vs previous |
30+|---|---|---|
31+| funcs | 541 | ±0 |
32+| classes | 221 | ±0 |
33+| fields | 1086 | ±0 |
34+| cyclo | 569 | ±0 |
35+| complex | 512 | ±0 |
36+| lcom | 106 | ±0 |
37+| lines | 9798 | ±0 |
38+| loc | 7798 | ±0 |
39+
40+### Most complex files
41+
42+| file | complex | cyclo | loc |
43+|---|---|---|---|
44+| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
45+| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
46+| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
47+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
48+| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
49+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
50+| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 |
51+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 |
52+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 |
53+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
54+| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 |
55+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
56+| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
57+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
58+| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 |
59+
60+## Trend
61+
62+| run | timestamp | error | warning | smells | complex | gate |
63+|---|---|---|---|---|---|---|
64+| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |
65+| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
66+| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
67+| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
68+| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
69+| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL |
70+| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
71+| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
72+| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
73+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
modified .quality/report-latest.md +12 -12
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-25T18:44:58Z
1+# Quality report — 2026-11-25T19:12:45Z
22
33 - **Gate**: ✅ **PASS**
4-- **Commit**: `9be357d` on `feature/v0.2-openai-server`
4+- **Commit**: `c1a7231` on `feature/v0.2-openai-server`
55 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
66 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #20 (previous: 2026-11-25T18:44:20Z)
7+- **Run**: #21 (previous: 2026-11-25T18:44:58Z)
88
99 ## Lint issues (`qlty check`)
1010
@@ -20,7 +20,7 @@ _none_
2020
2121 ## Code smells (`qlty smells`)
2222
23-Total: **0** (vs previous: -2)
23+Total: **0** (vs previous: ±0)
2424
2525 _none_
2626
@@ -28,14 +28,14 @@ _none_
2828
2929 | metric | total | vs previous |
3030 |---|---|---|
31-| funcs | 541 | -1 |
32-| classes | 221 | -2 |
33-| fields | 1086 | -1 |
34-| cyclo | 569 | -1 |
35-| complex | 512 | -1 |
31+| funcs | 541 | ±0 |
32+| classes | 221 | ±0 |
33+| fields | 1086 | ±0 |
34+| cyclo | 569 | ±0 |
35+| complex | 512 | ±0 |
3636 | lcom | 106 | ±0 |
37-| lines | 9798 | -11 |
38-| loc | 7798 | -13 |
37+| lines | 9798 | ±0 |
38+| loc | 7798 | ±0 |
3939
4040 ### Most complex files
4141
@@ -61,7 +61,6 @@ _none_
6161
6262 | run | timestamp | error | warning | smells | complex | gate |
6363 |---|---|---|---|---|---|---|
64-| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS |
6564 | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |
6665 | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
6766 | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
@@ -71,3 +70,4 @@ _none_
7170 | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
7271 | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
7372 | 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
73+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-25T18:44:58Z1+# Quality report — 2026-11-25T19:12:45Z
2 2
3 - **Gate**: ✅ **PASS**3 - **Gate**: ✅ **PASS**
4-- **Commit**: `9be357d` on `feature/v0.2-openai-server`4+- **Commit**: `c1a7231` 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**: #20 (previous: 2026-11-25T18:44:20Z)7+- **Run**: #21 (previous: 2026-11-25T18:44:58Z)
8 8
9 ## Lint issues (`qlty check`)9 ## Lint issues (`qlty check`)
10 10
@@ -20,7 +20,7 @@ _none_
20 20
21 ## Code smells (`qlty smells`)21 ## Code smells (`qlty smells`)
22 22
23-Total: **0** (vs previous: -2)23+Total: **0** (vs previous: ±0)
24 24
25 _none_25 _none_
26 26
@@ -28,14 +28,14 @@ _none_
28 28
29 | metric | total | vs previous |29 | metric | total | vs previous |
30 |---|---|---|30 |---|---|---|
31-| funcs | 541 | -1 |31+| funcs | 541 | ±0 |
32-| classes | 221 | -2 |32+| classes | 221 | ±0 |
33-| fields | 1086 | -1 |33+| fields | 1086 | ±0 |
34-| cyclo | 569 | -1 |34+| cyclo | 569 | ±0 |
35-| complex | 512 | -1 |35+| complex | 512 | ±0 |
36 | lcom | 106 | ±0 |36 | lcom | 106 | ±0 |
37-| lines | 9798 | -11 |37+| lines | 9798 | ±0 |
38-| loc | 7798 | -13 |38+| loc | 7798 | ±0 |
39 39
40 ### Most complex files40 ### Most complex files
41 41
@@ -61,7 +61,6 @@ _none_
61 61
62 | run | timestamp | error | warning | smells | complex | gate |62 | run | timestamp | error | warning | smells | complex | gate |
63 |---|---|---|---|---|---|---|63 |---|---|---|---|---|---|---|
64-| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS |
65 | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |64 | 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |
66 | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |65 | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
67 | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |66 | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
@@ -71,3 +70,4 @@ _none_
71 | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |70 | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
72 | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |71 | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
73 | 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |72 | 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
73+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
modified .tickets/issues/0031-pivot-razorbill-as-an-openai-compatible-mlx-mode.yaml +13 -3
@@ -1,12 +1,12 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 31
33 title: "Pivot: razorbill as an OpenAI-compatible MLX model server — scope and decisions"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-25T05:04:45.000Z
9+updatedAt: 2026-11-25T20:16:00.000Z
1010 labels:
1111 - "kind::chore"
1212 - "area::server"
@@ -83,12 +83,14 @@ tasks:
8383 closedAt: 2026-11-24T21:29:15.000Z
8484 - id: 5
8585 title: "Update .memory/summary.md and docs/en|fr architecture with the new direction"
86- state: open
86+ state: closed
8787 priority: medium
8888 author:
8989 name: k33g
9090 email: ph.charriere@gmail.com
9191 createdAt: 2026-11-24T21:17:08.000Z
92+ updatedAt: 2026-11-25T20:16:00.000Z
93+ closedAt: 2026-11-25T20:16:00.000Z
9294 - id: 6
9395 title: "Remove the agent code, keeping what the server reuses (model list/pull/rm, ModelStore, MLX loading, ThinkingSplitter, FakeEngine, YAML loader)"
9496 state: closed
@@ -113,3 +115,11 @@ comments:
113115 3. **HTTP framework**: Hummingbird 2.
114116 4. **API**: OpenAI-compatible only (`/v1/*`) — no Ollama `/api/*`.
115117 5. **Network**: `127.0.0.1` by default, and `0.0.0.0` must be possible (`--host 0.0.0.0` / `server.host`) to serve other machines — see #32.
118+ - id: 2
119+ author:
120+ name: k33g
121+ email: ph.charriere@gmail.com
122+ createdAt: 2026-11-25T20:16:00.000Z
123+ body: |
124+ Last task done with #45: docs/en|fr architecture (and the whole documentation) now describe the
125+ server; .memory/summary.md has described it since #32. Every task of the pivot is done.
@@ -1,12 +1,12 @@
1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2 id: 312 id: 31
3 title: "Pivot: razorbill as an OpenAI-compatible MLX model server — scope and decisions"3 title: "Pivot: razorbill as an OpenAI-compatible MLX model server — scope and decisions"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-24T21:17:08.000Z8 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-25T05:04:45.000Z9+updatedAt: 2026-11-25T20:16:00.000Z
10 labels:10 labels:
11 - "kind::chore"11 - "kind::chore"
12 - "area::server"12 - "area::server"
@@ -83,12 +83,14 @@ tasks:
83 closedAt: 2026-11-24T21:29:15.000Z83 closedAt: 2026-11-24T21:29:15.000Z
84 - id: 584 - id: 5
85 title: "Update .memory/summary.md and docs/en|fr architecture with the new direction"85 title: "Update .memory/summary.md and docs/en|fr architecture with the new direction"
86- state: open86+ state: closed
87 priority: medium87 priority: medium
88 author:88 author:
89 name: k33g89 name: k33g
90 email: ph.charriere@gmail.com90 email: ph.charriere@gmail.com
91 createdAt: 2026-11-24T21:17:08.000Z91 createdAt: 2026-11-24T21:17:08.000Z
92+ updatedAt: 2026-11-25T20:16:00.000Z
93+ closedAt: 2026-11-25T20:16:00.000Z
92 - id: 694 - id: 6
93 title: "Remove the agent code, keeping what the server reuses (model list/pull/rm, ModelStore, MLX loading, ThinkingSplitter, FakeEngine, YAML loader)"95 title: "Remove the agent code, keeping what the server reuses (model list/pull/rm, ModelStore, MLX loading, ThinkingSplitter, FakeEngine, YAML loader)"
94 state: closed96 state: closed
@@ -113,3 +115,11 @@ comments:
113 3. **HTTP framework**: Hummingbird 2.115 3. **HTTP framework**: Hummingbird 2.
114 4. **API**: OpenAI-compatible only (`/v1/*`) — no Ollama `/api/*`.116 4. **API**: OpenAI-compatible only (`/v1/*`) — no Ollama `/api/*`.
115 5. **Network**: `127.0.0.1` by default, and `0.0.0.0` must be possible (`--host 0.0.0.0` / `server.host`) to serve other machines — see #32.117 5. **Network**: `127.0.0.1` by default, and `0.0.0.0` must be possible (`--host 0.0.0.0` / `server.host`) to serve other machines — see #32.
118+ - id: 2
119+ author:
120+ name: k33g
121+ email: ph.charriere@gmail.com
122+ createdAt: 2026-11-25T20:16:00.000Z
123+ body: |
124+ Last task done with #45: docs/en|fr architecture (and the whole documentation) now describe the
125+ server; .memory/summary.md has described it since #32. Every task of the pivot is done.
modified .tickets/issues/0045-server-documentation-en-fr.yaml +33 -8
@@ -1,12 +1,12 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 45
33 title: "Server documentation (EN + FR)"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:29:15.000Z
9+updatedAt: 2026-11-25T20:15:00.000Z
1010 labels:
1111 - "documentation"
1212 - "area::docs"
@@ -31,42 +31,67 @@ body: |
3131 tasks:
3232 - id: 1
3333 title: "Tutorial: first request"
34- state: open
34+ state: closed
3535 priority: high
3636 author:
3737 name: k33g
3838 email: ph.charriere@gmail.com
3939 createdAt: 2026-11-24T21:17:08.000Z
40+ updatedAt: 2026-11-25T20:15:00.000Z
41+ closedAt: 2026-11-25T20:15:00.000Z
4042 - id: 2
4143 title: "How-to pages: structured output, function calling, embeddings, config"
42- state: open
44+ state: closed
4345 priority: high
4446 author:
4547 name: k33g
4648 email: ph.charriere@gmail.com
4749 createdAt: 2026-11-24T21:17:08.000Z
50+ updatedAt: 2026-11-25T20:15:00.000Z
51+ closedAt: 2026-11-25T20:15:00.000Z
4852 - id: 3
4953 title: "API and config reference"
50- state: open
54+ state: closed
5155 priority: high
5256 author:
5357 name: k33g
5458 email: ph.charriere@gmail.com
5559 createdAt: 2026-11-24T21:17:08.000Z
60+ updatedAt: 2026-11-25T20:15:00.000Z
61+ closedAt: 2026-11-25T20:15:00.000Z
5662 - id: 4
5763 title: "Explanation pages"
58- state: open
64+ state: closed
5965 priority: medium
6066 author:
6167 name: k33g
6268 email: ph.charriere@gmail.com
6369 createdAt: 2026-11-24T21:17:08.000Z
70+ updatedAt: 2026-11-25T20:15:00.000Z
71+ closedAt: 2026-11-25T20:15:00.000Z
6472 - id: 5
6573 title: "README and module diagram"
66- state: open
74+ state: closed
6775 priority: medium
6876 author:
6977 name: k33g
7078 email: ph.charriere@gmail.com
7179 createdAt: 2026-11-24T21:17:08.000Z
72-comments: []
80+ updatedAt: 2026-11-25T20:15:00.000Z
81+ closedAt: 2026-11-25T20:15:00.000Z
82+comments:
83+ - id: 1
84+ author:
85+ name: k33g
86+ email: ph.charriere@gmail.com
87+ createdAt: 2026-11-25T20:15:00.000Z
88+ body: |
89+ Docs rewritten around the server, EN + FR (Diátaxis). Agent pages removed (add-a-tool,
90+ bash tool, scripts, tool safety). Tutorial: first requests (curl, openai SDK). How-to: configure the
91+ server, OpenAI clients, structured output, function calling, embeddings, reasoning; manage-models,
92+ run-the-tests (compat suite), sandbox (rzb serve trap), build updated. Reference: http-api, errors,
93+ configuration, cli. Explanation: architecture, model lifecycle, constrained decoding, OpenAI
94+ compatibility, reasoning. README and packages.drawio (RazorbillServer + Hummingbird) updated.
95+ The 7 curl examples of each API reference run in the compat suite (models mapped to chat/embed):
96+ 14 pass on Linux. Links and anchors checked by script: 0 broken. Gate PASS (run #21).
97+
@@ -1,12 +1,12 @@
1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2 id: 452 id: 45
3 title: "Server documentation (EN + FR)"3 title: "Server documentation (EN + FR)"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-24T21:17:08.000Z8 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:29:15.000Z9+updatedAt: 2026-11-25T20:15:00.000Z
10 labels:10 labels:
11 - "documentation"11 - "documentation"
12 - "area::docs"12 - "area::docs"
@@ -31,42 +31,67 @@ body: |
31 tasks:31 tasks:
32 - id: 132 - id: 1
33 title: "Tutorial: first request"33 title: "Tutorial: first request"
34- state: open34+ state: closed
35 priority: high35 priority: high
36 author:36 author:
37 name: k33g37 name: k33g
38 email: ph.charriere@gmail.com38 email: ph.charriere@gmail.com
39 createdAt: 2026-11-24T21:17:08.000Z39 createdAt: 2026-11-24T21:17:08.000Z
40+ updatedAt: 2026-11-25T20:15:00.000Z
41+ closedAt: 2026-11-25T20:15:00.000Z
40 - id: 242 - id: 2
41 title: "How-to pages: structured output, function calling, embeddings, config"43 title: "How-to pages: structured output, function calling, embeddings, config"
42- state: open44+ state: closed
43 priority: high45 priority: high
44 author:46 author:
45 name: k33g47 name: k33g
46 email: ph.charriere@gmail.com48 email: ph.charriere@gmail.com
47 createdAt: 2026-11-24T21:17:08.000Z49 createdAt: 2026-11-24T21:17:08.000Z
50+ updatedAt: 2026-11-25T20:15:00.000Z
51+ closedAt: 2026-11-25T20:15:00.000Z
48 - id: 352 - id: 3
49 title: "API and config reference"53 title: "API and config reference"
50- state: open54+ state: closed
51 priority: high55 priority: high
52 author:56 author:
53 name: k33g57 name: k33g
54 email: ph.charriere@gmail.com58 email: ph.charriere@gmail.com
55 createdAt: 2026-11-24T21:17:08.000Z59 createdAt: 2026-11-24T21:17:08.000Z
60+ updatedAt: 2026-11-25T20:15:00.000Z
61+ closedAt: 2026-11-25T20:15:00.000Z
56 - id: 462 - id: 4
57 title: "Explanation pages"63 title: "Explanation pages"
58- state: open64+ state: closed
59 priority: medium65 priority: medium
60 author:66 author:
61 name: k33g67 name: k33g
62 email: ph.charriere@gmail.com68 email: ph.charriere@gmail.com
63 createdAt: 2026-11-24T21:17:08.000Z69 createdAt: 2026-11-24T21:17:08.000Z
70+ updatedAt: 2026-11-25T20:15:00.000Z
71+ closedAt: 2026-11-25T20:15:00.000Z
64 - id: 572 - id: 5
65 title: "README and module diagram"73 title: "README and module diagram"
66- state: open74+ state: closed
67 priority: medium75 priority: medium
68 author:76 author:
69 name: k33g77 name: k33g
70 email: ph.charriere@gmail.com78 email: ph.charriere@gmail.com
71 createdAt: 2026-11-24T21:17:08.000Z79 createdAt: 2026-11-24T21:17:08.000Z
72-comments: []80+ updatedAt: 2026-11-25T20:15:00.000Z
81+ closedAt: 2026-11-25T20:15:00.000Z
82+comments:
83+ - id: 1
84+ author:
85+ name: k33g
86+ email: ph.charriere@gmail.com
87+ createdAt: 2026-11-25T20:15:00.000Z
88+ body: |
89+ Docs rewritten around the server, EN + FR (Diátaxis). Agent pages removed (add-a-tool,
90+ bash tool, scripts, tool safety). Tutorial: first requests (curl, openai SDK). How-to: configure the
91+ server, OpenAI clients, structured output, function calling, embeddings, reasoning; manage-models,
92+ run-the-tests (compat suite), sandbox (rzb serve trap), build updated. Reference: http-api, errors,
93+ configuration, cli. Explanation: architecture, model lifecycle, constrained decoding, OpenAI
94+ compatibility, reasoning. README and packages.drawio (RazorbillServer + Hummingbird) updated.
95+ The 7 curl examples of each API reference run in the compat suite (models mapped to chat/embed):
96+ 14 pass on Linux. Links and anchors checked by script: 0 broken. Gate PASS (run #21).
97+
modified README.md +68 -63
@@ -1,74 +1,81 @@
11 # razorbill
22
3-razorbill is a local AI agent for the Mac. Its command is **`rzb`**. It runs its own models on the GPU (Apple Metal) with [MLX](https://github.com/ml-explore/mlx-swift-lm), is configured by a YAML file, and works both as a command-line tool and as a full-screen terminal UI.
3+razorbill is a model server for the Mac. Its command is **`rzb`**. It runs language and embedding models on the GPU (Apple Metal) with [MLX](https://github.com/ml-explore/mlx-swift-lm) and exposes them through an **OpenAI-compatible HTTP API**, so existing OpenAI clients, frameworks and chat UIs use local models by changing their base URL.
44
5-> **Status: v0.1.** The YAML configuration, the agent loop with the `bash` tool, the MLX engine (with thinking display and budget), the command-line mode and the full-screen terminal UI are implemented and tested. See [the v0.1 milestone](.tickets/milestones.yaml) for what is left.
5+> **Status: v0.2.** Chat completions (streaming, structured output with constrained decoding, function calling, reasoning), legacy text completions, embeddings, model management with queues and memory limits, a YAML server configuration, and an OpenAI compatibility suite are implemented and tested. Single native binary, no Python.
66
77 **Documentation:** [docs/en](docs/en/README.md) · [docs/fr](docs/fr/README.md) — tutorial, how-to guides, reference and explanations.
88
9-## Commands
9+## Quick start
1010
11-| Command | What it does | Status |
12-| --- | --- | --- |
13-| `rzb version` | Print the version and the engines this build contains | available |
14-| `rzb init` | Wizard: pick a model (downloaded or recommended), a prompt and tools, then write the agent's YAML file | available |
15-| `rzb run "prompt"` | Ask the agent once and print the answer; piped input is added to the prompt | available |
16-| `rzb chat` | Talk with the agent line by line in a plain terminal (`/reset`, `/exit`) | available |
17-| `rzb tui` | Talk with the agent in a full-screen terminal UI (Ctrl-T thinking, Ctrl-N new, PgUp/PgDn scroll, Ctrl-C stop/quit) | available |
18-| `rzb models list / pull / rm` | Manage the downloaded models | available |
19-| `rzb config validate` | Check an agent's YAML file | available |
11+```bash
12+rzb models pull mlx-community/Qwen3-4B-4bit
13+rzb serve # http://127.0.0.1:8080/v1
14+```
2015
21-An agent is described by **one YAML file**: model, system prompt, generation settings and tools. The format is implemented and validated (unknown keys, wrong types and out-of-range values are reported with their line). The commented example [examples/agent.yaml](examples/agent.yaml) lists every key with its default:
16+```python
17+from openai import OpenAI
2218
23-```yaml
24-name: swift-helper # required
25-model:
26- id: mlx-community/Qwen3-1.7B-4bit # or `path: ~/models/my-model`, or the short form `model: <id>`
27-generation:
28- temperature: 0.6
29- max_tokens: 1024
30- thinking: false # let reasoning models think first
31- # thinking_budget: 512 # and limit how long
32-system: |
33- You are a concise Swift expert. Today is {{date}}.
34-tools:
35- bash:
36- confirm: true # the first built-in tool asks before each command
37-ui:
38- show_stats: true
39- show_thinking: true # show the reasoning (TUI: Ctrl-T)
19+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
20+answer = client.chat.completions.create(
21+ model="mlx-community/Qwen3-4B-4bit",
22+ messages=[{"role": "user", "content": "Explain Swift actors in 3 lines."}],
23+)
24+print(answer.choices[0].message.content)
4025 ```
4126
42-- The system prompt accepts `{{date}}`, `{{cwd}}` and `{{env.NAME}}`.
43-- Without `--config`, `rzb` looks for `./razorbill.yaml`, then `~/.config/razorbill/agent.yaml`.
44-- Every key: [agent file reference](docs/en/reference/configuration.md).
27+Step by step: [your first requests to a local model](docs/en/tutorials/getting-started.md).
4528
46-## Quick start
29+## What the API offers
4730
48-```bash
49-rzb init # creates ./razorbill.yaml
50-rzb chat # talk with the agent, line by line
51-rzb tui # or in a full-screen terminal UI
52-rzb run "Explain Swift actors in 3 lines"
53-git diff | rzb run "Review this change" # piped input is added to the prompt
54-rzb run -m mlx-community/Qwen3-4B-4bit --temperature 0 "…" # options override the file
31+| Endpoint | Highlights |
32+| --- | --- |
33+| `POST /v1/chat/completions` | Streaming (SSE), `response_format` `json_object` / `json_schema` guaranteed by constrained decoding (works with `client.beta.chat.completions.parse`), `tools` / `tool_choice`, `reasoning_content`, reasoning on/off and budget, stop sequences, seed, penalties |
34+| `POST /v1/completions` | Raw-prompt completion, streaming, `echo` |
35+| `POST /v1/embeddings` | Float or base64 vectors, `dimensions`, results matching `sentence-transformers` |
36+| `GET /v1/models` | Declared and cached models, with `loaded` and `kind` |
37+
38+Fields razorbill cannot honour (`n` > 1, `logprobs`, images…) are refused with a 400 naming them, never silently ignored. Every field: [HTTP API reference](docs/en/reference/http-api.md).
39+
40+## Commands
41+
42+| Command | What it does |
43+| --- | --- |
44+| `rzb serve [--config server.yaml] [--host …] [--port …]` | Start the server |
45+| `rzb config validate server.yaml` | Check a server configuration file |
46+| `rzb models list / pull / rm` | Manage the downloaded models (Hugging Face cache) |
47+| `rzb version` | Print the version and the engines this build contains |
48+
49+## Configuration
50+
51+Optional. One YAML file declares short model names, generation defaults and locked settings, and limits; the commented example [examples/server.yaml](examples/server.yaml) lists every key.
52+
53+```yaml
54+models:
55+ - id: qwen3
56+ source: mlx-community/Qwen3-4B-4bit
57+ defaults: { thinking: true, thinking_budget: 512 }
58+ - id: embed
59+ source: BAAI/bge-small-en-v1.5
60+ kind: embedding
61+ preload: true
62+locked:
63+ max_tokens: 8192 # a ceiling for every client
64+limits:
65+ max_loaded_models: 2
66+ keep_alive: 10m
5567 ```
5668
57-The answer goes to standard output; progress, tool calls and statistics go to standard error. Exit codes: `0` success, `1` failure, `2` invalid or missing agent file, `64` wrong command line.
69+The server listens on `127.0.0.1` by default. To serve your network, set an API key (`RZB_API_KEY`) and use `--host 0.0.0.0`. Every key: [configuration reference](docs/en/reference/configuration.md).
5870
5971 ## Requirements
6072
6173 - A Mac with Apple Silicon (M1 or later) and macOS 14 or later.
6274 - Xcode 26 or later. `xcode-select -p` must point inside `Xcode.app`.
63-- The Metal toolchain, installed once per Xcode install:
64-
65- ```bash
66- xcodebuild -downloadComponent MetalToolchain
67- ```
68-
75+- The Metal toolchain, installed once per Xcode install: `xcodebuild -downloadComponent MetalToolchain`.
6976 - Network access to `huggingface.co` the first time a model is used. Models are then read from the Hugging Face cache (`~/.cache/huggingface/hub`).
7077
71-## Build and run on the Mac
78+## Build on the Mac
7279
7380 `swift build` cannot compile MLX's Metal shaders, so build with `xcodebuild`. The package has one Xcode scheme, `razorbill`.
7481
@@ -76,22 +83,20 @@ The answer goes to standard output; progress, tool calls and statistics go to st
7683 xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \
7784 -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
7885
79-.build/xcode/Build/Products/Release/rzb
86+.build/xcode/Build/Products/Release/rzb version
8087 # rzb 0.1.0 (engines: fake, mlx)
8188 ```
8289
83-The first build downloads and compiles the dependencies (MLX, swift-syntax…) and takes several minutes. Run `rzb` from `Build/Products/Release`: the MLX Metal library (`mlx-swift_Cmlx.bundle`) sits next to it.
90+The first build downloads and compiles the dependencies and takes several minutes. Run `rzb` from `Build/Products/Release`: the MLX Metal library (`mlx-swift_Cmlx.bundle`) sits next to it.
8491
8592 ## Run the tests
8693
87-One command, on the Mac or on Linux:
88-
8994 ```bash
90-scripts/test.sh
95+scripts/test.sh # unit tests: xcodebuild on the Mac (MLX included), swift test on Linux
96+scripts/compat.sh # OpenAI compatibility: openai library, LangChain, curl, against a real rzb serve
9197 ```
9298
93-- On the Mac it runs `xcodebuild test` on everything, MLX engine included.
94-- On Linux it runs `swift test --scratch-path .build/linux`. Everything except the MLX engine is built and tested there: MLX is only linked on macOS, and the rest of the code does not depend on it.
99+On Linux everything except the MLX engine is built and tested; the server then runs a fake engine. Details: [run the tests](docs/en/how-to/run-the-tests.md).
95100
96101 ## Develop from a Linux sandbox
97102
@@ -104,7 +109,6 @@ python3 tools/host-runner/host_runner.py
104109 # in the sandbox
105110 tools/host-runner/host.sh build . razorbill
106111 tools/host-runner/host.sh test . razorbill
107-tools/host-runner/host.sh run . rzb
108112 ```
109113
110114 Step by step: [Develop from a Linux sandbox](docs/en/how-to/develop-from-a-sandbox.md). Allowed actions and limits: [tools/host-runner/README.md](tools/host-runner/README.md).
@@ -113,12 +117,13 @@ Step by step: [Develop from a Linux sandbox](docs/en/how-to/develop-from-a-sandb
113117
114118 | Path | Contents |
115119 | --- | --- |
116-| `Sources/RazorbillCore` | Configuration, agent loop, engine and tool protocols, built-in tools. No MLX. |
117-| `Sources/RazorbillMLX` | The MLX engine (macOS only; empty on Linux). |
118-| `Sources/RazorbillCLI` | Command-line front-end: commands, line-mode chat, `rzb init`. |
119-| `Sources/RazorbillTUI` | Full-screen terminal front-end, on a small ANSI layer of its own. |
120-| `Sources/rzb` | The executable: wires the engine and the front-ends together. |
121-| `Tests/` | Unit tests (Swift Testing). |
120+| `Sources/RazorbillCore` | Engine protocol, settings, output constraints, server configuration, model catalog and cache, fake engine. No MLX. |
121+| `Sources/RazorbillMLX` | The MLX engines: chat, completions, constrained decoding, embeddings (macOS only; empty on Linux). |
122+| `Sources/RazorbillServer` | The OpenAI-compatible HTTP server (Hummingbird 2) and the model manager. |
123+| `Sources/RazorbillCLI` | The commands: `serve`, `config validate`, `models`, `version`. |
124+| `Sources/rzb` | The executable: registers the engines and starts the command line. |
125+| `Tests/` | Unit tests (Swift Testing); `Tests/Compatibility`: the OpenAI compatibility suite (pytest). |
126+| `examples/server.yaml` | Commented server configuration. |
122127 | `samples/01-query-model` | Standalone sample: send one prompt to one MLX model. |
123128 | `tools/host-runner` | Build, test and run on the Mac from the sandbox. |
124129 | `.tickets/` | Issues, epics and milestones (IssueSpec YAML format). |
@@ -1,74 +1,81 @@
1 # razorbill1 # razorbill
2 2
3-razorbill is a local AI agent for the Mac. Its command is **`rzb`**. It runs its own models on the GPU (Apple Metal) with [MLX](https://github.com/ml-explore/mlx-swift-lm), is configured by a YAML file, and works both as a command-line tool and as a full-screen terminal UI.3+razorbill is a model server for the Mac. Its command is **`rzb`**. It runs language and embedding models on the GPU (Apple Metal) with [MLX](https://github.com/ml-explore/mlx-swift-lm) and exposes them through an **OpenAI-compatible HTTP API**, so existing OpenAI clients, frameworks and chat UIs use local models by changing their base URL.
4 4
5-> **Status: v0.1.** The YAML configuration, the agent loop with the `bash` tool, the MLX engine (with thinking display and budget), the command-line mode and the full-screen terminal UI are implemented and tested. See [the v0.1 milestone](.tickets/milestones.yaml) for what is left.5+> **Status: v0.2.** Chat completions (streaming, structured output with constrained decoding, function calling, reasoning), legacy text completions, embeddings, model management with queues and memory limits, a YAML server configuration, and an OpenAI compatibility suite are implemented and tested. Single native binary, no Python.
6 6
7 **Documentation:** [docs/en](docs/en/README.md) · [docs/fr](docs/fr/README.md) — tutorial, how-to guides, reference and explanations.7 **Documentation:** [docs/en](docs/en/README.md) · [docs/fr](docs/fr/README.md) — tutorial, how-to guides, reference and explanations.
8 8
9-## Commands9+## Quick start
10 10
11-| Command | What it does | Status |11+```bash
12-| --- | --- | --- |12+rzb models pull mlx-community/Qwen3-4B-4bit
13-| `rzb version` | Print the version and the engines this build contains | available |13+rzb serve # http://127.0.0.1:8080/v1
14-| `rzb init` | Wizard: pick a model (downloaded or recommended), a prompt and tools, then write the agent's YAML file | available |14+```
15-| `rzb run "prompt"` | Ask the agent once and print the answer; piped input is added to the prompt | available |
16-| `rzb chat` | Talk with the agent line by line in a plain terminal (`/reset`, `/exit`) | available |
17-| `rzb tui` | Talk with the agent in a full-screen terminal UI (Ctrl-T thinking, Ctrl-N new, PgUp/PgDn scroll, Ctrl-C stop/quit) | available |
18-| `rzb models list / pull / rm` | Manage the downloaded models | available |
19-| `rzb config validate` | Check an agent's YAML file | available |
20 15
21-An agent is described by **one YAML file**: model, system prompt, generation settings and tools. The format is implemented and validated (unknown keys, wrong types and out-of-range values are reported with their line). The commented example [examples/agent.yaml](examples/agent.yaml) lists every key with its default:16+```python
17+from openai import OpenAI
22 18
23-```yaml19+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
24-name: swift-helper # required20+answer = client.chat.completions.create(
25-model:21+ model="mlx-community/Qwen3-4B-4bit",
26- id: mlx-community/Qwen3-1.7B-4bit # or `path: ~/models/my-model`, or the short form `model: <id>`22+ messages=[{"role": "user", "content": "Explain Swift actors in 3 lines."}],
27-generation:23+)
28- temperature: 0.624+print(answer.choices[0].message.content)
29- max_tokens: 1024
30- thinking: false # let reasoning models think first
31- # thinking_budget: 512 # and limit how long
32-system: |
33- You are a concise Swift expert. Today is {{date}}.
34-tools:
35- bash:
36- confirm: true # the first built-in tool asks before each command
37-ui:
38- show_stats: true
39- show_thinking: true # show the reasoning (TUI: Ctrl-T)
40 ```25 ```
41 26
42-- The system prompt accepts `{{date}}`, `{{cwd}}` and `{{env.NAME}}`.27+Step by step: [your first requests to a local model](docs/en/tutorials/getting-started.md).
43-- Without `--config`, `rzb` looks for `./razorbill.yaml`, then `~/.config/razorbill/agent.yaml`.
44-- Every key: [agent file reference](docs/en/reference/configuration.md).
45 28
46-## Quick start29+## What the API offers
47 30
48-```bash31+| Endpoint | Highlights |
49-rzb init # creates ./razorbill.yaml32+| --- | --- |
50-rzb chat # talk with the agent, line by line33+| `POST /v1/chat/completions` | Streaming (SSE), `response_format` `json_object` / `json_schema` guaranteed by constrained decoding (works with `client.beta.chat.completions.parse`), `tools` / `tool_choice`, `reasoning_content`, reasoning on/off and budget, stop sequences, seed, penalties |
51-rzb tui # or in a full-screen terminal UI34+| `POST /v1/completions` | Raw-prompt completion, streaming, `echo` |
52-rzb run "Explain Swift actors in 3 lines"35+| `POST /v1/embeddings` | Float or base64 vectors, `dimensions`, results matching `sentence-transformers` |
53-git diff | rzb run "Review this change" # piped input is added to the prompt36+| `GET /v1/models` | Declared and cached models, with `loaded` and `kind` |
54-rzb run -m mlx-community/Qwen3-4B-4bit --temperature 0 "…" # options override the file37+
38+Fields razorbill cannot honour (`n` > 1, `logprobs`, images…) are refused with a 400 naming them, never silently ignored. Every field: [HTTP API reference](docs/en/reference/http-api.md).
39+
40+## Commands
41+
42+| Command | What it does |
43+| --- | --- |
44+| `rzb serve [--config server.yaml] [--host …] [--port …]` | Start the server |
45+| `rzb config validate server.yaml` | Check a server configuration file |
46+| `rzb models list / pull / rm` | Manage the downloaded models (Hugging Face cache) |
47+| `rzb version` | Print the version and the engines this build contains |
48+
49+## Configuration
50+
51+Optional. One YAML file declares short model names, generation defaults and locked settings, and limits; the commented example [examples/server.yaml](examples/server.yaml) lists every key.
52+
53+```yaml
54+models:
55+ - id: qwen3
56+ source: mlx-community/Qwen3-4B-4bit
57+ defaults: { thinking: true, thinking_budget: 512 }
58+ - id: embed
59+ source: BAAI/bge-small-en-v1.5
60+ kind: embedding
61+ preload: true
62+locked:
63+ max_tokens: 8192 # a ceiling for every client
64+limits:
65+ max_loaded_models: 2
66+ keep_alive: 10m
55 ```67 ```
56 68
57-The answer goes to standard output; progress, tool calls and statistics go to standard error. Exit codes: `0` success, `1` failure, `2` invalid or missing agent file, `64` wrong command line.69+The server listens on `127.0.0.1` by default. To serve your network, set an API key (`RZB_API_KEY`) and use `--host 0.0.0.0`. Every key: [configuration reference](docs/en/reference/configuration.md).
58 70
59 ## Requirements71 ## Requirements
60 72
61 - A Mac with Apple Silicon (M1 or later) and macOS 14 or later.73 - A Mac with Apple Silicon (M1 or later) and macOS 14 or later.
62 - Xcode 26 or later. `xcode-select -p` must point inside `Xcode.app`.74 - Xcode 26 or later. `xcode-select -p` must point inside `Xcode.app`.
63-- The Metal toolchain, installed once per Xcode install:75+- The Metal toolchain, installed once per Xcode install: `xcodebuild -downloadComponent MetalToolchain`.
64-
65- ```bash
66- xcodebuild -downloadComponent MetalToolchain
67- ```
68-
69 - Network access to `huggingface.co` the first time a model is used. Models are then read from the Hugging Face cache (`~/.cache/huggingface/hub`).76 - Network access to `huggingface.co` the first time a model is used. Models are then read from the Hugging Face cache (`~/.cache/huggingface/hub`).
70 77
71-## Build and run on the Mac78+## Build on the Mac
72 79
73 `swift build` cannot compile MLX's Metal shaders, so build with `xcodebuild`. The package has one Xcode scheme, `razorbill`.80 `swift build` cannot compile MLX's Metal shaders, so build with `xcodebuild`. The package has one Xcode scheme, `razorbill`.
74 81
@@ -76,22 +83,20 @@ The answer goes to standard output; progress, tool calls and statistics go to st
76 xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \83 xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \
77 -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation84 -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
78 85
79-.build/xcode/Build/Products/Release/rzb86+.build/xcode/Build/Products/Release/rzb version
80 # rzb 0.1.0 (engines: fake, mlx)87 # rzb 0.1.0 (engines: fake, mlx)
81 ```88 ```
82 89
83-The first build downloads and compiles the dependencies (MLX, swift-syntax…) and takes several minutes. Run `rzb` from `Build/Products/Release`: the MLX Metal library (`mlx-swift_Cmlx.bundle`) sits next to it.90+The first build downloads and compiles the dependencies and takes several minutes. Run `rzb` from `Build/Products/Release`: the MLX Metal library (`mlx-swift_Cmlx.bundle`) sits next to it.
84 91
85 ## Run the tests92 ## Run the tests
86 93
87-One command, on the Mac or on Linux:
88-
89 ```bash94 ```bash
90-scripts/test.sh95+scripts/test.sh # unit tests: xcodebuild on the Mac (MLX included), swift test on Linux
96+scripts/compat.sh # OpenAI compatibility: openai library, LangChain, curl, against a real rzb serve
91 ```97 ```
92 98
93-- On the Mac it runs `xcodebuild test` on everything, MLX engine included.99+On Linux everything except the MLX engine is built and tested; the server then runs a fake engine. Details: [run the tests](docs/en/how-to/run-the-tests.md).
94-- On Linux it runs `swift test --scratch-path .build/linux`. Everything except the MLX engine is built and tested there: MLX is only linked on macOS, and the rest of the code does not depend on it.
95 100
96 ## Develop from a Linux sandbox101 ## Develop from a Linux sandbox
97 102
@@ -104,7 +109,6 @@ python3 tools/host-runner/host_runner.py
104 # in the sandbox109 # in the sandbox
105 tools/host-runner/host.sh build . razorbill110 tools/host-runner/host.sh build . razorbill
106 tools/host-runner/host.sh test . razorbill111 tools/host-runner/host.sh test . razorbill
107-tools/host-runner/host.sh run . rzb
108 ```112 ```
109 113
110 Step by step: [Develop from a Linux sandbox](docs/en/how-to/develop-from-a-sandbox.md). Allowed actions and limits: [tools/host-runner/README.md](tools/host-runner/README.md).114 Step by step: [Develop from a Linux sandbox](docs/en/how-to/develop-from-a-sandbox.md). Allowed actions and limits: [tools/host-runner/README.md](tools/host-runner/README.md).
@@ -113,12 +117,13 @@ Step by step: [Develop from a Linux sandbox](docs/en/how-to/develop-from-a-sandb
113 117
114 | Path | Contents |118 | Path | Contents |
115 | --- | --- |119 | --- | --- |
116-| `Sources/RazorbillCore` | Configuration, agent loop, engine and tool protocols, built-in tools. No MLX. |120+| `Sources/RazorbillCore` | Engine protocol, settings, output constraints, server configuration, model catalog and cache, fake engine. No MLX. |
117-| `Sources/RazorbillMLX` | The MLX engine (macOS only; empty on Linux). |121+| `Sources/RazorbillMLX` | The MLX engines: chat, completions, constrained decoding, embeddings (macOS only; empty on Linux). |
118-| `Sources/RazorbillCLI` | Command-line front-end: commands, line-mode chat, `rzb init`. |122+| `Sources/RazorbillServer` | The OpenAI-compatible HTTP server (Hummingbird 2) and the model manager. |
119-| `Sources/RazorbillTUI` | Full-screen terminal front-end, on a small ANSI layer of its own. |123+| `Sources/RazorbillCLI` | The commands: `serve`, `config validate`, `models`, `version`. |
120-| `Sources/rzb` | The executable: wires the engine and the front-ends together. |124+| `Sources/rzb` | The executable: registers the engines and starts the command line. |
121-| `Tests/` | Unit tests (Swift Testing). |125+| `Tests/` | Unit tests (Swift Testing); `Tests/Compatibility`: the OpenAI compatibility suite (pytest). |
126+| `examples/server.yaml` | Commented server configuration. |
122 | `samples/01-query-model` | Standalone sample: send one prompt to one MLX model. |127 | `samples/01-query-model` | Standalone sample: send one prompt to one MLX model. |
123 | `tools/host-runner` | Build, test and run on the Mac from the sandbox. |128 | `tools/host-runner` | Build, test and run on the Mac from the sandbox. |
124 | `.tickets/` | Issues, epics and milestones (IssueSpec YAML format). |129 | `.tickets/` | Issues, epics and milestones (IssueSpec YAML format). |
modified Tests/Compatibility/test_docs_curl.py +9 -2
@@ -1,8 +1,9 @@
11 """The `curl` examples of the API reference run against the server and answer without error.
22
33 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.
4+run, with the address replaced by the server under test and the documentation's models by the
5+suite's (`chat`, `embed`). An example that needs a real model says so with a `# real model`
6+comment in its block.
67 """
78
89 import json
@@ -17,6 +18,10 @@ from conftest import BASE_URL
1718
1819 ROOT = Path(__file__).resolve().parents[2]
1920 DOCS_ADDRESS = "http://127.0.0.1:8080/v1"
21+DOCS_MODELS = {
22+ "mlx-community/Qwen3-4B-4bit": "chat",
23+ "BAAI/bge-small-en-v1.5": "embed",
24+}
2025 BLOCK = re.compile(r"```bash\n(.*?)```", re.DOTALL)
2126
2227
@@ -42,6 +47,8 @@ def test_curl_example(block, fake_engine):
4247 if fake_engine and "# real model" in block:
4348 pytest.skip("needs a real model (the server runs the fake engine)")
4449 script = block.replace(DOCS_ADDRESS, BASE_URL)
50+ for documented, served in DOCS_MODELS.items():
51+ script = script.replace(f'"{documented}"', f'"{served}"')
4552 env = {**os.environ, "RZB_API_KEY": os.environ.get("RZB_API_KEY", "unused")}
4653 done = subprocess.run(
4754 ["bash", "-euo", "pipefail", "-c", script],
@@ -1,8 +1,9 @@
1 """The `curl` examples of the API reference run against the server and answer without error.1 """The `curl` examples of the API reference run against the server and answer without error.
2 2
3 Every fenced `bash` block of `docs/*/reference/*.md` that calls `http://127.0.0.1:8080/v1` is3 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 model4+run, with the address replaced by the server under test and the documentation's models by the
5-says so with a `# real model` comment in its block.5+suite's (`chat`, `embed`). An example that needs a real model says so with a `# real model`
6+comment in its block.
6 """7 """
7 8
8 import json9 import json
@@ -17,6 +18,10 @@ from conftest import BASE_URL
17 18
18 ROOT = Path(__file__).resolve().parents[2]19 ROOT = Path(__file__).resolve().parents[2]
19 DOCS_ADDRESS = "http://127.0.0.1:8080/v1"20 DOCS_ADDRESS = "http://127.0.0.1:8080/v1"
21+DOCS_MODELS = {
22+ "mlx-community/Qwen3-4B-4bit": "chat",
23+ "BAAI/bge-small-en-v1.5": "embed",
24+}
20 BLOCK = re.compile(r"```bash\n(.*?)```", re.DOTALL)25 BLOCK = re.compile(r"```bash\n(.*?)```", re.DOTALL)
21 26
22 27
@@ -42,6 +47,8 @@ def test_curl_example(block, fake_engine):
42 if fake_engine and "# real model" in block:47 if fake_engine and "# real model" in block:
43 pytest.skip("needs a real model (the server runs the fake engine)")48 pytest.skip("needs a real model (the server runs the fake engine)")
44 script = block.replace(DOCS_ADDRESS, BASE_URL)49 script = block.replace(DOCS_ADDRESS, BASE_URL)
50+ for documented, served in DOCS_MODELS.items():
51+ script = script.replace(f'"{documented}"', f'"{served}"')
45 env = {**os.environ, "RZB_API_KEY": os.environ.get("RZB_API_KEY", "unused")}52 env = {**os.environ, "RZB_API_KEY": os.environ.get("RZB_API_KEY", "unused")}
46 done = subprocess.run(53 done = subprocess.run(
47 ["bash", "-euo", "pipefail", "-c", script],54 ["bash", "-euo", "pipefail", "-c", script],
modified docs/README.md +1 -1
@@ -1,6 +1,6 @@
11 # razorbill documentation
22
3-razorbill (`rzb`) is a local AI agent for the Mac that runs its own MLX models, configured by one YAML file, in the terminal.
3+razorbill (`rzb`) is an MLX model server for Apple Silicon Macs, with an OpenAI-compatible API.
44
55 - 🇬🇧 [English documentation](en/README.md)
66 - 🇫🇷 [Documentation en français](fr/README.md)
@@ -1,6 +1,6 @@
1 # razorbill documentation1 # razorbill documentation
2 2
3-razorbill (`rzb`) is a local AI agent for the Mac that runs its own MLX models, configured by one YAML file, in the terminal.3+razorbill (`rzb`) is an MLX model server for Apple Silicon Macs, with an OpenAI-compatible API.
4 4
5 - 🇬🇧 [English documentation](en/README.md)5 - 🇬🇧 [English documentation](en/README.md)
6 - 🇫🇷 [Documentation en français](fr/README.md)6 - 🇫🇷 [Documentation en français](fr/README.md)
modified docs/diagrams/packages.drawio +19 -8
@@ -5,7 +5,7 @@
55 <mxCell id="0" />
66 <mxCell id="1" parent="0" />
77
8- <mxCell id="title" value="&lt;b&gt;razorbill v0.1 — Swift modules and their dependencies&lt;/b&gt;&lt;br&gt;Arrows point from a module to what it imports. Dashed: linked on macOS only." style="text;html=1;align=left;verticalAlign=top;fontSize=14;" vertex="1" parent="1">
8+ <mxCell id="title" value="&lt;b&gt;razorbill v0.2 — Swift modules and their dependencies&lt;/b&gt;&lt;br&gt;Arrows point from a module to what it imports. Dashed: linked on macOS only." style="text;html=1;align=left;verticalAlign=top;fontSize=14;" vertex="1" parent="1">
99 <mxGeometry x="40" y="20" width="760" height="50" as="geometry" />
1010 </mxCell>
1111
@@ -19,23 +19,23 @@
1919 <mxCell id="rzb" value="&lt;b&gt;rzb&lt;/b&gt; (executable)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;registers the engines (mlx, fake) and starts the CLI&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;shadow=1;" vertex="1" parent="1">
2020 <mxGeometry x="250" y="130" width="260" height="60" as="geometry" />
2121 </mxCell>
22- <mxCell id="cli" value="&lt;b&gt;RazorbillCLI&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;commands: init, run, chat, tui, models, config, version; line-mode chat; console I/O&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">
22+ <mxCell id="cli" value="&lt;b&gt;RazorbillCLI&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;commands: serve, config validate, models, version; console I/O, request log&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">
2323 <mxGeometry x="80" y="260" width="280" height="70" as="geometry" />
2424 </mxCell>
25- <mxCell id="tui" value="&lt;b&gt;RazorbillTUI&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;full-screen chat on its own ANSI layer: keys, layout, screen, terminal&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">
25+ <mxCell id="server" value="&lt;b&gt;RazorbillServer&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;OpenAI-compatible HTTP API: routes, streaming (SSE), errors, API key, model manager. No MLX.&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">
2626 <mxGeometry x="80" y="400" width="280" height="70" as="geometry" />
2727 </mxCell>
28- <mxCell id="mlx" value="&lt;b&gt;RazorbillMLX&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;the MLX inference engine: download, load, chat sessions, thinking budget (empty on Linux)&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;shadow=1;" vertex="1" parent="1">
28+ <mxCell id="mlx" value="&lt;b&gt;RazorbillMLX&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;MLX engines: chat, raw completion, thinking budget, constrained decoding, embeddings (empty on Linux)&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;shadow=1;" vertex="1" parent="1">
2929 <mxGeometry x="430" y="260" width="280" height="70" as="geometry" />
3030 </mxCell>
31- <mxCell id="core" value="&lt;b&gt;RazorbillCore&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;YAML configuration, agent loop, engine and tool protocols, bash tool, model cache. No MLX.&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;shadow=1;" vertex="1" parent="1">
31+ <mxCell id="core" value="&lt;b&gt;RazorbillCore&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;engine protocol, settings, output constraints, server configuration, model catalog and cache, fake engine. No MLX.&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;shadow=1;" vertex="1" parent="1">
3232 <mxGeometry x="230" y="560" width="300" height="80" as="geometry" />
3333 </mxCell>
3434
3535 <mxCell id="argparser" value="&lt;b&gt;swift-argument-parser&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;command-line parsing&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
3636 <mxGeometry x="820" y="130" width="340" height="50" as="geometry" />
3737 </mxCell>
38- <mxCell id="mlxlm" value="&lt;b&gt;mlx-swift-lm&lt;/b&gt; (MLXLLM, MLXLMCommon, MLXHuggingFace)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;LLM models, ChatSession, tool calls, thinking budget; on mlx-swift / Metal&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
38+ <mxCell id="mlxlm" value="&lt;b&gt;mlx-swift-lm&lt;/b&gt; (MLXLLM, MLXLMCommon, MLXHuggingFace, MLXGuidedGeneration, MLXEmbedders)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;LLM and embedding models, ChatSession, tool calls, thinking budget, XGrammar; on mlx-swift / Metal&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
3939 <mxGeometry x="820" y="230" width="340" height="60" as="geometry" />
4040 </mxCell>
4141 <mxCell id="hf" value="&lt;b&gt;swift-huggingface&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;Hugging Face Hub client: model downloads&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
@@ -44,6 +44,9 @@
4444 <mxCell id="tokenizers" value="&lt;b&gt;swift-transformers&lt;/b&gt; (Tokenizers)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;tokenizers and chat templates&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
4545 <mxGeometry x="820" y="400" width="340" height="50" as="geometry" />
4646 </mxCell>
47+ <mxCell id="hummingbird" value="&lt;b&gt;Hummingbird 2&lt;/b&gt;, swift-service-lifecycle, swift-log&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;HTTP server, graceful shutdown, logging&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
48+ <mxGeometry x="820" y="485" width="340" height="60" as="geometry" />
49+ </mxCell>
4750 <mxCell id="yams" value="&lt;b&gt;Yams&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;YAML parsing (with line numbers for errors)&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
4851 <mxGeometry x="820" y="575" width="340" height="50" as="geometry" />
4952 </mxCell>
@@ -54,7 +57,7 @@
5457 <mxCell id="e2" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="rzb" target="mlx">
5558 <mxGeometry relative="1" as="geometry" />
5659 </mxCell>
57- <mxCell id="e3" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="cli" target="tui">
60+ <mxCell id="e3" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="cli" target="server">
5861 <mxGeometry relative="1" as="geometry" />
5962 </mxCell>
6063 <mxCell id="e4" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="cli" target="core">
@@ -65,7 +68,7 @@
6568 </Array>
6669 </mxGeometry>
6770 </mxCell>
68- <mxCell id="e5" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="tui" target="core">
71+ <mxCell id="e5" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="server" target="core">
6972 <mxGeometry relative="1" as="geometry" />
7073 </mxCell>
7174 <mxCell id="e6" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="mlx" target="core">
@@ -92,6 +95,14 @@
9295 <mxCell id="e11" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#666666;" edge="1" parent="1" source="core" target="yams">
9396 <mxGeometry relative="1" as="geometry" />
9497 </mxCell>
98+ <mxCell id="e12" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#666666;" edge="1" parent="1" source="server" target="hummingbird">
99+ <mxGeometry relative="1" as="geometry">
100+ <Array as="points">
101+ <mxPoint x="760" y="435" />
102+ <mxPoint x="760" y="515" />
103+ </Array>
104+ </mxGeometry>
105+ </mxCell>
95106 </root>
96107 </mxGraphModel>
97108 </diagram>
@@ -5,7 +5,7 @@
5 <mxCell id="0" />5 <mxCell id="0" />
6 <mxCell id="1" parent="0" />6 <mxCell id="1" parent="0" />
7 7
8- <mxCell id="title" value="&lt;b&gt;razorbill v0.1 — Swift modules and their dependencies&lt;/b&gt;&lt;br&gt;Arrows point from a module to what it imports. Dashed: linked on macOS only." style="text;html=1;align=left;verticalAlign=top;fontSize=14;" vertex="1" parent="1">8+ <mxCell id="title" value="&lt;b&gt;razorbill v0.2 — Swift modules and their dependencies&lt;/b&gt;&lt;br&gt;Arrows point from a module to what it imports. Dashed: linked on macOS only." style="text;html=1;align=left;verticalAlign=top;fontSize=14;" vertex="1" parent="1">
9 <mxGeometry x="40" y="20" width="760" height="50" as="geometry" />9 <mxGeometry x="40" y="20" width="760" height="50" as="geometry" />
10 </mxCell>10 </mxCell>
11 11
@@ -19,23 +19,23 @@
19 <mxCell id="rzb" value="&lt;b&gt;rzb&lt;/b&gt; (executable)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;registers the engines (mlx, fake) and starts the CLI&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;shadow=1;" vertex="1" parent="1">19 <mxCell id="rzb" value="&lt;b&gt;rzb&lt;/b&gt; (executable)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;registers the engines (mlx, fake) and starts the CLI&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;shadow=1;" vertex="1" parent="1">
20 <mxGeometry x="250" y="130" width="260" height="60" as="geometry" />20 <mxGeometry x="250" y="130" width="260" height="60" as="geometry" />
21 </mxCell>21 </mxCell>
22- <mxCell id="cli" value="&lt;b&gt;RazorbillCLI&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;commands: init, run, chat, tui, models, config, version; line-mode chat; console I/O&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">22+ <mxCell id="cli" value="&lt;b&gt;RazorbillCLI&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;commands: serve, config validate, models, version; console I/O, request log&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">
23 <mxGeometry x="80" y="260" width="280" height="70" as="geometry" />23 <mxGeometry x="80" y="260" width="280" height="70" as="geometry" />
24 </mxCell>24 </mxCell>
25- <mxCell id="tui" value="&lt;b&gt;RazorbillTUI&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;full-screen chat on its own ANSI layer: keys, layout, screen, terminal&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">25+ <mxCell id="server" value="&lt;b&gt;RazorbillServer&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;OpenAI-compatible HTTP API: routes, streaming (SSE), errors, API key, model manager. No MLX.&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;shadow=1;" vertex="1" parent="1">
26 <mxGeometry x="80" y="400" width="280" height="70" as="geometry" />26 <mxGeometry x="80" y="400" width="280" height="70" as="geometry" />
27 </mxCell>27 </mxCell>
28- <mxCell id="mlx" value="&lt;b&gt;RazorbillMLX&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;the MLX inference engine: download, load, chat sessions, thinking budget (empty on Linux)&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;shadow=1;" vertex="1" parent="1">28+ <mxCell id="mlx" value="&lt;b&gt;RazorbillMLX&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;MLX engines: chat, raw completion, thinking budget, constrained decoding, embeddings (empty on Linux)&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;shadow=1;" vertex="1" parent="1">
29 <mxGeometry x="430" y="260" width="280" height="70" as="geometry" />29 <mxGeometry x="430" y="260" width="280" height="70" as="geometry" />
30 </mxCell>30 </mxCell>
31- <mxCell id="core" value="&lt;b&gt;RazorbillCore&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;YAML configuration, agent loop, engine and tool protocols, bash tool, model cache. No MLX.&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;shadow=1;" vertex="1" parent="1">31+ <mxCell id="core" value="&lt;b&gt;RazorbillCore&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;engine protocol, settings, output constraints, server configuration, model catalog and cache, fake engine. No MLX.&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;shadow=1;" vertex="1" parent="1">
32 <mxGeometry x="230" y="560" width="300" height="80" as="geometry" />32 <mxGeometry x="230" y="560" width="300" height="80" as="geometry" />
33 </mxCell>33 </mxCell>
34 34
35 <mxCell id="argparser" value="&lt;b&gt;swift-argument-parser&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;command-line parsing&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">35 <mxCell id="argparser" value="&lt;b&gt;swift-argument-parser&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;command-line parsing&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
36 <mxGeometry x="820" y="130" width="340" height="50" as="geometry" />36 <mxGeometry x="820" y="130" width="340" height="50" as="geometry" />
37 </mxCell>37 </mxCell>
38- <mxCell id="mlxlm" value="&lt;b&gt;mlx-swift-lm&lt;/b&gt; (MLXLLM, MLXLMCommon, MLXHuggingFace)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;LLM models, ChatSession, tool calls, thinking budget; on mlx-swift / Metal&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">38+ <mxCell id="mlxlm" value="&lt;b&gt;mlx-swift-lm&lt;/b&gt; (MLXLLM, MLXLMCommon, MLXHuggingFace, MLXGuidedGeneration, MLXEmbedders)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;LLM and embedding models, ChatSession, tool calls, thinking budget, XGrammar; on mlx-swift / Metal&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
39 <mxGeometry x="820" y="230" width="340" height="60" as="geometry" />39 <mxGeometry x="820" y="230" width="340" height="60" as="geometry" />
40 </mxCell>40 </mxCell>
41 <mxCell id="hf" value="&lt;b&gt;swift-huggingface&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;Hugging Face Hub client: model downloads&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">41 <mxCell id="hf" value="&lt;b&gt;swift-huggingface&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;Hugging Face Hub client: model downloads&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
@@ -44,6 +44,9 @@
44 <mxCell id="tokenizers" value="&lt;b&gt;swift-transformers&lt;/b&gt; (Tokenizers)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;tokenizers and chat templates&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">44 <mxCell id="tokenizers" value="&lt;b&gt;swift-transformers&lt;/b&gt; (Tokenizers)&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;tokenizers and chat templates&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
45 <mxGeometry x="820" y="400" width="340" height="50" as="geometry" />45 <mxGeometry x="820" y="400" width="340" height="50" as="geometry" />
46 </mxCell>46 </mxCell>
47+ <mxCell id="hummingbird" value="&lt;b&gt;Hummingbird 2&lt;/b&gt;, swift-service-lifecycle, swift-log&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;HTTP server, graceful shutdown, logging&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
48+ <mxGeometry x="820" y="485" width="340" height="60" as="geometry" />
49+ </mxCell>
47 <mxCell id="yams" value="&lt;b&gt;Yams&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;YAML parsing (with line numbers for errors)&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">50 <mxCell id="yams" value="&lt;b&gt;Yams&lt;/b&gt;&lt;br&gt;&lt;font style=&quot;font-size:11px&quot;&gt;YAML parsing (with line numbers for errors)&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" vertex="1" parent="1">
48 <mxGeometry x="820" y="575" width="340" height="50" as="geometry" />51 <mxGeometry x="820" y="575" width="340" height="50" as="geometry" />
49 </mxCell>52 </mxCell>
@@ -54,7 +57,7 @@
54 <mxCell id="e2" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="rzb" target="mlx">57 <mxCell id="e2" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="rzb" target="mlx">
55 <mxGeometry relative="1" as="geometry" />58 <mxGeometry relative="1" as="geometry" />
56 </mxCell>59 </mxCell>
57- <mxCell id="e3" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="cli" target="tui">60+ <mxCell id="e3" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="cli" target="server">
58 <mxGeometry relative="1" as="geometry" />61 <mxGeometry relative="1" as="geometry" />
59 </mxCell>62 </mxCell>
60 <mxCell id="e4" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="cli" target="core">63 <mxCell id="e4" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="cli" target="core">
@@ -65,7 +68,7 @@
65 </Array>68 </Array>
66 </mxGeometry>69 </mxGeometry>
67 </mxCell>70 </mxCell>
68- <mxCell id="e5" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="tui" target="core">71+ <mxCell id="e5" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="server" target="core">
69 <mxGeometry relative="1" as="geometry" />72 <mxGeometry relative="1" as="geometry" />
70 </mxCell>73 </mxCell>
71 <mxCell id="e6" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="mlx" target="core">74 <mxCell id="e6" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#333333;" edge="1" parent="1" source="mlx" target="core">
@@ -92,6 +95,14 @@
92 <mxCell id="e11" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#666666;" edge="1" parent="1" source="core" target="yams">95 <mxCell id="e11" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#666666;" edge="1" parent="1" source="core" target="yams">
93 <mxGeometry relative="1" as="geometry" />96 <mxGeometry relative="1" as="geometry" />
94 </mxCell>97 </mxCell>
98+ <mxCell id="e12" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;strokeColor=#666666;" edge="1" parent="1" source="server" target="hummingbird">
99+ <mxGeometry relative="1" as="geometry">
100+ <Array as="points">
101+ <mxPoint x="760" y="435" />
102+ <mxPoint x="760" y="515" />
103+ </Array>
104+ </mxGeometry>
105+ </mxCell>
95 </root>106 </root>
96 </mxGraphModel>107 </mxGraphModel>
97 </diagram>108 </diagram>
modified docs/en/README.md +18 -13
@@ -1,32 +1,37 @@
11 # razorbill documentation
22
3-razorbill is a local AI agent for the Mac. Its command, `rzb`, runs models on the GPU with MLX, reads the agent's description from a YAML file, and talks with you on the command line or in a full-screen terminal UI.
3+razorbill is a model server for the Mac. Its command, `rzb serve`, runs MLX models on the Apple Silicon GPU and exposes them through an OpenAI-compatible HTTP API: chat completions (streaming, structured output, function calling, reasoning), legacy text completions and embeddings. Existing OpenAI clients and frameworks use it by changing their base URL.
44
55 This documentation follows [Diátaxis](https://diataxis.fr): pick the section that matches what you need right now.
66
77 ## Learn — tutorials
88
9-- [Getting started](tutorials/getting-started.md): build `rzb`, create an agent, chat with it and let it run a command.
9+- [Your first requests to a local model](tutorials/getting-started.md): download a model, start the server, call it with `curl` and with the `openai` library.
1010
1111 ## Do — how-to guides
1212
1313 - [Build rzb on the Mac](how-to/build-on-the-mac.md)
1414 - [Manage models](how-to/manage-models.md)
15-- [Configure thinking](how-to/configure-thinking.md)
16-- [Use the bash tool](how-to/use-the-bash-tool.md)
17-- [Use rzb in scripts](how-to/use-rzb-in-scripts.md)
18-- [Add a tool](how-to/add-a-tool.md)
19-- [Run the tests](how-to/run-the-tests.md)
15+- [Configure the server](how-to/configure-the-server.md): model names, defaults, locks, limits, network access.
16+- [Use razorbill from an OpenAI client](how-to/use-openai-clients.md): Python, JavaScript, LangChain, chat UIs.
17+- [Get structured output](how-to/get-structured-output.md)
18+- [Use function calling](how-to/use-function-calling.md)
19+- [Compute embeddings](how-to/compute-embeddings.md)
20+- [Control reasoning](how-to/configure-thinking.md)
21+- [Run the tests](how-to/run-the-tests.md), the OpenAI compatibility suite included.
2022 - [Develop from a Linux sandbox](how-to/develop-from-a-sandbox.md)
2123
2224 ## Look up — reference
2325
24-- [Command line](reference/cli.md): commands, options, exit codes, chat commands, TUI keys.
25-- [Agent file](reference/configuration.md): every YAML key, its type, default and errors.
26-- [bash tool](reference/bash-tool.md): options, checks, output sent to the model.
26+- [HTTP API](reference/http-api.md): endpoints, fields supported, refused and ignored, responses, streaming.
27+- [Server configuration file](reference/configuration.md): every key, its type, default and errors.
28+- [Command line](reference/cli.md): `rzb serve`, `rzb models`, `rzb config validate`, exit codes.
29+- [API errors](reference/errors.md): statuses, types and codes.
2730
2831 ## Understand — explanation
2932
30-- [Architecture](explanation/architecture.md): the modules, why the code is split this way, why the Mac build uses `xcodebuild`.
31-- [Thinking models](explanation/thinking.md): how reasoning is separated from the answer, displayed and limited.
32-- [Tool safety](explanation/tool-safety.md): what the bash tool protects against, and what it does not.
33+- [Architecture](explanation/architecture.md): the modules, the path of a request, why the Mac build uses `xcodebuild`.
34+- [Model lifecycle and concurrency](explanation/model-lifecycle.md): loading, queues, memory, unloading, cancellation.
35+- [Constrained decoding](explanation/constrained-decoding.md): how JSON and tool calls are guaranteed, and the limits.
36+- [Reasoning models](explanation/thinking.md): how reasoning is separated, sent or hidden, and limited.
37+- [OpenAI compatibility](explanation/openai-compatibility.md): what "compatible" means here and how it is checked.
@@ -1,32 +1,37 @@
1 # razorbill documentation1 # razorbill documentation
2 2
3-razorbill is a local AI agent for the Mac. Its command, `rzb`, runs models on the GPU with MLX, reads the agent's description from a YAML file, and talks with you on the command line or in a full-screen terminal UI.3+razorbill is a model server for the Mac. Its command, `rzb serve`, runs MLX models on the Apple Silicon GPU and exposes them through an OpenAI-compatible HTTP API: chat completions (streaming, structured output, function calling, reasoning), legacy text completions and embeddings. Existing OpenAI clients and frameworks use it by changing their base URL.
4 4
5 This documentation follows [Diátaxis](https://diataxis.fr): pick the section that matches what you need right now.5 This documentation follows [Diátaxis](https://diataxis.fr): pick the section that matches what you need right now.
6 6
7 ## Learn — tutorials7 ## Learn — tutorials
8 8
9-- [Getting started](tutorials/getting-started.md): build `rzb`, create an agent, chat with it and let it run a command.9+- [Your first requests to a local model](tutorials/getting-started.md): download a model, start the server, call it with `curl` and with the `openai` library.
10 10
11 ## Do — how-to guides11 ## Do — how-to guides
12 12
13 - [Build rzb on the Mac](how-to/build-on-the-mac.md)13 - [Build rzb on the Mac](how-to/build-on-the-mac.md)
14 - [Manage models](how-to/manage-models.md)14 - [Manage models](how-to/manage-models.md)
15-- [Configure thinking](how-to/configure-thinking.md)15+- [Configure the server](how-to/configure-the-server.md): model names, defaults, locks, limits, network access.
16-- [Use the bash tool](how-to/use-the-bash-tool.md)16+- [Use razorbill from an OpenAI client](how-to/use-openai-clients.md): Python, JavaScript, LangChain, chat UIs.
17-- [Use rzb in scripts](how-to/use-rzb-in-scripts.md)17+- [Get structured output](how-to/get-structured-output.md)
18-- [Add a tool](how-to/add-a-tool.md)18+- [Use function calling](how-to/use-function-calling.md)
19-- [Run the tests](how-to/run-the-tests.md)19+- [Compute embeddings](how-to/compute-embeddings.md)
20+- [Control reasoning](how-to/configure-thinking.md)
21+- [Run the tests](how-to/run-the-tests.md), the OpenAI compatibility suite included.
20 - [Develop from a Linux sandbox](how-to/develop-from-a-sandbox.md)22 - [Develop from a Linux sandbox](how-to/develop-from-a-sandbox.md)
21 23
22 ## Look up — reference24 ## Look up — reference
23 25
24-- [Command line](reference/cli.md): commands, options, exit codes, chat commands, TUI keys.26+- [HTTP API](reference/http-api.md): endpoints, fields supported, refused and ignored, responses, streaming.
25-- [Agent file](reference/configuration.md): every YAML key, its type, default and errors.27+- [Server configuration file](reference/configuration.md): every key, its type, default and errors.
26-- [bash tool](reference/bash-tool.md): options, checks, output sent to the model.28+- [Command line](reference/cli.md): `rzb serve`, `rzb models`, `rzb config validate`, exit codes.
29+- [API errors](reference/errors.md): statuses, types and codes.
27 30
28 ## Understand — explanation31 ## Understand — explanation
29 32
30-- [Architecture](explanation/architecture.md): the modules, why the code is split this way, why the Mac build uses `xcodebuild`.33+- [Architecture](explanation/architecture.md): the modules, the path of a request, why the Mac build uses `xcodebuild`.
31-- [Thinking models](explanation/thinking.md): how reasoning is separated from the answer, displayed and limited.34+- [Model lifecycle and concurrency](explanation/model-lifecycle.md): loading, queues, memory, unloading, cancellation.
32-- [Tool safety](explanation/tool-safety.md): what the bash tool protects against, and what it does not.35+- [Constrained decoding](explanation/constrained-decoding.md): how JSON and tool calls are guaranteed, and the limits.
36+- [Reasoning models](explanation/thinking.md): how reasoning is separated, sent or hidden, and limited.
37+- [OpenAI compatibility](explanation/openai-compatibility.md): what "compatible" means here and how it is checked.
modified docs/en/explanation/architecture.md +24 -25
@@ -2,7 +2,7 @@
22
33 ## What is this about?
44
5-razorbill is one Swift package that produces one executable, `rzb`. Inside, the code is split into five modules with a strict direction of dependencies. This page explains that split, the path a message takes through it, and a few decisions that shape how the project is built.
5+razorbill is one Swift package that produces one executable, `rzb`, a model server: it loads MLX models on the Mac's GPU and exposes them through an OpenAI-compatible HTTP API. Inside, the code is split into five modules with a strict direction of dependencies. This page explains that split, the path a request takes through it, and a few decisions that shape how the project is built.
66
77 The diagram [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) shows the modules, their dependencies and the third-party packages.
88
@@ -10,47 +10,46 @@ The diagram [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) show
1010
1111 | Module | Role | Depends on |
1212 | --- | --- | --- |
13-| `RazorbillCore` | The agent file (loading, validation, variables), the agent loop, the protocols for engines and tools, the `bash` tool, the model cache. | Yams |
14-| `RazorbillMLX` | The MLX engine: download, loading, chat sessions, thinking detection and budget. | Core, mlx-swift-lm, swift-huggingface, swift-transformers (macOS only) |
15-| `RazorbillTUI` | The full-screen interface, on a small ANSI layer of its own. | Core |
16-| `RazorbillCLI` | The commands (`init`, `run`, `chat`, `tui`, `models`, `config`, `version`) and the line-mode chat. | Core, TUI, swift-argument-parser |
13+| `RazorbillCore` | The engine protocol and its events, generation settings, output constraints, the server configuration file (loading, validation), the model catalog and cache, the fake engine. | Yams |
14+| `RazorbillMLX` | The MLX engines: chat sessions, raw completions, thinking detection and budget, constrained decoding (XGrammar), embeddings. | Core, mlx-swift-lm, mlx-swift, swift-huggingface, swift-transformers (macOS only) |
15+| `RazorbillServer` | The HTTP server: routes, OpenAI request and response types, streaming, errors, authentication, the model manager. | Core, Hummingbird, swift-service-lifecycle |
16+| `RazorbillCLI` | The commands (`serve`, `config validate`, `models`, `version`). | Core, Server, swift-argument-parser, swift-log |
1717 | `rzb` | The executable: registers the engines and starts the command line. | CLI, MLX |
1818
19-Everything points towards `RazorbillCore`, and `RazorbillCore` knows nothing about MLX, terminals or command-line parsing. That is the property the rest of the design protects.
19+Everything points towards `RazorbillCore`, and `RazorbillCore` knows nothing about MLX, HTTP or command-line parsing. `RazorbillServer` does not know MLX either: it talks to engines only through the protocol.
2020
2121 ## Why it is split this way
2222
23-**The core must build without a GPU.** MLX needs Metal, which exists only on Apple platforms. Keeping MLX out of the core means the configuration, the agent loop, the tools, the CLI and the TUI build and are tested on Linux — which is where most of the development happens (see [develop from a Linux sandbox](../how-to/develop-from-a-sandbox.md)). `RazorbillMLX` links mlx-swift-lm only on macOS and its code is guarded by `#if canImport(MLXLLM)`; on Linux the module is empty and `rzb` has only the `fake` engine.
23+**Everything but MLX must build and be tested without a GPU.** MLX needs Metal, which exists only on Apple platforms. Keeping it out of the core and the server means the configuration, the HTTP layer, the OpenAI types, streaming, the model manager and the command line build and are tested on Linux, where most of the development happens (see [develop from a Linux sandbox](../how-to/develop-from-a-sandbox.md)). On Linux, `RazorbillMLX` is empty and `rzb` has only the `fake` engine, which answers `echo: …` — enough to test the whole server, and to run the OpenAI compatibility suite against its protocol.
2424
25-**Engines are replaceable.** The agent talks to an `InferenceEngine` protocol: load a model, open a session, send messages, receive a stream of events (text, reasoning, tool calls, statistics). MLX is one implementation; `FakeEngine` is another, which plays scripted turns and lets every test of the agent, the CLI and the TUI run without a model. Another runtime (llama.cpp, a remote API) would be one more module behind the same protocol, chosen with `--engine`.
25+**Engines are replaceable.** The server asks an `InferenceEngine` to load a model, open a session, send messages and stream events (text, reasoning, tool calls, statistics), to continue a raw prompt, or to embed texts. MLX is one implementation; another runtime would be one more module behind the same protocol.
2626
27-**Front-ends are thin.** `run`, `chat` and `tui` all go through the same `AgentLauncher`: find and load the file, apply the command-line overrides, build the tools, pick the engine, load the model. They differ only in how they read input and show events. The TUI keeps its state (`ChatState`) and its drawing (`ScreenRenderer`) apart from the real terminal (`PosixTerminal`), so its behaviour is tested with a fake terminal.
27+**The OpenAI layer is thin and strict.** Request types decode the OpenAI JSON, check every field, and produce a plan (messages, settings, output constraint). Fields razorbill cannot honour are refused with a 400 naming them rather than silently ignored (see [OpenAI compatibility](openai-compatibility.md)).
2828
29-## The agent loop
29+## The path of a chat request
3030
31-1. The user's message is added to the conversation and sent to the engine with the system prompt and the tool specifications.
32-2. The engine streams events. Text and reasoning go straight to the front-end.
33-3. When the model asks for a tool, the agent runs it (after the tool's own checks and, for `bash`, the user's confirmation) and sends the result back to the model, which continues.
34-4. The turn ends when the model answers without calling a tool, or after 8 tool rounds (an error then stops the turn).
31+1. Hummingbird receives `POST /v1/chat/completions`. Middlewares log it, apply CORS, check the API key, and turn any error into OpenAI's error body.
32+2. The body is decoded and validated into a `ChatPlan`; JSON Schemas are re-read to keep their key order. With `response_format`, an instruction carrying the schema is added to the system message.
33+3. The model manager resolves the name (declared id, or Hugging Face id), loads the model if needed, and gives the request a **lease**: one generation per model at a time, the others wait in a queue (see [model lifecycle](model-lifecycle.md)).
34+4. The engine opens a fresh session with the request's settings and constraint, renders the conversation with the model's chat template, and streams events.
35+5. The events become OpenAI pieces: stop sequences are applied, reasoning is separated or hidden, tool calls are numbered, and `finish_reason` and `usage` are computed.
36+6. The pieces are gathered into one `chat.completion`, or sent as Server-Sent Events as they come. When the answer ends — or the client disconnects — the lease is released.
3537
36-The conversation (`transcript`) stays in memory for the session; `/reset` and Ctrl-N clear it while keeping the model loaded.
38+The server is stateless: each request carries the whole conversation, and nothing is kept between requests but the loaded models.
3739
3840 ## Why the Mac build uses xcodebuild
3941
4042 MLX ships Metal shaders that must be compiled into a `default.metallib`. SwiftPM's `swift build` cannot compile Metal, so a binary built that way fails with `Failed to load the default metallib` as soon as a model loads. `xcodebuild` compiles them into `mlx-swift_Cmlx.bundle`, which must stay next to `rzb`. On Linux there is no MLX, so plain `swift build` / `swift test` work there.
4143
42-## Why a TUI layer of its own
43-
44-The full-screen interface needs little: raw keyboard input, the alternate screen, a few colours, resizing, and restoring the terminal on every exit path. A small layer over termios and ANSI codes does that without a dependency, keeps the TUI testable (the terminal is a protocol), and avoids depending on a library that would have to support both macOS and Linux.
45-
4644 ## Rejected alternatives
4745
48-- **An HTTP server like Ollama** was the first idea. It was dropped for an agent that loads its own models: no server to start, one process, one configuration file.
49-- **One agent file with several agents** was rejected for v0.1: one file per agent keeps the format and the lookup simple.
50-- **Configuration in Swift or JSON**: YAML was chosen for comments, readability, and error messages with line numbers.
46+- **A local agent** (version 0.1): `rzb` first ran one agent from a YAML file in the terminal, with its own tools. It was replaced by a server, because an OpenAI-compatible API lets every existing client, framework and agent use the Mac's GPU, instead of one built-in front-end.
47+- **Ollama's API** (`/api/chat`…) next to OpenAI's: two APIs to keep compatible for one benefit; OpenAI's is what frameworks speak.
48+- **Vapor instead of Hummingbird**: Hummingbird 2 is smaller, built on structured concurrency, and enough for six endpoints.
49+- **Python (mlx-lm's server)**: razorbill is a single native binary, with no Python environment to install.
5150
5251 ## How it relates to the rest
5352
54-- The keys of the agent file: [agent file reference](../reference/configuration.md).
55-- How reasoning is handled by the MLX engine: [thinking models](thinking.md).
56-- What the tools may and may not do: [tool safety](tool-safety.md).
53+- How models are loaded, shared and unloaded: [model lifecycle](model-lifecycle.md).
54+- How JSON and tool calls are guaranteed: [constrained decoding](constrained-decoding.md).
55+- How reasoning is separated from answers: [reasoning models](thinking.md).
@@ -2,7 +2,7 @@
2 2
3 ## What is this about?3 ## What is this about?
4 4
5-razorbill is one Swift package that produces one executable, `rzb`. Inside, the code is split into five modules with a strict direction of dependencies. This page explains that split, the path a message takes through it, and a few decisions that shape how the project is built.5+razorbill is one Swift package that produces one executable, `rzb`, a model server: it loads MLX models on the Mac's GPU and exposes them through an OpenAI-compatible HTTP API. Inside, the code is split into five modules with a strict direction of dependencies. This page explains that split, the path a request takes through it, and a few decisions that shape how the project is built.
6 6
7 The diagram [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) shows the modules, their dependencies and the third-party packages.7 The diagram [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) shows the modules, their dependencies and the third-party packages.
8 8
@@ -10,47 +10,46 @@ The diagram [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) show
10 10
11 | Module | Role | Depends on |11 | Module | Role | Depends on |
12 | --- | --- | --- |12 | --- | --- | --- |
13-| `RazorbillCore` | The agent file (loading, validation, variables), the agent loop, the protocols for engines and tools, the `bash` tool, the model cache. | Yams |13+| `RazorbillCore` | The engine protocol and its events, generation settings, output constraints, the server configuration file (loading, validation), the model catalog and cache, the fake engine. | Yams |
14-| `RazorbillMLX` | The MLX engine: download, loading, chat sessions, thinking detection and budget. | Core, mlx-swift-lm, swift-huggingface, swift-transformers (macOS only) |14+| `RazorbillMLX` | The MLX engines: chat sessions, raw completions, thinking detection and budget, constrained decoding (XGrammar), embeddings. | Core, mlx-swift-lm, mlx-swift, swift-huggingface, swift-transformers (macOS only) |
15-| `RazorbillTUI` | The full-screen interface, on a small ANSI layer of its own. | Core |15+| `RazorbillServer` | The HTTP server: routes, OpenAI request and response types, streaming, errors, authentication, the model manager. | Core, Hummingbird, swift-service-lifecycle |
16-| `RazorbillCLI` | The commands (`init`, `run`, `chat`, `tui`, `models`, `config`, `version`) and the line-mode chat. | Core, TUI, swift-argument-parser |16+| `RazorbillCLI` | The commands (`serve`, `config validate`, `models`, `version`). | Core, Server, swift-argument-parser, swift-log |
17 | `rzb` | The executable: registers the engines and starts the command line. | CLI, MLX |17 | `rzb` | The executable: registers the engines and starts the command line. | CLI, MLX |
18 18
19-Everything points towards `RazorbillCore`, and `RazorbillCore` knows nothing about MLX, terminals or command-line parsing. That is the property the rest of the design protects.19+Everything points towards `RazorbillCore`, and `RazorbillCore` knows nothing about MLX, HTTP or command-line parsing. `RazorbillServer` does not know MLX either: it talks to engines only through the protocol.
20 20
21 ## Why it is split this way21 ## Why it is split this way
22 22
23-**The core must build without a GPU.** MLX needs Metal, which exists only on Apple platforms. Keeping MLX out of the core means the configuration, the agent loop, the tools, the CLI and the TUI build and are tested on Linux — which is where most of the development happens (see [develop from a Linux sandbox](../how-to/develop-from-a-sandbox.md)). `RazorbillMLX` links mlx-swift-lm only on macOS and its code is guarded by `#if canImport(MLXLLM)`; on Linux the module is empty and `rzb` has only the `fake` engine.23+**Everything but MLX must build and be tested without a GPU.** MLX needs Metal, which exists only on Apple platforms. Keeping it out of the core and the server means the configuration, the HTTP layer, the OpenAI types, streaming, the model manager and the command line build and are tested on Linux, where most of the development happens (see [develop from a Linux sandbox](../how-to/develop-from-a-sandbox.md)). On Linux, `RazorbillMLX` is empty and `rzb` has only the `fake` engine, which answers `echo: …` — enough to test the whole server, and to run the OpenAI compatibility suite against its protocol.
24 24
25-**Engines are replaceable.** The agent talks to an `InferenceEngine` protocol: load a model, open a session, send messages, receive a stream of events (text, reasoning, tool calls, statistics). MLX is one implementation; `FakeEngine` is another, which plays scripted turns and lets every test of the agent, the CLI and the TUI run without a model. Another runtime (llama.cpp, a remote API) would be one more module behind the same protocol, chosen with `--engine`.25+**Engines are replaceable.** The server asks an `InferenceEngine` to load a model, open a session, send messages and stream events (text, reasoning, tool calls, statistics), to continue a raw prompt, or to embed texts. MLX is one implementation; another runtime would be one more module behind the same protocol.
26 26
27-**Front-ends are thin.** `run`, `chat` and `tui` all go through the same `AgentLauncher`: find and load the file, apply the command-line overrides, build the tools, pick the engine, load the model. They differ only in how they read input and show events. The TUI keeps its state (`ChatState`) and its drawing (`ScreenRenderer`) apart from the real terminal (`PosixTerminal`), so its behaviour is tested with a fake terminal.27+**The OpenAI layer is thin and strict.** Request types decode the OpenAI JSON, check every field, and produce a plan (messages, settings, output constraint). Fields razorbill cannot honour are refused with a 400 naming them rather than silently ignored (see [OpenAI compatibility](openai-compatibility.md)).
28 28
29-## The agent loop29+## The path of a chat request
30 30
31-1. The user's message is added to the conversation and sent to the engine with the system prompt and the tool specifications.31+1. Hummingbird receives `POST /v1/chat/completions`. Middlewares log it, apply CORS, check the API key, and turn any error into OpenAI's error body.
32-2. The engine streams events. Text and reasoning go straight to the front-end.32+2. The body is decoded and validated into a `ChatPlan`; JSON Schemas are re-read to keep their key order. With `response_format`, an instruction carrying the schema is added to the system message.
33-3. When the model asks for a tool, the agent runs it (after the tool's own checks and, for `bash`, the user's confirmation) and sends the result back to the model, which continues.33+3. The model manager resolves the name (declared id, or Hugging Face id), loads the model if needed, and gives the request a **lease**: one generation per model at a time, the others wait in a queue (see [model lifecycle](model-lifecycle.md)).
34-4. The turn ends when the model answers without calling a tool, or after 8 tool rounds (an error then stops the turn).34+4. The engine opens a fresh session with the request's settings and constraint, renders the conversation with the model's chat template, and streams events.
35+5. The events become OpenAI pieces: stop sequences are applied, reasoning is separated or hidden, tool calls are numbered, and `finish_reason` and `usage` are computed.
36+6. The pieces are gathered into one `chat.completion`, or sent as Server-Sent Events as they come. When the answer ends — or the client disconnects — the lease is released.
35 37
36-The conversation (`transcript`) stays in memory for the session; `/reset` and Ctrl-N clear it while keeping the model loaded.38+The server is stateless: each request carries the whole conversation, and nothing is kept between requests but the loaded models.
37 39
38 ## Why the Mac build uses xcodebuild40 ## Why the Mac build uses xcodebuild
39 41
40 MLX ships Metal shaders that must be compiled into a `default.metallib`. SwiftPM's `swift build` cannot compile Metal, so a binary built that way fails with `Failed to load the default metallib` as soon as a model loads. `xcodebuild` compiles them into `mlx-swift_Cmlx.bundle`, which must stay next to `rzb`. On Linux there is no MLX, so plain `swift build` / `swift test` work there.42 MLX ships Metal shaders that must be compiled into a `default.metallib`. SwiftPM's `swift build` cannot compile Metal, so a binary built that way fails with `Failed to load the default metallib` as soon as a model loads. `xcodebuild` compiles them into `mlx-swift_Cmlx.bundle`, which must stay next to `rzb`. On Linux there is no MLX, so plain `swift build` / `swift test` work there.
41 43
42-## Why a TUI layer of its own
43-
44-The full-screen interface needs little: raw keyboard input, the alternate screen, a few colours, resizing, and restoring the terminal on every exit path. A small layer over termios and ANSI codes does that without a dependency, keeps the TUI testable (the terminal is a protocol), and avoids depending on a library that would have to support both macOS and Linux.
45-
46 ## Rejected alternatives44 ## Rejected alternatives
47 45
48-- **An HTTP server like Ollama** was the first idea. It was dropped for an agent that loads its own models: no server to start, one process, one configuration file.46+- **A local agent** (version 0.1): `rzb` first ran one agent from a YAML file in the terminal, with its own tools. It was replaced by a server, because an OpenAI-compatible API lets every existing client, framework and agent use the Mac's GPU, instead of one built-in front-end.
49-- **One agent file with several agents** was rejected for v0.1: one file per agent keeps the format and the lookup simple.47+- **Ollama's API** (`/api/chat`…) next to OpenAI's: two APIs to keep compatible for one benefit; OpenAI's is what frameworks speak.
50-- **Configuration in Swift or JSON**: YAML was chosen for comments, readability, and error messages with line numbers.48+- **Vapor instead of Hummingbird**: Hummingbird 2 is smaller, built on structured concurrency, and enough for six endpoints.
49+- **Python (mlx-lm's server)**: razorbill is a single native binary, with no Python environment to install.
51 50
52 ## How it relates to the rest51 ## How it relates to the rest
53 52
54-- The keys of the agent file: [agent file reference](../reference/configuration.md).53+- How models are loaded, shared and unloaded: [model lifecycle](model-lifecycle.md).
55-- How reasoning is handled by the MLX engine: [thinking models](thinking.md).54+- How JSON and tool calls are guaranteed: [constrained decoding](constrained-decoding.md).
56-- What the tools may and may not do: [tool safety](tool-safety.md).55+- How reasoning is separated from answers: [reasoning models](thinking.md).
added docs/en/explanation/constrained-decoding.md +53 -0
new file mode 100644
@@ -0,0 +1,53 @@
1+# Constrained decoding — explanation
2+
3+## What is this about?
4+
5+A language model writes one token at a time, each sampled from a probability distribution over its whole vocabulary. Asking it nicely for JSON works most of the time; "most of the time" is not enough for a program that parses the answer. Structured output (`response_format`) and forced tool calls (`tool_choice: required`) are therefore **guaranteed** by razorbill, not requested: at each step, the tokens that would break the expected format are removed before sampling. This page explains how, where it stops, and the lessons learnt while building it.
6+
7+## How the guarantee works
8+
9+razorbill uses XGrammar, the grammar engine bundled with mlx-swift-lm. A JSON Schema (or a tool-call format) is compiled into a grammar for the model's tokenizer. During generation, a logit processor asks the grammar, at each step, which tokens may come next, and gives every other token a probability of zero. Whatever the model "wants", it can only write a valid continuation; when the grammar is complete, generation ends.
10+
11+The processor sits inside mlx-swift-lm's normal generation loop. Temperature, top-p, penalties, the thinking budget, streaming and tool-call parsing all keep working: the constraint only narrows the choice of tokens.
12+
13+**Reasoning models think first.** The processor stays inactive until the model closes its reasoning (`</think>`): the reasoning is free text, then the answer is constrained. Constraining the reasoning too would turn it into JSON, and the model would lose the benefit of thinking.
14+
15+## The grammar is not enough: telling the model
16+
17+The first version only constrained. Measured with Qwen3-4B, it worked well when the model answered directly, but with reasoning on, the answers were valid JSON with absurd content: a paragraph of prose in a `"country"` field, a population written as an endless string of digits. The cause is plain once seen: nothing in the prompt said JSON was expected, so the model planned a prose answer while thinking, and the grammar then forced that prose into the fields.
18+
19+razorbill therefore also **tells** the model: with `response_format`, one sentence is appended to the system message, carrying the schema for `json_schema`. With it, the same test went from prose in the fields to three correct answers out of three, with reasoning half as long. The grammar guarantees the form; the instruction makes the content sensible. OpenAI's models are trained for structured output and do not need this; local models do.
20+
21+## Key order
22+
23+A grammar generated from a schema writes an object's properties in the order the schema lists them. That order matters to clients: putting a `reasoning` field before `answer` is a known way to let a model think before it commits. razorbill's first version lost it: Swift's JSON decoder does not keep the order of object keys, so schemas reached the grammar sorted alphabetically. The request's schemas are now read with an order-preserving parser.
24+
25+## What cannot be guaranteed
26+
27+**Some JSON Schema keywords** are accepted by XGrammar but not enforced: `not`, `if` / `then` / `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. With `"strict": true`, the client asked for a guarantee, so razorbill refuses such a schema with a 400 naming the keyword rather than silently returning output that might break it. Without `strict`, they are ignored.
28+
29+**Forced tool calls depend on the model family.** Each family writes tool calls in its own syntax: `<tool_call>{"name": …, "arguments": …}</tool_call>` for Qwen and Hermes, `<|python_tag|>` and other forms for Llama, `[TOOL_CALLS]` for Mistral… razorbill builds forcing grammars (XGrammar "structural tags") for the `<tool_call>` JSON syntax only, which covers the most common tool-capable local models. For the other families, `tool_choice: required`, a named function, or a `strict` tool is refused with a 400, and `auto` still works through mlx-swift-lm's parsers.
30+
31+**Content.** A grammar guarantees that `population` is an integer, not that it is the right one. Small models (below about 1B parameters) follow schemas reliably and fill them poorly; at temperature 0 they can also loop inside a long string until `max_tokens`. Prefer a 4B model or larger for extraction.
32+
33+## Small-model pitfalls the server handles
34+
35+- **Whitespace loops.** JSON allows any amount of whitespace between tokens, and the bundled XGrammar version does not restrict it. Qwen3-0.6B, constrained, would sometimes write newlines forever. razorbill penalises long runs of whitespace tokens while a constraint is active.
36+- **Repeated calls.** Under `tool_choice: required`, a small model may call the same tool again and again until `max_tokens`, and the truncated last call is lost. A forced call therefore produces one call unless the client explicitly sends `parallel_tool_calls: true`.
37+- **JSON answers streamed in one piece.** mlx-swift-lm's tool-call parser holds back any answer starting with `{` in case it is a bare JSON tool call. Without tools in the request, razorbill switches to a parser without that fallback, so JSON streams token by token.
38+
39+## Costs
40+
41+The grammar is compiled for each request (about 0.2 s): the bundled XGrammar cannot copy a compiled grammar, so caching it would mean sharing mutable state between requests. Masking the vocabulary at each step also slows generation; measured on a small model in a debug build, about 90 tokens/s free against about 49 constrained.
42+
43+## Rejected alternatives
44+
45+- **Validate after generation and retry**: no guarantee, unbounded cost, and streaming would show invalid output.
46+- **Only the instruction, no grammar**: what models do without help is exactly what the guarantee is for.
47+- **Forcing tool calls for every family with hand-written grammars**: each syntax is a maintenance burden; refusing clearly is honest until a real need appears.
48+
49+## How it relates to the rest
50+
51+- How to use it: [get structured output](../how-to/get-structured-output.md) and [use function calling](../how-to/use-function-calling.md).
52+- The exact fields and refusals: [HTTP API reference](../reference/http-api.md#structured-output).
53+- How reasoning is separated before the constraint applies: [reasoning models](thinking.md).
new file mode 100644
@@ -0,0 +1,53 @@
1+# Constrained decoding — explanation
2+
3+## What is this about?
4+
5+A language model writes one token at a time, each sampled from a probability distribution over its whole vocabulary. Asking it nicely for JSON works most of the time; "most of the time" is not enough for a program that parses the answer. Structured output (`response_format`) and forced tool calls (`tool_choice: required`) are therefore **guaranteed** by razorbill, not requested: at each step, the tokens that would break the expected format are removed before sampling. This page explains how, where it stops, and the lessons learnt while building it.
6+
7+## How the guarantee works
8+
9+razorbill uses XGrammar, the grammar engine bundled with mlx-swift-lm. A JSON Schema (or a tool-call format) is compiled into a grammar for the model's tokenizer. During generation, a logit processor asks the grammar, at each step, which tokens may come next, and gives every other token a probability of zero. Whatever the model "wants", it can only write a valid continuation; when the grammar is complete, generation ends.
10+
11+The processor sits inside mlx-swift-lm's normal generation loop. Temperature, top-p, penalties, the thinking budget, streaming and tool-call parsing all keep working: the constraint only narrows the choice of tokens.
12+
13+**Reasoning models think first.** The processor stays inactive until the model closes its reasoning (`</think>`): the reasoning is free text, then the answer is constrained. Constraining the reasoning too would turn it into JSON, and the model would lose the benefit of thinking.
14+
15+## The grammar is not enough: telling the model
16+
17+The first version only constrained. Measured with Qwen3-4B, it worked well when the model answered directly, but with reasoning on, the answers were valid JSON with absurd content: a paragraph of prose in a `"country"` field, a population written as an endless string of digits. The cause is plain once seen: nothing in the prompt said JSON was expected, so the model planned a prose answer while thinking, and the grammar then forced that prose into the fields.
18+
19+razorbill therefore also **tells** the model: with `response_format`, one sentence is appended to the system message, carrying the schema for `json_schema`. With it, the same test went from prose in the fields to three correct answers out of three, with reasoning half as long. The grammar guarantees the form; the instruction makes the content sensible. OpenAI's models are trained for structured output and do not need this; local models do.
20+
21+## Key order
22+
23+A grammar generated from a schema writes an object's properties in the order the schema lists them. That order matters to clients: putting a `reasoning` field before `answer` is a known way to let a model think before it commits. razorbill's first version lost it: Swift's JSON decoder does not keep the order of object keys, so schemas reached the grammar sorted alphabetically. The request's schemas are now read with an order-preserving parser.
24+
25+## What cannot be guaranteed
26+
27+**Some JSON Schema keywords** are accepted by XGrammar but not enforced: `not`, `if` / `then` / `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. With `"strict": true`, the client asked for a guarantee, so razorbill refuses such a schema with a 400 naming the keyword rather than silently returning output that might break it. Without `strict`, they are ignored.
28+
29+**Forced tool calls depend on the model family.** Each family writes tool calls in its own syntax: `<tool_call>{"name": …, "arguments": …}</tool_call>` for Qwen and Hermes, `<|python_tag|>` and other forms for Llama, `[TOOL_CALLS]` for Mistral… razorbill builds forcing grammars (XGrammar "structural tags") for the `<tool_call>` JSON syntax only, which covers the most common tool-capable local models. For the other families, `tool_choice: required`, a named function, or a `strict` tool is refused with a 400, and `auto` still works through mlx-swift-lm's parsers.
30+
31+**Content.** A grammar guarantees that `population` is an integer, not that it is the right one. Small models (below about 1B parameters) follow schemas reliably and fill them poorly; at temperature 0 they can also loop inside a long string until `max_tokens`. Prefer a 4B model or larger for extraction.
32+
33+## Small-model pitfalls the server handles
34+
35+- **Whitespace loops.** JSON allows any amount of whitespace between tokens, and the bundled XGrammar version does not restrict it. Qwen3-0.6B, constrained, would sometimes write newlines forever. razorbill penalises long runs of whitespace tokens while a constraint is active.
36+- **Repeated calls.** Under `tool_choice: required`, a small model may call the same tool again and again until `max_tokens`, and the truncated last call is lost. A forced call therefore produces one call unless the client explicitly sends `parallel_tool_calls: true`.
37+- **JSON answers streamed in one piece.** mlx-swift-lm's tool-call parser holds back any answer starting with `{` in case it is a bare JSON tool call. Without tools in the request, razorbill switches to a parser without that fallback, so JSON streams token by token.
38+
39+## Costs
40+
41+The grammar is compiled for each request (about 0.2 s): the bundled XGrammar cannot copy a compiled grammar, so caching it would mean sharing mutable state between requests. Masking the vocabulary at each step also slows generation; measured on a small model in a debug build, about 90 tokens/s free against about 49 constrained.
42+
43+## Rejected alternatives
44+
45+- **Validate after generation and retry**: no guarantee, unbounded cost, and streaming would show invalid output.
46+- **Only the instruction, no grammar**: what models do without help is exactly what the guarantee is for.
47+- **Forcing tool calls for every family with hand-written grammars**: each syntax is a maintenance burden; refusing clearly is honest until a real need appears.
48+
49+## How it relates to the rest
50+
51+- How to use it: [get structured output](../how-to/get-structured-output.md) and [use function calling](../how-to/use-function-calling.md).
52+- The exact fields and refusals: [HTTP API reference](../reference/http-api.md#structured-output).
53+- How reasoning is separated before the constraint applies: [reasoning models](thinking.md).
added docs/en/explanation/model-lifecycle.md +48 -0
new file mode 100644
@@ -0,0 +1,48 @@
1+# Model lifecycle and concurrency — explanation
2+
3+## What is this about?
4+
5+A model is gigabytes of weights in the Mac's unified memory, and generating with it keeps the GPU busy. The server has to decide when to load a model, who may use it, what to do when several clients arrive at once, and when to give the memory back. All of that lives in one place, the **model manager** (`ModelManager`, an actor in `RazorbillServer`). This page explains its rules and why they were chosen.
6+
7+## One load, shared
8+
9+A model is loaded on the first request that needs it — or at start-up when it is declared with `preload: true` — and then shared by every request. Two names that point to the same repository (a declared `id` and its Hugging Face id, or two declared entries with different settings) share one load: the manager keys models by repository and revision, not by the name the client sent. A chat load and an embedding load of the same repository are different models, because they are loaded by different engines.
10+
11+## One generation at a time per model
12+
13+Requests for one model are served **one at a time, in arrival order**. The others wait in a queue of at most `limits.max_queue` requests; beyond it, the server answers 429 at once rather than letting clients pile up.
14+
15+Why not run several generations of one model at once? Token generation on Apple Silicon is mostly limited by memory bandwidth, so interleaving independent generations gains little: each answer arrives later, and each needs its own KV cache in memory. Batching several sequences in one forward pass is what would raise throughput, and razorbill does not do it (yet). A queue is simple, fair, and gives each client the full speed of the GPU when its turn comes.
16+
17+Different models do run in parallel: a chat answer and an embedding request use two different models, and therefore two different queues.
18+
19+## Making room
20+
21+Two limits decide how many models stay loaded:
22+
23+- `limits.max_loaded_models` (default 1): a count, easy to reason about.
24+- a memory budget of 75 % of the Mac's memory: the weights of the loaded models, read from the size of their `.safetensors` files, may not exceed it. The remaining quarter is for macOS, other applications, and the KV caches.
25+
26+When a model must be loaded and one of the limits would be exceeded, the manager unloads the **least recently used idle** model, then the next, until the new one fits. A model that is answering is never unloaded. If every loaded model is busy, the request gets a 503 `server_busy`; if the model is larger than the whole budget, a 503 `insufficient_memory`. Failing fast was preferred to waiting: the client can retry, or the operator can change the limits, whereas a silent wait looks like a hung server.
27+
28+## Unloading idle models
29+
30+A background service checks regularly (every quarter of `keep_alive`, at most every 30 seconds) and unloads models unused for `limits.keep_alive` (default 10 minutes). The next request loads the model again, which costs a few seconds for a small model. When the server stops (Ctrl-C, SIGTERM), every model is unloaded before the process exits.
31+
32+## When the client leaves
33+
34+A generation nobody will read wastes the GPU and delays everyone in the queue. The server therefore watches the connection while it answers: when the client disconnects, the generation task is cancelled, the model's turn is released, and the next request starts. A request still waiting in the queue is simply removed from it.
35+
36+During a stream, a client that vanishes is noticed only when a write fails. While the model is silent (loading, reading a long prompt, thinking with hidden reasoning), the server writes a `: keep-alive` comment every five seconds, so a departed client is noticed within seconds. Watching the connection requires reading the request to its end, which is why generation endpoints answer with `Connection: close`.
37+
38+## Rejected alternatives
39+
40+- **One process per model** (as some servers do): isolation, but every model would pay the runtime's memory, and sharing limits across processes needs a coordinator.
41+- **Unloading on a memory-pressure signal from macOS** instead of a budget: the signal arrives late, when swapping has already started; a budget is predictable.
42+- **Waiting for room instead of answering 503**: a request could wait indefinitely behind long generations; a clear error is easier to act on.
43+
44+## How it relates to the rest
45+
46+- The keys that set these limits: [configuration reference](../reference/configuration.md#limits).
47+- The errors a client sees: [errors reference](../reference/errors.md#codes).
48+- Where the manager sits in a request: [architecture](architecture.md#the-path-of-a-chat-request).
new file mode 100644
@@ -0,0 +1,48 @@
1+# Model lifecycle and concurrency — explanation
2+
3+## What is this about?
4+
5+A model is gigabytes of weights in the Mac's unified memory, and generating with it keeps the GPU busy. The server has to decide when to load a model, who may use it, what to do when several clients arrive at once, and when to give the memory back. All of that lives in one place, the **model manager** (`ModelManager`, an actor in `RazorbillServer`). This page explains its rules and why they were chosen.
6+
7+## One load, shared
8+
9+A model is loaded on the first request that needs it — or at start-up when it is declared with `preload: true` — and then shared by every request. Two names that point to the same repository (a declared `id` and its Hugging Face id, or two declared entries with different settings) share one load: the manager keys models by repository and revision, not by the name the client sent. A chat load and an embedding load of the same repository are different models, because they are loaded by different engines.
10+
11+## One generation at a time per model
12+
13+Requests for one model are served **one at a time, in arrival order**. The others wait in a queue of at most `limits.max_queue` requests; beyond it, the server answers 429 at once rather than letting clients pile up.
14+
15+Why not run several generations of one model at once? Token generation on Apple Silicon is mostly limited by memory bandwidth, so interleaving independent generations gains little: each answer arrives later, and each needs its own KV cache in memory. Batching several sequences in one forward pass is what would raise throughput, and razorbill does not do it (yet). A queue is simple, fair, and gives each client the full speed of the GPU when its turn comes.
16+
17+Different models do run in parallel: a chat answer and an embedding request use two different models, and therefore two different queues.
18+
19+## Making room
20+
21+Two limits decide how many models stay loaded:
22+
23+- `limits.max_loaded_models` (default 1): a count, easy to reason about.
24+- a memory budget of 75 % of the Mac's memory: the weights of the loaded models, read from the size of their `.safetensors` files, may not exceed it. The remaining quarter is for macOS, other applications, and the KV caches.
25+
26+When a model must be loaded and one of the limits would be exceeded, the manager unloads the **least recently used idle** model, then the next, until the new one fits. A model that is answering is never unloaded. If every loaded model is busy, the request gets a 503 `server_busy`; if the model is larger than the whole budget, a 503 `insufficient_memory`. Failing fast was preferred to waiting: the client can retry, or the operator can change the limits, whereas a silent wait looks like a hung server.
27+
28+## Unloading idle models
29+
30+A background service checks regularly (every quarter of `keep_alive`, at most every 30 seconds) and unloads models unused for `limits.keep_alive` (default 10 minutes). The next request loads the model again, which costs a few seconds for a small model. When the server stops (Ctrl-C, SIGTERM), every model is unloaded before the process exits.
31+
32+## When the client leaves
33+
34+A generation nobody will read wastes the GPU and delays everyone in the queue. The server therefore watches the connection while it answers: when the client disconnects, the generation task is cancelled, the model's turn is released, and the next request starts. A request still waiting in the queue is simply removed from it.
35+
36+During a stream, a client that vanishes is noticed only when a write fails. While the model is silent (loading, reading a long prompt, thinking with hidden reasoning), the server writes a `: keep-alive` comment every five seconds, so a departed client is noticed within seconds. Watching the connection requires reading the request to its end, which is why generation endpoints answer with `Connection: close`.
37+
38+## Rejected alternatives
39+
40+- **One process per model** (as some servers do): isolation, but every model would pay the runtime's memory, and sharing limits across processes needs a coordinator.
41+- **Unloading on a memory-pressure signal from macOS** instead of a budget: the signal arrives late, when swapping has already started; a budget is predictable.
42+- **Waiting for room instead of answering 503**: a request could wait indefinitely behind long generations; a clear error is easier to act on.
43+
44+## How it relates to the rest
45+
46+- The keys that set these limits: [configuration reference](../reference/configuration.md#limits).
47+- The errors a client sees: [errors reference](../reference/errors.md#codes).
48+- Where the manager sits in a request: [architecture](architecture.md#the-path-of-a-chat-request).
added docs/en/explanation/openai-compatibility.md +45 -0
new file mode 100644
@@ -0,0 +1,45 @@
1+# OpenAI compatibility — explanation
2+
3+## What is this about?
4+
5+"OpenAI-compatible" is a promise without a specification: OpenAI documents its own API, not what another server must do to be a substitute. Every local server draws the line somewhere. This page explains where razorbill draws it, and how that line is checked.
6+
7+## The goal: existing clients work unchanged
8+
9+The test is not "does the server accept the documented fields" but "does a program written for OpenAI work when its base URL is changed". That shifts attention to what clients actually do: the openai Python library's `parse()` with a Pydantic class, LangChain's `bind_tools` and `OpenAIEmbeddings`, streaming with `include_usage`, base64 embeddings (which the openai library requests by default, silently), error bodies that the libraries turn into typed exceptions.
10+
11+## Refuse rather than ignore
12+
13+When a request asks for something razorbill cannot do — several choices (`n`), log-probabilities, images, fill-in-the-middle, a schema keyword it cannot enforce, a forced tool call for an unsupported syntax — the server answers 400 and names the field. Ignoring the field would return an answer that looks right and is not what the client asked for: one choice instead of three, a schema rule silently broken. A clear error is found in the first test run; a silent difference is found in production.
14+
15+Fields that change nothing important are ignored, as OpenAI itself ignores unknown fields: `user`, `metadata`, `store`, `service_tier`…
16+
17+## Extensions, borrowed rather than invented
18+
19+Local models do things OpenAI's API has no field for, mostly around reasoning. Where another server already defined a convention, razorbill follows it, so clients that support it work without change:
20+
21+| Need | Field | Borrowed from |
22+| --- | --- | --- |
23+| Return the reasoning apart from the answer | `reasoning_content` (message and deltas) | DeepSeek, vLLM |
24+| Turn thinking on or off | `chat_template_kwargs.enable_thinking` | vLLM |
25+| Hide the reasoning | `include_reasoning: false` | OpenRouter |
26+| Count reasoning tokens | `usage.completion_tokens_details.reasoning_tokens` | OpenAI |
27+
28+Only `thinking_budget` is razorbill's own, because no common convention exists for a hard limit on reasoning tokens. `/v1/models` also adds `loaded` and `kind` to each model, which clients ignore.
29+
30+## Deliberate differences
31+
32+- **Defaults come from the server.** OpenAI's legacy completions default to 16 tokens; razorbill uses the server's configured `max_tokens`, because a local operator sets limits once for every client.
33+- **The prompt may change.** With `response_format`, the server adds an instruction carrying the schema to the system message (see [constrained decoding](constrained-decoding.md)). OpenAI's models are trained for structured output; local models need to be told.
34+- **Locked settings win.** An operator can impose `temperature` or cap `max_tokens` for every client, which OpenAI's API has no equivalent for.
35+
36+## How compatibility is checked
37+
38+Unit tests check the shapes; they cannot check that the real libraries agree with our reading of the shapes. A separate suite, `Tests/Compatibility`, drives a running `rzb serve` with the official clients — the `openai` library, LangChain, and every `curl` example of the API reference — and asserts what a user would see: a parsed Pydantic object, a tool round trip, cosine similarities equal to the Python `sentence-transformers` library's, typed exceptions on errors.
39+
40+It runs in two modes. On Linux, against the fake engine, it checks the protocol on every change. On the Mac, against MLX with real models, it checks behaviour; its first run found two real defects (schema keys sorted, and reasoning models writing prose into JSON fields), which unit tests had no way to see.
41+
42+## How it relates to the rest
43+
44+- What is supported, refused and ignored, field by field: [HTTP API reference](../reference/http-api.md).
45+- Running the suite: [run the tests](../how-to/run-the-tests.md#check-compatibility-with-real-openai-clients).
new file mode 100644
@@ -0,0 +1,45 @@
1+# OpenAI compatibility — explanation
2+
3+## What is this about?
4+
5+"OpenAI-compatible" is a promise without a specification: OpenAI documents its own API, not what another server must do to be a substitute. Every local server draws the line somewhere. This page explains where razorbill draws it, and how that line is checked.
6+
7+## The goal: existing clients work unchanged
8+
9+The test is not "does the server accept the documented fields" but "does a program written for OpenAI work when its base URL is changed". That shifts attention to what clients actually do: the openai Python library's `parse()` with a Pydantic class, LangChain's `bind_tools` and `OpenAIEmbeddings`, streaming with `include_usage`, base64 embeddings (which the openai library requests by default, silently), error bodies that the libraries turn into typed exceptions.
10+
11+## Refuse rather than ignore
12+
13+When a request asks for something razorbill cannot do — several choices (`n`), log-probabilities, images, fill-in-the-middle, a schema keyword it cannot enforce, a forced tool call for an unsupported syntax — the server answers 400 and names the field. Ignoring the field would return an answer that looks right and is not what the client asked for: one choice instead of three, a schema rule silently broken. A clear error is found in the first test run; a silent difference is found in production.
14+
15+Fields that change nothing important are ignored, as OpenAI itself ignores unknown fields: `user`, `metadata`, `store`, `service_tier`…
16+
17+## Extensions, borrowed rather than invented
18+
19+Local models do things OpenAI's API has no field for, mostly around reasoning. Where another server already defined a convention, razorbill follows it, so clients that support it work without change:
20+
21+| Need | Field | Borrowed from |
22+| --- | --- | --- |
23+| Return the reasoning apart from the answer | `reasoning_content` (message and deltas) | DeepSeek, vLLM |
24+| Turn thinking on or off | `chat_template_kwargs.enable_thinking` | vLLM |
25+| Hide the reasoning | `include_reasoning: false` | OpenRouter |
26+| Count reasoning tokens | `usage.completion_tokens_details.reasoning_tokens` | OpenAI |
27+
28+Only `thinking_budget` is razorbill's own, because no common convention exists for a hard limit on reasoning tokens. `/v1/models` also adds `loaded` and `kind` to each model, which clients ignore.
29+
30+## Deliberate differences
31+
32+- **Defaults come from the server.** OpenAI's legacy completions default to 16 tokens; razorbill uses the server's configured `max_tokens`, because a local operator sets limits once for every client.
33+- **The prompt may change.** With `response_format`, the server adds an instruction carrying the schema to the system message (see [constrained decoding](constrained-decoding.md)). OpenAI's models are trained for structured output; local models need to be told.
34+- **Locked settings win.** An operator can impose `temperature` or cap `max_tokens` for every client, which OpenAI's API has no equivalent for.
35+
36+## How compatibility is checked
37+
38+Unit tests check the shapes; they cannot check that the real libraries agree with our reading of the shapes. A separate suite, `Tests/Compatibility`, drives a running `rzb serve` with the official clients — the `openai` library, LangChain, and every `curl` example of the API reference — and asserts what a user would see: a parsed Pydantic object, a tool round trip, cosine similarities equal to the Python `sentence-transformers` library's, typed exceptions on errors.
39+
40+It runs in two modes. On Linux, against the fake engine, it checks the protocol on every change. On the Mac, against MLX with real models, it checks behaviour; its first run found two real defects (schema keys sorted, and reasoning models writing prose into JSON fields), which unit tests had no way to see.
41+
42+## How it relates to the rest
43+
44+- What is supported, refused and ignored, field by field: [HTTP API reference](../reference/http-api.md).
45+- Running the suite: [run the tests](../how-to/run-the-tests.md#check-compatibility-with-real-openai-clients).
modified docs/en/explanation/thinking.md +10 -11
@@ -1,16 +1,16 @@
1-# Thinking models — explanation
1+# Reasoning models — explanation
22
33 ## What is this about?
44
5-Some models (Qwen3, Qwen3.5, DeepSeek-R1…) write a chain of reasoning before their answer, between `<think>` and `</think>`. razorbill has to do three things with it: separate it from the answer, decide whether to show it, and, if asked, stop it before it eats the whole token budget. This page explains how, and why it is done that way.
5+Some models (Qwen3, Qwen3.5, DeepSeek-R1…) write a chain of reasoning before their answer, between `<think>` and `</think>`. razorbill has to do three things with it: separate it from the answer (OpenAI clients expect `content` to be the answer only), decide whether to send it, and, if asked, stop it before it eats the whole token budget. This page explains how, and why it is done that way.
66
77 ## Turning it on is the model's business
88
9-Whether a hybrid model thinks is decided by its **chat template**, the Jinja program shipped with the model that turns the conversation into the prompt. razorbill passes `enable_thinking` (from `generation.thinking`) to the template and lets it do the rest. Models that are not reasoning models simply ignore the flag.
9+Whether a hybrid model thinks is decided by its **chat template**, the Jinja program shipped with the model that turns the conversation into the prompt. razorbill passes `enable_thinking` to the template — from the request (`reasoning_effort`, `chat_template_kwargs.enable_thinking`) or else the configuration's `thinking` — and lets it do the rest. Models that are not reasoning models simply ignore the flag. Thinking is off unless a request or the configuration turns it on: most API clients expect fast, direct answers.
1010
1111 ## Separating reasoning from the answer
1212
13-The engine receives the output in small pieces, so a tag can arrive cut in two (`<thi` + `nk>`). The `ThinkingSplitter` keeps back any piece that could be the start of a tag until the next piece arrives, then emits *reasoning* events and *text* events. The front-ends only see those events, and the agent's transcript keeps the answer without the reasoning.
13+The engine receives the output in small pieces, so a tag can arrive cut in two (`<thi` + `nk>`). The `ThinkingSplitter` keeps back any piece that could be the start of a tag until the next piece arrives, then emits *reasoning* events and *text* events. The server turns them into `reasoning_content` and `content`, in whole answers and in stream deltas alike.
1414
1515 ### When the template opens the tag itself
1616
@@ -25,14 +25,11 @@ The model's output then starts inside the reasoning, and only `</think>` appears
2525
2626 Asking the template, rather than keeping a list of model names, means a new model with the same convention works without a change.
2727
28-## Showing it
28+## Sending it
2929
30-Reasoning is useful to understand an answer and noise in a script. So display is a separate setting from thinking (`ui.show_thinking`, default on):
30+Reasoning is useful to understand an answer and noise for a program. Sending it is therefore a separate setting from thinking: `include_reasoning: false` in a request, or `show_reasoning: false` in the configuration (in `locked`, for every client). The model still thinks; only `reasoning_content` is left out. `usage.completion_tokens_details.reasoning_tokens` still counts it, because those tokens took time and count in `max_tokens`.
3131
32-- in `run` and `chat` it goes to standard error, dimmed, so redirecting standard output keeps only the answer;
33-- in `tui` it is a block of its own that Ctrl-T shows or hides at any time.
34-
35-A model told not to think often still emits an empty `<think></think>`; empty reasoning is never displayed.
32+A model told not to think often still emits an empty `<think></think>`; empty reasoning is never sent.
3633
3734 ## Limiting it
3835
@@ -49,8 +46,10 @@ How to close the reasoning depends on the family:
4946 - **Detecting Qwen3.5 by its name**: fragile; the template is the source of truth.
5047 - **Cutting the text after `N` reasoning tokens and stopping generation**: the model would never get to answer.
5148 - **Raising `max_tokens` automatically when a budget is set**: hidden behaviour; the configuration check asks for a budget smaller than `max_tokens` instead.
49+- **Sending the reasoning inside `content`, between `<think>` tags**: some servers do; clients then show or parse the tags as part of the answer.
5250
5351 ## How it relates to the rest
5452
55-- The settings: [configure thinking](../how-to/configure-thinking.md) and the [agent file reference](../reference/configuration.md#generation).
53+- The settings: [control reasoning](../how-to/configure-thinking.md), the [HTTP API reference](../reference/http-api.md#request-fields) and the [configuration reference](../reference/configuration.md#defaults-and-locked).
54+- Reasoning before structured output: [constrained decoding](constrained-decoding.md).
5655 - Where the engine sits: [architecture](architecture.md).
@@ -1,16 +1,16 @@
1-# Thinking models — explanation1+# Reasoning models — explanation
2 2
3 ## What is this about?3 ## What is this about?
4 4
5-Some models (Qwen3, Qwen3.5, DeepSeek-R1…) write a chain of reasoning before their answer, between `<think>` and `</think>`. razorbill has to do three things with it: separate it from the answer, decide whether to show it, and, if asked, stop it before it eats the whole token budget. This page explains how, and why it is done that way.5+Some models (Qwen3, Qwen3.5, DeepSeek-R1…) write a chain of reasoning before their answer, between `<think>` and `</think>`. razorbill has to do three things with it: separate it from the answer (OpenAI clients expect `content` to be the answer only), decide whether to send it, and, if asked, stop it before it eats the whole token budget. This page explains how, and why it is done that way.
6 6
7 ## Turning it on is the model's business7 ## Turning it on is the model's business
8 8
9-Whether a hybrid model thinks is decided by its **chat template**, the Jinja program shipped with the model that turns the conversation into the prompt. razorbill passes `enable_thinking` (from `generation.thinking`) to the template and lets it do the rest. Models that are not reasoning models simply ignore the flag.9+Whether a hybrid model thinks is decided by its **chat template**, the Jinja program shipped with the model that turns the conversation into the prompt. razorbill passes `enable_thinking` to the template — from the request (`reasoning_effort`, `chat_template_kwargs.enable_thinking`) or else the configuration's `thinking` — and lets it do the rest. Models that are not reasoning models simply ignore the flag. Thinking is off unless a request or the configuration turns it on: most API clients expect fast, direct answers.
10 10
11 ## Separating reasoning from the answer11 ## Separating reasoning from the answer
12 12
13-The engine receives the output in small pieces, so a tag can arrive cut in two (`<thi` + `nk>`). The `ThinkingSplitter` keeps back any piece that could be the start of a tag until the next piece arrives, then emits *reasoning* events and *text* events. The front-ends only see those events, and the agent's transcript keeps the answer without the reasoning.13+The engine receives the output in small pieces, so a tag can arrive cut in two (`<thi` + `nk>`). The `ThinkingSplitter` keeps back any piece that could be the start of a tag until the next piece arrives, then emits *reasoning* events and *text* events. The server turns them into `reasoning_content` and `content`, in whole answers and in stream deltas alike.
14 14
15 ### When the template opens the tag itself15 ### When the template opens the tag itself
16 16
@@ -25,14 +25,11 @@ The model's output then starts inside the reasoning, and only `</think>` appears
25 25
26 Asking the template, rather than keeping a list of model names, means a new model with the same convention works without a change.26 Asking the template, rather than keeping a list of model names, means a new model with the same convention works without a change.
27 27
28-## Showing it28+## Sending it
29 29
30-Reasoning is useful to understand an answer and noise in a script. So display is a separate setting from thinking (`ui.show_thinking`, default on):30+Reasoning is useful to understand an answer and noise for a program. Sending it is therefore a separate setting from thinking: `include_reasoning: false` in a request, or `show_reasoning: false` in the configuration (in `locked`, for every client). The model still thinks; only `reasoning_content` is left out. `usage.completion_tokens_details.reasoning_tokens` still counts it, because those tokens took time and count in `max_tokens`.
31 31
32-- in `run` and `chat` it goes to standard error, dimmed, so redirecting standard output keeps only the answer;32+A model told not to think often still emits an empty `<think></think>`; empty reasoning is never sent.
33-- in `tui` it is a block of its own that Ctrl-T shows or hides at any time.
34-
35-A model told not to think often still emits an empty `<think></think>`; empty reasoning is never displayed.
36 33
37 ## Limiting it34 ## Limiting it
38 35
@@ -49,8 +46,10 @@ How to close the reasoning depends on the family:
49 - **Detecting Qwen3.5 by its name**: fragile; the template is the source of truth.46 - **Detecting Qwen3.5 by its name**: fragile; the template is the source of truth.
50 - **Cutting the text after `N` reasoning tokens and stopping generation**: the model would never get to answer.47 - **Cutting the text after `N` reasoning tokens and stopping generation**: the model would never get to answer.
51 - **Raising `max_tokens` automatically when a budget is set**: hidden behaviour; the configuration check asks for a budget smaller than `max_tokens` instead.48 - **Raising `max_tokens` automatically when a budget is set**: hidden behaviour; the configuration check asks for a budget smaller than `max_tokens` instead.
49+- **Sending the reasoning inside `content`, between `<think>` tags**: some servers do; clients then show or parse the tags as part of the answer.
52 50
53 ## How it relates to the rest51 ## How it relates to the rest
54 52
55-- The settings: [configure thinking](../how-to/configure-thinking.md) and the [agent file reference](../reference/configuration.md#generation).53+- The settings: [control reasoning](../how-to/configure-thinking.md), the [HTTP API reference](../reference/http-api.md#request-fields) and the [configuration reference](../reference/configuration.md#defaults-and-locked).
54+- Reasoning before structured output: [constrained decoding](constrained-decoding.md).
56 - Where the engine sits: [architecture](architecture.md).55 - Where the engine sits: [architecture](architecture.md).
deleted docs/en/explanation/tool-safety.md +0 -41
deleted file mode 100644
@@ -1,41 +0,0 @@
1-# Tool safety — explanation
2-
3-## What is this about?
4-
5-With the `bash` tool, a language model runs commands on your Mac with your rights. This page explains what razorbill does to keep that under control, what it does **not** protect against, and where the project is heading.
6-
7-## Why rzb cannot simply be sandboxed
8-
9-The usual answer to "an agent runs commands" is to run the agent in a container. razorbill cannot: it needs Metal and the GPU, which exist only on macOS, outside a Linux container. So `rzb` runs on the host, and so do the commands of its `bash` tool.
10-
11-## What v0.1 does
12-
13-Guards, from the strongest to the weakest:
14-
15-1. **Off by default.** No tool exists unless the agent file lists it.
16-2. **Confirmation by default.** With `confirm: true` (the default), you see each command and its directory and must answer `y`. Without a terminal, such commands are refused: an unattended run never executes something nobody approved, unless `confirm: false` is written explicitly in the file.
17-3. **Limits.** Each command is killed, with every process it started (its process group), after `timeout`; output is capped at `max_output` so a command cannot flood the model's context.
18-4. **Patterns.** `deny` patterns always win, then `allow` patterns must match.
19-
20-Refusals are sent to the model as results, in plain words, so it can adapt rather than fail.
21-
22-## What it does not protect against
23-
24-- **Patterns are not a sandbox.** They match text, not intent. `ls*` also matches `ls; rm -rf ~`; `deny: ["rm *"]` does not stop `find . -delete`, a script, or `python -c …`. Use `allow` lists for convenience, and keep `confirm: true` for safety.
25-- **Confirmation depends on you.** A long or obfuscated command can be approved by mistake.
26-- **Secrets are visible.** Commands inherit the whole environment of `rzb`: the model can read tokens with `env` or `echo $TOKEN`, and the output returns into its context. A system prompt with `{{env.NAME}}` puts the value itself into the prompt.
27-- **Prompt injection.** A file or web page read by a command can contain instructions aimed at the model. The model may follow them; only the guards above stand in the way.
28-
29-## Where it is heading
30-
31-These are open design tickets, not features:
32-
33-- **Secrets** (ticket #21): hide a list of variables, or all of them, from the model, while tools can still use them by name; redact their values in outputs.
34-- **A sandboxed shell** (ticket #22): keep the model on the Mac and send only command execution to a container, a VM or an `sbx` sandbox; plus explicit switches to disable built-in tools (`enabled: false`, `--no-tools`).
35-- **WebAssembly** (ticket #23): run tools as WASM modules inside `rzb`, with only the files and network access the configuration grants.
36-- **Guards for small models** (ticket #27): detect loops (the same command again and again) and stop or redirect the model.
37-
38-## How it relates to the rest
39-
40-- How to configure the tool: [use the bash tool](../how-to/use-the-bash-tool.md) and the [bash tool reference](../reference/bash-tool.md).
41-- How a tool call travels through the agent: [architecture](architecture.md#the-agent-loop).
deleted file mode 100644
@@ -1,41 +0,0 @@
1-# Tool safety — explanation
2-
3-## What is this about?
4-
5-With the `bash` tool, a language model runs commands on your Mac with your rights. This page explains what razorbill does to keep that under control, what it does **not** protect against, and where the project is heading.
6-
7-## Why rzb cannot simply be sandboxed
8-
9-The usual answer to "an agent runs commands" is to run the agent in a container. razorbill cannot: it needs Metal and the GPU, which exist only on macOS, outside a Linux container. So `rzb` runs on the host, and so do the commands of its `bash` tool.
10-
11-## What v0.1 does
12-
13-Guards, from the strongest to the weakest:
14-
15-1. **Off by default.** No tool exists unless the agent file lists it.
16-2. **Confirmation by default.** With `confirm: true` (the default), you see each command and its directory and must answer `y`. Without a terminal, such commands are refused: an unattended run never executes something nobody approved, unless `confirm: false` is written explicitly in the file.
17-3. **Limits.** Each command is killed, with every process it started (its process group), after `timeout`; output is capped at `max_output` so a command cannot flood the model's context.
18-4. **Patterns.** `deny` patterns always win, then `allow` patterns must match.
19-
20-Refusals are sent to the model as results, in plain words, so it can adapt rather than fail.
21-
22-## What it does not protect against
23-
24-- **Patterns are not a sandbox.** They match text, not intent. `ls*` also matches `ls; rm -rf ~`; `deny: ["rm *"]` does not stop `find . -delete`, a script, or `python -c …`. Use `allow` lists for convenience, and keep `confirm: true` for safety.
25-- **Confirmation depends on you.** A long or obfuscated command can be approved by mistake.
26-- **Secrets are visible.** Commands inherit the whole environment of `rzb`: the model can read tokens with `env` or `echo $TOKEN`, and the output returns into its context. A system prompt with `{{env.NAME}}` puts the value itself into the prompt.
27-- **Prompt injection.** A file or web page read by a command can contain instructions aimed at the model. The model may follow them; only the guards above stand in the way.
28-
29-## Where it is heading
30-
31-These are open design tickets, not features:
32-
33-- **Secrets** (ticket #21): hide a list of variables, or all of them, from the model, while tools can still use them by name; redact their values in outputs.
34-- **A sandboxed shell** (ticket #22): keep the model on the Mac and send only command execution to a container, a VM or an `sbx` sandbox; plus explicit switches to disable built-in tools (`enabled: false`, `--no-tools`).
35-- **WebAssembly** (ticket #23): run tools as WASM modules inside `rzb`, with only the files and network access the configuration grants.
36-- **Guards for small models** (ticket #27): detect loops (the same command again and again) and stop or redirect the model.
37-
38-## How it relates to the rest
39-
40-- How to configure the tool: [use the bash tool](../how-to/use-the-bash-tool.md) and the [bash tool reference](../reference/bash-tool.md).
41-- How a tool call travels through the agent: [architecture](architecture.md#the-agent-loop).
deleted docs/en/how-to/add-a-tool.md +0 -108
deleted file mode 100644
@@ -1,108 +0,0 @@
1-# How to add a tool
2-
3-This guide adds a built-in tool that agents can enable in their YAML file. It assumes you can build and test razorbill and know Swift. The example is `clock`, a tool that returns the current date and time in a given time zone.
4-
5-## 1. Write the tool
6-
7-Create `Sources/RazorbillCore/Tools/ClockTool.swift`. A tool is a type that conforms to `AgentTool`: a `spec` the model reads (name, description, JSON Schema of the arguments) and a `call` that runs it.
8-
9-```swift
10-import Foundation
11-
12-/// Built-in tool `clock`: the current date and time.
13-///
14-/// ```yaml
15-/// tools:
16-/// clock:
17-/// time_zone: Europe/Paris
18-/// ```
19-public struct ClockTool: AgentTool {
20- public static let name = "clock"
21-
22- public let defaultTimeZone: TimeZone
23-
24- public let spec = ToolSpec(
25- name: ClockTool.name,
26- description: "Return the current date and time (ISO 8601). Optionally in another time zone.",
27- parameters: .map([
28- "type": .string("object"),
29- "properties": .map([
30- "time_zone": .map([
31- "type": .string("string"),
32- "description": .string("IANA time zone, e.g. Asia/Tokyo"),
33- ])
34- ]),
35- ])
36- )
37-
38- /// Builds the tool from its YAML options.
39- public init(options: ConfigValue, environment: ToolEnvironment) throws {
40- let reader = OptionReader(options)
41- try reader.rejectUnknownKeys(["time_zone"])
42- let identifier = try reader.string("time_zone", default: TimeZone.current.identifier)
43- guard let zone = TimeZone(identifier: identifier) else {
44- throw ToolOptionError(key: "time_zone", message: "unknown time zone \(identifier)")
45- }
46- defaultTimeZone = zone
47- }
48-
49- public func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput {
50- var zone = defaultTimeZone
51- if let identifier = arguments["time_zone"]?.stringValue {
52- guard let requested = TimeZone(identifier: identifier) else {
53- return ToolOutput("unknown time zone \(identifier)", isError: true)
54- }
55- zone = requested
56- }
57- let formatter = ISO8601DateFormatter()
58- formatter.timeZone = zone
59- return ToolOutput(formatter.string(from: Date()))
60- }
61-}
62-```
63-
64-Rules that keep tools predictable:
65-
66-- Read options with `OptionReader` and reject unknown keys: typos then become configuration errors with their key path (`tools.clock.time_zne`).
67-- Throw `ToolOptionError` for a bad option, at load time. At call time, return `ToolOutput(…, isError: true)` for a bad argument: the model reads it and can correct itself.
68-- Ask before doing anything the user should approve, with `context.confirm(…)`, and refuse when `context.isInteractive` is false (see `BashTool`).
69-- Text sent to the model must not depend on the user's locale.
70-
71-## 2. Register it
72-
73-In `ToolRegistry.builtIn` (`Sources/RazorbillCore/Tools/ToolRegistry.swift`), add one line:
74-
75-```swift
76-registry.register(ClockTool.name, factory: ClockTool.init(options:environment:))
77-```
78-
79-`rzb init` now offers it, `rzb config validate` accepts it, and an agent enables it with:
80-
81-```yaml
82-tools:
83- clock:
84- time_zone: Europe/Paris
85-```
86-
87-## 3. Test it
88-
89-Add `Tests/RazorbillCoreTests/ClockToolTests.swift` with Swift Testing: options accepted and rejected, a valid call, an invalid argument. To test the whole loop without a model, script a `FakeEngine` turn that calls the tool:
90-
91-```swift
92-let engine = FakeEngine(script: [
93- [.toolCall(ToolCall(name: "clock", arguments: ["time_zone": .string("UTC")]))],
94- [.text("done")],
95-])
96-```
97-
98-Then run [the tests](run-the-tests.md).
99-
100-## Variants
101-
102-- **A tool only for one front-end or one build**: register it on the registry passed to `CLIEnvironment` instead of in `builtIn`.
103-- **A tool with side effects**: follow `BashTool` — `confirm` option, refusal without a terminal, timeouts, output limits.
104-
105-## See also
106-
107-- The `tools` key: [agent file reference](../reference/configuration.md#tools).
108-- How tools fit in the agent loop: [architecture](../explanation/architecture.md#the-agent-loop).
deleted file mode 100644
@@ -1,108 +0,0 @@
1-# How to add a tool
2-
3-This guide adds a built-in tool that agents can enable in their YAML file. It assumes you can build and test razorbill and know Swift. The example is `clock`, a tool that returns the current date and time in a given time zone.
4-
5-## 1. Write the tool
6-
7-Create `Sources/RazorbillCore/Tools/ClockTool.swift`. A tool is a type that conforms to `AgentTool`: a `spec` the model reads (name, description, JSON Schema of the arguments) and a `call` that runs it.
8-
9-```swift
10-import Foundation
11-
12-/// Built-in tool `clock`: the current date and time.
13-///
14-/// ```yaml
15-/// tools:
16-/// clock:
17-/// time_zone: Europe/Paris
18-/// ```
19-public struct ClockTool: AgentTool {
20- public static let name = "clock"
21-
22- public let defaultTimeZone: TimeZone
23-
24- public let spec = ToolSpec(
25- name: ClockTool.name,
26- description: "Return the current date and time (ISO 8601). Optionally in another time zone.",
27- parameters: .map([
28- "type": .string("object"),
29- "properties": .map([
30- "time_zone": .map([
31- "type": .string("string"),
32- "description": .string("IANA time zone, e.g. Asia/Tokyo"),
33- ])
34- ]),
35- ])
36- )
37-
38- /// Builds the tool from its YAML options.
39- public init(options: ConfigValue, environment: ToolEnvironment) throws {
40- let reader = OptionReader(options)
41- try reader.rejectUnknownKeys(["time_zone"])
42- let identifier = try reader.string("time_zone", default: TimeZone.current.identifier)
43- guard let zone = TimeZone(identifier: identifier) else {
44- throw ToolOptionError(key: "time_zone", message: "unknown time zone \(identifier)")
45- }
46- defaultTimeZone = zone
47- }
48-
49- public func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput {
50- var zone = defaultTimeZone
51- if let identifier = arguments["time_zone"]?.stringValue {
52- guard let requested = TimeZone(identifier: identifier) else {
53- return ToolOutput("unknown time zone \(identifier)", isError: true)
54- }
55- zone = requested
56- }
57- let formatter = ISO8601DateFormatter()
58- formatter.timeZone = zone
59- return ToolOutput(formatter.string(from: Date()))
60- }
61-}
62-```
63-
64-Rules that keep tools predictable:
65-
66-- Read options with `OptionReader` and reject unknown keys: typos then become configuration errors with their key path (`tools.clock.time_zne`).
67-- Throw `ToolOptionError` for a bad option, at load time. At call time, return `ToolOutput(…, isError: true)` for a bad argument: the model reads it and can correct itself.
68-- Ask before doing anything the user should approve, with `context.confirm(…)`, and refuse when `context.isInteractive` is false (see `BashTool`).
69-- Text sent to the model must not depend on the user's locale.
70-
71-## 2. Register it
72-
73-In `ToolRegistry.builtIn` (`Sources/RazorbillCore/Tools/ToolRegistry.swift`), add one line:
74-
75-```swift
76-registry.register(ClockTool.name, factory: ClockTool.init(options:environment:))
77-```
78-
79-`rzb init` now offers it, `rzb config validate` accepts it, and an agent enables it with:
80-
81-```yaml
82-tools:
83- clock:
84- time_zone: Europe/Paris
85-```
86-
87-## 3. Test it
88-
89-Add `Tests/RazorbillCoreTests/ClockToolTests.swift` with Swift Testing: options accepted and rejected, a valid call, an invalid argument. To test the whole loop without a model, script a `FakeEngine` turn that calls the tool:
90-
91-```swift
92-let engine = FakeEngine(script: [
93- [.toolCall(ToolCall(name: "clock", arguments: ["time_zone": .string("UTC")]))],
94- [.text("done")],
95-])
96-```
97-
98-Then run [the tests](run-the-tests.md).
99-
100-## Variants
101-
102-- **A tool only for one front-end or one build**: register it on the registry passed to `CLIEnvironment` instead of in `builtIn`.
103-- **A tool with side effects**: follow `BashTool` — `confirm` option, refusal without a terminal, timeouts, output limits.
104-
105-## See also
106-
107-- The `tools` key: [agent file reference](../reference/configuration.md#tools).
108-- How tools fit in the agent loop: [architecture](../explanation/architecture.md#the-agent-loop).
modified docs/en/how-to/build-on-the-mac.md +1 -1
@@ -1,6 +1,6 @@
11 # How to build rzb on the Mac
22
3-This guide builds the `rzb` executable from the sources. It assumes a Mac with Apple Silicon and the repository cloned.
3+This guide builds the `rzb` executable, the server, from the sources. It assumes a Mac with Apple Silicon and the repository cloned.
44
55 ## Prerequisites
66
@@ -1,6 +1,6 @@
1 # How to build rzb on the Mac1 # How to build rzb on the Mac
2 2
3-This guide builds the `rzb` executable from the sources. It assumes a Mac with Apple Silicon and the repository cloned.3+This guide builds the `rzb` executable, the server, from the sources. It assumes a Mac with Apple Silicon and the repository cloned.
4 4
5 ## Prerequisites5 ## Prerequisites
6 6
added docs/en/how-to/compute-embeddings.md +47 -0
new file mode 100644
@@ -0,0 +1,47 @@
1+# How to compute embeddings
2+
3+This guide turns texts into vectors for semantic search, clustering or RAG. It assumes `rzb serve` is running.
4+
5+## 1. Get an embedding model
6+
7+```bash
8+rzb models pull BAAI/bge-small-en-v1.5
9+```
10+
11+Models known to work: `BAAI/bge-small-en-v1.5` and `sentence-transformers/all-MiniLM-L6-v2` (384 dimensions; their vectors match the Python `sentence-transformers` library within 1e-3). Other BERT-family and Qwen3-Embedding models supported by mlx-swift-lm's embedders should work too.
12+
13+## 2. Declare it (recommended)
14+
15+```yaml
16+models:
17+ - id: embed
18+ source: BAAI/bge-small-en-v1.5
19+ kind: embedding
20+```
21+
22+Declared, it is listed as `"kind": "embedding"` by `/v1/models`, and a chat request to it is refused clearly. An undeclared Hugging Face id also works on `/v1/embeddings`.
23+
24+## 3. Ask for vectors
25+
26+```python
27+from openai import OpenAI
28+
29+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
30+result = client.embeddings.create(model="embed", input=["The cat sits on the mat.", "A feline rests on a rug."])
31+vectors = [item.embedding for item in result.data]
32+```
33+
34+Vectors are normalised: their dot product is their cosine similarity.
35+
36+## Variants
37+
38+- **Shorter vectors**: `dimensions=256` keeps the first 256 values and renormalises them. Meaningful for Matryoshka models (Qwen3-Embedding, nomic…); for others it loses quality.
39+- **Smaller responses**: `encoding_format="base64"` (the openai library asks for it by default and decodes it for you).
40+- **LangChain**: `OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="embed", check_embedding_ctx_length=False)`. Without `check_embedding_ctx_length=False`, LangChain sends token arrays, which the server refuses.
41+- **Long texts**: a text longer than the model accepts (512 tokens for bge-small) is a 400 naming it. Split your documents first.
42+- **Query prefixes**: models that expect a prefix (`query: `, `search_query: `, an instruction) need it in your text; the server adds nothing.
43+- **Chat and embeddings together**: set `limits.max_loaded_models: 2` so the two models stay loaded.
44+
45+## See also
46+
47+- Every field of `/v1/embeddings`: [HTTP API reference](../reference/http-api.md#post-v1embeddings).
new file mode 100644
@@ -0,0 +1,47 @@
1+# How to compute embeddings
2+
3+This guide turns texts into vectors for semantic search, clustering or RAG. It assumes `rzb serve` is running.
4+
5+## 1. Get an embedding model
6+
7+```bash
8+rzb models pull BAAI/bge-small-en-v1.5
9+```
10+
11+Models known to work: `BAAI/bge-small-en-v1.5` and `sentence-transformers/all-MiniLM-L6-v2` (384 dimensions; their vectors match the Python `sentence-transformers` library within 1e-3). Other BERT-family and Qwen3-Embedding models supported by mlx-swift-lm's embedders should work too.
12+
13+## 2. Declare it (recommended)
14+
15+```yaml
16+models:
17+ - id: embed
18+ source: BAAI/bge-small-en-v1.5
19+ kind: embedding
20+```
21+
22+Declared, it is listed as `"kind": "embedding"` by `/v1/models`, and a chat request to it is refused clearly. An undeclared Hugging Face id also works on `/v1/embeddings`.
23+
24+## 3. Ask for vectors
25+
26+```python
27+from openai import OpenAI
28+
29+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
30+result = client.embeddings.create(model="embed", input=["The cat sits on the mat.", "A feline rests on a rug."])
31+vectors = [item.embedding for item in result.data]
32+```
33+
34+Vectors are normalised: their dot product is their cosine similarity.
35+
36+## Variants
37+
38+- **Shorter vectors**: `dimensions=256` keeps the first 256 values and renormalises them. Meaningful for Matryoshka models (Qwen3-Embedding, nomic…); for others it loses quality.
39+- **Smaller responses**: `encoding_format="base64"` (the openai library asks for it by default and decodes it for you).
40+- **LangChain**: `OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="embed", check_embedding_ctx_length=False)`. Without `check_embedding_ctx_length=False`, LangChain sends token arrays, which the server refuses.
41+- **Long texts**: a text longer than the model accepts (512 tokens for bge-small) is a 400 naming it. Split your documents first.
42+- **Query prefixes**: models that expect a prefix (`query: `, `search_query: `, an instruction) need it in your text; the server adds nothing.
43+- **Chat and embeddings together**: set `limits.max_loaded_models: 2` so the two models stay loaded.
44+
45+## See also
46+
47+- Every field of `/v1/embeddings`: [HTTP API reference](../reference/http-api.md#post-v1embeddings).
added docs/en/how-to/configure-the-server.md +118 -0
new file mode 100644
@@ -0,0 +1,118 @@
1+# How to configure the server
2+
3+This guide writes a configuration file for `rzb serve`: short model names, generation defaults and locks, memory limits, and network access. It assumes you have started the server once (see the [tutorial](../tutorials/getting-started.md)).
4+
5+## 1. Write the file
6+
7+Start from the commented example:
8+
9+```bash
10+cp examples/server.yaml server.yaml
11+```
12+
13+Or write a minimal one:
14+
15+```yaml
16+models:
17+ - id: qwen3
18+ source: mlx-community/Qwen3-4B-4bit
19+ - id: embed
20+ source: BAAI/bge-small-en-v1.5
21+ kind: embedding
22+```
23+
24+Clients now send `"model": "qwen3"` instead of the Hugging Face id. Undeclared Hugging Face ids keep working.
25+
26+## 2. Check it, then use it
27+
28+```bash
29+rzb config validate server.yaml
30+rzb serve --config server.yaml
31+```
32+
33+`config validate` lists every problem with its line number; fix them and run it again.
34+
35+## Set defaults clients may change
36+
37+```yaml
38+defaults:
39+ temperature: 0.3
40+ max_tokens: 2048
41+```
42+
43+A request that sends `temperature` uses its own value; one that does not gets `0.3`.
44+
45+## Lock settings clients may not change
46+
47+```yaml
48+locked:
49+ max_tokens: 4096 # a ceiling: requests asking for more get 4096
50+ show_reasoning: false # never send the reasoning to clients
51+```
52+
53+`temperature`, `top_p`, `thinking` and `show_reasoning` are imposed; `max_tokens` and `thinking_budget` are ceilings.
54+
55+## Settings for one model only
56+
57+```yaml
58+models:
59+ - id: qwen3-thinking
60+ source: mlx-community/Qwen3-4B-4bit
61+ defaults: { thinking: true, thinking_budget: 512 }
62+ locked: { max_tokens: 8192 }
63+```
64+
65+The model's blocks apply after the top-level ones. Two entries may use the same `source` with different settings; they share one load.
66+
67+## Load a model at start-up
68+
69+```yaml
70+models:
71+ - id: embed
72+ source: BAAI/bge-small-en-v1.5
73+ kind: embedding
74+ preload: true
75+```
76+
77+The server then answers the first request without the loading delay.
78+
79+## Keep several models in memory
80+
81+```yaml
82+limits:
83+ max_loaded_models: 2 # e.g. one chat model and one embedding model
84+ keep_alive: 30m # unload a model idle for 30 minutes
85+ max_queue: 32 # requests waiting per model before a 429
86+```
87+
88+## Use a model from a local directory
89+
90+```yaml
91+models:
92+ - id: mine
93+ path: ~/models/my-mlx-model # config.json, tokenizer files, *.safetensors
94+```
95+
96+## Open the server to your network
97+
98+Set a key in the environment, then listen on every interface:
99+
100+```bash
101+export RZB_API_KEY="$(openssl rand -hex 24)"
102+rzb serve --config server.yaml --host 0.0.0.0
103+```
104+
105+Clients send `Authorization: Bearer <key>` (the `api_key` of OpenAI clients). To read the key from another variable, use `--api-key-env MY_VAR` or `server.api_key_env: MY_VAR`. The key never goes in the file.
106+
107+## Let a web page call the API
108+
109+```bash
110+rzb serve --config server.yaml --cors-origin http://localhost:3000
111+```
112+
113+Use `*` for any origin only with an API key: otherwise any page you open can use your models.
114+
115+## See also
116+
117+- Every key, type and default: [configuration reference](../reference/configuration.md).
118+- How models are loaded, queued and unloaded: [model lifecycle](../explanation/model-lifecycle.md).
new file mode 100644
@@ -0,0 +1,118 @@
1+# How to configure the server
2+
3+This guide writes a configuration file for `rzb serve`: short model names, generation defaults and locks, memory limits, and network access. It assumes you have started the server once (see the [tutorial](../tutorials/getting-started.md)).
4+
5+## 1. Write the file
6+
7+Start from the commented example:
8+
9+```bash
10+cp examples/server.yaml server.yaml
11+```
12+
13+Or write a minimal one:
14+
15+```yaml
16+models:
17+ - id: qwen3
18+ source: mlx-community/Qwen3-4B-4bit
19+ - id: embed
20+ source: BAAI/bge-small-en-v1.5
21+ kind: embedding
22+```
23+
24+Clients now send `"model": "qwen3"` instead of the Hugging Face id. Undeclared Hugging Face ids keep working.
25+
26+## 2. Check it, then use it
27+
28+```bash
29+rzb config validate server.yaml
30+rzb serve --config server.yaml
31+```
32+
33+`config validate` lists every problem with its line number; fix them and run it again.
34+
35+## Set defaults clients may change
36+
37+```yaml
38+defaults:
39+ temperature: 0.3
40+ max_tokens: 2048
41+```
42+
43+A request that sends `temperature` uses its own value; one that does not gets `0.3`.
44+
45+## Lock settings clients may not change
46+
47+```yaml
48+locked:
49+ max_tokens: 4096 # a ceiling: requests asking for more get 4096
50+ show_reasoning: false # never send the reasoning to clients
51+```
52+
53+`temperature`, `top_p`, `thinking` and `show_reasoning` are imposed; `max_tokens` and `thinking_budget` are ceilings.
54+
55+## Settings for one model only
56+
57+```yaml
58+models:
59+ - id: qwen3-thinking
60+ source: mlx-community/Qwen3-4B-4bit
61+ defaults: { thinking: true, thinking_budget: 512 }
62+ locked: { max_tokens: 8192 }
63+```
64+
65+The model's blocks apply after the top-level ones. Two entries may use the same `source` with different settings; they share one load.
66+
67+## Load a model at start-up
68+
69+```yaml
70+models:
71+ - id: embed
72+ source: BAAI/bge-small-en-v1.5
73+ kind: embedding
74+ preload: true
75+```
76+
77+The server then answers the first request without the loading delay.
78+
79+## Keep several models in memory
80+
81+```yaml
82+limits:
83+ max_loaded_models: 2 # e.g. one chat model and one embedding model
84+ keep_alive: 30m # unload a model idle for 30 minutes
85+ max_queue: 32 # requests waiting per model before a 429
86+```
87+
88+## Use a model from a local directory
89+
90+```yaml
91+models:
92+ - id: mine
93+ path: ~/models/my-mlx-model # config.json, tokenizer files, *.safetensors
94+```
95+
96+## Open the server to your network
97+
98+Set a key in the environment, then listen on every interface:
99+
100+```bash
101+export RZB_API_KEY="$(openssl rand -hex 24)"
102+rzb serve --config server.yaml --host 0.0.0.0
103+```
104+
105+Clients send `Authorization: Bearer <key>` (the `api_key` of OpenAI clients). To read the key from another variable, use `--api-key-env MY_VAR` or `server.api_key_env: MY_VAR`. The key never goes in the file.
106+
107+## Let a web page call the API
108+
109+```bash
110+rzb serve --config server.yaml --cors-origin http://localhost:3000
111+```
112+
113+Use `*` for any origin only with an API key: otherwise any page you open can use your models.
114+
115+## See also
116+
117+- Every key, type and default: [configuration reference](../reference/configuration.md).
118+- How models are loaded, queued and unloaded: [model lifecycle](../explanation/model-lifecycle.md).
modified docs/en/how-to/configure-thinking.md +46 -26
@@ -1,49 +1,69 @@
1-# How to configure thinking
1+# How to control reasoning
22
3-Reasoning models (Qwen3, Qwen3.5…) can think before they answer. This guide shows how to turn thinking on, choose whether you see it, and limit how long it lasts.
3+This guide turns the reasoning of thinking models (Qwen3, Qwen3.5, DeepSeek-R1…) on or off, limits it, and decides whether clients see it. It assumes a server running with a reasoning model, e.g. `mlx-community/Qwen3-4B-4bit`.
44
5-## Turn thinking on
5+## Turn it on or off for one request
66
7-In the agent file:
7+Send one of these fields (with the openai library, in `extra_body`):
88
9-```yaml
10-generation:
11- thinking: true
9+| Field | Thinking |
10+| --- | --- |
11+| `"reasoning_effort": "low"`, `"medium"` or `"high"` | on |
12+| `"reasoning_effort": "none"` or `"minimal"` | off |
13+| `"chat_template_kwargs": {"enable_thinking": true}` | on (wins over `reasoning_effort`) |
14+
15+```python
16+answer = client.chat.completions.create(
17+ model="mlx-community/Qwen3-4B-4bit",
18+ messages=[{"role": "user", "content": "Is 391 a prime number?"}],
19+ extra_body={"reasoning_effort": "high"},
20+)
21+print(answer.choices[0].message.reasoning_content) # the reasoning
22+print(answer.choices[0].message.content) # the answer only
1223 ```
1324
14-Or for one run: `rzb chat --think` (and `--no-think` to turn it off when the file turns it on).
25+`low`, `medium` and `high` behave the same: the model either thinks or not.
1526
16-## Show or hide the reasoning
27+## Turn it on by default
1728
1829 ```yaml
19-ui:
20- show_thinking: false # default true
30+defaults:
31+ thinking: true # every model…
32+models:
33+ - id: fast
34+ source: mlx-community/Qwen3-4B-4bit
35+ defaults: { thinking: false } # …except this one
2136 ```
2237
23-- `rzb run` and `rzb chat` print the reasoning dimmed on standard error, so `rzb run … > answer.txt` never keeps it.
24-- `rzb tui` starts with the reasoning shown or hidden as set here; **Ctrl-T** toggles it at any time.
38+Without configuration, models do not think unless a request asks for it.
39+
40+## Limit how long it thinks
2541
26-## Limit the thinking
42+Per request: `"thinking_budget": 256` (a razorbill extension). In the configuration:
2743
2844 ```yaml
29-generation:
30- max_tokens: 2048
31- thinking: true
32- thinking_budget: 512 # at most 512 tokens of reasoning, then the model answers
45+defaults:
46+ thinking_budget: 512
47+locked:
48+ thinking_budget: 2048 # a ceiling clients cannot exceed
3349 ```
3450
35-Or for one run: `rzb chat --think --thinking-budget 200`.
51+When the budget is spent, the model is made to close its reasoning and answer. The reasoning counts in `max_tokens`: keep `max_tokens` well above the budget. Models with no known reasoning protocol (Llama, Gemma) refuse a budget with a 400.
52+
53+## Hide the reasoning from clients
54+
55+- One request: `"include_reasoning": false`.
56+- Always: `locked: { show_reasoning: false }` in the configuration.
3657
37-- `0` makes the model answer at once.
38-- The reasoning counts inside `max_tokens`: the budget must be smaller, and should leave room for the answer.
39-- The budget only applies when `thinking` is on.
58+The model still thinks; `reasoning_content` is left out, and `usage.completion_tokens_details.reasoning_tokens` still counts it.
4059
4160 ## Variants
4261
43-- **A model that is not a reasoning model** (Llama, Gemma): `thinking` has no effect, and `thinking_budget` stops the agent with `… has no known thinking protocol: remove generation.thinking_budget`. Remove the budget for these models.
44-- **Answers cut short**: raise `max_tokens`, or lower `thinking_budget`.
62+- **Streaming**: the reasoning arrives in `delta.reasoning_content` before the answer's `delta.content`.
63+- **Clients that only read `content`** see the answer without the reasoning, which is what most chat UIs expect.
64+- **Structured output or tool calls**: the model thinks freely, then the constraint applies to the answer.
4565
4666 ## See also
4767
48-- The keys: [agent file reference](../reference/configuration.md#generation) and [`ui`](../reference/configuration.md#ui).
49-- How thinking is detected, shown and limited: [thinking models](../explanation/thinking.md).
68+- The fields: [HTTP API reference](../reference/http-api.md#request-fields) and [configuration reference](../reference/configuration.md#defaults-and-locked).
69+- How reasoning is separated and limited: [reasoning models](../explanation/thinking.md).
@@ -1,49 +1,69 @@
1-# How to configure thinking1+# How to control reasoning
2 2
3-Reasoning models (Qwen3, Qwen3.5…) can think before they answer. This guide shows how to turn thinking on, choose whether you see it, and limit how long it lasts.3+This guide turns the reasoning of thinking models (Qwen3, Qwen3.5, DeepSeek-R1…) on or off, limits it, and decides whether clients see it. It assumes a server running with a reasoning model, e.g. `mlx-community/Qwen3-4B-4bit`.
4 4
5-## Turn thinking on5+## Turn it on or off for one request
6 6
7-In the agent file:7+Send one of these fields (with the openai library, in `extra_body`):
8 8
9-```yaml9+| Field | Thinking |
10-generation:10+| --- | --- |
11- thinking: true11+| `"reasoning_effort": "low"`, `"medium"` or `"high"` | on |
12+| `"reasoning_effort": "none"` or `"minimal"` | off |
13+| `"chat_template_kwargs": {"enable_thinking": true}` | on (wins over `reasoning_effort`) |
14+
15+```python
16+answer = client.chat.completions.create(
17+ model="mlx-community/Qwen3-4B-4bit",
18+ messages=[{"role": "user", "content": "Is 391 a prime number?"}],
19+ extra_body={"reasoning_effort": "high"},
20+)
21+print(answer.choices[0].message.reasoning_content) # the reasoning
22+print(answer.choices[0].message.content) # the answer only
12 ```23 ```
13 24
14-Or for one run: `rzb chat --think` (and `--no-think` to turn it off when the file turns it on).25+`low`, `medium` and `high` behave the same: the model either thinks or not.
15 26
16-## Show or hide the reasoning27+## Turn it on by default
17 28
18 ```yaml29 ```yaml
19-ui:30+defaults:
20- show_thinking: false # default true31+ thinking: true # every model…
32+models:
33+ - id: fast
34+ source: mlx-community/Qwen3-4B-4bit
35+ defaults: { thinking: false } # …except this one
21 ```36 ```
22 37
23-- `rzb run` and `rzb chat` print the reasoning dimmed on standard error, so `rzb run … > answer.txt` never keeps it.38+Without configuration, models do not think unless a request asks for it.
24-- `rzb tui` starts with the reasoning shown or hidden as set here; **Ctrl-T** toggles it at any time.39+
40+## Limit how long it thinks
25 41
26-## Limit the thinking42+Per request: `"thinking_budget": 256` (a razorbill extension). In the configuration:
27 43
28 ```yaml44 ```yaml
29-generation:45+defaults:
30- max_tokens: 204846+ thinking_budget: 512
31- thinking: true47+locked:
32- thinking_budget: 512 # at most 512 tokens of reasoning, then the model answers48+ thinking_budget: 2048 # a ceiling clients cannot exceed
33 ```49 ```
34 50
35-Or for one run: `rzb chat --think --thinking-budget 200`.51+When the budget is spent, the model is made to close its reasoning and answer. The reasoning counts in `max_tokens`: keep `max_tokens` well above the budget. Models with no known reasoning protocol (Llama, Gemma) refuse a budget with a 400.
52+
53+## Hide the reasoning from clients
54+
55+- One request: `"include_reasoning": false`.
56+- Always: `locked: { show_reasoning: false }` in the configuration.
36 57
37-- `0` makes the model answer at once.58+The model still thinks; `reasoning_content` is left out, and `usage.completion_tokens_details.reasoning_tokens` still counts it.
38-- The reasoning counts inside `max_tokens`: the budget must be smaller, and should leave room for the answer.
39-- The budget only applies when `thinking` is on.
40 59
41 ## Variants60 ## Variants
42 61
43-- **A model that is not a reasoning model** (Llama, Gemma): `thinking` has no effect, and `thinking_budget` stops the agent with `… has no known thinking protocol: remove generation.thinking_budget`. Remove the budget for these models.62+- **Streaming**: the reasoning arrives in `delta.reasoning_content` before the answer's `delta.content`.
44-- **Answers cut short**: raise `max_tokens`, or lower `thinking_budget`.63+- **Clients that only read `content`** see the answer without the reasoning, which is what most chat UIs expect.
64+- **Structured output or tool calls**: the model thinks freely, then the constraint applies to the answer.
45 65
46 ## See also66 ## See also
47 67
48-- The keys: [agent file reference](../reference/configuration.md#generation) and [`ui`](../reference/configuration.md#ui).68+- The fields: [HTTP API reference](../reference/http-api.md#request-fields) and [configuration reference](../reference/configuration.md#defaults-and-locked).
49-- How thinking is detected, shown and limited: [thinking models](../explanation/thinking.md).69+- How reasoning is separated and limited: [reasoning models](../explanation/thinking.md).
modified docs/en/how-to/develop-from-a-sandbox.md +2 -2
@@ -45,14 +45,14 @@ swiftlint lint --quiet Sources Tests
4545
4646 tools/host-runner/host.sh build . razorbill # Mac: Release build with Metal
4747 tools/host-runner/host.sh test . razorbill # Mac: the whole suite, MLX included
48-tools/host-runner/host.sh run . rzb run --offline -m mlx-community/Qwen3-0.6B-4bit "Hello"
48+tools/host-runner/host.sh run . rzb models list
4949 ```
5050
5151 The script's exit code is the command's exit code on the Mac, so it can be chained like a local command. Files edited in the sandbox are the files the Mac builds: there is nothing to copy.
5252
5353 ## Limits
5454
55-- `host.sh run` has no terminal: use it for `rzb run`, not for `rzb chat`, `rzb init` or `rzb tui`. Try those in a terminal on the Mac.
55+- `host.sh run` has no terminal, and waits for the command to end: do not use it for `rzb serve`. Killing `host.sh` in the sandbox does not stop the server on the Mac, and host-runner then answers 409 to everything until you stop `rzb serve` on the Mac. Start the server in a terminal on the Mac instead; the sandbox reaches it at `http://host.docker.internal:8080/v1` (allow it once with `sbx policy allow network localhost:8080`).
5656 - host-runner runs one command at a time (a second request gets HTTP 409) and only knows `list`, `build`, `test`, `run`, `resolve` and `clean`, on `.` or `samples/<name>`.
5757 - Models are downloaded into the **Mac's** Hugging Face cache; the sandbox cannot see it.
5858
@@ -45,14 +45,14 @@ swiftlint lint --quiet Sources Tests
45 45
46 tools/host-runner/host.sh build . razorbill # Mac: Release build with Metal46 tools/host-runner/host.sh build . razorbill # Mac: Release build with Metal
47 tools/host-runner/host.sh test . razorbill # Mac: the whole suite, MLX included47 tools/host-runner/host.sh test . razorbill # Mac: the whole suite, MLX included
48-tools/host-runner/host.sh run . rzb run --offline -m mlx-community/Qwen3-0.6B-4bit "Hello"48+tools/host-runner/host.sh run . rzb models list
49 ```49 ```
50 50
51 The script's exit code is the command's exit code on the Mac, so it can be chained like a local command. Files edited in the sandbox are the files the Mac builds: there is nothing to copy.51 The script's exit code is the command's exit code on the Mac, so it can be chained like a local command. Files edited in the sandbox are the files the Mac builds: there is nothing to copy.
52 52
53 ## Limits53 ## Limits
54 54
55-- `host.sh run` has no terminal: use it for `rzb run`, not for `rzb chat`, `rzb init` or `rzb tui`. Try those in a terminal on the Mac.55+- `host.sh run` has no terminal, and waits for the command to end: do not use it for `rzb serve`. Killing `host.sh` in the sandbox does not stop the server on the Mac, and host-runner then answers 409 to everything until you stop `rzb serve` on the Mac. Start the server in a terminal on the Mac instead; the sandbox reaches it at `http://host.docker.internal:8080/v1` (allow it once with `sbx policy allow network localhost:8080`).
56 - host-runner runs one command at a time (a second request gets HTTP 409) and only knows `list`, `build`, `test`, `run`, `resolve` and `clean`, on `.` or `samples/<name>`.56 - host-runner runs one command at a time (a second request gets HTTP 409) and only knows `list`, `build`, `test`, `run`, `resolve` and `clean`, on `.` or `samples/<name>`.
57 - Models are downloaded into the **Mac's** Hugging Face cache; the sandbox cannot see it.57 - Models are downloaded into the **Mac's** Hugging Face cache; the sandbox cannot see it.
58 58
added docs/en/how-to/get-structured-output.md +70 -0
new file mode 100644
@@ -0,0 +1,70 @@
1+# How to get structured output
2+
3+This guide makes a model answer with JSON that follows a schema, so your program can parse it without checks. It assumes a server running with a chat model; the examples use `mlx-community/Qwen3-4B-4bit` (models below 1B parameters follow schemas, but often fill them poorly).
4+
5+## With the openai Python library and a Pydantic class
6+
7+```python
8+from openai import OpenAI
9+from pydantic import BaseModel
10+
11+class City(BaseModel):
12+ name: str
13+ country: str
14+ population: int
15+ landmarks: list[str]
16+
17+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
18+completion = client.beta.chat.completions.parse(
19+ model="mlx-community/Qwen3-4B-4bit",
20+ messages=[{"role": "user", "content": "Describe Lyon, France."}],
21+ response_format=City,
22+)
23+city = completion.choices[0].message.parsed # a City instance
24+```
25+
26+Run it with `uv run --with openai --with pydantic python city.py`. Recent versions of the library also offer `client.chat.completions.parse(...)`.
27+
28+## With any client: a JSON Schema
29+
30+Send `response_format` with the schema:
31+
32+```json
33+"response_format": {
34+ "type": "json_schema",
35+ "json_schema": {
36+ "name": "city",
37+ "strict": true,
38+ "schema": {
39+ "type": "object",
40+ "additionalProperties": false,
41+ "required": ["name", "country"],
42+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}
43+ }
44+ }
45+}
46+```
47+
48+The answer's `content` is a JSON string valid against the schema; parse it with your language's JSON library.
49+
50+## Any JSON object, without a schema
51+
52+```json
53+"response_format": {"type": "json_object"}
54+```
55+
56+Say in your prompt which keys you want: only the syntax is guaranteed.
57+
58+## Variants
59+
60+- **Streaming**: add `"stream": true`; the JSON arrives in pieces in `delta.content`. Join them before parsing.
61+- **Reasoning models**: with thinking on (`"reasoning_effort": "low"`), the model thinks freely, then writes the JSON; the reasoning is in `reasoning_content`. Leave room in `max_tokens` for both. For simple extractions, `"reasoning_effort": "none"` is faster.
62+- **Order of the keys**: properties come out in the order of the schema. Put a field such as `reasoning` before `answer` if you want the model to write it first.
63+- **A 400 naming a keyword** (`uniqueItems`, `multipleOf`, `not`, `if`…): with `"strict": true` the server refuses keywords it cannot enforce. Remove the keyword, or set `"strict": false` and check that rule in your code.
64+- **Your own system message**: keep it. The server appends one sentence asking for JSON (with the schema) to it.
65+- **Tools and structured output together**: `response_format` cannot be combined with a forced tool call (`tool_choice` `required` or named); with `tool_choice: "auto"` it applies to the text answer.
66+
67+## See also
68+
69+- Every field of `response_format`: [HTTP API reference](../reference/http-api.md#structured-output).
70+- How the constraint works, and its limits: [constrained decoding](../explanation/constrained-decoding.md).
new file mode 100644
@@ -0,0 +1,70 @@
1+# How to get structured output
2+
3+This guide makes a model answer with JSON that follows a schema, so your program can parse it without checks. It assumes a server running with a chat model; the examples use `mlx-community/Qwen3-4B-4bit` (models below 1B parameters follow schemas, but often fill them poorly).
4+
5+## With the openai Python library and a Pydantic class
6+
7+```python
8+from openai import OpenAI
9+from pydantic import BaseModel
10+
11+class City(BaseModel):
12+ name: str
13+ country: str
14+ population: int
15+ landmarks: list[str]
16+
17+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
18+completion = client.beta.chat.completions.parse(
19+ model="mlx-community/Qwen3-4B-4bit",
20+ messages=[{"role": "user", "content": "Describe Lyon, France."}],
21+ response_format=City,
22+)
23+city = completion.choices[0].message.parsed # a City instance
24+```
25+
26+Run it with `uv run --with openai --with pydantic python city.py`. Recent versions of the library also offer `client.chat.completions.parse(...)`.
27+
28+## With any client: a JSON Schema
29+
30+Send `response_format` with the schema:
31+
32+```json
33+"response_format": {
34+ "type": "json_schema",
35+ "json_schema": {
36+ "name": "city",
37+ "strict": true,
38+ "schema": {
39+ "type": "object",
40+ "additionalProperties": false,
41+ "required": ["name", "country"],
42+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}
43+ }
44+ }
45+}
46+```
47+
48+The answer's `content` is a JSON string valid against the schema; parse it with your language's JSON library.
49+
50+## Any JSON object, without a schema
51+
52+```json
53+"response_format": {"type": "json_object"}
54+```
55+
56+Say in your prompt which keys you want: only the syntax is guaranteed.
57+
58+## Variants
59+
60+- **Streaming**: add `"stream": true`; the JSON arrives in pieces in `delta.content`. Join them before parsing.
61+- **Reasoning models**: with thinking on (`"reasoning_effort": "low"`), the model thinks freely, then writes the JSON; the reasoning is in `reasoning_content`. Leave room in `max_tokens` for both. For simple extractions, `"reasoning_effort": "none"` is faster.
62+- **Order of the keys**: properties come out in the order of the schema. Put a field such as `reasoning` before `answer` if you want the model to write it first.
63+- **A 400 naming a keyword** (`uniqueItems`, `multipleOf`, `not`, `if`…): with `"strict": true` the server refuses keywords it cannot enforce. Remove the keyword, or set `"strict": false` and check that rule in your code.
64+- **Your own system message**: keep it. The server appends one sentence asking for JSON (with the schema) to it.
65+- **Tools and structured output together**: `response_format` cannot be combined with a forced tool call (`tool_choice` `required` or named); with `tool_choice: "auto"` it applies to the text answer.
66+
67+## See also
68+
69+- Every field of `response_format`: [HTTP API reference](../reference/http-api.md#structured-output).
70+- How the constraint works, and its limits: [constrained decoding](../explanation/constrained-decoding.md).
modified docs/en/how-to/manage-models.md +21 -21
@@ -1,10 +1,10 @@
11 # How to manage models
22
3-This guide shows how to find, download, use and delete the models `rzb` runs. It assumes `rzb` is built.
3+This guide shows how to find, download, serve and delete the models `rzb` runs. It assumes `rzb` is built.
44
55 ## Choose a model
66
7-`rzb` runs models in **MLX format**, usually published by `mlx-community` on Hugging Face. `rzb init` offers a short list of tested ones:
7+`rzb` runs models in **MLX format**, usually published by `mlx-community` on Hugging Face. Tested chat models:
88
99 | Model | Download |
1010 | --- | --- |
@@ -15,7 +15,7 @@ This guide shows how to find, download, use and delete the models `rzb` runs. It
1515 | `mlx-community/Llama-3.2-3B-Instruct-4bit` | about 1.8 GB |
1616 | `mlx-community/gemma-3-1b-it-qat-4bit` | about 800 MB |
1717
18-Any other MLX text model supported by mlx-swift-lm works too. GGUF files (for llama.cpp or Ollama) do not.
18+Any other MLX text model supported by mlx-swift-lm works too. GGUF files (for llama.cpp or Ollama) do not. For embedding models, see [compute embeddings](compute-embeddings.md).
1919
2020 ## Download a model ahead of time
2121
@@ -24,7 +24,7 @@ rzb models pull mlx-community/Qwen3-4B-4bit
2424 rzb models pull mlx-community/Qwen3-4B-4bit --revision <branch-tag-or-commit>
2525 ```
2626
27-Without this step, a model is downloaded the first time an agent uses it.
27+Without this step, a model is downloaded by the server the first time a request uses it, and that request waits for the whole download.
2828
2929 ## See what is downloaded
3030
@@ -33,30 +33,30 @@ rzb models list # the models rzb can load
3333 rzb models list --all # also GGUF repositories and unfinished downloads
3434 ```
3535
36-## Use a model
36+## Serve a model
3737
38-- In the agent file: `model: mlx-community/Qwen3-4B-4bit`, or the long form with `id:` and `revision:`.
39-- For one run only: `rzb chat -m mlx-community/Qwen3-4B-4bit`.
38+- By its Hugging Face id: clients send `"model": "mlx-community/Qwen3-4B-4bit"`.
39+- By a short name: declare it in the server configuration (see [configure the server](configure-the-server.md)):
4040
41-## Use a local model directory
42-
43-Point `model.path` at a directory that holds the model's `config.json`, tokenizer files and `*.safetensors`:
41+ ```yaml
42+ models:
43+ - id: qwen3
44+ source: mlx-community/Qwen3-4B-4bit
45+ revision: main # optional: a branch, tag or commit
46+ ```
4447
45-```yaml
46-model:
47- path: ~/models/my-model # relative paths start at the agent file's folder
48-```
48+- A specific revision without declaring it: `"model": "mlx-community/Qwen3-4B-4bit@<revision>"`.
4949
50-On the command line, a value starting with `/`, `./`, `../` or `~/` is a directory: `rzb run -m ./my-model "Hello"`.
50+## Use a local model directory
5151
52-## Work offline
52+Declare a `path` pointing at a directory that holds the model's `config.json`, tokenizer files and `*.safetensors`:
5353
54-```bash
55-rzb chat --offline
54+```yaml
55+models:
56+ - id: mine
57+ path: ~/models/my-model # relative paths start at the configuration file's folder
5658 ```
5759
58-`--offline` uses only what is already in the cache and fails instead of downloading. A model already in the cache is never re-checked online anyway.
59-
6060 ## Delete a model
6161
6262 ```bash
@@ -71,4 +71,4 @@ Models live in the Hugging Face cache, shared with the Python tools (`huggingfac
7171 ## See also
7272
7373 - Every `models` option: [command line reference](../reference/cli.md#rzb-models).
74-- The `model` key: [agent file reference](../reference/configuration.md#model).
74+- The `models` section: [configuration reference](../reference/configuration.md#models).
@@ -1,10 +1,10 @@
1 # How to manage models1 # How to manage models
2 2
3-This guide shows how to find, download, use and delete the models `rzb` runs. It assumes `rzb` is built.3+This guide shows how to find, download, serve and delete the models `rzb` runs. It assumes `rzb` is built.
4 4
5 ## Choose a model5 ## Choose a model
6 6
7-`rzb` runs models in **MLX format**, usually published by `mlx-community` on Hugging Face. `rzb init` offers a short list of tested ones:7+`rzb` runs models in **MLX format**, usually published by `mlx-community` on Hugging Face. Tested chat models:
8 8
9 | Model | Download |9 | Model | Download |
10 | --- | --- |10 | --- | --- |
@@ -15,7 +15,7 @@ This guide shows how to find, download, use and delete the models `rzb` runs. It
15 | `mlx-community/Llama-3.2-3B-Instruct-4bit` | about 1.8 GB |15 | `mlx-community/Llama-3.2-3B-Instruct-4bit` | about 1.8 GB |
16 | `mlx-community/gemma-3-1b-it-qat-4bit` | about 800 MB |16 | `mlx-community/gemma-3-1b-it-qat-4bit` | about 800 MB |
17 17
18-Any other MLX text model supported by mlx-swift-lm works too. GGUF files (for llama.cpp or Ollama) do not.18+Any other MLX text model supported by mlx-swift-lm works too. GGUF files (for llama.cpp or Ollama) do not. For embedding models, see [compute embeddings](compute-embeddings.md).
19 19
20 ## Download a model ahead of time20 ## Download a model ahead of time
21 21
@@ -24,7 +24,7 @@ rzb models pull mlx-community/Qwen3-4B-4bit
24 rzb models pull mlx-community/Qwen3-4B-4bit --revision <branch-tag-or-commit>24 rzb models pull mlx-community/Qwen3-4B-4bit --revision <branch-tag-or-commit>
25 ```25 ```
26 26
27-Without this step, a model is downloaded the first time an agent uses it.27+Without this step, a model is downloaded by the server the first time a request uses it, and that request waits for the whole download.
28 28
29 ## See what is downloaded29 ## See what is downloaded
30 30
@@ -33,30 +33,30 @@ rzb models list # the models rzb can load
33 rzb models list --all # also GGUF repositories and unfinished downloads33 rzb models list --all # also GGUF repositories and unfinished downloads
34 ```34 ```
35 35
36-## Use a model36+## Serve a model
37 37
38-- In the agent file: `model: mlx-community/Qwen3-4B-4bit`, or the long form with `id:` and `revision:`.38+- By its Hugging Face id: clients send `"model": "mlx-community/Qwen3-4B-4bit"`.
39-- For one run only: `rzb chat -m mlx-community/Qwen3-4B-4bit`.39+- By a short name: declare it in the server configuration (see [configure the server](configure-the-server.md)):
40 40
41-## Use a local model directory41+ ```yaml
42-42+ models:
43-Point `model.path` at a directory that holds the model's `config.json`, tokenizer files and `*.safetensors`:43+ - id: qwen3
44+ source: mlx-community/Qwen3-4B-4bit
45+ revision: main # optional: a branch, tag or commit
46+ ```
44 47
45-```yaml48+- A specific revision without declaring it: `"model": "mlx-community/Qwen3-4B-4bit@<revision>"`.
46-model:
47- path: ~/models/my-model # relative paths start at the agent file's folder
48-```
49 49
50-On the command line, a value starting with `/`, `./`, `../` or `~/` is a directory: `rzb run -m ./my-model "Hello"`.50+## Use a local model directory
51 51
52-## Work offline52+Declare a `path` pointing at a directory that holds the model's `config.json`, tokenizer files and `*.safetensors`:
53 53
54-```bash54+```yaml
55-rzb chat --offline55+models:
56+ - id: mine
57+ path: ~/models/my-model # relative paths start at the configuration file's folder
56 ```58 ```
57 59
58-`--offline` uses only what is already in the cache and fails instead of downloading. A model already in the cache is never re-checked online anyway.
59-
60 ## Delete a model60 ## Delete a model
61 61
62 ```bash62 ```bash
@@ -71,4 +71,4 @@ Models live in the Hugging Face cache, shared with the Python tools (`huggingfac
71 ## See also71 ## See also
72 72
73 - Every `models` option: [command line reference](../reference/cli.md#rzb-models).73 - Every `models` option: [command line reference](../reference/cli.md#rzb-models).
74-- The `model` key: [agent file reference](../reference/configuration.md#model).74+- The `models` section: [configuration reference](../reference/configuration.md#models).
modified docs/en/how-to/run-the-tests.md +15 -1
@@ -31,6 +31,20 @@ xcodebuild test -scheme razorbill -destination 'platform=macOS' -derivedDataPath
3131 -skipPackagePluginValidation -skipMacroValidation -only-testing:RazorbillMLXTests
3232 ```
3333
34+## Check compatibility with real OpenAI clients
35+
36+```bash
37+scripts/compat.sh # the whole suite
38+scripts/compat.sh -k tools # extra arguments go to pytest
39+```
40+
41+It starts `rzb serve` on port 18080 with a configuration of its own, runs `Tests/Compatibility` (pytest, with the `openai` library, LangChain, and the `curl` examples of the API reference) and stops the server. It needs [`uv`](https://docs.astral.sh/uv/), which installs the Python packages.
42+
43+- **On the Mac** the server runs MLX: pull `mlx-community/Qwen3-4B-4bit` and `BAAI/bge-small-en-v1.5` first. `mlx-community/Llama-3.2-3B-Instruct-4bit`, when cached, adds the tests of a second tool-call family. The script rebuilds `rzb` (incrementally) before running.
44+- **On Linux** the server runs the fake engine: the protocol is checked (shapes, streaming, errors) and the tests that need a real model are skipped.
45+- **Against a server you started**: `RZB_URL=http://127.0.0.1:8080/v1 scripts/compat.sh`. It must declare the ids `chat` and `embed` (and optionally `unforced`).
46+- Other models: `RZB_COMPAT_CHAT_SOURCE`, `RZB_COMPAT_EMBED_SOURCE`, `RZB_COMPAT_UNFORCED_SOURCE`.
47+
3448 ## Run the tests of the host-runner tool
3549
3650 ```bash
@@ -50,7 +64,7 @@ The last command writes a report under `.quality/` and exits with `0` when the q
5064 ## Variants
5165
5266 - **From a Linux sandbox, for the Mac part**: `tools/host-runner/host.sh test . razorbill`; see [Develop from a Linux sandbox](develop-from-a-sandbox.md).
53-- **Tests that need a terminal** (`rzb chat`, `rzb init`, `rzb tui`) use a scripted console or a fake terminal, so they run unattended. The real terminal behaviour is checked by hand.
67+- **Tests with a real model** (`ChatSmokeTests`, `ConstrainedSmokeTests`, `EmbeddingSmokeTests`, on the Mac) run only when their model is in the cache: `mlx-community/Qwen3-0.6B-4bit`, `sentence-transformers/all-MiniLM-L6-v2`, `BAAI/bge-small-en-v1.5`. Otherwise they are skipped.
5468
5569 ## See also
5670
@@ -31,6 +31,20 @@ xcodebuild test -scheme razorbill -destination 'platform=macOS' -derivedDataPath
31 -skipPackagePluginValidation -skipMacroValidation -only-testing:RazorbillMLXTests31 -skipPackagePluginValidation -skipMacroValidation -only-testing:RazorbillMLXTests
32 ```32 ```
33 33
34+## Check compatibility with real OpenAI clients
35+
36+```bash
37+scripts/compat.sh # the whole suite
38+scripts/compat.sh -k tools # extra arguments go to pytest
39+```
40+
41+It starts `rzb serve` on port 18080 with a configuration of its own, runs `Tests/Compatibility` (pytest, with the `openai` library, LangChain, and the `curl` examples of the API reference) and stops the server. It needs [`uv`](https://docs.astral.sh/uv/), which installs the Python packages.
42+
43+- **On the Mac** the server runs MLX: pull `mlx-community/Qwen3-4B-4bit` and `BAAI/bge-small-en-v1.5` first. `mlx-community/Llama-3.2-3B-Instruct-4bit`, when cached, adds the tests of a second tool-call family. The script rebuilds `rzb` (incrementally) before running.
44+- **On Linux** the server runs the fake engine: the protocol is checked (shapes, streaming, errors) and the tests that need a real model are skipped.
45+- **Against a server you started**: `RZB_URL=http://127.0.0.1:8080/v1 scripts/compat.sh`. It must declare the ids `chat` and `embed` (and optionally `unforced`).
46+- Other models: `RZB_COMPAT_CHAT_SOURCE`, `RZB_COMPAT_EMBED_SOURCE`, `RZB_COMPAT_UNFORCED_SOURCE`.
47+
34 ## Run the tests of the host-runner tool48 ## Run the tests of the host-runner tool
35 49
36 ```bash50 ```bash
@@ -50,7 +64,7 @@ The last command writes a report under `.quality/` and exits with `0` when the q
50 ## Variants64 ## Variants
51 65
52 - **From a Linux sandbox, for the Mac part**: `tools/host-runner/host.sh test . razorbill`; see [Develop from a Linux sandbox](develop-from-a-sandbox.md).66 - **From a Linux sandbox, for the Mac part**: `tools/host-runner/host.sh test . razorbill`; see [Develop from a Linux sandbox](develop-from-a-sandbox.md).
53-- **Tests that need a terminal** (`rzb chat`, `rzb init`, `rzb tui`) use a scripted console or a fake terminal, so they run unattended. The real terminal behaviour is checked by hand.67+- **Tests with a real model** (`ChatSmokeTests`, `ConstrainedSmokeTests`, `EmbeddingSmokeTests`, on the Mac) run only when their model is in the cache: `mlx-community/Qwen3-0.6B-4bit`, `sentence-transformers/all-MiniLM-L6-v2`, `BAAI/bge-small-en-v1.5`. Otherwise they are skipped.
54 68
55 ## See also69 ## See also
56 70
added docs/en/how-to/use-function-calling.md +75 -0
new file mode 100644
@@ -0,0 +1,75 @@
1+# How to use function calling
2+
3+This guide lets a model call functions of your program: it asks for a call, your code runs it, and the model uses the result in its answer. It assumes a server running with a chat model that supports tools; the examples use `mlx-community/Qwen3-4B-4bit`.
4+
5+## 1. Describe the functions
6+
7+```python
8+tools = [{
9+ "type": "function",
10+ "function": {
11+ "name": "get_weather",
12+ "description": "Current weather for a city",
13+ "parameters": {
14+ "type": "object",
15+ "properties": {"city": {"type": "string"}},
16+ "required": ["city"],
17+ },
18+ },
19+}]
20+```
21+
22+## 2. Ask, run the calls, send the results back
23+
24+```python
25+import json
26+from openai import OpenAI
27+
28+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
29+messages = [{"role": "user", "content": "What's the weather like in Lyon?"}]
30+
31+def get_weather(city):
32+ return {"city": city, "temp_c": 7, "sky": "rain"}
33+
34+while True:
35+ answer = client.chat.completions.create(
36+ model="mlx-community/Qwen3-4B-4bit", messages=messages, tools=tools
37+ ).choices[0]
38+ if answer.finish_reason != "tool_calls":
39+ print(answer.message.content)
40+ break
41+ messages.append(answer.message.model_dump(exclude_none=True))
42+ for call in answer.message.tool_calls:
43+ result = get_weather(**json.loads(call.function.arguments))
44+ messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
45+```
46+
47+Each request carries the whole conversation, the assistant's calls and the `tool` results included: the server keeps nothing between requests.
48+
49+## Force a call
50+
51+- `tool_choice="required"`: the answer is a call to one of the tools.
52+- `tool_choice={"type": "function", "function": {"name": "get_weather"}}`: the answer is a call to `get_weather`.
53+- `tool_choice="none"`: the model answers in text, without seeing the tools.
54+
55+A forced call is generated under a grammar: the name exists and the arguments match the schema. This works for models whose tool-call syntax is `<tool_call>{…}</tool_call>` (Qwen, Hermes…). Other families (Llama 3, Mistral, Gemma) answer 400 to a forced call: use `tool_choice="auto"` with them.
56+
57+## Get several calls at once
58+
59+A forced call produces one call. To let the model ask for several in one answer (weather and time, for example), send `parallel_tool_calls=True`. With `parallel_tool_calls=False`, only the first call is kept, whatever the mode.
60+
61+## Guarantee valid arguments in auto mode
62+
63+Add `"strict": True` to a function: its arguments are then generated under its schema whenever the model calls it, while the model remains free not to call it. The schema must not use keywords the decoder cannot enforce (see [structured output](get-structured-output.md#variants)).
64+
65+## Variants
66+
67+- **Streaming**: with `stream=True`, each call arrives whole in one chunk, in `delta.tool_calls` with its `index`; the last chunk has `finish_reason: "tool_calls"`.
68+- **LangChain**: `ChatOpenAI(base_url=…, model=…).bind_tools([...])` works as with OpenAI (see [use OpenAI clients](use-openai-clients.md)).
69+- **Small models** (below 1B) often answer in text in `auto` mode instead of calling; force the call or use a larger model.
70+- **Thinking**: a reasoning model may think before calling; add `extra_body={"reasoning_effort": "none"}` to skip it.
71+
72+## See also
73+
74+- Every field of `tools` and `tool_choice`: [HTTP API reference](../reference/http-api.md#tools).
75+- Why forced calls depend on the model family: [constrained decoding](../explanation/constrained-decoding.md).
new file mode 100644
@@ -0,0 +1,75 @@
1+# How to use function calling
2+
3+This guide lets a model call functions of your program: it asks for a call, your code runs it, and the model uses the result in its answer. It assumes a server running with a chat model that supports tools; the examples use `mlx-community/Qwen3-4B-4bit`.
4+
5+## 1. Describe the functions
6+
7+```python
8+tools = [{
9+ "type": "function",
10+ "function": {
11+ "name": "get_weather",
12+ "description": "Current weather for a city",
13+ "parameters": {
14+ "type": "object",
15+ "properties": {"city": {"type": "string"}},
16+ "required": ["city"],
17+ },
18+ },
19+}]
20+```
21+
22+## 2. Ask, run the calls, send the results back
23+
24+```python
25+import json
26+from openai import OpenAI
27+
28+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
29+messages = [{"role": "user", "content": "What's the weather like in Lyon?"}]
30+
31+def get_weather(city):
32+ return {"city": city, "temp_c": 7, "sky": "rain"}
33+
34+while True:
35+ answer = client.chat.completions.create(
36+ model="mlx-community/Qwen3-4B-4bit", messages=messages, tools=tools
37+ ).choices[0]
38+ if answer.finish_reason != "tool_calls":
39+ print(answer.message.content)
40+ break
41+ messages.append(answer.message.model_dump(exclude_none=True))
42+ for call in answer.message.tool_calls:
43+ result = get_weather(**json.loads(call.function.arguments))
44+ messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
45+```
46+
47+Each request carries the whole conversation, the assistant's calls and the `tool` results included: the server keeps nothing between requests.
48+
49+## Force a call
50+
51+- `tool_choice="required"`: the answer is a call to one of the tools.
52+- `tool_choice={"type": "function", "function": {"name": "get_weather"}}`: the answer is a call to `get_weather`.
53+- `tool_choice="none"`: the model answers in text, without seeing the tools.
54+
55+A forced call is generated under a grammar: the name exists and the arguments match the schema. This works for models whose tool-call syntax is `<tool_call>{…}</tool_call>` (Qwen, Hermes…). Other families (Llama 3, Mistral, Gemma) answer 400 to a forced call: use `tool_choice="auto"` with them.
56+
57+## Get several calls at once
58+
59+A forced call produces one call. To let the model ask for several in one answer (weather and time, for example), send `parallel_tool_calls=True`. With `parallel_tool_calls=False`, only the first call is kept, whatever the mode.
60+
61+## Guarantee valid arguments in auto mode
62+
63+Add `"strict": True` to a function: its arguments are then generated under its schema whenever the model calls it, while the model remains free not to call it. The schema must not use keywords the decoder cannot enforce (see [structured output](get-structured-output.md#variants)).
64+
65+## Variants
66+
67+- **Streaming**: with `stream=True`, each call arrives whole in one chunk, in `delta.tool_calls` with its `index`; the last chunk has `finish_reason: "tool_calls"`.
68+- **LangChain**: `ChatOpenAI(base_url=…, model=…).bind_tools([...])` works as with OpenAI (see [use OpenAI clients](use-openai-clients.md)).
69+- **Small models** (below 1B) often answer in text in `auto` mode instead of calling; force the call or use a larger model.
70+- **Thinking**: a reasoning model may think before calling; add `extra_body={"reasoning_effort": "none"}` to skip it.
71+
72+## See also
73+
74+- Every field of `tools` and `tool_choice`: [HTTP API reference](../reference/http-api.md#tools).
75+- Why forced calls depend on the model family: [constrained decoding](../explanation/constrained-decoding.md).
added docs/en/how-to/use-openai-clients.md +73 -0
new file mode 100644
@@ -0,0 +1,73 @@
1+# How to use razorbill from an OpenAI client
2+
3+This guide points existing OpenAI clients and frameworks at `rzb serve`. It assumes the server is running at `http://127.0.0.1:8080` (add your key if you set one).
4+
5+The rule is always the same: **base URL** `http://127.0.0.1:8080/v1`, **API key** any non-empty value (or the server's key), **model** a declared `id` or a Hugging Face id.
6+
7+## Python — openai
8+
9+```python
10+from openai import OpenAI
11+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
12+```
13+
14+razorbill-specific fields go in `extra_body`, for example `extra_body={"reasoning_effort": "none", "thinking_budget": 256}`.
15+
16+## JavaScript / TypeScript — openai
17+
18+```javascript
19+import OpenAI from "openai";
20+const client = new OpenAI({ baseURL: "http://127.0.0.1:8080/v1", apiKey: "unused" });
21+const answer = await client.chat.completions.create({
22+ model: "mlx-community/Qwen3-4B-4bit",
23+ messages: [{ role: "user", content: "Hello" }],
24+});
25+```
26+
27+## LangChain (Python)
28+
29+```python
30+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
31+
32+llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="mlx-community/Qwen3-4B-4bit")
33+embeddings = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused",
34+ model="BAAI/bge-small-en-v1.5", check_embedding_ctx_length=False)
35+```
36+
37+`check_embedding_ctx_length=False` is required: otherwise LangChain sends token arrays, which the server refuses.
38+
39+## Environment variables
40+
41+Many tools read the standard OpenAI variables:
42+
43+```bash
44+export OPENAI_BASE_URL=http://127.0.0.1:8080/v1
45+export OPENAI_API_KEY=unused
46+```
47+
48+## Chat UIs (Open WebUI and others)
49+
50+Add an "OpenAI API" connection with the base URL `http://127.0.0.1:8080/v1` and any key. If the UI runs in Docker, `127.0.0.1` is the container itself: use `http://host.docker.internal:8080/v1` and start the server with `--host 0.0.0.0` and an API key. The UI lists the models of `/v1/models`.
51+
52+## Tools that use the legacy completions API
53+
54+Code-completion plugins and benchmark harnesses (lm-eval…) that call `/v1/completions` work too: the prompt is continued as raw text. Fill-in-the-middle (`suffix`) and `logprobs` are refused.
55+
56+## curl
57+
58+```bash
59+curl -s http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" \
60+ -H "Authorization: Bearer $RZB_API_KEY" \
61+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Hello"}]}'
62+```
63+
64+## When something does not work
65+
66+- **404 `model_not_found`**: the client sends a model name the server does not know (some UIs default to `gpt-4o`). Pick a model from `/v1/models`.
67+- **400 naming a field**: the client sends something razorbill refuses rather than ignores (`n` > 1, `logprobs`, images…). The message says which field.
68+- **401**: the server has a key and the client sends another one, or none.
69+
70+## See also
71+
72+- What is supported, refused or ignored: [HTTP API reference](../reference/http-api.md).
73+- How compatibility is defined and checked: [OpenAI compatibility](../explanation/openai-compatibility.md).
new file mode 100644
@@ -0,0 +1,73 @@
1+# How to use razorbill from an OpenAI client
2+
3+This guide points existing OpenAI clients and frameworks at `rzb serve`. It assumes the server is running at `http://127.0.0.1:8080` (add your key if you set one).
4+
5+The rule is always the same: **base URL** `http://127.0.0.1:8080/v1`, **API key** any non-empty value (or the server's key), **model** a declared `id` or a Hugging Face id.
6+
7+## Python — openai
8+
9+```python
10+from openai import OpenAI
11+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
12+```
13+
14+razorbill-specific fields go in `extra_body`, for example `extra_body={"reasoning_effort": "none", "thinking_budget": 256}`.
15+
16+## JavaScript / TypeScript — openai
17+
18+```javascript
19+import OpenAI from "openai";
20+const client = new OpenAI({ baseURL: "http://127.0.0.1:8080/v1", apiKey: "unused" });
21+const answer = await client.chat.completions.create({
22+ model: "mlx-community/Qwen3-4B-4bit",
23+ messages: [{ role: "user", content: "Hello" }],
24+});
25+```
26+
27+## LangChain (Python)
28+
29+```python
30+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
31+
32+llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="mlx-community/Qwen3-4B-4bit")
33+embeddings = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused",
34+ model="BAAI/bge-small-en-v1.5", check_embedding_ctx_length=False)
35+```
36+
37+`check_embedding_ctx_length=False` is required: otherwise LangChain sends token arrays, which the server refuses.
38+
39+## Environment variables
40+
41+Many tools read the standard OpenAI variables:
42+
43+```bash
44+export OPENAI_BASE_URL=http://127.0.0.1:8080/v1
45+export OPENAI_API_KEY=unused
46+```
47+
48+## Chat UIs (Open WebUI and others)
49+
50+Add an "OpenAI API" connection with the base URL `http://127.0.0.1:8080/v1` and any key. If the UI runs in Docker, `127.0.0.1` is the container itself: use `http://host.docker.internal:8080/v1` and start the server with `--host 0.0.0.0` and an API key. The UI lists the models of `/v1/models`.
51+
52+## Tools that use the legacy completions API
53+
54+Code-completion plugins and benchmark harnesses (lm-eval…) that call `/v1/completions` work too: the prompt is continued as raw text. Fill-in-the-middle (`suffix`) and `logprobs` are refused.
55+
56+## curl
57+
58+```bash
59+curl -s http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" \
60+ -H "Authorization: Bearer $RZB_API_KEY" \
61+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Hello"}]}'
62+```
63+
64+## When something does not work
65+
66+- **404 `model_not_found`**: the client sends a model name the server does not know (some UIs default to `gpt-4o`). Pick a model from `/v1/models`.
67+- **400 naming a field**: the client sends something razorbill refuses rather than ignores (`n` > 1, `logprobs`, images…). The message says which field.
68+- **401**: the server has a key and the client sends another one, or none.
69+
70+## See also
71+
72+- What is supported, refused or ignored: [HTTP API reference](../reference/http-api.md).
73+- How compatibility is defined and checked: [OpenAI compatibility](../explanation/openai-compatibility.md).
deleted docs/en/how-to/use-rzb-in-scripts.md +0 -73
deleted file mode 100644
@@ -1,73 +0,0 @@
1-# How to use rzb in scripts
2-
3-`rzb run` asks the agent once and exits, which makes it usable in shell scripts, pipes and Makefiles. This guide shows the patterns.
4-
5-## Ask one question
6-
7-```bash
8-rzb run "Summarise the README in three bullet points"
9-```
10-
11-## Send a file or the output of a command
12-
13-Piped input is added after the prompt (separated by a blank line):
14-
15-```bash
16-git diff | rzb run "Review this change"
17-rzb run "Explain this code" < Sources/App/main.swift
18-cat error.log | rzb run # the piped text alone is the prompt
19-```
20-
21-## Keep only the answer
22-
23-The answer goes to **standard output**; download progress, thinking, tool calls and statistics go to **standard error**:
24-
25-```bash
26-rzb run "Write a commit message for this diff" < change.diff > message.txt
27-rzb run "…" 2>/dev/null # nothing but the answer on screen
28-```
29-
30-To also drop the statistics line, set `ui.show_stats: false` in the agent file.
31-
32-## Make answers reproducible
33-
34-```bash
35-rzb run --temperature 0 "…"
36-```
37-
38-## Choose the agent file
39-
40-```bash
41-rzb run -c agents/reviewer.yaml "…"
42-```
43-
44-Without `-c`, `rzb` uses `./razorbill.yaml`, then `~/.config/razorbill/agent.yaml`.
45-
46-## Check the result
47-
48-| Exit code | Meaning |
49-| --- | --- |
50-| `0` | the answer was printed |
51-| `1` | something failed while running (model, download, tool…) |
52-| `2` | the agent file is missing or invalid |
53-| `64` | wrong command line (unknown option, missing prompt) |
54-| `130` | interrupted (Ctrl-C) |
55-
56-```bash
57-if ! rzb run "…" > out.txt; then echo "rzb failed" >&2; fi
58-```
59-
60-## Validate an agent file in CI
61-
62-```bash
63-rzb config validate agents/reviewer.yaml
64-```
65-
66-## Variants
67-
68-- **Tools in scripts**: with no terminal, `bash` refuses commands that need confirmation; see [Use the bash tool](use-the-bash-tool.md#use-it-without-a-terminal-scripts-ci).
69-- **No network**: add `--offline` to fail fast if the model is not downloaded.
70-
71-## See also
72-
73-- Every option: [command line reference](../reference/cli.md).
deleted file mode 100644
@@ -1,73 +0,0 @@
1-# How to use rzb in scripts
2-
3-`rzb run` asks the agent once and exits, which makes it usable in shell scripts, pipes and Makefiles. This guide shows the patterns.
4-
5-## Ask one question
6-
7-```bash
8-rzb run "Summarise the README in three bullet points"
9-```
10-
11-## Send a file or the output of a command
12-
13-Piped input is added after the prompt (separated by a blank line):
14-
15-```bash
16-git diff | rzb run "Review this change"
17-rzb run "Explain this code" < Sources/App/main.swift
18-cat error.log | rzb run # the piped text alone is the prompt
19-```
20-
21-## Keep only the answer
22-
23-The answer goes to **standard output**; download progress, thinking, tool calls and statistics go to **standard error**:
24-
25-```bash
26-rzb run "Write a commit message for this diff" < change.diff > message.txt
27-rzb run "…" 2>/dev/null # nothing but the answer on screen
28-```
29-
30-To also drop the statistics line, set `ui.show_stats: false` in the agent file.
31-
32-## Make answers reproducible
33-
34-```bash
35-rzb run --temperature 0 "…"
36-```
37-
38-## Choose the agent file
39-
40-```bash
41-rzb run -c agents/reviewer.yaml "…"
42-```
43-
44-Without `-c`, `rzb` uses `./razorbill.yaml`, then `~/.config/razorbill/agent.yaml`.
45-
46-## Check the result
47-
48-| Exit code | Meaning |
49-| --- | --- |
50-| `0` | the answer was printed |
51-| `1` | something failed while running (model, download, tool…) |
52-| `2` | the agent file is missing or invalid |
53-| `64` | wrong command line (unknown option, missing prompt) |
54-| `130` | interrupted (Ctrl-C) |
55-
56-```bash
57-if ! rzb run "…" > out.txt; then echo "rzb failed" >&2; fi
58-```
59-
60-## Validate an agent file in CI
61-
62-```bash
63-rzb config validate agents/reviewer.yaml
64-```
65-
66-## Variants
67-
68-- **Tools in scripts**: with no terminal, `bash` refuses commands that need confirmation; see [Use the bash tool](use-the-bash-tool.md#use-it-without-a-terminal-scripts-ci).
69-- **No network**: add `--offline` to fail fast if the model is not downloaded.
70-
71-## See also
72-
73-- Every option: [command line reference](../reference/cli.md).
deleted docs/en/how-to/use-the-bash-tool.md +0 -54
deleted file mode 100644
@@ -1,54 +0,0 @@
1-# How to use the bash tool
2-
3-The `bash` tool lets the agent run shell commands on your Mac. This guide shows how to enable it and keep it under control.
4-
5-## Enable it, with confirmation
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true # the default: you accept each command
11-```
12-
13-The agent shows each command and waits for `y`. In `rzb tui` the question appears in the bottom line.
14-
15-## Restrict what it may run
16-
17-```yaml
18-tools:
19- bash:
20- allow: ["ls*", "cat *", "git status", "git diff*", "swift build*"]
21- deny: ["rm *", "sudo *", "git push*"]
22-```
23-
24-`deny` is checked first and always wins; when `allow` is given, a command must match one of its patterns. `*` stands for any text, `?` for one character. A refused command is reported to the model, which can try something else.
25-
26-## Use it without a terminal (scripts, CI)
27-
28-With no terminal to ask, commands that need confirmation are refused. To let them run unattended, turn confirmation off explicitly — and narrow `allow`:
29-
30-```yaml
31-tools:
32- bash:
33- confirm: false
34- allow: ["ls*", "git log*"]
35-```
36-
37-## Change where and how long commands run
38-
39-```yaml
40-tools:
41- bash:
42- workdir: ./project # relative to the directory rzb is started from
43- timeout: 2m # the command and everything it started are killed after this
44- max_output: 64KB # the rest of the output is dropped, with a marker
45-```
46-
47-## Turn it off
48-
49-Remove `bash` from `tools:` (or remove `tools:`): built-in tools exist only when listed.
50-
51-## See also
52-
53-- Every option, the order of the checks and the output format: [bash tool reference](../reference/bash-tool.md).
54-- Why patterns are not a sandbox, and what is planned: [tool safety](../explanation/tool-safety.md).
deleted file mode 100644
@@ -1,54 +0,0 @@
1-# How to use the bash tool
2-
3-The `bash` tool lets the agent run shell commands on your Mac. This guide shows how to enable it and keep it under control.
4-
5-## Enable it, with confirmation
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true # the default: you accept each command
11-```
12-
13-The agent shows each command and waits for `y`. In `rzb tui` the question appears in the bottom line.
14-
15-## Restrict what it may run
16-
17-```yaml
18-tools:
19- bash:
20- allow: ["ls*", "cat *", "git status", "git diff*", "swift build*"]
21- deny: ["rm *", "sudo *", "git push*"]
22-```
23-
24-`deny` is checked first and always wins; when `allow` is given, a command must match one of its patterns. `*` stands for any text, `?` for one character. A refused command is reported to the model, which can try something else.
25-
26-## Use it without a terminal (scripts, CI)
27-
28-With no terminal to ask, commands that need confirmation are refused. To let them run unattended, turn confirmation off explicitly — and narrow `allow`:
29-
30-```yaml
31-tools:
32- bash:
33- confirm: false
34- allow: ["ls*", "git log*"]
35-```
36-
37-## Change where and how long commands run
38-
39-```yaml
40-tools:
41- bash:
42- workdir: ./project # relative to the directory rzb is started from
43- timeout: 2m # the command and everything it started are killed after this
44- max_output: 64KB # the rest of the output is dropped, with a marker
45-```
46-
47-## Turn it off
48-
49-Remove `bash` from `tools:` (or remove `tools:`): built-in tools exist only when listed.
50-
51-## See also
52-
53-- Every option, the order of the checks and the output format: [bash tool reference](../reference/bash-tool.md).
54-- Why patterns are not a sandbox, and what is planned: [tool safety](../explanation/tool-safety.md).
deleted docs/en/reference/bash-tool.md +0 -77
deleted file mode 100644
@@ -1,77 +0,0 @@
1-# Reference: bash tool
2-
3-> The built-in tool `bash`: its options, the checks made before a command runs, and what the model receives.
4-
5-## Declaration
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true
11- workdir: .
12- timeout: 30s
13- max_output: 16KB
14- allow: ["ls*", "git status"]
15- deny: ["rm -rf*", "sudo *"]
16-```
17-
18-The tool exists only when `bash` is listed under `tools`.
19-
20-## Options
21-
22-| Option | Type | Default | Description |
23-| --- | --- | --- | --- |
24-| `confirm` | boolean | `true` | Ask the user before each command. |
25-| `workdir` | text | `.` | Directory the commands run in. A relative path starts at the directory `rzb` was started from. |
26-| `timeout` | duration | `30s` | Time after which the command and every process it started are killed. A number of seconds, or a number with `ms`, `s`, `m` or `h`. Must be positive. |
27-| `max_output` | size | `16KB` | Bytes of output kept (standard output and error together); the rest is dropped. A number of bytes, or a number with `B`, `KB` or `MB` (1 KB = 1024 bytes). Must be positive. |
28-| `allow` | list of patterns | empty (everything) | When not empty, a command must match one of these patterns. |
29-| `deny` | list of patterns | empty | A command that matches one of these patterns is refused. |
30-
31-Patterns match the whole command line: `*` is any text (spaces included), `?` is one character. `"git *"` matches `git status`; `"ls*"` matches `ls -la` and also `ls; rm -rf ~`.
32-
33-## Arguments sent by the model
34-
35-| Argument | Type | Required | Description |
36-| --- | --- | --- | --- |
37-| `command` | text | yes | The command line, run with `/bin/bash -c`. |
38-
39-## Checks, in order
40-
41-| Order | Check | Refusal sent to the model |
42-| --- | --- | --- |
43-| 1 | `command` present and not empty | `refused: the \`command\` argument (text) is missing` |
44-| 2 | matches a `deny` pattern | `refused: the command matches the deny pattern \`<pattern>\`` |
45-| 3 | `allow` not empty and no pattern matches | `refused: the command matches none of the allow patterns` |
46-| 4 | `confirm: true` and no terminal | `refused: no terminal to ask the user for confirmation (set \`confirm: false\` to allow this)` |
47-| 5 | `confirm: true` and the user answers no | `refused: the user declined to run it` |
48-
49-The confirmation shows `bash wants to run: <command> (in <workdir>)`. In `run` and `chat` the answer is `y` or `n` (default no); in `tui`, `y` accepts and `n`, Enter, Esc or Ctrl-C refuse.
50-
51-## Result sent to the model
52-
53-```
54-exit code: 0
55-stdout:
56-<standard output>
57-stderr:
58-<standard error>
59-```
60-
61-- `stdout:` and `stderr:` are present only when not empty.
62-- After a timeout, the first line is `timed out after <seconds>s: the command was killed`.
63-- When output was dropped, the last line is `[output truncated: <N> more bytes]`.
64-- The result is marked as an error when the exit code is not 0, on timeout, and for every refusal.
65-
66-## Environment of the commands
67-
68-Commands inherit the environment of `rzb` (all its variables) and run with the user's rights. Standard input is `/dev/null`.
69-
70-## Errors in the agent file
71-
72-| Error | Cause |
73-| --- | --- |
74-| `tools.bash.<key>: unknown option (expected one of: confirm, workdir, timeout, max_output, allow, deny)` | A key other than the six options. |
75-| `tools.bash.confirm: must be true or false`, `tools.bash.workdir: must be text`, `tools.bash.allow: must be a list of text` | Wrong type. |
76-| `tools.bash.timeout: must be a positive duration such as 30s, 2m or 500ms` | Invalid duration. |
77-| `tools.bash.max_output: must be a positive size such as 16KB or 1MB` | Invalid size. |
deleted file mode 100644
@@ -1,77 +0,0 @@
1-# Reference: bash tool
2-
3-> The built-in tool `bash`: its options, the checks made before a command runs, and what the model receives.
4-
5-## Declaration
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true
11- workdir: .
12- timeout: 30s
13- max_output: 16KB
14- allow: ["ls*", "git status"]
15- deny: ["rm -rf*", "sudo *"]
16-```
17-
18-The tool exists only when `bash` is listed under `tools`.
19-
20-## Options
21-
22-| Option | Type | Default | Description |
23-| --- | --- | --- | --- |
24-| `confirm` | boolean | `true` | Ask the user before each command. |
25-| `workdir` | text | `.` | Directory the commands run in. A relative path starts at the directory `rzb` was started from. |
26-| `timeout` | duration | `30s` | Time after which the command and every process it started are killed. A number of seconds, or a number with `ms`, `s`, `m` or `h`. Must be positive. |
27-| `max_output` | size | `16KB` | Bytes of output kept (standard output and error together); the rest is dropped. A number of bytes, or a number with `B`, `KB` or `MB` (1 KB = 1024 bytes). Must be positive. |
28-| `allow` | list of patterns | empty (everything) | When not empty, a command must match one of these patterns. |
29-| `deny` | list of patterns | empty | A command that matches one of these patterns is refused. |
30-
31-Patterns match the whole command line: `*` is any text (spaces included), `?` is one character. `"git *"` matches `git status`; `"ls*"` matches `ls -la` and also `ls; rm -rf ~`.
32-
33-## Arguments sent by the model
34-
35-| Argument | Type | Required | Description |
36-| --- | --- | --- | --- |
37-| `command` | text | yes | The command line, run with `/bin/bash -c`. |
38-
39-## Checks, in order
40-
41-| Order | Check | Refusal sent to the model |
42-| --- | --- | --- |
43-| 1 | `command` present and not empty | `refused: the \`command\` argument (text) is missing` |
44-| 2 | matches a `deny` pattern | `refused: the command matches the deny pattern \`<pattern>\`` |
45-| 3 | `allow` not empty and no pattern matches | `refused: the command matches none of the allow patterns` |
46-| 4 | `confirm: true` and no terminal | `refused: no terminal to ask the user for confirmation (set \`confirm: false\` to allow this)` |
47-| 5 | `confirm: true` and the user answers no | `refused: the user declined to run it` |
48-
49-The confirmation shows `bash wants to run: <command> (in <workdir>)`. In `run` and `chat` the answer is `y` or `n` (default no); in `tui`, `y` accepts and `n`, Enter, Esc or Ctrl-C refuse.
50-
51-## Result sent to the model
52-
53-```
54-exit code: 0
55-stdout:
56-<standard output>
57-stderr:
58-<standard error>
59-```
60-
61-- `stdout:` and `stderr:` are present only when not empty.
62-- After a timeout, the first line is `timed out after <seconds>s: the command was killed`.
63-- When output was dropped, the last line is `[output truncated: <N> more bytes]`.
64-- The result is marked as an error when the exit code is not 0, on timeout, and for every refusal.
65-
66-## Environment of the commands
67-
68-Commands inherit the environment of `rzb` (all its variables) and run with the user's rights. Standard input is `/dev/null`.
69-
70-## Errors in the agent file
71-
72-| Error | Cause |
73-| --- | --- |
74-| `tools.bash.<key>: unknown option (expected one of: confirm, workdir, timeout, max_output, allow, deny)` | A key other than the six options. |
75-| `tools.bash.confirm: must be true or false`, `tools.bash.workdir: must be text`, `tools.bash.allow: must be a list of text` | Wrong type. |
76-| `tools.bash.timeout: must be a positive duration such as 30s, 2m or 500ms` | Invalid duration. |
77-| `tools.bash.max_output: must be a positive size such as 16KB or 1MB` | Invalid size. |
modified docs/en/reference/cli.md +33 -95
@@ -1,6 +1,6 @@
11 # Reference: command line
22
3-> Every `rzb` command, option, exit code and in-session command of razorbill 0.1.0.
3+> Every `rzb` command, option and exit code of razorbill 0.1.0.
44
55 ```
66 rzb <command> [options]
@@ -10,129 +10,67 @@ rzb help <command>
1010
1111 | Command | Purpose |
1212 | --- | --- |
13-| [`rzb init`](#rzb-init) | Write an agent file with a wizard |
14-| [`rzb run`](#rzb-run) | One answer, then exit |
15-| [`rzb chat`](#rzb-chat) | Line-by-line conversation |
16-| [`rzb tui`](#rzb-tui) | Full-screen conversation |
13+| [`rzb serve`](#rzb-serve) | Start the OpenAI-compatible server |
14+| [`rzb config validate`](#rzb-config-validate) | Check a server configuration file |
1715 | [`rzb models`](#rzb-models) | List, download, delete models |
18-| [`rzb config validate`](#rzb-config-validate) | Check an agent file |
1916 | [`rzb version`](#rzb-version) | Version and engines |
2017
21-## Agent options
22-
23-Shared by `run`, `chat` and `tui`. Each one overrides the matching value of the agent file for this run only.
24-
25-| Option | Type | Default | Description |
26-| --- | --- | --- | --- |
27-| `-c`, `--config <file>` | path | `./razorbill.yaml`, then `~/.config/razorbill/agent.yaml` | Agent file to load. |
28-| `-m`, `--model <model>` | id or path | the file's `model` | Hugging Face id, or a local directory when the value starts with `/`, `./`, `../` or `~/`. Revision `main`. |
29-| `--temperature <n>` | number ≥ 0 | the file's | Sampling temperature. |
30-| `--max-tokens <n>` | integer > 0 | the file's | Maximum tokens per answer. |
31-| `--think` / `--no-think` | flag | the file's | Sets `generation.thinking`. |
32-| `--thinking-budget <n>` | integer ≥ 0 | the file's | Sets `generation.thinking_budget`. |
33-| `--offline` | flag | off | Use only models already in the cache; never download. |
34-| `--engine <name>` | `mlx`, `fake` | the first engine of the build (`mlx` on the Mac) | Engine running the model. `fake` answers `echo: <prompt>` without a model. |
35-
36-## rzb init
37-
38-Writes an agent file. Interactive by default: agent name, description, model (downloaded ones first, then recommended ones, then any Hugging Face id or a local directory), system prompt, temperature, maximum tokens, thinking (then thinking budget and whether to show the reasoning), built-in tools, confirmation, optional download.
39-
40-| Option | Default | Description |
41-| --- | --- | --- |
42-| `-o`, `--output <file>` | `razorbill.yaml` | File to write. |
43-| `--force` | off | Overwrite an existing file without asking. |
44-| `--name <name>` | `assistant` | Agent name (default answer of the wizard). |
45-| `--model <model>` | `mlx-community/Qwen3-1.7B-4bit` | Model (id or directory). |
46-| `-y`, `--yes` | off | Ask nothing: use the options and the defaults. Required without a terminal. |
47-| `--no-download` | off | Do not offer to download the model. |
48-
49-The written file always loads: it is parsed before being saved.
50-
51-## rzb run
18+## rzb serve
5219
5320 ```
54-rzb run [agent options] [<prompt> ...]
21+rzb serve [--config <file>] [--host <address>] [--port <n>] [--api-key-env <name>] [--cors-origin <origin>]
5522 ```
5623
57-The words of the prompt are joined with spaces. When standard input is not a terminal, its content is appended after a blank line; the prompt may then be omitted. The answer goes to standard output; download progress, thinking, tool calls and statistics go to standard error.
24+Starts the server and runs until Ctrl-C or SIGTERM; then it stops accepting requests, unloads the models and exits with code 0.
5825
59-## rzb chat
26+| Option | Type | Default | Description |
27+| --- | --- | --- | --- |
28+| `--config <file>` | path | none | Server configuration file ([reference](configuration.md)). Without it: no declared models, built-in defaults |
29+| `--host <address>` | string, not empty | `server.host`, else `127.0.0.1` | Address to listen on; `0.0.0.0` for every interface |
30+| `--port <n>` | integer, 1–65535 | `server.port`, else `8080` | TCP port |
31+| `--api-key-env <name>` | string | `server.api_key_env`, else `RZB_API_KEY` | Environment variable holding the API key. Set and not empty: every route but `/health` needs `Authorization: Bearer <key>` |
32+| `--cors-origin <origin>` | string | `server.cors_origin`, else none | Let browser pages from this origin call the API; `*` for any origin |
33+
34+Options win over the `server:` section of the file. On start it prints, on standard error:
6035
6136 ```
62-rzb chat [agent options]
37+config: server.yaml (2 declared models)
38+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop
6339 ```
6440
65-Reads one message per line from standard input and streams each answer. A failed answer prints `error: …` and the conversation continues.
41+The first line appears only with `--config`. Warnings (`warning: …`) are printed before the banner when the server listens on a network address without an API key, or allows every CORS origin without one. Then one log line per request: method, path, status, duration, and the model and token counts (`model=… tokens=<prompt>+<completion>`); prompts and answers are never logged.
6642
67-| Input | Effect |
68-| --- | --- |
69-| `/reset` | Start a new conversation (the model stays loaded). |
70-| `/help` | List these commands. |
71-| `/exit`, `/quit`, Ctrl-D | Quit. |
72-| empty line | Ignored. |
43+The engine is the first one of the build: `mlx` on the Mac, `fake` on Linux (which answers `echo: <last message>` without a model).
7344
74-## rzb tui
45+## rzb config validate
7546
7647 ```
77-rzb tui [agent options]
48+rzb config validate <file>
7849 ```
7950
80-Full-screen conversation. Needs a terminal on standard input and standard output; otherwise it exits with `error: rzb tui needs a terminal; use rzb run or rzb chat instead`.
81-
82-| Key | Effect |
83-| --- | --- |
84-| Enter | Send the input line (ignored while an answer is running). |
85-| Ctrl-C | Stop the running answer; quit when nothing runs. |
86-| Ctrl-D | Quit (when the input line is empty). |
87-| Ctrl-T | Show / hide the reasoning. |
88-| Ctrl-N | New conversation (when nothing runs). |
89-| PgUp / PgDn, ↑ / ↓ | Scroll the conversation. |
90-| ← / →, Home / End, Ctrl-A / Ctrl-E | Move in the input line. |
91-| Backspace / Delete, Ctrl-U | Delete a character / the whole line. |
92-| `y` / `n` | Answer a tool's confirmation (`n`, Enter, Esc and Ctrl-C refuse). |
93-
94-Commands typed in the input line: `/reset` or `/new` (new conversation), `/exit` or `/quit`.
95-
96-The title bar shows the agent, the model, the engine, then `● answering` or the last speed in tokens/s. The terminal is restored on exit, including on SIGTERM, SIGHUP and SIGQUIT.
51+Loads the file without starting anything. Prints `<file> is valid: 2 models (qwen3, embed), any Hugging Face MLX id accepted` on standard output, or every problem found with its line number ([format](configuration.md#errors)) and exit code 2.
9752
9853 ## rzb models
9954
10055 | Command | Arguments and options | Description |
10156 | --- | --- | --- |
102-| `rzb models list` | `--all`: also show repositories that are not loadable (GGUF, unfinished downloads), with a status column | Models in the cache: id, size, revisions. Prints the cache folder on standard error. |
103-| `rzb models pull <id>` | `--revision <rev>` (default `main`), `--engine <name>` | Download or update a model. |
104-| `rzb models rm <id>` | `-y`, `--yes`: do not ask (required without a terminal) | Delete a model from the cache. |
105-
106-The cache is `$HF_HUB_CACHE`, else `$HF_HOME/hub`, else `~/.cache/huggingface/hub`.
107-
108-## rzb config validate
57+| `rzb models list` | `--all`: also show repositories that are not loadable (GGUF, unfinished downloads), with a status column | Models in the cache, one per line: id, size, revisions. Prints the cache folder on standard error |
58+| `rzb models pull <id>` | `--revision <rev>` (default `main`), `--engine <name>` | Download or update a model (`*.safetensors`, `*.json`, `*.jinja`), with a progress bar |
59+| `rzb models rm <id>` | `-y`, `--yes`: do not ask (required without a terminal) | Delete a model from the cache |
10960
110-```
111-rzb config validate [<file>]
112-```
113-
114-Loads the file (default: the one `rzb` would use) and builds its tools. Prints `<file> is valid: agent "<name>", model <model>, tools: <names>` on standard output, or every problem found.
61+The cache is `$HF_HUB_CACHE`, else `$HF_HOME/hub`, else `~/.cache/huggingface/hub`, shared with the Python Hugging Face tools.
11562
11663 ## rzb version
11764
118-Prints `rzb 0.1.0 (engines: <names>)`. `rzb --version` prints `0.1.0`.
119-
120-## Output streams
121-
122-| Stream | Content |
123-| --- | --- |
124-| standard output | The answer (`run`, `chat`), `models list` lines, `config validate` result, version |
125-| standard error | Progress, prompts and questions, reasoning, tool calls (`→ bash command="…"`), tool results (`← bash: …`), statistics (`[N prompt tokens, N generated, N tokens/s]`), errors (`error: …`) |
126-
127-Colours and dimming are used only when standard error is a terminal and `NO_COLOR` is not set.
65+Prints `rzb 0.1.0 (engines: fake, mlx)` (the engines of this build, sorted). `rzb --version` prints `0.1.0`.
12866
12967 ## Exit codes
13068
13169 | Code | Meaning |
13270 | --- | --- |
133-| `0` | Success |
134-| `1` | Failure while running (model, download, tool, missing terminal) |
135-| `2` | Agent file missing or invalid |
71+| `0` | Success, or server stopped normally |
72+| `1` | Failure while running (download, model, port already in use…) |
73+| `2` | Configuration file missing or invalid |
13674 | `64` | Invalid command line |
13775 | `130` | Interrupted |
13876
@@ -140,6 +78,6 @@ Colours and dimming are used only when standard error is a terminal and `NO_COLO
14078
14179 | Variable | Effect |
14280 | --- | --- |
143-| `HF_HUB_CACHE`, `HF_HOME` | Location of the model cache. |
144-| `NO_COLOR` | Disables colours. |
145-| any `NAME` | Available to the system prompt as `{{env.NAME}}`; inherited by `bash` commands. |
81+| `RZB_API_KEY` (or the name given by `--api-key-env` / `server.api_key_env`) | API key of the server |
82+| `HF_HUB_CACHE`, `HF_HOME` | Location of the model cache |
83+| `NO_COLOR` | Disables colours on standard error |
@@ -1,6 +1,6 @@
1 # Reference: command line1 # Reference: command line
2 2
3-> Every `rzb` command, option, exit code and in-session command of razorbill 0.1.0.3+> Every `rzb` command, option and exit code of razorbill 0.1.0.
4 4
5 ```5 ```
6 rzb <command> [options]6 rzb <command> [options]
@@ -10,129 +10,67 @@ rzb help <command>
10 10
11 | Command | Purpose |11 | Command | Purpose |
12 | --- | --- |12 | --- | --- |
13-| [`rzb init`](#rzb-init) | Write an agent file with a wizard |13+| [`rzb serve`](#rzb-serve) | Start the OpenAI-compatible server |
14-| [`rzb run`](#rzb-run) | One answer, then exit |14+| [`rzb config validate`](#rzb-config-validate) | Check a server configuration file |
15-| [`rzb chat`](#rzb-chat) | Line-by-line conversation |
16-| [`rzb tui`](#rzb-tui) | Full-screen conversation |
17 | [`rzb models`](#rzb-models) | List, download, delete models |15 | [`rzb models`](#rzb-models) | List, download, delete models |
18-| [`rzb config validate`](#rzb-config-validate) | Check an agent file |
19 | [`rzb version`](#rzb-version) | Version and engines |16 | [`rzb version`](#rzb-version) | Version and engines |
20 17
21-## Agent options18+## rzb serve
22-
23-Shared by `run`, `chat` and `tui`. Each one overrides the matching value of the agent file for this run only.
24-
25-| Option | Type | Default | Description |
26-| --- | --- | --- | --- |
27-| `-c`, `--config <file>` | path | `./razorbill.yaml`, then `~/.config/razorbill/agent.yaml` | Agent file to load. |
28-| `-m`, `--model <model>` | id or path | the file's `model` | Hugging Face id, or a local directory when the value starts with `/`, `./`, `../` or `~/`. Revision `main`. |
29-| `--temperature <n>` | number ≥ 0 | the file's | Sampling temperature. |
30-| `--max-tokens <n>` | integer > 0 | the file's | Maximum tokens per answer. |
31-| `--think` / `--no-think` | flag | the file's | Sets `generation.thinking`. |
32-| `--thinking-budget <n>` | integer ≥ 0 | the file's | Sets `generation.thinking_budget`. |
33-| `--offline` | flag | off | Use only models already in the cache; never download. |
34-| `--engine <name>` | `mlx`, `fake` | the first engine of the build (`mlx` on the Mac) | Engine running the model. `fake` answers `echo: <prompt>` without a model. |
35-
36-## rzb init
37-
38-Writes an agent file. Interactive by default: agent name, description, model (downloaded ones first, then recommended ones, then any Hugging Face id or a local directory), system prompt, temperature, maximum tokens, thinking (then thinking budget and whether to show the reasoning), built-in tools, confirmation, optional download.
39-
40-| Option | Default | Description |
41-| --- | --- | --- |
42-| `-o`, `--output <file>` | `razorbill.yaml` | File to write. |
43-| `--force` | off | Overwrite an existing file without asking. |
44-| `--name <name>` | `assistant` | Agent name (default answer of the wizard). |
45-| `--model <model>` | `mlx-community/Qwen3-1.7B-4bit` | Model (id or directory). |
46-| `-y`, `--yes` | off | Ask nothing: use the options and the defaults. Required without a terminal. |
47-| `--no-download` | off | Do not offer to download the model. |
48-
49-The written file always loads: it is parsed before being saved.
50-
51-## rzb run
52 19
53 ```20 ```
54-rzb run [agent options] [<prompt> ...]21+rzb serve [--config <file>] [--host <address>] [--port <n>] [--api-key-env <name>] [--cors-origin <origin>]
55 ```22 ```
56 23
57-The words of the prompt are joined with spaces. When standard input is not a terminal, its content is appended after a blank line; the prompt may then be omitted. The answer goes to standard output; download progress, thinking, tool calls and statistics go to standard error.24+Starts the server and runs until Ctrl-C or SIGTERM; then it stops accepting requests, unloads the models and exits with code 0.
58 25
59-## rzb chat26+| Option | Type | Default | Description |
27+| --- | --- | --- | --- |
28+| `--config <file>` | path | none | Server configuration file ([reference](configuration.md)). Without it: no declared models, built-in defaults |
29+| `--host <address>` | string, not empty | `server.host`, else `127.0.0.1` | Address to listen on; `0.0.0.0` for every interface |
30+| `--port <n>` | integer, 1–65535 | `server.port`, else `8080` | TCP port |
31+| `--api-key-env <name>` | string | `server.api_key_env`, else `RZB_API_KEY` | Environment variable holding the API key. Set and not empty: every route but `/health` needs `Authorization: Bearer <key>` |
32+| `--cors-origin <origin>` | string | `server.cors_origin`, else none | Let browser pages from this origin call the API; `*` for any origin |
33+
34+Options win over the `server:` section of the file. On start it prints, on standard error:
60 35
61 ```36 ```
62-rzb chat [agent options]37+config: server.yaml (2 declared models)
38+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop
63 ```39 ```
64 40
65-Reads one message per line from standard input and streams each answer. A failed answer prints `error: …` and the conversation continues.41+The first line appears only with `--config`. Warnings (`warning: …`) are printed before the banner when the server listens on a network address without an API key, or allows every CORS origin without one. Then one log line per request: method, path, status, duration, and the model and token counts (`model=… tokens=<prompt>+<completion>`); prompts and answers are never logged.
66 42
67-| Input | Effect |43+The engine is the first one of the build: `mlx` on the Mac, `fake` on Linux (which answers `echo: <last message>` without a model).
68-| --- | --- |
69-| `/reset` | Start a new conversation (the model stays loaded). |
70-| `/help` | List these commands. |
71-| `/exit`, `/quit`, Ctrl-D | Quit. |
72-| empty line | Ignored. |
73 44
74-## rzb tui45+## rzb config validate
75 46
76 ```47 ```
77-rzb tui [agent options]48+rzb config validate <file>
78 ```49 ```
79 50
80-Full-screen conversation. Needs a terminal on standard input and standard output; otherwise it exits with `error: rzb tui needs a terminal; use rzb run or rzb chat instead`.51+Loads the file without starting anything. Prints `<file> is valid: 2 models (qwen3, embed), any Hugging Face MLX id accepted` on standard output, or every problem found with its line number ([format](configuration.md#errors)) and exit code 2.
81-
82-| Key | Effect |
83-| --- | --- |
84-| Enter | Send the input line (ignored while an answer is running). |
85-| Ctrl-C | Stop the running answer; quit when nothing runs. |
86-| Ctrl-D | Quit (when the input line is empty). |
87-| Ctrl-T | Show / hide the reasoning. |
88-| Ctrl-N | New conversation (when nothing runs). |
89-| PgUp / PgDn, ↑ / ↓ | Scroll the conversation. |
90-| ← / →, Home / End, Ctrl-A / Ctrl-E | Move in the input line. |
91-| Backspace / Delete, Ctrl-U | Delete a character / the whole line. |
92-| `y` / `n` | Answer a tool's confirmation (`n`, Enter, Esc and Ctrl-C refuse). |
93-
94-Commands typed in the input line: `/reset` or `/new` (new conversation), `/exit` or `/quit`.
95-
96-The title bar shows the agent, the model, the engine, then `● answering` or the last speed in tokens/s. The terminal is restored on exit, including on SIGTERM, SIGHUP and SIGQUIT.
97 52
98 ## rzb models53 ## rzb models
99 54
100 | Command | Arguments and options | Description |55 | Command | Arguments and options | Description |
101 | --- | --- | --- |56 | --- | --- | --- |
102-| `rzb models list` | `--all`: also show repositories that are not loadable (GGUF, unfinished downloads), with a status column | Models in the cache: id, size, revisions. Prints the cache folder on standard error. |57+| `rzb models list` | `--all`: also show repositories that are not loadable (GGUF, unfinished downloads), with a status column | Models in the cache, one per line: id, size, revisions. Prints the cache folder on standard error |
103-| `rzb models pull <id>` | `--revision <rev>` (default `main`), `--engine <name>` | Download or update a model. |58+| `rzb models pull <id>` | `--revision <rev>` (default `main`), `--engine <name>` | Download or update a model (`*.safetensors`, `*.json`, `*.jinja`), with a progress bar |
104-| `rzb models rm <id>` | `-y`, `--yes`: do not ask (required without a terminal) | Delete a model from the cache. |59+| `rzb models rm <id>` | `-y`, `--yes`: do not ask (required without a terminal) | Delete a model from the cache |
105-
106-The cache is `$HF_HUB_CACHE`, else `$HF_HOME/hub`, else `~/.cache/huggingface/hub`.
107-
108-## rzb config validate
109 60
110-```61+The cache is `$HF_HUB_CACHE`, else `$HF_HOME/hub`, else `~/.cache/huggingface/hub`, shared with the Python Hugging Face tools.
111-rzb config validate [<file>]
112-```
113-
114-Loads the file (default: the one `rzb` would use) and builds its tools. Prints `<file> is valid: agent "<name>", model <model>, tools: <names>` on standard output, or every problem found.
115 62
116 ## rzb version63 ## rzb version
117 64
118-Prints `rzb 0.1.0 (engines: <names>)`. `rzb --version` prints `0.1.0`.65+Prints `rzb 0.1.0 (engines: fake, mlx)` (the engines of this build, sorted). `rzb --version` prints `0.1.0`.
119-
120-## Output streams
121-
122-| Stream | Content |
123-| --- | --- |
124-| standard output | The answer (`run`, `chat`), `models list` lines, `config validate` result, version |
125-| standard error | Progress, prompts and questions, reasoning, tool calls (`→ bash command="…"`), tool results (`← bash: …`), statistics (`[N prompt tokens, N generated, N tokens/s]`), errors (`error: …`) |
126-
127-Colours and dimming are used only when standard error is a terminal and `NO_COLOR` is not set.
128 66
129 ## Exit codes67 ## Exit codes
130 68
131 | Code | Meaning |69 | Code | Meaning |
132 | --- | --- |70 | --- | --- |
133-| `0` | Success |71+| `0` | Success, or server stopped normally |
134-| `1` | Failure while running (model, download, tool, missing terminal) |72+| `1` | Failure while running (download, model, port already in use…) |
135-| `2` | Agent file missing or invalid |73+| `2` | Configuration file missing or invalid |
136 | `64` | Invalid command line |74 | `64` | Invalid command line |
137 | `130` | Interrupted |75 | `130` | Interrupted |
138 76
@@ -140,6 +78,6 @@ Colours and dimming are used only when standard error is a terminal and `NO_COLO
140 78
141 | Variable | Effect |79 | Variable | Effect |
142 | --- | --- |80 | --- | --- |
143-| `HF_HUB_CACHE`, `HF_HOME` | Location of the model cache. |81+| `RZB_API_KEY` (or the name given by `--api-key-env` / `server.api_key_env`) | API key of the server |
144-| `NO_COLOR` | Disables colours. |82+| `HF_HUB_CACHE`, `HF_HOME` | Location of the model cache |
145-| any `NAME` | Available to the system prompt as `{{env.NAME}}`; inherited by `bash` commands. |83+| `NO_COLOR` | Disables colours on standard error |
modified docs/en/reference/configuration.md +88 -103
@@ -1,138 +1,123 @@
1-# Reference: agent file
1+# Reference: server configuration file
22
3-> The YAML file that describes one agent: keys, types, defaults, variables, lookup and errors. razorbill 0.1.0.
3+> Every key of the YAML file given to `rzb serve --config <file>`, its type, default and checks. Check a file without starting the server with `rzb config validate <file>`. A commented example is in [`examples/server.yaml`](../../../examples/server.yaml).
44
5-## Lookup
6-
7-One file describes one agent. `rzb` uses, in this order:
8-
9-1. the file given with `-c` / `--config`;
10-2. `./razorbill.yaml` in the current directory;
11-3. `~/.config/razorbill/agent.yaml`.
12-
13-If none exists: `error: no agent configuration found (searched: …). Create one with rzb init.` (exit code 2).
14-
15-## Example
5+Every section is optional; an empty file, or no file at all, is a valid configuration. Unknown keys are errors. Every problem of a file is reported at once, with its key path and line number; the exit code is then 2.
166
177 ```yaml
18-name: swift-helper
19-description: Helps with Swift questions
20-model:
21- id: mlx-community/Qwen3-1.7B-4bit
22- revision: main
23-generation:
8+server:
9+ host: 127.0.0.1
10+ port: 8080
11+ api_key_env: RZB_API_KEY
12+defaults:
2413 temperature: 0.6
25- top_p: 1.0
26- max_tokens: 1024
27- thinking: false
28- thinking_budget: 512
29-system: |
30- You are a concise Swift expert. Today is {{date}}.
31-tools:
32- bash:
33- confirm: true
34-ui:
35- show_stats: true
36- show_thinking: true
14+ max_tokens: 2048
15+locked:
16+ max_tokens: 8192
17+models:
18+ - id: qwen3
19+ source: mlx-community/Qwen3-4B-4bit
20+ defaults: { thinking: true, thinking_budget: 512 }
21+ - id: embed
22+ source: BAAI/bge-small-en-v1.5
23+ kind: embedding
24+ preload: true
25+limits:
26+ max_loaded_models: 2
27+ keep_alive: 10m
28+ max_queue: 16
3729 ```
3830
39-The repository's [examples/agent.yaml](../../../examples/agent.yaml) is the same file with a comment on each key.
40-
4131 ## Top-level keys
4232
43-| Key | Type | Required | Default | Description |
44-| --- | --- | --- | --- | --- |
45-| `name` | text, not empty | yes | — | Agent name, shown in `chat` and `tui`. |
46-| `description` | text | no | none | Free description. |
47-| [`model`](#model) | text or mapping | yes | — | The model the agent runs. |
48-| [`generation`](#generation) | mapping | no | see below | Sampling and thinking settings. |
49-| [`system`](#system) | text | no | empty | System prompt, with [variables](#variables). |
50-| [`tools`](#tools) | mapping or list | no | no tools | Built-in tools the model may call. |
51-| [`ui`](#ui) | mapping | no | see below | Display settings. |
52-
53-Any other key is an error.
33+| Key | Type | Description |
34+| --- | --- | --- |
35+| `server` | mapping | Network settings ([server](#server)) |
36+| `defaults` | mapping | Generation settings every model starts from ([defaults and locked](#defaults-and-locked)) |
37+| `locked` | mapping | Generation settings clients cannot change or exceed |
38+| `models` | list | Models declared by name ([models](#models)) |
39+| `limits` | mapping | Memory and queue limits ([limits](#limits)) |
5440
55-## model
41+## server
5642
57-Either a Hugging Face id as text, or a mapping with exactly one of `id` and `path`.
43+Command-line options win over these keys ([`rzb serve`](cli.md#rzb-serve)).
5844
5945 | Key | Type | Default | Description |
6046 | --- | --- | --- | --- |
61-| `id` | text | — | Hugging Face repository of an MLX model, e.g. `mlx-community/Qwen3-1.7B-4bit`. |
62-| `revision` | text | `main` | Branch, tag or commit. Only with `id`. |
63-| `path` | text | — | Local directory with the model's `config.json`, tokenizer and `*.safetensors`. `~` is expanded; a relative path starts at the agent file's folder. |
47+| `host` | string, not empty | `127.0.0.1` | Address to listen on; `0.0.0.0` for every interface |
48+| `port` | integer, 1–65535 | `8080` | TCP port |
49+| `api_key_env` | string, not empty | `RZB_API_KEY` | Name of the environment variable holding the API key. The key itself never goes in the file. When the variable is set and not empty, every route except `/health` needs `Authorization: Bearer <key>` |
50+| `cors_origin` | string, not empty | none (CORS off) | Origin allowed to call the API from a browser; `*` for any origin |
6451
65-```yaml
66-model: mlx-community/Qwen3-1.7B-4bit # short form, revision main
67-```
68-
69-## generation
52+Warnings at start-up: listening on a non-loopback address without an API key; `cors_origin: "*"` without an API key.
7053
71-| Key | Type | Default | Constraint | Description |
72-| --- | --- | --- | --- | --- |
73-| `temperature` | number | `0.6` | ≥ 0 | Sampling temperature; `0` is deterministic. |
74-| `top_p` | number | `1.0` | in (0, 1] | Nucleus sampling threshold; `1` disables it. |
75-| `max_tokens` | integer | `1024` | > 0 | Maximum tokens generated per answer, reasoning included. |
76-| `thinking` | boolean | `false` | — | Lets reasoning models think before answering (`enable_thinking` in their chat template). |
77-| `thinking_budget` | integer | none (no limit) | ≥ 0 and < `max_tokens` | Maximum reasoning tokens; then the model is made to answer. Applies only when `thinking` is true. Fails at start for a model without a known reasoning protocol. |
54+## defaults and locked
7855
79-## system
56+The same keys, in the top-level `defaults` / `locked` and in each model's `defaults` / `locked`.
8057
81-Text sent as the system message of every conversation. Use a block scalar (`|`) for several lines. [Variables](#variables) are replaced when the file is loaded.
82-
83-## Variables
84-
85-| Variable | Value |
86-| --- | --- |
87-| `{{date}}` | Today's date, `YYYY-MM-DD`. |
88-| `{{cwd}}` | The directory `rzb` was started from. |
89-| `{{env.NAME}}` | The value of the environment variable `NAME`. |
90-
91-Spaces inside the braces are allowed (`{{ date }}`). An unknown variable or an unset environment variable is an error at key `system`.
58+| Key | Type | Built-in default | In `locked` |
59+| --- | --- | --- | --- |
60+| `temperature` | number, 0–2 | `0.6` | imposed |
61+| `top_p` | number, >0–1 | `1.0` | imposed |
62+| `max_tokens` | integer ≥ 1 | `1024` | ceiling (a smaller request is kept) |
63+| `thinking` | boolean | `false` | imposed |
64+| `thinking_budget` | integer ≥ 0, smaller than `max_tokens` of the same block | none (no limit) | ceiling |
65+| `show_reasoning` | boolean | `true` | imposed |
9266
93-## tools
67+- `thinking`: whether a reasoning model (Qwen3…) thinks before answering. Models that do not reason ignore it.
68+- `thinking_budget`: most tokens of reasoning; the model is then made to answer. Refused at request time (400) for models with no known reasoning protocol.
69+- `show_reasoning`: send the reasoning to clients (`reasoning_content`). With `false`, the model still thinks and `reasoning_tokens` still counts it.
9470
95-Built-in tools are enabled by being listed; nothing is enabled by default. Two forms:
71+The settings of a request are computed in this order, each step replacing the previous values it sets: built-in defaults → top-level `defaults` → the model's `defaults` → the request's fields → top-level `locked` → the model's `locked`. Models used by their Hugging Face id (not declared) get only the top-level blocks.
9672
97-```yaml
98-tools: # mapping: name → options (empty mapping or nothing for the defaults)
99- bash:
100- confirm: true
101-```
73+## models
10274
103-```yaml
104-tools: [bash] # list of names, default options
105-```
75+A list of entries. Clients may also use any Hugging Face id in MLX format without declaring it.
10676
107-| Tool | Options |
108-| --- | --- |
109-| `bash` | [bash tool reference](bash-tool.md) |
110-
111-An unknown tool name or option is an error at `tools.<name>` or `tools.<name>.<option>`.
77+| Key | Type | Default | Description |
78+| --- | --- | --- | --- |
79+| `id` | string, not empty, unique | required | The name clients send as `"model"` |
80+| `source` | string | one of `source` / `path` required | Hugging Face id, `org/name` |
81+| `revision` | string | `main` | Branch, tag or commit of `source`; not allowed with `path` |
82+| `path` | string | — | Directory of a model on disk (`config.json`, tokenizer, `*.safetensors`); `~` is expanded, a relative path starts at the configuration file's folder |
83+| `kind` | `chat` or `embedding` | `chat` | Which endpoints the model serves |
84+| `preload` | boolean | `false` | Load at start-up instead of on the first request |
85+| `defaults` | mapping | none | Generation defaults for this model ([keys](#defaults-and-locked)) |
86+| `locked` | mapping | none | Locked settings for this model |
11287
113-## ui
88+## limits
11489
11590 | Key | Type | Default | Description |
11691 | --- | --- | --- | --- |
117-| `show_stats` | boolean | `true` | Print token counts and speed after each answer (`run`, `chat`, `tui`). |
118-| `show_thinking` | boolean | `true` | Show the reasoning when the model thinks: dimmed on standard error in `run` and `chat`; initial state of Ctrl-T in `tui`. |
92+| `max_loaded_models` | integer ≥ 1 | `1` | Models kept in memory at once; beyond it, the least recently used idle model is unloaded |
93+| `keep_alive` | duration (`30s`, `10m`, `1h`) | `10m` | An idle model is unloaded after this long |
94+| `max_queue` | integer ≥ 1 | `16` | Requests waiting for one model; more get a 429 |
95+
96+Besides these limits, the weights loaded at once may not exceed 75 % of the Mac's memory: a model that cannot fit after unloading idle models gets a 503.
11997
12098 ## Errors
12199
122-Every problem is reported at once, with its line when known, and `rzb` exits with code 2:
100+Problems are printed together, then `rzb` exits with code 2:
123101
124102 ```
125-error: invalid configuration razorbill.yaml
126- - line 4: generation.temprature: unknown key (expected one of: temperature, top_p, max_tokens, thinking, thinking_budget)
127- - line 7: generation.thinking_budget: must be smaller than max_tokens (1024), which also counts the answer
103+error: invalid configuration server.yaml
104+ - line 3: server.port: must be between 1 and 65535
105+ - line 9: models[0].kind: must be one of: chat, embedding
128106 ```
129107
130-| Problem | Example message |
108+| Message (after `line N: <key path>:`) | Cause |
131109 | --- | --- |
132-| Missing required key | `name: is required` |
133-| Unknown key | `unknown key (expected one of: …)` |
134-| Wrong type | `must be text`, `must be a number`, `must be a whole number`, `must be true or false`, `must be a mapping (key: value lines)` |
135-| Value out of range | `must be 0 or more`, `must be in (0, 1]`, `must be more than 0` |
136-| Both or neither of `model.id` and `model.path` | `give either id or path, not both` |
137-| Unresolved variable | `{{env.TOKEN}}: environment variable TOKEN is not set`, `{{x}}: unknown variable (use date, cwd or env.NAME)` |
138-| Unknown tool | `unknown tool (available: bash)` |
110+| `unknown key (expected one of: …)` | Misspelt or unsupported key |
111+| `must be between 1 and 65535` | `server.port` out of range |
112+| `must be between 0 and 2`, `must be above 0 and at most 1`, … | Value out of range |
113+| `must be smaller than max_tokens (N)` | `thinking_budget` not below the `max_tokens` of the same block |
114+| `must be a duration such as 30s, 10m or 1h` | Unreadable `keep_alive` |
115+| `must be a list (lines starting with -)` | `models` is not a list |
116+| `is required (the name clients send as "model")` | Model entry without `id` |
117+| `duplicate id <id>` | Two entries with the same `id` |
118+| `is required (a Hugging Face id, or path:)` | Neither `source` nor `path` |
119+| `give either source or path, not both` | Both given |
120+| `only applies to source` | `revision` with `path` |
121+| `must be one of: chat, embedding` | Unknown `kind` |
122+| `not valid YAML: …` | Syntax error |
123+| `cannot read the file` | Missing or unreadable file |
@@ -1,138 +1,123 @@
1-# Reference: agent file1+# Reference: server configuration file
2 2
3-> The YAML file that describes one agent: keys, types, defaults, variables, lookup and errors. razorbill 0.1.0.3+> Every key of the YAML file given to `rzb serve --config <file>`, its type, default and checks. Check a file without starting the server with `rzb config validate <file>`. A commented example is in [`examples/server.yaml`](../../../examples/server.yaml).
4 4
5-## Lookup5+Every section is optional; an empty file, or no file at all, is a valid configuration. Unknown keys are errors. Every problem of a file is reported at once, with its key path and line number; the exit code is then 2.
6-
7-One file describes one agent. `rzb` uses, in this order:
8-
9-1. the file given with `-c` / `--config`;
10-2. `./razorbill.yaml` in the current directory;
11-3. `~/.config/razorbill/agent.yaml`.
12-
13-If none exists: `error: no agent configuration found (searched: …). Create one with rzb init.` (exit code 2).
14-
15-## Example
16 6
17 ```yaml7 ```yaml
18-name: swift-helper8+server:
19-description: Helps with Swift questions9+ host: 127.0.0.1
20-model:10+ port: 8080
21- id: mlx-community/Qwen3-1.7B-4bit11+ api_key_env: RZB_API_KEY
22- revision: main12+defaults:
23-generation:
24 temperature: 0.613 temperature: 0.6
25- top_p: 1.014+ max_tokens: 2048
26- max_tokens: 102415+locked:
27- thinking: false16+ max_tokens: 8192
28- thinking_budget: 51217+models:
29-system: |18+ - id: qwen3
30- You are a concise Swift expert. Today is {{date}}.19+ source: mlx-community/Qwen3-4B-4bit
31-tools:20+ defaults: { thinking: true, thinking_budget: 512 }
32- bash:21+ - id: embed
33- confirm: true22+ source: BAAI/bge-small-en-v1.5
34-ui:23+ kind: embedding
35- show_stats: true24+ preload: true
36- show_thinking: true25+limits:
26+ max_loaded_models: 2
27+ keep_alive: 10m
28+ max_queue: 16
37 ```29 ```
38 30
39-The repository's [examples/agent.yaml](../../../examples/agent.yaml) is the same file with a comment on each key.
40-
41 ## Top-level keys31 ## Top-level keys
42 32
43-| Key | Type | Required | Default | Description |33+| Key | Type | Description |
44-| --- | --- | --- | --- | --- |34+| --- | --- | --- |
45-| `name` | text, not empty | yes | — | Agent name, shown in `chat` and `tui`. |35+| `server` | mapping | Network settings ([server](#server)) |
46-| `description` | text | no | none | Free description. |36+| `defaults` | mapping | Generation settings every model starts from ([defaults and locked](#defaults-and-locked)) |
47-| [`model`](#model) | text or mapping | yes | — | The model the agent runs. |37+| `locked` | mapping | Generation settings clients cannot change or exceed |
48-| [`generation`](#generation) | mapping | no | see below | Sampling and thinking settings. |38+| `models` | list | Models declared by name ([models](#models)) |
49-| [`system`](#system) | text | no | empty | System prompt, with [variables](#variables). |39+| `limits` | mapping | Memory and queue limits ([limits](#limits)) |
50-| [`tools`](#tools) | mapping or list | no | no tools | Built-in tools the model may call. |
51-| [`ui`](#ui) | mapping | no | see below | Display settings. |
52-
53-Any other key is an error.
54 40
55-## model41+## server
56 42
57-Either a Hugging Face id as text, or a mapping with exactly one of `id` and `path`.43+Command-line options win over these keys ([`rzb serve`](cli.md#rzb-serve)).
58 44
59 | Key | Type | Default | Description |45 | Key | Type | Default | Description |
60 | --- | --- | --- | --- |46 | --- | --- | --- | --- |
61-| `id` | text | — | Hugging Face repository of an MLX model, e.g. `mlx-community/Qwen3-1.7B-4bit`. |47+| `host` | string, not empty | `127.0.0.1` | Address to listen on; `0.0.0.0` for every interface |
62-| `revision` | text | `main` | Branch, tag or commit. Only with `id`. |48+| `port` | integer, 1–65535 | `8080` | TCP port |
63-| `path` | text | — | Local directory with the model's `config.json`, tokenizer and `*.safetensors`. `~` is expanded; a relative path starts at the agent file's folder. |49+| `api_key_env` | string, not empty | `RZB_API_KEY` | Name of the environment variable holding the API key. The key itself never goes in the file. When the variable is set and not empty, every route except `/health` needs `Authorization: Bearer <key>` |
50+| `cors_origin` | string, not empty | none (CORS off) | Origin allowed to call the API from a browser; `*` for any origin |
64 51
65-```yaml52+Warnings at start-up: listening on a non-loopback address without an API key; `cors_origin: "*"` without an API key.
66-model: mlx-community/Qwen3-1.7B-4bit # short form, revision main
67-```
68-
69-## generation
70 53
71-| Key | Type | Default | Constraint | Description |54+## defaults and locked
72-| --- | --- | --- | --- | --- |
73-| `temperature` | number | `0.6` | ≥ 0 | Sampling temperature; `0` is deterministic. |
74-| `top_p` | number | `1.0` | in (0, 1] | Nucleus sampling threshold; `1` disables it. |
75-| `max_tokens` | integer | `1024` | > 0 | Maximum tokens generated per answer, reasoning included. |
76-| `thinking` | boolean | `false` | — | Lets reasoning models think before answering (`enable_thinking` in their chat template). |
77-| `thinking_budget` | integer | none (no limit) | ≥ 0 and < `max_tokens` | Maximum reasoning tokens; then the model is made to answer. Applies only when `thinking` is true. Fails at start for a model without a known reasoning protocol. |
78 55
79-## system56+The same keys, in the top-level `defaults` / `locked` and in each model's `defaults` / `locked`.
80 57
81-Text sent as the system message of every conversation. Use a block scalar (`|`) for several lines. [Variables](#variables) are replaced when the file is loaded.58+| Key | Type | Built-in default | In `locked` |
82-59+| --- | --- | --- | --- |
83-## Variables60+| `temperature` | number, 0–2 | `0.6` | imposed |
84-61+| `top_p` | number, >0–1 | `1.0` | imposed |
85-| Variable | Value |62+| `max_tokens` | integer ≥ 1 | `1024` | ceiling (a smaller request is kept) |
86-| --- | --- |63+| `thinking` | boolean | `false` | imposed |
87-| `{{date}}` | Today's date, `YYYY-MM-DD`. |64+| `thinking_budget` | integer ≥ 0, smaller than `max_tokens` of the same block | none (no limit) | ceiling |
88-| `{{cwd}}` | The directory `rzb` was started from. |65+| `show_reasoning` | boolean | `true` | imposed |
89-| `{{env.NAME}}` | The value of the environment variable `NAME`. |
90-
91-Spaces inside the braces are allowed (`{{ date }}`). An unknown variable or an unset environment variable is an error at key `system`.
92 66
93-## tools67+- `thinking`: whether a reasoning model (Qwen3…) thinks before answering. Models that do not reason ignore it.
68+- `thinking_budget`: most tokens of reasoning; the model is then made to answer. Refused at request time (400) for models with no known reasoning protocol.
69+- `show_reasoning`: send the reasoning to clients (`reasoning_content`). With `false`, the model still thinks and `reasoning_tokens` still counts it.
94 70
95-Built-in tools are enabled by being listed; nothing is enabled by default. Two forms:71+The settings of a request are computed in this order, each step replacing the previous values it sets: built-in defaults → top-level `defaults` → the model's `defaults` → the request's fields → top-level `locked` → the model's `locked`. Models used by their Hugging Face id (not declared) get only the top-level blocks.
96 72
97-```yaml73+## models
98-tools: # mapping: name → options (empty mapping or nothing for the defaults)
99- bash:
100- confirm: true
101-```
102 74
103-```yaml75+A list of entries. Clients may also use any Hugging Face id in MLX format without declaring it.
104-tools: [bash] # list of names, default options
105-```
106 76
107-| Tool | Options |77+| Key | Type | Default | Description |
108-| --- | --- |78+| --- | --- | --- | --- |
109-| `bash` | [bash tool reference](bash-tool.md) |79+| `id` | string, not empty, unique | required | The name clients send as `"model"` |
110-80+| `source` | string | one of `source` / `path` required | Hugging Face id, `org/name` |
111-An unknown tool name or option is an error at `tools.<name>` or `tools.<name>.<option>`.81+| `revision` | string | `main` | Branch, tag or commit of `source`; not allowed with `path` |
82+| `path` | string | — | Directory of a model on disk (`config.json`, tokenizer, `*.safetensors`); `~` is expanded, a relative path starts at the configuration file's folder |
83+| `kind` | `chat` or `embedding` | `chat` | Which endpoints the model serves |
84+| `preload` | boolean | `false` | Load at start-up instead of on the first request |
85+| `defaults` | mapping | none | Generation defaults for this model ([keys](#defaults-and-locked)) |
86+| `locked` | mapping | none | Locked settings for this model |
112 87
113-## ui88+## limits
114 89
115 | Key | Type | Default | Description |90 | Key | Type | Default | Description |
116 | --- | --- | --- | --- |91 | --- | --- | --- | --- |
117-| `show_stats` | boolean | `true` | Print token counts and speed after each answer (`run`, `chat`, `tui`). |92+| `max_loaded_models` | integer ≥ 1 | `1` | Models kept in memory at once; beyond it, the least recently used idle model is unloaded |
118-| `show_thinking` | boolean | `true` | Show the reasoning when the model thinks: dimmed on standard error in `run` and `chat`; initial state of Ctrl-T in `tui`. |93+| `keep_alive` | duration (`30s`, `10m`, `1h`) | `10m` | An idle model is unloaded after this long |
94+| `max_queue` | integer ≥ 1 | `16` | Requests waiting for one model; more get a 429 |
95+
96+Besides these limits, the weights loaded at once may not exceed 75 % of the Mac's memory: a model that cannot fit after unloading idle models gets a 503.
119 97
120 ## Errors98 ## Errors
121 99
122-Every problem is reported at once, with its line when known, and `rzb` exits with code 2:100+Problems are printed together, then `rzb` exits with code 2:
123 101
124 ```102 ```
125-error: invalid configuration razorbill.yaml103+error: invalid configuration server.yaml
126- - line 4: generation.temprature: unknown key (expected one of: temperature, top_p, max_tokens, thinking, thinking_budget)104+ - line 3: server.port: must be between 1 and 65535
127- - line 7: generation.thinking_budget: must be smaller than max_tokens (1024), which also counts the answer105+ - line 9: models[0].kind: must be one of: chat, embedding
128 ```106 ```
129 107
130-| Problem | Example message |108+| Message (after `line N: <key path>:`) | Cause |
131 | --- | --- |109 | --- | --- |
132-| Missing required key | `name: is required` |110+| `unknown key (expected one of: …)` | Misspelt or unsupported key |
133-| Unknown key | `unknown key (expected one of: …)` |111+| `must be between 1 and 65535` | `server.port` out of range |
134-| Wrong type | `must be text`, `must be a number`, `must be a whole number`, `must be true or false`, `must be a mapping (key: value lines)` |112+| `must be between 0 and 2`, `must be above 0 and at most 1`, … | Value out of range |
135-| Value out of range | `must be 0 or more`, `must be in (0, 1]`, `must be more than 0` |113+| `must be smaller than max_tokens (N)` | `thinking_budget` not below the `max_tokens` of the same block |
136-| Both or neither of `model.id` and `model.path` | `give either id or path, not both` |114+| `must be a duration such as 30s, 10m or 1h` | Unreadable `keep_alive` |
137-| Unresolved variable | `{{env.TOKEN}}: environment variable TOKEN is not set`, `{{x}}: unknown variable (use date, cwd or env.NAME)` |115+| `must be a list (lines starting with -)` | `models` is not a list |
138-| Unknown tool | `unknown tool (available: bash)` |116+| `is required (the name clients send as "model")` | Model entry without `id` |
117+| `duplicate id <id>` | Two entries with the same `id` |
118+| `is required (a Hugging Face id, or path:)` | Neither `source` nor `path` |
119+| `give either source or path, not both` | Both given |
120+| `only applies to source` | `revision` with `path` |
121+| `must be one of: chat, embedding` | Unknown `kind` |
122+| `not valid YAML: …` | Syntax error |
123+| `cannot read the file` | Missing or unreadable file |
added docs/en/reference/errors.md +59 -0
new file mode 100644
@@ -0,0 +1,59 @@
1+# Reference: API errors
2+
3+> The error body of `rzb serve` and every status, type and code it uses.
4+
5+Every error is a JSON body in OpenAI's shape, so OpenAI clients raise their usual exceptions (`openai.BadRequestError`, `openai.NotFoundError`…):
6+
7+```json
8+{"error": {"message": "temperature must be between 0 and 2.", "type": "invalid_request_error", "param": "temperature", "code": null}}
9+```
10+
11+| Field | Value |
12+| --- | --- |
13+| `message` | What is wrong, in plain words |
14+| `type` | Derived from the status (table below) |
15+| `param` | The request field at fault (`temperature`, `messages[2].content`, `response_format.json_schema.schema`…), or `null` |
16+| `code` | A stable code for some errors (table below), or `null` |
17+
18+During a stream, an error after the first chunk is sent as a last event, `data: {"error": {…}}`, and the stream ends without `[DONE]`.
19+
20+## Status and type
21+
22+| Status | `type` | When |
23+| --- | --- | --- |
24+| 400 | `invalid_request_error` | Malformed JSON, wrong type, value out of range, refused field, unsupported constraint, wrong model kind, input too long |
25+| 401 | `invalid_request_error` | Missing or wrong API key |
26+| 404 | `invalid_request_error` | Unknown model or unknown URL |
27+| 413 | `invalid_request_error` | Body larger than 16 MiB |
28+| 429 | `rate_limit_error` | Too many requests waiting for one model |
29+| 499 | — | The client closed the connection (written in the log only; the client is gone) |
30+| 500 | `server_error` | The model could not be loaded, or an unexpected error (no details are leaked) |
31+| 503 | `server_error` | No room to load the model now |
32+
33+## Codes
34+
35+| Code | Status | Message (example) | Cause |
36+| --- | --- | --- | --- |
37+| `invalid_api_key` | 401 | `Incorrect or missing API key. Send it as 'Authorization: Bearer <key>'.` | `Authorization: Bearer` missing or different from the server's key |
38+| `model_not_found` | 404 | `The model 'qwen9' does not exist.` | Neither a declared `id` nor a Hugging Face id `org/name` |
39+| `unknown_url` | 404 | `Invalid URL (GET /v1/nothing)` | No such endpoint |
40+| `model_not_supported` | 400 | `the model 'org/name' is not in MLX format (no .safetensors weights)` | The cached repository has no MLX weights (GGUF…) |
41+| `queue_full` | 429 | `too many requests waiting for 'qwen3' (max_queue: 16); retry later` | More than `limits.max_queue` requests waiting |
42+| `server_busy` | 503 | `cannot load 'qwen3': every loaded model is busy (max_loaded_models reached); retry later` | Every loaded model is answering and `max_loaded_models` is reached |
43+| `insufficient_memory` | 503 | `'org/big' needs about 40.0 GB of memory, only 24.0 GB can be freed for it` | The weights exceed what can be freed within 75 % of the memory |
44+| `model_load_failed` | 500 | `cannot load 'qwen3': …` | Download or load failure |
45+
46+## Common 400 messages
47+
48+| `param` | Message (example) |
49+| --- | --- |
50+| a field | `<field> must be between 0 and 2.`, `n must be 1 (one choice per request).`, `logprobs is not supported yet.` |
51+| `model` | `'embed' is a embedding model; this endpoint needs a chat model` |
52+| `messages[i].role` | `'function' is not a supported role …` |
53+| `messages[i].content` | `Content parts of type 'image_url' are not supported (only text, this model takes no images).` |
54+| `response_format.json_schema.schema` | `… uses 'uniqueItems' (at properties.tags), which strict mode cannot enforce; remove it or set strict to false.` |
55+| `tool_choice` | `tool_choice names nope, which is not in tools.` |
56+| `tool_choice` | `constrained tool calls are not supported for this model's tool-call syntax (llama3); only the <tool_call> JSON syntax (Qwen, Hermes…) is` |
57+| `thinking_budget` | `<model> has no known thinking protocol, so a thinking budget cannot be enforced: remove thinking_budget` |
58+| `input` | `input[1] has 3002 tokens; this model accepts at most 512` |
59+| `dimensions` | `dimensions 1000 is larger than this model's 384.` |
new file mode 100644
@@ -0,0 +1,59 @@
1+# Reference: API errors
2+
3+> The error body of `rzb serve` and every status, type and code it uses.
4+
5+Every error is a JSON body in OpenAI's shape, so OpenAI clients raise their usual exceptions (`openai.BadRequestError`, `openai.NotFoundError`…):
6+
7+```json
8+{"error": {"message": "temperature must be between 0 and 2.", "type": "invalid_request_error", "param": "temperature", "code": null}}
9+```
10+
11+| Field | Value |
12+| --- | --- |
13+| `message` | What is wrong, in plain words |
14+| `type` | Derived from the status (table below) |
15+| `param` | The request field at fault (`temperature`, `messages[2].content`, `response_format.json_schema.schema`…), or `null` |
16+| `code` | A stable code for some errors (table below), or `null` |
17+
18+During a stream, an error after the first chunk is sent as a last event, `data: {"error": {…}}`, and the stream ends without `[DONE]`.
19+
20+## Status and type
21+
22+| Status | `type` | When |
23+| --- | --- | --- |
24+| 400 | `invalid_request_error` | Malformed JSON, wrong type, value out of range, refused field, unsupported constraint, wrong model kind, input too long |
25+| 401 | `invalid_request_error` | Missing or wrong API key |
26+| 404 | `invalid_request_error` | Unknown model or unknown URL |
27+| 413 | `invalid_request_error` | Body larger than 16 MiB |
28+| 429 | `rate_limit_error` | Too many requests waiting for one model |
29+| 499 | — | The client closed the connection (written in the log only; the client is gone) |
30+| 500 | `server_error` | The model could not be loaded, or an unexpected error (no details are leaked) |
31+| 503 | `server_error` | No room to load the model now |
32+
33+## Codes
34+
35+| Code | Status | Message (example) | Cause |
36+| --- | --- | --- | --- |
37+| `invalid_api_key` | 401 | `Incorrect or missing API key. Send it as 'Authorization: Bearer <key>'.` | `Authorization: Bearer` missing or different from the server's key |
38+| `model_not_found` | 404 | `The model 'qwen9' does not exist.` | Neither a declared `id` nor a Hugging Face id `org/name` |
39+| `unknown_url` | 404 | `Invalid URL (GET /v1/nothing)` | No such endpoint |
40+| `model_not_supported` | 400 | `the model 'org/name' is not in MLX format (no .safetensors weights)` | The cached repository has no MLX weights (GGUF…) |
41+| `queue_full` | 429 | `too many requests waiting for 'qwen3' (max_queue: 16); retry later` | More than `limits.max_queue` requests waiting |
42+| `server_busy` | 503 | `cannot load 'qwen3': every loaded model is busy (max_loaded_models reached); retry later` | Every loaded model is answering and `max_loaded_models` is reached |
43+| `insufficient_memory` | 503 | `'org/big' needs about 40.0 GB of memory, only 24.0 GB can be freed for it` | The weights exceed what can be freed within 75 % of the memory |
44+| `model_load_failed` | 500 | `cannot load 'qwen3': …` | Download or load failure |
45+
46+## Common 400 messages
47+
48+| `param` | Message (example) |
49+| --- | --- |
50+| a field | `<field> must be between 0 and 2.`, `n must be 1 (one choice per request).`, `logprobs is not supported yet.` |
51+| `model` | `'embed' is a embedding model; this endpoint needs a chat model` |
52+| `messages[i].role` | `'function' is not a supported role …` |
53+| `messages[i].content` | `Content parts of type 'image_url' are not supported (only text, this model takes no images).` |
54+| `response_format.json_schema.schema` | `… uses 'uniqueItems' (at properties.tags), which strict mode cannot enforce; remove it or set strict to false.` |
55+| `tool_choice` | `tool_choice names nope, which is not in tools.` |
56+| `tool_choice` | `constrained tool calls are not supported for this model's tool-call syntax (llama3); only the <tool_call> JSON syntax (Qwen, Hermes…) is` |
57+| `thinking_budget` | `<model> has no known thinking protocol, so a thinking budget cannot be enforced: remove thinking_budget` |
58+| `input` | `input[1] has 3002 tokens; this model accepts at most 512` |
59+| `dimensions` | `dimensions 1000 is larger than this model's 384.` |
added docs/en/reference/http-api.md +295 -0
new file mode 100644
@@ -0,0 +1,295 @@
1+# Reference: HTTP API
2+
3+> The endpoints of `rzb serve`, the fields each one accepts, refuses or ignores, and what it answers. Error bodies and status codes are in the [errors reference](errors.md); the server's options in the [command-line reference](cli.md) and the [configuration reference](configuration.md).
4+
5+The examples use `mlx-community/Qwen3-4B-4bit` as chat model and `BAAI/bge-small-en-v1.5` as embedding model, both pulled beforehand with `rzb models pull`. The compatibility suite runs every `curl` example of this page against a real server (`scripts/compat.sh`).
6+
7+## General rules
8+
9+| Rule | Value |
10+| --- | --- |
11+| Base URL | `http://<host>:<port>/v1`, by default `http://127.0.0.1:8080/v1` |
12+| Request body | JSON (`Content-Type: application/json`), at most 16 MiB (larger: 413) |
13+| Response body | JSON, compact, keys sorted; streams are Server-Sent Events |
14+| Authentication | `Authorization: Bearer <key>` on every route except `/health`, when the server has an API key ([`--api-key-env`](cli.md#rzb-serve)); none otherwise |
15+| CORS | Off, unless `--cors-origin` / `server.cors_origin` is set |
16+| Unknown fields | Ignored, as OpenAI does, unless listed as refused below |
17+| Connections | Generation endpoints answer with `Connection: close` (the server watches the connection to stop a generation whose client has left) |
18+| Concurrency | One generation at a time per model; other requests for that model wait in a queue ([`limits`](configuration.md#limits)) |
19+
20+## Endpoints
21+
22+| Method and path | Purpose |
23+| --- | --- |
24+| `GET /health` | Liveness check, no authentication |
25+| `GET /v1/models` | Models the server can serve |
26+| `GET /v1/models/{id}` | One of them (`{id}` may contain `/`) |
27+| `POST /v1/chat/completions` | Chat answer, plain or streamed, with structured output, tools and reasoning |
28+| `POST /v1/completions` | Legacy text completion: the prompt is continued as raw text |
29+| `POST /v1/embeddings` | Embedding vectors |
30+
31+Any other path answers 404 with code `unknown_url`.
32+
33+## GET /health
34+
35+```bash
36+curl -s http://127.0.0.1:8080/health
37+```
38+
39+Answer: `{"status":"ok"}`, status 200, whenever the process is up.
40+
41+## GET /v1/models
42+
43+```bash
44+curl -s http://127.0.0.1:8080/v1/models
45+```
46+
47+Answer: `{"object": "list", "data": [<model>, …]}`. The list holds, in this order: the models declared in the configuration (under their `id`), then the loadable models of the Hugging Face cache, then models loaded by their Hugging Face id that are neither.
48+
49+| Field of `<model>` | Type | Value |
50+| --- | --- | --- |
51+| `id` | string | The name to put in `"model"` |
52+| `object` | string | `"model"` |
53+| `created` | integer | The server's start time (Unix seconds) |
54+| `owned_by` | string | `"razorbill"` |
55+| `loaded` | boolean | razorbill extension: in memory now |
56+| `kind` | string | razorbill extension: `chat` or `embedding`. A cached model that is not declared is reported as `chat` (the cache does not record the kind) |
57+
58+`GET /v1/models/{id}` answers one `<model>`, or 404 `model_not_found`.
59+
60+## Model names
61+
62+The `"model"` of a request is, in this order of lookup:
63+
64+1. the `id` of a model declared in the configuration; its `kind` must match the endpoint (chat for completions, embedding for embeddings), otherwise 400;
65+2. a Hugging Face repository id, `org/name` or `org/name@revision`, of a model in MLX format. It is downloaded on its first use if it is not in the cache, and taken to be of the endpoint's kind. A repository the cache shows without `.safetensors` weights (GGUF, for instance) is refused with 400 `model_not_supported`.
66+
67+Anything else is a 404 `model_not_found`.
68+
69+## POST /v1/chat/completions
70+
71+```bash
72+curl -s http://127.0.0.1:8080/v1/chat/completions \
73+ -H "Content-Type: application/json" \
74+ -d '{
75+ "model": "mlx-community/Qwen3-4B-4bit",
76+ "messages": [
77+ {"role": "system", "content": "Answer in one sentence."},
78+ {"role": "user", "content": "What is MLX?"}
79+ ],
80+ "temperature": 0.2,
81+ "max_tokens": 200
82+ }'
83+```
84+
85+### Request fields
86+
87+| Field | Type | Default | Description |
88+| --- | --- | --- | --- |
89+| `model` | string | required | See [model names](#model-names) |
90+| `messages` | array | required, not empty | See [messages](#messages) |
91+| `temperature` | number, 0–2 | configuration, else `0.6` | Sampling temperature |
92+| `top_p` | number, >0–1 | configuration, else `1.0` | Nucleus sampling |
93+| `max_tokens` | integer ≥ 1 | configuration, else `1024` | Most tokens generated, reasoning included |
94+| `max_completion_tokens` | integer ≥ 1 | — | Same as `max_tokens`; wins when both are sent |
95+| `stop` | string or array of ≤ 4 strings | none | The answer ends before the first occurrence; `finish_reason` is then `stop` |
96+| `seed` | integer | random | Sampler seed: same seed and settings, same answer |
97+| `presence_penalty` | number, −2–2 | none | Penalises tokens already present |
98+| `frequency_penalty` | number, −2–2 | none | Penalises tokens by their frequency |
99+| `stream` | boolean | `false` | Stream the answer as Server-Sent Events ([streaming](#streaming)) |
100+| `stream_options.include_usage` | boolean | `false` | Add a last chunk with `usage` |
101+| `response_format` | object | `{"type": "text"}` | `text`, `json_object` or `json_schema`; see [structured output](#structured-output) |
102+| `tools` | array | none | Functions the model may call; see [tools](#tools) |
103+| `tool_choice` | string or object | `auto` with tools, `none` without | `none`, `auto`, `required`, or `{"type": "function", "function": {"name": "…"}}` |
104+| `parallel_tool_calls` | boolean | `true`; `false` for a forced call | `false`: at most one call |
105+| `reasoning_effort` | string | configuration | `none` and `minimal` turn thinking off; `low`, `medium`, `high` turn it on (all three alike) |
106+| `chat_template_kwargs.enable_thinking` | boolean | — | vLLM's switch; wins over `reasoning_effort` |
107+| `thinking_budget` | integer ≥ 0 | configuration | razorbill extension: most tokens of reasoning before the model must answer |
108+| `include_reasoning` | boolean | configuration, else `true` | OpenRouter's switch: `false` leaves out `reasoning_content` (the model still thinks) |
109+
110+The configuration's `locked` values win over the request: `temperature`, `top_p`, `thinking` and `show_reasoning` are imposed, `max_tokens` and `thinking_budget` are ceilings ([configuration reference](configuration.md#defaults-and-locked)).
111+
112+### Refused fields
113+
114+These fields answer 400 naming the field, rather than being silently ignored:
115+
116+| Field | Refused when |
117+| --- | --- |
118+| `n` | other than 1 |
119+| `logprobs` | `true` |
120+| a message with role other than `system`, `developer`, `user`, `assistant`, `tool` | always |
121+| a content part of type other than `text` (images, audio…) | always |
122+| `response_format` combined with a forced tool call | `tool_choice` is `required` or names a function, or a tool is `strict` |
123+
124+### Messages
125+
126+| Role | Fields | Notes |
127+| --- | --- | --- |
128+| `system`, `developer` | `content` | `developer` is treated as `system` |
129+| `user` | `content` | |
130+| `assistant` | `content` (may be null), `tool_calls` | Previous answers, with the calls the model made |
131+| `tool` | `content`, `tool_call_id`, `name` | The result of a call |
132+
133+`content` is a string or an array of `{"type": "text", "text": "…"}` parts, joined with a line break. In `tool_calls`, `function.arguments` must be a JSON object encoded as a string, as OpenAI sends it.
134+
135+The conversation is rendered with the model's own chat template. The server keeps no state between requests.
136+
137+### Response
138+
139+```json
140+{
141+ "id": "chatcmpl-…",
142+ "object": "chat.completion",
143+ "created": 1764096042,
144+ "model": "mlx-community/Qwen3-4B-4bit",
145+ "choices": [{
146+ "index": 0,
147+ "message": {"role": "assistant", "content": "…", "reasoning_content": "…", "tool_calls": […]},
148+ "logprobs": null,
149+ "finish_reason": "stop"
150+ }],
151+ "usage": {"prompt_tokens": 20, "completion_tokens": 9, "total_tokens": 29,
152+ "completion_tokens_details": {"reasoning_tokens": 120}}
153+}
154+```
155+
156+| Field | Present | Value |
157+| --- | --- | --- |
158+| `id` | always | `chatcmpl-` and 24 hexadecimal digits |
159+| `model` | always | The `"model"` of the request, as sent |
160+| `message.content` | always | The answer; `null` when the model only called tools |
161+| `message.reasoning_content` | when the model thought and reasoning is shown | The reasoning, without the `<think>` tags |
162+| `message.tool_calls` | when the model called tools | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` a JSON string |
163+| `finish_reason` | always | `stop`, `length` (token limit) or `tool_calls` |
164+| `usage.completion_tokens_details.reasoning_tokens` | when the model thought | Pieces of reasoning received (about one per token), also counted when reasoning is hidden |
165+
166+When a stop sequence ends the answer, the engine is interrupted before it reports its counts: `usage` then counts one token per piece of text and `prompt_tokens` is 0.
167+
168+### Structured output
169+
170+| `response_format` | Effect |
171+| --- | --- |
172+| `{"type": "text"}` | No constraint |
173+| `{"type": "json_object"}` | The answer is one JSON object |
174+| `{"type": "json_schema", "json_schema": {"name": "…", "schema": {…}, "strict": true}}` | The answer is one JSON value valid against `schema` |
175+
176+- The constraint is enforced while tokens are generated (constrained decoding, on macOS with MLX); a reasoning model thinks freely first, and the constraint applies after its reasoning.
177+- The server adds one instruction to the system message (a system message is created if there is none): `Answer with a single JSON object.` for `json_object`; `Answer with a single JSON object that follows this JSON Schema:` followed by the schema for `json_schema`.
178+- Object properties are generated in the order the schema lists them.
179+- With `"strict": true`, a schema that uses a keyword the decoder cannot enforce is refused with 400 naming it and where it is: `not`, `if`, `then`, `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. Without `strict`, such keywords are ignored.
180+
181+```bash
182+curl -s http://127.0.0.1:8080/v1/chat/completions \
183+ -H "Content-Type: application/json" \
184+ -d '{
185+ "model": "mlx-community/Qwen3-4B-4bit",
186+ "messages": [{"role": "user", "content": "Describe Lyon."}],
187+ "response_format": {"type": "json_schema", "json_schema": {"name": "city", "strict": true,
188+ "schema": {"type": "object", "additionalProperties": false, "required": ["name", "country"],
189+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}}}},
190+ "reasoning_effort": "none"
191+ }'
192+```
193+
194+### Tools
195+
196+| `tools[i]` field | Type | Rules |
197+| --- | --- | --- |
198+| `type` | string | `"function"` |
199+| `function.name` | string | 1–64 letters, digits, `_` or `-`; unique |
200+| `function.description` | string | Optional |
201+| `function.parameters` | object | A JSON Schema object; default `{"type": "object", "properties": {}}` |
202+| `function.strict` | boolean | `true`: the arguments are generated under the schema (same keyword limits as `strict` structured output) |
203+
204+| `tool_choice` | Effect |
205+| --- | --- |
206+| `none` | Tools are not offered to the model; it answers in text |
207+| `auto` | The model decides; its calls are parsed from its output |
208+| `required` | The answer is tool calls only, generated under a grammar |
209+| `{"type": "function", "function": {"name": "f"}}` | The answer is one call to `f`, generated under a grammar |
210+
211+- Forced calls (`required`, a named function, or a `strict` tool) are only possible for models whose tool-call syntax is `<tool_call>{"name": …, "arguments": …}</tool_call>` (Qwen, Hermes and similar). For other families (Llama 3, Mistral, Gemma…) they answer 400; `auto` works for every family mlx-swift-lm can parse.
212+- A forced call produces one call, unless `parallel_tool_calls` is `true`.
213+- With `parallel_tool_calls: false`, calls after the first are dropped.
214+
215+```bash
216+curl -s http://127.0.0.1:8080/v1/chat/completions \
217+ -H "Content-Type: application/json" \
218+ -d '{
219+ "model": "mlx-community/Qwen3-4B-4bit",
220+ "messages": [{"role": "user", "content": "What is the weather in Lyon?"}],
221+ "tools": [{"type": "function", "function": {"name": "get_weather",
222+ "description": "Current weather for a city",
223+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
224+ "tool_choice": "required",
225+ "reasoning_effort": "none"
226+ }'
227+```
228+
229+## POST /v1/completions
230+
231+The legacy text-completion endpoint. The prompt is tokenized as is and continued: no chat template, no thinking, no tool-call parsing.
232+
233+```bash
234+curl -s http://127.0.0.1:8080/v1/completions \
235+ -H "Content-Type: application/json" \
236+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "prompt": "The capital of France is", "max_tokens": 8, "temperature": 0}'
237+```
238+
239+| Field | Type | Default | Description |
240+| --- | --- | --- | --- |
241+| `model` | string | required | A chat model ([model names](#model-names)) |
242+| `prompt` | string, or array of one string | required | The text to continue |
243+| `max_tokens` | integer ≥ 1 | configuration, else `1024` (OpenAI's default is 16) | Most tokens generated |
244+| `temperature`, `top_p`, `stop`, `seed`, `presence_penalty`, `frequency_penalty` | | | As for chat completions |
245+| `echo` | boolean | `false` | Put the prompt before the completion in `text` |
246+| `stream`, `stream_options.include_usage` | | `false` | As for chat completions |
247+
248+Refused with 400: `suffix` (no fill-in-the-middle), `logprobs` above 0, `n` or `best_of` other than 1, several prompts, token arrays.
249+
250+Response: `{"id": "cmpl-…", "object": "text_completion", "created", "model", "choices": [{"text", "index": 0, "logprobs": null, "finish_reason"}], "usage"}`. A stream sends objects of the same shape, each with a piece of `text`; with `echo`, the first one holds the prompt.
251+
252+## POST /v1/embeddings
253+
254+```bash
255+curl -s http://127.0.0.1:8080/v1/embeddings \
256+ -H "Content-Type: application/json" \
257+ -d '{"model": "BAAI/bge-small-en-v1.5", "input": ["The cat sits on the mat.", "A feline rests on a rug."]}'
258+```
259+
260+| Field | Type | Default | Description |
261+| --- | --- | --- | --- |
262+| `model` | string | required | An embedding model ([model names](#model-names)) |
263+| `input` | string or array of 1–2048 strings | required | Texts to embed; none may be empty. Token arrays are refused |
264+| `encoding_format` | `float` or `base64` | `float` | `base64`: each vector as little-endian float32 bytes, Base64-encoded |
265+| `dimensions` | integer ≥ 1 | the model's size | Keep the first `dimensions` values and renormalise (for Matryoshka models); larger than the model's size: 400 |
266+
267+Response: `{"object": "list", "data": [{"object": "embedding", "index": i, "embedding": […]}], "model", "usage": {"prompt_tokens", "total_tokens"}}`. Vectors are L2-normalised. A text longer than the model accepts is a 400 naming `input[i]` and the limit. Inputs are embedded in batches of 32. Pooling follows the model's sentence-transformers configuration.
268+
269+## Streaming
270+
271+With `"stream": true`, the answer is `text/event-stream`:
272+
273+```
274+data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],…}
275+
276+data: {…"choices":[{"index":0,"delta":{"content":"Hel"},…}]…}
277+
278+data: {…"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]…}
279+
280+data: [DONE]
281+
282+```
283+
284+- Chat chunks: a first chunk with `delta.role`, then pieces in `delta.content`, `delta.reasoning_content` or `delta.tool_calls` (each call whole, with its `index`), then an empty delta with `finish_reason`.
285+- With `stream_options.include_usage`, every chunk has `"usage": null` and a last chunk with empty `choices` carries the `usage`.
286+- While the model produces nothing (loading, long prompt), a comment line `: keep-alive` is sent every 5 seconds; SSE clients ignore it.
287+- An error after the stream started is sent as one last event `data: {"error": {…}}`, without `[DONE]`.
288+- When the client disconnects, the generation stops and the model is freed for the next request.
289+
290+```bash
291+curl -sN http://127.0.0.1:8080/v1/chat/completions \
292+ -H "Content-Type: application/json" \
293+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Count to 5."}],
294+ "stream": true, "stream_options": {"include_usage": true}, "reasoning_effort": "none"}'
295+```
new file mode 100644
@@ -0,0 +1,295 @@
1+# Reference: HTTP API
2+
3+> The endpoints of `rzb serve`, the fields each one accepts, refuses or ignores, and what it answers. Error bodies and status codes are in the [errors reference](errors.md); the server's options in the [command-line reference](cli.md) and the [configuration reference](configuration.md).
4+
5+The examples use `mlx-community/Qwen3-4B-4bit` as chat model and `BAAI/bge-small-en-v1.5` as embedding model, both pulled beforehand with `rzb models pull`. The compatibility suite runs every `curl` example of this page against a real server (`scripts/compat.sh`).
6+
7+## General rules
8+
9+| Rule | Value |
10+| --- | --- |
11+| Base URL | `http://<host>:<port>/v1`, by default `http://127.0.0.1:8080/v1` |
12+| Request body | JSON (`Content-Type: application/json`), at most 16 MiB (larger: 413) |
13+| Response body | JSON, compact, keys sorted; streams are Server-Sent Events |
14+| Authentication | `Authorization: Bearer <key>` on every route except `/health`, when the server has an API key ([`--api-key-env`](cli.md#rzb-serve)); none otherwise |
15+| CORS | Off, unless `--cors-origin` / `server.cors_origin` is set |
16+| Unknown fields | Ignored, as OpenAI does, unless listed as refused below |
17+| Connections | Generation endpoints answer with `Connection: close` (the server watches the connection to stop a generation whose client has left) |
18+| Concurrency | One generation at a time per model; other requests for that model wait in a queue ([`limits`](configuration.md#limits)) |
19+
20+## Endpoints
21+
22+| Method and path | Purpose |
23+| --- | --- |
24+| `GET /health` | Liveness check, no authentication |
25+| `GET /v1/models` | Models the server can serve |
26+| `GET /v1/models/{id}` | One of them (`{id}` may contain `/`) |
27+| `POST /v1/chat/completions` | Chat answer, plain or streamed, with structured output, tools and reasoning |
28+| `POST /v1/completions` | Legacy text completion: the prompt is continued as raw text |
29+| `POST /v1/embeddings` | Embedding vectors |
30+
31+Any other path answers 404 with code `unknown_url`.
32+
33+## GET /health
34+
35+```bash
36+curl -s http://127.0.0.1:8080/health
37+```
38+
39+Answer: `{"status":"ok"}`, status 200, whenever the process is up.
40+
41+## GET /v1/models
42+
43+```bash
44+curl -s http://127.0.0.1:8080/v1/models
45+```
46+
47+Answer: `{"object": "list", "data": [<model>, …]}`. The list holds, in this order: the models declared in the configuration (under their `id`), then the loadable models of the Hugging Face cache, then models loaded by their Hugging Face id that are neither.
48+
49+| Field of `<model>` | Type | Value |
50+| --- | --- | --- |
51+| `id` | string | The name to put in `"model"` |
52+| `object` | string | `"model"` |
53+| `created` | integer | The server's start time (Unix seconds) |
54+| `owned_by` | string | `"razorbill"` |
55+| `loaded` | boolean | razorbill extension: in memory now |
56+| `kind` | string | razorbill extension: `chat` or `embedding`. A cached model that is not declared is reported as `chat` (the cache does not record the kind) |
57+
58+`GET /v1/models/{id}` answers one `<model>`, or 404 `model_not_found`.
59+
60+## Model names
61+
62+The `"model"` of a request is, in this order of lookup:
63+
64+1. the `id` of a model declared in the configuration; its `kind` must match the endpoint (chat for completions, embedding for embeddings), otherwise 400;
65+2. a Hugging Face repository id, `org/name` or `org/name@revision`, of a model in MLX format. It is downloaded on its first use if it is not in the cache, and taken to be of the endpoint's kind. A repository the cache shows without `.safetensors` weights (GGUF, for instance) is refused with 400 `model_not_supported`.
66+
67+Anything else is a 404 `model_not_found`.
68+
69+## POST /v1/chat/completions
70+
71+```bash
72+curl -s http://127.0.0.1:8080/v1/chat/completions \
73+ -H "Content-Type: application/json" \
74+ -d '{
75+ "model": "mlx-community/Qwen3-4B-4bit",
76+ "messages": [
77+ {"role": "system", "content": "Answer in one sentence."},
78+ {"role": "user", "content": "What is MLX?"}
79+ ],
80+ "temperature": 0.2,
81+ "max_tokens": 200
82+ }'
83+```
84+
85+### Request fields
86+
87+| Field | Type | Default | Description |
88+| --- | --- | --- | --- |
89+| `model` | string | required | See [model names](#model-names) |
90+| `messages` | array | required, not empty | See [messages](#messages) |
91+| `temperature` | number, 0–2 | configuration, else `0.6` | Sampling temperature |
92+| `top_p` | number, >0–1 | configuration, else `1.0` | Nucleus sampling |
93+| `max_tokens` | integer ≥ 1 | configuration, else `1024` | Most tokens generated, reasoning included |
94+| `max_completion_tokens` | integer ≥ 1 | — | Same as `max_tokens`; wins when both are sent |
95+| `stop` | string or array of ≤ 4 strings | none | The answer ends before the first occurrence; `finish_reason` is then `stop` |
96+| `seed` | integer | random | Sampler seed: same seed and settings, same answer |
97+| `presence_penalty` | number, −2–2 | none | Penalises tokens already present |
98+| `frequency_penalty` | number, −2–2 | none | Penalises tokens by their frequency |
99+| `stream` | boolean | `false` | Stream the answer as Server-Sent Events ([streaming](#streaming)) |
100+| `stream_options.include_usage` | boolean | `false` | Add a last chunk with `usage` |
101+| `response_format` | object | `{"type": "text"}` | `text`, `json_object` or `json_schema`; see [structured output](#structured-output) |
102+| `tools` | array | none | Functions the model may call; see [tools](#tools) |
103+| `tool_choice` | string or object | `auto` with tools, `none` without | `none`, `auto`, `required`, or `{"type": "function", "function": {"name": "…"}}` |
104+| `parallel_tool_calls` | boolean | `true`; `false` for a forced call | `false`: at most one call |
105+| `reasoning_effort` | string | configuration | `none` and `minimal` turn thinking off; `low`, `medium`, `high` turn it on (all three alike) |
106+| `chat_template_kwargs.enable_thinking` | boolean | — | vLLM's switch; wins over `reasoning_effort` |
107+| `thinking_budget` | integer ≥ 0 | configuration | razorbill extension: most tokens of reasoning before the model must answer |
108+| `include_reasoning` | boolean | configuration, else `true` | OpenRouter's switch: `false` leaves out `reasoning_content` (the model still thinks) |
109+
110+The configuration's `locked` values win over the request: `temperature`, `top_p`, `thinking` and `show_reasoning` are imposed, `max_tokens` and `thinking_budget` are ceilings ([configuration reference](configuration.md#defaults-and-locked)).
111+
112+### Refused fields
113+
114+These fields answer 400 naming the field, rather than being silently ignored:
115+
116+| Field | Refused when |
117+| --- | --- |
118+| `n` | other than 1 |
119+| `logprobs` | `true` |
120+| a message with role other than `system`, `developer`, `user`, `assistant`, `tool` | always |
121+| a content part of type other than `text` (images, audio…) | always |
122+| `response_format` combined with a forced tool call | `tool_choice` is `required` or names a function, or a tool is `strict` |
123+
124+### Messages
125+
126+| Role | Fields | Notes |
127+| --- | --- | --- |
128+| `system`, `developer` | `content` | `developer` is treated as `system` |
129+| `user` | `content` | |
130+| `assistant` | `content` (may be null), `tool_calls` | Previous answers, with the calls the model made |
131+| `tool` | `content`, `tool_call_id`, `name` | The result of a call |
132+
133+`content` is a string or an array of `{"type": "text", "text": "…"}` parts, joined with a line break. In `tool_calls`, `function.arguments` must be a JSON object encoded as a string, as OpenAI sends it.
134+
135+The conversation is rendered with the model's own chat template. The server keeps no state between requests.
136+
137+### Response
138+
139+```json
140+{
141+ "id": "chatcmpl-…",
142+ "object": "chat.completion",
143+ "created": 1764096042,
144+ "model": "mlx-community/Qwen3-4B-4bit",
145+ "choices": [{
146+ "index": 0,
147+ "message": {"role": "assistant", "content": "…", "reasoning_content": "…", "tool_calls": […]},
148+ "logprobs": null,
149+ "finish_reason": "stop"
150+ }],
151+ "usage": {"prompt_tokens": 20, "completion_tokens": 9, "total_tokens": 29,
152+ "completion_tokens_details": {"reasoning_tokens": 120}}
153+}
154+```
155+
156+| Field | Present | Value |
157+| --- | --- | --- |
158+| `id` | always | `chatcmpl-` and 24 hexadecimal digits |
159+| `model` | always | The `"model"` of the request, as sent |
160+| `message.content` | always | The answer; `null` when the model only called tools |
161+| `message.reasoning_content` | when the model thought and reasoning is shown | The reasoning, without the `<think>` tags |
162+| `message.tool_calls` | when the model called tools | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` a JSON string |
163+| `finish_reason` | always | `stop`, `length` (token limit) or `tool_calls` |
164+| `usage.completion_tokens_details.reasoning_tokens` | when the model thought | Pieces of reasoning received (about one per token), also counted when reasoning is hidden |
165+
166+When a stop sequence ends the answer, the engine is interrupted before it reports its counts: `usage` then counts one token per piece of text and `prompt_tokens` is 0.
167+
168+### Structured output
169+
170+| `response_format` | Effect |
171+| --- | --- |
172+| `{"type": "text"}` | No constraint |
173+| `{"type": "json_object"}` | The answer is one JSON object |
174+| `{"type": "json_schema", "json_schema": {"name": "…", "schema": {…}, "strict": true}}` | The answer is one JSON value valid against `schema` |
175+
176+- The constraint is enforced while tokens are generated (constrained decoding, on macOS with MLX); a reasoning model thinks freely first, and the constraint applies after its reasoning.
177+- The server adds one instruction to the system message (a system message is created if there is none): `Answer with a single JSON object.` for `json_object`; `Answer with a single JSON object that follows this JSON Schema:` followed by the schema for `json_schema`.
178+- Object properties are generated in the order the schema lists them.
179+- With `"strict": true`, a schema that uses a keyword the decoder cannot enforce is refused with 400 naming it and where it is: `not`, `if`, `then`, `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. Without `strict`, such keywords are ignored.
180+
181+```bash
182+curl -s http://127.0.0.1:8080/v1/chat/completions \
183+ -H "Content-Type: application/json" \
184+ -d '{
185+ "model": "mlx-community/Qwen3-4B-4bit",
186+ "messages": [{"role": "user", "content": "Describe Lyon."}],
187+ "response_format": {"type": "json_schema", "json_schema": {"name": "city", "strict": true,
188+ "schema": {"type": "object", "additionalProperties": false, "required": ["name", "country"],
189+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}}}},
190+ "reasoning_effort": "none"
191+ }'
192+```
193+
194+### Tools
195+
196+| `tools[i]` field | Type | Rules |
197+| --- | --- | --- |
198+| `type` | string | `"function"` |
199+| `function.name` | string | 1–64 letters, digits, `_` or `-`; unique |
200+| `function.description` | string | Optional |
201+| `function.parameters` | object | A JSON Schema object; default `{"type": "object", "properties": {}}` |
202+| `function.strict` | boolean | `true`: the arguments are generated under the schema (same keyword limits as `strict` structured output) |
203+
204+| `tool_choice` | Effect |
205+| --- | --- |
206+| `none` | Tools are not offered to the model; it answers in text |
207+| `auto` | The model decides; its calls are parsed from its output |
208+| `required` | The answer is tool calls only, generated under a grammar |
209+| `{"type": "function", "function": {"name": "f"}}` | The answer is one call to `f`, generated under a grammar |
210+
211+- Forced calls (`required`, a named function, or a `strict` tool) are only possible for models whose tool-call syntax is `<tool_call>{"name": …, "arguments": …}</tool_call>` (Qwen, Hermes and similar). For other families (Llama 3, Mistral, Gemma…) they answer 400; `auto` works for every family mlx-swift-lm can parse.
212+- A forced call produces one call, unless `parallel_tool_calls` is `true`.
213+- With `parallel_tool_calls: false`, calls after the first are dropped.
214+
215+```bash
216+curl -s http://127.0.0.1:8080/v1/chat/completions \
217+ -H "Content-Type: application/json" \
218+ -d '{
219+ "model": "mlx-community/Qwen3-4B-4bit",
220+ "messages": [{"role": "user", "content": "What is the weather in Lyon?"}],
221+ "tools": [{"type": "function", "function": {"name": "get_weather",
222+ "description": "Current weather for a city",
223+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
224+ "tool_choice": "required",
225+ "reasoning_effort": "none"
226+ }'
227+```
228+
229+## POST /v1/completions
230+
231+The legacy text-completion endpoint. The prompt is tokenized as is and continued: no chat template, no thinking, no tool-call parsing.
232+
233+```bash
234+curl -s http://127.0.0.1:8080/v1/completions \
235+ -H "Content-Type: application/json" \
236+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "prompt": "The capital of France is", "max_tokens": 8, "temperature": 0}'
237+```
238+
239+| Field | Type | Default | Description |
240+| --- | --- | --- | --- |
241+| `model` | string | required | A chat model ([model names](#model-names)) |
242+| `prompt` | string, or array of one string | required | The text to continue |
243+| `max_tokens` | integer ≥ 1 | configuration, else `1024` (OpenAI's default is 16) | Most tokens generated |
244+| `temperature`, `top_p`, `stop`, `seed`, `presence_penalty`, `frequency_penalty` | | | As for chat completions |
245+| `echo` | boolean | `false` | Put the prompt before the completion in `text` |
246+| `stream`, `stream_options.include_usage` | | `false` | As for chat completions |
247+
248+Refused with 400: `suffix` (no fill-in-the-middle), `logprobs` above 0, `n` or `best_of` other than 1, several prompts, token arrays.
249+
250+Response: `{"id": "cmpl-…", "object": "text_completion", "created", "model", "choices": [{"text", "index": 0, "logprobs": null, "finish_reason"}], "usage"}`. A stream sends objects of the same shape, each with a piece of `text`; with `echo`, the first one holds the prompt.
251+
252+## POST /v1/embeddings
253+
254+```bash
255+curl -s http://127.0.0.1:8080/v1/embeddings \
256+ -H "Content-Type: application/json" \
257+ -d '{"model": "BAAI/bge-small-en-v1.5", "input": ["The cat sits on the mat.", "A feline rests on a rug."]}'
258+```
259+
260+| Field | Type | Default | Description |
261+| --- | --- | --- | --- |
262+| `model` | string | required | An embedding model ([model names](#model-names)) |
263+| `input` | string or array of 1–2048 strings | required | Texts to embed; none may be empty. Token arrays are refused |
264+| `encoding_format` | `float` or `base64` | `float` | `base64`: each vector as little-endian float32 bytes, Base64-encoded |
265+| `dimensions` | integer ≥ 1 | the model's size | Keep the first `dimensions` values and renormalise (for Matryoshka models); larger than the model's size: 400 |
266+
267+Response: `{"object": "list", "data": [{"object": "embedding", "index": i, "embedding": […]}], "model", "usage": {"prompt_tokens", "total_tokens"}}`. Vectors are L2-normalised. A text longer than the model accepts is a 400 naming `input[i]` and the limit. Inputs are embedded in batches of 32. Pooling follows the model's sentence-transformers configuration.
268+
269+## Streaming
270+
271+With `"stream": true`, the answer is `text/event-stream`:
272+
273+```
274+data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],…}
275+
276+data: {…"choices":[{"index":0,"delta":{"content":"Hel"},…}]…}
277+
278+data: {…"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]…}
279+
280+data: [DONE]
281+
282+```
283+
284+- Chat chunks: a first chunk with `delta.role`, then pieces in `delta.content`, `delta.reasoning_content` or `delta.tool_calls` (each call whole, with its `index`), then an empty delta with `finish_reason`.
285+- With `stream_options.include_usage`, every chunk has `"usage": null` and a last chunk with empty `choices` carries the `usage`.
286+- While the model produces nothing (loading, long prompt), a comment line `: keep-alive` is sent every 5 seconds; SSE clients ignore it.
287+- An error after the stream started is sent as one last event `data: {"error": {…}}`, without `[DONE]`.
288+- When the client disconnects, the generation stops and the model is freed for the next request.
289+
290+```bash
291+curl -sN http://127.0.0.1:8080/v1/chat/completions \
292+ -H "Content-Type: application/json" \
293+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Count to 5."}],
294+ "stream": true, "stream_options": {"include_usage": true}, "reasoning_effort": "none"}'
295+```
modified docs/en/tutorials/getting-started.md +114 -82
@@ -1,156 +1,188 @@
1-# Tutorial: your first razorbill agent
1+# Tutorial: your first requests to a local model
22
3-By the end of this tutorial, you will have built `rzb`, created an agent that runs the small model `mlx-community/Qwen3-0.6B-4bit` on your Mac's GPU, chatted with it, and watched it run a shell command after asking for your permission. It takes about fifteen minutes, most of it waiting for the first build.
3+By the end of this tutorial, you will have a model running on your Mac's GPU behind an OpenAI-compatible API, and you will have talked to it twice: once with `curl`, once from a Python program that uses the official `openai` library.
4+
5+No knowledge of MLX or of the OpenAI API is required.
46
57 ## Prerequisites
68
7-- A Mac with Apple Silicon (M1 or later), macOS 14 or later, and about 1 GB of free disk space.
8-- Xcode 26 or later, selected with `xcode-select` (`xcode-select -p` prints a path inside `Xcode.app`).
9-- The Metal toolchain, installed once: `xcodebuild -downloadComponent MetalToolchain`.
10-- Network access to `huggingface.co`.
11-- A clone of the razorbill repository. Every command below starts in its root folder.
9+- A Mac with Apple Silicon (M1 or later) and macOS 14 or later.
10+- `rzb` built, as described in [How to build rzb on the Mac](../how-to/build-on-the-mac.md). In this tutorial, `rzb` means `.build/xcode/Build/Products/Release/rzb`; to type it shorter, run this once in your terminal, from the repository root:
11+
12+ ```bash
13+ alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb"
14+ ```
1215
13-## Step 1 — Build rzb
16+- About 400 MB of free disk space, and an internet connection for the first download.
17+- [`uv`](https://docs.astral.sh/uv/) for step 5 (`brew install uv`).
18+
19+## Step 1 — Download a small model
1420
1521 Type:
1622
1723 ```bash
18-xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \
19- -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
24+rzb models pull mlx-community/Qwen3-0.6B-4bit
2025 ```
2126
22-The first build downloads and compiles the dependencies and takes several minutes. It ends with:
27+A progress bar runs, then you should see:
2328
2429 ```
25-** BUILD SUCCEEDED **
30+mlx-community/Qwen3-0.6B-4bit is downloaded.
2631 ```
2732
28-Now put the folder that holds `rzb` on your `PATH` for this terminal, and check it:
33+We now have a small model (0.6 billion parameters, 4-bit) in the Hugging Face cache on this Mac.
34+
35+## Step 2 — Start the server
36+
37+Type:
2938
3039 ```bash
31-export PATH="$PWD/.build/xcode/Build/Products/Release:$PATH"
32-rzb version
40+rzb serve
3341 ```
3442
3543 You should see:
3644
3745 ```
38-rzb 0.1.0 (engines: fake, mlx)
46+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (no API key) — Ctrl-C to stop
3947 ```
4048
41-We have a working `rzb` that can run MLX models.
49+The server is running and only accepts connections from this Mac. Leave this terminal open, and **open a second terminal** for the next steps.
4250
43-## Step 2 — Create an agent
51+## Step 3 — Check that it answers
4452
45-We work in a new, empty folder:
53+In the second terminal, type:
4654
4755 ```bash
48-mkdir -p ~/rzb-tutorial && cd ~/rzb-tutorial
49-rzb init --yes --name helper --model mlx-community/Qwen3-0.6B-4bit
56+curl -s http://127.0.0.1:8080/health
5057 ```
5158
5259 You should see:
5360
61+```json
62+{"status":"ok"}
5463 ```
55-Wrote razorbill.yaml. Next: rzb chat --config razorbill.yaml
56-It will be downloaded on first use (or now with: rzb models pull mlx-community/Qwen3-0.6B-4bit).
57-```
58-
59-Open `razorbill.yaml`: it describes the agent — its name, its model, its generation settings and its system prompt — with a comment on every line.
6064
61-## Step 3 — Download the model
62-
63-Type:
65+Now ask which models it can serve:
6466
6567 ```bash
66-rzb models pull mlx-community/Qwen3-0.6B-4bit
67-```
68-
69-A progress line counts up to 100 % and ends with:
70-
71-```
72-mlx-community/Qwen3-0.6B-4bit is downloaded.
68+curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool
7369 ```
7470
75-Check that razorbill sees it:
71+You should see a list that contains the model we downloaded:
7672
77-```bash
78-rzb models list
73+```json
74+{
75+ "data": [
76+ {
77+ "created": 1764096000,
78+ "id": "mlx-community/Qwen3-0.6B-4bit",
79+ "kind": "chat",
80+ "loaded": false,
81+ "object": "model",
82+ "owned_by": "razorbill"
83+ }
84+ ],
85+ "object": "list"
86+}
7987 ```
8088
81-You should see a line starting with `mlx-community/Qwen3-0.6B-4bit` followed by its size (about 350 MB) and `main`.
89+`"loaded": false`: the model is on disk but not in memory yet. It will be loaded by the first request.
8290
83-## Step 4 — Ask one question
91+## Step 4 — Ask a question with curl
8492
8593 Type:
8694
8795 ```bash
88-rzb run "What is the capital of France? Answer in one sentence."
96+curl -s http://127.0.0.1:8080/v1/chat/completions \
97+ -H "Content-Type: application/json" \
98+ -d '{
99+ "model": "mlx-community/Qwen3-0.6B-4bit",
100+ "messages": [{"role": "user", "content": "What is the capital of France? One sentence."}]
101+ }' | python3 -m json.tool
89102 ```
90103
91-`rzb` finds `razorbill.yaml` in the current folder, loads the model and prints an answer such as:
104+The first request takes a second or two longer: the model is being loaded. You should see an answer of this shape (the exact sentence may differ):
92105
93-```
94-The capital of France is Paris.
95-[24 prompt tokens, 9 generated, 150.2 tokens/s]
106+```json
107+{
108+ "choices": [
109+ {
110+ "finish_reason": "stop",
111+ "index": 0,
112+ "logprobs": null,
113+ "message": {
114+ "content": "The capital of France is Paris.",
115+ "role": "assistant"
116+ }
117+ }
118+ ],
119+ "created": 1764096042,
120+ "id": "chatcmpl-3f9c2a…",
121+ "model": "mlx-community/Qwen3-0.6B-4bit",
122+ "object": "chat.completion",
123+ "usage": {
124+ "completion_tokens": 9,
125+ "prompt_tokens": 20,
126+ "total_tokens": 29
127+ }
128+}
96129 ```
97130
98-The numbers on the last line change from one Mac to another. We have just run a language model on the GPU, entirely on this Mac.
131+In the first terminal, the server has logged the model load and the request, for example:
99132
100-## Step 5 — Have a conversation
101-
102-Type:
103-
104-```bash
105-rzb chat
133+```
134+2026-11-25T19:20:41+0100 info rzb: [RazorbillServer] loaded mlx-community/Qwen3-0.6B-4bit in 0.43 seconds
135+2026-11-25T19:20:42+0100 info rzb: [RazorbillServer] POST /v1/chat/completions 200 812ms model=mlx-community/Qwen3-0.6B-4bit tokens=20+9
106136 ```
107137
108-You should see the agent's name, its model and its engine, then a prompt:
138+We have just run a model on the GPU through the same API as OpenAI's.
109139
110-```
111-helper · mlx-community/Qwen3-0.6B-4bit · mlx — /help for commands
112-›
113-```
140+## Step 5 — Use the openai Python library
114141
115-Type `My name is Ada.`, press Enter, then type `What is my name?`. The agent remembers the first message and answers with your name. Type `/exit` to leave.
142+Any program written for the OpenAI API can use the server by changing its base URL. Create a file `first.py` with this content:
116143
117-## Step 6 — Let the agent run a command
144+```python
145+from openai import OpenAI
118146
119-Open `razorbill.yaml` in an editor and replace the line `tools: {}` with these two lines:
147+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
120148
121-```yaml
122-tools:
123- bash: {}
149+stream = client.chat.completions.create(
150+ model="mlx-community/Qwen3-0.6B-4bit",
151+ messages=[{"role": "user", "content": "Write a haiku about the sea."}],
152+ stream=True,
153+)
154+for chunk in stream:
155+ if chunk.choices and chunk.choices[0].delta.content:
156+ print(chunk.choices[0].delta.content, end="", flush=True)
157+print()
124158 ```
125159
126-Start the chat again and ask for something only a command can tell:
160+Run it:
127161
128162 ```bash
129-rzb chat
130-```
131-
132-```
133-› How many files are in the current folder? Use the bash tool.
163+uv run --with openai python first.py
134164 ```
135165
136-The model asks to run a command, and `rzb` asks you first:
166+You should see a haiku appear word by word, for example:
137167
138168 ```
139-→ bash command="ls | wc -l"
140-
141-bash wants to run: ls | wc -l (in /Users/you/rzb-tutorial)
142-Allow? [y/N]:
169+Waves fold into foam,
170+salt wind carries gull voices—
171+the tide keeps its time.
143172 ```
144173
145-The exact command may differ. Type `y` and press Enter. The command runs, its result goes back to the model, and the model answers — here, that there is one file (`razorbill.yaml`). Type `/exit`.
174+The server does not check `api_key` because we did not set one; the library still requires a value.
175+
176+## Step 6 — Stop the server
146177
147-Small models sometimes skip the tool and guess. If that happens, ask again, or set `model:` to `mlx-community/Qwen3-1.7B-4bit` (download it first with `rzb models pull`).
178+In the first terminal, press **Ctrl-C**. The server unloads the model and exits.
148179
149180 ## What now?
150181
151-You have built `rzb`, described an agent in a YAML file, run a model on your GPU and given it a tool it can only use with your consent. To go further:
182+You have downloaded a model, served it on your Mac, and called it with `curl` and with the `openai` library, streaming included. To go further:
152183
153-- Try the full-screen interface: `rzb tui`.
154-- To accomplish specific tasks → the [how-to guides](../README.md#do--how-to-guides), such as [configuring thinking](../how-to/configure-thinking.md) or [using the bash tool](../how-to/use-the-bash-tool.md).
155-- Every key of the file → the [agent file reference](../reference/configuration.md).
156-- How razorbill is put together → the [architecture explanation](../explanation/architecture.md).
184+- Give your models short names, defaults and limits: [How to configure the server](../how-to/configure-the-server.md).
185+- Get JSON that follows a schema: [How to get structured output](../how-to/get-structured-output.md).
186+- Let the model call your functions: [How to use function calling](../how-to/use-function-calling.md).
187+- Every endpoint and field: [HTTP API reference](../reference/http-api.md).
188+- How the server works inside: [Architecture](../explanation/architecture.md).
@@ -1,156 +1,188 @@
1-# Tutorial: your first razorbill agent1+# Tutorial: your first requests to a local model
2 2
3-By the end of this tutorial, you will have built `rzb`, created an agent that runs the small model `mlx-community/Qwen3-0.6B-4bit` on your Mac's GPU, chatted with it, and watched it run a shell command after asking for your permission. It takes about fifteen minutes, most of it waiting for the first build.3+By the end of this tutorial, you will have a model running on your Mac's GPU behind an OpenAI-compatible API, and you will have talked to it twice: once with `curl`, once from a Python program that uses the official `openai` library.
4+
5+No knowledge of MLX or of the OpenAI API is required.
4 6
5 ## Prerequisites7 ## Prerequisites
6 8
7-- A Mac with Apple Silicon (M1 or later), macOS 14 or later, and about 1 GB of free disk space.9+- A Mac with Apple Silicon (M1 or later) and macOS 14 or later.
8-- Xcode 26 or later, selected with `xcode-select` (`xcode-select -p` prints a path inside `Xcode.app`).10+- `rzb` built, as described in [How to build rzb on the Mac](../how-to/build-on-the-mac.md). In this tutorial, `rzb` means `.build/xcode/Build/Products/Release/rzb`; to type it shorter, run this once in your terminal, from the repository root:
9-- The Metal toolchain, installed once: `xcodebuild -downloadComponent MetalToolchain`.11+
10-- Network access to `huggingface.co`.12+ ```bash
11-- A clone of the razorbill repository. Every command below starts in its root folder.13+ alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb"
14+ ```
12 15
13-## Step 1 — Build rzb16+- About 400 MB of free disk space, and an internet connection for the first download.
17+- [`uv`](https://docs.astral.sh/uv/) for step 5 (`brew install uv`).
18+
19+## Step 1 — Download a small model
14 20
15 Type:21 Type:
16 22
17 ```bash23 ```bash
18-xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \24+rzb models pull mlx-community/Qwen3-0.6B-4bit
19- -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
20 ```25 ```
21 26
22-The first build downloads and compiles the dependencies and takes several minutes. It ends with:27+A progress bar runs, then you should see:
23 28
24 ```29 ```
25-** BUILD SUCCEEDED **30+mlx-community/Qwen3-0.6B-4bit is downloaded.
26 ```31 ```
27 32
28-Now put the folder that holds `rzb` on your `PATH` for this terminal, and check it:33+We now have a small model (0.6 billion parameters, 4-bit) in the Hugging Face cache on this Mac.
34+
35+## Step 2 — Start the server
36+
37+Type:
29 38
30 ```bash39 ```bash
31-export PATH="$PWD/.build/xcode/Build/Products/Release:$PATH"40+rzb serve
32-rzb version
33 ```41 ```
34 42
35 You should see:43 You should see:
36 44
37 ```45 ```
38-rzb 0.1.0 (engines: fake, mlx)46+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (no API key) — Ctrl-C to stop
39 ```47 ```
40 48
41-We have a working `rzb` that can run MLX models.49+The server is running and only accepts connections from this Mac. Leave this terminal open, and **open a second terminal** for the next steps.
42 50
43-## Step 2 — Create an agent51+## Step 3 — Check that it answers
44 52
45-We work in a new, empty folder:53+In the second terminal, type:
46 54
47 ```bash55 ```bash
48-mkdir -p ~/rzb-tutorial && cd ~/rzb-tutorial56+curl -s http://127.0.0.1:8080/health
49-rzb init --yes --name helper --model mlx-community/Qwen3-0.6B-4bit
50 ```57 ```
51 58
52 You should see:59 You should see:
53 60
61+```json
62+{"status":"ok"}
54 ```63 ```
55-Wrote razorbill.yaml. Next: rzb chat --config razorbill.yaml
56-It will be downloaded on first use (or now with: rzb models pull mlx-community/Qwen3-0.6B-4bit).
57-```
58-
59-Open `razorbill.yaml`: it describes the agent — its name, its model, its generation settings and its system prompt — with a comment on every line.
60 64
61-## Step 3 — Download the model65+Now ask which models it can serve:
62-
63-Type:
64 66
65 ```bash67 ```bash
66-rzb models pull mlx-community/Qwen3-0.6B-4bit68+curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool
67-```
68-
69-A progress line counts up to 100 % and ends with:
70-
71-```
72-mlx-community/Qwen3-0.6B-4bit is downloaded.
73 ```69 ```
74 70
75-Check that razorbill sees it:71+You should see a list that contains the model we downloaded:
76 72
77-```bash73+```json
78-rzb models list74+{
75+ "data": [
76+ {
77+ "created": 1764096000,
78+ "id": "mlx-community/Qwen3-0.6B-4bit",
79+ "kind": "chat",
80+ "loaded": false,
81+ "object": "model",
82+ "owned_by": "razorbill"
83+ }
84+ ],
85+ "object": "list"
86+}
79 ```87 ```
80 88
81-You should see a line starting with `mlx-community/Qwen3-0.6B-4bit` followed by its size (about 350 MB) and `main`.89+`"loaded": false`: the model is on disk but not in memory yet. It will be loaded by the first request.
82 90
83-## Step 4 — Ask one question91+## Step 4 — Ask a question with curl
84 92
85 Type:93 Type:
86 94
87 ```bash95 ```bash
88-rzb run "What is the capital of France? Answer in one sentence."96+curl -s http://127.0.0.1:8080/v1/chat/completions \
97+ -H "Content-Type: application/json" \
98+ -d '{
99+ "model": "mlx-community/Qwen3-0.6B-4bit",
100+ "messages": [{"role": "user", "content": "What is the capital of France? One sentence."}]
101+ }' | python3 -m json.tool
89 ```102 ```
90 103
91-`rzb` finds `razorbill.yaml` in the current folder, loads the model and prints an answer such as:104+The first request takes a second or two longer: the model is being loaded. You should see an answer of this shape (the exact sentence may differ):
92 105
93-```106+```json
94-The capital of France is Paris.107+{
95-[24 prompt tokens, 9 generated, 150.2 tokens/s]108+ "choices": [
109+ {
110+ "finish_reason": "stop",
111+ "index": 0,
112+ "logprobs": null,
113+ "message": {
114+ "content": "The capital of France is Paris.",
115+ "role": "assistant"
116+ }
117+ }
118+ ],
119+ "created": 1764096042,
120+ "id": "chatcmpl-3f9c2a…",
121+ "model": "mlx-community/Qwen3-0.6B-4bit",
122+ "object": "chat.completion",
123+ "usage": {
124+ "completion_tokens": 9,
125+ "prompt_tokens": 20,
126+ "total_tokens": 29
127+ }
128+}
96 ```129 ```
97 130
98-The numbers on the last line change from one Mac to another. We have just run a language model on the GPU, entirely on this Mac.131+In the first terminal, the server has logged the model load and the request, for example:
99 132
100-## Step 5 — Have a conversation133+```
101-134+2026-11-25T19:20:41+0100 info rzb: [RazorbillServer] loaded mlx-community/Qwen3-0.6B-4bit in 0.43 seconds
102-Type:135+2026-11-25T19:20:42+0100 info rzb: [RazorbillServer] POST /v1/chat/completions 200 812ms model=mlx-community/Qwen3-0.6B-4bit tokens=20+9
103-
104-```bash
105-rzb chat
106 ```136 ```
107 137
108-You should see the agent's name, its model and its engine, then a prompt:138+We have just run a model on the GPU through the same API as OpenAI's.
109 139
110-```140+## Step 5 — Use the openai Python library
111-helper · mlx-community/Qwen3-0.6B-4bit · mlx — /help for commands
112-›
113-```
114 141
115-Type `My name is Ada.`, press Enter, then type `What is my name?`. The agent remembers the first message and answers with your name. Type `/exit` to leave.142+Any program written for the OpenAI API can use the server by changing its base URL. Create a file `first.py` with this content:
116 143
117-## Step 6 — Let the agent run a command144+```python
145+from openai import OpenAI
118 146
119-Open `razorbill.yaml` in an editor and replace the line `tools: {}` with these two lines:147+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
120 148
121-```yaml149+stream = client.chat.completions.create(
122-tools:150+ model="mlx-community/Qwen3-0.6B-4bit",
123- bash: {}151+ messages=[{"role": "user", "content": "Write a haiku about the sea."}],
152+ stream=True,
153+)
154+for chunk in stream:
155+ if chunk.choices and chunk.choices[0].delta.content:
156+ print(chunk.choices[0].delta.content, end="", flush=True)
157+print()
124 ```158 ```
125 159
126-Start the chat again and ask for something only a command can tell:160+Run it:
127 161
128 ```bash162 ```bash
129-rzb chat163+uv run --with openai python first.py
130-```
131-
132-```
133-› How many files are in the current folder? Use the bash tool.
134 ```164 ```
135 165
136-The model asks to run a command, and `rzb` asks you first:166+You should see a haiku appear word by word, for example:
137 167
138 ```168 ```
139-→ bash command="ls | wc -l"169+Waves fold into foam,
140-170+salt wind carries gull voices—
141-bash wants to run: ls | wc -l (in /Users/you/rzb-tutorial)171+the tide keeps its time.
142-Allow? [y/N]:
143 ```172 ```
144 173
145-The exact command may differ. Type `y` and press Enter. The command runs, its result goes back to the model, and the model answers — here, that there is one file (`razorbill.yaml`). Type `/exit`.174+The server does not check `api_key` because we did not set one; the library still requires a value.
175+
176+## Step 6 — Stop the server
146 177
147-Small models sometimes skip the tool and guess. If that happens, ask again, or set `model:` to `mlx-community/Qwen3-1.7B-4bit` (download it first with `rzb models pull`).178+In the first terminal, press **Ctrl-C**. The server unloads the model and exits.
148 179
149 ## What now?180 ## What now?
150 181
151-You have built `rzb`, described an agent in a YAML file, run a model on your GPU and given it a tool it can only use with your consent. To go further:182+You have downloaded a model, served it on your Mac, and called it with `curl` and with the `openai` library, streaming included. To go further:
152 183
153-- Try the full-screen interface: `rzb tui`.184+- Give your models short names, defaults and limits: [How to configure the server](../how-to/configure-the-server.md).
154-- To accomplish specific tasks → the [how-to guides](../README.md#do--how-to-guides), such as [configuring thinking](../how-to/configure-thinking.md) or [using the bash tool](../how-to/use-the-bash-tool.md).185+- Get JSON that follows a schema: [How to get structured output](../how-to/get-structured-output.md).
155-- Every key of the file → the [agent file reference](../reference/configuration.md).186+- Let the model call your functions: [How to use function calling](../how-to/use-function-calling.md).
156-- How razorbill is put together → the [architecture explanation](../explanation/architecture.md).187+- Every endpoint and field: [HTTP API reference](../reference/http-api.md).
188+- How the server works inside: [Architecture](../explanation/architecture.md).
modified docs/fr/README.md +19 -14
@@ -1,32 +1,37 @@
11 # Documentation de razorbill
22
3-razorbill est un agent d'IA local pour le Mac. Sa commande, `rzb`, fait tourner des modèles sur le GPU avec MLX, lit la description de l'agent dans un fichier YAML, et dialogue avec vous en ligne de commande ou dans une interface plein écran du terminal.
3+razorbill est un serveur de modèles pour le Mac. Sa commande, `rzb serve`, fait tourner des modèles MLX sur le GPU Apple Silicon et les expose par une API HTTP compatible OpenAI : complétions de chat (streaming, sortie structurée, appel de fonctions, raisonnement), complétions de texte historiques et embeddings. Les clients et frameworks OpenAI existants l'utilisent en changeant leur URL de base.
44
5-Cette documentation suit [Diátaxis](https://diataxis.fr) : choisissez la section qui correspond à ce dont vous avez besoin maintenant.
5+Cette documentation suit [Diátaxis](https://diataxis.fr) : choisissez la section qui correspond à votre besoin du moment.
66
77 ## Apprendre — tutoriels
88
9-- [Premiers pas](tutorials/premiers-pas.md) : compiler `rzb`, créer un agent, discuter avec lui et le laisser lancer une commande.
9+- [Vos premières requêtes à un modèle local](tutorials/premiers-pas.md) : télécharger un modèle, démarrer le serveur, l'appeler avec `curl` et avec la bibliothèque `openai`.
1010
1111 ## Faire — guides pratiques
1212
1313 - [Compiler rzb sur le Mac](how-to/compiler-sur-le-mac.md)
1414 - [Gérer les modèles](how-to/gerer-les-modeles.md)
15-- [Régler la réflexion](how-to/regler-la-reflexion.md)
16-- [Utiliser l'outil bash](how-to/utiliser-l-outil-bash.md)
17-- [Utiliser rzb dans des scripts](how-to/utiliser-rzb-dans-des-scripts.md)
18-- [Ajouter un outil](how-to/ajouter-un-outil.md)
19-- [Lancer les tests](how-to/lancer-les-tests.md)
15+- [Configurer le serveur](how-to/configurer-le-serveur.md) : noms de modèles, valeurs par défaut, verrous, limites, accès réseau.
16+- [Utiliser razorbill depuis un client OpenAI](how-to/utiliser-des-clients-openai.md) : Python, JavaScript, LangChain, interfaces de chat.
17+- [Obtenir une sortie structurée](how-to/obtenir-une-sortie-structuree.md)
18+- [Utiliser l'appel de fonctions](how-to/utiliser-l-appel-de-fonctions.md)
19+- [Calculer des embeddings](how-to/calculer-des-embeddings.md)
20+- [Régler le raisonnement](how-to/regler-la-reflexion.md)
21+- [Lancer les tests](how-to/lancer-les-tests.md), suite de compatibilité OpenAI comprise.
2022 - [Développer depuis une sandbox Linux](how-to/developper-depuis-une-sandbox.md)
2123
2224 ## Consulter — référence
2325
24-- [Ligne de commande](reference/ligne-de-commande.md) : commandes, options, codes de sortie, commandes du chat, touches du TUI.
25-- [Fichier d'agent](reference/configuration.md) : chaque clé YAML, son type, sa valeur par défaut et ses erreurs.
26-- [Outil bash](reference/outil-bash.md) : options, vérifications, sortie envoyée au modèle.
26+- [API HTTP](reference/api-http.md) : endpoints, champs pris en charge, refusés et ignorés, réponses, streaming.
27+- [Fichier de configuration du serveur](reference/configuration.md) : chaque clé, son type, sa valeur par défaut et ses erreurs.
28+- [Ligne de commande](reference/ligne-de-commande.md) : `rzb serve`, `rzb models`, `rzb config validate`, codes de sortie.
29+- [Erreurs de l'API](reference/erreurs.md) : statuts, types et codes.
2730
2831 ## Comprendre — explications
2932
30-- [Architecture](explanation/architecture.md) : les modules, pourquoi le code est découpé ainsi, pourquoi la compilation sur le Mac passe par `xcodebuild`.
31-- [Modèles qui réfléchissent](explanation/reflexion.md) : comment la réflexion est séparée de la réponse, affichée et limitée.
32-- [Sécurité des outils](explanation/securite-des-outils.md) : ce contre quoi l'outil bash protège, et ce contre quoi il ne protège pas.
33+- [Architecture](explanation/architecture.md) : les modules, le trajet d'une requête, pourquoi la compilation sur le Mac passe par `xcodebuild`.
34+- [Cycle de vie des modèles et concurrence](explanation/cycle-de-vie-des-modeles.md) : chargement, files d'attente, mémoire, déchargement, annulation.
35+- [Décodage contraint](explanation/decodage-contraint.md) : comment le JSON et les appels d'outils sont garantis, et les limites.
36+- [Modèles qui raisonnent](explanation/reflexion.md) : comment le raisonnement est séparé, envoyé ou masqué, et limité.
37+- [Compatibilité OpenAI](explanation/compatibilite-openai.md) : ce que « compatible » veut dire ici, et comment c'est vérifié.
@@ -1,32 +1,37 @@
1 # Documentation de razorbill1 # Documentation de razorbill
2 2
3-razorbill est un agent d'IA local pour le Mac. Sa commande, `rzb`, fait tourner des modèles sur le GPU avec MLX, lit la description de l'agent dans un fichier YAML, et dialogue avec vous en ligne de commande ou dans une interface plein écran du terminal.3+razorbill est un serveur de modèles pour le Mac. Sa commande, `rzb serve`, fait tourner des modèles MLX sur le GPU Apple Silicon et les expose par une API HTTP compatible OpenAI : complétions de chat (streaming, sortie structurée, appel de fonctions, raisonnement), complétions de texte historiques et embeddings. Les clients et frameworks OpenAI existants l'utilisent en changeant leur URL de base.
4 4
5-Cette documentation suit [Diátaxis](https://diataxis.fr) : choisissez la section qui correspond à ce dont vous avez besoin maintenant.5+Cette documentation suit [Diátaxis](https://diataxis.fr) : choisissez la section qui correspond à votre besoin du moment.
6 6
7 ## Apprendre — tutoriels7 ## Apprendre — tutoriels
8 8
9-- [Premiers pas](tutorials/premiers-pas.md) : compiler `rzb`, créer un agent, discuter avec lui et le laisser lancer une commande.9+- [Vos premières requêtes à un modèle local](tutorials/premiers-pas.md) : télécharger un modèle, démarrer le serveur, l'appeler avec `curl` et avec la bibliothèque `openai`.
10 10
11 ## Faire — guides pratiques11 ## Faire — guides pratiques
12 12
13 - [Compiler rzb sur le Mac](how-to/compiler-sur-le-mac.md)13 - [Compiler rzb sur le Mac](how-to/compiler-sur-le-mac.md)
14 - [Gérer les modèles](how-to/gerer-les-modeles.md)14 - [Gérer les modèles](how-to/gerer-les-modeles.md)
15-- [Régler la réflexion](how-to/regler-la-reflexion.md)15+- [Configurer le serveur](how-to/configurer-le-serveur.md) : noms de modèles, valeurs par défaut, verrous, limites, accès réseau.
16-- [Utiliser l'outil bash](how-to/utiliser-l-outil-bash.md)16+- [Utiliser razorbill depuis un client OpenAI](how-to/utiliser-des-clients-openai.md) : Python, JavaScript, LangChain, interfaces de chat.
17-- [Utiliser rzb dans des scripts](how-to/utiliser-rzb-dans-des-scripts.md)17+- [Obtenir une sortie structurée](how-to/obtenir-une-sortie-structuree.md)
18-- [Ajouter un outil](how-to/ajouter-un-outil.md)18+- [Utiliser l'appel de fonctions](how-to/utiliser-l-appel-de-fonctions.md)
19-- [Lancer les tests](how-to/lancer-les-tests.md)19+- [Calculer des embeddings](how-to/calculer-des-embeddings.md)
20+- [Régler le raisonnement](how-to/regler-la-reflexion.md)
21+- [Lancer les tests](how-to/lancer-les-tests.md), suite de compatibilité OpenAI comprise.
20 - [Développer depuis une sandbox Linux](how-to/developper-depuis-une-sandbox.md)22 - [Développer depuis une sandbox Linux](how-to/developper-depuis-une-sandbox.md)
21 23
22 ## Consulter — référence24 ## Consulter — référence
23 25
24-- [Ligne de commande](reference/ligne-de-commande.md) : commandes, options, codes de sortie, commandes du chat, touches du TUI.26+- [API HTTP](reference/api-http.md) : endpoints, champs pris en charge, refusés et ignorés, réponses, streaming.
25-- [Fichier d'agent](reference/configuration.md) : chaque clé YAML, son type, sa valeur par défaut et ses erreurs.27+- [Fichier de configuration du serveur](reference/configuration.md) : chaque clé, son type, sa valeur par défaut et ses erreurs.
26-- [Outil bash](reference/outil-bash.md) : options, vérifications, sortie envoyée au modèle.28+- [Ligne de commande](reference/ligne-de-commande.md) : `rzb serve`, `rzb models`, `rzb config validate`, codes de sortie.
29+- [Erreurs de l'API](reference/erreurs.md) : statuts, types et codes.
27 30
28 ## Comprendre — explications31 ## Comprendre — explications
29 32
30-- [Architecture](explanation/architecture.md) : les modules, pourquoi le code est découpé ainsi, pourquoi la compilation sur le Mac passe par `xcodebuild`.33+- [Architecture](explanation/architecture.md) : les modules, le trajet d'une requête, pourquoi la compilation sur le Mac passe par `xcodebuild`.
31-- [Modèles qui réfléchissent](explanation/reflexion.md) : comment la réflexion est séparée de la réponse, affichée et limitée.34+- [Cycle de vie des modèles et concurrence](explanation/cycle-de-vie-des-modeles.md) : chargement, files d'attente, mémoire, déchargement, annulation.
32-- [Sécurité des outils](explanation/securite-des-outils.md) : ce contre quoi l'outil bash protège, et ce contre quoi il ne protège pas.35+- [Décodage contraint](explanation/decodage-contraint.md) : comment le JSON et les appels d'outils sont garantis, et les limites.
36+- [Modèles qui raisonnent](explanation/reflexion.md) : comment le raisonnement est séparé, envoyé ou masqué, et limité.
37+- [Compatibilité OpenAI](explanation/compatibilite-openai.md) : ce que « compatible » veut dire ici, et comment c'est vérifié.
modified docs/fr/explanation/architecture.md +26 -27
@@ -2,55 +2,54 @@
22
33 ## De quoi s'agit-il ?
44
5-razorbill est un seul package Swift qui produit un seul exécutable, `rzb`. À l'intérieur, le code est découpé en cinq modules, avec un sens de dépendance strict. Cette page explique ce découpage, le chemin d'un message à travers lui, et quelques décisions qui déterminent la façon dont le projet est compilé.
5+razorbill est un seul package Swift qui produit un seul exécutable, `rzb`, un serveur de modèles : il charge des modèles MLX sur le GPU du Mac et les expose par une API HTTP compatible OpenAI. À l'intérieur, le code est découpé en cinq modules, avec un sens de dépendance strict. Cette page explique ce découpage, le trajet d'une requête à travers lui, et quelques décisions qui façonnent la manière dont le projet est construit.
66
7-Le diagramme [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) montre les modules, leurs dépendances et les packages tiers.
7+Le schéma [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) montre les modules, leurs dépendances et les packages tiers.
88
99 ## Les modules
1010
1111 | Module | Rôle | Dépend de |
1212 | --- | --- | --- |
13-| `RazorbillCore` | Le fichier d'agent (chargement, validation, variables), la boucle de l'agent, les protocoles des moteurs et des outils, l'outil `bash`, le cache des modèles. | Yams |
14-| `RazorbillMLX` | Le moteur MLX : téléchargement, chargement, sessions de conversation, détection et budget de la réflexion. | Core, mlx-swift-lm, swift-huggingface, swift-transformers (macOS seulement) |
15-| `RazorbillTUI` | L'interface plein écran, sur une petite couche ANSI maison. | Core |
16-| `RazorbillCLI` | Les commandes (`init`, `run`, `chat`, `tui`, `models`, `config`, `version`) et le chat ligne par ligne. | Core, TUI, swift-argument-parser |
13+| `RazorbillCore` | Le protocole des moteurs et leurs événements, les réglages de génération, les contraintes de sortie, le fichier de configuration du serveur (chargement, validation), le catalogue et le cache des modèles, le moteur factice. | Yams |
14+| `RazorbillMLX` | Les moteurs MLX : sessions de chat, complétions brutes, détection et budget de la réflexion, décodage contraint (XGrammar), embeddings. | Core, mlx-swift-lm, mlx-swift, swift-huggingface, swift-transformers (macOS seulement) |
15+| `RazorbillServer` | Le serveur HTTP : routes, types de requêtes et de réponses OpenAI, streaming, erreurs, authentification, gestionnaire de modèles. | Core, Hummingbird, swift-service-lifecycle |
16+| `RazorbillCLI` | Les commandes (`serve`, `config validate`, `models`, `version`). | Core, Server, swift-argument-parser, swift-log |
1717 | `rzb` | L'exécutable : enregistre les moteurs et lance la ligne de commande. | CLI, MLX |
1818
19-Tout pointe vers `RazorbillCore`, et `RazorbillCore` ne sait rien de MLX, des terminaux ni de l'analyse de la ligne de commande. C'est la propriété que le reste de la conception protège.
19+Tout pointe vers `RazorbillCore`, et `RazorbillCore` ne sait rien de MLX, de HTTP ni de l'analyse de la ligne de commande. `RazorbillServer` ne connaît pas MLX non plus : il ne parle aux moteurs qu'à travers le protocole.
2020
2121 ## Pourquoi ce découpage
2222
23-**Le cœur doit se compiler sans GPU.** MLX a besoin de Metal, qui n'existe que sur les plateformes Apple. Garder MLX hors du cœur permet de compiler et de tester sur Linux la configuration, la boucle de l'agent, les outils, la CLI et le TUI — et c'est sur Linux que se fait l'essentiel du développement (voir [développer depuis une sandbox Linux](../how-to/developper-depuis-une-sandbox.md)). `RazorbillMLX` ne lie mlx-swift-lm que sur macOS et son code est protégé par `#if canImport(MLXLLM)` ; sur Linux le module est vide et `rzb` n'a que le moteur `fake`.
23+**Tout sauf MLX doit se compiler et se tester sans GPU.** MLX a besoin de Metal, qui n'existe que sur les plateformes Apple. Le tenir à l'écart du cœur et du serveur permet de compiler et de tester sur Linux la configuration, la couche HTTP, les types OpenAI, le streaming, le gestionnaire de modèles et la ligne de commande — c'est là que se fait l'essentiel du développement (voir [développer depuis une sandbox Linux](../how-to/developper-depuis-une-sandbox.md)). Sous Linux, `RazorbillMLX` est vide et `rzb` n'a que le moteur `fake`, qui répond `echo: …` : assez pour tester tout le serveur, et pour faire passer la suite de compatibilité OpenAI sur son protocole.
2424
25-**Les moteurs sont remplaçables.** L'agent parle à un protocole `InferenceEngine` : charger un modèle, ouvrir une session, envoyer des messages, recevoir un flux d'événements (texte, raisonnement, appels d'outils, statistiques). MLX en est une implémentation ; `FakeEngine` en est une autre, qui joue des tours scriptés et permet de tester l'agent, la CLI et le TUI sans modèle. Un autre moteur (llama.cpp, une API distante) serait un module de plus derrière le même protocole, choisi avec `--engine`.
25+**Les moteurs sont remplaçables.** Le serveur demande à un `InferenceEngine` de charger un modèle, d'ouvrir une session, d'envoyer des messages et de produire un flux d'événements (texte, raisonnement, appels d'outils, statistiques), de continuer un prompt brut, ou d'encoder des textes. MLX est une implémentation ; un autre runtime serait un module de plus derrière le même protocole.
2626
27-**Les interfaces sont minces.** `run`, `chat` et `tui` passent tous par le même `AgentLauncher` : trouver et charger le fichier, appliquer les options de la ligne de commande, construire les outils, choisir le moteur, charger le modèle. Ils ne diffèrent que par la façon de lire la saisie et d'afficher les événements. Le TUI sépare son état (`ChatState`) et son dessin (`ScreenRenderer`) du vrai terminal (`PosixTerminal`), ce qui permet de tester son comportement avec un faux terminal.
27+**La couche OpenAI est mince et stricte.** Les types de requêtes décodent le JSON d'OpenAI, vérifient chaque champ et produisent un plan (messages, réglages, contrainte de sortie). Les champs que razorbill ne sait pas honorer sont refusés avec un 400 qui les nomme au lieu d'être ignorés en silence (voir [compatibilité OpenAI](compatibilite-openai.md)).
2828
29-## La boucle de l'agent
29+## Le trajet d'une requête de chat
3030
31-1. Le message de l'utilisateur est ajouté à la conversation et envoyé au moteur avec le prompt système et la description des outils.
32-2. Le moteur envoie des événements au fil de l'eau. Le texte et le raisonnement vont directement à l'interface.
33-3. Quand le modèle demande un outil, l'agent l'exécute (après les vérifications propres à l'outil et, pour `bash`, l'accord de l'utilisateur) et renvoie le résultat au modèle, qui continue.
34-4. Le tour se termine quand le modèle répond sans appeler d'outil, ou après 8 tours d'outils (une erreur arrête alors le tour).
31+1. Hummingbird reçoit `POST /v1/chat/completions`. Des middlewares la journalisent, appliquent CORS, vérifient la clé d'API et transforment toute erreur en corps d'erreur OpenAI.
32+2. Le corps est décodé et validé en un `ChatPlan` ; les JSON Schemas sont relus pour garder l'ordre de leurs clés. Avec `response_format`, une consigne contenant le schéma est ajoutée au message système.
33+3. Le gestionnaire de modèles résout le nom (identifiant déclaré, ou identifiant Hugging Face), charge le modèle si besoin et donne à la requête un **bail** : une génération par modèle à la fois, les autres attendent dans une file (voir [cycle de vie des modèles](cycle-de-vie-des-modeles.md)).
34+4. Le moteur ouvre une nouvelle session avec les réglages et la contrainte de la requête, met la conversation en forme avec le chat template du modèle et produit des événements.
35+5. Les événements deviennent des morceaux OpenAI : les séquences d'arrêt sont appliquées, le raisonnement est séparé ou masqué, les appels d'outils sont numérotés, `finish_reason` et `usage` sont calculés.
36+6. Les morceaux sont rassemblés en un `chat.completion`, ou envoyés en Server-Sent Events au fil de l'eau. Quand la réponse se termine — ou que le client se déconnecte — le bail est libéré.
3537
36-La conversation (`transcript`) reste en mémoire pendant la session ; `/reset` et Ctrl-N l'effacent en gardant le modèle chargé.
38+Le serveur est sans état : chaque requête porte toute la conversation, et rien n'est conservé entre les requêtes, sauf les modèles chargés.
3739
3840 ## Pourquoi la compilation sur le Mac passe par xcodebuild
3941
40-MLX fournit des shaders Metal qui doivent être compilés en `default.metallib`. `swift build` (SwiftPM) ne sait pas compiler Metal : un binaire compilé ainsi échoue avec `Failed to load the default metallib` dès qu'un modèle se charge. `xcodebuild` les compile dans `mlx-swift_Cmlx.bundle`, qui doit rester à côté de `rzb`. Sur Linux il n'y a pas de MLX, donc `swift build` / `swift test` suffisent.
41-
42-## Pourquoi une couche TUI maison
43-
44-L'interface plein écran a besoin de peu de choses : la lecture du clavier en mode brut, l'écran alternatif, quelques couleurs, le redimensionnement, et la restauration du terminal à chaque sortie. Une petite couche au-dessus de termios et des codes ANSI fait cela sans dépendance, garde le TUI testable (le terminal est un protocole), et évite de dépendre d'une bibliothèque qui devrait prendre en charge à la fois macOS et Linux.
42+MLX fournit des shaders Metal qui doivent être compilés dans un `default.metallib`. Le `swift build` de SwiftPM ne sait pas compiler du Metal : un binaire construit ainsi échoue avec `Failed to load the default metallib` dès qu'un modèle se charge. `xcodebuild` les compile dans `mlx-swift_Cmlx.bundle`, qui doit rester à côté de `rzb`. Sous Linux il n'y a pas de MLX, donc `swift build` / `swift test` suffisent.
4543
4644 ## Alternatives écartées
4745
48-- **Un serveur HTTP comme Ollama** a été la première idée. Elle a été abandonnée au profit d'un agent qui charge ses propres modèles : pas de serveur à démarrer, un seul processus, un seul fichier de configuration.
49-- **Un fichier avec plusieurs agents** a été écarté pour la v0.1 : un fichier par agent garde le format et la recherche simples.
50-- **Une configuration en Swift ou en JSON** : YAML a été choisi pour les commentaires, la lisibilité, et des messages d'erreur avec numéro de ligne.
46+- **Un agent local** (version 0.1) : `rzb` faisait d'abord tourner un agent décrit dans un fichier YAML, dans le terminal, avec ses propres outils. Il a été remplacé par un serveur, parce qu'une API compatible OpenAI permet à tous les clients, frameworks et agents existants d'utiliser le GPU du Mac, au lieu d'une seule interface intégrée.
47+- **L'API d'Ollama** (`/api/chat`…) en plus de celle d'OpenAI : deux API à maintenir compatibles pour un seul bénéfice ; c'est l'API d'OpenAI que parlent les frameworks.
48+- **Vapor au lieu de Hummingbird** : Hummingbird 2 est plus petit, bâti sur la concurrence structurée, et suffit pour six endpoints.
49+- **Python (le serveur de mlx-lm)** : razorbill est un seul binaire natif, sans environnement Python à installer.
5150
5251 ## Lien avec le reste
5352
54-- Les clés du fichier d'agent : [référence du fichier d'agent](../reference/configuration.md).
55-- Comment le moteur MLX gère le raisonnement : [modèles qui réfléchissent](reflexion.md).
56-- Ce que les outils peuvent faire ou non : [sécurité des outils](securite-des-outils.md).
53+- Comment les modèles sont chargés, partagés et déchargés : [cycle de vie des modèles](cycle-de-vie-des-modeles.md).
54+- Comment le JSON et les appels d'outils sont garantis : [décodage contraint](decodage-contraint.md).
55+- Comment le raisonnement est séparé des réponses : [modèles qui raisonnent](reflexion.md).
@@ -2,55 +2,54 @@
2 2
3 ## De quoi s'agit-il ?3 ## De quoi s'agit-il ?
4 4
5-razorbill est un seul package Swift qui produit un seul exécutable, `rzb`. À l'intérieur, le code est découpé en cinq modules, avec un sens de dépendance strict. Cette page explique ce découpage, le chemin d'un message à travers lui, et quelques décisions qui déterminent la façon dont le projet est compilé.5+razorbill est un seul package Swift qui produit un seul exécutable, `rzb`, un serveur de modèles : il charge des modèles MLX sur le GPU du Mac et les expose par une API HTTP compatible OpenAI. À l'intérieur, le code est découpé en cinq modules, avec un sens de dépendance strict. Cette page explique ce découpage, le trajet d'une requête à travers lui, et quelques décisions qui façonnent la manière dont le projet est construit.
6 6
7-Le diagramme [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) montre les modules, leurs dépendances et les packages tiers.7+Le schéma [docs/diagrams/packages.drawio](../../diagrams/packages.drawio) montre les modules, leurs dépendances et les packages tiers.
8 8
9 ## Les modules9 ## Les modules
10 10
11 | Module | Rôle | Dépend de |11 | Module | Rôle | Dépend de |
12 | --- | --- | --- |12 | --- | --- | --- |
13-| `RazorbillCore` | Le fichier d'agent (chargement, validation, variables), la boucle de l'agent, les protocoles des moteurs et des outils, l'outil `bash`, le cache des modèles. | Yams |13+| `RazorbillCore` | Le protocole des moteurs et leurs événements, les réglages de génération, les contraintes de sortie, le fichier de configuration du serveur (chargement, validation), le catalogue et le cache des modèles, le moteur factice. | Yams |
14-| `RazorbillMLX` | Le moteur MLX : téléchargement, chargement, sessions de conversation, détection et budget de la réflexion. | Core, mlx-swift-lm, swift-huggingface, swift-transformers (macOS seulement) |14+| `RazorbillMLX` | Les moteurs MLX : sessions de chat, complétions brutes, détection et budget de la réflexion, décodage contraint (XGrammar), embeddings. | Core, mlx-swift-lm, mlx-swift, swift-huggingface, swift-transformers (macOS seulement) |
15-| `RazorbillTUI` | L'interface plein écran, sur une petite couche ANSI maison. | Core |15+| `RazorbillServer` | Le serveur HTTP : routes, types de requêtes et de réponses OpenAI, streaming, erreurs, authentification, gestionnaire de modèles. | Core, Hummingbird, swift-service-lifecycle |
16-| `RazorbillCLI` | Les commandes (`init`, `run`, `chat`, `tui`, `models`, `config`, `version`) et le chat ligne par ligne. | Core, TUI, swift-argument-parser |16+| `RazorbillCLI` | Les commandes (`serve`, `config validate`, `models`, `version`). | Core, Server, swift-argument-parser, swift-log |
17 | `rzb` | L'exécutable : enregistre les moteurs et lance la ligne de commande. | CLI, MLX |17 | `rzb` | L'exécutable : enregistre les moteurs et lance la ligne de commande. | CLI, MLX |
18 18
19-Tout pointe vers `RazorbillCore`, et `RazorbillCore` ne sait rien de MLX, des terminaux ni de l'analyse de la ligne de commande. C'est la propriété que le reste de la conception protège.19+Tout pointe vers `RazorbillCore`, et `RazorbillCore` ne sait rien de MLX, de HTTP ni de l'analyse de la ligne de commande. `RazorbillServer` ne connaît pas MLX non plus : il ne parle aux moteurs qu'à travers le protocole.
20 20
21 ## Pourquoi ce découpage21 ## Pourquoi ce découpage
22 22
23-**Le cœur doit se compiler sans GPU.** MLX a besoin de Metal, qui n'existe que sur les plateformes Apple. Garder MLX hors du cœur permet de compiler et de tester sur Linux la configuration, la boucle de l'agent, les outils, la CLI et le TUI — et c'est sur Linux que se fait l'essentiel du développement (voir [développer depuis une sandbox Linux](../how-to/developper-depuis-une-sandbox.md)). `RazorbillMLX` ne lie mlx-swift-lm que sur macOS et son code est protégé par `#if canImport(MLXLLM)` ; sur Linux le module est vide et `rzb` n'a que le moteur `fake`.23+**Tout sauf MLX doit se compiler et se tester sans GPU.** MLX a besoin de Metal, qui n'existe que sur les plateformes Apple. Le tenir à l'écart du cœur et du serveur permet de compiler et de tester sur Linux la configuration, la couche HTTP, les types OpenAI, le streaming, le gestionnaire de modèles et la ligne de commande — c'est là que se fait l'essentiel du développement (voir [développer depuis une sandbox Linux](../how-to/developper-depuis-une-sandbox.md)). Sous Linux, `RazorbillMLX` est vide et `rzb` n'a que le moteur `fake`, qui répond `echo: …` : assez pour tester tout le serveur, et pour faire passer la suite de compatibilité OpenAI sur son protocole.
24 24
25-**Les moteurs sont remplaçables.** L'agent parle à un protocole `InferenceEngine` : charger un modèle, ouvrir une session, envoyer des messages, recevoir un flux d'événements (texte, raisonnement, appels d'outils, statistiques). MLX en est une implémentation ; `FakeEngine` en est une autre, qui joue des tours scriptés et permet de tester l'agent, la CLI et le TUI sans modèle. Un autre moteur (llama.cpp, une API distante) serait un module de plus derrière le même protocole, choisi avec `--engine`.25+**Les moteurs sont remplaçables.** Le serveur demande à un `InferenceEngine` de charger un modèle, d'ouvrir une session, d'envoyer des messages et de produire un flux d'événements (texte, raisonnement, appels d'outils, statistiques), de continuer un prompt brut, ou d'encoder des textes. MLX est une implémentation ; un autre runtime serait un module de plus derrière le même protocole.
26 26
27-**Les interfaces sont minces.** `run`, `chat` et `tui` passent tous par le même `AgentLauncher` : trouver et charger le fichier, appliquer les options de la ligne de commande, construire les outils, choisir le moteur, charger le modèle. Ils ne diffèrent que par la façon de lire la saisie et d'afficher les événements. Le TUI sépare son état (`ChatState`) et son dessin (`ScreenRenderer`) du vrai terminal (`PosixTerminal`), ce qui permet de tester son comportement avec un faux terminal.27+**La couche OpenAI est mince et stricte.** Les types de requêtes décodent le JSON d'OpenAI, vérifient chaque champ et produisent un plan (messages, réglages, contrainte de sortie). Les champs que razorbill ne sait pas honorer sont refusés avec un 400 qui les nomme au lieu d'être ignorés en silence (voir [compatibilité OpenAI](compatibilite-openai.md)).
28 28
29-## La boucle de l'agent29+## Le trajet d'une requête de chat
30 30
31-1. Le message de l'utilisateur est ajouté à la conversation et envoyé au moteur avec le prompt système et la description des outils.31+1. Hummingbird reçoit `POST /v1/chat/completions`. Des middlewares la journalisent, appliquent CORS, vérifient la clé d'API et transforment toute erreur en corps d'erreur OpenAI.
32-2. Le moteur envoie des événements au fil de l'eau. Le texte et le raisonnement vont directement à l'interface.32+2. Le corps est décodé et validé en un `ChatPlan` ; les JSON Schemas sont relus pour garder l'ordre de leurs clés. Avec `response_format`, une consigne contenant le schéma est ajoutée au message système.
33-3. Quand le modèle demande un outil, l'agent l'exécute (après les vérifications propres à l'outil et, pour `bash`, l'accord de l'utilisateur) et renvoie le résultat au modèle, qui continue.33+3. Le gestionnaire de modèles résout le nom (identifiant déclaré, ou identifiant Hugging Face), charge le modèle si besoin et donne à la requête un **bail** : une génération par modèle à la fois, les autres attendent dans une file (voir [cycle de vie des modèles](cycle-de-vie-des-modeles.md)).
34-4. Le tour se termine quand le modèle répond sans appeler d'outil, ou après 8 tours d'outils (une erreur arrête alors le tour).34+4. Le moteur ouvre une nouvelle session avec les réglages et la contrainte de la requête, met la conversation en forme avec le chat template du modèle et produit des événements.
35+5. Les événements deviennent des morceaux OpenAI : les séquences d'arrêt sont appliquées, le raisonnement est séparé ou masqué, les appels d'outils sont numérotés, `finish_reason` et `usage` sont calculés.
36+6. Les morceaux sont rassemblés en un `chat.completion`, ou envoyés en Server-Sent Events au fil de l'eau. Quand la réponse se termine — ou que le client se déconnecte — le bail est libéré.
35 37
36-La conversation (`transcript`) reste en mémoire pendant la session ; `/reset` et Ctrl-N l'effacent en gardant le modèle chargé.38+Le serveur est sans état : chaque requête porte toute la conversation, et rien n'est conservé entre les requêtes, sauf les modèles chargés.
37 39
38 ## Pourquoi la compilation sur le Mac passe par xcodebuild40 ## Pourquoi la compilation sur le Mac passe par xcodebuild
39 41
40-MLX fournit des shaders Metal qui doivent être compilés en `default.metallib`. `swift build` (SwiftPM) ne sait pas compiler Metal : un binaire compilé ainsi échoue avec `Failed to load the default metallib` dès qu'un modèle se charge. `xcodebuild` les compile dans `mlx-swift_Cmlx.bundle`, qui doit rester à côté de `rzb`. Sur Linux il n'y a pas de MLX, donc `swift build` / `swift test` suffisent.42+MLX fournit des shaders Metal qui doivent être compilés dans un `default.metallib`. Le `swift build` de SwiftPM ne sait pas compiler du Metal : un binaire construit ainsi échoue avec `Failed to load the default metallib` dès qu'un modèle se charge. `xcodebuild` les compile dans `mlx-swift_Cmlx.bundle`, qui doit rester à côté de `rzb`. Sous Linux il n'y a pas de MLX, donc `swift build` / `swift test` suffisent.
41-
42-## Pourquoi une couche TUI maison
43-
44-L'interface plein écran a besoin de peu de choses : la lecture du clavier en mode brut, l'écran alternatif, quelques couleurs, le redimensionnement, et la restauration du terminal à chaque sortie. Une petite couche au-dessus de termios et des codes ANSI fait cela sans dépendance, garde le TUI testable (le terminal est un protocole), et évite de dépendre d'une bibliothèque qui devrait prendre en charge à la fois macOS et Linux.
45 43
46 ## Alternatives écartées44 ## Alternatives écartées
47 45
48-- **Un serveur HTTP comme Ollama** a été la première idée. Elle a été abandonnée au profit d'un agent qui charge ses propres modèles : pas de serveur à démarrer, un seul processus, un seul fichier de configuration.46+- **Un agent local** (version 0.1) : `rzb` faisait d'abord tourner un agent décrit dans un fichier YAML, dans le terminal, avec ses propres outils. Il a été remplacé par un serveur, parce qu'une API compatible OpenAI permet à tous les clients, frameworks et agents existants d'utiliser le GPU du Mac, au lieu d'une seule interface intégrée.
49-- **Un fichier avec plusieurs agents** a été écarté pour la v0.1 : un fichier par agent garde le format et la recherche simples.47+- **L'API d'Ollama** (`/api/chat`…) en plus de celle d'OpenAI : deux API à maintenir compatibles pour un seul bénéfice ; c'est l'API d'OpenAI que parlent les frameworks.
50-- **Une configuration en Swift ou en JSON** : YAML a été choisi pour les commentaires, la lisibilité, et des messages d'erreur avec numéro de ligne.48+- **Vapor au lieu de Hummingbird** : Hummingbird 2 est plus petit, bâti sur la concurrence structurée, et suffit pour six endpoints.
49+- **Python (le serveur de mlx-lm)** : razorbill est un seul binaire natif, sans environnement Python à installer.
51 50
52 ## Lien avec le reste51 ## Lien avec le reste
53 52
54-- Les clés du fichier d'agent : [référence du fichier d'agent](../reference/configuration.md).53+- Comment les modèles sont chargés, partagés et déchargés : [cycle de vie des modèles](cycle-de-vie-des-modeles.md).
55-- Comment le moteur MLX gère le raisonnement : [modèles qui réfléchissent](reflexion.md).54+- Comment le JSON et les appels d'outils sont garantis : [décodage contraint](decodage-contraint.md).
56-- Ce que les outils peuvent faire ou non : [sécurité des outils](securite-des-outils.md).55+- Comment le raisonnement est séparé des réponses : [modèles qui raisonnent](reflexion.md).
added docs/fr/explanation/compatibilite-openai.md +45 -0
new file mode 100644
@@ -0,0 +1,45 @@
1+# Compatibilité OpenAI — explication
2+
3+## De quoi s'agit-il ?
4+
5+« Compatible OpenAI » est une promesse sans spécification : OpenAI documente sa propre API, pas ce qu'un autre serveur doit faire pour la remplacer. Chaque serveur local trace la frontière quelque part. Cette page explique où razorbill la trace, et comment elle est vérifiée.
6+
7+## Le but : que les clients existants fonctionnent sans changement
8+
9+Le critère n'est pas « le serveur accepte-t-il les champs documentés » mais « un programme écrit pour OpenAI fonctionne-t-il quand on change son URL de base ». Cela déplace l'attention vers ce que font réellement les clients : le `parse()` de la bibliothèque Python openai avec une classe Pydantic, le `bind_tools` et les `OpenAIEmbeddings` de LangChain, le streaming avec `include_usage`, les embeddings en base64 (que la bibliothèque openai demande par défaut, sans le dire), les corps d'erreur que les bibliothèques transforment en exceptions typées.
10+
11+## Refuser plutôt qu'ignorer
12+
13+Quand une requête demande quelque chose que razorbill ne sait pas faire — plusieurs choix (`n`), des log-probabilités, des images, du fill-in-the-middle, un mot-clé de schéma qu'il ne sait pas appliquer, un appel d'outil forcé dans une syntaxe non prise en charge — le serveur répond 400 et nomme le champ. Ignorer le champ renverrait une réponse qui a l'air juste et n'est pas ce que le client a demandé : un choix au lieu de trois, une règle de schéma enfreinte en silence. Une erreur claire se trouve au premier test ; une différence silencieuse se trouve en production.
14+
15+Les champs qui ne changent rien d'important sont ignorés, comme OpenAI ignore lui-même les champs inconnus : `user`, `metadata`, `store`, `service_tier`…
16+
17+## Des extensions empruntées plutôt qu'inventées
18+
19+Les modèles locaux font des choses pour lesquelles l'API d'OpenAI n'a pas de champ, surtout autour du raisonnement. Quand un autre serveur a déjà défini une convention, razorbill la suit, pour que les clients qui la connaissent fonctionnent sans changement :
20+
21+| Besoin | Champ | Emprunté à |
22+| --- | --- | --- |
23+| Renvoyer le raisonnement à part de la réponse | `reasoning_content` (message et deltas) | DeepSeek, vLLM |
24+| Activer ou couper la réflexion | `chat_template_kwargs.enable_thinking` | vLLM |
25+| Masquer le raisonnement | `include_reasoning: false` | OpenRouter |
26+| Compter les tokens de raisonnement | `usage.completion_tokens_details.reasoning_tokens` | OpenAI |
27+
28+Seul `thinking_budget` est propre à razorbill, faute de convention commune pour une limite stricte des tokens de raisonnement. `/v1/models` ajoute aussi `loaded` et `kind` à chaque modèle, que les clients ignorent.
29+
30+## Différences assumées
31+
32+- **Les valeurs par défaut viennent du serveur.** Les complétions historiques d'OpenAI ont 16 tokens par défaut ; razorbill utilise le `max_tokens` configuré sur le serveur, parce qu'un opérateur local règle ses limites une fois pour tous les clients.
33+- **Le prompt peut changer.** Avec `response_format`, le serveur ajoute au message système une consigne contenant le schéma (voir [décodage contraint](decodage-contraint.md)). Les modèles d'OpenAI sont entraînés pour la sortie structurée ; les modèles locaux ont besoin qu'on le leur dise.
34+- **Les réglages verrouillés l'emportent.** Un opérateur peut imposer `temperature` ou plafonner `max_tokens` pour tous les clients, ce qui n'a pas d'équivalent dans l'API d'OpenAI.
35+
36+## Comment la compatibilité est vérifiée
37+
38+Les tests unitaires vérifient les formes ; ils ne peuvent pas vérifier que les vraies bibliothèques font la même lecture de ces formes que nous. Une suite à part, `Tests/Compatibility`, pilote un `rzb serve` en marche avec les clients officiels — la bibliothèque `openai`, LangChain, et chaque exemple `curl` de la référence de l'API — et vérifie ce que verrait un utilisateur : un objet Pydantic analysé, un aller-retour d'appel d'outil, des similarités cosinus égales à celles de la bibliothèque Python `sentence-transformers`, des exceptions typées sur les erreurs.
39+
40+Elle tourne en deux modes. Sous Linux, contre le moteur factice, elle vérifie le protocole à chaque changement. Sur le Mac, contre MLX avec de vrais modèles, elle vérifie le comportement ; son premier passage a trouvé deux vrais défauts (clés de schéma triées, et modèles qui raisonnent écrivant de la prose dans les champs JSON), que les tests unitaires n'avaient aucun moyen de voir.
41+
42+## Lien avec le reste
43+
44+- Ce qui est pris en charge, refusé et ignoré, champ par champ : [référence de l'API HTTP](../reference/api-http.md).
45+- Lancer la suite : [lancer les tests](../how-to/lancer-les-tests.md#vérifier-la-compatibilité-avec-de-vrais-clients-openai).
new file mode 100644
@@ -0,0 +1,45 @@
1+# Compatibilité OpenAI — explication
2+
3+## De quoi s'agit-il ?
4+
5+« Compatible OpenAI » est une promesse sans spécification : OpenAI documente sa propre API, pas ce qu'un autre serveur doit faire pour la remplacer. Chaque serveur local trace la frontière quelque part. Cette page explique où razorbill la trace, et comment elle est vérifiée.
6+
7+## Le but : que les clients existants fonctionnent sans changement
8+
9+Le critère n'est pas « le serveur accepte-t-il les champs documentés » mais « un programme écrit pour OpenAI fonctionne-t-il quand on change son URL de base ». Cela déplace l'attention vers ce que font réellement les clients : le `parse()` de la bibliothèque Python openai avec une classe Pydantic, le `bind_tools` et les `OpenAIEmbeddings` de LangChain, le streaming avec `include_usage`, les embeddings en base64 (que la bibliothèque openai demande par défaut, sans le dire), les corps d'erreur que les bibliothèques transforment en exceptions typées.
10+
11+## Refuser plutôt qu'ignorer
12+
13+Quand une requête demande quelque chose que razorbill ne sait pas faire — plusieurs choix (`n`), des log-probabilités, des images, du fill-in-the-middle, un mot-clé de schéma qu'il ne sait pas appliquer, un appel d'outil forcé dans une syntaxe non prise en charge — le serveur répond 400 et nomme le champ. Ignorer le champ renverrait une réponse qui a l'air juste et n'est pas ce que le client a demandé : un choix au lieu de trois, une règle de schéma enfreinte en silence. Une erreur claire se trouve au premier test ; une différence silencieuse se trouve en production.
14+
15+Les champs qui ne changent rien d'important sont ignorés, comme OpenAI ignore lui-même les champs inconnus : `user`, `metadata`, `store`, `service_tier`…
16+
17+## Des extensions empruntées plutôt qu'inventées
18+
19+Les modèles locaux font des choses pour lesquelles l'API d'OpenAI n'a pas de champ, surtout autour du raisonnement. Quand un autre serveur a déjà défini une convention, razorbill la suit, pour que les clients qui la connaissent fonctionnent sans changement :
20+
21+| Besoin | Champ | Emprunté à |
22+| --- | --- | --- |
23+| Renvoyer le raisonnement à part de la réponse | `reasoning_content` (message et deltas) | DeepSeek, vLLM |
24+| Activer ou couper la réflexion | `chat_template_kwargs.enable_thinking` | vLLM |
25+| Masquer le raisonnement | `include_reasoning: false` | OpenRouter |
26+| Compter les tokens de raisonnement | `usage.completion_tokens_details.reasoning_tokens` | OpenAI |
27+
28+Seul `thinking_budget` est propre à razorbill, faute de convention commune pour une limite stricte des tokens de raisonnement. `/v1/models` ajoute aussi `loaded` et `kind` à chaque modèle, que les clients ignorent.
29+
30+## Différences assumées
31+
32+- **Les valeurs par défaut viennent du serveur.** Les complétions historiques d'OpenAI ont 16 tokens par défaut ; razorbill utilise le `max_tokens` configuré sur le serveur, parce qu'un opérateur local règle ses limites une fois pour tous les clients.
33+- **Le prompt peut changer.** Avec `response_format`, le serveur ajoute au message système une consigne contenant le schéma (voir [décodage contraint](decodage-contraint.md)). Les modèles d'OpenAI sont entraînés pour la sortie structurée ; les modèles locaux ont besoin qu'on le leur dise.
34+- **Les réglages verrouillés l'emportent.** Un opérateur peut imposer `temperature` ou plafonner `max_tokens` pour tous les clients, ce qui n'a pas d'équivalent dans l'API d'OpenAI.
35+
36+## Comment la compatibilité est vérifiée
37+
38+Les tests unitaires vérifient les formes ; ils ne peuvent pas vérifier que les vraies bibliothèques font la même lecture de ces formes que nous. Une suite à part, `Tests/Compatibility`, pilote un `rzb serve` en marche avec les clients officiels — la bibliothèque `openai`, LangChain, et chaque exemple `curl` de la référence de l'API — et vérifie ce que verrait un utilisateur : un objet Pydantic analysé, un aller-retour d'appel d'outil, des similarités cosinus égales à celles de la bibliothèque Python `sentence-transformers`, des exceptions typées sur les erreurs.
39+
40+Elle tourne en deux modes. Sous Linux, contre le moteur factice, elle vérifie le protocole à chaque changement. Sur le Mac, contre MLX avec de vrais modèles, elle vérifie le comportement ; son premier passage a trouvé deux vrais défauts (clés de schéma triées, et modèles qui raisonnent écrivant de la prose dans les champs JSON), que les tests unitaires n'avaient aucun moyen de voir.
41+
42+## Lien avec le reste
43+
44+- Ce qui est pris en charge, refusé et ignoré, champ par champ : [référence de l'API HTTP](../reference/api-http.md).
45+- Lancer la suite : [lancer les tests](../how-to/lancer-les-tests.md#vérifier-la-compatibilité-avec-de-vrais-clients-openai).
added docs/fr/explanation/cycle-de-vie-des-modeles.md +48 -0
new file mode 100644
@@ -0,0 +1,48 @@
1+# Cycle de vie des modèles et concurrence — explication
2+
3+## De quoi s'agit-il ?
4+
5+Un modèle, ce sont des gigaoctets de poids dans la mémoire unifiée du Mac, et générer avec lui occupe le GPU. Le serveur doit décider quand charger un modèle, qui peut l'utiliser, que faire quand plusieurs clients arrivent en même temps, et quand rendre la mémoire. Tout cela vit à un seul endroit, le **gestionnaire de modèles** (`ModelManager`, un acteur de `RazorbillServer`). Cette page explique ses règles et pourquoi elles ont été choisies.
6+
7+## Un chargement, partagé
8+
9+Un modèle est chargé par la première requête qui en a besoin — ou au démarrage quand il est déclaré avec `preload: true` — puis partagé par toutes les requêtes. Deux noms qui désignent le même dépôt (un `id` déclaré et son identifiant Hugging Face, ou deux entrées déclarées avec des réglages différents) partagent un seul chargement : le gestionnaire range les modèles par dépôt et révision, pas par le nom envoyé par le client. Un chargement « chat » et un chargement « embedding » du même dépôt sont des modèles différents, car ils sont chargés par des moteurs différents.
10+
11+## Une génération à la fois par modèle
12+
13+Les requêtes pour un même modèle sont servies **une à la fois, dans l'ordre d'arrivée**. Les autres attendent dans une file d'au plus `limits.max_queue` requêtes ; au-delà, le serveur répond immédiatement 429 plutôt que de laisser les clients s'accumuler.
14+
15+Pourquoi ne pas faire tourner plusieurs générations d'un même modèle à la fois ? Sur Apple Silicon, la génération de tokens est surtout limitée par la bande passante mémoire : entrelacer des générations indépendantes rapporte peu, chaque réponse arrive plus tard, et chacune a besoin de son propre cache KV en mémoire. Ce qui augmenterait le débit, c'est de regrouper plusieurs séquences dans une même passe (batching), et razorbill ne le fait pas (encore). Une file est simple, équitable, et donne à chaque client toute la vitesse du GPU quand vient son tour.
16+
17+Des modèles différents, eux, tournent en parallèle : une réponse de chat et une requête d'embedding utilisent deux modèles différents, donc deux files différentes.
18+
19+## Faire de la place
20+
21+Deux limites décident du nombre de modèles chargés :
22+
23+- `limits.max_loaded_models` (1 par défaut) : un nombre, facile à raisonner.
24+- un budget mémoire de 75 % de la mémoire du Mac : les poids des modèles chargés, lus d'après la taille de leurs fichiers `.safetensors`, ne peuvent pas le dépasser. Le quart restant est pour macOS, les autres applications et les caches KV.
25+
26+Quand un modèle doit être chargé et qu'une des limites serait dépassée, le gestionnaire décharge le modèle **inactif utilisé le moins récemment**, puis le suivant, jusqu'à ce que le nouveau tienne. Un modèle en train de répondre n'est jamais déchargé. Si tous les modèles chargés sont occupés, la requête reçoit un 503 `server_busy` ; si le modèle est plus gros que tout le budget, un 503 `insufficient_memory`. Échouer vite a été préféré à l'attente : le client peut réessayer, ou l'opérateur changer les limites, alors qu'une attente silencieuse ressemble à un serveur bloqué.
27+
28+## Décharger les modèles inactifs
29+
30+Un service en arrière-plan vérifie régulièrement (tous les quarts de `keep_alive`, au plus toutes les 30 secondes) et décharge les modèles inutilisés depuis `limits.keep_alive` (10 minutes par défaut). La requête suivante recharge le modèle, ce qui coûte quelques secondes pour un petit modèle. Quand le serveur s'arrête (Ctrl-C, SIGTERM), tous les modèles sont déchargés avant la fin du processus.
31+
32+## Quand le client s'en va
33+
34+Une génération que personne ne lira gaspille le GPU et retarde toute la file. Le serveur surveille donc la connexion pendant qu'il répond : quand le client se déconnecte, la tâche de génération est annulée, le tour du modèle est libéré et la requête suivante démarre. Une requête encore en attente est simplement retirée de la file.
35+
36+Pendant un flux, un client disparu n'est remarqué que lorsqu'une écriture échoue. Tant que le modèle est silencieux (chargement, lecture d'un long prompt, réflexion masquée), le serveur écrit un commentaire `: keep-alive` toutes les cinq secondes, si bien qu'un client parti est repéré en quelques secondes. Surveiller la connexion oblige à lire la requête jusqu'au bout, d'où le `Connection: close` des endpoints de génération.
37+
38+## Alternatives écartées
39+
40+- **Un processus par modèle** (comme le font certains serveurs) : de l'isolation, mais chaque modèle paierait la mémoire du runtime, et partager des limites entre processus demande un coordinateur.
41+- **Décharger sur un signal de pression mémoire de macOS** au lieu d'un budget : le signal arrive tard, quand le swap a déjà commencé ; un budget est prévisible.
42+- **Attendre de la place au lieu de répondre 503** : une requête pourrait attendre indéfiniment derrière de longues générations ; une erreur claire est plus facile à traiter.
43+
44+## Lien avec le reste
45+
46+- Les clés qui règlent ces limites : [référence de la configuration](../reference/configuration.md#limits).
47+- Les erreurs que voit un client : [référence des erreurs](../reference/erreurs.md#codes).
48+- La place du gestionnaire dans une requête : [architecture](architecture.md#le-trajet-dune-requête-de-chat).
new file mode 100644
@@ -0,0 +1,48 @@
1+# Cycle de vie des modèles et concurrence — explication
2+
3+## De quoi s'agit-il ?
4+
5+Un modèle, ce sont des gigaoctets de poids dans la mémoire unifiée du Mac, et générer avec lui occupe le GPU. Le serveur doit décider quand charger un modèle, qui peut l'utiliser, que faire quand plusieurs clients arrivent en même temps, et quand rendre la mémoire. Tout cela vit à un seul endroit, le **gestionnaire de modèles** (`ModelManager`, un acteur de `RazorbillServer`). Cette page explique ses règles et pourquoi elles ont été choisies.
6+
7+## Un chargement, partagé
8+
9+Un modèle est chargé par la première requête qui en a besoin — ou au démarrage quand il est déclaré avec `preload: true` — puis partagé par toutes les requêtes. Deux noms qui désignent le même dépôt (un `id` déclaré et son identifiant Hugging Face, ou deux entrées déclarées avec des réglages différents) partagent un seul chargement : le gestionnaire range les modèles par dépôt et révision, pas par le nom envoyé par le client. Un chargement « chat » et un chargement « embedding » du même dépôt sont des modèles différents, car ils sont chargés par des moteurs différents.
10+
11+## Une génération à la fois par modèle
12+
13+Les requêtes pour un même modèle sont servies **une à la fois, dans l'ordre d'arrivée**. Les autres attendent dans une file d'au plus `limits.max_queue` requêtes ; au-delà, le serveur répond immédiatement 429 plutôt que de laisser les clients s'accumuler.
14+
15+Pourquoi ne pas faire tourner plusieurs générations d'un même modèle à la fois ? Sur Apple Silicon, la génération de tokens est surtout limitée par la bande passante mémoire : entrelacer des générations indépendantes rapporte peu, chaque réponse arrive plus tard, et chacune a besoin de son propre cache KV en mémoire. Ce qui augmenterait le débit, c'est de regrouper plusieurs séquences dans une même passe (batching), et razorbill ne le fait pas (encore). Une file est simple, équitable, et donne à chaque client toute la vitesse du GPU quand vient son tour.
16+
17+Des modèles différents, eux, tournent en parallèle : une réponse de chat et une requête d'embedding utilisent deux modèles différents, donc deux files différentes.
18+
19+## Faire de la place
20+
21+Deux limites décident du nombre de modèles chargés :
22+
23+- `limits.max_loaded_models` (1 par défaut) : un nombre, facile à raisonner.
24+- un budget mémoire de 75 % de la mémoire du Mac : les poids des modèles chargés, lus d'après la taille de leurs fichiers `.safetensors`, ne peuvent pas le dépasser. Le quart restant est pour macOS, les autres applications et les caches KV.
25+
26+Quand un modèle doit être chargé et qu'une des limites serait dépassée, le gestionnaire décharge le modèle **inactif utilisé le moins récemment**, puis le suivant, jusqu'à ce que le nouveau tienne. Un modèle en train de répondre n'est jamais déchargé. Si tous les modèles chargés sont occupés, la requête reçoit un 503 `server_busy` ; si le modèle est plus gros que tout le budget, un 503 `insufficient_memory`. Échouer vite a été préféré à l'attente : le client peut réessayer, ou l'opérateur changer les limites, alors qu'une attente silencieuse ressemble à un serveur bloqué.
27+
28+## Décharger les modèles inactifs
29+
30+Un service en arrière-plan vérifie régulièrement (tous les quarts de `keep_alive`, au plus toutes les 30 secondes) et décharge les modèles inutilisés depuis `limits.keep_alive` (10 minutes par défaut). La requête suivante recharge le modèle, ce qui coûte quelques secondes pour un petit modèle. Quand le serveur s'arrête (Ctrl-C, SIGTERM), tous les modèles sont déchargés avant la fin du processus.
31+
32+## Quand le client s'en va
33+
34+Une génération que personne ne lira gaspille le GPU et retarde toute la file. Le serveur surveille donc la connexion pendant qu'il répond : quand le client se déconnecte, la tâche de génération est annulée, le tour du modèle est libéré et la requête suivante démarre. Une requête encore en attente est simplement retirée de la file.
35+
36+Pendant un flux, un client disparu n'est remarqué que lorsqu'une écriture échoue. Tant que le modèle est silencieux (chargement, lecture d'un long prompt, réflexion masquée), le serveur écrit un commentaire `: keep-alive` toutes les cinq secondes, si bien qu'un client parti est repéré en quelques secondes. Surveiller la connexion oblige à lire la requête jusqu'au bout, d'où le `Connection: close` des endpoints de génération.
37+
38+## Alternatives écartées
39+
40+- **Un processus par modèle** (comme le font certains serveurs) : de l'isolation, mais chaque modèle paierait la mémoire du runtime, et partager des limites entre processus demande un coordinateur.
41+- **Décharger sur un signal de pression mémoire de macOS** au lieu d'un budget : le signal arrive tard, quand le swap a déjà commencé ; un budget est prévisible.
42+- **Attendre de la place au lieu de répondre 503** : une requête pourrait attendre indéfiniment derrière de longues générations ; une erreur claire est plus facile à traiter.
43+
44+## Lien avec le reste
45+
46+- Les clés qui règlent ces limites : [référence de la configuration](../reference/configuration.md#limits).
47+- Les erreurs que voit un client : [référence des erreurs](../reference/erreurs.md#codes).
48+- La place du gestionnaire dans une requête : [architecture](architecture.md#le-trajet-dune-requête-de-chat).
added docs/fr/explanation/decodage-contraint.md +53 -0
new file mode 100644
@@ -0,0 +1,53 @@
1+# Décodage contraint — explication
2+
3+## De quoi s'agit-il ?
4+
5+Un modèle de langage écrit un token à la fois, chacun tiré d'une distribution de probabilité sur tout son vocabulaire. Lui demander poliment du JSON marche la plupart du temps ; « la plupart du temps » ne suffit pas à un programme qui analyse la réponse. La sortie structurée (`response_format`) et les appels d'outils forcés (`tool_choice: required`) sont donc **garantis** par razorbill, pas seulement demandés : à chaque étape, les tokens qui casseraient le format attendu sont retirés avant le tirage. Cette page explique comment, où cela s'arrête, et les leçons tirées de sa construction.
6+
7+## Comment fonctionne la garantie
8+
9+razorbill utilise XGrammar, le moteur de grammaires fourni avec mlx-swift-lm. Un JSON Schema (ou un format d'appel d'outil) est compilé en grammaire pour le tokenizer du modèle. Pendant la génération, un processeur de logits demande à la grammaire, à chaque étape, quels tokens peuvent venir ensuite, et donne à tous les autres une probabilité nulle. Quoi que le modèle « veuille », il ne peut écrire qu'une suite valide ; quand la grammaire est complète, la génération s'arrête.
10+
11+Le processeur s'insère dans la boucle de génération normale de mlx-swift-lm. Température, top-p, pénalités, budget de réflexion, streaming et analyse des appels d'outils continuent de fonctionner : la contrainte ne fait que restreindre le choix des tokens.
12+
13+**Les modèles qui raisonnent réfléchissent d'abord.** Le processeur reste inactif jusqu'à ce que le modèle ferme son raisonnement (`</think>`) : le raisonnement est du texte libre, puis la réponse est contrainte. Contraindre aussi le raisonnement le transformerait en JSON, et le modèle perdrait le bénéfice de la réflexion.
14+
15+## La grammaire ne suffit pas : prévenir le modèle
16+
17+La première version ne faisait que contraindre. Mesuré avec Qwen3-4B, cela marchait bien quand le modèle répondait directement, mais avec la réflexion activée, les réponses étaient du JSON valide au contenu absurde : un paragraphe de prose dans un champ `"country"`, une population écrite comme une suite de chiffres sans fin. La cause est évidente une fois vue : rien dans le prompt ne disait qu'un JSON était attendu, donc le modèle préparait une réponse en prose pendant sa réflexion, et la grammaire forçait ensuite cette prose dans les champs.
18+
19+razorbill **prévient** donc aussi le modèle : avec `response_format`, une phrase est ajoutée au message système, avec le schéma pour `json_schema`. Avec elle, le même test est passé de la prose dans les champs à trois réponses correctes sur trois, avec une réflexion deux fois plus courte. La grammaire garantit la forme ; la consigne rend le contenu sensé. Les modèles d'OpenAI sont entraînés pour la sortie structurée et n'en ont pas besoin ; les modèles locaux, si.
20+
21+## L'ordre des clés
22+
23+Une grammaire générée depuis un schéma écrit les propriétés d'un objet dans l'ordre où le schéma les liste. Cet ordre compte pour les clients : placer un champ `reasoning` avant `answer` est une façon connue de laisser un modèle réfléchir avant de s'engager. La première version de razorbill le perdait : le décodeur JSON de Swift ne conserve pas l'ordre des clés d'un objet, et les schémas arrivaient à la grammaire triés par ordre alphabétique. Les schémas des requêtes sont maintenant lus avec un analyseur qui conserve l'ordre.
24+
25+## Ce qui ne peut pas être garanti
26+
27+**Certains mots-clés de JSON Schema** sont acceptés par XGrammar mais pas appliqués : `not`, `if` / `then` / `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. Avec `"strict": true`, le client a demandé une garantie : razorbill refuse donc un tel schéma avec un 400 qui nomme le mot-clé, plutôt que de renvoyer en silence une sortie qui pourrait l'enfreindre. Sans `strict`, ils sont ignorés.
28+
29+**Les appels d'outils forcés dépendent de la famille du modèle.** Chaque famille écrit ses appels dans sa propre syntaxe : `<tool_call>{"name": …, "arguments": …}</tool_call>` pour Qwen et Hermes, `<|python_tag|>` et d'autres formes pour Llama, `[TOOL_CALLS]` pour Mistral… razorbill construit des grammaires de forçage (les « structural tags » de XGrammar) pour la seule syntaxe JSON `<tool_call>`, qui couvre les modèles locaux à outils les plus courants. Pour les autres familles, `tool_choice: required`, une fonction nommée ou un outil `strict` sont refusés avec un 400, et `auto` fonctionne toujours grâce aux analyseurs de mlx-swift-lm.
30+
31+**Le contenu.** Une grammaire garantit que `population` est un entier, pas que c'est le bon. Les petits modèles (moins d'environ 1 milliard de paramètres) respectent les schémas de façon fiable mais les remplissent mal ; à température 0, ils peuvent aussi boucler dans une longue chaîne jusqu'à `max_tokens`. Préférez un modèle de 4B ou plus pour l'extraction.
32+
33+## Pièges des petits modèles que le serveur gère
34+
35+- **Boucles d'espaces.** Le JSON autorise n'importe quelle quantité d'espaces entre les tokens, et la version de XGrammar fournie ne la limite pas. Qwen3-0.6B, contraint, écrivait parfois des sauts de ligne sans fin. razorbill pénalise les longues suites de tokens d'espacement tant qu'une contrainte est active.
36+- **Appels répétés.** Sous `tool_choice: required`, un petit modèle peut appeler le même outil encore et encore jusqu'à `max_tokens`, et le dernier appel, tronqué, est perdu. Un appel forcé produit donc un seul appel, sauf si le client envoie explicitement `parallel_tool_calls: true`.
37+- **Réponses JSON envoyées d'un bloc.** L'analyseur d'appels d'outils de mlx-swift-lm retient toute réponse qui commence par `{`, au cas où ce serait un appel d'outil en JSON nu. Sans outils dans la requête, razorbill passe à un analyseur sans ce repli, et le JSON arrive token par token.
38+
39+## Coûts
40+
41+La grammaire est compilée pour chaque requête (environ 0,2 s) : la version de XGrammar fournie ne sait pas copier une grammaire compilée, et la mettre en cache reviendrait à partager un état modifiable entre requêtes. Masquer le vocabulaire à chaque étape ralentit aussi la génération ; mesuré sur un petit modèle dans une compilation de débogage, environ 90 tokens/s en génération libre contre environ 49 sous contrainte.
42+
43+## Alternatives écartées
44+
45+- **Valider après la génération et recommencer** : aucune garantie, un coût sans borne, et le streaming montrerait une sortie invalide.
46+- **Seulement la consigne, sans grammaire** : ce que font les modèles sans aide est justement ce que la garantie doit couvrir.
47+- **Forcer les appels d'outils pour toutes les familles avec des grammaires écrites à la main** : chaque syntaxe est une charge de maintenance ; refuser clairement est honnête tant qu'aucun besoin réel n'apparaît.
48+
49+## Lien avec le reste
50+
51+- Comment s'en servir : [obtenir une sortie structurée](../how-to/obtenir-une-sortie-structuree.md) et [utiliser l'appel de fonctions](../how-to/utiliser-l-appel-de-fonctions.md).
52+- Les champs exacts et les refus : [référence de l'API HTTP](../reference/api-http.md#sortie-structurée).
53+- Comment le raisonnement est séparé avant que la contrainte s'applique : [modèles qui raisonnent](reflexion.md).
new file mode 100644
@@ -0,0 +1,53 @@
1+# Décodage contraint — explication
2+
3+## De quoi s'agit-il ?
4+
5+Un modèle de langage écrit un token à la fois, chacun tiré d'une distribution de probabilité sur tout son vocabulaire. Lui demander poliment du JSON marche la plupart du temps ; « la plupart du temps » ne suffit pas à un programme qui analyse la réponse. La sortie structurée (`response_format`) et les appels d'outils forcés (`tool_choice: required`) sont donc **garantis** par razorbill, pas seulement demandés : à chaque étape, les tokens qui casseraient le format attendu sont retirés avant le tirage. Cette page explique comment, où cela s'arrête, et les leçons tirées de sa construction.
6+
7+## Comment fonctionne la garantie
8+
9+razorbill utilise XGrammar, le moteur de grammaires fourni avec mlx-swift-lm. Un JSON Schema (ou un format d'appel d'outil) est compilé en grammaire pour le tokenizer du modèle. Pendant la génération, un processeur de logits demande à la grammaire, à chaque étape, quels tokens peuvent venir ensuite, et donne à tous les autres une probabilité nulle. Quoi que le modèle « veuille », il ne peut écrire qu'une suite valide ; quand la grammaire est complète, la génération s'arrête.
10+
11+Le processeur s'insère dans la boucle de génération normale de mlx-swift-lm. Température, top-p, pénalités, budget de réflexion, streaming et analyse des appels d'outils continuent de fonctionner : la contrainte ne fait que restreindre le choix des tokens.
12+
13+**Les modèles qui raisonnent réfléchissent d'abord.** Le processeur reste inactif jusqu'à ce que le modèle ferme son raisonnement (`</think>`) : le raisonnement est du texte libre, puis la réponse est contrainte. Contraindre aussi le raisonnement le transformerait en JSON, et le modèle perdrait le bénéfice de la réflexion.
14+
15+## La grammaire ne suffit pas : prévenir le modèle
16+
17+La première version ne faisait que contraindre. Mesuré avec Qwen3-4B, cela marchait bien quand le modèle répondait directement, mais avec la réflexion activée, les réponses étaient du JSON valide au contenu absurde : un paragraphe de prose dans un champ `"country"`, une population écrite comme une suite de chiffres sans fin. La cause est évidente une fois vue : rien dans le prompt ne disait qu'un JSON était attendu, donc le modèle préparait une réponse en prose pendant sa réflexion, et la grammaire forçait ensuite cette prose dans les champs.
18+
19+razorbill **prévient** donc aussi le modèle : avec `response_format`, une phrase est ajoutée au message système, avec le schéma pour `json_schema`. Avec elle, le même test est passé de la prose dans les champs à trois réponses correctes sur trois, avec une réflexion deux fois plus courte. La grammaire garantit la forme ; la consigne rend le contenu sensé. Les modèles d'OpenAI sont entraînés pour la sortie structurée et n'en ont pas besoin ; les modèles locaux, si.
20+
21+## L'ordre des clés
22+
23+Une grammaire générée depuis un schéma écrit les propriétés d'un objet dans l'ordre où le schéma les liste. Cet ordre compte pour les clients : placer un champ `reasoning` avant `answer` est une façon connue de laisser un modèle réfléchir avant de s'engager. La première version de razorbill le perdait : le décodeur JSON de Swift ne conserve pas l'ordre des clés d'un objet, et les schémas arrivaient à la grammaire triés par ordre alphabétique. Les schémas des requêtes sont maintenant lus avec un analyseur qui conserve l'ordre.
24+
25+## Ce qui ne peut pas être garanti
26+
27+**Certains mots-clés de JSON Schema** sont acceptés par XGrammar mais pas appliqués : `not`, `if` / `then` / `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. Avec `"strict": true`, le client a demandé une garantie : razorbill refuse donc un tel schéma avec un 400 qui nomme le mot-clé, plutôt que de renvoyer en silence une sortie qui pourrait l'enfreindre. Sans `strict`, ils sont ignorés.
28+
29+**Les appels d'outils forcés dépendent de la famille du modèle.** Chaque famille écrit ses appels dans sa propre syntaxe : `<tool_call>{"name": …, "arguments": …}</tool_call>` pour Qwen et Hermes, `<|python_tag|>` et d'autres formes pour Llama, `[TOOL_CALLS]` pour Mistral… razorbill construit des grammaires de forçage (les « structural tags » de XGrammar) pour la seule syntaxe JSON `<tool_call>`, qui couvre les modèles locaux à outils les plus courants. Pour les autres familles, `tool_choice: required`, une fonction nommée ou un outil `strict` sont refusés avec un 400, et `auto` fonctionne toujours grâce aux analyseurs de mlx-swift-lm.
30+
31+**Le contenu.** Une grammaire garantit que `population` est un entier, pas que c'est le bon. Les petits modèles (moins d'environ 1 milliard de paramètres) respectent les schémas de façon fiable mais les remplissent mal ; à température 0, ils peuvent aussi boucler dans une longue chaîne jusqu'à `max_tokens`. Préférez un modèle de 4B ou plus pour l'extraction.
32+
33+## Pièges des petits modèles que le serveur gère
34+
35+- **Boucles d'espaces.** Le JSON autorise n'importe quelle quantité d'espaces entre les tokens, et la version de XGrammar fournie ne la limite pas. Qwen3-0.6B, contraint, écrivait parfois des sauts de ligne sans fin. razorbill pénalise les longues suites de tokens d'espacement tant qu'une contrainte est active.
36+- **Appels répétés.** Sous `tool_choice: required`, un petit modèle peut appeler le même outil encore et encore jusqu'à `max_tokens`, et le dernier appel, tronqué, est perdu. Un appel forcé produit donc un seul appel, sauf si le client envoie explicitement `parallel_tool_calls: true`.
37+- **Réponses JSON envoyées d'un bloc.** L'analyseur d'appels d'outils de mlx-swift-lm retient toute réponse qui commence par `{`, au cas où ce serait un appel d'outil en JSON nu. Sans outils dans la requête, razorbill passe à un analyseur sans ce repli, et le JSON arrive token par token.
38+
39+## Coûts
40+
41+La grammaire est compilée pour chaque requête (environ 0,2 s) : la version de XGrammar fournie ne sait pas copier une grammaire compilée, et la mettre en cache reviendrait à partager un état modifiable entre requêtes. Masquer le vocabulaire à chaque étape ralentit aussi la génération ; mesuré sur un petit modèle dans une compilation de débogage, environ 90 tokens/s en génération libre contre environ 49 sous contrainte.
42+
43+## Alternatives écartées
44+
45+- **Valider après la génération et recommencer** : aucune garantie, un coût sans borne, et le streaming montrerait une sortie invalide.
46+- **Seulement la consigne, sans grammaire** : ce que font les modèles sans aide est justement ce que la garantie doit couvrir.
47+- **Forcer les appels d'outils pour toutes les familles avec des grammaires écrites à la main** : chaque syntaxe est une charge de maintenance ; refuser clairement est honnête tant qu'aucun besoin réel n'apparaît.
48+
49+## Lien avec le reste
50+
51+- Comment s'en servir : [obtenir une sortie structurée](../how-to/obtenir-une-sortie-structuree.md) et [utiliser l'appel de fonctions](../how-to/utiliser-l-appel-de-fonctions.md).
52+- Les champs exacts et les refus : [référence de l'API HTTP](../reference/api-http.md#sortie-structurée).
53+- Comment le raisonnement est séparé avant que la contrainte s'applique : [modèles qui raisonnent](reflexion.md).
modified docs/fr/explanation/reflexion.md +10 -11
@@ -1,16 +1,16 @@
1-# Modèles qui réfléchissent — explication
1+# Modèles qui raisonnent — explication
22
33 ## De quoi s'agit-il ?
44
5-Certains modèles (Qwen3, Qwen3.5, DeepSeek-R1…) écrivent un raisonnement avant leur réponse, entre `<think>` et `</think>`. razorbill doit en faire trois choses : le séparer de la réponse, décider s'il l'affiche, et, si on le lui demande, l'arrêter avant qu'il ne consomme tout le budget de tokens. Cette page explique comment, et pourquoi c'est fait ainsi.
5+Certains modèles (Qwen3, Qwen3.5, DeepSeek-R1…) écrivent un raisonnement avant leur réponse, entre `<think>` et `</think>`. razorbill doit en faire trois choses : le séparer de la réponse (les clients OpenAI attendent que `content` ne contienne que la réponse), décider s'il l'envoie, et, si on le lui demande, l'arrêter avant qu'il ne consomme tout le budget de tokens. Cette page explique comment, et pourquoi c'est fait ainsi.
66
77 ## L'activer, c'est l'affaire du modèle
88
9-Qu'un modèle hybride réfléchisse ou non est décidé par son **gabarit de prompt** (chat template), le programme Jinja fourni avec le modèle qui transforme la conversation en prompt. razorbill transmet `enable_thinking` (issu de `generation.thinking`) au gabarit et le laisse faire le reste. Les modèles qui ne raisonnent pas ignorent simplement ce drapeau.
9+Qu'un modèle hybride réfléchisse ou non est décidé par son **gabarit de prompt** (chat template), le programme Jinja fourni avec le modèle qui transforme la conversation en prompt. razorbill transmet `enable_thinking` au gabarit — d'après la requête (`reasoning_effort`, `chat_template_kwargs.enable_thinking`) ou, à défaut, le `thinking` de la configuration — et le laisse faire le reste. Les modèles qui ne raisonnent pas ignorent simplement ce drapeau. La réflexion est coupée sauf si une requête ou la configuration l'active : la plupart des clients d'API attendent des réponses directes et rapides.
1010
1111 ## Séparer le raisonnement de la réponse
1212
13-Le moteur reçoit la sortie par petits morceaux : une balise peut arriver coupée en deux (`<thi` + `nk>`). Le `ThinkingSplitter` retient tout morceau qui pourrait être le début d'une balise jusqu'à l'arrivée du suivant, puis émet des événements *raisonnement* et des événements *texte*. Les interfaces ne voient que ces événements, et la conversation gardée par l'agent ne contient que la réponse, sans le raisonnement.
13+Le moteur reçoit la sortie par petits morceaux : une balise peut arriver coupée en deux (`<thi` + `nk>`). Le `ThinkingSplitter` retient tout morceau qui pourrait être le début d'une balise jusqu'à l'arrivée du suivant, puis émet des événements *raisonnement* et des événements *texte*. Le serveur les transforme en `reasoning_content` et `content`, dans les réponses entières comme dans les deltas d'un flux.
1414
1515 ### Quand le gabarit ouvre lui-même la balise
1616
@@ -25,14 +25,11 @@ La sortie du modèle commence alors à l'intérieur du raisonnement, et seul `</
2525
2626 Interroger le gabarit, plutôt que tenir une liste de noms de modèles, fait qu'un nouveau modèle qui suit la même convention fonctionne sans changement.
2727
28-## L'afficher
28+## L'envoyer
2929
30-Le raisonnement est utile pour comprendre une réponse et gênant dans un script. L'affichage est donc un réglage distinct de la réflexion (`ui.show_thinking`, activé par défaut) :
30+Le raisonnement est utile pour comprendre une réponse et gênant pour un programme. L'envoyer est donc un réglage distinct de la réflexion : `include_reasoning: false` dans une requête, ou `show_reasoning: false` dans la configuration (dans `locked`, pour tous les clients). Le modèle réfléchit quand même ; seul `reasoning_content` est retiré. `usage.completion_tokens_details.reasoning_tokens` le compte toujours, car ces tokens ont pris du temps et comptent dans `max_tokens`.
3131
32-- dans `run` et `chat`, il va sur la sortie d'erreur, en grisé : rediriger la sortie standard ne garde que la réponse ;
33-- dans `tui`, c'est un bloc à part que Ctrl-T affiche ou masque à tout moment.
34-
35-Un modèle à qui l'on dit de ne pas réfléchir émet souvent quand même un `<think></think>` vide ; un raisonnement vide n'est jamais affiché.
32+Un modèle à qui l'on dit de ne pas réfléchir émet souvent quand même un `<think></think>` vide ; un raisonnement vide n'est jamais envoyé.
3633
3734 ## Le limiter
3835
@@ -49,8 +46,10 @@ La façon de refermer le raisonnement dépend de la famille de modèles :
4946 - **Reconnaître Qwen3.5 à son nom** : fragile ; le gabarit fait foi.
5047 - **Couper le texte après `N` tokens de raisonnement et arrêter la génération** : le modèle n'aurait jamais le temps de répondre.
5148 - **Augmenter `max_tokens` automatiquement quand un budget est fixé** : comportement caché ; la vérification de la configuration exige plutôt un budget plus petit que `max_tokens`.
49+- **Envoyer le raisonnement dans `content`, entre balises `<think>`** : certains serveurs le font ; les clients montrent ou analysent alors les balises comme une partie de la réponse.
5250
5351 ## Lien avec le reste
5452
55-- Les réglages : [régler la réflexion](../how-to/regler-la-reflexion.md) et la [référence du fichier d'agent](../reference/configuration.md#generation).
53+- Les réglages : [régler le raisonnement](../how-to/regler-la-reflexion.md), la [référence de l'API HTTP](../reference/api-http.md#champs-de-la-requête) et la [référence de la configuration](../reference/configuration.md#defaults-et-locked).
54+- Le raisonnement avant la sortie structurée : [décodage contraint](decodage-contraint.md).
5655 - La place du moteur : [architecture](architecture.md).
@@ -1,16 +1,16 @@
1-# Modèles qui réfléchissent — explication1+# Modèles qui raisonnent — explication
2 2
3 ## De quoi s'agit-il ?3 ## De quoi s'agit-il ?
4 4
5-Certains modèles (Qwen3, Qwen3.5, DeepSeek-R1…) écrivent un raisonnement avant leur réponse, entre `<think>` et `</think>`. razorbill doit en faire trois choses : le séparer de la réponse, décider s'il l'affiche, et, si on le lui demande, l'arrêter avant qu'il ne consomme tout le budget de tokens. Cette page explique comment, et pourquoi c'est fait ainsi.5+Certains modèles (Qwen3, Qwen3.5, DeepSeek-R1…) écrivent un raisonnement avant leur réponse, entre `<think>` et `</think>`. razorbill doit en faire trois choses : le séparer de la réponse (les clients OpenAI attendent que `content` ne contienne que la réponse), décider s'il l'envoie, et, si on le lui demande, l'arrêter avant qu'il ne consomme tout le budget de tokens. Cette page explique comment, et pourquoi c'est fait ainsi.
6 6
7 ## L'activer, c'est l'affaire du modèle7 ## L'activer, c'est l'affaire du modèle
8 8
9-Qu'un modèle hybride réfléchisse ou non est décidé par son **gabarit de prompt** (chat template), le programme Jinja fourni avec le modèle qui transforme la conversation en prompt. razorbill transmet `enable_thinking` (issu de `generation.thinking`) au gabarit et le laisse faire le reste. Les modèles qui ne raisonnent pas ignorent simplement ce drapeau.9+Qu'un modèle hybride réfléchisse ou non est décidé par son **gabarit de prompt** (chat template), le programme Jinja fourni avec le modèle qui transforme la conversation en prompt. razorbill transmet `enable_thinking` au gabarit — d'après la requête (`reasoning_effort`, `chat_template_kwargs.enable_thinking`) ou, à défaut, le `thinking` de la configuration — et le laisse faire le reste. Les modèles qui ne raisonnent pas ignorent simplement ce drapeau. La réflexion est coupée sauf si une requête ou la configuration l'active : la plupart des clients d'API attendent des réponses directes et rapides.
10 10
11 ## Séparer le raisonnement de la réponse11 ## Séparer le raisonnement de la réponse
12 12
13-Le moteur reçoit la sortie par petits morceaux : une balise peut arriver coupée en deux (`<thi` + `nk>`). Le `ThinkingSplitter` retient tout morceau qui pourrait être le début d'une balise jusqu'à l'arrivée du suivant, puis émet des événements *raisonnement* et des événements *texte*. Les interfaces ne voient que ces événements, et la conversation gardée par l'agent ne contient que la réponse, sans le raisonnement.13+Le moteur reçoit la sortie par petits morceaux : une balise peut arriver coupée en deux (`<thi` + `nk>`). Le `ThinkingSplitter` retient tout morceau qui pourrait être le début d'une balise jusqu'à l'arrivée du suivant, puis émet des événements *raisonnement* et des événements *texte*. Le serveur les transforme en `reasoning_content` et `content`, dans les réponses entières comme dans les deltas d'un flux.
14 14
15 ### Quand le gabarit ouvre lui-même la balise15 ### Quand le gabarit ouvre lui-même la balise
16 16
@@ -25,14 +25,11 @@ La sortie du modèle commence alors à l'intérieur du raisonnement, et seul `</
25 25
26 Interroger le gabarit, plutôt que tenir une liste de noms de modèles, fait qu'un nouveau modèle qui suit la même convention fonctionne sans changement.26 Interroger le gabarit, plutôt que tenir une liste de noms de modèles, fait qu'un nouveau modèle qui suit la même convention fonctionne sans changement.
27 27
28-## L'afficher28+## L'envoyer
29 29
30-Le raisonnement est utile pour comprendre une réponse et gênant dans un script. L'affichage est donc un réglage distinct de la réflexion (`ui.show_thinking`, activé par défaut) :30+Le raisonnement est utile pour comprendre une réponse et gênant pour un programme. L'envoyer est donc un réglage distinct de la réflexion : `include_reasoning: false` dans une requête, ou `show_reasoning: false` dans la configuration (dans `locked`, pour tous les clients). Le modèle réfléchit quand même ; seul `reasoning_content` est retiré. `usage.completion_tokens_details.reasoning_tokens` le compte toujours, car ces tokens ont pris du temps et comptent dans `max_tokens`.
31 31
32-- dans `run` et `chat`, il va sur la sortie d'erreur, en grisé : rediriger la sortie standard ne garde que la réponse ;32+Un modèle à qui l'on dit de ne pas réfléchir émet souvent quand même un `<think></think>` vide ; un raisonnement vide n'est jamais envoyé.
33-- dans `tui`, c'est un bloc à part que Ctrl-T affiche ou masque à tout moment.
34-
35-Un modèle à qui l'on dit de ne pas réfléchir émet souvent quand même un `<think></think>` vide ; un raisonnement vide n'est jamais affiché.
36 33
37 ## Le limiter34 ## Le limiter
38 35
@@ -49,8 +46,10 @@ La façon de refermer le raisonnement dépend de la famille de modèles :
49 - **Reconnaître Qwen3.5 à son nom** : fragile ; le gabarit fait foi.46 - **Reconnaître Qwen3.5 à son nom** : fragile ; le gabarit fait foi.
50 - **Couper le texte après `N` tokens de raisonnement et arrêter la génération** : le modèle n'aurait jamais le temps de répondre.47 - **Couper le texte après `N` tokens de raisonnement et arrêter la génération** : le modèle n'aurait jamais le temps de répondre.
51 - **Augmenter `max_tokens` automatiquement quand un budget est fixé** : comportement caché ; la vérification de la configuration exige plutôt un budget plus petit que `max_tokens`.48 - **Augmenter `max_tokens` automatiquement quand un budget est fixé** : comportement caché ; la vérification de la configuration exige plutôt un budget plus petit que `max_tokens`.
49+- **Envoyer le raisonnement dans `content`, entre balises `<think>`** : certains serveurs le font ; les clients montrent ou analysent alors les balises comme une partie de la réponse.
52 50
53 ## Lien avec le reste51 ## Lien avec le reste
54 52
55-- Les réglages : [régler la réflexion](../how-to/regler-la-reflexion.md) et la [référence du fichier d'agent](../reference/configuration.md#generation).53+- Les réglages : [régler le raisonnement](../how-to/regler-la-reflexion.md), la [référence de l'API HTTP](../reference/api-http.md#champs-de-la-requête) et la [référence de la configuration](../reference/configuration.md#defaults-et-locked).
54+- Le raisonnement avant la sortie structurée : [décodage contraint](decodage-contraint.md).
56 - La place du moteur : [architecture](architecture.md).55 - La place du moteur : [architecture](architecture.md).
deleted docs/fr/explanation/securite-des-outils.md +0 -41
deleted file mode 100644
@@ -1,41 +0,0 @@
1-# Sécurité des outils — explication
2-
3-## De quoi s'agit-il ?
4-
5-Avec l'outil `bash`, un modèle de langage lance des commandes sur votre Mac avec vos droits. Cette page explique ce que fait razorbill pour garder cela sous contrôle, ce contre quoi il ne protège **pas**, et la direction que prend le projet.
6-
7-## Pourquoi rzb ne peut pas simplement être mis en sandbox
8-
9-La réponse habituelle à « un agent lance des commandes » est de faire tourner l'agent dans un container. razorbill ne le peut pas : il a besoin de Metal et du GPU, qui n'existent que sous macOS, hors d'un container Linux. `rzb` tourne donc sur la machine hôte, et les commandes de son outil `bash` aussi.
10-
11-## Ce que fait la v0.1
12-
13-Les protections, de la plus forte à la plus faible :
14-
15-1. **Désactivé par défaut.** Aucun outil n'existe si le fichier d'agent ne le liste pas.
16-2. **Confirmation par défaut.** Avec `confirm: true` (le défaut), vous voyez chaque commande et son dossier, et devez répondre `y`. Sans terminal, ces commandes sont refusées : une exécution sans surveillance n'exécute jamais rien que personne n'a approuvé, sauf si `confirm: false` est écrit explicitement dans le fichier.
17-3. **Limites.** Chaque commande est tuée, avec tous les processus qu'elle a lancés (son groupe de processus), après `timeout` ; la sortie est plafonnée à `max_output`, pour qu'une commande ne puisse pas inonder le contexte du modèle.
18-4. **Motifs.** Les motifs `deny` l'emportent toujours, puis les motifs `allow` doivent correspondre.
19-
20-Les refus sont envoyés au modèle comme des résultats, en clair : il peut s'adapter au lieu d'échouer.
21-
22-## Ce contre quoi il ne protège pas
23-
24-- **Les motifs ne sont pas une sandbox.** Ils comparent du texte, pas des intentions. `ls*` correspond aussi à `ls; rm -rf ~` ; `deny: ["rm *"]` n'empêche pas `find . -delete`, un script ou `python -c …`. Utilisez les listes `allow` pour le confort, et gardez `confirm: true` pour la sécurité.
25-- **La confirmation dépend de vous.** Une commande longue ou obscure peut être acceptée par erreur.
26-- **Les secrets sont visibles.** Les commandes héritent de tout l'environnement de `rzb` : le modèle peut lire des jetons avec `env` ou `echo $TOKEN`, et la sortie revient dans son contexte. Un prompt système avec `{{env.NOM}}` met la valeur elle-même dans le prompt.
27-- **L'injection de prompt.** Un fichier ou une page web lus par une commande peuvent contenir des instructions destinées au modèle. Le modèle peut les suivre ; seules les protections ci-dessus s'y opposent.
28-
29-## La direction prise
30-
31-Ce sont des tickets de réflexion ouverts, pas des fonctionnalités :
32-
33-- **Les secrets** (ticket #21) : masquer au modèle une liste de variables, ou toutes, tout en laissant les outils les utiliser par leur nom ; masquer leurs valeurs dans les sorties.
34-- **Un shell isolé** (ticket #22) : garder le modèle sur le Mac et n'envoyer que l'exécution des commandes dans un container, une VM ou une sandbox `sbx` ; plus des interrupteurs explicites pour désactiver les outils intégrés (`enabled: false`, `--no-tools`).
35-- **WebAssembly** (ticket #23) : exécuter des outils sous forme de modules WASM dans `rzb`, avec seulement les fichiers et l'accès réseau que la configuration accorde.
36-- **Des garde-fous pour les petits modèles** (ticket #27) : détecter les boucles (la même commande encore et encore) et arrêter ou réorienter le modèle.
37-
38-## Lien avec le reste
39-
40-- Configurer l'outil : [utiliser l'outil bash](../how-to/utiliser-l-outil-bash.md) et la [référence de l'outil bash](../reference/outil-bash.md).
41-- Le trajet d'un appel d'outil dans l'agent : [architecture](architecture.md#la-boucle-de-lagent).
deleted file mode 100644
@@ -1,41 +0,0 @@
1-# Sécurité des outils — explication
2-
3-## De quoi s'agit-il ?
4-
5-Avec l'outil `bash`, un modèle de langage lance des commandes sur votre Mac avec vos droits. Cette page explique ce que fait razorbill pour garder cela sous contrôle, ce contre quoi il ne protège **pas**, et la direction que prend le projet.
6-
7-## Pourquoi rzb ne peut pas simplement être mis en sandbox
8-
9-La réponse habituelle à « un agent lance des commandes » est de faire tourner l'agent dans un container. razorbill ne le peut pas : il a besoin de Metal et du GPU, qui n'existent que sous macOS, hors d'un container Linux. `rzb` tourne donc sur la machine hôte, et les commandes de son outil `bash` aussi.
10-
11-## Ce que fait la v0.1
12-
13-Les protections, de la plus forte à la plus faible :
14-
15-1. **Désactivé par défaut.** Aucun outil n'existe si le fichier d'agent ne le liste pas.
16-2. **Confirmation par défaut.** Avec `confirm: true` (le défaut), vous voyez chaque commande et son dossier, et devez répondre `y`. Sans terminal, ces commandes sont refusées : une exécution sans surveillance n'exécute jamais rien que personne n'a approuvé, sauf si `confirm: false` est écrit explicitement dans le fichier.
17-3. **Limites.** Chaque commande est tuée, avec tous les processus qu'elle a lancés (son groupe de processus), après `timeout` ; la sortie est plafonnée à `max_output`, pour qu'une commande ne puisse pas inonder le contexte du modèle.
18-4. **Motifs.** Les motifs `deny` l'emportent toujours, puis les motifs `allow` doivent correspondre.
19-
20-Les refus sont envoyés au modèle comme des résultats, en clair : il peut s'adapter au lieu d'échouer.
21-
22-## Ce contre quoi il ne protège pas
23-
24-- **Les motifs ne sont pas une sandbox.** Ils comparent du texte, pas des intentions. `ls*` correspond aussi à `ls; rm -rf ~` ; `deny: ["rm *"]` n'empêche pas `find . -delete`, un script ou `python -c …`. Utilisez les listes `allow` pour le confort, et gardez `confirm: true` pour la sécurité.
25-- **La confirmation dépend de vous.** Une commande longue ou obscure peut être acceptée par erreur.
26-- **Les secrets sont visibles.** Les commandes héritent de tout l'environnement de `rzb` : le modèle peut lire des jetons avec `env` ou `echo $TOKEN`, et la sortie revient dans son contexte. Un prompt système avec `{{env.NOM}}` met la valeur elle-même dans le prompt.
27-- **L'injection de prompt.** Un fichier ou une page web lus par une commande peuvent contenir des instructions destinées au modèle. Le modèle peut les suivre ; seules les protections ci-dessus s'y opposent.
28-
29-## La direction prise
30-
31-Ce sont des tickets de réflexion ouverts, pas des fonctionnalités :
32-
33-- **Les secrets** (ticket #21) : masquer au modèle une liste de variables, ou toutes, tout en laissant les outils les utiliser par leur nom ; masquer leurs valeurs dans les sorties.
34-- **Un shell isolé** (ticket #22) : garder le modèle sur le Mac et n'envoyer que l'exécution des commandes dans un container, une VM ou une sandbox `sbx` ; plus des interrupteurs explicites pour désactiver les outils intégrés (`enabled: false`, `--no-tools`).
35-- **WebAssembly** (ticket #23) : exécuter des outils sous forme de modules WASM dans `rzb`, avec seulement les fichiers et l'accès réseau que la configuration accorde.
36-- **Des garde-fous pour les petits modèles** (ticket #27) : détecter les boucles (la même commande encore et encore) et arrêter ou réorienter le modèle.
37-
38-## Lien avec le reste
39-
40-- Configurer l'outil : [utiliser l'outil bash](../how-to/utiliser-l-outil-bash.md) et la [référence de l'outil bash](../reference/outil-bash.md).
41-- Le trajet d'un appel d'outil dans l'agent : [architecture](architecture.md#la-boucle-de-lagent).
deleted docs/fr/how-to/ajouter-un-outil.md +0 -108
deleted file mode 100644
@@ -1,108 +0,0 @@
1-# Ajouter un outil
2-
3-Ce guide ajoute un outil intégré que les agents peuvent activer dans leur fichier YAML. Il suppose que vous savez compiler et tester razorbill, et que vous connaissez Swift. L'exemple est `clock`, un outil qui renvoie la date et l'heure courantes dans un fuseau horaire donné.
4-
5-## 1. Écrire l'outil
6-
7-Créez `Sources/RazorbillCore/Tools/ClockTool.swift`. Un outil est un type conforme à `AgentTool` : une `spec` que le modèle lit (nom, description, schéma JSON des arguments) et une méthode `call` qui l'exécute.
8-
9-```swift
10-import Foundation
11-
12-/// Built-in tool `clock`: the current date and time.
13-///
14-/// ```yaml
15-/// tools:
16-/// clock:
17-/// time_zone: Europe/Paris
18-/// ```
19-public struct ClockTool: AgentTool {
20- public static let name = "clock"
21-
22- public let defaultTimeZone: TimeZone
23-
24- public let spec = ToolSpec(
25- name: ClockTool.name,
26- description: "Return the current date and time (ISO 8601). Optionally in another time zone.",
27- parameters: .map([
28- "type": .string("object"),
29- "properties": .map([
30- "time_zone": .map([
31- "type": .string("string"),
32- "description": .string("IANA time zone, e.g. Asia/Tokyo"),
33- ])
34- ]),
35- ])
36- )
37-
38- /// Builds the tool from its YAML options.
39- public init(options: ConfigValue, environment: ToolEnvironment) throws {
40- let reader = OptionReader(options)
41- try reader.rejectUnknownKeys(["time_zone"])
42- let identifier = try reader.string("time_zone", default: TimeZone.current.identifier)
43- guard let zone = TimeZone(identifier: identifier) else {
44- throw ToolOptionError(key: "time_zone", message: "unknown time zone \(identifier)")
45- }
46- defaultTimeZone = zone
47- }
48-
49- public func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput {
50- var zone = defaultTimeZone
51- if let identifier = arguments["time_zone"]?.stringValue {
52- guard let requested = TimeZone(identifier: identifier) else {
53- return ToolOutput("unknown time zone \(identifier)", isError: true)
54- }
55- zone = requested
56- }
57- let formatter = ISO8601DateFormatter()
58- formatter.timeZone = zone
59- return ToolOutput(formatter.string(from: Date()))
60- }
61-}
62-```
63-
64-Les règles qui gardent les outils prévisibles :
65-
66-- Lisez les options avec `OptionReader` et refusez les clés inconnues : une faute de frappe devient alors une erreur de configuration avec son chemin (`tools.clock.time_zne`).
67-- Levez une `ToolOptionError` pour une mauvaise option, au chargement. À l'appel, renvoyez `ToolOutput(…, isError: true)` pour un mauvais argument : le modèle le lit et peut se corriger.
68-- Demandez l'accord de l'utilisateur avant toute action qu'il doit approuver, avec `context.confirm(…)`, et refusez quand `context.isInteractive` est faux (voir `BashTool`).
69-- Le texte envoyé au modèle ne doit pas dépendre de la langue ou des réglages régionaux de l'utilisateur.
70-
71-## 2. L'enregistrer
72-
73-Dans `ToolRegistry.builtIn` (`Sources/RazorbillCore/Tools/ToolRegistry.swift`), ajoutez une ligne :
74-
75-```swift
76-registry.register(ClockTool.name, factory: ClockTool.init(options:environment:))
77-```
78-
79-`rzb init` le propose désormais, `rzb config validate` l'accepte, et un agent l'active avec :
80-
81-```yaml
82-tools:
83- clock:
84- time_zone: Europe/Paris
85-```
86-
87-## 3. Le tester
88-
89-Ajoutez `Tests/RazorbillCoreTests/ClockToolTests.swift` avec Swift Testing : options acceptées et refusées, un appel valide, un argument invalide. Pour tester toute la boucle sans modèle, scriptez un tour de `FakeEngine` qui appelle l'outil :
90-
91-```swift
92-let engine = FakeEngine(script: [
93- [.toolCall(ToolCall(name: "clock", arguments: ["time_zone": .string("UTC")]))],
94- [.text("done")],
95-])
96-```
97-
98-Puis [lancez les tests](lancer-les-tests.md).
99-
100-## Variantes
101-
102-- **Un outil réservé à une interface ou à une compilation** : enregistrez-le sur le registre passé à `CLIEnvironment` plutôt que dans `builtIn`.
103-- **Un outil qui a des effets de bord** : suivez `BashTool` — option `confirm`, refus sans terminal, délais, limites de sortie.
104-
105-## Voir aussi
106-
107-- La clé `tools` : [référence du fichier d'agent](../reference/configuration.md#tools).
108-- La place des outils dans la boucle de l'agent : [architecture](../explanation/architecture.md#la-boucle-de-lagent).
deleted file mode 100644
@@ -1,108 +0,0 @@
1-# Ajouter un outil
2-
3-Ce guide ajoute un outil intégré que les agents peuvent activer dans leur fichier YAML. Il suppose que vous savez compiler et tester razorbill, et que vous connaissez Swift. L'exemple est `clock`, un outil qui renvoie la date et l'heure courantes dans un fuseau horaire donné.
4-
5-## 1. Écrire l'outil
6-
7-Créez `Sources/RazorbillCore/Tools/ClockTool.swift`. Un outil est un type conforme à `AgentTool` : une `spec` que le modèle lit (nom, description, schéma JSON des arguments) et une méthode `call` qui l'exécute.
8-
9-```swift
10-import Foundation
11-
12-/// Built-in tool `clock`: the current date and time.
13-///
14-/// ```yaml
15-/// tools:
16-/// clock:
17-/// time_zone: Europe/Paris
18-/// ```
19-public struct ClockTool: AgentTool {
20- public static let name = "clock"
21-
22- public let defaultTimeZone: TimeZone
23-
24- public let spec = ToolSpec(
25- name: ClockTool.name,
26- description: "Return the current date and time (ISO 8601). Optionally in another time zone.",
27- parameters: .map([
28- "type": .string("object"),
29- "properties": .map([
30- "time_zone": .map([
31- "type": .string("string"),
32- "description": .string("IANA time zone, e.g. Asia/Tokyo"),
33- ])
34- ]),
35- ])
36- )
37-
38- /// Builds the tool from its YAML options.
39- public init(options: ConfigValue, environment: ToolEnvironment) throws {
40- let reader = OptionReader(options)
41- try reader.rejectUnknownKeys(["time_zone"])
42- let identifier = try reader.string("time_zone", default: TimeZone.current.identifier)
43- guard let zone = TimeZone(identifier: identifier) else {
44- throw ToolOptionError(key: "time_zone", message: "unknown time zone \(identifier)")
45- }
46- defaultTimeZone = zone
47- }
48-
49- public func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput {
50- var zone = defaultTimeZone
51- if let identifier = arguments["time_zone"]?.stringValue {
52- guard let requested = TimeZone(identifier: identifier) else {
53- return ToolOutput("unknown time zone \(identifier)", isError: true)
54- }
55- zone = requested
56- }
57- let formatter = ISO8601DateFormatter()
58- formatter.timeZone = zone
59- return ToolOutput(formatter.string(from: Date()))
60- }
61-}
62-```
63-
64-Les règles qui gardent les outils prévisibles :
65-
66-- Lisez les options avec `OptionReader` et refusez les clés inconnues : une faute de frappe devient alors une erreur de configuration avec son chemin (`tools.clock.time_zne`).
67-- Levez une `ToolOptionError` pour une mauvaise option, au chargement. À l'appel, renvoyez `ToolOutput(…, isError: true)` pour un mauvais argument : le modèle le lit et peut se corriger.
68-- Demandez l'accord de l'utilisateur avant toute action qu'il doit approuver, avec `context.confirm(…)`, et refusez quand `context.isInteractive` est faux (voir `BashTool`).
69-- Le texte envoyé au modèle ne doit pas dépendre de la langue ou des réglages régionaux de l'utilisateur.
70-
71-## 2. L'enregistrer
72-
73-Dans `ToolRegistry.builtIn` (`Sources/RazorbillCore/Tools/ToolRegistry.swift`), ajoutez une ligne :
74-
75-```swift
76-registry.register(ClockTool.name, factory: ClockTool.init(options:environment:))
77-```
78-
79-`rzb init` le propose désormais, `rzb config validate` l'accepte, et un agent l'active avec :
80-
81-```yaml
82-tools:
83- clock:
84- time_zone: Europe/Paris
85-```
86-
87-## 3. Le tester
88-
89-Ajoutez `Tests/RazorbillCoreTests/ClockToolTests.swift` avec Swift Testing : options acceptées et refusées, un appel valide, un argument invalide. Pour tester toute la boucle sans modèle, scriptez un tour de `FakeEngine` qui appelle l'outil :
90-
91-```swift
92-let engine = FakeEngine(script: [
93- [.toolCall(ToolCall(name: "clock", arguments: ["time_zone": .string("UTC")]))],
94- [.text("done")],
95-])
96-```
97-
98-Puis [lancez les tests](lancer-les-tests.md).
99-
100-## Variantes
101-
102-- **Un outil réservé à une interface ou à une compilation** : enregistrez-le sur le registre passé à `CLIEnvironment` plutôt que dans `builtIn`.
103-- **Un outil qui a des effets de bord** : suivez `BashTool` — option `confirm`, refus sans terminal, délais, limites de sortie.
104-
105-## Voir aussi
106-
107-- La clé `tools` : [référence du fichier d'agent](../reference/configuration.md#tools).
108-- La place des outils dans la boucle de l'agent : [architecture](../explanation/architecture.md#la-boucle-de-lagent).
added docs/fr/how-to/calculer-des-embeddings.md +47 -0
new file mode 100644
@@ -0,0 +1,47 @@
1+# Calculer des embeddings
2+
3+Ce guide transforme des textes en vecteurs pour la recherche sémantique, le regroupement ou le RAG. Il suppose que `rzb serve` tourne.
4+
5+## 1. Récupérer un modèle d'embedding
6+
7+```bash
8+rzb models pull BAAI/bge-small-en-v1.5
9+```
10+
11+Modèles dont le fonctionnement est vérifié : `BAAI/bge-small-en-v1.5` et `sentence-transformers/all-MiniLM-L6-v2` (384 dimensions ; leurs vecteurs concordent avec la bibliothèque Python `sentence-transformers` à 1e-3 près). Les autres modèles de la famille BERT et les Qwen3-Embedding pris en charge par les embedders de mlx-swift-lm devraient aussi fonctionner.
12+
13+## 2. Le déclarer (recommandé)
14+
15+```yaml
16+models:
17+ - id: embed
18+ source: BAAI/bge-small-en-v1.5
19+ kind: embedding
20+```
21+
22+Déclaré, il apparaît avec `"kind": "embedding"` dans `/v1/models`, et une requête de chat vers lui est refusée clairement. Un identifiant Hugging Face non déclaré fonctionne aussi sur `/v1/embeddings`.
23+
24+## 3. Demander des vecteurs
25+
26+```python
27+from openai import OpenAI
28+
29+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
30+result = client.embeddings.create(model="embed", input=["The cat sits on the mat.", "A feline rests on a rug."])
31+vectors = [item.embedding for item in result.data]
32+```
33+
34+Les vecteurs sont normalisés : leur produit scalaire est leur similarité cosinus.
35+
36+## Variantes
37+
38+- **Vecteurs plus courts** : `dimensions=256` garde les 256 premières valeurs et les renormalise. Pertinent pour les modèles Matryoshka (Qwen3-Embedding, nomic…) ; pour les autres, la qualité baisse.
39+- **Réponses plus légères** : `encoding_format="base64"` (la bibliothèque openai le demande par défaut et le décode pour vous).
40+- **LangChain** : `OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="embed", check_embedding_ctx_length=False)`. Sans `check_embedding_ctx_length=False`, LangChain envoie des tableaux de tokens, que le serveur refuse.
41+- **Textes longs** : un texte plus long que ce qu'accepte le modèle (512 tokens pour bge-small) donne un 400 qui le nomme. Découpez d'abord vos documents.
42+- **Préfixes de requête** : les modèles qui attendent un préfixe (`query: `, `search_query: `, une instruction) doivent le recevoir dans votre texte ; le serveur n'ajoute rien.
43+- **Chat et embeddings ensemble** : réglez `limits.max_loaded_models: 2` pour que les deux modèles restent chargés.
44+
45+## Voir aussi
46+
47+- Chaque champ de `/v1/embeddings` : [référence de l'API HTTP](../reference/api-http.md#post-v1embeddings).
new file mode 100644
@@ -0,0 +1,47 @@
1+# Calculer des embeddings
2+
3+Ce guide transforme des textes en vecteurs pour la recherche sémantique, le regroupement ou le RAG. Il suppose que `rzb serve` tourne.
4+
5+## 1. Récupérer un modèle d'embedding
6+
7+```bash
8+rzb models pull BAAI/bge-small-en-v1.5
9+```
10+
11+Modèles dont le fonctionnement est vérifié : `BAAI/bge-small-en-v1.5` et `sentence-transformers/all-MiniLM-L6-v2` (384 dimensions ; leurs vecteurs concordent avec la bibliothèque Python `sentence-transformers` à 1e-3 près). Les autres modèles de la famille BERT et les Qwen3-Embedding pris en charge par les embedders de mlx-swift-lm devraient aussi fonctionner.
12+
13+## 2. Le déclarer (recommandé)
14+
15+```yaml
16+models:
17+ - id: embed
18+ source: BAAI/bge-small-en-v1.5
19+ kind: embedding
20+```
21+
22+Déclaré, il apparaît avec `"kind": "embedding"` dans `/v1/models`, et une requête de chat vers lui est refusée clairement. Un identifiant Hugging Face non déclaré fonctionne aussi sur `/v1/embeddings`.
23+
24+## 3. Demander des vecteurs
25+
26+```python
27+from openai import OpenAI
28+
29+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
30+result = client.embeddings.create(model="embed", input=["The cat sits on the mat.", "A feline rests on a rug."])
31+vectors = [item.embedding for item in result.data]
32+```
33+
34+Les vecteurs sont normalisés : leur produit scalaire est leur similarité cosinus.
35+
36+## Variantes
37+
38+- **Vecteurs plus courts** : `dimensions=256` garde les 256 premières valeurs et les renormalise. Pertinent pour les modèles Matryoshka (Qwen3-Embedding, nomic…) ; pour les autres, la qualité baisse.
39+- **Réponses plus légères** : `encoding_format="base64"` (la bibliothèque openai le demande par défaut et le décode pour vous).
40+- **LangChain** : `OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="embed", check_embedding_ctx_length=False)`. Sans `check_embedding_ctx_length=False`, LangChain envoie des tableaux de tokens, que le serveur refuse.
41+- **Textes longs** : un texte plus long que ce qu'accepte le modèle (512 tokens pour bge-small) donne un 400 qui le nomme. Découpez d'abord vos documents.
42+- **Préfixes de requête** : les modèles qui attendent un préfixe (`query: `, `search_query: `, une instruction) doivent le recevoir dans votre texte ; le serveur n'ajoute rien.
43+- **Chat et embeddings ensemble** : réglez `limits.max_loaded_models: 2` pour que les deux modèles restent chargés.
44+
45+## Voir aussi
46+
47+- Chaque champ de `/v1/embeddings` : [référence de l'API HTTP](../reference/api-http.md#post-v1embeddings).
modified docs/fr/how-to/compiler-sur-le-mac.md +1 -1
@@ -1,6 +1,6 @@
11 # Compiler rzb sur le Mac
22
3-Ce guide compile l'exécutable `rzb` à partir des sources. Il suppose un Mac Apple Silicon et le dépôt cloné.
3+Ce guide compile l'exécutable `rzb`, le serveur, à partir des sources. Il suppose un Mac Apple Silicon et le dépôt cloné.
44
55 ## Prérequis
66
@@ -1,6 +1,6 @@
1 # Compiler rzb sur le Mac1 # Compiler rzb sur le Mac
2 2
3-Ce guide compile l'exécutable `rzb` à partir des sources. Il suppose un Mac Apple Silicon et le dépôt cloné.3+Ce guide compile l'exécutable `rzb`, le serveur, à partir des sources. Il suppose un Mac Apple Silicon et le dépôt cloné.
4 4
5 ## Prérequis5 ## Prérequis
6 6
added docs/fr/how-to/configurer-le-serveur.md +118 -0
new file mode 100644
@@ -0,0 +1,118 @@
1+# Configurer le serveur
2+
3+Ce guide écrit un fichier de configuration pour `rzb serve` : noms courts de modèles, réglages de génération par défaut et verrouillés, limites de mémoire et accès réseau. Il suppose que vous avez déjà démarré le serveur une fois (voir le [tutoriel](../tutorials/premiers-pas.md)).
4+
5+## 1. Écrire le fichier
6+
7+Partez de l'exemple commenté :
8+
9+```bash
10+cp examples/server.yaml server.yaml
11+```
12+
13+Ou écrivez-en un minimal :
14+
15+```yaml
16+models:
17+ - id: qwen3
18+ source: mlx-community/Qwen3-4B-4bit
19+ - id: embed
20+ source: BAAI/bge-small-en-v1.5
21+ kind: embedding
22+```
23+
24+Les clients envoient maintenant `"model": "qwen3"` au lieu de l'identifiant Hugging Face. Les identifiants Hugging Face non déclarés continuent de fonctionner.
25+
26+## 2. Le vérifier, puis l'utiliser
27+
28+```bash
29+rzb config validate server.yaml
30+rzb serve --config server.yaml
31+```
32+
33+`config validate` liste chaque problème avec son numéro de ligne ; corrigez-les et relancez.
34+
35+## Définir des valeurs par défaut que les clients peuvent changer
36+
37+```yaml
38+defaults:
39+ temperature: 0.3
40+ max_tokens: 2048
41+```
42+
43+Une requête qui envoie `temperature` utilise sa propre valeur ; une requête qui ne l'envoie pas reçoit `0.3`.
44+
45+## Verrouiller des réglages que les clients ne peuvent pas changer
46+
47+```yaml
48+locked:
49+ max_tokens: 4096 # un plafond : les requêtes qui demandent plus reçoivent 4096
50+ show_reasoning: false # ne jamais envoyer le raisonnement aux clients
51+```
52+
53+`temperature`, `top_p`, `thinking` et `show_reasoning` sont imposés ; `max_tokens` et `thinking_budget` sont des plafonds.
54+
55+## Des réglages pour un seul modèle
56+
57+```yaml
58+models:
59+ - id: qwen3-thinking
60+ source: mlx-community/Qwen3-4B-4bit
61+ defaults: { thinking: true, thinking_budget: 512 }
62+ locked: { max_tokens: 8192 }
63+```
64+
65+Les blocs du modèle s'appliquent après ceux de premier niveau. Deux entrées peuvent utiliser la même `source` avec des réglages différents ; elles partagent un seul chargement.
66+
67+## Charger un modèle au démarrage
68+
69+```yaml
70+models:
71+ - id: embed
72+ source: BAAI/bge-small-en-v1.5
73+ kind: embedding
74+ preload: true
75+```
76+
77+Le serveur répond alors à la première requête sans le délai de chargement.
78+
79+## Garder plusieurs modèles en mémoire
80+
81+```yaml
82+limits:
83+ max_loaded_models: 2 # par exemple un modèle de chat et un modèle d'embedding
84+ keep_alive: 30m # décharger un modèle inactif depuis 30 minutes
85+ max_queue: 32 # requêtes en attente par modèle avant un 429
86+```
87+
88+## Utiliser un modèle d'un dossier local
89+
90+```yaml
91+models:
92+ - id: mine
93+ path: ~/models/my-mlx-model # config.json, fichiers du tokenizer, *.safetensors
94+```
95+
96+## Ouvrir le serveur à votre réseau
97+
98+Définissez une clé dans l'environnement, puis écoutez sur toutes les interfaces :
99+
100+```bash
101+export RZB_API_KEY="$(openssl rand -hex 24)"
102+rzb serve --config server.yaml --host 0.0.0.0
103+```
104+
105+Les clients envoient `Authorization: Bearer <clé>` (l'`api_key` des clients OpenAI). Pour lire la clé dans une autre variable : `--api-key-env MA_VAR` ou `server.api_key_env: MA_VAR`. La clé n'est jamais dans le fichier.
106+
107+## Permettre à une page web d'appeler l'API
108+
109+```bash
110+rzb serve --config server.yaml --cors-origin http://localhost:3000
111+```
112+
113+N'utilisez `*` (toutes les origines) qu'avec une clé d'API : sinon n'importe quelle page que vous ouvrez peut utiliser vos modèles.
114+
115+## Voir aussi
116+
117+- Chaque clé, type et valeur par défaut : [référence de la configuration](../reference/configuration.md).
118+- Comment les modèles sont chargés, mis en file d'attente et déchargés : [cycle de vie des modèles](../explanation/cycle-de-vie-des-modeles.md).
new file mode 100644
@@ -0,0 +1,118 @@
1+# Configurer le serveur
2+
3+Ce guide écrit un fichier de configuration pour `rzb serve` : noms courts de modèles, réglages de génération par défaut et verrouillés, limites de mémoire et accès réseau. Il suppose que vous avez déjà démarré le serveur une fois (voir le [tutoriel](../tutorials/premiers-pas.md)).
4+
5+## 1. Écrire le fichier
6+
7+Partez de l'exemple commenté :
8+
9+```bash
10+cp examples/server.yaml server.yaml
11+```
12+
13+Ou écrivez-en un minimal :
14+
15+```yaml
16+models:
17+ - id: qwen3
18+ source: mlx-community/Qwen3-4B-4bit
19+ - id: embed
20+ source: BAAI/bge-small-en-v1.5
21+ kind: embedding
22+```
23+
24+Les clients envoient maintenant `"model": "qwen3"` au lieu de l'identifiant Hugging Face. Les identifiants Hugging Face non déclarés continuent de fonctionner.
25+
26+## 2. Le vérifier, puis l'utiliser
27+
28+```bash
29+rzb config validate server.yaml
30+rzb serve --config server.yaml
31+```
32+
33+`config validate` liste chaque problème avec son numéro de ligne ; corrigez-les et relancez.
34+
35+## Définir des valeurs par défaut que les clients peuvent changer
36+
37+```yaml
38+defaults:
39+ temperature: 0.3
40+ max_tokens: 2048
41+```
42+
43+Une requête qui envoie `temperature` utilise sa propre valeur ; une requête qui ne l'envoie pas reçoit `0.3`.
44+
45+## Verrouiller des réglages que les clients ne peuvent pas changer
46+
47+```yaml
48+locked:
49+ max_tokens: 4096 # un plafond : les requêtes qui demandent plus reçoivent 4096
50+ show_reasoning: false # ne jamais envoyer le raisonnement aux clients
51+```
52+
53+`temperature`, `top_p`, `thinking` et `show_reasoning` sont imposés ; `max_tokens` et `thinking_budget` sont des plafonds.
54+
55+## Des réglages pour un seul modèle
56+
57+```yaml
58+models:
59+ - id: qwen3-thinking
60+ source: mlx-community/Qwen3-4B-4bit
61+ defaults: { thinking: true, thinking_budget: 512 }
62+ locked: { max_tokens: 8192 }
63+```
64+
65+Les blocs du modèle s'appliquent après ceux de premier niveau. Deux entrées peuvent utiliser la même `source` avec des réglages différents ; elles partagent un seul chargement.
66+
67+## Charger un modèle au démarrage
68+
69+```yaml
70+models:
71+ - id: embed
72+ source: BAAI/bge-small-en-v1.5
73+ kind: embedding
74+ preload: true
75+```
76+
77+Le serveur répond alors à la première requête sans le délai de chargement.
78+
79+## Garder plusieurs modèles en mémoire
80+
81+```yaml
82+limits:
83+ max_loaded_models: 2 # par exemple un modèle de chat et un modèle d'embedding
84+ keep_alive: 30m # décharger un modèle inactif depuis 30 minutes
85+ max_queue: 32 # requêtes en attente par modèle avant un 429
86+```
87+
88+## Utiliser un modèle d'un dossier local
89+
90+```yaml
91+models:
92+ - id: mine
93+ path: ~/models/my-mlx-model # config.json, fichiers du tokenizer, *.safetensors
94+```
95+
96+## Ouvrir le serveur à votre réseau
97+
98+Définissez une clé dans l'environnement, puis écoutez sur toutes les interfaces :
99+
100+```bash
101+export RZB_API_KEY="$(openssl rand -hex 24)"
102+rzb serve --config server.yaml --host 0.0.0.0
103+```
104+
105+Les clients envoient `Authorization: Bearer <clé>` (l'`api_key` des clients OpenAI). Pour lire la clé dans une autre variable : `--api-key-env MA_VAR` ou `server.api_key_env: MA_VAR`. La clé n'est jamais dans le fichier.
106+
107+## Permettre à une page web d'appeler l'API
108+
109+```bash
110+rzb serve --config server.yaml --cors-origin http://localhost:3000
111+```
112+
113+N'utilisez `*` (toutes les origines) qu'avec une clé d'API : sinon n'importe quelle page que vous ouvrez peut utiliser vos modèles.
114+
115+## Voir aussi
116+
117+- Chaque clé, type et valeur par défaut : [référence de la configuration](../reference/configuration.md).
118+- Comment les modèles sont chargés, mis en file d'attente et déchargés : [cycle de vie des modèles](../explanation/cycle-de-vie-des-modeles.md).
modified docs/fr/how-to/developper-depuis-une-sandbox.md +2 -2
@@ -45,14 +45,14 @@ swiftlint lint --quiet Sources Tests
4545
4646 tools/host-runner/host.sh build . razorbill # Mac : compilation Release avec Metal
4747 tools/host-runner/host.sh test . razorbill # Mac : toute la suite, MLX compris
48-tools/host-runner/host.sh run . rzb run --offline -m mlx-community/Qwen3-0.6B-4bit "Hello"
48+tools/host-runner/host.sh run . rzb models list
4949 ```
5050
5151 Le code de sortie du script est celui de la commande sur le Mac : on peut l'enchaîner comme une commande locale. Les fichiers modifiés dans la sandbox sont ceux que le Mac compile : il n'y a rien à copier.
5252
5353 ## Limites
5454
55-- `host.sh run` n'a pas de terminal : utilisez-le pour `rzb run`, pas pour `rzb chat`, `rzb init` ou `rzb tui`. Essayez ceux-là dans un terminal sur le Mac.
55+- `host.sh run` n'a pas de terminal et attend la fin de la commande : ne l'utilisez pas pour `rzb serve`. Tuer `host.sh` dans la sandbox n'arrête pas le serveur sur le Mac, et host-runner répond alors 409 à tout jusqu'à ce que vous arrêtiez `rzb serve` sur le Mac. Démarrez plutôt le serveur dans un terminal du Mac ; la sandbox le joint à `http://host.docker.internal:8080/v1` (autorisez-le une fois avec `sbx policy allow network localhost:8080`).
5656 - host-runner lance une commande à la fois (une deuxième requête reçoit HTTP 409) et ne connaît que `list`, `build`, `test`, `run`, `resolve` et `clean`, sur `.` ou `samples/<nom>`.
5757 - Les modèles sont téléchargés dans le cache Hugging Face **du Mac** ; la sandbox ne le voit pas.
5858
@@ -45,14 +45,14 @@ swiftlint lint --quiet Sources Tests
45 45
46 tools/host-runner/host.sh build . razorbill # Mac : compilation Release avec Metal46 tools/host-runner/host.sh build . razorbill # Mac : compilation Release avec Metal
47 tools/host-runner/host.sh test . razorbill # Mac : toute la suite, MLX compris47 tools/host-runner/host.sh test . razorbill # Mac : toute la suite, MLX compris
48-tools/host-runner/host.sh run . rzb run --offline -m mlx-community/Qwen3-0.6B-4bit "Hello"48+tools/host-runner/host.sh run . rzb models list
49 ```49 ```
50 50
51 Le code de sortie du script est celui de la commande sur le Mac : on peut l'enchaîner comme une commande locale. Les fichiers modifiés dans la sandbox sont ceux que le Mac compile : il n'y a rien à copier.51 Le code de sortie du script est celui de la commande sur le Mac : on peut l'enchaîner comme une commande locale. Les fichiers modifiés dans la sandbox sont ceux que le Mac compile : il n'y a rien à copier.
52 52
53 ## Limites53 ## Limites
54 54
55-- `host.sh run` n'a pas de terminal : utilisez-le pour `rzb run`, pas pour `rzb chat`, `rzb init` ou `rzb tui`. Essayez ceux-là dans un terminal sur le Mac.55+- `host.sh run` n'a pas de terminal et attend la fin de la commande : ne l'utilisez pas pour `rzb serve`. Tuer `host.sh` dans la sandbox n'arrête pas le serveur sur le Mac, et host-runner répond alors 409 à tout jusqu'à ce que vous arrêtiez `rzb serve` sur le Mac. Démarrez plutôt le serveur dans un terminal du Mac ; la sandbox le joint à `http://host.docker.internal:8080/v1` (autorisez-le une fois avec `sbx policy allow network localhost:8080`).
56 - host-runner lance une commande à la fois (une deuxième requête reçoit HTTP 409) et ne connaît que `list`, `build`, `test`, `run`, `resolve` et `clean`, sur `.` ou `samples/<nom>`.56 - host-runner lance une commande à la fois (une deuxième requête reçoit HTTP 409) et ne connaît que `list`, `build`, `test`, `run`, `resolve` et `clean`, sur `.` ou `samples/<nom>`.
57 - Les modèles sont téléchargés dans le cache Hugging Face **du Mac** ; la sandbox ne le voit pas.57 - Les modèles sont téléchargés dans le cache Hugging Face **du Mac** ; la sandbox ne le voit pas.
58 58
modified docs/fr/how-to/gerer-les-modeles.md +21 -21
@@ -1,10 +1,10 @@
11 # Gérer les modèles
22
3-Ce guide montre comment trouver, télécharger, utiliser et supprimer les modèles que `rzb` fait tourner. Il suppose que `rzb` est compilé.
3+Ce guide montre comment trouver, télécharger, servir et supprimer les modèles que `rzb` fait tourner. Il suppose que `rzb` est compilé.
44
55 ## Choisir un modèle
66
7-`rzb` fait tourner des modèles au **format MLX**, publiés le plus souvent par `mlx-community` sur Hugging Face. `rzb init` propose une courte liste de modèles testés :
7+`rzb` fait tourner des modèles au **format MLX**, publiés le plus souvent par `mlx-community` sur Hugging Face. Modèles de chat testés :
88
99 | Modèle | Téléchargement |
1010 | --- | --- |
@@ -15,7 +15,7 @@ Ce guide montre comment trouver, télécharger, utiliser et supprimer les modèl
1515 | `mlx-community/Llama-3.2-3B-Instruct-4bit` | environ 1,8 Go |
1616 | `mlx-community/gemma-3-1b-it-qat-4bit` | environ 800 Mo |
1717
18-Tout autre modèle de texte MLX pris en charge par mlx-swift-lm fonctionne aussi. Les fichiers GGUF (pour llama.cpp ou Ollama) ne fonctionnent pas.
18+Tout autre modèle de texte MLX pris en charge par mlx-swift-lm fonctionne aussi. Les fichiers GGUF (pour llama.cpp ou Ollama) ne fonctionnent pas. Pour les modèles d'embedding, voir [calculer des embeddings](calculer-des-embeddings.md).
1919
2020 ## Télécharger un modèle à l'avance
2121
@@ -24,7 +24,7 @@ rzb models pull mlx-community/Qwen3-4B-4bit
2424 rzb models pull mlx-community/Qwen3-4B-4bit --revision <branche-tag-ou-commit>
2525 ```
2626
27-Sans cette étape, un modèle est téléchargé la première fois qu'un agent l'utilise.
27+Sans cette étape, un modèle est téléchargé par le serveur la première fois qu'une requête l'utilise, et cette requête attend la fin de tout le téléchargement.
2828
2929 ## Voir ce qui est téléchargé
3030
@@ -33,30 +33,30 @@ rzb models list # les modèles que rzb peut charger
3333 rzb models list --all # plus les dépôts GGUF et les téléchargements inachevés
3434 ```
3535
36-## Utiliser un modèle
36+## Servir un modèle
3737
38-- Dans le fichier d'agent : `model: mlx-community/Qwen3-4B-4bit`, ou la forme longue avec `id:` et `revision:`.
39-- Pour une seule exécution : `rzb chat -m mlx-community/Qwen3-4B-4bit`.
38+- Par son identifiant Hugging Face : les clients envoient `"model": "mlx-community/Qwen3-4B-4bit"`.
39+- Par un nom court : déclarez-le dans la configuration du serveur (voir [configurer le serveur](configurer-le-serveur.md)) :
4040
41-## Utiliser un dossier de modèle local
41+ ```yaml
42+ models:
43+ - id: qwen3
44+ source: mlx-community/Qwen3-4B-4bit
45+ revision: main # facultatif : une branche, un tag ou un commit
46+ ```
4247
43-Faites pointer `model.path` sur un dossier qui contient le `config.json` du modèle, ses fichiers de tokenizer et ses `*.safetensors` :
48+- Une révision précise sans déclaration : `"model": "mlx-community/Qwen3-4B-4bit@<révision>"`.
4449
45-```yaml
46-model:
47- path: ~/models/mon-modele # un chemin relatif part du dossier du fichier d'agent
48-```
49-
50-En ligne de commande, une valeur qui commence par `/`, `./`, `../` ou `~/` est un dossier : `rzb run -m ./mon-modele "Bonjour"`.
50+## Utiliser un modèle d'un dossier local
5151
52-## Travailler hors ligne
52+Déclarez un `path` qui pointe vers un dossier contenant le `config.json` du modèle, les fichiers du tokenizer et les `*.safetensors` :
5353
54-```bash
55-rzb chat --offline
54+```yaml
55+models:
56+ - id: mine
57+ path: ~/models/mon-modele # un chemin relatif part du dossier du fichier de configuration
5658 ```
5759
58-`--offline` n'utilise que ce qui est déjà dans le cache et échoue au lieu de télécharger. Un modèle déjà présent dans le cache n'est de toute façon jamais revérifié en ligne.
59-
6060 ## Supprimer un modèle
6161
6262 ```bash
@@ -71,4 +71,4 @@ Les modèles sont dans le cache Hugging Face, partagé avec les outils Python (`
7171 ## Voir aussi
7272
7373 - Toutes les options de `models` : [référence de la ligne de commande](../reference/ligne-de-commande.md#rzb-models).
74-- La clé `model` : [référence du fichier d'agent](../reference/configuration.md#model).
74+- La section `models` : [référence de la configuration](../reference/configuration.md#models).
@@ -1,10 +1,10 @@
1 # Gérer les modèles1 # Gérer les modèles
2 2
3-Ce guide montre comment trouver, télécharger, utiliser et supprimer les modèles que `rzb` fait tourner. Il suppose que `rzb` est compilé.3+Ce guide montre comment trouver, télécharger, servir et supprimer les modèles que `rzb` fait tourner. Il suppose que `rzb` est compilé.
4 4
5 ## Choisir un modèle5 ## Choisir un modèle
6 6
7-`rzb` fait tourner des modèles au **format MLX**, publiés le plus souvent par `mlx-community` sur Hugging Face. `rzb init` propose une courte liste de modèles testés :7+`rzb` fait tourner des modèles au **format MLX**, publiés le plus souvent par `mlx-community` sur Hugging Face. Modèles de chat testés :
8 8
9 | Modèle | Téléchargement |9 | Modèle | Téléchargement |
10 | --- | --- |10 | --- | --- |
@@ -15,7 +15,7 @@ Ce guide montre comment trouver, télécharger, utiliser et supprimer les modèl
15 | `mlx-community/Llama-3.2-3B-Instruct-4bit` | environ 1,8 Go |15 | `mlx-community/Llama-3.2-3B-Instruct-4bit` | environ 1,8 Go |
16 | `mlx-community/gemma-3-1b-it-qat-4bit` | environ 800 Mo |16 | `mlx-community/gemma-3-1b-it-qat-4bit` | environ 800 Mo |
17 17
18-Tout autre modèle de texte MLX pris en charge par mlx-swift-lm fonctionne aussi. Les fichiers GGUF (pour llama.cpp ou Ollama) ne fonctionnent pas.18+Tout autre modèle de texte MLX pris en charge par mlx-swift-lm fonctionne aussi. Les fichiers GGUF (pour llama.cpp ou Ollama) ne fonctionnent pas. Pour les modèles d'embedding, voir [calculer des embeddings](calculer-des-embeddings.md).
19 19
20 ## Télécharger un modèle à l'avance20 ## Télécharger un modèle à l'avance
21 21
@@ -24,7 +24,7 @@ rzb models pull mlx-community/Qwen3-4B-4bit
24 rzb models pull mlx-community/Qwen3-4B-4bit --revision <branche-tag-ou-commit>24 rzb models pull mlx-community/Qwen3-4B-4bit --revision <branche-tag-ou-commit>
25 ```25 ```
26 26
27-Sans cette étape, un modèle est téléchargé la première fois qu'un agent l'utilise.27+Sans cette étape, un modèle est téléchargé par le serveur la première fois qu'une requête l'utilise, et cette requête attend la fin de tout le téléchargement.
28 28
29 ## Voir ce qui est téléchargé29 ## Voir ce qui est téléchargé
30 30
@@ -33,30 +33,30 @@ rzb models list # les modèles que rzb peut charger
33 rzb models list --all # plus les dépôts GGUF et les téléchargements inachevés33 rzb models list --all # plus les dépôts GGUF et les téléchargements inachevés
34 ```34 ```
35 35
36-## Utiliser un modèle36+## Servir un modèle
37 37
38-- Dans le fichier d'agent : `model: mlx-community/Qwen3-4B-4bit`, ou la forme longue avec `id:` et `revision:`.38+- Par son identifiant Hugging Face : les clients envoient `"model": "mlx-community/Qwen3-4B-4bit"`.
39-- Pour une seule exécution : `rzb chat -m mlx-community/Qwen3-4B-4bit`.39+- Par un nom court : déclarez-le dans la configuration du serveur (voir [configurer le serveur](configurer-le-serveur.md)) :
40 40
41-## Utiliser un dossier de modèle local41+ ```yaml
42+ models:
43+ - id: qwen3
44+ source: mlx-community/Qwen3-4B-4bit
45+ revision: main # facultatif : une branche, un tag ou un commit
46+ ```
42 47
43-Faites pointer `model.path` sur un dossier qui contient le `config.json` du modèle, ses fichiers de tokenizer et ses `*.safetensors` :48+- Une révision précise sans déclaration : `"model": "mlx-community/Qwen3-4B-4bit@<révision>"`.
44 49
45-```yaml50+## Utiliser un modèle d'un dossier local
46-model:
47- path: ~/models/mon-modele # un chemin relatif part du dossier du fichier d'agent
48-```
49-
50-En ligne de commande, une valeur qui commence par `/`, `./`, `../` ou `~/` est un dossier : `rzb run -m ./mon-modele "Bonjour"`.
51 51
52-## Travailler hors ligne52+Déclarez un `path` qui pointe vers un dossier contenant le `config.json` du modèle, les fichiers du tokenizer et les `*.safetensors` :
53 53
54-```bash54+```yaml
55-rzb chat --offline55+models:
56+ - id: mine
57+ path: ~/models/mon-modele # un chemin relatif part du dossier du fichier de configuration
56 ```58 ```
57 59
58-`--offline` n'utilise que ce qui est déjà dans le cache et échoue au lieu de télécharger. Un modèle déjà présent dans le cache n'est de toute façon jamais revérifié en ligne.
59-
60 ## Supprimer un modèle60 ## Supprimer un modèle
61 61
62 ```bash62 ```bash
@@ -71,4 +71,4 @@ Les modèles sont dans le cache Hugging Face, partagé avec les outils Python (`
71 ## Voir aussi71 ## Voir aussi
72 72
73 - Toutes les options de `models` : [référence de la ligne de commande](../reference/ligne-de-commande.md#rzb-models).73 - Toutes les options de `models` : [référence de la ligne de commande](../reference/ligne-de-commande.md#rzb-models).
74-- La clé `model` : [référence du fichier d'agent](../reference/configuration.md#model).74+- La section `models` : [référence de la configuration](../reference/configuration.md#models).
modified docs/fr/how-to/lancer-les-tests.md +15 -1
@@ -31,6 +31,20 @@ xcodebuild test -scheme razorbill -destination 'platform=macOS' -derivedDataPath
3131 -skipPackagePluginValidation -skipMacroValidation -only-testing:RazorbillMLXTests
3232 ```
3333
34+## Vérifier la compatibilité avec de vrais clients OpenAI
35+
36+```bash
37+scripts/compat.sh # toute la suite
38+scripts/compat.sh -k tools # les arguments supplémentaires vont à pytest
39+```
40+
41+Il démarre `rzb serve` sur le port 18080 avec sa propre configuration, lance `Tests/Compatibility` (pytest, avec la bibliothèque `openai`, LangChain, et les exemples `curl` de la référence de l'API) puis arrête le serveur. Il a besoin d'[`uv`](https://docs.astral.sh/uv/), qui installe les paquets Python.
42+
43+- **Sur le Mac**, le serveur fait tourner MLX : téléchargez d'abord `mlx-community/Qwen3-4B-4bit` et `BAAI/bge-small-en-v1.5`. `mlx-community/Llama-3.2-3B-Instruct-4bit`, s'il est dans le cache, ajoute les tests d'une deuxième famille d'appels d'outils. Le script recompile `rzb` (de façon incrémentale) avant de lancer les tests.
44+- **Sur Linux**, le serveur fait tourner le moteur factice : le protocole est vérifié (formes, streaming, erreurs) et les tests qui demandent un vrai modèle sont ignorés.
45+- **Contre un serveur que vous avez démarré** : `RZB_URL=http://127.0.0.1:8080/v1 scripts/compat.sh`. Il doit déclarer les identifiants `chat` et `embed` (et éventuellement `unforced`).
46+- Autres modèles : `RZB_COMPAT_CHAT_SOURCE`, `RZB_COMPAT_EMBED_SOURCE`, `RZB_COMPAT_UNFORCED_SOURCE`.
47+
3448 ## Lancer les tests de l'outil host-runner
3549
3650 ```bash
@@ -50,7 +64,7 @@ La dernière commande écrit un rapport dans `.quality/` et sort avec le code `0
5064 ## Variantes
5165
5266 - **Depuis une sandbox Linux, pour la partie Mac** : `tools/host-runner/host.sh test . razorbill` ; voir [Développer depuis une sandbox Linux](developper-depuis-une-sandbox.md).
53-- **Les tests qui ont besoin d'un terminal** (`rzb chat`, `rzb init`, `rzb tui`) utilisent une console scriptée ou un faux terminal : ils tournent sans intervention. Le comportement dans un vrai terminal se vérifie à la main.
67+- **Les tests avec un vrai modèle** (`ChatSmokeTests`, `ConstrainedSmokeTests`, `EmbeddingSmokeTests`, sur le Mac) ne tournent que si leur modèle est dans le cache : `mlx-community/Qwen3-0.6B-4bit`, `sentence-transformers/all-MiniLM-L6-v2`, `BAAI/bge-small-en-v1.5`. Sinon ils sont ignorés.
5468
5569 ## Voir aussi
5670
@@ -31,6 +31,20 @@ xcodebuild test -scheme razorbill -destination 'platform=macOS' -derivedDataPath
31 -skipPackagePluginValidation -skipMacroValidation -only-testing:RazorbillMLXTests31 -skipPackagePluginValidation -skipMacroValidation -only-testing:RazorbillMLXTests
32 ```32 ```
33 33
34+## Vérifier la compatibilité avec de vrais clients OpenAI
35+
36+```bash
37+scripts/compat.sh # toute la suite
38+scripts/compat.sh -k tools # les arguments supplémentaires vont à pytest
39+```
40+
41+Il démarre `rzb serve` sur le port 18080 avec sa propre configuration, lance `Tests/Compatibility` (pytest, avec la bibliothèque `openai`, LangChain, et les exemples `curl` de la référence de l'API) puis arrête le serveur. Il a besoin d'[`uv`](https://docs.astral.sh/uv/), qui installe les paquets Python.
42+
43+- **Sur le Mac**, le serveur fait tourner MLX : téléchargez d'abord `mlx-community/Qwen3-4B-4bit` et `BAAI/bge-small-en-v1.5`. `mlx-community/Llama-3.2-3B-Instruct-4bit`, s'il est dans le cache, ajoute les tests d'une deuxième famille d'appels d'outils. Le script recompile `rzb` (de façon incrémentale) avant de lancer les tests.
44+- **Sur Linux**, le serveur fait tourner le moteur factice : le protocole est vérifié (formes, streaming, erreurs) et les tests qui demandent un vrai modèle sont ignorés.
45+- **Contre un serveur que vous avez démarré** : `RZB_URL=http://127.0.0.1:8080/v1 scripts/compat.sh`. Il doit déclarer les identifiants `chat` et `embed` (et éventuellement `unforced`).
46+- Autres modèles : `RZB_COMPAT_CHAT_SOURCE`, `RZB_COMPAT_EMBED_SOURCE`, `RZB_COMPAT_UNFORCED_SOURCE`.
47+
34 ## Lancer les tests de l'outil host-runner48 ## Lancer les tests de l'outil host-runner
35 49
36 ```bash50 ```bash
@@ -50,7 +64,7 @@ La dernière commande écrit un rapport dans `.quality/` et sort avec le code `0
50 ## Variantes64 ## Variantes
51 65
52 - **Depuis une sandbox Linux, pour la partie Mac** : `tools/host-runner/host.sh test . razorbill` ; voir [Développer depuis une sandbox Linux](developper-depuis-une-sandbox.md).66 - **Depuis une sandbox Linux, pour la partie Mac** : `tools/host-runner/host.sh test . razorbill` ; voir [Développer depuis une sandbox Linux](developper-depuis-une-sandbox.md).
53-- **Les tests qui ont besoin d'un terminal** (`rzb chat`, `rzb init`, `rzb tui`) utilisent une console scriptée ou un faux terminal : ils tournent sans intervention. Le comportement dans un vrai terminal se vérifie à la main.67+- **Les tests avec un vrai modèle** (`ChatSmokeTests`, `ConstrainedSmokeTests`, `EmbeddingSmokeTests`, sur le Mac) ne tournent que si leur modèle est dans le cache : `mlx-community/Qwen3-0.6B-4bit`, `sentence-transformers/all-MiniLM-L6-v2`, `BAAI/bge-small-en-v1.5`. Sinon ils sont ignorés.
54 68
55 ## Voir aussi69 ## Voir aussi
56 70
added docs/fr/how-to/obtenir-une-sortie-structuree.md +70 -0
new file mode 100644
@@ -0,0 +1,70 @@
1+# Obtenir une sortie structurée
2+
3+Ce guide fait répondre un modèle avec du JSON conforme à un schéma, pour que votre programme puisse l'analyser sans vérification. Il suppose un serveur qui tourne avec un modèle de chat ; les exemples utilisent `mlx-community/Qwen3-4B-4bit` (les modèles de moins de 1 milliard de paramètres respectent les schémas, mais les remplissent souvent mal).
4+
5+## Avec la bibliothèque Python openai et une classe Pydantic
6+
7+```python
8+from openai import OpenAI
9+from pydantic import BaseModel
10+
11+class City(BaseModel):
12+ name: str
13+ country: str
14+ population: int
15+ landmarks: list[str]
16+
17+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
18+completion = client.beta.chat.completions.parse(
19+ model="mlx-community/Qwen3-4B-4bit",
20+ messages=[{"role": "user", "content": "Describe Lyon, France."}],
21+ response_format=City,
22+)
23+city = completion.choices[0].message.parsed # une instance de City
24+```
25+
26+Lancez-le avec `uv run --with openai --with pydantic python city.py`. Les versions récentes de la bibliothèque proposent aussi `client.chat.completions.parse(...)`.
27+
28+## Avec n'importe quel client : un JSON Schema
29+
30+Envoyez `response_format` avec le schéma :
31+
32+```json
33+"response_format": {
34+ "type": "json_schema",
35+ "json_schema": {
36+ "name": "city",
37+ "strict": true,
38+ "schema": {
39+ "type": "object",
40+ "additionalProperties": false,
41+ "required": ["name", "country"],
42+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}
43+ }
44+ }
45+}
46+```
47+
48+Le `content` de la réponse est une chaîne JSON valide selon le schéma ; analysez-la avec la bibliothèque JSON de votre langage.
49+
50+## N'importe quel objet JSON, sans schéma
51+
52+```json
53+"response_format": {"type": "json_object"}
54+```
55+
56+Précisez dans votre prompt les clés que vous voulez : seule la syntaxe est garantie.
57+
58+## Variantes
59+
60+- **Streaming** : ajoutez `"stream": true` ; le JSON arrive par morceaux dans `delta.content`. Assemblez-les avant de les analyser.
61+- **Modèles qui raisonnent** : avec la réflexion activée (`"reasoning_effort": "low"`), le modèle réfléchit librement, puis écrit le JSON ; le raisonnement est dans `reasoning_content`. Laissez de la place dans `max_tokens` pour les deux. Pour des extractions simples, `"reasoning_effort": "none"` est plus rapide.
62+- **Ordre des clés** : les propriétés sortent dans l'ordre du schéma. Placez un champ comme `reasoning` avant `answer` si vous voulez que le modèle l'écrive en premier.
63+- **Un 400 qui nomme un mot-clé** (`uniqueItems`, `multipleOf`, `not`, `if`…) : avec `"strict": true`, le serveur refuse les mots-clés qu'il ne sait pas appliquer. Retirez le mot-clé, ou passez `"strict": false` et vérifiez cette règle dans votre code.
64+- **Votre propre message système** : gardez-le. Le serveur y ajoute une phrase qui demande du JSON (avec le schéma).
65+- **Outils et sortie structurée ensemble** : `response_format` ne peut pas être combiné à un appel d'outil forcé (`tool_choice` `required` ou nommé) ; avec `tool_choice: "auto"`, il s'applique à la réponse en texte.
66+
67+## Voir aussi
68+
69+- Chaque champ de `response_format` : [référence de l'API HTTP](../reference/api-http.md#sortie-structurée).
70+- Comment la contrainte fonctionne, et ses limites : [décodage contraint](../explanation/decodage-contraint.md).
new file mode 100644
@@ -0,0 +1,70 @@
1+# Obtenir une sortie structurée
2+
3+Ce guide fait répondre un modèle avec du JSON conforme à un schéma, pour que votre programme puisse l'analyser sans vérification. Il suppose un serveur qui tourne avec un modèle de chat ; les exemples utilisent `mlx-community/Qwen3-4B-4bit` (les modèles de moins de 1 milliard de paramètres respectent les schémas, mais les remplissent souvent mal).
4+
5+## Avec la bibliothèque Python openai et une classe Pydantic
6+
7+```python
8+from openai import OpenAI
9+from pydantic import BaseModel
10+
11+class City(BaseModel):
12+ name: str
13+ country: str
14+ population: int
15+ landmarks: list[str]
16+
17+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
18+completion = client.beta.chat.completions.parse(
19+ model="mlx-community/Qwen3-4B-4bit",
20+ messages=[{"role": "user", "content": "Describe Lyon, France."}],
21+ response_format=City,
22+)
23+city = completion.choices[0].message.parsed # une instance de City
24+```
25+
26+Lancez-le avec `uv run --with openai --with pydantic python city.py`. Les versions récentes de la bibliothèque proposent aussi `client.chat.completions.parse(...)`.
27+
28+## Avec n'importe quel client : un JSON Schema
29+
30+Envoyez `response_format` avec le schéma :
31+
32+```json
33+"response_format": {
34+ "type": "json_schema",
35+ "json_schema": {
36+ "name": "city",
37+ "strict": true,
38+ "schema": {
39+ "type": "object",
40+ "additionalProperties": false,
41+ "required": ["name", "country"],
42+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}
43+ }
44+ }
45+}
46+```
47+
48+Le `content` de la réponse est une chaîne JSON valide selon le schéma ; analysez-la avec la bibliothèque JSON de votre langage.
49+
50+## N'importe quel objet JSON, sans schéma
51+
52+```json
53+"response_format": {"type": "json_object"}
54+```
55+
56+Précisez dans votre prompt les clés que vous voulez : seule la syntaxe est garantie.
57+
58+## Variantes
59+
60+- **Streaming** : ajoutez `"stream": true` ; le JSON arrive par morceaux dans `delta.content`. Assemblez-les avant de les analyser.
61+- **Modèles qui raisonnent** : avec la réflexion activée (`"reasoning_effort": "low"`), le modèle réfléchit librement, puis écrit le JSON ; le raisonnement est dans `reasoning_content`. Laissez de la place dans `max_tokens` pour les deux. Pour des extractions simples, `"reasoning_effort": "none"` est plus rapide.
62+- **Ordre des clés** : les propriétés sortent dans l'ordre du schéma. Placez un champ comme `reasoning` avant `answer` si vous voulez que le modèle l'écrive en premier.
63+- **Un 400 qui nomme un mot-clé** (`uniqueItems`, `multipleOf`, `not`, `if`…) : avec `"strict": true`, le serveur refuse les mots-clés qu'il ne sait pas appliquer. Retirez le mot-clé, ou passez `"strict": false` et vérifiez cette règle dans votre code.
64+- **Votre propre message système** : gardez-le. Le serveur y ajoute une phrase qui demande du JSON (avec le schéma).
65+- **Outils et sortie structurée ensemble** : `response_format` ne peut pas être combiné à un appel d'outil forcé (`tool_choice` `required` ou nommé) ; avec `tool_choice: "auto"`, il s'applique à la réponse en texte.
66+
67+## Voir aussi
68+
69+- Chaque champ de `response_format` : [référence de l'API HTTP](../reference/api-http.md#sortie-structurée).
70+- Comment la contrainte fonctionne, et ses limites : [décodage contraint](../explanation/decodage-contraint.md).
modified docs/fr/how-to/regler-la-reflexion.md +46 -26
@@ -1,49 +1,69 @@
1-# Régler la réflexion
1+# Régler le raisonnement
22
3-Les modèles qui raisonnent (Qwen3, Qwen3.5…) peuvent réfléchir avant de répondre. Ce guide montre comment activer la réflexion, choisir si vous la voyez, et limiter sa durée.
3+Ce guide active ou coupe le raisonnement des modèles qui réfléchissent (Qwen3, Qwen3.5, DeepSeek-R1…), le limite, et décide si les clients le voient. Il suppose un serveur qui tourne avec un modèle qui raisonne, par exemple `mlx-community/Qwen3-4B-4bit`.
44
5-## Activer la réflexion
5+## L'activer ou le couper pour une requête
66
7-Dans le fichier d'agent :
7+Envoyez l'un de ces champs (avec la bibliothèque openai, dans `extra_body`) :
88
9-```yaml
10-generation:
11- thinking: true
9+| Champ | Réflexion |
10+| --- | --- |
11+| `"reasoning_effort": "low"`, `"medium"` ou `"high"` | activée |
12+| `"reasoning_effort": "none"` ou `"minimal"` | coupée |
13+| `"chat_template_kwargs": {"enable_thinking": true}` | activée (l'emporte sur `reasoning_effort`) |
14+
15+```python
16+answer = client.chat.completions.create(
17+ model="mlx-community/Qwen3-4B-4bit",
18+ messages=[{"role": "user", "content": "Is 391 a prime number?"}],
19+ extra_body={"reasoning_effort": "high"},
20+)
21+print(answer.choices[0].message.reasoning_content) # le raisonnement
22+print(answer.choices[0].message.content) # la réponse seule
1223 ```
1324
14-Ou pour une exécution : `rzb chat --think` (et `--no-think` pour la désactiver quand le fichier l'active).
25+`low`, `medium` et `high` se comportent de la même façon : le modèle réfléchit ou non.
1526
16-## Afficher ou masquer le raisonnement
27+## L'activer par défaut
1728
1829 ```yaml
19-ui:
20- show_thinking: false # true par défaut
30+defaults:
31+ thinking: true # tous les modèles…
32+models:
33+ - id: fast
34+ source: mlx-community/Qwen3-4B-4bit
35+ defaults: { thinking: false } # …sauf celui-ci
2136 ```
2237
23-- `rzb run` et `rzb chat` affichent le raisonnement en grisé sur la sortie d'erreur : `rzb run … > reponse.txt` ne le garde donc jamais.
24-- `rzb tui` démarre avec le raisonnement affiché ou masqué selon ce réglage ; **Ctrl-T** le bascule à tout moment.
38+Sans configuration, les modèles ne réfléchissent pas, sauf si une requête le demande.
39+
40+## Limiter sa durée
2541
26-## Limiter la réflexion
42+Par requête : `"thinking_budget": 256` (une extension razorbill). Dans la configuration :
2743
2844 ```yaml
29-generation:
30- max_tokens: 2048
31- thinking: true
32- thinking_budget: 512 # au plus 512 tokens de raisonnement, puis le modèle répond
45+defaults:
46+ thinking_budget: 512
47+locked:
48+ thinking_budget: 2048 # un plafond que les clients ne peuvent pas dépasser
3349 ```
3450
35-Ou pour une exécution : `rzb chat --think --thinking-budget 200`.
51+Quand le budget est épuisé, le modèle est obligé de clore son raisonnement et de répondre. Le raisonnement compte dans `max_tokens` : gardez `max_tokens` bien au-dessus du budget. Les modèles sans protocole de raisonnement connu (Llama, Gemma) refusent un budget avec un 400.
52+
53+## Masquer le raisonnement aux clients
54+
55+- Pour une requête : `"include_reasoning": false`.
56+- Toujours : `locked: { show_reasoning: false }` dans la configuration.
3657
37-- `0` fait répondre le modèle tout de suite.
38-- Le raisonnement compte dans `max_tokens` : le budget doit être plus petit, et laisser de la place pour la réponse.
39-- Le budget ne s'applique que si `thinking` est activé.
58+Le modèle réfléchit quand même ; `reasoning_content` est retiré, et `usage.completion_tokens_details.reasoning_tokens` le compte toujours.
4059
4160 ## Variantes
4261
43-- **Un modèle qui ne raisonne pas** (Llama, Gemma) : `thinking` n'a aucun effet, et `thinking_budget` arrête l'agent avec `… has no known thinking protocol: remove generation.thinking_budget`. Retirez le budget pour ces modèles.
44-- **Réponses coupées** : augmentez `max_tokens`, ou baissez `thinking_budget`.
62+- **Streaming** : le raisonnement arrive dans `delta.reasoning_content` avant le `delta.content` de la réponse.
63+- **Les clients qui ne lisent que `content`** voient la réponse sans le raisonnement, ce qu'attendent la plupart des interfaces de chat.
64+- **Sortie structurée ou appels d'outils** : le modèle réfléchit librement, puis la contrainte s'applique à la réponse.
4565
4666 ## Voir aussi
4767
48-- Les clés : [référence du fichier d'agent](../reference/configuration.md#generation) et [`ui`](../reference/configuration.md#ui).
49-- Comment la réflexion est détectée, affichée et limitée : [modèles qui réfléchissent](../explanation/reflexion.md).
68+- Les champs : [référence de l'API HTTP](../reference/api-http.md#champs-de-la-requête) et [référence de la configuration](../reference/configuration.md#defaults-et-locked).
69+- Comment le raisonnement est séparé et limité : [modèles qui raisonnent](../explanation/reflexion.md).
@@ -1,49 +1,69 @@
1-# Régler la réflexion1+# Régler le raisonnement
2 2
3-Les modèles qui raisonnent (Qwen3, Qwen3.5…) peuvent réfléchir avant de répondre. Ce guide montre comment activer la réflexion, choisir si vous la voyez, et limiter sa durée.3+Ce guide active ou coupe le raisonnement des modèles qui réfléchissent (Qwen3, Qwen3.5, DeepSeek-R1…), le limite, et décide si les clients le voient. Il suppose un serveur qui tourne avec un modèle qui raisonne, par exemple `mlx-community/Qwen3-4B-4bit`.
4 4
5-## Activer la réflexion5+## L'activer ou le couper pour une requête
6 6
7-Dans le fichier d'agent :7+Envoyez l'un de ces champs (avec la bibliothèque openai, dans `extra_body`) :
8 8
9-```yaml9+| Champ | Réflexion |
10-generation:10+| --- | --- |
11- thinking: true11+| `"reasoning_effort": "low"`, `"medium"` ou `"high"` | activée |
12+| `"reasoning_effort": "none"` ou `"minimal"` | coupée |
13+| `"chat_template_kwargs": {"enable_thinking": true}` | activée (l'emporte sur `reasoning_effort`) |
14+
15+```python
16+answer = client.chat.completions.create(
17+ model="mlx-community/Qwen3-4B-4bit",
18+ messages=[{"role": "user", "content": "Is 391 a prime number?"}],
19+ extra_body={"reasoning_effort": "high"},
20+)
21+print(answer.choices[0].message.reasoning_content) # le raisonnement
22+print(answer.choices[0].message.content) # la réponse seule
12 ```23 ```
13 24
14-Ou pour une exécution : `rzb chat --think` (et `--no-think` pour la désactiver quand le fichier l'active).25+`low`, `medium` et `high` se comportent de la même façon : le modèle réfléchit ou non.
15 26
16-## Afficher ou masquer le raisonnement27+## L'activer par défaut
17 28
18 ```yaml29 ```yaml
19-ui:30+defaults:
20- show_thinking: false # true par défaut31+ thinking: true # tous les modèles…
32+models:
33+ - id: fast
34+ source: mlx-community/Qwen3-4B-4bit
35+ defaults: { thinking: false } # …sauf celui-ci
21 ```36 ```
22 37
23-- `rzb run` et `rzb chat` affichent le raisonnement en grisé sur la sortie d'erreur : `rzb run … > reponse.txt` ne le garde donc jamais.38+Sans configuration, les modèles ne réfléchissent pas, sauf si une requête le demande.
24-- `rzb tui` démarre avec le raisonnement affiché ou masqué selon ce réglage ; **Ctrl-T** le bascule à tout moment.39+
40+## Limiter sa durée
25 41
26-## Limiter la réflexion42+Par requête : `"thinking_budget": 256` (une extension razorbill). Dans la configuration :
27 43
28 ```yaml44 ```yaml
29-generation:45+defaults:
30- max_tokens: 204846+ thinking_budget: 512
31- thinking: true47+locked:
32- thinking_budget: 512 # au plus 512 tokens de raisonnement, puis le modèle répond48+ thinking_budget: 2048 # un plafond que les clients ne peuvent pas dépasser
33 ```49 ```
34 50
35-Ou pour une exécution : `rzb chat --think --thinking-budget 200`.51+Quand le budget est épuisé, le modèle est obligé de clore son raisonnement et de répondre. Le raisonnement compte dans `max_tokens` : gardez `max_tokens` bien au-dessus du budget. Les modèles sans protocole de raisonnement connu (Llama, Gemma) refusent un budget avec un 400.
52+
53+## Masquer le raisonnement aux clients
54+
55+- Pour une requête : `"include_reasoning": false`.
56+- Toujours : `locked: { show_reasoning: false }` dans la configuration.
36 57
37-- `0` fait répondre le modèle tout de suite.58+Le modèle réfléchit quand même ; `reasoning_content` est retiré, et `usage.completion_tokens_details.reasoning_tokens` le compte toujours.
38-- Le raisonnement compte dans `max_tokens` : le budget doit être plus petit, et laisser de la place pour la réponse.
39-- Le budget ne s'applique que si `thinking` est activé.
40 59
41 ## Variantes60 ## Variantes
42 61
43-- **Un modèle qui ne raisonne pas** (Llama, Gemma) : `thinking` n'a aucun effet, et `thinking_budget` arrête l'agent avec `… has no known thinking protocol: remove generation.thinking_budget`. Retirez le budget pour ces modèles.62+- **Streaming** : le raisonnement arrive dans `delta.reasoning_content` avant le `delta.content` de la réponse.
44-- **Réponses coupées** : augmentez `max_tokens`, ou baissez `thinking_budget`.63+- **Les clients qui ne lisent que `content`** voient la réponse sans le raisonnement, ce qu'attendent la plupart des interfaces de chat.
64+- **Sortie structurée ou appels d'outils** : le modèle réfléchit librement, puis la contrainte s'applique à la réponse.
45 65
46 ## Voir aussi66 ## Voir aussi
47 67
48-- Les clés : [référence du fichier d'agent](../reference/configuration.md#generation) et [`ui`](../reference/configuration.md#ui).68+- Les champs : [référence de l'API HTTP](../reference/api-http.md#champs-de-la-requête) et [référence de la configuration](../reference/configuration.md#defaults-et-locked).
49-- Comment la réflexion est détectée, affichée et limitée : [modèles qui réfléchissent](../explanation/reflexion.md).69+- Comment le raisonnement est séparé et limité : [modèles qui raisonnent](../explanation/reflexion.md).
added docs/fr/how-to/utiliser-des-clients-openai.md +73 -0
new file mode 100644
@@ -0,0 +1,73 @@
1+# Utiliser razorbill depuis un client OpenAI
2+
3+Ce guide branche des clients et frameworks OpenAI existants sur `rzb serve`. Il suppose que le serveur tourne à `http://127.0.0.1:8080` (ajoutez votre clé si vous en avez défini une).
4+
5+La règle est toujours la même : **URL de base** `http://127.0.0.1:8080/v1`, **clé d'API** n'importe quelle valeur non vide (ou la clé du serveur), **modèle** un `id` déclaré ou un identifiant Hugging Face.
6+
7+## Python — openai
8+
9+```python
10+from openai import OpenAI
11+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
12+```
13+
14+Les champs propres à razorbill vont dans `extra_body`, par exemple `extra_body={"reasoning_effort": "none", "thinking_budget": 256}`.
15+
16+## JavaScript / TypeScript — openai
17+
18+```javascript
19+import OpenAI from "openai";
20+const client = new OpenAI({ baseURL: "http://127.0.0.1:8080/v1", apiKey: "unused" });
21+const answer = await client.chat.completions.create({
22+ model: "mlx-community/Qwen3-4B-4bit",
23+ messages: [{ role: "user", content: "Hello" }],
24+});
25+```
26+
27+## LangChain (Python)
28+
29+```python
30+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
31+
32+llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="mlx-community/Qwen3-4B-4bit")
33+embeddings = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused",
34+ model="BAAI/bge-small-en-v1.5", check_embedding_ctx_length=False)
35+```
36+
37+`check_embedding_ctx_length=False` est indispensable : sinon LangChain envoie des tableaux de tokens, que le serveur refuse.
38+
39+## Variables d'environnement
40+
41+Beaucoup d'outils lisent les variables OpenAI standard :
42+
43+```bash
44+export OPENAI_BASE_URL=http://127.0.0.1:8080/v1
45+export OPENAI_API_KEY=unused
46+```
47+
48+## Interfaces de chat (Open WebUI et autres)
49+
50+Ajoutez une connexion « OpenAI API » avec l'URL de base `http://127.0.0.1:8080/v1` et n'importe quelle clé. Si l'interface tourne dans Docker, `127.0.0.1` désigne le conteneur lui-même : utilisez `http://host.docker.internal:8080/v1` et démarrez le serveur avec `--host 0.0.0.0` et une clé d'API. L'interface liste les modèles de `/v1/models`.
51+
52+## Outils qui utilisent l'API de complétion historique
53+
54+Les extensions de complétion de code et les bancs d'évaluation (lm-eval…) qui appellent `/v1/completions` fonctionnent aussi : le prompt est continué tel quel. Le fill-in-the-middle (`suffix`) et `logprobs` sont refusés.
55+
56+## curl
57+
58+```bash
59+curl -s http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" \
60+ -H "Authorization: Bearer $RZB_API_KEY" \
61+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Hello"}]}'
62+```
63+
64+## Quand quelque chose ne marche pas
65+
66+- **404 `model_not_found`** : le client envoie un nom de modèle que le serveur ne connaît pas (certaines interfaces mettent `gpt-4o` par défaut). Choisissez un modèle de `/v1/models`.
67+- **400 qui nomme un champ** : le client envoie quelque chose que razorbill refuse au lieu de l'ignorer (`n` > 1, `logprobs`, images…). Le message dit quel champ.
68+- **401** : le serveur a une clé et le client en envoie une autre, ou aucune.
69+
70+## Voir aussi
71+
72+- Ce qui est pris en charge, refusé ou ignoré : [référence de l'API HTTP](../reference/api-http.md).
73+- Comment la compatibilité est définie et vérifiée : [compatibilité OpenAI](../explanation/compatibilite-openai.md).
new file mode 100644
@@ -0,0 +1,73 @@
1+# Utiliser razorbill depuis un client OpenAI
2+
3+Ce guide branche des clients et frameworks OpenAI existants sur `rzb serve`. Il suppose que le serveur tourne à `http://127.0.0.1:8080` (ajoutez votre clé si vous en avez défini une).
4+
5+La règle est toujours la même : **URL de base** `http://127.0.0.1:8080/v1`, **clé d'API** n'importe quelle valeur non vide (ou la clé du serveur), **modèle** un `id` déclaré ou un identifiant Hugging Face.
6+
7+## Python — openai
8+
9+```python
10+from openai import OpenAI
11+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
12+```
13+
14+Les champs propres à razorbill vont dans `extra_body`, par exemple `extra_body={"reasoning_effort": "none", "thinking_budget": 256}`.
15+
16+## JavaScript / TypeScript — openai
17+
18+```javascript
19+import OpenAI from "openai";
20+const client = new OpenAI({ baseURL: "http://127.0.0.1:8080/v1", apiKey: "unused" });
21+const answer = await client.chat.completions.create({
22+ model: "mlx-community/Qwen3-4B-4bit",
23+ messages: [{ role: "user", content: "Hello" }],
24+});
25+```
26+
27+## LangChain (Python)
28+
29+```python
30+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
31+
32+llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused", model="mlx-community/Qwen3-4B-4bit")
33+embeddings = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="unused",
34+ model="BAAI/bge-small-en-v1.5", check_embedding_ctx_length=False)
35+```
36+
37+`check_embedding_ctx_length=False` est indispensable : sinon LangChain envoie des tableaux de tokens, que le serveur refuse.
38+
39+## Variables d'environnement
40+
41+Beaucoup d'outils lisent les variables OpenAI standard :
42+
43+```bash
44+export OPENAI_BASE_URL=http://127.0.0.1:8080/v1
45+export OPENAI_API_KEY=unused
46+```
47+
48+## Interfaces de chat (Open WebUI et autres)
49+
50+Ajoutez une connexion « OpenAI API » avec l'URL de base `http://127.0.0.1:8080/v1` et n'importe quelle clé. Si l'interface tourne dans Docker, `127.0.0.1` désigne le conteneur lui-même : utilisez `http://host.docker.internal:8080/v1` et démarrez le serveur avec `--host 0.0.0.0` et une clé d'API. L'interface liste les modèles de `/v1/models`.
51+
52+## Outils qui utilisent l'API de complétion historique
53+
54+Les extensions de complétion de code et les bancs d'évaluation (lm-eval…) qui appellent `/v1/completions` fonctionnent aussi : le prompt est continué tel quel. Le fill-in-the-middle (`suffix`) et `logprobs` sont refusés.
55+
56+## curl
57+
58+```bash
59+curl -s http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" \
60+ -H "Authorization: Bearer $RZB_API_KEY" \
61+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Hello"}]}'
62+```
63+
64+## Quand quelque chose ne marche pas
65+
66+- **404 `model_not_found`** : le client envoie un nom de modèle que le serveur ne connaît pas (certaines interfaces mettent `gpt-4o` par défaut). Choisissez un modèle de `/v1/models`.
67+- **400 qui nomme un champ** : le client envoie quelque chose que razorbill refuse au lieu de l'ignorer (`n` > 1, `logprobs`, images…). Le message dit quel champ.
68+- **401** : le serveur a une clé et le client en envoie une autre, ou aucune.
69+
70+## Voir aussi
71+
72+- Ce qui est pris en charge, refusé ou ignoré : [référence de l'API HTTP](../reference/api-http.md).
73+- Comment la compatibilité est définie et vérifiée : [compatibilité OpenAI](../explanation/compatibilite-openai.md).
added docs/fr/how-to/utiliser-l-appel-de-fonctions.md +75 -0
new file mode 100644
@@ -0,0 +1,75 @@
1+# Utiliser l'appel de fonctions
2+
3+Ce guide permet à un modèle d'appeler des fonctions de votre programme : il demande un appel, votre code l'exécute, et le modèle utilise le résultat dans sa réponse. Il suppose un serveur qui tourne avec un modèle de chat qui gère les outils ; les exemples utilisent `mlx-community/Qwen3-4B-4bit`.
4+
5+## 1. Décrire les fonctions
6+
7+```python
8+tools = [{
9+ "type": "function",
10+ "function": {
11+ "name": "get_weather",
12+ "description": "Current weather for a city",
13+ "parameters": {
14+ "type": "object",
15+ "properties": {"city": {"type": "string"}},
16+ "required": ["city"],
17+ },
18+ },
19+}]
20+```
21+
22+## 2. Demander, exécuter les appels, renvoyer les résultats
23+
24+```python
25+import json
26+from openai import OpenAI
27+
28+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
29+messages = [{"role": "user", "content": "What's the weather like in Lyon?"}]
30+
31+def get_weather(city):
32+ return {"city": city, "temp_c": 7, "sky": "rain"}
33+
34+while True:
35+ answer = client.chat.completions.create(
36+ model="mlx-community/Qwen3-4B-4bit", messages=messages, tools=tools
37+ ).choices[0]
38+ if answer.finish_reason != "tool_calls":
39+ print(answer.message.content)
40+ break
41+ messages.append(answer.message.model_dump(exclude_none=True))
42+ for call in answer.message.tool_calls:
43+ result = get_weather(**json.loads(call.function.arguments))
44+ messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
45+```
46+
47+Chaque requête porte toute la conversation, appels de l'assistant et résultats `tool` compris : le serveur ne garde rien entre les requêtes.
48+
49+## Forcer un appel
50+
51+- `tool_choice="required"` : la réponse est un appel à l'un des outils.
52+- `tool_choice={"type": "function", "function": {"name": "get_weather"}}` : la réponse est un appel à `get_weather`.
53+- `tool_choice="none"` : le modèle répond en texte, sans voir les outils.
54+
55+Un appel forcé est généré sous une grammaire : le nom existe et les arguments respectent le schéma. Cela fonctionne pour les modèles dont la syntaxe d'appel est `<tool_call>{…}</tool_call>` (Qwen, Hermes…). Les autres familles (Llama 3, Mistral, Gemma) répondent 400 à un appel forcé : utilisez `tool_choice="auto"` avec elles.
56+
57+## Obtenir plusieurs appels à la fois
58+
59+Un appel forcé produit un seul appel. Pour laisser le modèle en demander plusieurs dans une réponse (météo et heure, par exemple), envoyez `parallel_tool_calls=True`. Avec `parallel_tool_calls=False`, seul le premier appel est gardé, quel que soit le mode.
60+
61+## Garantir des arguments valides en mode auto
62+
63+Ajoutez `"strict": True` à une fonction : ses arguments sont alors générés selon son schéma chaque fois que le modèle l'appelle, tandis que le modèle reste libre de ne pas l'appeler. Le schéma ne doit pas utiliser de mots-clés que le décodeur ne sait pas appliquer (voir [sortie structurée](obtenir-une-sortie-structuree.md#variantes)).
64+
65+## Variantes
66+
67+- **Streaming** : avec `stream=True`, chaque appel arrive entier dans un morceau, dans `delta.tool_calls` avec son `index` ; le dernier morceau porte `finish_reason: "tool_calls"`.
68+- **LangChain** : `ChatOpenAI(base_url=…, model=…).bind_tools([...])` fonctionne comme avec OpenAI (voir [utiliser des clients OpenAI](utiliser-des-clients-openai.md)).
69+- **Petits modèles** (moins de 1 milliard de paramètres) : en mode `auto`, ils répondent souvent en texte au lieu d'appeler ; forcez l'appel ou prenez un modèle plus grand.
70+- **Réflexion** : un modèle qui raisonne peut réfléchir avant d'appeler ; ajoutez `extra_body={"reasoning_effort": "none"}` pour l'éviter.
71+
72+## Voir aussi
73+
74+- Chaque champ de `tools` et `tool_choice` : [référence de l'API HTTP](../reference/api-http.md#outils).
75+- Pourquoi les appels forcés dépendent de la famille du modèle : [décodage contraint](../explanation/decodage-contraint.md).
new file mode 100644
@@ -0,0 +1,75 @@
1+# Utiliser l'appel de fonctions
2+
3+Ce guide permet à un modèle d'appeler des fonctions de votre programme : il demande un appel, votre code l'exécute, et le modèle utilise le résultat dans sa réponse. Il suppose un serveur qui tourne avec un modèle de chat qui gère les outils ; les exemples utilisent `mlx-community/Qwen3-4B-4bit`.
4+
5+## 1. Décrire les fonctions
6+
7+```python
8+tools = [{
9+ "type": "function",
10+ "function": {
11+ "name": "get_weather",
12+ "description": "Current weather for a city",
13+ "parameters": {
14+ "type": "object",
15+ "properties": {"city": {"type": "string"}},
16+ "required": ["city"],
17+ },
18+ },
19+}]
20+```
21+
22+## 2. Demander, exécuter les appels, renvoyer les résultats
23+
24+```python
25+import json
26+from openai import OpenAI
27+
28+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
29+messages = [{"role": "user", "content": "What's the weather like in Lyon?"}]
30+
31+def get_weather(city):
32+ return {"city": city, "temp_c": 7, "sky": "rain"}
33+
34+while True:
35+ answer = client.chat.completions.create(
36+ model="mlx-community/Qwen3-4B-4bit", messages=messages, tools=tools
37+ ).choices[0]
38+ if answer.finish_reason != "tool_calls":
39+ print(answer.message.content)
40+ break
41+ messages.append(answer.message.model_dump(exclude_none=True))
42+ for call in answer.message.tool_calls:
43+ result = get_weather(**json.loads(call.function.arguments))
44+ messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
45+```
46+
47+Chaque requête porte toute la conversation, appels de l'assistant et résultats `tool` compris : le serveur ne garde rien entre les requêtes.
48+
49+## Forcer un appel
50+
51+- `tool_choice="required"` : la réponse est un appel à l'un des outils.
52+- `tool_choice={"type": "function", "function": {"name": "get_weather"}}` : la réponse est un appel à `get_weather`.
53+- `tool_choice="none"` : le modèle répond en texte, sans voir les outils.
54+
55+Un appel forcé est généré sous une grammaire : le nom existe et les arguments respectent le schéma. Cela fonctionne pour les modèles dont la syntaxe d'appel est `<tool_call>{…}</tool_call>` (Qwen, Hermes…). Les autres familles (Llama 3, Mistral, Gemma) répondent 400 à un appel forcé : utilisez `tool_choice="auto"` avec elles.
56+
57+## Obtenir plusieurs appels à la fois
58+
59+Un appel forcé produit un seul appel. Pour laisser le modèle en demander plusieurs dans une réponse (météo et heure, par exemple), envoyez `parallel_tool_calls=True`. Avec `parallel_tool_calls=False`, seul le premier appel est gardé, quel que soit le mode.
60+
61+## Garantir des arguments valides en mode auto
62+
63+Ajoutez `"strict": True` à une fonction : ses arguments sont alors générés selon son schéma chaque fois que le modèle l'appelle, tandis que le modèle reste libre de ne pas l'appeler. Le schéma ne doit pas utiliser de mots-clés que le décodeur ne sait pas appliquer (voir [sortie structurée](obtenir-une-sortie-structuree.md#variantes)).
64+
65+## Variantes
66+
67+- **Streaming** : avec `stream=True`, chaque appel arrive entier dans un morceau, dans `delta.tool_calls` avec son `index` ; le dernier morceau porte `finish_reason: "tool_calls"`.
68+- **LangChain** : `ChatOpenAI(base_url=…, model=…).bind_tools([...])` fonctionne comme avec OpenAI (voir [utiliser des clients OpenAI](utiliser-des-clients-openai.md)).
69+- **Petits modèles** (moins de 1 milliard de paramètres) : en mode `auto`, ils répondent souvent en texte au lieu d'appeler ; forcez l'appel ou prenez un modèle plus grand.
70+- **Réflexion** : un modèle qui raisonne peut réfléchir avant d'appeler ; ajoutez `extra_body={"reasoning_effort": "none"}` pour l'éviter.
71+
72+## Voir aussi
73+
74+- Chaque champ de `tools` et `tool_choice` : [référence de l'API HTTP](../reference/api-http.md#outils).
75+- Pourquoi les appels forcés dépendent de la famille du modèle : [décodage contraint](../explanation/decodage-contraint.md).
deleted docs/fr/how-to/utiliser-l-outil-bash.md +0 -54
deleted file mode 100644
@@ -1,54 +0,0 @@
1-# Utiliser l'outil bash
2-
3-L'outil `bash` permet à l'agent de lancer des commandes shell sur votre Mac. Ce guide montre comment l'activer et le garder sous contrôle.
4-
5-## L'activer, avec confirmation
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true # par défaut : vous acceptez chaque commande
11-```
12-
13-L'agent affiche chaque commande et attend `y`. Dans `rzb tui`, la question apparaît sur la ligne du bas.
14-
15-## Restreindre ce qu'il peut lancer
16-
17-```yaml
18-tools:
19- bash:
20- allow: ["ls*", "cat *", "git status", "git diff*", "swift build*"]
21- deny: ["rm *", "sudo *", "git push*"]
22-```
23-
24-`deny` est vérifié en premier et l'emporte toujours ; quand `allow` est donné, une commande doit correspondre à l'un de ses motifs. `*` remplace n'importe quel texte, `?` un seul caractère. Une commande refusée est signalée au modèle, qui peut essayer autre chose.
25-
26-## L'utiliser sans terminal (scripts, CI)
27-
28-Sans terminal pour poser la question, les commandes qui demandent une confirmation sont refusées. Pour les laisser tourner sans surveillance, désactivez explicitement la confirmation — et resserrez `allow` :
29-
30-```yaml
31-tools:
32- bash:
33- confirm: false
34- allow: ["ls*", "git log*"]
35-```
36-
37-## Changer où et combien de temps les commandes tournent
38-
39-```yaml
40-tools:
41- bash:
42- workdir: ./projet # relatif au dossier depuis lequel rzb est lancé
43- timeout: 2m # la commande et tout ce qu'elle a lancé sont tués après ce délai
44- max_output: 64KB # le reste de la sortie est abandonné, avec un marqueur
45-```
46-
47-## Le désactiver
48-
49-Retirez `bash` de `tools:` (ou retirez `tools:`) : les outils intégrés n'existent que s'ils sont listés.
50-
51-## Voir aussi
52-
53-- Toutes les options, l'ordre des vérifications et le format de sortie : [référence de l'outil bash](../reference/outil-bash.md).
54-- Pourquoi les motifs ne sont pas une sandbox, et ce qui est prévu : [sécurité des outils](../explanation/securite-des-outils.md).
deleted file mode 100644
@@ -1,54 +0,0 @@
1-# Utiliser l'outil bash
2-
3-L'outil `bash` permet à l'agent de lancer des commandes shell sur votre Mac. Ce guide montre comment l'activer et le garder sous contrôle.
4-
5-## L'activer, avec confirmation
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true # par défaut : vous acceptez chaque commande
11-```
12-
13-L'agent affiche chaque commande et attend `y`. Dans `rzb tui`, la question apparaît sur la ligne du bas.
14-
15-## Restreindre ce qu'il peut lancer
16-
17-```yaml
18-tools:
19- bash:
20- allow: ["ls*", "cat *", "git status", "git diff*", "swift build*"]
21- deny: ["rm *", "sudo *", "git push*"]
22-```
23-
24-`deny` est vérifié en premier et l'emporte toujours ; quand `allow` est donné, une commande doit correspondre à l'un de ses motifs. `*` remplace n'importe quel texte, `?` un seul caractère. Une commande refusée est signalée au modèle, qui peut essayer autre chose.
25-
26-## L'utiliser sans terminal (scripts, CI)
27-
28-Sans terminal pour poser la question, les commandes qui demandent une confirmation sont refusées. Pour les laisser tourner sans surveillance, désactivez explicitement la confirmation — et resserrez `allow` :
29-
30-```yaml
31-tools:
32- bash:
33- confirm: false
34- allow: ["ls*", "git log*"]
35-```
36-
37-## Changer où et combien de temps les commandes tournent
38-
39-```yaml
40-tools:
41- bash:
42- workdir: ./projet # relatif au dossier depuis lequel rzb est lancé
43- timeout: 2m # la commande et tout ce qu'elle a lancé sont tués après ce délai
44- max_output: 64KB # le reste de la sortie est abandonné, avec un marqueur
45-```
46-
47-## Le désactiver
48-
49-Retirez `bash` de `tools:` (ou retirez `tools:`) : les outils intégrés n'existent que s'ils sont listés.
50-
51-## Voir aussi
52-
53-- Toutes les options, l'ordre des vérifications et le format de sortie : [référence de l'outil bash](../reference/outil-bash.md).
54-- Pourquoi les motifs ne sont pas une sandbox, et ce qui est prévu : [sécurité des outils](../explanation/securite-des-outils.md).
deleted docs/fr/how-to/utiliser-rzb-dans-des-scripts.md +0 -73
deleted file mode 100644
@@ -1,73 +0,0 @@
1-# Utiliser rzb dans des scripts
2-
3-`rzb run` pose une question à l'agent puis s'arrête : il s'utilise donc dans des scripts shell, des pipes et des Makefiles. Ce guide montre les usages courants.
4-
5-## Poser une question
6-
7-```bash
8-rzb run "Summarise the README in three bullet points"
9-```
10-
11-## Envoyer un fichier ou la sortie d'une commande
12-
13-L'entrée reçue par un pipe est ajoutée après le prompt (séparée par une ligne vide) :
14-
15-```bash
16-git diff | rzb run "Review this change"
17-rzb run "Explain this code" < Sources/App/main.swift
18-cat error.log | rzb run # le texte reçu seul sert de prompt
19-```
20-
21-## Ne garder que la réponse
22-
23-La réponse va sur la **sortie standard** ; la progression des téléchargements, la réflexion, les appels d'outils et les statistiques vont sur la **sortie d'erreur** :
24-
25-```bash
26-rzb run "Write a commit message for this diff" < change.diff > message.txt
27-rzb run "…" 2>/dev/null # rien d'autre que la réponse à l'écran
28-```
29-
30-Pour supprimer aussi la ligne de statistiques, mettez `ui.show_stats: false` dans le fichier d'agent.
31-
32-## Rendre les réponses reproductibles
33-
34-```bash
35-rzb run --temperature 0 "…"
36-```
37-
38-## Choisir le fichier d'agent
39-
40-```bash
41-rzb run -c agents/reviewer.yaml "…"
42-```
43-
44-Sans `-c`, `rzb` utilise `./razorbill.yaml`, puis `~/.config/razorbill/agent.yaml`.
45-
46-## Vérifier le résultat
47-
48-| Code de sortie | Signification |
49-| --- | --- |
50-| `0` | la réponse a été affichée |
51-| `1` | quelque chose a échoué pendant l'exécution (modèle, téléchargement, outil…) |
52-| `2` | le fichier d'agent est absent ou invalide |
53-| `64` | ligne de commande incorrecte (option inconnue, prompt manquant) |
54-| `130` | interrompu (Ctrl-C) |
55-
56-```bash
57-if ! rzb run "…" > out.txt; then echo "rzb a échoué" >&2; fi
58-```
59-
60-## Valider un fichier d'agent en CI
61-
62-```bash
63-rzb config validate agents/reviewer.yaml
64-```
65-
66-## Variantes
67-
68-- **Des outils dans un script** : sans terminal, `bash` refuse les commandes qui demandent une confirmation ; voir [Utiliser l'outil bash](utiliser-l-outil-bash.md#lutiliser-sans-terminal-scripts-ci).
69-- **Pas de réseau** : ajoutez `--offline` pour échouer tout de suite si le modèle n'est pas téléchargé.
70-
71-## Voir aussi
72-
73-- Toutes les options : [référence de la ligne de commande](../reference/ligne-de-commande.md).
deleted file mode 100644
@@ -1,73 +0,0 @@
1-# Utiliser rzb dans des scripts
2-
3-`rzb run` pose une question à l'agent puis s'arrête : il s'utilise donc dans des scripts shell, des pipes et des Makefiles. Ce guide montre les usages courants.
4-
5-## Poser une question
6-
7-```bash
8-rzb run "Summarise the README in three bullet points"
9-```
10-
11-## Envoyer un fichier ou la sortie d'une commande
12-
13-L'entrée reçue par un pipe est ajoutée après le prompt (séparée par une ligne vide) :
14-
15-```bash
16-git diff | rzb run "Review this change"
17-rzb run "Explain this code" < Sources/App/main.swift
18-cat error.log | rzb run # le texte reçu seul sert de prompt
19-```
20-
21-## Ne garder que la réponse
22-
23-La réponse va sur la **sortie standard** ; la progression des téléchargements, la réflexion, les appels d'outils et les statistiques vont sur la **sortie d'erreur** :
24-
25-```bash
26-rzb run "Write a commit message for this diff" < change.diff > message.txt
27-rzb run "…" 2>/dev/null # rien d'autre que la réponse à l'écran
28-```
29-
30-Pour supprimer aussi la ligne de statistiques, mettez `ui.show_stats: false` dans le fichier d'agent.
31-
32-## Rendre les réponses reproductibles
33-
34-```bash
35-rzb run --temperature 0 "…"
36-```
37-
38-## Choisir le fichier d'agent
39-
40-```bash
41-rzb run -c agents/reviewer.yaml "…"
42-```
43-
44-Sans `-c`, `rzb` utilise `./razorbill.yaml`, puis `~/.config/razorbill/agent.yaml`.
45-
46-## Vérifier le résultat
47-
48-| Code de sortie | Signification |
49-| --- | --- |
50-| `0` | la réponse a été affichée |
51-| `1` | quelque chose a échoué pendant l'exécution (modèle, téléchargement, outil…) |
52-| `2` | le fichier d'agent est absent ou invalide |
53-| `64` | ligne de commande incorrecte (option inconnue, prompt manquant) |
54-| `130` | interrompu (Ctrl-C) |
55-
56-```bash
57-if ! rzb run "…" > out.txt; then echo "rzb a échoué" >&2; fi
58-```
59-
60-## Valider un fichier d'agent en CI
61-
62-```bash
63-rzb config validate agents/reviewer.yaml
64-```
65-
66-## Variantes
67-
68-- **Des outils dans un script** : sans terminal, `bash` refuse les commandes qui demandent une confirmation ; voir [Utiliser l'outil bash](utiliser-l-outil-bash.md#lutiliser-sans-terminal-scripts-ci).
69-- **Pas de réseau** : ajoutez `--offline` pour échouer tout de suite si le modèle n'est pas téléchargé.
70-
71-## Voir aussi
72-
73-- Toutes les options : [référence de la ligne de commande](../reference/ligne-de-commande.md).
added docs/fr/reference/api-http.md +295 -0
new file mode 100644
@@ -0,0 +1,295 @@
1+# Référence : API HTTP
2+
3+> Les endpoints de `rzb serve`, les champs que chacun accepte, refuse ou ignore, et ce qu'il répond. Les corps d'erreur et les statuts sont dans la [référence des erreurs](erreurs.md) ; les options du serveur dans la [référence de la ligne de commande](ligne-de-commande.md) et la [référence de la configuration](configuration.md).
4+
5+Les exemples utilisent `mlx-community/Qwen3-4B-4bit` comme modèle de chat et `BAAI/bge-small-en-v1.5` comme modèle d'embedding, tous deux téléchargés au préalable avec `rzb models pull`. La suite de compatibilité exécute chaque exemple `curl` de cette page contre un vrai serveur (`scripts/compat.sh`).
6+
7+## Règles générales
8+
9+| Règle | Valeur |
10+| --- | --- |
11+| URL de base | `http://<hôte>:<port>/v1`, par défaut `http://127.0.0.1:8080/v1` |
12+| Corps de requête | JSON (`Content-Type: application/json`), 16 Mio au plus (au-delà : 413) |
13+| Corps de réponse | JSON compact, clés triées ; les flux sont des Server-Sent Events |
14+| Authentification | `Authorization: Bearer <clé>` sur toutes les routes sauf `/health` quand le serveur a une clé d'API ([`--api-key-env`](ligne-de-commande.md#rzb-serve)) ; aucune sinon |
15+| CORS | Désactivé, sauf avec `--cors-origin` / `server.cors_origin` |
16+| Champs inconnus | Ignorés, comme le fait OpenAI, sauf ceux listés comme refusés ci-dessous |
17+| Connexions | Les endpoints de génération répondent avec `Connection: close` (le serveur surveille la connexion pour arrêter une génération dont le client est parti) |
18+| Concurrence | Une génération à la fois par modèle ; les autres requêtes pour ce modèle attendent dans une file ([`limits`](configuration.md#limits)) |
19+
20+## Endpoints
21+
22+| Méthode et chemin | Rôle |
23+| --- | --- |
24+| `GET /health` | Vérification que le processus vit, sans authentification |
25+| `GET /v1/models` | Modèles que le serveur peut servir |
26+| `GET /v1/models/{id}` | L'un d'eux (`{id}` peut contenir `/`) |
27+| `POST /v1/chat/completions` | Réponse de chat, entière ou en flux, avec sortie structurée, outils et raisonnement |
28+| `POST /v1/completions` | Complétion de texte historique : le prompt est continué tel quel |
29+| `POST /v1/embeddings` | Vecteurs d'embedding |
30+
31+Tout autre chemin répond 404 avec le code `unknown_url`.
32+
33+## GET /health
34+
35+```bash
36+curl -s http://127.0.0.1:8080/health
37+```
38+
39+Réponse : `{"status":"ok"}`, statut 200, tant que le processus tourne.
40+
41+## GET /v1/models
42+
43+```bash
44+curl -s http://127.0.0.1:8080/v1/models
45+```
46+
47+Réponse : `{"object": "list", "data": [<modèle>, …]}`. La liste contient, dans cet ordre : les modèles déclarés dans la configuration (sous leur `id`), puis les modèles chargeables du cache Hugging Face, puis les modèles chargés par leur identifiant Hugging Face qui ne sont ni l'un ni l'autre.
48+
49+| Champ de `<modèle>` | Type | Valeur |
50+| --- | --- | --- |
51+| `id` | chaîne | Le nom à mettre dans `"model"` |
52+| `object` | chaîne | `"model"` |
53+| `created` | entier | L'heure de démarrage du serveur (secondes Unix) |
54+| `owned_by` | chaîne | `"razorbill"` |
55+| `loaded` | booléen | Extension razorbill : en mémoire maintenant |
56+| `kind` | chaîne | Extension razorbill : `chat` ou `embedding`. Un modèle du cache non déclaré est indiqué `chat` (le cache ne mémorise pas le type) |
57+
58+`GET /v1/models/{id}` répond un `<modèle>`, ou 404 `model_not_found`.
59+
60+## Noms de modèles
61+
62+Le `"model"` d'une requête est cherché dans cet ordre :
63+
64+1. l'`id` d'un modèle déclaré dans la configuration ; son `kind` doit correspondre à l'endpoint (chat pour les complétions, embedding pour les embeddings), sinon 400 ;
65+2. un identifiant de dépôt Hugging Face, `org/nom` ou `org/nom@révision`, d'un modèle au format MLX. Il est téléchargé à sa première utilisation s'il n'est pas dans le cache, et considéré comme du type de l'endpoint. Un dépôt que le cache montre sans poids `.safetensors` (GGUF par exemple) est refusé avec un 400 `model_not_supported`.
66+
67+Tout le reste donne un 404 `model_not_found`.
68+
69+## POST /v1/chat/completions
70+
71+```bash
72+curl -s http://127.0.0.1:8080/v1/chat/completions \
73+ -H "Content-Type: application/json" \
74+ -d '{
75+ "model": "mlx-community/Qwen3-4B-4bit",
76+ "messages": [
77+ {"role": "system", "content": "Answer in one sentence."},
78+ {"role": "user", "content": "What is MLX?"}
79+ ],
80+ "temperature": 0.2,
81+ "max_tokens": 200
82+ }'
83+```
84+
85+### Champs de la requête
86+
87+| Champ | Type | Défaut | Description |
88+| --- | --- | --- | --- |
89+| `model` | chaîne | obligatoire | Voir [noms de modèles](#noms-de-modèles) |
90+| `messages` | tableau | obligatoire, non vide | Voir [messages](#messages) |
91+| `temperature` | nombre, 0–2 | configuration, sinon `0.6` | Température d'échantillonnage |
92+| `top_p` | nombre, >0–1 | configuration, sinon `1.0` | Échantillonnage par noyau |
93+| `max_tokens` | entier ≥ 1 | configuration, sinon `1024` | Nombre maximal de tokens générés, raisonnement compris |
94+| `max_completion_tokens` | entier ≥ 1 | — | Comme `max_tokens` ; l'emporte quand les deux sont envoyés |
95+| `stop` | chaîne ou tableau de ≤ 4 chaînes | aucun | La réponse s'arrête avant la première occurrence ; `finish_reason` vaut alors `stop` |
96+| `seed` | entier | aléatoire | Graine de l'échantillonneur : même graine et mêmes réglages, même réponse |
97+| `presence_penalty` | nombre, −2–2 | aucune | Pénalise les tokens déjà présents |
98+| `frequency_penalty` | nombre, −2–2 | aucune | Pénalise les tokens selon leur fréquence |
99+| `stream` | booléen | `false` | Envoyer la réponse en Server-Sent Events ([streaming](#streaming)) |
100+| `stream_options.include_usage` | booléen | `false` | Ajouter un dernier morceau avec `usage` |
101+| `response_format` | objet | `{"type": "text"}` | `text`, `json_object` ou `json_schema` ; voir [sortie structurée](#sortie-structurée) |
102+| `tools` | tableau | aucun | Fonctions que le modèle peut appeler ; voir [outils](#outils) |
103+| `tool_choice` | chaîne ou objet | `auto` avec outils, `none` sans | `none`, `auto`, `required`, ou `{"type": "function", "function": {"name": "…"}}` |
104+| `parallel_tool_calls` | booléen | `true` ; `false` pour un appel forcé | `false` : un appel au plus |
105+| `reasoning_effort` | chaîne | configuration | `none` et `minimal` coupent la réflexion ; `low`, `medium`, `high` l'activent (les trois de la même façon) |
106+| `chat_template_kwargs.enable_thinking` | booléen | — | L'interrupteur de vLLM ; l'emporte sur `reasoning_effort` |
107+| `thinking_budget` | entier ≥ 0 | configuration | Extension razorbill : nombre maximal de tokens de raisonnement avant que le modèle doive répondre |
108+| `include_reasoning` | booléen | configuration, sinon `true` | L'interrupteur d'OpenRouter : `false` retire `reasoning_content` (le modèle réfléchit quand même) |
109+
110+Les valeurs `locked` de la configuration l'emportent sur la requête : `temperature`, `top_p`, `thinking` et `show_reasoning` sont imposés, `max_tokens` et `thinking_budget` sont des plafonds ([référence de la configuration](configuration.md#defaults-et-locked)).
111+
112+### Champs refusés
113+
114+Ces champs répondent 400 en nommant le champ, au lieu d'être ignorés en silence :
115+
116+| Champ | Refusé quand |
117+| --- | --- |
118+| `n` | différent de 1 |
119+| `logprobs` | `true` |
120+| un message de rôle autre que `system`, `developer`, `user`, `assistant`, `tool` | toujours |
121+| une partie de contenu d'un autre type que `text` (images, audio…) | toujours |
122+| `response_format` combiné à un appel d'outil forcé | `tool_choice` vaut `required` ou nomme une fonction, ou un outil est `strict` |
123+
124+### Messages
125+
126+| Rôle | Champs | Remarques |
127+| --- | --- | --- |
128+| `system`, `developer` | `content` | `developer` est traité comme `system` |
129+| `user` | `content` | |
130+| `assistant` | `content` (peut être null), `tool_calls` | Les réponses précédentes, avec les appels faits par le modèle |
131+| `tool` | `content`, `tool_call_id`, `name` | Le résultat d'un appel |
132+
133+`content` est une chaîne ou un tableau de parties `{"type": "text", "text": "…"}`, jointes par un saut de ligne. Dans `tool_calls`, `function.arguments` doit être un objet JSON encodé en chaîne, comme l'envoie OpenAI.
134+
135+La conversation est mise en forme avec le chat template du modèle. Le serveur ne garde aucun état entre les requêtes.
136+
137+### Réponse
138+
139+```json
140+{
141+ "id": "chatcmpl-…",
142+ "object": "chat.completion",
143+ "created": 1764096042,
144+ "model": "mlx-community/Qwen3-4B-4bit",
145+ "choices": [{
146+ "index": 0,
147+ "message": {"role": "assistant", "content": "…", "reasoning_content": "…", "tool_calls": […]},
148+ "logprobs": null,
149+ "finish_reason": "stop"
150+ }],
151+ "usage": {"prompt_tokens": 20, "completion_tokens": 9, "total_tokens": 29,
152+ "completion_tokens_details": {"reasoning_tokens": 120}}
153+}
154+```
155+
156+| Champ | Présent | Valeur |
157+| --- | --- | --- |
158+| `id` | toujours | `chatcmpl-` suivi de 24 chiffres hexadécimaux |
159+| `model` | toujours | Le `"model"` de la requête, tel qu'envoyé |
160+| `message.content` | toujours | La réponse ; `null` quand le modèle n'a fait qu'appeler des outils |
161+| `message.reasoning_content` | quand le modèle a réfléchi et que le raisonnement est montré | Le raisonnement, sans les balises `<think>` |
162+| `message.tool_calls` | quand le modèle a appelé des outils | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` étant une chaîne JSON |
163+| `finish_reason` | toujours | `stop`, `length` (limite de tokens) ou `tool_calls` |
164+| `usage.completion_tokens_details.reasoning_tokens` | quand le modèle a réfléchi | Morceaux de raisonnement reçus (environ un par token), comptés même quand le raisonnement est masqué |
165+
166+Quand une séquence d'arrêt termine la réponse, le moteur est interrompu avant de fournir ses comptes : `usage` compte alors un token par morceau de texte et `prompt_tokens` vaut 0.
167+
168+### Sortie structurée
169+
170+| `response_format` | Effet |
171+| --- | --- |
172+| `{"type": "text"}` | Aucune contrainte |
173+| `{"type": "json_object"}` | La réponse est un objet JSON |
174+| `{"type": "json_schema", "json_schema": {"name": "…", "schema": {…}, "strict": true}}` | La réponse est une valeur JSON valide selon `schema` |
175+
176+- La contrainte est appliquée pendant la génération des tokens (décodage contraint, sur macOS avec MLX) ; un modèle qui raisonne réfléchit d'abord librement, et la contrainte s'applique après son raisonnement.
177+- Le serveur ajoute une consigne au message système (un message système est créé s'il n'y en a pas) : `Answer with a single JSON object.` pour `json_object` ; `Answer with a single JSON object that follows this JSON Schema:` suivi du schéma pour `json_schema`.
178+- Les propriétés d'un objet sont générées dans l'ordre où le schéma les liste.
179+- Avec `"strict": true`, un schéma qui utilise un mot-clé que le décodeur ne sait pas appliquer est refusé avec un 400 qui le nomme et dit où il se trouve : `not`, `if`, `then`, `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. Sans `strict`, ces mots-clés sont ignorés.
180+
181+```bash
182+curl -s http://127.0.0.1:8080/v1/chat/completions \
183+ -H "Content-Type: application/json" \
184+ -d '{
185+ "model": "mlx-community/Qwen3-4B-4bit",
186+ "messages": [{"role": "user", "content": "Describe Lyon."}],
187+ "response_format": {"type": "json_schema", "json_schema": {"name": "city", "strict": true,
188+ "schema": {"type": "object", "additionalProperties": false, "required": ["name", "country"],
189+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}}}},
190+ "reasoning_effort": "none"
191+ }'
192+```
193+
194+### Outils
195+
196+| Champ de `tools[i]` | Type | Règles |
197+| --- | --- | --- |
198+| `type` | chaîne | `"function"` |
199+| `function.name` | chaîne | 1 à 64 lettres, chiffres, `_` ou `-` ; unique |
200+| `function.description` | chaîne | Facultatif |
201+| `function.parameters` | objet | Un objet JSON Schema ; par défaut `{"type": "object", "properties": {}}` |
202+| `function.strict` | booléen | `true` : les arguments sont générés selon le schéma (mêmes limites de mots-clés que la sortie structurée `strict`) |
203+
204+| `tool_choice` | Effet |
205+| --- | --- |
206+| `none` | Les outils ne sont pas proposés au modèle ; il répond en texte |
207+| `auto` | Le modèle décide ; ses appels sont extraits de sa sortie |
208+| `required` | La réponse n'est faite que d'appels d'outils, générés sous une grammaire |
209+| `{"type": "function", "function": {"name": "f"}}` | La réponse est un appel à `f`, généré sous une grammaire |
210+
211+- Les appels forcés (`required`, une fonction nommée, ou un outil `strict`) ne sont possibles que pour les modèles dont la syntaxe d'appel est `<tool_call>{"name": …, "arguments": …}</tool_call>` (Qwen, Hermes et apparentés). Pour les autres familles (Llama 3, Mistral, Gemma…), ils répondent 400 ; `auto` fonctionne pour toutes les familles que mlx-swift-lm sait analyser.
212+- Un appel forcé produit un seul appel, sauf si `parallel_tool_calls` vaut `true`.
213+- Avec `parallel_tool_calls: false`, les appels après le premier sont écartés.
214+
215+```bash
216+curl -s http://127.0.0.1:8080/v1/chat/completions \
217+ -H "Content-Type: application/json" \
218+ -d '{
219+ "model": "mlx-community/Qwen3-4B-4bit",
220+ "messages": [{"role": "user", "content": "What is the weather in Lyon?"}],
221+ "tools": [{"type": "function", "function": {"name": "get_weather",
222+ "description": "Current weather for a city",
223+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
224+ "tool_choice": "required",
225+ "reasoning_effort": "none"
226+ }'
227+```
228+
229+## POST /v1/completions
230+
231+L'endpoint historique de complétion de texte. Le prompt est tokenisé tel quel puis continué : pas de chat template, pas de réflexion, pas d'analyse des appels d'outils.
232+
233+```bash
234+curl -s http://127.0.0.1:8080/v1/completions \
235+ -H "Content-Type: application/json" \
236+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "prompt": "The capital of France is", "max_tokens": 8, "temperature": 0}'
237+```
238+
239+| Champ | Type | Défaut | Description |
240+| --- | --- | --- | --- |
241+| `model` | chaîne | obligatoire | Un modèle de chat ([noms de modèles](#noms-de-modèles)) |
242+| `prompt` | chaîne, ou tableau d'une chaîne | obligatoire | Le texte à continuer |
243+| `max_tokens` | entier ≥ 1 | configuration, sinon `1024` (celui d'OpenAI est 16) | Nombre maximal de tokens générés |
244+| `temperature`, `top_p`, `stop`, `seed`, `presence_penalty`, `frequency_penalty` | | | Comme pour les complétions de chat |
245+| `echo` | booléen | `false` | Placer le prompt avant la complétion dans `text` |
246+| `stream`, `stream_options.include_usage` | | `false` | Comme pour les complétions de chat |
247+
248+Refusés avec un 400 : `suffix` (pas de fill-in-the-middle), `logprobs` supérieur à 0, `n` ou `best_of` différents de 1, plusieurs prompts, tableaux de tokens.
249+
250+Réponse : `{"id": "cmpl-…", "object": "text_completion", "created", "model", "choices": [{"text", "index": 0, "logprobs": null, "finish_reason"}], "usage"}`. Un flux envoie des objets de même forme, chacun avec un morceau de `text` ; avec `echo`, le premier contient le prompt.
251+
252+## POST /v1/embeddings
253+
254+```bash
255+curl -s http://127.0.0.1:8080/v1/embeddings \
256+ -H "Content-Type: application/json" \
257+ -d '{"model": "BAAI/bge-small-en-v1.5", "input": ["The cat sits on the mat.", "A feline rests on a rug."]}'
258+```
259+
260+| Champ | Type | Défaut | Description |
261+| --- | --- | --- | --- |
262+| `model` | chaîne | obligatoire | Un modèle d'embedding ([noms de modèles](#noms-de-modèles)) |
263+| `input` | chaîne ou tableau de 1 à 2048 chaînes | obligatoire | Textes à encoder ; aucun ne peut être vide. Les tableaux de tokens sont refusés |
264+| `encoding_format` | `float` ou `base64` | `float` | `base64` : chaque vecteur en octets float32 little-endian, encodés en Base64 |
265+| `dimensions` | entier ≥ 1 | la taille du modèle | Garder les `dimensions` premières valeurs et renormaliser (modèles Matryoshka) ; plus grand que la taille du modèle : 400 |
266+
267+Réponse : `{"object": "list", "data": [{"object": "embedding", "index": i, "embedding": […]}], "model", "usage": {"prompt_tokens", "total_tokens"}}`. Les vecteurs sont normalisés (norme L2). Un texte plus long que ce qu'accepte le modèle donne un 400 qui nomme `input[i]` et la limite. Les entrées sont encodées par lots de 32. Le pooling suit la configuration sentence-transformers du modèle.
268+
269+## Streaming
270+
271+Avec `"stream": true`, la réponse est en `text/event-stream` :
272+
273+```
274+data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],…}
275+
276+data: {…"choices":[{"index":0,"delta":{"content":"Hel"},…}]…}
277+
278+data: {…"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]…}
279+
280+data: [DONE]
281+
282+```
283+
284+- Morceaux de chat : un premier morceau avec `delta.role`, puis des fragments dans `delta.content`, `delta.reasoning_content` ou `delta.tool_calls` (chaque appel entier, avec son `index`), puis un delta vide avec `finish_reason`.
285+- Avec `stream_options.include_usage`, chaque morceau porte `"usage": null` et un dernier morceau, aux `choices` vides, porte l'`usage`.
286+- Tant que le modèle ne produit rien (chargement, long prompt), une ligne de commentaire `: keep-alive` est envoyée toutes les 5 secondes ; les clients SSE l'ignorent.
287+- Une erreur survenue après le début du flux est envoyée comme dernier événement `data: {"error": {…}}`, sans `[DONE]`.
288+- Quand le client se déconnecte, la génération s'arrête et le modèle est libéré pour la requête suivante.
289+
290+```bash
291+curl -sN http://127.0.0.1:8080/v1/chat/completions \
292+ -H "Content-Type: application/json" \
293+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Count to 5."}],
294+ "stream": true, "stream_options": {"include_usage": true}, "reasoning_effort": "none"}'
295+```
new file mode 100644
@@ -0,0 +1,295 @@
1+# Référence : API HTTP
2+
3+> Les endpoints de `rzb serve`, les champs que chacun accepte, refuse ou ignore, et ce qu'il répond. Les corps d'erreur et les statuts sont dans la [référence des erreurs](erreurs.md) ; les options du serveur dans la [référence de la ligne de commande](ligne-de-commande.md) et la [référence de la configuration](configuration.md).
4+
5+Les exemples utilisent `mlx-community/Qwen3-4B-4bit` comme modèle de chat et `BAAI/bge-small-en-v1.5` comme modèle d'embedding, tous deux téléchargés au préalable avec `rzb models pull`. La suite de compatibilité exécute chaque exemple `curl` de cette page contre un vrai serveur (`scripts/compat.sh`).
6+
7+## Règles générales
8+
9+| Règle | Valeur |
10+| --- | --- |
11+| URL de base | `http://<hôte>:<port>/v1`, par défaut `http://127.0.0.1:8080/v1` |
12+| Corps de requête | JSON (`Content-Type: application/json`), 16 Mio au plus (au-delà : 413) |
13+| Corps de réponse | JSON compact, clés triées ; les flux sont des Server-Sent Events |
14+| Authentification | `Authorization: Bearer <clé>` sur toutes les routes sauf `/health` quand le serveur a une clé d'API ([`--api-key-env`](ligne-de-commande.md#rzb-serve)) ; aucune sinon |
15+| CORS | Désactivé, sauf avec `--cors-origin` / `server.cors_origin` |
16+| Champs inconnus | Ignorés, comme le fait OpenAI, sauf ceux listés comme refusés ci-dessous |
17+| Connexions | Les endpoints de génération répondent avec `Connection: close` (le serveur surveille la connexion pour arrêter une génération dont le client est parti) |
18+| Concurrence | Une génération à la fois par modèle ; les autres requêtes pour ce modèle attendent dans une file ([`limits`](configuration.md#limits)) |
19+
20+## Endpoints
21+
22+| Méthode et chemin | Rôle |
23+| --- | --- |
24+| `GET /health` | Vérification que le processus vit, sans authentification |
25+| `GET /v1/models` | Modèles que le serveur peut servir |
26+| `GET /v1/models/{id}` | L'un d'eux (`{id}` peut contenir `/`) |
27+| `POST /v1/chat/completions` | Réponse de chat, entière ou en flux, avec sortie structurée, outils et raisonnement |
28+| `POST /v1/completions` | Complétion de texte historique : le prompt est continué tel quel |
29+| `POST /v1/embeddings` | Vecteurs d'embedding |
30+
31+Tout autre chemin répond 404 avec le code `unknown_url`.
32+
33+## GET /health
34+
35+```bash
36+curl -s http://127.0.0.1:8080/health
37+```
38+
39+Réponse : `{"status":"ok"}`, statut 200, tant que le processus tourne.
40+
41+## GET /v1/models
42+
43+```bash
44+curl -s http://127.0.0.1:8080/v1/models
45+```
46+
47+Réponse : `{"object": "list", "data": [<modèle>, …]}`. La liste contient, dans cet ordre : les modèles déclarés dans la configuration (sous leur `id`), puis les modèles chargeables du cache Hugging Face, puis les modèles chargés par leur identifiant Hugging Face qui ne sont ni l'un ni l'autre.
48+
49+| Champ de `<modèle>` | Type | Valeur |
50+| --- | --- | --- |
51+| `id` | chaîne | Le nom à mettre dans `"model"` |
52+| `object` | chaîne | `"model"` |
53+| `created` | entier | L'heure de démarrage du serveur (secondes Unix) |
54+| `owned_by` | chaîne | `"razorbill"` |
55+| `loaded` | booléen | Extension razorbill : en mémoire maintenant |
56+| `kind` | chaîne | Extension razorbill : `chat` ou `embedding`. Un modèle du cache non déclaré est indiqué `chat` (le cache ne mémorise pas le type) |
57+
58+`GET /v1/models/{id}` répond un `<modèle>`, ou 404 `model_not_found`.
59+
60+## Noms de modèles
61+
62+Le `"model"` d'une requête est cherché dans cet ordre :
63+
64+1. l'`id` d'un modèle déclaré dans la configuration ; son `kind` doit correspondre à l'endpoint (chat pour les complétions, embedding pour les embeddings), sinon 400 ;
65+2. un identifiant de dépôt Hugging Face, `org/nom` ou `org/nom@révision`, d'un modèle au format MLX. Il est téléchargé à sa première utilisation s'il n'est pas dans le cache, et considéré comme du type de l'endpoint. Un dépôt que le cache montre sans poids `.safetensors` (GGUF par exemple) est refusé avec un 400 `model_not_supported`.
66+
67+Tout le reste donne un 404 `model_not_found`.
68+
69+## POST /v1/chat/completions
70+
71+```bash
72+curl -s http://127.0.0.1:8080/v1/chat/completions \
73+ -H "Content-Type: application/json" \
74+ -d '{
75+ "model": "mlx-community/Qwen3-4B-4bit",
76+ "messages": [
77+ {"role": "system", "content": "Answer in one sentence."},
78+ {"role": "user", "content": "What is MLX?"}
79+ ],
80+ "temperature": 0.2,
81+ "max_tokens": 200
82+ }'
83+```
84+
85+### Champs de la requête
86+
87+| Champ | Type | Défaut | Description |
88+| --- | --- | --- | --- |
89+| `model` | chaîne | obligatoire | Voir [noms de modèles](#noms-de-modèles) |
90+| `messages` | tableau | obligatoire, non vide | Voir [messages](#messages) |
91+| `temperature` | nombre, 0–2 | configuration, sinon `0.6` | Température d'échantillonnage |
92+| `top_p` | nombre, >0–1 | configuration, sinon `1.0` | Échantillonnage par noyau |
93+| `max_tokens` | entier ≥ 1 | configuration, sinon `1024` | Nombre maximal de tokens générés, raisonnement compris |
94+| `max_completion_tokens` | entier ≥ 1 | — | Comme `max_tokens` ; l'emporte quand les deux sont envoyés |
95+| `stop` | chaîne ou tableau de ≤ 4 chaînes | aucun | La réponse s'arrête avant la première occurrence ; `finish_reason` vaut alors `stop` |
96+| `seed` | entier | aléatoire | Graine de l'échantillonneur : même graine et mêmes réglages, même réponse |
97+| `presence_penalty` | nombre, −2–2 | aucune | Pénalise les tokens déjà présents |
98+| `frequency_penalty` | nombre, −2–2 | aucune | Pénalise les tokens selon leur fréquence |
99+| `stream` | booléen | `false` | Envoyer la réponse en Server-Sent Events ([streaming](#streaming)) |
100+| `stream_options.include_usage` | booléen | `false` | Ajouter un dernier morceau avec `usage` |
101+| `response_format` | objet | `{"type": "text"}` | `text`, `json_object` ou `json_schema` ; voir [sortie structurée](#sortie-structurée) |
102+| `tools` | tableau | aucun | Fonctions que le modèle peut appeler ; voir [outils](#outils) |
103+| `tool_choice` | chaîne ou objet | `auto` avec outils, `none` sans | `none`, `auto`, `required`, ou `{"type": "function", "function": {"name": "…"}}` |
104+| `parallel_tool_calls` | booléen | `true` ; `false` pour un appel forcé | `false` : un appel au plus |
105+| `reasoning_effort` | chaîne | configuration | `none` et `minimal` coupent la réflexion ; `low`, `medium`, `high` l'activent (les trois de la même façon) |
106+| `chat_template_kwargs.enable_thinking` | booléen | — | L'interrupteur de vLLM ; l'emporte sur `reasoning_effort` |
107+| `thinking_budget` | entier ≥ 0 | configuration | Extension razorbill : nombre maximal de tokens de raisonnement avant que le modèle doive répondre |
108+| `include_reasoning` | booléen | configuration, sinon `true` | L'interrupteur d'OpenRouter : `false` retire `reasoning_content` (le modèle réfléchit quand même) |
109+
110+Les valeurs `locked` de la configuration l'emportent sur la requête : `temperature`, `top_p`, `thinking` et `show_reasoning` sont imposés, `max_tokens` et `thinking_budget` sont des plafonds ([référence de la configuration](configuration.md#defaults-et-locked)).
111+
112+### Champs refusés
113+
114+Ces champs répondent 400 en nommant le champ, au lieu d'être ignorés en silence :
115+
116+| Champ | Refusé quand |
117+| --- | --- |
118+| `n` | différent de 1 |
119+| `logprobs` | `true` |
120+| un message de rôle autre que `system`, `developer`, `user`, `assistant`, `tool` | toujours |
121+| une partie de contenu d'un autre type que `text` (images, audio…) | toujours |
122+| `response_format` combiné à un appel d'outil forcé | `tool_choice` vaut `required` ou nomme une fonction, ou un outil est `strict` |
123+
124+### Messages
125+
126+| Rôle | Champs | Remarques |
127+| --- | --- | --- |
128+| `system`, `developer` | `content` | `developer` est traité comme `system` |
129+| `user` | `content` | |
130+| `assistant` | `content` (peut être null), `tool_calls` | Les réponses précédentes, avec les appels faits par le modèle |
131+| `tool` | `content`, `tool_call_id`, `name` | Le résultat d'un appel |
132+
133+`content` est une chaîne ou un tableau de parties `{"type": "text", "text": "…"}`, jointes par un saut de ligne. Dans `tool_calls`, `function.arguments` doit être un objet JSON encodé en chaîne, comme l'envoie OpenAI.
134+
135+La conversation est mise en forme avec le chat template du modèle. Le serveur ne garde aucun état entre les requêtes.
136+
137+### Réponse
138+
139+```json
140+{
141+ "id": "chatcmpl-…",
142+ "object": "chat.completion",
143+ "created": 1764096042,
144+ "model": "mlx-community/Qwen3-4B-4bit",
145+ "choices": [{
146+ "index": 0,
147+ "message": {"role": "assistant", "content": "…", "reasoning_content": "…", "tool_calls": […]},
148+ "logprobs": null,
149+ "finish_reason": "stop"
150+ }],
151+ "usage": {"prompt_tokens": 20, "completion_tokens": 9, "total_tokens": 29,
152+ "completion_tokens_details": {"reasoning_tokens": 120}}
153+}
154+```
155+
156+| Champ | Présent | Valeur |
157+| --- | --- | --- |
158+| `id` | toujours | `chatcmpl-` suivi de 24 chiffres hexadécimaux |
159+| `model` | toujours | Le `"model"` de la requête, tel qu'envoyé |
160+| `message.content` | toujours | La réponse ; `null` quand le modèle n'a fait qu'appeler des outils |
161+| `message.reasoning_content` | quand le modèle a réfléchi et que le raisonnement est montré | Le raisonnement, sans les balises `<think>` |
162+| `message.tool_calls` | quand le modèle a appelé des outils | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` étant une chaîne JSON |
163+| `finish_reason` | toujours | `stop`, `length` (limite de tokens) ou `tool_calls` |
164+| `usage.completion_tokens_details.reasoning_tokens` | quand le modèle a réfléchi | Morceaux de raisonnement reçus (environ un par token), comptés même quand le raisonnement est masqué |
165+
166+Quand une séquence d'arrêt termine la réponse, le moteur est interrompu avant de fournir ses comptes : `usage` compte alors un token par morceau de texte et `prompt_tokens` vaut 0.
167+
168+### Sortie structurée
169+
170+| `response_format` | Effet |
171+| --- | --- |
172+| `{"type": "text"}` | Aucune contrainte |
173+| `{"type": "json_object"}` | La réponse est un objet JSON |
174+| `{"type": "json_schema", "json_schema": {"name": "…", "schema": {…}, "strict": true}}` | La réponse est une valeur JSON valide selon `schema` |
175+
176+- La contrainte est appliquée pendant la génération des tokens (décodage contraint, sur macOS avec MLX) ; un modèle qui raisonne réfléchit d'abord librement, et la contrainte s'applique après son raisonnement.
177+- Le serveur ajoute une consigne au message système (un message système est créé s'il n'y en a pas) : `Answer with a single JSON object.` pour `json_object` ; `Answer with a single JSON object that follows this JSON Schema:` suivi du schéma pour `json_schema`.
178+- Les propriétés d'un objet sont générées dans l'ordre où le schéma les liste.
179+- Avec `"strict": true`, un schéma qui utilise un mot-clé que le décodeur ne sait pas appliquer est refusé avec un 400 qui le nomme et dit où il se trouve : `not`, `if`, `then`, `else`, `dependentRequired`, `dependentSchemas`, `multipleOf`, `uniqueItems`, `contains`, `minContains`, `maxContains`. Sans `strict`, ces mots-clés sont ignorés.
180+
181+```bash
182+curl -s http://127.0.0.1:8080/v1/chat/completions \
183+ -H "Content-Type: application/json" \
184+ -d '{
185+ "model": "mlx-community/Qwen3-4B-4bit",
186+ "messages": [{"role": "user", "content": "Describe Lyon."}],
187+ "response_format": {"type": "json_schema", "json_schema": {"name": "city", "strict": true,
188+ "schema": {"type": "object", "additionalProperties": false, "required": ["name", "country"],
189+ "properties": {"name": {"type": "string"}, "country": {"type": "string"}}}}},
190+ "reasoning_effort": "none"
191+ }'
192+```
193+
194+### Outils
195+
196+| Champ de `tools[i]` | Type | Règles |
197+| --- | --- | --- |
198+| `type` | chaîne | `"function"` |
199+| `function.name` | chaîne | 1 à 64 lettres, chiffres, `_` ou `-` ; unique |
200+| `function.description` | chaîne | Facultatif |
201+| `function.parameters` | objet | Un objet JSON Schema ; par défaut `{"type": "object", "properties": {}}` |
202+| `function.strict` | booléen | `true` : les arguments sont générés selon le schéma (mêmes limites de mots-clés que la sortie structurée `strict`) |
203+
204+| `tool_choice` | Effet |
205+| --- | --- |
206+| `none` | Les outils ne sont pas proposés au modèle ; il répond en texte |
207+| `auto` | Le modèle décide ; ses appels sont extraits de sa sortie |
208+| `required` | La réponse n'est faite que d'appels d'outils, générés sous une grammaire |
209+| `{"type": "function", "function": {"name": "f"}}` | La réponse est un appel à `f`, généré sous une grammaire |
210+
211+- Les appels forcés (`required`, une fonction nommée, ou un outil `strict`) ne sont possibles que pour les modèles dont la syntaxe d'appel est `<tool_call>{"name": …, "arguments": …}</tool_call>` (Qwen, Hermes et apparentés). Pour les autres familles (Llama 3, Mistral, Gemma…), ils répondent 400 ; `auto` fonctionne pour toutes les familles que mlx-swift-lm sait analyser.
212+- Un appel forcé produit un seul appel, sauf si `parallel_tool_calls` vaut `true`.
213+- Avec `parallel_tool_calls: false`, les appels après le premier sont écartés.
214+
215+```bash
216+curl -s http://127.0.0.1:8080/v1/chat/completions \
217+ -H "Content-Type: application/json" \
218+ -d '{
219+ "model": "mlx-community/Qwen3-4B-4bit",
220+ "messages": [{"role": "user", "content": "What is the weather in Lyon?"}],
221+ "tools": [{"type": "function", "function": {"name": "get_weather",
222+ "description": "Current weather for a city",
223+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
224+ "tool_choice": "required",
225+ "reasoning_effort": "none"
226+ }'
227+```
228+
229+## POST /v1/completions
230+
231+L'endpoint historique de complétion de texte. Le prompt est tokenisé tel quel puis continué : pas de chat template, pas de réflexion, pas d'analyse des appels d'outils.
232+
233+```bash
234+curl -s http://127.0.0.1:8080/v1/completions \
235+ -H "Content-Type: application/json" \
236+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "prompt": "The capital of France is", "max_tokens": 8, "temperature": 0}'
237+```
238+
239+| Champ | Type | Défaut | Description |
240+| --- | --- | --- | --- |
241+| `model` | chaîne | obligatoire | Un modèle de chat ([noms de modèles](#noms-de-modèles)) |
242+| `prompt` | chaîne, ou tableau d'une chaîne | obligatoire | Le texte à continuer |
243+| `max_tokens` | entier ≥ 1 | configuration, sinon `1024` (celui d'OpenAI est 16) | Nombre maximal de tokens générés |
244+| `temperature`, `top_p`, `stop`, `seed`, `presence_penalty`, `frequency_penalty` | | | Comme pour les complétions de chat |
245+| `echo` | booléen | `false` | Placer le prompt avant la complétion dans `text` |
246+| `stream`, `stream_options.include_usage` | | `false` | Comme pour les complétions de chat |
247+
248+Refusés avec un 400 : `suffix` (pas de fill-in-the-middle), `logprobs` supérieur à 0, `n` ou `best_of` différents de 1, plusieurs prompts, tableaux de tokens.
249+
250+Réponse : `{"id": "cmpl-…", "object": "text_completion", "created", "model", "choices": [{"text", "index": 0, "logprobs": null, "finish_reason"}], "usage"}`. Un flux envoie des objets de même forme, chacun avec un morceau de `text` ; avec `echo`, le premier contient le prompt.
251+
252+## POST /v1/embeddings
253+
254+```bash
255+curl -s http://127.0.0.1:8080/v1/embeddings \
256+ -H "Content-Type: application/json" \
257+ -d '{"model": "BAAI/bge-small-en-v1.5", "input": ["The cat sits on the mat.", "A feline rests on a rug."]}'
258+```
259+
260+| Champ | Type | Défaut | Description |
261+| --- | --- | --- | --- |
262+| `model` | chaîne | obligatoire | Un modèle d'embedding ([noms de modèles](#noms-de-modèles)) |
263+| `input` | chaîne ou tableau de 1 à 2048 chaînes | obligatoire | Textes à encoder ; aucun ne peut être vide. Les tableaux de tokens sont refusés |
264+| `encoding_format` | `float` ou `base64` | `float` | `base64` : chaque vecteur en octets float32 little-endian, encodés en Base64 |
265+| `dimensions` | entier ≥ 1 | la taille du modèle | Garder les `dimensions` premières valeurs et renormaliser (modèles Matryoshka) ; plus grand que la taille du modèle : 400 |
266+
267+Réponse : `{"object": "list", "data": [{"object": "embedding", "index": i, "embedding": […]}], "model", "usage": {"prompt_tokens", "total_tokens"}}`. Les vecteurs sont normalisés (norme L2). Un texte plus long que ce qu'accepte le modèle donne un 400 qui nomme `input[i]` et la limite. Les entrées sont encodées par lots de 32. Le pooling suit la configuration sentence-transformers du modèle.
268+
269+## Streaming
270+
271+Avec `"stream": true`, la réponse est en `text/event-stream` :
272+
273+```
274+data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],…}
275+
276+data: {…"choices":[{"index":0,"delta":{"content":"Hel"},…}]…}
277+
278+data: {…"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]…}
279+
280+data: [DONE]
281+
282+```
283+
284+- Morceaux de chat : un premier morceau avec `delta.role`, puis des fragments dans `delta.content`, `delta.reasoning_content` ou `delta.tool_calls` (chaque appel entier, avec son `index`), puis un delta vide avec `finish_reason`.
285+- Avec `stream_options.include_usage`, chaque morceau porte `"usage": null` et un dernier morceau, aux `choices` vides, porte l'`usage`.
286+- Tant que le modèle ne produit rien (chargement, long prompt), une ligne de commentaire `: keep-alive` est envoyée toutes les 5 secondes ; les clients SSE l'ignorent.
287+- Une erreur survenue après le début du flux est envoyée comme dernier événement `data: {"error": {…}}`, sans `[DONE]`.
288+- Quand le client se déconnecte, la génération s'arrête et le modèle est libéré pour la requête suivante.
289+
290+```bash
291+curl -sN http://127.0.0.1:8080/v1/chat/completions \
292+ -H "Content-Type: application/json" \
293+ -d '{"model": "mlx-community/Qwen3-4B-4bit", "messages": [{"role": "user", "content": "Count to 5."}],
294+ "stream": true, "stream_options": {"include_usage": true}, "reasoning_effort": "none"}'
295+```
modified docs/fr/reference/configuration.md +88 -103
@@ -1,138 +1,123 @@
1-# Référence : fichier d'agent
1+# Référence : fichier de configuration du serveur
22
3-> Le fichier YAML qui décrit un agent : clés, types, valeurs par défaut, variables, recherche du fichier et erreurs. razorbill 0.1.0.
3+> Chaque clé du fichier YAML passé à `rzb serve --config <fichier>`, son type, sa valeur par défaut et ses contrôles. Pour vérifier un fichier sans démarrer le serveur : `rzb config validate <fichier>`. Un exemple commenté se trouve dans [`examples/server.yaml`](../../../examples/server.yaml).
44
5-## Recherche du fichier
6-
7-Un fichier décrit un agent. `rzb` utilise, dans cet ordre :
8-
9-1. le fichier donné avec `-c` / `--config` ;
10-2. `./razorbill.yaml` dans le dossier courant ;
11-3. `~/.config/razorbill/agent.yaml`.
12-
13-S'il n'en existe aucun : `error: no agent configuration found (searched: …). Create one with rzb init.` (code de sortie 2).
14-
15-## Exemple
5+Toutes les sections sont facultatives ; un fichier vide, ou pas de fichier du tout, est une configuration valide. Les clés inconnues sont des erreurs. Tous les problèmes d'un fichier sont signalés en une fois, avec le chemin de la clé et le numéro de ligne ; le code de sortie est alors 2.
166
177 ```yaml
18-name: swift-helper
19-description: Helps with Swift questions
20-model:
21- id: mlx-community/Qwen3-1.7B-4bit
22- revision: main
23-generation:
8+server:
9+ host: 127.0.0.1
10+ port: 8080
11+ api_key_env: RZB_API_KEY
12+defaults:
2413 temperature: 0.6
25- top_p: 1.0
26- max_tokens: 1024
27- thinking: false
28- thinking_budget: 512
29-system: |
30- You are a concise Swift expert. Today is {{date}}.
31-tools:
32- bash:
33- confirm: true
34-ui:
35- show_stats: true
36- show_thinking: true
14+ max_tokens: 2048
15+locked:
16+ max_tokens: 8192
17+models:
18+ - id: qwen3
19+ source: mlx-community/Qwen3-4B-4bit
20+ defaults: { thinking: true, thinking_budget: 512 }
21+ - id: embed
22+ source: BAAI/bge-small-en-v1.5
23+ kind: embedding
24+ preload: true
25+limits:
26+ max_loaded_models: 2
27+ keep_alive: 10m
28+ max_queue: 16
3729 ```
3830
39-Le fichier [examples/agent.yaml](../../../examples/agent.yaml) du dépôt est le même, avec un commentaire sur chaque clé.
40-
4131 ## Clés de premier niveau
4232
43-| Clé | Type | Obligatoire | Défaut | Description |
44-| --- | --- | --- | --- | --- |
45-| `name` | texte non vide | oui | — | Nom de l'agent, affiché dans `chat` et `tui`. |
46-| `description` | texte | non | aucune | Description libre. |
47-| [`model`](#model) | texte ou dictionnaire | oui | — | Le modèle que l'agent fait tourner. |
48-| [`generation`](#generation) | dictionnaire | non | voir ci-dessous | Réglages d'échantillonnage et de réflexion. |
49-| [`system`](#system) | texte | non | vide | Prompt système, avec des [variables](#variables). |
50-| [`tools`](#tools) | dictionnaire ou liste | non | aucun outil | Outils intégrés que le modèle peut appeler. |
51-| [`ui`](#ui) | dictionnaire | non | voir ci-dessous | Réglages d'affichage. |
52-
53-Toute autre clé est une erreur.
33+| Clé | Type | Description |
34+| --- | --- | --- |
35+| `server` | table | Réglages réseau ([server](#server)) |
36+| `defaults` | table | Réglages de génération de départ de tous les modèles ([defaults et locked](#defaults-et-locked)) |
37+| `locked` | table | Réglages de génération que les clients ne peuvent ni changer ni dépasser |
38+| `models` | liste | Modèles déclarés par nom ([models](#models)) |
39+| `limits` | table | Limites de mémoire et de file d'attente ([limits](#limits)) |
5440
55-## model
41+## server
5642
57-Soit un identifiant Hugging Face sous forme de texte, soit un dictionnaire avec exactement une des clés `id` et `path`.
43+Les options de la ligne de commande l'emportent sur ces clés ([`rzb serve`](ligne-de-commande.md#rzb-serve)).
5844
5945 | Clé | Type | Défaut | Description |
6046 | --- | --- | --- | --- |
61-| `id` | texte | — | Dépôt Hugging Face d'un modèle MLX, par exemple `mlx-community/Qwen3-1.7B-4bit`. |
62-| `revision` | texte | `main` | Branche, tag ou commit. Seulement avec `id`. |
63-| `path` | texte | — | Dossier local contenant le `config.json` du modèle, son tokenizer et ses `*.safetensors`. `~` est développé ; un chemin relatif part du dossier du fichier d'agent. |
47+| `host` | chaîne non vide | `127.0.0.1` | Adresse d'écoute ; `0.0.0.0` pour toutes les interfaces |
48+| `port` | entier, 1–65535 | `8080` | Port TCP |
49+| `api_key_env` | chaîne non vide | `RZB_API_KEY` | Nom de la variable d'environnement qui contient la clé d'API. La clé elle-même n'est jamais dans le fichier. Quand la variable est définie et non vide, toutes les routes sauf `/health` exigent `Authorization: Bearer <clé>` |
50+| `cors_origin` | chaîne non vide | aucune (CORS désactivé) | Origine autorisée à appeler l'API depuis un navigateur ; `*` pour toutes |
6451
65-```yaml
66-model: mlx-community/Qwen3-1.7B-4bit # forme courte, révision main
67-```
68-
69-## generation
52+Avertissements au démarrage : écoute sur une adresse autre que la boucle locale sans clé d'API ; `cors_origin: "*"` sans clé d'API.
7053
71-| Clé | Type | Défaut | Contrainte | Description |
72-| --- | --- | --- | --- | --- |
73-| `temperature` | nombre | `0.6` | ≥ 0 | Température d'échantillonnage ; `0` est déterministe. |
74-| `top_p` | nombre | `1.0` | dans ]0, 1] | Seuil de l'échantillonnage nucleus ; `1` le désactive. |
75-| `max_tokens` | entier | `1024` | > 0 | Nombre maximal de tokens générés par réponse, raisonnement compris. |
76-| `thinking` | booléen | `false` | — | Laisse les modèles qui raisonnent réfléchir avant de répondre (`enable_thinking` dans leur gabarit de prompt). |
77-| `thinking_budget` | entier | aucun (pas de limite) | ≥ 0 et < `max_tokens` | Nombre maximal de tokens de raisonnement ; le modèle est ensuite amené à répondre. Ne s'applique que si `thinking` est vrai. Échoue au démarrage pour un modèle sans protocole de réflexion connu. |
54+## defaults et locked
7855
79-## system
56+Les mêmes clés, dans les blocs `defaults` / `locked` de premier niveau et dans ceux de chaque modèle.
8057
81-Texte envoyé comme message système de chaque conversation. Utilisez un bloc (`|`) pour plusieurs lignes. Les [variables](#variables) sont remplacées au chargement du fichier.
82-
83-## Variables
84-
85-| Variable | Valeur |
86-| --- | --- |
87-| `{{date}}` | La date du jour, `AAAA-MM-JJ`. |
88-| `{{cwd}}` | Le dossier depuis lequel `rzb` a été lancé. |
89-| `{{env.NOM}}` | La valeur de la variable d'environnement `NOM`. |
90-
91-Les espaces dans les accolades sont acceptés (`{{ date }}`). Une variable inconnue ou une variable d'environnement non définie est une erreur sur la clé `system`.
58+| Clé | Type | Défaut intégré | Dans `locked` |
59+| --- | --- | --- | --- |
60+| `temperature` | nombre, 0–2 | `0.6` | imposé |
61+| `top_p` | nombre, >0–1 | `1.0` | imposé |
62+| `max_tokens` | entier ≥ 1 | `1024` | plafond (une demande plus petite est gardée) |
63+| `thinking` | booléen | `false` | imposé |
64+| `thinking_budget` | entier ≥ 0, inférieur au `max_tokens` du même bloc | aucun (pas de limite) | plafond |
65+| `show_reasoning` | booléen | `true` | imposé |
9266
93-## tools
67+- `thinking` : si un modèle qui raisonne (Qwen3…) réfléchit avant de répondre. Les modèles qui ne raisonnent pas l'ignorent.
68+- `thinking_budget` : nombre maximal de tokens de raisonnement ; le modèle est ensuite obligé de répondre. Refusé à la requête (400) pour les modèles sans protocole de raisonnement connu.
69+- `show_reasoning` : envoyer le raisonnement aux clients (`reasoning_content`). Avec `false`, le modèle réfléchit quand même et `reasoning_tokens` le compte toujours.
9470
95-Les outils intégrés sont activés en étant listés ; aucun n'est activé par défaut. Deux formes :
71+Les réglages d'une requête sont calculés dans cet ordre, chaque étape remplaçant les valeurs qu'elle définit : défauts intégrés → `defaults` de premier niveau → `defaults` du modèle → champs de la requête → `locked` de premier niveau → `locked` du modèle. Les modèles utilisés par leur identifiant Hugging Face (non déclarés) ne reçoivent que les blocs de premier niveau.
9672
97-```yaml
98-tools: # dictionnaire : nom → options (dictionnaire vide ou rien pour les défauts)
99- bash:
100- confirm: true
101-```
73+## models
10274
103-```yaml
104-tools: [bash] # liste de noms, options par défaut
105-```
75+Une liste d'entrées. Les clients peuvent aussi utiliser tout identifiant Hugging Face au format MLX sans le déclarer.
10676
107-| Outil | Options |
108-| --- | --- |
109-| `bash` | [référence de l'outil bash](outil-bash.md) |
110-
111-Un nom d'outil ou une option inconnus sont une erreur sur `tools.<nom>` ou `tools.<nom>.<option>`.
77+| Clé | Type | Défaut | Description |
78+| --- | --- | --- | --- |
79+| `id` | chaîne non vide, unique | obligatoire | Le nom que les clients envoient dans `"model"` |
80+| `source` | chaîne | `source` ou `path` obligatoire | Identifiant Hugging Face, `org/nom` |
81+| `revision` | chaîne | `main` | Branche, tag ou commit de `source` ; interdit avec `path` |
82+| `path` | chaîne | — | Dossier d'un modèle sur disque (`config.json`, tokenizer, `*.safetensors`) ; `~` est développé, un chemin relatif part du dossier du fichier de configuration |
83+| `kind` | `chat` ou `embedding` | `chat` | Les endpoints que le modèle sert |
84+| `preload` | booléen | `false` | Charger au démarrage au lieu de la première requête |
85+| `defaults` | table | aucun | Réglages par défaut de ce modèle ([clés](#defaults-et-locked)) |
86+| `locked` | table | aucun | Réglages verrouillés de ce modèle |
11287
113-## ui
88+## limits
11489
11590 | Clé | Type | Défaut | Description |
11691 | --- | --- | --- | --- |
117-| `show_stats` | booléen | `true` | Afficher le nombre de tokens et la vitesse après chaque réponse (`run`, `chat`, `tui`). |
118-| `show_thinking` | booléen | `true` | Afficher le raisonnement quand le modèle réfléchit : en grisé sur la sortie d'erreur dans `run` et `chat` ; état de départ de Ctrl-T dans `tui`. |
92+| `max_loaded_models` | entier ≥ 1 | `1` | Modèles gardés en mémoire en même temps ; au-delà, le modèle inactif utilisé le moins récemment est déchargé |
93+| `keep_alive` | durée (`30s`, `10m`, `1h`) | `10m` | Un modèle inactif est déchargé après ce délai |
94+| `max_queue` | entier ≥ 1 | `16` | Requêtes en attente pour un modèle ; les suivantes reçoivent un 429 |
95+
96+En plus de ces limites, les poids chargés en même temps ne peuvent pas dépasser 75 % de la mémoire du Mac : un modèle qui ne tient pas, même après déchargement des modèles inactifs, reçoit un 503.
11997
12098 ## Erreurs
12199
122-Tous les problèmes sont signalés en une fois, avec leur ligne quand elle est connue, et `rzb` sort avec le code 2 :
100+Les problèmes sont affichés ensemble, puis `rzb` sort avec le code 2 :
123101
124102 ```
125-error: invalid configuration razorbill.yaml
126- - line 4: generation.temprature: unknown key (expected one of: temperature, top_p, max_tokens, thinking, thinking_budget)
127- - line 7: generation.thinking_budget: must be smaller than max_tokens (1024), which also counts the answer
103+error: invalid configuration server.yaml
104+ - line 3: server.port: must be between 1 and 65535
105+ - line 9: models[0].kind: must be one of: chat, embedding
128106 ```
129107
130-| Problème | Exemple de message |
108+| Message (après `line N: <chemin de clé>:`) | Cause |
131109 | --- | --- |
132-| Clé obligatoire absente | `name: is required` |
133-| Clé inconnue | `unknown key (expected one of: …)` |
134-| Mauvais type | `must be text`, `must be a number`, `must be a whole number`, `must be true or false`, `must be a mapping (key: value lines)` |
135-| Valeur hors limites | `must be 0 or more`, `must be in (0, 1]`, `must be more than 0` |
136-| `model.id` et `model.path` tous les deux, ou aucun | `give either id or path, not both` |
137-| Variable non résolue | `{{env.TOKEN}}: environment variable TOKEN is not set`, `{{x}}: unknown variable (use date, cwd or env.NAME)` |
138-| Outil inconnu | `unknown tool (available: bash)` |
110+| `unknown key (expected one of: …)` | Clé mal orthographiée ou non prise en charge |
111+| `must be between 1 and 65535` | `server.port` hors limites |
112+| `must be between 0 and 2`, `must be above 0 and at most 1`, … | Valeur hors limites |
113+| `must be smaller than max_tokens (N)` | `thinking_budget` pas inférieur au `max_tokens` du même bloc |
114+| `must be a duration such as 30s, 10m or 1h` | `keep_alive` illisible |
115+| `must be a list (lines starting with -)` | `models` n'est pas une liste |
116+| `is required (the name clients send as "model")` | Entrée de modèle sans `id` |
117+| `duplicate id <id>` | Deux entrées avec le même `id` |
118+| `is required (a Hugging Face id, or path:)` | Ni `source` ni `path` |
119+| `give either source or path, not both` | Les deux sont donnés |
120+| `only applies to source` | `revision` avec `path` |
121+| `must be one of: chat, embedding` | `kind` inconnu |
122+| `not valid YAML: …` | Erreur de syntaxe |
123+| `cannot read the file` | Fichier absent ou illisible |
@@ -1,138 +1,123 @@
1-# Référence : fichier d'agent1+# Référence : fichier de configuration du serveur
2 2
3-> Le fichier YAML qui décrit un agent : clés, types, valeurs par défaut, variables, recherche du fichier et erreurs. razorbill 0.1.0.3+> Chaque clé du fichier YAML passé à `rzb serve --config <fichier>`, son type, sa valeur par défaut et ses contrôles. Pour vérifier un fichier sans démarrer le serveur : `rzb config validate <fichier>`. Un exemple commenté se trouve dans [`examples/server.yaml`](../../../examples/server.yaml).
4 4
5-## Recherche du fichier5+Toutes les sections sont facultatives ; un fichier vide, ou pas de fichier du tout, est une configuration valide. Les clés inconnues sont des erreurs. Tous les problèmes d'un fichier sont signalés en une fois, avec le chemin de la clé et le numéro de ligne ; le code de sortie est alors 2.
6-
7-Un fichier décrit un agent. `rzb` utilise, dans cet ordre :
8-
9-1. le fichier donné avec `-c` / `--config` ;
10-2. `./razorbill.yaml` dans le dossier courant ;
11-3. `~/.config/razorbill/agent.yaml`.
12-
13-S'il n'en existe aucun : `error: no agent configuration found (searched: …). Create one with rzb init.` (code de sortie 2).
14-
15-## Exemple
16 6
17 ```yaml7 ```yaml
18-name: swift-helper8+server:
19-description: Helps with Swift questions9+ host: 127.0.0.1
20-model:10+ port: 8080
21- id: mlx-community/Qwen3-1.7B-4bit11+ api_key_env: RZB_API_KEY
22- revision: main12+defaults:
23-generation:
24 temperature: 0.613 temperature: 0.6
25- top_p: 1.014+ max_tokens: 2048
26- max_tokens: 102415+locked:
27- thinking: false16+ max_tokens: 8192
28- thinking_budget: 51217+models:
29-system: |18+ - id: qwen3
30- You are a concise Swift expert. Today is {{date}}.19+ source: mlx-community/Qwen3-4B-4bit
31-tools:20+ defaults: { thinking: true, thinking_budget: 512 }
32- bash:21+ - id: embed
33- confirm: true22+ source: BAAI/bge-small-en-v1.5
34-ui:23+ kind: embedding
35- show_stats: true24+ preload: true
36- show_thinking: true25+limits:
26+ max_loaded_models: 2
27+ keep_alive: 10m
28+ max_queue: 16
37 ```29 ```
38 30
39-Le fichier [examples/agent.yaml](../../../examples/agent.yaml) du dépôt est le même, avec un commentaire sur chaque clé.
40-
41 ## Clés de premier niveau31 ## Clés de premier niveau
42 32
43-| Clé | Type | Obligatoire | Défaut | Description |33+| Clé | Type | Description |
44-| --- | --- | --- | --- | --- |34+| --- | --- | --- |
45-| `name` | texte non vide | oui | — | Nom de l'agent, affiché dans `chat` et `tui`. |35+| `server` | table | Réglages réseau ([server](#server)) |
46-| `description` | texte | non | aucune | Description libre. |36+| `defaults` | table | Réglages de génération de départ de tous les modèles ([defaults et locked](#defaults-et-locked)) |
47-| [`model`](#model) | texte ou dictionnaire | oui | — | Le modèle que l'agent fait tourner. |37+| `locked` | table | Réglages de génération que les clients ne peuvent ni changer ni dépasser |
48-| [`generation`](#generation) | dictionnaire | non | voir ci-dessous | Réglages d'échantillonnage et de réflexion. |38+| `models` | liste | Modèles déclarés par nom ([models](#models)) |
49-| [`system`](#system) | texte | non | vide | Prompt système, avec des [variables](#variables). |39+| `limits` | table | Limites de mémoire et de file d'attente ([limits](#limits)) |
50-| [`tools`](#tools) | dictionnaire ou liste | non | aucun outil | Outils intégrés que le modèle peut appeler. |
51-| [`ui`](#ui) | dictionnaire | non | voir ci-dessous | Réglages d'affichage. |
52-
53-Toute autre clé est une erreur.
54 40
55-## model41+## server
56 42
57-Soit un identifiant Hugging Face sous forme de texte, soit un dictionnaire avec exactement une des clés `id` et `path`.43+Les options de la ligne de commande l'emportent sur ces clés ([`rzb serve`](ligne-de-commande.md#rzb-serve)).
58 44
59 | Clé | Type | Défaut | Description |45 | Clé | Type | Défaut | Description |
60 | --- | --- | --- | --- |46 | --- | --- | --- | --- |
61-| `id` | texte | — | Dépôt Hugging Face d'un modèle MLX, par exemple `mlx-community/Qwen3-1.7B-4bit`. |47+| `host` | chaîne non vide | `127.0.0.1` | Adresse d'écoute ; `0.0.0.0` pour toutes les interfaces |
62-| `revision` | texte | `main` | Branche, tag ou commit. Seulement avec `id`. |48+| `port` | entier, 1–65535 | `8080` | Port TCP |
63-| `path` | texte | — | Dossier local contenant le `config.json` du modèle, son tokenizer et ses `*.safetensors`. `~` est développé ; un chemin relatif part du dossier du fichier d'agent. |49+| `api_key_env` | chaîne non vide | `RZB_API_KEY` | Nom de la variable d'environnement qui contient la clé d'API. La clé elle-même n'est jamais dans le fichier. Quand la variable est définie et non vide, toutes les routes sauf `/health` exigent `Authorization: Bearer <clé>` |
50+| `cors_origin` | chaîne non vide | aucune (CORS désactivé) | Origine autorisée à appeler l'API depuis un navigateur ; `*` pour toutes |
64 51
65-```yaml52+Avertissements au démarrage : écoute sur une adresse autre que la boucle locale sans clé d'API ; `cors_origin: "*"` sans clé d'API.
66-model: mlx-community/Qwen3-1.7B-4bit # forme courte, révision main
67-```
68-
69-## generation
70 53
71-| Clé | Type | Défaut | Contrainte | Description |54+## defaults et locked
72-| --- | --- | --- | --- | --- |
73-| `temperature` | nombre | `0.6` | ≥ 0 | Température d'échantillonnage ; `0` est déterministe. |
74-| `top_p` | nombre | `1.0` | dans ]0, 1] | Seuil de l'échantillonnage nucleus ; `1` le désactive. |
75-| `max_tokens` | entier | `1024` | > 0 | Nombre maximal de tokens générés par réponse, raisonnement compris. |
76-| `thinking` | booléen | `false` | — | Laisse les modèles qui raisonnent réfléchir avant de répondre (`enable_thinking` dans leur gabarit de prompt). |
77-| `thinking_budget` | entier | aucun (pas de limite) | ≥ 0 et < `max_tokens` | Nombre maximal de tokens de raisonnement ; le modèle est ensuite amené à répondre. Ne s'applique que si `thinking` est vrai. Échoue au démarrage pour un modèle sans protocole de réflexion connu. |
78 55
79-## system56+Les mêmes clés, dans les blocs `defaults` / `locked` de premier niveau et dans ceux de chaque modèle.
80 57
81-Texte envoyé comme message système de chaque conversation. Utilisez un bloc (`|`) pour plusieurs lignes. Les [variables](#variables) sont remplacées au chargement du fichier.58+| Clé | Type | Défaut intégré | Dans `locked` |
82-59+| --- | --- | --- | --- |
83-## Variables60+| `temperature` | nombre, 0–2 | `0.6` | imposé |
84-61+| `top_p` | nombre, >0–1 | `1.0` | imposé |
85-| Variable | Valeur |62+| `max_tokens` | entier ≥ 1 | `1024` | plafond (une demande plus petite est gardée) |
86-| --- | --- |63+| `thinking` | booléen | `false` | imposé |
87-| `{{date}}` | La date du jour, `AAAA-MM-JJ`. |64+| `thinking_budget` | entier ≥ 0, inférieur au `max_tokens` du même bloc | aucun (pas de limite) | plafond |
88-| `{{cwd}}` | Le dossier depuis lequel `rzb` a été lancé. |65+| `show_reasoning` | booléen | `true` | imposé |
89-| `{{env.NOM}}` | La valeur de la variable d'environnement `NOM`. |
90-
91-Les espaces dans les accolades sont acceptés (`{{ date }}`). Une variable inconnue ou une variable d'environnement non définie est une erreur sur la clé `system`.
92 66
93-## tools67+- `thinking` : si un modèle qui raisonne (Qwen3…) réfléchit avant de répondre. Les modèles qui ne raisonnent pas l'ignorent.
68+- `thinking_budget` : nombre maximal de tokens de raisonnement ; le modèle est ensuite obligé de répondre. Refusé à la requête (400) pour les modèles sans protocole de raisonnement connu.
69+- `show_reasoning` : envoyer le raisonnement aux clients (`reasoning_content`). Avec `false`, le modèle réfléchit quand même et `reasoning_tokens` le compte toujours.
94 70
95-Les outils intégrés sont activés en étant listés ; aucun n'est activé par défaut. Deux formes :71+Les réglages d'une requête sont calculés dans cet ordre, chaque étape remplaçant les valeurs qu'elle définit : défauts intégrés → `defaults` de premier niveau → `defaults` du modèle → champs de la requête → `locked` de premier niveau → `locked` du modèle. Les modèles utilisés par leur identifiant Hugging Face (non déclarés) ne reçoivent que les blocs de premier niveau.
96 72
97-```yaml73+## models
98-tools: # dictionnaire : nom → options (dictionnaire vide ou rien pour les défauts)
99- bash:
100- confirm: true
101-```
102 74
103-```yaml75+Une liste d'entrées. Les clients peuvent aussi utiliser tout identifiant Hugging Face au format MLX sans le déclarer.
104-tools: [bash] # liste de noms, options par défaut
105-```
106 76
107-| Outil | Options |77+| Clé | Type | Défaut | Description |
108-| --- | --- |78+| --- | --- | --- | --- |
109-| `bash` | [référence de l'outil bash](outil-bash.md) |79+| `id` | chaîne non vide, unique | obligatoire | Le nom que les clients envoient dans `"model"` |
110-80+| `source` | chaîne | `source` ou `path` obligatoire | Identifiant Hugging Face, `org/nom` |
111-Un nom d'outil ou une option inconnus sont une erreur sur `tools.<nom>` ou `tools.<nom>.<option>`.81+| `revision` | chaîne | `main` | Branche, tag ou commit de `source` ; interdit avec `path` |
82+| `path` | chaîne | — | Dossier d'un modèle sur disque (`config.json`, tokenizer, `*.safetensors`) ; `~` est développé, un chemin relatif part du dossier du fichier de configuration |
83+| `kind` | `chat` ou `embedding` | `chat` | Les endpoints que le modèle sert |
84+| `preload` | booléen | `false` | Charger au démarrage au lieu de la première requête |
85+| `defaults` | table | aucun | Réglages par défaut de ce modèle ([clés](#defaults-et-locked)) |
86+| `locked` | table | aucun | Réglages verrouillés de ce modèle |
112 87
113-## ui88+## limits
114 89
115 | Clé | Type | Défaut | Description |90 | Clé | Type | Défaut | Description |
116 | --- | --- | --- | --- |91 | --- | --- | --- | --- |
117-| `show_stats` | booléen | `true` | Afficher le nombre de tokens et la vitesse après chaque réponse (`run`, `chat`, `tui`). |92+| `max_loaded_models` | entier ≥ 1 | `1` | Modèles gardés en mémoire en même temps ; au-delà, le modèle inactif utilisé le moins récemment est déchargé |
118-| `show_thinking` | booléen | `true` | Afficher le raisonnement quand le modèle réfléchit : en grisé sur la sortie d'erreur dans `run` et `chat` ; état de départ de Ctrl-T dans `tui`. |93+| `keep_alive` | durée (`30s`, `10m`, `1h`) | `10m` | Un modèle inactif est déchargé après ce délai |
94+| `max_queue` | entier ≥ 1 | `16` | Requêtes en attente pour un modèle ; les suivantes reçoivent un 429 |
95+
96+En plus de ces limites, les poids chargés en même temps ne peuvent pas dépasser 75 % de la mémoire du Mac : un modèle qui ne tient pas, même après déchargement des modèles inactifs, reçoit un 503.
119 97
120 ## Erreurs98 ## Erreurs
121 99
122-Tous les problèmes sont signalés en une fois, avec leur ligne quand elle est connue, et `rzb` sort avec le code 2 :100+Les problèmes sont affichés ensemble, puis `rzb` sort avec le code 2 :
123 101
124 ```102 ```
125-error: invalid configuration razorbill.yaml103+error: invalid configuration server.yaml
126- - line 4: generation.temprature: unknown key (expected one of: temperature, top_p, max_tokens, thinking, thinking_budget)104+ - line 3: server.port: must be between 1 and 65535
127- - line 7: generation.thinking_budget: must be smaller than max_tokens (1024), which also counts the answer105+ - line 9: models[0].kind: must be one of: chat, embedding
128 ```106 ```
129 107
130-| Problème | Exemple de message |108+| Message (après `line N: <chemin de clé>:`) | Cause |
131 | --- | --- |109 | --- | --- |
132-| Clé obligatoire absente | `name: is required` |110+| `unknown key (expected one of: …)` | Clé mal orthographiée ou non prise en charge |
133-| Clé inconnue | `unknown key (expected one of: …)` |111+| `must be between 1 and 65535` | `server.port` hors limites |
134-| Mauvais type | `must be text`, `must be a number`, `must be a whole number`, `must be true or false`, `must be a mapping (key: value lines)` |112+| `must be between 0 and 2`, `must be above 0 and at most 1`, … | Valeur hors limites |
135-| Valeur hors limites | `must be 0 or more`, `must be in (0, 1]`, `must be more than 0` |113+| `must be smaller than max_tokens (N)` | `thinking_budget` pas inférieur au `max_tokens` du même bloc |
136-| `model.id` et `model.path` tous les deux, ou aucun | `give either id or path, not both` |114+| `must be a duration such as 30s, 10m or 1h` | `keep_alive` illisible |
137-| Variable non résolue | `{{env.TOKEN}}: environment variable TOKEN is not set`, `{{x}}: unknown variable (use date, cwd or env.NAME)` |115+| `must be a list (lines starting with -)` | `models` n'est pas une liste |
138-| Outil inconnu | `unknown tool (available: bash)` |116+| `is required (the name clients send as "model")` | Entrée de modèle sans `id` |
117+| `duplicate id <id>` | Deux entrées avec le même `id` |
118+| `is required (a Hugging Face id, or path:)` | Ni `source` ni `path` |
119+| `give either source or path, not both` | Les deux sont donnés |
120+| `only applies to source` | `revision` avec `path` |
121+| `must be one of: chat, embedding` | `kind` inconnu |
122+| `not valid YAML: …` | Erreur de syntaxe |
123+| `cannot read the file` | Fichier absent ou illisible |
added docs/fr/reference/erreurs.md +59 -0
new file mode 100644
@@ -0,0 +1,59 @@
1+# Référence : erreurs de l'API
2+
3+> Le corps d'erreur de `rzb serve` et chaque statut, type et code qu'il utilise.
4+
5+Chaque erreur est un corps JSON au format d'OpenAI, si bien que les clients OpenAI lèvent leurs exceptions habituelles (`openai.BadRequestError`, `openai.NotFoundError`…) :
6+
7+```json
8+{"error": {"message": "temperature must be between 0 and 2.", "type": "invalid_request_error", "param": "temperature", "code": null}}
9+```
10+
11+| Champ | Valeur |
12+| --- | --- |
13+| `message` | Ce qui ne va pas, en clair |
14+| `type` | Déduit du statut (tableau ci-dessous) |
15+| `param` | Le champ de la requête en cause (`temperature`, `messages[2].content`, `response_format.json_schema.schema`…), ou `null` |
16+| `code` | Un code stable pour certaines erreurs (tableau ci-dessous), ou `null` |
17+
18+Pendant un flux, une erreur survenue après le premier morceau est envoyée comme dernier événement, `data: {"error": {…}}`, et le flux se termine sans `[DONE]`.
19+
20+## Statut et type
21+
22+| Statut | `type` | Quand |
23+| --- | --- | --- |
24+| 400 | `invalid_request_error` | JSON mal formé, mauvais type, valeur hors limites, champ refusé, contrainte non prise en charge, mauvais type de modèle, entrée trop longue |
25+| 401 | `invalid_request_error` | Clé d'API absente ou fausse |
26+| 404 | `invalid_request_error` | Modèle inconnu ou URL inconnue |
27+| 413 | `invalid_request_error` | Corps de plus de 16 Mio |
28+| 429 | `rate_limit_error` | Trop de requêtes en attente pour un modèle |
29+| 499 | — | Le client a fermé la connexion (seulement dans le journal ; le client est parti) |
30+| 500 | `server_error` | Le modèle n'a pas pu être chargé, ou erreur inattendue (aucun détail n'est divulgué) |
31+| 503 | `server_error` | Pas de place pour charger le modèle maintenant |
32+
33+## Codes
34+
35+| Code | Statut | Message (exemple) | Cause |
36+| --- | --- | --- | --- |
37+| `invalid_api_key` | 401 | `Incorrect or missing API key. Send it as 'Authorization: Bearer <key>'.` | `Authorization: Bearer` absent ou différent de la clé du serveur |
38+| `model_not_found` | 404 | `The model 'qwen9' does not exist.` | Ni un `id` déclaré, ni un identifiant Hugging Face `org/nom` |
39+| `unknown_url` | 404 | `Invalid URL (GET /v1/nothing)` | Endpoint inexistant |
40+| `model_not_supported` | 400 | `the model 'org/name' is not in MLX format (no .safetensors weights)` | Le dépôt du cache n'a pas de poids MLX (GGUF…) |
41+| `queue_full` | 429 | `too many requests waiting for 'qwen3' (max_queue: 16); retry later` | Plus de `limits.max_queue` requêtes en attente |
42+| `server_busy` | 503 | `cannot load 'qwen3': every loaded model is busy (max_loaded_models reached); retry later` | Tous les modèles chargés répondent et `max_loaded_models` est atteint |
43+| `insufficient_memory` | 503 | `'org/big' needs about 40.0 GB of memory, only 24.0 GB can be freed for it` | Les poids dépassent ce qui peut être libéré dans les 75 % de la mémoire |
44+| `model_load_failed` | 500 | `cannot load 'qwen3': …` | Échec du téléchargement ou du chargement |
45+
46+## Messages 400 courants
47+
48+| `param` | Message (exemple) |
49+| --- | --- |
50+| un champ | `<field> must be between 0 and 2.`, `n must be 1 (one choice per request).`, `logprobs is not supported yet.` |
51+| `model` | `'embed' is a embedding model; this endpoint needs a chat model` |
52+| `messages[i].role` | `'function' is not a supported role …` |
53+| `messages[i].content` | `Content parts of type 'image_url' are not supported (only text, this model takes no images).` |
54+| `response_format.json_schema.schema` | `… uses 'uniqueItems' (at properties.tags), which strict mode cannot enforce; remove it or set strict to false.` |
55+| `tool_choice` | `tool_choice names nope, which is not in tools.` |
56+| `tool_choice` | `constrained tool calls are not supported for this model's tool-call syntax (llama3); only the <tool_call> JSON syntax (Qwen, Hermes…) is` |
57+| `thinking_budget` | `<model> has no known thinking protocol, so a thinking budget cannot be enforced: remove thinking_budget` |
58+| `input` | `input[1] has 3002 tokens; this model accepts at most 512` |
59+| `dimensions` | `dimensions 1000 is larger than this model's 384.` |
new file mode 100644
@@ -0,0 +1,59 @@
1+# Référence : erreurs de l'API
2+
3+> Le corps d'erreur de `rzb serve` et chaque statut, type et code qu'il utilise.
4+
5+Chaque erreur est un corps JSON au format d'OpenAI, si bien que les clients OpenAI lèvent leurs exceptions habituelles (`openai.BadRequestError`, `openai.NotFoundError`…) :
6+
7+```json
8+{"error": {"message": "temperature must be between 0 and 2.", "type": "invalid_request_error", "param": "temperature", "code": null}}
9+```
10+
11+| Champ | Valeur |
12+| --- | --- |
13+| `message` | Ce qui ne va pas, en clair |
14+| `type` | Déduit du statut (tableau ci-dessous) |
15+| `param` | Le champ de la requête en cause (`temperature`, `messages[2].content`, `response_format.json_schema.schema`…), ou `null` |
16+| `code` | Un code stable pour certaines erreurs (tableau ci-dessous), ou `null` |
17+
18+Pendant un flux, une erreur survenue après le premier morceau est envoyée comme dernier événement, `data: {"error": {…}}`, et le flux se termine sans `[DONE]`.
19+
20+## Statut et type
21+
22+| Statut | `type` | Quand |
23+| --- | --- | --- |
24+| 400 | `invalid_request_error` | JSON mal formé, mauvais type, valeur hors limites, champ refusé, contrainte non prise en charge, mauvais type de modèle, entrée trop longue |
25+| 401 | `invalid_request_error` | Clé d'API absente ou fausse |
26+| 404 | `invalid_request_error` | Modèle inconnu ou URL inconnue |
27+| 413 | `invalid_request_error` | Corps de plus de 16 Mio |
28+| 429 | `rate_limit_error` | Trop de requêtes en attente pour un modèle |
29+| 499 | — | Le client a fermé la connexion (seulement dans le journal ; le client est parti) |
30+| 500 | `server_error` | Le modèle n'a pas pu être chargé, ou erreur inattendue (aucun détail n'est divulgué) |
31+| 503 | `server_error` | Pas de place pour charger le modèle maintenant |
32+
33+## Codes
34+
35+| Code | Statut | Message (exemple) | Cause |
36+| --- | --- | --- | --- |
37+| `invalid_api_key` | 401 | `Incorrect or missing API key. Send it as 'Authorization: Bearer <key>'.` | `Authorization: Bearer` absent ou différent de la clé du serveur |
38+| `model_not_found` | 404 | `The model 'qwen9' does not exist.` | Ni un `id` déclaré, ni un identifiant Hugging Face `org/nom` |
39+| `unknown_url` | 404 | `Invalid URL (GET /v1/nothing)` | Endpoint inexistant |
40+| `model_not_supported` | 400 | `the model 'org/name' is not in MLX format (no .safetensors weights)` | Le dépôt du cache n'a pas de poids MLX (GGUF…) |
41+| `queue_full` | 429 | `too many requests waiting for 'qwen3' (max_queue: 16); retry later` | Plus de `limits.max_queue` requêtes en attente |
42+| `server_busy` | 503 | `cannot load 'qwen3': every loaded model is busy (max_loaded_models reached); retry later` | Tous les modèles chargés répondent et `max_loaded_models` est atteint |
43+| `insufficient_memory` | 503 | `'org/big' needs about 40.0 GB of memory, only 24.0 GB can be freed for it` | Les poids dépassent ce qui peut être libéré dans les 75 % de la mémoire |
44+| `model_load_failed` | 500 | `cannot load 'qwen3': …` | Échec du téléchargement ou du chargement |
45+
46+## Messages 400 courants
47+
48+| `param` | Message (exemple) |
49+| --- | --- |
50+| un champ | `<field> must be between 0 and 2.`, `n must be 1 (one choice per request).`, `logprobs is not supported yet.` |
51+| `model` | `'embed' is a embedding model; this endpoint needs a chat model` |
52+| `messages[i].role` | `'function' is not a supported role …` |
53+| `messages[i].content` | `Content parts of type 'image_url' are not supported (only text, this model takes no images).` |
54+| `response_format.json_schema.schema` | `… uses 'uniqueItems' (at properties.tags), which strict mode cannot enforce; remove it or set strict to false.` |
55+| `tool_choice` | `tool_choice names nope, which is not in tools.` |
56+| `tool_choice` | `constrained tool calls are not supported for this model's tool-call syntax (llama3); only the <tool_call> JSON syntax (Qwen, Hermes…) is` |
57+| `thinking_budget` | `<model> has no known thinking protocol, so a thinking budget cannot be enforced: remove thinking_budget` |
58+| `input` | `input[1] has 3002 tokens; this model accepts at most 512` |
59+| `dimensions` | `dimensions 1000 is larger than this model's 384.` |
modified docs/fr/reference/ligne-de-commande.md +33 -95
@@ -1,6 +1,6 @@
11 # Référence : ligne de commande
22
3-> Chaque commande, option et code de sortie de `rzb`, et les commandes utilisables pendant une session, pour razorbill 0.1.0.
3+> Chaque commande, option et code de sortie de `rzb`, pour razorbill 0.1.0.
44
55 ```
66 rzb <commande> [options]
@@ -10,129 +10,67 @@ rzb help <commande>
1010
1111 | Commande | Rôle |
1212 | --- | --- |
13-| [`rzb init`](#rzb-init) | Écrire un fichier d'agent avec un assistant |
14-| [`rzb run`](#rzb-run) | Une réponse, puis sortie |
15-| [`rzb chat`](#rzb-chat) | Conversation ligne par ligne |
16-| [`rzb tui`](#rzb-tui) | Conversation plein écran |
13+| [`rzb serve`](#rzb-serve) | Démarrer le serveur compatible OpenAI |
14+| [`rzb config validate`](#rzb-config-validate) | Vérifier un fichier de configuration du serveur |
1715 | [`rzb models`](#rzb-models) | Lister, télécharger, supprimer des modèles |
18-| [`rzb config validate`](#rzb-config-validate) | Vérifier un fichier d'agent |
1916 | [`rzb version`](#rzb-version) | Version et moteurs |
2017
21-## Options de l'agent
22-
23-Communes à `run`, `chat` et `tui`. Chacune remplace la valeur correspondante du fichier d'agent, pour cette exécution seulement.
24-
25-| Option | Type | Défaut | Description |
26-| --- | --- | --- | --- |
27-| `-c`, `--config <fichier>` | chemin | `./razorbill.yaml`, puis `~/.config/razorbill/agent.yaml` | Fichier d'agent à charger. |
28-| `-m`, `--model <modèle>` | id ou chemin | le `model` du fichier | Identifiant Hugging Face, ou dossier local quand la valeur commence par `/`, `./`, `../` ou `~/`. Révision `main`. |
29-| `--temperature <n>` | nombre ≥ 0 | celle du fichier | Température d'échantillonnage. |
30-| `--max-tokens <n>` | entier > 0 | celui du fichier | Nombre maximal de tokens par réponse. |
31-| `--think` / `--no-think` | drapeau | celui du fichier | Fixe `generation.thinking`. |
32-| `--thinking-budget <n>` | entier ≥ 0 | celui du fichier | Fixe `generation.thinking_budget`. |
33-| `--offline` | drapeau | désactivé | N'utiliser que les modèles déjà dans le cache ; ne jamais télécharger. |
34-| `--engine <nom>` | `mlx`, `fake` | le premier moteur de la compilation (`mlx` sur le Mac) | Moteur qui fait tourner le modèle. `fake` répond `echo: <prompt>` sans modèle. |
35-
36-## rzb init
37-
38-Écrit un fichier d'agent. Interactif par défaut : nom de l'agent, description, modèle (d'abord les modèles téléchargés, puis les modèles recommandés, puis n'importe quel identifiant Hugging Face ou un dossier local), prompt système, température, nombre maximal de tokens, réflexion (puis budget de réflexion et affichage du raisonnement), outils intégrés, confirmation, téléchargement éventuel.
39-
40-| Option | Défaut | Description |
41-| --- | --- | --- |
42-| `-o`, `--output <fichier>` | `razorbill.yaml` | Fichier à écrire. |
43-| `--force` | désactivé | Écraser un fichier existant sans demander. |
44-| `--name <nom>` | `assistant` | Nom de l'agent (réponse par défaut de l'assistant). |
45-| `--model <modèle>` | `mlx-community/Qwen3-1.7B-4bit` | Modèle (identifiant ou dossier). |
46-| `-y`, `--yes` | désactivé | Ne rien demander : utiliser les options et les valeurs par défaut. Obligatoire sans terminal. |
47-| `--no-download` | désactivé | Ne pas proposer de télécharger le modèle. |
48-
49-Le fichier écrit se charge toujours : il est relu avant d'être enregistré.
50-
51-## rzb run
18+## rzb serve
5219
5320 ```
54-rzb run [options de l'agent] [<prompt> ...]
21+rzb serve [--config <fichier>] [--host <adresse>] [--port <n>] [--api-key-env <nom>] [--cors-origin <origine>]
5522 ```
5623
57-Les mots du prompt sont joints par des espaces. Quand l'entrée standard n'est pas un terminal, son contenu est ajouté après une ligne vide ; le prompt peut alors être omis. La réponse va sur la sortie standard ; la progression des téléchargements, la réflexion, les appels d'outils et les statistiques vont sur la sortie d'erreur.
24+Démarre le serveur et tourne jusqu'à Ctrl-C ou SIGTERM ; il cesse alors d'accepter des requêtes, décharge les modèles et sort avec le code 0.
5825
59-## rzb chat
26+| Option | Type | Défaut | Description |
27+| --- | --- | --- | --- |
28+| `--config <fichier>` | chemin | aucun | Fichier de configuration du serveur ([référence](configuration.md)). Sans lui : aucun modèle déclaré, défauts intégrés |
29+| `--host <adresse>` | chaîne non vide | `server.host`, sinon `127.0.0.1` | Adresse d'écoute ; `0.0.0.0` pour toutes les interfaces |
30+| `--port <n>` | entier, 1–65535 | `server.port`, sinon `8080` | Port TCP |
31+| `--api-key-env <nom>` | chaîne | `server.api_key_env`, sinon `RZB_API_KEY` | Variable d'environnement qui contient la clé d'API. Définie et non vide : toutes les routes sauf `/health` exigent `Authorization: Bearer <clé>` |
32+| `--cors-origin <origine>` | chaîne | `server.cors_origin`, sinon aucune | Autoriser les pages web de cette origine à appeler l'API ; `*` pour toutes |
33+
34+Les options l'emportent sur la section `server:` du fichier. Au démarrage, il affiche sur la sortie d'erreur :
6035
6136 ```
62-rzb chat [options de l'agent]
37+config: server.yaml (2 declared models)
38+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop
6339 ```
6440
65-Lit un message par ligne sur l'entrée standard et affiche chaque réponse au fil de l'eau. Une réponse en échec affiche `error: …` et la conversation continue.
41+La première ligne n'apparaît qu'avec `--config`. Des avertissements (`warning: …`) précèdent la bannière quand le serveur écoute sur une adresse réseau sans clé d'API, ou autorise toutes les origines CORS sans clé. Ensuite, une ligne de journal par requête : méthode, chemin, statut, durée, et le modèle et les nombres de tokens (`model=… tokens=<prompt>+<complétion>`) ; les prompts et les réponses ne sont jamais journalisés.
6642
67-| Saisie | Effet |
68-| --- | --- |
69-| `/reset` | Nouvelle conversation (le modèle reste chargé). |
70-| `/help` | Liste ces commandes. |
71-| `/exit`, `/quit`, Ctrl-D | Quitter. |
72-| ligne vide | Ignorée. |
43+Le moteur est le premier de la compilation : `mlx` sur le Mac, `fake` sous Linux (qui répond `echo: <dernier message>` sans modèle).
7344
74-## rzb tui
45+## rzb config validate
7546
7647 ```
77-rzb tui [options de l'agent]
48+rzb config validate <fichier>
7849 ```
7950
80-Conversation plein écran. Exige un terminal sur l'entrée et la sortie standard ; sinon il s'arrête avec `error: rzb tui needs a terminal; use rzb run or rzb chat instead`.
81-
82-| Touche | Effet |
83-| --- | --- |
84-| Entrée | Envoyer la ligne de saisie (ignorée pendant une réponse). |
85-| Ctrl-C | Arrêter la réponse en cours ; quitter s'il n'y en a pas. |
86-| Ctrl-D | Quitter (quand la ligne de saisie est vide). |
87-| Ctrl-T | Afficher / masquer le raisonnement. |
88-| Ctrl-N | Nouvelle conversation (quand rien ne tourne). |
89-| PgUp / PgDn, ↑ / ↓ | Faire défiler la conversation. |
90-| ← / →, Début / Fin, Ctrl-A / Ctrl-E | Se déplacer dans la ligne de saisie. |
91-| Retour arrière / Suppr, Ctrl-U | Effacer un caractère / toute la ligne. |
92-| `y` / `n` | Répondre à la confirmation d'un outil (`n`, Entrée, Échap et Ctrl-C refusent). |
93-
94-Commandes tapées dans la ligne de saisie : `/reset` ou `/new` (nouvelle conversation), `/exit` ou `/quit`.
95-
96-La barre de titre affiche l'agent, le modèle, le moteur, puis `● answering` ou la dernière vitesse en tokens/s. Le terminal est restauré à la sortie, y compris sur SIGTERM, SIGHUP et SIGQUIT.
51+Charge le fichier sans rien démarrer. Affiche `<fichier> is valid: 2 models (qwen3, embed), any Hugging Face MLX id accepted` sur la sortie standard, ou chaque problème trouvé avec son numéro de ligne ([format](configuration.md#erreurs)) et le code de sortie 2.
9752
9853 ## rzb models
9954
10055 | Commande | Arguments et options | Description |
10156 | --- | --- | --- |
102-| `rzb models list` | `--all` : affiche aussi les dépôts non chargeables (GGUF, téléchargements inachevés), avec une colonne d'état | Les modèles du cache : identifiant, taille, révisions. Affiche le dossier du cache sur la sortie d'erreur. |
103-| `rzb models pull <id>` | `--revision <rév>` (défaut `main`), `--engine <nom>` | Télécharger ou mettre à jour un modèle. |
104-| `rzb models rm <id>` | `-y`, `--yes` : ne pas demander (obligatoire sans terminal) | Supprimer un modèle du cache. |
105-
106-Le cache est `$HF_HUB_CACHE`, sinon `$HF_HOME/hub`, sinon `~/.cache/huggingface/hub`.
107-
108-## rzb config validate
57+| `rzb models list` | `--all` : montrer aussi les dépôts non chargeables (GGUF, téléchargements inachevés), avec une colonne d'état | Modèles du cache, un par ligne : identifiant, taille, révisions. Affiche le dossier du cache sur la sortie d'erreur |
58+| `rzb models pull <id>` | `--revision <rév>` (défaut `main`), `--engine <nom>` | Télécharger ou mettre à jour un modèle (`*.safetensors`, `*.json`, `*.jinja`), avec une barre de progression |
59+| `rzb models rm <id>` | `-y`, `--yes` : ne pas demander (obligatoire sans terminal) | Supprimer un modèle du cache |
10960
110-```
111-rzb config validate [<fichier>]
112-```
113-
114-Charge le fichier (par défaut celui que `rzb` utiliserait) et construit ses outils. Affiche `<fichier> is valid: agent "<nom>", model <modèle>, tools: <noms>` sur la sortie standard, ou chaque problème trouvé.
61+Le cache est `$HF_HUB_CACHE`, sinon `$HF_HOME/hub`, sinon `~/.cache/huggingface/hub`, partagé avec les outils Python de Hugging Face.
11562
11663 ## rzb version
11764
118-Affiche `rzb 0.1.0 (engines: <noms>)`. `rzb --version` affiche `0.1.0`.
119-
120-## Flux de sortie
121-
122-| Flux | Contenu |
123-| --- | --- |
124-| sortie standard | La réponse (`run`, `chat`), les lignes de `models list`, le résultat de `config validate`, la version |
125-| sortie d'erreur | Progression, invites et questions, raisonnement, appels d'outils (`→ bash command="…"`), résultats d'outils (`← bash: …`), statistiques (`[N prompt tokens, N generated, N tokens/s]`), erreurs (`error: …`) |
126-
127-Les couleurs et le grisé ne sont utilisés que si la sortie d'erreur est un terminal et que `NO_COLOR` n'est pas défini.
65+Affiche `rzb 0.1.0 (engines: fake, mlx)` (les moteurs de cette compilation, triés). `rzb --version` affiche `0.1.0`.
12866
12967 ## Codes de sortie
13068
13169 | Code | Signification |
13270 | --- | --- |
133-| `0` | Succès |
134-| `1` | Échec pendant l'exécution (modèle, téléchargement, outil, terminal manquant) |
135-| `2` | Fichier d'agent absent ou invalide |
71+| `0` | Succès, ou serveur arrêté normalement |
72+| `1` | Échec pendant l'exécution (téléchargement, modèle, port déjà utilisé…) |
73+| `2` | Fichier de configuration absent ou invalide |
13674 | `64` | Ligne de commande invalide |
13775 | `130` | Interrompu |
13876
@@ -140,6 +78,6 @@ Les couleurs et le grisé ne sont utilisés que si la sortie d'erreur est un ter
14078
14179 | Variable | Effet |
14280 | --- | --- |
143-| `HF_HUB_CACHE`, `HF_HOME` | Emplacement du cache des modèles. |
144-| `NO_COLOR` | Désactive les couleurs. |
145-| tout `NOM` | Disponible dans le prompt système sous la forme `{{env.NOM}}` ; hérité par les commandes de `bash`. |
81+| `RZB_API_KEY` (ou le nom donné par `--api-key-env` / `server.api_key_env`) | Clé d'API du serveur |
82+| `HF_HUB_CACHE`, `HF_HOME` | Emplacement du cache des modèles |
83+| `NO_COLOR` | Désactive les couleurs sur la sortie d'erreur |
@@ -1,6 +1,6 @@
1 # Référence : ligne de commande1 # Référence : ligne de commande
2 2
3-> Chaque commande, option et code de sortie de `rzb`, et les commandes utilisables pendant une session, pour razorbill 0.1.0.3+> Chaque commande, option et code de sortie de `rzb`, pour razorbill 0.1.0.
4 4
5 ```5 ```
6 rzb <commande> [options]6 rzb <commande> [options]
@@ -10,129 +10,67 @@ rzb help <commande>
10 10
11 | Commande | Rôle |11 | Commande | Rôle |
12 | --- | --- |12 | --- | --- |
13-| [`rzb init`](#rzb-init) | Écrire un fichier d'agent avec un assistant |13+| [`rzb serve`](#rzb-serve) | Démarrer le serveur compatible OpenAI |
14-| [`rzb run`](#rzb-run) | Une réponse, puis sortie |14+| [`rzb config validate`](#rzb-config-validate) | Vérifier un fichier de configuration du serveur |
15-| [`rzb chat`](#rzb-chat) | Conversation ligne par ligne |
16-| [`rzb tui`](#rzb-tui) | Conversation plein écran |
17 | [`rzb models`](#rzb-models) | Lister, télécharger, supprimer des modèles |15 | [`rzb models`](#rzb-models) | Lister, télécharger, supprimer des modèles |
18-| [`rzb config validate`](#rzb-config-validate) | Vérifier un fichier d'agent |
19 | [`rzb version`](#rzb-version) | Version et moteurs |16 | [`rzb version`](#rzb-version) | Version et moteurs |
20 17
21-## Options de l'agent18+## rzb serve
22-
23-Communes à `run`, `chat` et `tui`. Chacune remplace la valeur correspondante du fichier d'agent, pour cette exécution seulement.
24-
25-| Option | Type | Défaut | Description |
26-| --- | --- | --- | --- |
27-| `-c`, `--config <fichier>` | chemin | `./razorbill.yaml`, puis `~/.config/razorbill/agent.yaml` | Fichier d'agent à charger. |
28-| `-m`, `--model <modèle>` | id ou chemin | le `model` du fichier | Identifiant Hugging Face, ou dossier local quand la valeur commence par `/`, `./`, `../` ou `~/`. Révision `main`. |
29-| `--temperature <n>` | nombre ≥ 0 | celle du fichier | Température d'échantillonnage. |
30-| `--max-tokens <n>` | entier > 0 | celui du fichier | Nombre maximal de tokens par réponse. |
31-| `--think` / `--no-think` | drapeau | celui du fichier | Fixe `generation.thinking`. |
32-| `--thinking-budget <n>` | entier ≥ 0 | celui du fichier | Fixe `generation.thinking_budget`. |
33-| `--offline` | drapeau | désactivé | N'utiliser que les modèles déjà dans le cache ; ne jamais télécharger. |
34-| `--engine <nom>` | `mlx`, `fake` | le premier moteur de la compilation (`mlx` sur le Mac) | Moteur qui fait tourner le modèle. `fake` répond `echo: <prompt>` sans modèle. |
35-
36-## rzb init
37-
38-Écrit un fichier d'agent. Interactif par défaut : nom de l'agent, description, modèle (d'abord les modèles téléchargés, puis les modèles recommandés, puis n'importe quel identifiant Hugging Face ou un dossier local), prompt système, température, nombre maximal de tokens, réflexion (puis budget de réflexion et affichage du raisonnement), outils intégrés, confirmation, téléchargement éventuel.
39-
40-| Option | Défaut | Description |
41-| --- | --- | --- |
42-| `-o`, `--output <fichier>` | `razorbill.yaml` | Fichier à écrire. |
43-| `--force` | désactivé | Écraser un fichier existant sans demander. |
44-| `--name <nom>` | `assistant` | Nom de l'agent (réponse par défaut de l'assistant). |
45-| `--model <modèle>` | `mlx-community/Qwen3-1.7B-4bit` | Modèle (identifiant ou dossier). |
46-| `-y`, `--yes` | désactivé | Ne rien demander : utiliser les options et les valeurs par défaut. Obligatoire sans terminal. |
47-| `--no-download` | désactivé | Ne pas proposer de télécharger le modèle. |
48-
49-Le fichier écrit se charge toujours : il est relu avant d'être enregistré.
50-
51-## rzb run
52 19
53 ```20 ```
54-rzb run [options de l'agent] [<prompt> ...]21+rzb serve [--config <fichier>] [--host <adresse>] [--port <n>] [--api-key-env <nom>] [--cors-origin <origine>]
55 ```22 ```
56 23
57-Les mots du prompt sont joints par des espaces. Quand l'entrée standard n'est pas un terminal, son contenu est ajouté après une ligne vide ; le prompt peut alors être omis. La réponse va sur la sortie standard ; la progression des téléchargements, la réflexion, les appels d'outils et les statistiques vont sur la sortie d'erreur.24+Démarre le serveur et tourne jusqu'à Ctrl-C ou SIGTERM ; il cesse alors d'accepter des requêtes, décharge les modèles et sort avec le code 0.
58 25
59-## rzb chat26+| Option | Type | Défaut | Description |
27+| --- | --- | --- | --- |
28+| `--config <fichier>` | chemin | aucun | Fichier de configuration du serveur ([référence](configuration.md)). Sans lui : aucun modèle déclaré, défauts intégrés |
29+| `--host <adresse>` | chaîne non vide | `server.host`, sinon `127.0.0.1` | Adresse d'écoute ; `0.0.0.0` pour toutes les interfaces |
30+| `--port <n>` | entier, 1–65535 | `server.port`, sinon `8080` | Port TCP |
31+| `--api-key-env <nom>` | chaîne | `server.api_key_env`, sinon `RZB_API_KEY` | Variable d'environnement qui contient la clé d'API. Définie et non vide : toutes les routes sauf `/health` exigent `Authorization: Bearer <clé>` |
32+| `--cors-origin <origine>` | chaîne | `server.cors_origin`, sinon aucune | Autoriser les pages web de cette origine à appeler l'API ; `*` pour toutes |
33+
34+Les options l'emportent sur la section `server:` du fichier. Au démarrage, il affiche sur la sortie d'erreur :
60 35
61 ```36 ```
62-rzb chat [options de l'agent]37+config: server.yaml (2 declared models)
38+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop
63 ```39 ```
64 40
65-Lit un message par ligne sur l'entrée standard et affiche chaque réponse au fil de l'eau. Une réponse en échec affiche `error: …` et la conversation continue.41+La première ligne n'apparaît qu'avec `--config`. Des avertissements (`warning: …`) précèdent la bannière quand le serveur écoute sur une adresse réseau sans clé d'API, ou autorise toutes les origines CORS sans clé. Ensuite, une ligne de journal par requête : méthode, chemin, statut, durée, et le modèle et les nombres de tokens (`model=… tokens=<prompt>+<complétion>`) ; les prompts et les réponses ne sont jamais journalisés.
66 42
67-| Saisie | Effet |43+Le moteur est le premier de la compilation : `mlx` sur le Mac, `fake` sous Linux (qui répond `echo: <dernier message>` sans modèle).
68-| --- | --- |
69-| `/reset` | Nouvelle conversation (le modèle reste chargé). |
70-| `/help` | Liste ces commandes. |
71-| `/exit`, `/quit`, Ctrl-D | Quitter. |
72-| ligne vide | Ignorée. |
73 44
74-## rzb tui45+## rzb config validate
75 46
76 ```47 ```
77-rzb tui [options de l'agent]48+rzb config validate <fichier>
78 ```49 ```
79 50
80-Conversation plein écran. Exige un terminal sur l'entrée et la sortie standard ; sinon il s'arrête avec `error: rzb tui needs a terminal; use rzb run or rzb chat instead`.51+Charge le fichier sans rien démarrer. Affiche `<fichier> is valid: 2 models (qwen3, embed), any Hugging Face MLX id accepted` sur la sortie standard, ou chaque problème trouvé avec son numéro de ligne ([format](configuration.md#erreurs)) et le code de sortie 2.
81-
82-| Touche | Effet |
83-| --- | --- |
84-| Entrée | Envoyer la ligne de saisie (ignorée pendant une réponse). |
85-| Ctrl-C | Arrêter la réponse en cours ; quitter s'il n'y en a pas. |
86-| Ctrl-D | Quitter (quand la ligne de saisie est vide). |
87-| Ctrl-T | Afficher / masquer le raisonnement. |
88-| Ctrl-N | Nouvelle conversation (quand rien ne tourne). |
89-| PgUp / PgDn, ↑ / ↓ | Faire défiler la conversation. |
90-| ← / →, Début / Fin, Ctrl-A / Ctrl-E | Se déplacer dans la ligne de saisie. |
91-| Retour arrière / Suppr, Ctrl-U | Effacer un caractère / toute la ligne. |
92-| `y` / `n` | Répondre à la confirmation d'un outil (`n`, Entrée, Échap et Ctrl-C refusent). |
93-
94-Commandes tapées dans la ligne de saisie : `/reset` ou `/new` (nouvelle conversation), `/exit` ou `/quit`.
95-
96-La barre de titre affiche l'agent, le modèle, le moteur, puis `● answering` ou la dernière vitesse en tokens/s. Le terminal est restauré à la sortie, y compris sur SIGTERM, SIGHUP et SIGQUIT.
97 52
98 ## rzb models53 ## rzb models
99 54
100 | Commande | Arguments et options | Description |55 | Commande | Arguments et options | Description |
101 | --- | --- | --- |56 | --- | --- | --- |
102-| `rzb models list` | `--all` : affiche aussi les dépôts non chargeables (GGUF, téléchargements inachevés), avec une colonne d'état | Les modèles du cache : identifiant, taille, révisions. Affiche le dossier du cache sur la sortie d'erreur. |57+| `rzb models list` | `--all` : montrer aussi les dépôts non chargeables (GGUF, téléchargements inachevés), avec une colonne d'état | Modèles du cache, un par ligne : identifiant, taille, révisions. Affiche le dossier du cache sur la sortie d'erreur |
103-| `rzb models pull <id>` | `--revision <rév>` (défaut `main`), `--engine <nom>` | Télécharger ou mettre à jour un modèle. |58+| `rzb models pull <id>` | `--revision <rév>` (défaut `main`), `--engine <nom>` | Télécharger ou mettre à jour un modèle (`*.safetensors`, `*.json`, `*.jinja`), avec une barre de progression |
104-| `rzb models rm <id>` | `-y`, `--yes` : ne pas demander (obligatoire sans terminal) | Supprimer un modèle du cache. |59+| `rzb models rm <id>` | `-y`, `--yes` : ne pas demander (obligatoire sans terminal) | Supprimer un modèle du cache |
105-
106-Le cache est `$HF_HUB_CACHE`, sinon `$HF_HOME/hub`, sinon `~/.cache/huggingface/hub`.
107-
108-## rzb config validate
109 60
110-```61+Le cache est `$HF_HUB_CACHE`, sinon `$HF_HOME/hub`, sinon `~/.cache/huggingface/hub`, partagé avec les outils Python de Hugging Face.
111-rzb config validate [<fichier>]
112-```
113-
114-Charge le fichier (par défaut celui que `rzb` utiliserait) et construit ses outils. Affiche `<fichier> is valid: agent "<nom>", model <modèle>, tools: <noms>` sur la sortie standard, ou chaque problème trouvé.
115 62
116 ## rzb version63 ## rzb version
117 64
118-Affiche `rzb 0.1.0 (engines: <noms>)`. `rzb --version` affiche `0.1.0`.65+Affiche `rzb 0.1.0 (engines: fake, mlx)` (les moteurs de cette compilation, triés). `rzb --version` affiche `0.1.0`.
119-
120-## Flux de sortie
121-
122-| Flux | Contenu |
123-| --- | --- |
124-| sortie standard | La réponse (`run`, `chat`), les lignes de `models list`, le résultat de `config validate`, la version |
125-| sortie d'erreur | Progression, invites et questions, raisonnement, appels d'outils (`→ bash command="…"`), résultats d'outils (`← bash: …`), statistiques (`[N prompt tokens, N generated, N tokens/s]`), erreurs (`error: …`) |
126-
127-Les couleurs et le grisé ne sont utilisés que si la sortie d'erreur est un terminal et que `NO_COLOR` n'est pas défini.
128 66
129 ## Codes de sortie67 ## Codes de sortie
130 68
131 | Code | Signification |69 | Code | Signification |
132 | --- | --- |70 | --- | --- |
133-| `0` | Succès |71+| `0` | Succès, ou serveur arrêté normalement |
134-| `1` | Échec pendant l'exécution (modèle, téléchargement, outil, terminal manquant) |72+| `1` | Échec pendant l'exécution (téléchargement, modèle, port déjà utilisé…) |
135-| `2` | Fichier d'agent absent ou invalide |73+| `2` | Fichier de configuration absent ou invalide |
136 | `64` | Ligne de commande invalide |74 | `64` | Ligne de commande invalide |
137 | `130` | Interrompu |75 | `130` | Interrompu |
138 76
@@ -140,6 +78,6 @@ Les couleurs et le grisé ne sont utilisés que si la sortie d'erreur est un ter
140 78
141 | Variable | Effet |79 | Variable | Effet |
142 | --- | --- |80 | --- | --- |
143-| `HF_HUB_CACHE`, `HF_HOME` | Emplacement du cache des modèles. |81+| `RZB_API_KEY` (ou le nom donné par `--api-key-env` / `server.api_key_env`) | Clé d'API du serveur |
144-| `NO_COLOR` | Désactive les couleurs. |82+| `HF_HUB_CACHE`, `HF_HOME` | Emplacement du cache des modèles |
145-| tout `NOM` | Disponible dans le prompt système sous la forme `{{env.NOM}}` ; hérité par les commandes de `bash`. |83+| `NO_COLOR` | Désactive les couleurs sur la sortie d'erreur |
deleted docs/fr/reference/outil-bash.md +0 -77
deleted file mode 100644
@@ -1,77 +0,0 @@
1-# Référence : outil bash
2-
3-> L'outil intégré `bash` : ses options, les vérifications faites avant qu'une commande s'exécute, et ce que reçoit le modèle.
4-
5-## Déclaration
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true
11- workdir: .
12- timeout: 30s
13- max_output: 16KB
14- allow: ["ls*", "git status"]
15- deny: ["rm -rf*", "sudo *"]
16-```
17-
18-L'outil n'existe que si `bash` est listé sous `tools`.
19-
20-## Options
21-
22-| Option | Type | Défaut | Description |
23-| --- | --- | --- | --- |
24-| `confirm` | booléen | `true` | Demander l'accord de l'utilisateur avant chaque commande. |
25-| `workdir` | texte | `.` | Dossier dans lequel les commandes s'exécutent. Un chemin relatif part du dossier depuis lequel `rzb` a été lancé. |
26-| `timeout` | durée | `30s` | Délai après lequel la commande et tous les processus qu'elle a lancés sont tués. Un nombre de secondes, ou un nombre suivi de `ms`, `s`, `m` ou `h`. Doit être positif. |
27-| `max_output` | taille | `16KB` | Octets de sortie conservés (sortie standard et sortie d'erreur ensemble) ; le reste est abandonné. Un nombre d'octets, ou un nombre suivi de `B`, `KB` ou `MB` (1 KB = 1024 octets). Doit être positif. |
28-| `allow` | liste de motifs | vide (tout) | Si elle n'est pas vide, une commande doit correspondre à l'un de ces motifs. |
29-| `deny` | liste de motifs | vide | Une commande qui correspond à l'un de ces motifs est refusée. |
30-
31-Les motifs portent sur toute la ligne de commande : `*` remplace n'importe quel texte (espaces compris), `?` un caractère. `"git *"` correspond à `git status` ; `"ls*"` correspond à `ls -la` et aussi à `ls; rm -rf ~`.
32-
33-## Arguments envoyés par le modèle
34-
35-| Argument | Type | Obligatoire | Description |
36-| --- | --- | --- | --- |
37-| `command` | texte | oui | La ligne de commande, exécutée avec `/bin/bash -c`. |
38-
39-## Vérifications, dans l'ordre
40-
41-| Ordre | Vérification | Refus envoyé au modèle |
42-| --- | --- | --- |
43-| 1 | `command` présent et non vide | `refused: the \`command\` argument (text) is missing` |
44-| 2 | correspond à un motif `deny` | `refused: the command matches the deny pattern \`<motif>\`` |
45-| 3 | `allow` non vide et aucun motif ne correspond | `refused: the command matches none of the allow patterns` |
46-| 4 | `confirm: true` et pas de terminal | `refused: no terminal to ask the user for confirmation (set \`confirm: false\` to allow this)` |
47-| 5 | `confirm: true` et l'utilisateur répond non | `refused: the user declined to run it` |
48-
49-La confirmation affiche `bash wants to run: <commande> (in <dossier>)`. Dans `run` et `chat`, la réponse est `y` ou `n` (non par défaut) ; dans `tui`, `y` accepte et `n`, Entrée, Échap ou Ctrl-C refusent.
50-
51-## Résultat envoyé au modèle
52-
53-```
54-exit code: 0
55-stdout:
56-<sortie standard>
57-stderr:
58-<sortie d'erreur>
59-```
60-
61-- `stdout:` et `stderr:` ne sont présents que s'ils ne sont pas vides.
62-- Après un dépassement de délai, la première ligne est `timed out after <secondes>s: the command was killed`.
63-- Quand de la sortie a été abandonnée, la dernière ligne est `[output truncated: <N> more bytes]`.
64-- Le résultat est marqué comme une erreur quand le code de sortie n'est pas 0, après un dépassement de délai, et pour chaque refus.
65-
66-## Environnement des commandes
67-
68-Les commandes héritent de l'environnement de `rzb` (toutes ses variables) et s'exécutent avec les droits de l'utilisateur. L'entrée standard est `/dev/null`.
69-
70-## Erreurs dans le fichier d'agent
71-
72-| Erreur | Cause |
73-| --- | --- |
74-| `tools.bash.<clé>: unknown option (expected one of: confirm, workdir, timeout, max_output, allow, deny)` | Une clé autre que les six options. |
75-| `tools.bash.confirm: must be true or false`, `tools.bash.workdir: must be text`, `tools.bash.allow: must be a list of text` | Mauvais type. |
76-| `tools.bash.timeout: must be a positive duration such as 30s, 2m or 500ms` | Durée invalide. |
77-| `tools.bash.max_output: must be a positive size such as 16KB or 1MB` | Taille invalide. |
deleted file mode 100644
@@ -1,77 +0,0 @@
1-# Référence : outil bash
2-
3-> L'outil intégré `bash` : ses options, les vérifications faites avant qu'une commande s'exécute, et ce que reçoit le modèle.
4-
5-## Déclaration
6-
7-```yaml
8-tools:
9- bash:
10- confirm: true
11- workdir: .
12- timeout: 30s
13- max_output: 16KB
14- allow: ["ls*", "git status"]
15- deny: ["rm -rf*", "sudo *"]
16-```
17-
18-L'outil n'existe que si `bash` est listé sous `tools`.
19-
20-## Options
21-
22-| Option | Type | Défaut | Description |
23-| --- | --- | --- | --- |
24-| `confirm` | booléen | `true` | Demander l'accord de l'utilisateur avant chaque commande. |
25-| `workdir` | texte | `.` | Dossier dans lequel les commandes s'exécutent. Un chemin relatif part du dossier depuis lequel `rzb` a été lancé. |
26-| `timeout` | durée | `30s` | Délai après lequel la commande et tous les processus qu'elle a lancés sont tués. Un nombre de secondes, ou un nombre suivi de `ms`, `s`, `m` ou `h`. Doit être positif. |
27-| `max_output` | taille | `16KB` | Octets de sortie conservés (sortie standard et sortie d'erreur ensemble) ; le reste est abandonné. Un nombre d'octets, ou un nombre suivi de `B`, `KB` ou `MB` (1 KB = 1024 octets). Doit être positif. |
28-| `allow` | liste de motifs | vide (tout) | Si elle n'est pas vide, une commande doit correspondre à l'un de ces motifs. |
29-| `deny` | liste de motifs | vide | Une commande qui correspond à l'un de ces motifs est refusée. |
30-
31-Les motifs portent sur toute la ligne de commande : `*` remplace n'importe quel texte (espaces compris), `?` un caractère. `"git *"` correspond à `git status` ; `"ls*"` correspond à `ls -la` et aussi à `ls; rm -rf ~`.
32-
33-## Arguments envoyés par le modèle
34-
35-| Argument | Type | Obligatoire | Description |
36-| --- | --- | --- | --- |
37-| `command` | texte | oui | La ligne de commande, exécutée avec `/bin/bash -c`. |
38-
39-## Vérifications, dans l'ordre
40-
41-| Ordre | Vérification | Refus envoyé au modèle |
42-| --- | --- | --- |
43-| 1 | `command` présent et non vide | `refused: the \`command\` argument (text) is missing` |
44-| 2 | correspond à un motif `deny` | `refused: the command matches the deny pattern \`<motif>\`` |
45-| 3 | `allow` non vide et aucun motif ne correspond | `refused: the command matches none of the allow patterns` |
46-| 4 | `confirm: true` et pas de terminal | `refused: no terminal to ask the user for confirmation (set \`confirm: false\` to allow this)` |
47-| 5 | `confirm: true` et l'utilisateur répond non | `refused: the user declined to run it` |
48-
49-La confirmation affiche `bash wants to run: <commande> (in <dossier>)`. Dans `run` et `chat`, la réponse est `y` ou `n` (non par défaut) ; dans `tui`, `y` accepte et `n`, Entrée, Échap ou Ctrl-C refusent.
50-
51-## Résultat envoyé au modèle
52-
53-```
54-exit code: 0
55-stdout:
56-<sortie standard>
57-stderr:
58-<sortie d'erreur>
59-```
60-
61-- `stdout:` et `stderr:` ne sont présents que s'ils ne sont pas vides.
62-- Après un dépassement de délai, la première ligne est `timed out after <secondes>s: the command was killed`.
63-- Quand de la sortie a été abandonnée, la dernière ligne est `[output truncated: <N> more bytes]`.
64-- Le résultat est marqué comme une erreur quand le code de sortie n'est pas 0, après un dépassement de délai, et pour chaque refus.
65-
66-## Environnement des commandes
67-
68-Les commandes héritent de l'environnement de `rzb` (toutes ses variables) et s'exécutent avec les droits de l'utilisateur. L'entrée standard est `/dev/null`.
69-
70-## Erreurs dans le fichier d'agent
71-
72-| Erreur | Cause |
73-| --- | --- |
74-| `tools.bash.<clé>: unknown option (expected one of: confirm, workdir, timeout, max_output, allow, deny)` | Une clé autre que les six options. |
75-| `tools.bash.confirm: must be true or false`, `tools.bash.workdir: must be text`, `tools.bash.allow: must be a list of text` | Mauvais type. |
76-| `tools.bash.timeout: must be a positive duration such as 30s, 2m or 500ms` | Durée invalide. |
77-| `tools.bash.max_output: must be a positive size such as 16KB or 1MB` | Taille invalide. |
modified docs/fr/tutorials/premiers-pas.md +114 -82
@@ -1,156 +1,188 @@
1-# Tutoriel : votre premier agent razorbill
1+# Tutoriel : vos premières requêtes à un modèle local
22
3-À la fin de ce tutoriel, vous aurez compilé `rzb`, créé un agent qui fait tourner le petit modèle `mlx-community/Qwen3-0.6B-4bit` sur le GPU de votre Mac, discuté avec lui, et vu l'agent lancer une commande shell après vous avoir demandé la permission. Comptez environ un quart d'heure, surtout pour la première compilation.
3+À la fin de ce tutoriel, vous aurez un modèle qui tourne sur le GPU de votre Mac derrière une API compatible OpenAI, et vous lui aurez parlé deux fois : une fois avec `curl`, une fois depuis un programme Python qui utilise la bibliothèque officielle `openai`.
4+
5+Aucune connaissance de MLX ni de l'API OpenAI n'est nécessaire.
46
57 ## Prérequis
68
7-- Un Mac Apple Silicon (M1 ou plus récent), macOS 14 ou plus récent, et environ 1 Go d'espace disque libre.
8-- Xcode 26 ou plus récent, sélectionné avec `xcode-select` (`xcode-select -p` affiche un chemin dans `Xcode.app`).
9-- La chaîne d'outils Metal, installée une fois : `xcodebuild -downloadComponent MetalToolchain`.
10-- Un accès réseau à `huggingface.co`.
11-- Un clone du dépôt razorbill. Chaque commande ci-dessous commence à sa racine.
9+- Un Mac Apple Silicon (M1 ou plus récent) sous macOS 14 ou plus récent.
10+- `rzb` compilé, comme décrit dans [Compiler rzb sur le Mac](../how-to/compiler-sur-le-mac.md). Dans ce tutoriel, `rzb` désigne `.build/xcode/Build/Products/Release/rzb` ; pour l'écrire plus court, lancez une fois dans votre terminal, depuis la racine du dépôt :
11+
12+ ```bash
13+ alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb"
14+ ```
1215
13-## Étape 1 — Compiler rzb
16+- Environ 400 Mo d'espace disque libre, et une connexion internet pour le premier téléchargement.
17+- [`uv`](https://docs.astral.sh/uv/) pour l'étape 5 (`brew install uv`).
18+
19+## Étape 1 — Télécharger un petit modèle
1420
1521 Tapez :
1622
1723 ```bash
18-xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \
19- -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
24+rzb models pull mlx-community/Qwen3-0.6B-4bit
2025 ```
2126
22-La première compilation télécharge et compile les dépendances et prend plusieurs minutes. Elle se termine par :
27+Une barre de progression défile, puis vous devez voir :
2328
2429 ```
25-** BUILD SUCCEEDED **
30+mlx-community/Qwen3-0.6B-4bit is downloaded.
2631 ```
2732
28-Ajoutez maintenant le dossier qui contient `rzb` à votre `PATH` pour ce terminal, puis vérifiez :
33+Nous avons maintenant un petit modèle (0,6 milliard de paramètres, en 4 bits) dans le cache Hugging Face de ce Mac.
34+
35+## Étape 2 — Démarrer le serveur
36+
37+Tapez :
2938
3039 ```bash
31-export PATH="$PWD/.build/xcode/Build/Products/Release:$PATH"
32-rzb version
40+rzb serve
3341 ```
3442
3543 Vous devez voir :
3644
3745 ```
38-rzb 0.1.0 (engines: fake, mlx)
46+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (no API key) — Ctrl-C to stop
3947 ```
4048
41-Nous avons un `rzb` qui fonctionne et qui sait faire tourner des modèles MLX.
49+Le serveur tourne et n'accepte que les connexions venant de ce Mac. Laissez ce terminal ouvert, et **ouvrez un second terminal** pour la suite.
4250
43-## Étape 2 — Créer un agent
51+## Étape 3 — Vérifier qu'il répond
4452
45-Nous travaillons dans un nouveau dossier vide :
53+Dans le second terminal, tapez :
4654
4755 ```bash
48-mkdir -p ~/rzb-tutorial && cd ~/rzb-tutorial
49-rzb init --yes --name helper --model mlx-community/Qwen3-0.6B-4bit
56+curl -s http://127.0.0.1:8080/health
5057 ```
5158
5259 Vous devez voir :
5360
61+```json
62+{"status":"ok"}
5463 ```
55-Wrote razorbill.yaml. Next: rzb chat --config razorbill.yaml
56-It will be downloaded on first use (or now with: rzb models pull mlx-community/Qwen3-0.6B-4bit).
57-```
58-
59-Ouvrez `razorbill.yaml` : il décrit l'agent — son nom, son modèle, ses réglages de génération et son prompt système — avec un commentaire sur chaque ligne.
6064
61-## Étape 3 — Télécharger le modèle
62-
63-Tapez :
65+Demandez-lui maintenant quels modèles il peut servir :
6466
6567 ```bash
66-rzb models pull mlx-community/Qwen3-0.6B-4bit
67-```
68-
69-Une ligne de progression monte jusqu'à 100 % et se termine par :
70-
71-```
72-mlx-community/Qwen3-0.6B-4bit is downloaded.
68+curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool
7369 ```
7470
75-Vérifiez que razorbill le voit :
71+Vous devez voir une liste qui contient le modèle téléchargé :
7672
77-```bash
78-rzb models list
73+```json
74+{
75+ "data": [
76+ {
77+ "created": 1764096000,
78+ "id": "mlx-community/Qwen3-0.6B-4bit",
79+ "kind": "chat",
80+ "loaded": false,
81+ "object": "model",
82+ "owned_by": "razorbill"
83+ }
84+ ],
85+ "object": "list"
86+}
7987 ```
8088
81-Vous devez voir une ligne qui commence par `mlx-community/Qwen3-0.6B-4bit`, suivie de sa taille (environ 350 Mo) et de `main`.
89+`"loaded": false` : le modèle est sur le disque mais pas encore en mémoire. La première requête le chargera.
8290
83-## Étape 4 — Poser une question
91+## Étape 4 — Poser une question avec curl
8492
8593 Tapez :
8694
8795 ```bash
88-rzb run "What is the capital of France? Answer in one sentence."
96+curl -s http://127.0.0.1:8080/v1/chat/completions \
97+ -H "Content-Type: application/json" \
98+ -d '{
99+ "model": "mlx-community/Qwen3-0.6B-4bit",
100+ "messages": [{"role": "user", "content": "What is the capital of France? One sentence."}]
101+ }' | python3 -m json.tool
89102 ```
90103
91-`rzb` trouve `razorbill.yaml` dans le dossier courant, charge le modèle et affiche une réponse comme :
104+La première requête prend une ou deux secondes de plus : le modèle se charge. Vous devez voir une réponse de cette forme (la phrase exacte peut varier) :
92105
93-```
94-The capital of France is Paris.
95-[24 prompt tokens, 9 generated, 150.2 tokens/s]
106+```json
107+{
108+ "choices": [
109+ {
110+ "finish_reason": "stop",
111+ "index": 0,
112+ "logprobs": null,
113+ "message": {
114+ "content": "The capital of France is Paris.",
115+ "role": "assistant"
116+ }
117+ }
118+ ],
119+ "created": 1764096042,
120+ "id": "chatcmpl-3f9c2a…",
121+ "model": "mlx-community/Qwen3-0.6B-4bit",
122+ "object": "chat.completion",
123+ "usage": {
124+ "completion_tokens": 9,
125+ "prompt_tokens": 20,
126+ "total_tokens": 29
127+ }
128+}
96129 ```
97130
98-Les chiffres de la dernière ligne varient d'un Mac à l'autre. Nous venons de faire tourner un modèle de langage sur le GPU, entièrement sur ce Mac.
131+Dans le premier terminal, le serveur a journalisé le chargement du modèle et la requête, par exemple :
99132
100-## Étape 5 — Avoir une conversation
101-
102-Tapez :
103-
104-```bash
105-rzb chat
133+```
134+2026-11-25T19:20:41+0100 info rzb: [RazorbillServer] loaded mlx-community/Qwen3-0.6B-4bit in 0.43 seconds
135+2026-11-25T19:20:42+0100 info rzb: [RazorbillServer] POST /v1/chat/completions 200 812ms model=mlx-community/Qwen3-0.6B-4bit tokens=20+9
106136 ```
107137
108-Vous devez voir le nom de l'agent, son modèle et son moteur, puis une invite :
138+Nous venons de faire tourner un modèle sur le GPU à travers la même API que celle d'OpenAI.
109139
110-```
111-helper · mlx-community/Qwen3-0.6B-4bit · mlx — /help for commands
112-›
113-```
140+## Étape 5 — Utiliser la bibliothèque Python openai
114141
115-Tapez `My name is Ada.`, appuyez sur Entrée, puis tapez `What is my name?`. L'agent se souvient du premier message et répond avec votre nom. Tapez `/exit` pour sortir.
142+Tout programme écrit pour l'API OpenAI peut utiliser le serveur en changeant son URL de base. Créez un fichier `first.py` avec ce contenu :
116143
117-## Étape 6 — Laisser l'agent lancer une commande
144+```python
145+from openai import OpenAI
118146
119-Ouvrez `razorbill.yaml` dans un éditeur et remplacez la ligne `tools: {}` par ces deux lignes :
147+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
120148
121-```yaml
122-tools:
123- bash: {}
149+stream = client.chat.completions.create(
150+ model="mlx-community/Qwen3-0.6B-4bit",
151+ messages=[{"role": "user", "content": "Write a haiku about the sea."}],
152+ stream=True,
153+)
154+for chunk in stream:
155+ if chunk.choices and chunk.choices[0].delta.content:
156+ print(chunk.choices[0].delta.content, end="", flush=True)
157+print()
124158 ```
125159
126-Relancez le chat et demandez quelque chose que seule une commande peut savoir :
160+Lancez-le :
127161
128162 ```bash
129-rzb chat
130-```
131-
132-```
133-› How many files are in the current folder? Use the bash tool.
163+uv run --with openai python first.py
134164 ```
135165
136-Le modèle demande à lancer une commande, et `rzb` vous demande d'abord votre accord :
166+Vous devez voir un haïku apparaître mot à mot, par exemple :
137167
138168 ```
139-→ bash command="ls | wc -l"
140-
141-bash wants to run: ls | wc -l (in /Users/you/rzb-tutorial)
142-Allow? [y/N]:
169+Waves fold into foam,
170+salt wind carries gull voices—
171+the tide keeps its time.
143172 ```
144173
145-La commande exacte peut varier. Tapez `y` puis Entrée. La commande s'exécute, son résultat repart vers le modèle, et le modèle répond — ici, qu'il y a un fichier (`razorbill.yaml`). Tapez `/exit`.
174+Le serveur ne vérifie pas `api_key`, car nous n'en avons pas défini ; la bibliothèque exige tout de même une valeur.
175+
176+## Étape 6 — Arrêter le serveur
146177
147-Les petits modèles sautent parfois l'outil et devinent. Si cela arrive, reposez la question, ou mettez `model:` à `mlx-community/Qwen3-1.7B-4bit` (téléchargez-le d'abord avec `rzb models pull`).
178+Dans le premier terminal, appuyez sur **Ctrl-C**. Le serveur décharge le modèle et s'arrête.
148179
149180 ## Et maintenant ?
150181
151-Vous avez compilé `rzb`, décrit un agent dans un fichier YAML, fait tourner un modèle sur votre GPU et donné à l'agent un outil qu'il ne peut utiliser qu'avec votre accord. Pour aller plus loin :
182+Vous avez téléchargé un modèle, l'avez servi depuis votre Mac et l'avez appelé avec `curl` et avec la bibliothèque `openai`, streaming compris. Pour aller plus loin :
152183
153-- Essayez l'interface plein écran : `rzb tui`.
154-- Pour des tâches précises → les [guides pratiques](../README.md#faire--guides-pratiques), comme [régler la réflexion](../how-to/regler-la-reflexion.md) ou [utiliser l'outil bash](../how-to/utiliser-l-outil-bash.md).
155-- Toutes les clés du fichier → la [référence du fichier d'agent](../reference/configuration.md).
156-- Comment razorbill est construit → l'[explication de l'architecture](../explanation/architecture.md).
184+- Donner des noms courts à vos modèles, des valeurs par défaut et des limites : [Configurer le serveur](../how-to/configurer-le-serveur.md).
185+- Obtenir du JSON qui respecte un schéma : [Obtenir une sortie structurée](../how-to/obtenir-une-sortie-structuree.md).
186+- Laisser le modèle appeler vos fonctions : [Utiliser l'appel de fonctions](../how-to/utiliser-l-appel-de-fonctions.md).
187+- Chaque endpoint et chaque champ : [référence de l'API HTTP](../reference/api-http.md).
188+- Le fonctionnement interne du serveur : [Architecture](../explanation/architecture.md).
@@ -1,156 +1,188 @@
1-# Tutoriel : votre premier agent razorbill1+# Tutoriel : vos premières requêtes à un modèle local
2 2
3-À la fin de ce tutoriel, vous aurez compilé `rzb`, créé un agent qui fait tourner le petit modèle `mlx-community/Qwen3-0.6B-4bit` sur le GPU de votre Mac, discuté avec lui, et vu l'agent lancer une commande shell après vous avoir demandé la permission. Comptez environ un quart d'heure, surtout pour la première compilation.3+À la fin de ce tutoriel, vous aurez un modèle qui tourne sur le GPU de votre Mac derrière une API compatible OpenAI, et vous lui aurez parlé deux fois : une fois avec `curl`, une fois depuis un programme Python qui utilise la bibliothèque officielle `openai`.
4+
5+Aucune connaissance de MLX ni de l'API OpenAI n'est nécessaire.
4 6
5 ## Prérequis7 ## Prérequis
6 8
7-- Un Mac Apple Silicon (M1 ou plus récent), macOS 14 ou plus récent, et environ 1 Go d'espace disque libre.9+- Un Mac Apple Silicon (M1 ou plus récent) sous macOS 14 ou plus récent.
8-- Xcode 26 ou plus récent, sélectionné avec `xcode-select` (`xcode-select -p` affiche un chemin dans `Xcode.app`).10+- `rzb` compilé, comme décrit dans [Compiler rzb sur le Mac](../how-to/compiler-sur-le-mac.md). Dans ce tutoriel, `rzb` désigne `.build/xcode/Build/Products/Release/rzb` ; pour l'écrire plus court, lancez une fois dans votre terminal, depuis la racine du dépôt :
9-- La chaîne d'outils Metal, installée une fois : `xcodebuild -downloadComponent MetalToolchain`.11+
10-- Un accès réseau à `huggingface.co`.12+ ```bash
11-- Un clone du dépôt razorbill. Chaque commande ci-dessous commence à sa racine.13+ alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb"
14+ ```
12 15
13-## Étape 1 — Compiler rzb16+- Environ 400 Mo d'espace disque libre, et une connexion internet pour le premier téléchargement.
17+- [`uv`](https://docs.astral.sh/uv/) pour l'étape 5 (`brew install uv`).
18+
19+## Étape 1 — Télécharger un petit modèle
14 20
15 Tapez :21 Tapez :
16 22
17 ```bash23 ```bash
18-xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \24+rzb models pull mlx-community/Qwen3-0.6B-4bit
19- -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
20 ```25 ```
21 26
22-La première compilation télécharge et compile les dépendances et prend plusieurs minutes. Elle se termine par :27+Une barre de progression défile, puis vous devez voir :
23 28
24 ```29 ```
25-** BUILD SUCCEEDED **30+mlx-community/Qwen3-0.6B-4bit is downloaded.
26 ```31 ```
27 32
28-Ajoutez maintenant le dossier qui contient `rzb` à votre `PATH` pour ce terminal, puis vérifiez :33+Nous avons maintenant un petit modèle (0,6 milliard de paramètres, en 4 bits) dans le cache Hugging Face de ce Mac.
34+
35+## Étape 2 — Démarrer le serveur
36+
37+Tapez :
29 38
30 ```bash39 ```bash
31-export PATH="$PWD/.build/xcode/Build/Products/Release:$PATH"40+rzb serve
32-rzb version
33 ```41 ```
34 42
35 Vous devez voir :43 Vous devez voir :
36 44
37 ```45 ```
38-rzb 0.1.0 (engines: fake, mlx)46+rzb 0.1.0 serving http://127.0.0.1:8080/v1 (no API key) — Ctrl-C to stop
39 ```47 ```
40 48
41-Nous avons un `rzb` qui fonctionne et qui sait faire tourner des modèles MLX.49+Le serveur tourne et n'accepte que les connexions venant de ce Mac. Laissez ce terminal ouvert, et **ouvrez un second terminal** pour la suite.
42 50
43-## Étape 2 — Créer un agent51+## Étape 3 — Vérifier qu'il répond
44 52
45-Nous travaillons dans un nouveau dossier vide :53+Dans le second terminal, tapez :
46 54
47 ```bash55 ```bash
48-mkdir -p ~/rzb-tutorial && cd ~/rzb-tutorial56+curl -s http://127.0.0.1:8080/health
49-rzb init --yes --name helper --model mlx-community/Qwen3-0.6B-4bit
50 ```57 ```
51 58
52 Vous devez voir :59 Vous devez voir :
53 60
61+```json
62+{"status":"ok"}
54 ```63 ```
55-Wrote razorbill.yaml. Next: rzb chat --config razorbill.yaml
56-It will be downloaded on first use (or now with: rzb models pull mlx-community/Qwen3-0.6B-4bit).
57-```
58-
59-Ouvrez `razorbill.yaml` : il décrit l'agent — son nom, son modèle, ses réglages de génération et son prompt système — avec un commentaire sur chaque ligne.
60 64
61-## Étape 3 — Télécharger le modèle65+Demandez-lui maintenant quels modèles il peut servir :
62-
63-Tapez :
64 66
65 ```bash67 ```bash
66-rzb models pull mlx-community/Qwen3-0.6B-4bit68+curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool
67-```
68-
69-Une ligne de progression monte jusqu'à 100 % et se termine par :
70-
71-```
72-mlx-community/Qwen3-0.6B-4bit is downloaded.
73 ```69 ```
74 70
75-Vérifiez que razorbill le voit :71+Vous devez voir une liste qui contient le modèle téléchargé :
76 72
77-```bash73+```json
78-rzb models list74+{
75+ "data": [
76+ {
77+ "created": 1764096000,
78+ "id": "mlx-community/Qwen3-0.6B-4bit",
79+ "kind": "chat",
80+ "loaded": false,
81+ "object": "model",
82+ "owned_by": "razorbill"
83+ }
84+ ],
85+ "object": "list"
86+}
79 ```87 ```
80 88
81-Vous devez voir une ligne qui commence par `mlx-community/Qwen3-0.6B-4bit`, suivie de sa taille (environ 350 Mo) et de `main`.89+`"loaded": false` : le modèle est sur le disque mais pas encore en mémoire. La première requête le chargera.
82 90
83-## Étape 4 — Poser une question91+## Étape 4 — Poser une question avec curl
84 92
85 Tapez :93 Tapez :
86 94
87 ```bash95 ```bash
88-rzb run "What is the capital of France? Answer in one sentence."96+curl -s http://127.0.0.1:8080/v1/chat/completions \
97+ -H "Content-Type: application/json" \
98+ -d '{
99+ "model": "mlx-community/Qwen3-0.6B-4bit",
100+ "messages": [{"role": "user", "content": "What is the capital of France? One sentence."}]
101+ }' | python3 -m json.tool
89 ```102 ```
90 103
91-`rzb` trouve `razorbill.yaml` dans le dossier courant, charge le modèle et affiche une réponse comme :104+La première requête prend une ou deux secondes de plus : le modèle se charge. Vous devez voir une réponse de cette forme (la phrase exacte peut varier) :
92 105
93-```106+```json
94-The capital of France is Paris.107+{
95-[24 prompt tokens, 9 generated, 150.2 tokens/s]108+ "choices": [
109+ {
110+ "finish_reason": "stop",
111+ "index": 0,
112+ "logprobs": null,
113+ "message": {
114+ "content": "The capital of France is Paris.",
115+ "role": "assistant"
116+ }
117+ }
118+ ],
119+ "created": 1764096042,
120+ "id": "chatcmpl-3f9c2a…",
121+ "model": "mlx-community/Qwen3-0.6B-4bit",
122+ "object": "chat.completion",
123+ "usage": {
124+ "completion_tokens": 9,
125+ "prompt_tokens": 20,
126+ "total_tokens": 29
127+ }
128+}
96 ```129 ```
97 130
98-Les chiffres de la dernière ligne varient d'un Mac à l'autre. Nous venons de faire tourner un modèle de langage sur le GPU, entièrement sur ce Mac.131+Dans le premier terminal, le serveur a journalisé le chargement du modèle et la requête, par exemple :
99 132
100-## Étape 5 — Avoir une conversation133+```
101-134+2026-11-25T19:20:41+0100 info rzb: [RazorbillServer] loaded mlx-community/Qwen3-0.6B-4bit in 0.43 seconds
102-Tapez :135+2026-11-25T19:20:42+0100 info rzb: [RazorbillServer] POST /v1/chat/completions 200 812ms model=mlx-community/Qwen3-0.6B-4bit tokens=20+9
103-
104-```bash
105-rzb chat
106 ```136 ```
107 137
108-Vous devez voir le nom de l'agent, son modèle et son moteur, puis une invite :138+Nous venons de faire tourner un modèle sur le GPU à travers la même API que celle d'OpenAI.
109 139
110-```140+## Étape 5 — Utiliser la bibliothèque Python openai
111-helper · mlx-community/Qwen3-0.6B-4bit · mlx — /help for commands
112-›
113-```
114 141
115-Tapez `My name is Ada.`, appuyez sur Entrée, puis tapez `What is my name?`. L'agent se souvient du premier message et répond avec votre nom. Tapez `/exit` pour sortir.142+Tout programme écrit pour l'API OpenAI peut utiliser le serveur en changeant son URL de base. Créez un fichier `first.py` avec ce contenu :
116 143
117-## Étape 6 — Laisser l'agent lancer une commande144+```python
145+from openai import OpenAI
118 146
119-Ouvrez `razorbill.yaml` dans un éditeur et remplacez la ligne `tools: {}` par ces deux lignes :147+client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
120 148
121-```yaml149+stream = client.chat.completions.create(
122-tools:150+ model="mlx-community/Qwen3-0.6B-4bit",
123- bash: {}151+ messages=[{"role": "user", "content": "Write a haiku about the sea."}],
152+ stream=True,
153+)
154+for chunk in stream:
155+ if chunk.choices and chunk.choices[0].delta.content:
156+ print(chunk.choices[0].delta.content, end="", flush=True)
157+print()
124 ```158 ```
125 159
126-Relancez le chat et demandez quelque chose que seule une commande peut savoir :160+Lancez-le :
127 161
128 ```bash162 ```bash
129-rzb chat163+uv run --with openai python first.py
130-```
131-
132-```
133-› How many files are in the current folder? Use the bash tool.
134 ```164 ```
135 165
136-Le modèle demande à lancer une commande, et `rzb` vous demande d'abord votre accord :166+Vous devez voir un haïku apparaître mot à mot, par exemple :
137 167
138 ```168 ```
139-→ bash command="ls | wc -l"169+Waves fold into foam,
140-170+salt wind carries gull voices—
141-bash wants to run: ls | wc -l (in /Users/you/rzb-tutorial)171+the tide keeps its time.
142-Allow? [y/N]:
143 ```172 ```
144 173
145-La commande exacte peut varier. Tapez `y` puis Entrée. La commande s'exécute, son résultat repart vers le modèle, et le modèle répond — ici, qu'il y a un fichier (`razorbill.yaml`). Tapez `/exit`.174+Le serveur ne vérifie pas `api_key`, car nous n'en avons pas défini ; la bibliothèque exige tout de même une valeur.
175+
176+## Étape 6 — Arrêter le serveur
146 177
147-Les petits modèles sautent parfois l'outil et devinent. Si cela arrive, reposez la question, ou mettez `model:` à `mlx-community/Qwen3-1.7B-4bit` (téléchargez-le d'abord avec `rzb models pull`).178+Dans le premier terminal, appuyez sur **Ctrl-C**. Le serveur décharge le modèle et s'arrête.
148 179
149 ## Et maintenant ?180 ## Et maintenant ?
150 181
151-Vous avez compilé `rzb`, décrit un agent dans un fichier YAML, fait tourner un modèle sur votre GPU et donné à l'agent un outil qu'il ne peut utiliser qu'avec votre accord. Pour aller plus loin :182+Vous avez téléchargé un modèle, l'avez servi depuis votre Mac et l'avez appelé avec `curl` et avec la bibliothèque `openai`, streaming compris. Pour aller plus loin :
152 183
153-- Essayez l'interface plein écran : `rzb tui`.184+- Donner des noms courts à vos modèles, des valeurs par défaut et des limites : [Configurer le serveur](../how-to/configurer-le-serveur.md).
154-- Pour des tâches précises → les [guides pratiques](../README.md#faire--guides-pratiques), comme [régler la réflexion](../how-to/regler-la-reflexion.md) ou [utiliser l'outil bash](../how-to/utiliser-l-outil-bash.md).185+- Obtenir du JSON qui respecte un schéma : [Obtenir une sortie structurée](../how-to/obtenir-une-sortie-structuree.md).
155-- Toutes les clés du fichier → la [référence du fichier d'agent](../reference/configuration.md).186+- Laisser le modèle appeler vos fonctions : [Utiliser l'appel de fonctions](../how-to/utiliser-l-appel-de-fonctions.md).
156-- Comment razorbill est construit → l'[explication de l'architecture](../explanation/architecture.md).187+- Chaque endpoint et chaque champ : [référence de l'API HTTP](../reference/api-http.md).
188+- Le fonctionnement interne du serveur : [Architecture](../explanation/architecture.md).