Skip to content

vllm.tool_parsers.hy_v4_tool_parser

Classes:

  • ExtractResult –

    Return of extract_tool_calls (non-streaming).

  • HYV4ToolExtractor –

    Pure tool-call parsing logic for HYV4. Returns plain dicts; no vLLM types.

  • HYV4ToolParser –

    vLLM adapter around HYV4ToolExtractor.

  • StreamDelta –

    Return of extract_tool_calls_streaming.

  • StreamToolCall –

    One streaming tool-call delta.

  • ToolCallDict –

    One extracted tool call. arguments is a JSON-encoded string.

  • ToolSchema –

    A tool as seen by this parser (built by the wrapper from request.tools).

Functions:

ExtractResult

Bases: TypedDict

Return of extract_tool_calls (non-streaming).

HYV4ToolExtractor

Pure tool-call parsing logic for HYV4. Returns plain dicts; no vLLM types.

Holds only parser state: the structural token strings/ids, the compiled regexes, and the streaming incremental state. Stateless argument parsing is delegated to the module-level utilities above.

Streaming has two entry paths sharing one incremental argument parser, selected by the guided flag of extract_tool_calls_streaming: normal / auto tool choice detects markers on atomic token ids so ordinary < in content is never withheld, while structural-tag guided decoding detects them on the string level because the grammar may split a marker across sub-word tokens.

Methods:

_extract_streaming_incremental(name_new, pending_name, tools)

Incremental phase-2: scan tags in buffer, emit JSON diffs.

Strategy: - Track completed args and emit each one as a JSON fragment. - For string-typed args, stream the value character-by-character. - Withhold the closing } until </tool_call> is seen.

We build JSON manually via fragments rather than using json.dumps with a cursor, because json.dumps of partial-vs-full string values produces incompatible prefixes (e.g. ""} vs "Hello"}).

_make_args_delta(argument_diff)

Build an args-only streaming delta (no id/type -> new=False).

_reset_streaming_tool_state()

Reset the streaming state for a single tool call.

extract_tool_calls_streaming(previous_text, current_text, delta_text, previous_token_ids, current_token_ids, delta_token_ids, tools, *, guided=False)

Consume one engine delta and emit content / tool-call deltas.

Two entry paths share the same incremental argument parser: - guided=False (normal / auto tool choice): the structural markers arrive as atomic tokenizer tokens, so detection is done on token ids and ordinary < in model content is never withheld. - guided=True (structural-tag constrained decoding): the grammar only constrains strings, so <tool_calls...> may be split across sub-word tokens and must be detected on the string level.

Parameters:

  • previous_text

    (str) –

    Text decoded before this delta.

  • current_text

    (str) –

    Full text decoded so far.

  • delta_text

    (str) –

    Text decoded in this delta.

  • previous_token_ids

    (Sequence[int]) –

    Token ids before this delta.

  • current_token_ids

    (Sequence[int]) –

    Token ids decoded so far.

  • delta_token_ids

    (Sequence[int]) –

    Token ids in this delta.

  • tools

    (list[ToolSchema] | None) –

    Plain tool schemas used for argument typing.

  • guided

    (bool, default: False ) –

    Whether guided decoding may split markers into sub-word tokens.

Returns:

  • StreamDelta | None –

    A streaming delta carrying content and/or the tool calls drained

  • StreamDelta | None –

    from the buffer, or None when nothing can be emitted yet.

HYV4ToolParser

Bases: ToolParser

vLLM adapter around HYV4ToolExtractor.

Converts the extractor's plain dicts to vLLM protocol objects, mints tool-call ids, and mirrors prev_tool_call_arr / streamed_args_for_tool so the serving layer sees live state.

Methods:

_is_guided(request) staticmethod

Whether a structural tag constrains this request's decoding.

get_structural_tag only applies to required / named tool choice and the serving layer records the result on the request. A structural tag constrains strings rather than token ids, so the <tool_calls> marker can arrive split across sub-word tokens and must be detected on the string level.

Parameters:

Returns:

  • bool –

    True when the streaming parser must use the string-marker path.

get_structural_tag(request, *, reasoning=False, strict_level=ToolStrictLevel.AUTO)

Build a structural tag matching HYV4's tool tokens.

Overridden only to pass the per-checkpoint token_suffix through to the builder; everything else follows the base implementation.

Named (forced) tool choice is constrained with the same structural tag: because supports_required_and_named is False, required and named requests are parsed by the HYV4 extractor, which only recognizes the HYV4 structural tokens -- the default JSON guided-decoding path would make the model emit JSON the extractor silently drops.

Parameters:

Returns:

  • StructuralTag | None –

    The structural tag, or None when structural tagging does not apply.

StreamDelta

Bases: TypedDict

Return of extract_tool_calls_streaming.

A single engine delta can carry content plus every tool call that was drained from the buffer (batched decode), so tool_calls is not limited to one entry.

StreamToolCall

Bases: TypedDict

One streaming tool-call delta.

new is True only on the chunk that first emits this tool's name -- the wrapper mints an id + sets type on that chunk only. arguments is the incremental JSON diff (or None).

ToolCallDict

Bases: TypedDict

One extracted tool call. arguments is a JSON-encoded string.

ToolSchema

Bases: TypedDict

A tool as seen by this parser (built by the wrapper from request.tools).

_allows_null(arg_schema)

Return whether the property schema admits a null value.

_deserialize(value)

Deserialize a string value using json.loads then ast.literal_eval.

_find_schema_anchor(root_schema, anchor)

Find a local JSON Schema anchor with bounded traversal.

_get_arg_schema(function_name, arg_key, tools)

Look up an argument and resolve its local schema type references.

_get_schema_options(arg_schema)

Normalize any property schema into a list of sub-schemas. - has type (single type) → return [arg_schema] - anyOf / oneOf → recursively expand union branches - fallback → [{"type": "string"}]

Note: single type has the highest priority.

_get_types(arg_schema)

Extract normalized, non-null type set from a property schema.

_is_only_string_type(function_name, arg_key, tools)

Stream partial values only for non-nullable pure strings.

A quoted prefix cannot grow into an unquoted null, array, or object.

_is_ref_type(schema)

Return whether a schema expresses its type only through $ref.

_normalize_type(raw_type)

Map non-standard type aliases to JSON Schema standard names.

First performs exact lookup in _TYPE_ALIASES. On miss, falls back to prefix-based matching using startswith() - int/uint/long/short/unsigned → "integer" - num/float* → "number"

_parse_value(value, function_name, arg_key, tools)

Unified argument value parser with anyOf/oneOf support.

Fallthrough chain

null → bool → int → number(wildcard_number) → json.loads for array/object → string → _deserialize

_resolve_json_pointer(root_schema, pointer)

Resolve a local JSON Pointer against the parameter schema.

_resolve_local_schema_ref(root_schema, ref)

Resolve a same-document pointer, root reference, or anchor.

_resolve_ref_type(schema, root_schema, seen_refs=frozenset(), ref_hops=0)

Resolve a reference to type information, without mutating the schema.

_resolve_union_ref_types(schema, root_schema, seen_refs=frozenset(), ref_hops=0)

Resolve reference-only branches of anyOf and oneOf.

_tools_to_plain(tools)

Convert tool-schema objects into plain dicts for the extractor.

_try_parse_bool(value)

Try to parse a string as bool; return None on failure.

_try_parse_int(value)

Try to parse a string as int; return None on failure.

_try_parse_wildcard_number(value)

Try to parse a string as a number (int or float).

Decision rule: if the string contains '.' or 'e'/'E' (scientific notation), parse as float; otherwise parse as int.

Examples: "5" → 5, "5.0" → 5.0, "1e3" → 1000.0, "-3" → -3. Return None on failure.

detect_token_suffix(tokenizer)

Detect the per-checkpoint suffix used by Hunyuan structural tokens.

Parameters:

  • tokenizer

    (TokenizerLike) –

    Tokenizer of the served checkpoint.

Returns:

  • str –

    The suffix including its leading colon (e.g. ":6124c78e"), or ""

  • str –

    when the checkpoint uses unsuffixed tokens.

Raises:

  • RuntimeError –

    The tokenizer declares the structural tokens through model_specific_special_tokens, which transformers 5 no longer round-trips.