The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy)!: count endpoints return errors in their source API shape instead of silent local counts (#46815)
Mateo Wangb21e659c2472
diff --git a/litellm/integrations/gitlab/gitlab_prompt_manager.py b/litellm/integrations/gitlab/gitlab_prompt_manager.pyindex 85b91821f6c..adaacd615a8 100644--- a/litellm/integrations/gitlab/gitlab_prompt_manager.py+++ b/litellm/integrations/gitlab/gitlab_prompt_manager.py@@ -219,7 +219,7 @@ class GitLabTemplateManager:elif value.replace(".", "").isdigit():try:result[key] = float(value)- except Exception:+ except ValueError:result[key] = valueelse:result[key] = value.strip("\"'")diff --git a/litellm/llms/anthropic/count_tokens/token_counter.py b/litellm/llms/anthropic/count_tokens/token_counter.pyindex d78de0037a0..55eaa0d2ac6 100644--- a/litellm/llms/anthropic/count_tokens/token_counter.py+++ b/litellm/llms/anthropic/count_tokens/token_counter.py@@ -6,6 +6,7 @@ from typing import Any, Finalfrom pydantic import JsonValue+import litellmfrom litellm._logging import verbose_loggerfrom litellm.exceptions import AuthenticationErrorfrom litellm.llms.anthropic.count_tokens.handler import AnthropicCountTokensHandler@@ -61,14 +62,24 @@ class AnthropicTokenCounter(BaseTokenCounter):try:auth_header: Final = await AnthropicModelInfo.aget_auth_header(- api_key=litellm_params.get("api_key"),+ api_key=litellm_params.get("api_key") or litellm.anthropic_key or litellm.api_key,api_base=api_base,litellm_params=litellm_params,allow_workload_identity=True,)if auth_header is None:- verbose_logger.warning("No Anthropic credential found for token counting")- return None+ return TokenCountResponse(+ total_tokens=0,+ request_model=request_model,+ model_used=model_to_use,+ tokenizer_type="anthropic_api",+ error=True,+ error_message=(+ f"No Anthropic API key is set for model {request_model or model_to_use}, so tokens can't be "+ "counted. Set api_key on the deployment or ANTHROPIC_API_KEY in the proxy environment."+ ),+ status_code=401,+ )result: Final = await anthropic_count_tokens_handler.handle_count_tokens_request(model=model_to_use,diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py b/litellm/llms/azure_ai/anthropic/count_tokens/handler.pyindex 0e0b68df449..53734a77f3c 100644--- a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py+++ b/litellm/llms/azure_ai/anthropic/count_tokens/handler.py@@ -30,7 +30,7 @@ class AzureAIAnthropicCountTokensHandler(AzureAIAnthropicCountTokensConfig):self,model: str,messages: list[dict[str, JsonValue]],- api_key: str,+ api_key: str | None,api_base: str,litellm_params: dict[str, object] | None = None,timeout: float | httpx.Timeout | None = None,@@ -80,6 +80,15 @@ class AzureAIAnthropicCountTokensHandler(AzureAIAnthropicCountTokensConfig):api_key=api_key,litellm_params=litellm_params,)+ if not {"x-api-key", "Authorization"} & headers.keys():+ raise AnthropicError(+ status_code=401,+ message=(+ f"No Azure AI API key or Entra ID credential is set for model {model}, so tokens can't be "+ "counted. Set api_key or an Entra ID credential on the deployment, or AZURE_AI_API_KEY or "+ "AZURE_API_KEY in the proxy environment."+ ),+ )# Use LiteLLM's async httpx clientasync_client: Final = get_async_httpx_client(llm_provider=litellm.LlmProviders.AZURE_AI)diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py b/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.pyindex 2707d24ee07..0ed432cc394 100644--- a/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py+++ b/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py@@ -7,6 +7,7 @@ from typing import Any, Finalfrom pydantic import JsonValue+import litellmfrom litellm._logging import verbose_loggerfrom litellm.llms.azure_ai.anthropic.count_tokens.handler import (AzureAIAnthropicCountTokensHandler,@@ -18,6 +19,21 @@ from litellm.types.utils import LlmProviders, TokenCountMessagesFormat, TokenCouazure_ai_anthropic_count_tokens_handler: Final = AzureAIAnthropicCountTokensHandler()+def _missing_api_base_response(request_model: str, model_to_use: str) -> TokenCountResponse:+ return TokenCountResponse(+ total_tokens=0,+ request_model=request_model,+ model_used=model_to_use,+ tokenizer_type="azure_ai_anthropic_api",+ error=True,+ error_message=(+ f"No Azure AI API base is set for model {request_model or model_to_use}, so tokens can't be counted. "+ "Set api_base on the deployment or AZURE_AI_API_BASE or AZURE_API_BASE in the proxy environment."+ ),+ status_code=500,+ )++class AzureAIAnthropicTokenCounter(BaseTokenCounter):"""Token counter implementation for Azure AI Anthropic provider using the CountTokens API."""@@ -65,18 +81,15 @@ class AzureAIAnthropicTokenCounter(BaseTokenCounter):if not api_key:api_key = os.getenv("AZURE_AI_API_KEY")- # Get API base from deployment config or environment- api_base = litellm_params.get("api_base")- if not api_base:- api_base = os.getenv("AZURE_AI_API_BASE")-- if not api_key:- verbose_logger.warning("No Azure AI API key found for token counting")- return None+ api_base: Final = (+ litellm_params.get("api_base")+ or os.getenv("AZURE_AI_API_BASE")+ or os.getenv("AZURE_API_BASE")+ or litellm.api_base+ )if not api_base:- verbose_logger.warning("No Azure AI API base found for token counting")- return None+ return _missing_api_base_response(request_model, model_to_use)try:result: Final = await azure_ai_anthropic_count_tokens_handler.handle_count_tokens_request(diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.pyindex d7455439151..5946a1f4480 100644--- a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py+++ b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py@@ -24,7 +24,7 @@ class AzureAIAnthropicCountTokensConfig(AnthropicCountTokensConfig):def get_required_headers(self,- api_key: str,+ api_key: str | None,litellm_params: dict[str, object] | None = None,) -> dict[str, str]:"""@@ -45,12 +45,12 @@ class AzureAIAnthropicCountTokensConfig(AnthropicCountTokensConfig):"Content-Type": "application/json","anthropic-version": "2023-06-01","anthropic-beta": ANTHROPIC_TOKEN_COUNTING_BETA_VERSION,- "x-api-key": api_key, # Azure AI Anthropic requires this header+ **({"x-api-key": api_key} if api_key else {}),}# Also set up Azure auth headers for flexibilitylitellm_params = litellm_params or {}- if "api_key" not in litellm_params:+ if api_key and "api_key" not in litellm_params:litellm_params["api_key"] = api_keylitellm_params_obj: Final = GenericLiteLLMParams.model_validate(litellm_params)@@ -58,8 +58,9 @@ class AzureAIAnthropicCountTokensConfig(AnthropicCountTokensConfig):# Get Azure auth headers (api-key or Authorization)azure_headers = BaseAzureLLM.base_validate_azure_environment(headers={}, litellm_params=litellm_params_obj)- # Merge Azure auth headersheaders.update(azure_headers)+ if "api-key" in azure_headers:+ headers.setdefault("x-api-key", azure_headers["api-key"])return headersdiff --git a/litellm/llms/openai/responses/count_tokens/token_counter.py b/litellm/llms/openai/responses/count_tokens/token_counter.pyindex 43b3ae9f6f1..7c0697626ca 100644--- a/litellm/llms/openai/responses/count_tokens/token_counter.py+++ b/litellm/llms/openai/responses/count_tokens/token_counter.py@@ -2,20 +2,21 @@OpenAI Token Counter implementation using the Responses API /input_tokens endpoint."""-import osfrom collections.abc import Mapping, Sequencefrom typing import Any, Final+import openaifrom pydantic import JsonValuefrom typing_extensions import assert_neverfrom litellm._logging import verbose_logger+from litellm.litellm_core_utils.asyncify import asyncifyfrom litellm.llms.anthropic.pass_through.convertible_blocks import unconvertible_blocks_errorfrom litellm.llms.anthropic.pass_through.responses_adapters.transformation import (LiteLLMAnthropicToResponsesAPIAdapter,)from litellm.llms.base_llm.base_utils import BaseTokenCounter-from litellm.llms.openai.common_utils import OpenAIError+from litellm.llms.openai.common_utils import OpenAIError, get_openai_credentialsfrom litellm.llms.openai.responses.count_tokens.handler import (OpenAICountTokensHandler,)@@ -23,12 +24,26 @@ from litellm.llms.openai.responses.count_tokens.transformation import (OpenAICountTokensConfig,ResponsesCountRequestParts,)+from litellm.llms.openai.workload_identity import (+ OpenAIWorkloadIdentityConfig,+ get_workload_identity_bearer_token,+ resolve_openai_workload_identity_config,+)from litellm.types.utils import LlmProviders, TokenCountMessagesFormat, TokenCountResponse# Global handler instance - reuse across all token counting requestsopenai_count_tokens_handler: Final = OpenAICountTokensHandler()+def _workload_identity_config(litellm_params: Mapping[str, object]) -> OpenAIWorkloadIdentityConfig | None:+ api_base: Final = litellm_params.get("api_base")+ return resolve_openai_workload_identity_config(+ api_key=None,+ api_base=api_base if isinstance(api_base, str) else None,+ litellm_params=litellm_params,+ )++class OpenAITokenCounter(BaseTokenCounter):"""Token counter implementation for OpenAI provider using the Responses API."""@@ -107,16 +122,27 @@ class OpenAITokenCounter(BaseTokenCounter):deployment = deployment or {}litellm_params: Final = deployment.get("litellm_params", {})- # Get OpenAI API key from deployment config or environment- api_key = litellm_params.get("api_key")- if not api_key:- api_key = os.getenv("OPENAI_API_KEY")+ credentials: Final = get_openai_credentials(+ api_base=litellm_params.get("api_base"), api_key=litellm_params.get("api_key")+ )+ credential: Final = credentials.api_key or _workload_identity_config(litellm_params)- if not api_key:- verbose_logger.warning("No OpenAI API key found for token counting")- return None+ if credential is None:+ return TokenCountResponse(+ total_tokens=0,+ request_model=request_model,+ model_used=model_to_use,+ tokenizer_type="openai_api",+ error=True,+ error_message=(+ f"No OpenAI API key is set for model {request_model or model_to_use}, so tokens can't be "+ "counted. Set api_key or workload identity on the deployment, or OPENAI_API_KEY in the proxy "+ "environment."+ ),+ status_code=401,+ )- api_base: Final = litellm_params.get("api_base")+ api_base: Final = credentials.api_baseinput_items, instructions, counted_tools, text = self._responses_request_parts(model_to_use=model_to_use,@@ -132,6 +158,11 @@ class OpenAITokenCounter(BaseTokenCounter):return Nonetry:+ api_key: Final = (+ credential+ if isinstance(credential, str)+ else await asyncify(get_workload_identity_bearer_token)(credential)+ )result: Final = await openai_count_tokens_handler.handle_count_tokens_request(model=model_to_use,input=input_items,@@ -163,6 +194,17 @@ class OpenAITokenCounter(BaseTokenCounter):error_message=e.message,status_code=e.status_code,)+ except openai.AuthenticationError as e:+ verbose_logger.warning("OpenAI workload identity token exchange failed: %s", e.message)+ return TokenCountResponse(+ total_tokens=0,+ request_model=request_model,+ model_used=model_to_use,+ tokenizer_type="openai_api",+ error=True,+ error_message=e.message,+ status_code=401,+ )except Exception as e:verbose_logger.warning("Error calling OpenAI CountTokens API: %s", e)return TokenCountResponse(diff --git a/litellm/proxy/anthropic_endpoints/endpoints.py b/litellm/proxy/anthropic_endpoints/endpoints.pyindex 4d0eb6a166a..ee1ac79c820 100644--- a/litellm/proxy/anthropic_endpoints/endpoints.py+++ b/litellm/proxy/anthropic_endpoints/endpoints.py@@ -29,6 +29,7 @@ from litellm.proxy.common_request_processing import (create_response,log_llm_api_exception,proxy_exception_from_http_exception,+ proxy_exception_from_route_error,resolve_litellm_call_id,)from litellm.proxy.common_utils.error_body_call_id import error_body_call_id@@ -339,10 +340,10 @@ async def count_tokens(messages: Final = data.get("messages", [])if not model_name:- raise HTTPException(status_code=400, detail={"error": "model parameter is required"})+ raise HTTPException(status_code=400, detail="model parameter is required")if not messages:- raise HTTPException(status_code=400, detail={"error": "messages parameter is required"})+ raise HTTPException(status_code=400, detail="messages parameter is required")# Create TokenCountRequest for the internal endpointfrom litellm.proxy._types import TokenCountRequest@@ -360,13 +361,13 @@ async def count_tokens(messages_format="anthropic",output_format=_requested_output_format(data),)- except HTTPException:- raise+ except HTTPException as e:+ return _anthropic_error_json_response(proxy_exception_from_http_exception(e, {}), request)except ProxyException as e:return _anthropic_error_json_response(e, request)except Exception as e:log_llm_api_exception(e, litellm_call_id)- raise HTTPException(status_code=500, detail={"error": f"Internal server error: {e}"})+ return _anthropic_error_json_response(proxy_exception_from_route_error(e), request)else:return {"input_tokens": token_response.total_tokens}diff --git a/litellm/proxy/google_endpoints/endpoints.py b/litellm/proxy/google_endpoints/endpoints.pyindex 784e3d4719f..d382ff53ffb 100644--- a/litellm/proxy/google_endpoints/endpoints.py+++ b/litellm/proxy/google_endpoints/endpoints.py@@ -1,16 +1,22 @@from collections.abc import Mappingfrom itertools import chain+from types import MappingProxyTypefrom typing import Finalfrom fastapi import APIRouter, Depends, HTTPException, Request, Response-from fastapi.responses import ORJSONResponse+from fastapi.responses import JSONResponse, ORJSONResponsefrom pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter, ValidationErrorfrom litellm.litellm_core_utils.json_validation_rule import normalize_json_schema_typesfrom litellm.proxy._types import *-from litellm.proxy._types import TokenCountRequest+from litellm.proxy._types import ProxyException, TokenCountRequestfrom litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth-from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing+from litellm.proxy.common_request_processing import (+ ProxyBaseLLMRequestProcessing,+ log_llm_api_exception,+ proxy_exception_from_http_exception,+ resolve_litellm_call_id,+)from litellm.proxy.common_utils.http_parsing_utils import ( # noqa: F401 # legacy module exports_read_request_body, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package exportread_request_body,@@ -63,6 +69,37 @@ def _input_schema(declaration: _GoogleCountTokensFunctionDeclaration) -> object:return {"type": "object", "properties": {}}+_GOOGLE_RPC_STATUS: Final = MappingProxyType(+ {+ 400: "INVALID_ARGUMENT",+ 401: "UNAUTHENTICATED",+ 403: "PERMISSION_DENIED",+ 404: "NOT_FOUND",+ 409: "ABORTED",+ 429: "RESOURCE_EXHAUSTED",+ 499: "CANCELLED",+ 501: "UNIMPLEMENTED",+ 503: "UNAVAILABLE",+ 504: "DEADLINE_EXCEEDED",+ }+)+++def _google_error_response(request: Request, error: ProxyException) -> JSONResponse:+ from litellm.proxy.proxy_server import (+ _close_dangling_otel_server_span, # pyright: ignore[reportPrivateUsage] # proxy_server keeps the span-close helper private; error JSONResponses returned by the route must stamp the OTel server span like the global ProxyException handler does+ )++ status_code: Final = int(error.code) if error.code is not None and error.code.isdigit() else 500+ _close_dangling_otel_server_span(request, status_code, exc=error)+ status: Final = _GOOGLE_RPC_STATUS.get(status_code, "INTERNAL" if status_code >= 500 else "FAILED_PRECONDITION")+ return JSONResponse(+ status_code=status_code,+ content={"error": {"code": status_code, "message": error.message, "status": status}},+ headers=error.headers,+ )++def _google_count_tokens_request(model_name: str, data: object) -> TokenCountRequest:from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter@@ -251,16 +288,26 @@ async def google_count_tokens(request: Request, model_name: str):data: Final = await read_request_body(request=request)try:token_request: Final = _google_count_tokens_request(model_name, data)- except ValidationError as error:- raise HTTPException(status_code=400, detail="Invalid Google countTokens request body") from error+ except ValidationError:+ return _google_error_response(+ request,+ ProxyException(+ message="Invalid Google countTokens request body", type="invalid_request_error", param=None, code=400+ ),+ )- # Call the internal token counter function with direct request flag set to False- token_response: Final = await internal_token_counter(- request=token_request,- call_endpoint=True,- )- if token_response is None:- return TokenCountDetailsResponse(totalTokens=0, promptTokensDetails=[])+ try:+ token_response: Final = await internal_token_counter(request=token_request, call_endpoint=True)+ except ProxyException as error:+ return _google_error_response(request, error)+ except HTTPException as error:+ return _google_error_response(request, proxy_exception_from_http_exception(error, {}))+ except Exception as error:+ log_llm_api_exception(error, resolve_litellm_call_id(request.headers.get("x-litellm-call-id")))+ return _google_error_response(+ request,+ ProxyException(message="Internal server error", type="internal_server_error", param=None, code=500),+ )original_response: Final[dict] = token_response.original_response or {}return TokenCountDetailsResponse(totalTokens=original_response.get("totalTokens") or token_response.total_tokens or 0,diff --git a/tests/integration/providers/test_count_tokens_error_shapes_wire.py b/tests/integration/providers/test_count_tokens_error_shapes_wire.pynew file mode 100644index 00000000000..200f5e81673--- /dev/null+++ b/tests/integration/providers/test_count_tokens_error_shapes_wire.py@@ -0,0 +1,205 @@+import json+from collections.abc import Iterator+from typing import Final++import anthropic+import openai+import pytest+from integration._support.client import Gateway, gateway_from_environment+from integration._support.process import OwnedProxy, graceful_stop_seconds, owned_proxy_process+from integration._support.wire import Reply, Request, wire_server+from pydantic import JsonValue, TypeAdapter++pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)++_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_MESSAGES: Final[list[JsonValue]] = [{"role": "user", "content": "Count this synthetic request."}]+_PROVIDER_KEY_VARIABLES: Final = (+ "ANTHROPIC_API_KEY",+ "ANTHROPIC_AUTH_TOKEN",+ "AZURE_AI_API_KEY",+ "AZURE_API_KEY",+ "AZURE_OPENAI_API_KEY",+ "AZURE_AD_TOKEN",+ "AZURE_CLIENT_ID",+ "AZURE_CLIENT_SECRET",+ "AZURE_TENANT_ID",+ "OPENAI_API_KEY",+)++[email protected](scope="module")+def keyless_proxy(tmp_path_factory: pytest.TempPathFactory) -> Iterator[OwnedProxy]:+ with (+ gateway_from_environment() as gateway,+ owned_proxy_process(+ gateway,+ tmp_path_factory.mktemp("count-tokens-error-shapes"),+ {},+ remove_environment=_PROVIDER_KEY_VARIABLES,+ workers=1,+ ) as owned,+ ):+ yield owned++[email protected](scope="module")+def azure_environment_key_proxy(tmp_path_factory: pytest.TempPathFactory) -> Iterator[OwnedProxy]:+ with (+ gateway_from_environment() as gateway,+ owned_proxy_process(+ gateway,+ tmp_path_factory.mktemp("count-tokens-azure-environment-key"),+ {"AZURE_API_KEY": "synthetic-azure-env-key"},+ remove_environment=tuple(name for name in _PROVIDER_KEY_VARIABLES if name != "AZURE_API_KEY"),+ workers=1,+ ) as owned,+ ):+ yield owned+++def _anthropic(gateway: Gateway) -> anthropic.Anthropic:+ return anthropic.Anthropic(+ api_key=gateway.key, base_url=str(gateway.client.base_url), max_retries=0, http_client=gateway.client+ )+++def _never_called(request: Request) -> Reply:+ raise AssertionError(f"count reached the provider without a key: {request.target}")+++ ("deployment", "missing"),+ (+ ({"model": "anthropic/claude-sonnet-4-6"}, "No Anthropic API key is set for model "),+ ({"model": "azure_ai/claude-sonnet-4-6"}, "No Azure AI API key or Entra ID credential is set for model "),+ ),+ ids=("anthropic", "azure_ai_anthropic"),+)+def test_anthropic_count_without_a_provider_credential_is_an_anthropic_401(+ keyless_proxy: OwnedProxy, deployment: dict[str, JsonValue], missing: str+) -> None:+ gateway: Final = keyless_proxy.gateway+ with wire_server(_never_called) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(**deployment, api_base=wire.url, api_key=None, num_retries=0)+ with pytest.raises(anthropic.AuthenticationError) as raised:+ _anthropic(gateway).messages.count_tokens(model=model, messages=_MESSAGES)+ assert raised.value.body == {+ "type": "error",+ "error": {"type": "authentication_error", "message": raised.value.body["error"]["message"]},+ }+ assert missing in raised.value.message, raised.value.message+ assert wire.drain() == ()+++def test_azure_ai_anthropic_count_sends_the_azure_environment_key_as_x_api_key(+ azure_environment_key_proxy: OwnedProxy,+) -> None:+ gateway: Final = azure_environment_key_proxy.gateway++ def count(request: Request) -> Reply:+ assert request.headers.get("x-api-key") == "synthetic-azure-env-key", request.headers+ return Reply(body=json.dumps({"input_tokens": 58}).encode())++ with wire_server(count) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model="azure_ai/claude-sonnet-4-6",+ api_base=wire.url,+ api_key=None,+ num_retries=0,+ )+ result: Final = _anthropic(gateway).messages.count_tokens(model=model, messages=_MESSAGES)+ assert result.input_tokens == 58+++def test_azure_ai_anthropic_count_authenticates_with_an_entra_token(keyless_proxy: OwnedProxy) -> None:+ gateway: Final = keyless_proxy.gateway++ def count(request: Request) -> Reply:+ assert request.headers.get("authorization") == "Bearer synthetic-entra-token", request.headers+ assert "x-api-key" not in request.headers, request.headers+ return Reply(body=json.dumps({"input_tokens": 61}).encode())++ with wire_server(count) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model="azure_ai/claude-sonnet-4-6",+ api_base=wire.url,+ api_key=None,+ azure_ad_token="synthetic-entra-token",+ num_retries=0,+ )+ result: Final = _anthropic(gateway).messages.count_tokens(model=model, messages=_MESSAGES)+ assert result.input_tokens == 61+ assert len(wire.drain()) == 1+++def test_anthropic_count_request_errors_use_the_anthropic_envelope(keyless_proxy: OwnedProxy) -> None:+ gateway: Final = keyless_proxy.gateway+ upstream_error: Final = {"type": "error", "error": {"type": "invalid_request_error", "message": "scripted reject"}}+ with (+ wire_server(lambda _request: Reply(status=400, body=json.dumps(upstream_error).encode())) as wire,+ gateway.scenario() as scenario,+ ):+ model: Final = scenario.model(+ model="anthropic/claude-sonnet-4-6", api_base=wire.url, api_key="synthetic-key", num_retries=0+ )+ missing_messages: Final = gateway.request("POST", "/v1/messages/count_tokens", {"model": model})+ assert missing_messages.status_code == 400, missing_messages.text+ assert _JSON_OBJECT.validate_json(missing_messages.content) == {+ "type": "error",+ "error": {"type": "invalid_request_error", "message": "messages parameter is required"},+ }++ rejected: Final = gateway.request(+ "POST", "/v1/messages/count_tokens", {"model": model, "messages": _MESSAGES}+ )+ assert rejected.status_code == 400, rejected.text+ body: Final = _JSON_OBJECT.validate_json(rejected.content)+ assert set(body) <= {"type", "error", "request_id"}, body+ assert body["error"] == upstream_error["error"], body+ assert len(wire.drain()) == 1+++def test_openai_input_tokens_without_a_provider_key_is_an_openai_401(keyless_proxy: OwnedProxy) -> None:+ gateway: Final = keyless_proxy.gateway+ with wire_server(_never_called) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model="openai/gpt-4o-mini", api_base=f"{wire.url}/v1", api_key=None, num_retries=0+ )+ client: Final = openai.OpenAI(+ api_key=gateway.key, base_url=str(gateway.client.base_url), max_retries=0, http_client=gateway.client+ )+ with pytest.raises(openai.AuthenticationError) as raised:+ client.responses.input_tokens.count(model=model, input="Count this synthetic request.")+ assert f"No OpenAI API key is set for model {model}" in raised.value.message+ assert wire.drain() == ()+++def test_google_count_tokens_errors_use_the_google_envelope(keyless_proxy: OwnedProxy) -> None:+ gateway: Final = keyless_proxy.gateway+ upstream_error: Final = {+ "error": {"code": 400, "message": "API key not valid. Please pass a valid API key.", "status": "INVALID_ARGUMENT"}+ }+ with (+ wire_server(lambda _request: Reply(status=400, body=json.dumps(upstream_error).encode())) as wire,+ gateway.scenario() as scenario,+ ):+ model: Final = scenario.model(+ model="gemini/gemini-2.5-flash", api_base=wire.url, api_key="synthetic-key", num_retries=0+ )+ rejected: Final = gateway.request(+ "POST",+ f"/v1beta/models/{model}:countTokens",+ {"contents": [{"role": "user", "parts": [{"text": "Count this synthetic request."}]}]},+ )+ assert rejected.status_code == 400, rejected.text+ error: Final = _JSON_OBJECT.validate_json(rejected.content)["error"]+ assert isinstance(error, dict) and error["code"] == 400 and error["status"] == "INVALID_ARGUMENT", error+ assert "API key not valid" in str(error["message"]), error+ assert len(wire.drain()) == 1++ malformed: Final = gateway.request("POST", f"/v1beta/models/{model}:countTokens", {"contents": "not-a-list"})+ assert malformed.status_code == 400, malformed.text+ assert _JSON_OBJECT.validate_json(malformed.content) == {+ "error": {"code": 400, "message": "Invalid Google countTokens request body", "status": "INVALID_ARGUMENT"}+ }diff --git a/tests/unit/llms/anthropic/test_count_tokens_oauth.py b/tests/unit/llms/anthropic/test_count_tokens_oauth.pyindex 7f717091754..16ec513916c 100644--- a/tests/unit/llms/anthropic/test_count_tokens_oauth.py+++ b/tests/unit/llms/anthropic/test_count_tokens_oauth.py@@ -197,6 +197,30 @@ class TestCountTokensUsesWorkloadIdentity:assert ANTHROPIC_TOKEN_COUNTING_BETA_VERSION in betasassert ANTHROPIC_OAUTH_BETA_HEADER not in betas+ @pytest.mark.asyncio+ async def test_a_global_anthropic_key_counts_like_chat_would_authenticate(+ self, monkeypatch, httpx_transport_clients+ ):+ for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_BASE", "ANTHROPIC_BASE_URL"):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setattr(litellm, "anthropic_key", FAKE_REGULAR_KEY)++ with respx.mock(assert_all_called=True) as router:+ route = router.post("https://api.anthropic.com/v1/messages/count_tokens").mock(+ return_value=httpx.Response(200, json={"input_tokens": 13})+ )+ result = await AnthropicTokenCounter().count_tokens(+ model_to_use="claude-sonnet-4-5",+ messages=[{"role": "user", "content": "hi"}],+ contents=None,+ deployment={"litellm_params": {"model": "anthropic/claude-sonnet-4-5"}},+ request_model="claude-sonnet-4-5",+ )++ assert result is not None+ assert result.total_tokens == 13+ assert route.calls.last.request.headers["x-api-key"] == FAKE_REGULAR_KEY+@pytest.mark.asyncioasync def test_a_failed_mint_degrades_like_an_anthropic_error(self, monkeypatch):from litellm.llms.anthropic.count_tokens import token_counter as token_counter_modulediff --git a/tests/unit/llms/azure_ai/anthropic/count_tokens/test_token_counter.py b/tests/unit/llms/azure_ai/anthropic/count_tokens/test_token_counter.pyindex 29380c6fc53..86ad6c8d9d9 100644--- a/tests/unit/llms/azure_ai/anthropic/count_tokens/test_token_counter.py+++ b/tests/unit/llms/azure_ai/anthropic/count_tokens/test_token_counter.py@@ -186,3 +186,27 @@ async def test_undecodable_count_body_becomes_a_500_error_response_carrying_the_"status_code": 500,})++[email protected]("set_base", ("env", "global"), ids=("AZURE_API_BASE", "litellm.api_base"))+async def test_count_uses_the_shared_api_base_chat_would_use(monkeypatch: pytest.MonkeyPatch, set_base: str) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.delenv("AZURE_AI_API_BASE", raising=False)+ monkeypatch.delenv("AZURE_API_BASE", raising=False)+ if set_base == "env":+ monkeypatch.setenv("AZURE_API_BASE", API_BASE)+ else:+ monkeypatch.setattr(litellm, "api_base", API_BASE)+ with respx.mock:+ route: Final = respx.post(COUNT_URL).mock(return_value=httpx.Response(200, json={"input_tokens": 6}))+ result: Final = await AzureAIAnthropicTokenCounter().count_tokens(+ model_to_use="claude-sonnet-4-5",+ messages=[{"role": "user", "content": "hi"}],+ contents=None,+ deployment={"litellm_params": {"api_key": "azure-key"}},+ request_model="azure_ai/claude-sonnet-4-5",+ )+ assert result is not None+ assert result.total_tokens == 6+ assert route.calleddiff --git a/tests/unit/llms/openai/responses/count_tokens/test_token_counter.py b/tests/unit/llms/openai/responses/count_tokens/test_token_counter.pyindex 976ecff01ea..befdc5ee9fd 100644--- a/tests/unit/llms/openai/responses/count_tokens/test_token_counter.py+++ b/tests/unit/llms/openai/responses/count_tokens/test_token_counter.py@@ -388,3 +388,44 @@ async def test_undecodable_count_body_becomes_a_500_error_response_carrying_the_"status_code": 500,})+++async def test_count_uses_the_global_openai_key_chat_would_use(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "openai_key", "sk-from-litellm-settings")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ with respx.mock:+ route: Final = respx.post(COUNT_URL).mock(return_value=httpx.Response(200, json={"input_tokens": 9}))+ result: Final = await OpenAITokenCounter().count_tokens(+ model_to_use="gpt-4o",+ messages=[{"role": "user", "content": "hi"}],+ contents=None,+ deployment={"litellm_params": {}},+ request_model="openai/gpt-4o",+ )+ assert result is not None+ assert result.total_tokens == 9+ assert route.calls.last.request.headers["authorization"] == "Bearer sk-from-litellm-settings"+++async def test_count_sends_the_global_key_only_to_the_global_api_base(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "openai_key", "sk-private-gateway")+ monkeypatch.setattr(litellm, "api_base", "https://gateway.internal.example/v1")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ with respx.mock:+ route: Final = respx.post("https://gateway.internal.example/v1/responses/input_tokens").mock(+ return_value=httpx.Response(200, json={"input_tokens": 4})+ )+ result: Final = await OpenAITokenCounter().count_tokens(+ model_to_use="gpt-4o",+ messages=[{"role": "user", "content": "hi"}],+ contents=None,+ deployment={"litellm_params": {}},+ request_model="openai/gpt-4o",+ )+ assert result is not None+ assert result.total_tokens == 4+ assert route.calls.last.request.headers["authorization"] == "Bearer sk-private-gateway"diff --git a/tests/unit/llms/openai/test_openai_workload_identity.py b/tests/unit/llms/openai/test_openai_workload_identity.pyindex d0cf52d0e28..2236de1eb5f 100644--- a/tests/unit/llms/openai/test_openai_workload_identity.py+++ b/tests/unit/llms/openai/test_openai_workload_identity.py@@ -648,3 +648,56 @@ class TestClientsideBaseOverride:)is None)+++class TestCountTokens:+ @pytest.mark.asyncio+ @respx.mock+ async def test_count_authenticates_with_the_workload_identity_bearer(+ self, wif_env: OpenAIWorkloadIdentityConfig, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from litellm.llms.openai.responses.count_tokens.token_counter import OpenAITokenCounter++ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "api_key", None)+ monkeypatch.setattr(litellm, "openai_key", None)+ mock_token_exchange()+ count_route: Final = respx.post("https://api.openai.com/v1/responses/input_tokens").mock(+ return_value=httpx.Response(200, json={"input_tokens": 12})+ )+ result: Final = await OpenAITokenCounter().count_tokens(+ model_to_use="gpt-4o",+ messages=[{"role": "user", "content": "hi"}],+ contents=None,+ deployment={"litellm_params": {}},+ request_model="openai/gpt-4o",+ )+ assert result is not None+ assert result.error is False+ assert result.total_tokens == 12+ assert count_route.calls.last.request.headers["authorization"] == "Bearer exchanged-bearer-token"++ @pytest.mark.asyncio+ @respx.mock+ async def test_failed_mint_becomes_a_count_error_response(+ self, wif_env: OpenAIWorkloadIdentityConfig, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from litellm.llms.openai.responses.count_tokens.token_counter import OpenAITokenCounter++ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "api_key", None)+ monkeypatch.setattr(litellm, "openai_key", None)+ respx.post(TOKEN_EXCHANGE_URL).mock(return_value=httpx.Response(400, json={"error": "invalid_grant"}))+ count_route: Final = respx.post("https://api.openai.com/v1/responses/input_tokens")+ result: Final = await OpenAITokenCounter().count_tokens(+ model_to_use="gpt-4o",+ messages=[{"role": "user", "content": "hi"}],+ contents=None,+ deployment={"litellm_params": {}},+ request_model="openai/gpt-4o",+ )+ assert result is not None+ assert result.error is True+ assert result.status_code == 401+ assert result.total_tokens == 0+ assert not count_route.calleddiff --git a/tests/unit/proxy/anthropic_endpoints/test_endpoints.py b/tests/unit/proxy/anthropic_endpoints/test_endpoints.pyindex 69d182667ec..e4129ebbc39 100644--- a/tests/unit/proxy/anthropic_endpoints/test_endpoints.py+++ b/tests/unit/proxy/anthropic_endpoints/test_endpoints.py@@ -440,8 +440,6 @@ class TestErrorLogCarriesCallId:@pytest.mark.asyncioasync def test_count_tokens_failure_log_carries_callers_call_id(self, caplog: pytest.LogCaptureFixture):- from fastapi import HTTPException-import litellm.proxy.anthropic_endpoints.endpoints as epimport litellm.proxy.proxy_server as proxy_serverfrom litellm.proxy._types import UserAPIKeyAuth@@ -460,11 +458,10 @@ class TestErrorLogCarriesCallId:proxy_server, "count_request_tokens", new=AsyncMock(side_effect=RuntimeError("tokenizer down"))), # test-quality-ok: module global imported at call time; the test targets the endpoint's except blockcaplog.at_level(logging.ERROR, logger="LiteLLM Proxy"),- pytest.raises(HTTPException) as raised,):- await ep.count_tokens(request=request, user_api_key_dict=UserAPIKeyAuth())+ response = await ep.count_tokens(request=request, user_api_key_dict=UserAPIKeyAuth())- assert raised.value.status_code == 500+ assert response.status_code == 500record = self._error_record(caplog)assert record.litellm_call_id == call_idassert call_id in record.getMessage()diff --git a/tests/unit/proxy/google_endpoints/test_google_api_endpoints.py b/tests/unit/proxy/google_endpoints/test_google_api_endpoints.pyindex 451792109de..114bbb184c6 100644--- a/tests/unit/proxy/google_endpoints/test_google_api_endpoints.py+++ b/tests/unit/proxy/google_endpoints/test_google_api_endpoints.py@@ -182,6 +182,29 @@ def test_google_count_tokens_unchanged():assert body["totalTokens"] == 7+def test_google_count_tokens_unexpected_failure_uses_the_google_error_envelope():+ try:+ client = _build_test_client()+ except ImportError as e:+ pytest.skip(f"Skipping test due to missing dependency: {e}")++ with patch(+ "litellm.proxy.proxy_server.token_counter",+ new_callable=AsyncMock,+ side_effect=RuntimeError("tokenizer unavailable"),+ ):+ response = client.post(+ "/v1beta/models/test-model:countTokens",+ json={"contents": [{"role": "user", "parts": [{"text": "Hello"}]}]},+ )++ assert response.status_code == 500+ error = response.json()["error"]+ assert error["code"] == 500+ assert error["status"] == "INTERNAL"+ assert "tokenizer unavailable" not in error["message"]++def test_google_count_tokens_uses_normalized_total_when_provider_shape_differs():"""A provider that counts in Anthropic shape (Bedrock, Anthropic) carries no totalTokens key, so the normalized total must win over the raw response's missing field."""try:diff --git a/tests/unit/proxy/test_proxy_token_counter.py b/tests/unit/proxy/test_proxy_token_counter.pyindex 9bed719227f..fbe47e4a3d7 100644--- a/tests/unit/proxy/test_proxy_token_counter.py+++ b/tests/unit/proxy/test_proxy_token_counter.py@@ -327,22 +327,16 @@ async def test_internal_token_counter_anthropic_provider_detection():setattr(litellm.proxy.proxy_server, "llm_router", llm_router)- # Test with is_direct_request=False but non-Anthropic provider- response = await token_counter(- request=TokenCountRequest(- model="gpt-test",- messages=[{"role": "user", "content": "hello"}],- ),- call_endpoint=True,- )-- print("Non-Anthropic provider test response:", response)-- # Verify response structure- assert response.request_model == "gpt-test"- assert response.model_used == "gpt-4"- assert response.total_tokens > 0- assert response.tokenizer_type == "openai_tokenizer" # Should use LiteLLM tokenizer+ with pytest.raises(ProxyException) as missing_key:+ await token_counter(+ request=TokenCountRequest(+ model="gpt-test",+ messages=[{"role": "user", "content": "hello"}],+ ),+ call_endpoint=True,+ )+ assert missing_key.value.code == "401"+ assert "No OpenAI API key is set for model gpt-test" in missing_key.value.message@pytest.mark.asyncio@@ -352,12 +346,14 @@ async def test_anthropic_endpoint_error_handling():"""from unittest.mock import MagicMock- from fastapi import HTTPException, Request+ from fastapi import Requestfrom litellm.proxy.anthropic_endpoints.endpoints import count_tokens# Mock request objectmock_request = MagicMock(spec=Request)+ mock_request.headers = {}+ mock_request.scope = {}mock_user_api_key_dict = MagicMock()# Test missing model parameter@@ -375,12 +371,13 @@ async def test_anthropic_endpoint_error_handling():anthropic_endpoints.read_request_body = mock_read_request_bodytry:- # Should raise HTTPException for missing model- with pytest.raises(HTTPException) as exc_info:- await count_tokens(mock_request, mock_user_api_key_dict)+ response = await count_tokens(mock_request, mock_user_api_key_dict)- assert exc_info.value.status_code == 400- assert "model parameter is required" in str(exc_info.value.detail)+ assert response.status_code == 400+ assert json.loads(response.body) == {+ "type": "error",+ "error": {"type": "invalid_request_error", "message": "model parameter is required"},+ }print("✅ Error handling test passed!")@@ -471,7 +468,7 @@ async def test_factory_gpt4_endpoint_does_not_call_anthropic_counter():mock_router.model_list = [{"model_name": "gpt-4",- "litellm_params": {"model": "openai/gpt-4"},+ "litellm_params": {"model": "databricks/gpt-4"},"model_info": {},}]@@ -480,7 +477,7 @@ async def test_factory_gpt4_endpoint_does_not_call_anthropic_counter():mock_router.async_get_available_deployment = AsyncMock(return_value={"model_name": "gpt-4",- "litellm_params": {"model": "openai/gpt-4"},+ "litellm_params": {"model": "databricks/gpt-4"},"model_info": {},})