test_chat.py 31.4 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
# imports for structured outputs tests
5
import json
6
from collections import defaultdict
7
8
9
10

import jsonschema
import openai  # use the official client for correctness check
import pytest
11
import pytest_asyncio
12
import regex as re
13
import requests
14
import torch
15
from openai import BadRequestError
16

17
from tests.utils import RemoteOpenAIServer
18
19
20
21
22
from vllm.entrypoints.openai.chat_completion.protocol import (
    ChatCompletionRequest,
)
from vllm.sampling_params import SamplingParams

23
24
25
26
# any model with a chat template should work here
MODEL_NAME = "HuggingFaceH4/zephyr-7b-beta"


27
28
29
30
31
32
33
34
@pytest.fixture(scope="module")
def zephyr_lora_files():
    """Download zephyr LoRA files once per test session."""
    from huggingface_hub import snapshot_download

    return snapshot_download(repo_id="typeof/zephyr-7b-beta-lora")


35
@pytest.fixture(scope="module")
36
def server(zephyr_lora_files):
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
    args = [
        # use half precision for speed and memory savings in CI environment
        "--dtype",
        "bfloat16",
        "--max-model-len",
        "8192",
        "--enforce-eager",
        # lora config below
        "--enable-lora",
        "--lora-modules",
        f"zephyr-lora={zephyr_lora_files}",
        "--max-lora-rank",
        "64",
        "--max-cpu-loras",
        "2",
        "--max-num-seqs",
        "128",
    ]

    with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
57
        yield remote_server
58
59


60
61
62
63
@pytest_asyncio.fixture
async def client(server):
    async with server.get_async_client() as async_client:
        yield async_client
64
65
66
67
68
69


@pytest.mark.asyncio
@pytest.mark.parametrize(
    # first test base model, then test loras
    "model_name",
70
    [MODEL_NAME, "zephyr-lora"],
71
72
)
async def test_no_logprobs_chat(client: openai.AsyncOpenAI, model_name: str):
73
74
75
76
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "what is 1+1?"},
    ]
77

78
79
80
81
82
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=5,
        temperature=0.0,
83
84
        logprobs=False,
    )
85
86
87
88
89
90
91
92
93
94
95
96

    choice = chat_completion.choices[0]
    assert choice.logprobs is None


@pytest.mark.asyncio
@pytest.mark.parametrize(
    # just test 1 lora hereafter
    "model_name",
    [MODEL_NAME, "zephyr-lora"],
)
async def test_zero_logprobs_chat(client: openai.AsyncOpenAI, model_name: str):
97
98
99
100
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "what is 1+1?"},
    ]
101

102
103
104
105
106
107
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=5,
        temperature=0.0,
        logprobs=True,
108
109
        top_logprobs=0,
    )
110
111
112
113
114
115
116
117
118
119
120
121
122

    choice = chat_completion.choices[0]
    assert choice.logprobs is not None
    assert choice.logprobs.content is not None
    assert len(choice.logprobs.content[0].top_logprobs) == 0


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME, "zephyr-lora"],
)
async def test_some_logprobs_chat(client: openai.AsyncOpenAI, model_name: str):
123
124
125
126
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "what is 1+1?"},
    ]
127

128
129
130
131
132
133
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=5,
        temperature=0.0,
        logprobs=True,
134
135
        top_logprobs=5,
    )
136
137
138
139
140
141
142
143
144
145
146
147

    choice = chat_completion.choices[0]
    assert choice.logprobs is not None
    assert choice.logprobs.content is not None
    assert len(choice.logprobs.content[0].top_logprobs) == 5


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME, "zephyr-lora"],
)
148
149
150
151
152
async def test_too_many_chat_logprobs(client: openai.AsyncOpenAI, model_name: str):
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "what is 1+1?"},
    ]
153
154
155

    # Default max_logprobs is 20, so this should raise an error
    with pytest.raises((openai.BadRequestError, openai.APIError)):
156
157
158
159
160
161
162
163
        stream = await client.chat.completions.create(
            model=model_name,
            messages=messages,
            max_completion_tokens=10,
            logprobs=True,
            top_logprobs=21,
            stream=True,
        )
164
165
166
167
        async for chunk in stream:
            ...

    with pytest.raises(openai.BadRequestError):
168
169
170
171
172
173
174
175
        await client.chat.completions.create(
            model=model_name,
            messages=messages,
            max_completion_tokens=10,
            logprobs=True,
            top_logprobs=30,
            stream=False,
        )
176
177

    # the server should still work afterwards
178
    chat_completion = await client.chat.completions.create(
179
180
        model=model_name, messages=messages, max_completion_tokens=10, stream=False
    )
181
182
183
184
    message = chat_completion.choices[0].message
    assert message.content is not None and len(message.content) >= 0


185
186
187
188
189
@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name, prompt_logprobs",
    [(MODEL_NAME, 1), (MODEL_NAME, 0), (MODEL_NAME, -1), (MODEL_NAME, None)],
)
190
async def test_prompt_logprobs_chat(
191
    client: openai.AsyncOpenAI, model_name: str, prompt_logprobs: int | None
192
):
193
    params: dict = {
194
195
196
197
198
199
200
201
202
203
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Who won the world series in 2020?"},
            {
                "role": "assistant",
                "content": "The Los Angeles Dodgers won the World Series in 2020.",
            },
            {"role": "user", "content": "Where was it played?"},
        ],
        "model": model_name,
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    }

    if prompt_logprobs is not None:
        params["extra_body"] = {"prompt_logprobs": prompt_logprobs}

    if prompt_logprobs is not None and prompt_logprobs < 0:
        with pytest.raises(BadRequestError):
            await client.chat.completions.create(**params)
    else:
        completion = await client.chat.completions.create(**params)
        if prompt_logprobs is not None:
            assert completion.prompt_logprobs is not None
            assert len(completion.prompt_logprobs) > 0
        else:
            assert completion.prompt_logprobs is None


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME],
)
226
227
228
async def test_more_than_one_prompt_logprobs_chat(
    client: openai.AsyncOpenAI, model_name: str
):
229
    params: dict = {
230
231
232
233
234
235
236
237
238
239
240
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Who won the world series in 2020?"},
            {
                "role": "assistant",
                "content": "The Los Angeles Dodgers won the World Series in 2020.",
            },
            {"role": "user", "content": "Where was it played?"},
        ],
        "model": model_name,
        "extra_body": {"prompt_logprobs": 1},
241
242
243
244
245
246
247
248
249
250
251
    }

    completion_1 = await client.chat.completions.create(**params)

    params["extra_body"] = {"prompt_logprobs": 2}
    completion_2 = await client.chat.completions.create(**params)

    assert len(completion_1.prompt_logprobs[3]) == 1
    assert len(completion_2.prompt_logprobs[3]) == 2


252
253
254
255
256
@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME, "zephyr-lora"],
)
257
258
259
260
261
async def test_single_chat_session(client: openai.AsyncOpenAI, model_name: str):
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "what is 1+1?"},
    ]
262
    # test single completion
263
264
265
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
266
        max_completion_tokens=5,
267
        logprobs=True,
268
269
        top_logprobs=5,
    )
270
271
272
273
    assert chat_completion.id is not None
    assert len(chat_completion.choices) == 1

    choice = chat_completion.choices[0]
274

275
276
    assert choice.finish_reason == "length"
    assert chat_completion.usage == openai.types.CompletionUsage(
277
        completion_tokens=5, prompt_tokens=37, total_tokens=42
278
    )
279
280

    message = choice.message
281
    assert message.content is not None and len(message.content) >= 5
282
283
284
285
286
287
288
289
    assert message.role == "assistant"
    messages.append({"role": "assistant", "content": message.content})

    # test multi-turn dialogue
    messages.append({"role": "user", "content": "express your result in json"})
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
290
        max_completion_tokens=5,
291
292
293
294
295
296
297
298
299
300
301
302
    )
    message = chat_completion.choices[0].message
    assert message.content is not None and len(message.content) >= 0


@pytest.mark.asyncio
@pytest.mark.parametrize(
    # just test 1 lora hereafter
    "model_name",
    [MODEL_NAME, "zephyr-lora"],
)
async def test_chat_streaming(client: openai.AsyncOpenAI, model_name: str):
303
304
305
306
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "what is 1+1?"},
    ]
307
308
309
310
311

    # test single completion
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
312
        max_completion_tokens=10,
313
314
315
316
317
318
319
320
321
        temperature=0.0,
    )
    output = chat_completion.choices[0].message.content
    stop_reason = chat_completion.choices[0].finish_reason

    # test streaming
    stream = await client.chat.completions.create(
        model=model_name,
        messages=messages,
322
        max_completion_tokens=10,
323
324
325
        temperature=0.0,
        stream=True,
    )
326
    chunks: list[str] = []
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    finish_reason_count = 0
    async for chunk in stream:
        delta = chunk.choices[0].delta
        if delta.role:
            assert delta.role == "assistant"
        if delta.content:
            chunks.append(delta.content)
        if chunk.choices[0].finish_reason is not None:
            finish_reason_count += 1
    # finish reason should only return in last block
    assert finish_reason_count == 1
    assert chunk.choices[0].finish_reason == stop_reason
    assert delta.content
    assert "".join(chunks) == output


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    ["HuggingFaceH4/zephyr-7b-beta", "zephyr-lora"],
)
348
349
350
351
352
353
354
async def test_chat_completion_stream_options(
    client: openai.AsyncOpenAI, model_name: str
):
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the capital of France?"},
    ]
355
356
357
358
359

    # Test stream=True, stream_options={"include_usage": False}
    stream = await client.chat.completions.create(
        model=model_name,
        messages=messages,
360
        max_completion_tokens=10,
361
362
        temperature=0.0,
        stream=True,
363
364
        stream_options={"include_usage": False},
    )
365
366
367
    async for chunk in stream:
        assert chunk.usage is None

368
369
    # Test stream=True, stream_options={"include_usage": True,
    #                                   "continuous_usage_stats": False}}
370
371
372
373
374
375
376
377
    stream = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=10,
        temperature=0.0,
        stream=True,
        stream_options={"include_usage": True, "continuous_usage_stats": False},
    )
378
379
380
381
382
383

    async for chunk in stream:
        if chunk.choices[0].finish_reason is None:
            assert chunk.usage is None
        else:
            assert chunk.usage is None
384
            final_chunk = await anext(stream)
385
386
387
388
            assert final_chunk.usage is not None
            assert final_chunk.usage.prompt_tokens > 0
            assert final_chunk.usage.completion_tokens > 0
            assert final_chunk.usage.total_tokens == (
389
390
                final_chunk.usage.prompt_tokens + final_chunk.usage.completion_tokens
            )
391
392
393
394
395
396
397
            assert final_chunk.choices == []

    # Test stream=False, stream_options={"include_usage": None}
    with pytest.raises(BadRequestError):
        await client.chat.completions.create(
            model=model_name,
            messages=messages,
398
            max_completion_tokens=10,
399
400
            temperature=0.0,
            stream=False,
401
402
            stream_options={"include_usage": None},
        )
403
404
405
406
407
408

    # Test stream=False, stream_options={"include_usage": True}
    with pytest.raises(BadRequestError):
        await client.chat.completions.create(
            model=model_name,
            messages=messages,
409
            max_completion_tokens=10,
410
411
            temperature=0.0,
            stream=False,
412
413
            stream_options={"include_usage": True},
        )
414

415
416
417
418
419
    # Test stream=True, stream_options={"include_usage": True,
    #                           "continuous_usage_stats": True}
    stream = await client.chat.completions.create(
        model=model_name,
        messages=messages,
420
        max_completion_tokens=10,
421
        extra_body=dict(min_tokens=10),
422
423
424
425
        temperature=0.0,
        stream=True,
        stream_options={
            "include_usage": True,
426
            "continuous_usage_stats": True,
427
428
        },
    )
429
    last_completion_tokens = 0
430
431
    async for chunk in stream:
        assert chunk.usage.prompt_tokens >= 0
432
433
434
435
436
437
438
439
440
441
442
        assert (
            last_completion_tokens == 0
            or chunk.usage.completion_tokens > last_completion_tokens
            or (
                not chunk.choices
                and chunk.usage.completion_tokens == last_completion_tokens
            )
        )
        assert chunk.usage.total_tokens == (
            chunk.usage.prompt_tokens + chunk.usage.completion_tokens
        )
443
444
445
        last_completion_tokens = chunk.usage.completion_tokens

    assert last_completion_tokens == 10
446

447
448

@pytest.mark.asyncio
449
async def test_structured_outputs_choice_chat(
450
451
452
    client: openai.AsyncOpenAI,
    sample_structured_outputs_choices,
):
453
454
455
456
457
458
459
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {
            "role": "user",
            "content": "The best language for type-safe systems programming is ",
        },
    ]
460
461
462
    chat_completion = await client.chat.completions.create(
        model=MODEL_NAME,
        messages=messages,
463
        max_completion_tokens=10,
464
        temperature=0.7,
465
        extra_body=dict(
466
467
468
            structured_outputs={"choice": sample_structured_outputs_choices}
        ),
    )
469
    choice1 = chat_completion.choices[0].message.content
470
    assert choice1 in sample_structured_outputs_choices
471
472

    messages.append({"role": "assistant", "content": choice1})
473
    messages.append({"role": "user", "content": "I disagree, pick another one"})
474
475
476
    chat_completion = await client.chat.completions.create(
        model=MODEL_NAME,
        messages=messages,
477
        max_completion_tokens=10,
478
        temperature=0.7,
479
        extra_body=dict(
480
481
482
            structured_outputs={"choice": sample_structured_outputs_choices}
        ),
    )
483
    choice2 = chat_completion.choices[0].message.content
484
    assert choice2 in sample_structured_outputs_choices
485
486
487
488
    assert choice1 != choice2


@pytest.mark.asyncio
489
490
491
492
async def test_structured_outputs_json_chat(
    client: openai.AsyncOpenAI,
    sample_json_schema,
):
493
494
495
496
497
498
499
500
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {
            "role": "user",
            "content": f"Give an example JSON for an employee profile that "
            f"fits this schema: {sample_json_schema}",
        },
    ]
501
502
503
    chat_completion = await client.chat.completions.create(
        model=MODEL_NAME,
        messages=messages,
504
        max_completion_tokens=1000,
505
506
        extra_body=dict(structured_outputs={"json": sample_json_schema}),
    )
507
508
509
    message = chat_completion.choices[0].message
    assert message.content is not None
    json1 = json.loads(message.content)
510
    jsonschema.validate(instance=json1, schema=sample_json_schema)
511
512

    messages.append({"role": "assistant", "content": message.content})
513
514
515
    messages.append(
        {"role": "user", "content": "Give me another one with a different name and age"}
    )
516
517
518
    chat_completion = await client.chat.completions.create(
        model=MODEL_NAME,
        messages=messages,
519
        max_completion_tokens=1000,
520
521
        extra_body=dict(structured_outputs={"json": sample_json_schema}),
    )
522
523
524
    message = chat_completion.choices[0].message
    assert message.content is not None
    json2 = json.loads(message.content)
525
    jsonschema.validate(instance=json2, schema=sample_json_schema)
526
527
528
529
530
    assert json1["name"] != json2["name"]
    assert json1["age"] != json2["age"]


@pytest.mark.asyncio
531
532
533
534
async def test_structured_outputs_regex_chat(
    client: openai.AsyncOpenAI,
    sample_regex,
):
535
536
537
538
539
540
541
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {
            "role": "user",
            "content": f"Give an example IP address with this regex: {sample_regex}",
        },
    ]
542
543
544
    chat_completion = await client.chat.completions.create(
        model=MODEL_NAME,
        messages=messages,
545
        max_completion_tokens=20,
546
547
        extra_body=dict(structured_outputs={"regex": sample_regex}),
    )
548
549
    ip1 = chat_completion.choices[0].message.content
    assert ip1 is not None
550
    assert re.fullmatch(sample_regex, ip1) is not None
551
552
553
554
555
556

    messages.append({"role": "assistant", "content": ip1})
    messages.append({"role": "user", "content": "Give me a different one"})
    chat_completion = await client.chat.completions.create(
        model=MODEL_NAME,
        messages=messages,
557
        max_completion_tokens=20,
558
559
        extra_body=dict(structured_outputs={"regex": sample_regex}),
    )
560
561
    ip2 = chat_completion.choices[0].message.content
    assert ip2 is not None
562
    assert re.fullmatch(sample_regex, ip2) is not None
563
564
565
566
    assert ip1 != ip2


@pytest.mark.asyncio
567
async def test_structured_outputs_type_error(client: openai.AsyncOpenAI):
568
569
570
571
572
573
574
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {
            "role": "user",
            "content": "The best language for type-safe systems programming is ",
        },
    ]
575
576

    with pytest.raises(openai.BadRequestError):
577
578
579
        _ = await client.chat.completions.create(
            model=MODEL_NAME,
            messages=messages,
580
581
            extra_body=dict(structured_outputs={"regex": {1: "Python", 2: "C++"}}),
        )
582
583
584


@pytest.mark.asyncio
585
async def test_structured_outputs_choice_chat_logprobs(
586
587
588
589
590
591
592
593
594
    client: openai.AsyncOpenAI, sample_structured_outputs_choices
):
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {
            "role": "user",
            "content": "The best language for type-safe systems programming is ",
        },
    ]
595
596
597
    chat_completion = await client.chat.completions.create(
        model=MODEL_NAME,
        messages=messages,
598
        max_completion_tokens=10,
599
600
        logprobs=True,
        top_logprobs=5,
601
        extra_body=dict(
602
603
604
            structured_outputs={"choice": sample_structured_outputs_choices}
        ),
    )
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619

    assert chat_completion.choices[0].logprobs is not None
    assert chat_completion.choices[0].logprobs.content is not None
    top_logprobs = chat_completion.choices[0].logprobs.content[0].top_logprobs

    # -9999.0 is the minimum logprob returned by OpenAI
    for item in top_logprobs:
        assert item.logprob >= -9999.0, f"Failed (top_logprobs={top_logprobs})"


@pytest.mark.asyncio
async def test_response_format_json_object(client: openai.AsyncOpenAI):
    for _ in range(2):
        resp = await client.chat.completions.create(
            model=MODEL_NAME,
620
621
622
623
624
625
626
627
628
629
630
            messages=[
                {
                    "role": "user",
                    "content": (
                        "what is 1+1? please respond with a JSON object, "
                        'the format is {"result": 2}'
                    ),
                }
            ],
            response_format={"type": "json_object"},
        )
631
632
633
634
635
636
637
638

        content = resp.choices[0].message.content
        assert content is not None

        loaded = json.loads(content)
        assert loaded == {"result": 2}, loaded


639
@pytest.mark.asyncio
640
async def test_response_format_json_schema(client: openai.AsyncOpenAI):
641
642
    prompt = 'what is 1+1? The format is "result": 2'
    # Check that this prompt cannot lead to a valid JSON without json_schema
643
644
645
    for _ in range(2):
        resp = await client.chat.completions.create(
            model=MODEL_NAME,
646
            messages=[{"role": "user", "content": prompt}],
647
648
649
650
651
652
653
654
655
656
        )
        content = resp.choices[0].message.content
        assert content is not None
        with pytest.raises((json.JSONDecodeError, AssertionError)):
            loaded = json.loads(content)
            assert loaded == {"result": 2}, loaded

    for _ in range(2):
        resp = await client.chat.completions.create(
            model=MODEL_NAME,
657
            messages=[{"role": "user", "content": prompt}],
658
659
660
661
662
663
664
            response_format={
                "type": "json_schema",
                "json_schema": {
                    "name": "foo_test",
                    "schema": {
                        "type": "object",
                        "properties": {
665
                            "result": {"type": "integer"},
666
667
                        },
                    },
668
669
670
                },
            },
        )
671
672
673
674
675
676
677
678

        content = resp.choices[0].message.content
        assert content is not None

        loaded = json.loads(content)
        assert loaded == {"result": 2}, loaded


679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
@pytest.mark.asyncio
async def test_response_format_text(client: openai.AsyncOpenAI):
    for _ in range(2):
        resp = await client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {
                    "role": "user",
                    "content": "what is 1+1?",
                }
            ],
            max_completion_tokens=10,
            response_format={"type": "text"},
        )

        content = resp.choices[0].message.content
        assert content is not None


698
@pytest.mark.asyncio
699
700
701
async def test_extra_fields_allowed(client: openai.AsyncOpenAI):
    resp = await client.chat.completions.create(
        model=MODEL_NAME,
702
703
704
705
706
707
708
        messages=[
            {
                "role": "user",
                "content": "what is 1+1?",
                "extra_field": "0",
            }
        ],  # type: ignore
709
        temperature=0,
710
711
        seed=0,
    )
712
713
714

    content = resp.choices[0].message.content
    assert content is not None
715
716
717
718


@pytest.mark.asyncio
async def test_complex_message_content(client: openai.AsyncOpenAI):
719
720
721
722
723
724
    content = [
        {
            "type": "text",
            "text": "what is 1+1? please provide the result without any other text.",
        }
    ]
725
726
    resp = await client.chat.completions.create(
        model=MODEL_NAME,
727
728
729
        messages=[
            {
                "role": "user",
730
                "content": content,
731
732
            }
        ],
733
        temperature=0,
734
735
        seed=0,
    )
736
737
738
739
740
741
742
743
744
745
746
    content = resp.choices[0].message.content
    assert content == "2"


@pytest.mark.asyncio
async def test_custom_role(client: openai.AsyncOpenAI):
    # Not sure how the model handles custom roles so we just check that
    # both string and complex message content are handled in the same way

    resp1 = await client.chat.completions.create(
        model=MODEL_NAME,
747
748
749
750
751
752
        messages=[
            {
                "role": "my-custom-role",
                "content": "what is 1+1?",
            }
        ],  # type: ignore
753
        temperature=0,
754
755
        seed=0,
    )
756
757
758

    resp2 = await client.chat.completions.create(
        model=MODEL_NAME,
759
760
761
762
763
764
        messages=[
            {
                "role": "my-custom-role",
                "content": [{"type": "text", "text": "what is 1+1?"}],
            }
        ],  # type: ignore
765
        temperature=0,
766
767
        seed=0,
    )
768
769
770
771
772
773
774
775

    content1 = resp1.choices[0].message.content
    content2 = resp2.choices[0].message.content
    assert content1 == content2


@pytest.mark.asyncio
async def test_long_seed(client: openai.AsyncOpenAI):
776
    for seed in [torch.iinfo(torch.long).min - 1, torch.iinfo(torch.long).max + 1]:
777
778
779
        with pytest.raises(BadRequestError) as exc_info:
            await client.chat.completions.create(
                model=MODEL_NAME,
780
781
782
783
784
785
                messages=[
                    {
                        "role": "system",
                        "content": "You are a helpful assistant.",
                    }
                ],
786
                temperature=0,
787
788
                seed=seed,
            )
789

790
791
792
793
        assert (
            "greater_than_equal" in exc_info.value.message
            or "less_than_equal" in exc_info.value.message
        )
794
795


796
@pytest.mark.asyncio
797
798
799
800
801
async def test_invocations(server: RemoteOpenAIServer, client: openai.AsyncOpenAI):
    messages = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "what is 1+1?"},
    ]
802
803
804
805
806
807
808
809
810
811
812

    request_args = {
        "model": MODEL_NAME,
        "messages": messages,
        "max_completion_tokens": 5,
        "temperature": 0.0,
        "logprobs": False,
    }

    chat_completion = await client.chat.completions.create(**request_args)

813
814
815
    invocation_response = requests.post(
        server.url_for("invocations"), json=request_args
    )
816
817
818
819
820
821
822
    invocation_response.raise_for_status()

    chat_output = chat_completion.model_dump()
    invocation_output = invocation_response.json()

    assert chat_output.keys() == invocation_output.keys()
    assert chat_output["choices"] == invocation_output["choices"]
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022


# Test n parameter for chat completions
# Tests that the n parameter works correctly for regular sampling
# (non-beam search) in chat completions, addressing issue #34305.


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME],
)
async def test_chat_completion_n_parameter_non_streaming(
    client: openai.AsyncOpenAI, model_name: str
):
    """Test that n parameter returns multiple choices for non-streaming requests."""
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the opposite of big?"},
    ]

    # Test with n=3
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=20,
        temperature=0.7,
        n=3,
        stream=False,
    )

    assert len(chat_completion.choices) == 3

    # Verify each choice has content and correct index
    for i, choice in enumerate(chat_completion.choices):
        assert choice.index == i
        assert choice.message.content is not None
        assert len(choice.message.content) > 0

    # Verify all responses are different (highly likely with temperature > 0)
    contents = [choice.message.content for choice in chat_completion.choices]
    assert len(set(contents)) > 1, "Expected different responses with n=3"


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME],
)
async def test_chat_completion_n_parameter_streaming(
    client: openai.AsyncOpenAI, model_name: str
):
    """Test that n parameter returns multiple choices for streaming requests."""
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the capital of France?"},
    ]

    stream = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=15,
        temperature=0.7,
        n=2,
        stream=True,
    )

    # Collect all chunks using defaultdict for dynamic handling
    chunks_by_index = defaultdict(list)
    async for chunk in stream:
        for choice in chunk.choices:
            if choice.delta.content:
                chunks_by_index[choice.index].append(choice.delta.content)

    # Verify both choices received content
    assert len(chunks_by_index[0]) > 0, "Choice 0 received no content chunks"
    assert len(chunks_by_index[1]) > 0, "Choice 1 received no content chunks"

    # Reconstruct full responses
    response_0 = "".join(chunks_by_index[0])
    response_1 = "".join(chunks_by_index[1])

    assert len(response_0) > 0, "Choice 0 has empty response"
    assert len(response_1) > 0, "Choice 1 has empty response"


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME],
)
async def test_chat_completion_n_with_seed(client: openai.AsyncOpenAI, model_name: str):
    """Test that n parameter works correctly with seed parameter."""
    messages = [
        {"role": "user", "content": "Say hello."},
    ]

    # Test that seed parameter is accepted and works with n > 1
    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=10,
        temperature=0.8,
        n=2,
        seed=42,
        stream=False,
    )

    # Verify we get n=2 choices
    assert len(chat_completion.choices) == 2

    # Verify both choices have valid content
    for i, choice in enumerate(chat_completion.choices):
        assert choice.index == i
        assert choice.message.content is not None
        assert len(choice.message.content) > 0


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "model_name",
    [MODEL_NAME],
)
async def test_chat_completion_n_equals_1(client: openai.AsyncOpenAI, model_name: str):
    """Test that n=1 (default) still works correctly."""
    messages = [
        {"role": "user", "content": "Hello!"},
    ]

    chat_completion = await client.chat.completions.create(
        model=model_name,
        messages=messages,
        max_completion_tokens=10,
        temperature=0.7,
        n=1,
        stream=False,
    )

    assert len(chat_completion.choices) == 1
    assert chat_completion.choices[0].index == 0
    assert chat_completion.choices[0].message.content is not None


# Unit tests for n parameter in ChatCompletionRequest.to_sampling_params()
def test_chat_completion_request_n_parameter_to_sampling_params():
    """Test that n parameter is correctly passed to SamplingParams."""
    # Test with n=3
    request = ChatCompletionRequest(
        model="test-model",
        messages=[{"role": "user", "content": "Hello"}],
        n=3,
        max_tokens=10,
    )

    sampling_params = request.to_sampling_params(
        max_tokens=10,
        default_sampling_params={},
    )

    assert isinstance(sampling_params, SamplingParams)
    assert sampling_params.n == 3, f"Expected n=3, got n={sampling_params.n}"


def test_chat_completion_request_n_parameter_default():
    """Test that n parameter defaults to 1."""
    request = ChatCompletionRequest(
        model="test-model",
        messages=[{"role": "user", "content": "Hello"}],
        # n not specified, should default to 1
        max_tokens=10,
    )

    assert request.n == 1, "n should default to 1"
    sampling_params = request.to_sampling_params(
        max_tokens=10,
        default_sampling_params={},
    )

    # SamplingParams.from_optional converts None to 1
    assert sampling_params.n == 1, f"Expected n=1 (default), got n={sampling_params.n}"


def test_chat_completion_request_n_parameter_various_values():
    """Test n parameter with various values."""
    for n_value in [1, 2, 5, 10]:
        request = ChatCompletionRequest(
            model="test-model",
            messages=[{"role": "user", "content": "Test"}],
            n=n_value,
            max_tokens=10,
        )

        sampling_params = request.to_sampling_params(
            max_tokens=10,
            default_sampling_params={},
        )

        assert sampling_params.n == n_value, (
            f"Expected n={n_value}, got n={sampling_params.n}"
        )