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

9
import json
10
import re
11
import time
12
import unittest
13

14
import numpy as np
15
import openai
16

yichuan~'s avatar
yichuan~ committed
17
from sglang.srt.hf_transformers_utils import get_tokenizer
18
from sglang.srt.utils import kill_process_tree
19
from sglang.test.test_utils import (
20
    DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST,
Lianmin Zheng's avatar
Lianmin Zheng committed
21
    DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
22
23
    DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
    DEFAULT_URL_FOR_TEST,
24
    CustomTestCase,
25
26
    popen_launch_server,
)
27
28


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

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

yichuan~'s avatar
yichuan~ committed
48
    def run_completion(
49
50
51
52
53
54
55
        self,
        echo,
        logprobs,
        use_list_input,
        parallel_sample_num,
        token_input,
        return_hidden_states,
yichuan~'s avatar
yichuan~ committed
56
    ):
57
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
58
        prompt = "The capital of France is"
yichuan~'s avatar
yichuan~ committed
59
60
61
62
63
64
        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))
65
66

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

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

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

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

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

97
            # 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
98
            # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
yichuan~'s avatar
yichuan~ committed
99
            assert ret_num_top_logprobs > 0
100

101
102
103
            # 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
104

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

113
114
115
116
117
118
119
120
121
122
123
124
        if return_hidden_states:
            hidden_states = response.choices[0].hidden_states
            assert hidden_states is not None, "hidden_states was none"
            hidden_states = np.asarray(hidden_states)
            assert (
                len(hidden_states.shape) == 1
            ), f"hidden_states shape is not correct, was {hidden_states.shape}"
        else:
            assert not hasattr(
                response.choices[0], "hidden_states"
            ), "hidden_states was returned and should not have been"

125
    def run_completion_stream(
126
127
128
129
130
131
132
        self,
        echo,
        logprobs,
        use_list_input,
        parallel_sample_num,
        token_input,
        return_hidden_states,
133
    ):
134
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
135
        prompt = "The capital of France is"
yichuan~'s avatar
yichuan~ committed
136
        if token_input:
137
138
            prompt_input = self.tokenizer.encode(prompt)
            num_prompt_tokens = len(prompt_input)
yichuan~'s avatar
yichuan~ committed
139
        else:
140
141
142
143
144
145
146
147
148
149
150
            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

151
152
        generator = client.completions.create(
            model=self.model,
yichuan~'s avatar
yichuan~ committed
153
154
            prompt=prompt_arg,
            temperature=0,
155
156
157
158
            max_tokens=32,
            echo=echo,
            logprobs=logprobs,
            stream=True,
159
            stream_options={"include_usage": True},
160
            n=parallel_sample_num,
161
            extra_body=dict(return_hidden_states=return_hidden_states),
162
163
        )

164
        is_firsts = {}
165
        hidden_states = None
166
        for response in generator:
167
168
            usage = response.usage
            if usage is not None:
169
170
171
172
173
174
175
176
177
178
                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"
                continue

            if (
                hasattr(response.choices[0], "hidden_states")
                and response.choices[0].hidden_states is not None
            ):
                hidden_states = response.choices[0].hidden_states
179
                continue
180
181
182
183

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

184
            if logprobs:
185
186
187
188
                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"
189
                if not (is_first and echo):
190
191
                    assert isinstance(
                        response.choices[0].logprobs.top_logprobs[0], dict
192
                    ), f"top_logprobs was not a dictionary"
193
194
195
                    ret_num_top_logprobs = len(
                        response.choices[0].logprobs.top_logprobs[0]
                    )
196
                    # 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
197
                    # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
198
                    assert ret_num_top_logprobs > 0, f"ret_num_top_logprobs was 0"
199

200
            if is_first:
201
                if echo:
yichuan~'s avatar
yichuan~ committed
202
203
                    assert response.choices[0].text.startswith(
                        prompt
204
205
                    ), f"{response.choices[0].text} and all args {echo} {logprobs} {token_input} {is_first}"
                is_firsts[index] = False
206
207
            assert response.id, f"no id in response"
            assert response.created, f"no created in response"
208

209
210
211
212
213
        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"

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
        if return_hidden_states:
            assert hidden_states is not None, "hidden_states is not returned"
            try:
                hidden_states = np.asarray(hidden_states)
            except Exception as e:
                raise Exception(f"Failed to convert hidden states to numpy array: {e}")
            assert (
                len(hidden_states.shape) == 1
            ), f"hidden_states shape is not correct, was {hidden_states.shape}"
        else:
            assert (
                hidden_states is None
            ), "hidden_states was returned and should not have been"

    def run_chat_completion(self, logprobs, parallel_sample_num, return_hidden_states):
229
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
230
231
232
233
        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
234
235
236
237
                {
                    "role": "user",
                    "content": "What is the capital of France? Answer in a few words.",
                },
238
239
240
241
            ],
            temperature=0,
            logprobs=logprobs is not None and logprobs > 0,
            top_logprobs=logprobs,
yichuan~'s avatar
yichuan~ committed
242
            n=parallel_sample_num,
243
            extra_body=dict(return_hidden_states=return_hidden_states),
244
        )
Ying Sheng's avatar
Ying Sheng committed
245

246
247
248
249
250
251
252
253
254
255
256
        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
257

yichuan~'s avatar
yichuan~ committed
258
        assert len(response.choices) == parallel_sample_num
259
260
261
262
263
264
265
266
        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

267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
        if return_hidden_states:
            hidden_states = response.choices[0].hidden_states
            assert hidden_states is not None, "hidden_states is not returned"
            hidden_states = np.asarray(hidden_states)
            assert (
                len(hidden_states.shape) == 1
            ), f"hidden_states shape is not correct, was {hidden_states.shape}"
        else:
            assert not hasattr(
                response.choices[0], "hidden_states"
            ), "hidden_states was returned and should not have been"

    def run_chat_completion_stream(
        self, logprobs, parallel_sample_num=1, return_hidden_states=False
    ):
282
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
283
284
285
286
287
288
289
290
291
292
        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,
293
            stream_options={"include_usage": True},
294
            n=parallel_sample_num,
295
            extra_body=dict(return_hidden_states=return_hidden_states),
296
297
        )

298
        is_firsts = {}
299
300
        hidden_states = None
        top_logprob_tokens = []
301
        for response in generator:
302
303
            usage = response.usage
            if usage is not None:
304
305
306
307
308
309
310
                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"
                continue

            if hasattr(response.choices[0].delta, "hidden_states"):
                hidden_states = response.choices[0].delta.hidden_states
311
312
                continue

313
            index = response.choices[0].index
314
            data = response.choices[0].delta
315

316
            if is_firsts.get(index, True):
317
318
319
                assert (
                    data.role == "assistant"
                ), f"data.role was not 'assistant' for first chunk"
320
                is_firsts[index] = False
321
322
323
                continue

            if logprobs:
324
                assert response.choices[0].logprobs, f"logprobs was not returned"
yichuan~'s avatar
yichuan~ committed
325
326
                assert isinstance(
                    response.choices[0].logprobs.content[0].top_logprobs[0].token, str
327
                ), f"top_logprobs token was not a string"
yichuan~'s avatar
yichuan~ committed
328
329
                assert isinstance(
                    response.choices[0].logprobs.content[0].top_logprobs, list
330
                ), f"top_logprobs was not a list"
yichuan~'s avatar
yichuan~ committed
331
332
333
334
335
336
                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}"
337
338
339
                top_logprob_tokens.append(
                    response.choices[0].logprobs.content[0].top_logprobs[0].token
                )
340

341
342
343
            assert (
                len(top_logprob_tokens) <= 2 or len(set(top_logprob_tokens)) > 1
            ), "Top Logprob tokens should not consistent of the same token repeated"
344
345
346
347
348
349
            assert (
                isinstance(data.content, str)
                or isinstance(data.reasoning_content, str)
                or len(data.tool_calls) > 0
                or response.choices[0].finish_reason
            )
350
351
352
            assert response.id
            assert response.created

353
354
355
356
357
        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"

358
359
360
361
362
363
364
365
366
367
368
369
370
371
        if return_hidden_states:
            assert hidden_states is not None, "hidden_states is not returned"
            try:
                hidden_states = np.asarray(hidden_states)
            except Exception as e:
                raise Exception(f"Failed to convert hidden states to numpy array: {e}")
            assert (
                len(hidden_states.shape) == 1
            ), f"hidden_states shape is not correct, was {hidden_states.shape}"
        else:
            assert (
                hidden_states is None
            ), "hidden_states was returned and should not have been"

372
    def _create_batch(self, mode, client):
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
        if mode == "completion":
            input_file_path = "complete_input.jsonl"
            # write content to input file
            content = [
                {
                    "custom_id": "request-1",
                    "method": "POST",
                    "url": "/v1/completions",
                    "body": {
                        "model": "gpt-3.5-turbo-instruct",
                        "prompt": "List 3 names of famous soccer player: ",
                        "max_tokens": 20,
                    },
                },
                {
                    "custom_id": "request-2",
                    "method": "POST",
                    "url": "/v1/completions",
                    "body": {
                        "model": "gpt-3.5-turbo-instruct",
                        "prompt": "List 6 names of famous basketball player:  ",
                        "max_tokens": 40,
                    },
                },
                {
                    "custom_id": "request-3",
                    "method": "POST",
                    "url": "/v1/completions",
                    "body": {
                        "model": "gpt-3.5-turbo-instruct",
                        "prompt": "List 6 names of famous tenniss player:  ",
                        "max_tokens": 40,
                    },
                },
            ]

        else:
            input_file_path = "chat_input.jsonl"
            content = [
                {
                    "custom_id": "request-1",
                    "method": "POST",
                    "url": "/v1/chat/completions",
                    "body": {
                        "model": "gpt-3.5-turbo-0125",
                        "messages": [
                            {
                                "role": "system",
                                "content": "You are a helpful assistant.",
                            },
                            {
                                "role": "user",
                                "content": "Hello! List 3 NBA players and tell a story",
                            },
                        ],
                        "max_tokens": 30,
                    },
                },
                {
                    "custom_id": "request-2",
                    "method": "POST",
                    "url": "/v1/chat/completions",
                    "body": {
                        "model": "gpt-3.5-turbo-0125",
                        "messages": [
                            {"role": "system", "content": "You are an assistant. "},
                            {
                                "role": "user",
                                "content": "Hello! List three capital and tell a story",
                            },
                        ],
                        "max_tokens": 50,
                    },
                },
            ]
448

449
450
451
        with open(input_file_path, "w") as file:
            for line in content:
                file.write(json.dumps(line) + "\n")
452

453
454
455
456
457
458
459
460
461
462
463
464
        with open(input_file_path, "rb") as file:
            uploaded_file = client.files.create(file=file, purpose="batch")
        if mode == "completion":
            endpoint = "/v1/completions"
        elif mode == "chat":
            endpoint = "/v1/chat/completions"
        completion_window = "24h"
        batch_job = client.batches.create(
            input_file_id=uploaded_file.id,
            endpoint=endpoint,
            completion_window=completion_window,
        )
465

466
        return batch_job, content, uploaded_file
467
468
469

    def run_batch(self, mode):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
470
        batch_job, content, uploaded_file = self._create_batch(mode=mode, client=client)
471

472
473
474
475
476
477
        while batch_job.status not in ["completed", "failed", "cancelled"]:
            time.sleep(3)
            print(
                f"Batch job status: {batch_job.status}...trying again in 3 seconds..."
            )
            batch_job = client.batches.retrieve(batch_job.id)
478
479
480
        assert (
            batch_job.status == "completed"
        ), f"Batch job status is not completed: {batch_job.status}"
481
482
483
484
485
486
        assert batch_job.request_counts.completed == len(content)
        assert batch_job.request_counts.failed == 0
        assert batch_job.request_counts.total == len(content)

        result_file_id = batch_job.output_file_id
        file_response = client.files.content(result_file_id)
yichuan~'s avatar
yichuan~ committed
487
488
489
490
491
492
        result_content = file_response.read().decode("utf-8")  # Decode bytes to string
        results = [
            json.loads(line)
            for line in result_content.split("\n")
            if line.strip() != ""
        ]
493
        assert len(results) == len(content)
494
495
496
        for delete_fid in [uploaded_file.id, result_file_id]:
            del_pesponse = client.files.delete(delete_fid)
            assert del_pesponse.deleted
497

498
499
    def run_cancel_batch(self, mode):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
500
        batch_job, _, uploaded_file = self._create_batch(mode=mode, client=client)
501
502
503
504
505
506
507
508
509
510
511
512
513
514

        assert batch_job.status not in ["cancelling", "cancelled"]

        batch_job = client.batches.cancel(batch_id=batch_job.id)
        assert batch_job.status == "cancelling"

        while batch_job.status not in ["failed", "cancelled"]:
            batch_job = client.batches.retrieve(batch_job.id)
            print(
                f"Batch job status: {batch_job.status}...trying again in 3 seconds..."
            )
            time.sleep(3)

        assert batch_job.status == "cancelled"
515
516
        del_response = client.files.delete(uploaded_file.id)
        assert del_response.deleted
517

518
    def test_completion(self):
519
520
521
522
523
524
525
526
527
528
529
530
531
532
        for return_hidden_states in [False, True]:
            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,
                                    return_hidden_states,
                                )
533
534

    def test_completion_stream(self):
535
        # parallel sampling and list input are not supported in streaming mode
536
537
538
539
540
541
542
543
544
545
546
547
548
549
        for return_hidden_states in [False, True]:
            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,
                                    return_hidden_states,
                                )
550

551
    def test_chat_completion(self):
552
553
554
555
556
557
        for return_hidden_states in [False, True]:
            for logprobs in [None, 5]:
                for parallel_sample_num in [1, 2]:
                    self.run_chat_completion(
                        logprobs, parallel_sample_num, return_hidden_states
                    )
558
559

    def test_chat_completion_stream(self):
560
561
562
563
564
565
        for return_hidden_states in [False, True]:
            for logprobs in [None, 5]:
                for parallel_sample_num in [1, 2]:
                    self.run_chat_completion_stream(
                        logprobs, parallel_sample_num, return_hidden_states
                    )
566

567
568
569
570
    def test_batch(self):
        for mode in ["completion", "chat"]:
            self.run_batch(mode)

571
    def test_cancel_batch(self):
572
573
574
        for mode in ["completion", "chat"]:
            self.run_cancel_batch(mode)

575
    def test_regex(self):
576
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
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

        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)

605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
    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)

621
622
623
624
    def test_response_prefill(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        response = client.chat.completions.create(
625
            model="meta-llama/Llama-3.1-8B-Instruct",
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
            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,
644
            extra_body={"continue_final_message": True},
645
646
647
648
649
650
651
652
        )

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

653
654
655
656
657
658
    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)

659

660
661
662
663
# -------------------------------------------------------------------------
#    EBNF Test Class: TestOpenAIServerEBNF
#    Launches the server with xgrammar, has only EBNF tests
# -------------------------------------------------------------------------
664
class TestOpenAIServerEBNF(CustomTestCase):
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
    @classmethod
    def setUpClass(cls):
        cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.api_key = "sk-123456"

        # passing xgrammar specifically
        other_args = ["--grammar-backend", "xgrammar"]
        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"
        cls.tokenizer = get_tokenizer(DEFAULT_SMALL_MODEL_NAME_FOR_TEST)

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

    def test_ebnf(self):
        """
        Ensure we can pass `ebnf` to the local openai server
        and that it enforces the grammar.
        """
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        ebnf_grammar = r"""
        root ::= "Hello" | "Hi" | "Hey"
        """
        pattern = re.compile(r"^(Hello|Hi|Hey)[.!?]*\s*$")

        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful EBNF test bot."},
                {"role": "user", "content": "Say a greeting (Hello, Hi, or Hey)."},
            ],
            temperature=0,
            max_tokens=32,
            extra_body={"ebnf": ebnf_grammar},
        )
        text = response.choices[0].message.content.strip()
        print("EBNF test output:", repr(text))
        self.assertTrue(len(text) > 0, "Got empty text from EBNF generation")
        self.assertRegex(text, pattern, f"Text '{text}' doesn't match EBNF choices")

    def test_ebnf_strict_json(self):
        """
        A stricter EBNF that produces exactly {"name":"Alice"} format
        with no trailing punctuation or extra fields.
        """
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        ebnf_grammar = r"""
        root    ::= "{" pair "}"
        pair    ::= "\"name\"" ":" string
        string  ::= "\"" [A-Za-z]+ "\""
        """
        pattern = re.compile(r'^\{"name":"[A-Za-z]+"\}$')

        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "EBNF mini-JSON generator."},
                {
                    "role": "user",
                    "content": "Generate single key JSON with only letters.",
                },
            ],
            temperature=0,
            max_tokens=64,
            extra_body={"ebnf": ebnf_grammar},
        )
        text = response.choices[0].message.content.strip()
        print("EBNF strict JSON test output:", repr(text))
        self.assertTrue(len(text) > 0, "Got empty text from EBNF strict JSON test")
        self.assertRegex(
            text, pattern, f"Text '{text}' not matching the EBNF strict JSON shape"
        )


747
class TestOpenAIEmbedding(CustomTestCase):
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
784
785
    @classmethod
    def setUpClass(cls):
        cls.model = DEFAULT_SMALL_EMBEDDING_MODEL_NAME_FOR_TEST
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.api_key = "sk-123456"

        # Configure embedding-specific args
        other_args = ["--is-embedding", "--enable-metrics"]
        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"

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

    def test_embedding_single(self):
        """Test single embedding request"""
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        response = client.embeddings.create(model=self.model, input="Hello world")
        self.assertEqual(len(response.data), 1)
        self.assertTrue(len(response.data[0].embedding) > 0)

    def test_embedding_batch(self):
        """Test batch embedding request"""
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        response = client.embeddings.create(
            model=self.model, input=["Hello world", "Test text"]
        )
        self.assertEqual(len(response.data), 2)
        self.assertTrue(len(response.data[0].embedding) > 0)
        self.assertTrue(len(response.data[1].embedding) > 0)

786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
    def test_empty_string_embedding(self):
        """Test embedding an empty string."""

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

        # Text embedding example with empty string
        text = ""
        # Expect a BadRequestError for empty input
        with self.assertRaises(openai.BadRequestError) as cm:
            client.embeddings.create(
                model=self.model,
                input=text,
            )
        # check the status code
        self.assertEqual(cm.exception.status_code, 400)

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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
class TestOpenAIServerIgnoreEOS(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 test_ignore_eos(self):
        """
        Test that ignore_eos=True allows generation to continue beyond EOS token
        and reach the max_tokens limit.
        """
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        max_tokens = 200

        response_default = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "Count from 1 to 20."},
            ],
            temperature=0,
            max_tokens=max_tokens,
            extra_body={"ignore_eos": False},
        )

        response_ignore_eos = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "Count from 1 to 20."},
            ],
            temperature=0,
            max_tokens=max_tokens,
            extra_body={"ignore_eos": True},
        )

        default_tokens = len(
            self.tokenizer.encode(response_default.choices[0].message.content)
        )
        ignore_eos_tokens = len(
            self.tokenizer.encode(response_ignore_eos.choices[0].message.content)
        )

        # Check if ignore_eos resulted in more tokens or exactly max_tokens
        # The ignore_eos response should either:
        # 1. Have more tokens than the default response (if default stopped at EOS before max_tokens)
        # 2. Have exactly max_tokens (if it reached the max_tokens limit)
        self.assertTrue(
            ignore_eos_tokens > default_tokens or ignore_eos_tokens >= max_tokens,
            f"ignore_eos did not generate more tokens: {ignore_eos_tokens} vs {default_tokens}",
        )

        self.assertEqual(
            response_ignore_eos.choices[0].finish_reason,
            "length",
            f"Expected finish_reason='length' for ignore_eos=True, got {response_ignore_eos.choices[0].finish_reason}",
        )


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