Skip to content

vllm.tool_parsers.apertus_tool_parser

Tool call parser for Apertus models.

Extracts tool calls from the format: <|tools_prefix|>[{"function_name": {"arg1": "value1", ...}}, ...]<|tools_suffix|>

Used when --enable-auto-tool-choice --tool-call-parser apertus are set.

Classes:

ApertusToolParser

Bases: ToolParser

Tool call parser for Apertus models.

Handles the extraction of tool calls from text in both non-streaming (complete string) and streaming (chunked token) environments.

The expected Apertus function call format is a JSON array of single-key dictionaries sandwiched between special tokens: <|tools_prefix|>[{"function_name": {"arg1": "value1"}}, ...]<|tools_suffix|>

Examples:

>>> tokenizer = ...  # Mock tokenizer
>>> parser = ApertusToolParser(tokenizer)
>>> output = 'I will check. <|tools_prefix|>[{"get_weather": '            '{"city": "Paris"}}]<|tools_suffix|>'
>>> request = ChatCompletionRequest(...)
>>> info = parser.extract_tool_calls(output, request)
>>> info.content
"I will check."
>>> info.tool_calls[0].function.name
"get_weather"
>>> info.tool_calls[0].function.arguments
'{"city": "Paris"}'

Methods:

__init__(tokenizer, tools=None)

Initializes the ApertusToolParser.

Parameters:

  • tokenizer

    (TokenizerLike) –

    The model's tokenizer. Must be provided to interact with special tokens.

  • tools

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

    Optional list of tools available for the current request.

Raises:

  • ValueError –

    If the model_tokenizer is not successfully passed to the base class.

_buffer_delta_text(delta_text)

Buffers incoming delta chunks to prevent fragmentation of multi-token special tags.

If a chunk ends with a partial match of <|tools_prefix|> or <|tools_suffix|>, it holds that part back until the next chunk clarifies if it's the actual tag or just normal text.

Parameters:

  • delta_text

    (str) –

    The newly generated text chunk

Returns:

  • str –

    The safe, verified text chunk free of partial tag collisions.

Examples:

>>> parser = ApertusToolParser(...)
>>> parser._buffer_delta_text("Let me check <|tool"             "Let me check "  # "<|tool" is buffered internally
>>> parser._buffer_delta_text("s_prefix|>"             "<|tools_prefix|>"  # Buffer released on completion

_emit_tool_name(parsed, index, tool_calls)

Extracts and emits the function name mapped to a new tool call ID.

Parameters:

  • parsed

    (list) –

    The partially parsed JSON list containing tool dictionaries.

  • index

    (int) –

    The active index within the JSON list.

  • tool_calls

    (list[DeltaToolCall]) –

    The running list of delta chunks to mutate.

Examples:

Appends DeltaToolCall(index=0, function=DeltaFunctionCall(name="get_weather", ...)) to the tool_calls list and marks the name as sent.

_extract_streaming(current_text, delta_text)

Core streaming logic. Separates visible chat text from JSON blocks and computes diffs.

Parameters:

  • current_text

    (str) –

    The full generated output string so far.

  • delta_text

    (str) –

    The latest chunk of text added.

Returns:

  • DeltaMessage | None –

    A DeltaMessage containing the content delta and/or tool_calls delta.

_get_tool_diff(parsed, index, is_final)

Calculates the exact string difference to safely append new tool parameters.

This ensures characters like {, }, and " don't jump around unevenly in the UI frontend while streaming incomplete JSON arguments.

Parameters:

  • parsed

    (list) –

    The latest list of parsed JSON objects.

  • index

    (int) –

    The active tool's array index.

  • is_final

    (bool) –

    Whether to emit trailing structural brackets (True if block is done).

Returns:

  • DeltaToolCall | None –

    A DeltaToolCall mapping to the arguments diff, or None if no text was appended.

Examples:

>>> # Previous streamed state: '{"city": "Pari'
>>> # Current full parse state: '{"city": "Paris"}'
>>> # Returns diff (closing bracket suppressed until final):
>>> parser._get_tool_diff(parsed, index=0, is_final=False)
DeltaToolCall(index=0, function=DeltaFunctionCall(arguments='s'))

_parse_and_diff_json(json_str, is_final)

Parses an isolated, potentially incomplete streaming JSON array and returns newly accumulated tool call diffs.

Parameters:

  • json_str

    (str) –

    The extracted JSON array string so far (e.g. [{"weather": {"city": "Par"}]).

  • is_final

    (bool) –

    True if the tool block has received its closing<|tools_suffix|>

Returns:

  • list[DeltaToolCall] –

    A list of DeltaToolCall

  • list[DeltaToolCall] –

    items representing string diffs in function arguments

  • list[DeltaToolCall] –

    to stream back to the client.

_reset_streaming_state()

Resets all streaming state variables for a new completion request.

This clears the delta text buffer and resets the pointers used to track the currently streaming tool index and arguments. Called implicitly during initialization and should be called between separate streams.

adjust_request(request)

Adjusts the generation request to ensure special tool tokens are not skipped.

Forces skip_special_tokens=False if tools are actively being evaluated, ensuring the tools special tokens are surfaced to the engine for parsing.

Parameters:

Returns:

extract_tool_calls(model_output, request)

Extract tool calls from a complete model response (non-streaming).

Parameters:

  • model_output

    (str) –

    The full completion string generated by the model.

  • request

    (ChatCompletionRequest) –

    The current chat completion request context containing tool schemas.

Returns:

  • ExtractedToolCallInformation –

    An ExtractedToolCallInformation object containing normal text content

  • ExtractedToolCallInformation –

    and a list of fully formatted ToolCall objects.

Examples:

>>> output = 'Let me see. <|tools_prefix|>[{"get_weather":'                 '{"loc": "Paris"}}]<|tools_suffix|>'
>>> info = parser.extract_tool_calls(output, request)
>>> info.tools_called
True
>>> info.content
'Let me see.'
>>> info.tool_calls[0].function.name
'get_weather'

extract_tool_calls_streaming(previous_text, current_text, delta_text, previous_token_ids, current_token_ids, delta_token_ids, request)

Handles streaming chunks.

Parameters:

  • previous_text

    (str) –

    The complete model text generated prior to this chunk.

  • current_text

    (str) –

    The complete model text including this chunk.

  • delta_text

    (str) –

    The incremental text addition.

  • previous_token_ids

    (Sequence[int]) –

    Tokens generated prior to this chunk.

  • current_token_ids

    (Sequence[int]) –

    Total tokens generated.

  • delta_token_ids

    (Sequence[int]) –

    Incremental token additions.

  • request

    (ChatCompletionRequest) –

    The chat completion request.

Returns:

  • DeltaMessage | None –

    A DeltaMessage with updated content or tool argument diffs, or None if

  • DeltaMessage | None –

    the chunk shouldn't emit visible changes yet (e.g. it was purely buffered).

Examples:

>>> prev = '<|tools_prefix|>[{"get_weather": {"loc'
>>> cur = '<|tools_prefix|>[{"get_weather": {"location": "Paris"}}'
>>> delta = 'ation": "Paris"}}'
>>> msg = parser.extract_tool_calls_streaming(
...     prev, cur, delta, ..., request
... )
>>> msg.tool_calls[0].function.arguments
'ation": "Paris"}'