protocol.py 9.39 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Copyright 2023-2024 SGLang Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

Lianmin Zheng's avatar
Lianmin Zheng committed
16
"""Pydantic models for OpenAI API protocol"""
Liangsheng Yin's avatar
Liangsheng Yin committed
17

18
19
import time
from typing import Dict, List, Optional, Union
Lianmin Zheng's avatar
Lianmin Zheng committed
20

21
from pydantic import BaseModel, Field
Lianmin Zheng's avatar
Lianmin Zheng committed
22
from typing_extensions import Literal
Lianmin Zheng's avatar
Lianmin Zheng committed
23

24

zhyncs's avatar
zhyncs committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class ModelCard(BaseModel):
    """Model cards."""

    id: str
    object: str = "model"
    created: int = Field(default_factory=lambda: int(time.time()))
    owned_by: str = "sglang"
    root: Optional[str] = None


class ModelList(BaseModel):
    """Model list consists of model cards."""

    object: str = "list"
    data: List[ModelCard] = []


42
43
44
45
46
47
48
49
class ErrorResponse(BaseModel):
    object: str = "error"
    message: str
    type: str
    param: Optional[str] = None
    code: int


50
51
52
53
54
55
56
class LogProbs(BaseModel):
    text_offset: List[int] = Field(default_factory=list)
    token_logprobs: List[Optional[float]] = Field(default_factory=list)
    tokens: List[str] = Field(default_factory=list)
    top_logprobs: List[Optional[Dict[str, float]]] = Field(default_factory=list)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class TopLogprob(BaseModel):
    token: str
    bytes: List[int]
    logprob: float


class ChatCompletionTokenLogprob(BaseModel):
    token: str
    bytes: List[int]
    logprob: float
    top_logprobs: List[TopLogprob]


class ChoiceLogprobs(BaseModel):
    # build for v1/chat/completions response
    content: List[ChatCompletionTokenLogprob]


75
76
77
78
79
80
class UsageInfo(BaseModel):
    prompt_tokens: int = 0
    total_tokens: int = 0
    completion_tokens: Optional[int] = 0


81
82
83
84
class StreamOptions(BaseModel):
    include_usage: Optional[bool] = False


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class FileRequest(BaseModel):
    # https://platform.openai.com/docs/api-reference/files/create
    file: bytes  # The File object (not file name) to be uploaded
    purpose: str = (
        "batch"  # The intended purpose of the uploaded file, default is "batch"
    )


class FileResponse(BaseModel):
    id: str
    object: str = "file"
    bytes: int
    created_at: int
    filename: str
    purpose: str


102
103
104
105
106
107
class FileDeleteResponse(BaseModel):
    id: str
    object: str = "file"
    deleted: bool


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
class BatchRequest(BaseModel):
    input_file_id: (
        str  # The ID of an uploaded file that contains requests for the new batch
    )
    endpoint: str  # The endpoint to be used for all requests in the batch
    completion_window: str  # The time frame within which the batch should be processed
    metadata: Optional[dict] = None  # Optional custom metadata for the batch


class BatchResponse(BaseModel):
    id: str
    object: str = "batch"
    endpoint: str
    errors: Optional[dict] = None
    input_file_id: str
    completion_window: str
    status: str = "validating"
    output_file_id: Optional[str] = None
    error_file_id: Optional[str] = None
    created_at: int
    in_progress_at: Optional[int] = None
    expires_at: Optional[int] = None
    finalizing_at: Optional[int] = None
    completed_at: Optional[int] = None
    failed_at: Optional[int] = None
    expired_at: Optional[int] = None
    cancelling_at: Optional[int] = None
    cancelled_at: Optional[int] = None
    request_counts: dict = {"total": 0, "completed": 0, "failed": 0}
    metadata: Optional[dict] = None


140
class CompletionRequest(BaseModel):
141
142
    # Ordered by official OpenAI API documentation
    # https://platform.openai.com/docs/api-reference/completions/create
143
    model: str
144
145
    prompt: Union[List[int], List[List[int]], str, List[str]]
    best_of: Optional[int] = None
146
147
148
    echo: Optional[bool] = False
    frequency_penalty: Optional[float] = 0.0
    logit_bias: Optional[Dict[str, float]] = None
149
150
151
152
153
154
155
    logprobs: Optional[int] = None
    max_tokens: Optional[int] = 16
    n: int = 1
    presence_penalty: Optional[float] = 0.0
    seed: Optional[int] = None
    stop: Optional[Union[str, List[str]]] = Field(default_factory=list)
    stream: Optional[bool] = False
156
    stream_options: Optional[StreamOptions] = None
157
158
159
    suffix: Optional[str] = None
    temperature: Optional[float] = 1.0
    top_p: Optional[float] = 1.0
160
161
    user: Optional[str] = None

162
163
    # Extra parameters for SRT backend only and will be ignored by OpenAI models.
    regex: Optional[str] = None
164
    json_schema: Optional[str] = None
Mingyi's avatar
Mingyi committed
165
    ignore_eos: Optional[bool] = False
166
167
168
    min_tokens: Optional[int] = 0
    repetition_penalty: Optional[float] = 1.0
    stop_token_ids: Optional[List[int]] = Field(default_factory=list)
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

class CompletionResponseChoice(BaseModel):
    index: int
    text: str
    logprobs: Optional[LogProbs] = None
    finish_reason: Optional[str] = None


class CompletionResponse(BaseModel):
    id: str
    object: str = "text_completion"
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
    choices: List[CompletionResponseChoice]
    usage: UsageInfo


class CompletionResponseStreamChoice(BaseModel):
    index: int
    text: str
    logprobs: Optional[LogProbs] = None
    finish_reason: Optional[str] = None


class CompletionStreamResponse(BaseModel):
    id: str
    object: str = "text_completion"
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
    choices: List[CompletionResponseStreamChoice]
200
    usage: Optional[UsageInfo] = None
Cody Yu's avatar
Cody Yu committed
201
202


203
204
205
206
207
208
209
210
211
212
213
214
215
class ChatCompletionMessageContentTextPart(BaseModel):
    type: Literal["text"]
    text: str


class ChatCompletionMessageContentImageURL(BaseModel):
    url: str
    detail: Optional[Literal["auto", "low", "high"]] = "auto"


class ChatCompletionMessageContentImagePart(BaseModel):
    type: Literal["image_url"]
    image_url: ChatCompletionMessageContentImageURL
216
    modalities: Optional[Literal["image", "multi-images", "video"]] = "image"
217
218
219
220
221
222
223


ChatCompletionMessageContentPart = Union[
    ChatCompletionMessageContentTextPart, ChatCompletionMessageContentImagePart
]


224
225
226
227
228
class ChatCompletionMessageGenericParam(BaseModel):
    role: Literal["system", "assistant"]
    content: Union[str, List[ChatCompletionMessageContentTextPart]]


229
230
231
232
233
234
235
236
237
238
class ChatCompletionMessageUserParam(BaseModel):
    role: Literal["user"]
    content: Union[str, List[ChatCompletionMessageContentPart]]


ChatCompletionMessageParam = Union[
    ChatCompletionMessageGenericParam, ChatCompletionMessageUserParam
]


239
240
241
242
243
class ResponseFormat(BaseModel):
    # type must be "json_object" or "text"
    type: Literal["text", "json_object"]


Cody Yu's avatar
Cody Yu committed
244
class ChatCompletionRequest(BaseModel):
245
246
247
    # Ordered by official OpenAI API documentation
    # https://platform.openai.com/docs/api-reference/chat/create
    messages: List[ChatCompletionMessageParam]
Cody Yu's avatar
Cody Yu committed
248
    model: str
249
250
251
252
    frequency_penalty: Optional[float] = 0.0
    logit_bias: Optional[Dict[str, float]] = None
    logprobs: Optional[bool] = False
    top_logprobs: Optional[int] = None
253
    max_tokens: Optional[int] = None
Cody Yu's avatar
Cody Yu committed
254
    n: Optional[int] = 1
255
256
257
    presence_penalty: Optional[float] = 0.0
    response_format: Optional[ResponseFormat] = None
    seed: Optional[int] = None
Cody Yu's avatar
Cody Yu committed
258
259
    stop: Optional[Union[str, List[str]]] = Field(default_factory=list)
    stream: Optional[bool] = False
260
    stream_options: Optional[StreamOptions] = None
261
262
    temperature: Optional[float] = 0.7
    top_p: Optional[float] = 1.0
Cody Yu's avatar
Cody Yu committed
263
264
    user: Optional[str] = None

265
266
    # Extra parameters for SRT backend only and will be ignored by OpenAI models.
    regex: Optional[str] = None
267
    json_schema: Optional[str] = None
268
269
270
    min_tokens: Optional[int] = 0
    repetition_penalty: Optional[float] = 1.0
    stop_token_ids: Optional[List[int]] = Field(default_factory=list)
271

Cody Yu's avatar
Cody Yu committed
272
273
274
275
276
277
278
279
280

class ChatMessage(BaseModel):
    role: Optional[str] = None
    content: Optional[str] = None


class ChatCompletionResponseChoice(BaseModel):
    index: int
    message: ChatMessage
281
282
    logprobs: Optional[Union[LogProbs, ChoiceLogprobs]] = None
    finish_reason: str
Cody Yu's avatar
Cody Yu committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301


class ChatCompletionResponse(BaseModel):
    id: str
    object: str = "chat.completion"
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
    choices: List[ChatCompletionResponseChoice]
    usage: UsageInfo


class DeltaMessage(BaseModel):
    role: Optional[str] = None
    content: Optional[str] = None


class ChatCompletionResponseStreamChoice(BaseModel):
    index: int
    delta: DeltaMessage
yichuan~'s avatar
yichuan~ committed
302
    logprobs: Optional[Union[LogProbs, ChoiceLogprobs]] = None
Cody Yu's avatar
Cody Yu committed
303
304
305
306
307
308
309
310
    finish_reason: Optional[str] = None


class ChatCompletionStreamResponse(BaseModel):
    id: str
    object: str = "chat.completion.chunk"
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
Liangsheng Yin's avatar
Liangsheng Yin committed
311
    choices: List[ChatCompletionResponseStreamChoice]
312
    usage: Optional[UsageInfo] = None
313
314
315
316
317
318
319
320
321
322
323
324


class EmbeddingRequest(BaseModel):
    # Ordered by official OpenAI API documentation
    # https://platform.openai.com/docs/api-reference/embeddings/create
    input: Union[List[int], List[List[int]], str, List[str]]
    model: str
    encoding_format: str = "float"
    dimensions: int = None
    user: Optional[str] = None


Ying Sheng's avatar
Ying Sheng committed
325
326
327
class EmbeddingObject(BaseModel):
    embedding: List[float]
    index: int
328
    object: str = "embedding"
Ying Sheng's avatar
Ying Sheng committed
329
330
331
332
333
334


class EmbeddingResponse(BaseModel):
    data: List[EmbeddingObject]
    model: str
    object: str = "list"
335
    usage: Optional[UsageInfo] = None