-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathopenai_api_protocol.py
More file actions
446 lines (353 loc) · 15.9 KB
/
openai_api_protocol.py
File metadata and controls
446 lines (353 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
137
138
139
140
141
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
172
173
174
175
176
177
178
179
180
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
371
372
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
"""Protocols in MLC LLM for OpenAI API.
Adapted from FastChat's OpenAI protocol:
https://github.com/lm-sys/FastChat/blob/main/fastchat/protocol/openai_api_protocol.py
"""
# pylint: disable=missing-class-docstring
import json
import time
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
import shortuuid
from pydantic import BaseModel, Field, field_validator, model_validator
from .conversation_protocol import Conversation
from .debug_protocol import DebugConfig
from .error_protocol import BadRequestError
################ Commons ################
# OPenAI API compatible limits
CHAT_COMPLETION_MAX_TOP_LOGPROBS = 20
COMPLETION_MAX_TOP_LOGPROBS = 5
class ListResponse(BaseModel):
object: str = "list"
data: List[Any]
class TopLogProbs(BaseModel):
token: str
logprob: float
bytes: Optional[List[int]]
class LogProbsContent(BaseModel):
token: str
logprob: float
bytes: Optional[List[int]]
top_logprobs: List[TopLogProbs] = []
class LogProbs(BaseModel):
content: List[LogProbsContent]
class CompletionLogProbs(BaseModel):
# The position of the token in the concatenated str: prompt + completion_text
# TODO(vvchernov): skip optional after support
text_offset: Optional[List[int]]
token_logprobs: List[float]
tokens: List[str]
top_logprobs: List[Dict[str, float]]
class CompletionUsage(BaseModel):
prompt_tokens: int
completion_tokens: int
total_tokens: int
extra: Optional[Dict[str, Any]] = None
"""Extra metrics and info that may be returned by debug_config
"""
class StreamOptions(BaseModel):
include_usage: Optional[bool]
################ v1/models ################
class ModelResponse(BaseModel):
"""OpenAI "v1/models" response protocol.
API reference: https://platform.openai.com/docs/api-reference/models/object
"""
id: str
created: int = Field(default_factory=lambda: int(time.time()))
object: str = "model"
owned_by: str = "MLC-LLM"
################ v1/completions ################
class RequestResponseFormat(BaseModel):
type: Literal["text", "json_object", "structural_tag"] = "text"
"""This field is named json_schema instead of schema because BaseModel defines a method called
schema. During construction of RequestResponseFormat, key "schema" still should be used:
`RequestResponseFormat(type="json_object", schema="{}")`
"""
json_schema: Optional[str] = Field(default=None, alias="schema")
"""These field are only used for type="structural_tag"."""
tags: Optional[List[Dict[str, str]]] = Field(default=None, alias="tags")
triggers: Optional[List[str]] = Field(default=None, alias="triggers")
@model_validator(mode="after")
def check_request_response_format(self) -> "RequestResponseFormat":
"""Check if the RequestResponseFormat is valid."""
if self.type == "structural_tag":
if self.tags is None or self.triggers is None:
raise ValueError("structural_tag type must contain keys 'tags' and 'triggers'.")
for tag in self.tags:
if set(tag.keys()) != {"begin", "schema", "end"}:
raise ValueError(
f"Each tag must contain exactly 'begin', 'schema' and 'end' keys. Got keys: {list(tag.keys())}."
)
elif self.tags is not None or self.triggers is not None:
raise Warning(
"'tags' and 'triggers' attributes should be used when type='structural_tag'"
)
return self
class CompletionRequest(BaseModel):
"""OpenAI completion request protocol.
API reference: https://platform.openai.com/docs/api-reference/completions/create
"""
model: Optional[str] = None
prompt: Union[str, List[int]]
best_of: int = 1
echo: bool = False
frequency_penalty: Optional[float] = None
presence_penalty: Optional[float] = None
logprobs: Optional[int] = None
logit_bias: Optional[Dict[int, float]] = None
max_tokens: Optional[int] = None
n: int = 1
seed: Optional[int] = None
stop: Optional[Union[str, List[str]]] = None
stream: bool = False
stream_options: Optional[StreamOptions] = None
suffix: Optional[str] = None
temperature: Optional[float] = None
top_p: Optional[float] = None
user: Optional[str] = None
response_format: Optional[RequestResponseFormat] = None
debug_config: Optional[DebugConfig] = None
@field_validator("frequency_penalty", "presence_penalty")
@classmethod
def check_penalty_range(cls, penalty_value: Optional[float]) -> Optional[float]:
"""Check if the penalty value is in range [-2, 2]."""
if penalty_value and (penalty_value < -2 or penalty_value > 2):
raise ValueError("Penalty value should be in range [-2, 2].")
return penalty_value
@field_validator("logit_bias")
@classmethod
def check_logit_bias(
cls, logit_bias_value: Optional[Dict[int, float]]
) -> Optional[Dict[int, float]]:
"""Check if the logit bias key is given as an integer."""
if logit_bias_value is None:
return None
for token_id, bias in logit_bias_value.items():
if abs(bias) > 100:
raise ValueError(
"Logit bias value should be in range [-100, 100], while value "
f"{bias} is given for token id {token_id}"
)
return logit_bias_value
@model_validator(mode="after")
def check_logprobs(self) -> "CompletionRequest":
"""Check if the logprobs requirements are valid."""
if self.logprobs is not None and (
self.logprobs < 0 or self.logprobs > COMPLETION_MAX_TOP_LOGPROBS
):
raise ValueError(f'"logprobs" must be in range [0, {COMPLETION_MAX_TOP_LOGPROBS}]')
return self
class CompletionResponseChoice(BaseModel):
finish_reason: Optional[Literal["stop", "length", "preempt"]] = None
index: int = 0
logprobs: Optional[CompletionLogProbs] = None
text: str
class CompletionResponse(BaseModel):
"""OpenAI completion response protocol.
API reference: https://platform.openai.com/docs/api-reference/completions/object
"""
id: str
choices: List[CompletionResponseChoice]
created: int = Field(default_factory=lambda: int(time.time()))
model: Optional[str] = None
object: str = "text_completion"
usage: Optional[CompletionUsage] = None
################ v1/chat/completions ################
class ChatFunction(BaseModel):
description: Optional[str] = None
name: str
parameters: Dict
strict: bool = True
class ChatTool(BaseModel):
type: Literal["function"]
function: ChatFunction
class ChatFunctionCall(BaseModel):
name: str
arguments: Union[None, Dict[str, Any]] = None
class ChatToolCall(BaseModel):
id: str = Field(default_factory=lambda: f"call_{shortuuid.random()}")
type: Literal["function"]
function: ChatFunctionCall
class ChatCompletionMessage(BaseModel):
content: Optional[Union[str, List[Dict]]] = None
role: Literal["system", "user", "assistant", "tool"]
name: Optional[str] = None
tool_calls: Optional[List[ChatToolCall]] = None
tool_call_id: Optional[str] = None
class ChatCompletionRequest(BaseModel):
"""OpenAI chat completion request protocol.
API reference: https://platform.openai.com/docs/api-reference/chat/create
"""
messages: List[ChatCompletionMessage]
model: Optional[str] = None
frequency_penalty: Optional[float] = None
presence_penalty: Optional[float] = None
logprobs: bool = False
top_logprobs: int = 0
logit_bias: Optional[Dict[int, float]] = None
max_tokens: Optional[int] = None
n: int = 1
seed: Optional[int] = None
stop: Optional[Union[str, List[str]]] = None
stream: bool = False
stream_options: Optional[StreamOptions] = None
temperature: Optional[float] = None
top_p: Optional[float] = None
tools: Optional[List[ChatTool]] = None
tool_choice: Optional[Union[Literal["none", "auto"], Dict]] = None
user: Optional[str] = None
response_format: Optional[RequestResponseFormat] = None
# NOTE: debug_config is not part of OpenAI protocol
# we add it to enable extra debug options
debug_config: Optional[DebugConfig] = None
@field_validator("frequency_penalty", "presence_penalty")
@classmethod
def check_penalty_range(cls, penalty_value: Optional[float]) -> Optional[float]:
"""Check if the penalty value is in range [-2, 2]."""
if penalty_value and (penalty_value < -2 or penalty_value > 2):
raise ValueError("Penalty value should be in range [-2, 2].")
return penalty_value
@field_validator("logit_bias")
@classmethod
def check_logit_bias(
cls, logit_bias_value: Optional[Dict[int, float]]
) -> Optional[Dict[int, float]]:
"""Check if the logit bias key is given as an integer."""
if logit_bias_value is None:
return None
for token_id, bias in logit_bias_value.items():
if abs(bias) > 100:
raise ValueError(
"Logit bias value should be in range [-100, 100], while value "
f"{bias} is given for token id {token_id}"
)
return logit_bias_value
@model_validator(mode="after")
def check_logprobs(self) -> "ChatCompletionRequest":
"""Check if the logprobs requirements are valid."""
if self.top_logprobs < 0 or self.top_logprobs > CHAT_COMPLETION_MAX_TOP_LOGPROBS:
raise ValueError(
f'"top_logprobs" must be in range [0, {CHAT_COMPLETION_MAX_TOP_LOGPROBS}]'
)
if not self.logprobs and self.top_logprobs > 0:
raise ValueError('"logprobs" must be True to support "top_logprobs"')
return self
@model_validator(mode="after")
def check_stream_options(self) -> "ChatCompletionRequest":
"""Check stream options"""
if self.stream_options is None:
return self
if not self.stream:
raise ValueError("stream must be set to True when stream_options is present")
return self
@model_validator(mode="after")
def check_debug_config(self) -> "ChatCompletionRequest":
"""Check debug config"""
if self.debug_config is None:
return self
if self.debug_config.special_request is None:
return self
if not self.stream:
raise ValueError("DebugConfig.special_request requires stream=True")
if self.stream_options is None or not self.stream_options.include_usage:
raise ValueError("DebugConfig.special_request requires include_usage in stream_options")
return self
def check_message_validity(self) -> None:
"""Check if the given chat messages are valid. Return error message if invalid."""
for i, message in enumerate(self.messages):
if message.role == "system" and i != 0:
raise BadRequestError(
f"System prompt at position {i} in the message list is invalid."
)
if message.tool_call_id is not None:
if message.role != "tool":
raise BadRequestError("Non-tool message having `tool_call_id` is invalid.")
if isinstance(message.content, list):
if message.role != "user":
raise BadRequestError("Non-user message having a list of content is invalid.")
if message.tool_calls is not None:
if message.role != "assistant":
raise BadRequestError("Non-assistant message having `tool_calls` is invalid.")
raise BadRequestError("Assistant message having `tool_calls` is not supported yet.")
def check_function_call_usage(self, conv_template: Conversation) -> None:
"""Check if function calling is used and update the conversation template.
Return error message if invalid request format for function calling.
"""
# return if no tools are provided or tool_choice is set to none
if self.tools is None or (isinstance(self.tool_choice, str) and self.tool_choice == "none"):
conv_template.use_function_calling = False
return
# select the tool based on the tool_choice if specified
if isinstance(self.tool_choice, dict):
if self.tool_choice["type"] != "function": # pylint: disable=unsubscriptable-object
raise BadRequestError("Only 'function' tool choice is supported")
if len(self.tool_choice["function"]) > 1: # pylint: disable=unsubscriptable-object
raise BadRequestError("Only one tool is supported when tool_choice is specified")
for tool in self.tools: # pylint: disable=not-an-iterable
if (
tool.function.name
== self.tool_choice["function"][ # pylint: disable=unsubscriptable-object
"name"
]
):
conv_template.use_function_calling = True
conv_template.function_string = tool.function.model_dump_json(by_alias=True)
return
# pylint: disable=unsubscriptable-object
raise BadRequestError(
f"The tool_choice function {self.tool_choice['function']['name']}"
" is not found in the tools list"
)
# pylint: enable=unsubscriptable-object
if isinstance(self.tool_choice, str) and self.tool_choice != "auto":
raise BadRequestError(f"Invalid tool_choice value: {self.tool_choice}")
function_list = []
for tool in self.tools: # pylint: disable=not-an-iterable
if tool.type != "function":
raise BadRequestError("Only 'function' tool type is supported")
function_list.append(tool.function.model_dump(by_alias=True))
conv_template.use_function_calling = True
conv_template.function_string = json.dumps(function_list)
class ChatCompletionResponseChoice(BaseModel):
finish_reason: Optional[Literal["stop", "length", "tool_calls", "error"]] = None
index: int = 0
message: ChatCompletionMessage
logprobs: Optional[LogProbs] = None
class ChatCompletionStreamResponseChoice(BaseModel):
finish_reason: Optional[Literal["stop", "length", "tool_calls", "error"]] = None
index: int = 0
delta: ChatCompletionMessage
logprobs: Optional[LogProbs] = None
class ChatCompletionResponse(BaseModel):
"""OpenAI completion response protocol.
API reference: https://platform.openai.com/docs/api-reference/chat/object
"""
id: str
choices: List[ChatCompletionResponseChoice]
created: int = Field(default_factory=lambda: int(time.time()))
model: Optional[str] = None
system_fingerprint: str
object: Literal["chat.completion"] = "chat.completion"
usage: Optional[CompletionUsage] = None
class ChatCompletionStreamResponse(BaseModel):
"""OpenAI completion stream response protocol.
API reference: https://platform.openai.com/docs/api-reference/chat/streaming
"""
id: str
choices: List[ChatCompletionStreamResponseChoice]
created: int = Field(default_factory=lambda: int(time.time()))
model: Optional[str] = None
system_fingerprint: str
object: Literal["chat.completion.chunk"] = "chat.completion.chunk"
usage: Optional[CompletionUsage] = None
################################################
def openai_api_get_unsupported_fields(
request: Union[CompletionRequest, ChatCompletionRequest],
) -> List[str]:
"""Get the unsupported fields in the request."""
unsupported_field_default_values: List[Tuple[str, Any]] = [
("best_of", 1),
]
unsupported_fields: List[str] = []
for field, value in unsupported_field_default_values:
if hasattr(request, field) and getattr(request, field) != value:
unsupported_fields.append(field)
return unsupported_fields