Skip to content

vllm.parser.engine.incremental_lexer

Incremental text lexer that converts text chunks into terminal tokens, with prefix-match buffering for ambiguous boundaries.

Classes:

  • IncrementalLexer –

    Converts streaming text into terminal tokens.

  • LexerShape –

    Immutable pre-computed data derived from terminal definitions.

IncrementalLexer

Converts streaming text into terminal tokens.

The key feature is prefix-match buffering: when the text in the buffer could be the start of a multi-character terminal (e.g. "<tool_" that could become "<tool_call>"), the lexer holds the text rather than emitting it. When the next chunk arrives, it either completes the terminal or flushes the buffered text as content.

Terminals are tried in priority order (literals first, then by descending priority, then by pattern length).

Source code in vllm/parser/engine/incremental_lexer.py
class IncrementalLexer:
    """Converts streaming text into terminal tokens.

    The key feature is **prefix-match buffering**: when the text in the
    buffer could be the start of a multi-character terminal (e.g.
    `"<tool_"` that could become `"<tool_call>"`), the lexer holds
    the text rather than emitting it.  When the next chunk arrives, it
    either completes the terminal or flushes the buffered text as
    content.

    Terminals are tried in priority order (literals first, then by
    descending priority, then by pattern length).
    """

    def __init__(
        self,
        terminals: list[TerminalDef] | LexerShape,
        content_terminal: str = CONTENT_TERMINAL,
    ) -> None:
        if isinstance(terminals, LexerShape):
            shape = terminals
        else:
            shape = LexerShape(terminals)
        self._shape = shape
        self.terminals = shape.terminals
        self.content_terminal = content_terminal
        self.buffer = ""
        self._token_counts: list[int] = []

        self._literal_strings = shape.literal_strings
        self._max_literal_len = shape.max_literal_len
        self._literal_first_chars = shape.literal_first_chars
        self._has_only_literals = shape.has_only_literals
        self._prefix_set = shape.prefix_set
        self._literals_by_first = shape.literals_by_first

    def reset(self) -> None:
        self.buffer = ""
        self._token_counts.clear()

    def feed(
        self,
        text: str,
        token_texts: tuple[str, ...] = (),
        token_count: int = 0,
    ) -> list[LexToken]:
        char_token_counts = self._char_token_counts(text, token_texts, token_count)
        if not self.buffer and self._has_only_literals and self._literal_first_chars:
            for ch in text:
                if ch in self._literal_first_chars:
                    break
            else:
                return [LexToken(self.content_terminal, text, sum(char_token_counts))]
        self.buffer += text
        self._token_counts.extend(char_token_counts)
        return self._drain()

    def flush(self) -> list[LexToken]:
        tokens: list[LexToken] = []
        if self.buffer:
            tokens.extend(self._drain(final=True))
        if self.buffer:
            tokens.append(
                LexToken(self.content_terminal, self.buffer, sum(self._token_counts))
            )
            self.buffer = ""
            self._token_counts.clear()
        return tokens

    @staticmethod
    def _char_token_counts(
        text: str,
        token_texts: tuple[str, ...],
        token_count: int,
    ) -> list[int]:
        counts = [0] * len(text)
        if not text:
            return counts
        if token_texts:
            pos = 0
            assigned = 0
            for token_text in token_texts:
                if not token_text:
                    continue
                found = text.find(token_text, pos)
                if found < 0:
                    continue
                counts[found] += 1
                assigned += 1
                pos = found + len(token_text)
            missing = token_count - assigned
            if missing > 0:
                counts[0] += missing
        elif token_count:
            counts[0] = token_count
        return counts

    def _drain(self, *, final: bool = False) -> list[LexToken]:
        # Walk an index through the buffer and trim it once at the end, so
        # draining a long buffer costs time linear in its length.
        tokens: list[LexToken] = []
        first_chars = self._literal_first_chars
        content_terminal = self.content_terminal
        has_only_literals = self._has_only_literals
        literals_by_first = self._literals_by_first
        prefix_set = self._prefix_set
        max_literal_len = self._max_literal_len
        buf = self.buffer
        counts = self._token_counts
        n = len(buf)
        pos = 0

        def emit(terminal: str, end: int, value: str | None = None) -> None:
            nonlocal pos
            tokens.append(
                LexToken(
                    terminal,
                    buf[pos:end] if value is None else value,
                    sum(counts[pos:end]),
                )
            )
            pos = end

        while pos < n:
            if has_only_literals and first_chars:
                for i in range(pos, n):
                    if buf[i] in first_chars:
                        break
                else:
                    emit(content_terminal, n)
                    break

            best_match: tuple[str, str, int] | None = None

            first = buf[pos]
            for lit, name in literals_by_first.get(first, ()):
                if buf.startswith(lit, pos) and (
                    best_match is None or len(lit) > best_match[2]
                ):
                    best_match = (name, lit, len(lit))

            # If the rest of the buffer is both a complete literal and the
            # prefix of a longer literal, wait for the next chunk. For example,
            # "<invoke name=" should not be emitted before the next chunk
            # proves whether this is the quoted form '<invoke name="'.
            rest = buf[pos:] if n - pos < max_literal_len else None
            if rest is not None and rest in prefix_set and not final:
                if best_match is not None:
                    longer_match = False
                    for lit, _ in literals_by_first.get(first, ()):
                        if len(lit) > best_match[2] and lit.startswith(rest):
                            longer_match = True
                            break
                    if not longer_match:
                        emit(best_match[0], pos + best_match[2], best_match[1])
                        continue
                    break
                else:
                    break

            if best_match is not None:
                emit(best_match[0], pos + best_match[2], best_match[1])
            else:
                emit(content_terminal, self._find_content_boundary(buf, pos))

        self.buffer = buf[pos:]
        del counts[:pos]
        return tokens

    def _find_content_boundary(self, buf: str, start: int) -> int:
        n = len(buf)
        first_chars = self._literal_first_chars
        for i in range(start + 1, n):
            if buf[i] not in first_chars:
                continue
            remaining = n - i
            for lit, _ in self._literal_strings:
                check_len = min(remaining, len(lit))
                if buf[i : i + check_len] == lit[:check_len]:
                    return i
        return n

LexerShape

Immutable pre-computed data derived from terminal definitions.

Created once per ParserEngineConfig and shared across all IncrementalLexer instances that use the same config.

Source code in vllm/parser/engine/incremental_lexer.py
class LexerShape:
    """Immutable pre-computed data derived from terminal definitions.

    Created once per `ParserEngineConfig` and shared across all
    `IncrementalLexer` instances that use the same config.
    """

    __slots__ = (
        "terminals",
        "literal_strings",
        "max_literal_len",
        "literal_first_chars",
        "has_only_literals",
        "prefix_set",
        "literals_by_first",
    )

    def __init__(self, terminals: list[TerminalDef]) -> None:
        self.terminals = sorted(
            terminals,
            key=lambda t: (not t.is_literal, -len(t.pattern.pattern)),
        )
        literal_strings: list[tuple[str, str]] = []
        for t in self.terminals:
            if t.is_literal:
                literal_strings.append((t.literal, t.name))

        self.literal_strings = literal_strings
        max_len = 0
        for lit, _ in literal_strings:
            if len(lit) > max_len:
                max_len = len(lit)
        self.max_literal_len = max_len
        self.literal_first_chars = frozenset(
            lit[0] for lit, _ in literal_strings if lit
        )
        self.has_only_literals = all(t.is_literal for t in terminals)

        prefix_set: set[str] = set()
        for lit, _ in literal_strings:
            for i in range(1, len(lit)):
                prefix_set.add(lit[:i])
        self.prefix_set = frozenset(prefix_set)

        by_first: dict[str, list[tuple[str, str]]] = {}
        for lit, name in literal_strings:
            if lit:
                by_first.setdefault(lit[0], []).append((lit, name))
        self.literals_by_first = by_first