Skip to content

vllm.entrypoints.openai.responses.protocol

Classes:

Functions:

PromptCacheOptions

Bases: OpenAIBaseModel

OpenAI prompt_cache_options; defined here because openai>=2.25 lacks it

Source code in vllm/entrypoints/openai/responses/protocol.py
class PromptCacheOptions(OpenAIBaseModel):
    """OpenAI prompt_cache_options; defined here because openai>=2.25 lacks it"""

    mode: Literal["implicit", "explicit"] = "implicit"
    ttl: Literal["30m"] = "30m"
    comparison_response_id: str | None = None

PromptCacheOptionsParam

Bases: PromptCacheOptions

Request-side variant; prewarm is request-only in OpenAI's schema.

Source code in vllm/entrypoints/openai/responses/protocol.py
class PromptCacheOptionsParam(PromptCacheOptions):
    """Request-side variant; prewarm is request-only in OpenAI's schema."""

    prewarm: bool | None = None

    def to_response(self) -> PromptCacheOptions:
        return PromptCacheOptions(
            mode=self.mode,
            ttl=self.ttl,
            comparison_response_id=self.comparison_response_id,
        )

ResponseRawMessageAndToken

Bases: OpenAIBaseModel

Class to show the raw message. If message / tokens diverge, tokens is the source of truth

Source code in vllm/entrypoints/openai/responses/protocol.py
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"

ResponsesRequest

Bases: OpenAIBaseModel

Methods:

Source code in vllm/entrypoints/openai/responses/protocol.py
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 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
 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
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 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
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
class ResponsesRequest(OpenAIBaseModel):
    # Ordered by official OpenAI API documentation
    # https://platform.openai.com/docs/api-reference/responses/create
    background: bool | None = False
    include: (
        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",
            ],
        ]
        | None
    ) = None
    input: (
        str
        | Annotated[
            list[
                Annotated[
                    ResponseInputOutputItem,
                    BeforeValidator(_default_input_image_details),
                ]
            ],
            FailFast(),
        ]
    )
    instructions: str | None = None
    max_output_tokens: int | None = None
    max_tool_calls: int | None = None
    metadata: Metadata | None = None
    model: str | None = None
    logit_bias: dict[str, float] | None = None
    parallel_tool_calls: bool | None = True
    previous_response_id: str | None = None
    prompt: ResponsePrompt | None = None
    reasoning: Reasoning | None = None
    include_reasoning: bool = Field(
        default=True,
        description=(
            "Whether to include reasoning content in the response. "
            "When false, reasoning tokens are still generated but "
            "excluded from the output. This reduces network traffic "
            "without affecting model inference."
        ),
    )
    service_tier: Literal["auto", "default", "flex", "scale", "priority"] = "auto"
    store: bool | None = True
    stream: bool | None = False
    temperature: float | None = None
    text: ResponseTextConfig | None = None
    tool_choice: ToolChoice = "auto"
    tools: list[Tool] = Field(default_factory=list)
    top_logprobs: TopLogprobsParam = 0
    top_p: float | None = None
    top_k: int | None = None
    min_p: float | None = None
    truncation: Literal["auto", "disabled"] | None = "disabled"
    user: str | None = None
    skip_special_tokens: bool | None = None
    spaces_between_special_tokens: bool = True
    include_stop_str_in_output: bool = False
    presence_penalty: float | None = Field(
        default=None,
        ge=-2.0,
        le=2.0,
        description=(
            "The presence penalty that was used to penalize new tokens based on "
            "whether they appear in the text so far."
        ),
    )
    frequency_penalty: float | None = Field(
        default=None,
        ge=-2.0,
        le=2.0,
        description=(
            "The frequency penalty that was used to penalize new tokens based on "
            "their frequency in the text so far."
        ),
    )
    prompt_cache_key: str | None = Field(
        default=None,
        description=(
            "A key that was used to read from or write to the prompt cache."
            "Note: This field has not been implemented yet "
            "and vLLM will ignore it."
        ),
    )
    prompt_cache_options: PromptCacheOptionsParam | None = Field(
        default=None,
        description=(
            "Prompt-caching options. Accepted and echoed in the response; "
            "vLLM does not act on them."
        ),
    )
    prompt_cache_retention: PromptCacheRetention | None = Field(
        default=None,
        description=(
            "Prompt cache retention policy. Accepted and echoed in the "
            "response; vLLM does not act on it."
        ),
    )
    safety_identifier: str | None = Field(
        default=None,
        description=(
            "Stable identifier for the end user. Accepted and echoed in the "
            "response; vLLM does not act on it."
        ),
    )

    # --8<-- [start:responses-extra-params]
    watermarking: bool | None = None
    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 "
            "through out the inference process and return in response."
        ),
    )
    session_id: str | None = Field(
        default=None,
        description=(
            "Stable session identity shared by related requests. Unlike "
            "request_id, this value is expected to remain stable across "
            "multiple requests in the same conversation or agent session."
        ),
    )
    media_io_kwargs: dict[str, dict[str, Any]] | None = Field(
        default=None,
        description=(
            "Additional kwargs to pass to the media IO connectors, "
            "keyed by modality. Merged with engine-level media_io_kwargs."
        ),
    )
    mm_processor_kwargs: dict[str, Any] | None = Field(
        default=None,
        description=("Additional kwargs to pass to the HF processor."),
    )
    priority: int = Field(
        default=0,
        ge=PRIORITY_MIN,
        le=PRIORITY_MAX,
        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."
        ),
    )
    mm_payload: MMPayload = Field(
        default="tensors",
        description=(
            "What the render response's `features` carry for multimodal "
            "items. 'tensors' serializes the processed tensors into "
            "`kwargs_data` and `mm_metadata`. 'metadata' sets `kwargs_data` to "
            "null and keeps `mm_metadata` for prefill with "
            "`ec_transfer_params`. 'none' sets both to null for callers that "
            "need only the token layout and item hashes, such as cache-aware "
            "routers. `mm_metadata` is null if any modality has no metadata, "
            "which 'metadata' rejects. Do not send a 'none' response to "
            "`/inference/v1/generate` which reads a null `kwargs_data` as "
            "every item being cached. Only supported on the render endpoints. "
            "Ignored on regular generation endpoints."
        ),
    )
    return_mm_kwargs: bool | None = Field(
        default=None,
        deprecated="return_mm_kwargs is deprecated in favor of the mm_payload field",
        description=(
            "Deprecated alias: false is the same as `mm_payload='none'`. "
            "Ignored when `mm_payload` is set."
        ),
    )
    cache_salt: str | None = Field(
        default=None,
        min_length=1,
        max_length=1024,
        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)."
        ),
    )

    enable_response_messages: bool = Field(
        default=False,
        description=(
            "Dictates whether or not to return messages as part of the "
            "response object. Currently only supported for non-background."
        ),
    )
    # 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
    structured_outputs: StructuredOutputsParams | None = Field(
        default=None,
        description="Additional kwargs for structured outputs",
    )

    repetition_penalty: float | None = None
    seed: int | None = Field(None, ge=_INT64_MIN, le=_INT64_MAX)
    stop: StopParam = []
    stop_token_ids: list[int] | None = []
    ignore_eos: bool = False
    thinking_token_budget: ThinkingTokenBudget = None
    vllm_xargs: dict[str, str | int | float | list[str | int | float]] | None = Field(
        default=None,
        description=(
            "Additional request parameters with (list of) string or "
            "numeric values, used by custom extensions."
        ),
    )
    kv_transfer_params: dict[str, Any] | None = Field(
        default=None,
        description="KVTransfer parameters used for disaggregated serving.",
    )
    ec_transfer_params: dict[str, Any] | None = Field(
        default=None,
        description=(
            "ECTransfer parameters used for encoder-cache disaggregated serving."
        ),
    )
    chat_template_kwargs: dict[str, Any] | None = Field(
        default=None,
        description=(
            "Additional keyword args to pass to the chat template renderer. "
            "Will be accessible by the template."
        ),
    )
    # --8<-- [end:responses-extra-params]

    @field_validator("prompt_cache_retention", mode="before")
    @classmethod
    def _normalize_prompt_cache_retention(cls, value: object) -> object:
        return "in_memory" if value == "in-memory" else value

    def build_chat_params(
        self,
        default_template: str | None,
        default_template_content_format: ChatTemplateContentFormatOption,
        reasoning_effort_map: dict[str, str] | None = None,
    ) -> ChatParams:
        from .utils import should_continue_final_message

        # Check if we should continue the final message (partial completion)
        # This enables Anthropic-style partial message completion where the
        # user provides an incomplete assistant message to continue from.
        continue_final = should_continue_final_message(self.input)

        reasoning = self.reasoning
        reasoning_effort = map_reasoning_effort(
            None if reasoning is None else reasoning.effort, reasoning_effort_map
        )

        extra_kwargs: dict[str, Any] = dict(
            add_generation_prompt=not continue_final,
            continue_final_message=continue_final,
            reasoning_effort=reasoning_effort,
        )

        # When reasoning is requested, activate thinking for models whose
        # chat templates require explicit opt-in (e.g., Gemma4 defaults
        # enable_thinking to false). For templates that don't declare the
        # variable, resolve_chat_template_kwargs filters it out harmlessly.
        user_kwargs = self.chat_template_kwargs or {}
        if reasoning_effort is not None and "enable_thinking" not in user_kwargs:
            extra_kwargs["enable_thinking"] = reasoning_effort != "none"

        return ChatParams(
            chat_template=default_template,
            chat_template_content_format=default_template_content_format,
            chat_template_kwargs=merge_kwargs(
                self.chat_template_kwargs,
                extra_kwargs,
            ),
            media_io_kwargs=self.media_io_kwargs,
            tool_choice=self.tool_choice if self.tools else None,
            parallel_tool_calls=self.parallel_tool_calls is not False,
        )

    def build_tok_params(self, model_config: ModelConfig) -> TokenizeParams:
        return TokenizeParams(
            max_total_tokens=model_config.max_model_len,
            max_output_tokens=self.max_output_tokens,
            truncate_prompt_tokens=-1 if self.truncation != "disabled" else None,
            max_total_tokens_param="max_model_len",
            max_output_tokens_param="max_output_tokens",
        )

    _grammar_from_parser: bool = PrivateAttr(default=False)
    """CAUTION: Should only be set by the parser's adjust_request."""

    _parser_structured_outputs: StructuredOutputsParams | None = PrivateAttr(
        default=None
    )
    """Parser-derived constraints that preserve the public request's text metadata."""

    _DEFAULT_SAMPLING_PARAMS: ClassVar[dict] = {
        "temperature": 1.0,
        "top_p": 1.0,
        "top_k": 0,
        "min_p": 0.0,
    }

    def extract_structured_outputs(self) -> StructuredOutputsParams | None:
        """Normalize request constraints into `StructuredOutputsParams`."""
        if self._parser_structured_outputs is not None:
            return self._parser_structured_outputs
        if self.text is None or self.text.format is None:
            return self.structured_outputs

        if self.structured_outputs is not None:
            raise VLLMValidationError(
                "Cannot specify both structured_outputs and text.format",
                parameter="structured_outputs",
            )

        response_format = self.text.format
        if response_format.type == "json_object":
            return StructuredOutputsParams(json_object=True)
        if (
            response_format.type == "json_schema"
            and response_format.schema_ is not None
        ):
            return StructuredOutputsParams(
                json=response_format.schema_  # type: ignore[call-arg]
                # --follow-imports skip hides the class definition but also hides
                # multiple third party conflicts, so best of both evils
            )
        return None

    def to_sampling_params(
        self,
        default_max_tokens: int,
        default_sampling_params: dict | None = None,
    ) -> 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(
                "temperature", self._DEFAULT_SAMPLING_PARAMS["temperature"]
            )
        if (top_p := self.top_p) is None:
            top_p = default_sampling_params.get(
                "top_p", self._DEFAULT_SAMPLING_PARAMS["top_p"]
            )
        if (top_k := self.top_k) is None:
            top_k = default_sampling_params.get(
                "top_k", self._DEFAULT_SAMPLING_PARAMS["top_k"]
            )
        if (min_p := self.min_p) is None:
            min_p = default_sampling_params.get(
                "min_p", self._DEFAULT_SAMPLING_PARAMS["min_p"]
            )

        if (repetition_penalty := self.repetition_penalty) is None:
            repetition_penalty = default_sampling_params.get("repetition_penalty", 1.0)

        if (presence_penalty := self.presence_penalty) is None:
            presence_penalty = default_sampling_params.get("presence_penalty", 0.0)

        if (frequency_penalty := self.frequency_penalty) is None:
            frequency_penalty = default_sampling_params.get("frequency_penalty", 0.0)

        if (skip_special_tokens := self.skip_special_tokens) is None:
            skip_special_tokens = default_sampling_params.get(
                "skip_special_tokens", True
            )

        stop = self.stop if self.stop else []
        if isinstance(stop, str):
            stop = [stop]

        extra_args: dict[str, Any] = self.vllm_xargs if self.vllm_xargs else {}
        if self.kv_transfer_params:
            extra_args["kv_transfer_params"] = self.kv_transfer_params
        if self.ec_transfer_params:
            extra_args["ec_transfer_params"] = self.ec_transfer_params

        return SamplingParams.from_optional(
            temperature=temperature,
            watermarking=self.watermarking,
            top_p=top_p,
            top_k=top_k,
            min_p=min_p,
            max_tokens=max_tokens,
            logprobs=self.top_logprobs if self.is_include_output_logprobs() else None,
            stop=stop,
            stop_token_ids=self.stop_token_ids,
            frequency_penalty=frequency_penalty,
            presence_penalty=presence_penalty,
            repetition_penalty=repetition_penalty,
            seed=self.seed,
            ignore_eos=self.ignore_eos,
            output_kind=(
                RequestOutputKind.DELTA if self.stream else RequestOutputKind.FINAL_ONLY
            ),
            structured_outputs=self.extract_structured_outputs(),
            logit_bias=self.logit_bias,
            thinking_token_budget=self.thinking_token_budget,
            extra_args=extra_args,
            skip_clone=True,  # Created fresh per request, safe to skip clone
            skip_special_tokens=skip_special_tokens,
            spaces_between_special_tokens=self.spaces_between_special_tokens,
            include_stop_str_in_output=self.include_stop_str_in_output,
        )

    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")
    @classmethod
    def apply_return_mm_kwargs_alias(cls, data: Any) -> Any:
        return resolve_return_mm_kwargs_alias(data)

    @model_validator(mode="before")
    @classmethod
    def check_cache_salt_support(cls, data: Any) -> Any:
        if not isinstance(data, dict):
            return data
        validate_cache_salt(data.get("cache_salt"))
        return data

    @model_validator(mode="before")
    @classmethod
    def validate_background(cls, data):
        if not isinstance(data, dict):
            return data
        if not data.get("background"):
            return data
        if not data.get("store", True):
            raise VLLMValidationError(
                "background can only be used when `store` is true",
                parameter="background",
            )
        return data

    @model_validator(mode="before")
    @classmethod
    def validate_prompt(cls, data):
        if not isinstance(data, dict):
            return data
        if data.get("prompt") is not None:
            raise VLLMValidationError(
                "prompt template is not supported", parameter="prompt"
            )
        return data

    @model_validator(mode="before")
    @classmethod
    def input_item_parsing(cls, data):
        """Parse input items that are missing required fields or that Pydantic
        cannot disambiguate in a Union of TypedDict / BaseModel types.

        Specifically handles:
        - function_call -> ResponseFunctionToolCall
        - reasoning     -> ResponseReasoningItem (auto-generates id)
        - message(role=assistant) -> ResponseOutputMessage (auto-generates
          id/status and annotations)

        Invalid structures are left for Pydantic to reject.
        """
        if not isinstance(data, dict):
            return data
        input_data = data.get("input")

        # Early return for None, strings, or bytes
        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:
            normalized_item = cls._normalize_openresponses_input_item(item)

            if not isinstance(normalized_item, dict):
                processed_input.append(normalized_item)
                continue

            item_type = normalized_item.get("type")

            if item_type == "function_call":
                try:
                    processed_input.append(ResponseFunctionToolCall(**normalized_item))
                except ValidationError:
                    logger.debug(
                        "Failed to parse function_call to ResponseFunctionToolCall, "
                        "leaving for Pydantic validation"
                    )
                    processed_input.append(normalized_item)

            elif item_type == "reasoning":
                try:
                    processed_input.append(ResponseReasoningItem(**normalized_item))
                except ValidationError:
                    logger.debug(
                        "Failed to parse reasoning to ResponseReasoningItem, "
                        "leaving for Pydantic validation"
                    )
                    processed_input.append(normalized_item)

            elif item_type == "message" and normalized_item.get("role") == "assistant":
                if not isinstance(normalized_item.get("content"), list):
                    # String content is a valid EasyInputMessageParam,
                    # do not coerce it to ResponseOutputMessage
                    processed_input.append(item)
                    continue

                try:
                    processed_input.append(ResponseOutputMessage(**normalized_item))
                except ValidationError:
                    logger.debug(
                        "Failed to parse assistant message to ResponseOutputMessage, "
                        "leaving for Pydantic validation"
                    )
                    processed_input.append(item)

            else:
                processed_input.append(normalized_item)

        data["input"] = processed_input
        return data

    @staticmethod
    def _normalize_openresponses_input_item(item: Any) -> Any:
        """Normalize input items to bridge OpenResponses schema and openai-python.

        The OpenResponses specification treats several fields as optional
        (`id`, `status` on assistant/reasoning items; `annotations`
        on output_text content) that the openai-python SDK marks as
        required.  Fill sensible defaults so payloads conforming to the
        OpenResponses spec pass SDK validation.
        """
        if not isinstance(item, dict):
            return item

        item_type = item.get("type", "message")
        should_fill = item_type == "reasoning" or (
            item_type == "message" and item.get("role") == "assistant"
        )
        if not should_fill:
            return item

        normalized_item = item.copy()
        # ``type`` is optional in the OpenResponses schema but load-bearing for
        # SDK validation: without it a filled-in assistant item matches
        # ``ItemReference`` in the input union and collapses to ``{"id": ...}``,
        # silently dropping role/content. Stamp back the type we keyed off.
        normalized_item["type"] = item_type
        if normalized_item.get("id") in (None, ""):
            prefix = "rs" if item_type == "reasoning" else "msg"
            normalized_item["id"] = f"{prefix}_{random_uuid()}"
        if normalized_item.get("status") in (None, ""):
            normalized_item["status"] = "completed"
        if item_type == "reasoning" and normalized_item.get("summary") is None:
            normalized_item["summary"] = []

        # OpenResponses schema treats ``annotations`` as optional for
        # output_text content, but the openai SDK requires it.
        if item_type == "message" and isinstance(normalized_item.get("content"), list):
            normalized_content = []
            for content_item in normalized_item["content"]:
                if (
                    isinstance(content_item, dict)
                    and content_item.get("type") == "output_text"
                    and "annotations" not in content_item
                ):
                    content_item = {**content_item, "annotations": []}
                normalized_content.append(content_item)
            normalized_item["content"] = normalized_content

        return normalized_item

    @model_validator(mode="before")
    @classmethod
    def check_custom_tool_format(cls, data):
        if not isinstance(data, dict):
            return data
        tools = data.get("tools")
        if not isinstance(tools, list):
            return data
        for tool in tools:
            if isinstance(tool, dict):
                tool_dict = tool
            elif hasattr(tool, "model_dump"):
                tool_dict = tool.model_dump()
            else:
                continue
            tool_format = tool_dict.get("format")
            if (
                tool_dict.get("type") == "custom"
                and isinstance(tool_format, dict)
                and tool_format.get("type") == "grammar"
            ):
                raise VLLMValidationError(
                    "Custom tools with a grammar format are not supported; "
                    "only free-form text custom tools are accepted.",
                    parameter="tools",
                )
        return data

    @model_validator(mode="before")
    @classmethod
    def check_tool_usage(cls, data):
        if not isinstance(data, dict):
            return data

        tools = data.get("tools")
        if tools is not None and not isinstance(tools, list):
            # Leave it to field validation, which answers with a 400.
            return data
        tool_choice = data.get("tool_choice", "auto")
        has_tools = tools is not None and len(tools) > 0
        is_named_tool_choice = isinstance(tool_choice, dict) and tool_choice.get(
            "type"
        ) in ("function", "custom")

        if not has_tools:
            if tool_choice in ("auto", "none"):
                data["tool_choice"] = "none"
            elif tool_choice == "required":
                raise VLLMValidationError(
                    "Tool choice 'required' must be specified with 'tools' parameter.",
                    parameter="tool_choice",
                )
            elif is_named_tool_choice:
                raise VLLMValidationError(
                    "Tool choice 'function' not found in 'tools' parameter.",
                    parameter="tool_choice",
                )
        elif is_named_tool_choice and tools is not None:
            tool_name = tool_choice.get("name")
            if not tool_name:
                raise VLLMValidationError(
                    "Tool choice 'function' not found in 'tools' parameter.",
                    parameter="tool_choice",
                )
            resolved = _resolve_named_tool_choice(tool_name, tools)
            if resolved != tool_name:
                data["tool_choice"] = {**tool_choice, "name": resolved}

        return data

    @model_validator(mode="before")
    @classmethod
    def hoist_additional_tools_items(cls, data):
        """Move tools declared by `additional_tools` input items into `tools`.

        Clients such as Codex declare tools through an input item
        (`{"type": "additional_tools", "role": "developer", "tools": [...]}`)
        rather than the top-level `tools` field. Everything downstream reads
        `request.tools`, so merge them there and drop the item from `input`.

        Defined last on purpose: Pydantic runs `before` validators in reverse
        definition order, so this runs before the validators that read `tools`.
        """
        if not isinstance(data, dict):
            return data
        input_data = data.get("input")
        if not isinstance(input_data, list):
            return data

        remaining_input = []
        additional_tools = []
        for item in input_data:
            if not (isinstance(item, dict) and item.get("type") == "additional_tools"):
                remaining_input.append(item)
                continue
            item_tools = item.get("tools")
            if not isinstance(item_tools, list):
                raise VLLMValidationError(
                    "`additional_tools` input items must contain a `tools` list.",
                    parameter="input",
                )
            additional_tools.extend(item_tools)

        if len(remaining_input) == len(input_data):
            return data
        data["input"] = remaining_input
        tools = data.get("tools")
        # A non-list `tools` is left to field validation, which rejects it. The
        # items still leave `input`, so an openai SDK without the
        # `additional_tools` input type adds no errors of its own to that one.
        if isinstance(tools, list | None):
            data["tools"] = _merge_additional_tools(tools or [], additional_tools)
        return data

_grammar_from_parser = PrivateAttr(default=False) class-attribute instance-attribute

CAUTION: Should only be set by the parser's adjust_request.

_parser_structured_outputs = PrivateAttr(default=None) class-attribute instance-attribute

Parser-derived constraints that preserve the public request's text metadata.

_normalize_openresponses_input_item(item) staticmethod

Normalize input items to bridge OpenResponses schema and openai-python.

The OpenResponses specification treats several fields as optional (id, status on assistant/reasoning items; annotations on output_text content) that the openai-python SDK marks as required. Fill sensible defaults so payloads conforming to the OpenResponses spec pass SDK validation.

Source code in vllm/entrypoints/openai/responses/protocol.py
@staticmethod
def _normalize_openresponses_input_item(item: Any) -> Any:
    """Normalize input items to bridge OpenResponses schema and openai-python.

    The OpenResponses specification treats several fields as optional
    (`id`, `status` on assistant/reasoning items; `annotations`
    on output_text content) that the openai-python SDK marks as
    required.  Fill sensible defaults so payloads conforming to the
    OpenResponses spec pass SDK validation.
    """
    if not isinstance(item, dict):
        return item

    item_type = item.get("type", "message")
    should_fill = item_type == "reasoning" or (
        item_type == "message" and item.get("role") == "assistant"
    )
    if not should_fill:
        return item

    normalized_item = item.copy()
    # ``type`` is optional in the OpenResponses schema but load-bearing for
    # SDK validation: without it a filled-in assistant item matches
    # ``ItemReference`` in the input union and collapses to ``{"id": ...}``,
    # silently dropping role/content. Stamp back the type we keyed off.
    normalized_item["type"] = item_type
    if normalized_item.get("id") in (None, ""):
        prefix = "rs" if item_type == "reasoning" else "msg"
        normalized_item["id"] = f"{prefix}_{random_uuid()}"
    if normalized_item.get("status") in (None, ""):
        normalized_item["status"] = "completed"
    if item_type == "reasoning" and normalized_item.get("summary") is None:
        normalized_item["summary"] = []

    # OpenResponses schema treats ``annotations`` as optional for
    # output_text content, but the openai SDK requires it.
    if item_type == "message" and isinstance(normalized_item.get("content"), list):
        normalized_content = []
        for content_item in normalized_item["content"]:
            if (
                isinstance(content_item, dict)
                and content_item.get("type") == "output_text"
                and "annotations" not in content_item
            ):
                content_item = {**content_item, "annotations": []}
            normalized_content.append(content_item)
        normalized_item["content"] = normalized_content

    return normalized_item

extract_structured_outputs()

Normalize request constraints into StructuredOutputsParams.

Source code in vllm/entrypoints/openai/responses/protocol.py
def extract_structured_outputs(self) -> StructuredOutputsParams | None:
    """Normalize request constraints into `StructuredOutputsParams`."""
    if self._parser_structured_outputs is not None:
        return self._parser_structured_outputs
    if self.text is None or self.text.format is None:
        return self.structured_outputs

    if self.structured_outputs is not None:
        raise VLLMValidationError(
            "Cannot specify both structured_outputs and text.format",
            parameter="structured_outputs",
        )

    response_format = self.text.format
    if response_format.type == "json_object":
        return StructuredOutputsParams(json_object=True)
    if (
        response_format.type == "json_schema"
        and response_format.schema_ is not None
    ):
        return StructuredOutputsParams(
            json=response_format.schema_  # type: ignore[call-arg]
            # --follow-imports skip hides the class definition but also hides
            # multiple third party conflicts, so best of both evils
        )
    return None

hoist_additional_tools_items(data) classmethod

Move tools declared by additional_tools input items into tools.

Clients such as Codex declare tools through an input item ({"type": "additional_tools", "role": "developer", "tools": [...]}) rather than the top-level tools field. Everything downstream reads request.tools, so merge them there and drop the item from input.

Defined last on purpose: Pydantic runs before validators in reverse definition order, so this runs before the validators that read tools.

Source code in vllm/entrypoints/openai/responses/protocol.py
@model_validator(mode="before")
@classmethod
def hoist_additional_tools_items(cls, data):
    """Move tools declared by `additional_tools` input items into `tools`.

    Clients such as Codex declare tools through an input item
    (`{"type": "additional_tools", "role": "developer", "tools": [...]}`)
    rather than the top-level `tools` field. Everything downstream reads
    `request.tools`, so merge them there and drop the item from `input`.

    Defined last on purpose: Pydantic runs `before` validators in reverse
    definition order, so this runs before the validators that read `tools`.
    """
    if not isinstance(data, dict):
        return data
    input_data = data.get("input")
    if not isinstance(input_data, list):
        return data

    remaining_input = []
    additional_tools = []
    for item in input_data:
        if not (isinstance(item, dict) and item.get("type") == "additional_tools"):
            remaining_input.append(item)
            continue
        item_tools = item.get("tools")
        if not isinstance(item_tools, list):
            raise VLLMValidationError(
                "`additional_tools` input items must contain a `tools` list.",
                parameter="input",
            )
        additional_tools.extend(item_tools)

    if len(remaining_input) == len(input_data):
        return data
    data["input"] = remaining_input
    tools = data.get("tools")
    # A non-list `tools` is left to field validation, which rejects it. The
    # items still leave `input`, so an openai SDK without the
    # `additional_tools` input type adds no errors of its own to that one.
    if isinstance(tools, list | None):
        data["tools"] = _merge_additional_tools(tools or [], additional_tools)
    return data

input_item_parsing(data) classmethod

Parse input items that are missing required fields or that Pydantic cannot disambiguate in a Union of TypedDict / BaseModel types.

Specifically handles: - function_call -> ResponseFunctionToolCall - reasoning -> ResponseReasoningItem (auto-generates id) - message(role=assistant) -> ResponseOutputMessage (auto-generates id/status and annotations)

Invalid structures are left for Pydantic to reject.

Source code in vllm/entrypoints/openai/responses/protocol.py
@model_validator(mode="before")
@classmethod
def input_item_parsing(cls, data):
    """Parse input items that are missing required fields or that Pydantic
    cannot disambiguate in a Union of TypedDict / BaseModel types.

    Specifically handles:
    - function_call -> ResponseFunctionToolCall
    - reasoning     -> ResponseReasoningItem (auto-generates id)
    - message(role=assistant) -> ResponseOutputMessage (auto-generates
      id/status and annotations)

    Invalid structures are left for Pydantic to reject.
    """
    if not isinstance(data, dict):
        return data
    input_data = data.get("input")

    # Early return for None, strings, or bytes
    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:
        normalized_item = cls._normalize_openresponses_input_item(item)

        if not isinstance(normalized_item, dict):
            processed_input.append(normalized_item)
            continue

        item_type = normalized_item.get("type")

        if item_type == "function_call":
            try:
                processed_input.append(ResponseFunctionToolCall(**normalized_item))
            except ValidationError:
                logger.debug(
                    "Failed to parse function_call to ResponseFunctionToolCall, "
                    "leaving for Pydantic validation"
                )
                processed_input.append(normalized_item)

        elif item_type == "reasoning":
            try:
                processed_input.append(ResponseReasoningItem(**normalized_item))
            except ValidationError:
                logger.debug(
                    "Failed to parse reasoning to ResponseReasoningItem, "
                    "leaving for Pydantic validation"
                )
                processed_input.append(normalized_item)

        elif item_type == "message" and normalized_item.get("role") == "assistant":
            if not isinstance(normalized_item.get("content"), list):
                # String content is a valid EasyInputMessageParam,
                # do not coerce it to ResponseOutputMessage
                processed_input.append(item)
                continue

            try:
                processed_input.append(ResponseOutputMessage(**normalized_item))
            except ValidationError:
                logger.debug(
                    "Failed to parse assistant message to ResponseOutputMessage, "
                    "leaving for Pydantic validation"
                )
                processed_input.append(item)

        else:
            processed_input.append(normalized_item)

    data["input"] = processed_input
    return data

is_include_output_logprobs()

Check if the request includes output logprobs.

Source code in vllm/entrypoints/openai/responses/protocol.py
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
    )

_default_input_image_details(value)

Set the API default for input images before SDK type validation.

Source code in vllm/entrypoints/openai/responses/protocol.py
def _default_input_image_details(value: Any) -> Any:
    """Set the API default for input images before SDK type validation."""
    if not isinstance(value, dict):
        return value

    content = value.get("content")
    if not isinstance(content, list):
        return value

    new_content = []
    changed = False
    for part in content:
        new_part = part
        if (
            isinstance(part, dict)
            and part.get("type") == "input_image"
            and "detail" not in part
        ):
            new_part = {**part, "detail": "auto"}
            changed = True
        new_content.append(new_part)

    return {**value, "content": new_content} if changed else value

_merge_additional_tools(tools, added)

Append added to tools, keeping one definition per tool.

Named tools are keyed by (type, namespace, name). A repeated key replaces the earlier definition in place, so the latest one wins (a client resending its history carries every redefinition), and a namespace that is already present is updated and gains only its new tools.

Source code in vllm/entrypoints/openai/responses/protocol.py
def _merge_additional_tools(tools: list[Any], added: list[Any]) -> list[Any]:
    """Append `added` to `tools`, keeping one definition per tool.

    Named tools are keyed by (type, namespace, name). A repeated key replaces
    the earlier definition in place, so the latest one wins (a client resending
    its history carries every redefinition), and a namespace that is already
    present is updated and gains only its new tools.
    """

    def is_namespace(tool: Any) -> bool:
        return (
            isinstance(tool, dict)
            and tool.get("type") == "namespace"
            and isinstance(tool.get("name"), str)
            and isinstance(tool.get("tools"), list)
        )

    def key(tool: Any, namespace: str | None = None) -> tuple | None:
        if isinstance(tool, dict) and isinstance(tool.get("name"), str):
            return (tool.get("type"), namespace, tool["name"])
        return None

    # Namespaces get their own tools list, so updating one never mutates input.
    merged = [{**t, "tools": list(t["tools"])} if is_namespace(t) else t for t in tools]
    namespaces: dict[str, int] = {}
    # Where each named tool lives: its index, or its namespace's index and its
    # index within that namespace.
    top_level: dict[tuple, int] = {}
    namespaced: dict[tuple, tuple[int, int]] = {}
    for index, tool in enumerate(merged):
        if is_namespace(tool):
            namespaces.setdefault(tool["name"], index)
            for position, namespaced_tool in enumerate(tool["tools"]):
                if (k := key(namespaced_tool, tool["name"])) is not None:
                    namespaced.setdefault(k, (index, position))
        elif (k := key(tool)) is not None:
            top_level.setdefault(k, index)

    for tool in added:
        if not is_namespace(tool):
            k = key(tool)
            if k in top_level:
                merged[top_level[k]] = tool
            else:
                if k is not None:
                    top_level[k] = len(merged)
                merged.append(tool)
            continue
        name = tool["name"]
        if name in namespaces:
            index = namespaces[name]
            merged[index] = {**tool, "tools": merged[index]["tools"]}
        else:
            index = namespaces[name] = len(merged)
            merged.append({**tool, "tools": []})
        for namespaced_tool in tool["tools"]:
            k = key(namespaced_tool, name)
            if k in namespaced:
                owner, slot = namespaced[k]
                merged[owner]["tools"][slot] = namespaced_tool
            else:
                if k is not None:
                    namespaced[k] = (index, len(merged[index]["tools"]))
                merged[index]["tools"].append(namespaced_tool)
    return merged

_resolve_named_tool_choice(tool_name, tools)

Resolve a named tool choice to the flat <namespace>__<name> form.

Source code in vllm/entrypoints/openai/responses/protocol.py
def _resolve_named_tool_choice(tool_name: str, tools: list[Any]) -> str:
    """Resolve a named tool choice to the flat `<namespace>__<name>` form."""
    from vllm.tool_parsers.utils import flat_namespace_tool_name

    exact_names: set[str] = set()
    local_names: dict[str, list[str]] = {}
    for tool in tools:
        if _tool_field(tool, "type") == "namespace":
            namespace = _tool_field(tool, "name")
            namespaced_tools = _tool_field(tool, "tools")
            if not isinstance(namespaced_tools, list) or not isinstance(namespace, str):
                return tool_name
            for namespaced_tool in namespaced_tools:
                local_name = _tool_field(namespaced_tool, "name")
                if not isinstance(local_name, str):
                    continue
                flat_name = flat_namespace_tool_name(namespace, local_name)
                exact_names.add(flat_name)
                local_names.setdefault(local_name, []).append(flat_name)
        else:
            name = _tool_field(tool, "name")
            if isinstance(name, str):
                exact_names.add(name)
    if tool_name in exact_names:
        return tool_name
    candidates = local_names.get(tool_name, [])
    if len(candidates) == 1:
        return candidates[0]
    if len(candidates) > 1:
        raise VLLMValidationError(
            f"Tool choice '{tool_name}' is ambiguous: it is defined in more "
            f"than one namespace ({', '.join(candidates)}). Select it by its "
            "full '<namespace>__<name>' name.",
            parameter="tool_choice",
        )
    raise VLLMValidationError(
        "Tool choice 'function' not found in 'tools' parameter.",
        parameter="tool_choice",
    )

serialize_message(msg)

Serializes a single message.

Source code in vllm/entrypoints/openai/responses/protocol.py
def serialize_message(msg):
    """Serializes a single message."""
    if isinstance(msg, dict):
        return msg
    elif hasattr(msg, "to_dict"):
        return msg.to_dict()
    else:
        # fallback to pydantic dump
        return msg.model_dump(mode="json", by_alias=True)

serialize_messages(msgs)

Serializes multiple messages.

Source code in vllm/entrypoints/openai/responses/protocol.py
def serialize_messages(msgs):
    """Serializes multiple messages."""
    return [serialize_message(msg) for msg in msgs] if msgs else None