Manual test plan for v0.2 steps 8-9 (#38-#42)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1a6201b parent: e171b51 modified
.memory/history.md +10 -0 | @@ -206,3 +206,13 @@ | ||
| 206 | 206 | pooling/prefix config. `rzb models pull` fetched both reference models on the Mac. Linux 144, |
| 207 | 207 | Mac 167, gate PASS (run #16). #42 closed. End of the user's #38–#42 request; testing checklist |
| 208 | 208 | given in the final answer. |
| 209 | + | |
| 210 | +## 2026-11-25 — manual test plan for #38–#42 | |
| 211 | + | |
| 212 | +Asked for a Markdown document explaining everything to test by hand. Wrote `TEST-PLAN-v0.2.md` | |
| 213 | +(repo root, French, temporary: not part of the Diátaxis docs; delete once v0.2 is validated). | |
| 214 | +It covers Release build, a test config (qwen4b / llama3b / embed, max_loaded_models 2), structured | |
| 215 | +output, constrained-decoding speed, tools (auto/required/named/none/parallel, Llama 400), embeddings | |
| 216 | +(SDK, dimensions, base64, LangChain, Matryoshka, wrong kind, too long), known limits, report grid. | |
| 217 | +Correction: the server does not log tok/s (an earlier answer said it did); the plan computes it | |
| 218 | +from `usage`. No code change, no tests run. | |
| @@ -206,3 +206,13 @@ | |||
| 206 | pooling/prefix config. `rzb models pull` fetched both reference models on the Mac. Linux 144, | 206 | pooling/prefix config. `rzb models pull` fetched both reference models on the Mac. Linux 144, |
| 207 | Mac 167, gate PASS (run #16). #42 closed. End of the user's #38–#42 request; testing checklist | 207 | Mac 167, gate PASS (run #16). #42 closed. End of the user's #38–#42 request; testing checklist |
| 208 | given in the final answer. | 208 | given in the final answer. |
| 209 | + | ||
| 210 | +## 2026-11-25 — manual test plan for #38–#42 | ||
| 211 | + | ||
| 212 | +Asked for a Markdown document explaining everything to test by hand. Wrote `TEST-PLAN-v0.2.md` | ||
| 213 | +(repo root, French, temporary: not part of the Diátaxis docs; delete once v0.2 is validated). | ||
| 214 | +It covers Release build, a test config (qwen4b / llama3b / embed, max_loaded_models 2), structured | ||
| 215 | +output, constrained-decoding speed, tools (auto/required/named/none/parallel, Llama 400), embeddings | ||
| 216 | +(SDK, dimensions, base64, LangChain, Matryoshka, wrong kind, too long), known limits, report grid. | ||
| 217 | +Correction: the server does not log tok/s (an earlier answer said it did); the plan computes it | ||
| 218 | +from `usage`. No code change, no tests run. | ||
added
TEST-PLAN-v0.2.md +507 -0 | new file mode 100644 | ||
| @@ -0,0 +1,507 @@ | ||
| 1 | +# Plan de test manuel — rzb serve v0.2 (#38 → #42) | |
| 2 | + | |
| 3 | +Ce document liste ce qu'il reste à vérifier **à la main, sur le Mac**, après les tickets #38 à #42 | |
| 4 | +(sorties structurées, appels d'outils, embeddings). Les tests automatiques passent déjà (Linux 144, | |
| 5 | +Mac 167) : ici, on vérifie ce qu'ils ne couvrent pas — de vrais clients, de plus gros modèles, | |
| 6 | +d'autres familles de modèles, et la vitesse en Release. | |
| 7 | + | |
| 8 | +Chaque test a : la commande à lancer, **le résultat attendu**, et une case à cocher. Notez ce qui | |
| 9 | +échoue (commande + sortie) dans la section [Rapport](#rapport) à la fin. | |
| 10 | + | |
| 11 | +Durée estimée : 1 h à 1 h 30, dont l'essentiel en téléchargements de modèles. | |
| 12 | + | |
| 13 | +--- | |
| 14 | + | |
| 15 | +## 0. Préparation | |
| 16 | + | |
| 17 | +### 0.1 Compiler en Release | |
| 18 | + | |
| 19 | +```bash | |
| 20 | +cd ~/kDrive/Rickub/bots-garden/razorbill | |
| 21 | +xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \ | |
| 22 | + -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation | |
| 23 | +alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb" | |
| 24 | +rzb version | |
| 25 | +``` | |
| 26 | + | |
| 27 | +- [ ] `rzb version` affiche la version et `engines: mlx`. | |
| 28 | + | |
| 29 | +### 0.2 Télécharger les modèles | |
| 30 | + | |
| 31 | +```bash | |
| 32 | +rzb models pull mlx-community/Qwen3-4B-4bit # ~2,3 Go — chat, outils, JSON | |
| 33 | +rzb models pull mlx-community/Llama-3.2-3B-Instruct-4bit # ~1,8 Go — 2e famille d'outils | |
| 34 | +rzb models pull BAAI/bge-small-en-v1.5 # déjà en cache normalement | |
| 35 | +rzb models list | |
| 36 | +``` | |
| 37 | + | |
| 38 | +Optionnel (test Matryoshka, §4.4) : un modèle d'embedding Qwen3 au format MLX, par exemple | |
| 39 | +`mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ` (vérifiez le nom exact sur Hugging Face). | |
| 40 | + | |
| 41 | +### 0.3 Configuration de test | |
| 42 | + | |
| 43 | +Enregistrez ceci dans `/tmp/rzb-test.yaml` : | |
| 44 | + | |
| 45 | +```yaml | |
| 46 | +server: | |
| 47 | + host: 127.0.0.1 | |
| 48 | + port: 8080 | |
| 49 | + | |
| 50 | +models: | |
| 51 | + - id: qwen4b | |
| 52 | + source: mlx-community/Qwen3-4B-4bit | |
| 53 | + kind: chat | |
| 54 | + - id: llama3b | |
| 55 | + source: mlx-community/Llama-3.2-3B-Instruct-4bit | |
| 56 | + kind: chat | |
| 57 | + - id: embed | |
| 58 | + source: BAAI/bge-small-en-v1.5 | |
| 59 | + kind: embedding | |
| 60 | + preload: true | |
| 61 | + | |
| 62 | +limits: | |
| 63 | + max_loaded_models: 2 | |
| 64 | + keep_alive: 10m | |
| 65 | +``` | |
| 66 | + | |
| 67 | +```bash | |
| 68 | +rzb config validate /tmp/rzb-test.yaml | |
| 69 | +rzb serve --config /tmp/rzb-test.yaml | |
| 70 | +``` | |
| 71 | + | |
| 72 | +- [ ] `config validate` ne signale aucune erreur. | |
| 73 | +- [ ] Le serveur démarre, affiche `serving http://127.0.0.1:8080`, et le log indique que `embed` | |
| 74 | + est chargé au démarrage (`preload: true`). | |
| 75 | + | |
| 76 | +Laissez ce terminal ouvert (les logs serviront) et ouvrez-en un second pour la suite. | |
| 77 | + | |
| 78 | +> Pas de clé d'API dans cette config : les clients peuvent envoyer n'importe quelle valeur | |
| 79 | +> (`api_key="x"`). Si `RZB_API_KEY` est définie dans votre shell **et** déclarée via | |
| 80 | +> `api_key_env`, utilisez sa valeur. | |
| 81 | + | |
| 82 | +### 0.4 Outils côté client | |
| 83 | + | |
| 84 | +Les exemples Python utilisent `uv` (pas d'environnement à créer) : | |
| 85 | + | |
| 86 | +```bash | |
| 87 | +uv --version # sinon : brew install uv | |
| 88 | +``` | |
| 89 | + | |
| 90 | +### 0.5 Premier contact | |
| 91 | + | |
| 92 | +```bash | |
| 93 | +curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool | |
| 94 | +``` | |
| 95 | + | |
| 96 | +- [ ] La liste contient `qwen4b`, `llama3b` (`"kind": "chat"`) et `embed` (`"kind": "embedding"`), | |
| 97 | + plus les modèles du cache. | |
| 98 | + | |
| 99 | +--- | |
| 100 | + | |
| 101 | +## 1. Sorties structurées — `response_format` (#39) | |
| 102 | + | |
| 103 | +### 1.1 `parse()` du SDK openai avec une classe Pydantic — **critère d'acceptation de #39** | |
| 104 | + | |
| 105 | +```bash | |
| 106 | +uv run --with openai --with pydantic python - <<'EOF' | |
| 107 | +from openai import OpenAI | |
| 108 | +from pydantic import BaseModel | |
| 109 | + | |
| 110 | +class City(BaseModel): | |
| 111 | + name: str | |
| 112 | + country: str | |
| 113 | + population: int | |
| 114 | + landmarks: list[str] | |
| 115 | + | |
| 116 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 117 | +completion = client.beta.chat.completions.parse( | |
| 118 | + model="qwen4b", | |
| 119 | + messages=[{"role": "user", "content": "Describe Lyon, France."}], | |
| 120 | + response_format=City, | |
| 121 | +) | |
| 122 | +message = completion.choices[0].message | |
| 123 | +print("parsed :", message.parsed) | |
| 124 | +print("raison :", (getattr(message, "reasoning_content", None) or "")[:200]) | |
| 125 | +EOF | |
| 126 | +``` | |
| 127 | + | |
| 128 | +- [ ] `parsed` est un objet `City` rempli (pas `None`), sans exception de validation. | |
| 129 | +- [ ] Recommencez 3 fois : toujours un JSON valide. | |
| 130 | + | |
| 131 | +> Selon la version du SDK, `client.chat.completions.parse(...)` (sans `beta`) existe aussi : | |
| 132 | +> testez celle que vous avez. | |
| 133 | + | |
| 134 | +### 1.2 Avec réflexion activée | |
| 135 | + | |
| 136 | +Même script, en ajoutant à l'appel `parse(...)` : | |
| 137 | + | |
| 138 | +```python | |
| 139 | + extra_body={"reasoning_effort": "high"}, | |
| 140 | +``` | |
| 141 | + | |
| 142 | +- [ ] `reasoning_content` contient la réflexion (texte libre, pas du JSON). | |
| 143 | +- [ ] `parsed` reste un objet `City` valide : la contrainte ne s'applique qu'après `</think>`. | |
| 144 | + | |
| 145 | +### 1.3 `json_object` avec curl | |
| 146 | + | |
| 147 | +```bash | |
| 148 | +curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | |
| 149 | + "model": "qwen4b", | |
| 150 | + "messages": [{"role": "user", "content": "Give me 3 French cheeses with their region, as JSON."}], | |
| 151 | + "response_format": {"type": "json_object"}, | |
| 152 | + "reasoning_effort": "none" | |
| 153 | +}' | python3 -c 'import json,sys; c=json.load(sys.stdin)["choices"][0]["message"]["content"]; print(json.dumps(json.loads(c), indent=2, ensure_ascii=False))' | |
| 154 | +``` | |
| 155 | + | |
| 156 | +- [ ] La commande affiche un objet JSON (le `json.loads` ne lève pas d'erreur). | |
| 157 | + | |
| 158 | +### 1.4 Streaming d'un `json_schema` | |
| 159 | + | |
| 160 | +```bash | |
| 161 | +curl -sN http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | |
| 162 | + "model": "qwen4b", "stream": true, "reasoning_effort": "none", | |
| 163 | + "messages": [{"role": "user", "content": "List 5 planets with their diameter in km."}], | |
| 164 | + "response_format": {"type": "json_schema", "json_schema": {"name": "planets", "strict": true, | |
| 165 | + "schema": {"type": "object", "additionalProperties": false, "required": ["planets"], | |
| 166 | + "properties": {"planets": {"type": "array", "items": {"type": "object", | |
| 167 | + "additionalProperties": false, "required": ["name", "diameter_km"], | |
| 168 | + "properties": {"name": {"type": "string"}, "diameter_km": {"type": "number"}}}}}}}} | |
| 169 | +}' | |
| 170 | +``` | |
| 171 | + | |
| 172 | +- [ ] Les lignes `data: {...}` arrivent **au fil de l'eau**, chacune avec un petit morceau de JSON | |
| 173 | + dans `delta.content` (pas un seul bloc à la fin). | |
| 174 | +- [ ] Le flux se termine par `finish_reason: "stop"` puis `data: [DONE]`. | |
| 175 | +- [ ] En recollant les `content`, on obtient un JSON qui respecte le schéma. | |
| 176 | + | |
| 177 | +### 1.5 Schéma strict avec un mot-clé non appliqué → 400 | |
| 178 | + | |
| 179 | +```bash | |
| 180 | +curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | |
| 181 | + "model": "qwen4b", | |
| 182 | + "messages": [{"role": "user", "content": "3 tags"}], | |
| 183 | + "response_format": {"type": "json_schema", "json_schema": {"name": "tags", "strict": true, | |
| 184 | + "schema": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}}} | |
| 185 | +}' | |
| 186 | +``` | |
| 187 | + | |
| 188 | +- [ ] Réponse **400** `{"error": {...}}` dont le message nomme `uniqueItems`. | |
| 189 | +- [ ] Le même appel avec `"strict": false` est accepté (le mot-clé est simplement ignoré). | |
| 190 | + | |
| 191 | +--- | |
| 192 | + | |
| 193 | +## 2. Vitesse du décodage contraint (Release) | |
| 194 | + | |
| 195 | +Mes mesures (build **Debug**, Qwen3-0.6B) : ~90 tok/s en libre, ~49 tok/s sous contrainte. Le | |
| 196 | +serveur ne logue pas les tok/s : ce script les calcule à partir de `usage`. | |
| 197 | + | |
| 198 | +```bash | |
| 199 | +uv run --with openai python - <<'EOF' | |
| 200 | +import time | |
| 201 | +from openai import OpenAI | |
| 202 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 203 | +prompt = [{"role": "user", "content": "Describe 10 European capitals: name, country, population, one fact each."}] | |
| 204 | +schema = {"type": "json_schema", "json_schema": {"name": "capitals", "schema": { | |
| 205 | + "type": "object", "properties": {"capitals": {"type": "array", "items": {"type": "object", | |
| 206 | + "properties": {"name": {"type": "string"}, "country": {"type": "string"}, | |
| 207 | + "population": {"type": "integer"}, "fact": {"type": "string"}}, | |
| 208 | + "required": ["name", "country", "population", "fact"]}}}, "required": ["capitals"]}}} | |
| 209 | +client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=5) # chauffe | |
| 210 | +for label, extra in [("libre", {}), ("json_object", {"response_format": {"type": "json_object"}}), | |
| 211 | + ("json_schema", {"response_format": schema})]: | |
| 212 | + start = time.time() | |
| 213 | + r = client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=800, | |
| 214 | + extra_body={"reasoning_effort": "none"}, **extra) | |
| 215 | + elapsed = time.time() - start | |
| 216 | + n = r.usage.completion_tokens | |
| 217 | + print(f"{label:12} {n:4} tokens {elapsed:5.1f} s {n / elapsed:5.1f} tok/s") | |
| 218 | +EOF | |
| 219 | +``` | |
| 220 | + | |
| 221 | +- [ ] Notez les trois débits dans le rapport. **Attendu** : le contraint reste dans le même ordre | |
| 222 | + de grandeur que le libre (au pire ~2× plus lent). Un écart de 5× ou plus est un problème. | |
| 223 | +- [ ] Optionnel : relancez avec `model="mlx-community/Qwen3-0.6B-4bit"` pour comparer à mes chiffres Debug. | |
| 224 | + | |
| 225 | +--- | |
| 226 | + | |
| 227 | +## 3. Appels d'outils (#40, #41) | |
| 228 | + | |
| 229 | +### 3.1 Aller-retour complet en `auto` avec Qwen3-4B | |
| 230 | + | |
| 231 | +```bash | |
| 232 | +uv run --with openai python - <<'EOF' | |
| 233 | +import json | |
| 234 | +from openai import OpenAI | |
| 235 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 236 | +MODEL = "qwen4b" | |
| 237 | +tools = [{"type": "function", "function": { | |
| 238 | + "name": "get_weather", "description": "Current weather for a city", | |
| 239 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 240 | + "required": ["city"]}}}] | |
| 241 | +messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | |
| 242 | + | |
| 243 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | |
| 244 | +msg = r.choices[0].message | |
| 245 | +print("1) finish_reason:", r.choices[0].finish_reason) | |
| 246 | +print(" tool_calls :", msg.tool_calls) | |
| 247 | +assert msg.tool_calls, "aucun appel d'outil" | |
| 248 | + | |
| 249 | +messages.append(msg.model_dump(exclude_none=True)) | |
| 250 | +for call in msg.tool_calls: | |
| 251 | + args = json.loads(call.function.arguments) | |
| 252 | + messages.append({"role": "tool", "tool_call_id": call.id, | |
| 253 | + "content": json.dumps({"city": args["city"], "temp_c": 7, "sky": "rain"})}) | |
| 254 | + | |
| 255 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | |
| 256 | +print("2) réponse finale:", r.choices[0].message.content) | |
| 257 | +EOF | |
| 258 | +``` | |
| 259 | + | |
| 260 | +- [ ] Étape 1 : `finish_reason` vaut `tool_calls`, avec un appel `get_weather` dont les | |
| 261 | + `arguments` sont un JSON valide (`{"city": "Lyon"}`). | |
| 262 | +- [ ] Étape 2 : la réponse finale parle de 7 °C et de pluie à Lyon. | |
| 263 | + | |
| 264 | +### 3.2 Même script en streaming | |
| 265 | + | |
| 266 | +Remplacez le premier `create(...)` par une version `stream=True` et affichez les deltas : | |
| 267 | + | |
| 268 | +```python | |
| 269 | +for chunk in client.chat.completions.create(model=MODEL, messages=messages, tools=tools, stream=True): | |
| 270 | + if chunk.choices: | |
| 271 | + print(chunk.choices[0].delta, chunk.choices[0].finish_reason) | |
| 272 | +``` | |
| 273 | + | |
| 274 | +- [ ] Un delta contient `tool_calls` avec `index: 0`, un `id`, `type: "function"` et le nom et les | |
| 275 | + arguments ; le dernier chunk a `finish_reason: "tool_calls"`. | |
| 276 | + | |
| 277 | +### 3.3 Deuxième famille (Llama 3.2) en `auto` — **critère de #40, non vérifié** | |
| 278 | + | |
| 279 | +Relancez le script 3.1 avec `MODEL = "llama3b"`. | |
| 280 | + | |
| 281 | +- [ ] `tool_calls` est rempli correctement (nom + arguments JSON), **pas** du texte brut du genre | |
| 282 | + `{"name": "get_weather", ...}` dans `content`. | |
| 283 | +- [ ] La réponse finale utilise le résultat de l'outil. | |
| 284 | + | |
| 285 | +Si vous avez un Mistral au format MLX (ex. `mlx-community/Mistral-7B-Instruct-v0.3-4bit`), même test. | |
| 286 | + | |
| 287 | +### 3.4 Appels forcés sur Qwen : `required` et fonction nommée | |
| 288 | + | |
| 289 | +Dans le script 3.1 (`MODEL = "qwen4b"`), remplacez le message par une question **sans rapport** | |
| 290 | +avec la météo (« Raconte-moi une blague ») et ajoutez au premier appel : | |
| 291 | + | |
| 292 | +```python | |
| 293 | + tool_choice="required", | |
| 294 | +``` | |
| 295 | + | |
| 296 | +puis refaites avec : | |
| 297 | + | |
| 298 | +```python | |
| 299 | + tool_choice={"type": "function", "function": {"name": "get_weather"}}, | |
| 300 | +``` | |
| 301 | + | |
| 302 | +- [ ] Dans les deux cas, il y a **exactement un** appel `get_weather` avec des arguments valides, | |
| 303 | + même si la question ne s'y prête pas : la grammaire l'impose. | |
| 304 | + | |
| 305 | +### 3.5 Appel forcé sur Llama → 400 attendu | |
| 306 | + | |
| 307 | +Même chose que 3.4 avec `MODEL = "llama3b"` et `tool_choice="required"`. | |
| 308 | + | |
| 309 | +- [ ] Erreur **400** (`openai.BadRequestError`) avec un message expliquant que la syntaxe d'appel | |
| 310 | + de ce modèle ne permet pas de forcer un outil. C'est le comportement voulu. | |
| 311 | +- [ ] Avec `tool_choice="auto"`, le même modèle fonctionne (cf. 3.3). | |
| 312 | + | |
| 313 | +### 3.6 `tool_choice: "none"` | |
| 314 | + | |
| 315 | +Script 3.1 avec `tool_choice="none"`. | |
| 316 | + | |
| 317 | +- [ ] Réponse en texte, aucun `tool_calls`, `finish_reason: "stop"`. | |
| 318 | + | |
| 319 | +### 3.7 Appels parallèles | |
| 320 | + | |
| 321 | +Ajoutez un second outil et posez une question qui demande les deux : | |
| 322 | + | |
| 323 | +```python | |
| 324 | +tools.append({"type": "function", "function": { | |
| 325 | + "name": "get_time", "description": "Current local time in a city", | |
| 326 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | |
| 327 | + "required": ["city"]}}}) | |
| 328 | +messages = [{"role": "user", "content": "What's the weather and the local time in Tokyo?"}] | |
| 329 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | |
| 330 | + tool_choice="required", parallel_tool_calls=True) | |
| 331 | +print(r.choices[0].message.tool_calls) | |
| 332 | +``` | |
| 333 | + | |
| 334 | +- [ ] Deux appels (`get_weather` et `get_time`), chacun avec un `id` différent. | |
| 335 | +- [ ] Sans `parallel_tool_calls=True` : un seul appel (comportement voulu des appels forcés). | |
| 336 | + | |
| 337 | +### 3.8 Un vrai client agent (optionnel, mais très parlant) | |
| 338 | + | |
| 339 | +Par exemple LangChain : | |
| 340 | + | |
| 341 | +```bash | |
| 342 | +uv run --with langchain-openai python - <<'EOF' | |
| 343 | +from langchain_openai import ChatOpenAI | |
| 344 | +from langchain_core.tools import tool | |
| 345 | + | |
| 346 | +@tool | |
| 347 | +def add(a: int, b: int) -> int: | |
| 348 | + """Add two integers.""" | |
| 349 | + return a + b | |
| 350 | + | |
| 351 | +llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x", model="qwen4b") | |
| 352 | +msg = llm.bind_tools([add]).invoke("What is 1234 + 4321? Use the tool.") | |
| 353 | +print(msg.tool_calls) | |
| 354 | +EOF | |
| 355 | +``` | |
| 356 | + | |
| 357 | +- [ ] `msg.tool_calls` contient un appel `add` avec `{"a": 1234, "b": 4321}`. | |
| 358 | + | |
| 359 | +--- | |
| 360 | + | |
| 361 | +## 4. Embeddings (#42) | |
| 362 | + | |
| 363 | +### 4.1 SDK openai | |
| 364 | + | |
| 365 | +```bash | |
| 366 | +uv run --with openai --with numpy python - <<'EOF' | |
| 367 | +import numpy as np | |
| 368 | +from openai import OpenAI | |
| 369 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | |
| 370 | +texts = ["The cat sits on the mat.", "A feline is resting on a rug.", "Stock markets fell sharply today."] | |
| 371 | +for model in ["embed", "BAAI/bge-small-en-v1.5"]: | |
| 372 | + r = client.embeddings.create(model=model, input=texts) | |
| 373 | + v = np.array([d.embedding for d in r.data]) | |
| 374 | + print(model, v.shape, "usage:", r.usage) | |
| 375 | + print(" cos(chat, félin) =", round(float(v[0] @ v[1]), 4), " cos(chat, bourse) =", round(float(v[0] @ v[2]), 4)) | |
| 376 | +EOF | |
| 377 | +``` | |
| 378 | + | |
| 379 | +- [ ] Forme `(3, 384)` pour les deux noms (alias de config et id Hugging Face). | |
| 380 | +- [ ] cos(chat, félin) ≈ **0,755**, cos(chat, bourse) ≈ **0,324** (valeurs de sentence-transformers). | |
| 381 | +- [ ] `usage.prompt_tokens` > 0. | |
| 382 | + | |
| 383 | +### 4.2 `dimensions` et `encoding_format: base64` | |
| 384 | + | |
| 385 | +```bash | |
| 386 | +curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | |
| 387 | + -d '{"model": "embed", "input": "bonjour", "dimensions": 64}' \ | |
| 388 | + | python3 -c 'import json,sys; e=json.load(sys.stdin)["data"][0]["embedding"]; print(len(e), sum(x*x for x in e))' | |
| 389 | + | |
| 390 | +curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | |
| 391 | + -d '{"model": "embed", "input": "bonjour", "encoding_format": "base64"}' \ | |
| 392 | + | python3 -c 'import json,sys,base64,struct; b=base64.b64decode(json.load(sys.stdin)["data"][0]["embedding"]); print(len(b)//4, struct.unpack("<3f", b[:12]))' | |
| 393 | +``` | |
| 394 | + | |
| 395 | +- [ ] Premier appel : `64` et une norme au carré ≈ `1.0` (vecteur tronqué puis renormalisé). | |
| 396 | +- [ ] Second appel : `384` et trois nombres flottants plausibles (entre -1 et 1). | |
| 397 | +- [ ] `"dimensions": 1000` → **400** qui indique la dimension native (384). | |
| 398 | + | |
| 399 | +> Le SDK openai demande lui-même `base64` par défaut quand on n'impose rien : le test 4.1 couvre | |
| 400 | +> donc déjà ce chemin côté SDK. | |
| 401 | + | |
| 402 | +### 4.3 LangChain `OpenAIEmbeddings` | |
| 403 | + | |
| 404 | +```bash | |
| 405 | +uv run --with langchain-openai python - <<'EOF' | |
| 406 | +from langchain_openai import OpenAIEmbeddings | |
| 407 | +emb = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="x", model="embed", | |
| 408 | + check_embedding_ctx_length=False) | |
| 409 | +v = emb.embed_documents(["hello world", "bonjour le monde"]) | |
| 410 | +print(len(v), len(v[0])) | |
| 411 | +print(len(emb.embed_query("hi"))) | |
| 412 | +EOF | |
| 413 | +``` | |
| 414 | + | |
| 415 | +- [ ] `2 384` puis `384`. | |
| 416 | +- [ ] Sans `check_embedding_ctx_length=False` : **400** « token arrays are not supported yet ». | |
| 417 | + C'est une limite connue (LangChain envoie alors des tokens tiktoken) ; dites-moi si vous | |
| 418 | + voulez qu'elle soit levée. | |
| 419 | + | |
| 420 | +### 4.4 Modèle Matryoshka (optionnel) | |
| 421 | + | |
| 422 | +Ajoutez dans `/tmp/rzb-test.yaml`, puis redémarrez le serveur : | |
| 423 | + | |
| 424 | +```yaml | |
| 425 | + - id: qembed | |
| 426 | + source: mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ # nom exact à vérifier | |
| 427 | + kind: embedding | |
| 428 | +``` | |
| 429 | + | |
| 430 | +Relancez le script 4.1 avec `model="qembed"`, puis avec `dimensions=256` passé à `create(...)`. | |
| 431 | + | |
| 432 | +- [ ] Le modèle se charge (sinon, notez l'erreur exacte : ce modèle n'a jamais été essayé). | |
| 433 | +- [ ] cos(chat, félin) > cos(chat, bourse), en pleine dimension comme en 256. | |
| 434 | + | |
| 435 | +### 4.5 Chat et embedding chargés ensemble | |
| 436 | + | |
| 437 | +Avec `max_loaded_models: 2` : faites un appel de chat sur `qwen4b`, puis un embedding sur `embed`, | |
| 438 | +puis de nouveau un chat. | |
| 439 | + | |
| 440 | +- [ ] Les logs du serveur ne montrent **aucun** `unloaded` entre les appels ; le second chat | |
| 441 | + répond tout de suite (pas de rechargement). | |
| 442 | + | |
| 443 | +### 4.6 Mauvais type de modèle | |
| 444 | + | |
| 445 | +```bash | |
| 446 | +curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | |
| 447 | + -d '{"model": "qwen4b", "input": "x"}' | |
| 448 | +curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' \ | |
| 449 | + -d '{"model": "embed", "messages": [{"role": "user", "content": "hi"}]}' | |
| 450 | +``` | |
| 451 | + | |
| 452 | +- [ ] Les deux renvoient une erreur JSON claire (400) qui dit que le modèle n'est pas du bon type, | |
| 453 | + sans planter ni charger un modèle pour rien. | |
| 454 | + | |
| 455 | +### 4.7 Texte trop long | |
| 456 | + | |
| 457 | +```bash | |
| 458 | +python3 -c 'import json; print(json.dumps({"model": "embed", "input": ["court", "mot " * 3000]}))' \ | |
| 459 | + | curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' -d @- | |
| 460 | +``` | |
| 461 | + | |
| 462 | +- [ ] **400** qui désigne `input[1]` et la limite du modèle (512 tokens pour bge-small). | |
| 463 | + | |
| 464 | +--- | |
| 465 | + | |
| 466 | +## 5. Limites connues (pas des bugs) | |
| 467 | + | |
| 468 | +- `/v1/models` affiche `"kind": "chat"` pour un modèle d'embedding **non déclaré** présent dans le | |
| 469 | + cache (le cache ne connaît pas le type). Les modèles déclarés avec `kind:` sont justes. | |
| 470 | +- Pas d'option de troncature des textes trop longs : 400 (cf. 4.7). | |
| 471 | +- `input` sous forme de tokens (listes d'entiers) refusé (cf. 4.3). | |
| 472 | +- Les préfixes d'instruction (`search_query:`, `Instruct: …`) sont à ajouter côté client. | |
| 473 | +- Appels d'outils **forcés** (`required`, fonction nommée, outil `strict`) : uniquement pour les | |
| 474 | + modèles à syntaxe `<tool_call>` JSON (Qwen, Hermes). Les autres familles → 400 (cf. 3.5). | |
| 475 | +- Les grammaires sont recompilées à chaque requête (~0,2 s), la version de XGrammar embarquée ne | |
| 476 | + permettant pas de les mettre en cache. | |
| 477 | + | |
| 478 | +--- | |
| 479 | + | |
| 480 | +## Rapport | |
| 481 | + | |
| 482 | +Copiez ce bloc et remplissez-le ; envoyez-moi les lignes en ❌ avec la commande et la sortie. | |
| 483 | + | |
| 484 | +```text | |
| 485 | +0. Préparation : ✅ / ❌ | |
| 486 | +1.1 parse() Pydantic : | |
| 487 | +1.2 + reasoning : | |
| 488 | +1.3 json_object : | |
| 489 | +1.4 json_schema stream : | |
| 490 | +1.5 uniqueItems → 400 : | |
| 491 | +2. débits (tok/s) : libre=… json_object=… json_schema=… | |
| 492 | +3.1 outils auto Qwen : | |
| 493 | +3.2 outils en stream : | |
| 494 | +3.3 outils auto Llama : | |
| 495 | +3.4 forcés Qwen : | |
| 496 | +3.5 forcé Llama → 400 : | |
| 497 | +3.6 tool_choice none : | |
| 498 | +3.7 parallèles : | |
| 499 | +3.8 LangChain agent : | |
| 500 | +4.1 embeddings SDK : cos=… | |
| 501 | +4.2 dimensions/base64 : | |
| 502 | +4.3 LangChain embed : | |
| 503 | +4.4 Matryoshka : | |
| 504 | +4.5 chat + embed : | |
| 505 | +4.6 mauvais type : | |
| 506 | +4.7 texte trop long : | |
| 507 | +``` | |
| new file mode 100644 | |||
| @@ -0,0 +1,507 @@ | |||
| 1 | +# Plan de test manuel — rzb serve v0.2 (#38 → #42) | ||
| 2 | + | ||
| 3 | +Ce document liste ce qu'il reste à vérifier **à la main, sur le Mac**, après les tickets #38 à #42 | ||
| 4 | +(sorties structurées, appels d'outils, embeddings). Les tests automatiques passent déjà (Linux 144, | ||
| 5 | +Mac 167) : ici, on vérifie ce qu'ils ne couvrent pas — de vrais clients, de plus gros modèles, | ||
| 6 | +d'autres familles de modèles, et la vitesse en Release. | ||
| 7 | + | ||
| 8 | +Chaque test a : la commande à lancer, **le résultat attendu**, et une case à cocher. Notez ce qui | ||
| 9 | +échoue (commande + sortie) dans la section [Rapport](#rapport) à la fin. | ||
| 10 | + | ||
| 11 | +Durée estimée : 1 h à 1 h 30, dont l'essentiel en téléchargements de modèles. | ||
| 12 | + | ||
| 13 | +--- | ||
| 14 | + | ||
| 15 | +## 0. Préparation | ||
| 16 | + | ||
| 17 | +### 0.1 Compiler en Release | ||
| 18 | + | ||
| 19 | +```bash | ||
| 20 | +cd ~/kDrive/Rickub/bots-garden/razorbill | ||
| 21 | +xcodebuild build -scheme razorbill -destination 'platform=macOS' -configuration Release \ | ||
| 22 | + -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation | ||
| 23 | +alias rzb="$PWD/.build/xcode/Build/Products/Release/rzb" | ||
| 24 | +rzb version | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +- [ ] `rzb version` affiche la version et `engines: mlx`. | ||
| 28 | + | ||
| 29 | +### 0.2 Télécharger les modèles | ||
| 30 | + | ||
| 31 | +```bash | ||
| 32 | +rzb models pull mlx-community/Qwen3-4B-4bit # ~2,3 Go — chat, outils, JSON | ||
| 33 | +rzb models pull mlx-community/Llama-3.2-3B-Instruct-4bit # ~1,8 Go — 2e famille d'outils | ||
| 34 | +rzb models pull BAAI/bge-small-en-v1.5 # déjà en cache normalement | ||
| 35 | +rzb models list | ||
| 36 | +``` | ||
| 37 | + | ||
| 38 | +Optionnel (test Matryoshka, §4.4) : un modèle d'embedding Qwen3 au format MLX, par exemple | ||
| 39 | +`mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ` (vérifiez le nom exact sur Hugging Face). | ||
| 40 | + | ||
| 41 | +### 0.3 Configuration de test | ||
| 42 | + | ||
| 43 | +Enregistrez ceci dans `/tmp/rzb-test.yaml` : | ||
| 44 | + | ||
| 45 | +```yaml | ||
| 46 | +server: | ||
| 47 | + host: 127.0.0.1 | ||
| 48 | + port: 8080 | ||
| 49 | + | ||
| 50 | +models: | ||
| 51 | + - id: qwen4b | ||
| 52 | + source: mlx-community/Qwen3-4B-4bit | ||
| 53 | + kind: chat | ||
| 54 | + - id: llama3b | ||
| 55 | + source: mlx-community/Llama-3.2-3B-Instruct-4bit | ||
| 56 | + kind: chat | ||
| 57 | + - id: embed | ||
| 58 | + source: BAAI/bge-small-en-v1.5 | ||
| 59 | + kind: embedding | ||
| 60 | + preload: true | ||
| 61 | + | ||
| 62 | +limits: | ||
| 63 | + max_loaded_models: 2 | ||
| 64 | + keep_alive: 10m | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +```bash | ||
| 68 | +rzb config validate /tmp/rzb-test.yaml | ||
| 69 | +rzb serve --config /tmp/rzb-test.yaml | ||
| 70 | +``` | ||
| 71 | + | ||
| 72 | +- [ ] `config validate` ne signale aucune erreur. | ||
| 73 | +- [ ] Le serveur démarre, affiche `serving http://127.0.0.1:8080`, et le log indique que `embed` | ||
| 74 | + est chargé au démarrage (`preload: true`). | ||
| 75 | + | ||
| 76 | +Laissez ce terminal ouvert (les logs serviront) et ouvrez-en un second pour la suite. | ||
| 77 | + | ||
| 78 | +> Pas de clé d'API dans cette config : les clients peuvent envoyer n'importe quelle valeur | ||
| 79 | +> (`api_key="x"`). Si `RZB_API_KEY` est définie dans votre shell **et** déclarée via | ||
| 80 | +> `api_key_env`, utilisez sa valeur. | ||
| 81 | + | ||
| 82 | +### 0.4 Outils côté client | ||
| 83 | + | ||
| 84 | +Les exemples Python utilisent `uv` (pas d'environnement à créer) : | ||
| 85 | + | ||
| 86 | +```bash | ||
| 87 | +uv --version # sinon : brew install uv | ||
| 88 | +``` | ||
| 89 | + | ||
| 90 | +### 0.5 Premier contact | ||
| 91 | + | ||
| 92 | +```bash | ||
| 93 | +curl -s http://127.0.0.1:8080/v1/models | python3 -m json.tool | ||
| 94 | +``` | ||
| 95 | + | ||
| 96 | +- [ ] La liste contient `qwen4b`, `llama3b` (`"kind": "chat"`) et `embed` (`"kind": "embedding"`), | ||
| 97 | + plus les modèles du cache. | ||
| 98 | + | ||
| 99 | +--- | ||
| 100 | + | ||
| 101 | +## 1. Sorties structurées — `response_format` (#39) | ||
| 102 | + | ||
| 103 | +### 1.1 `parse()` du SDK openai avec une classe Pydantic — **critère d'acceptation de #39** | ||
| 104 | + | ||
| 105 | +```bash | ||
| 106 | +uv run --with openai --with pydantic python - <<'EOF' | ||
| 107 | +from openai import OpenAI | ||
| 108 | +from pydantic import BaseModel | ||
| 109 | + | ||
| 110 | +class City(BaseModel): | ||
| 111 | + name: str | ||
| 112 | + country: str | ||
| 113 | + population: int | ||
| 114 | + landmarks: list[str] | ||
| 115 | + | ||
| 116 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 117 | +completion = client.beta.chat.completions.parse( | ||
| 118 | + model="qwen4b", | ||
| 119 | + messages=[{"role": "user", "content": "Describe Lyon, France."}], | ||
| 120 | + response_format=City, | ||
| 121 | +) | ||
| 122 | +message = completion.choices[0].message | ||
| 123 | +print("parsed :", message.parsed) | ||
| 124 | +print("raison :", (getattr(message, "reasoning_content", None) or "")[:200]) | ||
| 125 | +EOF | ||
| 126 | +``` | ||
| 127 | + | ||
| 128 | +- [ ] `parsed` est un objet `City` rempli (pas `None`), sans exception de validation. | ||
| 129 | +- [ ] Recommencez 3 fois : toujours un JSON valide. | ||
| 130 | + | ||
| 131 | +> Selon la version du SDK, `client.chat.completions.parse(...)` (sans `beta`) existe aussi : | ||
| 132 | +> testez celle que vous avez. | ||
| 133 | + | ||
| 134 | +### 1.2 Avec réflexion activée | ||
| 135 | + | ||
| 136 | +Même script, en ajoutant à l'appel `parse(...)` : | ||
| 137 | + | ||
| 138 | +```python | ||
| 139 | + extra_body={"reasoning_effort": "high"}, | ||
| 140 | +``` | ||
| 141 | + | ||
| 142 | +- [ ] `reasoning_content` contient la réflexion (texte libre, pas du JSON). | ||
| 143 | +- [ ] `parsed` reste un objet `City` valide : la contrainte ne s'applique qu'après `</think>`. | ||
| 144 | + | ||
| 145 | +### 1.3 `json_object` avec curl | ||
| 146 | + | ||
| 147 | +```bash | ||
| 148 | +curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | ||
| 149 | + "model": "qwen4b", | ||
| 150 | + "messages": [{"role": "user", "content": "Give me 3 French cheeses with their region, as JSON."}], | ||
| 151 | + "response_format": {"type": "json_object"}, | ||
| 152 | + "reasoning_effort": "none" | ||
| 153 | +}' | python3 -c 'import json,sys; c=json.load(sys.stdin)["choices"][0]["message"]["content"]; print(json.dumps(json.loads(c), indent=2, ensure_ascii=False))' | ||
| 154 | +``` | ||
| 155 | + | ||
| 156 | +- [ ] La commande affiche un objet JSON (le `json.loads` ne lève pas d'erreur). | ||
| 157 | + | ||
| 158 | +### 1.4 Streaming d'un `json_schema` | ||
| 159 | + | ||
| 160 | +```bash | ||
| 161 | +curl -sN http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | ||
| 162 | + "model": "qwen4b", "stream": true, "reasoning_effort": "none", | ||
| 163 | + "messages": [{"role": "user", "content": "List 5 planets with their diameter in km."}], | ||
| 164 | + "response_format": {"type": "json_schema", "json_schema": {"name": "planets", "strict": true, | ||
| 165 | + "schema": {"type": "object", "additionalProperties": false, "required": ["planets"], | ||
| 166 | + "properties": {"planets": {"type": "array", "items": {"type": "object", | ||
| 167 | + "additionalProperties": false, "required": ["name", "diameter_km"], | ||
| 168 | + "properties": {"name": {"type": "string"}, "diameter_km": {"type": "number"}}}}}}}} | ||
| 169 | +}' | ||
| 170 | +``` | ||
| 171 | + | ||
| 172 | +- [ ] Les lignes `data: {...}` arrivent **au fil de l'eau**, chacune avec un petit morceau de JSON | ||
| 173 | + dans `delta.content` (pas un seul bloc à la fin). | ||
| 174 | +- [ ] Le flux se termine par `finish_reason: "stop"` puis `data: [DONE]`. | ||
| 175 | +- [ ] En recollant les `content`, on obtient un JSON qui respecte le schéma. | ||
| 176 | + | ||
| 177 | +### 1.5 Schéma strict avec un mot-clé non appliqué → 400 | ||
| 178 | + | ||
| 179 | +```bash | ||
| 180 | +curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{ | ||
| 181 | + "model": "qwen4b", | ||
| 182 | + "messages": [{"role": "user", "content": "3 tags"}], | ||
| 183 | + "response_format": {"type": "json_schema", "json_schema": {"name": "tags", "strict": true, | ||
| 184 | + "schema": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}}} | ||
| 185 | +}' | ||
| 186 | +``` | ||
| 187 | + | ||
| 188 | +- [ ] Réponse **400** `{"error": {...}}` dont le message nomme `uniqueItems`. | ||
| 189 | +- [ ] Le même appel avec `"strict": false` est accepté (le mot-clé est simplement ignoré). | ||
| 190 | + | ||
| 191 | +--- | ||
| 192 | + | ||
| 193 | +## 2. Vitesse du décodage contraint (Release) | ||
| 194 | + | ||
| 195 | +Mes mesures (build **Debug**, Qwen3-0.6B) : ~90 tok/s en libre, ~49 tok/s sous contrainte. Le | ||
| 196 | +serveur ne logue pas les tok/s : ce script les calcule à partir de `usage`. | ||
| 197 | + | ||
| 198 | +```bash | ||
| 199 | +uv run --with openai python - <<'EOF' | ||
| 200 | +import time | ||
| 201 | +from openai import OpenAI | ||
| 202 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 203 | +prompt = [{"role": "user", "content": "Describe 10 European capitals: name, country, population, one fact each."}] | ||
| 204 | +schema = {"type": "json_schema", "json_schema": {"name": "capitals", "schema": { | ||
| 205 | + "type": "object", "properties": {"capitals": {"type": "array", "items": {"type": "object", | ||
| 206 | + "properties": {"name": {"type": "string"}, "country": {"type": "string"}, | ||
| 207 | + "population": {"type": "integer"}, "fact": {"type": "string"}}, | ||
| 208 | + "required": ["name", "country", "population", "fact"]}}}, "required": ["capitals"]}}} | ||
| 209 | +client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=5) # chauffe | ||
| 210 | +for label, extra in [("libre", {}), ("json_object", {"response_format": {"type": "json_object"}}), | ||
| 211 | + ("json_schema", {"response_format": schema})]: | ||
| 212 | + start = time.time() | ||
| 213 | + r = client.chat.completions.create(model="qwen4b", messages=prompt, max_tokens=800, | ||
| 214 | + extra_body={"reasoning_effort": "none"}, **extra) | ||
| 215 | + elapsed = time.time() - start | ||
| 216 | + n = r.usage.completion_tokens | ||
| 217 | + print(f"{label:12} {n:4} tokens {elapsed:5.1f} s {n / elapsed:5.1f} tok/s") | ||
| 218 | +EOF | ||
| 219 | +``` | ||
| 220 | + | ||
| 221 | +- [ ] Notez les trois débits dans le rapport. **Attendu** : le contraint reste dans le même ordre | ||
| 222 | + de grandeur que le libre (au pire ~2× plus lent). Un écart de 5× ou plus est un problème. | ||
| 223 | +- [ ] Optionnel : relancez avec `model="mlx-community/Qwen3-0.6B-4bit"` pour comparer à mes chiffres Debug. | ||
| 224 | + | ||
| 225 | +--- | ||
| 226 | + | ||
| 227 | +## 3. Appels d'outils (#40, #41) | ||
| 228 | + | ||
| 229 | +### 3.1 Aller-retour complet en `auto` avec Qwen3-4B | ||
| 230 | + | ||
| 231 | +```bash | ||
| 232 | +uv run --with openai python - <<'EOF' | ||
| 233 | +import json | ||
| 234 | +from openai import OpenAI | ||
| 235 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 236 | +MODEL = "qwen4b" | ||
| 237 | +tools = [{"type": "function", "function": { | ||
| 238 | + "name": "get_weather", "description": "Current weather for a city", | ||
| 239 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 240 | + "required": ["city"]}}}] | ||
| 241 | +messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] | ||
| 242 | + | ||
| 243 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | ||
| 244 | +msg = r.choices[0].message | ||
| 245 | +print("1) finish_reason:", r.choices[0].finish_reason) | ||
| 246 | +print(" tool_calls :", msg.tool_calls) | ||
| 247 | +assert msg.tool_calls, "aucun appel d'outil" | ||
| 248 | + | ||
| 249 | +messages.append(msg.model_dump(exclude_none=True)) | ||
| 250 | +for call in msg.tool_calls: | ||
| 251 | + args = json.loads(call.function.arguments) | ||
| 252 | + messages.append({"role": "tool", "tool_call_id": call.id, | ||
| 253 | + "content": json.dumps({"city": args["city"], "temp_c": 7, "sky": "rain"})}) | ||
| 254 | + | ||
| 255 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) | ||
| 256 | +print("2) réponse finale:", r.choices[0].message.content) | ||
| 257 | +EOF | ||
| 258 | +``` | ||
| 259 | + | ||
| 260 | +- [ ] Étape 1 : `finish_reason` vaut `tool_calls`, avec un appel `get_weather` dont les | ||
| 261 | + `arguments` sont un JSON valide (`{"city": "Lyon"}`). | ||
| 262 | +- [ ] Étape 2 : la réponse finale parle de 7 °C et de pluie à Lyon. | ||
| 263 | + | ||
| 264 | +### 3.2 Même script en streaming | ||
| 265 | + | ||
| 266 | +Remplacez le premier `create(...)` par une version `stream=True` et affichez les deltas : | ||
| 267 | + | ||
| 268 | +```python | ||
| 269 | +for chunk in client.chat.completions.create(model=MODEL, messages=messages, tools=tools, stream=True): | ||
| 270 | + if chunk.choices: | ||
| 271 | + print(chunk.choices[0].delta, chunk.choices[0].finish_reason) | ||
| 272 | +``` | ||
| 273 | + | ||
| 274 | +- [ ] Un delta contient `tool_calls` avec `index: 0`, un `id`, `type: "function"` et le nom et les | ||
| 275 | + arguments ; le dernier chunk a `finish_reason: "tool_calls"`. | ||
| 276 | + | ||
| 277 | +### 3.3 Deuxième famille (Llama 3.2) en `auto` — **critère de #40, non vérifié** | ||
| 278 | + | ||
| 279 | +Relancez le script 3.1 avec `MODEL = "llama3b"`. | ||
| 280 | + | ||
| 281 | +- [ ] `tool_calls` est rempli correctement (nom + arguments JSON), **pas** du texte brut du genre | ||
| 282 | + `{"name": "get_weather", ...}` dans `content`. | ||
| 283 | +- [ ] La réponse finale utilise le résultat de l'outil. | ||
| 284 | + | ||
| 285 | +Si vous avez un Mistral au format MLX (ex. `mlx-community/Mistral-7B-Instruct-v0.3-4bit`), même test. | ||
| 286 | + | ||
| 287 | +### 3.4 Appels forcés sur Qwen : `required` et fonction nommée | ||
| 288 | + | ||
| 289 | +Dans le script 3.1 (`MODEL = "qwen4b"`), remplacez le message par une question **sans rapport** | ||
| 290 | +avec la météo (« Raconte-moi une blague ») et ajoutez au premier appel : | ||
| 291 | + | ||
| 292 | +```python | ||
| 293 | + tool_choice="required", | ||
| 294 | +``` | ||
| 295 | + | ||
| 296 | +puis refaites avec : | ||
| 297 | + | ||
| 298 | +```python | ||
| 299 | + tool_choice={"type": "function", "function": {"name": "get_weather"}}, | ||
| 300 | +``` | ||
| 301 | + | ||
| 302 | +- [ ] Dans les deux cas, il y a **exactement un** appel `get_weather` avec des arguments valides, | ||
| 303 | + même si la question ne s'y prête pas : la grammaire l'impose. | ||
| 304 | + | ||
| 305 | +### 3.5 Appel forcé sur Llama → 400 attendu | ||
| 306 | + | ||
| 307 | +Même chose que 3.4 avec `MODEL = "llama3b"` et `tool_choice="required"`. | ||
| 308 | + | ||
| 309 | +- [ ] Erreur **400** (`openai.BadRequestError`) avec un message expliquant que la syntaxe d'appel | ||
| 310 | + de ce modèle ne permet pas de forcer un outil. C'est le comportement voulu. | ||
| 311 | +- [ ] Avec `tool_choice="auto"`, le même modèle fonctionne (cf. 3.3). | ||
| 312 | + | ||
| 313 | +### 3.6 `tool_choice: "none"` | ||
| 314 | + | ||
| 315 | +Script 3.1 avec `tool_choice="none"`. | ||
| 316 | + | ||
| 317 | +- [ ] Réponse en texte, aucun `tool_calls`, `finish_reason: "stop"`. | ||
| 318 | + | ||
| 319 | +### 3.7 Appels parallèles | ||
| 320 | + | ||
| 321 | +Ajoutez un second outil et posez une question qui demande les deux : | ||
| 322 | + | ||
| 323 | +```python | ||
| 324 | +tools.append({"type": "function", "function": { | ||
| 325 | + "name": "get_time", "description": "Current local time in a city", | ||
| 326 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | ||
| 327 | + "required": ["city"]}}}) | ||
| 328 | +messages = [{"role": "user", "content": "What's the weather and the local time in Tokyo?"}] | ||
| 329 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, | ||
| 330 | + tool_choice="required", parallel_tool_calls=True) | ||
| 331 | +print(r.choices[0].message.tool_calls) | ||
| 332 | +``` | ||
| 333 | + | ||
| 334 | +- [ ] Deux appels (`get_weather` et `get_time`), chacun avec un `id` différent. | ||
| 335 | +- [ ] Sans `parallel_tool_calls=True` : un seul appel (comportement voulu des appels forcés). | ||
| 336 | + | ||
| 337 | +### 3.8 Un vrai client agent (optionnel, mais très parlant) | ||
| 338 | + | ||
| 339 | +Par exemple LangChain : | ||
| 340 | + | ||
| 341 | +```bash | ||
| 342 | +uv run --with langchain-openai python - <<'EOF' | ||
| 343 | +from langchain_openai import ChatOpenAI | ||
| 344 | +from langchain_core.tools import tool | ||
| 345 | + | ||
| 346 | +@tool | ||
| 347 | +def add(a: int, b: int) -> int: | ||
| 348 | + """Add two integers.""" | ||
| 349 | + return a + b | ||
| 350 | + | ||
| 351 | +llm = ChatOpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x", model="qwen4b") | ||
| 352 | +msg = llm.bind_tools([add]).invoke("What is 1234 + 4321? Use the tool.") | ||
| 353 | +print(msg.tool_calls) | ||
| 354 | +EOF | ||
| 355 | +``` | ||
| 356 | + | ||
| 357 | +- [ ] `msg.tool_calls` contient un appel `add` avec `{"a": 1234, "b": 4321}`. | ||
| 358 | + | ||
| 359 | +--- | ||
| 360 | + | ||
| 361 | +## 4. Embeddings (#42) | ||
| 362 | + | ||
| 363 | +### 4.1 SDK openai | ||
| 364 | + | ||
| 365 | +```bash | ||
| 366 | +uv run --with openai --with numpy python - <<'EOF' | ||
| 367 | +import numpy as np | ||
| 368 | +from openai import OpenAI | ||
| 369 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | ||
| 370 | +texts = ["The cat sits on the mat.", "A feline is resting on a rug.", "Stock markets fell sharply today."] | ||
| 371 | +for model in ["embed", "BAAI/bge-small-en-v1.5"]: | ||
| 372 | + r = client.embeddings.create(model=model, input=texts) | ||
| 373 | + v = np.array([d.embedding for d in r.data]) | ||
| 374 | + print(model, v.shape, "usage:", r.usage) | ||
| 375 | + print(" cos(chat, félin) =", round(float(v[0] @ v[1]), 4), " cos(chat, bourse) =", round(float(v[0] @ v[2]), 4)) | ||
| 376 | +EOF | ||
| 377 | +``` | ||
| 378 | + | ||
| 379 | +- [ ] Forme `(3, 384)` pour les deux noms (alias de config et id Hugging Face). | ||
| 380 | +- [ ] cos(chat, félin) ≈ **0,755**, cos(chat, bourse) ≈ **0,324** (valeurs de sentence-transformers). | ||
| 381 | +- [ ] `usage.prompt_tokens` > 0. | ||
| 382 | + | ||
| 383 | +### 4.2 `dimensions` et `encoding_format: base64` | ||
| 384 | + | ||
| 385 | +```bash | ||
| 386 | +curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | ||
| 387 | + -d '{"model": "embed", "input": "bonjour", "dimensions": 64}' \ | ||
| 388 | + | python3 -c 'import json,sys; e=json.load(sys.stdin)["data"][0]["embedding"]; print(len(e), sum(x*x for x in e))' | ||
| 389 | + | ||
| 390 | +curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | ||
| 391 | + -d '{"model": "embed", "input": "bonjour", "encoding_format": "base64"}' \ | ||
| 392 | + | python3 -c 'import json,sys,base64,struct; b=base64.b64decode(json.load(sys.stdin)["data"][0]["embedding"]); print(len(b)//4, struct.unpack("<3f", b[:12]))' | ||
| 393 | +``` | ||
| 394 | + | ||
| 395 | +- [ ] Premier appel : `64` et une norme au carré ≈ `1.0` (vecteur tronqué puis renormalisé). | ||
| 396 | +- [ ] Second appel : `384` et trois nombres flottants plausibles (entre -1 et 1). | ||
| 397 | +- [ ] `"dimensions": 1000` → **400** qui indique la dimension native (384). | ||
| 398 | + | ||
| 399 | +> Le SDK openai demande lui-même `base64` par défaut quand on n'impose rien : le test 4.1 couvre | ||
| 400 | +> donc déjà ce chemin côté SDK. | ||
| 401 | + | ||
| 402 | +### 4.3 LangChain `OpenAIEmbeddings` | ||
| 403 | + | ||
| 404 | +```bash | ||
| 405 | +uv run --with langchain-openai python - <<'EOF' | ||
| 406 | +from langchain_openai import OpenAIEmbeddings | ||
| 407 | +emb = OpenAIEmbeddings(base_url="http://127.0.0.1:8080/v1", api_key="x", model="embed", | ||
| 408 | + check_embedding_ctx_length=False) | ||
| 409 | +v = emb.embed_documents(["hello world", "bonjour le monde"]) | ||
| 410 | +print(len(v), len(v[0])) | ||
| 411 | +print(len(emb.embed_query("hi"))) | ||
| 412 | +EOF | ||
| 413 | +``` | ||
| 414 | + | ||
| 415 | +- [ ] `2 384` puis `384`. | ||
| 416 | +- [ ] Sans `check_embedding_ctx_length=False` : **400** « token arrays are not supported yet ». | ||
| 417 | + C'est une limite connue (LangChain envoie alors des tokens tiktoken) ; dites-moi si vous | ||
| 418 | + voulez qu'elle soit levée. | ||
| 419 | + | ||
| 420 | +### 4.4 Modèle Matryoshka (optionnel) | ||
| 421 | + | ||
| 422 | +Ajoutez dans `/tmp/rzb-test.yaml`, puis redémarrez le serveur : | ||
| 423 | + | ||
| 424 | +```yaml | ||
| 425 | + - id: qembed | ||
| 426 | + source: mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ # nom exact à vérifier | ||
| 427 | + kind: embedding | ||
| 428 | +``` | ||
| 429 | + | ||
| 430 | +Relancez le script 4.1 avec `model="qembed"`, puis avec `dimensions=256` passé à `create(...)`. | ||
| 431 | + | ||
| 432 | +- [ ] Le modèle se charge (sinon, notez l'erreur exacte : ce modèle n'a jamais été essayé). | ||
| 433 | +- [ ] cos(chat, félin) > cos(chat, bourse), en pleine dimension comme en 256. | ||
| 434 | + | ||
| 435 | +### 4.5 Chat et embedding chargés ensemble | ||
| 436 | + | ||
| 437 | +Avec `max_loaded_models: 2` : faites un appel de chat sur `qwen4b`, puis un embedding sur `embed`, | ||
| 438 | +puis de nouveau un chat. | ||
| 439 | + | ||
| 440 | +- [ ] Les logs du serveur ne montrent **aucun** `unloaded` entre les appels ; le second chat | ||
| 441 | + répond tout de suite (pas de rechargement). | ||
| 442 | + | ||
| 443 | +### 4.6 Mauvais type de modèle | ||
| 444 | + | ||
| 445 | +```bash | ||
| 446 | +curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' \ | ||
| 447 | + -d '{"model": "qwen4b", "input": "x"}' | ||
| 448 | +curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' \ | ||
| 449 | + -d '{"model": "embed", "messages": [{"role": "user", "content": "hi"}]}' | ||
| 450 | +``` | ||
| 451 | + | ||
| 452 | +- [ ] Les deux renvoient une erreur JSON claire (400) qui dit que le modèle n'est pas du bon type, | ||
| 453 | + sans planter ni charger un modèle pour rien. | ||
| 454 | + | ||
| 455 | +### 4.7 Texte trop long | ||
| 456 | + | ||
| 457 | +```bash | ||
| 458 | +python3 -c 'import json; print(json.dumps({"model": "embed", "input": ["court", "mot " * 3000]}))' \ | ||
| 459 | + | curl -s http://127.0.0.1:8080/v1/embeddings -H 'Content-Type: application/json' -d @- | ||
| 460 | +``` | ||
| 461 | + | ||
| 462 | +- [ ] **400** qui désigne `input[1]` et la limite du modèle (512 tokens pour bge-small). | ||
| 463 | + | ||
| 464 | +--- | ||
| 465 | + | ||
| 466 | +## 5. Limites connues (pas des bugs) | ||
| 467 | + | ||
| 468 | +- `/v1/models` affiche `"kind": "chat"` pour un modèle d'embedding **non déclaré** présent dans le | ||
| 469 | + cache (le cache ne connaît pas le type). Les modèles déclarés avec `kind:` sont justes. | ||
| 470 | +- Pas d'option de troncature des textes trop longs : 400 (cf. 4.7). | ||
| 471 | +- `input` sous forme de tokens (listes d'entiers) refusé (cf. 4.3). | ||
| 472 | +- Les préfixes d'instruction (`search_query:`, `Instruct: …`) sont à ajouter côté client. | ||
| 473 | +- Appels d'outils **forcés** (`required`, fonction nommée, outil `strict`) : uniquement pour les | ||
| 474 | + modèles à syntaxe `<tool_call>` JSON (Qwen, Hermes). Les autres familles → 400 (cf. 3.5). | ||
| 475 | +- Les grammaires sont recompilées à chaque requête (~0,2 s), la version de XGrammar embarquée ne | ||
| 476 | + permettant pas de les mettre en cache. | ||
| 477 | + | ||
| 478 | +--- | ||
| 479 | + | ||
| 480 | +## Rapport | ||
| 481 | + | ||
| 482 | +Copiez ce bloc et remplissez-le ; envoyez-moi les lignes en ❌ avec la commande et la sortie. | ||
| 483 | + | ||
| 484 | +```text | ||
| 485 | +0. Préparation : ✅ / ❌ | ||
| 486 | +1.1 parse() Pydantic : | ||
| 487 | +1.2 + reasoning : | ||
| 488 | +1.3 json_object : | ||
| 489 | +1.4 json_schema stream : | ||
| 490 | +1.5 uniqueItems → 400 : | ||
| 491 | +2. débits (tok/s) : libre=… json_object=… json_schema=… | ||
| 492 | +3.1 outils auto Qwen : | ||
| 493 | +3.2 outils en stream : | ||
| 494 | +3.3 outils auto Llama : | ||
| 495 | +3.4 forcés Qwen : | ||
| 496 | +3.5 forcé Llama → 400 : | ||
| 497 | +3.6 tool_choice none : | ||
| 498 | +3.7 parallèles : | ||
| 499 | +3.8 LangChain agent : | ||
| 500 | +4.1 embeddings SDK : cos=… | ||
| 501 | +4.2 dimensions/base64 : | ||
| 502 | +4.3 LangChain embed : | ||
| 503 | +4.4 Matryoshka : | ||
| 504 | +4.5 chat + embed : | ||
| 505 | +4.6 mauvais type : | ||
| 506 | +4.7 texte trop long : | ||
| 507 | +``` | ||