test_openai_server.py 41.3 KB
Newer Older
1
"""
2
3
4
5
python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_completion
python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_completion_stream
python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_chat_completion
python3 -m unittest openai_server.basic.test_openai_server.TestOpenAIServer.test_chat_completion_stream
6
"""
Chayenne's avatar
Chayenne committed
7

8
import json
9
import random
10
import re
11
import unittest
12
13
from concurrent.futures import ThreadPoolExecutor
from typing import Optional
14

15
import numpy as np
16
import openai
17
import requests
18

19
from sglang.srt.sampling.custom_logit_processor import CustomLogitProcessor
20
from sglang.srt.utils import kill_process_tree
21
from sglang.srt.utils.hf_transformers_utils import get_tokenizer
woodx's avatar
woodx committed
22
from sglang.test.runners import TEST_RERANK_QUERY_DOCS
23
from sglang.test.test_utils import (
woodx's avatar
woodx committed
24
    DEFAULT_SMALL_CROSS_ENCODER_MODEL_NAME_FOR_TEST,
Lianmin Zheng's avatar
Lianmin Zheng committed
25
    DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
26
27
    DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
    DEFAULT_URL_FOR_TEST,
28
    CustomTestCase,
29
30
    popen_launch_server,
)
31
32


33
class TestOpenAIServer(CustomTestCase):
34
35
    @classmethod
    def setUpClass(cls):
Lianmin Zheng's avatar
Lianmin Zheng committed
36
        cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
37
        cls.base_url = DEFAULT_URL_FOR_TEST
38
39
        cls.api_key = "sk-123456"
        cls.process = popen_launch_server(
40
41
42
43
            cls.model,
            cls.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
            api_key=cls.api_key,
44
        )
45
        cls.base_url += "/v1"
Lianmin Zheng's avatar
Lianmin Zheng committed
46
        cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)
47
48
49

    @classmethod
    def tearDownClass(cls):
50
        kill_process_tree(cls.process.pid)
51

yichuan~'s avatar
yichuan~ committed
52
    def run_completion(
53
        self, echo, logprobs, use_list_input, parallel_sample_num, token_input
yichuan~'s avatar
yichuan~ committed
54
    ):
55
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
56
        prompt = "The capital of France is"
yichuan~'s avatar
yichuan~ committed
57
58
59
60
61
62
        if token_input:
            prompt_input = self.tokenizer.encode(prompt)
            num_prompt_tokens = len(prompt_input)
        else:
            prompt_input = prompt
            num_prompt_tokens = len(self.tokenizer.encode(prompt))
63
64

        if use_list_input:
yichuan~'s avatar
yichuan~ committed
65
            prompt_arg = [prompt_input, prompt_input]
66
            num_choices = len(prompt_arg)
yichuan~'s avatar
yichuan~ committed
67
            num_prompt_tokens *= 2
68
        else:
yichuan~'s avatar
yichuan~ committed
69
            prompt_arg = prompt_input
70
71
            num_choices = 1

72
73
        response = client.completions.create(
            model=self.model,
74
            prompt=prompt_arg,
yichuan~'s avatar
yichuan~ committed
75
            temperature=0,
76
77
78
            max_tokens=32,
            echo=echo,
            logprobs=logprobs,
yichuan~'s avatar
yichuan~ committed
79
            n=parallel_sample_num,
80
        )
81

yichuan~'s avatar
yichuan~ committed
82
        assert len(response.choices) == num_choices * parallel_sample_num
83

Cody Yu's avatar
Cody Yu committed
84
        if echo:
85
            text = response.choices[0].text
86
            assert text.startswith(prompt)
yichuan~'s avatar
yichuan~ committed
87

Cody Yu's avatar
Cody Yu committed
88
        if logprobs:
89
90
91
            assert response.choices[0].logprobs
            assert isinstance(response.choices[0].logprobs.tokens[0], str)
            assert isinstance(response.choices[0].logprobs.top_logprobs[1], dict)
92
            ret_num_top_logprobs = len(response.choices[0].logprobs.top_logprobs[1])
93

94
            # FIXME: Sometimes, some top_logprobs are missing in the return value. The reason is that some output id maps to the same output token and duplicate in the map
95
            # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
yichuan~'s avatar
yichuan~ committed
96
            assert ret_num_top_logprobs > 0
97

98
99
100
            # when echo=True and request.logprobs>0, logprob_start_len is 0, so the first token's logprob would be None.
            if not echo:
                assert response.choices[0].logprobs.token_logprobs[0]
yichuan~'s avatar
yichuan~ committed
101

102
103
        assert response.id
        assert response.created
yichuan~'s avatar
yichuan~ committed
104
105
106
        assert (
            response.usage.prompt_tokens == num_prompt_tokens
        ), f"{response.usage.prompt_tokens} vs {num_prompt_tokens}"
107
108
109
        assert response.usage.completion_tokens > 0
        assert response.usage.total_tokens > 0

110
    def run_completion_stream(
111
        self, echo, logprobs, use_list_input, parallel_sample_num, token_input
112
    ):
113
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
114
        prompt = "The capital of France is"
yichuan~'s avatar
yichuan~ committed
115
        if token_input:
116
117
            prompt_input = self.tokenizer.encode(prompt)
            num_prompt_tokens = len(prompt_input)
yichuan~'s avatar
yichuan~ committed
118
        else:
119
120
121
122
123
124
125
126
127
128
129
            prompt_input = prompt
            num_prompt_tokens = len(self.tokenizer.encode(prompt))

        if use_list_input:
            prompt_arg = [prompt_input, prompt_input]
            num_choices = len(prompt_arg)
            num_prompt_tokens *= 2
        else:
            prompt_arg = prompt_input
            num_choices = 1

130
131
        generator = client.completions.create(
            model=self.model,
yichuan~'s avatar
yichuan~ committed
132
133
            prompt=prompt_arg,
            temperature=0,
134
135
136
137
            max_tokens=32,
            echo=echo,
            logprobs=logprobs,
            stream=True,
138
            stream_options={"include_usage": True},
139
            n=parallel_sample_num,
140
141
        )

142
        is_firsts = {}
143
        for response in generator:
144
145
            usage = response.usage
            if usage is not None:
146
147
148
                assert usage.prompt_tokens > 0, f"usage.prompt_tokens was zero"
                assert usage.completion_tokens > 0, f"usage.completion_tokens was zero"
                assert usage.total_tokens > 0, f"usage.total_tokens was zero"
149
                continue
150
151
152
153

            index = response.choices[0].index
            is_first = is_firsts.get(index, True)

154
            if logprobs:
155
156
157
158
                assert response.choices[0].logprobs, f"no logprobs in response"
                assert isinstance(
                    response.choices[0].logprobs.tokens[0], str
                ), f"{response.choices[0].logprobs.tokens[0]} is not a string"
159
                if not (is_first and echo):
160
161
                    assert isinstance(
                        response.choices[0].logprobs.top_logprobs[0], dict
162
                    ), f"top_logprobs was not a dictionary"
163
164
165
                    ret_num_top_logprobs = len(
                        response.choices[0].logprobs.top_logprobs[0]
                    )
166
                    # FIXME: Sometimes, some top_logprobs are missing in the return value. The reason is that some output id maps to the same output token and duplicate in the map
167
                    # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
168
                    assert ret_num_top_logprobs > 0, f"ret_num_top_logprobs was 0"
169

170
            if is_first:
171
                if echo:
yichuan~'s avatar
yichuan~ committed
172
173
                    assert response.choices[0].text.startswith(
                        prompt
174
175
                    ), f"{response.choices[0].text} and all args {echo} {logprobs} {token_input} {is_first}"
                is_firsts[index] = False
176
177
            assert response.id, f"no id in response"
            assert response.created, f"no created in response"
178

179
180
181
182
183
        for index in [i for i in range(parallel_sample_num * num_choices)]:
            assert not is_firsts.get(
                index, True
            ), f"index {index} is not found in the response"

184
    def run_chat_completion(self, logprobs, parallel_sample_num):
185
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
186
187
188
189
        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
Ying Sheng's avatar
Ying Sheng committed
190
191
192
193
                {
                    "role": "user",
                    "content": "What is the capital of France? Answer in a few words.",
                },
194
195
196
197
            ],
            temperature=0,
            logprobs=logprobs is not None and logprobs > 0,
            top_logprobs=logprobs,
yichuan~'s avatar
yichuan~ committed
198
            n=parallel_sample_num,
199
        )
Ying Sheng's avatar
Ying Sheng committed
200

201
202
203
204
205
206
207
208
209
210
211
        if logprobs:
            assert isinstance(
                response.choices[0].logprobs.content[0].top_logprobs[0].token, str
            )

            ret_num_top_logprobs = len(
                response.choices[0].logprobs.content[0].top_logprobs
            )
            assert (
                ret_num_top_logprobs == logprobs
            ), f"{ret_num_top_logprobs} vs {logprobs}"
Ying Sheng's avatar
Ying Sheng committed
212

yichuan~'s avatar
yichuan~ committed
213
        assert len(response.choices) == parallel_sample_num
214
215
216
217
218
219
220
221
        assert response.choices[0].message.role == "assistant"
        assert isinstance(response.choices[0].message.content, str)
        assert response.id
        assert response.created
        assert response.usage.prompt_tokens > 0
        assert response.usage.completion_tokens > 0
        assert response.usage.total_tokens > 0

222
    def run_chat_completion_stream(self, logprobs, parallel_sample_num=1):
223
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
224
225
226
227
228
229
230
231
232
233
        generator = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
                {"role": "user", "content": "What is the capital of France?"},
            ],
            temperature=0,
            logprobs=logprobs is not None and logprobs > 0,
            top_logprobs=logprobs,
            stream=True,
234
            stream_options={"include_usage": True},
235
            n=parallel_sample_num,
236
237
        )

238
        is_firsts = {}
239
        is_finished = {}
240
        finish_reason_counts = {}
241
        for response in generator:
242
243
            usage = response.usage
            if usage is not None:
244
245
246
                assert usage.prompt_tokens > 0, f"usage.prompt_tokens was zero"
                assert usage.completion_tokens > 0, f"usage.completion_tokens was zero"
                assert usage.total_tokens > 0, f"usage.total_tokens was zero"
247
248
                continue

249
            index = response.choices[0].index
250
251
252
            finish_reason = response.choices[0].finish_reason
            if finish_reason is not None:
                is_finished[index] = True
253
                finish_reason_counts[index] = finish_reason_counts.get(index, 0) + 1
254

255
            data = response.choices[0].delta
256

257
            if is_firsts.get(index, True):
258
259
260
                assert (
                    data.role == "assistant"
                ), f"data.role was not 'assistant' for first chunk"
261
                is_firsts[index] = False
262
263
                continue

264
            if logprobs and not is_finished.get(index, False):
265
                assert response.choices[0].logprobs, f"logprobs was not returned"
yichuan~'s avatar
yichuan~ committed
266
267
                assert isinstance(
                    response.choices[0].logprobs.content[0].top_logprobs[0].token, str
268
                ), f"top_logprobs token was not a string"
yichuan~'s avatar
yichuan~ committed
269
270
                assert isinstance(
                    response.choices[0].logprobs.content[0].top_logprobs, list
271
                ), f"top_logprobs was not a list"
yichuan~'s avatar
yichuan~ committed
272
273
274
275
276
277
                ret_num_top_logprobs = len(
                    response.choices[0].logprobs.content[0].top_logprobs
                )
                assert (
                    ret_num_top_logprobs == logprobs
                ), f"{ret_num_top_logprobs} vs {logprobs}"
278

279
280
281
            assert (
                isinstance(data.content, str)
                or isinstance(data.reasoning_content, str)
282
                or (isinstance(data.tool_calls, list) and len(data.tool_calls) > 0)
283
284
                or response.choices[0].finish_reason
            )
285
286
287
            assert response.id
            assert response.created

288
289
290
291
292
        for index in [i for i in range(parallel_sample_num)]:
            assert not is_firsts.get(
                index, True
            ), f"index {index} is not found in the response"

293
294
295
296
297
298
299
300
301
        # Verify that each choice gets exactly one finish_reason chunk
        for index in range(parallel_sample_num):
            assert (
                index in finish_reason_counts
            ), f"No finish_reason found for index {index}"
            assert (
                finish_reason_counts[index] == 1
            ), f"Expected 1 finish_reason chunk for index {index}, got {finish_reason_counts[index]}"

302
    def test_completion(self):
303
304
305
306
307
308
309
310
311
312
313
314
        for echo in [False, True]:
            for logprobs in [None, 5]:
                for use_list_input in [True, False]:
                    for parallel_sample_num in [1, 2]:
                        for token_input in [False, True]:
                            self.run_completion(
                                echo,
                                logprobs,
                                use_list_input,
                                parallel_sample_num,
                                token_input,
                            )
315
316

    def test_completion_stream(self):
317
        # parallel sampling and list input are not supported in streaming mode
318
319
320
321
322
323
324
325
326
327
328
329
        for echo in [False, True]:
            for logprobs in [None, 5]:
                for use_list_input in [True, False]:
                    for parallel_sample_num in [1, 2]:
                        for token_input in [False, True]:
                            self.run_completion_stream(
                                echo,
                                logprobs,
                                use_list_input,
                                parallel_sample_num,
                                token_input,
                            )
330

331
    def test_chat_completion(self):
332
333
334
        for logprobs in [None, 5]:
            for parallel_sample_num in [1, 2]:
                self.run_chat_completion(logprobs, parallel_sample_num)
335
336

    def test_chat_completion_stream(self):
337
338
339
        for logprobs in [None, 5]:
            for parallel_sample_num in [1, 2]:
                self.run_chat_completion_stream(logprobs, parallel_sample_num)
340
341

    def test_regex(self):
342
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

        regex = (
            r"""\{\n"""
            + r"""   "name": "[\w]+",\n"""
            + r"""   "population": [\d]+\n"""
            + r"""\}"""
        )

        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
                {"role": "user", "content": "Introduce the capital of France."},
            ],
            temperature=0,
            max_tokens=128,
            extra_body={"regex": regex},
        )
        text = response.choices[0].message.content

        try:
            js_obj = json.loads(text)
        except (TypeError, json.decoder.JSONDecodeError):
            print("JSONDecodeError", text)
            raise
        assert isinstance(js_obj["name"], str)
        assert isinstance(js_obj["population"], int)

371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
    def test_penalty(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
                {"role": "user", "content": "Introduce the capital of France."},
            ],
            temperature=0,
            max_tokens=32,
            frequency_penalty=1.0,
        )
        text = response.choices[0].message.content
        assert isinstance(text, str)

387
388
389
390
    def test_response_prefill(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        response = client.chat.completions.create(
391
            model="meta-llama/Llama-3.1-8B-Instruct",
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
                {
                    "role": "user",
                    "content": """
Extract the name, size, price, and color from this product description as a JSON object:

<description>
The SmartHome Mini is a compact smart home assistant available in black or white for only $49.99. At just 5 inches wide, it lets you control lights, thermostats, and other connected devices via voice or app—no matter where you place it in your home. This affordable little hub brings convenient hands-free control to your smart devices.
</description>
""",
                },
                {
                    "role": "assistant",
                    "content": "{\n",
                },
            ],
            temperature=0,
410
            extra_body={"continue_final_message": True},
411
412
413
414
415
416
417
418
        )

        assert (
            response.choices[0]
            .message.content.strip()
            .startswith('"name": "SmartHome Mini",')
        )

419
420
421
422
423
424
    def test_model_list(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        models = list(client.models.list())
        assert len(models) == 1
        assert isinstance(getattr(models[0], "max_model_len", None), int)

425
426
427
428
429
430
431
432
433
434
435
436
    def test_retrieve_model(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        # Test retrieving an existing model
        retrieved_model = client.models.retrieve(self.model)
        self.assertEqual(retrieved_model.id, self.model)
        self.assertEqual(retrieved_model.root, self.model)

        # Test retrieving a non-existent model
        with self.assertRaises(openai.NotFoundError):
            client.models.retrieve("non-existent-model")

437

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
class TestOpenAIServerv1Responses(CustomTestCase):
    @classmethod
    def setUpClass(cls):
        cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.api_key = "sk-123456"
        cls.process = popen_launch_server(
            cls.model,
            cls.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
            api_key=cls.api_key,
        )
        cls.base_url += "/v1"
        cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)

    @classmethod
    def tearDownClass(cls):
        kill_process_tree(cls.process.pid)

    def run_response(
        self,
        input_text: str = "The capital of France is",
        *,
        instructions: str | None = None,
        temperature: float | None = 0.0,
        top_p: float | None = 1.0,
        max_output_tokens: int | None = 32,
        store: bool | None = True,
        parallel_tool_calls: bool | None = True,
        tool_choice: str | None = "auto",
        previous_response_id: str | None = None,
        truncation: str | None = "disabled",
        user: str | None = None,
        metadata: dict | None = None,
    ):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        payload = {
            "model": self.model,
            "input": input_text,
            "temperature": temperature,
            "top_p": top_p,
            "max_output_tokens": max_output_tokens,
            "store": store,
            "parallel_tool_calls": parallel_tool_calls,
            "tool_choice": tool_choice,
            "previous_response_id": previous_response_id,
            "truncation": truncation,
            "user": user,
            "instructions": instructions,
        }
        if metadata is not None:
            payload["metadata"] = metadata
        payload = {k: v for k, v in payload.items() if v is not None}
        return client.responses.create(**payload)

    def run_response_stream(
        self,
        input_text: str = "The capital of France is",
        *,
        instructions: str | None = None,
        temperature: float | None = 0.0,
        top_p: float | None = 1.0,
        max_output_tokens: int | None = 32,
        store: bool | None = True,
        parallel_tool_calls: bool | None = True,
        tool_choice: str | None = "auto",
        previous_response_id: str | None = None,
        truncation: str | None = "disabled",
        user: str | None = None,
        metadata: dict | None = None,
    ):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        payload = {
            "model": self.model,
            "input": input_text,
            "temperature": temperature,
            "top_p": top_p,
            "max_output_tokens": max_output_tokens,
            "store": store,
            "parallel_tool_calls": parallel_tool_calls,
            "tool_choice": tool_choice,
            "previous_response_id": previous_response_id,
            "truncation": truncation,
            "user": user,
            "instructions": instructions,
            "stream": True,
            "stream_options": {"include_usage": True},
        }
        if metadata is not None:
            payload["metadata"] = metadata
        payload = {k: v for k, v in payload.items() if v is not None}

        aggregated_text = ""
        saw_created = False
        saw_in_progress = False
        saw_completed = False
        final_usage_ok = False

        stream_ctx = getattr(client.responses, "stream", None)
        if callable(stream_ctx):
            stream_payload = dict(payload)
            stream_payload.pop("stream", None)
            stream_payload.pop("stream_options", None)
            with client.responses.stream(**stream_payload) as stream:
                for event in stream:
                    et = getattr(event, "type", None)
                    if et == "response.created":
                        saw_created = True
                    elif et == "response.in_progress":
                        saw_in_progress = True
                    elif et == "response.output_text.delta":
                        # event.delta expected to be a string
                        delta = getattr(event, "delta", "")
                        if isinstance(delta, str):
                            aggregated_text += delta
                    elif et == "response.completed":
                        saw_completed = True
                        # Validate streaming-completed usage mapping
                        resp = getattr(event, "response", None)
                        try:
                            # resp may be dict-like already
                            usage = (
                                resp.get("usage")
                                if isinstance(resp, dict)
                                else getattr(resp, "usage", None)
                            )
                            if isinstance(usage, dict):
                                final_usage_ok = all(
                                    k in usage
                                    for k in (
                                        "input_tokens",
                                        "output_tokens",
                                        "total_tokens",
                                    )
                                )
                        except Exception:
                            pass
                _ = stream.get_final_response()
        else:
            generator = client.responses.create(**payload)
            for event in generator:
                et = getattr(event, "type", None)
                if et == "response.created":
                    saw_created = True
                elif et == "response.in_progress":
                    saw_in_progress = True
                elif et == "response.output_text.delta":
                    delta = getattr(event, "delta", "")
                    if isinstance(delta, str):
                        aggregated_text += delta
                elif et == "response.completed":
                    saw_completed = True

        return (
            aggregated_text,
            saw_created,
            saw_in_progress,
            saw_completed,
            final_usage_ok,
        )

    def run_chat_completion_stream(self, logprobs=None, parallel_sample_num=1):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        generator = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
                {"role": "user", "content": "What is the capital of France?"},
            ],
            temperature=0,
            logprobs=logprobs is not None and logprobs > 0,
            top_logprobs=logprobs,
            stream=True,
            stream_options={"include_usage": True},
            n=parallel_sample_num,
        )
        for _ in generator:
            pass

    # ---- tests ----
    def test_response(self):
        resp = self.run_response(temperature=0, max_output_tokens=32)
        assert resp.id
        assert resp.object == "response"
        assert resp.created_at
        assert isinstance(resp.model, str)
        assert isinstance(resp.output, list)
        assert resp.status in (
            "completed",
            "in_progress",
            "queued",
            "failed",
            "cancelled",
        )
        if resp.status == "completed":
            assert resp.usage is not None
            assert resp.usage.prompt_tokens >= 0
            assert resp.usage.completion_tokens >= 0
            assert resp.usage.total_tokens >= 0
        if hasattr(resp, "error"):
            assert resp.error is None
        if hasattr(resp, "incomplete_details"):
            assert resp.incomplete_details is None
        if getattr(resp, "text", None):
            fmt = resp.text.get("format") if isinstance(resp.text, dict) else None
            if fmt:
                assert fmt.get("type") == "text"

    def test_response_stream(self):
        aggregated_text, saw_created, saw_in_progress, saw_completed, final_usage_ok = (
            self.run_response_stream(temperature=0, max_output_tokens=32)
        )
        assert saw_created, "Did not observe response.created"
        assert saw_in_progress, "Did not observe response.in_progress"
        assert saw_completed, "Did not observe response.completed"
        assert isinstance(aggregated_text, str)
        assert len(aggregated_text) >= 0
        assert final_usage_ok or True  # final_usage's stats are not done for now

    def test_response_completion(self):
        resp = self.run_response(temperature=0, max_output_tokens=16)
        assert resp.status in ("completed", "in_progress", "queued")
        if resp.status == "completed":
            assert resp.usage is not None
            assert resp.usage.total_tokens >= 0

    def test_response_completion_stream(self):
        _, saw_created, saw_in_progress, saw_completed, final_usage_ok = (
            self.run_response_stream(temperature=0, max_output_tokens=16)
        )
        assert saw_created
        assert saw_in_progress
        assert saw_completed
        assert final_usage_ok or True  # final_usage's stats are not done for now

    def test_regex(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        regex = (
            r"""\{\n"""
            + r"""   "name": "[\w]+",\n"""
            + r"""   "population": [\d]+\n"""
            + r"""\}"""
        )

        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
                {"role": "user", "content": "Introduce the capital of France."},
            ],
            temperature=0,
            max_tokens=128,
            extra_body={"regex": regex},
        )
        text = response.choices[0].message.content

        try:
            js_obj = json.loads(text)
        except (TypeError, json.decoder.JSONDecodeError):
            print("JSONDecodeError", text)
            raise
        assert isinstance(js_obj["name"], str)
        assert isinstance(js_obj["population"], int)

    def test_error(self):
        url = f"{self.base_url}/responses"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }
        payload = {
            "model": self.model,
            "input": "Hi",
            "previous_response_id": "bad",  # invalid prefix
        }
        r = requests.post(url, headers=headers, json=payload)
        self.assertEqual(r.status_code, 400)
        body = r.json()
        self.assertIn("error", body)
        self.assertIn("message", body["error"])
        self.assertIn("type", body["error"])
        self.assertIn("code", body["error"])

    def test_penalty(self):
        url = f"{self.base_url}/responses"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }
        payload = {
            "model": self.model,
            "input": "Introduce the capital of France.",
            "temperature": 0,
            "max_output_tokens": 32,
            "frequency_penalty": 1.0,
        }
        r = requests.post(url, headers=headers, json=payload)
        self.assertEqual(r.status_code, 200)
        body = r.json()
        self.assertEqual(body.get("object"), "response")
        self.assertIn("output", body)
        self.assertIn("status", body)
        if "usage" in body:
            self.assertIn("prompt_tokens", body["usage"])
            self.assertIn("total_tokens", body["usage"])

    def test_response_prefill(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        response = client.chat.completions.create(
            model="meta-llama/Llama-3.1-8B-Instruct",
            messages=[
                {"role": "system", "content": "You are a helpful AI assistant"},
                {
                    "role": "user",
                    "content": """
Extract the name, size, price, and color from this product description as a JSON object:

<description>
The SmartHome Mini is a compact smart home assistant available in black or white for only $49.99. At just 5 inches wide, it lets you control lights, thermostats, and other connected devices via voice or app—no matter where you place it in your home. This affordable little hub brings convenient hands-free control to your smart devices.
</description>
""",
                },
                {
                    "role": "assistant",
                    "content": "{\n",
                },
            ],
            temperature=0,
            extra_body={"continue_final_message": True},
        )

        assert (
            response.choices[0]
            .message.content.strip()
            .startswith('"name": "SmartHome Mini",')
        )

    def test_model_list(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        models = list(client.models.list())
        assert len(models) == 1
        assert isinstance(getattr(models[0], "max_model_len", None), int)


woodx's avatar
woodx committed
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
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
class TestOpenAIV1Rerank(CustomTestCase):
    @classmethod
    def setUpClass(cls):
        cls.model = DEFAULT_SMALL_CROSS_ENCODER_MODEL_NAME_FOR_TEST
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.api_key = "sk-123456"
        cls.score_tolerance = 1e-2

        # Configure embedding-specific args
        other_args = [
            "--is-embedding",
            "--enable-metrics",
            "--disable-radix-cache",
            "--chunked-prefill-size",
            "-1",
            "--attention-backend",
            "torch_native",
        ]
        cls.process = popen_launch_server(
            cls.model,
            cls.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
            api_key=cls.api_key,
            other_args=other_args,
        )
        cls.base_url += "/v1/rerank"

    @classmethod
    def tearDownClass(cls):
        kill_process_tree(cls.process.pid)

    def run_rerank(self, query, docs):
        response = requests.post(
            self.base_url,
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
            },
            json={"query": query, "documents": docs},
        )

        return response.json()

    def test_rerank_single(self):
        """Test single rerank request"""
        query = TEST_RERANK_QUERY_DOCS[0]["query"]
        docs = TEST_RERANK_QUERY_DOCS[0]["documents"]

        response = self.run_rerank(query, docs)

        self.assertEqual(len(response), 1)
        self.assertTrue(isinstance(response[0]["score"], float))
        self.assertTrue(isinstance(response[0]["document"], str))
        self.assertTrue(isinstance(response[0]["index"], int))

    def test_rerank_batch(self):
        """Test batch rerank request"""
        query = TEST_RERANK_QUERY_DOCS[1]["query"]
        docs = TEST_RERANK_QUERY_DOCS[1]["documents"]

        response = self.run_rerank(query, docs)

        self.assertEqual(len(response), 2)
        self.assertTrue(isinstance(response[0]["score"], float))
        self.assertTrue(isinstance(response[1]["score"], float))
        self.assertTrue(isinstance(response[0]["document"], str))
        self.assertTrue(isinstance(response[1]["document"], str))
        self.assertTrue(isinstance(response[0]["index"], int))
        self.assertTrue(isinstance(response[1]["index"], int))


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
class TestOpenAIServerCustomLogitProcessor(CustomTestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.api_key = "sk-123456"
        cls.process = popen_launch_server(
            cls.model,
            cls.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
            api_key=cls.api_key,
            other_args=["--enable-custom-logit-processor"],
        )
        cls.base_url += "/v1"
        cls.tokenizer = get_tokenizer(cls.model)

    @classmethod
    def tearDownClass(cls) -> None:
        kill_process_tree(cls.process.pid)

    def run_custom_logit_processor(self, target_token_id: Optional[int] = None) -> None:
        """
        Test custom logit processor with custom params.

        If target_token_id is None, the custom logit processor won't be passed in.
        """

        class DeterministicLogitProcessor(CustomLogitProcessor):
            """A dummy logit processor that changes the logits to always sample the given token id."""

            CUSTOM_PARAM_KEY = "token_id"

            def __call__(self, logits, custom_param_list):
                assert logits.shape[0] == len(custom_param_list)

                for i, param_dict in enumerate(custom_param_list):
                    # Mask all other tokens
                    logits[i, :] = -float("inf")
                    # Assign highest probability to the specified token
                    logits[i, param_dict[self.CUSTOM_PARAM_KEY]] = 0.0

                return logits

        extra_body = {}

        if target_token_id is not None:
            extra_body["custom_logit_processor"] = (
                DeterministicLogitProcessor().to_str()
            )
            extra_body["custom_params"] = {
                "token_id": target_token_id,
            }

        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        max_tokens = 200

        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {
                    "role": "user",
                    "content": "Question: Is Paris the Capital of France?",
                },
            ],
            temperature=0.0,
            max_tokens=max_tokens,
            extra_body=extra_body,
        )

        if target_token_id is not None:
            target_text = self.tokenizer.decode([target_token_id] * max_tokens)
            self.assertTrue(
                target_text == response.choices[0].message.content,
                f"{target_token_id=}\n{target_text=}\n{response.model_dump(mode='json')}",
            )

    def test_custom_logit_processor(self) -> None:
        """Test custom logit processor with a single request."""
        self.run_custom_logit_processor(target_token_id=5)

    def test_custom_logit_processor_batch_mixed(self) -> None:
        """Test a batch of requests mixed of requests with and without custom logit processor."""
        target_token_ids = list(range(32)) + [None] * 16
        random.shuffle(target_token_ids)
        with ThreadPoolExecutor(len(target_token_ids)) as executor:
            list(executor.map(self.run_custom_logit_processor, target_token_ids))


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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
class TestOpenAIV1Score(CustomTestCase):
    @classmethod
    def setUpClass(cls):
        cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.api_key = "sk-123456"

        cls.process = popen_launch_server(
            cls.model,
            cls.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
            api_key=cls.api_key,
        )
        cls.base_url += "/v1/score"
        cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)

    @classmethod
    def tearDownClass(cls):
        kill_process_tree(cls.process.pid)

    def run_score(
        self, query, items, label_token_ids, apply_softmax=False, item_first=False
    ):
        response = requests.post(
            self.base_url,
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": self.model,
                "query": query,
                "items": items,
                "label_token_ids": label_token_ids,
                "apply_softmax": apply_softmax,
                "item_first": item_first,
            },
        )
        return response.json()

    def test_score_text_input(self):
        """Test scoring with text input"""
        query = "The capital of France is"
        items = ["Paris", "London", "Berlin"]

        # Get valid token IDs from the tokenizer
        label_token_ids = []
        for item in items:
            token_ids = self.tokenizer.encode(item, add_special_tokens=False)
            if not token_ids:
                self.fail(f"Failed to encode item: {item}")
            label_token_ids.append(token_ids[0])

        response = self.run_score(query, items, label_token_ids, apply_softmax=True)

        # Handle error responses
        if response.get("type") == "BadRequestError":
            self.fail(f"Score request failed with error: {response['message']}")

        # Verify response structure
        self.assertIn("scores", response, "Response should have a 'scores' field")
        self.assertIsInstance(response["scores"], list, "scores should be a list")
        self.assertEqual(
            len(response["scores"]),
            len(items),
            "Number of scores should match number of items",
        )

        # Each score should be a list of floats in the order of label_token_ids
        for i, score_list in enumerate(response["scores"]):
            self.assertIsInstance(score_list, list, f"Score {i} should be a list")
            self.assertEqual(
                len(score_list),
                len(label_token_ids),
                f"Score {i} length should match label_token_ids",
            )
            self.assertTrue(
                all(isinstance(v, float) for v in score_list),
                f"Score {i} values should be floats",
            )
            self.assertAlmostEqual(
                sum(score_list),
                1.0,
                places=6,
                msg=f"Score {i} probabilities should sum to 1",
            )

    def test_score_token_input(self):
        """Test scoring with token IDs input"""
        query = "The capital of France is"
        items = ["Paris", "London", "Berlin"]

        # Get valid token IDs
        query_ids = self.tokenizer.encode(query, add_special_tokens=False)
        item_ids = [
            self.tokenizer.encode(item, add_special_tokens=False) for item in items
        ]
        label_token_ids = [
            ids[0] for ids in item_ids if ids
        ]  # Get first token ID of each item

        response = self.run_score(
            query_ids, item_ids, label_token_ids, apply_softmax=True
        )

        # Handle error responses
        if response.get("type") == "BadRequestError":
            self.fail(f"Score request failed with error: {response['message']}")

        # Verify response structure
        self.assertIn("scores", response, "Response should have a 'scores' field")
        self.assertIsInstance(response["scores"], list, "scores should be a list")
        self.assertEqual(
            len(response["scores"]),
            len(items),
            "Number of scores should match number of items",
        )

        # Each score should be a list of floats in the order of label_token_ids
        for i, score_list in enumerate(response["scores"]):
            self.assertIsInstance(score_list, list, f"Score {i} should be a list")
            self.assertEqual(
                len(score_list),
                len(label_token_ids),
                f"Score {i} length should match label_token_ids",
            )
            self.assertTrue(
                all(isinstance(v, float) for v in score_list),
                f"Score {i} values should be floats",
            )
            self.assertAlmostEqual(
                sum(score_list),
                1.0,
                places=6,
                msg=f"Score {i} probabilities should sum to 1",
            )

    def test_score_error_handling(self):
        """Test error handling for invalid inputs"""
        query = "The capital of France is"
        items = ["Paris", "London", "Berlin"]

        # Test with invalid token ID
        response = requests.post(
            self.base_url,
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": self.model,
                "query": query,
                "items": items,
                "label_token_ids": [999999],  # Invalid token ID
                "apply_softmax": True,
            },
        )
        self.assertEqual(response.status_code, 400)
        error_response = response.json()
        self.assertEqual(error_response["type"], "BadRequestError")
        self.assertIn("Token ID 999999 is out of vocabulary", error_response["message"])


1106
if __name__ == "__main__":
Lianmin Zheng's avatar
Lianmin Zheng committed
1107
    unittest.main()