openai.py 9.35 KB
Newer Older
1
2
import logging
import time
3
from typing import Callable, List, Optional, Union
Lianmin Zheng's avatar
Lianmin Zheng committed
4
5

import numpy as np
Liangsheng Yin's avatar
Liangsheng Yin committed
6

Lianmin Zheng's avatar
Lianmin Zheng committed
7
from sglang.backend.base_backend import BaseBackend
Lianmin Zheng's avatar
Lianmin Zheng committed
8
from sglang.lang.chat_template import ChatTemplate, get_chat_template_by_model_path
Lianmin Zheng's avatar
Lianmin Zheng committed
9
from sglang.lang.interpreter import StreamExecutor
10
from sglang.lang.ir import SglSamplingParams
Lianmin Zheng's avatar
Lianmin Zheng committed
11
12

try:
13
    import openai
Liangsheng Yin's avatar
Liangsheng Yin committed
14
    import tiktoken
Lianmin Zheng's avatar
Lianmin Zheng committed
15
16
17
18
except ImportError as e:
    openai = tiktoken = e


19
20
21
logger = logging.getLogger("openai")


Lianmin Zheng's avatar
Lianmin Zheng committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def create_logit_bias_int(tokenizer):
    """Get logit bias for integer numbers."""
    int_token_ids = []

    tokens = tokenizer._mergeable_ranks
    for token, token_id in tokens.items():
        s = tokenizer.decode([token_id])
        if all([c.isdigit() for c in s]) or s in [" "]:
            int_token_ids.append(token_id)
            if len(int_token_ids) >= 300:  # OpenAI API limit
                break
    special_tokens = tokenizer._special_tokens
    mask = {t: 100 for t in int_token_ids[:299]}
    mask[special_tokens["<|endoftext|>"]] = 100
    return mask


39
40
INSTRUCT_MODEL_NAMES = [
    "gpt-3.5-turbo-instruct",
Lianmin Zheng's avatar
Lianmin Zheng committed
41
42
43
44
]


class OpenAI(BaseBackend):
Lianmin Zheng's avatar
Lianmin Zheng committed
45
46
47
48
49
50
51
52
53
    def __init__(
        self,
        model_name: str,
        is_chat_model: Optional[bool] = None,
        chat_template: Optional[ChatTemplate] = None,
        is_azure: bool = False,
        *args,
        **kwargs,
    ):
Lianmin Zheng's avatar
Lianmin Zheng committed
54
55
56
        super().__init__()

        if isinstance(openai, Exception):
57
            raise openai
Lianmin Zheng's avatar
Lianmin Zheng committed
58

59
60
61
62
63
        if is_azure:
            self.client = openai.AzureOpenAI(*args, **kwargs)
        else:
            self.client = openai.OpenAI(*args, **kwargs)

Lianmin Zheng's avatar
Lianmin Zheng committed
64
        self.model_name = model_name
65
66
67
68
        try:
            self.tokenizer = tiktoken.encoding_for_model(model_name)
        except KeyError:
            self.tokenizer = tiktoken.get_encoding("cl100k_base")
Lianmin Zheng's avatar
Lianmin Zheng committed
69
70
        self.logit_bias_int = create_logit_bias_int(self.tokenizer)

Lianmin Zheng's avatar
Lianmin Zheng committed
71
72
73
        self.chat_template = chat_template or get_chat_template_by_model_path(
            model_name
        )
74
75
76

        if is_chat_model is not None:
            self.is_chat_model = is_chat_model
77
        else:
78
79
80
81
            if model_name in INSTRUCT_MODEL_NAMES:
                self.is_chat_model = False
            else:
                self.is_chat_model = True
Lianmin Zheng's avatar
Lianmin Zheng committed
82

83
        self.chat_begin_str = self.chat_template.role_prefix_and_suffix["assistant"][0]
Lianmin Zheng's avatar
Lianmin Zheng committed
84
85
86
87
88
89
90

    def get_chat_template(self):
        return self.chat_template

    def generate(
        self,
        s: StreamExecutor,
91
        sampling_params: SglSamplingParams,
Lianmin Zheng's avatar
Lianmin Zheng committed
92
93
94
    ):
        if sampling_params.dtype is None:
            if self.is_chat_model:
95
                if not s.text_.endswith(self.chat_begin_str):
Ying Sheng's avatar
Ying Sheng committed
96
97
98
99
                    raise RuntimeError(
                        "This use case is not supported. "
                        "For OpenAI chat models, sgl.gen must be right after sgl.assistant"
                    )
Lianmin Zheng's avatar
Lianmin Zheng committed
100
101
102
103
104
105
106
107
108
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
                prompt = s.messages_
            else:
                prompt = s.text_

            kwargs = sampling_params.to_openai_kwargs()
            comp = openai_completion(
                client=self.client,
                is_chat=self.is_chat_model,
                model=self.model_name,
                prompt=prompt,
                **kwargs,
            )
        elif sampling_params.dtype in [str, "str", "string"]:
            kwargs = sampling_params.to_openai_kwargs()
            kwargs.pop("stop")
            comp = openai_completion(
                client=self.client,
                is_chat=self.is_chat_model,
                model=self.model_name,
                prompt=s.text_ + '"',
                stop='"',
                **kwargs,
            )
            comp = '"' + comp + '"'
        elif sampling_params.dtype in [int, "int"]:
            kwargs = sampling_params.to_openai_kwargs()
            kwargs.pop("stop")
            comp = openai_completion(
                client=self.client,
                is_chat=self.is_chat_model,
                model=self.model_name,
                prompt=s.text_,
                logit_bias=self.logit_bias_int,
                stop=[" "],
                **kwargs,
            )
        else:
Yaya Sy's avatar
Yaya Sy committed
137
            raise ValueError(f"Unknown dtype: {sampling_params.dtype}")
Lianmin Zheng's avatar
Lianmin Zheng committed
138
139
140
141
142
143

        return comp, {}

    def generate_stream(
        self,
        s: StreamExecutor,
144
        sampling_params: SglSamplingParams,
Lianmin Zheng's avatar
Lianmin Zheng committed
145
146
147
    ):
        if sampling_params.dtype is None:
            if self.is_chat_model:
148
149
150
151
152
                if not s.text_.endswith(self.chat_begin_str):
                    raise RuntimeError(
                        "This use case is not supported. "
                        "For OpenAI chat models, sgl.gen must be right after sgl.assistant"
                    )
Lianmin Zheng's avatar
Lianmin Zheng committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
                prompt = s.messages_
            else:
                prompt = s.text_

            kwargs = sampling_params.to_openai_kwargs()
            generator = openai_completion_stream(
                client=self.client,
                is_chat=self.is_chat_model,
                model=self.model_name,
                prompt=prompt,
                **kwargs,
            )
            return generator
        else:
167
            raise ValueError(f"Unknown dtype: {sampling_params.dtype}")
Lianmin Zheng's avatar
Lianmin Zheng committed
168
169
170
171
172
173
174

    def select(
        self,
        s: StreamExecutor,
        choices: List[str],
        temperature: float,
    ):
175
176
177
178
179
180
        if self.is_chat_model:
            raise NotImplementedError(
                "select/choices is not supported for chat models. "
                "Please try to use a non-chat model such as gpt-3.5-turbo-instruct"
            )

Lianmin Zheng's avatar
Lianmin Zheng committed
181
182
183
184
185
186
187
188
189
190
191
192
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
221
222
223
224
225
226
227
228
229
230
        n_choices = len(choices)
        token_ids = [self.tokenizer.encode(x) for x in choices]
        scores = [0] * n_choices
        valid = [len(x) > 0 for x in token_ids]
        prompt_tokens = self.tokenizer.encode(s.text_)

        max_len = max([len(x) for x in token_ids])
        for step in range(max_len):
            # Build logit bias
            logit_bias = {}
            for i in range(n_choices):
                if valid[i]:
                    logit_bias[token_ids[i][step]] = 100

            # Call API
            ret = self.client.completions.create(
                model=self.model_name,
                prompt=prompt_tokens,
                logit_bias=logit_bias,
                max_tokens=1,
                temperature=temperature,
            )
            ret_str = ret.choices[0].text
            ret_token = self.tokenizer.encode(ret_str)[0]

            # TODO:
            # 1. return logits as the scores
            # 2. compute logits of the full choice
            # 3. consider chunk-based decoding

            # Update valid
            hit = False
            for i in range(n_choices):
                if valid[i]:
                    if step == len(token_ids[i]) - 1:
                        valid[i] = False

                    if ret_token == token_ids[i][step]:
                        scores[i] += 1
                        hit = True
                    else:
                        valid[i] = False
            assert hit

            if np.sum(valid) <= 1:
                break

            prompt_tokens.append(ret_token)

        decision = choices[np.argmax(scores)]
231
        return decision, scores, scores
Lianmin Zheng's avatar
Lianmin Zheng committed
232
233


234
235
236
237
238
239
240
241
def openai_completion(client, retries=3, is_chat=None, prompt=None, **kwargs):
    for attempt in range(retries):
        try:
            if is_chat:
                if "stop" in kwargs and kwargs["stop"] is None:
                    kwargs.pop("stop")
                ret = client.chat.completions.create(messages=prompt, **kwargs)
                comp = ret.choices[0].message.content
Lianmin Zheng's avatar
Lianmin Zheng committed
242
            else:
243
244
245
246
247
248
249
250
251
252
253
254
255
256
                ret = client.completions.create(prompt=prompt, **kwargs)
                if isinstance(prompt, (list, tuple)):
                    comp = [c.text for c in ret.choices]
                else:
                    comp = ret.choices[0].text
            break
        except (openai.APIError, openai.APIConnectionError, openai.RateLimitError) as e:
            logger.error(f"OpenAI Error: {e}. Waiting 5 seconds...")
            time.sleep(5)
            if attempt == retries - 1:
                raise e
        except Exception as e:
            logger.error(f"RuntimeError {e}.")
            raise e
Lianmin Zheng's avatar
Lianmin Zheng committed
257
258
259
260

    return comp


261
262
263
264
265
266
267
268
269
270
def openai_completion_stream(client, retries=3, is_chat=None, prompt=None, **kwargs):
    for attempt in range(retries):
        try:
            if is_chat:
                if "stop" in kwargs and kwargs["stop"] is None:
                    kwargs.pop("stop")
                generator = client.chat.completions.create(
                    messages=prompt, stream=True, **kwargs
                )
                for ret in generator:
271
272
273
274
                    try:
                        content = ret.choices[0].delta.content
                    except IndexError:
                        content = None
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
                    yield content or "", {}
            else:
                generator = client.completions.create(
                    prompt=prompt, stream=True, **kwargs
                )
                for ret in generator:
                    content = ret.choices[0].text
                    yield content or "", {}
            break
        except (openai.APIError, openai.APIConnectionError, openai.RateLimitError) as e:
            logger.error(f"OpenAI Error: {e}. Waiting 5 seconds...")
            time.sleep(5)
            if attempt == retries - 1:
                raise e
        except Exception as e:
            logger.error(f"RuntimeError {e}.")
            raise e