mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
* fix(proxy): count a contents-only body on /utils/token_counter The route now fills messages from Google-style contents when the caller sent none, using the same translation as the Google countTokens route, so the local count and the framed fallback can read the conversation instead of answering 500 * test(proxy): pin that a prompt sent with contents drops like one sent with messages * test(integration): expect the Vertex partner custom_tokenizer to count a contents-only body * fix(proxy): count Google bodies on /utils/token_counter like the countTokens route and reject unreadable contents The route now maps systemInstruction and Google functionDeclarations tools through the countTokens route's own translation, keeping the caller's system and OpenAI or Anthropic tools. A contents entry without a parts list, or an unreadable systemInstruction, answers 400 naming the field on both count routes instead of 500. Same-name function calls in one turn get numbered ids that their responses answer, so Claude no longer rejects them as duplicate tool results * fix(google_genai): pair each function response with its call by id or order across turns A function response now answers the call that carries its id, else the oldest unanswered call of the same name, even when the responses come in a later turn. Calls without an id get call_<name>, then numbered ids that skip any id the conversation already uses, so search and search_1 no longer clash. The pairing sorts once instead of scanning every earlier call. An unreadable systemInstruction now answers 400 with the JSON path of the bad field and the kind of value it expected. * fix(google_genai): keep tool call ids short and stable and skip system media on /utils Caller ids now only pair each function response with its call. They are no longer sent upstream, so a long caller id no longer gets OpenAI's 64 character 400. A null or non-string id is read as no id instead of dropping the part. The first call of each name keeps call_<name>, and a later call of the same name gets call<n> from its position in the conversation. Ids no longer grow with the name, and an earlier turn keeps its ids when later turns add calls. /utils/token_counter counts the text of a systemInstruction and skips a part with only media, instead of answering 400 for a body Google accepts. * fix(google_genai): pair a tool response with the latest call before it and count entries without parts A function response without a matching caller id now pairs with the earliest unanswered call of the same name in the latest model turn before it, so a call the user skipped stays unanswered and the later call keeps its result. A contents entry without parts counts as an empty turn on both count routes, the way Google's own countTokens and the generateContent route read it, and /utils/token_counter names the exact field when parts or an entry has the wrong type. * fix(gemini): count a contents entry without parts instead of answering 500 The Gemini count handler read parts off every entry, so a contents entry without parts, which Google counts as an empty turn, answered 500 on both count routes. It now sends that entry to Google as the caller wrote it. * fix(google_genai): pair reused caller ids and answer skipped calls A function response now pairs with the latest unanswered call that has its caller id, so ids reused across turns or restarted per turn pair with the call they were sent for. A call a later turn left unanswered gets the same skipped result modify_params adds, so OpenAI and Bedrock Converse accept the conversation. /utils/token_counter keeps an OpenAI tool sent without type * fix(google_genai): list skipped results after the answers to their turn A model reads parallel tool results in order, so a skipped result listed before the caller's answers made GPT give Paris the skipped result and Rome the Paris forecast. A skipped result now follows the answers the next turn sent, which is the order the modify_params filler uses * fix(google_genai): list skipped results after every answer to their turn When the caller split the answers to one model turn across two user turns, the skipped result went between them and GPT read it as the second answer. A skipped result now follows the last user turn that answers its model turn * fix(google_genai): keep skipped results after answers split by empty or text turns A skipped result now goes after the last answer before the next model turn. An empty or text-only user turn between split answers used to end the search early, so GPT read the later answer as the skipped call's result * revert(google_genai): leave Google tool call pairing out of the token counter fix Repeated function call pairing in GoogleGenAIAdapter is a separate translation bug that also affects countTokens and generateContent, so it moves to its own change. This restores the adapter, the shared skipped tool result helper, and their tests to the merge base. --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
177 lines
6.6 KiB
Python
177 lines
6.6 KiB
Python
"""
|
|
Regression tests for the proxy token_counter custom_tokenizer bug.
|
|
|
|
Bug: model_info was never populated from the matched deployment, so
|
|
custom_tokenizer was always None and token counting silently fell back to the
|
|
OpenAI tokenizer instead of the configured HuggingFace tokenizer.
|
|
|
|
The HuggingFace download boundary (Tokenizer.from_pretrained) is mocked so these
|
|
stay hermetic unit tests; the proxy's extraction-and-selection path runs for real.
|
|
"""
|
|
|
|
from collections.abc import Mapping
|
|
from typing import Final
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
from fastapi import Request, Response
|
|
|
|
import litellm
|
|
import litellm.proxy.proxy_server
|
|
import litellm.utils
|
|
from litellm import Router
|
|
from litellm.proxy._types import ProxyException, TokenCountRequest, UserAPIKeyAuth
|
|
from litellm.proxy.proxy_server import count_request_tokens, token_counter
|
|
from litellm.types.utils import TokenCountResponse
|
|
|
|
|
|
def _fake_hf_tokenizer(num_tokens: int) -> MagicMock:
|
|
tokenizer = MagicMock()
|
|
tokenizer.encode_batch_fast.return_value = [[0] * num_tokens]
|
|
return tokenizer
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_custom_tokenizer_from_model_info_is_used(monkeypatch):
|
|
"""
|
|
A deployment carrying model_info.custom_tokenizer must load and use that
|
|
tokenizer. The model name deliberately matches no built-in HuggingFace
|
|
tokenizer, so without the fix the response would fall back to
|
|
"openai_tokenizer" and from_pretrained would never see the configured id.
|
|
"""
|
|
llm_router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "my-embedding-model",
|
|
"litellm_params": {
|
|
"model": "openai/self-hosted-embedder",
|
|
"api_base": "http://localhost:8080/v1",
|
|
},
|
|
"model_info": {
|
|
"mode": "embedding",
|
|
"custom_tokenizer": {
|
|
"identifier": "my-org/custom-tokenizer",
|
|
"revision": "v2",
|
|
"auth_token": None,
|
|
},
|
|
},
|
|
}
|
|
]
|
|
)
|
|
monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", llm_router)
|
|
|
|
with patch.object(litellm.utils, "tokenizer_dispatch") as mock_tokenizer_cls:
|
|
mock_tokenizer_cls.from_pretrained.return_value = _fake_hf_tokenizer(7)
|
|
|
|
response = await count_request_tokens(
|
|
request=TokenCountRequest(
|
|
model="my-embedding-model",
|
|
messages=[{"role": "user", "content": "Bonjour le monde"}],
|
|
)
|
|
)
|
|
|
|
mock_tokenizer_cls.from_pretrained.assert_called_once_with("my-org/custom-tokenizer", revision="v2", token=None)
|
|
assert response.tokenizer_type == "huggingface_tokenizer"
|
|
assert response.request_model == "my-embedding-model"
|
|
assert response.model_used == "self-hosted-embedder"
|
|
assert response.total_tokens >= 7
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_model_without_custom_tokenizer_uses_default(monkeypatch):
|
|
"""
|
|
Control: a deployment with no custom_tokenizer must not touch HuggingFace and
|
|
must report the default OpenAI tokenizer.
|
|
"""
|
|
llm_router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "gpt-4",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
"model_info": {},
|
|
}
|
|
]
|
|
)
|
|
monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", llm_router)
|
|
|
|
with patch.object(litellm.utils, "tokenizer_dispatch") as mock_tokenizer_cls:
|
|
response = await count_request_tokens(
|
|
request=TokenCountRequest(
|
|
model="gpt-4",
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
)
|
|
)
|
|
|
|
mock_tokenizer_cls.from_pretrained.assert_not_called()
|
|
assert response.tokenizer_type == "openai_tokenizer"
|
|
assert response.model_used == "gpt-4"
|
|
assert response.total_tokens > 0
|
|
|
|
|
|
|
|
def _vertex_glm_router(model_info: Mapping[str, object]) -> Router:
|
|
return Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "vertex-glm",
|
|
"litellm_params": {
|
|
"model": "vertex_ai/zai-org/glm-5.2-maas",
|
|
"vertex_project": "test-project",
|
|
"vertex_location": "global",
|
|
},
|
|
"model_info": dict(model_info),
|
|
}
|
|
]
|
|
)
|
|
|
|
|
|
async def _vertex_glm_count(body: Mapping[str, object]) -> TokenCountResponse:
|
|
return await token_counter(
|
|
request=TokenCountRequest.model_validate({"model": "vertex-glm", **body}),
|
|
http_request=Request(
|
|
{"type": "http", "method": "POST", "path": "/utils/token_counter", "query_string": b"", "headers": []}
|
|
),
|
|
fastapi_response=Response(),
|
|
user_api_key_dict=UserAPIKeyAuth(),
|
|
call_endpoint=True,
|
|
)
|
|
|
|
|
|
_GLM_TOKENIZER: Final = {"custom_tokenizer": {"identifier": "zai-org/GLM-5.2", "revision": "main", "auth_token": None}}
|
|
|
|
_RETURN_OK_MESSAGES: Final = {"messages": [{"role": "user", "content": "Return exactly OK."}]}
|
|
_RETURN_OK_CONTENTS: Final = {"contents": [{"role": "user", "parts": [{"text": "Return exactly OK."}]}]}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_custom_tokenizer_counts_a_vertex_partner_model_without_a_count_route(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", _vertex_glm_router(_GLM_TOKENIZER))
|
|
|
|
with patch.object(litellm.utils, "tokenizer_dispatch") as mock_tokenizer_cls:
|
|
mock_tokenizer_cls.from_pretrained.return_value = _fake_hf_tokenizer(9)
|
|
|
|
from_messages: Final = await _vertex_glm_count(_RETURN_OK_MESSAGES)
|
|
from_contents: Final = await _vertex_glm_count(_RETURN_OK_CONTENTS)
|
|
|
|
mock_tokenizer_cls.from_pretrained.assert_called_once_with("zai-org/GLM-5.2", revision="main", token=None)
|
|
assert (from_messages.error, from_contents.error) == (False, False)
|
|
assert from_messages.tokenizer_type == from_contents.tokenizer_type == "huggingface_tokenizer"
|
|
assert from_contents.total_tokens == from_messages.total_tokens >= 9
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"body", [pytest.param(_RETURN_OK_MESSAGES, id="messages"), pytest.param(_RETURN_OK_CONTENTS, id="contents")]
|
|
)
|
|
async def test_count_of_a_vertex_partner_model_without_a_count_route_or_tokenizer_answers_400(
|
|
monkeypatch: pytest.MonkeyPatch, body: Mapping[str, object]
|
|
) -> None:
|
|
monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", _vertex_glm_router({}))
|
|
|
|
with pytest.raises(ProxyException) as raised:
|
|
await _vertex_glm_count(body)
|
|
|
|
assert raised.value.code == "400"
|
|
assert raised.value.message == "LiteLLM does not support counting tokens for Vertex AI model zai-org/glm-5.2-maas."
|