Skip to content

guidellm.backends.openai.request_handlers

Request handlers for formatting requests and processing API responses from different OpenAI endpoints.

Provides a pluggable system for handling format differences while supporting both streaming and non-streaming responses. Each handler implements the GenerationRequestHandler protocol to format json requests, parse API responses, extract usage metrics, and convert results into standardized GenerationResponse.

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") or "audio_input",
                audio_columns[0].get("audio"),
                audio_columns[0].get("mimetype"),
            )
        }

        return arguments

    def compile_non_streaming(
        self,
        request: GenerationRequest,
        arguments: GenerationRequestArguments,
        response: dict,
    ) -> GenerationResponse:
        """
        Process a complete audio transcription or translation response.

        :param request: Original generation request
        :param arguments: The request arguments that were sent
        :param response: Complete API response containing top-level text and usage
        :return: Standardized GenerationResponse with extracted text and metrics
        """
        text = response.get("text")
        input_metrics, output_metrics = self.extract_metrics(
            response.get("usage"), text
        )

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

    def post_validation(self, response: GenerationResponse) -> None:
        """Reject audio responses that omit the transcription text field.

        An empty string is a valid transcription for silent or VAD-filtered audio.

        :param response: The compiled audio response to validate.
        :raises ValueError: If the response has no transcription text field.
        """
        if response.text is None:
            raise ValueError(
                "[UNUSABLE_BACKEND_RESPONSE] backend resolved with empty response "
                "payload"
            )

    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()

compile_non_streaming(request, arguments, response)

Process a complete audio transcription or translation response.

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 top-level text and usage

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 audio transcription or translation response.

    :param request: Original generation request
    :param arguments: The request arguments that were sent
    :param response: Complete API response containing top-level text and usage
    :return: Standardized GenerationResponse with extracted text and metrics
    """
    text = response.get("text")
    input_metrics, output_metrics = self.extract_metrics(
        response.get("usage"), text
    )

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

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") or "audio_input",
            audio_columns[0].get("audio"),
            audio_columns[0].get("mimetype"),
        )
    }

    return arguments

post_validation(response)

Reject audio responses that omit the transcription text field.

An empty string is a valid transcription for silent or VAD-filtered audio.

Parameters:

Name Type Description Default
response GenerationResponse

The compiled audio response to validate.

required

Raises:

Type Description
ValueError

If the response has no transcription text field.

Source code in src/guidellm/backends/openai/request_handlers.py
def post_validation(self, response: GenerationResponse) -> None:
    """Reject audio responses that omit the transcription text field.

    An empty string is a valid transcription for silent or VAD-filtered audio.

    :param response: The compiled audio response to validate.
    :raises ValueError: If the response has no transcription text field.
    """
    if response.text is None:
        raise ValueError(
            "[UNUSABLE_BACKEND_RESPONSE] backend resolved with empty response "
            "payload"
        )

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
 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
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
@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`` from ``tool_choice_column`` when present,
           otherwise ``"required"``, or ``"none"`` on turns that must not
           emit tool calls.
        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", _dataset_tool_choice(data))

        _constrain_tool_call_body(body, data, "max_completion_tokens")

    def _append_request_content_messages(
        self,
        messages: list[dict[str, Any]],
        req: GenerationRequest,
        **kwargs,
    ) -> None:
        """Append current-turn content: recorded chat dicts or text/multimodal.

        When ``raw_messages_column`` is set, those dicts are extended as-is so
        multi-turn replay can send user, assistant, and tool messages without
        wrapping them as a single user string.

        :param messages: Message list to extend in place.
        :param req: Request whose columns supply the current turn.
        :param kwargs: Forwarded format kwargs (``extras`` for multimodal).
        """
        recorded = _recorded_chat_messages(req.columns)
        if recorded is not None:
            messages.extend(recorded)
            return

        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})

    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: recorded messages, or system + user content.
            self._append_request_content_messages(messages, req, **kwargs)

            # 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
        :raises ValueError: If ``messages`` cannot be built from columns, extras,
            history, or a tool-injection turn.
        """
        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: recorded messages, or system + user content.
            self._append_request_content_messages(
                arguments.body["messages"], data, **kwargs
            )

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

        _require_request_payload(
            arguments,
            endpoint="/v1/chat/completions",
            field="messages",
            sources=(
                "raw_messages_column, text_column, prefix_column, or media columns"
            ),
            columns=data.columns,
        )
        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,
            response_metrics=self.response_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,
            response_metrics=self.response_metrics,
        )

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,
        response_metrics=self.response_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,
        response_metrics=self.response_metrics,
    )

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

Raises:

Type Description
ValueError

If messages cannot be built from columns, extras, history, or a tool-injection turn.

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
    :raises ValueError: If ``messages`` cannot be built from columns, extras,
        history, or a tool-injection turn.
    """
    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: recorded messages, or system + user content.
        self._append_request_content_messages(
            arguments.body["messages"], data, **kwargs
        )

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

    _require_request_payload(
        arguments,
        endpoint="/v1/chat/completions",
        field="messages",
        sources=(
            "raw_messages_column, text_column, prefix_column, or media columns"
        ),
        columns=data.columns,
    )
    return arguments

EmbeddingsRequestHandler

Bases: OpenAIRequestHandler

Request handler for OpenAI-style embeddings endpoints.

Handles embeddings requests which do not support streaming and return embedding vectors instead of generated text. Processes input text into embeddings for performance benchmarking.

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

    Handles embeddings requests which do not support streaming and return
    embedding vectors instead of generated text. Processes input text into
    embeddings for performance benchmarking.
    """

    def format(
        self,
        data: GenerationRequest,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,  # noqa: ARG002
        **kwargs: Any,
    ) -> GenerationRequestArguments:
        """
        Format the embeddings generation request.

        :param data: The generation request to format
        :param history: Request/response history (unused for embeddings)
        :param **kwargs: Additional keyword arguments (model, encoding_format, etc.)
        :return: The formatted request arguments
        :raises ValueError: If ``input`` cannot be built from ``text_column`` or extras.
        """
        arguments = GenerationRequestArguments()
        arguments.body = {}
        arguments.stream = False  # Embeddings never stream

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

        # Build input from text columns
        input_texts = []
        for text in data.columns.get("text_column", []):
            if text:
                input_texts.append(text)

        # Use single string if only one text, otherwise list
        if len(input_texts) == 1:
            arguments.body["input"] = input_texts[0]
        else:
            arguments.body["input"] = input_texts

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

        _require_request_payload(
            arguments,
            endpoint="/v1/embeddings",
            field="input",
            sources="text_column",
            columns=data.columns,
        )
        return arguments

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

        :param request: Original generation request
        :param arguments: Request arguments used
        :param response: Raw API response data
        :return: GenerationResponse with embeddings data
        """
        # Extract usage data
        usage = response.get("usage", {})

        # Build response (no text output for embeddings)
        return GenerationResponse(
            request_id=request.request_id,
            request_args=arguments.model_dump_json(),
            text="",  # Embeddings don't generate text
            input_metrics=UsageMetrics(
                text_tokens=usage.get("prompt_tokens", 0),
            ),
            # output_metrics defaults to UsageMetrics() with all None values
        )

    def add_streaming_line(self, line: str) -> int | None:  # noqa: ARG002
        """
        Embeddings do not support streaming.

        :param line: Streaming line (unused)
        :return: None (not supported)
        :raises NotImplementedError: Embeddings never stream
        """
        raise NotImplementedError("Embeddings do not support streaming")

    def compile_streaming(  # noqa: ARG002
        self, request: GenerationRequest, arguments: GenerationRequestArguments
    ) -> GenerationResponse:
        """
        Embeddings do not support streaming.

        :param request: Generation request (unused)
        :param arguments: Request arguments (unused)
        :return: Never returns
        :raises NotImplementedError: Embeddings never stream
        """
        raise NotImplementedError("Embeddings do not support streaming")

add_streaming_line(line)

Embeddings do not support streaming.

Parameters:

Name Type Description Default
line str

Streaming line (unused)

required

Returns:

Type Description
int | None

None (not supported)

Raises:

Type Description
NotImplementedError

Embeddings never stream

Source code in src/guidellm/backends/openai/request_handlers.py
def add_streaming_line(self, line: str) -> int | None:  # noqa: ARG002
    """
    Embeddings do not support streaming.

    :param line: Streaming line (unused)
    :return: None (not supported)
    :raises NotImplementedError: Embeddings never stream
    """
    raise NotImplementedError("Embeddings do not support streaming")

compile_non_streaming(request, arguments, response)

Process a complete non-streaming embeddings API response.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request

required
arguments GenerationRequestArguments

Request arguments used

required
response Any

Raw API response data

required

Returns:

Type Description
GenerationResponse

GenerationResponse with embeddings data

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 embeddings API response.

    :param request: Original generation request
    :param arguments: Request arguments used
    :param response: Raw API response data
    :return: GenerationResponse with embeddings data
    """
    # Extract usage data
    usage = response.get("usage", {})

    # Build response (no text output for embeddings)
    return GenerationResponse(
        request_id=request.request_id,
        request_args=arguments.model_dump_json(),
        text="",  # Embeddings don't generate text
        input_metrics=UsageMetrics(
            text_tokens=usage.get("prompt_tokens", 0),
        ),
        # output_metrics defaults to UsageMetrics() with all None values
    )

compile_streaming(request, arguments)

Embeddings do not support streaming.

Parameters:

Name Type Description Default
request GenerationRequest

Generation request (unused)

required
arguments GenerationRequestArguments

Request arguments (unused)

required

Returns:

Type Description
GenerationResponse

Never returns

Raises:

Type Description
NotImplementedError

Embeddings never stream

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_streaming(  # noqa: ARG002
    self, request: GenerationRequest, arguments: GenerationRequestArguments
) -> GenerationResponse:
    """
    Embeddings do not support streaming.

    :param request: Generation request (unused)
    :param arguments: Request arguments (unused)
    :return: Never returns
    :raises NotImplementedError: Embeddings never stream
    """
    raise NotImplementedError("Embeddings do not support streaming")

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

Format the embeddings generation request.

Parameters:

Name Type Description Default
data GenerationRequest

The generation request to format

required
history HistoryT[GenerationRequest, GenerationResponse] | None

Request/response history (unused for embeddings)

None
**kwargs Any

Additional keyword arguments (model, encoding_format, etc.)

{}

Returns:

Type Description
GenerationRequestArguments

The formatted request arguments

Raises:

Type Description
ValueError

If input cannot be built from text_column or extras.

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

    :param data: The generation request to format
    :param history: Request/response history (unused for embeddings)
    :param **kwargs: Additional keyword arguments (model, encoding_format, etc.)
    :return: The formatted request arguments
    :raises ValueError: If ``input`` cannot be built from ``text_column`` or extras.
    """
    arguments = GenerationRequestArguments()
    arguments.body = {}
    arguments.stream = False  # Embeddings never stream

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

    # Build input from text columns
    input_texts = []
    for text in data.columns.get("text_column", []):
        if text:
            input_texts.append(text)

    # Use single string if only one text, otherwise list
    if len(input_texts) == 1:
        arguments.body["input"] = input_texts[0]
    else:
        arguments.body["input"] = input_texts

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

    _require_request_payload(
        arguments,
        endpoint="/v1/embeddings",
        field="input",
        sources="text_column",
        columns=data.columns,
    )
    return arguments

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()

PoolingRequestHandler

Bases: ChatCompletionsRequestHandler

Request handler for vLLM pooling endpoints.

Inherits from ChatCompletionsRequestHandler and overrides format() to handle pooling-specific request structure with nested data fields.

Source code in src/guidellm/backends/openai/request_handlers.py
@OpenAIRequestHandlerFactory.register("/pooling")
class PoolingRequestHandler(ChatCompletionsRequestHandler):
    """
    Request handler for vLLM pooling endpoints.

    Inherits from ChatCompletionsRequestHandler and overrides format() to handle
    pooling-specific request structure with nested data fields.
    """

    def post_validation(self, response: GenerationResponse) -> None:  # noqa: ARG002
        """Pooling responses produce non-text output; skip validation."""

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

        :param data: The generation request to format
        :param history: Optional request/response history (unused for pooling)
        :param **kwargs: Additional keyword arguments for request formatting
        :return: The formatted request arguments
        """
        arguments = GenerationRequestArguments()
        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
            arguments.body["stream_options"] = {
                "include_usage": True,
                "continuous_usage_stats": True,
            }

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

        # Build pooling request body from text_column (which contains the dict)
        pooling_data = data.columns.get("pooling_column", [])
        if pooling_data and isinstance(pooling_data[0], dict):
            # Use the dict directly from text_column
            pooling_entry = pooling_data[0]
            if "data" in pooling_entry:
                arguments.body["data"] = pooling_entry["data"]
            if "priority" in pooling_entry:
                arguments.body["priority"] = pooling_entry["priority"]

        return arguments

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

Format the pooling generation request into the appropriate structure.

Parameters:

Name Type Description Default
data GenerationRequest

The generation request to format

required
history HistoryT[GenerationRequest, GenerationResponse] | None

Optional request/response history (unused for pooling)

None
**kwargs Any

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,  # noqa: ARG002
    **kwargs: Any,
) -> GenerationRequestArguments:
    """
    Format the pooling generation request into the appropriate structure.

    :param data: The generation request to format
    :param history: Optional request/response history (unused for pooling)
    :param **kwargs: Additional keyword arguments for request formatting
    :return: The formatted request arguments
    """
    arguments = GenerationRequestArguments()
    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
        arguments.body["stream_options"] = {
            "include_usage": True,
            "continuous_usage_stats": True,
        }

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

    # Build pooling request body from text_column (which contains the dict)
    pooling_data = data.columns.get("pooling_column", [])
    if pooling_data and isinstance(pooling_data[0], dict):
        # Use the dict directly from text_column
        pooling_entry = pooling_data[0]
        if "data" in pooling_entry:
            arguments.body["data"] = pooling_entry["data"]
        if "priority" in pooling_entry:
            arguments.body["priority"] = pooling_entry["priority"]

    return arguments

post_validation(response)

Pooling responses produce non-text output; skip validation.

Source code in src/guidellm/backends/openai/request_handlers.py
def post_validation(self, response: GenerationResponse) -> None:  # noqa: ARG002
    """Pooling responses produce non-text output; skip validation."""

RealtimeTranscriptionWSRequestHandler

Bases: OpenAIWSRequestHandler

WebSocket handler for realtime audio transcription (/v1/realtime).

Concrete :class:OpenAIWSRequestHandler for vLLM realtime transcription: validates audio input in format(), interprets transcription events in add_streaming_event(), and assembles the final GenerationResponse with audio metrics in compile_streaming().

Source code in src/guidellm/backends/openai/request_handlers.py
@OpenAIWSRequestHandlerFactory.register("/v1/realtime")
class RealtimeTranscriptionWSRequestHandler(OpenAIWSRequestHandler):
    """
    WebSocket handler for realtime audio transcription (``/v1/realtime``).

    Concrete :class:`OpenAIWSRequestHandler` for vLLM realtime transcription:
    validates audio input in ``format()``, interprets transcription events in
    ``add_streaming_event()``, and assembles the final ``GenerationResponse``
    with audio metrics in ``compile_streaming()``.
    """

    def __init__(self) -> None:
        """
        Initialize streaming state for one realtime transcription request.

        Sets up audio metrics extraction and accumulators for transcription text
        and usage data from WebSocket event frames.
        """
        self._audio_metrics = AudioRequestHandler()
        self._streaming_texts: list[str] = []
        self._streaming_usage: dict[str, int | dict[str, int]] | None = None

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

    @staticmethod
    def extract_single_audio(data: GenerationRequest) -> dict[str, Any]:
        """Return the single ``audio_column`` entry required for realtime streaming."""
        audio_columns = data.columns.get("audio_column", [])
        if len(audio_columns) != 1:
            raise ValueError(
                "Realtime WebSocket transcription expects exactly one audio_column "
                f"entry; got {len(audio_columns)}."
            )
        return audio_columns[0]

    def format(
        self,
        data: GenerationRequest,
        response: GenerationResponse | None = None,
        history: HistoryT[GenerationRequest, GenerationResponse] | None = None,
        **kwargs: Any,
    ) -> GenerationRequestArguments:
        """
        Validate the request and build metadata for ``request_args``.

        Validates the audio column once, PCM-encodes it into base64 chunks, and
        attaches those chunks to ``body`` for the WebSocket backend to send.

        :param data: Must contain exactly one ``audio_column`` entry.
        :param response: Not supported (raises if provided).
        :param history: Not supported (raises if provided).
        :param kwargs: Must include ``model`` and ``websocket_path``.
        :return: Arguments with wire-protocol metadata and ``audio_chunks`` in ``body``.
        """
        if history or response:
            raise ValueError(
                "RealtimeTranscriptionWSRequestHandler does not support multiturn."
            )
        audio_entry = self.extract_single_audio(data)
        model = kwargs.get("model")
        if model is None:
            raise ValueError("model is required for realtime WebSocket format()")
        websocket_path = kwargs.get("websocket_path")
        if websocket_path is None:
            raise ValueError(
                "websocket_path is required for realtime WebSocket format()"
            )
        chunk_samples = kwargs.get("chunk_samples", 3200)
        audio_chunks = pcm16_append_b64_chunks(
            audio_entry,
            chunk_samples=chunk_samples,
        )
        arguments = GenerationRequestArguments()
        arguments.body = {
            "model": model,
            "websocket_path": websocket_path,
            "chunk_samples": chunk_samples,
            WS_AUDIO_CHUNKS_BODY_KEY: audio_chunks,
        }
        return arguments

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

        :param event: Parsed JSON dict from a WebSocket text frame.
        :return: Classified streaming update for the generic WS backend loop.
        :raises RuntimeError: On ``error`` type events.
        """
        event_type = event.get("type")
        if event_type == "transcription.delta":
            delta = event.get("delta") or ""
            self._streaming_texts.append(delta)
            if delta:
                return WSStreamingEventResult(
                    kind=WSEventResult.CONTENT, content_tokens=1
                )
            return WSStreamingEventResult(kind=WSEventResult.REQUEST_ITERATION)
        if event_type == "transcription.done":
            self._streaming_usage = event.get("usage")
            final_text = event.get("text")
            # Server may send only ``text`` on done, replacing accumulated deltas.
            if final_text:
                self._streaming_texts = [final_text]
            return WSStreamingEventResult(kind=WSEventResult.STREAM_END)
        if event_type == "error":
            err = event.get("error")
            raise RuntimeError(format_ws_error(err))
        return WSStreamingEventResult(kind=WSEventResult.IGNORED)

    def compile_streaming(
        self, request: GenerationRequest, arguments: GenerationRequestArguments
    ) -> GenerationResponse:
        """
        Assemble accumulated transcription text and usage into a response.

        :param request: Original generation request.
        :param arguments: Request arguments from format().
        :return: Final GenerationResponse with audio metrics.
        """
        full_text = self.streaming_text
        inp, outp = self._audio_metrics.extract_metrics(
            self._streaming_usage, full_text
        )
        body = dict(arguments.body or {})
        body.pop(WS_AUDIO_CHUNKS_BODY_KEY, None)
        request_args = arguments.model_copy(update={"body": body or None})
        return GenerationResponse(
            request_id=request.request_id,
            request_args=request_args.model_dump_json(),
            text=full_text,
            input_metrics=inp,
            output_metrics=outp,
        )

streaming_text property

Accumulated transcription text from processed events.

__init__()

Initialize streaming state for one realtime transcription request.

Sets up audio metrics extraction and accumulators for transcription text and usage data from WebSocket event frames.

Source code in src/guidellm/backends/openai/request_handlers.py
def __init__(self) -> None:
    """
    Initialize streaming state for one realtime transcription request.

    Sets up audio metrics extraction and accumulators for transcription text
    and usage data from WebSocket event frames.
    """
    self._audio_metrics = AudioRequestHandler()
    self._streaming_texts: list[str] = []
    self._streaming_usage: dict[str, int | dict[str, int]] | None = None

add_streaming_event(event)

Process one JSON event from the vLLM realtime WebSocket.

Parameters:

Name Type Description Default
event dict[str, Any]

Parsed JSON dict from a WebSocket text frame.

required

Returns:

Type Description
WSStreamingEventResult

Classified streaming update for the generic WS backend loop.

Raises:

Type Description
RuntimeError

On error type 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 from the vLLM realtime WebSocket.

    :param event: Parsed JSON dict from a WebSocket text frame.
    :return: Classified streaming update for the generic WS backend loop.
    :raises RuntimeError: On ``error`` type events.
    """
    event_type = event.get("type")
    if event_type == "transcription.delta":
        delta = event.get("delta") or ""
        self._streaming_texts.append(delta)
        if delta:
            return WSStreamingEventResult(
                kind=WSEventResult.CONTENT, content_tokens=1
            )
        return WSStreamingEventResult(kind=WSEventResult.REQUEST_ITERATION)
    if event_type == "transcription.done":
        self._streaming_usage = event.get("usage")
        final_text = event.get("text")
        # Server may send only ``text`` on done, replacing accumulated deltas.
        if final_text:
            self._streaming_texts = [final_text]
        return WSStreamingEventResult(kind=WSEventResult.STREAM_END)
    if event_type == "error":
        err = event.get("error")
        raise RuntimeError(format_ws_error(err))
    return WSStreamingEventResult(kind=WSEventResult.IGNORED)

compile_streaming(request, arguments)

Assemble accumulated transcription text and usage into a response.

Parameters:

Name Type Description Default
request GenerationRequest

Original generation request.

required
arguments GenerationRequestArguments

Request arguments from format().

required

Returns:

Type Description
GenerationResponse

Final GenerationResponse with audio metrics.

Source code in src/guidellm/backends/openai/request_handlers.py
def compile_streaming(
    self, request: GenerationRequest, arguments: GenerationRequestArguments
) -> GenerationResponse:
    """
    Assemble accumulated transcription text and usage into a response.

    :param request: Original generation request.
    :param arguments: Request arguments from format().
    :return: Final GenerationResponse with audio metrics.
    """
    full_text = self.streaming_text
    inp, outp = self._audio_metrics.extract_metrics(
        self._streaming_usage, full_text
    )
    body = dict(arguments.body or {})
    body.pop(WS_AUDIO_CHUNKS_BODY_KEY, None)
    request_args = arguments.model_copy(update={"body": body or None})
    return GenerationResponse(
        request_id=request.request_id,
        request_args=request_args.model_dump_json(),
        text=full_text,
        input_metrics=inp,
        output_metrics=outp,
    )

extract_single_audio(data) staticmethod

Return the single audio_column entry required for realtime streaming.

Source code in src/guidellm/backends/openai/request_handlers.py
@staticmethod
def extract_single_audio(data: GenerationRequest) -> dict[str, Any]:
    """Return the single ``audio_column`` entry required for realtime streaming."""
    audio_columns = data.columns.get("audio_column", [])
    if len(audio_columns) != 1:
        raise ValueError(
            "Realtime WebSocket transcription expects exactly one audio_column "
            f"entry; got {len(audio_columns)}."
        )
    return audio_columns[0]

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

Validate the request and build metadata for request_args.

Validates the audio column once, PCM-encodes it into base64 chunks, and attaches those chunks to body for the WebSocket backend to send.

Parameters:

Name Type Description Default
data GenerationRequest

Must contain exactly one audio_column entry.

required
response GenerationResponse | None

Not supported (raises if provided).

None
history HistoryT[GenerationRequest, GenerationResponse] | None

Not supported (raises if provided).

None
kwargs Any

Must include model and websocket_path.

{}

Returns:

Type Description
GenerationRequestArguments

Arguments with wire-protocol metadata and audio_chunks in body.

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: Any,
) -> GenerationRequestArguments:
    """
    Validate the request and build metadata for ``request_args``.

    Validates the audio column once, PCM-encodes it into base64 chunks, and
    attaches those chunks to ``body`` for the WebSocket backend to send.

    :param data: Must contain exactly one ``audio_column`` entry.
    :param response: Not supported (raises if provided).
    :param history: Not supported (raises if provided).
    :param kwargs: Must include ``model`` and ``websocket_path``.
    :return: Arguments with wire-protocol metadata and ``audio_chunks`` in ``body``.
    """
    if history or response:
        raise ValueError(
            "RealtimeTranscriptionWSRequestHandler does not support multiturn."
        )
    audio_entry = self.extract_single_audio(data)
    model = kwargs.get("model")
    if model is None:
        raise ValueError("model is required for realtime WebSocket format()")
    websocket_path = kwargs.get("websocket_path")
    if websocket_path is None:
        raise ValueError(
            "websocket_path is required for realtime WebSocket format()"
        )
    chunk_samples = kwargs.get("chunk_samples", 3200)
    audio_chunks = pcm16_append_b64_chunks(
        audio_entry,
        chunk_samples=chunk_samples,
    )
    arguments = GenerationRequestArguments()
    arguments.body = {
        "model": model,
        "websocket_path": websocket_path,
        "chunk_samples": chunk_samples,
        WS_AUDIO_CHUNKS_BODY_KEY: audio_chunks,
    }
    return arguments

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
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
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
@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:
            self._append_request_content_input_items(items, req, **kwargs)

            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`` from ``tool_choice_column`` when present,
           otherwise ``"required"``, or ``"none"`` on turns that must not
           emit tool calls.
        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", _dataset_tool_choice(data))

        _constrain_tool_call_body(body, data, "max_output_tokens")

    def _append_request_content_input_items(
        self,
        items: list[dict[str, Any]],
        req: GenerationRequest,
        **kwargs,
    ) -> None:
        """Append current-turn content as Responses ``input`` items.

        ``text_column`` / media wrap as a user message. ``raw_messages_column``
        is ignored here; a missing ``input`` after format raises.

        :param items: Input item list to extend in place.
        :param req: Request whose columns supply the current turn.
        :param kwargs: Forwarded format kwargs (``extras`` for multimodal).
        """
        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})

    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":
            self._append_request_content_input_items(input_items, data, **kwargs)

        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)

        _require_request_payload(
            arguments,
            endpoint="/v1/responses",
            field="input",
            sources="text_column or media columns",
            columns=data.columns,
        )
        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 {}

        line = line[len("data:") :].strip()
        if line == "[DONE]":
            return None

        data = json.loads(line)
        _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 {}
            if event_type == "response.failed":
                _check_streaming_error(resp)
            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
            ),
            cached_tokens=input_details.get("cached_tokens"),
            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 {}

    line = line[len("data:") :].strip()
    if line == "[DONE]":
        return None

    data = json.loads(line)
    _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
        self.response_metrics: dict[str, Any] | 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
        :raises ValueError: If ``prompt`` cannot be built from columns, extras,
            or history.
        """
        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)

        _require_request_payload(
            arguments,
            endpoint="/v1/completions",
            field="prompt",
            sources="text_column or prefix_column",
            columns=data.columns,
        )
        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,
            response_metrics=self.response_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,
            response_metrics=self.response_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 not line or not (line := line.strip()) or not line.startswith("data:"):
            return {}

        line = line[len("data:") :].strip()
        if line == "[DONE]":
            return None

        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.

        A backend may report its own per-request metrics beside `usage`; vLLM does,
        under `metrics`. Those are recorded here rather than returned, so every handler
        picks them up without widening this signature.

        :param response: Complete API response containing choices and usage data
        :return: Tuple of choices list and usage dictionary
        """
        if isinstance(metrics := response.get("metrics"), dict):
            self.response_metrics = metrics
        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
            ),
            cached_tokens=input_details.get("cached_tokens"),
            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
    self.response_metrics: dict[str, Any] | 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,
        response_metrics=self.response_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,
        response_metrics=self.response_metrics,
    )

extract_choices_and_usage(response)

Extract choices and usage data from the API response.

A backend may report its own per-request metrics beside usage; vLLM does, under metrics. Those are recorded here rather than returned, so every handler picks them up without widening this signature.

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.

    A backend may report its own per-request metrics beside `usage`; vLLM does,
    under `metrics`. Those are recorded here rather than returned, so every handler
    picks them up without widening this signature.

    :param response: Complete API response containing choices and usage data
    :return: Tuple of choices list and usage dictionary
    """
    if isinstance(metrics := response.get("metrics"), dict):
        self.response_metrics = metrics
    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 not line or not (line := line.strip()) or not line.startswith("data:"):
        return {}

    line = line[len("data:") :].strip()
    if line == "[DONE]":
        return None

    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
        ),
        cached_tokens=input_details.get("cached_tokens"),
        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

Raises:

Type Description
ValueError

If prompt cannot be built from columns, extras, or history.

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
    :raises ValueError: If ``prompt`` cannot be built from columns, extras,
        or history.
    """
    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)

    _require_request_payload(
        arguments,
        endpoint="/v1/completions",
        field="prompt",
        sources="text_column or prefix_column",
        columns=data.columns,
    )
    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)

ToolCall

Bases: BaseModel

A single tool call from an OpenAI-compatible API response.

Source code in src/guidellm/schemas/base/tool_call.py
class ToolCall(BaseModel):
    """A single tool call from an OpenAI-compatible API response."""

    id: str = ""
    type: str = "function"
    function: ToolCallFunction = Field(default_factory=ToolCallFunction)

ToolCallFunction

Bases: BaseModel

Function name and arguments for a single tool call.

Source code in src/guidellm/schemas/base/tool_call.py
class ToolCallFunction(BaseModel):
    """Function name and arguments for a single tool call."""

    name: str = ""
    arguments: str = ""

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