qwen3coder_tool_parser.py 32.2 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import ast
4
5
6
import json
import uuid
from collections.abc import Sequence
7
from typing import Any
8
9
10

import regex as re

11
from vllm.entrypoints.openai.chat_completion.protocol import (
12
13
    ChatCompletionRequest,
    ChatCompletionToolsParam,
14
15
)
from vllm.entrypoints.openai.engine.protocol import (
16
17
18
19
20
21
22
    DeltaFunctionCall,
    DeltaMessage,
    DeltaToolCall,
    ExtractedToolCallInformation,
    FunctionCall,
    ToolCall,
)
23
from vllm.logger import init_logger
24
from vllm.tokenizers import TokenizerLike
25
26
27
from vllm.tool_parsers.abstract_tool_parser import (
    ToolParser,
)
28
29
30
31
32

logger = init_logger(__name__)


class Qwen3CoderToolParser(ToolParser):
33
    def __init__(self, tokenizer: TokenizerLike):
34
35
36
37
        super().__init__(tokenizer)

        self.current_tool_name_sent: bool = False
        self.prev_tool_call_arr: list[dict] = []
38
        # Override base class type - we use string IDs for tool calls
39
        self.current_tool_id: str | None = None  # type: ignore
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
        self.streamed_args_for_tool: list[str] = []

        # Sentinel tokens for streaming mode
        self.tool_call_start_token: str = "<tool_call>"
        self.tool_call_end_token: str = "</tool_call>"
        self.tool_call_prefix: str = "<function="
        self.function_end_token: str = "</function>"
        self.parameter_prefix: str = "<parameter="
        self.parameter_end_token: str = "</parameter>"
        self.is_tool_call_started: bool = False
        self.failed_count: int = 0

        # Enhanced streaming state - reset for each new message
        self._reset_streaming_state()

        # Regex patterns
        self.tool_call_complete_regex = re.compile(
57
58
            r"<tool_call>(.*?)</tool_call>", re.DOTALL
        )
59
        self.tool_call_regex = re.compile(
60
61
            r"<tool_call>(.*?)</tool_call>|<tool_call>(.*?)$", re.DOTALL
        )
62
        self.tool_call_function_regex = re.compile(
63
64
            r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL
        )
65
        self.tool_call_parameter_regex = re.compile(
66
            r"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)",
67
68
            re.DOTALL,
        )
69
70
71
72

        if not self.model_tokenizer:
            raise ValueError(
                "The model tokenizer must be passed to the ToolParser "
73
74
                "constructor during construction."
            )
75

76
        self.tool_call_start_token_id = self.vocab.get(self.tool_call_start_token)
77
78
        self.tool_call_end_token_id = self.vocab.get(self.tool_call_end_token)

79
        if self.tool_call_start_token_id is None or self.tool_call_end_token_id is None:
80
81
            raise RuntimeError(
                "Qwen3 XML Tool parser could not locate tool call start/end "
82
83
                "tokens in the tokenizer!"
            )
84

85
86
87
        logger.info(
            "vLLM Successfully import tool parser %s !", self.__class__.__name__
        )
88
89
90
91
92
93
94
95
96
97

    def _generate_tool_call_id(self) -> str:
        """Generate a unique tool call ID."""
        return f"call_{uuid.uuid4().hex[:24]}"

    def _reset_streaming_state(self):
        """Reset all streaming state."""
        self.current_tool_index = 0
        self.is_tool_call_started = False
        self.header_sent = False
98
        self.current_tool_id = None
99
100
101
102
103
104
105
106
107
        self.current_function_name = None
        self.current_param_name = None
        self.current_param_value = ""
        self.param_count = 0
        self.in_param = False
        self.in_function = False
        self.accumulated_text = ""
        self.json_started = False
        self.json_closed = False
108
109
110
111
112
        # Store accumulated parameters for type conversion
        self.accumulated_params = {}
        self.streaming_request = None

    def _get_arguments_config(
113
        self, func_name: str, tools: list[ChatCompletionToolsParam] | None
114
    ) -> dict:
115
116
        """Extract argument configuration for a function."""
        if tools is None:
117
            return {}
118
        for config in tools:
119
120
121
            if not hasattr(config, "type") or not (
                hasattr(config, "function") and hasattr(config.function, "name")
            ):
122
123
124
125
126
127
128
129
130
131
132
                continue
            if config.type == "function" and config.function.name == func_name:
                if not hasattr(config.function, "parameters"):
                    return {}
                params = config.function.parameters
                if isinstance(params, dict) and "properties" in params:
                    return params["properties"]
                elif isinstance(params, dict):
                    return params
                else:
                    return {}
133
        logger.debug("Tool '%s' is not defined in the tools list.", func_name)
134
135
        return {}

136
137
138
    def _convert_param_value(
        self, param_value: str, param_name: str, param_config: dict, func_name: str
    ) -> Any:
139
140
141
142
        """Convert parameter value based on its type in the schema."""
        # Handle null value for any type
        if param_value.lower() == "null":
            return None
143

144
145
        if param_name not in param_config:
            if param_config != {}:
146
                logger.debug(
147
148
                    "Parsed parameter '%s' is not defined in the tool "
                    "parameters for tool '%s', directly returning the "
149
150
151
152
                    "string value.",
                    param_name,
                    func_name,
                )
153
154
            return param_value

155
156
157
158
        if (
            isinstance(param_config[param_name], dict)
            and "type" in param_config[param_name]
        ):
159
160
161
162
163
            param_type = str(param_config[param_name]["type"]).strip().lower()
        else:
            param_type = "string"
        if param_type in ["string", "str", "text", "varchar", "char", "enum"]:
            return param_value
164
165
166
167
168
169
170
        elif (
            param_type.startswith("int")
            or param_type.startswith("uint")
            or param_type.startswith("long")
            or param_type.startswith("short")
            or param_type.startswith("unsigned")
        ):
171
172
173
            try:
                return int(param_value)
            except (ValueError, TypeError):
174
                logger.debug(
175
176
                    "Parsed value '%s' of parameter '%s' is not an "
                    "integer in tool '%s', degenerating to string.",
177
178
179
180
                    param_value,
                    param_name,
                    func_name,
                )
181
                return param_value
182
183
184
        elif param_type.startswith("num") or param_type.startswith("float"):
            try:
                float_param_value = float(param_value)
185
186
187
188
189
                return (
                    float_param_value
                    if float_param_value - int(float_param_value) != 0
                    else int(float_param_value)
                )
190
            except (ValueError, TypeError):
191
                logger.debug(
192
                    "Parsed value '%s' of parameter '%s' is not a float "
193
194
195
196
197
                    "in tool '%s', degenerating to string.",
                    param_value,
                    param_name,
                    func_name,
                )
198
                return param_value
199
200
201
        elif param_type in ["boolean", "bool", "binary"]:
            param_value = param_value.lower()
            if param_value not in ["true", "false"]:
202
                logger.debug(
203
204
                    "Parsed value '%s' of parameter '%s' is not a boolean "
                    "(`true` or `false`) in tool '%s', degenerating to "
205
206
207
208
209
                    "false.",
                    param_value,
                    param_name,
                    func_name,
                )
210
211
            return param_value == "true"
        else:
212
213
214
215
216
            if (
                param_type in ["object", "array", "arr"]
                or param_type.startswith("dict")
                or param_type.startswith("list")
            ):
217
                try:
218
219
220
                    param_value = json.loads(param_value)
                    return param_value
                except (json.JSONDecodeError, TypeError, ValueError):
221
                    logger.debug(
222
223
                        "Parsed value '%s' of parameter '%s' cannot be "
                        "parsed with json.loads in tool '%s', will try "
224
225
226
227
228
                        "other methods to parse it.",
                        param_value,
                        param_name,
                        func_name,
                    )
229
230
231
            try:
                param_value = ast.literal_eval(param_value)  # safer
            except (ValueError, SyntaxError, TypeError):
232
                logger.debug(
233
234
                    "Parsed value '%s' of parameter '%s' cannot be "
                    "converted via Python `ast.literal_eval()` in tool "
235
236
237
238
239
                    "'%s', degenerating to string.",
                    param_value,
                    param_name,
                    func_name,
                )
240
241
242
            return param_value

    def _parse_xml_function_call(
243
244
        self, function_call_str: str, tools: list[ChatCompletionToolsParam] | None
    ) -> ToolCall | None:
245
        # Extract function name
246
247
248
249
        end_index = function_call_str.find(">")
        # If there's no ">" character, this is not a valid xml function call
        if end_index == -1:
            return None
250
        function_name = function_call_str[:end_index]
251
        param_config = self._get_arguments_config(function_name, tools)
252
        parameters = function_call_str[end_index + 1 :]
253
        param_dict = {}
254
        for match_text in self.tool_call_parameter_regex.findall(parameters):
255
256
            idx = match_text.index(">")
            param_name = match_text[:idx]
257
            param_value = str(match_text[idx + 1 :])
258
259
260
261
262
263
            # Remove prefix and trailing \n
            if param_value.startswith("\n"):
                param_value = param_value[1:]
            if param_value.endswith("\n"):
                param_value = param_value[:-1]

264
            param_dict[param_name] = self._convert_param_value(
265
266
                param_value, param_name, param_config, function_name
            )
267
268
        return ToolCall(
            type="function",
269
270
271
            function=FunctionCall(
                name=function_name, arguments=json.dumps(param_dict, ensure_ascii=False)
            ),
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        )

    def _get_function_calls(self, model_output: str) -> list[str]:
        # Find all tool calls
        matched_ranges = self.tool_call_regex.findall(model_output)
        raw_tool_calls = [
            match[0] if match[0] else match[1] for match in matched_ranges
        ]

        # Back-off strategy if no tool_call tags found
        if len(raw_tool_calls) == 0:
            raw_tool_calls = [model_output]

        raw_function_calls = []
        for tool_call in raw_tool_calls:
287
            raw_function_calls.extend(self.tool_call_function_regex.findall(tool_call))
288
289
290
291
292
293
294
295
296
297
298
299
300

        function_calls = [
            match[0] if match[0] else match[1] for match in raw_function_calls
        ]
        return function_calls

    def extract_tool_calls(
        self,
        model_output: str,
        request: ChatCompletionRequest,
    ) -> ExtractedToolCallInformation:
        # Quick check to avoid unnecessary processing
        if self.tool_call_prefix not in model_output:
301
302
303
            return ExtractedToolCallInformation(
                tools_called=False, tool_calls=[], content=model_output
            )
304
305
306
307

        try:
            function_calls = self._get_function_calls(model_output)
            if len(function_calls) == 0:
308
309
310
                return ExtractedToolCallInformation(
                    tools_called=False, tool_calls=[], content=model_output
                )
311
312
313
314
315
316

            tool_calls = [
                self._parse_xml_function_call(function_call_str, request.tools)
                for function_call_str in function_calls
            ]

317
            # Populate prev_tool_call_arr for serving layer to set finish_reason
318
319
320
            self.prev_tool_call_arr.clear()  # Clear previous calls
            for tool_call in tool_calls:
                if tool_call:
321
322
323
324
325
326
                    self.prev_tool_call_arr.append(
                        {
                            "name": tool_call.function.name,
                            "arguments": tool_call.function.arguments,
                        }
                    )
327
328
329

            # Extract content before tool calls
            content_index = model_output.find(self.tool_call_start_token)
330
331
            idx = model_output.find(self.tool_call_prefix)
            content_index = content_index if content_index >= 0 else idx
332
            content = model_output[:content_index]  # .rstrip()
333
            valid_tool_calls = [tc for tc in tool_calls if tc is not None]
334
            return ExtractedToolCallInformation(
335
336
                tools_called=(len(valid_tool_calls) > 0),
                tool_calls=valid_tool_calls,
337
338
339
340
341
                content=content if content else None,
            )

        except Exception:
            logger.exception("Error in extracting tool call from response.")
342
343
344
            return ExtractedToolCallInformation(
                tools_called=False, tool_calls=[], content=model_output
            )
345
346
347
348
349
350
351
352
353
354

    def extract_tool_calls_streaming(
        self,
        previous_text: str,
        current_text: str,
        delta_text: str,
        previous_token_ids: Sequence[int],
        current_token_ids: Sequence[int],
        delta_token_ids: Sequence[int],
        request: ChatCompletionRequest,
355
    ) -> DeltaMessage | None:
356
357
358
359
360
361
        # Store request for type conversion
        if not previous_text:
            self._reset_streaming_state()
            self.streaming_request = request

        # If no delta text, return None unless it's an EOS token after tools
362
363
        if not delta_text:
            # Check if this is an EOS token after all tool calls are complete
364
365
            # Check for tool calls in text even if is_tool_call_started
            # is False (might have been reset after processing all tools)
366
            if delta_token_ids and self.tool_call_end_token_id not in delta_token_ids:
367
368
                # Count complete tool calls
                complete_calls = len(
369
370
                    self.tool_call_complete_regex.findall(current_text)
                )
371
372
373

                # If we have completed tool calls and populated
                # prev_tool_call_arr
374
                if complete_calls > 0 and len(self.prev_tool_call_arr) > 0:
375
                    # Check if all tool calls are closed
376
                    open_calls = current_text.count(
377
378
                        self.tool_call_start_token
                    ) - current_text.count(self.tool_call_end_token)
379
                    if open_calls == 0:
380
                        # Return empty delta for finish_reason processing
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
                        return DeltaMessage(content="")
                elif not self.is_tool_call_started and current_text:
                    # This is a regular content response that's now complete
                    return DeltaMessage(content="")
            return None

        # Update accumulated text
        self.accumulated_text = current_text

        # Check if we need to advance to next tool
        if self.json_closed and not self.in_function:
            # Check if this tool call has ended
            tool_ends = current_text.count(self.tool_call_end_token)
            if tool_ends > self.current_tool_index:
                # This tool has ended, advance to next
                self.current_tool_index += 1
                self.header_sent = False
                self.param_count = 0
                self.json_started = False
                self.json_closed = False
401
                self.accumulated_params = {}
402
403

                # Check if there are more tool calls
404
405
                tool_starts = current_text.count(self.tool_call_start_token)
                if self.current_tool_index >= tool_starts:
406
407
408
409
410
411
412
413
                    # No more tool calls
                    self.is_tool_call_started = False
                # Continue processing next tool
                return None

        # Handle normal content before tool calls
        if not self.is_tool_call_started:
            # Check if tool call is starting
414
415
416
417
            if (
                self.tool_call_start_token_id in delta_token_ids
                or self.tool_call_start_token in delta_text
            ):
418
419
420
                self.is_tool_call_started = True
                # Return any content before the tool call
                if self.tool_call_start_token in delta_text:
421
422
423
                    content_before = delta_text[
                        : delta_text.index(self.tool_call_start_token)
                    ]
424
425
426
427
428
                    if content_before:
                        return DeltaMessage(content=content_before)
                return None
            else:
                # Check if we're between tool calls - skip whitespace
429
430
431
432
                if (
                    current_text.rstrip().endswith(self.tool_call_end_token)
                    and delta_text.strip() == ""
                ):
433
434
435
436
437
438
439
440
441
442
443
444
445
446
                    # We just ended a tool call, skip whitespace
                    return None
                # Normal content, no tool call
                return DeltaMessage(content=delta_text)

        # Check if we're between tool calls (waiting for next one)
        # Count tool calls we've seen vs processed
        tool_starts_count = current_text.count(self.tool_call_start_token)
        if self.current_tool_index >= tool_starts_count:
            # We're past all tool calls, shouldn't be here
            return None

        # We're in a tool call, find the current tool call portion
        # Need to find the correct tool call based on current_tool_index
447
        tool_start_positions: list[int] = []
448
449
450
451
452
        idx = 0
        while True:
            idx = current_text.find(self.tool_call_start_token, idx)
            if idx == -1:
                break
453
            tool_start_positions.append(idx)
454
455
            idx += len(self.tool_call_start_token)

456
        if self.current_tool_index >= len(tool_start_positions):
457
458
459
            # No more tool calls to process yet
            return None

460
        tool_start_idx = tool_start_positions[self.current_tool_index]
461
        # Find where this tool call ends (or current position if not ended yet)
462
        tool_end_idx = current_text.find(self.tool_call_end_token, tool_start_idx)
463
464
465
        if tool_end_idx == -1:
            tool_text = current_text[tool_start_idx:]
        else:
466
467
468
            tool_text = current_text[
                tool_start_idx : tool_end_idx + len(self.tool_call_end_token)
            ]
469
470
471
472

        # Looking for function header
        if not self.header_sent:
            if self.tool_call_prefix in tool_text:
473
                func_start = tool_text.find(self.tool_call_prefix) + len(
474
475
                    self.tool_call_prefix
                )
476
477
478
479
480
                func_end = tool_text.find(">", func_start)

                if func_end != -1:
                    # Found complete function name
                    self.current_function_name = tool_text[func_start:func_end]
481
                    self.current_tool_id = self._generate_tool_call_id()
482
483
484
                    self.header_sent = True
                    self.in_function = True

485
486
                    # IMPORTANT: Add to prev_tool_call_arr immediately when
                    # we detect a tool call. This ensures
487
488
489
                    # finish_reason="tool_calls" even if parsing isn't complete
                    already_added = any(
                        tool.get("name") == self.current_function_name
490
491
                        for tool in self.prev_tool_call_arr
                    )
492
                    if not already_added:
493
494
495
496
497
498
                        self.prev_tool_call_arr.append(
                            {
                                "name": self.current_function_name,
                                "arguments": "{}",  # Placeholder, will be updated later
                            }
                        )
499
500

                    # Send header with function info
501
502
503
504
505
506
507
508
509
510
511
512
                    return DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_index,
                                id=self.current_tool_id,
                                function=DeltaFunctionCall(
                                    name=self.current_function_name, arguments=""
                                ),
                                type="function",
                            )
                        ]
                    )
513
514
515
516
517
            return None

        # We've sent header, now handle function body
        if self.in_function:
            # Send opening brace if not sent yet
518
            if not self.json_started and self.parameter_prefix not in delta_text:
519
                self.json_started = True
520
521
522
523
524
525
526
527
                return DeltaMessage(
                    tool_calls=[
                        DeltaToolCall(
                            index=self.current_tool_index,
                            function=DeltaFunctionCall(arguments="{"),
                        )
                    ]
                )
528
529
530
531
532
533
534
535
536
537

            # Make sure json_started is set if we're processing parameters
            if not self.json_started:
                self.json_started = True

            # Check for function end in accumulated text
            if not self.json_closed and self.function_end_token in tool_text:
                # Close JSON
                self.json_closed = True

538
539
540
541
                # Extract complete tool call to update
                # prev_tool_call_arr with final arguments
                # Find the function content
                func_start = tool_text.find(self.tool_call_prefix) + len(
542
543
544
                    self.tool_call_prefix
                )
                func_content_end = tool_text.find(self.function_end_token, func_start)
545
546
547
548
549
                if func_content_end != -1:
                    func_content = tool_text[func_start:func_content_end]
                    # Parse to get the complete arguments
                    try:
                        parsed_tool = self._parse_xml_function_call(
550
551
552
553
554
                            func_content,
                            self.streaming_request.tools
                            if self.streaming_request
                            else None,
                        )
555
                        if parsed_tool:
556
557
                            # Update existing entry in
                            # prev_tool_call_arr with complete args
558
                            for i, tool in enumerate(self.prev_tool_call_arr):
559
                                if tool.get("name") == parsed_tool.function.name:
560
                                    args = parsed_tool.function.arguments
561
                                    self.prev_tool_call_arr[i]["arguments"] = args
562
563
564
565
                                    break
                    except Exception:
                        pass  # Ignore parsing errors during streaming

566
567
568
569
570
571
572
573
                result = DeltaMessage(
                    tool_calls=[
                        DeltaToolCall(
                            index=self.current_tool_index,
                            function=DeltaFunctionCall(arguments="}"),
                        )
                    ]
                )
574
575
576
577

                # Reset state for next tool
                self.in_function = False
                self.json_closed = True
578
                self.accumulated_params = {}
579
580
581
582

                return result

            # Look for parameters
583
584
585
586
587
588
589
590
591
            # Find all parameter starts
            param_starts = []
            idx = 0
            while True:
                idx = tool_text.find(self.parameter_prefix, idx)
                if idx == -1:
                    break
                param_starts.append(idx)
                idx += len(self.parameter_prefix)
592
593

            # Check if we should start a new parameter
594
595
596
597
598
            if (
                not self.in_param
                and self.param_count < len(param_starts)
                and len(param_starts) > self.param_count
            ):
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
                # Process the next parameter
                param_idx = param_starts[self.param_count]
                param_start = param_idx + len(self.parameter_prefix)
                remaining = tool_text[param_start:]

                if ">" in remaining:
                    # We have the complete parameter name
                    name_end = remaining.find(">")
                    self.current_param_name = remaining[:name_end]

                    # Find the parameter value
                    value_start = param_start + name_end + 1
                    value_text = tool_text[value_start:]
                    if value_text.startswith("\n"):
                        value_text = value_text[1:]

                    # Find where this parameter ends
                    param_end_idx = value_text.find(self.parameter_end_token)
                    if param_end_idx == -1:
                        # No closing tag, look for next parameter or
                        # function end
                        next_param_idx = value_text.find(self.parameter_prefix)
                        func_end_idx = value_text.find(self.function_end_token)

623
624
625
                        if next_param_idx != -1 and (
                            func_end_idx == -1 or next_param_idx < func_end_idx
                        ):
626
627
628
629
630
631
632
633
634
635
                            param_end_idx = next_param_idx
                        elif func_end_idx != -1:
                            param_end_idx = func_end_idx
                        else:
                            # Neither found, check if tool call is complete
                            if self.tool_call_end_token in tool_text:
                                # Tool call is complete, so parameter
                                # must be complete too. Use all
                                # remaining text before function end
                                param_end_idx = len(value_text)
636
                            else:
637
638
639
640
641
642
643
644
645
646
                                # Still streaming, wait for more content
                                return None

                    if param_end_idx != -1:
                        # Complete parameter found
                        param_value = value_text[:param_end_idx]
                        if param_value.endswith("\n"):
                            param_value = param_value[:-1]

                        # Store raw value for later processing
647
                        self.accumulated_params[self.current_param_name] = param_value
648
649
650
651
652

                        # Get parameter configuration for type conversion
                        param_config = self._get_arguments_config(
                            self.current_function_name or "",
                            self.streaming_request.tools
653
654
655
                            if self.streaming_request
                            else None,
                        )
656
657
658

                        # Convert param value to appropriate type
                        converted_value = self._convert_param_value(
659
660
661
662
663
                            param_value,
                            self.current_param_name,
                            param_config,
                            self.current_function_name or "",
                        )
664
665
666

                        # Build JSON fragment based on the converted type
                        # Use json.dumps to properly serialize the value
667
668
669
                        serialized_value = json.dumps(
                            converted_value, ensure_ascii=False
                        )
670
671

                        if self.param_count == 0:
672
673
674
                            json_fragment = (
                                f'"{self.current_param_name}": {serialized_value}'
                            )
675
                        else:
676
677
678
                            json_fragment = (
                                f', "{self.current_param_name}": {serialized_value}'
                            )
679
680
681

                        self.param_count += 1

682
683
684
685
686
687
688
689
                        return DeltaMessage(
                            tool_calls=[
                                DeltaToolCall(
                                    index=self.current_tool_index,
                                    function=DeltaFunctionCall(arguments=json_fragment),
                                )
                            ]
                        )
690
691
692

            # Continue parameter value - Not used in the current implementation
            # since we process complete parameters above
693
694
695
696
697
698
699
700
701
            if self.in_param:
                if self.parameter_end_token in delta_text:
                    # End of parameter
                    end_idx = delta_text.find(self.parameter_end_token)
                    value_chunk = delta_text[:end_idx]

                    # Skip past > if at start
                    if not self.current_param_value and ">" in value_chunk:
                        gt_idx = value_chunk.find(">")
702
                        value_chunk = value_chunk[gt_idx + 1 :]
703

704
                    if not self.current_param_value and value_chunk.startswith("\n"):
705
706
                        value_chunk = value_chunk[1:]

707
                    # Store complete value
708
                    full_value = self.current_param_value + value_chunk
709
                    self.accumulated_params[self.current_param_name] = full_value
710
711
712
713
714

                    # Get parameter configuration for type conversion
                    param_config = self._get_arguments_config(
                        self.current_function_name or "",
                        self.streaming_request.tools
715
716
717
                        if self.streaming_request
                        else None,
                    )
718
719
720

                    # Convert the parameter value to the appropriate type
                    converted_value = self._convert_param_value(
721
722
723
724
725
                        full_value,
                        self.current_param_name or "",
                        param_config,
                        self.current_function_name or "",
                    )
726
727

                    # Serialize the converted value
728
                    serialized_value = json.dumps(converted_value, ensure_ascii=False)
729
730
731
732

                    # Since we've been streaming the quoted version,
                    # we need to close it properly
                    # This is complex - for now just complete the value
733
734
735
                    self.in_param = False
                    self.current_param_value = ""

736
                    # Just close the current parameter string
737
738
739
740
741
742
743
744
745
746
                    return DeltaMessage(
                        tool_calls=[
                            DeltaToolCall(
                                index=self.current_tool_index,
                                function=DeltaFunctionCall(
                                    arguments='"'
                                ),  # Close the string quote
                            )
                        ]
                    )
747
748
749
750
751
752
753
                else:
                    # Continue accumulating value
                    value_chunk = delta_text

                    # Handle first chunk after param name
                    if not self.current_param_value and ">" in value_chunk:
                        gt_idx = value_chunk.find(">")
754
                        value_chunk = value_chunk[gt_idx + 1 :]
755

756
                    if not self.current_param_value and value_chunk.startswith("\n"):
757
758
759
760
                        value_chunk = value_chunk[1:]

                    if value_chunk:
                        # Stream the escaped delta
761
762
763
764
765
766
767
                        prev_escaped = (
                            json.dumps(self.current_param_value, ensure_ascii=False)[
                                1:-1
                            ]
                            if self.current_param_value
                            else ""
                        )
768
                        self.current_param_value += value_chunk
769
770
771
772
                        full_escaped = json.dumps(
                            self.current_param_value, ensure_ascii=False
                        )[1:-1]
                        delta_escaped = full_escaped[len(prev_escaped) :]
773
774

                        if delta_escaped:
775
776
777
778
779
780
781
782
783
784
                            return DeltaMessage(
                                tool_calls=[
                                    DeltaToolCall(
                                        index=self.current_tool_index,
                                        function=DeltaFunctionCall(
                                            arguments=delta_escaped
                                        ),
                                    )
                                ]
                            )
785

786
        return None