Skip to content

vllm.renderers.online_derenderer

Classes:

Functions:

OnlineDerenderer

Methods:

_decode_output(tokenizer, token_ids, finish_reason, stop_reason, request, seed_state, skip_special_tokens, spaces_between_special_tokens)

Decode a complete output into the text the engine returns.

Drops the stop token (_drop_stop_token), then cuts the text at the stop string that ended generation. That is the reported stop_reason when it is a string, or else the request's stop list when the host reported nothing. Like the engine, a stop string only counts when it ends past the first min_tokens tokens, and it overrides a stop token as the stop_reason.

Returns:

  • tuple[str, int | str | None] –

    The output text and the stop_reason.

_derender_chat_stream_parsed(parser_cls, model, generate_chunk, state, chat_request, prompt_tokens, prompt_token_ids)

Parser path for streaming chat derender: replay + parse_delta.

Parser internal state (buffered markup, reasoning/tool phase, etc.) cannot be serialized into DerenderStreamState, so each call builds a fresh parser and replays every prior output token through parse_delta (discarding the result) before processing this chunk's tokens for real.

Every chunk, replayed or live, goes through one parse_delta call with the tokens it arrived with (more than one under e.g. speculative decoding). Replay recovers those boundaries from state.output_chunk_lens, so the rebuilt parser state matches standard serving, which calls parse_delta once per engine step. Text comes from a fresh incremental detokenizer with special tokens preserved (see _decode_params), seeded from the prompt tail on every call since replay starts from scratch.

Logprobs need no replay: a generate chunk's logprobs cover exactly that chunk's tokens, so they are resolved once and attached to whatever delta the parser emits for the chunk, as the coupled chat endpoint does. Only the byte-fallback context crosses chunks, via state.logprob_context_token_ids. With include_reasoning=False logprobs are dropped on every chunk, again like the coupled endpoint.

_detokenize_delta(tokenizer, delta_token_ids, state, skip_special_tokens=True, spaces_between_special_tokens=True)

Incrementally detokenize delta_token_ids from prior stream state.

Resumes decoding from the offsets carried in state rather than replaying token history. state.prev_token_ids holds the trailing decode window (from prefix_offset onward) that detokenize_incrementally still needs to reproduce any partially read multi-byte character (tracked by read_offset). The delta tokens are fed straight onto it.

The window is bounded. detokenize_incrementally never reads before prefix_offset, so after each token we trim the window to that tail and rebase the offsets to it. State transport therefore stays O(window) per chunk instead of re-sending the full token history.

Parameters:

  • tokenizer

    (TokenizerLike) –

    The tokenizer to decode with.

  • delta_token_ids

    (list[int]) –

    New token IDs from this generate chunk.

  • state

    (DerenderStreamState) –

    Client carried detok state from the previous call.

  • skip_special_tokens

    (bool, default: True ) –

    Passed through to the tokenizer.

  • spaces_between_special_tokens

    (bool, default: True ) –

    Passed through to the tokenizer.

Returns:

  • str –

    (new_text, updated_state) — the delta text for this chunk and the

  • DerenderStreamState –

    state to pass to the next call.

_drop_stop_token(token_ids, finish_reason, stop_reason, request)

Leave out the token that stopped generation, as the engine's detokenizer does, unless include_stop_str_in_output is set.

A reported int stop_reason names that token. None is the primary EOS on current generate hosts, but older hosts never report it, so the last id is checked against the request's stop tokens and the model's EOS ids (unless ignore_eos) the way check_stop does. The check also guards against finish_reason defaulting to "stop" when the client sends neither.

Returns:

  • list[int] –

    The ids to decode and the stop_reason, set to the token id when

  • int | str | None –

    the check found a stop token other than the primary EOS.

_parse_and_assemble(tokenizer, text, token_ids, chat_request, chat_template_kwargs, prompt_token_ids, role, history_tool_call_count=None)

Parse decoded output text into an assistant ChatMessage.

Parameters:

  • tokenizer

    (TokenizerLike) –

    Tokenizer handed to the parser.

  • text

    (str) –

    Decoded output text to parse.

  • token_ids

    (Sequence[int]) –

    Output token IDs the text was decoded from.

  • chat_request

    (ChatCompletionRequest) –

    Request supplying tools, tool_choice and include_reasoning.

  • chat_template_kwargs

    (dict[str, Any]) –

    Already resolved template kwargs.

  • prompt_token_ids

    (list[int] | None) –

    Prompt token IDs, if known.

  • role

    (str) –

    Role of the returned message.

  • history_tool_call_count

    (int | None, default: None ) –

    Tool calls in the conversation, for requests that carry no messages. None derives it from chat_request.

Returns:

  • ChatMessage –

    The assembled message and the number of reasoning

  • int –

    tokens the parser counts in token_ids (0 without a reasoning

  • tuple[ChatMessage, int] –

    parser).

derender_chat(generate_response, chat_request=None, prompt_token_ids=None) async

Returns the choices, the resolved prompt_logprobs, and completion_tokens_details (reasoning tokens summed over the choices; None without a reasoning parser).

derender_chat_stream(model, generate_chunk, state=None, chat_request=None, prompt_tokens=None, prompt_token_ids=None) async

Process one GenerateStreamResponse chunk for streaming chat derender.

Unlike OpenAI's API, which always emits the role on the very first chunk, this emits it on the first chunk with a non empty choices list. A leading usage only chunk therefore defers the role to the following content chunk instead of sending an empty role only delta. With echo, the echoed text leads that chunk's content, where /v1/chat/completions sends it as its own chunk.

Parameters:

  • model

    (str) –

    Model name for the response object.

  • generate_chunk

    (GenerateTokensStreamResponse) –

    One SSE chunk from /inference/v1/generate.

  • state

    (DerenderStreamState | None, default: None ) –

    Client carried detok state (None for first call).

  • chat_request

    (ChatCompletionRequest | None, default: None ) –

    Original ChatCompletionRequest from /render. Required when a reasoning or tool parser is configured (validated by the caller — see ServingDerender) because plain detokenization would leak raw parser markup into content.

  • prompt_tokens

    (int | None, default: None ) –

    Prompt token count for the usage chunk.

  • prompt_token_ids

    (list[int] | None, default: None ) –

    Prompt token IDs. Required on the parser path (validated by the caller) and optional otherwise, falling back to generate_chunk.prompt_token_ids. See DerenderChatStreamRequest.prompt_token_ids.

Returns:

  • ChatCompletionStreamResponse –

    (chunk, updated_state) — the derendered SSE chunk and the state

  • DerenderStreamState –

    the client must pass to the next call.

derender_completion_stream(model, generate_chunk, state=None, prompt_tokens=None, completion_request=None, prompt_token_ids=None) async

Process one GenerateStreamResponse chunk for streaming completions.

Each call takes one SSE chunk from /inference/v1/generate plus the client carried stream_state and returns a CompletionStreamResponse chunk and the updated state.

The generate stream emits one choice per SSE event, so this method processes one output sequence at a time. For n > 1 the client maintains one DerenderStreamState per choice.index.

Parameters:

  • model

    (str) –

    Model name for the response object.

  • generate_chunk

    (GenerateTokensStreamResponse) –

    One SSE chunk from /inference/v1/generate.

  • state

    (DerenderStreamState | None, default: None ) –

    Client carried detok state (None → first call).

  • prompt_tokens

    (int | None, default: None ) –

    Prompt token count for usage (from the render step).

  • completion_request

    (CompletionRequest | None, default: None ) –

    Original CompletionRequest from /render; supplies skip_special_tokens.

  • prompt_token_ids

    (list[int] | None, default: None ) –

    Seeds the first chunk's decode. Falls back to generate_chunk.prompt_token_ids.

Returns:

  • tuple[CompletionStreamResponse, DerenderStreamState] –

    (chunk, updated_state) — the derendered chunk and updated state.

derender_text_choices(outputs, chat_request, history_tool_call_cnt, prompt_token_ids) async

Parse the engine's decoded output text into assistant messages.

Parameters:

  • outputs

    (Sequence[CompletionOutput]) –

    Final engine outputs, already detokenized.

  • chat_request

    (ChatCompletionRequest | None) –

    Chat request built from parse_context. With None or no parser on this server, the message content is the text.

  • history_tool_call_cnt

    (int) –

    Tool calls already in the conversation.

  • prompt_token_ids

    (list[int] | None) –

    Prompt token IDs, if known.

Returns:

  • list[tuple[ChatMessage, str]] –

    One message and chat finish_reason per output in order, and

  • CompletionTokenUsageInfo | None –

    completion_tokens_details (reasoning tokens summed over the

  • tuple[list[tuple[ChatMessage, str]], CompletionTokenUsageInfo | None] –

    outputs; None without a reasoning parser).

make_stream_processor(chat_request, history_tool_call_cnt)

Build the request-scoped processor for one streamed choice.

Parameters:

  • chat_request

    (ChatCompletionRequest | None) –

    Request from ParseContext.to_chat_request(). Unused when the server has no parser.

  • history_tool_call_cnt

    (int) –

    Tool calls already in the conversation, for deterministic tool call IDs.

Returns:

Raises:

  • ValueError –

    If the parser rejects the request.

  • VLLMValidationError –

    If the parser rejects the request.

stream_completion_tokens_details(processors, output_token_ids)

Count reasoning tokens over every streamed choice.

Parameters:

Returns:

  • CompletionTokenUsageInfo | None –

    Reasoning tokens summed over the choices, or None without a

  • CompletionTokenUsageInfo | None –

    reasoning parser.

_chat_top_logprobs_limit(chat_request)

The cut /v1/chat/completions applies (chat_top_logprobs_limit, the same helper its _get_top_logprobs uses). None keeps every candidate, which is also what happens without a chat_request or with one that does not ask for logprobs: it then says nothing about the cut, so the candidates generate returned are passed through.

_completion_top_logprobs_limit(completion_request)

The cut /v1/completions applies (completion_top_logprobs_limit, the same helper _create_completion_logprobs uses). None keeps every candidate, which is also what happens without a completion_request or with one that does not ask for logprobs (logprobs unset).

_convert_chat_logprobs_to_completion_logprobs(logprobs, generate_logprobs, initial_text_offset=0)

Convert ChatCompletionLogProbs (per-token objects) to CompletionLogProbs (parallel flat lists) as required by the /v1/completions response schema.

generate_logprobs is what logprobs was resolved from. A position with no candidates there had no logprobs in the engine output, which /v1/completions reports as None; every other position is a dict of the candidates the cut kept.

initial_text_offset keeps text_offset absolute across streaming chunks, mirroring the generate streaming path.

_correct_decoded_token(token_id, context_token_ids, tokenizer)

Use preceding tokens as context to fix U+FFFD from byte-fallback.

Mirrors LogprobsProcessor._correct_decoded_token in v1/engine/logprobs.py.

_decode_params(tokenizer, request, preserve_special=False)

Derive (skip_special_tokens, spaces_between_special_tokens) the way the engine does (IncrementalDetokenizer).

Parameters:

  • tokenizer

    (TokenizerLike) –

    Picks the engine's fast or slow detokenizer rules.

  • request

    (ChatCompletionRequest | CompletionRequest | None) –

    The original request, if the caller supplied one.

  • preserve_special

    (bool, default: False ) –

    Keep special tokens so a parser can see markers. The serving side does this via adjust_request, except for MistralTokenizer, which keeps the parser's markers when skipping.

_logprob_context_tail(context_token_ids, delta_token_ids)

Advance the carried logprob context by this chunk's sampled tokens.

_resolve_logprobs(logprobs, tokenizer, initial_context_token_ids=(), top_limit=None, return_tokens_as_token_ids=False)

Convert generate's integer-id logprobs to the OpenAI chat shape.

The generate server has no tokenizer, so token and bytes are filled here, with the same U+FFFD byte-fallback correction the coupled path applies (_correct_decoded_token, which needs the preceding sampled token ids as context). initial_context_token_ids seeds that context with sampled IDs from preceding chunks (streaming), so multi-byte characters split across chunk boundaries still resolve.

Generate returns every candidate the engine produced for a position (the sampled token first, then the top k). top_limit applies the target endpoint's cut before decoding, so each derender endpoint returns what its coupled counterpart would; None keeps all of them.

_resolve_prompt_logprobs(prompt_logprobs, tokenizer)

Fill missing decoded_token values in prompt logprobs.

A --tokens-only generate server has no tokenizer, so it returns decoded_token=None. Mirrors LogprobsProcessor._update_prompt_logprobs in v1/engine/logprobs.py: decode each token id, then fix U+FFFD using the preceding prompt tokens (the first entry of each earlier position).

_seed_stream_state(tokenizer, prompt_token_ids, skip_special_tokens)

Build the initial decode state from the prompt tail, the same way the engine primes its incremental detokenizer. Without it, Metaspace tokenizers drop the first output token's leading space.

Returns an empty state when prompt_token_ids is empty or omitted.

_stop_strings(request)

The request's stop as a list, like SamplingParams normalizes it.

resolve_prompt_tokens(prompt_tokens, usage)

The request's prompt_tokens if set (0 included), else the generate usage.prompt_tokens, else 0 when the generate response has no usage.