serving_chat.py 42.6 KB
Newer Older
1
2
from __future__ import annotations

3
import copy
4
5
6
7
import json
import logging
import time
import uuid
8
from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, List, Optional, Union
9
10

from fastapi import Request
11
from fastapi.responses import ORJSONResponse, StreamingResponse
12
13
14
15
16
17
18
19
20
21
22
23
24
25

from sglang.srt.entrypoints.openai.protocol import (
    ChatCompletionRequest,
    ChatCompletionResponse,
    ChatCompletionResponseChoice,
    ChatCompletionResponseStreamChoice,
    ChatCompletionStreamResponse,
    ChatCompletionTokenLogprob,
    ChatMessage,
    ChoiceLogprobs,
    DeltaMessage,
    ErrorResponse,
    FunctionResponse,
    LogProbs,
26
    MessageProcessingResult,
27
28
29
30
    ToolCall,
    TopLogprob,
)
from sglang.srt.entrypoints.openai.serving_base import OpenAIServingBase
31
from sglang.srt.entrypoints.openai.usage_processor import UsageProcessor
32
from sglang.srt.entrypoints.openai.utils import (
33
    process_hidden_states_from_ret,
34
35
36
37
    to_openai_style_logprobs,
)
from sglang.srt.function_call.function_call_parser import FunctionCallParser
from sglang.srt.managers.io_struct import GenerateReqInput
38
39
40
from sglang.srt.parser.conversation import generate_chat_conv
from sglang.srt.parser.jinja_template_utils import process_content_for_template_format
from sglang.srt.parser.reasoning_parser import ReasoningParser
41
42
from sglang.utils import convert_json_schema_to_str

43
44
45
46
if TYPE_CHECKING:
    from sglang.srt.managers.template_manager import TemplateManager
    from sglang.srt.managers.tokenizer_manager import TokenizerManager

47
48
49
50
logger = logging.getLogger(__name__)


class OpenAIServingChat(OpenAIServingBase):
51
    """Handler for /v1/chat/completions requests"""
52

53
    def __init__(
54
55
56
        self,
        tokenizer_manager: TokenizerManager,
        template_manager: TemplateManager,
57
58
59
    ):
        super().__init__(tokenizer_manager)
        self.template_manager = template_manager
60
        self.tool_call_parser = self.tokenizer_manager.server_args.tool_call_parser
61
62
63
64

    def _request_id_prefix(self) -> str:
        return "chatcmpl-"

65
66
67
68
69
70
71
72
73
74
75
76
    def _validate_request(self, request: ChatCompletionRequest) -> Optional[str]:
        """Validate that the input is valid."""
        if not request.messages:
            return "Messages cannot be empty."

        if (
            isinstance(request.tool_choice, str)
            and request.tool_choice.lower() == "required"
            and not request.tools
        ):
            return "Tools cannot be empty if tool choice is set to required."

77
78
79
80
81
82
83
84
85
86
87
88
        max_output_tokens = request.max_completion_tokens or request.max_tokens
        server_context_length = self.tokenizer_manager.server_args.context_length
        if (
            max_output_tokens
            and server_context_length
            and max_output_tokens > server_context_length
        ):
            return (
                f"max_completion_tokens is too large: {max_output_tokens}."
                f"This model supports at most {server_context_length} completion tokens."
            )

89
90
91
92
93
        if request.response_format and request.response_format.type == "json_schema":
            schema = getattr(request.response_format.json_schema, "schema_", None)
            if schema is None:
                return "schema_ is required for json_schema response format request."

94
95
        return None

96
97
    def _convert_to_internal_request(
        self,
98
        request: ChatCompletionRequest,
99
        raw_request: Request = None,
100
    ) -> tuple[GenerateReqInput, ChatCompletionRequest]:
101
102
103
104
105
106
107
108
        reasoning_effort = (
            request.chat_template_kwargs.pop("reasoning_effort", None)
            if request.chat_template_kwargs
            else None
        )
        if reasoning_effort is not None:
            request.reasoning_effort = reasoning_effort

109
110
111
        """Convert OpenAI chat completion request to internal format"""
        is_multimodal = self.tokenizer_manager.model_config.is_multimodal

112
        # Process messages and apply chat template
113
        processed_messages = self._process_messages(request, is_multimodal)
114

115
116
117
118
119
120
121
122
123
124
        # Build sampling parameters
        sampling_params = self._build_sampling_params(
            request,
            processed_messages.stop,
            processed_messages.tool_call_constraint,
        )

        # Handle single vs multiple requests
        if is_multimodal:
            prompt_kwargs = {"text": processed_messages.prompt}
125
        else:
126
127
128
129
130
            if isinstance(processed_messages.prompt_ids, str):
                prompt_kwargs = {"text": processed_messages.prompt_ids}
            else:
                prompt_kwargs = {"input_ids": processed_messages.prompt_ids}

131
132
133
        # Extract customer labels from raw request headers
        customer_labels = self.extract_customer_labels(raw_request)

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        adapted_request = GenerateReqInput(
            **prompt_kwargs,
            image_data=processed_messages.image_data,
            video_data=processed_messages.video_data,
            audio_data=processed_messages.audio_data,
            sampling_params=sampling_params,
            return_logprob=request.logprobs,
            logprob_start_len=-1,
            top_logprobs_num=request.top_logprobs or 0,
            stream=request.stream,
            return_text_in_logprobs=True,
            modalities=processed_messages.modalities,
            lora_path=request.lora_path,
            bootstrap_host=request.bootstrap_host,
            bootstrap_port=request.bootstrap_port,
            bootstrap_room=request.bootstrap_room,
            return_hidden_states=request.return_hidden_states,
            rid=request.rid,
152
            customer_labels=customer_labels,
153
        )
154

155
        return adapted_request, request
156
157
158

    def _process_messages(
        self, request: ChatCompletionRequest, is_multimodal: bool
159
    ) -> MessageProcessingResult:
160
        """Process chat messages and apply chat template"""
161
162
163
164
165
166
167
168
169
170
        is_gpt_oss = (
            hasattr(self.tokenizer_manager.model_config, "hf_config")
            and hasattr(self.tokenizer_manager.model_config.hf_config, "model_type")
            and self.tokenizer_manager.model_config.hf_config.model_type == "gpt_oss"
        )

        # GptOss model needs to keep special tokens for harmony parsing
        if is_gpt_oss:
            request.skip_special_tokens = False

171
172
        tool_call_constraint = None

173
174
175
176
177
178
        # Apply chat template and its stop strings
        tools = None
        if request.tools and request.tool_choice != "none":
            request.skip_special_tokens = False
            if not isinstance(request.tool_choice, str):
                tools = [
179
                    item.function.model_dump()
180
181
182
                    for item in request.tools
                    if item.function.name == request.tool_choice.function.name
                ]
183
            else:
184
                tools = [item.function.model_dump() for item in request.tools]
185
186
187
188
189
            if self.tool_call_parser:
                parser = FunctionCallParser(request.tools, self.tool_call_parser)
                tool_call_constraint = parser.get_structure_constraint(
                    request.tool_choice
                )
190
191
192
193

        # Use chat template
        if self.template_manager.chat_template_name is None:
            result = self._apply_jinja_template(request, tools, is_multimodal)
194
        else:
195
196
197
198
            result = self._apply_conversation_template(request, is_multimodal)

        result.tool_call_constraint = tool_call_constraint
        return result
199
200
201
202
203
204

    def _apply_jinja_template(
        self,
        request: ChatCompletionRequest,
        tools: Optional[List[Dict]],
        is_multimodal: bool,
205
    ) -> MessageProcessingResult:
206
        """Apply Jinja chat template"""
207
208
        prompt = ""
        prompt_ids = []
209
210
        openai_compatible_messages = []
        image_data = []
211
        video_data = []
212
213
214
        audio_data = []
        modalities = []

215
        template_content_format = self.template_manager.jinja_template_content_format
216
217
218
219
220
221
222
223
224
225
226

        for message in request.messages:
            if message.content is None:
                message.content = ""
            msg_dict = message.model_dump()

            # Process content based on detected template format
            processed_msg = process_content_for_template_format(
                msg_dict,
                template_content_format,
                image_data,
227
                video_data,
228
229
230
                audio_data,
                modalities,
            )
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

            # per the Transformers docs & maintainers, tool call arguments in
            # assistant-role messages with tool_calls need to be dicts not JSON str -
            # this is how tool-use chat templates will expect them moving forwards
            # so, for messages that have tool_calls, parse the string (which we get
            # from openAI format) to dict
            if (
                processed_msg["role"] == "assistant"
                and "tool_calls" in processed_msg
                and isinstance(processed_msg["tool_calls"], list)
            ):
                for item in processed_msg["tool_calls"]:
                    if "arguments" in item["function"] and isinstance(
                        item["function"]["arguments"], str
                    ):
                        item["function"]["arguments"] = json.loads(
                            item["function"]["arguments"]
                        )

250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
            openai_compatible_messages.append(processed_msg)

        # Handle assistant prefix for continue_final_message
        assistant_prefix = None
        if (
            openai_compatible_messages
            and openai_compatible_messages[-1]["role"] == "assistant"
        ):
            if request.continue_final_message:
                assistant_prefix = openai_compatible_messages[-1]["content"]
                openai_compatible_messages = openai_compatible_messages[:-1]

        try:
            prompt_ids = self.tokenizer_manager.tokenizer.apply_chat_template(
                openai_compatible_messages,
                tokenize=True,
                add_generation_prompt=True,
                tools=tools,
268
                reasoning_effort=request.reasoning_effort,
269
270
271
272
273
                **(
                    request.chat_template_kwargs if request.chat_template_kwargs else {}
                ),
            )
        except Exception:
274
275
276
            # This except branch will be triggered when the chosen model
            # has a different tools input format that is not compatible
            # with openAI's apply_chat_template tool_call format, like Mistral.
277
278
279
280
281
282
283
284
285
286
            tools = (
                [t if "function" in t else {"function": t} for t in tools]
                if tools
                else None
            )
            prompt_ids = self.tokenizer_manager.tokenizer.apply_chat_template(
                openai_compatible_messages,
                tokenize=True,
                add_generation_prompt=True,
                tools=tools,
287
                reasoning_effort=request.reasoning_effort,
288
289
290
291
292
293
294
295
296
297
298
299
300
301
                **(
                    request.chat_template_kwargs if request.chat_template_kwargs else {}
                ),
            )

        if assistant_prefix:
            encoded = self.tokenizer_manager.tokenizer.encode(assistant_prefix)
            if encoded and encoded[0] == self.tokenizer_manager.tokenizer.bos_token_id:
                encoded = encoded[1:]
            prompt_ids += encoded

        if is_multimodal:
            prompt = self.tokenizer_manager.tokenizer.decode(prompt_ids)

302
303
304
        stop = request.stop
        image_data = image_data if image_data else None
        audio_data = audio_data if audio_data else None
305
        video_data = video_data if video_data else None
306
        modalities = modalities if modalities else []
307
308
309
310
        return MessageProcessingResult(
            prompt=prompt,
            prompt_ids=prompt_ids,
            image_data=image_data,
311
            video_data=video_data,
312
313
314
315
            audio_data=audio_data,
            modalities=modalities,
            stop=stop,
        )
316
317

    def _apply_conversation_template(
318
319
320
        self,
        request: ChatCompletionRequest,
        is_multimodal: bool,
321
    ) -> MessageProcessingResult:
322
        """Apply conversation template"""
323
324
325
        prompt = ""
        prompt_ids = []
        conv = generate_chat_conv(request, self.template_manager.chat_template_name)
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

        # If we should continue the final assistant message, adjust the conversation.
        if (
            request.continue_final_message
            and request.messages
            and request.messages[-1].role == "assistant"
        ):
            # Remove the auto-added blank assistant turn, if present.
            if conv.messages and conv.messages[-1][1] is None:
                conv.messages.pop()
            # Rebuild the prompt from the conversation.
            prompt = conv.get_prompt()
            # Strip trailing stop tokens or separators that indicate end-of-assistant.
            if isinstance(conv.stop_str, list):
                for stop_token in conv.stop_str:
                    if prompt.endswith(stop_token):
                        prompt = prompt[: -len(stop_token)]
            elif isinstance(conv.stop_str, str) and prompt.endswith(conv.stop_str):
                prompt = prompt[: -len(conv.stop_str)]
            if conv.sep and prompt.endswith(conv.sep):
                prompt = prompt[: -len(conv.sep)]
            if getattr(conv, "sep2", None) and prompt.endswith(conv.sep2):
                prompt = prompt[: -len(conv.sep2)]
        else:
            prompt = conv.get_prompt()
351
352
            if self._get_enable_thinking_from_request(request):
                prompt += "<think>"  # Note(Xinyuan): hard code thinking token
353

354
        image_data = conv.image_data if conv.image_data else None
355
        video_data = conv.video_data if conv.video_data else None
356
357
        audio_data = conv.audio_data if conv.audio_data else None
        modalities = conv.modalities if conv.modalities else []
358
        stop = copy.copy(conv.stop_str or [] if not request.ignore_eos else [])
359
360
361
362
363
364
365

        if request.stop:
            if isinstance(request.stop, str):
                stop.append(request.stop)
            else:
                stop.extend(request.stop)

366
367
368
        if not is_multimodal:
            prompt_ids = self.tokenizer_manager.tokenizer.encode(prompt)

369
370
371
372
        return MessageProcessingResult(
            prompt=prompt,
            prompt_ids=prompt_ids,
            image_data=image_data,
373
            video_data=video_data,
374
375
376
377
            audio_data=audio_data,
            modalities=modalities,
            stop=stop,
        )
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447

    def _build_sampling_params(
        self,
        request: ChatCompletionRequest,
        stop: List[str],
        tool_call_constraint: Optional[Any],
    ) -> Dict[str, Any]:
        """Build sampling parameters for the request"""

        sampling_params = {
            "temperature": request.temperature,
            "max_new_tokens": request.max_tokens or request.max_completion_tokens,
            "min_new_tokens": request.min_tokens,
            "stop": stop,
            "stop_token_ids": request.stop_token_ids,
            "top_p": request.top_p,
            "top_k": request.top_k,
            "min_p": request.min_p,
            "presence_penalty": request.presence_penalty,
            "frequency_penalty": request.frequency_penalty,
            "repetition_penalty": request.repetition_penalty,
            "regex": request.regex,
            "ebnf": request.ebnf,
            "n": request.n,
            "no_stop_trim": request.no_stop_trim,
            "ignore_eos": request.ignore_eos,
            "skip_special_tokens": request.skip_special_tokens,
            "logit_bias": request.logit_bias,
        }

        if request.response_format and request.response_format.type == "json_schema":
            sampling_params["json_schema"] = convert_json_schema_to_str(
                request.response_format.json_schema.schema_
            )
        elif request.response_format and request.response_format.type == "json_object":
            sampling_params["json_schema"] = '{"type": "object"}'
        elif (
            request.response_format and request.response_format.type == "structural_tag"
        ):
            sampling_params["structural_tag"] = convert_json_schema_to_str(
                request.response_format.model_dump(by_alias=True)
            )

        # Check if there are already existing output constraints
        has_existing_constraints = (
            sampling_params.get("regex")
            or sampling_params.get("ebnf")
            or sampling_params.get("structural_tag")
            or sampling_params.get("json_schema")
        )

        if tool_call_constraint and has_existing_constraints:
            logger.warning("Constrained decoding is not compatible with tool calls.")
        elif tool_call_constraint:
            constraint_type, constraint_value = tool_call_constraint
            if constraint_type == "structural_tag":
                sampling_params[constraint_type] = convert_json_schema_to_str(
                    constraint_value.model_dump(by_alias=True)
                )
            else:
                sampling_params[constraint_type] = constraint_value
        return sampling_params

    async def _handle_streaming_request(
        self,
        adapted_request: GenerateReqInput,
        request: ChatCompletionRequest,
        raw_request: Request,
    ) -> StreamingResponse:
        """Handle streaming chat completion request"""
448
449
450
451
452
        return StreamingResponse(
            self._generate_chat_stream(adapted_request, request, raw_request),
            media_type="text/event-stream",
            background=self.tokenizer_manager.create_abort_task(adapted_request),
        )
453

454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
    async def _generate_chat_stream(
        self,
        adapted_request: GenerateReqInput,
        request: ChatCompletionRequest,
        raw_request: Request,
    ) -> AsyncGenerator[str, None]:
        """Generate streaming chat completion response"""
        # Parsers for tool calls and reasoning
        parser_dict = {}
        reasoning_parser_dict = {}

        # State tracking for streaming
        is_firsts = {}
        stream_buffers = {}
        n_prev_tokens = {}
469
470
        has_tool_calls = {}
        finish_reasons = {}
471
472
473
474
475

        # Usage tracking
        prompt_tokens = {}
        completion_tokens = {}
        cached_tokens = {}
476
        hidden_states = {}
477

478
479
480
481
482
        try:
            async for content in self.tokenizer_manager.generate_request(
                adapted_request, raw_request
            ):
                index = content.get("index", 0)
483

484
485
486
                prompt_tokens[index] = content["meta_info"]["prompt_tokens"]
                completion_tokens[index] = content["meta_info"]["completion_tokens"]
                cached_tokens[index] = content["meta_info"].get("cached_tokens", 0)
487
                hidden_states[index] = content["meta_info"].get("hidden_states", None)
488

489
490
491
492
493
494
495
496
497
                # Handle logprobs
                choice_logprobs = None
                if request.logprobs:
                    choice_logprobs = self._process_streaming_logprobs(
                        content, n_prev_tokens.get(index, 0)
                    )
                    n_prev_tokens[index] = len(
                        content["meta_info"]["output_token_logprobs"]
                    )
498

499
500
501
                finish_reason = content["meta_info"]["finish_reason"]
                finish_reason_type = finish_reason["type"] if finish_reason else None

502
503
504
505
                # Track finish_reason for each index
                if finish_reason_type:
                    finish_reasons[index] = finish_reason

506
507
508
509
510
511
512
                # First chunk with role
                if is_firsts.get(index, True):
                    is_firsts[index] = False
                    delta = DeltaMessage(role="assistant", content="")
                    choice_data = ChatCompletionResponseStreamChoice(
                        index=index,
                        delta=delta,
513
514
                        finish_reason=None,
                        logprobs=None,
515
516
517
518
519
520
                    )
                    chunk = ChatCompletionStreamResponse(
                        id=content["meta_info"]["id"],
                        created=int(time.time()),
                        choices=[choice_data],
                        model=request.model,
521
                    )
522
                    yield f"data: {chunk.model_dump_json()}\n\n"
523

524
525
526
                stream_buffer = stream_buffers.get(index, "")
                delta = content["text"][len(stream_buffer) :]
                stream_buffers[index] = stream_buffer + delta
527
528
529
530
531
532
533
534
535
536

                # Handle reasoning content
                if (
                    self.tokenizer_manager.server_args.reasoning_parser
                    and request.separate_reasoning
                ):
                    reasoning_text, delta = self._process_reasoning_stream(
                        index, delta, reasoning_parser_dict, content, request
                    )
                    if reasoning_text:
537
538
                        choice_data = ChatCompletionResponseStreamChoice(
                            index=index,
539
                            delta=DeltaMessage(reasoning_content=reasoning_text),
540
                            finish_reason=None,
541
542
543
544
545
546
547
548
549
550
                        )
                        chunk = ChatCompletionStreamResponse(
                            id=content["meta_info"]["id"],
                            created=int(time.time()),
                            choices=[choice_data],
                            model=request.model,
                        )
                        yield f"data: {chunk.model_dump_json()}\n\n"

                # Handle tool calls
551
552
553
554
555
                if (
                    request.tool_choice != "none"
                    and request.tools
                    and self.tool_call_parser
                ):
556
                    async for chunk in self._process_tool_call_stream(
557
558
559
560
561
                        index,
                        delta,
                        parser_dict,
                        content,
                        request,
562
                        has_tool_calls,
563
                    ):
564
565
                        if chunk:
                            yield chunk
566
567
568
569
570
571
572
573
574

                    # Send any remaining tool call arguments when generation finishes
                    if finish_reason_type is not None and index in parser_dict:
                        parser = parser_dict[index]
                        remaining_chunk = self._check_for_unstreamed_tool_args(
                            parser, content, request, index
                        )
                        if remaining_chunk:
                            yield remaining_chunk
575

576
577
                else:
                    # Regular content
578
                    if delta:
579
580
                        choice_data = ChatCompletionResponseStreamChoice(
                            index=index,
581
                            delta=DeltaMessage(content=delta),
582
583
                            finish_reason=None,
                            matched_stop=None,
584
585
586
587
588
589
590
591
592
593
                            logprobs=choice_logprobs,
                        )
                        chunk = ChatCompletionStreamResponse(
                            id=content["meta_info"]["id"],
                            created=int(time.time()),
                            choices=[choice_data],
                            model=request.model,
                        )
                        yield f"data: {chunk.model_dump_json()}\n\n"

594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
            # Send finish_reason chunks for each index that completed
            for idx, finish_reason_data in finish_reasons.items():
                finish_reason_type = finish_reason_data["type"]

                # Change finish_reason to "tool_calls" if we had tool calls and stopped naturally
                final_finish_reason = finish_reason_type
                if has_tool_calls.get(idx, False) and finish_reason_type == "stop":
                    final_finish_reason = "tool_calls"

                finish_reason_chunk = ChatCompletionStreamResponse(
                    id=content["meta_info"][
                        "id"
                    ],  # NOTE: openai uses the same chatcmpl-id for all indices
                    created=int(time.time()),
                    choices=[
                        ChatCompletionResponseStreamChoice(
                            index=idx,
                            delta=DeltaMessage(),
                            finish_reason=final_finish_reason,
                            matched_stop=(
                                finish_reason_data["matched"]
                                if "matched" in finish_reason_data
                                else None
                            ),
                        )
                    ],
                    model=request.model,
                    usage=None,
                )
                yield f"data: {finish_reason_chunk.model_dump_json()}\n\n"
624

625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
            # Send hidden states if requested
            if request.return_hidden_states and hidden_states:
                for index, choice_hidden_states in hidden_states.items():
                    if choice_hidden_states:
                        last_token_hidden_states = (
                            choice_hidden_states[-1]
                            if len(choice_hidden_states) > 1
                            else []
                        )
                        hidden_states_chunk = ChatCompletionStreamResponse(
                            id=content["meta_info"]["id"],
                            created=int(time.time()),
                            choices=[
                                ChatCompletionResponseStreamChoice(
                                    index=index,
                                    delta=DeltaMessage(
                                        hidden_states=last_token_hidden_states
                                    ),
643
                                    finish_reason=None,  # Hidden states don't need finish_reason
644
645
646
647
648
649
                                )
                            ],
                            model=request.model,
                        )
                        yield f"data: {hidden_states_chunk.model_dump_json()}\n\n"

650
651
            # Additional usage chunk
            if request.stream_options and request.stream_options.include_usage:
652
                usage = UsageProcessor.calculate_streaming_usage(
653
654
655
                    prompt_tokens,
                    completion_tokens,
                    cached_tokens,
656
657
                    n_choices=request.n,
                    enable_cache_report=self.tokenizer_manager.server_args.enable_cache_report,
658
659
                )
                usage_chunk = ChatCompletionStreamResponse(
660
661
                    id=content["meta_info"]["id"],
                    created=int(time.time()),
662
                    choices=[],  # Empty choices array as per OpenAI spec
663
664
665
                    model=request.model,
                    usage=usage,
                )
666
                yield f"data: {usage_chunk.model_dump_json()}\n\n"
667

668
        except ValueError as e:
669
670
            error = self.create_streaming_error_response(str(e))
            yield f"data: {error}\n\n"
671

672
        yield "data: [DONE]\n\n"
673
674
675
676
677
678

    async def _handle_non_streaming_request(
        self,
        adapted_request: GenerateReqInput,
        request: ChatCompletionRequest,
        raw_request: Request,
679
    ) -> Union[ChatCompletionResponse, ErrorResponse, ORJSONResponse]:
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        """Handle non-streaming chat completion request"""
        try:
            ret = await self.tokenizer_manager.generate_request(
                adapted_request, raw_request
            ).__anext__()
        except ValueError as e:
            return self.create_error_response(str(e))

        if not isinstance(ret, list):
            ret = [ret]

        response = self._build_chat_response(
            request,
            ret,
            int(time.time()),
        )

        return response

    def _build_chat_response(
        self,
        request: ChatCompletionRequest,
        ret: List[Dict[str, Any]],
        created: int,
704
    ) -> Union[ChatCompletionResponse, ORJSONResponse]:
705
706
707
708
709
710
711
712
713
        """Build chat completion response from generation results"""
        choices = []

        for idx, ret_item in enumerate(ret):
            # Process logprobs
            choice_logprobs = None
            if request.logprobs:
                choice_logprobs = self._process_response_logprobs(ret_item)

714
715
716
            # Handle hidden states
            hidden_states = process_hidden_states_from_ret(ret_item, request)

717
718
719
720
721
            finish_reason = ret_item["meta_info"]["finish_reason"]
            text = ret_item["text"]

            # Handle reasoning content
            reasoning_text = None
722
            reasoning_parser = self.tokenizer_manager.server_args.reasoning_parser
723
            if reasoning_parser and request.separate_reasoning:
724
725
726
727
                is_force_reasoning = (
                    self.template_manager.force_reasoning
                    or self._get_enable_thinking_from_request(request)
                )
728
729
                try:
                    parser = ReasoningParser(
730
731
                        model_type=reasoning_parser,
                        stream_reasoning=False,
732
                        force_reasoning=is_force_reasoning,
733
734
735
736
737
738
739
740
741
742
743
744
                    )
                    reasoning_text, text = parser.parse_non_stream(text)
                except Exception as e:
                    logger.error(f"Reasoning parsing error: {e}")
                    return self.create_error_response(
                        "Failed to parse reasoning content",
                        err_type="InternalServerError",
                        status_code=500,
                    )

            # Handle tool calls
            tool_calls = None
745
746
747
748
749
            if (
                request.tool_choice != "none"
                and request.tools
                and self.tool_call_parser
            ):
750
                tool_calls, text, finish_reason = self._process_tool_calls(
751
                    text, request.tools, finish_reason
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
                )

            choice_data = ChatCompletionResponseChoice(
                index=idx,
                message=ChatMessage(
                    role="assistant",
                    content=text if text else None,
                    tool_calls=tool_calls,
                    reasoning_content=reasoning_text if reasoning_text else None,
                ),
                logprobs=choice_logprobs,
                finish_reason=finish_reason["type"] if finish_reason else None,
                matched_stop=(
                    finish_reason["matched"]
                    if finish_reason and "matched" in finish_reason
                    else None
                ),
769
                hidden_states=hidden_states,
770
771
772
773
            )
            choices.append(choice_data)

        # Calculate usage
774
        usage = UsageProcessor.calculate_response_usage(
775
776
777
            ret,
            n_choices=request.n,
            enable_cache_report=self.tokenizer_manager.server_args.enable_cache_report,
778
        )
779
780
781
782
783
784
785

        return ChatCompletionResponse(
            id=ret[0]["meta_info"]["id"],
            created=created,
            model=request.model,
            choices=choices,
            usage=usage,
786
            metadata={"weight_version": ret[0]["meta_info"]["weight_version"]},
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
        )

    def _process_logprobs_tokens(
        self, logprobs: LogProbs, use_token_index: bool = False
    ) -> List[ChatCompletionTokenLogprob]:
        """Common helper to process logprobs tokens for both streaming and non-streaming

        Args:
            logprobs: LogProbs data from model
            use_token_index: True for non-streaming (use token_idx), False for streaming (use index 0)
        """
        token_logprobs = []

        for token_idx, (token, logprob) in enumerate(
            zip(logprobs.tokens, logprobs.token_logprobs)
        ):
            token_bytes = list(token.encode("utf-8"))
            top_logprobs = []
            if logprobs.top_logprobs:
                # - Non-streaming (use_token_index=True): uses token_idx for full data
                # - Streaming (use_token_index=False): uses index 0 for pre-sliced data
                top_logprobs_idx = token_idx if use_token_index else 0
                for top_token, top_logprob in logprobs.top_logprobs[
                    top_logprobs_idx
                ].items():
                    top_token_bytes = list(top_token.encode("utf-8"))
                    top_logprobs.append(
                        TopLogprob(
                            token=top_token,
                            bytes=top_token_bytes,
                            logprob=top_logprob,
                        )
                    )
            token_logprobs.append(
                ChatCompletionTokenLogprob(
                    token=token,
                    bytes=token_bytes,
                    logprob=logprob,
                    top_logprobs=top_logprobs,
                )
            )

        return token_logprobs

    def _process_response_logprobs(self, ret_item: Dict[str, Any]) -> ChoiceLogprobs:
        """Process logprobs for non-streaming response"""
        logprobs = to_openai_style_logprobs(
            output_token_logprobs=ret_item["meta_info"]["output_token_logprobs"],
            output_top_logprobs=ret_item["meta_info"].get("output_top_logprobs", None),
        )

        token_logprobs = self._process_logprobs_tokens(logprobs, use_token_index=True)
        return ChoiceLogprobs(content=token_logprobs)

    def _process_tool_calls(
        self,
        text: str,
        tools: List[Any],
        finish_reason: Dict[str, Any],
    ) -> tuple[Optional[List[ToolCall]], str, Dict[str, Any]]:
        """Process tool calls in the response"""
848
        parser = FunctionCallParser(tools, self.tool_call_parser)
849
850
851
852
853
854
        if parser.has_tool_call(text):
            if finish_reason["type"] == "stop":
                finish_reason["type"] = "tool_calls"
                finish_reason["matched"] = None
            try:
                text, call_info_list = parser.parse_non_stream(text)
855
856
857
                tool_calls = []
                for call_info in call_info_list:
                    # For Kimi-K2, align tool_call_id with the model format: functions.{name}:{index}
858
859
860
861
                    if (
                        self.tool_call_parser == "kimi_k2"
                        and call_info.name is not None
                    ):
862
863
864
865
866
867
868
869
870
871
872
873
                        tool_id = f"functions.{call_info.name}:{call_info.tool_index}"
                    else:
                        tool_id = f"call_{uuid.uuid4().hex[:24]}"

                    tool_calls.append(
                        ToolCall(
                            id=tool_id,
                            index=getattr(call_info, "tool_index", None),
                            function=FunctionResponse(
                                name=call_info.name, arguments=call_info.parameters
                            ),
                        )
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
                    )
                return tool_calls, text, finish_reason
            except Exception as e:
                logger.error(f"Tool call parsing error: {e}")
                # Return error but don't fail the whole request
                return None, text, finish_reason

        return None, text, finish_reason

    def _process_streaming_logprobs(
        self, content: Dict[str, Any], n_prev_token: int
    ) -> ChoiceLogprobs:
        """Process logprobs for streaming response"""
        logprobs = to_openai_style_logprobs(
            output_token_logprobs=content["meta_info"]["output_token_logprobs"][
                n_prev_token:
            ],
            output_top_logprobs=content["meta_info"].get("output_top_logprobs", [])[
                n_prev_token:
            ],
        )

        token_logprobs = self._process_logprobs_tokens(logprobs, use_token_index=False)
        return ChoiceLogprobs(content=token_logprobs)

    def _process_reasoning_stream(
        self,
        index: int,
        delta: str,
        reasoning_parser_dict: Dict[int, ReasoningParser],
        content: Dict[str, Any],
        request: ChatCompletionRequest,
    ) -> tuple[Optional[str], str]:
        """Process reasoning content in streaming response"""
        if index not in reasoning_parser_dict:
909
910
911
912
            is_force_reasoning = (
                self.template_manager.force_reasoning
                or self._get_enable_thinking_from_request(request)
            )
913
914
915
            reasoning_parser_dict[index] = ReasoningParser(
                self.tokenizer_manager.server_args.reasoning_parser,
                request.stream_reasoning,
916
                is_force_reasoning,
917
918
919
920
            )
        reasoning_parser = reasoning_parser_dict[index]
        return reasoning_parser.parse_stream_chunk(delta)

921
    def _get_enable_thinking_from_request(self, request: ChatCompletionRequest) -> bool:
922
923
924
925
926
927
928
929
        """Extracts the 'enable_thinking' flag from request chat_template_kwargs.

        NOTE: This parameter is only useful for models that support enable_thinking
        flag, such as Qwen3.

        Args:
            request_obj: The request object (or an item from a list of requests).
        Returns:
930
            The boolean value of 'enable_thinking' if found, otherwise False.
931
        """
932
933
934
935
936
937
938
939
940
        if hasattr(request, "chat_template_kwargs") and request.chat_template_kwargs:
            # For Qwen3 models, `enable_thinking` is supported.
            if request.chat_template_kwargs.get("enable_thinking") is not None:
                return request.chat_template_kwargs.get("enable_thinking")
            # For DeepSeek-V3.1 models, `thinking` is supported.
            elif request.chat_template_kwargs.get("thinking") is not None:
                return request.chat_template_kwargs.get("thinking")
            else:
                return False
941
        return False
942

943
944
945
946
947
948
949
    async def _process_tool_call_stream(
        self,
        index: int,
        delta: str,
        parser_dict: Dict[int, FunctionCallParser],
        content: Dict[str, Any],
        request: ChatCompletionRequest,
950
        has_tool_calls: Dict[int, bool],
951
952
953
954
955
    ):
        """Process tool calls in streaming response"""
        if index not in parser_dict:
            parser_dict[index] = FunctionCallParser(
                tools=request.tools,
956
                tool_call_parser=self.tool_call_parser,
957
958
959
960
961
962
963
964
965
966
            )
        parser = parser_dict[index]

        normal_text, calls = parser.parse_stream_chunk(delta)

        # Yield normal text
        if normal_text:
            choice_data = ChatCompletionResponseStreamChoice(
                index=index,
                delta=DeltaMessage(content=normal_text),
967
                finish_reason=None,
968
969
970
971
972
973
974
            )
            chunk = ChatCompletionStreamResponse(
                id=content["meta_info"]["id"],
                created=int(time.time()),
                choices=[choice_data],
                model=request.model,
            )
975
            yield f"data: {chunk.model_dump_json()}\n\n"
976
977
978

        # Yield tool calls
        for call_item in calls:
979
980
981
            # Mark that this choice has tool calls
            has_tool_calls[index] = True

982
983
984
            # Tool call ID should be generated only once per tool call
            if call_item.name:
                # First chunk: include ID and function name
985
                if self.tool_call_parser == "kimi_k2":
986
987
988
989
                    # Align with Kimi-K2 format: functions.{name}:{index}
                    tool_call_id = f"functions.{call_item.name}:{call_item.tool_index}"
                else:
                    tool_call_id = f"call_{uuid.uuid4().hex[:24]}"
990
991
992
993
994
995
                function_name = call_item.name
            else:
                # Subsequent chunks: null ID and name for argument deltas
                tool_call_id = None
                function_name = None

996
            tool_call = ToolCall(
997
                id=tool_call_id,
998
999
                index=call_item.tool_index,
                function=FunctionResponse(
1000
                    name=function_name,
1001
1002
1003
1004
1005
1006
1007
                    arguments=call_item.parameters,
                ),
            )

            choice_data = ChatCompletionResponseStreamChoice(
                index=index,
                delta=DeltaMessage(tool_calls=[tool_call]),
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
                finish_reason=None,
            )
            chunk = ChatCompletionStreamResponse(
                id=content["meta_info"]["id"],
                created=int(time.time()),
                choices=[choice_data],
                model=request.model,
            )
            yield f"data: {chunk.model_dump_json()}\n\n"

    def _check_for_unstreamed_tool_args(
        self,
        parser: FunctionCallParser,
        content: Dict[str, Any],
        request: ChatCompletionRequest,
        index: int,
    ) -> Optional[str]:
        """
        Check for any remaining tool call arguments that need to be streamed
        when generation finishes. This ensures tool calls are properly completed
        even if the model generates the final arguments in the last chunk.
        """
        # Only check if we have tool calls and the parser has tracked data
        if (
            not hasattr(parser.detector, "prev_tool_call_arr")
            or not parser.detector.prev_tool_call_arr
        ):
            return None

        if (
            not hasattr(parser.detector, "streamed_args_for_tool")
            or not parser.detector.streamed_args_for_tool
        ):
            return None

        # Get the last tool call that was being processed
        tool_index = len(parser.detector.prev_tool_call_arr) - 1
        if tool_index < 0 or tool_index >= len(parser.detector.streamed_args_for_tool):
            return None

        # Get expected vs actual arguments
        expected_args = parser.detector.prev_tool_call_arr[tool_index].get(
            "arguments", {}
        )
        expected_call = json.dumps(expected_args, ensure_ascii=False)
        actual_call = parser.detector.streamed_args_for_tool[tool_index]

        # Check if there are remaining arguments to send
        remaining_call = (
            expected_call.replace(actual_call, "", 1)
            if actual_call in expected_call
            else ""
        )

        if remaining_call:
            # Create tool call chunk with remaining arguments
            tool_call = ToolCall(
                id=None,  # No ID for argument deltas
                index=tool_index,
                function=FunctionResponse(
                    name=None,  # No name for argument deltas
                    arguments=remaining_call,
1070
1071
                ),
            )
1072
1073
1074
1075
1076
1077
1078

            choice_data = ChatCompletionResponseStreamChoice(
                index=index,
                delta=DeltaMessage(tool_calls=[tool_call]),
                finish_reason=None,  # Don't send finish_reason with this chunk
            )

1079
1080
1081
1082
1083
1084
            chunk = ChatCompletionStreamResponse(
                id=content["meta_info"]["id"],
                created=int(time.time()),
                choices=[choice_data],
                model=request.model,
            )
1085

1086
1087
1088
            return f"data: {chunk.model_dump_json()}\n\n"

        return None