serving.py 55.9 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import asyncio
4
import json
5
import sys
6
import time
7
import traceback
8
from collections.abc import AsyncGenerator, Callable, Iterable, Mapping
9
from dataclasses import dataclass, field
10
from http import HTTPStatus
11
from typing import Any, ClassVar, Generic, TypeAlias, TypeVar, cast
12

13
import numpy as np
14
from fastapi import Request
15
16
17
from openai.types.responses import (
    ToolChoiceFunction,
)
18
19
from pydantic import ConfigDict, TypeAdapter
from starlette.datastructures import Headers
20

21
import vllm.envs as envs
22
from vllm.beam_search import BeamSearchSequence, create_sort_beams_key_function
23
from vllm.engine.protocol import EngineClient
24
25
26
27
28
from vllm.entrypoints.chat_utils import (
    ChatCompletionMessageParam,
    ChatTemplateContentFormatOption,
    ConversationMessage,
)
29
from vllm.entrypoints.logger import RequestLogger
30
from vllm.entrypoints.openai.chat_completion.protocol import (
31
    ChatCompletionNamedToolChoiceParam,
32
33
    ChatCompletionRequest,
    ChatCompletionResponse,
34
)
35
from vllm.entrypoints.openai.completion.protocol import (
36
37
    CompletionRequest,
    CompletionResponse,
38
39
)
from vllm.entrypoints.openai.engine.protocol import (
40
41
    ErrorInfo,
    ErrorResponse,
42
    FunctionCall,
43
    FunctionDefinition,
44
)
45
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
46
47
48
49
50
51
from vllm.entrypoints.openai.responses.context import (
    ConversationContext,
    HarmonyContext,
    ParsableContext,
    StreamingHarmonyContext,
)
52
53
54
55
from vllm.entrypoints.openai.responses.protocol import (
    ResponseInputOutputItem,
    ResponsesRequest,
)
56
57
58
from vllm.entrypoints.openai.responses.utils import (
    construct_input_messages,
)
59
60
61
62
63
from vllm.entrypoints.openai.translations.protocol import (
    TranscriptionRequest,
    TranscriptionResponse,
    TranslationRequest,
)
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from vllm.entrypoints.pooling.classify.protocol import (
    ClassificationChatRequest,
    ClassificationCompletionRequest,
    ClassificationRequest,
    ClassificationResponse,
)
from vllm.entrypoints.pooling.embed.protocol import (
    EmbeddingChatRequest,
    EmbeddingCompletionRequest,
    EmbeddingRequest,
    EmbeddingResponse,
)
from vllm.entrypoints.pooling.pooling.protocol import (
    IOProcessorRequest,
    PoolingResponse,
)
from vllm.entrypoints.pooling.score.protocol import (
    RerankRequest,
82
83
    ScoreDataRequest,
    ScoreQueriesDocumentsRequest,
84
85
    ScoreRequest,
    ScoreResponse,
86
    ScoreTextRequest,
87
)
88
from vllm.entrypoints.renderer import BaseRenderer, CompletionRenderer, RenderConfig
89
from vllm.entrypoints.serve.disagg.protocol import GenerateRequest, GenerateResponse
90
91
92
93
94
95
from vllm.entrypoints.serve.tokenize.protocol import (
    DetokenizeRequest,
    TokenizeChatRequest,
    TokenizeCompletionRequest,
    TokenizeResponse,
)
96
from vllm.entrypoints.utils import _validate_truncation_size, sanitize_message
97
from vllm.exceptions import VLLMValidationError
98
from vllm.inputs.data import PromptType, TokensPrompt
99
100
101
102
103
from vllm.inputs.parse import (
    PromptComponents,
    get_prompt_components,
    is_explicit_encoder_decoder_prompt,
)
104
from vllm.logger import init_logger
105
from vllm.logprobs import Logprob, PromptLogprobs
106
from vllm.lora.request import LoRARequest
107
from vllm.multimodal import MultiModalDataDict
108
from vllm.outputs import CompletionOutput, PoolingRequestOutput, RequestOutput
109
from vllm.pooling_params import PoolingParams
110
from vllm.reasoning import ReasoningParser, ReasoningParserManager
111
from vllm.renderers import RendererLike
112
from vllm.sampling_params import BeamSearchParams, SamplingParams
113
from vllm.tokenizers import TokenizerLike
114
from vllm.tool_parsers import ToolParser, ToolParserManager
115
116
117
118
119
from vllm.tracing import (
    contains_trace_headers,
    extract_trace_headers,
    log_tracing_disabled_warning,
)
120
from vllm.utils import random_uuid
121
from vllm.utils.async_utils import (
122
    AsyncMicrobatchTokenizer,
123
    collect_from_async_generator,
124
125
    merge_async_iterators,
)
126
from vllm.v1.engine import EngineCoreRequest
127

128
129
130
131
132
133
134
135
136

class GenerationError(Exception):
    """raised when finish_reason indicates internal server error (500)"""

    def __init__(self, message: str = "Internal server error"):
        super().__init__(message)
        self.status_code = HTTPStatus.INTERNAL_SERVER_ERROR


137
138
logger = init_logger(__name__)

139
140
141
142
143
CompletionLikeRequest: TypeAlias = (
    CompletionRequest
    | DetokenizeRequest
    | EmbeddingCompletionRequest
    | RerankRequest
144
    | ClassificationCompletionRequest
145
146
147
    | ScoreRequest
    | TokenizeCompletionRequest
)
148

149
ChatLikeRequest: TypeAlias = (
150
151
152
153
    ChatCompletionRequest
    | EmbeddingChatRequest
    | TokenizeChatRequest
    | ClassificationChatRequest
154
155
156
157
158
159
160
161
)
SpeechToTextRequest: TypeAlias = TranscriptionRequest | TranslationRequest
AnyRequest: TypeAlias = (
    CompletionLikeRequest
    | ChatLikeRequest
    | SpeechToTextRequest
    | ResponsesRequest
    | IOProcessorRequest
162
    | GenerateRequest
163
164
165
166
167
168
169
170
171
172
173
)

AnyResponse: TypeAlias = (
    CompletionResponse
    | ChatCompletionResponse
    | EmbeddingResponse
    | TranscriptionResponse
    | TokenizeResponse
    | PoolingResponse
    | ClassificationResponse
    | ScoreResponse
174
    | GenerateResponse
175
)
176

177

178
179
180
RequestT = TypeVar("RequestT", bound=AnyRequest)


181
182
@dataclass(kw_only=True)
class RequestProcessingMixin:
183
    """
184
    Mixin for request processing,
185
186
    handling prompt preparation and engine input.
    """
187

188
    engine_prompts: list[TokensPrompt] | None = field(default_factory=list)
189
190


191
192
@dataclass(kw_only=True)
class ResponseGenerationMixin:
193
    """
194
    Mixin for response generation,
195
196
    managing result generators and final batch results.
    """
197

198
199
200
    result_generator: (
        AsyncGenerator[tuple[int, RequestOutput | PoolingRequestOutput], None] | None
    ) = None
201
    final_res_batch: list[RequestOutput | PoolingRequestOutput] = field(
202
203
        default_factory=list
    )
204
205
206
207

    model_config = ConfigDict(arbitrary_types_allowed=True)


208
209
@dataclass(kw_only=True)
class ServeContext(RequestProcessingMixin, ResponseGenerationMixin, Generic[RequestT]):
210
    request: RequestT
211
    raw_request: Request | None = None
212
213
    model_name: str
    request_id: str
214
    created_time: int = field(default_factory=lambda: int(time.time()))
215
    lora_request: LoRARequest | None = None
216
217


218
219
220
@dataclass(kw_only=True)
class ClassificationServeContext(ServeContext[ClassificationRequest]):
    pass
221
222


223
@dataclass(kw_only=True)
224
class EmbeddingServeContext(ServeContext[EmbeddingRequest]):
225
    chat_template: str | None = None
226
227
228
    chat_template_content_format: ChatTemplateContentFormatOption


229
class OpenAIServing:
230
231
232
233
    request_id_prefix: ClassVar[str] = """
    A short string prepended to every request’s ID (e.g. "embd", "classify")
    so you can easily tell “this ID came from Embedding vs Classification.”
    """
234

235
236
    def __init__(
        self,
237
        engine_client: EngineClient,
238
        models: OpenAIServingModels,
239
        *,
240
        request_logger: RequestLogger | None,
241
        return_tokens_as_token_ids: bool = False,
242
        log_error_stack: bool = False,
243
    ):
244
245
        super().__init__()

246
        self.engine_client = engine_client
247

248
        self.models = models
249

250
        self.request_logger = request_logger
251
        self.return_tokens_as_token_ids = return_tokens_as_token_ids
252

253
        self._async_tokenizer_pool: dict[TokenizerLike, AsyncMicrobatchTokenizer] = {}
254
        self.log_error_stack = log_error_stack
255

256
        self.input_processor = self.models.input_processor
257
        self.io_processor = self.models.io_processor
258
        self.renderer = self.models.renderer
259
260
261
        self.model_config = self.models.model_config
        self.max_model_len = self.model_config.max_model_len

262
    def _get_tool_parser(
263
        self, tool_parser_name: str | None = None, enable_auto_tools: bool = False
264
    ) -> Callable[[TokenizerLike], ToolParser] | None:
265
266
267
268
        """Get the tool parser based on the name."""
        parser = None
        if not enable_auto_tools or tool_parser_name is None:
            return parser
269
        logger.info('"auto" tool choice has been enabled.')
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

        try:
            if tool_parser_name == "pythonic" and self.model_config.model.startswith(
                "meta-llama/Llama-3.2"
            ):
                logger.warning(
                    "Llama3.2 models may struggle to emit valid pythonic tool calls"
                )
            parser = ToolParserManager.get_tool_parser(tool_parser_name)
        except Exception as e:
            raise TypeError(
                "Error: --enable-auto-tool-choice requires "
                f"tool_parser:'{tool_parser_name}' which has not "
                "been registered"
            ) from e
        return parser

    def _get_reasoning_parser(
        self,
        reasoning_parser_name: str,
290
    ) -> Callable[[TokenizerLike], ReasoningParser] | None:
291
292
293
294
295
296
297
298
299
300
301
        """Get the reasoning parser based on the name."""
        parser = None
        if not reasoning_parser_name:
            return None
        try:
            parser = ReasoningParserManager.get_reasoning_parser(reasoning_parser_name)
            assert parser is not None
        except Exception as e:
            raise TypeError(f"{reasoning_parser_name=} has not been registered") from e
        return parser

302
    async def reset_mm_cache(self) -> None:
303
        self.input_processor.clear_mm_cache()
304
305
        await self.engine_client.reset_mm_cache()

306
307
308
309
310
    async def beam_search(
        self,
        prompt: PromptType,
        request_id: str,
        params: BeamSearchParams,
311
        lora_request: LoRARequest | None = None,
312
        trace_headers: Mapping[str, str] | None = None,
313
314
315
316
317
318
319
320
    ) -> AsyncGenerator[RequestOutput, None]:
        beam_width = params.beam_width
        max_tokens = params.max_tokens
        ignore_eos = params.ignore_eos
        temperature = params.temperature
        length_penalty = params.length_penalty
        include_stop_str_in_output = params.include_stop_str_in_output

321
322
        input_processor = self.input_processor
        tokenizer = input_processor.tokenizer
323
        if tokenizer is None:
324
325
326
327
            raise VLLMValidationError(
                "You cannot use beam search when `skip_tokenizer_init=True`",
                parameter="skip_tokenizer_init",
                value=True,
328
329
330
331
332
333
334
            )

        eos_token_id: int = tokenizer.eos_token_id  # type: ignore

        if is_explicit_encoder_decoder_prompt(prompt):
            raise NotImplementedError

335
        prompt_text: str | None
336
        prompt_token_ids: list[int]
337
        multi_modal_data: MultiModalDataDict | None
338
339
340
341
342
343
344
345
346
        if isinstance(prompt, str):
            prompt_text = prompt
            prompt_token_ids = []
            multi_modal_data = None
        else:
            prompt_text = prompt.get("prompt")  # type: ignore
            prompt_token_ids = prompt.get("prompt_token_ids", [])  # type: ignore
            multi_modal_data = prompt.get("multi_modal_data")  # type: ignore

347
348
349
350
351
352
353
354
355
356
        mm_processor_kwargs: dict[str, Any] | None = None

        # This is a workaround to fix multimodal beam search; this is a
        # bandaid fix for 2 small problems:
        # 1. Multi_modal_data on the processed_inputs currently resolves to
        #    `None`.
        # 2. preprocessing above expands the multimodal placeholders. However,
        #    this happens again in generation, so the double expansion causes
        #    a mismatch.
        # TODO - would be ideal to handle this more gracefully.
357
358
359
360
361

        tokenized_length = len(prompt_token_ids)

        sort_beams_key = create_sort_beams_key_function(eos_token_id, length_penalty)

362
        logprobs_num = 2 * beam_width
363
        beam_search_params = SamplingParams(
364
            logprobs=logprobs_num,
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
            max_tokens=1,
            temperature=temperature,
        )
        all_beams = [
            BeamSearchSequence(
                tokens=prompt_token_ids,
                cum_logprob=0,
                logprobs=[],
                multi_modal_data=multi_modal_data,
                mm_processor_kwargs=mm_processor_kwargs,
                lora_request=lora_request,
            )
        ]
        completed = []

        for _ in range(max_tokens):
            prompts_batch, lora_req_batch = zip(
                *[
                    (
384
                        TokensPrompt(
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
                            prompt_token_ids=beam.tokens,
                            multi_modal_data=beam.multi_modal_data,
                            mm_processor_kwargs=beam.mm_processor_kwargs,
                        ),
                        beam.lora_request,
                    )
                    for beam in all_beams
                ]
            )

            tasks = []
            request_id_batch = f"{request_id}-{random_uuid()}"

            for i, (individual_prompt, lora_req) in enumerate(
                zip(prompts_batch, lora_req_batch)
            ):
                request_id_item = f"{request_id_batch}-beam-{i}"
                task = asyncio.create_task(
                    collect_from_async_generator(
                        self.engine_client.generate(
                            individual_prompt,
                            beam_search_params,
                            request_id_item,
                            lora_request=lora_req,
409
                            trace_headers=trace_headers,
410
411
412
413
414
415
416
417
                        )
                    )
                )
                tasks.append(task)

            output = [x[0] for x in await asyncio.gather(*tasks)]

            new_beams = []
418
419
420
421
422
423
424
425
            # Store all new tokens generated by beam
            all_beams_token_id = []
            # Store the cumulative probability of all tokens
            # generated by beam search
            all_beams_logprob = []
            # Iterate through all beam inference results
            for i, result in enumerate(output):
                current_beam = all_beams[i]
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448

                # check for error finish reason and abort beam search
                if result.outputs[0].finish_reason == "error":
                    # yield error output and terminate beam search
                    yield RequestOutput(
                        request_id=request_id,
                        prompt=prompt_text,
                        outputs=[
                            CompletionOutput(
                                index=0,
                                text="",
                                token_ids=[],
                                cumulative_logprob=None,
                                logprobs=None,
                                finish_reason="error",
                            )
                        ],
                        finished=True,
                        prompt_token_ids=prompt_token_ids,
                        prompt_logprobs=None,
                    )
                    return

449
450
                if result.outputs[0].logprobs is not None:
                    logprobs = result.outputs[0].logprobs[0]
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
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
                    all_beams_token_id.extend(list(logprobs.keys()))
                    all_beams_logprob.extend(
                        [
                            current_beam.cum_logprob + obj.logprob
                            for obj in logprobs.values()
                        ]
                    )

            # Handle the token for the end of sentence (EOS)
            all_beams_token_id = np.array(all_beams_token_id)
            all_beams_logprob = np.array(all_beams_logprob)

            if not ignore_eos:
                # Get the index position of eos token in all generated results
                eos_idx = np.where(all_beams_token_id == eos_token_id)[0]
                for idx in eos_idx:
                    current_beam = all_beams[idx // logprobs_num]
                    result = output[idx // logprobs_num]
                    assert result.outputs[0].logprobs is not None
                    logprobs_entry = result.outputs[0].logprobs[0]
                    completed.append(
                        BeamSearchSequence(
                            tokens=current_beam.tokens + [eos_token_id]
                            if include_stop_str_in_output
                            else current_beam.tokens,
                            logprobs=current_beam.logprobs + [logprobs_entry],
                            cum_logprob=float(all_beams_logprob[idx]),
                            finish_reason="stop",
                            stop_reason=eos_token_id,
                        )
                    )
                # After processing, set the log probability of the eos condition
                # to negative infinity.
                all_beams_logprob[eos_idx] = -np.inf

            # Processing non-EOS tokens
            # Get indices of the top beam_width probabilities
            topn_idx = np.argpartition(np.negative(all_beams_logprob), beam_width)[
                :beam_width
            ]

            for idx in topn_idx:
                current_beam = all_beams[idx // logprobs_num]
                result = output[idx // logprobs_num]
                token_id = int(all_beams_token_id[idx])
                assert result.outputs[0].logprobs is not None
                logprobs_entry = result.outputs[0].logprobs[0]
                new_beams.append(
                    BeamSearchSequence(
                        tokens=current_beam.tokens + [token_id],
                        logprobs=current_beam.logprobs + [logprobs_entry],
                        lora_request=current_beam.lora_request,
                        cum_logprob=float(all_beams_logprob[idx]),
                        multi_modal_data=current_beam.multi_modal_data,
                        mm_processor_kwargs=current_beam.mm_processor_kwargs,
                    )
                )

            all_beams = new_beams
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543

        completed.extend(all_beams)
        sorted_completed = sorted(completed, key=sort_beams_key, reverse=True)
        best_beams = sorted_completed[:beam_width]

        for beam in best_beams:
            if beam.tokens[-1] == eos_token_id and not ignore_eos:
                # Skip the eos token in the text.
                tokens = beam.tokens[tokenized_length:-1]
            else:
                tokens = beam.tokens[tokenized_length:]
            beam.text = tokenizer.decode(tokens)

        yield RequestOutput(
            request_id=request_id,
            prompt=prompt_text,
            outputs=[
                CompletionOutput(
                    text=beam.text,  # type: ignore
                    cumulative_logprob=beam.cum_logprob,
                    token_ids=beam.tokens[tokenized_length:],
                    index=i,
                    logprobs=beam.logprobs,
                    finish_reason=beam.finish_reason
                    if beam.finish_reason is not None
                    else "length",
                    stop_reason=beam.stop_reason,
                )
                for (i, beam) in enumerate(best_beams)
            ],
            finished=True,
            prompt_token_ids=prompt_token_ids,
            prompt_logprobs=None,
        )
544

545
    def _get_completion_renderer(self) -> BaseRenderer:
546
547
548
549
550
551
        """
        Get a Renderer instance with the provided tokenizer.
        Uses shared async tokenizer pool for efficiency.
        """
        return CompletionRenderer(
            model_config=self.model_config,
552
            tokenizer=self.renderer.tokenizer,
553
554
            async_tokenizer_pool=self._async_tokenizer_pool,
        )
555

556
557
558
559
560
561
562
563
564
565
566
567
568
    def _build_render_config(
        self,
        request: Any,
    ) -> RenderConfig:
        """
        Build and return a `RenderConfig` for an endpoint.

        Used by the renderer to control how prompts are prepared
        (e.g., tokenization and length handling). Endpoints should
        implement this with logic appropriate to their request type.
        """
        raise NotImplementedError

569
570
    def _get_async_tokenizer(self, tokenizer) -> AsyncMicrobatchTokenizer:
        """
571
        Return (and cache) an `AsyncMicrobatchTokenizer` bound to the
572
573
574
575
576
577
578
        given tokenizer.
        """
        async_tokenizer = self._async_tokenizer_pool.get(tokenizer)
        if async_tokenizer is None:
            async_tokenizer = AsyncMicrobatchTokenizer(tokenizer)
            self._async_tokenizer_pool[tokenizer] = async_tokenizer
        return async_tokenizer
579

580
581
582
    async def _preprocess(
        self,
        ctx: ServeContext,
583
    ) -> ErrorResponse | None:
584
585
586
587
588
589
590
591
592
        """
        Default preprocessing hook. Subclasses may override
        to prepare `ctx` (classification, embedding, etc.).
        """
        return None

    def _build_response(
        self,
        ctx: ServeContext,
593
    ) -> AnyResponse | ErrorResponse:
594
595
596
597
598
599
600
601
602
        """
        Default response builder. Subclass may override this method
        to return the appropriate response object.
        """
        return self.create_error_response("unimplemented endpoint")

    async def handle(
        self,
        ctx: ServeContext,
603
604
    ) -> AnyResponse | ErrorResponse:
        generation: AsyncGenerator[AnyResponse | ErrorResponse, None]
605
606
607
608
609
610
611
612
613
614
        generation = self._pipeline(ctx)

        async for response in generation:
            return response

        return self.create_error_response("No response yielded from pipeline")

    async def _pipeline(
        self,
        ctx: ServeContext,
615
    ) -> AsyncGenerator[AnyResponse | ErrorResponse, None]:
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
        """Execute the request processing pipeline yielding responses."""
        if error := await self._check_model(ctx.request):
            yield error
        if error := self._validate_request(ctx):
            yield error

        preprocess_ret = await self._preprocess(ctx)
        if isinstance(preprocess_ret, ErrorResponse):
            yield preprocess_ret

        generators_ret = await self._prepare_generators(ctx)
        if isinstance(generators_ret, ErrorResponse):
            yield generators_ret

        collect_ret = await self._collect_batch(ctx)
        if isinstance(collect_ret, ErrorResponse):
            yield collect_ret

        yield self._build_response(ctx)

636
    def _validate_request(self, ctx: ServeContext) -> ErrorResponse | None:
637
        truncate_prompt_tokens = getattr(ctx.request, "truncate_prompt_tokens", None)
638

639
640
641
642
        if (
            truncate_prompt_tokens is not None
            and truncate_prompt_tokens > self.max_model_len
        ):
643
644
645
            return self.create_error_response(
                "truncate_prompt_tokens value is "
                "greater than max_model_len."
646
647
                " Please, select a smaller truncation size."
            )
648
649
        return None

650
651
652
    def _create_pooling_params(
        self,
        ctx: ServeContext,
653
    ) -> PoolingParams | ErrorResponse:
654
655
        if not hasattr(ctx.request, "to_pooling_params"):
            return self.create_error_response(
656
657
                "Request type does not support pooling parameters"
            )
658
659
660

        return ctx.request.to_pooling_params()

661
662
663
    async def _prepare_generators(
        self,
        ctx: ServeContext,
664
    ) -> ErrorResponse | None:
665
        """Schedule the request and get the result generator."""
666
        generators: list[
667
            AsyncGenerator[RequestOutput | PoolingRequestOutput, None]
668
        ] = []
669
670

        try:
671
672
673
674
675
            trace_headers = (
                None
                if ctx.raw_request is None
                else await self._get_trace_headers(ctx.raw_request.headers)
            )
676

677
678
679
            pooling_params = self._create_pooling_params(ctx)
            if isinstance(pooling_params, ErrorResponse):
                return pooling_params
680
681

            if ctx.engine_prompts is None:
682
                return self.create_error_response("Engine prompts not available")
683
684
685
686

            for i, engine_prompt in enumerate(ctx.engine_prompts):
                request_id_item = f"{ctx.request_id}-{i}"

687
688
                self._log_inputs(
                    request_id_item,
689
                    engine_prompt,
690
691
692
                    params=pooling_params,
                    lora_request=ctx.lora_request,
                )
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709

                generator = self.engine_client.encode(
                    engine_prompt,
                    pooling_params,
                    request_id_item,
                    lora_request=ctx.lora_request,
                    trace_headers=trace_headers,
                    priority=getattr(ctx.request, "priority", 0),
                )

                generators.append(generator)

            ctx.result_generator = merge_async_iterators(*generators)

            return None

        except Exception as e:
710
            return self.create_error_response(e)
711
712
713
714

    async def _collect_batch(
        self,
        ctx: ServeContext,
715
    ) -> ErrorResponse | None:
716
717
718
        """Collect batch results from the result generator."""
        try:
            if ctx.engine_prompts is None:
719
                return self.create_error_response("Engine prompts not available")
720
721

            num_prompts = len(ctx.engine_prompts)
722
            final_res_batch: list[RequestOutput | PoolingRequestOutput | None]
723
724
725
            final_res_batch = [None] * num_prompts

            if ctx.result_generator is None:
726
                return self.create_error_response("Result generator not available")
727
728
729
730
731
732

            async for i, res in ctx.result_generator:
                final_res_batch[i] = res

            if None in final_res_batch:
                return self.create_error_response(
733
734
                    "Failed to generate results for all prompts"
                )
735

736
            ctx.final_res_batch = [res for res in final_res_batch if res is not None]
737
738
739
740

            return None

        except Exception as e:
741
            return self.create_error_response(e)
742

743
    def create_error_response(
744
        self,
745
        message: str | Exception,
746
747
        err_type: str = "BadRequestError",
        status_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
748
        param: str | None = None,
749
    ) -> ErrorResponse:
750
751
752
753
754
        exc: Exception | None = None

        if isinstance(message, Exception):
            exc = message

755
            from vllm.exceptions import VLLMValidationError
756
757
758
759
760

            if isinstance(exc, VLLMValidationError):
                err_type = "BadRequestError"
                status_code = HTTPStatus.BAD_REQUEST
                param = exc.parameter
761
            elif isinstance(exc, (ValueError, TypeError, RuntimeError, OverflowError)):
762
763
764
765
                # Common validation errors from user input
                err_type = "BadRequestError"
                status_code = HTTPStatus.BAD_REQUEST
                param = None
766
767
768
769
            elif isinstance(exc, NotImplementedError):
                err_type = "NotImplementedError"
                status_code = HTTPStatus.NOT_IMPLEMENTED
                param = None
770
771
772
773
774
775
776
777
778
779
780
781
            elif exc.__class__.__name__ == "TemplateError":
                # jinja2.TemplateError (avoid importing jinja2)
                err_type = "BadRequestError"
                status_code = HTTPStatus.BAD_REQUEST
                param = None
            else:
                err_type = "InternalServerError"
                status_code = HTTPStatus.INTERNAL_SERVER_ERROR
                param = None

            message = str(exc)

782
783
784
785
786
787
        if self.log_error_stack:
            exc_type, _, _ = sys.exc_info()
            if exc_type is not None:
                traceback.print_exc()
            else:
                traceback.print_stack()
788

789
        return ErrorResponse(
790
            error=ErrorInfo(
791
                message=sanitize_message(message),
792
793
794
795
                type=err_type,
                code=status_code.value,
                param=param,
            )
796
        )
797

798
    def create_streaming_error_response(
799
        self,
800
        message: str | Exception,
801
802
        err_type: str = "BadRequestError",
        status_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
803
        param: str | None = None,
804
    ) -> str:
805
        json_str = json.dumps(
806
            self.create_error_response(
807
808
809
810
                message=message,
                err_type=err_type,
                status_code=status_code,
                param=param,
811
812
            ).model_dump()
        )
813
814
        return json_str

815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
    def _raise_if_error(self, finish_reason: str | None, request_id: str) -> None:
        """Raise GenerationError if finish_reason indicates an error."""
        if finish_reason == "error":
            logger.error(
                "Request %s failed with an internal error during generation",
                request_id,
            )
            raise GenerationError("Internal server error")

    def _convert_generation_error_to_response(
        self, e: GenerationError
    ) -> ErrorResponse:
        """Convert GenerationError to ErrorResponse."""
        return self.create_error_response(
            str(e),
            err_type="InternalServerError",
            status_code=e.status_code,
        )

    def _convert_generation_error_to_streaming_response(
        self, e: GenerationError
    ) -> str:
        """Convert GenerationError to streaming error response."""
        return self.create_streaming_error_response(
            str(e),
            err_type="InternalServerError",
            status_code=e.status_code,
        )

844
    async def _check_model(
845
846
        self,
        request: AnyRequest,
847
    ) -> ErrorResponse | None:
848
849
        error_response = None

850
        if self._is_model_supported(request.model):
851
            return None
852
        if request.model in self.models.lora_requests:
853
            return None
854
855
856
857
858
        if (
            envs.VLLM_ALLOW_RUNTIME_LORA_UPDATING
            and request.model
            and (load_result := await self.models.resolve_lora(request.model))
        ):
859
860
            if isinstance(load_result, LoRARequest):
                return None
861
862
863
864
            if (
                isinstance(load_result, ErrorResponse)
                and load_result.error.code == HTTPStatus.BAD_REQUEST.value
            ):
865
866
867
                error_response = load_result

        return error_response or self.create_error_response(
868
869
            message=f"The model `{request.model}` does not exist.",
            err_type="NotFoundError",
870
            status_code=HTTPStatus.NOT_FOUND,
871
            param="model",
872
        )
873

874
    def _get_active_default_mm_loras(self, request: AnyRequest) -> LoRARequest | None:
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
        """Determine if there are any active default multimodal loras."""
        # TODO: Currently this is only enabled for chat completions
        # to be better aligned with only being enabled for .generate
        # when run offline. It would be nice to support additional
        # tasks types in the future.
        message_types = self._get_message_types(request)
        default_mm_loras = set()

        for lora in self.models.lora_requests.values():
            # Best effort match for default multimodal lora adapters;
            # There is probably a better way to do this, but currently
            # this matches against the set of 'types' in any content lists
            # up until '_', e.g., to match audio_url -> audio
            if lora.lora_name in message_types:
                default_mm_loras.add(lora)

        # Currently only support default modality specific loras if
        # we have exactly one lora matched on the request.
        if len(default_mm_loras) == 1:
            return default_mm_loras.pop()
        return None

897
    def _maybe_get_adapters(
898
899
900
        self,
        request: AnyRequest,
        supports_default_mm_loras: bool = False,
901
    ) -> LoRARequest | None:
902
        if request.model in self.models.lora_requests:
903
            return self.models.lora_requests[request.model]
904
905
906
907
908
909

        # Currently only support default modality specific loras
        # if we have exactly one lora matched on the request.
        if supports_default_mm_loras:
            default_mm_lora = self._get_active_default_mm_loras(request)
            if default_mm_lora is not None:
910
                return default_mm_lora
911
912

        if self._is_model_supported(request.model):
913
            return None
914

915
        # if _check_model has been called earlier, this will be unreachable
916
        raise ValueError(f"The model `{request.model}` does not exist.")
917

918
919
920
921
922
923
924
925
926
927
    def _get_message_types(self, request: AnyRequest) -> set[str]:
        """Retrieve the set of types from message content dicts up
        until `_`; we use this to match potential multimodal data
        with default per modality loras.
        """
        message_types: set[str] = set()

        if not hasattr(request, "messages"):
            return message_types

928
929
930
931
932
        messages = request.messages
        if messages is None or isinstance(messages, (str, bytes)):
            return message_types

        for message in messages:
933
934
935
936
937
            if (
                isinstance(message, dict)
                and "content" in message
                and isinstance(message["content"], list)
            ):
938
939
940
941
942
                for content_dict in message["content"]:
                    if "type" in content_dict:
                        message_types.add(content_dict["type"].split("_")[0])
        return message_types

943
    async def _normalize_prompt_text_to_input(
944
945
946
        self,
        request: AnyRequest,
        prompt: str,
947
        tokenizer: TokenizerLike,
948
        add_special_tokens: bool,
949
    ) -> TokensPrompt:
950
951
        async_tokenizer = self._get_async_tokenizer(tokenizer)

952
953
954
955
        if (
            self.model_config.encoder_config is not None
            and self.model_config.encoder_config.get("do_lower_case", False)
        ):
956
957
            prompt = prompt.lower()

958
        truncate_prompt_tokens = getattr(request, "truncate_prompt_tokens", None)
959

960
        if truncate_prompt_tokens is None:
961
            encoded = await async_tokenizer(
962
963
                prompt, add_special_tokens=add_special_tokens
            )
964
965
        elif truncate_prompt_tokens < 0:
            # Negative means we cap at the model's max length
966
967
968
969
            encoded = await async_tokenizer(
                prompt,
                add_special_tokens=add_special_tokens,
                truncation=True,
970
971
                max_length=self.max_model_len,
            )
972
        else:
973
974
975
976
            encoded = await async_tokenizer(
                prompt,
                add_special_tokens=add_special_tokens,
                truncation=True,
977
978
                max_length=truncate_prompt_tokens,
            )
979
980
981
982
983
984

        input_ids = encoded.input_ids
        input_text = prompt

        return self._validate_input(request, input_ids, input_text)

985
    async def _normalize_prompt_tokens_to_input(
986
987
        self,
        request: AnyRequest,
988
        prompt_ids: list[int],
989
        tokenizer: TokenizerLike | None,
990
    ) -> TokensPrompt:
991
        truncate_prompt_tokens = getattr(request, "truncate_prompt_tokens", None)
992

993
        if truncate_prompt_tokens is None:
994
            input_ids = prompt_ids
995
        elif truncate_prompt_tokens < 0:
996
            input_ids = prompt_ids[-self.max_model_len :]
997
998
999
        else:
            input_ids = prompt_ids[-truncate_prompt_tokens:]

1000
1001
1002
1003
1004
        if tokenizer is None:
            input_text = ""
        else:
            async_tokenizer = self._get_async_tokenizer(tokenizer)
            input_text = await async_tokenizer.decode(input_ids)
1005

1006
1007
1008
1009
1010
        return self._validate_input(request, input_ids, input_text)

    def _validate_input(
        self,
        request: AnyRequest,
1011
        input_ids: list[int],
1012
        input_text: str,
1013
    ) -> TokensPrompt:
1014
1015
        token_num = len(input_ids)

1016
1017
        # Note: EmbeddingRequest, ClassificationRequest,
        # and ScoreRequest doesn't have max_tokens
1018
        if isinstance(
1019
            request,
1020
1021
1022
            (
                EmbeddingChatRequest,
                EmbeddingCompletionRequest,
1023
1024
1025
                ScoreDataRequest,
                ScoreTextRequest,
                ScoreQueriesDocumentsRequest,
1026
                RerankRequest,
1027
1028
                ClassificationCompletionRequest,
                ClassificationChatRequest,
1029
1030
            ),
        ):
1031
1032
            # Note: input length can be up to the entire model context length
            # since these requests don't generate tokens.
1033
            if token_num > self.max_model_len:
1034
                operations: dict[type[AnyRequest], str] = {
1035
1036
1037
                    ScoreDataRequest: "score",
                    ScoreTextRequest: "score",
                    ScoreQueriesDocumentsRequest: "score",
1038
1039
                    ClassificationCompletionRequest: "classification",
                    ClassificationChatRequest: "classification",
1040
                }
1041
                operation = operations.get(type(request), "embedding generation")
1042
                raise VLLMValidationError(
1043
1044
                    f"This model's maximum context length is "
                    f"{self.max_model_len} tokens. However, you requested "
1045
                    f"{token_num} tokens in the input for {operation}. "
1046
1047
1048
                    f"Please reduce the length of the input.",
                    parameter="input_tokens",
                    value=token_num,
1049
                )
1050
            return TokensPrompt(prompt=input_text, prompt_token_ids=input_ids)
1051

1052
1053
        # Note: TokenizeRequest and DetokenizeRequest doesn't have max_tokens
        # and does not require model context length validation
1054
        if isinstance(
1055
1056
            request,
            (TokenizeCompletionRequest, TokenizeChatRequest, DetokenizeRequest),
1057
        ):
1058
            return TokensPrompt(prompt=input_text, prompt_token_ids=input_ids)
1059

1060
1061
1062
1063
1064
        # chat completion endpoint supports max_completion_tokens
        if isinstance(request, ChatCompletionRequest):
            # TODO(#9845): remove max_tokens when field dropped from OpenAI API
            max_tokens = request.max_completion_tokens or request.max_tokens
        else:
1065
            max_tokens = getattr(request, "max_tokens", None)
1066
1067
1068
1069

        # Note: input length can be up to model context length - 1 for
        # completion-like requests.
        if token_num >= self.max_model_len:
1070
            raise VLLMValidationError(
1071
                f"This model's maximum context length is "
1072
1073
                f"{self.max_model_len} tokens. However, your request has "
                f"{token_num} input tokens. Please reduce the length of "
1074
1075
1076
                "the input messages.",
                parameter="input_tokens",
                value=token_num,
1077
            )
1078

1079
        if max_tokens is not None and token_num + max_tokens > self.max_model_len:
1080
            raise VLLMValidationError(
1081
1082
1083
1084
                "'max_tokens' or 'max_completion_tokens' is too large: "
                f"{max_tokens}. This model's maximum context length is "
                f"{self.max_model_len} tokens and your request has "
                f"{token_num} input tokens ({max_tokens} > {self.max_model_len}"
1085
1086
1087
                f" - {token_num}).",
                parameter="max_tokens",
                value=max_tokens,
1088
            )
1089

1090
        return TokensPrompt(prompt=input_text, prompt_token_ids=input_ids)
1091

1092
    async def _tokenize_prompt_input_async(
1093
1094
        self,
        request: AnyRequest,
1095
        tokenizer: TokenizerLike,
1096
        prompt_input: str | list[int],
1097
        add_special_tokens: bool = True,
1098
    ) -> TokensPrompt:
1099
        """
1100
        A simpler implementation that tokenizes a single prompt input.
1101
        """
1102
        async for result in self._tokenize_prompt_inputs_async(
1103
1104
            request,
            tokenizer,
1105
            [prompt_input],
1106
            add_special_tokens=add_special_tokens,
1107
1108
1109
        ):
            return result
        raise ValueError("No results yielded from tokenization")
1110

1111
    async def _tokenize_prompt_inputs_async(
1112
1113
        self,
        request: AnyRequest,
1114
        tokenizer: TokenizerLike,
1115
        prompt_inputs: Iterable[str | list[int]],
1116
        add_special_tokens: bool = True,
1117
    ) -> AsyncGenerator[TokensPrompt, None]:
1118
        """
1119
        A simpler implementation that tokenizes multiple prompt inputs.
1120
        """
1121
1122
        for prompt in prompt_inputs:
            if isinstance(prompt, str):
1123
                yield await self._normalize_prompt_text_to_input(
1124
                    request,
1125
1126
                    prompt=prompt,
                    tokenizer=tokenizer,
1127
1128
1129
                    add_special_tokens=add_special_tokens,
                )
            else:
1130
                yield await self._normalize_prompt_tokens_to_input(
1131
                    request,
1132
1133
                    prompt_ids=prompt,
                    tokenizer=tokenizer,
1134
1135
                )

1136
1137
    def _validate_chat_template(
        self,
1138
1139
        request_chat_template: str | None,
        chat_template_kwargs: dict[str, Any] | None,
1140
        trust_request_chat_template: bool,
1141
    ) -> ErrorResponse | None:
1142
        if not trust_request_chat_template and (
1143
1144
1145
1146
1147
1148
            request_chat_template is not None
            or (
                chat_template_kwargs
                and chat_template_kwargs.get("chat_template") is not None
            )
        ):
1149
1150
1151
            return self.create_error_response(
                "Chat template is passed with request, but "
                "--trust-request-chat-template is not set. "
1152
1153
                "Refused request with untrusted chat template."
            )
1154
1155
        return None

1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
    @staticmethod
    def _prepare_extra_chat_template_kwargs(
        request_chat_template_kwargs: dict[str, Any] | None = None,
        default_chat_template_kwargs: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Helper to merge server-default and request-specific chat template kwargs."""
        request_chat_template_kwargs = request_chat_template_kwargs or {}
        if default_chat_template_kwargs is None:
            return request_chat_template_kwargs
        # Apply server defaults first, then request kwargs override.
        return default_chat_template_kwargs | request_chat_template_kwargs

1168
1169
    async def _preprocess_chat(
        self,
1170
        request: ChatLikeRequest | ResponsesRequest,
1171
        renderer: RendererLike,
1172
        messages: list[ChatCompletionMessageParam],
1173
        chat_template: str | None,
1174
        chat_template_content_format: ChatTemplateContentFormatOption,
1175
1176
        add_generation_prompt: bool = True,
        continue_final_message: bool = False,
1177
1178
1179
        tool_dicts: list[dict[str, Any]] | None = None,
        documents: list[dict[str, str]] | None = None,
        chat_template_kwargs: dict[str, Any] | None = None,
1180
        default_chat_template_kwargs: dict[str, Any] | None = None,
1181
        tool_parser: Callable[[TokenizerLike], ToolParser] | None = None,
1182
        add_special_tokens: bool = False,
1183
    ) -> tuple[list[ConversationMessage], list[TokensPrompt]]:
1184
1185
1186
1187
1188
1189
1190
1191
1192
        chat_template_kwargs = {
            "chat_template": chat_template,
            "add_generation_prompt": add_generation_prompt,
            "continue_final_message": continue_final_message,
            "tools": tool_dicts,
            "documents": documents,
            **(chat_template_kwargs or {}),
        }
        chat_template_kwargs = self._prepare_extra_chat_template_kwargs(
1193
1194
1195
            chat_template_kwargs,
            default_chat_template_kwargs,
        )
1196

1197
1198
1199
1200
1201
        # Use the async tokenizer in `OpenAIServing` if possible.
        # Later we can move it into the renderer so that we can return both
        # text and token IDs in the same prompt from `render_messages_async`
        # which is used for logging and `enable_response_messages`.
        from vllm.tokenizers.mistral import MistralTokenizer
1202

1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
        conversation, engine_prompt = await renderer.render_messages_async(
            messages,
            chat_template_content_format=chat_template_content_format,
            tokenize=(
                chat_template_kwargs.pop("tokenize", False)
                or isinstance(renderer.tokenizer, MistralTokenizer)
            ),
            **chat_template_kwargs,
        )

        if "prompt_token_ids" not in engine_prompt:
            extra_data = engine_prompt
            engine_prompt = await self._tokenize_prompt_input_async(
                request,
                renderer.get_tokenizer(),
                engine_prompt["prompt"],
                add_special_tokens=add_special_tokens,
1220
            )
1221
1222
            # Fill in other keys like MM data
            engine_prompt.update(extra_data)  # type: ignore
1223
        else:
1224
1225
1226
1227
            self._validate_input(
                request=request,
                input_ids=engine_prompt["prompt_token_ids"],  # type: ignore
                input_text="",
1228
1229
            )

1230
1231
1232
1233
1234
1235
        engine_prompt = cast(TokensPrompt, engine_prompt)

        if request.mm_processor_kwargs is not None:
            engine_prompt["mm_processor_kwargs"] = request.mm_processor_kwargs
        if (cache_salt := getattr(request, "cache_salt", None)) is not None:
            engine_prompt["cache_salt"] = cache_salt
1236

1237
1238
1239
        # tool parsing is done only if a tool_parser has been set and if
        # tool_choice is not "none" (if tool_choice is "none" but a tool_parser
        # is set, we want to prevent parsing a tool_call hallucinated by the LLM
1240
1241
1242
        should_parse_tools = tool_parser is not None and (
            hasattr(request, "tool_choice") and request.tool_choice != "none"
        )
1243
1244

        if should_parse_tools:
1245
1246
1247
1248
1249
            if not isinstance(request, ChatCompletionRequest | ResponsesRequest):
                msg = (
                    "Tool usage is only supported for Chat Completions API "
                    "or Responses API requests."
                )
1250
                raise NotImplementedError(msg)
1251

1252
1253
            tokenizer = renderer.get_tokenizer()
            request = tool_parser(tokenizer).adjust_request(request=request)  # type: ignore
1254

1255
        return conversation, [engine_prompt]
1256

1257
1258
1259
1260
    async def _process_inputs(
        self,
        request_id: str,
        engine_prompt: PromptType,
1261
        params: SamplingParams | PoolingParams,
1262
        *,
1263
1264
        lora_request: LoRARequest | None,
        trace_headers: Mapping[str, str] | None,
1265
        priority: int,
1266
        data_parallel_rank: int | None = None,
1267
    ) -> tuple[EngineCoreRequest, dict[str, Any]]:
1268
        """Use the Processor to process inputs for AsyncLLM."""
1269
        tokenization_kwargs: dict[str, Any] = {}
1270
1271
1272
        _validate_truncation_size(
            self.max_model_len, params.truncate_prompt_tokens, tokenization_kwargs
        )
1273

1274
        engine_request = self.input_processor.process_inputs(
1275
1276
            request_id,
            engine_prompt,
1277
            params,
1278
1279
1280
1281
            lora_request=lora_request,
            tokenization_kwargs=tokenization_kwargs,
            trace_headers=trace_headers,
            priority=priority,
1282
            data_parallel_rank=data_parallel_rank,
1283
1284
1285
        )
        return engine_request, tokenization_kwargs

1286
1287
1288
    async def _render_next_turn(
        self,
        request: ResponsesRequest,
1289
        renderer: RendererLike,
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
        messages: list[ResponseInputOutputItem],
        tool_dicts: list[dict[str, Any]] | None,
        tool_parser,
        chat_template: str | None,
        chat_template_content_format: ChatTemplateContentFormatOption,
    ):
        new_messages = construct_input_messages(
            request_input=messages,
        )

1300
        _, engine_prompts = await self._preprocess_chat(
1301
            request,
1302
            renderer,
1303
1304
1305
1306
1307
1308
            new_messages,
            tool_dicts=tool_dicts,
            tool_parser=tool_parser,
            chat_template=chat_template,
            chat_template_content_format=chat_template_content_format,
        )
1309
        return engine_prompts
1310

1311
1312
1313
    async def _generate_with_builtin_tools(
        self,
        request_id: str,
1314
        engine_prompt: TokensPrompt,
1315
1316
        sampling_params: SamplingParams,
        context: ConversationContext,
1317
        lora_request: LoRARequest | None = None,
1318
1319
1320
        priority: int = 0,
        **kwargs,
    ):
1321
1322
        prompt_text, _, _ = self._get_prompt_components(engine_prompt)

1323
        orig_priority = priority
1324
        sub_request = 0
1325
        while True:
1326
1327
            # Ensure that each sub-request has a unique request id.
            sub_request_id = f"{request_id}_{sub_request}"
1328
            self._log_inputs(
1329
                sub_request_id,
1330
                engine_prompt,
1331
1332
1333
                params=sampling_params,
                lora_request=lora_request,
            )
1334
            trace_headers = kwargs.get("trace_headers")
1335
            engine_request, tokenization_kwargs = await self._process_inputs(
1336
                sub_request_id,
1337
1338
                engine_prompt,
                sampling_params,
1339
1340
1341
                lora_request=lora_request,
                trace_headers=trace_headers,
                priority=priority,
1342
            )
1343
1344
1345
1346

            generator = self.engine_client.generate(
                engine_request,
                sampling_params,
1347
                sub_request_id,
1348
1349
                lora_request=lora_request,
                priority=priority,
1350
1351
                prompt_text=prompt_text,
                tokenization_kwargs=tokenization_kwargs,
1352
1353
                **kwargs,
            )
1354

1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
            async for res in generator:
                context.append_output(res)
                # NOTE(woosuk): The stop condition is handled by the engine.
                yield context

            if not context.need_builtin_tool_call():
                # The model did not ask for a tool call, so we're done.
                break

            # Call the tool and update the context with the result.
            tool_output = await context.call_tool()
1366
            context.append_tool_output(tool_output)
1367
1368
1369
1370
1371
1372

            # TODO: uncomment this and enable tool output streaming
            # yield context

            # Create inputs for the next turn.
            # Render the next prompt token ids.
1373
1374
            if isinstance(context, (HarmonyContext, StreamingHarmonyContext)):
                prompt_token_ids = context.render_for_completion()
1375
                engine_prompt = TokensPrompt(prompt_token_ids=prompt_token_ids)
1376
            elif isinstance(context, ParsableContext):
1377
                engine_prompts = await self._render_next_turn(
1378
                    context.request,
1379
                    context.renderer,
1380
1381
1382
1383
1384
1385
1386
                    context.parser.response_messages,
                    context.tool_dicts,
                    context.tool_parser_cls,
                    context.chat_template,
                    context.chat_template_content_format,
                )
                engine_prompt = engine_prompts[0]
1387
                prompt_text, _, _ = self._get_prompt_components(engine_prompt)
1388

1389
            # Update the sampling params.
1390
1391
1392
            sampling_params.max_tokens = self.max_model_len - len(
                engine_prompt["prompt_token_ids"]
            )
1393
1394
            # OPTIMIZATION
            priority = orig_priority - 1
1395
            sub_request += 1
1396

1397
1398
    def _get_prompt_components(self, prompt: PromptType) -> PromptComponents:
        return get_prompt_components(prompt)
1399

1400
1401
1402
    def _log_inputs(
        self,
        request_id: str,
1403
        inputs: PromptType,
1404
1405
        params: SamplingParams | PoolingParams | BeamSearchParams | None,
        lora_request: LoRARequest | None,
1406
1407
1408
    ) -> None:
        if self.request_logger is None:
            return
1409

1410
        prompt, prompt_token_ids, prompt_embeds = self._get_prompt_components(inputs)
1411
1412
1413
1414
1415

        self.request_logger.log_inputs(
            request_id,
            prompt,
            prompt_token_ids,
1416
            prompt_embeds,
1417
1418
1419
            params=params,
            lora_request=lora_request,
        )
1420

1421
1422
1423
    async def _get_trace_headers(
        self,
        headers: Headers,
1424
    ) -> Mapping[str, str] | None:
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
        is_tracing_enabled = await self.engine_client.is_tracing_enabled()

        if is_tracing_enabled:
            return extract_trace_headers(headers)

        if contains_trace_headers(headers):
            log_tracing_disabled_warning()

        return None

1435
    @staticmethod
1436
    def _base_request_id(
1437
1438
        raw_request: Request | None, default: str | None = None
    ) -> str | None:
1439
        """Pulls the request id to use from a header, if provided"""
1440
1441
1442
1443
        if raw_request is not None and (
            (req_id := raw_request.headers.get("X-Request-Id")) is not None
        ):
            return req_id
1444

1445
        return random_uuid() if default is None else default
1446

1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
    @staticmethod
    def _get_data_parallel_rank(raw_request: Request | None) -> int | None:
        """Pulls the data parallel rank from a header, if provided"""
        if raw_request is None:
            return None

        rank_str = raw_request.headers.get("X-data-parallel-rank")
        if rank_str is None:
            return None

        try:
            return int(rank_str)
        except ValueError:
            return None

1462
1463
1464
    @staticmethod
    def _parse_tool_calls_from_content(
        request: ResponsesRequest | ChatCompletionRequest,
1465
        tokenizer: TokenizerLike | None,
1466
        enable_auto_tools: bool,
1467
        tool_parser_cls: Callable[[TokenizerLike], ToolParser] | None,
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
        content: str | None = None,
    ) -> tuple[list[FunctionCall] | None, str | None]:
        function_calls = list[FunctionCall]()
        if request.tool_choice and isinstance(request.tool_choice, ToolChoiceFunction):
            assert content is not None
            # Forced Function Call
            function_calls.append(
                FunctionCall(name=request.tool_choice.name, arguments=content)
            )
            content = None  # Clear content since tool is called.
        elif request.tool_choice and isinstance(
            request.tool_choice, ChatCompletionNamedToolChoiceParam
        ):
            assert content is not None
            # Forced Function Call
            function_calls.append(
                FunctionCall(name=request.tool_choice.function.name, arguments=content)
            )
            content = None  # Clear content since tool is called.
        elif request.tool_choice == "required":
            assert content is not None
            tool_calls = TypeAdapter(list[FunctionDefinition]).validate_json(content)
            function_calls.extend(
                [
                    FunctionCall(
                        name=tool_call.name,
                        arguments=json.dumps(tool_call.parameters, ensure_ascii=False),
                    )
                    for tool_call in tool_calls
                ]
            )
            content = None  # Clear content since tool is called.
        elif (
            tool_parser_cls
            and enable_auto_tools
            and (request.tool_choice == "auto" or request.tool_choice is None)
        ):
1505
1506
1507
1508
1509
            if tokenizer is None:
                raise ValueError(
                    "Tokenizer not available when `skip_tokenizer_init=True`"
                )

1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
            # Automatic Tool Call Parsing
            try:
                tool_parser = tool_parser_cls(tokenizer)
            except RuntimeError as e:
                logger.exception("Error in tool parser creation.")
                raise e
            tool_call_info = tool_parser.extract_tool_calls(
                content if content is not None else "",
                request=request,  # type: ignore
            )
            if tool_call_info is not None and tool_call_info.tools_called:
                # extract_tool_calls() returns a list of tool calls.
                function_calls.extend(
                    FunctionCall(
                        name=tool_call.function.name,
                        arguments=tool_call.function.arguments,
                    )
                    for tool_call in tool_call_info.tool_calls
                )
                content = tool_call_info.content
1530
1531
                if content and content.strip() == "":
                    content = None
1532
1533
1534
1535
1536
1537
            else:
                # No tool calls.
                return None, content

        return function_calls, content

1538
    @staticmethod
1539
1540
1541
    def _get_decoded_token(
        logprob: Logprob,
        token_id: int,
1542
        tokenizer: TokenizerLike | None,
1543
1544
        return_as_token_id: bool = False,
    ) -> str:
1545
1546
1547
        if return_as_token_id:
            return f"token_id:{token_id}"

1548
1549
        if logprob.decoded_token is not None:
            return logprob.decoded_token
1550
1551
1552
1553
1554
1555

        if tokenizer is None:
            raise ValueError(
                "Unable to get tokenizer because `skip_tokenizer_init=True`"
            )

1556
        return tokenizer.decode(token_id)
1557

1558
    def _is_model_supported(self, model_name: str | None) -> bool:
1559
1560
        if not model_name:
            return True
1561
        return self.models.is_base_model(model_name)
1562

1563
1564

def clamp_prompt_logprobs(
1565
1566
    prompt_logprobs: PromptLogprobs | None,
) -> PromptLogprobs | None:
1567
1568
1569
1570
1571
1572
1573
    if prompt_logprobs is None:
        return prompt_logprobs

    for logprob_dict in prompt_logprobs:
        if logprob_dict is None:
            continue
        for logprob_values in logprob_dict.values():
1574
            if logprob_values.logprob == float("-inf"):
1575
1576
                logprob_values.logprob = -9999.0
    return prompt_logprobs