protocol.py 61.1 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
# Adapted from
# https://github.com/lm-sys/FastChat/blob/168ccc29d3f7edc50823016105c024fe2282732a/fastchat/protocol/openai_api_protocol.py
6
import json
Zhuohan Li's avatar
Zhuohan Li committed
7
import time
8
from http import HTTPStatus
9
from typing import Annotated, Any, ClassVar, Literal, TypeAlias
Zhuohan Li's avatar
Zhuohan Li committed
10

11
import regex as re
12
import torch
13
from fastapi import HTTPException, UploadFile
14
15
16
17
18
from openai.types.responses import (
    ResponseCodeInterpreterCallCodeDeltaEvent,
    ResponseCodeInterpreterCallCodeDoneEvent,
    ResponseCodeInterpreterCallCompletedEvent,
    ResponseCodeInterpreterCallInProgressEvent,
19
20
21
22
23
    ResponseCodeInterpreterCallInterpretingEvent,
    ResponseContentPartAddedEvent,
    ResponseContentPartDoneEvent,
    ResponseFunctionToolCall,
    ResponseInputItemParam,
24
25
26
27
    ResponseMcpCallArgumentsDeltaEvent,
    ResponseMcpCallArgumentsDoneEvent,
    ResponseMcpCallCompletedEvent,
    ResponseMcpCallInProgressEvent,
28
29
30
31
32
33
34
35
36
37
38
    ResponseOutputItem,
    ResponseOutputItemAddedEvent,
    ResponseOutputItemDoneEvent,
    ResponsePrompt,
    ResponseReasoningTextDeltaEvent,
    ResponseReasoningTextDoneEvent,
    ResponseStatus,
    ResponseWebSearchCallCompletedEvent,
    ResponseWebSearchCallInProgressEvent,
    ResponseWebSearchCallSearchingEvent,
)
39
from openai.types.responses import (
40
41
42
    ResponseCompletedEvent as OpenAIResponseCompletedEvent,
)
from openai.types.responses import ResponseCreatedEvent as OpenAIResponseCreatedEvent
43
from openai.types.responses import (
44
45
    ResponseInProgressEvent as OpenAIResponseInProgressEvent,
)
46
from openai.types.responses.response_reasoning_item import (
47
48
    Content as ResponseReasoningTextContent,
)
49
from openai_harmony import Message as OpenAIHarmonyMessage
50
51
52
53
54

# Backward compatibility for OpenAI client versions
try:  # For older openai versions (< 1.100.0)
    from openai.types.responses import ResponseTextConfig
except ImportError:  # For newer openai versions (>= 1.100.0)
55
    from openai.types.responses import ResponseFormatTextConfig as ResponseTextConfig
56

57

58
from openai.types.responses.response import IncompleteDetails, ToolChoice
59
60
from openai.types.responses.tool import Tool
from openai.types.shared import Metadata, Reasoning
61
62
63
64
from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
65
    ValidationError,
66
    field_serializer,
67
68
    model_validator,
)
Zhuohan Li's avatar
Zhuohan Li committed
69

70
from vllm.entrypoints.chat_utils import ChatCompletionMessageParam, make_tool_call_id
71
from vllm.exceptions import VLLMValidationError
72
from vllm.logger import init_logger
73
from vllm.logprobs import Logprob
74
75
76
77
78
79
from vllm.sampling_params import (
    BeamSearchParams,
    RequestOutputKind,
    SamplingParams,
    StructuredOutputsParams,
)
80
81
from vllm.utils import random_uuid
from vllm.utils.import_utils import resolve_obj_by_qualname
82

83
84
logger = init_logger(__name__)

85
_LONG_INFO = torch.iinfo(torch.long)
86

Zhuohan Li's avatar
Zhuohan Li committed
87

88
class OpenAIBaseModel(BaseModel):
89
90
91
    # OpenAI API does allow extra fields
    model_config = ConfigDict(extra="allow")

92
    # Cache class field names
93
    field_names: ClassVar[set[str] | None] = None
94

95
    @model_validator(mode="wrap")
96
    @classmethod
97
98
99
100
    def __log_extra_fields__(cls, data, handler):
        result = handler(data)
        if not isinstance(data, dict):
            return result
101
102
        field_names = cls.field_names
        if field_names is None:
103
104
105
106
            # Get all class field names and their potential aliases
            field_names = set()
            for field_name, field in cls.model_fields.items():
                field_names.add(field_name)
107
                if alias := getattr(field, "alias", None):
108
109
110
111
112
113
                    field_names.add(alias)
            cls.field_names = field_names

        # Compare against both field names and aliases
        if any(k not in field_names for k in data):
            logger.warning(
114
                "The following fields were present in the request but ignored: %s",
115
116
                data.keys() - field_names,
            )
117
        return result
118
119


120
class ErrorInfo(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
121
122
    message: str
    type: str
123
    param: str | None = None
124
    code: int
Zhuohan Li's avatar
Zhuohan Li committed
125
126


127
128
129
130
class ErrorResponse(OpenAIBaseModel):
    error: ErrorInfo


131
class ModelPermission(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
132
133
134
135
136
137
138
139
140
141
    id: str = Field(default_factory=lambda: f"modelperm-{random_uuid()}")
    object: str = "model_permission"
    created: int = Field(default_factory=lambda: int(time.time()))
    allow_create_engine: bool = False
    allow_sampling: bool = True
    allow_logprobs: bool = True
    allow_search_indices: bool = False
    allow_view: bool = True
    allow_fine_tuning: bool = False
    organization: str = "*"
142
    group: str | None = None
143
    is_blocking: bool = False
Zhuohan Li's avatar
Zhuohan Li committed
144
145


146
class ModelCard(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
147
148
149
    id: str
    object: str = "model"
    created: int = Field(default_factory=lambda: int(time.time()))
Woosuk Kwon's avatar
Woosuk Kwon committed
150
    owned_by: str = "vllm"
151
152
153
    root: str | None = None
    parent: str | None = None
    max_model_len: int | None = None
154
    permission: list[ModelPermission] = Field(default_factory=list)
Zhuohan Li's avatar
Zhuohan Li committed
155
156


157
class ModelList(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
158
    object: str = "list"
159
    data: list[ModelCard] = Field(default_factory=list)
Zhuohan Li's avatar
Zhuohan Li committed
160
161


162
class PromptTokenUsageInfo(OpenAIBaseModel):
163
    cached_tokens: int | None = None
164
165


166
class UsageInfo(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
167
168
    prompt_tokens: int = 0
    total_tokens: int = 0
169
170
    completion_tokens: int | None = 0
    prompt_tokens_details: PromptTokenUsageInfo | None = None
Zhuohan Li's avatar
Zhuohan Li committed
171
172


173
174
class RequestResponseMetadata(BaseModel):
    request_id: str
175
    final_usage_info: UsageInfo | None = None
176
177


178
179
class JsonSchemaResponseFormat(OpenAIBaseModel):
    name: str
180
    description: str | None = None
181
182
    # schema is the field in openai but that causes conflicts with pydantic so
    # instead use json_schema with an alias
183
184
    json_schema: dict[str, Any] | None = Field(default=None, alias="schema")
    strict: bool | None = None
185
186


187
class LegacyStructuralTag(OpenAIBaseModel):
188
189
190
    begin: str
    # schema is the field, but that causes conflicts with pydantic so
    # instead use structural_tag_schema with an alias
191
    structural_tag_schema: dict[str, Any] | None = Field(default=None, alias="schema")
192
193
194
    end: str


195
class LegacyStructuralTagResponseFormat(OpenAIBaseModel):
196
    type: Literal["structural_tag"]
197
    structures: list[LegacyStructuralTag]
198
199
200
    triggers: list[str]


201
202
203
204
205
206
207
208
209
210
class StructuralTagResponseFormat(OpenAIBaseModel):
    type: Literal["structural_tag"]
    format: Any


AnyStructuralTagResponseFormat: TypeAlias = (
    LegacyStructuralTagResponseFormat | StructuralTagResponseFormat
)


211
class ResponseFormat(OpenAIBaseModel):
212
    # type must be "json_schema", "json_object", or "text"
213
    type: Literal["text", "json_object", "json_schema"]
214
    json_schema: JsonSchemaResponseFormat | None = None
215
216


217
218
219
AnyResponseFormat: TypeAlias = (
    ResponseFormat | StructuralTagResponseFormat | LegacyStructuralTagResponseFormat
)
220
221


222
class StreamOptions(OpenAIBaseModel):
223
224
    include_usage: bool | None = True
    continuous_usage_stats: bool | None = False
225
226


227
228
class FunctionDefinition(OpenAIBaseModel):
    name: str
229
230
    description: str | None = None
    parameters: dict[str, Any] | None = None
231
232


233
234
# extra="forbid" is a workaround to have kwargs as a field,
# see https://github.com/pydantic/pydantic/issues/3125
235
236
class LogitsProcessorConstructor(BaseModel):
    qualname: str
237
238
    args: list[Any] | None = None
    kwargs: dict[str, Any] | None = None
239

240
241
    model_config = ConfigDict(extra="forbid")

242

243
LogitsProcessors = list[str | LogitsProcessorConstructor]
244
245


246
def get_logits_processors(
247
248
    processors: LogitsProcessors | None, pattern: str | None
) -> list[Any] | None:
249
250
251
    if processors and pattern:
        logits_processors = []
        for processor in processors:
252
            qualname = processor if isinstance(processor, str) else processor.qualname
253
254
255
256
            if not re.match(pattern, qualname):
                raise ValueError(
                    f"Logits processor '{qualname}' is not allowed by this "
                    "server. See --logits-processor-pattern engine argument "
257
258
                    "for more information."
                )
259
260
261
262
263
264
265
            try:
                logits_processor = resolve_obj_by_qualname(qualname)
            except Exception as e:
                raise ValueError(
                    f"Logits processor '{qualname}' could not be resolved: {e}"
                ) from e
            if isinstance(processor, LogitsProcessorConstructor):
266
267
268
                logits_processor = logits_processor(
                    *processor.args or [], **processor.kwargs or {}
                )
269
270
271
272
273
            logits_processors.append(logits_processor)
        return logits_processors
    elif processors:
        raise ValueError(
            "The `logits_processors` argument is not supported by this "
274
            "server. See --logits-processor-pattern engine argument "
275
276
            "for more information."
        )
277
278
279
    return None


280
ResponseInputOutputItem: TypeAlias = ResponseInputItemParam | ResponseOutputItem
281
282


283
284
285
class ResponsesRequest(OpenAIBaseModel):
    # Ordered by official OpenAI API documentation
    # https://platform.openai.com/docs/api-reference/responses/create
286
287
    background: bool | None = False
    include: (
288
289
290
291
292
293
294
295
296
297
        list[
            Literal[
                "code_interpreter_call.outputs",
                "computer_call_output.output.image_url",
                "file_search_call.results",
                "message.input_image.image_url",
                "message.output_text.logprobs",
                "reasoning.encrypted_content",
            ],
        ]
298
299
300
301
302
303
304
305
        | None
    ) = None
    input: str | list[ResponseInputOutputItem]
    instructions: str | None = None
    max_output_tokens: int | None = None
    max_tool_calls: int | None = None
    metadata: Metadata | None = None
    model: str | None = None
306
    logit_bias: dict[str, float] | None = None
307
308
309
310
    parallel_tool_calls: bool | None = True
    previous_response_id: str | None = None
    prompt: ResponsePrompt | None = None
    reasoning: Reasoning | None = None
311
    service_tier: Literal["auto", "default", "flex", "scale", "priority"] = "auto"
312
313
314
315
    store: bool | None = True
    stream: bool | None = False
    temperature: float | None = None
    text: ResponseTextConfig | None = None
316
317
    tool_choice: ToolChoice = "auto"
    tools: list[Tool] = Field(default_factory=list)
318
319
    top_logprobs: int | None = 0
    top_p: float | None = None
320
    top_k: int | None = None
321
322
    truncation: Literal["auto", "disabled"] | None = "disabled"
    user: str | None = None
323
324
325
326
327
328
329

    # --8<-- [start:responses-extra-params]
    request_id: str = Field(
        default_factory=lambda: f"resp_{random_uuid()}",
        description=(
            "The request_id related to this request. If the caller does "
            "not set it, a random_uuid will be generated. This id is used "
330
331
            "through out the inference process and return in response."
        ),
332
    )
333
    mm_processor_kwargs: dict[str, Any] | None = Field(
334
335
336
337
338
339
340
341
        default=None,
        description=("Additional kwargs to pass to the HF processor."),
    )
    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
342
343
            "if the served model does not use priority scheduling."
        ),
344
    )
345
    cache_salt: str | None = Field(
346
347
348
349
350
351
352
        default=None,
        description=(
            "If specified, the prefix cache will be salted with the provided "
            "string to prevent an attacker to guess prompts in multi-user "
            "environments. The salt should be random, protected from "
            "access by 3rd parties, and long enough to be "
            "unpredictable (e.g., 43 characters base64-encoded, corresponding "
353
            "to 256 bit)."
354
355
        ),
    )
356
357
358
359
360

    enable_response_messages: bool = Field(
        default=False,
        description=(
            "Dictates whether or not to return messages as part of the "
361
            "response object. Currently only supported for"
362
363
364
            "non-background and gpt-oss only. "
        ),
    )
365
366
367
368
369
    # similar to input_messages / output_messages in ResponsesResponse
    # we take in previous_input_messages (ie in harmony format)
    # this cannot be used in conjunction with previous_response_id
    # TODO: consider supporting non harmony messages as well
    previous_input_messages: list[OpenAIHarmonyMessage | dict] | None = None
370
371
372
373
374
    # --8<-- [end:responses-extra-params]

    _DEFAULT_SAMPLING_PARAMS = {
        "temperature": 1.0,
        "top_p": 1.0,
375
        "top_k": 0,
376
377
378
379
380
    }

    def to_sampling_params(
        self,
        default_max_tokens: int,
381
        default_sampling_params: dict | None = None,
382
383
384
385
386
387
388
389
390
    ) -> SamplingParams:
        if self.max_output_tokens is None:
            max_tokens = default_max_tokens
        else:
            max_tokens = min(self.max_output_tokens, default_max_tokens)

        default_sampling_params = default_sampling_params or {}
        if (temperature := self.temperature) is None:
            temperature = default_sampling_params.get(
391
392
                "temperature", self._DEFAULT_SAMPLING_PARAMS["temperature"]
            )
393
394
        if (top_p := self.top_p) is None:
            top_p = default_sampling_params.get(
395
396
                "top_p", self._DEFAULT_SAMPLING_PARAMS["top_p"]
            )
397
398
        if (top_k := self.top_k) is None:
            top_k = default_sampling_params.get(
399
                "top_k", self._DEFAULT_SAMPLING_PARAMS["top_k"]
400
            )
401
        stop_token_ids = default_sampling_params.get("stop_token_ids")
402

403
404
405
406
407
408
409
        # Structured output
        structured_outputs = None
        if self.text is not None and self.text.format is not None:
            response_format = self.text.format
            if (
                response_format.type == "json_schema"
                and response_format.schema_ is not None
410
            ):
411
412
                structured_outputs = StructuredOutputsParams(
                    json=response_format.schema_
413
                )
414
415
            elif response_format.type == "json_object":
                raise NotImplementedError("json_object is not supported")
416

417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
        # TODO: add more parameters
        return SamplingParams.from_optional(
            temperature=temperature,
            top_p=top_p,
            top_k=top_k,
            max_tokens=max_tokens,
            logprobs=self.top_logprobs if self.is_include_output_logprobs() else None,
            stop_token_ids=stop_token_ids,
            output_kind=(
                RequestOutputKind.DELTA if self.stream else RequestOutputKind.FINAL_ONLY
            ),
            structured_outputs=structured_outputs,
            logit_bias=self.logit_bias,
            skip_clone=True,  # Created fresh per request, safe to skip clone
        )
432

433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
    def is_include_output_logprobs(self) -> bool:
        """Check if the request includes output logprobs."""
        if self.include is None:
            return False
        return (
            isinstance(self.include, list)
            and "message.output_text.logprobs" in self.include
        )

    @model_validator(mode="before")
    def validate_background(cls, data):
        if not data.get("background"):
            return data
        if not data.get("store", True):
            raise ValueError("background can only be used when `store` is true")
448
449
        return data

450
    @model_validator(mode="before")
451
452
453
454
    def validate_prompt(cls, data):
        if data.get("prompt") is not None:
            raise VLLMValidationError(
                "prompt template is not supported", parameter="prompt"
455
            )
456
457
        return data

458
459
    @model_validator(mode="before")
    def check_cache_salt_support(cls, data):
460
461
462
463
464
465
        if data.get("cache_salt") is not None and (
            not isinstance(data["cache_salt"], str) or not data["cache_salt"]
        ):
            raise ValueError(
                "Parameter 'cache_salt' must be a non-empty string if provided."
            )
466
467
        return data

468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
    @model_validator(mode="before")
    def function_call_parsing(cls, data):
        """Parse function_call dictionaries into ResponseFunctionToolCall objects.
        This ensures Pydantic can properly resolve union types in the input field.
        Function calls provided as dicts are converted to ResponseFunctionToolCall
        objects before validation, while invalid structures are left for Pydantic
        to reject with appropriate error messages.
        """

        input_data = data.get("input")

        # Early return for None, strings, or bytes
        # (strings are iterable but shouldn't be processed)
        if input_data is None or isinstance(input_data, (str, bytes)):
            return data

        # Convert iterators (like ValidatorIterator) to list
        if not isinstance(input_data, list):
            try:
                input_data = list(input_data)
            except TypeError:
                # Not iterable, leave as-is for Pydantic to handle
                return data

        processed_input = []
        for item in input_data:
            if isinstance(item, dict) and item.get("type") == "function_call":
                try:
                    processed_input.append(ResponseFunctionToolCall(**item))
                except ValidationError:
                    # Let Pydantic handle validation for malformed function calls
                    logger.debug(
                        "Failed to parse function_call to ResponseFunctionToolCall, "
                        "leaving for Pydantic validation"
                    )
                    processed_input.append(item)
            else:
                processed_input.append(item)

        data["input"] = processed_input
        return data

Zhuohan Li's avatar
Zhuohan Li committed
510

511
class CompletionRequest(OpenAIBaseModel):
512
513
    # Ordered by official OpenAI API documentation
    # https://platform.openai.com/docs/api-reference/completions/create
514
515
516
517
518
519
520
    model: str | None = None
    prompt: list[int] | list[list[int]] | str | list[str] | None = None
    echo: bool | None = False
    frequency_penalty: float | None = 0.0
    logit_bias: dict[str, float] | None = None
    logprobs: int | None = None
    max_tokens: int | None = 16
521
    n: int = 1
522
523
524
525
526
527
528
529
530
    presence_penalty: float | None = 0.0
    seed: int | None = Field(None, ge=_LONG_INFO.min, le=_LONG_INFO.max)
    stop: str | list[str] | None = []
    stream: bool | None = False
    stream_options: StreamOptions | None = None
    suffix: str | None = None
    temperature: float | None = None
    top_p: float | None = None
    user: str | None = None
531

532
    # --8<-- [start:completion-sampling-params]
533
    use_beam_search: bool = False
534
535
536
    top_k: int | None = None
    min_p: float | None = None
    repetition_penalty: float | None = None
537
    length_penalty: float = 1.0
538
    stop_token_ids: list[int] | None = []
539
540
541
542
543
    include_stop_str_in_output: bool = False
    ignore_eos: bool = False
    min_tokens: int = 0
    skip_special_tokens: bool = True
    spaces_between_special_tokens: bool = True
544
545
546
    truncate_prompt_tokens: Annotated[int, Field(ge=-1, le=_LONG_INFO.max)] | None = (
        None
    )
547
548
    allowed_token_ids: list[int] | None = None
    prompt_logprobs: int | None = None
549
    # --8<-- [end:completion-sampling-params]
550

551
    # --8<-- [start:completion-extra-params]
552
    prompt_embeds: bytes | list[bytes] | None = None
553
554
    add_special_tokens: bool = Field(
        default=True,
555
        description=(
556
            "If true (the default), special tokens (e.g. BOS) will be added to "
557
558
            "the prompt."
        ),
559
    )
560
    response_format: AnyResponseFormat | None = Field(
561
        default=None,
562
563
564
565
566
        description=(
            "Similar to chat completion, this parameter specifies the format "
            "of output. Only {'type': 'json_object'}, {'type': 'json_schema'}"
            ", {'type': 'structural_tag'}, or {'type': 'text' } is supported."
        ),
567
    )
568
    structured_outputs: StructuredOutputsParams | None = Field(
569
        default=None,
570
        description="Additional kwargs for structured outputs",
571
    )
572
573
574
575
576
    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
577
578
            "if the served model does not use priority scheduling."
        ),
579
    )
580
    request_id: str = Field(
581
        default_factory=random_uuid,
582
583
584
        description=(
            "The request_id related to this request. If the caller does "
            "not set it, a random_uuid will be generated. This id is used "
585
586
            "through out the inference process and return in response."
        ),
587
    )
588
    logits_processors: LogitsProcessors | None = Field(
589
590
591
592
593
594
595
596
597
        default=None,
        description=(
            "A list of either qualified names of logits processors, or "
            "constructor objects, to apply when sampling. A constructor is "
            "a JSON object with a required 'qualname' field specifying the "
            "qualified name of the processor class/factory, and optional "
            "'args' and 'kwargs' fields containing positional and keyword "
            "arguments. For example: {'qualname': "
            "'my_module.MyLogitsProcessor', 'args': [1, 2], 'kwargs': "
598
599
600
            "{'param': 'value'}}."
        ),
    )
601

602
    return_tokens_as_token_ids: bool | None = Field(
603
604
605
606
        default=None,
        description=(
            "If specified with 'logprobs', tokens are represented "
            " as strings of the form 'token_id:{token_id}' so that tokens "
607
608
609
            "that are not JSON-encodable can be identified."
        ),
    )
610
    return_token_ids: bool | None = Field(
611
612
613
614
615
616
        default=None,
        description=(
            "If specified, the result will include token IDs alongside the "
            "generated text. In streaming mode, prompt_token_ids is included "
            "only in the first chunk, and token_ids contains the delta tokens "
            "for each chunk. This is useful for debugging or when you "
617
618
619
            "need to map generated text back to input tokens."
        ),
    )
620

621
    cache_salt: str | None = Field(
622
623
624
625
626
627
628
        default=None,
        description=(
            "If specified, the prefix cache will be salted with the provided "
            "string to prevent an attacker to guess prompts in multi-user "
            "environments. The salt should be random, protected from "
            "access by 3rd parties, and long enough to be "
            "unpredictable (e.g., 43 characters base64-encoded, corresponding "
629
            "to 256 bit)."
630
631
        ),
    )
632

633
    kv_transfer_params: dict[str, Any] | None = Field(
Robert Shaw's avatar
Robert Shaw committed
634
        default=None,
635
636
        description="KVTransfer parameters used for disaggregated serving.",
    )
Robert Shaw's avatar
Robert Shaw committed
637

638
    vllm_xargs: dict[str, str | int | float] | None = Field(
639
        default=None,
640
641
642
643
        description=(
            "Additional request parameters with string or "
            "numeric values, used by custom extensions."
        ),
644
645
    )

646
    # --8<-- [end:completion-extra-params]
Zhuohan Li's avatar
Zhuohan Li committed
647

648
649
650
651
652
    # Default sampling parameters for completion requests
    _DEFAULT_SAMPLING_PARAMS: dict = {
        "repetition_penalty": 1.0,
        "temperature": 1.0,
        "top_p": 1.0,
653
        "top_k": 0,
654
655
656
657
        "min_p": 0.0,
    }

    def to_beam_search_params(
658
659
        self,
        max_tokens: int,
660
        default_sampling_params: dict | None = None,
661
662
663
    ) -> BeamSearchParams:
        if default_sampling_params is None:
            default_sampling_params = {}
664
        n = self.n if self.n is not None else 1
665
666
667

        if (temperature := self.temperature) is None:
            temperature = default_sampling_params.get("temperature", 1.0)
668
669
670
671
672
673

        return BeamSearchParams(
            beam_width=n,
            max_tokens=max_tokens,
            ignore_eos=self.ignore_eos,
            temperature=temperature,
674
            length_penalty=self.length_penalty,
675
676
            include_stop_str_in_output=self.include_stop_str_in_output,
        )
677

678
    def to_sampling_params(
679
        self,
680
        max_tokens: int,
681
682
        logits_processor_pattern: str | None,
        default_sampling_params: dict | None = None,
683
    ) -> SamplingParams:
684
685
        if default_sampling_params is None:
            default_sampling_params = {}
686

687
688
689
690
691
692
693
694
        # Default parameters
        if (repetition_penalty := self.repetition_penalty) is None:
            repetition_penalty = default_sampling_params.get(
                "repetition_penalty",
                self._DEFAULT_SAMPLING_PARAMS["repetition_penalty"],
            )
        if (temperature := self.temperature) is None:
            temperature = default_sampling_params.get(
695
696
                "temperature", self._DEFAULT_SAMPLING_PARAMS["temperature"]
            )
697
698
        if (top_p := self.top_p) is None:
            top_p = default_sampling_params.get(
699
700
                "top_p", self._DEFAULT_SAMPLING_PARAMS["top_p"]
            )
701
702
        if (top_k := self.top_k) is None:
            top_k = default_sampling_params.get(
703
704
                "top_k", self._DEFAULT_SAMPLING_PARAMS["top_k"]
            )
705
706
        if (min_p := self.min_p) is None:
            min_p = default_sampling_params.get(
707
708
                "min_p", self._DEFAULT_SAMPLING_PARAMS["min_p"]
            )
709

710
711
712
713
        prompt_logprobs = self.prompt_logprobs
        if prompt_logprobs is None and self.echo:
            prompt_logprobs = self.logprobs

714
715
        echo_without_generation = self.echo and self.max_tokens == 0

716
717
718
719
720
721
722
723
724
725
726
727
        response_format = self.response_format
        if response_format is not None:
            # If structured outputs wasn't already enabled,
            # we must enable it for these features to work
            if self.structured_outputs is None:
                self.structured_outputs = StructuredOutputsParams()

            # Set structured output params for response format
            if response_format.type == "json_object":
                self.structured_outputs.json_object = True
            elif response_format.type == "json_schema":
                json_schema = response_format.json_schema
728
                assert json_schema is not None
729
730
731
                self.structured_outputs.json = json_schema.json_schema
            elif response_format.type == "structural_tag":
                structural_tag = response_format
732
                assert structural_tag is not None and isinstance(
733
734
735
736
737
                    structural_tag,
                    (
                        LegacyStructuralTagResponseFormat,
                        StructuralTagResponseFormat,
                    ),
738
739
                )
                s_tag_obj = structural_tag.model_dump(by_alias=True)
740
                self.structured_outputs.structural_tag = json.dumps(s_tag_obj)
741

742
743
744
745
        extra_args: dict[str, Any] = self.vllm_xargs if self.vllm_xargs else {}
        if self.kv_transfer_params:
            # Pass in kv_transfer_params via extra_args
            extra_args["kv_transfer_params"] = self.kv_transfer_params
746
        return SamplingParams.from_optional(
747
748
749
            n=self.n,
            presence_penalty=self.presence_penalty,
            frequency_penalty=self.frequency_penalty,
750
751
752
753
754
            repetition_penalty=repetition_penalty,
            temperature=temperature,
            top_p=top_p,
            top_k=top_k,
            min_p=min_p,
Nick Hill's avatar
Nick Hill committed
755
            seed=self.seed,
756
757
            stop=self.stop,
            stop_token_ids=self.stop_token_ids,
758
            logprobs=self.logprobs,
759
            ignore_eos=self.ignore_eos,
760
            max_tokens=max_tokens if not echo_without_generation else 1,
761
            min_tokens=self.min_tokens,
762
            prompt_logprobs=prompt_logprobs,
763
            skip_special_tokens=self.skip_special_tokens,
764
            spaces_between_special_tokens=self.spaces_between_special_tokens,
765
            include_stop_str_in_output=self.include_stop_str_in_output,
766
767
768
            logits_processors=get_logits_processors(
                self.logits_processors, logits_processor_pattern
            ),
769
            truncate_prompt_tokens=self.truncate_prompt_tokens,
770
771
772
            output_kind=RequestOutputKind.DELTA
            if self.stream
            else RequestOutputKind.FINAL_ONLY,
773
            structured_outputs=self.structured_outputs,
774
            logit_bias=self.logit_bias,
Robert Shaw's avatar
Robert Shaw committed
775
            allowed_token_ids=self.allowed_token_ids,
776
            extra_args=extra_args or None,
777
            skip_clone=True,  # Created fresh per request, safe to skip clone
778
        )
779

780
781
    @model_validator(mode="before")
    @classmethod
782
    def check_structured_outputs_count(cls, data):
783
        if data.get("structured_outputs", None) is None:
784
785
            return data

786
        structured_outputs_kwargs = data["structured_outputs"]
787
788
        count = sum(
            structured_outputs_kwargs.get(k) is not None
789
790
            for k in ("json", "regex", "choice")
        )
791
        if count > 1:
792
            raise VLLMValidationError(
793
                "You can only use one kind of constraints for structured "
794
795
                "outputs ('json', 'regex' or 'choice').",
                parameter="structured_outputs",
796
            )
797
798
        return data

799
800
801
    @model_validator(mode="before")
    @classmethod
    def check_logprobs(cls, data):
802
        if (prompt_logprobs := data.get("prompt_logprobs")) is not None:
803
            if data.get("stream") and (prompt_logprobs > 0 or prompt_logprobs == -1):
804
805
806
                raise VLLMValidationError(
                    "`prompt_logprobs` are not available when `stream=True`.",
                    parameter="prompt_logprobs",
807
                )
808

809
            if prompt_logprobs < 0 and prompt_logprobs != -1:
810
811
812
813
814
                raise VLLMValidationError(
                    "`prompt_logprobs` must be a positive value or -1.",
                    parameter="prompt_logprobs",
                    value=prompt_logprobs,
                )
815
        if (logprobs := data.get("logprobs")) is not None and logprobs < 0:
816
817
818
819
820
            raise VLLMValidationError(
                "`logprobs` must be a positive value.",
                parameter="logprobs",
                value=logprobs,
            )
821

822
823
        return data

824
825
826
827
    @model_validator(mode="before")
    @classmethod
    def validate_stream_options(cls, data):
        if data.get("stream_options") and not data.get("stream"):
828
829
830
831
            raise VLLMValidationError(
                "Stream options can only be defined when `stream=True`.",
                parameter="stream_options",
            )
832

833
834
        return data

835
836
837
    @model_validator(mode="before")
    @classmethod
    def validate_prompt_and_prompt_embeds(cls, data):
838
839
840
        prompt = data.get("prompt")
        prompt_embeds = data.get("prompt_embeds")

841
842
843
844
        prompt_is_empty = prompt is None or (isinstance(prompt, str) and prompt == "")
        embeds_is_empty = prompt_embeds is None or (
            isinstance(prompt_embeds, list) and len(prompt_embeds) == 0
        )
845
846

        if prompt_is_empty and embeds_is_empty:
847
            raise ValueError(
848
849
850
                "Either prompt or prompt_embeds must be provided and non-empty."
            )

851
852
        return data

853
854
855
    @model_validator(mode="before")
    @classmethod
    def check_cache_salt_support(cls, data):
856
857
858
859
860
861
        if data.get("cache_salt") is not None and (
            not isinstance(data["cache_salt"], str) or not data["cache_salt"]
        ):
            raise ValueError(
                "Parameter 'cache_salt' must be a non-empty string if provided."
            )
862
863
        return data

Zhuohan Li's avatar
Zhuohan Li committed
864

865
class CompletionLogProbs(OpenAIBaseModel):
866
    text_offset: list[int] = Field(default_factory=list)
867
    token_logprobs: list[float | None] = Field(default_factory=list)
868
    tokens: list[str] = Field(default_factory=list)
869
    top_logprobs: list[dict[str, float] | None] = Field(default_factory=list)
Zhuohan Li's avatar
Zhuohan Li committed
870
871


872
class CompletionResponseChoice(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
873
874
    index: int
    text: str
875
876
877
    logprobs: CompletionLogProbs | None = None
    finish_reason: str | None = None
    stop_reason: int | str | None = Field(
878
879
880
881
        default=None,
        description=(
            "The stop string or token id that caused the completion "
            "to stop, None if the completion finished for some other reason "
882
883
            "including encountering the EOS token"
        ),
884
    )
885
886
887
    token_ids: list[int] | None = None  # For response
    prompt_logprobs: list[dict[int, Logprob] | None] | None = None
    prompt_token_ids: list[int] | None = None  # For prompt
Zhuohan Li's avatar
Zhuohan Li committed
888
889


890
class CompletionResponse(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
891
    id: str = Field(default_factory=lambda: f"cmpl-{random_uuid()}")
892
    object: Literal["text_completion"] = "text_completion"
Zhuohan Li's avatar
Zhuohan Li committed
893
894
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
895
    choices: list[CompletionResponseChoice]
896
897
    service_tier: Literal["auto", "default", "flex", "scale", "priority"] | None = None
    system_fingerprint: str | None = None
Zhuohan Li's avatar
Zhuohan Li committed
898
    usage: UsageInfo
899
900

    # vLLM-specific fields that are not in OpenAI spec
901
    kv_transfer_params: dict[str, Any] | None = Field(
902
903
        default=None, description="KVTransfer parameters."
    )
Zhuohan Li's avatar
Zhuohan Li committed
904
905


906
class CompletionResponseStreamChoice(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
907
908
    index: int
    text: str
909
910
911
    logprobs: CompletionLogProbs | None = None
    finish_reason: str | None = None
    stop_reason: int | str | None = Field(
912
913
914
915
        default=None,
        description=(
            "The stop string or token id that caused the completion "
            "to stop, None if the completion finished for some other reason "
916
917
            "including encountering the EOS token"
        ),
918
    )
919
920
    # not part of the OpenAI spec but for tracing the tokens
    # prompt tokens is put into choice to align with CompletionResponseChoice
921
922
    prompt_token_ids: list[int] | None = None
    token_ids: list[int] | None = None
Zhuohan Li's avatar
Zhuohan Li committed
923
924


925
class CompletionStreamResponse(OpenAIBaseModel):
Zhuohan Li's avatar
Zhuohan Li committed
926
927
928
929
    id: str = Field(default_factory=lambda: f"cmpl-{random_uuid()}")
    object: str = "text_completion"
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
930
    choices: list[CompletionResponseStreamChoice]
931
    usage: UsageInfo | None = Field(default=None)
932
933


934
935
936
937
938
939
class FunctionCall(OpenAIBaseModel):
    name: str
    arguments: str


class ToolCall(OpenAIBaseModel):
940
    id: str = Field(default_factory=make_tool_call_id)
941
942
943
944
    type: Literal["function"] = "function"
    function: FunctionCall


945
class DeltaFunctionCall(BaseModel):
946
947
    name: str | None = None
    arguments: str | None = None
948
949
950
951


# a tool call delta where everything is optional
class DeltaToolCall(OpenAIBaseModel):
952
953
    id: str | None = None
    type: Literal["function"] | None = None
954
    index: int
955
    function: DeltaFunctionCall | None = None
956
957
958
959
960
961
962


class ExtractedToolCallInformation(BaseModel):
    # indicate if tools were called
    tools_called: bool

    # extracted tool calls
963
    tool_calls: list[ToolCall]
964
965
966

    # content - per OpenAI spec, content AND tool calls can be returned rarely
    # But some models will do this intentionally
967
    content: str | None = None
968
969


970
class DeltaMessage(OpenAIBaseModel):
971
972
    role: str | None = None
    content: str | None = None
973
    reasoning: str | None = None
974
    reasoning_content: str | None = None
975
    """Deprecated: use `reasoning` instead."""
976
    tool_calls: list[DeltaToolCall] = Field(default_factory=list)
977

978
979
980
981
982
983
    @model_validator(mode="after")
    def handle_deprecated_reasoning_content(self):
        """Copy reasoning to reasoning_content for backward compatibility."""
        self.reasoning_content = self.reasoning
        return self

984

985
986
class TranscriptionResponseStreamChoice(OpenAIBaseModel):
    delta: DeltaMessage
987
988
    finish_reason: str | None = None
    stop_reason: int | str | None = None
989
990
991
992
993
994
995
996


class TranscriptionStreamResponse(OpenAIBaseModel):
    id: str = Field(default_factory=lambda: f"trsc-{random_uuid()}")
    object: Literal["transcription.chunk"] = "transcription.chunk"
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
    choices: list[TranscriptionResponseStreamChoice]
997
    usage: UsageInfo | None = Field(default=None)
998
999


1000
1001
class InputTokensDetails(OpenAIBaseModel):
    cached_tokens: int
1002
1003
    input_tokens_per_turn: list[int] = Field(default_factory=list)
    cached_tokens_per_turn: list[int] = Field(default_factory=list)
1004
1005
1006


class OutputTokensDetails(OpenAIBaseModel):
1007
1008
    reasoning_tokens: int = 0
    tool_output_tokens: int = 0
1009
1010
    output_tokens_per_turn: list[int] = Field(default_factory=list)
    tool_output_tokens_per_turn: list[int] = Field(default_factory=list)
1011
1012
1013
1014
1015
1016
1017
1018


class ResponseUsage(OpenAIBaseModel):
    input_tokens: int
    input_tokens_details: InputTokensDetails
    output_tokens: int
    output_tokens_details: OutputTokensDetails
    total_tokens: int
1019
1020


1021
1022
1023
1024
1025
1026
def serialize_message(msg):
    """
    Serializes a single message
    """
    if isinstance(msg, dict):
        return msg
1027
    elif hasattr(msg, "to_dict"):
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
        return msg.to_dict()
    else:
        # fallback to pyandic dump
        return msg.model_dump_json()


def serialize_messages(msgs):
    """
    Serializes multiple messages
    """
    return [serialize_message(msg) for msg in msgs] if msgs else None


1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
class ResponseRawMessageAndToken(OpenAIBaseModel):
    """Class to show the raw message.
    If message / tokens diverge, tokens is the source of truth"""

    message: str
    tokens: list[int]
    type: Literal["raw_message_tokens"] = "raw_message_tokens"


ResponseInputOutputMessage: TypeAlias = (
    list[ChatCompletionMessageParam] | list[ResponseRawMessageAndToken]
)


1055
1056
1057
1058
class ResponsesResponse(OpenAIBaseModel):
    id: str = Field(default_factory=lambda: f"resp_{random_uuid()}")
    created_at: int = Field(default_factory=lambda: int(time.time()))
    # error: Optional[ResponseError] = None
1059
1060
1061
    incomplete_details: IncompleteDetails | None = None
    instructions: str | None = None
    metadata: Metadata | None = None
1062
1063
    model: str
    object: Literal["response"] = "response"
1064
    output: list[ResponseOutputItem]
1065
1066
1067
1068
1069
1070
1071
    parallel_tool_calls: bool
    temperature: float
    tool_choice: ToolChoice
    tools: list[Tool]
    top_p: float
    background: bool
    max_output_tokens: int
1072
1073
1074
1075
    max_tool_calls: int | None = None
    previous_response_id: str | None = None
    prompt: ResponsePrompt | None = None
    reasoning: Reasoning | None = None
1076
1077
    service_tier: Literal["auto", "default", "flex", "scale", "priority"]
    status: ResponseStatus
1078
1079
    text: ResponseTextConfig | None = None
    top_logprobs: int | None = None
1080
    truncation: Literal["auto", "disabled"]
1081
1082
    usage: ResponseUsage | None = None
    user: str | None = None
1083

1084
    # --8<-- [start:responses-response-extra-params]
1085
1086
1087
    # These are populated when enable_response_messages is set to True
    # NOTE: custom serialization is needed
    # see serialize_input_messages and serialize_output_messages
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
    input_messages: ResponseInputOutputMessage | None = Field(
        default=None,
        description=(
            "If enable_response_messages, we can show raw token input to model."
        ),
    )
    output_messages: ResponseInputOutputMessage | None = Field(
        default=None,
        description=(
            "If enable_response_messages, we can show raw token output of model."
        ),
    )
    # --8<-- [end:responses-response-extra-params]
1101
1102
1103
1104
1105
1106

    # NOTE: openAI harmony doesn't serialize TextContent properly,
    # TODO: this fixes for TextContent, but need to verify for tools etc
    # https://github.com/openai/harmony/issues/78
    @field_serializer("output_messages", when_used="json")
    def serialize_output_messages(self, msgs, _info):
1107
        return serialize_messages(msgs)
1108
1109
1110
1111
1112

    # NOTE: openAI harmony doesn't serialize TextContent properly, this fixes it
    # https://github.com/openai/harmony/issues/78
    @field_serializer("input_messages", when_used="json")
    def serialize_input_messages(self, msgs, _info):
1113
        return serialize_messages(msgs)
1114

1115
1116
1117
1118
1119
1120
1121
1122
1123
    @classmethod
    def from_request(
        cls,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
        model_name: str,
        created_time: int,
        output: list[ResponseOutputItem],
        status: ResponseStatus,
1124
        usage: ResponseUsage | None = None,
1125
1126
        input_messages: ResponseInputOutputMessage | None = None,
        output_messages: ResponseInputOutputMessage | None = None,
1127
    ) -> "ResponsesResponse":
1128
        incomplete_details: IncompleteDetails | None = None
1129
1130
        if status == "incomplete":
            incomplete_details = IncompleteDetails(reason="max_output_tokens")
1131
1132
1133
        # TODO: implement the other reason for incomplete_details,
        # which is content_filter
        # incomplete_details = IncompleteDetails(reason='content_filter')
1134
1135
1136
        return cls(
            id=request.request_id,
            created_at=created_time,
1137
            incomplete_details=incomplete_details,
1138
1139
1140
1141
            instructions=request.instructions,
            metadata=request.metadata,
            model=model_name,
            output=output,
1142
1143
            input_messages=input_messages,
            output_messages=output_messages,
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
            parallel_tool_calls=request.parallel_tool_calls,
            temperature=sampling_params.temperature,
            tool_choice=request.tool_choice,
            tools=request.tools,
            top_p=sampling_params.top_p,
            background=request.background,
            max_output_tokens=sampling_params.max_tokens,
            max_tool_calls=request.max_tool_calls,
            previous_response_id=request.previous_response_id,
            prompt=request.prompt,
            reasoning=request.reasoning,
            service_tier=request.service_tier,
            status=status,
            text=request.text,
            top_logprobs=sampling_params.logprobs,
            truncation=request.truncation,
            user=request.user,
            usage=usage,
        )


1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# TODO: this code can be removed once
# https://github.com/openai/openai-python/issues/2634 has been resolved
class ResponseReasoningPartDoneEvent(OpenAIBaseModel):
    content_index: int
    """The index of the content part that is done."""

    item_id: str
    """The ID of the output item that the content part was added to."""

    output_index: int
    """The index of the output item that the content part was added to."""

    part: ResponseReasoningTextContent
    """The content part that is done."""

    sequence_number: int
    """The sequence number of this event."""

    type: Literal["response.reasoning_part.done"]
    """The type of the event. Always `response.reasoning_part.done`."""


# TODO: this code can be removed once
# https://github.com/openai/openai-python/issues/2634 has been resolved
class ResponseReasoningPartAddedEvent(OpenAIBaseModel):
    content_index: int
    """The index of the content part that is done."""

    item_id: str
    """The ID of the output item that the content part was added to."""

    output_index: int
    """The index of the output item that the content part was added to."""

    part: ResponseReasoningTextContent
    """The content part that is done."""

    sequence_number: int
    """The sequence number of this event."""

    type: Literal["response.reasoning_part.added"]
    """The type of the event. Always `response.reasoning_part.added`."""


1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
# vLLM Streaming Events
# Note: we override the response type with the vLLM ResponsesResponse type
class ResponseCompletedEvent(OpenAIResponseCompletedEvent):
    response: ResponsesResponse  # type: ignore[override]


class ResponseCreatedEvent(OpenAIResponseCreatedEvent):
    response: ResponsesResponse  # type: ignore[override]


class ResponseInProgressEvent(OpenAIResponseInProgressEvent):
    response: ResponsesResponse  # type: ignore[override]


1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
StreamingResponsesResponse: TypeAlias = (
    ResponseCreatedEvent
    | ResponseInProgressEvent
    | ResponseCompletedEvent
    | ResponseOutputItemAddedEvent
    | ResponseOutputItemDoneEvent
    | ResponseContentPartAddedEvent
    | ResponseContentPartDoneEvent
    | ResponseReasoningTextDeltaEvent
    | ResponseReasoningTextDoneEvent
    | ResponseReasoningPartAddedEvent
    | ResponseReasoningPartDoneEvent
    | ResponseCodeInterpreterCallInProgressEvent
    | ResponseCodeInterpreterCallCodeDeltaEvent
    | ResponseWebSearchCallInProgressEvent
    | ResponseWebSearchCallSearchingEvent
    | ResponseWebSearchCallCompletedEvent
    | ResponseCodeInterpreterCallCodeDoneEvent
    | ResponseCodeInterpreterCallInterpretingEvent
    | ResponseCodeInterpreterCallCompletedEvent
1243
1244
1245
1246
    | ResponseMcpCallArgumentsDeltaEvent
    | ResponseMcpCallArgumentsDoneEvent
    | ResponseMcpCallInProgressEvent
    | ResponseMcpCallCompletedEvent
1247
)
1248

1249

1250
## Protocols for Audio
1251
AudioResponseFormat: TypeAlias = Literal["json", "text", "srt", "verbose_json", "vtt"]
1252
1253
1254
1255


class TranscriptionRequest(OpenAIBaseModel):
    # Ordered by official OpenAI API documentation
1256
    # https://platform.openai.com/docs/api-reference/audio/createTranscription
1257
1258
1259
1260
1261
1262
1263

    file: UploadFile
    """
    The audio file object (not file name) to transcribe, in one of these
    formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.
    """

1264
    model: str | None = None
1265
1266
1267
    """ID of the model to use.
    """

1268
    language: str | None = None
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
    """The language of the input audio.

    Supplying the input language in
    [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format
    will improve accuracy and latency.
    """

    prompt: str = Field(default="")
    """An optional text to guide the model's style or continue a previous audio
    segment.

    The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting)
    should match the audio language.
    """

    response_format: AudioResponseFormat = Field(default="json")
    """
    The format of the output, in one of these options: `json`, `text`, `srt`,
    `verbose_json`, or `vtt`.
    """

    ## TODO (varun) : Support if set to 0, certain thresholds are met !!

1292
    timestamp_granularities: list[Literal["word", "segment"]] = Field(
1293
1294
        alias="timestamp_granularities[]", default=[]
    )
1295
1296
1297
1298
1299
1300
1301
1302
    """The timestamp granularities to populate for this transcription.

    `response_format` must be set `verbose_json` to use timestamp granularities.
    Either or both of these options are supported: `word`, or `segment`. Note:
    There is no additional latency for segment timestamps, but generating word
    timestamps incurs additional latency.
    """

1303
    stream: bool | None = False
1304
    """When set, it will enable output to be streamed in a similar fashion
1305
    as the Chat Completion endpoint.
1306
    """
1307
    # --8<-- [start:transcription-extra-params]
1308
    # Flattened stream option to simplify form data.
1309
1310
    stream_include_usage: bool | None = False
    stream_continuous_usage_stats: bool | None = False
1311

1312
    vllm_xargs: dict[str, str | int | float] | None = Field(
1313
        default=None,
1314
1315
1316
1317
        description=(
            "Additional request parameters with string or "
            "numeric values, used by custom extensions."
        ),
1318
    )
1319
    # --8<-- [end:transcription-extra-params]
1320

1321
    to_language: str | None = None
1322
1323
    """The language of the output audio we transcribe to.

1324
    Please note that this is not currently used by supported models at this
1325
1326
1327
    time, but it is a placeholder for future use, matching translation api.
    """

1328
    # --8<-- [start:transcription-sampling-params]
1329
1330
1331
1332
1333
1334
1335
1336
1337
    temperature: float = Field(default=0.0)
    """The sampling temperature, between 0 and 1.

    Higher values like 0.8 will make the output more random, while lower values
    like 0.2 will make it more focused / deterministic. If set to 0, the model
    will use [log probability](https://en.wikipedia.org/wiki/Log_probability)
    to automatically increase the temperature until certain thresholds are hit.
    """

1338
    top_p: float | None = None
1339
    """Enables nucleus (top-p) sampling, where tokens are selected from the
1340
1341
1342
    smallest possible set whose cumulative probability exceeds `p`.
    """

1343
    top_k: int | None = None
1344
1345
    """Limits sampling to the `k` most probable tokens at each step."""

1346
    min_p: float | None = None
1347
    """Filters out tokens with a probability lower than `min_p`, ensuring a
1348
1349
1350
    minimum likelihood threshold during sampling.
    """

1351
    seed: int | None = Field(None, ge=_LONG_INFO.min, le=_LONG_INFO.max)
1352
1353
    """The seed to use for sampling."""

1354
    frequency_penalty: float | None = 0.0
1355
1356
    """The frequency penalty to use for sampling."""

1357
    repetition_penalty: float | None = None
1358
1359
    """The repetition penalty to use for sampling."""

1360
    presence_penalty: float | None = 0.0
1361
    """The presence penalty to use for sampling."""
1362
1363
1364

    max_completion_tokens: int | None = None
    """The maximum number of tokens to generate."""
1365
    # --8<-- [end:transcription-sampling-params]
1366

1367
1368
    # Default sampling parameters for transcription requests.
    _DEFAULT_SAMPLING_PARAMS: dict = {
1369
1370
1371
        "repetition_penalty": 1.0,
        "temperature": 1.0,
        "top_p": 1.0,
1372
        "top_k": 0,
1373
        "min_p": 0.0,
1374
1375
1376
    }

    def to_sampling_params(
1377
        self, default_max_tokens: int, default_sampling_params: dict | None = None
1378
    ) -> SamplingParams:
1379
1380
1381
1382
        max_tokens = default_max_tokens

        if default_sampling_params is None:
            default_sampling_params = {}
1383

1384
1385
1386
        # Default parameters
        if (temperature := self.temperature) is None:
            temperature = default_sampling_params.get(
1387
1388
                "temperature", self._DEFAULT_SAMPLING_PARAMS["temperature"]
            )
1389
1390
        if (top_p := self.top_p) is None:
            top_p = default_sampling_params.get(
1391
1392
                "top_p", self._DEFAULT_SAMPLING_PARAMS["top_p"]
            )
1393
1394
        if (top_k := self.top_k) is None:
            top_k = default_sampling_params.get(
1395
1396
                "top_k", self._DEFAULT_SAMPLING_PARAMS["top_k"]
            )
1397
1398
        if (min_p := self.min_p) is None:
            min_p = default_sampling_params.get(
1399
1400
                "min_p", self._DEFAULT_SAMPLING_PARAMS["min_p"]
            )
1401
1402
1403
1404

        if (repetition_penalty := self.repetition_penalty) is None:
            repetition_penalty = default_sampling_params.get(
                "repetition_penalty",
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
                self._DEFAULT_SAMPLING_PARAMS["repetition_penalty"],
            )

        return SamplingParams.from_optional(
            temperature=temperature,
            max_tokens=max_tokens,
            seed=self.seed,
            top_p=top_p,
            top_k=top_k,
            min_p=min_p,
            frequency_penalty=self.frequency_penalty,
            repetition_penalty=repetition_penalty,
            presence_penalty=self.presence_penalty,
            output_kind=RequestOutputKind.DELTA
            if self.stream
            else RequestOutputKind.FINAL_ONLY,
            extra_args=self.vllm_xargs,
1422
            skip_clone=True,  # Created fresh per request, safe to skip clone
1423
        )
1424
1425
1426

    @model_validator(mode="before")
    @classmethod
1427
1428
1429
1430
1431
1432
1433
    def validate_transcription_request(cls, data):
        if isinstance(data.get("file"), str):
            raise HTTPException(
                status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
                detail="Expected 'file' to be a file-like object, not 'str'.",
            )

1434
1435
1436
        stream_opts = ["stream_include_usage", "stream_continuous_usage_stats"]
        stream = data.get("stream", False)
        if any(bool(data.get(so, False)) for so in stream_opts) and not stream:
1437
1438
1439
1440
1441
1442
1443
1444
1445
            # Find which specific stream option was set
            invalid_param = next(
                (so for so in stream_opts if data.get(so, False)),
                "stream_include_usage",
            )
            raise VLLMValidationError(
                "Stream options can only be defined when `stream=True`.",
                parameter=invalid_param,
            )
1446
1447

        return data
1448
1449
1450


# Transcription response objects
1451
1452
1453
1454
1455
class TranscriptionUsageAudio(OpenAIBaseModel):
    type: Literal["duration"] = "duration"
    seconds: int


1456
1457
1458
class TranscriptionResponse(OpenAIBaseModel):
    text: str
    """The transcribed text."""
1459
    usage: TranscriptionUsageAudio
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476


class TranscriptionWord(OpenAIBaseModel):
    end: float
    """End time of the word in seconds."""

    start: float
    """Start time of the word in seconds."""

    word: str
    """The text content of the word."""


class TranscriptionSegment(OpenAIBaseModel):
    id: int
    """Unique identifier of the segment."""

1477
    avg_logprob: float | None = None
1478
1479
1480
1481
1482
    """Average logprob of the segment.

    If the value is lower than -1, consider the logprobs failed.
    """

1483
    compression_ratio: float | None = None
1484
1485
1486
1487
1488
1489
1490
1491
    """Compression ratio of the segment.

    If the value is greater than 2.4, consider the compression failed.
    """

    end: float
    """End time of the segment in seconds."""

1492
    no_speech_prob: float | None = None
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
    """Probability of no speech in the segment.

    If the value is higher than 1.0 and the `avg_logprob` is below -1, consider
    this segment silent.
    """

    seek: int
    """Seek offset of the segment."""

    start: float
    """Start time of the segment in seconds."""

    temperature: float
    """Temperature parameter used for generating the segment."""

    text: str
    """Text content of the segment."""

1511
    tokens: list[int]
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
    """Array of token IDs for the text content."""


class TranscriptionResponseVerbose(OpenAIBaseModel):
    duration: str
    """The duration of the input audio."""

    language: str
    """The language of the input audio."""

    text: str
    """The transcribed text."""

1525
    segments: list[TranscriptionSegment] | None = None
1526
1527
    """Segments of the transcribed text and their corresponding details."""

1528
    words: list[TranscriptionWord] | None = None
1529
    """Extracted words and their corresponding timestamps."""
1530
1531


1532
1533
1534
1535
1536
TranscriptionResponseVariant: TypeAlias = (
    TranscriptionResponse | TranscriptionResponseVerbose
)


1537
1538
class TranslationResponseStreamChoice(OpenAIBaseModel):
    delta: DeltaMessage
1539
1540
    finish_reason: str | None = None
    stop_reason: int | str | None = None
1541
1542
1543
1544
1545
1546
1547
1548


class TranslationStreamResponse(OpenAIBaseModel):
    id: str = Field(default_factory=lambda: f"trsl-{random_uuid()}")
    object: Literal["translation.chunk"] = "translation.chunk"
    created: int = Field(default_factory=lambda: int(time.time()))
    model: str
    choices: list[TranslationResponseStreamChoice]
1549
    usage: UsageInfo | None = Field(default=None)
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561


class TranslationRequest(OpenAIBaseModel):
    # Ordered by official OpenAI API documentation
    # https://platform.openai.com/docs/api-reference/audio/createTranslation

    file: UploadFile
    """
    The audio file object (not file name) to translate, in one of these
    formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.
    """

1562
    model: str | None = None
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
    """ID of the model to use.
    """

    prompt: str = Field(default="")
    """An optional text to guide the model's style or continue a previous audio
    segment.

    The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting)
    should match the audio language.
    """

    response_format: AudioResponseFormat = Field(default="json")
    """
    The format of the output, in one of these options: `json`, `text`, `srt`,
    `verbose_json`, or `vtt`.
    """

    # TODO support additional sampling parameters
    # --8<-- [start:translation-sampling-params]
1582
    seed: int | None = Field(None, ge=_LONG_INFO.min, le=_LONG_INFO.max)
1583
1584
    """The seed to use for sampling."""

1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
    temperature: float = Field(default=0.0)
    """The sampling temperature, between 0 and 1.

    Higher values like 0.8 will make the output more random, while lower values
    like 0.2 will make it more focused / deterministic. If set to 0, the model
    will use [log probability](https://en.wikipedia.org/wiki/Log_probability)
    to automatically increase the temperature until certain thresholds are hit.
    """
    # --8<-- [end:translation-sampling-params]

    # --8<-- [start:translation-extra-params]
1596
    language: str | None = None
1597
1598
1599
1600
1601
1602
1603
    """The language of the input audio we translate from.

    Supplying the input language in
    [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format
    will improve accuracy.
    """

1604
    to_language: str | None = None
1605
1606
1607
1608
1609
1610
1611
    """The language of the input audio we translate to.

    Please note that this is not supported by all models, refer to the specific
    model documentation for more details.
    For instance, Whisper only supports `to_language=en`.
    """

1612
    stream: bool | None = False
1613
    """Custom field not present in the original OpenAI definition. When set,
1614
    it will enable output to be streamed in a similar fashion as the Chat
1615
    Completion endpoint.
1616
1617
    """
    # Flattened stream option to simplify form data.
1618
1619
    stream_include_usage: bool | None = False
    stream_continuous_usage_stats: bool | None = False
1620
1621
1622

    max_completion_tokens: int | None = None
    """The maximum number of tokens to generate."""
1623
1624
1625
1626
1627
1628
1629
1630
    # --8<-- [end:translation-extra-params]

    # Default sampling parameters for translation requests.
    _DEFAULT_SAMPLING_PARAMS: dict = {
        "temperature": 0,
    }

    def to_sampling_params(
1631
        self, default_max_tokens: int, default_sampling_params: dict | None = None
1632
    ) -> SamplingParams:
1633
1634
1635
1636
1637
1638
1639
        max_tokens = default_max_tokens

        if default_sampling_params is None:
            default_sampling_params = {}
        # Default parameters
        if (temperature := self.temperature) is None:
            temperature = default_sampling_params.get(
1640
1641
                "temperature", self._DEFAULT_SAMPLING_PARAMS["temperature"]
            )
1642

1643
1644
1645
1646
1647
1648
1649
        return SamplingParams.from_optional(
            temperature=temperature,
            max_tokens=max_tokens,
            seed=self.seed,
            output_kind=RequestOutputKind.DELTA
            if self.stream
            else RequestOutputKind.FINAL_ONLY,
1650
            skip_clone=True,  # Created fresh per request, safe to skip clone
1651
        )
1652
1653
1654
1655
1656
1657
1658

    @model_validator(mode="before")
    @classmethod
    def validate_stream_options(cls, data):
        stream_opts = ["stream_include_usage", "stream_continuous_usage_stats"]
        stream = data.get("stream", False)
        if any(bool(data.get(so, False)) for so in stream_opts) and not stream:
1659
1660
1661
1662
1663
1664
1665
1666
1667
            # Find which specific stream option was set
            invalid_param = next(
                (so for so in stream_opts if data.get(so, False)),
                "stream_include_usage",
            )
            raise VLLMValidationError(
                "Stream options can only be defined when `stream=True`.",
                parameter=invalid_param,
            )
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692

        return data


# Translation response objects
class TranslationResponse(OpenAIBaseModel):
    text: str
    """The translated text."""


class TranslationWord(OpenAIBaseModel):
    end: float
    """End time of the word in seconds."""

    start: float
    """Start time of the word in seconds."""

    word: str
    """The text content of the word."""


class TranslationSegment(OpenAIBaseModel):
    id: int
    """Unique identifier of the segment."""

1693
    avg_logprob: float | None = None
1694
1695
1696
1697
1698
    """Average logprob of the segment.

    If the value is lower than -1, consider the logprobs failed.
    """

1699
    compression_ratio: float | None = None
1700
1701
1702
1703
1704
1705
1706
1707
    """Compression ratio of the segment.

    If the value is greater than 2.4, consider the compression failed.
    """

    end: float
    """End time of the segment in seconds."""

1708
    no_speech_prob: float | None = None
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
    """Probability of no speech in the segment.

    If the value is higher than 1.0 and the `avg_logprob` is below -1, consider
    this segment silent.
    """

    seek: int
    """Seek offset of the segment."""

    start: float
    """Start time of the segment in seconds."""

    temperature: float
    """Temperature parameter used for generating the segment."""

    text: str
    """Text content of the segment."""

    tokens: list[int]
    """Array of token IDs for the text content."""


class TranslationResponseVerbose(OpenAIBaseModel):
    duration: str
    """The duration of the input audio."""

    language: str
    """The language of the input audio."""

    text: str
    """The translated text."""

1741
    segments: list[TranslationSegment] | None = None
1742
1743
    """Segments of the translated text and their corresponding details."""

1744
    words: list[TranslationWord] | None = None
1745
    """Extracted words and their corresponding timestamps."""
1746
1747


1748
1749
1750
TranslationResponseVariant: TypeAlias = TranslationResponse | TranslationResponseVerbose


1751
1752
1753
####### Tokens IN <> Tokens OUT #######
class GenerateRequest(BaseModel):
    request_id: str = Field(
1754
        default_factory=random_uuid,
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
        description=(
            "The request_id related to this request. If the caller does "
            "not set it, a random_uuid will be generated. This id is used "
            "through out the inference process and return in response."
        ),
    )
    token_ids: list[int]
    """The token ids to generate text from."""

    # features: MultiModalFeatureSpec
    # TODO (NickLucche): implement once Renderer work is completed
    features: str | None = None
    """The processed MM inputs for the model."""

    sampling_params: SamplingParams
    """The sampling parameters for the model."""

    model: str | None = None

    stream: bool | None = False
    stream_options: StreamOptions | None = None
    cache_salt: str | None = Field(
        default=None,
        description=(
            "If specified, the prefix cache will be salted with the provided "
            "string to prevent an attacker to guess prompts in multi-user "
            "environments. The salt should be random, protected from "
            "access by 3rd parties, and long enough to be "
            "unpredictable (e.g., 43 characters base64-encoded, corresponding "
            "to 256 bit)."
        ),
    )
    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
            "if the served model does not use priority scheduling."
        ),
    )
    kv_transfer_params: dict[str, Any] | None = Field(
        default=None,
        description="KVTransfer parameters used for disaggregated serving.",
    )