BerriAI/litellm · error · ValueError

Unexpected key ; expected 'tool_calls' or 'function_call

Error message

Unexpected key {key!r}; expected 'tool_calls' or 'function_call'

What it means

Token counting dispatcher guard: _count_function_call_tokens was called with a key other than 'tool_calls' or 'function_call', meaning the caller routed an unrecognized message field into tool-call counting — an internal dispatch contract violation.

Solutions

  1. Remove the unexpected key; only 'tool_calls' or 'function_call' are expected there.
  2. Check the message dict for misspelled keys.
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at litellm/litellm_core_utils/token_counter.py:431 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/f573ac46f5351da0. Report an issue: GitHub.

Appendix: source

Thrown at litellm/litellm_core_utils/token_counter.py:431

    `function_call` dict. Only the `arguments` string is counted (matching the
    existing tool_calls behavior); names are accounted for elsewhere via the
    tool/function definitions and `tool_choice`.
    """
    if key == "tool_calls":
        if not isinstance(value, list):
            raise ValueError(f"Unsupported type {type(value)} for key tool_calls in message {message}")
        total = 0
        for tool_call in value:
            if "function" not in tool_call:
                raise ValueError(f"Unsupported tool call {tool_call} must contain a function key")
            function_arguments = tool_call["function"].get("arguments", "")
            total += count_function(str(function_arguments))
        return total
    if key == "function_call":
        if not isinstance(value, Mapping):
            raise ValueError(f"Unsupported type {type(value)} for key function_call in message {message}")
        return count_function(str(value.get("arguments", "")))
    raise ValueError(f"Unexpected key {key!r}; expected 'tool_calls' or 'function_call'")


def _count_messages(
    params: _MessageCountParams,
    messages: list[AllMessageValues],
    use_default_image_token_count: bool,
    default_token_count: int | None,
) -> int:
    """
    Count the number of tokens in a list of messages.

    Args:
        params (_MessageCountParams): The parameters for counting tokens.
        messages (List[AllMessageValues]): The list of messages to count tokens in.
        use_default_image_token_count (bool): When True, will NOT make a GET request to the image URL and instead return the default image dimensions.
        default_token_count (Optional[int]): The default number of tokens to return for a message block, if an error occurs.
    """
    num_tokens = 0

View on GitHub (pinned to 77b7c6c40c)