Skip to content

vllm.tool_parsers.kimi_k3_tool_parser

Tool-call parser for the Kimi K3 (XTML) chat format.

This turns the generated XTML response and tools channels back into OpenAI-compatible content and tool_calls.

K3 assistant tool calls live in a nested tools channel::

<|open|>tools<|sep|>
  <|open|>call tool="python" index="1"<|sep|>
    <|open|>argument key="code" type="string"<|sep|>print(1)<|close|>argument<|sep|>
    <|open|>argument key="opts" type="object"<|sep|>{"a":1}<|close|>argument<|sep|>
  <|close|>call<|sep|>
<|close|>tools<|sep|>

where <|open|>, <|close|>, <|sep|> are dedicated special tokens. The plain reply lives in a sibling response channel which is unwrapped into content. response always precedes tools (see the protocol channel grammar).

Argument decoding mirrors the template's type tagging (inverse encoding): * type="string" -> value is the RAW text, no unescaping (template emits it raw) * other types -> value is JSON-decoded (number/boolean/null/object/array)

Attribute values (tool=, index=, key=, type=) ARE escaped on the encode side (& -> &amp;, " -> &quot;), so _attrs reverses them on decode (&quot; before &amp; -- reverse of encode order).

Known limitation: because string argument and response bodies are emitted raw, a value that literally contains <|close|>argument<|sep|> or <|close|>response<|sep|> is indistinguishable from a real closing marker.

Classes:

KimiK3ToolParser

Bases: ToolParser

Source code in vllm/tool_parsers/kimi_k3_tool_parser.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
class KimiK3ToolParser(ToolParser):
    supports_required_and_named = False
    # Enables the vLLM-side XTML structural tag builder
    # (``get_kimi_k3_structural_tag`` in ``structural_tag_registry``). With
    # ``VLLM_ENFORCE_STRICT_TOOL_CALLING`` on (default), ``_apply_structural_tag``
    # constrains generation to K3's ``<|open|>tools<|sep|>`` channel for
    # ``required`` (and ``auto`` when a tool sets ``strict``) instead of the
    # generic JSON guided decoding, which conflicts with the XTML format.
    structural_tag_model = "kimi_k3"

    def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
        super().__init__(tokenizer, tools)

        self.tools_open = "<|open|>tools<|sep|>"
        self.tools_close = "<|close|>tools<|sep|>"
        self.response_open = "<|open|>response<|sep|>"
        self.response_close = "<|close|>response<|sep|>"

        # Regexes operate on detokenized text. The XTML markers reach us as the
        # literal strings <|open|>/<|close|>/<|sep|>. adjust_request keeps them
        # from being stripped and suppresses spacing between adjacent token
        # pieces. As DEFENSE-IN-DEPTH we still tolerate optional whitespace
        # WITHIN a marker (e.g. "<|open|> tools <|sep|>") in case some serving
        # path leaves vLLM's added-token spacing on -- this `\s*` is a no-op on
        # clean input, so the normal byte-exact path is unaffected. We do NOT
        # strip body whitespace, so clean content stays byte-exact.
        # All bodies use non-greedy (.*?) so each block stops at its own first
        # closing marker -- see the module-level KNOWN LIMITATION about
        # literal-marker values.
        self._tools_open_re = re.compile(_O + r"\s*tools\s*" + _S)
        self._tools_close_re = re.compile(_C + r"\s*tools\s*" + _S)
        self._response_open_re = re.compile(_O + r"\s*response\s*" + _S)
        self._response_close_re = re.compile(_C + r"\s*response\s*" + _S)
        self._message_close_re = re.compile(_C + r"\s*message\s*" + _S)
        self._call_re = re.compile(
            _O
            + r"\s*call\s+(?P<attrs>"
            + _TEXT_UNTIL_SEP
            + r")"
            + _S
            + r"(?P<body>.*?)"
            + _C
            + r"\s*call\s*"
            + _S,
            re.DOTALL,
        )
        self._arg_re = re.compile(
            _O
            + r"\s*argument\s+(?P<attrs>"
            + _TEXT_UNTIL_SEP
            + r")"
            + _S
            + r"(?P<val>.*?)"
            + _C
            + r"\s*argument\s*"
            + _S,
            re.DOTALL,
        )
        # attr segment: key="value" (value already escaped on the encode side)
        self._attr_re = re.compile(r'(?P<k>\w+)="(?P<v>[^"]*)"')
        self._response_re = re.compile(
            _O + r"\s*response\s*" + _S + r"(?P<c>.*?)" + _C + r"\s*response\s*" + _S,
            re.DOTALL,
        )
        self._call_close_re = re.compile(_C + r"\s*call\s*" + _S)
        self._call_open_re = re.compile(
            _O + r"\s*call\s+(?P<attrs>" + _TEXT_UNTIL_SEP + r")" + _S,
            re.DOTALL,
        )
        self._arg_open_re = re.compile(
            _O + r"\s*argument\s+(?P<attrs>" + _TEXT_UNTIL_SEP + r")" + _S,
            re.DOTALL,
        )
        self._arg_close_re = re.compile(_C + r"\s*argument\s*" + _S)

        # streaming state
        self._sent_content_idx = 0
        self._sent_tool_call_count = 0
        self._stream_tool_idx = 0
        self._stream_call: _StreamingCall | None = None
        self._stream_tools_closed = False

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

    def adjust_request(
        self, request: ChatCompletionRequest | ResponsesRequest
    ) -> ChatCompletionRequest | ResponsesRequest:
        named = isinstance(
            request.tool_choice,
            (
                ChatCompletionNamedToolChoiceParam,
                ToolChoiceFunction,
                ToolChoiceCustom,
            ),
        )
        structured_outputs = getattr(request, "structured_outputs", None)
        has_structural_tag = (
            structured_outputs is not None
            and structured_outputs.structural_tag is not None
        )
        if named and not has_structural_tag:
            # Without the XTML structural tag there is no way to force the
            # named call (the generic JSON guided-decoding path conflicts
            # with the XTML channel format).
            raise VLLMValidationError(
                "Named tool choice for Kimi K3 requires strict tool calling "
                "(VLLM_ENFORCE_STRICT_TOOL_CALLING) so the XTML structural "
                "tag can force the call. Otherwise use `tool_choice` set to "
                '"auto", "required", or "none".',
                parameter="tool_choice",
                value=request.tool_choice,
            )

        if request.tools and (request.tool_choice == "required" or named):
            # K3 emits tool calls in XTML. When strict tool calling is enabled,
            # DelegatingParser._apply_structural_tag has already attached the K3
            # XTML structural tag (structural_tag_model = "kimi_k3"). We return
            # early to skip the generic parent path, which would otherwise attach
            # JSON guided decoding when strict calling is off -- that JSON
            # constraint conflicts with the <|open|>tools<|sep|> channel.
            request.skip_special_tokens = False
            if hasattr(request, "spaces_between_special_tokens"):
                request.spaces_between_special_tokens = False
            return request

        request = super().adjust_request(request)
        # The XTML markers (<|open|>/<|close|>/<|sep|>,
        # <|open|>response<|sep|> ...) must
        # reach this parser as CONTIGUOUS literal text. Two request flags govern
        # that, and vLLM's detokenizer couples them:
        #   effective_spaces_between =
        #       skip_special_tokens OR spaces_between_special_tokens
        #   (vllm/v1/engine/detokenizer.py).
        # The detokenizer treats these control tokens as separate sub-texts and,
        # when the effective flag is True, joins them with spaces ->
        # "<|open|> response <|sep|>", which the regexes below would NOT match.
        # Forcing BOTH flags off is the only way to suppress that spacing. We
        # set both unconditionally: the response channel is unwrapped from these
        # markers even with no tools.
        request.skip_special_tokens = False
        if hasattr(request, "spaces_between_special_tokens"):
            request.spaces_between_special_tokens = False
        return request

    def _attrs(self, s: str) -> dict[str, str]:
        return {
            m["k"]: m["v"].replace("&quot;", '"').replace("&amp;", "&")
            for m in self._attr_re.finditer(s)
        }

    def _decode_call(self, attrs: str, body: str) -> ToolCall | None:
        """Decode one `call` block into a `ToolCall`.

        `attrs` is the text between `<|open|>call ` and `<|sep|>` (carries
        `tool=` / `index=`); `body` is the sequence of `argument` blocks.
        Each argument is re-typed per its `type=` tag: strings pass through
        raw, everything else is JSON-decoded (falling back to raw text if the
        JSON is malformed, so a partial stream never raises). Returns `None`
        when no tool name is present (an empty/garbage block is dropped).
        """
        call_attrs = self._attrs(attrs)
        tool_name = call_attrs.get("tool", "")
        arguments: dict = {}
        for arg_match in self._arg_re.finditer(body):
            arg_attrs = self._attrs(arg_match["attrs"])
            key = arg_attrs.get("key", "")
            arg_type = arg_attrs.get("type", "string")
            raw_value = arg_match["val"]
            if arg_type == "string":
                arguments[key] = raw_value
            else:
                try:
                    arguments[key] = json.loads(raw_value)
                except json.JSONDecodeError:
                    arguments[key] = raw_value
        if not tool_name:
            return None
        return ToolCall(
            type="function",
            function=FunctionCall(
                name=tool_name,
                arguments=json.dumps(arguments, ensure_ascii=False),
            ),
        )

    def _strip_response_content(self, text: str) -> str | None:
        """Strip XTML response/message markers from generated response text.

        In chat serving, `<|open|>response<|sep|>` is often part of the prompt
        generation prefix, so the model output may only contain the body plus
        `<|close|>response<|sep|>`. Handle both that consumed-prefix shape and a
        complete `<|open|>response<|sep|>... <|close|>response<|sep|>` wrapper.
        """
        m_open = self._response_open_re.search(text)
        if m_open is not None:
            m_close = self._response_close_re.search(text, m_open.end())
            if m_close is not None:
                text = text[m_open.end() : m_close.start()]
            else:
                text = text[m_open.end() :]
        else:
            text = self._response_close_re.sub("", text)
        text = self._message_close_re.sub("", text)
        return text or None

    def _content(self, model_output: str, before: str) -> str | None:
        # prefer the unwrapped response channel; else the text before the tools
        m = self._response_re.search(model_output)
        if m is not None:
            return m["c"] or None
        return self._strip_response_content(before)

    def _extract_response_content(self, current_text: str) -> str | None:
        # Streaming response text is computed from the accumulated text. This is
        # what keeps split markers from leaking:
        #   <|open|> / response / <|sep|>Hi     -> emit only "Hi" after open closes
        #   Hi<|open|> / tools / <|sep|>...     -> emit "Hi", hold the tools marker
        #   Hi<|close|> / response / <|sep|>... -> emit "Hi", hold the close marker
        m_open = self._response_open_re.search(current_text)
        # In the normal chat path, the response-open marker may be consumed as
        # the generation prefix. Then generated text starts directly with the
        # response body or with <|close|>response<|sep|> before a tools channel.
        body_start = m_open.end() if m_open is not None else 0
        m_tools = self._tools_open_re.search(current_text, body_start)
        m_rclose = self._response_close_re.search(current_text, body_start)
        tools_start = m_tools.start() if m_tools else -1
        response_end = m_rclose.start() if m_rclose else -1

        candidates = [i for i in (tools_start, response_end) if i != -1]
        if candidates:
            sendable_idx = min(candidates)
        else:
            overlap = max(
                _partial_tag_overlap(current_text, self.response_open),
                _partial_tag_overlap(current_text, self.response_close),
                _partial_tag_overlap(current_text, self.tools_open),
            )
            sendable_idx = len(current_text) - overlap

        if sendable_idx <= body_start:
            return None
        if self._sent_content_idx < body_start:
            self._sent_content_idx = body_start
        if sendable_idx <= self._sent_content_idx:
            return None

        content = current_text[self._sent_content_idx : sendable_idx]
        self._sent_content_idx = sendable_idx
        return content or None

    @staticmethod
    def _append_arguments(
        deltas: list[DeltaToolCall], index: int | None, arguments: str
    ) -> None:
        if index is None or not arguments:
            return
        if deltas and deltas[-1].index == index and deltas[-1].function is not None:
            function = deltas[-1].function
            function.arguments = (function.arguments or "") + arguments
            return
        deltas.append(
            DeltaToolCall(
                index=index,
                function=DeltaFunctionCall(arguments=arguments).model_dump(
                    exclude_none=True
                ),
            )
        )

    def _stream_tool_calls(self, text: str) -> list[DeltaToolCall]:
        """Stream calls from the tools channel without waiting for call close.

        String values are raw XTML text, so they can be JSON-escaped and sent
        as they arrive. Other values are JSON-decoded and normalized like the
        non-streaming path, so they are sent once their argument closes.
        """
        deltas: list[DeltaToolCall] = []
        pos = self._stream_tool_idx
        if self._stream_tools_closed:
            return deltas
        m_tools_close = self._tools_close_re.search(text, pos, partial=True)
        tools_end = len(text) if m_tools_close is None else m_tools_close.start()
        text = text[:tools_end]
        while True:
            call = self._stream_call
            if call is None:
                m_call = self._call_open_re.search(text, pos, partial=True)
                if m_call is None:
                    pos = len(text)
                    break
                if m_call.partial:
                    pos = m_call.start()
                    break
                name = self._attrs(m_call["attrs"]).get("tool", "")
                index = self._sent_tool_call_count if name else None
                self._stream_call = _StreamingCall(index)
                pos = m_call.end()
                if index is not None:
                    self._sent_tool_call_count += 1
                    deltas.append(
                        DeltaToolCall(
                            index=index,
                            id=make_tool_call_id(),
                            type="function",
                            function=DeltaFunctionCall(
                                name=name, arguments="{"
                            ).model_dump(exclude_none=True),
                        )
                    )
                continue

            if call.arg_type is None:
                m_arg = self._arg_open_re.search(text, pos, partial=True)
                m_close = self._call_close_re.search(text, pos, partial=True)
                complete = [
                    match
                    for match in (m_arg, m_close)
                    if match is not None and not match.partial
                ]
                if not complete:
                    pos = min(
                        (match.start() for match in (m_arg, m_close) if match),
                        default=len(text),
                    )
                    break
                match = min(complete, key=lambda item: item.start())
                pos = match.end()
                if match is m_close:
                    self._append_arguments(deltas, call.index, "}")
                    self._stream_call = None
                    continue
                attrs = self._attrs(match["attrs"])
                call.arg_type = attrs.get("type", "string")
                call.value_start = call.value_sent = pos
                prefix = ", " if call.arg_count else ""
                prefix += json.dumps(attrs.get("key", ""), ensure_ascii=False) + ": "
                if call.arg_type == "string":
                    prefix += '"'
                    self._append_arguments(deltas, call.index, prefix)
                    call.arg_count += 1
                else:
                    call.arg_prefix = prefix
                continue

            m_value_close = self._arg_close_re.search(text, pos, partial=True)
            m_call_close = self._call_close_re.search(text, pos, partial=True)
            value_end = min(
                (
                    match.start()
                    for match in (m_value_close, m_call_close)
                    if match is not None
                ),
                default=len(text),
            )
            if call.arg_type == "string":
                value = text[call.value_sent : value_end]
                self._append_arguments(
                    deltas, call.index, json.dumps(value, ensure_ascii=False)[1:-1]
                )
                call.value_sent = value_end
            if (
                m_call_close is not None
                and not m_call_close.partial
                and m_call_close.start() == value_end
                and (
                    m_value_close is None
                    or m_value_close.partial
                    or m_call_close.start() < m_value_close.start()
                )
            ):
                # The call closed before this argument closed. Typed values have
                # not been emitted yet, so drop them like the non-streaming path.
                # String text was already streamed, so close it as valid JSON.
                suffix = '"}' if call.arg_type == "string" else "}"
                self._append_arguments(deltas, call.index, suffix)
                self._stream_call = None
                pos = m_call_close.end()
                continue
            if m_value_close is None or m_value_close.partial:
                pos = value_end
                break
            if call.arg_type == "string":
                self._append_arguments(deltas, call.index, '"')
            else:
                raw_value = text[call.value_start : value_end]
                try:
                    value = json.loads(raw_value)
                except json.JSONDecodeError:
                    value = raw_value
                self._append_arguments(
                    deltas,
                    call.index,
                    call.arg_prefix + json.dumps(value, ensure_ascii=False),
                )
                call.arg_count += 1
                call.arg_prefix = ""
            call.arg_type = None
            pos = m_value_close.end()

        if m_tools_close is not None and not m_tools_close.partial:
            call = self._stream_call
            if call is not None:
                # Tool calls cannot continue after the tools channel closes. Close
                # an already announced call so its streamed arguments stay valid.
                suffix = '"}' if call.arg_type == "string" else "}"
                self._append_arguments(deltas, call.index, suffix)
                self._stream_call = None
            self._stream_tools_closed = True
            pos = m_tools_close.end()
        self._stream_tool_idx = pos
        return deltas

    def extract_tool_calls(
        self, model_output: str, request: ChatCompletionRequest
    ) -> ExtractedToolCallInformation:
        m_open = self._tools_open_re.search(model_output)
        if m_open is None:
            # no tools channel -> content is the response channel (unwrapped)
            return ExtractedToolCallInformation(
                tools_called=False,
                tool_calls=[],
                content=self._content(model_output, model_output),
            )
        try:
            before = model_output[: m_open.start()]
            start = m_open.end()
            m_close = self._tools_close_re.search(model_output, start)
            section = (
                model_output[start:]
                if m_close is None
                else model_output[start : m_close.start()]
            )

            tool_calls = [
                tc
                for m in self._call_re.finditer(section)
                if (tc := self._decode_call(m["attrs"], m["body"])) is not None
            ]
            if not tool_calls:
                return ExtractedToolCallInformation(
                    tools_called=False,
                    tool_calls=[],
                    content=self._content(model_output, before),
                )
            return ExtractedToolCallInformation(
                tools_called=True,
                tool_calls=tool_calls,
                content=self._content(model_output, before),
            )
        except Exception:
            logger.exception("Error extracting K3 tool calls.")
            return ExtractedToolCallInformation(
                tools_called=False, tool_calls=[], content=model_output
            )

    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,
    ) -> DeltaMessage | None:
        content = self._extract_response_content(current_text)
        m_tools = self._tools_open_re.search(current_text)
        if m_tools is None:
            return DeltaMessage(content=content) if content else None

        self._stream_tool_idx = max(self._stream_tool_idx, m_tools.end())
        deltas = self._stream_tool_calls(current_text)
        if not deltas:
            return DeltaMessage(content=content) if content else None
        return DeltaMessage(content=content, tool_calls=deltas)

_decode_call(attrs, body)

Decode one call block into a ToolCall.

attrs is the text between <|open|>call and <|sep|> (carries tool= / index=); body is the sequence of argument blocks. Each argument is re-typed per its type= tag: strings pass through raw, everything else is JSON-decoded (falling back to raw text if the JSON is malformed, so a partial stream never raises). Returns None when no tool name is present (an empty/garbage block is dropped).

Source code in vllm/tool_parsers/kimi_k3_tool_parser.py
def _decode_call(self, attrs: str, body: str) -> ToolCall | None:
    """Decode one `call` block into a `ToolCall`.

    `attrs` is the text between `<|open|>call ` and `<|sep|>` (carries
    `tool=` / `index=`); `body` is the sequence of `argument` blocks.
    Each argument is re-typed per its `type=` tag: strings pass through
    raw, everything else is JSON-decoded (falling back to raw text if the
    JSON is malformed, so a partial stream never raises). Returns `None`
    when no tool name is present (an empty/garbage block is dropped).
    """
    call_attrs = self._attrs(attrs)
    tool_name = call_attrs.get("tool", "")
    arguments: dict = {}
    for arg_match in self._arg_re.finditer(body):
        arg_attrs = self._attrs(arg_match["attrs"])
        key = arg_attrs.get("key", "")
        arg_type = arg_attrs.get("type", "string")
        raw_value = arg_match["val"]
        if arg_type == "string":
            arguments[key] = raw_value
        else:
            try:
                arguments[key] = json.loads(raw_value)
            except json.JSONDecodeError:
                arguments[key] = raw_value
    if not tool_name:
        return None
    return ToolCall(
        type="function",
        function=FunctionCall(
            name=tool_name,
            arguments=json.dumps(arguments, ensure_ascii=False),
        ),
    )

_stream_tool_calls(text)

Stream calls from the tools channel without waiting for call close.

String values are raw XTML text, so they can be JSON-escaped and sent as they arrive. Other values are JSON-decoded and normalized like the non-streaming path, so they are sent once their argument closes.

Source code in vllm/tool_parsers/kimi_k3_tool_parser.py
def _stream_tool_calls(self, text: str) -> list[DeltaToolCall]:
    """Stream calls from the tools channel without waiting for call close.

    String values are raw XTML text, so they can be JSON-escaped and sent
    as they arrive. Other values are JSON-decoded and normalized like the
    non-streaming path, so they are sent once their argument closes.
    """
    deltas: list[DeltaToolCall] = []
    pos = self._stream_tool_idx
    if self._stream_tools_closed:
        return deltas
    m_tools_close = self._tools_close_re.search(text, pos, partial=True)
    tools_end = len(text) if m_tools_close is None else m_tools_close.start()
    text = text[:tools_end]
    while True:
        call = self._stream_call
        if call is None:
            m_call = self._call_open_re.search(text, pos, partial=True)
            if m_call is None:
                pos = len(text)
                break
            if m_call.partial:
                pos = m_call.start()
                break
            name = self._attrs(m_call["attrs"]).get("tool", "")
            index = self._sent_tool_call_count if name else None
            self._stream_call = _StreamingCall(index)
            pos = m_call.end()
            if index is not None:
                self._sent_tool_call_count += 1
                deltas.append(
                    DeltaToolCall(
                        index=index,
                        id=make_tool_call_id(),
                        type="function",
                        function=DeltaFunctionCall(
                            name=name, arguments="{"
                        ).model_dump(exclude_none=True),
                    )
                )
            continue

        if call.arg_type is None:
            m_arg = self._arg_open_re.search(text, pos, partial=True)
            m_close = self._call_close_re.search(text, pos, partial=True)
            complete = [
                match
                for match in (m_arg, m_close)
                if match is not None and not match.partial
            ]
            if not complete:
                pos = min(
                    (match.start() for match in (m_arg, m_close) if match),
                    default=len(text),
                )
                break
            match = min(complete, key=lambda item: item.start())
            pos = match.end()
            if match is m_close:
                self._append_arguments(deltas, call.index, "}")
                self._stream_call = None
                continue
            attrs = self._attrs(match["attrs"])
            call.arg_type = attrs.get("type", "string")
            call.value_start = call.value_sent = pos
            prefix = ", " if call.arg_count else ""
            prefix += json.dumps(attrs.get("key", ""), ensure_ascii=False) + ": "
            if call.arg_type == "string":
                prefix += '"'
                self._append_arguments(deltas, call.index, prefix)
                call.arg_count += 1
            else:
                call.arg_prefix = prefix
            continue

        m_value_close = self._arg_close_re.search(text, pos, partial=True)
        m_call_close = self._call_close_re.search(text, pos, partial=True)
        value_end = min(
            (
                match.start()
                for match in (m_value_close, m_call_close)
                if match is not None
            ),
            default=len(text),
        )
        if call.arg_type == "string":
            value = text[call.value_sent : value_end]
            self._append_arguments(
                deltas, call.index, json.dumps(value, ensure_ascii=False)[1:-1]
            )
            call.value_sent = value_end
        if (
            m_call_close is not None
            and not m_call_close.partial
            and m_call_close.start() == value_end
            and (
                m_value_close is None
                or m_value_close.partial
                or m_call_close.start() < m_value_close.start()
            )
        ):
            # The call closed before this argument closed. Typed values have
            # not been emitted yet, so drop them like the non-streaming path.
            # String text was already streamed, so close it as valid JSON.
            suffix = '"}' if call.arg_type == "string" else "}"
            self._append_arguments(deltas, call.index, suffix)
            self._stream_call = None
            pos = m_call_close.end()
            continue
        if m_value_close is None or m_value_close.partial:
            pos = value_end
            break
        if call.arg_type == "string":
            self._append_arguments(deltas, call.index, '"')
        else:
            raw_value = text[call.value_start : value_end]
            try:
                value = json.loads(raw_value)
            except json.JSONDecodeError:
                value = raw_value
            self._append_arguments(
                deltas,
                call.index,
                call.arg_prefix + json.dumps(value, ensure_ascii=False),
            )
            call.arg_count += 1
            call.arg_prefix = ""
        call.arg_type = None
        pos = m_value_close.end()

    if m_tools_close is not None and not m_tools_close.partial:
        call = self._stream_call
        if call is not None:
            # Tool calls cannot continue after the tools channel closes. Close
            # an already announced call so its streamed arguments stay valid.
            suffix = '"}' if call.arg_type == "string" else "}"
            self._append_arguments(deltas, call.index, suffix)
            self._stream_call = None
        self._stream_tools_closed = True
        pos = m_tools_close.end()
    self._stream_tool_idx = pos
    return deltas

_strip_response_content(text)

Strip XTML response/message markers from generated response text.

In chat serving, <|open|>response<|sep|> is often part of the prompt generation prefix, so the model output may only contain the body plus <|close|>response<|sep|>. Handle both that consumed-prefix shape and a complete <|open|>response<|sep|>... <|close|>response<|sep|> wrapper.

Source code in vllm/tool_parsers/kimi_k3_tool_parser.py
def _strip_response_content(self, text: str) -> str | None:
    """Strip XTML response/message markers from generated response text.

    In chat serving, `<|open|>response<|sep|>` is often part of the prompt
    generation prefix, so the model output may only contain the body plus
    `<|close|>response<|sep|>`. Handle both that consumed-prefix shape and a
    complete `<|open|>response<|sep|>... <|close|>response<|sep|>` wrapper.
    """
    m_open = self._response_open_re.search(text)
    if m_open is not None:
        m_close = self._response_close_re.search(text, m_open.end())
        if m_close is not None:
            text = text[m_open.end() : m_close.start()]
        else:
            text = text[m_open.end() :]
    else:
        text = self._response_close_re.sub("", text)
    text = self._message_close_re.sub("", text)
    return text or None