Skip to content

guidellm.backends.openai

AudioRequestHandler

Bases: ChatCompletionsRequestHandler

Request handler for audio transcription and translation endpoints.

Processes responses from audio processing APIs that convert speech to text, handling both transcription and translation services. Manages audio-specific usage metrics including audio tokens and processing duration.

Example: :: handler = AudioResponseHandler() response = handler.compile_non_streaming(request, api_response)

Source code in src/guidellm/backends/openai/request_handlers.py
@OpenAIRequestHandlerFactory.register(
    ["/v1/audio/transcriptions", "/v1/audio/translations"]
)
class AudioRequestHandler(ChatCompletionsRequestHandler):
    """
    Request handler for audio transcription and translation endpoints.

    Processes responses from audio processing APIs that convert speech to text,
    handling both transcription and translation services. Manages audio-specific
    usage metrics including audio tokens and processing duration.

    Example:
    ::
        handler = AudioResponseHandler()
        response = handler.compile_non_streaming(request, api_response)
    """

    def __init__(self):
        """
        Initialize the audio response handler.

        Sets up internal state for accumulating streaming response data including
        audio buffers, text chunks, and usage metrics.
        """
        super().__init__()
        self.streaming_buffer: bytearray = bytearray()

    def format(
        self,
        data: GenerationRequest,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
        **kwargs,
    ) -> GenerationRequestArguments:  # noqa: C901
        """
        Format the audio transcription generation request into the
        appropriate structure.

        :param data: The generation request to format
        :param **kwargs: Additional keyword arguments for request formatting
        :return: The formatted request arguments
        """
        if history:
            raise ValueError("AudioRequestHandler does not support multiturn.")

        arguments = GenerationRequestArguments(files={})
        arguments.body = {}

        # Add model
        if kwargs.get("model") is not None:
            arguments.body["model"] = kwargs["model"]

        # Configure streaming
        if kwargs.get("stream"):
            arguments.stream = True
            arguments.body["stream"] = True
            # NOTE: File upload endpoints use flattened stream options
            arguments.body["stream_include_usage"] = True
            arguments.body["stream_continuous_usage_stats"] = True

        # Apply extra arguments
        if kwargs.get("extras"):
            arguments.model_combine(kwargs["extras"])

        # Build audio input
        audio_columns = data.columns.get("audio_column", [])
        if len(audio_columns) != 1:
            raise ValueError(
                f"GenerativeAudioTranscriptionRequestFormatter expects exactly "
                f"one audio column, but got {len(audio_columns)}."
            )

        arguments.files = {
            "file": (
                audio_columns[0].get("file_name", "audio_input"),
                audio_columns[0].get("audio"),
                audio_columns[0].get("mimetype"),
            )
        }

        return arguments

    def extract_metrics(
        self, usage: dict[str, int | dict[str, int]] | None, text: str | None
    ) -> tuple[UsageMetrics, UsageMetrics]:
        """
        Extract input and output usage metrics from audio API response usage data.

        Handles audio-specific metrics including processing duration and audio tokens
        in addition to standard text token counts.

        :param usage: Usage data dictionary from audio API response
        :param text: Generated text for calculating word and character counts.
            None means text is not applicable (metrics will be None);
            empty string means text was applicable but empty (metrics will be 0).
        :return: Tuple of input_metrics and output_metrics as UsageMetrics objects
        """
        if text is None:
            # text not applicable (e.g. tool-call-only) — exclude from aggregation
            text_words = None
            text_chars = None
        else:
            text_words = len(text.split())
            text_chars = len(text)

        if not usage:
            return UsageMetrics(), UsageMetrics(
                text_words=text_words,
                text_characters=text_chars,
            )

        usage_metrics: dict[str, int] = cast("dict[str, int]", usage)

        return UsageMetrics(
            audio_tokens=(usage_metrics.get("prompt_tokens") or 0),
        ), UsageMetrics(
            text_tokens=(usage_metrics.get("completion_tokens") or 0),
            text_words=text_words,
            text_characters=text_chars,
        )

__init__()

Initialize the audio response handler.

Sets up internal state for accumulating streaming response data including audio buffers, text chunks, and usage metrics.

Source code in src/guidellm/backends/openai/request_handlers.py
def __init__(self):
    """
    Initialize the audio response handler.

    Sets up internal state for accumulating streaming response data including
    audio buffers, text chunks, and usage metrics.
    """
    super().__init__()
    self.streaming_buffer: bytearray = bytearray()

extract_metrics(usage, text)

Extract input and output usage metrics from audio API response usage data.

Handles audio-specific metrics including processing duration and audio tokens in addition to standard text token counts.

Parameters:

Name Type Description Default
usage dict[str, int | dict[str, int]] | None

Usage data dictionary from audio API response

required
text str | None

Generated text for calculating word and character counts. None means text is not applicable (metrics will be None); empty string means text was applicable but empty (metrics will be 0).

required

Returns:

Type Description
tuple[UsageMetrics, UsageMetrics]

Tuple of input_metrics and output_metrics as UsageMetrics objects

Source code in src/guidellm/backends/openai/request_handlers.py
def extract_metrics(
    self, usage: dict[str, int | dict[str, int]] | None, text: str | None
) -> tuple[UsageMetrics, UsageMetrics]:
    """
    Extract input and output usage metrics from audio API response usage data.

    Handles audio-specific metrics including processing duration and audio tokens
    in addition to standard text token counts.

    :param usage: Usage data dictionary from audio API response
    :param text: Generated text for calculating word and character counts.
        None means text is not applicable (metrics will be None);
        empty string means text was applicable but empty (metrics will be 0).
    :return: Tuple of input_metrics and output_metrics as UsageMetrics objects
    """
    if text is None:
        # text not applicable (e.g. tool-call-only) — exclude from aggregation
        text_words = None
        text_chars = None
    else:
        text_words = len(text.split())
        text_chars = len(text)

    if not usage:
        return UsageMetrics(), UsageMetrics(
            text_words=text_words,
            text_characters=text_chars,
        )

    usage_metrics: dict[str, int] = cast("dict[str, int]", usage)

    return UsageMetrics(
        audio_tokens=(usage_metrics.get("prompt_tokens") or 0),
    ), UsageMetrics(
        text_tokens=(usage_metrics.get("completion_tokens") or 0),
        text_words=text_words,
        text_characters=text_chars,
    )

format(data, history=None, **kwargs)

Format the audio transcription generation request into the appropriate structure.

Parameters:

Name Type Description Default
data GenerationRequest

The generation request to format

required
**kwargs

Additional keyword arguments for request formatting

{}

Returns:

Type Description
GenerationRequestArguments

The formatted request arguments

Source code in src/guidellm/backends/openai/request_handlers.py
def format(
    self,
    data: GenerationRequest,
    history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
    **kwargs,
) -> GenerationRequestArguments:  # noqa: C901
    """
    Format the audio transcription generation request into the
    appropriate structure.

    :param data: The generation request to format
    :param **kwargs: Additional keyword arguments for request formatting
    :return: The formatted request arguments
    """
    if history:
        raise ValueError("AudioRequestHandler does not support multiturn.")

    arguments = GenerationRequestArguments(files={})
    arguments.body = {}

    # Add model
    if kwargs.get("model") is not None:
        arguments.body["model"] = kwargs["model"]

    # Configure streaming
    if kwargs.get("stream"):
        arguments.stream = True
        arguments.body["stream"] = True
        # NOTE: File upload endpoints use flattened stream options
        arguments.body["stream_include_usage"] = True
        arguments.body["stream_continuous_usage_stats"] = True

    # Apply extra arguments
    if kwargs.get("extras"):
        arguments.model_combine(kwargs["extras"])

    # Build audio input
    audio_columns = data.columns.get("audio_column", [])
    if len(audio_columns) != 1:
        raise ValueError(
            f"GenerativeAudioTranscriptionRequestFormatter expects exactly "
            f"one audio column, but got {len(audio_columns)}."
        )

    arguments.files = {
        "file": (
            audio_columns[0].get("file_name", "audio_input"),
            audio_columns[0].get("audio"),
            audio_columns[0].get("mimetype"),
        )
    }

    return arguments

ChatCompletionsRequestHandler

Bases: TextCompletionsRequestHandler

Request handler for OpenAI-style chat completion endpoints.

Extends TextCompletionsResponseHandler to handle chat completion requests where generated text is nested within message objects in the choices array. Processes both streaming and non-streaming chat completion responses, including tool call responses where the model outputs tool_calls instead of text content.

Source code in src/guidellm/backends/openai/request_handlers.py
 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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
@OpenAIRequestHandlerFactory.register("/v1/chat/completions")
class ChatCompletionsRequestHandler(TextCompletionsRequestHandler):
    """
    Request handler for OpenAI-style chat completion endpoints.

    Extends TextCompletionsResponseHandler to handle chat completion requests where
    generated text is nested within message objects in the choices array. Processes
    both streaming and non-streaming chat completion responses, including tool call
    responses where the model outputs ``tool_calls`` instead of text content.
    """

    def __init__(self):
        super().__init__()
        # Full tool call payloads accumulated across streaming deltas,
        # keyed by the delta ``index`` field.  Needed for multi-turn tool
        # calling so the response carries the id/name/arguments of each call.
        self.streaming_tool_calls: dict[int, ToolCall] = {}
        self.streaming_reasoning_texts: list[str] = []
        self._last_iteration_had_content: bool = False

    @property
    def last_iteration_had_content(self) -> bool:
        """
        :return: True if the last chunk carried output (text/tool-call) tokens,
            not solely reasoning tokens.
        """
        return self._last_iteration_had_content

    @staticmethod
    def _ensure_tool_format(tool: dict[str, Any]) -> dict[str, Any]:
        """Normalise a single tool definition to Chat Completions format.

        Chat Completions expects
        ``{"type": "function", "function": {"name": ..., ...}}``.
        If the tool is already in that format it is returned as-is.  If it is in the
        flat Responses API format (top-level ``name``, no ``function`` key) the detail
        fields are wrapped into a nested ``function`` dict.

        :param tool: A single tool definition dict in either format.
        :return: The tool in Chat Completions format.
        """
        if "name" in tool and "function" not in tool:
            fn = {k: tool[k] for k in _FUNCTION_DETAIL_KEYS if k in tool}
            return {"type": tool.get("type", "function"), "function": fn}
        return tool

    def _format_prompts(
        self,
        column_data: list,
        column_type: str,
        content_extras: dict[str, Any] | None = None,
    ) -> list[dict[str, Any]]:
        """
        Helper method to format different types of data columns
        into the appropriate structure for chat messages.
        """
        formatted_data = []
        for item in column_data:
            if column_type == "text_column":
                content = {"type": "text", "text": item}
                if content_extras:
                    content.update(content_extras)
                formatted_data.append(content)
            elif column_type == "image_column":
                formatted_data.append(
                    {
                        "type": "image_url",
                        "image_url": {"url": item.get("image")},
                    }
                )
            elif column_type == "video_column":
                formatted_data.append(
                    {
                        "type": "video_url",
                        "video_url": {"url": item.get("video")},
                    }
                )
            elif column_type == "audio_column":
                formatted_data.append(
                    {
                        "type": "input_audio",
                        "input_audio": {
                            "data": base64.b64encode(item.get("audio", b"")).decode(
                                "utf-8"
                            ),
                            "format": item.get("format"),
                        },
                    }
                )
            else:
                raise ValueError(f"Unsupported column type: {column_type}")

        return formatted_data

    @staticmethod
    def _build_tool_response_messages(
        tool_calls: list[ToolCall],
        tool_response_columns: list[Any],
    ) -> list[dict[str, Any]]:
        """Build synthetic ``role: "tool"`` messages for each tool call.

        Uses per-request tool response content from ``tool_response_columns``
        when available, falling back to
        :attr:`settings.default_synthetic_tool_response`.

        :param tool_calls: The tool call objects from the prior assistant response.
        :param tool_response_columns: Per-tool-call response content from the
            dataset, which may be ``str`` or ``bytes`` (orjson).
        :return: List of tool-role message dicts ready to append to messages.
        """
        messages: list[dict[str, Any]] = []
        for idx, tc in enumerate(tool_calls):
            # The OpenAI spec allows the server to do multiple tool calls.
            # If the quantity of calls exceeds those in the dataset, inject the
            # default synthetic tool response.
            raw_content = (
                tool_response_columns[idx]
                if idx < len(tool_response_columns)
                else settings.default_synthetic_tool_response
            )
            # The project JSON utils can return bytes or string; ensure string.
            content = (
                raw_content.decode("utf-8")
                if isinstance(raw_content, bytes)
                else raw_content
            )
            messages.append(
                {
                    "role": "tool",
                    "tool_call_id": tc.id,
                    "content": content,
                }
            )
        return messages

    @staticmethod
    def _apply_tool_call_overrides(
        body: dict[str, Any],
        data: GenerationRequest,
    ) -> None:
        """Inject tool definitions and constrain the request body for tool calling.

        Handles three concerns:

        1. Deserializes and injects tool definitions from dataset columns.
        2. Sets ``tool_choice`` to ``"required"`` or ``"none"`` depending on
           whether the current turn expects a tool call.
        3. Removes body keys that are incompatible with tool calling
           (``ignore_eos``, ``stop``, and token-limit keys on tool-call turns).

        :param body: The mutable request body dict being built.
        :param data: The current generation request.
        """
        tools_column = data.columns.get("tools_column", [])
        if tools_column:
            tools_value = tools_column[0]
            # JSON-serialized tool definitions (e.g. from synthetic data
            # generators that store tools as strings for HuggingFace Features
            # compatibility). The project JSON utils can return bytes or str.
            if isinstance(tools_value, str | bytes):
                tools_value = json.loads(tools_value)
            if isinstance(tools_value, list):
                body["tools"] = [
                    ChatCompletionsRequestHandler._ensure_tool_format(t)
                    for t in tools_value
                ]
                body.setdefault("tool_choice", "required")

        if "tools" not in body:
            body.pop("tool_choice", None)
            return

        # Standard and injection turns should not produce tool calls even
        # when tool definitions are in the body (e.g. from extras).
        if data.turn_type in ("standard", "tool_response_injection"):
            body["tool_choice"] = "none"

        # Tool calling requires the model to stop naturally after producing
        # valid JSON; ignore_eos would force generation past that point and
        # break the server's constrained decoding grammar.
        # max_completion_tokens would truncate output mid-JSON and corrupt
        # the arguments sent in conversation history on follow-up turns.
        if data.turn_type == "client_tool_call":
            body.pop("ignore_eos", None)
            body.pop("stop", None)

    def _build_history_messages(
        self,
        history: HistoryT[GenerationRequest, GenerationResponse],
        **kwargs,
    ) -> list[dict[str, Any]]:
        """Build the messages array from completed conversation turns.

        :param history: Completed (request, response) pairs.
        :param kwargs: Forwarded config (``multiturn_reasoning``, etc.).
        :return: Flat list of message dicts ready to extend into the body.
        """
        messages: list[dict[str, Any]] = []
        for idx, (req, res) in enumerate(history):
            # Passes in the prior response so that past data can be included,
            # like for tool calling.
            prior_response = history[idx - 1][1] if idx > 0 else None
            messages.extend(
                self._build_turn_messages(req, res, prior_response, **kwargs)
            )
        return messages

    def _build_turn_messages(  # noqa: C901
        self,
        req: GenerationRequest,
        res: GenerationResponse | None,
        prior_response: GenerationResponse | None,
        **kwargs,
    ) -> list[dict[str, Any]]:
        """Build messages for a single history turn.

        Dispatches on ``req.turn_type``:

        * ``"client_tool_call"``: user content + assistant tool_calls (no tool
          response messages — those come from the following injection turn).
        * ``"tool_response_injection"``: tool-role messages built from
          ``prior_response.tool_calls`` IDs + this turn's
          ``tool_response_column``, then the assistant text response.
        * ``"standard"``: user content + assistant text response.

        :param req: The request for this history turn.
        :param res: The response the server gave for this turn.
        :param prior_response: The response from the immediately preceding
            history turn (used by injection turns for ``tool_call_id``s).
        :param kwargs: Forwarded config (``multiturn_reasoning``, etc.).
        :return: List of message dicts for this turn.
        """
        messages: list[dict[str, Any]] = []
        multiturn_reasoning = kwargs.get("multiturn_reasoning", False)

        if req.turn_type == "tool_response_injection":
            # Injection turn: tool-role messages then assistant text.
            if prior_response and prior_response.tool_calls:
                tool_response_columns = req.columns.get("tool_response_column", [])
                messages.extend(
                    self._build_tool_response_messages(
                        prior_response.tool_calls, tool_response_columns
                    )
                )
            if res is not None and res.text is not None:
                wrapped = _wrap_reasoning(res.reasoning_text, multiturn_reasoning)
                content = res.text
                if wrapped:
                    content = wrapped + content
                messages.append({"role": "assistant", "content": content})
        else:
            # Standard or tool_call turn: system + user content.
            prefix = " ".join(req.columns.get("prefix_column", []))
            if prefix:
                messages.append({"role": "system", "content": prefix})

            extras = kwargs.get("extras")
            content_extras = extras.content if extras is not None else None
            prompts = [
                self._format_prompts(
                    req.columns.get(col, []),
                    col,
                    content_extras,
                )
                for col in (
                    "text_column",
                    "image_column",
                    "video_column",
                    "audio_column",
                )
            ]
            user_content = list(roundrobin(*prompts))
            if user_content:
                messages.append({"role": "user", "content": user_content})

            # Assistant response for history replay.
            wrapped = _wrap_reasoning(
                res.reasoning_text if res else None, multiturn_reasoning
            )
            if res is not None:
                if res.tool_calls:
                    # Tool-call turn: assistant with tool_calls only.
                    # Tool response messages come from the injection turn.
                    assistant_content = res.text
                    if wrapped:
                        assistant_content = wrapped + (assistant_content or "")
                    messages.append(
                        {
                            "role": "assistant",
                            "content": assistant_content,
                            "tool_calls": [tc.model_dump() for tc in res.tool_calls],
                        }
                    )
                elif res.text is not None or wrapped:
                    content = res.text or ""
                    if wrapped:
                        content = wrapped + content
                    messages.append({"role": "assistant", "content": content})

        return messages

    def format(  # noqa: C901, PLR0912, PLR0915
        self,
        data: GenerationRequest,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
        **kwargs,
    ) -> GenerationRequestArguments:
        """
        Format the chat completion generation request into the appropriate structure.

        :param data: The generation request to format
        :param history: Prior (request, response) pairs in the conversation
        :param **kwargs: Additional keyword arguments for request formatting
        :return: The formatted request arguments
        """
        arguments = GenerationRequestArguments()
        arguments.body = {}  # The type checker works best with body assigned here

        # Add model
        if kwargs.get("model") is not None:
            arguments.body["model"] = kwargs["model"]

        # Configure streaming
        if kwargs.get("stream"):
            arguments.stream = True
            arguments.body["stream"] = True
            arguments.body["stream_options"] = {
                "include_usage": True,
                "continuous_usage_stats": True,
            }

        # Handle output tokens
        if data.output_metrics.text_tokens:
            arguments.body.update(
                {
                    "max_completion_tokens": data.output_metrics.text_tokens,
                    "stop": None,
                    "ignore_eos": True,
                }
            )
        elif kwargs.get("max_tokens") is not None:
            arguments.body["max_completion_tokens"] = kwargs["max_tokens"]

        # Apply extra arguments
        if kwargs.get("extras"):
            arguments.model_combine(kwargs["extras"])

        # Build messages from history
        arguments.body["messages"] = (
            self._build_history_messages(history, **kwargs) if history else []
        )

        # Build the current turn's messages
        if data.turn_type == "tool_response_injection":
            # Injection turn: send tool results back to the server.
            # tool_call_ids come from the last history entry's response.
            prior_response = history[-1][1] if history else None
            if prior_response and prior_response.tool_calls:
                tool_response_columns = data.columns.get("tool_response_column", [])
                arguments.body["messages"].extend(
                    self._build_tool_response_messages(
                        prior_response.tool_calls, tool_response_columns
                    )
                )
        else:
            # Standard or tool_call turn: system prompt + user content.
            prefix = " ".join(data.columns.get("prefix_column", []))
            if prefix:
                arguments.body["messages"].append({"role": "system", "content": prefix})

            extras = kwargs.get("extras")
            content_extras = extras.content if extras is not None else None
            prompts = [
                self._format_prompts(
                    data.columns.get(col, []),
                    col,
                    content_extras,
                )
                for col in (
                    "text_column",
                    "image_column",
                    "video_column",
                    "audio_column",
                )
            ]
            user_content = list(roundrobin(*prompts))
            if user_content:
                arguments.body["messages"].append(
                    {"role": "user", "content": user_content}
                )

        # Inject tool definitions and apply tool-call-specific overrides.
        self._apply_tool_call_overrides(arguments.body, data)

        return arguments

    def compile_non_streaming(
        self,
        request: GenerationRequest,
        arguments: GenerationRequestArguments,
        response: dict,
    ) -> GenerationResponse:
        """
        Process a complete chat completion response.

        Extracts content from the message object within choices, handling the nested
        structure specific to chat completion endpoints.

        :param request: Original generation request
        :param arguments: The request arguments that were sent
        :param response: Complete API response containing choices and usage data
        :return: Standardized GenerationResponse with extracted content and metrics
        """
        choices, usage = self.extract_choices_and_usage(response)
        choice: dict[str, dict] = choices[0] if choices else {}
        message = choice.get("message", {})
        text = message.get("content")
        reasoning_text = (
            message.get("reasoning") or message.get("reasoning_content") or None
        )
        raw_tool_calls = message.get("tool_calls")
        if text is None and not raw_tool_calls:
            text = ""  # Edge case: null content and no tools
        input_metrics, output_metrics = self.extract_metrics(usage, text)

        tool_calls: list[ToolCall] | None = None
        if raw_tool_calls:
            tool_calls = [ToolCall.model_validate(tc) for tc in raw_tool_calls]
        _apply_tool_call_metrics(
            output_metrics, len(tool_calls) if tool_calls else 0, text
        )

        return GenerationResponse(
            request_id=request.request_id,
            request_args=arguments.model_dump_json(),
            response_id=response.get("id"),  # use vLLM ID if available
            text=text,
            reasoning_text=reasoning_text,
            tool_calls=tool_calls,
            input_metrics=input_metrics,
            output_metrics=output_metrics,
        )

    def add_streaming_line(self, line: str) -> int | None:
        """
        Process a single line from a chat completion streaming response.

        Handles the chat completion specific delta structure where content is nested
        within delta objects in the streaming response chunks. Also accumulates
        ``tool_calls`` deltas when the model streams function call output.

        :param line: Raw SSE line from the streaming response
        :return: 1 if content was extracted, 0 if line ignored, None if done
        """
        if not (data := self.extract_line_data(line)):
            return None if data is None else 0

        if "id" in data and self.streaming_response_id is None:
            self.streaming_response_id = data["id"]

        updated = False
        # Tracks whether this iteration produced user-visible content (not
        # reasoning-only). Used by the HTTP layer to set TTFOT timing.
        had_content = False
        choices, usage = self.extract_choices_and_usage(data)
        choice: dict[str, dict] = choices[0] if choices else {}
        delta = choice.get("delta", {}) if choices else {}

        # Reasoning tokens trigger TTFT (updated=True) but are not
        # considered "content" for the TTFOT metric.
        if reasoning := (delta.get("reasoning") or delta.get("reasoning_content")):
            self.streaming_reasoning_texts.append(reasoning)
            updated = True
        if content := delta.get("content"):
            self.streaming_texts.append(content)
            updated = True
            had_content = True

        # Accumulate streamed tool_calls deltas.  Each tool call may be split
        # across multiple chunks; we reassemble by ``index``.
        # ``tool_calls`` could be either missing or ``null`` in the delta
        # (some OpenAI-compatible servers emit this), handle both cases
        for tc_delta in delta.get("tool_calls") or []:
            self._accumulate_tool_call_delta(tc_delta)
            updated = True
            had_content = True

        if usage:
            self.streaming_usage = usage

        # Only update the flag when we processed a token-bearing iteration;
        # non-updating lines should not reset the flag.
        if updated:
            self._last_iteration_had_content = had_content
        return 1 if updated else 0

    def _accumulate_tool_call_delta(self, tc_delta: dict[str, Any]) -> None:
        """Merge a single streaming tool_call delta into accumulated state.

        Each tool call is split across multiple SSE chunks.  This method
        creates or updates the :class:`ToolCall` entry keyed by the
        delta's ``index`` field.

        :param tc_delta: A single element from the ``tool_calls`` array in a
            streaming chat completion delta.
        """
        idx = tc_delta["index"]

        if idx not in self.streaming_tool_calls:
            self.streaming_tool_calls[idx] = ToolCall(
                id=tc_delta.get("id", ""),
                type=tc_delta.get("type", "function"),
            )

        tc = self.streaming_tool_calls[idx]
        fn_delta = tc_delta.get("function", {})

        if fn_id := tc_delta.get("id"):
            tc.id = fn_id
        if fn_name := fn_delta.get("name"):
            tc.function.name += fn_name
        if fn_args := fn_delta.get("arguments"):
            tc.function.arguments += fn_args

    def compile_streaming(
        self, request: GenerationRequest, arguments: GenerationRequestArguments
    ) -> GenerationResponse:
        """
        Compile accumulated streaming chat completion content into a final response.

        :param request: Original generation request
        :return: Standardized GenerationResponse with concatenated content and metrics
        """
        return _compile_streaming_response(
            request,
            arguments,
            self.streaming_texts,
            self.streaming_tool_calls,
            self.streaming_usage,
            self.streaming_response_id,
            self.extract_metrics,
            streaming_reasoning_texts=self.streaming_reasoning_texts,
        )

last_iteration_had_content property

Returns:

Type Description
bool

True if the last chunk carried output (text/tool-call) tokens, not solely reasoning tokens.

add_streaming_line(line)

Process a single line from a chat completion streaming response.

Handles the chat completion specific delta structure where content is nested within delta objects in the streaming response chunks. Also accumulates tool_calls deltas when the model streams function call output.

Parameters:

Name Type Description Default
line str

Raw SSE line from the streaming response

required

Returns:

Type Description
int | None

1 if content was extracted, 0 if line ignored, None if done

Source code in src/guidellm/backends/openai/request_handlers.py
def add_streaming_line(self, line: str) -> int | None:
    """
    Process a single line from a chat completion streaming response.

    Handles the chat completion specific delta structure where content is nested
    within delta objects in the streaming response chunks. Also accumulates
    ``tool_calls`` deltas when the model streams function call output.

    :param line: Raw SSE line from the streaming response
    :return: 1 if content was extracted, 0 if line ignored, None if done
    """
    if not (data := self.extract_line_data(line)):
        return None if data is None else 0

    if "id" in data and self.streaming_response_id is None:
        self.streaming_response_id = data["id"]

    updated = False
    # Tracks whether this iteration produced user-visible content (not
    # reasoning-only). Used by the HTTP layer to set TTFOT timing.
    had_content = False
    choices, usage = self.extract_choices_and_usage(data)
    choice: dict[str, dict] = choices[0] if choices else {}
    delta = choice.get("delta", {}) if choices else {}

    # Reasoning tokens trigger TTFT (updated=True) but are not
    # considered "content" for the TTFOT metric.
    if reasoning := (delta.get("reasoning") or delta.get("reasoning_content")):
        self.streaming_reasoning_texts.append(reasoning)
        updated = True
    if content := delta.get("content"):
        self.streaming_texts.append(content)
        updated = True
        had_content = True

    # Accumulate streamed tool_calls deltas.  Each tool call may be split
    # across multiple chunks; we reassemble by ``index``.
    # ``tool_calls`` could be either missing or ``null`` in the delta
    # (some OpenAI-compatible servers emit this), handle both cases
    for tc_delta in delta.get("tool_calls") or []:
        self._accumulate_tool_call_delta(tc_delta)
        updated = True
        had_content = True

    if usage:
        self.streaming_usage = usage

    # Only update the flag when we processed a token-bearing iteration;
    # non-updating lines should not reset the flag.
    if updated:
        self._last_iteration_had_content = had_content
    return 1 if updated else 0

compile_non_streaming(request, arguments, response)

Process a complete chat completion response.

Extracts content from the message object within choices, handling the nested structure specific to chat completion endpoints.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required
arguments GenerationRequestArguments

The request arguments that were sent

required
response dict

Complete API response containing choices and usage data

required

Returns:

Type Description
GenerationResponse

Standardized GenerationResponse with extracted content and metrics

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_non_streaming(
    self,
    request: GenerationRequest,
    arguments: GenerationRequestArguments,
    response: dict,
) -> GenerationResponse:
    """
    Process a complete chat completion response.

    Extracts content from the message object within choices, handling the nested
    structure specific to chat completion endpoints.

    :param request: Original generation request
    :param arguments: The request arguments that were sent
    :param response: Complete API response containing choices and usage data
    :return: Standardized GenerationResponse with extracted content and metrics
    """
    choices, usage = self.extract_choices_and_usage(response)
    choice: dict[str, dict] = choices[0] if choices else {}
    message = choice.get("message", {})
    text = message.get("content")
    reasoning_text = (
        message.get("reasoning") or message.get("reasoning_content") or None
    )
    raw_tool_calls = message.get("tool_calls")
    if text is None and not raw_tool_calls:
        text = ""  # Edge case: null content and no tools
    input_metrics, output_metrics = self.extract_metrics(usage, text)

    tool_calls: list[ToolCall] | None = None
    if raw_tool_calls:
        tool_calls = [ToolCall.model_validate(tc) for tc in raw_tool_calls]
    _apply_tool_call_metrics(
        output_metrics, len(tool_calls) if tool_calls else 0, text
    )

    return GenerationResponse(
        request_id=request.request_id,
        request_args=arguments.model_dump_json(),
        response_id=response.get("id"),  # use vLLM ID if available
        text=text,
        reasoning_text=reasoning_text,
        tool_calls=tool_calls,
        input_metrics=input_metrics,
        output_metrics=output_metrics,
    )

compile_streaming(request, arguments)

Compile accumulated streaming chat completion content into a final response.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required

Returns:

Type Description
GenerationResponse

Standardized GenerationResponse with concatenated content and metrics

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_streaming(
    self, request: GenerationRequest, arguments: GenerationRequestArguments
) -> GenerationResponse:
    """
    Compile accumulated streaming chat completion content into a final response.

    :param request: Original generation request
    :return: Standardized GenerationResponse with concatenated content and metrics
    """
    return _compile_streaming_response(
        request,
        arguments,
        self.streaming_texts,
        self.streaming_tool_calls,
        self.streaming_usage,
        self.streaming_response_id,
        self.extract_metrics,
        streaming_reasoning_texts=self.streaming_reasoning_texts,
    )

format(data, history=None, **kwargs)

Format the chat completion generation request into the appropriate structure.

Parameters:

Name Type Description Default
data GenerationRequest

The generation request to format

required
history HistoryT[GenerationRequest, GenerationResponse] | None

Prior (request, response) pairs in the conversation

None
**kwargs

Additional keyword arguments for request formatting

{}

Returns:

Type Description
GenerationRequestArguments

The formatted request arguments

Source code in src/guidellm/backends/openai/request_handlers.py
def format(  # noqa: C901, PLR0912, PLR0915
    self,
    data: GenerationRequest,
    history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
    **kwargs,
) -> GenerationRequestArguments:
    """
    Format the chat completion generation request into the appropriate structure.

    :param data: The generation request to format
    :param history: Prior (request, response) pairs in the conversation
    :param **kwargs: Additional keyword arguments for request formatting
    :return: The formatted request arguments
    """
    arguments = GenerationRequestArguments()
    arguments.body = {}  # The type checker works best with body assigned here

    # Add model
    if kwargs.get("model") is not None:
        arguments.body["model"] = kwargs["model"]

    # Configure streaming
    if kwargs.get("stream"):
        arguments.stream = True
        arguments.body["stream"] = True
        arguments.body["stream_options"] = {
            "include_usage": True,
            "continuous_usage_stats": True,
        }

    # Handle output tokens
    if data.output_metrics.text_tokens:
        arguments.body.update(
            {
                "max_completion_tokens": data.output_metrics.text_tokens,
                "stop": None,
                "ignore_eos": True,
            }
        )
    elif kwargs.get("max_tokens") is not None:
        arguments.body["max_completion_tokens"] = kwargs["max_tokens"]

    # Apply extra arguments
    if kwargs.get("extras"):
        arguments.model_combine(kwargs["extras"])

    # Build messages from history
    arguments.body["messages"] = (
        self._build_history_messages(history, **kwargs) if history else []
    )

    # Build the current turn's messages
    if data.turn_type == "tool_response_injection":
        # Injection turn: send tool results back to the server.
        # tool_call_ids come from the last history entry's response.
        prior_response = history[-1][1] if history else None
        if prior_response and prior_response.tool_calls:
            tool_response_columns = data.columns.get("tool_response_column", [])
            arguments.body["messages"].extend(
                self._build_tool_response_messages(
                    prior_response.tool_calls, tool_response_columns
                )
            )
    else:
        # Standard or tool_call turn: system prompt + user content.
        prefix = " ".join(data.columns.get("prefix_column", []))
        if prefix:
            arguments.body["messages"].append({"role": "system", "content": prefix})

        extras = kwargs.get("extras")
        content_extras = extras.content if extras is not None else None
        prompts = [
            self._format_prompts(
                data.columns.get(col, []),
                col,
                content_extras,
            )
            for col in (
                "text_column",
                "image_column",
                "video_column",
                "audio_column",
            )
        ]
        user_content = list(roundrobin(*prompts))
        if user_content:
            arguments.body["messages"].append(
                {"role": "user", "content": user_content}
            )

    # Inject tool definitions and apply tool-call-specific overrides.
    self._apply_tool_call_overrides(arguments.body, data)

    return arguments

OpenAIHTTPBackend

Bases: Backend

HTTP backend for OpenAI-compatible servers.

Supports OpenAI API, vLLM servers, and other compatible endpoints with text/chat completions, streaming, authentication, and multimodal inputs. Handles request formatting, response parsing, error handling, and token usage tracking with flexible parameter customization.

Example: :: backend_args = OpenAIHTTPBackendArgs( target="http://localhost:8000", model="gpt-3.5-turbo", api_key="your-api-key", ) backend = OpenAIHTTPBackend(backend_args)

await backend.process_startup()
async for response, request_info in backend.resolve(request, info):
    process_response(response)
await backend.process_shutdown()
Source code in src/guidellm/backends/openai/http.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
@Backend.register("openai_http")
class OpenAIHTTPBackend(Backend):
    """
    HTTP backend for OpenAI-compatible servers.

    Supports OpenAI API, vLLM servers, and other compatible endpoints with
    text/chat completions, streaming, authentication, and multimodal inputs.
    Handles request formatting, response parsing, error handling, and token
    usage tracking with flexible parameter customization.

    Example:
    ::
        backend_args = OpenAIHTTPBackendArgs(
            target="http://localhost:8000",
            model="gpt-3.5-turbo",
            api_key="your-api-key",
        )
        backend = OpenAIHTTPBackend(backend_args)

        await backend.process_startup()
        async for response, request_info in backend.resolve(request, info):
            process_response(response)
        await backend.process_shutdown()
    """

    _args: OpenAIHTTPBackendArgs

    def __init__(
        self,
        arguments: OpenAIHTTPBackendArgs,
    ):
        """
        Initialize OpenAI HTTP backend with server configuration.
        """
        super().__init__(arguments)

        # Runtime state
        self._in_process = False
        self._async_client: httpx.AsyncClient | None = None

    async def process_startup(self):
        """
        Initialize HTTP client and backend resources.

        :raises RuntimeError: If backend is already initialized
        :raises httpx.RequestError: If HTTP client cannot be created
        """
        if self._in_process:
            raise RuntimeError("Backend already started up for process.")

        self._async_client = httpx.AsyncClient(
            http2=self._args.http2,
            timeout=httpx.Timeout(
                FALLBACK_TIMEOUT,
                read=self._args.timeout,
                connect=self._args.timeout_connect,
            ),
            follow_redirects=self._args.follow_redirects,
            verify=self._args.verify,
            # Allow unlimited connections
            limits=httpx.Limits(
                max_connections=None,
                max_keepalive_connections=None,
                keepalive_expiry=5.0,  # default
            ),
        )
        self._in_process = True

    async def process_shutdown(self):
        """
        Clean up HTTP client and backend resources.

        :raises RuntimeError: If backend was not properly initialized
        :raises httpx.RequestError: If HTTP client cannot be closed
        """
        if not self._in_process:
            raise RuntimeError("Backend not started up for process.")

        await self._async_client.aclose()  # type: ignore [union-attr]
        self._async_client = None
        self._in_process = False

    async def validate(self):
        """
        Validate backend connectivity and configuration.

        :raises RuntimeError: If backend cannot connect or validate configuration
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")

        if not self._args.validate_backend:
            return

        try:
            validate_kwargs: dict[str, Any] = {
                "method": "GET",
                "url": f"{self._args.target}/{self._args.api_routes['/health']}",
            }
            existing_headers = validate_kwargs.get("headers")
            built_headers = self._build_headers(existing_headers)
            validate_kwargs["headers"] = built_headers
            response = await self._async_client.request(**validate_kwargs)
            response.raise_for_status()
        except Exception as exc:
            raise RuntimeError(
                "Backend validation request failed. Could not connect to the server "
                "or validate the backend configuration."
            ) from exc

    async def available_models(self) -> list[str]:
        """
        Get available models from the target server.

        :return: List of model identifiers
        :raises httpx.HTTPError: If models endpoint returns an error
        :raises RuntimeError: If backend is not initialized
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")

        target = f"{self._args.target}/{self._args.api_routes['/v1/models']}"
        response = await self._async_client.get(target, headers=self._build_headers())
        response.raise_for_status()

        return [item["id"] for item in response.json()["data"]]

    async def default_model(self) -> str:
        """
        Get the default model for this backend.

        :return: Model name or None if no model is available
        """
        if self._args.model or not self._in_process:
            return self._args.model

        models = await self.available_models()
        self._args.model = models[0] if models else ""
        return self._args.model

    async def resolve(  # type: ignore[override, misc]
        self,
        request: GenerationRequest,
        request_info: RequestInfo,
        history: list[tuple[GenerationRequest, GenerationResponse | None]]
        | None = None,
    ) -> AsyncIterator[tuple[GenerationResponse | None, RequestInfo]]:
        """
        Process generation request and yield progressive responses.

        Handles request formatting, timing tracking, API communication, and
        response parsing with streaming support.

        :param request: Generation request with content and parameters
        :param request_info: Request tracking info updated with timing metadata
        :param history: Conversation history (currently not supported)
        :raises NotImplementedError: If history is provided
        :raises RuntimeError: If backend is not initialized
        :raises ValueError: If request type is unsupported
        :yields: Tuples of (response, updated_request_info) as generation progresses
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")

        (
            request_handler,
            arguments,
            request_kwargs,
        ) = await self._prepare_resolve_request(request, history)

        if not arguments.stream:
            async for item in self._resolve_non_streaming(
                request, request_info, request_handler, arguments, request_kwargs
            ):
                yield item
            return

        async for item in self._resolve_streaming(
            request, request_info, request_handler, arguments, request_kwargs
        ):
            yield item

    async def _prepare_resolve_request(
        self,
        request: GenerationRequest,
        history: list[tuple[GenerationRequest, GenerationResponse | None]]
        | None = None,
    ) -> tuple[
        OpenAIRequestHandler,
        GenerationRequestArguments,
        dict[str, Any],
    ]:
        """
        Build the request handler, format arguments, and prepare HTTP kwargs.

        :param request: Generation request with content and parameters
        :param history: Optional conversation history for multi-turn requests
        :return: Tuple of (request_handler, formatted_arguments, http_kwargs)
        :raises ValueError: If request format is unsupported
        """
        if (
            request_path := self._args.api_routes.get(self._args.request_format)
        ) is None:
            raise ValueError(
                f"Unsupported request format '{self._args.request_format}'"
            )

        request_handler = OpenAIRequestHandlerFactory.create(
            self._args.request_format,
        )
        arguments: GenerationRequestArguments = request_handler.format(
            data=request,
            history=history,
            model=(await self.default_model()),
            stream=self._args.stream,
            extras=self._args.extras,
            max_tokens=self._args.max_tokens,
            server_history=self._args.server_history,
            multiturn_reasoning=self._args.multiturn_reasoning,
        )

        request_url = f"{self._args.target}/{request_path}"
        request_files = (
            {
                key: tuple(value) if isinstance(value, list) else value
                for key, value in arguments.files.items()
            }
            if arguments.files
            else None
        )
        # Omit `None` from output JSON
        deep_filter(arguments.body or {}, lambda _, v: v is not None)
        request_json = arguments.body if not request_files else None
        request_data = arguments.body if request_files else None

        request_kwargs: dict[str, Any] = {
            "url": request_url,
            "method": arguments.method or "POST",
            "params": arguments.params,
            "headers": self._build_headers(arguments.headers),
            "json": request_json,
            "data": request_data,
            "files": request_files,
        }

        return request_handler, arguments, request_kwargs

    async def _resolve_non_streaming(
        self,
        request: GenerationRequest,
        request_info: RequestInfo,
        request_handler: OpenAIRequestHandler,
        arguments: GenerationRequestArguments,
        request_kwargs: dict[str, Any],
    ) -> AsyncIterator[tuple[GenerationResponse | None, RequestInfo]]:
        """
        Handle a non-streaming generation request.

        :param request: The original generation request
        :param request_info: Request tracking info updated with timing metadata
        :param request_handler: Handler for compiling the response
        :param arguments: Formatted request arguments
        :param request_kwargs: Prepared HTTP request keyword arguments
        :yields: Single (response, request_info) tuple
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")

        request_info.timings.request_start = time.time()
        response = await self._async_client.request(**request_kwargs)
        request_info.timings.request_end = time.time()
        response.raise_for_status()
        data = response.json()
        gen_response = request_handler.compile_non_streaming(request, arguments, data)
        request_handler.post_validation(gen_response)
        yield gen_response, request_info
        self._check_tool_call_expectations(request, gen_response)

    async def _resolve_streaming(
        self,
        request: GenerationRequest,
        request_info: RequestInfo,
        request_handler: OpenAIRequestHandler,
        arguments: GenerationRequestArguments,
        request_kwargs: dict[str, Any],
    ) -> AsyncIterator[tuple[GenerationResponse | None, RequestInfo]]:
        """
        Handle a streaming generation request with progressive timing updates.

        :param request: The original generation request
        :param request_info: Request tracking info updated with timing metadata
        :param request_handler: Handler for processing stream lines and compiling
        :param arguments: Formatted request arguments
        :param request_kwargs: Prepared HTTP request keyword arguments
        :yields: Tuples of (response, request_info) as generation progresses
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")

        try:
            request_info.timings.request_start = time.time()

            async with self._async_client.stream(**request_kwargs) as stream:
                stream.raise_for_status()
                end_reached = False

                async for chunk in self._aiter_lines(stream):
                    stream.raise_for_status()
                    iter_time = time.time()

                    if request_info.timings.first_request_iteration is None:
                        request_info.timings.first_request_iteration = iter_time
                    request_info.timings.last_request_iteration = iter_time
                    request_info.timings.request_iterations += 1

                    iterations = request_handler.add_streaming_line(chunk)
                    if iterations is None or iterations <= 0 or end_reached:
                        end_reached = end_reached or iterations is None
                        if end_reached:
                            # Break eagerly once the handler signals completion
                            # (e.g. "data: [DONE]" or "response.completed").
                            # Using continue instead would hang on servers that
                            # keep the HTTP/2 stream open after the last event.
                            break
                        continue

                    if request_info.timings.first_token_iteration is None:
                        request_info.timings.first_token_iteration = iter_time
                        request_info.timings.token_iterations = 0
                        yield None, request_info

                    # TTFOT: record the first content (non-reasoning) token.
                    # For non-reasoning models this fires on the same iteration
                    # as first_token_iteration, making TTFOT == TTFT.
                    if (
                        request_info.timings.first_output_token_iteration is None
                        and request_handler.last_iteration_had_content
                    ):
                        request_info.timings.first_output_token_iteration = iter_time

                    request_info.timings.last_token_iteration = iter_time
                    request_info.timings.token_iterations += iterations

            request_info.timings.request_end = time.time()
            gen_response = request_handler.compile_streaming(request, arguments)
            request_handler.post_validation(gen_response)
            self._check_tool_call_expectations(request, gen_response)
            yield gen_response, request_info
        except asyncio.CancelledError as err:
            # Yield current result to store iterative results before propagating
            yield request_handler.compile_streaming(request, arguments), request_info
            raise err

    async def _aiter_lines(self, stream: httpx.Response) -> AsyncIterator[str]:
        """
        Asynchronously iterate over lines in an HTTP response stream.

        :param stream: HTTP response object with streaming content
        :yield: Lines of text from the response stream
        """
        async for line in stream.aiter_lines():
            if not line.strip():
                continue  # Skip blank lines
            yield line

    def _build_headers(
        self, existing_headers: dict[str, str] | None = None
    ) -> dict[str, str] | None:
        """
        Build headers dictionary with bearer token authentication.

        Merges the Authorization bearer token header (if api_key is set) with any
        existing headers. User-provided headers take precedence over the bearer token.

        :param existing_headers: Optional existing headers to merge with
        :return: Dictionary of headers with bearer token included if api_key is set
        """
        headers: dict[str, str] = {}

        # Add bearer token if api_key is set
        if self._args.api_key:
            token = self._args.api_key.get_secret_value()
            headers["Authorization"] = f"Bearer {token}"

        # Merge with existing headers (user headers take precedence)
        if existing_headers:
            headers = {**headers, **existing_headers}

        return headers or None

    def _check_tool_call_expectations(
        self,
        request: GenerationRequest,
        response: GenerationResponse,
    ) -> None:
        """Validate that a tool-call turn actually produced tool calls.

        Called before the final yield in ``resolve`` so that any raised
        exception prevents the normal yield and is instead handled by the
        ``except`` block (which yields the response once before propagating).
        When the request expected a tool call but the model didn't produce one,
        raises an exception according to ``tool_call_missing_behavior``:

        * ``ignore_continue`` -- no-op; the conversation proceeds normally.
        * ``ignore_stop`` -- raises :class:`asyncio.CancelledError` so the
          worker cancels remaining turns.
        * ``error_stop`` -- raises :class:`ValueError` so the worker marks
          the current turn as errored and cancels remaining turns.

        :param request: The generation request that was resolved.
        :param response: The compiled response from the model.
        """
        if request.turn_type != "client_tool_call" or response.tool_calls:
            return

        behavior = self._args.tool_call_missing_behavior
        if behavior == "ignore_continue":
            pass
        elif behavior == "ignore_stop":
            raise asyncio.CancelledError("Expected tool call but model produced none")
        elif behavior == "error_stop":
            raise ValueError("Expected tool call but model produced none")

__init__(arguments)

Initialize OpenAI HTTP backend with server configuration.

Source code in src/guidellm/backends/openai/http.py
def __init__(
    self,
    arguments: OpenAIHTTPBackendArgs,
):
    """
    Initialize OpenAI HTTP backend with server configuration.
    """
    super().__init__(arguments)

    # Runtime state
    self._in_process = False
    self._async_client: httpx.AsyncClient | None = None

available_models() async

Get available models from the target server.

Returns:

Type Description
list[str]

List of model identifiers

Raises:

Type Description
httpx.HTTPError

If models endpoint returns an error

RuntimeError

If backend is not initialized

Source code in src/guidellm/backends/openai/http.py
async def available_models(self) -> list[str]:
    """
    Get available models from the target server.

    :return: List of model identifiers
    :raises httpx.HTTPError: If models endpoint returns an error
    :raises RuntimeError: If backend is not initialized
    """
    if self._async_client is None:
        raise RuntimeError("Backend not started up for process.")

    target = f"{self._args.target}/{self._args.api_routes['/v1/models']}"
    response = await self._async_client.get(target, headers=self._build_headers())
    response.raise_for_status()

    return [item["id"] for item in response.json()["data"]]

default_model() async

Get the default model for this backend.

Returns:

Type Description
str

Model name or None if no model is available

Source code in src/guidellm/backends/openai/http.py
async def default_model(self) -> str:
    """
    Get the default model for this backend.

    :return: Model name or None if no model is available
    """
    if self._args.model or not self._in_process:
        return self._args.model

    models = await self.available_models()
    self._args.model = models[0] if models else ""
    return self._args.model

process_shutdown() async

Clean up HTTP client and backend resources.

Raises:

Type Description
RuntimeError

If backend was not properly initialized

httpx.RequestError

If HTTP client cannot be closed

Source code in src/guidellm/backends/openai/http.py
async def process_shutdown(self):
    """
    Clean up HTTP client and backend resources.

    :raises RuntimeError: If backend was not properly initialized
    :raises httpx.RequestError: If HTTP client cannot be closed
    """
    if not self._in_process:
        raise RuntimeError("Backend not started up for process.")

    await self._async_client.aclose()  # type: ignore [union-attr]
    self._async_client = None
    self._in_process = False

process_startup() async

Initialize HTTP client and backend resources.

Raises:

Type Description
RuntimeError

If backend is already initialized

httpx.RequestError

If HTTP client cannot be created

Source code in src/guidellm/backends/openai/http.py
async def process_startup(self):
    """
    Initialize HTTP client and backend resources.

    :raises RuntimeError: If backend is already initialized
    :raises httpx.RequestError: If HTTP client cannot be created
    """
    if self._in_process:
        raise RuntimeError("Backend already started up for process.")

    self._async_client = httpx.AsyncClient(
        http2=self._args.http2,
        timeout=httpx.Timeout(
            FALLBACK_TIMEOUT,
            read=self._args.timeout,
            connect=self._args.timeout_connect,
        ),
        follow_redirects=self._args.follow_redirects,
        verify=self._args.verify,
        # Allow unlimited connections
        limits=httpx.Limits(
            max_connections=None,
            max_keepalive_connections=None,
            keepalive_expiry=5.0,  # default
        ),
    )
    self._in_process = True

resolve(request, request_info, history=None) async

Process generation request and yield progressive responses.

Handles request formatting, timing tracking, API communication, and response parsing with streaming support.

:yields: Tuples of (response, updated_request_info) as generation progresses

Parameters:

Name Type Description Default
request GenerationRequest

Generation request with content and parameters

required
request_info RequestInfo

Request tracking info updated with timing metadata

required
history list[tuple[GenerationRequest, GenerationResponse | None]] | None

Conversation history (currently not supported)

None

Raises:

Type Description
NotImplementedError

If history is provided

RuntimeError

If backend is not initialized

ValueError

If request type is unsupported

Source code in src/guidellm/backends/openai/http.py
async def resolve(  # type: ignore[override, misc]
    self,
    request: GenerationRequest,
    request_info: RequestInfo,
    history: list[tuple[GenerationRequest, GenerationResponse | None]]
    | None = None,
) -> AsyncIterator[tuple[GenerationResponse | None, RequestInfo]]:
    """
    Process generation request and yield progressive responses.

    Handles request formatting, timing tracking, API communication, and
    response parsing with streaming support.

    :param request: Generation request with content and parameters
    :param request_info: Request tracking info updated with timing metadata
    :param history: Conversation history (currently not supported)
    :raises NotImplementedError: If history is provided
    :raises RuntimeError: If backend is not initialized
    :raises ValueError: If request type is unsupported
    :yields: Tuples of (response, updated_request_info) as generation progresses
    """
    if self._async_client is None:
        raise RuntimeError("Backend not started up for process.")

    (
        request_handler,
        arguments,
        request_kwargs,
    ) = await self._prepare_resolve_request(request, history)

    if not arguments.stream:
        async for item in self._resolve_non_streaming(
            request, request_info, request_handler, arguments, request_kwargs
        ):
            yield item
        return

    async for item in self._resolve_streaming(
        request, request_info, request_handler, arguments, request_kwargs
    ):
        yield item

validate() async

Validate backend connectivity and configuration.

Raises:

Type Description
RuntimeError

If backend cannot connect or validate configuration

Source code in src/guidellm/backends/openai/http.py
async def validate(self):
    """
    Validate backend connectivity and configuration.

    :raises RuntimeError: If backend cannot connect or validate configuration
    """
    if self._async_client is None:
        raise RuntimeError("Backend not started up for process.")

    if not self._args.validate_backend:
        return

    try:
        validate_kwargs: dict[str, Any] = {
            "method": "GET",
            "url": f"{self._args.target}/{self._args.api_routes['/health']}",
        }
        existing_headers = validate_kwargs.get("headers")
        built_headers = self._build_headers(existing_headers)
        validate_kwargs["headers"] = built_headers
        response = await self._async_client.request(**validate_kwargs)
        response.raise_for_status()
    except Exception as exc:
        raise RuntimeError(
            "Backend validation request failed. Could not connect to the server "
            "or validate the backend configuration."
        ) from exc

OpenAIRequestHandler

Bases: Protocol

Protocol for handling OpenAI request endpoint

Defines the interface to format the request for a given endpoint and to process both streaming and non-streaming responses from backend APIs, converting them into standardized GenerationResponse objects with consistent metrics extraction.

Source code in src/guidellm/backends/openai/request_handlers.py
class OpenAIRequestHandler(Protocol):
    """
    Protocol for handling OpenAI request endpoint

    Defines the interface to format the request for a given endpoint and to
    process both streaming and non-streaming responses from backend APIs,
    converting them into standardized GenerationResponse objects
    with consistent metrics extraction.
    """

    def format(
        self,
        data: GenerationRequest,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
        **kwargs,
    ) -> GenerationRequestArguments:
        """
        Format the generation request into the appropriate structure for
        the backend API.

        :param data: The generation request to format
        :param history: Prior (request, response) pairs in the conversation
        :param **kwargs: Additional keyword arguments for request formatting
        :return: The formatted request arguments
        """
        ...

    def compile_non_streaming(
        self,
        request: GenerationRequest,
        arguments: GenerationRequestArguments,
        response: Any,
    ) -> GenerationResponse:
        """
        Process a complete non-streaming API response.

        :param request: Original generation request
        :param response: Raw API response data from the backend
        :return: Standardized GenerationResponse with extracted metrics
        """
        ...

    @property
    def last_iteration_had_content(self) -> bool:
        """
        Whether the last chunk carried output (text/tool-call) tokens,
        not solely reasoning tokens.

        Used by the HTTP streaming loop to detect the first output token
        for TTFOT measurement.

        :return: True if the last chunk carried output tokens, not solely
            reasoning tokens.
        """
        ...

    def add_streaming_line(self, line: str) -> int | None:
        """
        Process a single line from a streaming response.

        :param line: Raw line from the streaming response
        :return: 1 if content was updated, 0 if line was ignored, None if done
        """
        ...

    def compile_streaming(
        self, request: GenerationRequest, arguments: GenerationRequestArguments
    ) -> GenerationResponse:
        """
        Compile accumulated streaming data into a final response.

        :param request: Original generation request
        :return: Standardized GenerationResponse with extracted metrics
        """
        ...

    def post_validation(self, response: GenerationResponse) -> None:
        """Validate a compiled response before returning it.

        Default implementation is permissive (no-op). Handlers override
        this to reject responses that lack usable output for their
        endpoint type.

        :param response: The compiled generation response to validate.
        :raises ValueError: If the response is unusable.
        """
        ...

last_iteration_had_content property

Whether the last chunk carried output (text/tool-call) tokens, not solely reasoning tokens.

Used by the HTTP streaming loop to detect the first output token for TTFOT measurement.

Returns:

Type Description
bool

True if the last chunk carried output tokens, not solely reasoning tokens.

add_streaming_line(line)

Process a single line from a streaming response.

Parameters:

Name Type Description Default
line str

Raw line from the streaming response

required

Returns:

Type Description
int | None

1 if content was updated, 0 if line was ignored, None if done

Source code in src/guidellm/backends/openai/request_handlers.py
def add_streaming_line(self, line: str) -> int | None:
    """
    Process a single line from a streaming response.

    :param line: Raw line from the streaming response
    :return: 1 if content was updated, 0 if line was ignored, None if done
    """
    ...

compile_non_streaming(request, arguments, response)

Process a complete non-streaming API response.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required
response Any

Raw API response data from the backend

required

Returns:

Type Description
GenerationResponse

Standardized GenerationResponse with extracted metrics

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_non_streaming(
    self,
    request: GenerationRequest,
    arguments: GenerationRequestArguments,
    response: Any,
) -> GenerationResponse:
    """
    Process a complete non-streaming API response.

    :param request: Original generation request
    :param response: Raw API response data from the backend
    :return: Standardized GenerationResponse with extracted metrics
    """
    ...

compile_streaming(request, arguments)

Compile accumulated streaming data into a final response.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required

Returns:

Type Description
GenerationResponse

Standardized GenerationResponse with extracted metrics

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_streaming(
    self, request: GenerationRequest, arguments: GenerationRequestArguments
) -> GenerationResponse:
    """
    Compile accumulated streaming data into a final response.

    :param request: Original generation request
    :return: Standardized GenerationResponse with extracted metrics
    """
    ...

format(data, history=None, **kwargs)

Format the generation request into the appropriate structure for the backend API.

Parameters:

Name Type Description Default
data GenerationRequest

The generation request to format

required
history HistoryT[GenerationRequest, GenerationResponse] | None

Prior (request, response) pairs in the conversation

None
**kwargs

Additional keyword arguments for request formatting

{}

Returns:

Type Description
GenerationRequestArguments

The formatted request arguments

Source code in src/guidellm/backends/openai/request_handlers.py
def format(
    self,
    data: GenerationRequest,
    history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
    **kwargs,
) -> GenerationRequestArguments:
    """
    Format the generation request into the appropriate structure for
    the backend API.

    :param data: The generation request to format
    :param history: Prior (request, response) pairs in the conversation
    :param **kwargs: Additional keyword arguments for request formatting
    :return: The formatted request arguments
    """
    ...

post_validation(response)

Validate a compiled response before returning it.

Default implementation is permissive (no-op). Handlers override this to reject responses that lack usable output for their endpoint type.

Parameters:

Name Type Description Default
response GenerationResponse

The compiled generation response to validate.

required

Raises:

Type Description
ValueError

If the response is unusable.

Source code in src/guidellm/backends/openai/request_handlers.py
def post_validation(self, response: GenerationResponse) -> None:
    """Validate a compiled response before returning it.

    Default implementation is permissive (no-op). Handlers override
    this to reject responses that lack usable output for their
    endpoint type.

    :param response: The compiled generation response to validate.
    :raises ValueError: If the response is unusable.
    """
    ...

OpenAIRequestHandlerFactory

Bases: RegistryMixin[type[OpenAIRequestHandler]]

Factory for registering and creating OpenAI request handlers by request type.

Registry-based system for associating handler classes with specific API types, enabling automatic selection of the appropriate handler for processing responses from different generation services.

Source code in src/guidellm/backends/openai/request_handlers.py
class OpenAIRequestHandlerFactory(RegistryMixin[type[OpenAIRequestHandler]]):
    """
    Factory for registering and creating OpenAI request handlers by request type.

    Registry-based system for associating handler classes with specific API
    types, enabling automatic selection of the appropriate handler for processing
    responses from different generation services.
    """

    @classmethod
    def create(
        cls,
        request_type: str,
        handler_overrides: dict[str, type[OpenAIRequestHandler]] | None = None,
    ) -> OpenAIRequestHandler:
        """
        Create a request handler class for the given request type.

        :param request_type: The type of generation request (e.g., "/chat/completions")
        :param handler_overrides: Optional mapping of request types to handler classes
            to override the default registry by checking first and then falling back
            to the registered handlers.
        :return: The corresponding instantiated GenerationResponseHandler
        :raises ValueError: When no handler is registered for the request type
        """
        if handler_overrides and request_type in handler_overrides:
            return handler_overrides[request_type]()

        handler_cls = cls.get_registered_object(request_type)
        if not handler_cls:
            raise ValueError(
                f"No response handler registered for type '{request_type}'."
            )

        return handler_cls()

create(request_type, handler_overrides=None) classmethod

Create a request handler class for the given request type.

Parameters:

Name Type Description Default
request_type str

The type of generation request (e.g., "/chat/completions")

required
handler_overrides dict[str, type[OpenAIRequestHandler]] | None

Optional mapping of request types to handler classes to override the default registry by checking first and then falling back to the registered handlers.

None

Returns:

Type Description
OpenAIRequestHandler

The corresponding instantiated GenerationResponseHandler

Raises:

Type Description
ValueError

When no handler is registered for the request type

Source code in src/guidellm/backends/openai/request_handlers.py
@classmethod
def create(
    cls,
    request_type: str,
    handler_overrides: dict[str, type[OpenAIRequestHandler]] | None = None,
) -> OpenAIRequestHandler:
    """
    Create a request handler class for the given request type.

    :param request_type: The type of generation request (e.g., "/chat/completions")
    :param handler_overrides: Optional mapping of request types to handler classes
        to override the default registry by checking first and then falling back
        to the registered handlers.
    :return: The corresponding instantiated GenerationResponseHandler
    :raises ValueError: When no handler is registered for the request type
    """
    if handler_overrides and request_type in handler_overrides:
        return handler_overrides[request_type]()

    handler_cls = cls.get_registered_object(request_type)
    if not handler_cls:
        raise ValueError(
            f"No response handler registered for type '{request_type}'."
        )

    return handler_cls()

OpenAIWSRequestHandler

Bases: Protocol

Protocol for WebSocket-based streaming request handlers.

Defines the interface for handlers that interpret JSON event frames from a WebSocket connection, accumulate streaming state, and compile a final response. Mirrors the HTTP handler lifecycle (format -> stream -> compile) but uses structured event dicts instead of SSE text lines.

Source code in src/guidellm/backends/openai/request_handlers.py
class OpenAIWSRequestHandler(Protocol):
    """
    Protocol for WebSocket-based streaming request handlers.

    Defines the interface for handlers that interpret JSON event frames from a
    WebSocket connection, accumulate streaming state, and compile a final response.
    Mirrors the HTTP handler lifecycle (format -> stream -> compile) but uses
    structured event dicts instead of SSE text lines.
    """

    def format(
        self,
        data: GenerationRequest,
        response: GenerationResponse | None = None,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
        **kwargs,
    ) -> GenerationRequestArguments:
        """
        Format and validate the generation request for the WebSocket endpoint.

        :param data: The generation request to format
        :param response: Optional previous response for multi-turn
        :param history: Optional conversation history
        :param kwargs: Additional keyword arguments (model, websocket_path, etc.)
        :return: The formatted request arguments with metadata
        """
        ...

    def add_streaming_event(self, event: dict[str, Any]) -> WSStreamingEventResult:
        """
        Process one JSON event frame from the WebSocket.

        :param event: Parsed JSON dict from a WebSocket text frame
        :return: Classified result for timing updates and loop control
        :raises RuntimeError: On server error events
        """
        ...

    @property
    def streaming_text(self) -> str:
        """Accumulated transcription text from processed events."""
        ...

    def compile_streaming(
        self, request: GenerationRequest, arguments: GenerationRequestArguments
    ) -> GenerationResponse:
        """
        Assemble accumulated streaming state into a final GenerationResponse.

        Called after the event loop completes (normal or cancelled).

        :param request: Original generation request
        :param arguments: Request arguments from format()
        :return: Standardized GenerationResponse with extracted metrics
        """
        ...

    def post_validation(self, response: GenerationResponse) -> None:
        """Validate a compiled response before returning it.

        Default implementation is permissive (no-op). Handlers override
        this to reject responses that lack usable output for their
        endpoint type.

        :param response: The compiled generation response to validate.
        :raises ValueError: If the response is unusable.
        """
        ...

streaming_text property

Accumulated transcription text from processed events.

add_streaming_event(event)

Process one JSON event frame from the WebSocket.

Parameters:

Name Type Description Default
event dict[str, Any]

Parsed JSON dict from a WebSocket text frame

required

Returns:

Type Description
WSStreamingEventResult

Classified result for timing updates and loop control

Raises:

Type Description
RuntimeError

On server error events

Source code in src/guidellm/backends/openai/request_handlers.py
def add_streaming_event(self, event: dict[str, Any]) -> WSStreamingEventResult:
    """
    Process one JSON event frame from the WebSocket.

    :param event: Parsed JSON dict from a WebSocket text frame
    :return: Classified result for timing updates and loop control
    :raises RuntimeError: On server error events
    """
    ...

compile_streaming(request, arguments)

Assemble accumulated streaming state into a final GenerationResponse.

Called after the event loop completes (normal or cancelled).

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required
arguments GenerationRequestArguments

Request arguments from format()

required

Returns:

Type Description
GenerationResponse

Standardized GenerationResponse with extracted metrics

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_streaming(
    self, request: GenerationRequest, arguments: GenerationRequestArguments
) -> GenerationResponse:
    """
    Assemble accumulated streaming state into a final GenerationResponse.

    Called after the event loop completes (normal or cancelled).

    :param request: Original generation request
    :param arguments: Request arguments from format()
    :return: Standardized GenerationResponse with extracted metrics
    """
    ...

format(data, response=None, history=None, **kwargs)

Format and validate the generation request for the WebSocket endpoint.

Parameters:

Name Type Description Default
data GenerationRequest

The generation request to format

required
response GenerationResponse | None

Optional previous response for multi-turn

None
history HistoryT[GenerationRequest, GenerationResponse] | None

Optional conversation history

None
kwargs

Additional keyword arguments (model, websocket_path, etc.)

{}

Returns:

Type Description
GenerationRequestArguments

The formatted request arguments with metadata

Source code in src/guidellm/backends/openai/request_handlers.py
def format(
    self,
    data: GenerationRequest,
    response: GenerationResponse | None = None,
    history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
    **kwargs,
) -> GenerationRequestArguments:
    """
    Format and validate the generation request for the WebSocket endpoint.

    :param data: The generation request to format
    :param response: Optional previous response for multi-turn
    :param history: Optional conversation history
    :param kwargs: Additional keyword arguments (model, websocket_path, etc.)
    :return: The formatted request arguments with metadata
    """
    ...

post_validation(response)

Validate a compiled response before returning it.

Default implementation is permissive (no-op). Handlers override this to reject responses that lack usable output for their endpoint type.

Parameters:

Name Type Description Default
response GenerationResponse

The compiled generation response to validate.

required

Raises:

Type Description
ValueError

If the response is unusable.

Source code in src/guidellm/backends/openai/request_handlers.py
def post_validation(self, response: GenerationResponse) -> None:
    """Validate a compiled response before returning it.

    Default implementation is permissive (no-op). Handlers override
    this to reject responses that lack usable output for their
    endpoint type.

    :param response: The compiled generation response to validate.
    :raises ValueError: If the response is unusable.
    """
    ...

OpenAIWSRequestHandlerFactory

Bases: RegistryMixin['type[OpenAIWSRequestHandler]']

Factory for registering and creating WebSocket request handlers by path.

Source code in src/guidellm/backends/openai/request_handlers.py
class OpenAIWSRequestHandlerFactory(RegistryMixin["type[OpenAIWSRequestHandler]"]):
    """Factory for registering and creating WebSocket request handlers by path."""

    @classmethod
    def create(cls, request_type: str) -> OpenAIWSRequestHandler:
        """
        Create a WebSocket request handler for the given request path.

        :param request_type: The WebSocket path (e.g., "/v1/realtime")
        :return: Instantiated handler implementing OpenAIWSRequestHandler
        :raises ValueError: When no handler is registered for the path
        """
        handler_cls = cls.get_registered_object(request_type)
        if not handler_cls:
            raise ValueError(
                f"No WebSocket handler registered for type '{request_type}'."
            )
        return handler_cls()

create(request_type) classmethod

Create a WebSocket request handler for the given request path.

Parameters:

Name Type Description Default
request_type str

The WebSocket path (e.g., "/v1/realtime")

required

Returns:

Type Description
OpenAIWSRequestHandler

Instantiated handler implementing OpenAIWSRequestHandler

Raises:

Type Description
ValueError

When no handler is registered for the path

Source code in src/guidellm/backends/openai/request_handlers.py
@classmethod
def create(cls, request_type: str) -> OpenAIWSRequestHandler:
    """
    Create a WebSocket request handler for the given request path.

    :param request_type: The WebSocket path (e.g., "/v1/realtime")
    :return: Instantiated handler implementing OpenAIWSRequestHandler
    :raises ValueError: When no handler is registered for the path
    """
    handler_cls = cls.get_registered_object(request_type)
    if not handler_cls:
        raise ValueError(
            f"No WebSocket handler registered for type '{request_type}'."
        )
    return handler_cls()

OpenAIWebSocketBackend

Bases: Backend

WebSocket client for realtime (streaming) audio transcription.

Connects to a vLLM-style /v1/realtime WebSocket, streams PCM16 audio chunks, and maps transcription.* events into GenerationResponse with timings.

Example: :: args = OpenAIWebSocketBackendArgs( target="http://localhost:8000", model="my-model", ) backend = OpenAIWebSocketBackend(args)

await backend.process_startup()
async for response, request_info in backend.resolve(request, info):
    ...
await backend.process_shutdown()
Source code in src/guidellm/backends/openai/websocket.py
@Backend.register("openai_websocket")
class OpenAIWebSocketBackend(Backend):
    """
    WebSocket client for realtime (streaming) audio transcription.

    Connects to a vLLM-style ``/v1/realtime`` WebSocket, streams PCM16 audio chunks,
    and maps ``transcription.*`` events into ``GenerationResponse`` with timings.

    Example:
    ::
        args = OpenAIWebSocketBackendArgs(
            target="http://localhost:8000",
            model="my-model",
        )
        backend = OpenAIWebSocketBackend(args)

        await backend.process_startup()
        async for response, request_info in backend.resolve(request, info):
            ...
        await backend.process_shutdown()
    """

    _args: OpenAIWebSocketBackendArgs

    def __init__(self, arguments: OpenAIWebSocketBackendArgs):
        """
        Initialize the WebSocket backend from validated args.

        :param arguments: Typed configuration including target, model, and paths.
        """
        super().__init__(arguments)
        self._resolved_model = (arguments.model or "").strip()
        self.validate_backend: dict[str, Any] | None = resolve_validate_kwargs(
            arguments.validate_backend,
            self._args.target,
            _WS_API_ROUTES,
        )
        self._in_process = False
        self._async_client: httpx.AsyncClient | None = None

    @property
    def websocket_path(self) -> str:
        """
        HTTP path segment on the host used for the WebSocket URL.

        :return: Resolved path from ``request_format``.
        """
        return self._args.request_format

    @property
    def info(self) -> dict[str, Any]:
        """
        Return a snapshot of backend configuration for logging or debugging.

        :return: Dict of target, model, WebSocket path, timeouts, and validation opts.
        """
        return {
            "target": self._args.target,
            "model": self._resolved_model or self._args.model,
            "websocket_path": self.websocket_path,
            "chunk_samples": self._args.chunk_samples,
            "timeout": self._args.timeout,
            "timeout_connect": self._args.timeout_connect,
            "verify": self._args.verify,
            "validate_backend": self.validate_backend,
        }

    def _parsed_target(self) -> ParseResult:
        """Parse ``target`` into a URL structure for scheme and host lookup."""
        raw = (
            self._args.target
            if "://" in self._args.target
            else f"http://{self._args.target}"
        )
        return urlparse(raw)

    def _ws_url(self) -> str:
        """Build ``ws://`` or ``wss://`` URL including :attr:`websocket_path`."""
        parsed = self._parsed_target()
        if not parsed.netloc:
            raise ValueError(f"Invalid target URL for WebSocket: {self._args.target!r}")
        ws_scheme = "wss" if parsed.scheme in ("https", "wss") else "ws"
        path = self.websocket_path
        if not path.startswith("/"):
            path = f"/{path}"
        return f"{ws_scheme}://{parsed.netloc}{path}"

    def _ssl_context(self) -> ssl.SSLContext | None:
        """TLS context for secure WebSockets; ``None`` when using plain ``ws``."""
        if self._parsed_target().scheme in ("http", "ws"):
            return None
        ctx = ssl.create_default_context()
        if not self._args.verify:
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
        return ctx

    def _build_headers(
        self, existing_headers: dict[str, str] | None = None
    ) -> dict[str, str] | None:
        """Merge bearer auth and optional headers for HTTP and WebSocket handshakes."""
        return build_headers(self._args.api_key, existing_headers)

    async def process_startup(self) -> None:
        """
        Create the shared :class:`httpx.AsyncClient` used for health and ``/v1/models``.

        :raises RuntimeError: If the backend was already started in this process.
        """
        if self._in_process:
            raise RuntimeError("Backend already started up for process.")
        self._async_client = httpx.AsyncClient(
            timeout=httpx.Timeout(
                FALLBACK_TIMEOUT,
                read=self._args.timeout,
                connect=self._args.timeout_connect,
            ),
            verify=self._args.verify,
            limits=httpx.Limits(
                max_connections=None,
                max_keepalive_connections=None,
                keepalive_expiry=5.0,
            ),
        )
        self._in_process = True

    async def process_shutdown(self) -> None:
        """
        Close the HTTP client and reset process-local state.

        :raises RuntimeError: If the backend was not started.
        """
        if not self._in_process:
            raise RuntimeError("Backend not started up for process.")
        client = self._async_client
        if client is None:
            raise RuntimeError("Backend not started up for process.")
        await client.aclose()
        self._async_client = None
        self._in_process = False

    async def validate(self) -> None:
        """
        Run the configured HTTP probe (same semantics as ``openai_http``).

        :raises RuntimeError: If the client is not started or the probe fails.
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")
        if not self.validate_backend:
            return
        validate_kwargs = {**self.validate_backend}
        existing_headers = validate_kwargs.get("headers")
        validate_kwargs["headers"] = build_headers(self._args.api_key, existing_headers)
        try:
            response = await self._async_client.request(**validate_kwargs)
            response.raise_for_status()
        except Exception as exc:
            raise RuntimeError(
                "Backend validation request failed. Could not connect to the server "
                "or validate the backend configuration."
            ) from exc

    async def available_models(self) -> list[str]:
        """
        List model IDs from ``GET /v1/models`` on the HTTP target.

        :return: Model identifiers from the OpenAI-style payload.
        :raises RuntimeError: If the client is not started or the response is invalid.
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")
        target = f"{self._args.target}/v1/models"
        response = await self._async_client.get(
            target, headers=build_headers(self._args.api_key)
        )
        response.raise_for_status()
        return [item["id"] for item in response.json()["data"]]

    async def default_model(self) -> str:
        """
        Return the configured model, or the first from ``available_models`` if empty.

        :return: Non-empty model name when discoverable; otherwise ``""``.
        """
        if self._resolved_model:
            return self._resolved_model
        if not self._in_process:
            return ""
        models = await self.available_models()
        self._resolved_model = models[0] if models else ""
        return self._resolved_model

    async def resolve(  # type: ignore[override, misc]  # noqa: C901, PLR0912, PLR0915
        self,
        request: GenerationRequest,
        request_info: RequestInfo,
        history: list[tuple[GenerationRequest, GenerationResponse | None]]
        | None = None,
    ) -> AsyncIterator[tuple[GenerationResponse | None, RequestInfo]]:
        """
        Stream one realtime transcription over WebSocket for a single audio column.

        Delegates event interpretation to the registered
        :class:`~guidellm.backends.openai.request_handlers.OpenAIWSRequestHandler`
        via ``add_streaming_event`` / ``compile_streaming``, while this method handles
        only I/O and timing.

        :param request: Must contain exactly one ``audio_column`` entry.
        :param request_info: Timings updated as events arrive.
        :param history: Not supported; raises ``NotImplementedError`` if non-empty.
        :raises NotImplementedError: If ``history`` is provided.
        :raises RuntimeError: If the client is not started, model is missing, or the
            peer returns an error event.
        :yields: ``(response_or_none, request_info)`` until stream completion.
        """
        if self._async_client is None:
            raise RuntimeError("Backend not started up for process.")
        if history:
            raise NotImplementedError(
                "openai_websocket does not support multiturn/history yet."
            )

        model_name = await self.default_model()
        if not str(model_name).strip():
            raise RuntimeError(
                "No model configured for openai_websocket and /v1/models returned "
                "none. Pass --model or ensure the server lists at least one model."
            )

        handler = OpenAIWSRequestHandlerFactory.create(self.websocket_path)
        arguments = handler.format(
            request,
            model=model_name,
            websocket_path=self.websocket_path,
            chunk_samples=self._args.chunk_samples,
        )
        body = arguments.body or {}
        chunks = body.get(WS_AUDIO_CHUNKS_BODY_KEY)
        if not isinstance(chunks, list):
            raise RuntimeError(
                "Realtime WebSocket handler format() did not provide "
                f"{WS_AUDIO_CHUNKS_BODY_KEY!r}."
            )

        session_update: dict[str, Any] = {"type": "session.update"}
        extras = self._args.extras or {}
        if extras:
            for key, val in extras.items():
                if key not in ("type", "model"):
                    session_update[key] = val
        session_update["model"] = model_name

        ssl_ctx = self._ssl_context()
        ws_headers = build_headers(self._args.api_key)

        try:
            request_info.timings.request_start = time.time()
            connect_kw: dict[str, Any] = {
                "ssl": ssl_ctx,
                "open_timeout": self._args.timeout_connect,
            }
            if ws_headers:
                connect_kw["additional_headers"] = ws_headers
            async with ws_connect(self._ws_url(), **connect_kw) as ws:
                raw_first = await self._recv_ws(ws)
                first_event = _load_ws_event(raw_first)
                if first_event.get("type") == "error":
                    raise RuntimeError(format_ws_error(first_event.get("error")))
                if first_event.get("type") != "session.created":
                    raise RuntimeError(
                        f"Expected session.created, got {first_event.get('type')!r}"
                    )
                await ws.send(_json_text(session_update))
                for b64_chunk in chunks:
                    await ws.send(
                        _json_text(
                            {"type": "input_audio_buffer.append", "audio": b64_chunk}
                        )
                    )
                await ws.send(
                    _json_text({"type": "input_audio_buffer.commit", "final": False})
                )
                await ws.send(
                    _json_text({"type": "input_audio_buffer.commit", "final": True})
                )

                ignored_events = 0
                while True:
                    raw = await self._recv_ws(ws)
                    event = _load_ws_event(raw)
                    update = handler.add_streaming_event(event)

                    if update.kind is WSEventResult.STREAM_END:
                        iter_time = time.time()
                        request_info.timings.request_end = iter_time
                        # Done-only path: first-token timing when text exists.
                        if (
                            request_info.timings.first_token_iteration is None
                            and _record_content_tokens(
                                request_info,
                                content_tokens=1 if handler.streaming_text else 0,
                                record_request_iteration=True,
                            )
                        ):
                            yield None, request_info
                        break

                    if update.kind in (
                        WSEventResult.CONTENT,
                        WSEventResult.REQUEST_ITERATION,
                    ):
                        if _record_content_tokens(
                            request_info,
                            content_tokens=update.content_tokens,
                            record_request_iteration=True,
                        ):
                            yield None, request_info
                    elif update.kind is WSEventResult.IGNORED:
                        ignored_events += 1
                        if ignored_events > _MAX_IGNORED_WS_EVENT_TYPES:
                            raise RuntimeError(
                                "Exceeded maximum ignored realtime WebSocket events "
                                f"(last type={event.get('type')!r})."
                            )

                compiled = handler.compile_streaming(request, arguments)
                handler.post_validation(compiled)
                yield compiled, request_info

        except asyncio.CancelledError as err:
            yield handler.compile_streaming(request, arguments), request_info
            raise err
        finally:
            if (
                request_info.timings.request_start is not None
                and request_info.timings.request_end is None
            ):
                request_info.timings.request_end = time.time()

    async def _recv_ws(self, ws: ClientConnection) -> str:
        """
        Receive one text frame from the WebSocket, honoring per-message timeout.

        :param ws: Active realtime connection.
        :return: Decoded UTF-8 text from the server.
        """
        if self._args.timeout is None:
            msg = await ws.recv()
        else:
            msg = await asyncio.wait_for(ws.recv(), timeout=self._args.timeout)
        if isinstance(msg, bytes):
            return msg.decode()
        return str(msg)

info property

Return a snapshot of backend configuration for logging or debugging.

Returns:

Type Description
dict[str, Any]

Dict of target, model, WebSocket path, timeouts, and validation opts.

websocket_path property

HTTP path segment on the host used for the WebSocket URL.

Returns:

Type Description
str

Resolved path from request_format.

__init__(arguments)

Initialize the WebSocket backend from validated args.

Parameters:

Name Type Description Default
arguments OpenAIWebSocketBackendArgs

Typed configuration including target, model, and paths.

required
Source code in src/guidellm/backends/openai/websocket.py
def __init__(self, arguments: OpenAIWebSocketBackendArgs):
    """
    Initialize the WebSocket backend from validated args.

    :param arguments: Typed configuration including target, model, and paths.
    """
    super().__init__(arguments)
    self._resolved_model = (arguments.model or "").strip()
    self.validate_backend: dict[str, Any] | None = resolve_validate_kwargs(
        arguments.validate_backend,
        self._args.target,
        _WS_API_ROUTES,
    )
    self._in_process = False
    self._async_client: httpx.AsyncClient | None = None

available_models() async

List model IDs from GET /v1/models on the HTTP target.

Returns:

Type Description
list[str]

Model identifiers from the OpenAI-style payload.

Raises:

Type Description
RuntimeError

If the client is not started or the response is invalid.

Source code in src/guidellm/backends/openai/websocket.py
async def available_models(self) -> list[str]:
    """
    List model IDs from ``GET /v1/models`` on the HTTP target.

    :return: Model identifiers from the OpenAI-style payload.
    :raises RuntimeError: If the client is not started or the response is invalid.
    """
    if self._async_client is None:
        raise RuntimeError("Backend not started up for process.")
    target = f"{self._args.target}/v1/models"
    response = await self._async_client.get(
        target, headers=build_headers(self._args.api_key)
    )
    response.raise_for_status()
    return [item["id"] for item in response.json()["data"]]

default_model() async

Return the configured model, or the first from available_models if empty.

Returns:

Type Description
str

Non-empty model name when discoverable; otherwise "".

Source code in src/guidellm/backends/openai/websocket.py
async def default_model(self) -> str:
    """
    Return the configured model, or the first from ``available_models`` if empty.

    :return: Non-empty model name when discoverable; otherwise ``""``.
    """
    if self._resolved_model:
        return self._resolved_model
    if not self._in_process:
        return ""
    models = await self.available_models()
    self._resolved_model = models[0] if models else ""
    return self._resolved_model

process_shutdown() async

Close the HTTP client and reset process-local state.

Raises:

Type Description
RuntimeError

If the backend was not started.

Source code in src/guidellm/backends/openai/websocket.py
async def process_shutdown(self) -> None:
    """
    Close the HTTP client and reset process-local state.

    :raises RuntimeError: If the backend was not started.
    """
    if not self._in_process:
        raise RuntimeError("Backend not started up for process.")
    client = self._async_client
    if client is None:
        raise RuntimeError("Backend not started up for process.")
    await client.aclose()
    self._async_client = None
    self._in_process = False

process_startup() async

Create the shared :class:httpx.AsyncClient used for health and /v1/models.

Raises:

Type Description
RuntimeError

If the backend was already started in this process.

Source code in src/guidellm/backends/openai/websocket.py
async def process_startup(self) -> None:
    """
    Create the shared :class:`httpx.AsyncClient` used for health and ``/v1/models``.

    :raises RuntimeError: If the backend was already started in this process.
    """
    if self._in_process:
        raise RuntimeError("Backend already started up for process.")
    self._async_client = httpx.AsyncClient(
        timeout=httpx.Timeout(
            FALLBACK_TIMEOUT,
            read=self._args.timeout,
            connect=self._args.timeout_connect,
        ),
        verify=self._args.verify,
        limits=httpx.Limits(
            max_connections=None,
            max_keepalive_connections=None,
            keepalive_expiry=5.0,
        ),
    )
    self._in_process = True

resolve(request, request_info, history=None) async

Stream one realtime transcription over WebSocket for a single audio column.

Delegates event interpretation to the registered :class:~guidellm.backends.openai.request_handlers.OpenAIWSRequestHandler via add_streaming_event / compile_streaming, while this method handles only I/O and timing.

:yields: (response_or_none, request_info) until stream completion.

Parameters:

Name Type Description Default
request GenerationRequest

Must contain exactly one audio_column entry.

required
request_info RequestInfo

Timings updated as events arrive.

required
history list[tuple[GenerationRequest, GenerationResponse | None]] | None

Not supported; raises NotImplementedError if non-empty.

None

Raises:

Type Description
NotImplementedError

If history is provided.

RuntimeError

If the client is not started, model is missing, or the peer returns an error event.

Source code in src/guidellm/backends/openai/websocket.py
async def resolve(  # type: ignore[override, misc]  # noqa: C901, PLR0912, PLR0915
    self,
    request: GenerationRequest,
    request_info: RequestInfo,
    history: list[tuple[GenerationRequest, GenerationResponse | None]]
    | None = None,
) -> AsyncIterator[tuple[GenerationResponse | None, RequestInfo]]:
    """
    Stream one realtime transcription over WebSocket for a single audio column.

    Delegates event interpretation to the registered
    :class:`~guidellm.backends.openai.request_handlers.OpenAIWSRequestHandler`
    via ``add_streaming_event`` / ``compile_streaming``, while this method handles
    only I/O and timing.

    :param request: Must contain exactly one ``audio_column`` entry.
    :param request_info: Timings updated as events arrive.
    :param history: Not supported; raises ``NotImplementedError`` if non-empty.
    :raises NotImplementedError: If ``history`` is provided.
    :raises RuntimeError: If the client is not started, model is missing, or the
        peer returns an error event.
    :yields: ``(response_or_none, request_info)`` until stream completion.
    """
    if self._async_client is None:
        raise RuntimeError("Backend not started up for process.")
    if history:
        raise NotImplementedError(
            "openai_websocket does not support multiturn/history yet."
        )

    model_name = await self.default_model()
    if not str(model_name).strip():
        raise RuntimeError(
            "No model configured for openai_websocket and /v1/models returned "
            "none. Pass --model or ensure the server lists at least one model."
        )

    handler = OpenAIWSRequestHandlerFactory.create(self.websocket_path)
    arguments = handler.format(
        request,
        model=model_name,
        websocket_path=self.websocket_path,
        chunk_samples=self._args.chunk_samples,
    )
    body = arguments.body or {}
    chunks = body.get(WS_AUDIO_CHUNKS_BODY_KEY)
    if not isinstance(chunks, list):
        raise RuntimeError(
            "Realtime WebSocket handler format() did not provide "
            f"{WS_AUDIO_CHUNKS_BODY_KEY!r}."
        )

    session_update: dict[str, Any] = {"type": "session.update"}
    extras = self._args.extras or {}
    if extras:
        for key, val in extras.items():
            if key not in ("type", "model"):
                session_update[key] = val
    session_update["model"] = model_name

    ssl_ctx = self._ssl_context()
    ws_headers = build_headers(self._args.api_key)

    try:
        request_info.timings.request_start = time.time()
        connect_kw: dict[str, Any] = {
            "ssl": ssl_ctx,
            "open_timeout": self._args.timeout_connect,
        }
        if ws_headers:
            connect_kw["additional_headers"] = ws_headers
        async with ws_connect(self._ws_url(), **connect_kw) as ws:
            raw_first = await self._recv_ws(ws)
            first_event = _load_ws_event(raw_first)
            if first_event.get("type") == "error":
                raise RuntimeError(format_ws_error(first_event.get("error")))
            if first_event.get("type") != "session.created":
                raise RuntimeError(
                    f"Expected session.created, got {first_event.get('type')!r}"
                )
            await ws.send(_json_text(session_update))
            for b64_chunk in chunks:
                await ws.send(
                    _json_text(
                        {"type": "input_audio_buffer.append", "audio": b64_chunk}
                    )
                )
            await ws.send(
                _json_text({"type": "input_audio_buffer.commit", "final": False})
            )
            await ws.send(
                _json_text({"type": "input_audio_buffer.commit", "final": True})
            )

            ignored_events = 0
            while True:
                raw = await self._recv_ws(ws)
                event = _load_ws_event(raw)
                update = handler.add_streaming_event(event)

                if update.kind is WSEventResult.STREAM_END:
                    iter_time = time.time()
                    request_info.timings.request_end = iter_time
                    # Done-only path: first-token timing when text exists.
                    if (
                        request_info.timings.first_token_iteration is None
                        and _record_content_tokens(
                            request_info,
                            content_tokens=1 if handler.streaming_text else 0,
                            record_request_iteration=True,
                        )
                    ):
                        yield None, request_info
                    break

                if update.kind in (
                    WSEventResult.CONTENT,
                    WSEventResult.REQUEST_ITERATION,
                ):
                    if _record_content_tokens(
                        request_info,
                        content_tokens=update.content_tokens,
                        record_request_iteration=True,
                    ):
                        yield None, request_info
                elif update.kind is WSEventResult.IGNORED:
                    ignored_events += 1
                    if ignored_events > _MAX_IGNORED_WS_EVENT_TYPES:
                        raise RuntimeError(
                            "Exceeded maximum ignored realtime WebSocket events "
                            f"(last type={event.get('type')!r})."
                        )

            compiled = handler.compile_streaming(request, arguments)
            handler.post_validation(compiled)
            yield compiled, request_info

    except asyncio.CancelledError as err:
        yield handler.compile_streaming(request, arguments), request_info
        raise err
    finally:
        if (
            request_info.timings.request_start is not None
            and request_info.timings.request_end is None
        ):
            request_info.timings.request_end = time.time()

validate() async

Run the configured HTTP probe (same semantics as openai_http).

Raises:

Type Description
RuntimeError

If the client is not started or the probe fails.

Source code in src/guidellm/backends/openai/websocket.py
async def validate(self) -> None:
    """
    Run the configured HTTP probe (same semantics as ``openai_http``).

    :raises RuntimeError: If the client is not started or the probe fails.
    """
    if self._async_client is None:
        raise RuntimeError("Backend not started up for process.")
    if not self.validate_backend:
        return
    validate_kwargs = {**self.validate_backend}
    existing_headers = validate_kwargs.get("headers")
    validate_kwargs["headers"] = build_headers(self._args.api_key, existing_headers)
    try:
        response = await self._async_client.request(**validate_kwargs)
        response.raise_for_status()
    except Exception as exc:
        raise RuntimeError(
            "Backend validation request failed. Could not connect to the server "
            "or validate the backend configuration."
        ) from exc

OpenAIWebSocketBackendArgs

Bases: BackendArgs

Typed configuration for :class:OpenAIWebSocketBackend.

Source code in src/guidellm/backends/openai/websocket.py
@BackendArgs.register("openai_websocket")
class OpenAIWebSocketBackendArgs(BackendArgs):
    """Typed configuration for :class:`OpenAIWebSocketBackend`."""

    kind: Literal["openai_websocket"] = Field(
        default="openai_websocket",
        description="Type identifier for the backend configuration.",
    )
    target: str = Field(
        description=(
            "HTTP(S) base URL of the server (WebSocket URL is derived from it)."
        ),
    )
    model: str = Field(
        default_factory=str,
        description="Model identifier for generation requests.",
    )
    request_format: str = Field(
        default="/v1/realtime",
        description=(
            "Realtime WebSocket path (only /v1/realtime is supported today). "
            "Use the same top-level CLI flags as ``openai_http``: "
            "--request-format / --request-type."
        ),
    )
    chunk_samples: int = Field(
        default=3200,
        ge=1,
        description="PCM16 frames per input_audio_buffer.append chunk (16 kHz).",
    )
    api_key: SecretStr | None = Field(
        default=None, description="Bearer token if required."
    )  # noqa: F821
    verify: bool = Field(default=False, description="Verify TLS certificates.")
    timeout: float | None = Field(
        default=None,
        description="Per-message read timeout for WebSocket receives (seconds).",
    )
    timeout_connect: float = Field(
        default=FALLBACK_TIMEOUT,
        description="Timeout for establishing the WebSocket connection.",
    )
    validate_backend: bool | str | dict[str, Any] = Field(
        default=True,
        description=(
            "HTTP health check before benchmarks (same semantics as openai_http)."
        ),
    )
    extras: dict[str, Any] | None = Field(
        default=None,
        description="Extra fields merged into session.update (backend model wins).",
    )

    @field_validator("target", mode="after")
    @classmethod
    def strip_target(cls, value: str) -> str:
        """Strip trailing slashes and ``/v1`` suffix from the target URL."""
        return value.rstrip("/").removesuffix("/v1")

    @field_validator("request_format")
    @classmethod
    def validate_request_format(cls, v: str) -> str:
        """Validate ``request_format`` against allowed WebSocket paths."""
        stripped = v.strip()
        if stripped != "/v1/realtime":
            raise ValueError(f"request_format must be '/v1/realtime', got {stripped!r}")
        return stripped

strip_target(value) classmethod

Strip trailing slashes and /v1 suffix from the target URL.

Source code in src/guidellm/backends/openai/websocket.py
@field_validator("target", mode="after")
@classmethod
def strip_target(cls, value: str) -> str:
    """Strip trailing slashes and ``/v1`` suffix from the target URL."""
    return value.rstrip("/").removesuffix("/v1")

validate_request_format(v) classmethod

Validate request_format against allowed WebSocket paths.

Source code in src/guidellm/backends/openai/websocket.py
@field_validator("request_format")
@classmethod
def validate_request_format(cls, v: str) -> str:
    """Validate ``request_format`` against allowed WebSocket paths."""
    stripped = v.strip()
    if stripped != "/v1/realtime":
        raise ValueError(f"request_format must be '/v1/realtime', got {stripped!r}")
    return stripped

ResponsesRequestHandler

Bases: OpenAIRequestHandler

Request handler for the OpenAI Responses API endpoint.

Handles the /v1/responses format which uses input instead of messages, instructions for system prompts, and a different response/streaming shape than chat completions. Supports both streaming and non-streaming responses.

Source code in src/guidellm/backends/openai/request_handlers.py
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
@OpenAIRequestHandlerFactory.register("/v1/responses")
class ResponsesRequestHandler(OpenAIRequestHandler):
    """
    Request handler for the OpenAI Responses API endpoint.

    Handles the /v1/responses format which uses `input` instead of `messages`,
    `instructions` for system prompts, and a different response/streaming shape
    than chat completions. Supports both streaming and non-streaming responses.
    """

    def __init__(self):
        self.streaming_texts: list[str] = []
        self.streaming_usage: dict[str, int | dict[str, int]] | None = None
        self.streaming_response_id: str | None = None
        # Accumulated function_call items keyed by output_index, used to
        # reconstruct tool_calls on GenerationResponse after streaming.
        self.streaming_tool_calls: dict[int, ToolCall] = {}
        self.streaming_reasoning_texts: list[str] = []
        self._last_iteration_had_content: bool = False

    @property
    def last_iteration_had_content(self) -> bool:
        """
        :return: True if the last chunk carried output (text/tool-call) tokens,
            not solely reasoning tokens.
        """
        return self._last_iteration_had_content

    @staticmethod
    def _ensure_tool_format(tool: dict[str, Any]) -> dict[str, Any]:
        """Normalise a single tool definition to Responses API format.

        The Responses API expects ``{"type": "function", "name": ..., ...}`` with
        detail fields at the top level.  If the tool is already in that format it is
        returned as-is.  If it is in Chat Completions format (nested ``function``
        key, no top-level ``name``) the detail fields are flattened up.

        :param tool: A single tool definition dict in either format.
        :return: The tool in Responses API format.
        """
        if "function" in tool and "name" not in tool:
            fn = tool["function"]
            converted = {"type": tool.get("type", "function")}
            for key in _FUNCTION_DETAIL_KEYS:
                if key in fn:
                    converted[key] = fn[key]
            return converted
        return tool

    def _format_prompts(
        self,
        column_data: list,
        column_type: str,
        content_extras: dict[str, Any] | None = None,
    ) -> list[dict[str, Any]]:
        formatted_data: list[dict[str, Any]] = []
        for item in column_data:
            if column_type == "text_column":
                content = {"type": "input_text", "text": item}
                if content_extras:
                    content.update(content_extras)
                formatted_data.append(content)
            elif column_type == "image_column":
                formatted_data.append(
                    {
                        "type": "input_image",
                        "image_url": item.get("image"),
                    }
                )
            elif column_type == "audio_column":
                formatted_data.append(
                    {
                        "type": "input_file",
                        "file_data": base64.b64encode(item.get("audio", b"")).decode(
                            "utf-8"
                        ),
                    }
                )
        return formatted_data

    def _build_history_input_items(
        self,
        history: HistoryT[GenerationRequest, GenerationResponse],
        **kwargs,
    ) -> list[dict[str, Any]]:
        """Build the ``input`` array from completed conversation turns.

        Iterates through history with neighbor access so that injection
        turns can pull ``tool_call_id``s from the preceding turn's response.

        :param history: Completed (request, response) pairs.
        :param kwargs: Forwarded config (``multiturn_reasoning``, etc.).
        :return: Flat list of input item dicts.
        """
        items: list[dict[str, Any]] = []
        for idx, (req, res) in enumerate(history):
            prior_response = history[idx - 1][1] if idx > 0 else None
            items.extend(
                self._build_turn_input_items(req, res, prior_response, **kwargs)
            )
        return items

    def _build_turn_input_items(  # noqa: C901
        self,
        req: GenerationRequest,
        res: GenerationResponse | None,
        prior_response: GenerationResponse | None,
        **kwargs,
    ) -> list[dict[str, Any]]:
        """Build input items for a single history turn.

        Dispatches on ``req.turn_type`` analogously to the chat completions
        handler's ``_build_turn_messages``.

        :param req: The request for this history turn.
        :param res: The response the server gave for this turn.
        :param prior_response: Response from the preceding history turn
            (used by injection turns for ``call_id``s).
        :param kwargs: Forwarded config (``multiturn_reasoning``, etc.).
        :return: List of input item dicts for this turn.
        """
        items: list[dict[str, Any]] = []
        multiturn_reasoning = kwargs.get("multiturn_reasoning", False)

        if req.turn_type == "tool_response_injection":
            # Injection turn: function_call_output items then assistant text.
            if prior_response and prior_response.tool_calls:
                items.extend(
                    self._build_function_call_outputs(
                        prior_response.tool_calls,
                        req.columns.get("tool_response_column", []),
                    )
                )
            if res is not None and res.text is not None:
                wrapped = _wrap_reasoning(res.reasoning_text, multiturn_reasoning)
                content = res.text
                if wrapped:
                    content = wrapped + content
                items.append({"role": "assistant", "content": content})
        else:
            # Standard or tool_call turn: user content.
            extras = kwargs.get("extras")
            content_extras = extras.content if extras is not None else None
            prompts = [
                self._format_prompts(
                    req.columns.get(col, []),
                    col,
                    content_extras,
                )
                for col in (
                    "text_column",
                    "image_column",
                    "video_column",
                    "audio_column",
                )
            ]
            content_parts = list(roundrobin(*prompts))
            if content_parts:
                items.append({"role": "user", "content": content_parts})

            wrapped = _wrap_reasoning(
                res.reasoning_text if res else None, multiturn_reasoning
            )
            if res is not None:
                if res.tool_calls:
                    # Tool-call turn: function_call items only.
                    # function_call_output items come from the injection turn.
                    for tc in res.tool_calls:
                        items.append(self._tool_call_to_responses_item(tc))
                elif res.text is not None or wrapped:
                    content = res.text or ""
                    if wrapped:
                        content = wrapped + content
                    items.append({"role": "assistant", "content": content})

        return items

    @staticmethod
    def _build_function_call_outputs(
        tool_calls: list[ToolCall],
        tool_response_columns: list[Any],
    ) -> list[dict[str, Any]]:
        """Build ``function_call_output`` items from tool calls and response data.

        :param tool_calls: Tool call objects supplying ``call_id``s.
        :param tool_response_columns: Per-call response content from the
            dataset, falling back to the default synthetic response.
        :return: List of ``function_call_output`` dicts.
        """
        outputs: list[dict[str, Any]] = []
        for idx, tc in enumerate(tool_calls):
            raw_content = (
                tool_response_columns[idx]
                if idx < len(tool_response_columns)
                else settings.default_synthetic_tool_response
            )
            content = (
                raw_content.decode("utf-8")
                if isinstance(raw_content, bytes)
                else raw_content
            )
            outputs.append(
                {
                    "type": "function_call_output",
                    "call_id": tc.id,
                    "output": content,
                }
            )
        return outputs

    @staticmethod
    def _apply_tool_call_overrides(
        body: dict[str, Any],
        data: GenerationRequest,
    ) -> None:
        """Inject tool definitions and constrain the request body for tool calling.

        Handles three concerns:

        1. Deserializes and injects tool definitions from dataset columns,
           normalising to Responses API format when necessary.
        2. Sets ``tool_choice`` to ``"required"`` or ``"none"`` depending on
           whether the current turn expects a tool call.
        3. Removes body keys that are incompatible with tool calling
           (``ignore_eos``, ``stop``, and ``max_output_tokens`` on tool-call
           turns).

        :param body: The mutable request body dict being built.
        :param data: The current generation request.
        """
        tools_column = data.columns.get("tools_column", [])
        if tools_column:
            tools_value = tools_column[0]
            if isinstance(tools_value, str | bytes):
                tools_value = json.loads(tools_value)
            if isinstance(tools_value, list):
                body["tools"] = [
                    ResponsesRequestHandler._ensure_tool_format(t) for t in tools_value
                ]
                body.setdefault("tool_choice", "required")

        if "tools" not in body:
            body.pop("tool_choice", None)
            return

        if data.turn_type in ("standard", "tool_response_injection"):
            body["tool_choice"] = "none"

        # Tool calling requires the model to stop naturally after producing
        # valid JSON; ignore_eos would force generation past that point.
        # max_output_tokens would truncate output mid-JSON and corrupt
        # the arguments sent in conversation history on follow-up turns.
        if data.turn_type == "client_tool_call":
            body.pop("ignore_eos", None)
            body.pop("stop", None)
            body.pop("max_output_tokens", None)

    def format(  # noqa: C901
        self,
        data: GenerationRequest,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
        **kwargs,
    ) -> GenerationRequestArguments:
        use_server_history = kwargs.get("server_history") and history

        arguments = GenerationRequestArguments()
        arguments.body = {}

        if kwargs.get("model") is not None:
            arguments.body["model"] = kwargs["model"]

        if kwargs.get("stream"):
            arguments.stream = True
            arguments.body["stream"] = True
            # Unlike chat completions, we don't send stream_options here.
            # The Responses API's stream_options only controls obfuscation,
            # not usage reporting. vLLM always includes usage data in the
            # response.completed SSE event for this endpoint.
            # Unfortunately, this complicates getting accurate stats when canceled.

        if data.output_metrics.text_tokens:
            arguments.body["max_output_tokens"] = data.output_metrics.text_tokens
            # stop/ignore_eos are vLLM-specific sampling params that force
            # the model to generate exactly N tokens, matching the behavior
            # of the chat completions handler for controlled benchmarking.
            arguments.body["stop"] = None
            arguments.body["ignore_eos"] = True
        elif kwargs.get("max_tokens") is not None:
            arguments.body["max_output_tokens"] = kwargs["max_tokens"]

        if kwargs.get("extras"):
            arguments.model_combine(kwargs["extras"])

        prefix = " ".join(data.columns.get("prefix_column", []))
        if prefix:
            arguments.body["instructions"] = prefix

        # Build input items from history
        input_items: list[dict[str, Any]] = []
        if history and not use_server_history:
            input_items = self._build_history_input_items(history, **kwargs)

        # Build the current turn's input items.
        # When server_history is active, _apply_server_history handles
        # function_call_output injection, so skip it here.
        if data.turn_type == "tool_response_injection" and not use_server_history:
            prior_response = history[-1][1] if history else None
            if prior_response and prior_response.tool_calls:
                input_items.extend(
                    self._build_function_call_outputs(
                        prior_response.tool_calls,
                        data.columns.get("tool_response_column", []),
                    )
                )
        elif data.turn_type != "tool_response_injection":
            # Standard or tool_call turn: user content.
            extras = kwargs.get("extras")
            content_extras = extras.content if extras is not None else None
            prompts = [
                self._format_prompts(
                    data.columns.get(col, []),
                    col,
                    content_extras,
                )
                for col in (
                    "text_column",
                    "image_column",
                    "video_column",
                    "audio_column",
                )
            ]
            content_parts = list(roundrobin(*prompts))
            if content_parts:
                input_items.append({"role": "user", "content": content_parts})

        arguments.body["input"] = input_items

        # Server-side history: reference the previous response by ID and
        # include any tool outputs the server cannot know (tool execution
        # is client-side).  Only the immediate follow-up after a tool-call
        # response needs function_call_output items; subsequent turns have
        # no tool_calls on the last response so this branch is skipped.
        if use_server_history:
            self._apply_server_history(arguments.body, history, data)  # type: ignore[arg-type]

        self._apply_tool_call_overrides(arguments.body, data)

        return arguments

    @staticmethod
    def _extract_reasoning_text(response: dict) -> str | None:
        """Extract reasoning summary text from Responses API output items.

        Reasoning items have ``type: "reasoning"`` with a list of ``summary``
        objects, each containing a ``text`` field.

        :param response: Full Responses API response dict.
        :return: Concatenated reasoning text, or None if absent.
        """
        parts: list[str] = []
        for item in response.get("output", []):
            if item.get("type") != "reasoning":
                continue
            for summary in item.get("summary", []):
                if txt := summary.get("text"):
                    parts.append(txt)
        return "".join(parts) or None

    def compile_non_streaming(
        self,
        request: GenerationRequest,
        arguments: GenerationRequestArguments,
        response: dict,
    ) -> GenerationResponse:
        text = self._extract_output_text(response)
        reasoning_text = self._extract_reasoning_text(response)
        raw_items = [
            item
            for item in response.get("output", [])
            if item.get("type") == "function_call"
        ]
        tool_calls: list[ToolCall] | None = (
            [self._responses_item_to_tool_call(item) for item in raw_items]
            if raw_items
            else None
        )
        if text is None and not tool_calls:
            text = ""
        usage = response.get("usage", {})
        input_metrics, output_metrics = self.extract_metrics(usage, text)
        _apply_tool_call_metrics(
            output_metrics, len(tool_calls) if tool_calls else 0, text
        )

        return GenerationResponse(
            request_id=request.request_id,
            request_args=arguments.model_dump_json(),
            response_id=response.get("id"),
            text=text,
            reasoning_text=reasoning_text,
            tool_calls=tool_calls,
            input_metrics=input_metrics,
            output_metrics=output_metrics,
        )

    def compile_streaming(
        self, request: GenerationRequest, arguments: GenerationRequestArguments
    ) -> GenerationResponse:
        return _compile_streaming_response(
            request,
            arguments,
            self.streaming_texts,
            self.streaming_tool_calls,
            self.streaming_usage,
            self.streaming_response_id,
            self.extract_metrics,
            streaming_reasoning_texts=self.streaming_reasoning_texts,
        )

    def post_validation(self, response: GenerationResponse) -> None:
        """Reject responses with no text, tool calls, or output tokens."""
        _validate_text_response(response)

    def extract_line_data(self, line: str) -> dict[str, Any] | None:
        """Parse a Responses API SSE line.

        The Responses API streams paired ``event: <type>`` and ``data: <json>``
        lines, unlike chat completions which only uses ``data:`` lines.  The
        event type is redundantly embedded in the JSON payload's ``type`` field,
        so ``event:`` lines are skipped, keeping only ``data:`` lines.
        """
        line = line.strip()

        if not line or not line.startswith("data:"):
            return {}

        if line == "data: [DONE]":
            return None

        data = json.loads(line[len("data:") :].strip())
        _check_streaming_error(data)
        return data

    @staticmethod
    def _responses_item_to_tool_call(item: dict[str, Any]) -> ToolCall:
        """Convert a Responses API ``function_call`` output item to a
        ``ToolCall``.

        The Responses API uses a flat structure (``call_id``, ``name``,
        ``arguments``) while ``ToolCall`` nests name/arguments
        inside a ``function`` sub-object.

        :param item: A Responses API ``function_call`` dict.
        :return: The equivalent ``ToolCall``.
        """
        return ToolCall(
            id=item.get("call_id", ""),
            type="function",
            function=ToolCallFunction(
                name=item.get("name", ""),
                arguments=item.get("arguments", ""),
            ),
        )

    @staticmethod
    def _tool_call_to_responses_item(tc: ToolCall) -> dict[str, Any]:
        """Convert a ``ToolCall`` back to a Responses API
        ``function_call`` input item for multi-turn replay.

        :param tc: The canonical tool call object.
        :return: A dict suitable for the Responses API ``input`` array.
        """
        return {
            "type": "function_call",
            "call_id": tc.id,
            "name": tc.function.name,
            "arguments": tc.function.arguments,
        }

    def _apply_server_history(
        self,
        body: dict[str, Any],
        history: HistoryT[GenerationRequest, GenerationResponse],
        current_request: GenerationRequest,
    ) -> None:
        """Apply server-side history fields to the request body.

        Sets ``previous_response_id`` from the last response in history.
        For injection turns, prepends ``function_call_output`` items using
        the injection turn's ``tool_response_column`` and the preceding
        response's tool call IDs.

        :param body: The mutable request body dict being built.
        :param history: The conversation history up to this point.
        :param current_request: The current request being formatted.
        """
        _, last_response = history[-1]
        if last_response and last_response.response_id:
            body["previous_response_id"] = last_response.response_id
        # For injection turns the tool_response_column lives on the
        # current request and the tool_call IDs come from the last
        # history entry's response.
        if (
            current_request.turn_type == "tool_response_injection"
            and last_response
            and last_response.tool_calls
        ):
            body["input"] = (
                self._build_function_call_outputs(
                    last_response.tool_calls,
                    current_request.columns.get("tool_response_column", []),
                )
                + body["input"]
            )

    def _handle_streaming_function_call(
        self, event_type: str, data: dict[str, Any]
    ) -> int | None:
        """Process function_call-related streaming events.

        Accumulates ``ToolCall`` objects keyed by ``output_index``.
        The Responses API streams ``call_id`` / ``name`` / ``arguments`` at
        the top level; these are mapped into the canonical
        ``ToolCall`` shape used across all handlers.

        :returns: Token count delta, or ``None`` if unrecognized.
        """
        # First event for a new tool call: the server announces the
        # function_call output item with its call_id and name.  We
        # create a new ToolCall entry keyed by output_index so that
        # subsequent argument deltas can append to the right object.
        if (
            event_type == "response.output_item.added"
            and data.get("item", {}).get("type") == "function_call"
        ):
            idx = data["output_index"]
            item = data["item"]
            self.streaming_tool_calls[idx] = ToolCall(
                id=item.get("call_id", ""),
                type="function",
                function=ToolCallFunction(
                    name=item.get("name", ""),
                    arguments=item.get("arguments", ""),
                ),
            )
            return 1

        # Incremental argument chunk: append the JSON fragment to the
        # tool call that was created by the output_item.added event above.
        if event_type == "response.function_call_arguments.delta":
            idx = data.get("output_index", -1)
            if idx in self.streaming_tool_calls:
                self.streaming_tool_calls[idx].function.arguments += data.get(
                    "delta", ""
                )
            return 1

        # Final arguments payload: the server sends the complete argument
        # string once streaming is finished.  We overwrite whatever was
        # accumulated from deltas to guarantee consistency.
        if event_type == "response.function_call_arguments.done":
            idx = data.get("output_index", -1)
            if idx in self.streaming_tool_calls:
                self.streaming_tool_calls[idx].function.arguments = data.get(
                    "arguments",
                    self.streaming_tool_calls[idx].function.arguments,
                )
            return 1

        # Not a function-call event; let the caller handle it.
        return None

    def _handle_streaming_text_delta(
        self, event_type: str, data: dict[str, Any]
    ) -> int | None:
        """
        Handle reasoning and output text delta events, updating
        ``_last_iteration_had_content`` accordingly.

        :return: 0 or 1 if handled, None if not a text delta event.
        """
        if event_type == "response.reasoning_summary_text.delta":
            delta = data.get("delta", "")
            if delta:
                self.streaming_reasoning_texts.append(delta)
                self._last_iteration_had_content = False
                return 1
            return 0

        if event_type == "response.output_text.delta":
            delta = data.get("delta", "")
            if delta:
                self.streaming_texts.append(delta)
                self._last_iteration_had_content = True
                return 1
            return 0

        return None

    def add_streaming_line(self, line: str) -> int | None:
        if not (data := self.extract_line_data(line)):
            return None if data is None else 0

        event_type = data.get("type", "")

        # Extract the response ID from the response.created event which
        # carries a nested "response" object containing the actual ID.
        if self.streaming_response_id is None:
            resp = data.get("response", {})
            if isinstance(resp, dict) and "id" in resp:
                self.streaming_response_id = resp["id"]

        text_result = self._handle_streaming_text_delta(event_type, data)
        if text_result is not None:
            return text_result

        # Function call deltas are always treated as content for TTFOT
        fc_result = self._handle_streaming_function_call(event_type, data)
        if fc_result is not None:
            self._last_iteration_had_content = True
            return fc_result

        if event_type in (
            "response.completed",
            "response.failed",
            "response.incomplete",
        ):
            # All three are terminal SSE events. response.completed is the
            # normal case; response.failed and response.incomplete may be sent
            # by some providers instead. Each carries a final response object
            # with optional usage data. Returning None signals the streaming
            # loop in http.py to break out of the stream.
            resp = data.get("response") or {}
            usage = resp.get("usage")
            if usage:
                self.streaming_usage = usage
            if self.streaming_response_id is None and "id" in resp:
                self.streaming_response_id = resp["id"]
            return None

        return 0

    def extract_metrics(
        self, usage: dict[str, int | dict[str, int]] | None, text: str | None
    ) -> tuple[UsageMetrics, UsageMetrics]:
        # Responses API uses "input_tokens"/"output_tokens" in its usage
        # payload, unlike chat completions' "prompt_tokens"/"completion_tokens".
        # It also provides "input_tokens_details" and "output_tokens_details"
        # for multimodal breakdowns, mirroring chat completions'
        # "prompt_tokens_details"/"completion_tokens_details".
        if text is None:
            # text not applicable — exclude from aggregation
            text_words = None
            text_chars = None
        else:
            text_words = len(text.split())
            text_chars = len(text)

        if not usage:
            return UsageMetrics(), UsageMetrics(
                text_words=text_words,
                text_characters=text_chars,
            )

        usage_metrics: dict[str, int] = cast("dict[str, int]", usage)
        input_details: dict[str, int] = cast(
            "dict[str, int]", usage.get("input_tokens_details", {}) or {}
        )
        output_details: dict[str, int] = cast(
            "dict[str, int]", usage.get("output_tokens_details", {}) or {}
        )

        return UsageMetrics(
            text_tokens=(
                input_details.get("text_tokens")
                or usage_metrics.get("input_tokens")
                or 0
            ),
            image_tokens=input_details.get("image_tokens"),
            video_tokens=input_details.get("video_tokens"),
            audio_tokens=input_details.get("audio_tokens"),
            audio_seconds=input_details.get("seconds"),
        ), UsageMetrics(
            text_tokens=(
                output_details.get("text_tokens")
                or usage_metrics.get("output_tokens")
                or 0
            ),
            text_words=text_words,
            text_characters=text_chars,
            image_tokens=output_details.get("image_tokens"),
            video_tokens=output_details.get("video_tokens"),
            audio_tokens=output_details.get("audio_tokens"),
            audio_seconds=output_details.get("seconds"),
        )

    @staticmethod
    def _extract_output_text(response: dict) -> str | None:
        """Extract generated text from a Responses API response object.

        :returns: ``None`` when no message/output_text items exist (e.g. tool-call-
        only responses), so callers can distinguish "no text" from "empty text".
        """
        texts: list[str] = []
        for item in response.get("output", []):
            if item.get("type") != "message":
                continue
            for part in item.get("content", []):
                if part.get("type") == "output_text":
                    texts.append(part.get("text", ""))
        return "".join(texts) if texts else None

last_iteration_had_content property

Returns:

Type Description
bool

True if the last chunk carried output (text/tool-call) tokens, not solely reasoning tokens.

extract_line_data(line)

Parse a Responses API SSE line.

The Responses API streams paired event: <type> and data: <json> lines, unlike chat completions which only uses data: lines. The event type is redundantly embedded in the JSON payload's type field, so event: lines are skipped, keeping only data: lines.

Source code in src/guidellm/backends/openai/request_handlers.py
def extract_line_data(self, line: str) -> dict[str, Any] | None:
    """Parse a Responses API SSE line.

    The Responses API streams paired ``event: <type>`` and ``data: <json>``
    lines, unlike chat completions which only uses ``data:`` lines.  The
    event type is redundantly embedded in the JSON payload's ``type`` field,
    so ``event:`` lines are skipped, keeping only ``data:`` lines.
    """
    line = line.strip()

    if not line or not line.startswith("data:"):
        return {}

    if line == "data: [DONE]":
        return None

    data = json.loads(line[len("data:") :].strip())
    _check_streaming_error(data)
    return data

post_validation(response)

Reject responses with no text, tool calls, or output tokens.

Source code in src/guidellm/backends/openai/request_handlers.py
def post_validation(self, response: GenerationResponse) -> None:
    """Reject responses with no text, tool calls, or output tokens."""
    _validate_text_response(response)

TextCompletionsRequestHandler

Bases: OpenAIRequestHandler

Request handler for OpenAI-style legacy completion endpoints.

Processes responses from text completion APIs that return generated text in the 'choices' array with 'text' fields. Handles both streaming and non-streaming responses, extracting usage metrics for input and output tokens.

Example: :: handler = TextCompletionsResponseHandler() response = handler.compile_non_streaming(request, api_response)

Source code in src/guidellm/backends/openai/request_handlers.py
@OpenAIRequestHandlerFactory.register("/v1/completions")
class TextCompletionsRequestHandler(OpenAIRequestHandler):
    """
    Request handler for OpenAI-style legacy completion endpoints.

    Processes responses from text completion APIs that return generated text in the
    'choices' array with 'text' fields. Handles both streaming and non-streaming
    responses, extracting usage metrics for input and output tokens.

    Example:
    ::
        handler = TextCompletionsResponseHandler()
        response = handler.compile_non_streaming(request, api_response)
    """

    def __init__(self):
        """
        Initialize the text completions response handler.

        Sets up internal state for accumulating streaming response data including
        text chunks and usage metrics.
        """
        self.streaming_texts: list[str] = []
        self.streaming_usage: dict[str, int | dict[str, int]] | None = None
        self.streaming_response_id: str | None = None

    @property
    def last_iteration_had_content(self) -> bool:
        """
        Text completions (``/v1/completions``) have no reasoning concept, so
        every token is content. ChatCompletionsRequestHandler and
        ResponsesRequestHandler override this with a tracked flag that starts
        ``False`` and only becomes ``True`` when a content or tool call delta
        arrives.

        :return: Always True for the text completions base class
        """
        return True

    def format(  # noqa: C901
        self,
        data: GenerationRequest,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
        **kwargs,
    ) -> GenerationRequestArguments:
        """
        Format the text completion generation request into the appropriate structure.

        :param data: The generation request to format
        :param **kwargs: Additional keyword arguments for request formatting
        :return: The formatted request arguments
        """
        arguments: GenerationRequestArguments = GenerationRequestArguments()
        arguments.body = {}  # The type checker works better setting this field here

        # Add model
        if kwargs.get("model") is not None:
            arguments.body["model"] = kwargs["model"]

        # Configure streaming
        if kwargs.get("stream"):
            arguments.stream = True
            arguments.body["stream"] = True
            arguments.body["stream_options"] = {
                "include_usage": True,
                "continuous_usage_stats": True,
            }

        # Handle output tokens
        if data.output_metrics.text_tokens:
            arguments.body["max_tokens"] = data.output_metrics.text_tokens
            arguments.body["stop"] = None
            arguments.body["ignore_eos"] = True
        elif kwargs.get("max_tokens") is not None:
            arguments.body["max_tokens"] = kwargs["max_tokens"]

        # Apply extra arguments
        if kwargs.get("extras"):
            arguments.model_combine(kwargs["extras"])

        ## Build prompt ##
        prompts: list[str] = []

        # Include history: previous prompts and their responses
        if history:
            for req, res in history:
                prompts.extend(req.columns.get("prefix_column", []))
                prompts.extend(req.columns.get("text_column", []))
                if res and res.text:
                    prompts.append(res.text)

        # Include prefix
        prompts.extend(data.columns.get("prefix_column", []))
        # Include text column
        prompts.extend(data.columns.get("text_column", []))

        if prompts:
            arguments.body["prompt"] = " ".join(prompts)

        return arguments

    def compile_non_streaming(
        self,
        request: GenerationRequest,
        arguments: GenerationRequestArguments,
        response: dict,
    ) -> GenerationResponse:
        """
        Process a complete text completion response.

        :param request: Original generation request
        :param response: Complete API response containing choices and usage data
        :return: Standardized GenerationResponse with extracted text and metrics
        """
        choices, usage = self.extract_choices_and_usage(response)
        choice = choices[0] if choices else {}
        text = choice.get("text", "")
        input_metrics, output_metrics = self.extract_metrics(usage, text)

        return GenerationResponse(
            request_id=request.request_id,
            request_args=arguments.model_dump_json(),
            response_id=response.get("id"),  # use vLLM ID if available
            text=text,
            input_metrics=input_metrics,
            output_metrics=output_metrics,
        )

    def add_streaming_line(self, line: str) -> int | None:
        """
        Process a single line from a text completion streaming response.

        Parses Server-Sent Events (SSE) formatted lines, extracting text content
        and usage metrics. Accumulates text chunks for final response compilation.

        :param line: Raw SSE line from the streaming response
        :return: 1 if text content was extracted, 0 if line ignored, None if done
        """
        if not (data := self.extract_line_data(line)):
            return None if data is None else 0

        if "id" in data and self.streaming_response_id is None:
            self.streaming_response_id = data["id"]

        updated = False
        choices, usage = self.extract_choices_and_usage(data)
        choice = choices[0] if choices else {}

        if choices and (text := choice.get("text")):
            self.streaming_texts.append(text)
            updated = True

        if usage:
            self.streaming_usage = usage

        return 1 if updated else 0

    def compile_streaming(
        self, request: GenerationRequest, arguments: GenerationRequestArguments
    ) -> GenerationResponse:
        """
        Compile accumulated streaming text chunks into a final response.

        :param request: Original generation request
        :return: Standardized GenerationResponse with concatenated text and metrics
        """
        text = "".join(self.streaming_texts)
        input_metrics, output_metrics = self.extract_metrics(self.streaming_usage, text)

        return GenerationResponse(
            request_id=request.request_id,
            request_args=arguments.model_dump_json(),
            response_id=self.streaming_response_id,  # use vLLM ID if available
            text=text,
            input_metrics=input_metrics,
            output_metrics=output_metrics,
        )

    def post_validation(self, response: GenerationResponse) -> None:
        """Reject responses with no text, tool calls, or output tokens."""
        _validate_text_response(response)

    def extract_line_data(self, line: str) -> dict[str, Any] | None:
        """
        Extract JSON data from a streaming response line.

        :param line: Raw line from the streaming response
        :return: Parsed JSON data as dictionary, or None if line indicates completion
        """
        if line == "data: [DONE]":
            return None

        if not line or not (line := line.strip()) or not line.startswith("data:"):
            return {}

        line = line[len("data:") :].strip()

        data = json.loads(line)
        _check_streaming_error(data)
        return data

    def extract_choices_and_usage(
        self, response: dict
    ) -> tuple[list[dict], dict[str, int | dict[str, int]]]:
        """
        Extract choices and usage data from the API response.

        :param response: Complete API response containing choices and usage data
        :return: Tuple of choices list and usage dictionary
        """
        return response.get("choices", []), response.get("usage", {})

    def extract_metrics(
        self, usage: dict[str, int | dict[str, int]] | None, text: str | None
    ) -> tuple[UsageMetrics, UsageMetrics]:
        """
        Extract input and output usage metrics from API response usage data.

        :param usage: Usage data dictionary from API response
        :param text: Generated text for calculating word and character counts.
            None means text is not applicable (metrics will be None);
            empty string means text was applicable but empty (metrics will be 0).
        :return: Tuple of input_metrics and output_metrics as UsageMetrics objects
        """
        if text is None:
            # text not applicable (e.g. tool-call-only) — exclude from aggregation
            text_words = None
            text_chars = None
        else:
            text_words = len(text.split())
            text_chars = len(text)

        if not usage:
            return UsageMetrics(), UsageMetrics(
                text_words=text_words,
                text_characters=text_chars,
            )

        input_details: dict[str, int] = cast(
            "dict[str, int]", usage.get("prompt_tokens_details", {}) or {}
        )
        output_details: dict[str, int] = cast(
            "dict[str, int]", usage.get("completion_tokens_details", {}) or {}
        )
        usage_metrics: dict[str, int] = cast("dict[str, int]", usage)

        return UsageMetrics(
            text_tokens=(
                input_details.get("prompt_tokens")
                or usage_metrics.get("prompt_tokens")
                or 0
            ),
            image_tokens=input_details.get("image_tokens"),
            video_tokens=input_details.get("video_tokens"),
            audio_tokens=input_details.get("audio_tokens"),
            audio_seconds=input_details.get("seconds"),
        ), UsageMetrics(
            text_tokens=(
                output_details.get("completion_tokens")
                or usage_metrics.get("completion_tokens")
                or 0
            ),
            text_words=text_words,
            text_characters=text_chars,
            image_tokens=output_details.get("image_tokens"),
            video_tokens=output_details.get("video_tokens"),
            audio_tokens=output_details.get("audio_tokens"),
            audio_seconds=output_details.get("seconds"),
        )

last_iteration_had_content property

Text completions (/v1/completions) have no reasoning concept, so every token is content. ChatCompletionsRequestHandler and ResponsesRequestHandler override this with a tracked flag that starts False and only becomes True when a content or tool call delta arrives.

Returns:

Type Description
bool

Always True for the text completions base class

__init__()

Initialize the text completions response handler.

Sets up internal state for accumulating streaming response data including text chunks and usage metrics.

Source code in src/guidellm/backends/openai/request_handlers.py
def __init__(self):
    """
    Initialize the text completions response handler.

    Sets up internal state for accumulating streaming response data including
    text chunks and usage metrics.
    """
    self.streaming_texts: list[str] = []
    self.streaming_usage: dict[str, int | dict[str, int]] | None = None
    self.streaming_response_id: str | None = None

add_streaming_line(line)

Process a single line from a text completion streaming response.

Parses Server-Sent Events (SSE) formatted lines, extracting text content and usage metrics. Accumulates text chunks for final response compilation.

Parameters:

Name Type Description Default
line str

Raw SSE line from the streaming response

required

Returns:

Type Description
int | None

1 if text content was extracted, 0 if line ignored, None if done

Source code in src/guidellm/backends/openai/request_handlers.py
def add_streaming_line(self, line: str) -> int | None:
    """
    Process a single line from a text completion streaming response.

    Parses Server-Sent Events (SSE) formatted lines, extracting text content
    and usage metrics. Accumulates text chunks for final response compilation.

    :param line: Raw SSE line from the streaming response
    :return: 1 if text content was extracted, 0 if line ignored, None if done
    """
    if not (data := self.extract_line_data(line)):
        return None if data is None else 0

    if "id" in data and self.streaming_response_id is None:
        self.streaming_response_id = data["id"]

    updated = False
    choices, usage = self.extract_choices_and_usage(data)
    choice = choices[0] if choices else {}

    if choices and (text := choice.get("text")):
        self.streaming_texts.append(text)
        updated = True

    if usage:
        self.streaming_usage = usage

    return 1 if updated else 0

compile_non_streaming(request, arguments, response)

Process a complete text completion response.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required
response dict

Complete API response containing choices and usage data

required

Returns:

Type Description
GenerationResponse

Standardized GenerationResponse with extracted text and metrics

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_non_streaming(
    self,
    request: GenerationRequest,
    arguments: GenerationRequestArguments,
    response: dict,
) -> GenerationResponse:
    """
    Process a complete text completion response.

    :param request: Original generation request
    :param response: Complete API response containing choices and usage data
    :return: Standardized GenerationResponse with extracted text and metrics
    """
    choices, usage = self.extract_choices_and_usage(response)
    choice = choices[0] if choices else {}
    text = choice.get("text", "")
    input_metrics, output_metrics = self.extract_metrics(usage, text)

    return GenerationResponse(
        request_id=request.request_id,
        request_args=arguments.model_dump_json(),
        response_id=response.get("id"),  # use vLLM ID if available
        text=text,
        input_metrics=input_metrics,
        output_metrics=output_metrics,
    )

compile_streaming(request, arguments)

Compile accumulated streaming text chunks into a final response.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required

Returns:

Type Description
GenerationResponse

Standardized GenerationResponse with concatenated text and metrics

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_streaming(
    self, request: GenerationRequest, arguments: GenerationRequestArguments
) -> GenerationResponse:
    """
    Compile accumulated streaming text chunks into a final response.

    :param request: Original generation request
    :return: Standardized GenerationResponse with concatenated text and metrics
    """
    text = "".join(self.streaming_texts)
    input_metrics, output_metrics = self.extract_metrics(self.streaming_usage, text)

    return GenerationResponse(
        request_id=request.request_id,
        request_args=arguments.model_dump_json(),
        response_id=self.streaming_response_id,  # use vLLM ID if available
        text=text,
        input_metrics=input_metrics,
        output_metrics=output_metrics,
    )

extract_choices_and_usage(response)

Extract choices and usage data from the API response.

Parameters:

Name Type Description Default
response dict

Complete API response containing choices and usage data

required

Returns:

Type Description
tuple[list[dict], dict[str, int | dict[str, int]]]

Tuple of choices list and usage dictionary

Source code in src/guidellm/backends/openai/request_handlers.py
def extract_choices_and_usage(
    self, response: dict
) -> tuple[list[dict], dict[str, int | dict[str, int]]]:
    """
    Extract choices and usage data from the API response.

    :param response: Complete API response containing choices and usage data
    :return: Tuple of choices list and usage dictionary
    """
    return response.get("choices", []), response.get("usage", {})

extract_line_data(line)

Extract JSON data from a streaming response line.

Parameters:

Name Type Description Default
line str

Raw line from the streaming response

required

Returns:

Type Description
dict[str, Any] | None

Parsed JSON data as dictionary, or None if line indicates completion

Source code in src/guidellm/backends/openai/request_handlers.py
def extract_line_data(self, line: str) -> dict[str, Any] | None:
    """
    Extract JSON data from a streaming response line.

    :param line: Raw line from the streaming response
    :return: Parsed JSON data as dictionary, or None if line indicates completion
    """
    if line == "data: [DONE]":
        return None

    if not line or not (line := line.strip()) or not line.startswith("data:"):
        return {}

    line = line[len("data:") :].strip()

    data = json.loads(line)
    _check_streaming_error(data)
    return data

extract_metrics(usage, text)

Extract input and output usage metrics from API response usage data.

Parameters:

Name Type Description Default
usage dict[str, int | dict[str, int]] | None

Usage data dictionary from API response

required
text str | None

Generated text for calculating word and character counts. None means text is not applicable (metrics will be None); empty string means text was applicable but empty (metrics will be 0).

required

Returns:

Type Description
tuple[UsageMetrics, UsageMetrics]

Tuple of input_metrics and output_metrics as UsageMetrics objects

Source code in src/guidellm/backends/openai/request_handlers.py
def extract_metrics(
    self, usage: dict[str, int | dict[str, int]] | None, text: str | None
) -> tuple[UsageMetrics, UsageMetrics]:
    """
    Extract input and output usage metrics from API response usage data.

    :param usage: Usage data dictionary from API response
    :param text: Generated text for calculating word and character counts.
        None means text is not applicable (metrics will be None);
        empty string means text was applicable but empty (metrics will be 0).
    :return: Tuple of input_metrics and output_metrics as UsageMetrics objects
    """
    if text is None:
        # text not applicable (e.g. tool-call-only) — exclude from aggregation
        text_words = None
        text_chars = None
    else:
        text_words = len(text.split())
        text_chars = len(text)

    if not usage:
        return UsageMetrics(), UsageMetrics(
            text_words=text_words,
            text_characters=text_chars,
        )

    input_details: dict[str, int] = cast(
        "dict[str, int]", usage.get("prompt_tokens_details", {}) or {}
    )
    output_details: dict[str, int] = cast(
        "dict[str, int]", usage.get("completion_tokens_details", {}) or {}
    )
    usage_metrics: dict[str, int] = cast("dict[str, int]", usage)

    return UsageMetrics(
        text_tokens=(
            input_details.get("prompt_tokens")
            or usage_metrics.get("prompt_tokens")
            or 0
        ),
        image_tokens=input_details.get("image_tokens"),
        video_tokens=input_details.get("video_tokens"),
        audio_tokens=input_details.get("audio_tokens"),
        audio_seconds=input_details.get("seconds"),
    ), UsageMetrics(
        text_tokens=(
            output_details.get("completion_tokens")
            or usage_metrics.get("completion_tokens")
            or 0
        ),
        text_words=text_words,
        text_characters=text_chars,
        image_tokens=output_details.get("image_tokens"),
        video_tokens=output_details.get("video_tokens"),
        audio_tokens=output_details.get("audio_tokens"),
        audio_seconds=output_details.get("seconds"),
    )

format(data, history=None, **kwargs)

Format the text completion generation request into the appropriate structure.

Parameters:

Name Type Description Default
data GenerationRequest

The generation request to format

required
**kwargs

Additional keyword arguments for request formatting

{}

Returns:

Type Description
GenerationRequestArguments

The formatted request arguments

Source code in src/guidellm/backends/openai/request_handlers.py
def format(  # noqa: C901
    self,
    data: GenerationRequest,
    history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
    **kwargs,
) -> GenerationRequestArguments:
    """
    Format the text completion generation request into the appropriate structure.

    :param data: The generation request to format
    :param **kwargs: Additional keyword arguments for request formatting
    :return: The formatted request arguments
    """
    arguments: GenerationRequestArguments = GenerationRequestArguments()
    arguments.body = {}  # The type checker works better setting this field here

    # Add model
    if kwargs.get("model") is not None:
        arguments.body["model"] = kwargs["model"]

    # Configure streaming
    if kwargs.get("stream"):
        arguments.stream = True
        arguments.body["stream"] = True
        arguments.body["stream_options"] = {
            "include_usage": True,
            "continuous_usage_stats": True,
        }

    # Handle output tokens
    if data.output_metrics.text_tokens:
        arguments.body["max_tokens"] = data.output_metrics.text_tokens
        arguments.body["stop"] = None
        arguments.body["ignore_eos"] = True
    elif kwargs.get("max_tokens") is not None:
        arguments.body["max_tokens"] = kwargs["max_tokens"]

    # Apply extra arguments
    if kwargs.get("extras"):
        arguments.model_combine(kwargs["extras"])

    ## Build prompt ##
    prompts: list[str] = []

    # Include history: previous prompts and their responses
    if history:
        for req, res in history:
            prompts.extend(req.columns.get("prefix_column", []))
            prompts.extend(req.columns.get("text_column", []))
            if res and res.text:
                prompts.append(res.text)

    # Include prefix
    prompts.extend(data.columns.get("prefix_column", []))
    # Include text column
    prompts.extend(data.columns.get("text_column", []))

    if prompts:
        arguments.body["prompt"] = " ".join(prompts)

    return arguments

post_validation(response)

Reject responses with no text, tool calls, or output tokens.

Source code in src/guidellm/backends/openai/request_handlers.py
def post_validation(self, response: GenerationResponse) -> None:
    """Reject responses with no text, tool calls, or output tokens."""
    _validate_text_response(response)

WSEventResult

Bases: Enum

Classification of a processed WebSocket streaming event.

Source code in src/guidellm/backends/openai/request_handlers.py
class WSEventResult(Enum):
    """Classification of a processed WebSocket streaming event."""

    STREAM_END = auto()
    CONTENT = auto()
    REQUEST_ITERATION = auto()
    IGNORED = auto()

WSStreamingEventResult dataclass

Result of processing one WebSocket JSON event frame.

Parameters:

Name Type Description Default
kind WSEventResult

How the backend should update timings and loop control.

required
content_tokens int

New content tokens when kind is CONTENT.

0
Source code in src/guidellm/backends/openai/request_handlers.py
@dataclass(frozen=True)
class WSStreamingEventResult:
    """
    Result of processing one WebSocket JSON event frame.

    :param kind: How the backend should update timings and loop control.
    :param content_tokens: New content tokens when ``kind`` is ``CONTENT``.
    """

    kind: WSEventResult
    content_tokens: int = 0