Skip to content

vllm.parser.chat_parsing

Response parsing: convert model-emitted text into the assistant-message dict used by chat templates, driven by a declarative response_template spec.

Modules:

Classes:

  • ResponseParser –

    This class implements a streaming parser with a response_template. If you don't need streaming and

Functions:

  • parse_response –

    The main function for response parsing when you don't want streaming. Takes generated output

ResponseParser

This class implements a streaming parser with a response_template. If you don't need streaming and just want to parse a complete message, use the parse_response function above. Streaming parsing emits events indicating when regions (message fields) are opened and closed, with the model writing to the region that is currently open.

Usage

parser = ResponseParser(response_template, prefix=chat_prompt) for event in parser.initial_events: handle(event) for chunk in model_text_stream: for event in parser.feed(chunk): handle(event) message, final_events = parser.finalize() for event in final_events: handle(event)

Pass OpenAI-style tools= dictionaries to cast tool-call arguments using the calling tool's JSON schema as each region closes.

Events can be "region_open", "region_chunk", "region_close", or "region_malformed". Open, close and malformed events carry start and end, the span of input_text the event consumed: its opening or closing delimiter, empty for implicit boundaries. Explicit opens also carry the opener's named captures. A region whose value fails to parse ends with "region_malformed" instead of "region_close", carrying the error, and parsing continues after it.

ResponseParser requires the chat prefix (i.e. the chat history, the prefill before the current generation). This is because chat templates or assistant prefills can sometimes write part of the message, and if we only see the model output, and not the template, then we can't reliably parse the message in those cases. Any events produced while consuming the prefix are exposed as initial_events, so renderers can show prefill regions before the model writes anything; closed prefill regions also land in the output dict.

Methods:

  • feed –

    Feeds more text/tokens from the model output into the tokenizer, and returns any events that result

  • finalize –

    Close the stream and return the final message dict together with

Attributes:

  • input_text (str) –

    Raw parser input after start-anchor truncation. Before the first feed(), this is

input_text property

Raw parser input after start-anchor truncation. Before the first feed(), this is exactly the truncated prefix, so its length marks where generated text begins.

_accumulate(events, text)

Route text into the currently active region. When the current region is the null sink (no implicit declared, no explicit open), we silently discard. Every routed chunk emits a region_chunk event so consumers can render live; dirty=True flags chunks from structured parsers (json, xml-inline, kv-lines) whose raw bytes will only be parsed into the final value on close.

_can_grow(kind, field, m)

Whether a complete match ending at the current buffer edge could still change as more input arrives -- in which case we defer rather than commit. A match ending before the edge has already seen its terminating byte and is final. At the edge: zero-width matches ($ / \Z) are only real at true EOS; a fully-present literal that no other literal in its set extends cannot grow (the fast path that keeps literal delimiters zero-latency); anything else (regex delimiters, prefix-overlapping literal lists) might.

_close_current(events, close_start, close_end)

Close the current region and reset to the implicit/null region. Skipped (aside from the reset) when the current region never opened -- avoids vacuous open/close pairs at every explicit boundary.

_consume_prefix(prefix)

Loads the prefix (the chat prefill sent to the model), right-truncates it to the start of the assistant message (as determined by start_anchor) and then runs the remainder through the parser. Events produced while processing the prefix are stashed on initial_events so callers can replay them into a renderer before feeding model output.

Think of this as the "get the parser up to speed on the story so far" method.

_scan(watch, eos)

Single pass over the watched delimiters, using the regex module's partial matching to decide -- per delimiter -- whether it can be committed now or must be held. Returns (best, hold_start):

  • best is the earliest-starting delimiter we can safely commit now (longest on ties, opens before closes), or None.
  • hold_start is the leftmost buffer position occupied by a still-pending match: a partial (incomplete) delimiter, or a complete one ending at the buffer edge that more input could still grow. Bytes before it are safe to emit; bytes from it onward must be held. It stays len(self._buffer) when nothing is pending, letting the caller flush the whole buffer.

A complete match is committable only if it starts strictly before hold_start -- otherwise an earlier (or co-located) pending delimiter could turn out to be the real one. At EOS nothing can grow, so partial matching is skipped and every complete match is committable.

(The regex module always reports the empty string as a live prefix, so a partial search with no real match returns a zero-width match at the buffer end; that lands in the pending branch with start == len(self._buffer), a no-op for hold_start.)

_watchlist()

Patterns we care about right now: the close of the currently-open explicit region, or -- if we're in the implicit/null region -- every explicit open plus the implicit's own close (if any).

feed(text)

Feeds more text/tokens from the model output into the tokenizer, and returns any events that result (regions entered or left). This is the method you want to call after each generation step.

finalize()

Close the stream and return the final message dict together with any finalization events. This is necessary because some regions may only end at the end of the sequence, so you won't see the event telling you they're ready until the sequence is finalized.

parse_response(text, response_template, *, prefix=None, tools=None)

The main function for response parsing when you don't want streaming. Takes generated output and the prompt prefix and parses them without streaming any events, then returns the parsed message.

Pass OpenAI-style tools dictionaries to cast tool-call arguments using the calling tool's JSON schema.