Skip to content

vllm.tokenizers.deepseek_v41

Functions:

_add_updated_tool_schemas(conversation, tools)

Like deepseek-recipe, follow each user turn whose tool results reference tools with a system turn listing those tools' schemas, in reference order.

Source code in vllm/tokenizers/deepseek_v41.py
def _add_updated_tool_schemas(
    conversation: list[dict[str, Any]], tools: list[dict[str, Any]] | None
) -> list[dict[str, Any]]:
    """Like deepseek-recipe, follow each user turn whose tool results reference
    tools with a system turn listing those tools' schemas, in reference order."""
    tools_by_name = {tool["function"]["name"]: tool for tool in tools or []}
    result: list[dict[str, Any]] = []
    referenced: list[dict[str, Any]] = []
    for message, next_message in zip(conversation, [*conversation[1:], {}]):
        result.append(message)
        names = message.pop("_tool_references", [])
        # Without tools (e.g. tool_choice "none"), references stay unlisted.
        for name in names if tools else []:
            if name not in tools_by_name:
                raise ValueError(f"tool_reference {name!r} not found in tools")
            referenced.append(_tool_schema(tools_by_name[name]))
        if referenced and next_message.get("role") not in ("user", "tool"):
            result.append(
                {"role": "system", "content": "", "updated_tools": referenced}
            )
            referenced = []
    return result

get_deepseek_v41_tokenizer(tokenizer)

Wrap an HF tokenizer with the V4.1 prompt encoder.

Source code in vllm/tokenizers/deepseek_v41.py
def get_deepseek_v41_tokenizer(tokenizer: HfTokenizer) -> HfTokenizer:
    """Wrap an HF tokenizer with the V4.1 prompt encoder."""
    wrapped = copy.copy(tokenizer)
    added_vocab = tokenizer.get_added_vocab()

    class _DeepseekV41Tokenizer(tokenizer.__class__):  # type: ignore
        def apply_chat_template(
            self,
            messages: list[ChatCompletionMessageParam],
            tools: list[dict[str, Any]] | None = None,
            image_order: list[int] | None = None,
            **kwargs,
        ) -> str | list[int]:
            # The generic renderer's conversation has already flattened text
            # parts with '\n'. V4.1 encodes the original messages with '\n\n'.
            conversation = _normalize_messages(messages)
            conversation = _add_updated_tool_schemas(conversation, tools)
            # As in deepseek-recipe, deferred tools load through tool search.
            listed = [_tool_schema(t) for t in tools or [] if not _is_deferred(t)]
            if tools and not listed:
                raise ValueError(
                    "At least one tool must have defer_loading=false; "
                    "all tools cannot be deferred."
                )
            if listed:
                system = next(
                    (
                        m
                        for m in conversation
                        if m["role"] == "system" and "updated_tools" not in m
                    ),
                    None,
                )
                if system is None:
                    system = {"role": "system", "content": ""}
                    conversation.insert(0, system)
                system["tools"] = listed

            thinking = bool(kwargs.get("thinking") or kwargs.get("enable_thinking"))
            if "thinking" not in kwargs and "enable_thinking" not in kwargs:
                thinking = True
            effort = kwargs.get("reasoning_effort")
            if effort == "none":
                thinking = False
                effort = None
            if effort is None:
                effort = "high"
            if not (
                (type(effort) is int and 1 <= effort <= 100)
                or (isinstance(effort, str) and effort in REASONING_EFFORT_MAPPINGS)
            ):
                raise ValueError(
                    "DeepSeek V4.1 reasoning_effort must be low, high, xhigh, max, "
                    "or an integer within [1, 100] in chat_template_kwargs"
                )

            prompt = encode_messages(
                conversation,
                thinking_mode="thinking" if thinking else "chat",
                drop_thinking=kwargs.get("drop_thinking", True),
                reasoning_effort=effort,
                image_order=image_order,
                add_generation_prompt=kwargs.get("add_generation_prompt", True),
                continue_final_message=kwargs.get("continue_final_message", False),
            )
            if kwargs.get("tokenize", True):
                tokenizer_kwargs = {
                    key: kwargs[key]
                    for key in ("truncation", "max_length")
                    if key in kwargs
                }
                return self.encode(prompt, add_special_tokens=False, **tokenizer_kwargs)
            return prompt

        def num_special_tokens_to_add(self) -> int:
            return len(self.encode(""))

        def get_added_vocab(self) -> dict[str, int]:
            return added_vocab.copy()

        def __reduce__(self):
            return get_deepseek_v41_tokenizer, (tokenizer,)

    _DeepseekV41Tokenizer.__name__ = f"DSV41{tokenizer.__class__.__name__}"
    wrapped.__class__ = _DeepseekV41Tokenizer
    return wrapped