mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-30 01:08:33 +00:00
* fix(count_tokens): apply context_management edits in the Gemini /v1/messages/count_tokens count /v1/messages runs clear_tool_uses context edits before it sends an Anthropic body to a Gemini or Vertex AI deployment, but /v1/messages/count_tokens counted the body unedited, so a request with older tool results cleared counted about 2.8x what inference bills. The count now runs the same history and context-edit step inference runs, honors additional_drop_params on the deployment, and skips compact edits so a count never makes a paid summary call. * fix(count_tokens): match the Gemini count to inference for compact edits and drop opt-outs Run compact edits in the count without the summary call so trigger checks and history slicing match /v1/messages, honor a request-level additional_drop_params, keep the full body when any deployment in the model group drops context_management, and answer 400 naming a block Gemini cannot count when an edit trigger fails on it * fix(count_tokens): count the unedited body when an edit fails and honor deployment ids in the drop check * fix(count_tokens): log a failed edit in the count at debug, since the send already logs it * fix(count_tokens): resolve a deployment id before wildcard routes in the drop check, as the router does * fix(count_tokens): honor the router-wide additional_drop_params opt-out in the drop check The router merges default_litellm_params between the deployment and the request, so a router-wide context_management opt-out makes /v1/messages send the full history. The count now reads it in the same order. Adds the audit's wire tests for the count's context edits. * fix(count_tokens): read the opt-out of a deployment the router serves by its litellm model name * fix(count_tokens): read the opt-out and drop_params from the deployments the router and completion_model send to * fix(messages): drop an invalid context_management spec under drop_params so the send matches the count * fix(count_tokens): give Claude Code and Codex counts the drop_params default /v1/messages gives them The proxy turns on drop_params for Claude Code and Codex user agents on /v1/messages. The count now applies the same default, so an invalid context_management spec drops on both endpoints instead of the count answering 400 while the send answers 200. The wire test also covers default_fallbacks, model_group_alias, and completion_model routes. * test(count_tokens): cover a coding agent that turns drop_params off and stop two count tests running as Claude Code
427 lines
14 KiB
Python
427 lines
14 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import os
|
|
import random
|
|
import traceback
|
|
from collections import defaultdict
|
|
from collections.abc import Callable
|
|
from typing import Final, Literal
|
|
|
|
import pytest
|
|
|
|
import litellm
|
|
from litellm import Router
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_wildcard_openai_routing():
|
|
"""
|
|
Initialize router with *, all models go through * and use OPENAI_API_KEY
|
|
"""
|
|
try:
|
|
model_list = [
|
|
{
|
|
"model_name": "*",
|
|
"litellm_params": {
|
|
"model": "openai/*",
|
|
"api_key": os.getenv("OPENAI_API_KEY"),
|
|
},
|
|
"tpm": 100,
|
|
},
|
|
]
|
|
|
|
router = Router(
|
|
model_list=model_list,
|
|
)
|
|
|
|
messages = [
|
|
{"content": "Tell me a joke.", "role": "user"},
|
|
]
|
|
|
|
selection_counts = defaultdict(int)
|
|
for _ in range(25):
|
|
response = await router.acompletion(
|
|
model="gpt-4",
|
|
messages=messages,
|
|
mock_response="good morning",
|
|
)
|
|
# print("response1", response)
|
|
|
|
selection_counts[response["model"]] += 1
|
|
|
|
response = await router.acompletion(
|
|
model="gpt-3.5-turbo",
|
|
messages=messages,
|
|
mock_response="good morning",
|
|
)
|
|
# print("response2", response)
|
|
|
|
selection_counts[response["model"]] += 1
|
|
|
|
response = await router.acompletion(
|
|
model="gpt-4-turbo-preview",
|
|
messages=messages,
|
|
mock_response="good morning",
|
|
)
|
|
# print("response3", response)
|
|
|
|
# print("response", response)
|
|
|
|
selection_counts[response["model"]] += 1
|
|
|
|
assert selection_counts["gpt-4"] == 25
|
|
assert selection_counts["gpt-3.5-turbo"] == 25
|
|
assert selection_counts["gpt-4-turbo-preview"] == 25
|
|
|
|
except Exception as e:
|
|
pytest.fail(f"Error occurred: {e}")
|
|
|
|
|
|
def test_get_available_deployment_for_pass_through():
|
|
"""
|
|
Test get_available_deployment_for_pass_through function
|
|
- Tests that only deployments with use_in_pass_through=True are returned
|
|
- Tests that BadRequestError is raised when no pass-through deployments exist
|
|
"""
|
|
try:
|
|
litellm.set_verbose = False
|
|
model_list = [
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "gpt-3.5-turbo",
|
|
"api_key": os.getenv("OPENAI_API_KEY"),
|
|
"use_in_pass_through": True,
|
|
},
|
|
},
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "azure/gpt-4.1-mini",
|
|
"api_key": os.getenv("AZURE_API_KEY"),
|
|
"api_base": os.getenv("AZURE_API_BASE"),
|
|
"api_version": os.getenv("AZURE_API_VERSION"),
|
|
"use_in_pass_through": False,
|
|
},
|
|
},
|
|
]
|
|
router = Router(
|
|
model_list=model_list,
|
|
)
|
|
|
|
# Test that only pass-through deployment is returned
|
|
selected_model = router.get_available_deployment_for_pass_through("gpt-3.5-turbo")
|
|
assert selected_model["litellm_params"]["model"] == "gpt-3.5-turbo"
|
|
assert selected_model["litellm_params"]["use_in_pass_through"] is True
|
|
|
|
router.reset()
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
pytest.fail(f"Error occurred: {e}")
|
|
|
|
|
|
def test_get_available_deployment_for_pass_through_no_deployments():
|
|
"""
|
|
Test get_available_deployment_for_pass_through raises BadRequestError
|
|
when no deployments have use_in_pass_through=True
|
|
"""
|
|
try:
|
|
litellm.set_verbose = False
|
|
model_list = [
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "gpt-3.5-turbo",
|
|
"api_key": os.getenv("OPENAI_API_KEY"),
|
|
"use_in_pass_through": False,
|
|
},
|
|
},
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "azure/gpt-4.1-mini",
|
|
"api_key": os.getenv("AZURE_API_KEY"),
|
|
"api_base": os.getenv("AZURE_API_BASE"),
|
|
"api_version": os.getenv("AZURE_API_VERSION"),
|
|
"use_in_pass_through": False,
|
|
},
|
|
},
|
|
]
|
|
router = Router(
|
|
model_list=model_list,
|
|
)
|
|
|
|
# Test that BadRequestError is raised when no pass-through deployments exist
|
|
with pytest.raises(litellm.BadRequestError) as exc_info:
|
|
router.get_available_deployment_for_pass_through("gpt-3.5-turbo")
|
|
e = exc_info.value
|
|
assert "use_in_pass_through=True" in str(e)
|
|
|
|
router.reset()
|
|
except Exception as e:
|
|
if isinstance(e, litellm.BadRequestError):
|
|
pass # Expected error
|
|
else:
|
|
traceback.print_exc()
|
|
pytest.fail(f"Error occurred: {e}")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_get_available_deployment_for_pass_through():
|
|
"""
|
|
Test async_get_available_deployment_for_pass_through function
|
|
- Tests that only deployments with use_in_pass_through=True are returned
|
|
- Tests async version works correctly
|
|
"""
|
|
try:
|
|
litellm.set_verbose = False
|
|
model_list = [
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "gpt-3.5-turbo",
|
|
"api_key": os.getenv("OPENAI_API_KEY"),
|
|
"use_in_pass_through": True,
|
|
},
|
|
},
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "azure/gpt-4.1-mini",
|
|
"api_key": os.getenv("AZURE_API_KEY"),
|
|
"api_base": os.getenv("AZURE_API_BASE"),
|
|
"api_version": os.getenv("AZURE_API_VERSION"),
|
|
"use_in_pass_through": False,
|
|
},
|
|
},
|
|
]
|
|
router = Router(
|
|
model_list=model_list,
|
|
)
|
|
|
|
# Test that only pass-through deployment is returned
|
|
selected_model = await router.async_get_available_deployment_for_pass_through(
|
|
model="gpt-3.5-turbo", request_kwargs={}
|
|
)
|
|
assert selected_model["litellm_params"]["model"] == "gpt-3.5-turbo"
|
|
assert selected_model["litellm_params"]["use_in_pass_through"] is True
|
|
|
|
router.reset()
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
pytest.fail(f"Error occurred: {e}")
|
|
|
|
|
|
def test_filter_pass_through_deployments():
|
|
"""
|
|
Test _filter_pass_through_deployments function
|
|
- Tests that it correctly filters deployments with use_in_pass_through=True
|
|
"""
|
|
try:
|
|
litellm.set_verbose = False
|
|
model_list = [
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "gpt-3.5-turbo",
|
|
"api_key": os.getenv("OPENAI_API_KEY"),
|
|
"use_in_pass_through": True,
|
|
},
|
|
},
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "azure/gpt-4.1-mini",
|
|
"api_key": os.getenv("AZURE_API_KEY"),
|
|
"api_base": os.getenv("AZURE_API_BASE"),
|
|
"api_version": os.getenv("AZURE_API_VERSION"),
|
|
"use_in_pass_through": False,
|
|
},
|
|
},
|
|
{
|
|
"model_name": "gpt-3.5-turbo",
|
|
"litellm_params": {
|
|
"model": "azure/gpt-35-turbo",
|
|
"api_key": os.getenv("AZURE_API_KEY"),
|
|
"api_base": os.getenv("AZURE_API_BASE"),
|
|
"api_version": os.getenv("AZURE_API_VERSION"),
|
|
"use_in_pass_through": True,
|
|
},
|
|
},
|
|
]
|
|
router = Router(
|
|
model_list=model_list,
|
|
)
|
|
|
|
# Get all healthy deployments
|
|
healthy_deployments = router.get_model_list()
|
|
|
|
# Filter pass-through deployments
|
|
pass_through_deployments = router._filter_pass_through_deployments(healthy_deployments)
|
|
|
|
# Should only have 2 deployments with use_in_pass_through=True
|
|
assert len(pass_through_deployments) == 2
|
|
|
|
# Verify all returned deployments have use_in_pass_through=True
|
|
for deployment in pass_through_deployments:
|
|
assert deployment["litellm_params"]["use_in_pass_through"] is True
|
|
|
|
router.reset()
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
pytest.fail(f"Error occurred: {e}")
|
|
|
|
|
|
async def _weighted_async_deployment_ids(router: Router) -> tuple[str, ...]:
|
|
random.seed(2025)
|
|
deployments: Final = tuple(
|
|
[
|
|
await router.async_get_available_deployment(model="shared", messages=None, request_kwargs={})
|
|
for _ in range(1000)
|
|
]
|
|
)
|
|
return tuple(deployment["model_info"]["id"] for deployment in deployments)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("metric", "placement", "async_selection"),
|
|
[
|
|
pytest.param("rpm", "deployment", False, id="rpm-deployment"),
|
|
pytest.param("rpm", "deployment", True, id="rpm-async"),
|
|
pytest.param("rpm", "router", False, id="rpm-router"),
|
|
pytest.param("tpm", "deployment", False, id="tpm-deployment"),
|
|
pytest.param("tpm", "router", False, id="tpm-router"),
|
|
],
|
|
)
|
|
def test_weighted_selection_router(
|
|
metric: Literal["rpm", "tpm"],
|
|
placement: Literal["deployment", "router"],
|
|
async_selection: bool,
|
|
) -> None:
|
|
random.seed(2025)
|
|
low_limit, high_limit = (6, 1440) if metric == "rpm" else (5, 90)
|
|
low_params: Final = {"model": "openai/low", "api_key": "test-key"} | (
|
|
{metric: low_limit} if placement == "deployment" else {}
|
|
)
|
|
high_params: Final = {"model": "openai/high", "api_key": "test-key"} | (
|
|
{metric: high_limit} if placement == "deployment" else {}
|
|
)
|
|
low_deployment: Final = {
|
|
"model_name": "shared",
|
|
"litellm_params": low_params,
|
|
"model_info": {"id": "low"},
|
|
} | ({metric: low_limit} if placement == "router" else {})
|
|
high_deployment: Final = {
|
|
"model_name": "shared",
|
|
"litellm_params": high_params,
|
|
"model_info": {"id": "high"},
|
|
} | ({metric: high_limit} if placement == "router" else {})
|
|
router: Final = Router(model_list=[low_deployment, high_deployment])
|
|
selected_ids: Final = (
|
|
asyncio.run(_weighted_async_deployment_ids(router))
|
|
if async_selection
|
|
else tuple(router.get_available_deployment("shared")["model_info"]["id"] for _ in range(1000))
|
|
)
|
|
|
|
assert selected_ids.count("high") / len(selected_ids) > 0.89
|
|
|
|
|
|
def test_weighted_selection_router_no_rpm_set() -> None:
|
|
router: Final = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "shared",
|
|
"litellm_params": {"model": "openai/low", "api_key": "test-key"},
|
|
"model_info": {"id": "low"},
|
|
},
|
|
{
|
|
"model_name": "shared",
|
|
"litellm_params": {"model": "openai/high", "api_key": "test-key"},
|
|
"model_info": {"id": "high"},
|
|
},
|
|
{
|
|
"model_name": "unrelated",
|
|
"litellm_params": {"model": "openai/unrelated", "api_key": "test-key"},
|
|
"model_info": {"id": "unrelated"},
|
|
},
|
|
]
|
|
)
|
|
selected_ids: Final = tuple(router.get_available_deployment("shared")["model_info"]["id"] for _ in range(100))
|
|
|
|
assert set(selected_ids) == {"low", "high"}
|
|
|
|
|
|
def test_model_group_aliases_select_the_target_group() -> None:
|
|
router: Final = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "target",
|
|
"litellm_params": {"model": "openai/target", "api_key": "test-key"},
|
|
"model_info": {"id": "target-deployment"},
|
|
}
|
|
],
|
|
model_group_alias={"alias": "target"},
|
|
)
|
|
deployment: Final = router.get_available_deployment("alias")
|
|
|
|
assert deployment["model_name"] == "target"
|
|
assert deployment["model_info"]["id"] == "target-deployment"
|
|
|
|
|
|
_ROUTABLE_MODEL_LIST: Final = [
|
|
{
|
|
"model_name": "shared",
|
|
"litellm_params": {"model": "openai/shared-low", "api_key": "test-key"},
|
|
"model_info": {"id": "low"},
|
|
},
|
|
{
|
|
"model_name": "shared",
|
|
"litellm_params": {"model": "openai/shared-high", "api_key": "test-key"},
|
|
"model_info": {"id": "high"},
|
|
},
|
|
{
|
|
"model_name": "unrelated",
|
|
"litellm_params": {"model": "openai/unrelated", "api_key": "test-key"},
|
|
"model_info": {"id": "unrelated"},
|
|
},
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("requested_model", "make_router", "expected_ids"),
|
|
(
|
|
("shared", lambda: Router(model_list=_ROUTABLE_MODEL_LIST), {"low", "high"}),
|
|
("high", lambda: Router(model_list=_ROUTABLE_MODEL_LIST), {"high"}),
|
|
("openai/unrelated", lambda: Router(model_list=_ROUTABLE_MODEL_LIST), {"unrelated"}),
|
|
(
|
|
"unknown",
|
|
lambda: Router(model_list=_ROUTABLE_MODEL_LIST, default_fallbacks=["shared"]),
|
|
{"low", "high"},
|
|
),
|
|
(
|
|
"alias",
|
|
lambda: Router(model_list=_ROUTABLE_MODEL_LIST, model_group_alias={"alias": "openai/unrelated"}),
|
|
{"unrelated"},
|
|
),
|
|
("unknown", lambda: Router(model_list=_ROUTABLE_MODEL_LIST), set()),
|
|
),
|
|
ids=(
|
|
"model-group",
|
|
"deployment-id",
|
|
"litellm-model-name",
|
|
"default-fallback",
|
|
"alias-to-a-litellm-model-name",
|
|
"unroutable",
|
|
),
|
|
)
|
|
def test_get_routable_deployments_returns_every_deployment_routing_can_pick(
|
|
requested_model: str, make_router: Callable[[], Router], expected_ids: set[str]
|
|
) -> None:
|
|
router: Final = make_router()
|
|
|
|
routable_ids: Final = {
|
|
deployment["model_info"]["id"] for deployment in router.get_routable_deployments(requested_model)
|
|
}
|
|
|
|
assert routable_ids == expected_ids
|