| @@ -118,6 +118,7 @@ completion = client.beta.chat.completions.parse( |
| 118 | model="qwen4b", | 118 | model="qwen4b", |
| 119 | messages=[{"role": "user", "content": "Describe Lyon, France."}], | 119 | messages=[{"role": "user", "content": "Describe Lyon, France."}], |
| 120 | response_format=City, | 120 | response_format=City, |
| | 121 | + extra_body={"reasoning_effort": "high"}, |
| 121 | ) | 122 | ) |
| 122 | message = completion.choices[0].message | 123 | message = completion.choices[0].message |
| 123 | print("parsed :", message.parsed) | 124 | print("parsed :", message.parsed) |
| @@ -133,10 +134,28 @@ EOF |
| 133 | | 134 | |
| 134 | ### 1.2 Avec réflexion activée | 135 | ### 1.2 Avec réflexion activée |
| 135 | | 136 | |
| 136 | -Même script, en ajoutant à l'appel `parse(...)` : | 137 | +```bash |
| | 138 | +uv run --with openai --with pydantic python - <<'EOF' |
| | 139 | +from openai import OpenAI |
| | 140 | +from pydantic import BaseModel |
| | 141 | + |
| | 142 | +class City(BaseModel): |
| | 143 | + name: str |
| | 144 | + country: str |
| | 145 | + population: int |
| | 146 | + landmarks: list[str] |
| 137 | | 147 | |
| 138 | -```python | 148 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 149 | +completion = client.beta.chat.completions.parse( |
| | 150 | + model="qwen4b", |
| | 151 | + messages=[{"role": "user", "content": "Describe Lyon, France."}], |
| | 152 | + response_format=City, |
| 139 | extra_body={"reasoning_effort": "high"}, | 153 | extra_body={"reasoning_effort": "high"}, |
| | 154 | +) |
| | 155 | +message = completion.choices[0].message |
| | 156 | +print("parsed :", message.parsed) |
| | 157 | +print("raison :", (getattr(message, "reasoning_content", None) or "")[:500]) |
| | 158 | +EOF |
| 140 | ``` | 159 | ``` |
| 141 | | 160 | |
| 142 | - [ ] `reasoning_content` contient la réflexion (texte libre, pas du JSON). | 161 | - [ ] `reasoning_content` contient la réflexion (texte libre, pas du JSON). |
| @@ -261,78 +280,181 @@ EOF |
| 261 | `arguments` sont un JSON valide (`{"city": "Lyon"}`). | 280 | `arguments` sont un JSON valide (`{"city": "Lyon"}`). |
| 262 | - [ ] Étape 2 : la réponse finale parle de 7 °C et de pluie à Lyon. | 281 | - [ ] Étape 2 : la réponse finale parle de 7 °C et de pluie à Lyon. |
| 263 | | 282 | |
| 264 | -### 3.2 Même script en streaming | 283 | +### 3.2 Appel d'outil en streaming |
| 265 | | 284 | |
| 266 | -Remplacez le premier `create(...)` par une version `stream=True` et affichez les deltas : | 285 | +```bash |
| | 286 | +uv run --with openai python - <<'EOF' |
| | 287 | +from openai import OpenAI |
| | 288 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 289 | +MODEL = "qwen4b" |
| | 290 | +tools = [{"type": "function", "function": { |
| | 291 | + "name": "get_weather", "description": "Current weather for a city", |
| | 292 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, |
| | 293 | + "required": ["city"]}}}] |
| | 294 | +messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] |
| 267 | | 295 | |
| 268 | -```python | 296 | +stream = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, stream=True) |
| 269 | -for chunk in client.chat.completions.create(model=MODEL, messages=messages, tools=tools, stream=True): | 297 | +for chunk in stream: |
| 270 | if chunk.choices: | 298 | if chunk.choices: |
| 271 | - print(chunk.choices[0].delta, chunk.choices[0].finish_reason) | 299 | + choice = chunk.choices[0] |
| | 300 | + print(choice.delta.model_dump(exclude_none=True), "| finish:", choice.finish_reason) |
| | 301 | +EOF |
| 272 | ``` | 302 | ``` |
| 273 | | 303 | |
| 274 | - [ ] Un delta contient `tool_calls` avec `index: 0`, un `id`, `type: "function"` et le nom et les | 304 | - [ ] 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"`. | 305 | + arguments ; le dernier chunk a `finish: tool_calls`. |
| 276 | | 306 | |
| 277 | ### 3.3 Deuxième famille (Llama 3.2) en `auto` — **critère de #40, non vérifié** | 307 | ### 3.3 Deuxième famille (Llama 3.2) en `auto` — **critère de #40, non vérifié** |
| 278 | | 308 | |
| 279 | -Relancez le script 3.1 avec `MODEL = "llama3b"`. | 309 | +```bash |
| | 310 | +uv run --with openai python - <<'EOF' |
| | 311 | +import json |
| | 312 | +from openai import OpenAI |
| | 313 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 314 | +MODEL = "llama3b" |
| | 315 | +tools = [{"type": "function", "function": { |
| | 316 | + "name": "get_weather", "description": "Current weather for a city", |
| | 317 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, |
| | 318 | + "required": ["city"]}}}] |
| | 319 | +messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] |
| | 320 | + |
| | 321 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) |
| | 322 | +msg = r.choices[0].message |
| | 323 | +print("1) finish_reason:", r.choices[0].finish_reason) |
| | 324 | +print(" tool_calls :", msg.tool_calls) |
| | 325 | +print(" content :", msg.content) |
| | 326 | +assert msg.tool_calls, "aucun appel d'outil" |
| | 327 | + |
| | 328 | +messages.append(msg.model_dump(exclude_none=True)) |
| | 329 | +for call in msg.tool_calls: |
| | 330 | + args = json.loads(call.function.arguments) |
| | 331 | + messages.append({"role": "tool", "tool_call_id": call.id, |
| | 332 | + "content": json.dumps({"city": args["city"], "temp_c": 7, "sky": "rain"})}) |
| | 333 | + |
| | 334 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools) |
| | 335 | +print("2) réponse finale:", r.choices[0].message.content) |
| | 336 | +EOF |
| | 337 | +``` |
| 280 | | 338 | |
| 281 | - [ ] `tool_calls` est rempli correctement (nom + arguments JSON), **pas** du texte brut du genre | 339 | - [ ] `tool_calls` est rempli correctement (nom + arguments JSON), **pas** du texte brut du genre |
| 282 | `{"name": "get_weather", ...}` dans `content`. | 340 | `{"name": "get_weather", ...}` dans `content`. |
| 283 | - [ ] La réponse finale utilise le résultat de l'outil. | 341 | - [ ] La réponse finale utilise le résultat de l'outil. |
| 284 | | 342 | |
| 285 | -Si vous avez un Mistral au format MLX (ex. `mlx-community/Mistral-7B-Instruct-v0.3-4bit`), même test. | 343 | +Si vous avez un Mistral au format MLX (ex. `mlx-community/Mistral-7B-Instruct-v0.3-4bit`), relancez |
| | 344 | +ce script en remplaçant `MODEL = "llama3b"` par l'id du modèle. |
| 286 | | 345 | |
| 287 | ### 3.4 Appels forcés sur Qwen : `required` et fonction nommée | 346 | ### 3.4 Appels forcés sur Qwen : `required` et fonction nommée |
| 288 | | 347 | |
| 289 | -Dans le script 3.1 (`MODEL = "qwen4b"`), remplacez le message par une question **sans rapport** | 348 | +La question n'a **rien à voir** avec la météo : seule la grammaire peut produire l'appel. |
| 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 | | 349 | |
| 298 | -```python | 350 | +```bash |
| 299 | - tool_choice={"type": "function", "function": {"name": "get_weather"}}, | 351 | +uv run --with openai python - <<'EOF' |
| | 352 | +from openai import OpenAI |
| | 353 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 354 | +MODEL = "qwen4b" |
| | 355 | +tools = [{"type": "function", "function": { |
| | 356 | + "name": "get_weather", "description": "Current weather for a city", |
| | 357 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, |
| | 358 | + "required": ["city"]}}}] |
| | 359 | +messages = [{"role": "user", "content": "Tell me a joke."}] |
| | 360 | + |
| | 361 | +for label, choice in [("required", "required"), |
| | 362 | + ("nommée", {"type": "function", "function": {"name": "get_weather"}})]: |
| | 363 | + r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, |
| | 364 | + tool_choice=choice) |
| | 365 | + calls = r.choices[0].message.tool_calls or [] |
| | 366 | + print(f"{label:9} finish={r.choices[0].finish_reason} {len(calls)} appel(s)") |
| | 367 | + for call in calls: |
| | 368 | + print(" ", call.function.name, call.function.arguments) |
| | 369 | +EOF |
| 300 | ``` | 370 | ``` |
| 301 | | 371 | |
| 302 | -- [ ] Dans les deux cas, il y a **exactement un** appel `get_weather` avec des arguments valides, | 372 | +- [ ] Pour `required` comme pour la fonction nommée : `finish=tool_calls` et **exactement un** |
| 303 | - même si la question ne s'y prête pas : la grammaire l'impose. | 373 | + appel `get_weather` avec des arguments JSON valides. |
| 304 | | 374 | |
| 305 | ### 3.5 Appel forcé sur Llama → 400 attendu | 375 | ### 3.5 Appel forcé sur Llama → 400 attendu |
| 306 | | 376 | |
| 307 | -Même chose que 3.4 avec `MODEL = "llama3b"` et `tool_choice="required"`. | 377 | +```bash |
| | 378 | +uv run --with openai python - <<'EOF' |
| | 379 | +import openai |
| | 380 | +from openai import OpenAI |
| | 381 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 382 | +MODEL = "llama3b" |
| | 383 | +tools = [{"type": "function", "function": { |
| | 384 | + "name": "get_weather", "description": "Current weather for a city", |
| | 385 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, |
| | 386 | + "required": ["city"]}}}] |
| | 387 | +messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] |
| | 388 | + |
| | 389 | +for choice in ["required", "auto"]: |
| | 390 | + try: |
| | 391 | + r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, |
| | 392 | + tool_choice=choice) |
| | 393 | + print(f"{choice:8} OK finish={r.choices[0].finish_reason}", |
| | 394 | + r.choices[0].message.tool_calls) |
| | 395 | + except openai.BadRequestError as error: |
| | 396 | + print(f"{choice:8} 400 ", error.body) |
| | 397 | +EOF |
| | 398 | +``` |
| 308 | | 399 | |
| 309 | -- [ ] Erreur **400** (`openai.BadRequestError`) avec un message expliquant que la syntaxe d'appel | 400 | +- [ ] `required` : **400** avec un message expliquant que la syntaxe d'appel de ce modèle ne permet |
| 310 | - de ce modèle ne permet pas de forcer un outil. C'est le comportement voulu. | 401 | + pas de forcer un outil. C'est le comportement voulu. |
| 311 | -- [ ] Avec `tool_choice="auto"`, le même modèle fonctionne (cf. 3.3). | 402 | +- [ ] `auto` : OK, avec un appel `get_weather` (cf. 3.3). |
| 312 | | 403 | |
| 313 | ### 3.6 `tool_choice: "none"` | 404 | ### 3.6 `tool_choice: "none"` |
| 314 | | 405 | |
| 315 | -Script 3.1 avec `tool_choice="none"`. | 406 | +```bash |
| | 407 | +uv run --with openai python - <<'EOF' |
| | 408 | +from openai import OpenAI |
| | 409 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 410 | +MODEL = "qwen4b" |
| | 411 | +tools = [{"type": "function", "function": { |
| | 412 | + "name": "get_weather", "description": "Current weather for a city", |
| | 413 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, |
| | 414 | + "required": ["city"]}}}] |
| | 415 | +messages = [{"role": "user", "content": "What's the weather like in Lyon right now?"}] |
| | 416 | + |
| | 417 | +r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, tool_choice="none") |
| | 418 | +msg = r.choices[0].message |
| | 419 | +print("finish_reason:", r.choices[0].finish_reason) |
| | 420 | +print("tool_calls :", msg.tool_calls) |
| | 421 | +print("content :", msg.content) |
| | 422 | +EOF |
| | 423 | +``` |
| 316 | | 424 | |
| 317 | -- [ ] Réponse en texte, aucun `tool_calls`, `finish_reason: "stop"`. | 425 | +- [ ] `finish_reason: stop`, `tool_calls: None`, et une réponse en texte. |
| 318 | | 426 | |
| 319 | ### 3.7 Appels parallèles | 427 | ### 3.7 Appels parallèles |
| 320 | | 428 | |
| 321 | -Ajoutez un second outil et posez une question qui demande les deux : | 429 | +```bash |
| 322 | - | 430 | +uv run --with openai python - <<'EOF' |
| 323 | -```python | 431 | +from openai import OpenAI |
| 324 | -tools.append({"type": "function", "function": { | 432 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| 325 | - "name": "get_time", "description": "Current local time in a city", | 433 | +MODEL = "qwen4b" |
| 326 | - "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, | 434 | +tools = [ |
| 327 | - "required": ["city"]}}}) | 435 | + {"type": "function", "function": { |
| | 436 | + "name": "get_weather", "description": "Current weather for a city", |
| | 437 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, |
| | 438 | + "required": ["city"]}}}, |
| | 439 | + {"type": "function", "function": { |
| | 440 | + "name": "get_time", "description": "Current local time in a city", |
| | 441 | + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, |
| | 442 | + "required": ["city"]}}}, |
| | 443 | +] |
| 328 | messages = [{"role": "user", "content": "What's the weather and the local time in Tokyo?"}] | 444 | 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, | 445 | + |
| 330 | - tool_choice="required", parallel_tool_calls=True) | 446 | +for parallel in [True, False]: |
| 331 | -print(r.choices[0].message.tool_calls) | 447 | + r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, |
| | 448 | + tool_choice="required", parallel_tool_calls=parallel) |
| | 449 | + calls = r.choices[0].message.tool_calls or [] |
| | 450 | + print(f"parallel_tool_calls={parallel}: {len(calls)} appel(s)") |
| | 451 | + for call in calls: |
| | 452 | + print(" ", call.id, call.function.name, call.function.arguments) |
| | 453 | +EOF |
| 332 | ``` | 454 | ``` |
| 333 | | 455 | |
| 334 | -- [ ] Deux appels (`get_weather` et `get_time`), chacun avec un `id` différent. | 456 | +- [ ] `parallel_tool_calls=True` : deux appels (`get_weather` et `get_time`), avec des `id` différents. |
| 335 | -- [ ] Sans `parallel_tool_calls=True` : un seul appel (comportement voulu des appels forcés). | 457 | +- [ ] `parallel_tool_calls=False` : un seul appel (comportement voulu des appels forcés). |
| 336 | | 458 | |
| 337 | ### 3.8 Un vrai client agent (optionnel, mais très parlant) | 459 | ### 3.8 Un vrai client agent (optionnel, mais très parlant) |
| 338 | | 460 | |
| @@ -368,7 +490,7 @@ import numpy as np |
| 368 | from openai import OpenAI | 490 | from openai import OpenAI |
| 369 | client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") | 491 | 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."] | 492 | 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"]: | 493 | +for model in ["qembed", "BAAI/bge-small-en-v1.5"]: |
| 372 | r = client.embeddings.create(model=model, input=texts) | 494 | r = client.embeddings.create(model=model, input=texts) |
| 373 | v = np.array([d.embedding for d in r.data]) | 495 | v = np.array([d.embedding for d in r.data]) |
| 374 | print(model, v.shape, "usage:", r.usage) | 496 | print(model, v.shape, "usage:", r.usage) |
| @@ -419,7 +541,8 @@ EOF |
| 419 | | 541 | |
| 420 | ### 4.4 Modèle Matryoshka (optionnel) | 542 | ### 4.4 Modèle Matryoshka (optionnel) |
| 421 | | 543 | |
| 422 | -Ajoutez dans `/tmp/rzb-test.yaml`, puis redémarrez le serveur : | 544 | +Ajoutez ce modèle sous `models:` dans `/tmp/rzb-test.yaml`, puis redémarrez le serveur |
| | 545 | +(Ctrl-C, puis `rzb serve --config /tmp/rzb-test.yaml`) : |
| 423 | | 546 | |
| 424 | ```yaml | 547 | ```yaml |
| 425 | - id: qembed | 548 | - id: qembed |
| @@ -427,18 +550,57 @@ Ajoutez dans `/tmp/rzb-test.yaml`, puis redémarrez le serveur : |
| 427 | kind: embedding | 550 | kind: embedding |
| 428 | ``` | 551 | ``` |
| 429 | | 552 | |
| 430 | -Relancez le script 4.1 avec `model="qembed"`, puis avec `dimensions=256` passé à `create(...)`. | 553 | +```bash |
| | 554 | +uv run --with openai --with numpy python - <<'EOF' |
| | 555 | +import numpy as np |
| | 556 | +from openai import OpenAI |
| | 557 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 558 | +texts = ["The cat sits on the mat.", "A feline is resting on a rug.", "Stock markets fell sharply today."] |
| | 559 | +for dimensions in [None, 256]: |
| | 560 | + extra = {} if dimensions is None else {"dimensions": dimensions} |
| | 561 | + r = client.embeddings.create(model="qembed", input=texts, **extra) |
| | 562 | + v = np.array([d.embedding for d in r.data]) |
| | 563 | + print(f"dimensions={dimensions}: forme {v.shape}, normes {np.round(np.linalg.norm(v, axis=1), 4)}") |
| | 564 | + print(" cos(chat, félin) =", round(float(v[0] @ v[1]), 4), |
| | 565 | + " cos(chat, bourse) =", round(float(v[0] @ v[2]), 4)) |
| | 566 | +EOF |
| | 567 | +``` |
| 431 | | 568 | |
| 432 | - [ ] Le modèle se charge (sinon, notez l'erreur exacte : ce modèle n'a jamais été essayé). | 569 | - [ ] Le modèle se charge (sinon, notez l'erreur exacte : ce modèle n'a jamais été essayé). |
| | 570 | +- [ ] Forme `(3, 1024)` puis `(3, 256)`, normes ≈ 1. |
| 433 | - [ ] cos(chat, félin) > cos(chat, bourse), en pleine dimension comme en 256. | 571 | - [ ] cos(chat, félin) > cos(chat, bourse), en pleine dimension comme en 256. |
| 434 | | 572 | |
| 435 | ### 4.5 Chat et embedding chargés ensemble | 573 | ### 4.5 Chat et embedding chargés ensemble |
| 436 | | 574 | |
| 437 | -Avec `max_loaded_models: 2` : faites un appel de chat sur `qwen4b`, puis un embedding sur `embed`, | 575 | +Avec `max_loaded_models: 2`, en gardant un œil sur les logs du serveur : |
| 438 | -puis de nouveau un chat. | 576 | + |
| | 577 | +```bash |
| | 578 | +uv run --with openai python - <<'EOF' |
| | 579 | +import time |
| | 580 | +from openai import OpenAI |
| | 581 | +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="x") |
| | 582 | + |
| | 583 | +def chat(label): |
| | 584 | + start = time.time() |
| | 585 | + r = client.chat.completions.create(model="qwen4b", max_tokens=20, |
| | 586 | + messages=[{"role": "user", "content": "Say hello."}], |
| | 587 | + extra_body={"reasoning_effort": "none"}) |
| | 588 | + print(f"{label:10} {time.time() - start:5.2f} s {r.choices[0].message.content!r}") |
| | 589 | + |
| | 590 | +def embed(label): |
| | 591 | + start = time.time() |
| | 592 | + r = client.embeddings.create(model="embed", input=["hello"]) |
| | 593 | + print(f"{label:10} {time.time() - start:5.2f} s {len(r.data[0].embedding)} dimensions") |
| | 594 | + |
| | 595 | +chat("chat 1") # charge qwen4b si besoin |
| | 596 | +embed("embed") # embed est déjà chargé (preload) |
| | 597 | +chat("chat 2") # doit être immédiat : qwen4b est resté chargé |
| | 598 | +embed("embed 2") |
| | 599 | +EOF |
| | 600 | +``` |
| 439 | | 601 | |
| 440 | -- [ ] Les logs du serveur ne montrent **aucun** `unloaded` entre les appels ; le second chat | 602 | +- [ ] `chat 2` et `embed 2` répondent en une fraction de seconde (pas de rechargement). |
| 441 | - répond tout de suite (pas de rechargement). | 603 | +- [ ] Les logs du serveur ne montrent **aucun** `unloaded` pendant le script. |
| 442 | | 604 | |
| 443 | ### 4.6 Mauvais type de modèle | 605 | ### 4.6 Mauvais type de modèle |
| 444 | | 606 | |