test_openai_server.py 7.81 KB
Newer Older
1
import json
2
import unittest
3
4

import openai
5
6

from sglang.srt.utils import kill_child_process
7
from sglang.test.test_utils import MODEL_NAME_FOR_TEST, popen_launch_server
8
9
10
11
12
13


class TestOpenAIServer(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
14
        cls.model = MODEL_NAME_FOR_TEST
15
        cls.base_url = f"http://localhost:30000"
16
17
18
19
        cls.api_key = "sk-123456"
        cls.process = popen_launch_server(
            cls.model, cls.base_url, timeout=300, api_key=cls.api_key
        )
20
        cls.base_url += "/v1"
21
22
23
24
25

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

26
    def run_completion(self, echo, logprobs, use_list_input):
27
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
28
        prompt = "The capital of France is"
29
30
31
32
33
34
35
36

        if use_list_input:
            prompt_arg = [prompt, prompt]
            num_choices = len(prompt_arg)
        else:
            prompt_arg = prompt
            num_choices = 1

37
38
        response = client.completions.create(
            model=self.model,
39
            prompt=prompt_arg,
40
41
42
43
44
            temperature=0.1,
            max_tokens=32,
            echo=echo,
            logprobs=logprobs,
        )
45
46
47

        assert len(response.choices) == num_choices

Cody Yu's avatar
Cody Yu committed
48
        if echo:
49
            text = response.choices[0].text
50
            assert text.startswith(prompt)
Cody Yu's avatar
Cody Yu committed
51
        if logprobs:
52
53
54
            assert response.choices[0].logprobs
            assert isinstance(response.choices[0].logprobs.tokens[0], str)
            assert isinstance(response.choices[0].logprobs.top_logprobs[1], dict)
55
56
57
            ret_num_top_logprobs = len(response.choices[0].logprobs.top_logprobs[1])
            # FIXME: Fix this bug. Sometimes, some top_logprobs are missing in the return value.
            # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
58
59
60
61
62
63
64
65
66
67
68
            if echo:
                assert response.choices[0].logprobs.token_logprobs[0] == None
            else:
                assert response.choices[0].logprobs.token_logprobs[0] != None
        assert response.id
        assert response.created
        assert response.usage.prompt_tokens > 0
        assert response.usage.completion_tokens > 0
        assert response.usage.total_tokens > 0

    def run_completion_stream(self, echo, logprobs):
69
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
        prompt = "The capital of France is"
        generator = client.completions.create(
            model=self.model,
            prompt=prompt,
            temperature=0.1,
            max_tokens=32,
            echo=echo,
            logprobs=logprobs,
            stream=True,
        )

        first = True
        for response in generator:
            if logprobs:
                assert response.choices[0].logprobs
                assert isinstance(response.choices[0].logprobs.tokens[0], str)
                if not (first and echo):
87
88
89
90
91
92
93
94
                    assert isinstance(
                        response.choices[0].logprobs.top_logprobs[0], dict
                    )
                    ret_num_top_logprobs = len(
                        response.choices[0].logprobs.top_logprobs[0]
                    )
                    # FIXME: Fix this bug. Sometimes, some top_logprobs are missing in the return value.
                    # assert ret_num_top_logprobs == logprobs, f"{ret_num_top_logprobs} vs {logprobs}"
95
96
97
98
99
100
101
102
103
104
105
106

            if first:
                if echo:
                    assert response.choices[0].text.startswith(prompt)
                first = False

            assert response.id
            assert response.created
            assert response.usage.prompt_tokens > 0
            assert response.usage.completion_tokens > 0
            assert response.usage.total_tokens > 0

107
    def run_chat_completion(self, logprobs):
108
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        response = 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,
            max_tokens=32,
            logprobs=logprobs is not None and logprobs > 0,
            top_logprobs=logprobs,
        )
        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}"

        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

    def run_chat_completion_stream(self, logprobs):
141
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
        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,
            max_tokens=32,
            logprobs=logprobs is not None and logprobs > 0,
            top_logprobs=logprobs,
            stream=True,
        )

        is_first = True
        for response in generator:
            data = response.choices[0].delta
            if is_first:
                data.role == "assistant"
                is_first = False
                continue

            if logprobs:
                # FIXME: Fix this bug. Return top_logprobs in the streaming mode.
                pass

            assert isinstance(data.content, str)

            assert response.id
            assert response.created

172
173
174
    def test_completion(self):
        for echo in [False, True]:
            for logprobs in [None, 5]:
175
176
                for use_list_input in [True, False]:
                    self.run_completion(echo, logprobs, use_list_input)
177
178

    def test_completion_stream(self):
179
180
        for echo in [False, True]:
            for logprobs in [None, 5]:
181
                self.run_completion_stream(echo, logprobs)
182

183
184
185
186
187
188
189
190
191
    def test_chat_completion(self):
        for logprobs in [None, 5]:
            self.run_chat_completion(logprobs)

    def test_chat_completion_stream(self):
        for logprobs in [None, 5]:
            self.run_chat_completion_stream(logprobs)

    def test_regex(self):
192
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220

        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)

221

222
if __name__ == "__main__":
223
    unittest.main(warnings="ignore")
224

225
226
227
228
    # t = TestOpenAIServer()
    # t.setUpClass()
    # t.test_chat_completion_stream()
    # t.tearDownClass()