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

import asyncio
5
import json
6
import time
7
import uuid
8
from collections import deque
9
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Sequence
10
from contextlib import AsyncExitStack
11
from copy import copy
12
from dataclasses import dataclass, replace
13
from http import HTTPStatus
14
from typing import Final
15
16
17

import jinja2
from fastapi import Request
18
19
20
21
22
23
from openai.types.responses import (
    ResponseCodeInterpreterCallCodeDeltaEvent,
    ResponseCodeInterpreterCallCodeDoneEvent,
    ResponseCodeInterpreterCallCompletedEvent,
    ResponseCodeInterpreterCallInProgressEvent,
    ResponseCodeInterpreterCallInterpretingEvent,
24
25
26
    ResponseCodeInterpreterToolCallParam,
    ResponseContentPartAddedEvent,
    ResponseContentPartDoneEvent,
27
28
    ResponseFunctionCallArgumentsDeltaEvent,
    ResponseFunctionCallArgumentsDoneEvent,
29
30
    ResponseFunctionToolCall,
    ResponseFunctionWebSearch,
31
32
33
34
    ResponseMcpCallArgumentsDeltaEvent,
    ResponseMcpCallArgumentsDoneEvent,
    ResponseMcpCallCompletedEvent,
    ResponseMcpCallInProgressEvent,
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    ResponseOutputItem,
    ResponseOutputItemAddedEvent,
    ResponseOutputItemDoneEvent,
    ResponseOutputMessage,
    ResponseOutputText,
    ResponseReasoningItem,
    ResponseReasoningTextDeltaEvent,
    ResponseReasoningTextDoneEvent,
    ResponseStatus,
    ResponseTextDeltaEvent,
    ResponseTextDoneEvent,
    ResponseWebSearchCallCompletedEvent,
    ResponseWebSearchCallInProgressEvent,
    ResponseWebSearchCallSearchingEvent,
    response_function_web_search,
    response_text_delta_event,
)
52
from openai.types.responses.response_output_item import McpCall
53
from openai.types.responses.response_output_text import Logprob, LogprobTopLogprob
54
from openai.types.responses.response_reasoning_item import (
55
56
    Content as ResponseReasoningTextContent,
)
57
from openai.types.responses.tool import Mcp, Tool
58
from openai_harmony import Message as OpenAIHarmonyMessage
59
from pydantic import TypeAdapter
60

61
from vllm import envs
62
from vllm.engine.protocol import EngineClient
63
64
65
from vllm.entrypoints.chat_utils import (
    ChatCompletionMessageParam,
    ChatTemplateContentFormatOption,
66
    make_tool_call_id,
67
)
68
from vllm.entrypoints.logger import RequestLogger
69
from vllm.entrypoints.mcp.tool_server import ToolServer
70
from vllm.entrypoints.openai.engine.protocol import (
71
72
73
74
    DeltaMessage,
    ErrorResponse,
    RequestResponseMetadata,
)
75
from vllm.entrypoints.openai.engine.serving import (
76
77
78
    GenerationError,
    OpenAIServing,
)
79
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
80
81
82
83
84
85
86
87
88
89
90
91
from vllm.entrypoints.openai.parser.harmony_utils import (
    construct_harmony_previous_input_messages,
    get_developer_message,
    get_stop_tokens_for_assistant_actions,
    get_system_message,
    get_user_message,
    has_custom_tools,
    parse_output_message,
    parse_remaining_state,
    parse_response_input,
    render_for_completion,
)
92
93
94
95
96
97
98
from vllm.entrypoints.openai.responses.context import (
    ConversationContext,
    HarmonyContext,
    ParsableContext,
    SimpleContext,
    StreamingHarmonyContext,
)
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from vllm.entrypoints.openai.responses.protocol import (
    InputTokensDetails,
    OutputTokensDetails,
    ResponseCompletedEvent,
    ResponseCreatedEvent,
    ResponseInProgressEvent,
    ResponseInputOutputMessage,
    ResponseReasoningPartAddedEvent,
    ResponseReasoningPartDoneEvent,
    ResponsesRequest,
    ResponsesResponse,
    ResponseUsage,
    StreamingResponsesResponse,
)
113
from vllm.entrypoints.openai.responses.utils import (
114
    construct_input_messages,
115
    construct_tool_dicts,
116
    extract_tool_types,
117
    should_continue_final_message,
118
)
119
from vllm.entrypoints.utils import get_max_tokens
120
from vllm.exceptions import VLLMValidationError
121
from vllm.inputs.data import TokensPrompt
122
from vllm.logger import init_logger
123
124
from vllm.logprobs import Logprob as SampleLogprob
from vllm.logprobs import SampleLogprobs
125
from vllm.outputs import CompletionOutput
126
from vllm.renderers import RendererLike
127
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
128
from vllm.tokenizers import TokenizerLike
129
130
131
132
133
from vllm.utils import random_uuid

logger = init_logger(__name__)


134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@dataclass
class HarmonyStreamingState:
    """Mutable state for harmony streaming event processing."""

    current_content_index: int = -1
    current_output_index: int = 0
    current_item_id: str = ""
    sent_output_item_added: bool = False
    is_first_function_call_delta: bool = False

    def reset_for_new_item(self) -> None:
        """Reset state when expecting a new output item."""
        self.current_output_index += 1
        self.sent_output_item_added = False
        self.is_first_function_call_delta = False


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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


190
191
192
193
194
195
class OpenAIServingResponses(OpenAIServing):
    def __init__(
        self,
        engine_client: EngineClient,
        models: OpenAIServingModels,
        *,
196
197
        request_logger: RequestLogger | None,
        chat_template: str | None,
198
199
200
201
        chat_template_content_format: ChatTemplateContentFormatOption,
        return_tokens_as_token_ids: bool = False,
        reasoning_parser: str = "",
        enable_auto_tools: bool = False,
202
203
        tool_parser: str | None = None,
        tool_server: ToolServer | None = None,
204
205
        enable_prompt_tokens_details: bool = False,
        enable_force_include_usage: bool = False,
206
        enable_log_outputs: bool = False,
207
        log_error_stack: bool = False,
208
209
210
211
212
213
    ) -> None:
        super().__init__(
            engine_client=engine_client,
            models=models,
            request_logger=request_logger,
            return_tokens_as_token_ids=return_tokens_as_token_ids,
214
            log_error_stack=log_error_stack,
215
216
217
218
        )

        self.chat_template = chat_template
        self.chat_template_content_format: Final = chat_template_content_format
219
        self.enable_log_outputs = enable_log_outputs
220

221
222
        self.reasoning_parser = self._get_reasoning_parser(
            reasoning_parser_name=reasoning_parser
223
        )
224
225
        self.enable_prompt_tokens_details = enable_prompt_tokens_details
        self.enable_force_include_usage = enable_force_include_usage
226

227
        self.default_sampling_params = self.model_config.get_diff_sampling_param()
228

229
230
231
232
233
        # 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.
234
        self.enable_store = envs.VLLM_ENABLE_RESPONSES_API_STORE
235
236
237
238
        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 "
239
240
                "the store."
            )
241

242
        self.use_harmony = self.model_config.hf_config.model_type == "gpt_oss"
243
        if self.use_harmony:
244
245
246
247
            logger.warning(
                "For gpt-oss, we ignore --enable-auto-tool-choice "
                "and always enable tool use."
            )
248
249
250
251
252
            # 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(
253
254
                get_stop_tokens_for_assistant_actions()
            )
255
256
257
258
259
260
261
262
263
264
265

        # Handle tool call ID type for Kimi K2 (supporting test mocking via overrides)
        hf_overrides = getattr(self.model_config, "hf_overrides", None)
        if self.model_config.hf_text_config.model_type == "kimi_k2" or (
            isinstance(hf_overrides, dict)
            and hf_overrides.get("model_type") == "kimi_k2"
        ):
            self.tool_call_id_type = "kimi_k2"
        else:
            self.tool_call_id_type = "random"

266
        self.enable_auto_tools = enable_auto_tools
267
        # set up tool use
268
269
270
        self.tool_parser = self._get_tool_parser(
            tool_parser_name=tool_parser, enable_auto_tools=enable_auto_tools
        )
271
        # HACK(woosuk): This is a hack. We should use a better store.
272
273
        # FIXME: If enable_store=True, this may cause a memory leak since we
        # never remove responses from the store.
274
275
276
277
        self.response_store: dict[str, ResponsesResponse] = {}
        self.response_store_lock = asyncio.Lock()

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

282
283
284
        # 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.
285
286
287
        self.event_store: dict[
            str, tuple[deque[StreamingResponsesResponse], asyncio.Event]
        ] = {}
288

289
290
        self.background_tasks: dict[str, asyncio.Task] = {}

291
292
        self.tool_server = tool_server

293
    def _validate_generator_input(
294
        self, engine_prompt: TokensPrompt
295
    ) -> ErrorResponse | None:
296
297
298
299
300
301
        """Add validations to the input to the generator here."""
        if self.max_model_len <= len(engine_prompt["prompt_token_ids"]):
            error_message = (
                "The engine prompt length"
                f" {len(engine_prompt['prompt_token_ids'])} "
                f"exceeds the max_model_len {self.max_model_len}. "
302
303
                "Please reduce prompt."
            )
304
305
306
307
            return self.create_error_response(
                err_type="invalid_request_error",
                message=error_message,
                status_code=HTTPStatus.BAD_REQUEST,
308
                param="input",
309
310
311
            )
        return None

312
313
314
315
316
317
318
319
    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,
320
                param="logprobs",
321
322
323
324
325
326
327
328
329
330
331
332
            )
        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,
333
                param="background",
334
            )
335
336
337
338
339
340
        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,
341
                param="previous_response_id",
342
            )
343
344
        return None

345
346
347
    async def create_responses(
        self,
        request: ResponsesRequest,
348
349
350
351
352
353
        raw_request: Request | None = None,
    ) -> (
        AsyncGenerator[StreamingResponsesResponse, None]
        | ResponsesResponse
        | ErrorResponse
    ):
354
355
356
357
        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
358
359
360
        maybe_validation_error = self._validate_create_responses_input(request)
        if maybe_validation_error is not None:
            return maybe_validation_error
361
362
363
364
365
366
367

        # 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

368
        if request.store and not self.enable_store:
369
370
371
372
373
374
375
            # 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
376

377
378
379
380
381
382
383
384
385
386
387
        # 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

        try:
388
            lora_request = self._maybe_get_adapters(request)
389
            model_name = self.models.model_name(lora_request)
390
391
            renderer = self.engine_client.renderer
            tokenizer = renderer.get_tokenizer()
392

393
            if self.use_harmony:
394
395
                messages, engine_prompts = self._make_request_with_harmony(
                    request, prev_response
396
                )
397
            else:
398
                messages, engine_prompts = await self._make_request(
399
                    request, prev_response, renderer
400
                )
401

402
403
404
405
406
407
408
        except (
            ValueError,
            TypeError,
            RuntimeError,
            jinja2.TemplateError,
            NotImplementedError,
        ) as e:
409
            logger.exception("Error in preprocessing prompt inputs")
410
            return self.create_error_response(e)
411

412
        request_metadata = RequestResponseMetadata(request_id=request.request_id)
413
414
415
416
        if raw_request:
            raw_request.state.request_metadata = request_metadata

        # Schedule the request and get the result generator.
417
        generators: list[AsyncGenerator[ConversationContext, None]] = []
418
419

        builtin_tool_list: list[str] = []
420
        if self.tool_server is not None:
421
422
423
424
            if self.tool_server.has_tool("browser"):
                builtin_tool_list.append("browser")
            if self.tool_server.has_tool("python"):
                builtin_tool_list.append("python")
425
426
            if self.tool_server.has_tool("container"):
                builtin_tool_list.append("container")
427

428
429
430
431
432
433
        if self.tool_server is not None:
            available_tools = builtin_tool_list
        else:
            assert len(builtin_tool_list) == 0
            available_tools = []
        try:
434
            for engine_prompt in engine_prompts:
435
436
437
438
                maybe_error = self._validate_generator_input(engine_prompt)
                if maybe_error is not None:
                    return maybe_error

439
440
441
442
443
                default_max_tokens = get_max_tokens(
                    self.max_model_len,
                    request,
                    engine_prompt,
                    self.default_sampling_params,
444
                )
445

446
                sampling_params = request.to_sampling_params(
447
448
                    default_max_tokens, self.default_sampling_params
                )
449

450
451
452
453
454
                trace_headers = (
                    None
                    if raw_request is None
                    else await self._get_trace_headers(raw_request.headers)
                )
455
456
457
458

                context: ConversationContext
                if self.use_harmony:
                    if request.stream:
459
                        context = StreamingHarmonyContext(messages, available_tools)
460
461
462
                    else:
                        context = HarmonyContext(messages, available_tools)
                else:
463
                    if envs.VLLM_USE_EXPERIMENTAL_PARSER_CONTEXT:
464
                        # This is a feature in development for parsing
465
466
467
                        # tokens during generation instead of at the end
                        context = ParsableContext(
                            response_messages=messages,
468
                            renderer=renderer,
469
470
                            reasoning_parser_cls=self.reasoning_parser,
                            request=request,
471
472
473
474
                            tool_parser_cls=self.tool_parser,
                            available_tools=available_tools,
                            chat_template=self.chat_template,
                            chat_template_content_format=self.chat_template_content_format,
475
476
477
                        )
                    else:
                        context = SimpleContext()
478
479
480

                if self.reasoning_parser is not None:
                    reasoning_parser = self.reasoning_parser(tokenizer)
481
482
483
484
485
486
487
488
489
490
491
492
                    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
                            ),
493
                        )
494
495
496
497
498
499
500
501
                generator = self._generate_with_builtin_tools(
                    request_id=request.request_id,
                    engine_prompt=engine_prompt,
                    sampling_params=sampling_params,
                    context=context,
                    lora_request=lora_request,
                    priority=request.priority,
                    trace_headers=trace_headers,
502
                )
503
504
                generators.append(generator)
        except ValueError as e:
505
            return self.create_error_response(e)
506

507
        assert len(generators) == 1
508
        (result_generator,) = generators
509
510
511
512

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

514
515
516
517
518
519
520
521
522
523
524
525
526
        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
527

528
            # Run the request in the background.
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
            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}",
                )
557

558
559
560
561
            # For cleanup.
            response_id = response.id
            self.background_tasks[response_id] = task
            task.add_done_callback(
562
563
                lambda _: self.background_tasks.pop(response_id, None)
            )
564
565

            if request.stream:
566
                return self.responses_background_stream_generator(request.request_id)
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
            return response

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

        try:
            return await self.responses_full_generator(
                request,
                sampling_params,
                result_generator,
                context,
                model_name,
                tokenizer,
                request_metadata,
            )
590
591
        except GenerationError as e:
            return self._convert_generation_error_to_response(e)
592
        except Exception as e:
593
            return self.create_error_response(e)
594

595
596
597
    async def _make_request(
        self,
        request: ResponsesRequest,
598
        prev_response: ResponsesResponse | None,
599
        renderer: RendererLike,
600
    ):
601
        tool_dicts = construct_tool_dicts(request.tools, request.tool_choice)
602
        # Construct the input messages.
603
604
605
606
607
608
        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,
        )
609
610
611
612
        # Check if we should continue the final message (partial completion)
        # This enables Anthropic-style partial message completion where the
        # user provides an incomplete assistant message to continue from.
        continue_final = should_continue_final_message(request.input)
613
614
615
616
617
618
        chat_template_kwargs = dict(
            reasoning_effort=None
            if request.reasoning is None
            else request.reasoning.effort
        )

619
        _, engine_prompts = await self._preprocess_chat(
620
            request,
621
            renderer,
622
            messages,
623
624
            tool_dicts=tool_dicts,
            tool_parser=self.tool_parser,
625
626
            chat_template=self.chat_template,
            chat_template_content_format=self.chat_template_content_format,
627
628
629
630
631
            # When continuing a partial message, we set continue_final_message=True
            # and add_generation_prompt=False so the model continues the message
            # rather than starting a new one.
            add_generation_prompt=not continue_final,
            continue_final_message=continue_final,
632
            chat_template_kwargs=chat_template_kwargs,
633
        )
634
        return messages, engine_prompts
635
636
637
638

    def _make_request_with_harmony(
        self,
        request: ResponsesRequest,
639
        prev_response: ResponsesResponse | None,
640
641
642
    ):
        if request.tool_choice != "auto":
            raise NotImplementedError(
643
644
                "Only 'auto' tool_choice is supported in response API with Harmony"
            )
645

646
        messages = self._construct_input_messages_with_harmony(request, prev_response)
647
        prompt_token_ids = render_for_completion(messages)
648
        engine_prompt = TokensPrompt(prompt_token_ids=prompt_token_ids)
649
650
651
652
653

        # Add cache_salt if provided in the request
        if request.cache_salt is not None:
            engine_prompt["cache_salt"] = request.cache_salt

654
        return messages, [engine_prompt]
655

656
657
658
659
660
661
    async def _initialize_tool_sessions(
        self,
        request: ResponsesRequest,
        context: ConversationContext,
        exit_stack: AsyncExitStack,
    ):
662
663
664
665
        # we should only initialize the tool session if the request needs tools
        if len(request.tools) == 0:
            return
        mcp_tools = {
666
            tool.server_label: tool for tool in request.tools if tool.type == "mcp"
667
        }
668
669
670
        await context.init_tool_sessions(
            self.tool_server, exit_stack, request.request_id, mcp_tools
        )
671

672
673
674
675
    async def responses_full_generator(
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
676
        result_generator: AsyncIterator[ConversationContext],
677
        context: ConversationContext,
678
        model_name: str,
679
        tokenizer: TokenizerLike,
680
        request_metadata: RequestResponseMetadata,
681
682
        created_time: int | None = None,
    ) -> ErrorResponse | ResponsesResponse:
683
684
685
        if created_time is None:
            created_time = int(time.time())

686
687
        async with AsyncExitStack() as exit_stack:
            try:
688
                await self._initialize_tool_sessions(request, context, exit_stack)
689
690
691
692
693
                async for _ in result_generator:
                    pass
            except asyncio.CancelledError:
                return self.create_error_response("Client disconnected")
            except ValueError as e:
694
                return self.create_error_response(e)
695

696
697
698
699
700
        # NOTE: Implementation of stauts is still WIP, but for now
        # we guarantee that if the status is not "completed", it is accurate.
        # "completed" is implemented as the "catch-all" for now.
        status: ResponseStatus = "completed"

701
702
        input_messages: ResponseInputOutputMessage | None = None
        output_messages: ResponseInputOutputMessage | None = None
703
704
705
        if self.use_harmony:
            assert isinstance(context, HarmonyContext)
            output = self._make_response_output_items_with_harmony(context)
706
            if request.enable_response_messages:
707
708
                input_messages = context.messages[: context.num_init_messages]
                output_messages = context.messages[context.num_init_messages :]
709
            num_tool_output_tokens = context.num_tool_output_tokens
710
711
712
713
714
            if len(output) > 0:
                if context.finish_reason == "length":
                    status = "incomplete"
                elif context.finish_reason == "abort":
                    status = "cancelled"
715
716
                else:
                    self._raise_if_error(context.finish_reason, request.request_id)
717
718
            else:
                status = "incomplete"
719
        elif isinstance(context, ParsableContext):
720
            output = context.parser.make_response_output_items_from_parsable_context()
721
722

            if request.enable_response_messages:
723
724
                input_messages = context.input_messages
                output_messages = context.output_messages
725
726
727
728

            # TODO: Calculate usage.
            # assert final_res.prompt_token_ids is not None
            num_tool_output_tokens = 0
729
730
731
732

            # Check finish reason from the parser
            if context.parser.finish_reason == "length":
                status = "incomplete"
733
        else:
734
            assert isinstance(context, SimpleContext)
735
736
            # Use final_output which has accumulated text/token_ids/logprobs
            final_res = context.final_output
737
738
739
740
            assert final_res is not None
            assert len(final_res.outputs) == 1
            final_output = final_res.outputs[0]

741
742
743
            # finish_reason='error' indicates retryable internal error
            self._raise_if_error(final_output.finish_reason, request.request_id)

744
745
746
747
            # Check if generation was stopped due to max_tokens
            if final_output.finish_reason == "length":
                status = "incomplete"

748
            output = self._make_response_output_items(request, final_output, tokenizer)
749

750
            if request.enable_response_messages:
751
752
753
                input_messages = context.input_messages
                output_messages = context.output_messages

754
755
            # Calculate usage.
            assert final_res.prompt_token_ids is not None
756
757
            num_tool_output_tokens = 0

758
        assert isinstance(context, (SimpleContext, HarmonyContext, ParsableContext))
759
760
761
762
        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
763
764
765
766

        usage = ResponseUsage(
            input_tokens=num_prompt_tokens,
            output_tokens=num_generated_tokens,
767
            total_tokens=num_prompt_tokens + num_generated_tokens,
768
769
770
771
772
773
774
775
776
            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
                ],
            ),
777
            output_tokens_details=OutputTokensDetails(
778
                reasoning_tokens=num_reasoning_tokens,
779
                tool_output_tokens=num_tool_output_tokens,
780
781
782
783
784
785
                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
                ],
786
            ),
787
788
789
790
        )
        response = ResponsesResponse.from_request(
            request,
            sampling_params,
791
792
            input_messages=input_messages,
            output_messages=output_messages,
793
794
795
            model_name=model_name,
            created_time=created_time,
            output=output,
796
            status=status,
797
798
799
800
801
802
803
            usage=usage,
        )

        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.
804
                if stored_response is None or stored_response.status != "cancelled":
805
806
807
                    self.response_store[response.id] = response
        return response

808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
    def _is_mcp_tool_by_namespace(self, recipient: str | None) -> bool:
        """
        Determine if a tool call is an MCP tool based on recipient prefix.

        - Tools starting with "functions." are function calls
        - Everything else is an MCP tool
        """
        if recipient is None:
            return False

        # Function calls have "functions." prefix
        # Everything else is an MCP tool
        return not recipient.startswith("functions.")

    _TOOL_NAME_TO_MCP_SERVER_LABEL: Final[dict[str, str]] = {
        "python": "code_interpreter",
        "container": "container",
        "browser": "web_search_preview",
    }

828
829
830
831
    def _topk_logprobs(
        self,
        logprobs: dict[int, SampleLogprob],
        top_logprobs: int,
832
        tokenizer: TokenizerLike,
833
    ) -> list[LogprobTopLogprob]:
834
835
836
837
838
        """Returns the top-k logprobs from the logprobs dictionary."""
        out = []
        for i, (token_id, _logprob) in enumerate(logprobs.items()):
            if i >= top_logprobs:
                break
839
840
841
842
843
            text = (
                _logprob.decoded_token
                if _logprob.decoded_token is not None
                else tokenizer.decode([token_id])
            )
844
845
846
847
848
            out.append(
                LogprobTopLogprob(
                    token=text,
                    logprob=max(_logprob.logprob, -9999.0),
                    bytes=list(text.encode("utf-8", errors="replace")),
849
850
                )
            )
851
852
853
        return out

    def _create_response_logprobs(
854
855
        self,
        token_ids: Sequence[int],
856
        logprobs: SampleLogprobs | None,
857
        tokenizer: TokenizerLike,
858
        top_logprobs: int | None = None,
859
    ) -> list[Logprob]:
860
861
        assert logprobs is not None, "logprobs must be provided"
        assert len(token_ids) == len(logprobs), (
862
863
            "token_ids and logprobs.token_ids must have the same length"
        )
864
865
866
867
        out = []
        for i, token_id in enumerate(token_ids):
            logprob = logprobs[i]
            token_logprob = logprob[token_id]
868
869
870
871
872
            text = (
                token_logprob.decoded_token
                if token_logprob.decoded_token is not None
                else tokenizer.decode([token_id])
            )
873
874
875
876
877
            out.append(
                Logprob(
                    token=text,
                    logprob=max(token_logprob.logprob, -9999.0),
                    bytes=list(text.encode("utf-8", errors="replace")),
878
879
880
881
882
883
884
                    top_logprobs=(
                        self._topk_logprobs(
                            logprob, top_logprobs=top_logprobs, tokenizer=tokenizer
                        )
                        if top_logprobs
                        else []
                    ),
885
886
                )
            )
887
888
        return out

889
890
891
    def _create_stream_response_logprobs(
        self,
        token_ids: Sequence[int],
892
        logprobs: SampleLogprobs | None,
893
        tokenizer: TokenizerLike,
894
        top_logprobs: int | None = None,
895
    ) -> list[response_text_delta_event.Logprob]:
896
897
898
899
900
901
        lgs = self._create_response_logprobs(
            token_ids=token_ids,
            logprobs=logprobs,
            tokenizer=tokenizer,
            top_logprobs=top_logprobs,
        )
902
903
904
905
906
907
        return [
            response_text_delta_event.Logprob(
                token=lg.token,
                logprob=lg.logprob,
                top_logprobs=[
                    response_text_delta_event.LogprobTopLogprob(
908
909
                        token=tl.token, logprob=tl.logprob
                    )
910
                    for tl in lg.top_logprobs
911
912
913
                ],
            )
            for lg in lgs
914
915
        ]

916
917
918
919
    def _make_response_output_items(
        self,
        request: ResponsesRequest,
        final_output: CompletionOutput,
920
        tokenizer: TokenizerLike,
921
922
923
924
925
926
927
928
    ) -> list[ResponseOutputItem]:
        if self.reasoning_parser:
            try:
                reasoning_parser = self.reasoning_parser(tokenizer)
            except RuntimeError as e:
                logger.exception("Error in reasoning parser creation.")
                raise e

929
            reasoning, content = reasoning_parser.extract_reasoning(
930
931
                final_output.text, request=request
            )
932
        else:
933
            reasoning = None
934
935
            content = final_output.text

936
937
938
939
940
        # Log complete response if output logging is enabled
        if self.enable_log_outputs and self.request_logger:
            output_text = ""
            if content:
                output_text = content
941
942
            elif reasoning:
                output_text = f"[reasoning: {reasoning}]"
943
944
945
946
947
948
949
950
951
952
953

            if output_text:
                self.request_logger.log_outputs(
                    request_id=request.request_id,
                    outputs=output_text,
                    output_token_ids=final_output.token_ids,
                    finish_reason=final_output.finish_reason,
                    is_streaming=False,
                    delta=False,
                )

954
955
        reasoning_item = None
        message_item = None
956
        if reasoning:
957
958
959
960
961
            reasoning_item = ResponseReasoningItem(
                id=f"rs_{random_uuid()}",
                summary=[],
                type="reasoning",
                content=[
962
                    ResponseReasoningTextContent(text=reasoning, type="reasoning_text")
963
964
965
                ],
                status=None,  # NOTE: Only the last output item has status.
            )
966
967
968
969
970
971
972
        tool_calls, content = self._parse_tool_calls_from_content(
            request=request,
            tokenizer=tokenizer,
            content=content,
            enable_auto_tools=self.enable_auto_tools,
            tool_parser_cls=self.tool_parser,
        )
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991

        if content or (self.use_harmony and tool_calls):
            res_text_part = None
            if content:
                res_text_part = ResponseOutputText(
                    text=content,
                    annotations=[],  # TODO
                    type="output_text",
                    logprobs=(
                        self._create_response_logprobs(
                            token_ids=final_output.token_ids,
                            logprobs=final_output.logprobs,
                            tokenizer=tokenizer,
                            top_logprobs=request.top_logprobs,
                        )
                        if request.is_include_output_logprobs()
                        else None
                    ),
                )
992
            message_item = ResponseOutputMessage(
993
                id=f"msg_{random_uuid()}",
994
                content=[res_text_part] if res_text_part else [],
995
996
997
998
                role="assistant",
                status="completed",
                type="message",
            )
999
1000
1001
1002
1003
1004
1005
        outputs = []

        if reasoning_item:
            outputs.append(reasoning_item)
        if message_item:
            outputs.append(message_item)
        if tool_calls:
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
            # We use a simple counter for history_tool_call_count because
            # we don't track the history of tool calls in the Responses API yet.
            # This means that the tool call index will start from 0 for each
            # request.
            tool_call_items = []
            for history_tool_call_cnt, tool_call in enumerate(tool_calls):
                tool_call_items.append(
                    ResponseFunctionToolCall(
                        id=f"fc_{random_uuid()}",
                        call_id=tool_call.id
                        if tool_call.id
                        else make_tool_call_id(
                            id_type=self.tool_call_id_type,
                            func_name=tool_call.name,
                            idx=history_tool_call_cnt,
                        ),
                        type="function_call",
                        status="completed",
                        name=tool_call.name,
                        arguments=tool_call.arguments,
                    )
1027
1028
1029
                )
            outputs.extend(tool_call_items)
        return outputs
1030
1031
1032
1033
1034

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

1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
    def _extract_system_message_from_request(self, request) -> str | None:
        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"
                ):
                    system_msg = response_msg.get("content")
                    break
        return system_msg

1057
    def _construct_harmony_system_input_message(
1058
        self, request: ResponsesRequest, with_custom_tools: bool, tool_types: set[str]
1059
    ) -> OpenAIHarmonyMessage:
1060
1061
        model_identity = self._extract_system_message_from_request(request)

1062
        reasoning_effort = request.reasoning.effort if request.reasoning else None
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073

        # 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
1074
1075
            and self.tool_server is not None
            and self.tool_server.has_tool("browser")
1076
            else None
1077
        )
1078
1079
1080
1081
1082
        python_description = (
            self.tool_server.get_tool_description(
                "python", allowed_tools_map.get("code_interpreter")
            )
            if "code_interpreter" in tool_types
1083
1084
            and self.tool_server is not None
            and self.tool_server.has_tool("python")
1085
            else None
1086
        )
1087
1088
1089
1090
1091
        container_description = (
            self.tool_server.get_tool_description(
                "container", allowed_tools_map.get("container")
            )
            if "container" in tool_types
1092
1093
            and self.tool_server is not None
            and self.tool_server.has_tool("container")
1094
            else None
1095
        )
1096

1097
        sys_msg = get_system_message(
1098
            model_identity=model_identity,
1099
            reasoning_effort=reasoning_effort,
1100
1101
1102
            browser_description=browser_description,
            python_description=python_description,
            container_description=container_description,
1103
1104
1105
1106
1107
            instructions=request.instructions,
            with_custom_tools=with_custom_tools,
        )
        return sys_msg

1108
1109
1110
    def _construct_input_messages_with_harmony(
        self,
        request: ResponsesRequest,
1111
        prev_response: ResponsesResponse | None,
1112
1113
1114
1115
    ) -> list[OpenAIHarmonyMessage]:
        messages: list[OpenAIHarmonyMessage] = []
        if prev_response is None:
            # New conversation.
1116
            tool_types = extract_tool_types(request.tools)
1117
            with_custom_tools = has_custom_tools(tool_types)
1118
1119
1120

            sys_msg = self._construct_harmony_system_input_message(
                request, with_custom_tools, tool_types
1121
1122
            )
            messages.append(sys_msg)
1123
1124
            if with_custom_tools:
                dev_msg = get_developer_message(
1125
1126
                    instructions=request.instructions, tools=request.tools
                )
1127
                messages.append(dev_msg)
1128
1129
            messages += construct_harmony_previous_input_messages(request)

1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
        else:
            # Continue the previous conversation.
            # FIXME(woosuk): Currently, request params like reasoning and
            # instructions are ignored.
            prev_msgs = self.msg_store[prev_response.id]
            # Remove the previous chain-of-thoughts if there is a new "final"
            # message. Note that this also removes these messages from the
            # msg_store.
            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
1149
1150
                    recent_turn_msgs = prev_msgs[prev_final_msg_idx + 1 :]
                    del prev_msgs[prev_final_msg_idx + 1 :]
1151
1152
                    for msg in recent_turn_msgs:
                        assert isinstance(msg, OpenAIHarmonyMessage)
1153
                        prev_msgs.append(msg)
1154
1155
            messages.extend(prev_msgs)
        # Append the new input.
co63oc's avatar
co63oc committed
1156
        # Responses API supports simple text inputs without chat format.
1157
1158
1159
1160
1161
1162
1163
1164
        if isinstance(request.input, str):
            messages.append(get_user_message(request.input))
        else:
            if prev_response is not None:
                prev_outputs = copy(prev_response.output)
            else:
                prev_outputs = []
            for response_msg in request.input:
1165
1166
1167
1168
                new_msg = parse_response_input(response_msg, prev_outputs)
                if new_msg.author.role != "system":
                    messages.append(new_msg)

1169
                # User passes in a tool call request and its output. We need
1170
1171
1172
1173
1174
1175
1176
                # to add the tool call request to prev_outputs so that the
                # parse_response_input can find the tool call request when
                # parsing the tool call output.
                if isinstance(response_msg, ResponseFunctionToolCall):
                    prev_outputs.append(response_msg)
        return messages

1177
1178
1179
1180
1181
1182
    async def _run_background_request_stream(
        self,
        request: ResponsesRequest,
        *args,
        **kwargs,
    ):
1183
        event_deque: deque[StreamingResponsesResponse] = deque()
1184
1185
1186
1187
        new_event_signal = asyncio.Event()
        self.event_store[request.request_id] = (event_deque, new_event_signal)
        response = None
        try:
1188
            generator = self.responses_stream_generator(request, *args, **kwargs)
1189
1190
1191
            async for event in generator:
                event_deque.append(event)
                new_event_signal.set()  # Signal new event available
1192
1193
        except GenerationError as e:
            response = self._convert_generation_error_to_response(e)
1194
        except Exception as e:
1195
            logger.exception("Background request failed for %s", request.request_id)
1196
            response = self.create_error_response(e)
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
        finally:
            new_event_signal.set()

        if response is not None and 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"

1209
1210
1211
1212
1213
1214
1215
    async def _run_background_request(
        self,
        request: ResponsesRequest,
        *args,
        **kwargs,
    ):
        try:
1216
            response = await self.responses_full_generator(request, *args, **kwargs)
1217
1218
        except GenerationError as e:
            response = self._convert_generation_error_to_response(e)
1219
        except Exception as e:
1220
            logger.exception("Background request failed for %s", request.request_id)
1221
            response = self.create_error_response(e)
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231

        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"

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

        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
1255
                if getattr(event, "type", "unknown") == "response.completed":
1256
                    return
1257
1258
1259
1260
                current_index += 1

            await new_event_signal.wait()

1261
1262
1263
    async def retrieve_responses(
        self,
        response_id: str,
1264
1265
1266
1267
1268
1269
1270
        starting_after: int | None,
        stream: bool | None,
    ) -> (
        ErrorResponse
        | ResponsesResponse
        | AsyncGenerator[StreamingResponsesResponse, None]
    ):
1271
1272
1273
1274
1275
        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)
1276
1277
1278
1279
1280
1281

        if stream:
            return self.responses_background_stream_generator(
                response_id,
                starting_after,
            )
1282
1283
1284
1285
1286
        return response

    async def cancel_responses(
        self,
        response_id: str,
1287
    ) -> ErrorResponse | ResponsesResponse:
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
        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.",
1298
                    param="response_id",
1299
1300
1301
1302
1303
1304
                )

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

        # Abort the request.
1305
        if task := self.background_tasks.get(response_id):
1306
1307
1308
1309
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
1310
                logger.exception("Background task for %s was cancelled", response_id)
1311
1312
1313
1314
1315
1316
1317
        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,
1318
            param="response_id",
1319
        )
1320
1321
1322
1323

    def _make_store_not_supported_error(self) -> ErrorResponse:
        return self.create_error_response(
            err_type="invalid_request_error",
1324
1325
1326
1327
1328
1329
            message=(
                "`store=True` (default) is not supported. Please set "
                "`store=False` in Responses API or set "
                "`VLLM_ENABLE_RESPONSES_API_STORE=1` in the env var when "
                "starting the vLLM server."
            ),
1330
            status_code=HTTPStatus.BAD_REQUEST,
1331
            param="store",
1332
        )
1333

1334
    async def _process_simple_streaming_events(
1335
1336
1337
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
1338
        result_generator: AsyncIterator[ConversationContext | None],
1339
1340
        context: ConversationContext,
        model_name: str,
1341
        tokenizer: TokenizerLike,
1342
        request_metadata: RequestResponseMetadata,
1343
        created_time: int,
1344
        _increment_sequence_number_and_return: Callable[
1345
1346
            [StreamingResponsesResponse], StreamingResponsesResponse
        ],
1347
    ) -> AsyncGenerator[StreamingResponsesResponse, None]:
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
        current_content_index = 0
        current_output_index = 0
        current_item_id = ""
        reasoning_parser = None
        if self.reasoning_parser:
            reasoning_parser = self.reasoning_parser(tokenizer)
        previous_text = ""
        previous_token_ids: list[int] = []
        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
            if ctx.last_output.outputs:
                output = ctx.last_output.outputs[0]
1364
1365
                # finish_reason='error' indicates a retryable error
                self._raise_if_error(output.finish_reason, request.request_id)
1366
                if reasoning_parser:
1367
1368
1369
1370
1371
1372
1373
                    delta_message = reasoning_parser.extract_reasoning_streaming(
                        previous_text=previous_text,
                        current_text=previous_text + output.text,
                        delta_text=output.text,
                        previous_token_ids=previous_token_ids,
                        current_token_ids=previous_token_ids + output.token_ids,
                        delta_token_ids=output.token_ids,
1374
1375
                    )
                else:
1376
1377
1378
                    delta_message = DeltaMessage(
                        content=output.text,
                    )
1379
1380
1381
1382
1383
1384
                previous_text += output.text
                previous_token_ids += output.token_ids
                if not delta_message:
                    continue
                if not first_delta_sent:
                    current_item_id = str(uuid.uuid4())
1385
                    if delta_message.reasoning:
1386
                        yield _increment_sequence_number_and_return(
1387
1388
1389
1390
                            ResponseOutputItemAddedEvent(
                                type="response.output_item.added",
                                sequence_number=-1,
                                output_index=current_output_index,
1391
                                item=ResponseReasoningItem(
1392
1393
1394
1395
1396
                                    type="reasoning",
                                    id=current_item_id,
                                    summary=[],
                                    status="in_progress",
                                ),
1397
1398
                            )
                        )
1399
                    else:
1400
                        yield _increment_sequence_number_and_return(
1401
1402
1403
1404
                            ResponseOutputItemAddedEvent(
                                type="response.output_item.added",
                                sequence_number=-1,
                                output_index=current_output_index,
1405
                                item=ResponseOutputMessage(
1406
1407
1408
1409
1410
1411
                                    id=current_item_id,
                                    type="message",
                                    role="assistant",
                                    content=[],
                                    status="in_progress",
                                ),
1412
1413
                            )
                        )
1414
                    yield _increment_sequence_number_and_return(
1415
                        ResponseContentPartAddedEvent(
1416
1417
1418
1419
1420
                            type="response.content_part.added",
                            sequence_number=-1,
                            output_index=current_output_index,
                            item_id=current_item_id,
                            content_index=current_content_index,
1421
                            part=ResponseOutputText(
1422
1423
1424
1425
1426
                                type="output_text",
                                text="",
                                annotations=[],
                                logprobs=[],
                            ),
1427
1428
                        )
                    )
1429
1430
1431
1432
1433
1434
                    current_content_index += 1
                    first_delta_sent = True
                # todo(kebe7jun) tool call support

                # check delta message and previous delta message are
                # same as content or reasoning content
1435
1436
                if (
                    previous_delta_messages
1437
                    and previous_delta_messages[-1].reasoning is not None
1438
1439
                    and delta_message.content is not None
                ):
1440
1441
                    # from reasoning to normal content, send done
                    # event for reasoning
1442
                    reason_content = "".join(
1443
                        pm.reasoning
1444
                        for pm in previous_delta_messages
1445
                        if pm.reasoning is not None
1446
                    )
1447
                    yield _increment_sequence_number_and_return(
1448
1449
1450
1451
1452
1453
1454
                        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,
1455
1456
                        )
                    )
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
                    current_content_index = 0
                    reasoning_item = ResponseReasoningItem(
                        type="reasoning",
                        content=[
                            ResponseReasoningTextContent(
                                text=reason_content,
                                type="reasoning_text",
                            ),
                        ],
                        status="completed",
                        id=current_item_id,
                        summary=[],
                    )
1470
                    yield _increment_sequence_number_and_return(
1471
1472
1473
1474
1475
                        ResponseOutputItemDoneEvent(
                            type="response.output_item.done",
                            sequence_number=-1,
                            output_index=current_output_index,
                            item=reasoning_item,
1476
1477
                        )
                    )
1478
                    yield _increment_sequence_number_and_return(
1479
                        ResponseOutputItemAddedEvent(
1480
1481
1482
                            type="response.output_item.added",
                            sequence_number=-1,
                            output_index=current_output_index,
1483
                            item=ResponseOutputMessage(
1484
1485
1486
1487
1488
1489
                                id=current_item_id,
                                type="message",
                                role="assistant",
                                content=[],
                                status="in_progress",
                            ),
1490
1491
                        )
                    )
1492
1493
                    current_output_index += 1
                    current_item_id = str(uuid.uuid4())
1494
                    yield _increment_sequence_number_and_return(
1495
                        ResponseContentPartAddedEvent(
1496
1497
1498
1499
1500
                            type="response.content_part.added",
                            sequence_number=-1,
                            output_index=current_output_index,
                            item_id=current_item_id,
                            content_index=current_content_index,
1501
                            part=ResponseOutputText(
1502
1503
1504
1505
1506
                                type="output_text",
                                text="",
                                annotations=[],
                                logprobs=[],
                            ),
1507
1508
                        )
                    )
1509
1510
1511
                    current_content_index += 1
                    # reset previous delta messages
                    previous_delta_messages = []
1512

1513
                if delta_message.reasoning is not None:
1514
                    yield _increment_sequence_number_and_return(
1515
1516
1517
1518
1519
1520
                        ResponseReasoningTextDeltaEvent(
                            type="response.reasoning_text.delta",
                            sequence_number=-1,
                            content_index=current_content_index,
                            output_index=current_output_index,
                            item_id=current_item_id,
1521
                            delta=delta_message.reasoning,
1522
1523
                        )
                    )
1524
                elif delta_message.content is not None:
1525
                    yield _increment_sequence_number_and_return(
1526
                        ResponseTextDeltaEvent(
1527
1528
1529
1530
1531
1532
                            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,
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
                            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 []
                            ),
1543
1544
                        )
                    )
1545
1546
1547
1548
                current_content_index += 1

                previous_delta_messages.append(delta_message)
        if previous_delta_messages:
1549
            if previous_delta_messages[-1].reasoning is not None:
1550
                reason_content = "".join(
1551
                    pm.reasoning
1552
                    for pm in previous_delta_messages
1553
                    if pm.reasoning is not None
1554
                )
1555
                yield _increment_sequence_number_and_return(
1556
1557
1558
1559
1560
1561
1562
                    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,
1563
1564
                    )
                )
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
                current_content_index += 1
                reasoning_item = ResponseReasoningItem(
                    type="reasoning",
                    content=[
                        ResponseReasoningTextContent(
                            text=reason_content,
                            type="reasoning_text",
                        ),
                    ],
                    status="completed",
                    id=current_item_id,
                    summary=[],
                )
1578
                yield _increment_sequence_number_and_return(
1579
1580
1581
1582
1583
                    ResponseOutputItemDoneEvent(
                        type="response.output_item.done",
                        sequence_number=-1,
                        output_index=current_output_index,
                        item=reasoning_item,
1584
1585
                    )
                )
1586
            elif previous_delta_messages[-1].content is not None:
1587
1588
1589
1590
1591
                final_content = "".join(
                    pm.content
                    for pm in previous_delta_messages
                    if pm.content is not None
                )
1592
                yield _increment_sequence_number_and_return(
1593
                    ResponseTextDoneEvent(
1594
1595
1596
1597
1598
1599
1600
                        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,
1601
1602
                    )
                )
1603
1604
1605
1606
1607
1608
                current_content_index += 1
                part = ResponseOutputText(
                    text=final_content,
                    type="output_text",
                    annotations=[],
                )
1609
                yield _increment_sequence_number_and_return(
1610
                    ResponseContentPartDoneEvent(
1611
1612
1613
1614
1615
1616
                        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,
1617
1618
                    )
                )
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
                current_content_index += 1
                item = ResponseOutputMessage(
                    type="message",
                    role="assistant",
                    content=[
                        part,
                    ],
                    status="completed",
                    id=current_item_id,
                    summary=[],
                )
1630
                yield _increment_sequence_number_and_return(
1631
1632
1633
1634
1635
                    ResponseOutputItemDoneEvent(
                        type="response.output_item.done",
                        sequence_number=-1,
                        output_index=current_output_index,
                        item=item,
1636
1637
                    )
                )
1638

1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
    def _emit_function_call_done_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events when a function call completes."""
        function_name = previous_item.recipient[len("functions.") :]
        events = []
        events.append(
            ResponseFunctionCallArgumentsDoneEvent(
                type="response.function_call_arguments.done",
                arguments=previous_item.content[0].text,
                name=function_name,
                item_id=state.current_item_id,
                output_index=state.current_output_index,
                sequence_number=-1,
            )
        )
        function_call_item = ResponseFunctionToolCall(
            type="function_call",
            arguments=previous_item.content[0].text,
            name=function_name,
            item_id=state.current_item_id,
            output_index=state.current_output_index,
            sequence_number=-1,
            call_id=f"fc_{random_uuid()}",
            status="completed",
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=function_call_item,
            )
        )
        return events

    def _emit_mcp_call_done_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events when an MCP tool call completes."""
        server_label = self._TOOL_NAME_TO_MCP_SERVER_LABEL.get(
            previous_item.recipient, previous_item.recipient
        )
        events = []
        events.append(
            ResponseMcpCallArgumentsDoneEvent(
                type="response.mcp_call_arguments.done",
                arguments=previous_item.content[0].text,
                name=previous_item.recipient,
                item_id=state.current_item_id,
                output_index=state.current_output_index,
                sequence_number=-1,
            )
        )
        events.append(
            ResponseMcpCallCompletedEvent(
                type="response.mcp_call.completed",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=McpCall(
                    type="mcp_call",
                    arguments=previous_item.content[0].text,
                    name=previous_item.recipient,
                    id=state.current_item_id,
                    server_label=server_label,
                    status="completed",
                ),
            )
        )
        return events

    def _emit_reasoning_done_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events when a reasoning (analysis) item completes."""
        content = ResponseReasoningTextContent(
            text=previous_item.content[0].text,
            type="reasoning_text",
        )
        reasoning_item = ResponseReasoningItem(
            type="reasoning",
            content=[content],
            status="completed",
            id=state.current_item_id,
            summary=[],
        )
        events = []
        events.append(
            ResponseReasoningTextDoneEvent(
                type="response.reasoning_text.done",
                item_id=state.current_item_id,
                sequence_number=-1,
                output_index=state.current_output_index,
                content_index=state.current_content_index,
                text=previous_item.content[0].text,
            )
        )
        events.append(
            ResponseReasoningPartDoneEvent(
                type="response.reasoning_part.done",
                sequence_number=-1,
                item_id=state.current_item_id,
                output_index=state.current_output_index,
                content_index=state.current_content_index,
                part=content,
            )
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=reasoning_item,
            )
        )
        return events

    def _emit_text_output_done_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events when a final text output item completes."""
        text_content = ResponseOutputText(
            type="output_text",
            text=previous_item.content[0].text,
            annotations=[],
        )
        events = []
        events.append(
            ResponseTextDoneEvent(
                type="response.output_text.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                content_index=state.current_content_index,
                text=previous_item.content[0].text,
                logprobs=[],
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseContentPartDoneEvent(
                type="response.content_part.done",
                sequence_number=-1,
                item_id=state.current_item_id,
                output_index=state.current_output_index,
                content_index=state.current_content_index,
                part=text_content,
            )
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=ResponseOutputMessage(
                    id=state.current_item_id,
                    type="message",
                    role="assistant",
                    content=[text_content],
                    status="completed",
                ),
            )
        )
        return events

    def _emit_previous_item_done_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit done events for the previous item when expecting a new start."""
        if previous_item.recipient is not None:
            # Deal with tool call
            if previous_item.recipient.startswith("functions."):
                return self._emit_function_call_done_events(previous_item, state)
            elif (
                self._is_mcp_tool_by_namespace(previous_item.recipient)
                and state.current_item_id is not None
                and state.current_item_id.startswith("mcp_")
            ):
                return self._emit_mcp_call_done_events(previous_item, state)
        elif previous_item.channel == "analysis":
            return self._emit_reasoning_done_events(previous_item, state)
        elif previous_item.channel == "final":
            return self._emit_text_output_done_events(previous_item, state)
        return []

    def _emit_final_channel_delta_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for final channel text delta streaming."""
        events = []
        if not state.sent_output_item_added:
            state.sent_output_item_added = True
            state.current_item_id = f"msg_{random_uuid()}"
            events.append(
                ResponseOutputItemAddedEvent(
                    type="response.output_item.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item=ResponseOutputMessage(
                        id=state.current_item_id,
                        type="message",
                        role="assistant",
                        content=[],
                        status="in_progress",
                    ),
                )
            )
            state.current_content_index += 1
            events.append(
                ResponseContentPartAddedEvent(
                    type="response.content_part.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item_id=state.current_item_id,
                    content_index=state.current_content_index,
                    part=ResponseOutputText(
                        type="output_text",
                        text="",
                        annotations=[],
                        logprobs=[],
                    ),
                )
            )
        events.append(
            ResponseTextDeltaEvent(
                type="response.output_text.delta",
                sequence_number=-1,
                content_index=state.current_content_index,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
1888
                delta=ctx.last_content_delta,
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
                # TODO, use logprobs from ctx.last_request_output
                logprobs=[],
            )
        )
        return events

    def _emit_analysis_channel_delta_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for analysis channel reasoning delta streaming."""
        events = []
        if not state.sent_output_item_added:
            state.sent_output_item_added = True
            state.current_item_id = f"msg_{random_uuid()}"
            events.append(
                ResponseOutputItemAddedEvent(
                    type="response.output_item.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item=ResponseReasoningItem(
                        type="reasoning",
                        id=state.current_item_id,
                        summary=[],
                        status="in_progress",
                    ),
                )
            )
            state.current_content_index += 1
            events.append(
                ResponseReasoningPartAddedEvent(
                    type="response.reasoning_part.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item_id=state.current_item_id,
                    content_index=state.current_content_index,
                    part=ResponseReasoningTextContent(
                        text="",
                        type="reasoning_text",
                    ),
                )
            )
        events.append(
            ResponseReasoningTextDeltaEvent(
                type="response.reasoning_text.delta",
                item_id=state.current_item_id,
                output_index=state.current_output_index,
                content_index=state.current_content_index,
1938
                delta=ctx.last_content_delta,
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
                sequence_number=-1,
            )
        )
        return events

    def _emit_mcp_tool_delta_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
        recipient: str,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for MCP tool delta streaming."""
        server_label = self._TOOL_NAME_TO_MCP_SERVER_LABEL.get(recipient, recipient)
        events = []
        if not state.sent_output_item_added:
            state.sent_output_item_added = True
            state.current_item_id = f"mcp_{random_uuid()}"
            events.append(
                ResponseOutputItemAddedEvent(
                    type="response.output_item.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item=McpCall(
                        type="mcp_call",
                        id=state.current_item_id,
                        name=recipient,
                        arguments="",
                        server_label=server_label,
                        status="in_progress",
                    ),
                )
            )
            events.append(
                ResponseMcpCallInProgressEvent(
                    type="response.mcp_call.in_progress",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item_id=state.current_item_id,
                )
            )
        events.append(
            ResponseMcpCallArgumentsDeltaEvent(
                type="response.mcp_call_arguments.delta",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
1985
                delta=ctx.last_content_delta,
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
            )
        )
        return events

    def _emit_code_interpreter_delta_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for code interpreter delta streaming."""
        events = []
        if not state.sent_output_item_added:
            state.sent_output_item_added = True
            state.current_item_id = f"tool_{random_uuid()}"
            events.append(
                ResponseOutputItemAddedEvent(
                    type="response.output_item.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item=ResponseCodeInterpreterToolCallParam(
                        type="code_interpreter_call",
                        id=state.current_item_id,
                        code=None,
                        container_id="auto",
                        outputs=None,
                        status="in_progress",
                    ),
                )
            )
            events.append(
                ResponseCodeInterpreterCallInProgressEvent(
                    type="response.code_interpreter_call.in_progress",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item_id=state.current_item_id,
                )
            )
        events.append(
            ResponseCodeInterpreterCallCodeDeltaEvent(
                type="response.code_interpreter_call_code.delta",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
2029
                delta=ctx.last_content_delta,
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
            )
        )
        return events

    def _emit_mcp_prefix_delta_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for MCP prefix (mcp.*) delta streaming."""
        events = []
        if not state.sent_output_item_added:
            state.sent_output_item_added = True
            state.current_item_id = f"mcp_{random_uuid()}"
            mcp_name = ctx.parser.current_recipient[len("mcp.") :]

            events.append(
                ResponseOutputItemAddedEvent(
                    type="response.output_item.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item=McpCall(
                        type="mcp_call",
                        id=state.current_item_id,
                        name=mcp_name,
                        arguments="",
                        server_label=mcp_name,
                        status="in_progress",
                    ),
                )
            )
            events.append(
                ResponseMcpCallInProgressEvent(
                    type="response.mcp_call.in_progress",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item_id=state.current_item_id,
                )
            )

        events.append(
            ResponseMcpCallArgumentsDeltaEvent(
                type="response.mcp_call_arguments.delta",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
2076
                delta=ctx.last_content_delta,
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
            )
        )
        return events

    def _emit_content_delta_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for content delta streaming based on channel type."""
2087
        if not ctx.last_content_delta:
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
            return []

        if (
            ctx.parser.current_channel == "final"
            and ctx.parser.current_recipient is None
        ):
            return self._emit_final_channel_delta_events(ctx, state)
        elif (
            ctx.parser.current_channel == "analysis"
            and ctx.parser.current_recipient is None
        ):
            return self._emit_analysis_channel_delta_events(ctx, state)
        # built-in tools will be triggered on the analysis channel
        # However, occasionally built-in tools will
        # still be output to commentary.
        elif (
            ctx.parser.current_channel == "commentary"
            or ctx.parser.current_channel == "analysis"
        ) and ctx.parser.current_recipient is not None:
            recipient = ctx.parser.current_recipient
            # Check for function calls first - they have their own event handling
            if recipient.startswith("functions."):
                return self._emit_function_call_delta_events(ctx, state)
            is_mcp_tool = self._is_mcp_tool_by_namespace(recipient)
            if is_mcp_tool:
                return self._emit_mcp_tool_delta_events(ctx, state, recipient)
            else:
                return self._emit_code_interpreter_delta_events(ctx, state)
        elif (
            (
                ctx.parser.current_channel == "commentary"
                or ctx.parser.current_channel == "analysis"
            )
            and ctx.parser.current_recipient is not None
            and ctx.parser.current_recipient.startswith("mcp.")
        ):
            return self._emit_mcp_prefix_delta_events(ctx, state)

        return []

    def _emit_browser_tool_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for browser tool calls (web search)."""
        function_name = previous_item.recipient[len("browser.") :]
        parsed_args = json.loads(previous_item.content[0].text)
        action = None

        if function_name == "search":
            action = response_function_web_search.ActionSearch(
                type="search",
                query=parsed_args["query"],
            )
        elif function_name == "open":
            action = response_function_web_search.ActionOpenPage(
                type="open_page",
                # TODO: translate to url
                url=f"cursor:{parsed_args.get('cursor', '')}",
            )
        elif function_name == "find":
            action = response_function_web_search.ActionFind(
                type="find",
                pattern=parsed_args["pattern"],
                # TODO: translate to url
                url=f"cursor:{parsed_args.get('cursor', '')}",
            )
        else:
            raise ValueError(f"Unknown function name: {function_name}")

        state.current_item_id = f"tool_{random_uuid()}"
        events = []
        events.append(
            ResponseOutputItemAddedEvent(
                type="response.output_item.added",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=response_function_web_search.ResponseFunctionWebSearch(
                    # TODO: generate a unique id for web search call
                    type="web_search_call",
                    id=state.current_item_id,
                    action=action,
                    status="in_progress",
                ),
            )
        )
        events.append(
            ResponseWebSearchCallInProgressEvent(
                type="response.web_search_call.in_progress",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseWebSearchCallSearchingEvent(
                type="response.web_search_call.searching",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        # enqueue
        events.append(
            ResponseWebSearchCallCompletedEvent(
                type="response.web_search_call.completed",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=ResponseFunctionWebSearch(
                    type="web_search_call",
                    id=state.current_item_id,
                    action=action,
                    status="completed",
                ),
            )
        )
        return events

    def _emit_mcp_tool_completion_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events when an MCP tool completes during assistant action turn."""
        recipient = previous_item.recipient
        server_label = self._TOOL_NAME_TO_MCP_SERVER_LABEL.get(recipient, recipient)
        events = []
        events.append(
            ResponseMcpCallArgumentsDoneEvent(
                type="response.mcp_call_arguments.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
                arguments=previous_item.content[0].text,
                name=recipient,
            )
        )
        events.append(
            ResponseMcpCallCompletedEvent(
                type="response.mcp_call.completed",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=McpCall(
                    type="mcp_call",
                    id=state.current_item_id,
                    name=recipient,
                    arguments=previous_item.content[0].text,
                    server_label=server_label,
                    status="completed",
                ),
            )
        )
        return events

    def _emit_code_interpreter_completion_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events when code interpreter completes."""
        events = []
        events.append(
            ResponseCodeInterpreterCallCodeDoneEvent(
                type="response.code_interpreter_call_code.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
                code=previous_item.content[0].text,
            )
        )
        events.append(
            ResponseCodeInterpreterCallInterpretingEvent(
                type="response.code_interpreter_call.interpreting",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseCodeInterpreterCallCompletedEvent(
                type="response.code_interpreter_call.completed",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=ResponseCodeInterpreterToolCallParam(
                    type="code_interpreter_call",
                    id=state.current_item_id,
                    code=previous_item.content[0].text,
                    container_id="auto",
                    outputs=[],
                    status="completed",
                ),
            )
        )
        return events

    def _emit_mcp_prefix_completion_events(
        self,
        previous_item,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events when an MCP prefix tool (mcp.*) completes."""
        mcp_name = previous_item.recipient[len("mcp.") :]
        events = []
        events.append(
            ResponseMcpCallArgumentsDoneEvent(
                type="response.mcp_call_arguments.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
                arguments=previous_item.content[0].text,
                name=mcp_name,
            )
        )
        events.append(
            ResponseMcpCallCompletedEvent(
                type="response.mcp_call.completed",
                sequence_number=-1,
                output_index=state.current_output_index,
                item_id=state.current_item_id,
            )
        )
        events.append(
            ResponseOutputItemDoneEvent(
                type="response.output_item.done",
                sequence_number=-1,
                output_index=state.current_output_index,
                item=McpCall(
                    type="mcp_call",
                    id=state.current_item_id,
                    name=mcp_name,
                    arguments=previous_item.content[0].text,
                    server_label=mcp_name,
                    status="completed",
                ),
            )
        )
        return events

    def _emit_tool_action_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for tool action turn."""
        if not ctx.is_assistant_action_turn() or len(ctx.parser.messages) == 0:
            return []

        events = []
        previous_item = ctx.parser.messages[-1]

        # Handle browser tool
        if (
            self.tool_server is not None
            and self.tool_server.has_tool("browser")
            and previous_item.recipient is not None
            and previous_item.recipient.startswith("browser.")
        ):
            events.extend(self._emit_browser_tool_events(previous_item, state))

        # Handle tool completion
        if (
            self.tool_server is not None
            and previous_item.recipient is not None
            and state.current_item_id is not None
            and state.sent_output_item_added
        ):
            recipient = previous_item.recipient
            # Handle MCP prefix tool completion first
            if recipient.startswith("mcp."):
                events.extend(
                    self._emit_mcp_prefix_completion_events(previous_item, state)
                )
            else:
                # Handle other MCP tool and code interpreter completion
                is_mcp_tool = self._is_mcp_tool_by_namespace(
                    recipient
                ) and state.current_item_id.startswith("mcp_")
                if is_mcp_tool:
                    events.extend(
                        self._emit_mcp_tool_completion_events(previous_item, state)
                    )
                else:
                    events.extend(
                        self._emit_code_interpreter_completion_events(
                            previous_item, state
                        )
                    )

        return events

    def _emit_function_call_delta_events(
        self,
        ctx: StreamingHarmonyContext,
        state: HarmonyStreamingState,
    ) -> list[StreamingResponsesResponse]:
        """Emit events for developer function calls on commentary channel."""
        if not (
            ctx.parser.current_channel == "commentary"
            and ctx.parser.current_recipient
            and ctx.parser.current_recipient.startswith("functions.")
        ):
            return []

        events = []
        if state.is_first_function_call_delta is False:
            state.is_first_function_call_delta = True
            fc_name = ctx.parser.current_recipient[len("functions.") :]
            state.current_item_id = f"fc_{random_uuid()}"
            tool_call_item = ResponseFunctionToolCall(
                name=fc_name,
                type="function_call",
                id=state.current_item_id,
                call_id=f"call_{random_uuid()}",
                arguments="",
                status="in_progress",
            )
            events.append(
                ResponseOutputItemAddedEvent(
                    type="response.output_item.added",
                    sequence_number=-1,
                    output_index=state.current_output_index,
                    item=tool_call_item,
                )
            )
        # Always emit the delta (including on first call)
        events.append(
            ResponseFunctionCallArgumentsDeltaEvent(
                item_id=state.current_item_id,
2441
                delta=ctx.last_content_delta,
2442
2443
2444
2445
2446
2447
2448
                output_index=state.current_output_index,
                sequence_number=-1,
                type="response.function_call_arguments.delta",
            )
        )
        return events

2449
2450
2451
2452
    async def _process_harmony_streaming_events(
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
2453
        result_generator: AsyncIterator[ConversationContext | None],
2454
2455
        context: ConversationContext,
        model_name: str,
2456
        tokenizer: TokenizerLike,
2457
2458
        request_metadata: RequestResponseMetadata,
        created_time: int,
2459
        _increment_sequence_number_and_return: Callable[
2460
2461
            [StreamingResponsesResponse], StreamingResponsesResponse
        ],
2462
    ) -> AsyncGenerator[StreamingResponsesResponse, None]:
2463
2464
        state = HarmonyStreamingState()

2465
2466
2467
        async for ctx in result_generator:
            assert isinstance(ctx, StreamingHarmonyContext)

2468
2469
2470
            # finish_reason='error' indicates a retryable error
            self._raise_if_error(ctx.finish_reason, request.request_id)

2471
2472
2473
            if ctx.is_expecting_start():
                if len(ctx.parser.messages) > 0:
                    previous_item = ctx.parser.messages[-1]
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
                    for event in self._emit_previous_item_done_events(
                        previous_item, state
                    ):
                        yield _increment_sequence_number_and_return(event)
                state.reset_for_new_item()

            # Stream the output of a harmony message
            for event in self._emit_content_delta_events(ctx, state):
                yield _increment_sequence_number_and_return(event)

            # Stream tool call outputs
            for event in self._emit_tool_action_events(ctx, state):
                yield _increment_sequence_number_and_return(event)
2487

2488
2489
2490
2491
    async def responses_stream_generator(
        self,
        request: ResponsesRequest,
        sampling_params: SamplingParams,
2492
        result_generator: AsyncIterator[ConversationContext | None],
2493
2494
        context: ConversationContext,
        model_name: str,
2495
        tokenizer: TokenizerLike,
2496
        request_metadata: RequestResponseMetadata,
2497
        created_time: int | None = None,
2498
    ) -> AsyncGenerator[StreamingResponsesResponse, None]:
2499
2500
2501
2502
2503
        # TODO:
        # 1. Handle disconnect

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

2504
2505
        sequence_number = 0

2506
        def _increment_sequence_number_and_return(
2507
            event: StreamingResponsesResponse,
2508
        ) -> StreamingResponsesResponse:
2509
2510
            nonlocal sequence_number
            # Set sequence_number if the event has this attribute
2511
            if hasattr(event, "sequence_number"):
2512
2513
                event.sequence_number = sequence_number
            sequence_number += 1
2514
            return event
2515

2516
        async with AsyncExitStack() as exit_stack:
2517
            if self.use_harmony:
2518
2519
                # TODO: in streaming, we noticed this bug:
                # https://github.com/vllm-project/vllm/issues/25697
2520
                await self._initialize_tool_sessions(request, context, exit_stack)
2521
2522
2523
                processer = self._process_harmony_streaming_events
            else:
                processer = self._process_simple_streaming_events
2524
            # TODO Hanchen make sampling params to include the structural tag
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534

            initial_response = ResponsesResponse.from_request(
                request,
                sampling_params,
                model_name=model_name,
                created_time=created_time,
                output=[],
                status="in_progress",
                usage=None,
            ).model_dump()
2535
            yield _increment_sequence_number_and_return(
2536
2537
2538
2539
                ResponseCreatedEvent(
                    type="response.created",
                    sequence_number=-1,
                    response=initial_response,
2540
2541
                )
            )
2542
            yield _increment_sequence_number_and_return(
2543
2544
2545
2546
                ResponseInProgressEvent(
                    type="response.in_progress",
                    sequence_number=-1,
                    response=initial_response,
2547
2548
                )
            )
2549

2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
            try:
                async for event_data in processer(
                    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
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585

            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,
            )
2586
            yield _increment_sequence_number_and_return(
2587
                ResponseCompletedEvent(
2588
2589
                    type="response.completed",
                    sequence_number=-1,
2590
                    response=final_response,
2591
2592
                )
            )