serving.py 83.7 KB
Newer Older
1
2
3
4
5
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import asyncio
import time
6
import uuid
7
from collections import deque
8
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Mapping, Sequence
9
from contextlib import AsyncExitStack
10
from copy import copy
11
from http import HTTPStatus
12
from typing import Any, Final
13
14

from fastapi import Request
15
from openai.types.responses import (
16
17
    ResponseContentPartAddedEvent,
    ResponseContentPartDoneEvent,
18
19
    ResponseFunctionCallArgumentsDeltaEvent,
    ResponseFunctionCallArgumentsDoneEvent,
20
    ResponseFunctionToolCall,
21
    ResponseFunctionToolCallItem,
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    ResponseOutputItem,
    ResponseOutputItemAddedEvent,
    ResponseOutputItemDoneEvent,
    ResponseOutputMessage,
    ResponseOutputText,
    ResponseReasoningItem,
    ResponseReasoningTextDeltaEvent,
    ResponseReasoningTextDoneEvent,
    ResponseStatus,
    ResponseTextDeltaEvent,
    ResponseTextDoneEvent,
    response_text_delta_event,
)
from openai.types.responses.response_output_text import Logprob, LogprobTopLogprob
36
from openai.types.responses.response_reasoning_item import (
37
38
    Content as ResponseReasoningTextContent,
)
39
from openai.types.responses.tool import Mcp, Tool
40
from openai_harmony import Message as OpenAIHarmonyMessage
41
from pydantic import TypeAdapter
42

43
from vllm import envs
44
from vllm.config.utils import replace
45
from vllm.engine.protocol import EngineClient
46
47
48
from vllm.entrypoints.chat_utils import (
    ChatCompletionMessageParam,
    ChatTemplateContentFormatOption,
49
    get_tool_call_id_type,
50
)
51
from vllm.entrypoints.logger import RequestLogger
52
from vllm.entrypoints.mcp.tool_server import ToolServer
53
from vllm.entrypoints.openai.engine.protocol import (
54
55
56
57
    DeltaMessage,
    ErrorResponse,
    RequestResponseMetadata,
)
58
from vllm.entrypoints.openai.engine.serving import (
59
60
61
    GenerationError,
    OpenAIServing,
)
62
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
63
64
65
66
67
68
69
70
from vllm.entrypoints.openai.parser.harmony_utils import (
    get_developer_message,
    get_stop_tokens_for_assistant_actions,
    get_system_message,
    get_user_message,
    has_custom_tools,
    render_for_completion,
)
71
72
73
74
75
76
77
from vllm.entrypoints.openai.responses.context import (
    ConversationContext,
    HarmonyContext,
    ParsableContext,
    SimpleContext,
    StreamingHarmonyContext,
)
78
79
80
81
82
83
from vllm.entrypoints.openai.responses.harmony import (
    construct_harmony_previous_input_messages,
    harmony_to_response_output,
    parser_state_to_response_output,
    response_input_to_harmony,
)
84
85
86
87
88
89
from vllm.entrypoints.openai.responses.protocol import (
    InputTokensDetails,
    OutputTokensDetails,
    ResponseCompletedEvent,
    ResponseCreatedEvent,
    ResponseInProgressEvent,
90
    ResponseInputOutputItem,
91
    ResponseInputOutputMessage,
92
93
    ResponseReasoningPartAddedEvent,
    ResponseReasoningPartDoneEvent,
94
95
96
97
98
    ResponsesRequest,
    ResponsesResponse,
    ResponseUsage,
    StreamingResponsesResponse,
)
99
from vllm.entrypoints.openai.responses.streaming_events import (
100
    StreamingState,
101
102
103
104
    emit_content_delta_events,
    emit_previous_item_done_events,
    emit_tool_action_events,
)
105
from vllm.entrypoints.openai.responses.utils import (
106
    construct_input_messages,
107
    construct_tool_dicts,
108
109
    extract_tool_types,
)
110
from vllm.entrypoints.serve.render.serving import OpenAIServingRender
111
from vllm.entrypoints.utils import get_max_tokens
112
from vllm.exceptions import VLLMValidationError
113
from vllm.inputs import EngineInput, tokens_input
114
from vllm.logger import init_logger
115
116
from vllm.logprobs import Logprob as SampleLogprob
from vllm.logprobs import SampleLogprobs
117
from vllm.lora.request import LoRARequest
118
from vllm.outputs import CompletionOutput
119
from vllm.parser import ParserManager
120
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
121
from vllm.tokenizers import TokenizerLike
122
from vllm.tool_parsers import ToolParser
123
from vllm.utils import random_uuid
124
from vllm.utils.collection_utils import as_list
125
126
127
128

logger = init_logger(__name__)


129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def _extract_allowed_tools_from_mcp_requests(
    tools: list[Tool],
) -> dict[str, list[str] | None]:
    """
    Extract allowed_tools mapping from MCP tool requests.

    Returns a dictionary mapping server_label to allowed_tools list.
    Handles both list format and McpAllowedToolsMcpToolFilter object format.

    Special handling:
    - If allowed_tools is None, returns None (allows all tools)
    - If allowed_tools contains "*", returns None (allows all tools)
    - Otherwise, returns the list of specific tool names

    This function can be reused for both harmony and non-harmony MCP calls.
    """
    allowed_tools_map: dict[str, list[str] | None] = {}
    for tool in tools:
        if not isinstance(tool, Mcp):
            continue

        # allowed_tools can be a list or an object with tool_names
        # Extract the actual list of tool names
        allowed_tools_val = None
        if tool.allowed_tools is not None:
            if isinstance(tool.allowed_tools, list):
                allowed_tools_val = tool.allowed_tools
            elif hasattr(tool.allowed_tools, "tool_names"):
                # It's an McpAllowedToolsMcpToolFilter object
                allowed_tools_val = tool.allowed_tools.tool_names

        # Normalize "*" to None (both mean "allow all tools")
        if allowed_tools_val is not None and "*" in allowed_tools_val:
            allowed_tools_val = None

        allowed_tools_map[tool.server_label] = allowed_tools_val
    return allowed_tools_map


168
169
170
171
172
class OpenAIServingResponses(OpenAIServing):
    def __init__(
        self,
        engine_client: EngineClient,
        models: OpenAIServingModels,
173
        openai_serving_render: OpenAIServingRender,
174
        *,
175
176
        request_logger: RequestLogger | None,
        chat_template: str | None,
177
178
179
180
        chat_template_content_format: ChatTemplateContentFormatOption,
        return_tokens_as_token_ids: bool = False,
        reasoning_parser: str = "",
        enable_auto_tools: bool = False,
181
182
        tool_parser: str | None = None,
        tool_server: ToolServer | None = None,
183
184
        enable_prompt_tokens_details: bool = False,
        enable_force_include_usage: bool = False,
185
        enable_log_outputs: bool = False,
186
187
188
189
190
191
192
193
    ) -> None:
        super().__init__(
            engine_client=engine_client,
            models=models,
            request_logger=request_logger,
            return_tokens_as_token_ids=return_tokens_as_token_ids,
        )

194
        self.openai_serving_render = openai_serving_render
195
196
        self.chat_template = chat_template
        self.chat_template_content_format: Final = chat_template_content_format
197
        self.enable_log_outputs = enable_log_outputs
198

199
200
201
202
203
204
205
        # Set up the unified parser - either a unified parser or fall back to
        # separate parsers accessed through the parser interface
        self.parser = ParserManager.get_parser(
            tool_parser_name=tool_parser,
            reasoning_parser_name=reasoning_parser,
            enable_auto_tools=enable_auto_tools,
            model_name=self.model_config.model,
206
        )
207
208
        self.enable_prompt_tokens_details = enable_prompt_tokens_details
        self.enable_force_include_usage = enable_force_include_usage
209

210
        self.default_sampling_params = self.model_config.get_diff_sampling_param()
211
212
213
214
215
216
        mc = self.model_config
        self.override_max_tokens = (
            self.default_sampling_params.get("max_tokens")
            if mc.generation_config not in ("auto", "vllm")
            else getattr(mc, "override_generation_config", {}).get("max_new_tokens")
        )
217

218
219
220
221
222
        # If False (default), the "store" option is (silently) ignored and the
        # response is not stored. If True, the response is stored in memory.
        # NOTE(woosuk): This may not be intuitive for users, as the default
        # behavior in OpenAI's Responses API is to store the response, but
        # vLLM's default behavior is not.
223
        self.enable_store = envs.VLLM_ENABLE_RESPONSES_API_STORE
224
225
226
227
        if self.enable_store:
            logger.warning_once(
                "`VLLM_ENABLE_RESPONSES_API_STORE` is enabled. This may "
                "cause a memory leak since we never remove responses from "
228
229
                "the store."
            )
230

231
        self.use_harmony = self.model_config.hf_config.model_type == "gpt_oss"
232
        if self.use_harmony:
233
234
235
236
            logger.warning(
                "For gpt-oss, we ignore --enable-auto-tool-choice "
                "and always enable tool use."
            )
237
238
239
240
241
            # OpenAI models have two EOS-like tokens: <|return|> and <|call|>.
            # We need to add them to the stop token ids.
            if "stop_token_ids" not in self.default_sampling_params:
                self.default_sampling_params["stop_token_ids"] = []
            self.default_sampling_params["stop_token_ids"].extend(
242
243
                get_stop_tokens_for_assistant_actions()
            )
244

245
        self.tool_call_id_type = get_tool_call_id_type(self.model_config)
246

247
        self.enable_auto_tools = enable_auto_tools
248
        # HACK(woosuk): This is a hack. We should use a better store.
249
250
        # FIXME: If enable_store=True, this may cause a memory leak since we
        # never remove responses from the store.
251
252
253
254
        self.response_store: dict[str, ResponsesResponse] = {}
        self.response_store_lock = asyncio.Lock()

        # HACK(woosuk): This is a hack. We should use a better store.
255
256
        # FIXME: If enable_store=True, this may cause a memory leak since we
        # never remove messages from the store.
257
258
        self.msg_store: dict[str, list[ChatCompletionMessageParam]] = {}

259
260
261
        # HACK(wuhang): This is a hack. We should use a better store.
        # FIXME: If enable_store=True, this may cause a memory leak since we
        # never remove events from the store.
262
263
264
        self.event_store: dict[
            str, tuple[deque[StreamingResponsesResponse], asyncio.Event]
        ] = {}
265

266
267
        self.background_tasks: dict[str, asyncio.Task] = {}

268
269
        self.tool_server = tool_server

270
    def _validate_generator_input(
271
        self,
272
        engine_input: EngineInput,
273
    ) -> ErrorResponse | None:
274
        """Add validations to the input to the generator here."""
275
        prompt_len = self._extract_prompt_len(engine_input)
276
277
278
        max_model_len = self.model_config.max_model_len

        if prompt_len >= max_model_len:
279
            error_message = (
280
                f"The engine prompt length {prompt_len} "
281
                f"exceeds the max_model_len {max_model_len}. "
282
283
                "Please reduce prompt."
            )
284
285
286
287
            return self.create_error_response(
                err_type="invalid_request_error",
                message=error_message,
                status_code=HTTPStatus.BAD_REQUEST,
288
                param="input",
289
            )
290

291
292
        return None

293
294
295
296
297
298
299
300
    def _validate_create_responses_input(
        self, request: ResponsesRequest
    ) -> ErrorResponse | None:
        if self.use_harmony and request.is_include_output_logprobs():
            return self.create_error_response(
                err_type="invalid_request_error",
                message="logprobs are not supported with gpt-oss models",
                status_code=HTTPStatus.BAD_REQUEST,
301
                param="logprobs",
302
303
304
305
306
307
308
309
310
311
312
313
            )
        if request.store and not self.enable_store and request.background:
            return self.create_error_response(
                err_type="invalid_request_error",
                message=(
                    "This vLLM engine does not support `store=True` and "
                    "therefore does not support the background mode. To "
                    "enable these features, set the environment variable "
                    "`VLLM_ENABLE_RESPONSES_API_STORE=1` when launching "
                    "the vLLM server."
                ),
                status_code=HTTPStatus.BAD_REQUEST,
314
                param="background",
315
            )
316
317
318
319
320
321
        if request.previous_input_messages and request.previous_response_id:
            return self.create_error_response(
                err_type="invalid_request_error",
                message="Only one of `previous_input_messages` and "
                "`previous_response_id` can be set.",
                status_code=HTTPStatus.BAD_REQUEST,
322
                param="previous_response_id",
323
            )
324
325
        return None

326
327
328
    async def create_responses(
        self,
        request: ResponsesRequest,
329
330
331
332
333
334
        raw_request: Request | None = None,
    ) -> (
        AsyncGenerator[StreamingResponsesResponse, None]
        | ResponsesResponse
        | ErrorResponse
    ):
335
336
337
338
        error_check_ret = await self._check_model(request)
        if error_check_ret is not None:
            logger.error("Error with model %s", error_check_ret)
            return error_check_ret
339
340
341
        maybe_validation_error = self._validate_create_responses_input(request)
        if maybe_validation_error is not None:
            return maybe_validation_error
342
343
344
345
346
347
348

        # If the engine is dead, raise the engine's DEAD_ERROR.
        # This is required for the streaming case, where we return a
        # success status before we actually start generating text :).
        if self.engine_client.errored:
            raise self.engine_client.dead_error

349
        if request.store and not self.enable_store:
350
351
352
353
354
355
356
            # Disable the store option.
            # NOTE(woosuk): Although returning an error is possible, we opted
            # to implicitly disable store and process the request anyway, as
            # we assume most users do not intend to actually store the response
            # (i.e., their request's `store=True` just because it's the default
            # value).
            request.store = False
357

358
359
360
361
362
363
364
365
366
367
        # Handle the previous response ID.
        prev_response_id = request.previous_response_id
        if prev_response_id is not None:
            async with self.response_store_lock:
                prev_response = self.response_store.get(prev_response_id)
            if prev_response is None:
                return self._make_not_found_error(prev_response_id)
        else:
            prev_response = None

368
369
        lora_request = self._maybe_get_adapters(request)
        model_name = self.models.model_name(lora_request)
370

371
        if self.use_harmony:
372
            messages, engine_inputs = self._make_request_with_harmony(
373
374
375
                request, prev_response
            )
        else:
376
            messages, engine_inputs = await self._make_request(request, prev_response)
377

378
        request_metadata = RequestResponseMetadata(request_id=request.request_id)
379
380
381
382
        if raw_request:
            raw_request.state.request_metadata = request_metadata

        # Schedule the request and get the result generator.
383
        max_model_len = self.model_config.max_model_len
384
        generators: list[AsyncGenerator[ConversationContext, None]] = []
385

386
387
388
389
390
        # Only include builtin tools that the request actually asked for.
        # Without this filter, tools registered on the server (e.g. via
        # --tool-server demo) would be available for execution even when
        # the request didn't enable them.
        requested_tool_types = extract_tool_types(request.tools)
391
        builtin_tool_list: list[str] = []
392
        if self.tool_server is not None:
393
394
395
396
            if (
                self.tool_server.has_tool("browser")
                and "web_search_preview" in requested_tool_types
            ):
397
                builtin_tool_list.append("browser")
398
399
400
401
            if (
                self.tool_server.has_tool("python")
                and "code_interpreter" in requested_tool_types
            ):
402
                builtin_tool_list.append("python")
403
404
405
406
            if (
                self.tool_server.has_tool("container")
                and "container" in requested_tool_types
            ):
407
                builtin_tool_list.append("container")
408

409
410
411
412
413
        if self.tool_server is not None:
            available_tools = builtin_tool_list
        else:
            assert len(builtin_tool_list) == 0
            available_tools = []
414
415
        tokenizer = self.renderer.get_tokenizer()

416
417
        for engine_input in engine_inputs:
            maybe_error = self._validate_generator_input(engine_input)
418
419
420
421
422
423
            if maybe_error is not None:
                return maybe_error

            default_max_tokens = get_max_tokens(
                max_model_len,
                request.max_output_tokens,
424
                self._extract_prompt_len(engine_input),
425
426
427
                self.default_sampling_params,
                self.override_max_tokens,
            )
428

429
430
431
            sampling_params = request.to_sampling_params(
                default_max_tokens, self.default_sampling_params
            )
432

433
434
435
436
437
            trace_headers = (
                None
                if raw_request is None
                else await self._get_trace_headers(raw_request.headers)
            )
438

439
440
441
442
            context: ConversationContext
            if self.use_harmony:
                if request.stream:
                    context = StreamingHarmonyContext(messages, available_tools)
443
                else:
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
                    context = HarmonyContext(messages, available_tools)
            else:
                if envs.VLLM_USE_EXPERIMENTAL_PARSER_CONTEXT:
                    # This is a feature in development for parsing
                    # tokens during generation instead of at the end
                    context = ParsableContext(
                        response_messages=messages,
                        tokenizer=tokenizer,
                        reasoning_parser_cls=self.parser.reasoning_parser_cls
                        if self.parser
                        else None,
                        request=request,
                        tool_parser_cls=self.parser.tool_parser_cls
                        if self.parser
                        else None,
                        available_tools=available_tools,
                        chat_template=self.chat_template,
                        chat_template_content_format=self.chat_template_content_format,
                    )
                else:
                    context = SimpleContext()

            if self.parser and self.parser.reasoning_parser_cls is not None:
                reasoning_parser = self.parser.reasoning_parser_cls(tokenizer)
                if (
                    isinstance(
                        struct_out := sampling_params.structured_outputs,
                        StructuredOutputsParams,
                    )
                    and struct_out.all_non_structural_tag_constraints_none()
                ):
                    sampling_params.structured_outputs = replace(
                        struct_out,
                        structural_tag=reasoning_parser.prepare_structured_tag(
                            struct_out.structural_tag, self.tool_server
                        ),
                    )
            generator = self._generate_with_builtin_tools(
                request_id=request.request_id,
483
                engine_input=engine_input,
484
485
486
487
488
489
490
                sampling_params=sampling_params,
                context=context,
                lora_request=lora_request,
                priority=request.priority,
                trace_headers=trace_headers,
            )
            generators.append(generator)
491

492
        assert len(generators) == 1
493
        (result_generator,) = generators
494
495
496
497

        # Store the input messages.
        if request.store:
            self.msg_store[request.request_id] = messages
498

499
500
501
502
503
504
505
506
507
508
509
510
511
        if request.background:
            created_time = int(time.time())
            response = ResponsesResponse.from_request(
                request,
                sampling_params,
                model_name=model_name,
                created_time=created_time,
                output=[],
                status="queued",
                usage=None,
            )
            async with self.response_store_lock:
                self.response_store[response.id] = response
512

513
            # Run the request in the background.
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
            if request.stream:
                task = asyncio.create_task(
                    self._run_background_request_stream(
                        request,
                        sampling_params,
                        result_generator,
                        context,
                        model_name,
                        tokenizer,
                        request_metadata,
                        created_time,
                    ),
                    name=f"create_{request.request_id}",
                )
            else:
                task = asyncio.create_task(
                    self._run_background_request(
                        request,
                        sampling_params,
                        result_generator,
                        context,
                        model_name,
                        tokenizer,
                        request_metadata,
                        created_time,
                    ),
                    name=f"create_{response.id}",
                )
542

543
544
545
546
            # For cleanup.
            response_id = response.id
            self.background_tasks[response_id] = task
            task.add_done_callback(
547
548
                lambda _: self.background_tasks.pop(response_id, None)
            )
549
550

            if request.stream:
551
                return self.responses_background_stream_generator(request.request_id)
552
553
554
555
556
557
558
559
560
561
562
563
564
            return response

        if request.stream:
            return self.responses_stream_generator(
                request,
                sampling_params,
                result_generator,
                context,
                model_name,
                tokenizer,
                request_metadata,
            )

565
566
567
568
569
570
571
572
573
        return await self.responses_full_generator(
            request,
            sampling_params,
            result_generator,
            context,
            model_name,
            tokenizer,
            request_metadata,
        )
574

575
576
577
    async def _make_request(
        self,
        request: ResponsesRequest,
578
        prev_response: ResponsesResponse | None,
579
    ):
580
        tool_dicts = construct_tool_dicts(request.tools, request.tool_choice)
581
        # Construct the input messages.
582
583
584
585
586
587
        messages = construct_input_messages(
            request_instructions=request.instructions,
            request_input=request.input,
            prev_msg=self.msg_store.get(prev_response.id) if prev_response else None,
            prev_response_output=prev_response.output if prev_response else None,
        )
588

589
        _, engine_inputs = await self.openai_serving_render.preprocess_chat(
590
591
            request,
            messages,
592
593
594
            default_template=self.chat_template,
            default_template_content_format=self.chat_template_content_format,
            default_template_kwargs=None,
595
            tool_dicts=tool_dicts,
596
            tool_parser=self.parser.tool_parser_cls if self.parser else None,
597
        )
598
        return messages, engine_inputs
599

600
601
602
603
604
    async def _render_next_turn(
        self,
        request: ResponsesRequest,
        messages: list[ResponseInputOutputItem],
        tool_dicts: list[dict[str, Any]] | None,
605
        tool_parser: type[ToolParser] | None,
606
607
608
609
610
611
612
        chat_template: str | None,
        chat_template_content_format: ChatTemplateContentFormatOption,
    ):
        new_messages = construct_input_messages(
            request_input=messages,
        )

613
        _, engine_inputs = await self.openai_serving_render.preprocess_chat(
614
615
616
617
618
619
620
621
            request,
            new_messages,
            default_template=chat_template,
            default_template_content_format=chat_template_content_format,
            default_template_kwargs=None,
            tool_dicts=tool_dicts,
            tool_parser=tool_parser,
        )
622
        return engine_inputs
623
624
625
626

    async def _generate_with_builtin_tools(
        self,
        request_id: str,
627
        engine_input: EngineInput,
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
        sampling_params: SamplingParams,
        context: ConversationContext,
        lora_request: LoRARequest | None = None,
        priority: int = 0,
        trace_headers: Mapping[str, str] | None = None,
    ):
        max_model_len = self.model_config.max_model_len

        orig_priority = priority
        sub_request = 0
        while True:
            # Ensure that each sub-request has a unique request id.
            sub_request_id = f"{request_id}_{sub_request}"

            self._log_inputs(
                sub_request_id,
644
                engine_input,
645
646
647
648
649
                params=sampling_params,
                lora_request=lora_request,
            )

            generator = self.engine_client.generate(
650
                engine_input,
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
                sampling_params,
                sub_request_id,
                lora_request=lora_request,
                trace_headers=trace_headers,
                priority=priority,
            )

            async for res in generator:
                context.append_output(res)
                # NOTE(woosuk): The stop condition is handled by the engine.
                yield context

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

            # Call the tool and update the context with the result.
            tool_output = await context.call_tool()
            context.append_tool_output(tool_output)

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

            # Create inputs for the next turn.
            # Render the next prompt token ids and update sampling_params.
            if isinstance(context, (HarmonyContext, StreamingHarmonyContext)):
                token_ids = context.render_for_completion()
678
                engine_input = tokens_input(token_ids)
679
680
681

                sampling_params.max_tokens = max_model_len - len(token_ids)
            elif isinstance(context, ParsableContext):
682
                (engine_input,) = await self._render_next_turn(
683
684
685
686
687
688
689
690
691
692
693
                    context.request,
                    context.parser.response_messages,
                    context.tool_dicts,
                    context.tool_parser_cls,
                    context.chat_template,
                    context.chat_template_content_format,
                )

                sampling_params.max_tokens = get_max_tokens(
                    max_model_len,
                    context.request.max_output_tokens,
694
                    self._extract_prompt_len(engine_input),
695
696
697
698
699
700
701
702
                    self.default_sampling_params,  # type: ignore
                    self.override_max_tokens,  # type: ignore
                )

            # OPTIMIZATION
            priority = orig_priority - 1
            sub_request += 1

703
704
705
    def _make_request_with_harmony(
        self,
        request: ResponsesRequest,
706
        prev_response: ResponsesResponse | None,
707
708
709
    ):
        if request.tool_choice != "auto":
            raise NotImplementedError(
710
711
                "Only 'auto' tool_choice is supported in response API with Harmony"
            )
712

713
        arrival_time = time.time()
714
        messages = self._construct_input_messages_with_harmony(request, prev_response)
715
        prompt_token_ids = render_for_completion(messages)
716
717
        engine_input = tokens_input(prompt_token_ids, cache_salt=request.cache_salt)
        engine_input["arrival_time"] = arrival_time
718

719
        return messages, [engine_input]
720

721
722
723
724
725
726
    async def _initialize_tool_sessions(
        self,
        request: ResponsesRequest,
        context: ConversationContext,
        exit_stack: AsyncExitStack,
    ):
727
728
729
730
        # we should only initialize the tool session if the request needs tools
        if len(request.tools) == 0:
            return
        mcp_tools = {
731
            tool.server_label: tool for tool in request.tools if tool.type == "mcp"
732
        }
733
734
735
        await context.init_tool_sessions(
            self.tool_server, exit_stack, request.request_id, mcp_tools
        )
736

737
738
739
740
    async def responses_full_generator(
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
741
        result_generator: AsyncIterator[ConversationContext],
742
        context: ConversationContext,
743
        model_name: str,
744
        tokenizer: TokenizerLike,
745
        request_metadata: RequestResponseMetadata,
746
747
        created_time: int | None = None,
    ) -> ErrorResponse | ResponsesResponse:
748
749
750
        if created_time is None:
            created_time = int(time.time())

751
752
        async with AsyncExitStack() as exit_stack:
            try:
753
                await self._initialize_tool_sessions(request, context, exit_stack)
754
755
756
757
                async for _ in result_generator:
                    pass
            except asyncio.CancelledError:
                return self.create_error_response("Client disconnected")
758

759
        # NOTE: Implementation of status is still WIP, but for now
760
761
762
763
        # we guarantee that if the status is not "completed", it is accurate.
        # "completed" is implemented as the "catch-all" for now.
        status: ResponseStatus = "completed"

764
765
        input_messages: ResponseInputOutputMessage | None = None
        output_messages: ResponseInputOutputMessage | None = None
766
767
768
        if self.use_harmony:
            assert isinstance(context, HarmonyContext)
            output = self._make_response_output_items_with_harmony(context)
769
            if request.enable_response_messages:
770
771
                input_messages = context.messages[: context.num_init_messages]
                output_messages = context.messages[context.num_init_messages :]
772
            num_tool_output_tokens = context.num_tool_output_tokens
773
774
775
776
777
            if len(output) > 0:
                if context.finish_reason == "length":
                    status = "incomplete"
                elif context.finish_reason == "abort":
                    status = "cancelled"
778
779
                else:
                    self._raise_if_error(context.finish_reason, request.request_id)
780
781
            else:
                status = "incomplete"
782
        elif isinstance(context, ParsableContext):
783
            output = context.parser.make_response_output_items_from_parsable_context()
784
785

            if request.enable_response_messages:
786
787
                input_messages = context.input_messages
                output_messages = context.output_messages
788
789
790
791

            # TODO: Calculate usage.
            # assert final_res.prompt_token_ids is not None
            num_tool_output_tokens = 0
792
793
794
795

            # Check finish reason from the parser
            if context.parser.finish_reason == "length":
                status = "incomplete"
796
        else:
797
            assert isinstance(context, SimpleContext)
798
799
            # Use final_output which has accumulated text/token_ids/logprobs
            final_res = context.final_output
800
801
802
803
            assert final_res is not None
            assert len(final_res.outputs) == 1
            final_output = final_res.outputs[0]

804
805
806
            # finish_reason='error' indicates retryable internal error
            self._raise_if_error(final_output.finish_reason, request.request_id)

807
808
809
810
            # Check if generation was stopped due to max_tokens
            if final_output.finish_reason == "length":
                status = "incomplete"

811
            output = self._make_response_output_items(request, final_output, tokenizer)
812

813
            if request.enable_response_messages:
814
815
816
                input_messages = context.input_messages
                output_messages = context.output_messages

817
818
            # Calculate usage.
            assert final_res.prompt_token_ids is not None
819
820
            num_tool_output_tokens = 0

821
        assert isinstance(context, (SimpleContext, HarmonyContext, ParsableContext))
822
823
824
825
        num_prompt_tokens = context.num_prompt_tokens
        num_generated_tokens = context.num_output_tokens
        num_cached_tokens = context.num_cached_tokens
        num_reasoning_tokens = context.num_reasoning_tokens
826
827
828
829
830
831
832
833
834
835
836
837
838
        # For text-based reasoning parsers (e.g., <think>...</think>),
        # HarmonyContext already counts reasoning tokens via channels.
        # For Simple/Parsable contexts, derive reasoning_tokens from
        # accumulated output token IDs using the parser if not already set.
        if (
            num_reasoning_tokens == 0
            and self.parser is not None
            and self.parser.reasoning_parser_cls is not None
            and isinstance(context, (SimpleContext, ParsableContext))
        ):
            reasoning_parser = self.parser.reasoning_parser_cls(tokenizer)
            accumulated = getattr(context, "_accumulated_token_ids", []) or []
            num_reasoning_tokens = reasoning_parser.count_reasoning_tokens(accumulated)
839
840
841
842

        usage = ResponseUsage(
            input_tokens=num_prompt_tokens,
            output_tokens=num_generated_tokens,
843
            total_tokens=num_prompt_tokens + num_generated_tokens,
844
845
846
847
848
849
850
851
852
            input_tokens_details=InputTokensDetails(
                cached_tokens=num_cached_tokens,
                input_tokens_per_turn=[
                    turn.input_tokens for turn in context.all_turn_metrics
                ],
                cached_tokens_per_turn=[
                    turn.cached_input_tokens for turn in context.all_turn_metrics
                ],
            ),
853
            output_tokens_details=OutputTokensDetails(
854
                reasoning_tokens=num_reasoning_tokens,
855
                tool_output_tokens=num_tool_output_tokens,
856
857
858
859
860
861
                output_tokens_per_turn=[
                    turn.output_tokens for turn in context.all_turn_metrics
                ],
                tool_output_tokens_per_turn=[
                    turn.tool_output_tokens for turn in context.all_turn_metrics
                ],
862
            ),
863
864
865
866
        )
        response = ResponsesResponse.from_request(
            request,
            sampling_params,
867
868
            input_messages=input_messages,
            output_messages=output_messages,
869
870
871
            model_name=model_name,
            created_time=created_time,
            output=output,
872
            status=status,
873
            usage=usage,
874
            kv_transfer_params=context.kv_transfer_params,
875
876
877
878
879
880
        )

        if request.store:
            async with self.response_store_lock:
                stored_response = self.response_store.get(response.id)
                # If the response is already cancelled, don't update it.
881
                if stored_response is None or stored_response.status != "cancelled":
882
883
884
                    self.response_store[response.id] = response
        return response

885
886
887
888
    def _topk_logprobs(
        self,
        logprobs: dict[int, SampleLogprob],
        top_logprobs: int,
889
        tokenizer: TokenizerLike,
890
    ) -> list[LogprobTopLogprob]:
891
892
893
894
895
        """Returns the top-k logprobs from the logprobs dictionary."""
        out = []
        for i, (token_id, _logprob) in enumerate(logprobs.items()):
            if i >= top_logprobs:
                break
896
897
898
899
900
            text = self._get_decoded_token(
                logprob=_logprob,
                token_id=token_id,
                tokenizer=tokenizer,
                return_as_token_id=self.return_tokens_as_token_ids,
901
            )
902
903
904
905
906
            out.append(
                LogprobTopLogprob(
                    token=text,
                    logprob=max(_logprob.logprob, -9999.0),
                    bytes=list(text.encode("utf-8", errors="replace")),
907
908
                )
            )
909
910
911
        return out

    def _create_response_logprobs(
912
913
        self,
        token_ids: Sequence[int],
914
        logprobs: SampleLogprobs | None,
915
        tokenizer: TokenizerLike,
916
        top_logprobs: int | None = None,
917
    ) -> list[Logprob]:
918
919
        assert logprobs is not None, "logprobs must be provided"
        assert len(token_ids) == len(logprobs), (
920
921
            "token_ids and logprobs.token_ids must have the same length"
        )
922
923
924
925
        out = []
        for i, token_id in enumerate(token_ids):
            logprob = logprobs[i]
            token_logprob = logprob[token_id]
926
927
928
929
930
            text = self._get_decoded_token(
                logprob=token_logprob,
                token_id=token_id,
                tokenizer=tokenizer,
                return_as_token_id=self.return_tokens_as_token_ids,
931
            )
932
933
934
935
936
            out.append(
                Logprob(
                    token=text,
                    logprob=max(token_logprob.logprob, -9999.0),
                    bytes=list(text.encode("utf-8", errors="replace")),
937
938
939
940
941
942
943
                    top_logprobs=(
                        self._topk_logprobs(
                            logprob, top_logprobs=top_logprobs, tokenizer=tokenizer
                        )
                        if top_logprobs
                        else []
                    ),
944
945
                )
            )
946
947
        return out

948
949
950
    def _create_stream_response_logprobs(
        self,
        token_ids: Sequence[int],
951
        logprobs: SampleLogprobs | None,
952
        tokenizer: TokenizerLike,
953
        top_logprobs: int | None = None,
954
    ) -> list[response_text_delta_event.Logprob]:
955
956
957
958
959
960
        lgs = self._create_response_logprobs(
            token_ids=token_ids,
            logprobs=logprobs,
            tokenizer=tokenizer,
            top_logprobs=top_logprobs,
        )
961
962
963
964
965
966
        return [
            response_text_delta_event.Logprob(
                token=lg.token,
                logprob=lg.logprob,
                top_logprobs=[
                    response_text_delta_event.LogprobTopLogprob(
967
968
                        token=tl.token, logprob=tl.logprob
                    )
969
                    for tl in lg.top_logprobs
970
971
972
                ],
            )
            for lg in lgs
973
974
        ]

975
976
977
978
    def _make_response_output_items(
        self,
        request: ResponsesRequest,
        final_output: CompletionOutput,
979
        tokenizer: TokenizerLike,
980
    ) -> list[ResponseOutputItem]:
981
982
        # Log complete response if output logging is enabled
        if self.enable_log_outputs and self.request_logger:
983
984
985
986
987
988
989
990
            self.request_logger.log_outputs(
                request_id=request.request_id,
                outputs=final_output.text,
                output_token_ids=final_output.token_ids,
                finish_reason=final_output.finish_reason,
                is_streaming=False,
                delta=False,
            )
991

992
993
994
995
996
997
998
999
        # Compute logprobs if requested
        logprobs = None
        if request.is_include_output_logprobs() and final_output.logprobs:
            logprobs = self._create_response_logprobs(
                token_ids=final_output.token_ids,
                logprobs=final_output.logprobs,
                tokenizer=tokenizer,
                top_logprobs=request.top_logprobs,
1000
            )
1001

1002
1003
        # Use parser to extract and create response output items
        if self.parser:
1004
            parser = self.parser(tokenizer, request.tools)
1005
1006
            return parser.extract_response_outputs(
                model_output=final_output.text,
1007
                model_output_token_ids=final_output.token_ids,
1008
1009
1010
1011
1012
1013
1014
1015
1016
                request=request,
                enable_auto_tools=self.enable_auto_tools,
                tool_call_id_type=self.tool_call_id_type,
                logprobs=logprobs,
            )

        # Fallback when no parser is configured
        return [
            ResponseOutputMessage(
1017
                id=f"msg_{random_uuid()}",
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
                content=[
                    ResponseOutputText(
                        text=final_output.text,
                        annotations=[],
                        type="output_text",
                        logprobs=logprobs,
                    )
                ]
                if final_output.text
                else [],
1028
1029
1030
1031
                role="assistant",
                status="completed",
                type="message",
            )
1032
        ]
1033
1034
1035
1036
1037

    def _make_response_output_items_with_harmony(
        self,
        context: HarmonyContext,
    ) -> list[ResponseOutputItem]:
1038
        output_items: list[ResponseOutputItem] = []
1039
1040
        num_init_messages = context.num_init_messages
        for msg in context.messages[num_init_messages:]:
1041
            output_items.extend(harmony_to_response_output(msg))
1042
        # Handle the generation stopped in the middle (if any).
1043
        last_items = parser_state_to_response_output(context.parser)
1044
1045
1046
1047
        if last_items:
            output_items.extend(last_items)
        return output_items

1048
1049
1050
    def _extract_system_message_from_request(
        self, request: ResponsesRequest
    ) -> str | None:
1051
1052
1053
1054
1055
1056
1057
        system_msg = None
        if not isinstance(request.input, str):
            for response_msg in request.input:
                if (
                    isinstance(response_msg, dict)
                    and response_msg.get("role") == "system"
                ):
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
                    content = response_msg.get("content")
                    if isinstance(content, str):
                        system_msg = content
                    elif isinstance(content, list):
                        for param in content:
                            if (
                                isinstance(param, dict)
                                and param.get("type") == "input_text"
                            ):
                                system_msg = param.get("text")
                                break
1069
1070
1071
                    break
        return system_msg

1072
    def _construct_harmony_system_input_message(
1073
        self, request: ResponsesRequest, with_custom_tools: bool, tool_types: set[str]
1074
    ) -> OpenAIHarmonyMessage:
1075
1076
        model_identity = self._extract_system_message_from_request(request)

1077
        reasoning_effort = request.reasoning.effort if request.reasoning else None
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088

        # Extract allowed_tools from MCP tool requests
        allowed_tools_map = _extract_allowed_tools_from_mcp_requests(request.tools)

        # Get filtered tool descriptions first.
        # If get_tool_description returns None (due to filtering), the tool is disabled.
        browser_description = (
            self.tool_server.get_tool_description(
                "browser", allowed_tools_map.get("web_search_preview")
            )
            if "web_search_preview" in tool_types
1089
1090
            and self.tool_server is not None
            and self.tool_server.has_tool("browser")
1091
            else None
1092
        )
1093
1094
1095
1096
1097
        python_description = (
            self.tool_server.get_tool_description(
                "python", allowed_tools_map.get("code_interpreter")
            )
            if "code_interpreter" in tool_types
1098
1099
            and self.tool_server is not None
            and self.tool_server.has_tool("python")
1100
            else None
1101
        )
1102
1103
1104
1105
1106
        container_description = (
            self.tool_server.get_tool_description(
                "container", allowed_tools_map.get("container")
            )
            if "container" in tool_types
1107
1108
            and self.tool_server is not None
            and self.tool_server.has_tool("container")
1109
            else None
1110
        )
1111

1112
        sys_msg = get_system_message(
1113
            model_identity=model_identity,
1114
            reasoning_effort=reasoning_effort,
1115
1116
1117
            browser_description=browser_description,
            python_description=python_description,
            container_description=container_description,
1118
1119
1120
1121
1122
            instructions=request.instructions,
            with_custom_tools=with_custom_tools,
        )
        return sys_msg

1123
1124
1125
    def _construct_input_messages_with_harmony(
        self,
        request: ResponsesRequest,
1126
        prev_response: ResponsesResponse | None,
1127
1128
1129
1130
    ) -> list[OpenAIHarmonyMessage]:
        messages: list[OpenAIHarmonyMessage] = []
        if prev_response is None:
            # New conversation.
1131
            tool_types = extract_tool_types(request.tools)
1132
            with_custom_tools = has_custom_tools(tool_types)
1133
1134
1135

            sys_msg = self._construct_harmony_system_input_message(
                request, with_custom_tools, tool_types
1136
1137
            )
            messages.append(sys_msg)
1138
1139
            if with_custom_tools:
                dev_msg = get_developer_message(
1140
1141
                    instructions=request.instructions, tools=request.tools
                )
1142
                messages.append(dev_msg)
1143
1144
            messages += construct_harmony_previous_input_messages(request)

1145
1146
1147
1148
1149
        else:
            # Continue the previous conversation.
            # FIXME(woosuk): Currently, request params like reasoning and
            # instructions are ignored.
            prev_msgs = self.msg_store[prev_response.id]
1150
1151
1152
1153
1154
1155
1156
1157
1158

            # FIXME(woosuk): The slice-delete-reappend cycle below is
            # currently a no-op --- it removes messages then puts them all
            # back unfiltered. It may be intentionally deferred (see FIXME
            # above) or redundant if the Harmony encoder already strips
            # analysis messages at render time. If analysis messages need
            # to be dropped here, add a channel != "analysis" filter when
            # re-appending, similar to auto_drop_analysis_messages in
            # harmony_utils.py.
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
            if len(prev_msgs) > 0:
                last_msg = prev_msgs[-1]
                assert isinstance(last_msg, OpenAIHarmonyMessage)
                if last_msg.channel == "final":
                    prev_final_msg_idx = -1
                    for i in range(len(prev_msgs) - 2, -1, -1):
                        prev_msg_i = prev_msgs[i]
                        assert isinstance(prev_msg_i, OpenAIHarmonyMessage)
                        if prev_msg_i.channel == "final":
                            prev_final_msg_idx = i
                            break
1170
1171
                    recent_turn_msgs = prev_msgs[prev_final_msg_idx + 1 :]
                    del prev_msgs[prev_final_msg_idx + 1 :]
1172
1173
                    for msg in recent_turn_msgs:
                        assert isinstance(msg, OpenAIHarmonyMessage)
1174
                        prev_msgs.append(msg)
1175
1176
            messages.extend(prev_msgs)
        # Append the new input.
co63oc's avatar
co63oc committed
1177
        # Responses API supports simple text inputs without chat format.
1178
        if isinstance(request.input, str):
1179
1180
1181
1182
1183
            # Skip empty string input when previous_input_messages supplies
            # the full conversation history --- an empty trailing user message
            # confuses the model into thinking nothing was sent.
            if request.input or not request.previous_input_messages:
                messages.append(get_user_message(request.input))
1184
1185
1186
1187
1188
1189
        else:
            if prev_response is not None:
                prev_outputs = copy(prev_response.output)
            else:
                prev_outputs = []
            for response_msg in request.input:
1190
                new_msg = response_input_to_harmony(response_msg, prev_outputs)
1191
                if new_msg is not None and new_msg.author.role != "system":
1192
1193
                    messages.append(new_msg)

1194
                # User passes in a tool call request and its output. We need
1195
1196
                # to add the tool call request to prev_outputs so that
                # response_input_to_harmony can find the tool call request when
1197
1198
1199
1200
1201
                # parsing the tool call output.
                if isinstance(response_msg, ResponseFunctionToolCall):
                    prev_outputs.append(response_msg)
        return messages

1202
1203
1204
1205
1206
1207
    async def _run_background_request_stream(
        self,
        request: ResponsesRequest,
        *args,
        **kwargs,
    ):
1208
        event_deque: deque[StreamingResponsesResponse] = deque()
1209
1210
        new_event_signal = asyncio.Event()
        self.event_store[request.request_id] = (event_deque, new_event_signal)
1211
        generator = self.responses_stream_generator(request, *args, **kwargs)
1212
1213
1214
1215
1216
1217
1218
        try:
            async for event in generator:
                event_deque.append(event)
                new_event_signal.set()  # Signal new event available
        finally:
            new_event_signal.set()

1219
1220
1221
1222
1223
1224
    async def _run_background_request(
        self,
        request: ResponsesRequest,
        *args,
        **kwargs,
    ):
1225
        response = await self.responses_full_generator(request, *args, **kwargs)
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235

        if isinstance(response, ErrorResponse):
            # If the request has failed, update the status to "failed".
            response_id = request.request_id
            async with self.response_store_lock:
                stored_response = self.response_store.get(response_id)
                assert stored_response is not None
                if stored_response.status not in ("completed", "cancelled"):
                    stored_response.status = "failed"

1236
1237
1238
    async def responses_background_stream_generator(
        self,
        response_id: str,
1239
        starting_after: int | None = None,
1240
    ) -> AsyncGenerator[StreamingResponsesResponse, None]:
1241
        if response_id not in self.event_store:
1242
1243
1244
1245
1246
            raise VLLMValidationError(
                f"Unknown response_id: {response_id}",
                parameter="response_id",
                value=response_id,
            )
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258

        event_deque, new_event_signal = self.event_store[response_id]
        start_index = 0 if starting_after is None else starting_after + 1
        current_index = start_index

        while True:
            new_event_signal.clear()

            # Yield existing events from start_index
            while current_index < len(event_deque):
                event = event_deque[current_index]
                yield event
1259
                if getattr(event, "type", "unknown") == "response.completed":
1260
                    return
1261
1262
1263
1264
                current_index += 1

            await new_event_signal.wait()

1265
1266
1267
    async def retrieve_responses(
        self,
        response_id: str,
1268
1269
1270
1271
1272
1273
1274
        starting_after: int | None,
        stream: bool | None,
    ) -> (
        ErrorResponse
        | ResponsesResponse
        | AsyncGenerator[StreamingResponsesResponse, None]
    ):
1275
1276
1277
1278
1279
        async with self.response_store_lock:
            response = self.response_store.get(response_id)

        if response is None:
            return self._make_not_found_error(response_id)
1280
1281
1282
1283
1284
1285

        if stream:
            return self.responses_background_stream_generator(
                response_id,
                starting_after,
            )
1286
1287
1288
1289
1290
        return response

    async def cancel_responses(
        self,
        response_id: str,
1291
    ) -> ErrorResponse | ResponsesResponse:
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
        async with self.response_store_lock:
            response = self.response_store.get(response_id)
            if response is None:
                return self._make_not_found_error(response_id)

            prev_status = response.status
            if prev_status not in ("queued", "in_progress"):
                return self.create_error_response(
                    err_type="invalid_request_error",
                    message="Cannot cancel a synchronous response.",
1302
                    param="response_id",
1303
1304
1305
1306
1307
1308
                )

            # Update the status to "cancelled".
            response.status = "cancelled"

        # Abort the request.
1309
        if task := self.background_tasks.get(response_id):
1310
1311
1312
1313
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
1314
                logger.exception("Background task for %s was cancelled", response_id)
1315
1316
1317
1318
1319
1320
1321
        return response

    def _make_not_found_error(self, response_id: str) -> ErrorResponse:
        return self.create_error_response(
            err_type="invalid_request_error",
            message=f"Response with id '{response_id}' not found.",
            status_code=HTTPStatus.NOT_FOUND,
1322
            param="response_id",
1323
        )
1324

1325
    async def _process_simple_streaming_events(
1326
1327
1328
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
1329
        result_generator: AsyncIterator[ConversationContext | None],
1330
1331
        context: ConversationContext,
        model_name: str,
1332
        tokenizer: TokenizerLike,
1333
        request_metadata: RequestResponseMetadata,
1334
        created_time: int,
1335
        _increment_sequence_number_and_return: Callable[
1336
1337
            [StreamingResponsesResponse], StreamingResponsesResponse
        ],
1338
    ) -> AsyncGenerator[StreamingResponsesResponse, None]:
1339
1340
1341
1342
        current_content_index = 0
        current_output_index = 0
        current_item_id = ""
        reasoning_parser = None
1343
1344
        if self.parser and self.parser.reasoning_parser_cls:
            reasoning_parser = self.parser.reasoning_parser_cls(tokenizer)
1345
1346
        tool_parser = None
        if self.parser and self.parser.tool_parser_cls:
1347
            tool_parser = self.parser.tool_parser_cls(tokenizer, request.tools)
1348
1349
        reasoning_ended = False
        tool_call_text_started = False
1350
1351
        previous_text = ""
        previous_token_ids: list[int] = []
1352
        prompt_is_reasoning_end = None
1353
1354
1355
1356
1357
1358
        first_delta_sent = False
        previous_delta_messages: list[DeltaMessage] = []
        async for ctx in result_generator:
            assert isinstance(ctx, SimpleContext)
            if ctx.last_output is None:
                continue
1359
1360
1361
1362
            if reasoning_parser and prompt_is_reasoning_end is None:
                prompt_is_reasoning_end = reasoning_parser.is_reasoning_end(
                    ctx.last_output.prompt_token_ids
                )
1363
1364
            if ctx.last_output.outputs:
                output = ctx.last_output.outputs[0]
1365
1366
                # finish_reason='error' indicates a retryable error
                self._raise_if_error(output.finish_reason, request.request_id)
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
                delta_text = output.text
                delta_token_ids = as_list(output.token_ids)
                current_text = previous_text + delta_text
                current_token_ids = previous_token_ids + delta_token_ids

                if reasoning_parser and tool_parser:
                    if prompt_is_reasoning_end:
                        reasoning_ended = True
                    if not reasoning_ended:
                        delta_message = reasoning_parser.extract_reasoning_streaming(
                            previous_text=previous_text,
                            current_text=current_text,
                            delta_text=delta_text,
                            previous_token_ids=previous_token_ids,
                            current_token_ids=current_token_ids,
                            delta_token_ids=delta_token_ids,
                        )
                        if reasoning_parser.is_reasoning_end(delta_token_ids):
                            reasoning_ended = True
                            current_token_ids = reasoning_parser.extract_content_ids(
                                delta_token_ids
                            )
                            if delta_message and delta_message.content:
                                current_text = delta_message.content
                                delta_message.content = None
                            else:
                                current_text = ""

                    if reasoning_ended:
                        if not tool_call_text_started:
                            tool_call_text_started = True
                            previous_text = ""
                            previous_token_ids = []
                            delta_text = current_text
                            delta_token_ids = current_token_ids

                        delta_message = tool_parser.extract_tool_calls_streaming(
                            previous_text=previous_text,
                            current_text=current_text,
                            delta_text=delta_text,
                            previous_token_ids=previous_token_ids,
                            current_token_ids=current_token_ids,
                            delta_token_ids=delta_token_ids,
                            request=request,  # type: ignore[arg-type]
                        )
                elif reasoning_parser:
1413
1414
                    delta_message = reasoning_parser.extract_reasoning_streaming(
                        previous_text=previous_text,
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
                        current_text=current_text,
                        delta_text=delta_text,
                        previous_token_ids=previous_token_ids,
                        current_token_ids=current_token_ids,
                        delta_token_ids=delta_token_ids,
                    )
                elif tool_parser:
                    delta_message = tool_parser.extract_tool_calls_streaming(
                        previous_text=previous_text,
                        current_text=current_text,
                        delta_text=delta_text,
1426
                        previous_token_ids=previous_token_ids,
1427
1428
1429
                        current_token_ids=current_token_ids,
                        delta_token_ids=delta_token_ids,
                        request=request,  # type: ignore[arg-type]
1430
1431
                    )
                else:
1432
1433
1434
                    delta_message = DeltaMessage(
                        content=output.text,
                    )
1435
1436
                previous_text = current_text
                previous_token_ids = current_token_ids
1437
1438
1439
                if not delta_message:
                    continue
                if not first_delta_sent:
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
                    current_item_id = random_uuid()
                    if delta_message.tool_calls:
                        current_tool_call_id = f"call_{random_uuid()}"
                        assert len(delta_message.tool_calls) == 1, (
                            "Multiple tool calls in one delta is not supported"
                        )
                        assert delta_message.tool_calls[0].function is not None, (
                            "Tool call without function is not supported"
                        )
                        assert delta_message.tool_calls[0].function.name is not None, (
                            "Tool call without function name is not supported"
                        )
                        current_tool_call_name = delta_message.tool_calls[
                            0
                        ].function.name
                        yield _increment_sequence_number_and_return(
                            ResponseOutputItemAddedEvent(
                                type="response.output_item.added",
                                sequence_number=-1,
                                output_index=current_output_index,
                                item=ResponseFunctionToolCallItem(
                                    type="function_call",
                                    id=current_item_id,
                                    call_id=current_tool_call_id,
                                    name=current_tool_call_name,
                                    arguments=delta_message.tool_calls[
                                        0
                                    ].function.arguments,
                                    status="in_progress",
                                ),
                            )
                        )
                    elif delta_message.reasoning:
1473
                        yield _increment_sequence_number_and_return(
1474
1475
1476
1477
                            ResponseOutputItemAddedEvent(
                                type="response.output_item.added",
                                sequence_number=-1,
                                output_index=current_output_index,
1478
                                item=ResponseReasoningItem(
1479
1480
1481
1482
1483
                                    type="reasoning",
                                    id=current_item_id,
                                    summary=[],
                                    status="in_progress",
                                ),
1484
1485
                            )
                        )
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
                        yield _increment_sequence_number_and_return(
                            ResponseReasoningPartAddedEvent(
                                type="response.reasoning_part.added",
                                sequence_number=-1,
                                output_index=current_output_index,
                                item_id=current_item_id,
                                content_index=current_content_index,
                                part=ResponseReasoningTextContent(
                                    text="",
                                    type="reasoning_text",
                                ),
                            )
                        )
1499
                    elif not delta_message.tool_calls:
1500
                        yield _increment_sequence_number_and_return(
1501
1502
1503
1504
                            ResponseOutputItemAddedEvent(
                                type="response.output_item.added",
                                sequence_number=-1,
                                output_index=current_output_index,
1505
                                item=ResponseOutputMessage(
1506
1507
1508
1509
1510
1511
                                    id=current_item_id,
                                    type="message",
                                    role="assistant",
                                    content=[],
                                    status="in_progress",
                                ),
1512
1513
                            )
                        )
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
                        yield _increment_sequence_number_and_return(
                            ResponseContentPartAddedEvent(
                                type="response.content_part.added",
                                sequence_number=-1,
                                output_index=current_output_index,
                                item_id=current_item_id,
                                content_index=current_content_index,
                                part=ResponseOutputText(
                                    type="output_text",
                                    text="",
                                    annotations=[],
                                    logprobs=[],
                                ),
                            )
1528
                        )
1529
1530
1531
1532
                    first_delta_sent = True

                # check delta message and previous delta message are
                # same as content or reasoning content
1533
1534
                if (
                    previous_delta_messages
1535
                    and previous_delta_messages[-1].reasoning is not None
1536
1537
                    and delta_message.content is not None
                ):
1538
1539
                    # from reasoning to normal content, send done
                    # event for reasoning
1540
                    reason_content = "".join(
1541
                        pm.reasoning
1542
                        for pm in previous_delta_messages
1543
                        if pm.reasoning is not None
1544
                    )
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564

                    # delta message could have both reasoning and
                    # content. Include current delta's reasoning in the
                    # finalization since it may carry the tail end of
                    # reasoning text (e.g. when reasoning end and
                    # content start arrive in the same delta).
                    if delta_message.reasoning is not None:
                        yield _increment_sequence_number_and_return(
                            ResponseReasoningTextDeltaEvent(
                                type="response.reasoning_text.delta",
                                sequence_number=-1,
                                content_index=current_content_index,
                                output_index=current_output_index,
                                item_id=current_item_id,
                                delta=delta_message.reasoning,
                            )
                        )
                        reason_content += delta_message.reasoning
                        delta_message = DeltaMessage(content=delta_message.content)

1565
                    yield _increment_sequence_number_and_return(
1566
1567
1568
1569
1570
1571
1572
                        ResponseReasoningTextDoneEvent(
                            type="response.reasoning_text.done",
                            item_id=current_item_id,
                            sequence_number=-1,
                            output_index=current_output_index,
                            content_index=current_content_index,
                            text=reason_content,
1573
1574
                        )
                    )
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
                    yield _increment_sequence_number_and_return(
                        ResponseReasoningPartDoneEvent(
                            type="response.reasoning_part.done",
                            sequence_number=-1,
                            item_id=current_item_id,
                            output_index=current_output_index,
                            content_index=current_content_index,
                            part=ResponseReasoningTextContent(
                                text=reason_content,
                                type="reasoning_text",
                            ),
                        )
                    )
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
                    current_content_index = 0
                    reasoning_item = ResponseReasoningItem(
                        type="reasoning",
                        content=[
                            ResponseReasoningTextContent(
                                text=reason_content,
                                type="reasoning_text",
                            ),
                        ],
                        status="completed",
                        id=current_item_id,
                        summary=[],
                    )
1601
                    yield _increment_sequence_number_and_return(
1602
1603
1604
1605
1606
                        ResponseOutputItemDoneEvent(
                            type="response.output_item.done",
                            sequence_number=-1,
                            output_index=current_output_index,
                            item=reasoning_item,
1607
1608
                        )
                    )
1609
1610
                    current_output_index += 1
                    current_item_id = str(uuid.uuid4())
1611
                    yield _increment_sequence_number_and_return(
1612
                        ResponseOutputItemAddedEvent(
1613
1614
1615
                            type="response.output_item.added",
                            sequence_number=-1,
                            output_index=current_output_index,
1616
                            item=ResponseOutputMessage(
1617
1618
1619
1620
1621
1622
                                id=current_item_id,
                                type="message",
                                role="assistant",
                                content=[],
                                status="in_progress",
                            ),
1623
1624
                        )
                    )
1625
                    yield _increment_sequence_number_and_return(
1626
                        ResponseContentPartAddedEvent(
1627
1628
1629
1630
1631
                            type="response.content_part.added",
                            sequence_number=-1,
                            output_index=current_output_index,
                            item_id=current_item_id,
                            content_index=current_content_index,
1632
                            part=ResponseOutputText(
1633
1634
1635
1636
1637
                                type="output_text",
                                text="",
                                annotations=[],
                                logprobs=[],
                            ),
1638
1639
                        )
                    )
1640
1641
                    # reset previous delta messages
                    previous_delta_messages = []
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
                if delta_message.tool_calls and delta_message.tool_calls[0].function:
                    if delta_message.tool_calls[0].function.arguments:
                        yield _increment_sequence_number_and_return(
                            ResponseFunctionCallArgumentsDeltaEvent(
                                type="response.function_call_arguments.delta",
                                sequence_number=-1,
                                output_index=current_output_index,
                                item_id=current_item_id,
                                delta=delta_message.tool_calls[0].function.arguments,
                            )
                        )
                    # tool call initiated with no arguments
                    elif delta_message.tool_calls[0].function.name:
                        # send done with current content part
                        # and add new function call item
                        yield _increment_sequence_number_and_return(
                            ResponseTextDoneEvent(
                                type="response.output_text.done",
                                sequence_number=-1,
                                output_index=current_output_index,
                                content_index=current_content_index,
                                text="",
                                logprobs=[],
                                item_id=current_item_id,
                            )
                        )
                        yield _increment_sequence_number_and_return(
                            ResponseContentPartDoneEvent(
                                type="response.content_part.done",
                                sequence_number=-1,
                                item_id=current_item_id,
                                output_index=current_output_index,
                                content_index=current_content_index,
                                part=ResponseOutputText(
                                    type="output_text",
                                    text="",
                                    annotations=[],
                                    logprobs=[],
                                ),
                            )
                        )
                        yield _increment_sequence_number_and_return(
                            ResponseOutputItemDoneEvent(
                                type="response.output_item.done",
                                sequence_number=-1,
                                output_index=current_output_index,
                                item=ResponseOutputMessage(
                                    id=current_item_id,
                                    type="message",
                                    role="assistant",
                                    content=[],
                                    status="completed",
                                ),
                            )
                        )
                        current_output_index += 1
                        current_item_id = random_uuid()
                        assert delta_message.tool_calls[0].function is not None
                        current_tool_call_name = delta_message.tool_calls[
                            0
                        ].function.name
                        current_tool_call_id = f"call_{random_uuid()}"
                        yield _increment_sequence_number_and_return(
                            ResponseOutputItemAddedEvent(
                                type="response.output_item.added",
                                sequence_number=-1,
                                output_index=current_output_index,
                                item=ResponseFunctionToolCallItem(
                                    type="function_call",
                                    id=current_item_id,
                                    call_id=current_tool_call_id,
                                    name=current_tool_call_name,
                                    arguments="",
                                    status="in_progress",
                                ),
                            )
                        )
                        # skip content part for tool call
                        current_content_index = 1
                        continue
                elif delta_message.reasoning is not None:
1723
                    yield _increment_sequence_number_and_return(
1724
1725
1726
1727
1728
1729
                        ResponseReasoningTextDeltaEvent(
                            type="response.reasoning_text.delta",
                            sequence_number=-1,
                            content_index=current_content_index,
                            output_index=current_output_index,
                            item_id=current_item_id,
1730
                            delta=delta_message.reasoning,
1731
1732
                        )
                    )
1733
                elif delta_message.content:
1734
                    yield _increment_sequence_number_and_return(
1735
                        ResponseTextDeltaEvent(
1736
1737
1738
1739
1740
1741
                            type="response.output_text.delta",
                            sequence_number=-1,
                            content_index=current_content_index,
                            output_index=current_output_index,
                            item_id=current_item_id,
                            delta=delta_message.content,
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
                            logprobs=(
                                self._create_stream_response_logprobs(
                                    token_ids=output.token_ids,
                                    logprobs=output.logprobs,
                                    tokenizer=tokenizer,
                                    top_logprobs=request.top_logprobs,
                                )
                                if request.is_include_output_logprobs()
                                else []
                            ),
1752
1753
                        )
                    )
1754
1755

                previous_delta_messages.append(delta_message)
1756

1757
        if previous_delta_messages:
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
            parts = []
            for pm in previous_delta_messages:
                if pm.tool_calls:
                    assert len(pm.tool_calls) == 1, (
                        "Multiple tool calls in one delta is not supported"
                    )
                    assert pm.tool_calls[0].function is not None, (
                        "Tool call without function is not supported"
                    )
                    parts.append(pm.tool_calls[0].function.arguments or "")

            tool_call_arguments = "".join(parts)
            if tool_call_arguments:
                yield _increment_sequence_number_and_return(
                    ResponseFunctionCallArgumentsDoneEvent(
                        type="response.function_call_arguments.done",
                        sequence_number=-1,
                        output_index=current_output_index,
                        item_id=current_item_id,
                        arguments=tool_call_arguments,
                        name=current_tool_call_name,
                    )
                )
                current_content_index = 0
                function_call_item = ResponseFunctionToolCall(
                    type="function_call",
                    name=current_tool_call_name,
                    arguments=tool_call_arguments,
                    status="completed",
                    id=current_item_id,
                    call_id=current_tool_call_id,
                )
                yield _increment_sequence_number_and_return(
                    ResponseOutputItemDoneEvent(
                        type="response.output_item.done",
                        sequence_number=-1,
                        output_index=current_output_index,
                        item=function_call_item,
                    )
                )

            elif previous_delta_messages[-1].reasoning is not None:
1800
                reason_content = "".join(
1801
                    pm.reasoning
1802
                    for pm in previous_delta_messages
1803
                    if pm.reasoning is not None
1804
                )
1805
                yield _increment_sequence_number_and_return(
1806
1807
1808
1809
1810
1811
1812
                    ResponseReasoningTextDoneEvent(
                        type="response.reasoning_text.done",
                        item_id=current_item_id,
                        sequence_number=-1,
                        output_index=current_output_index,
                        content_index=current_content_index,
                        text=reason_content,
1813
1814
                    )
                )
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
                yield _increment_sequence_number_and_return(
                    ResponseReasoningPartDoneEvent(
                        type="response.reasoning_part.done",
                        sequence_number=-1,
                        item_id=current_item_id,
                        output_index=current_output_index,
                        content_index=current_content_index,
                        part=ResponseReasoningTextContent(
                            text=reason_content,
                            type="reasoning_text",
                        ),
                    )
                )
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
                reasoning_item = ResponseReasoningItem(
                    type="reasoning",
                    content=[
                        ResponseReasoningTextContent(
                            text=reason_content,
                            type="reasoning_text",
                        ),
                    ],
                    status="completed",
                    id=current_item_id,
                    summary=[],
                )
1840
                yield _increment_sequence_number_and_return(
1841
1842
1843
1844
1845
                    ResponseOutputItemDoneEvent(
                        type="response.output_item.done",
                        sequence_number=-1,
                        output_index=current_output_index,
                        item=reasoning_item,
1846
1847
                    )
                )
1848
            elif previous_delta_messages[-1].content:
1849
                final_content = "".join(
1850
                    pm.content for pm in previous_delta_messages if pm.content
1851
                )
1852
                yield _increment_sequence_number_and_return(
1853
                    ResponseTextDoneEvent(
1854
1855
1856
1857
1858
1859
1860
                        type="response.output_text.done",
                        sequence_number=-1,
                        output_index=current_output_index,
                        content_index=current_content_index,
                        text=final_content,
                        logprobs=[],
                        item_id=current_item_id,
1861
1862
                    )
                )
1863
1864
1865
1866
1867
                part = ResponseOutputText(
                    text=final_content,
                    type="output_text",
                    annotations=[],
                )
1868
                yield _increment_sequence_number_and_return(
1869
                    ResponseContentPartDoneEvent(
1870
1871
1872
1873
1874
1875
                        type="response.content_part.done",
                        sequence_number=-1,
                        item_id=current_item_id,
                        output_index=current_output_index,
                        content_index=current_content_index,
                        part=part,
1876
1877
                    )
                )
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
                item = ResponseOutputMessage(
                    type="message",
                    role="assistant",
                    content=[
                        part,
                    ],
                    status="completed",
                    id=current_item_id,
                    summary=[],
                )
1888
                yield _increment_sequence_number_and_return(
1889
1890
1891
1892
1893
                    ResponseOutputItemDoneEvent(
                        type="response.output_item.done",
                        sequence_number=-1,
                        output_index=current_output_index,
                        item=item,
1894
1895
                    )
                )
1896
1897
1898
1899
1900

    async def _process_harmony_streaming_events(
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
1901
        result_generator: AsyncIterator[ConversationContext | None],
1902
1903
        context: ConversationContext,
        model_name: str,
1904
        tokenizer: TokenizerLike,
1905
1906
        request_metadata: RequestResponseMetadata,
        created_time: int,
1907
        _increment_sequence_number_and_return: Callable[
1908
1909
            [StreamingResponsesResponse], StreamingResponsesResponse
        ],
1910
    ) -> AsyncGenerator[StreamingResponsesResponse, None]:
1911
        state = StreamingState()
1912

1913
1914
1915
        async for ctx in result_generator:
            assert isinstance(ctx, StreamingHarmonyContext)

1916
1917
1918
            # finish_reason='error' indicates a retryable error
            self._raise_if_error(ctx.finish_reason, request.request_id)

1919
1920
1921
            if ctx.is_expecting_start():
                if len(ctx.parser.messages) > 0:
                    previous_item = ctx.parser.messages[-1]
1922
                    for event in emit_previous_item_done_events(previous_item, state):
1923
1924
1925
1926
                        yield _increment_sequence_number_and_return(event)
                state.reset_for_new_item()

            # Stream the output of a harmony message
1927
            for event in emit_content_delta_events(ctx, state):
1928
1929
1930
                yield _increment_sequence_number_and_return(event)

            # Stream tool call outputs
1931
            for event in emit_tool_action_events(ctx, state, self.tool_server):
1932
                yield _increment_sequence_number_and_return(event)
1933

1934
1935
1936
1937
    async def responses_stream_generator(
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
1938
        result_generator: AsyncIterator[ConversationContext | None],
1939
1940
        context: ConversationContext,
        model_name: str,
1941
        tokenizer: TokenizerLike,
1942
        request_metadata: RequestResponseMetadata,
1943
        created_time: int | None = None,
1944
    ) -> AsyncGenerator[StreamingResponsesResponse, None]:
1945
1946
1947
1948
1949
        # TODO:
        # 1. Handle disconnect

        created_time = created_time or int(time.time())

1950
1951
        sequence_number = 0

1952
        def _increment_sequence_number_and_return(
1953
            event: StreamingResponsesResponse,
1954
        ) -> StreamingResponsesResponse:
1955
1956
            nonlocal sequence_number
            # Set sequence_number if the event has this attribute
1957
            if hasattr(event, "sequence_number"):
1958
1959
                event.sequence_number = sequence_number
            sequence_number += 1
1960
            return event
1961

1962
        async with AsyncExitStack() as exit_stack:
1963
            if self.use_harmony:
1964
1965
                # TODO: in streaming, we noticed this bug:
                # https://github.com/vllm-project/vllm/issues/25697
1966
                await self._initialize_tool_sessions(request, context, exit_stack)
Jiayi Yan's avatar
Jiayi Yan committed
1967
                processor = self._process_harmony_streaming_events
1968
            else:
Jiayi Yan's avatar
Jiayi Yan committed
1969
                processor = self._process_simple_streaming_events
1970
            # TODO Hanchen make sampling params to include the structural tag
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980

            initial_response = ResponsesResponse.from_request(
                request,
                sampling_params,
                model_name=model_name,
                created_time=created_time,
                output=[],
                status="in_progress",
                usage=None,
            ).model_dump()
1981
            yield _increment_sequence_number_and_return(
1982
1983
1984
1985
                ResponseCreatedEvent(
                    type="response.created",
                    sequence_number=-1,
                    response=initial_response,
1986
1987
                )
            )
1988
            yield _increment_sequence_number_and_return(
1989
1990
1991
1992
                ResponseInProgressEvent(
                    type="response.in_progress",
                    sequence_number=-1,
                    response=initial_response,
1993
1994
                )
            )
1995

1996
            try:
Jiayi Yan's avatar
Jiayi Yan committed
1997
                async for event_data in processor(
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
                    request,
                    sampling_params,
                    result_generator,
                    context,
                    model_name,
                    tokenizer,
                    request_metadata,
                    created_time,
                    _increment_sequence_number_and_return,
                ):
                    yield event_data
            except GenerationError as e:
                error_json = self._convert_generation_error_to_streaming_response(e)
                yield _increment_sequence_number_and_return(
                    TypeAdapter(StreamingResponsesResponse).validate_json(error_json)
                )
                return
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031

            async def empty_async_generator():
                # A hack to trick Python to think this is a generator but
                # in fact it immediately returns.
                if False:
                    yield

            final_response = await self.responses_full_generator(
                request,
                sampling_params,
                empty_async_generator(),
                context,
                model_name,
                tokenizer,
                request_metadata,
                created_time=created_time,
            )
2032
            yield _increment_sequence_number_and_return(
2033
                ResponseCompletedEvent(
2034
2035
                    type="response.completed",
                    sequence_number=-1,
2036
                    response=final_response,
2037
2038
                )
            )