litellm/tests/unit/proxy/hooks/test_batch_rate_limiter.py

1196 lines
48 KiB
Python

"""
Tests for `tpd_limit` (tokens per day) enforcement on batch submissions.
A batch's rows are scheduled by the provider, so a caller cannot keep a large
batch under a per-minute RPM/TPM budget. Scopes that configure `tpd_limit`
are charged against a 24h token window instead of their minute counters.
"""
import base64
import json
import time
from collections.abc import Callable, Iterator, Sequence
from datetime import datetime, timezone
from typing import Final, Literal
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
import respx
from fastapi import HTTPException
from typing_extensions import ReadOnly, TypedDict
import litellm
from litellm import DualCache
from litellm.constants import BATCH_TPD_WINDOW_SECONDS
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.hooks.batch_rate_limiter import BatchFileUsage, PROXY_BatchRateLimiter
from litellm.proxy.hooks.parallel_request_limiter_v3 import (
PROJECT_ITPM_DESCRIPTOR_KEY,
PROXY_MaxParallelRequestsHandler_v3,
get_batch_rate_limiter,
run_scoped,
)
from litellm.proxy.utils import InternalUsageCache, hash_token
from litellm.redis.stores.rate_limits import RateLimitScope, RateLimitStore
from litellm.types.llms.openai import ChatCompletionUserMessage, LiteLLMBatchCreateRequest
from tests._support.rust_parallel_request_limiter import RustParallelRequestLimiter
class _Clock:
def __init__(self, start: datetime):
self.now = start
def __call__(self) -> datetime:
return self.now
def _make_limiters(clock: _Clock | None = None, rate_limit_store: RateLimitStore | None = None):
internal_usage_cache = InternalUsageCache(dual_cache=DualCache())
rate_limiter = PROXY_MaxParallelRequestsHandler_v3(
internal_usage_cache=internal_usage_cache, time_provider=clock, rate_limit_store=rate_limit_store
)
batch_limiter = get_batch_rate_limiter(rate_limiter)
assert batch_limiter is not None
return internal_usage_cache, rate_limiter, batch_limiter
async def _counter(internal_usage_cache, rate_limiter, descriptor_key, value, rate_limit_type):
(raw,) = rate_limiter.rate_limits.local((RateLimitScope(descriptor_key, value).counter(rate_limit_type),))
return int(raw or 0)
@pytest.mark.asyncio
async def test_batch_over_rpm_and_tpm_but_under_tpd_is_accepted():
internal_usage_cache, rate_limiter, batch_limiter = _make_limiters()
api_key = hash_token("tpd-key")
user_api_key_dict = UserAPIKeyAuth(api_key=api_key, rpm_limit=1, tpm_limit=10, tpd_limit=1000)
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict,
data={},
batch_usage=BatchFileUsage(total_tokens=500, request_count=50),
)
assert await _counter(internal_usage_cache, rate_limiter, "api_key_tpd", api_key, "tokens") == 500
assert await _counter(internal_usage_cache, rate_limiter, "api_key", api_key, "requests") == 0
assert await _counter(internal_usage_cache, rate_limiter, "api_key", api_key, "tokens") == 0
@pytest.mark.asyncio
async def test_cumulative_batch_tokens_over_tpd_returns_429_with_remaining_daily_window():
window_start = datetime(2026, 9, 13, 8, 0, 0, tzinfo=timezone.utc)
clock = _Clock(window_start)
_internal_usage_cache, _rate_limiter, batch_limiter = _make_limiters(clock)
user_api_key_dict = UserAPIKeyAuth(api_key=hash_token("tpd-key-2"), rpm_limit=1, tpd_limit=1000)
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict,
data={},
batch_usage=BatchFileUsage(total_tokens=600, request_count=6),
)
clock.now = datetime(2026, 9, 13, 11, 0, 0, tzinfo=timezone.utc)
with pytest.raises(HTTPException) as exc:
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict,
data={},
batch_usage=BatchFileUsage(total_tokens=600, request_count=6),
)
assert exc.value.status_code == 429
assert "api_key_tpd" in str(exc.value.detail)
assert "600 tokens but only 400 tokens remaining out of 1000 TPD limit" in str(exc.value.detail)
assert exc.value.headers["retry-after"] == str(BATCH_TPD_WINDOW_SECONDS - 3 * 3600)
assert exc.value.headers["reset_at"] == "2026-09-14 08:00:00 UTC"
def _make_native_limiter() -> tuple[InternalUsageCache, RustParallelRequestLimiter]:
internal_usage_cache: Final = InternalUsageCache(dual_cache=DualCache())
return internal_usage_cache, RustParallelRequestLimiter(internal_usage_cache=internal_usage_cache)
async def _submit_counted_batch(
monkeypatch: pytest.MonkeyPatch,
rate_limiter: RustParallelRequestLimiter,
user_api_key_dict: UserAPIKeyAuth,
usage: BatchFileUsage,
) -> None:
async def counted(*_: object, **__: object) -> BatchFileUsage:
return usage
monkeypatch.setattr(PROXY_BatchRateLimiter, "count_input_file_usage", counted)
await rate_limiter.async_pre_call_hook(
user_api_key_dict,
DualCache(),
{"model": _BATCH_MODEL, "input_file_id": "file-counted", "endpoint": "/v1/chat/completions"},
"acreate_batch",
)
@pytest.mark.asyncio
async def test_failed_batch_submission_refunds_tpd_tokens(monkeypatch: pytest.MonkeyPatch):
internal_usage_cache, rate_limiter = _make_native_limiter()
api_key = hash_token("tpd-refund-key")
user_api_key_dict = UserAPIKeyAuth(api_key=api_key, rpm_limit=1, tpd_limit=1000)
await _submit_counted_batch(
monkeypatch, rate_limiter, user_api_key_dict, BatchFileUsage(total_tokens=600, request_count=6)
)
await rate_limiter.async_post_call_failure_hook(
request_data={},
original_exception=RuntimeError("provider rejected the file"),
user_api_key_dict=user_api_key_dict,
)
assert await _counter(internal_usage_cache, rate_limiter, "api_key_tpd", api_key, "tokens") == 0
await _submit_counted_batch(
monkeypatch, rate_limiter, user_api_key_dict, BatchFileUsage(total_tokens=1000, request_count=10)
)
assert await _counter(internal_usage_cache, rate_limiter, "api_key_tpd", api_key, "tokens") == 1000
@pytest.mark.asyncio
async def test_tpd_refund_applies_once_and_only_to_daily_counters(monkeypatch: pytest.MonkeyPatch):
internal_usage_cache, rate_limiter = _make_native_limiter()
team_key = UserAPIKeyAuth(
api_key=hash_token("tpd-refund-team-key"),
rpm_limit=100,
tpm_limit=10_000,
team_id="team-r",
team_tpd_limit=5000,
)
await _submit_counted_batch(monkeypatch, rate_limiter, team_key, BatchFileUsage(total_tokens=800, request_count=8))
await rate_limiter.async_post_call_failure_hook(
request_data={}, original_exception=RuntimeError("boom"), user_api_key_dict=team_key
)
await rate_limiter.async_post_call_failure_hook(
request_data={}, original_exception=RuntimeError("boom"), user_api_key_dict=team_key
)
assert await _counter(internal_usage_cache, rate_limiter, "team_tpd", "team-r", "tokens") == 0
assert await _counter(internal_usage_cache, rate_limiter, "api_key", team_key.api_key, "tokens") == 800
assert await _counter(internal_usage_cache, rate_limiter, "api_key", team_key.api_key, "requests") == 8
@pytest.mark.asyncio
async def test_rejected_batch_leaves_nothing_to_refund():
internal_usage_cache, rate_limiter, batch_limiter = _make_limiters()
api_key = hash_token("tpd-rejected-key")
user_api_key_dict = UserAPIKeyAuth(api_key=api_key, tpd_limit=100)
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict, data={}, batch_usage=BatchFileUsage(total_tokens=90, request_count=9)
)
with pytest.raises(HTTPException):
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict, data={}, batch_usage=BatchFileUsage(total_tokens=20, request_count=2)
)
await rate_limiter.async_post_call_failure_hook(
request_data={}, original_exception=RuntimeError("429 bubbled up"), user_api_key_dict=user_api_key_dict
)
assert await _counter(internal_usage_cache, rate_limiter, "api_key_tpd", api_key, "tokens") == 90
@pytest.mark.asyncio
async def test_batch_without_tpd_still_enforces_minute_rpm():
_internal_usage_cache, _rate_limiter, batch_limiter = _make_limiters()
user_api_key_dict = UserAPIKeyAuth(api_key=hash_token("rpm-only-key"), rpm_limit=1, tpm_limit=1000)
with pytest.raises(HTTPException) as exc:
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict,
data={},
batch_usage=BatchFileUsage(total_tokens=50, request_count=5),
)
assert exc.value.status_code == 429
assert "RPM limit" in str(exc.value.detail)
@pytest.mark.asyncio
async def test_team_tpd_replaces_team_minute_limits_but_key_minute_limits_still_apply():
internal_usage_cache, rate_limiter, batch_limiter = _make_limiters()
team_key = UserAPIKeyAuth(
api_key=hash_token("team-key"),
team_id="team-1",
team_rpm_limit=1,
team_tpm_limit=10,
team_tpd_limit=5000,
)
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=team_key,
data={},
batch_usage=BatchFileUsage(total_tokens=800, request_count=8),
)
assert await _counter(internal_usage_cache, rate_limiter, "team_tpd", "team-1", "tokens") == 800
assert await _counter(internal_usage_cache, rate_limiter, "team", "team-1", "requests") == 0
key_rpm_in_team_with_tpd = UserAPIKeyAuth(
api_key=hash_token("team-key-2"),
rpm_limit=1,
team_id="team-1",
team_tpd_limit=5000,
)
with pytest.raises(HTTPException) as exc:
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=key_rpm_in_team_with_tpd,
data={},
batch_usage=BatchFileUsage(total_tokens=10, request_count=2),
)
assert exc.value.status_code == 429
assert "api_key:" in str(exc.value.detail)
assert "RPM limit" in str(exc.value.detail)
@pytest.mark.asyncio
async def test_end_user_tpd_is_enforced_per_end_user():
_internal_usage_cache, _rate_limiter, batch_limiter = _make_limiters()
first_customer = UserAPIKeyAuth(
api_key=hash_token("shared-key"), end_user_id="customer-a", end_user_rpm_limit=1, end_user_tpd_limit=100
)
second_customer = UserAPIKeyAuth(
api_key=hash_token("shared-key"), end_user_id="customer-b", end_user_rpm_limit=1, end_user_tpd_limit=100
)
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=first_customer, data={}, batch_usage=BatchFileUsage(total_tokens=90, request_count=9)
)
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=second_customer, data={}, batch_usage=BatchFileUsage(total_tokens=90, request_count=9)
)
with pytest.raises(HTTPException) as exc:
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=first_customer, data={}, batch_usage=BatchFileUsage(total_tokens=20, request_count=2)
)
assert exc.value.status_code == 429
assert "end_user_tpd: customer-a" in str(exc.value.detail)
@pytest.mark.asyncio
async def test_tpd_only_key_is_not_skipped_as_having_no_limits():
_internal_usage_cache, _rate_limiter, batch_limiter = _make_limiters()
descriptors = await batch_limiter._create_batch_rate_limit_descriptors(
user_api_key_dict=UserAPIKeyAuth(api_key=hash_token("tpd-only"), tpd_limit=100),
data={},
)
assert batch_limiter._has_applicable_batch_rate_limits(descriptors) is True
@pytest.mark.asyncio
async def test_online_descriptors_ignore_tpd_limit():
_internal_usage_cache, rate_limiter, _batch_limiter = _make_limiters()
api_key = hash_token("online-key")
scoped = await run_scoped(
rate_limiter,
UserAPIKeyAuth(api_key=api_key, rpm_limit=5, tpd_limit=100, team_id="t", team_tpd_limit=9),
{"model": "gpt-4o"},
{"kind": "request"},
{"kind": "build"},
)
descriptors = scoped.descriptors
assert [(d["key"], d["rate_limit"]["window_size"]) for d in descriptors] == [("api_key", rate_limiter.window_size)]
@pytest.fixture(params=["Europe/Paris", "Asia/Kolkata", "America/Los_Angeles"])
def process_timezone(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> Iterator[str]:
monkeypatch.setenv("TZ", request.param)
time.tzset()
yield request.param
monkeypatch.undo()
time.tzset()
@pytest.mark.skipif(not hasattr(time, "tzset"), reason="switching the process timezone needs time.tzset()")
@pytest.mark.asyncio
async def test_batch_rate_limit_error_reports_reset_time_in_utc_on_a_non_utc_proxy(process_timezone: str) -> None:
window_start: Final = datetime(2026, 9, 13, 8, 0, 0, tzinfo=timezone.utc)
clock: Final = _Clock(window_start)
_internal_usage_cache, _rate_limiter, batch_limiter = _make_limiters(clock)
user_api_key_dict: Final = UserAPIKeyAuth(api_key=hash_token("tpd-key-utc"), rpm_limit=1, tpd_limit=1000)
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict,
data={},
batch_usage=BatchFileUsage(total_tokens=600, request_count=6),
)
clock.now = datetime(2026, 9, 13, 11, 0, 0, tzinfo=timezone.utc)
with pytest.raises(HTTPException) as exc:
await batch_limiter._check_and_increment_batch_counters(
user_api_key_dict=user_api_key_dict,
data={},
batch_usage=BatchFileUsage(total_tokens=600, request_count=6),
)
assert exc.value.status_code == 429
assert exc.value.headers["retry-after"] == str(BATCH_TPD_WINDOW_SECONDS - 3 * 3600)
assert exc.value.headers["reset_at"] == "2026-09-14 08:00:00 UTC"
assert str(exc.value.detail).endswith("Limit resets at: 2026-09-14 08:00:00 UTC")
_BATCH_MODEL: Final = "gpt-3.5-turbo"
_MANAGED_DEPLOYMENT_ALIAS: Final = "managed-deployment-alias"
_MANAGED_FILE_ID: Final = (
"bGl0ZWxsbV9wcm94eTphcHBsaWNhdGlvbi9vY3RldC1zdHJlYW07dW5pZmllZF9pZCxyZWdyZXNzaW9uLXRlc3QtZmlsZQ=="
)
class _BatchBody(TypedDict):
model: ReadOnly[str]
messages: ReadOnly[Sequence[ChatCompletionUserMessage]]
class _BatchLine(TypedDict):
custom_id: ReadOnly[str]
method: ReadOnly[Literal["POST"]]
url: ReadOnly[Literal["/v1/chat/completions"]]
body: ReadOnly[_BatchBody]
@pytest.fixture
def openai_files(monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter) -> respx.MockRouter:
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
return respx_mock
def _batch_rows(messages: Sequence[str]) -> tuple[_BatchLine, ...]:
return tuple(
_BatchLine(
custom_id=f"request-{i}",
method="POST",
url="/v1/chat/completions",
body=_BatchBody(model=_BATCH_MODEL, messages=(ChatCompletionUserMessage(role="user", content=message),)),
)
for i, message in enumerate(messages, start=1)
)
def _serve_file(router: respx.MockRouter, file_id: str, rows: Sequence[_BatchLine]) -> respx.Route:
jsonl: Final = "\n".join(json.dumps(row) for row in rows)
return router.get(f"https://api.openai.com/v1/files/{file_id}/content").mock(
return_value=httpx.Response(200, content=jsonl.encode())
)
def _token_counter_total(rows: Sequence[_BatchLine]) -> int:
return sum(litellm.token_counter(model=row["body"]["model"], messages=row["body"]["messages"]) for row in rows)
def _create_batch_data(input_file_id: str) -> LiteLLMBatchCreateRequest:
return LiteLLMBatchCreateRequest(model=_BATCH_MODEL, input_file_id=input_file_id)
@pytest.mark.asyncio
async def test_count_input_file_usage_matches_token_counter(openai_files: respx.MockRouter):
_, _, batch_limiter = _make_limiters()
rows: Final = _batch_rows(("Hello", "Hi there", "Hey"))
content_route: Final = _serve_file(openai_files, "file-abc123", rows)
usage: Final = await batch_limiter.count_input_file_usage(file_id="file-abc123", custom_llm_provider="openai")
assert content_route.call_count == 1
assert usage.request_count == 3
assert usage.total_tokens == _token_counter_total(rows)
@pytest.mark.asyncio
async def test_batch_rate_limit_single_file_under_and_over_tpm(openai_files: respx.MockRouter):
small_rows: Final = _batch_rows(("Hello", "Hi", "Hey"))
big_rows: Final = _batch_rows(
("This is a longer message that will consume more tokens from the rate limit. " * 100,) * 3
)
_serve_file(openai_files, "file-small", small_rows)
_serve_file(openai_files, "file-big", big_rows)
user_api_key_dict: Final = UserAPIKeyAuth(api_key="test-key-123", tpm_limit=200, rpm_limit=10)
_, _, small_limiter = _make_limiters()
data_small: Final = dict(_create_batch_data("file-small"))
result: Final = await small_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=DualCache(),
data=data_small,
call_type="acreate_batch",
)
assert result is data_small
assert data_small["_batch_token_count"] == _token_counter_total(small_rows)
assert data_small["_batch_request_count"] == 3
_, _, big_limiter = _make_limiters()
with pytest.raises(HTTPException) as exc_info:
await big_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=DualCache(),
data=dict(_create_batch_data("file-big")),
call_type="acreate_batch",
)
assert exc_info.value.status_code == 429
assert "tokens" in str(exc_info.value.detail).lower()
@pytest.mark.asyncio
async def test_batch_rate_limit_cumulative_tpm_rejects_second_request(openai_files: respx.MockRouter):
_, _, batch_limiter = _make_limiters()
user_api_key_dict: Final = UserAPIKeyAuth(api_key="test-key-456", tpm_limit=200, rpm_limit=10)
first_rows: Final = _batch_rows(("This message has some content to reach about 100 tokens total. " * 4,) * 2)
second_rows: Final = _batch_rows(
("This is another message with more content to exceed the remaining limit. " * 11,) * 2
)
_serve_file(openai_files, "file-1", first_rows)
_serve_file(openai_files, "file-2", second_rows)
first_tokens: Final = _token_counter_total(first_rows)
assert first_tokens <= 200 < first_tokens + _token_counter_total(second_rows)
first_data: Final = dict(_create_batch_data("file-1"))
first_result: Final = await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=DualCache(),
data=first_data,
call_type="acreate_batch",
)
assert first_result is first_data
assert first_data["_batch_token_count"] == first_tokens
with pytest.raises(HTTPException) as exc_info:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=DualCache(),
data=dict(_create_batch_data("file-2")),
call_type="acreate_batch",
)
assert exc_info.value.status_code == 429
assert "tokens" in str(exc_info.value.detail).lower()
@pytest.mark.asyncio
async def test_batch_rate_limiter_reads_a_provider_file_with_user_context(openai_files: respx.MockRouter):
_, _, batch_limiter = _make_limiters()
user_api_key_dict: Final = UserAPIKeyAuth(
api_key="test-key-managed-files", user_id="test-user-abc123", tpm_limit=500, rpm_limit=10
)
rows: Final = _batch_rows(("This is a test message for batch rate limiting with managed files. " * 5,) * 3)
content_route: Final = _serve_file(openai_files, "file-abc123", rows)
data: Final = dict(_create_batch_data("file-abc123"))
result: Final = await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=DualCache(),
data=data,
call_type="acreate_batch",
)
assert content_route.call_count == 1
assert result is data
assert data["_batch_token_count"] == _token_counter_total(rows)
assert data["_batch_request_count"] == 3
@pytest.mark.asyncio
async def test_batch_rate_limiter_without_user_context(openai_files: respx.MockRouter):
_, _, batch_limiter = _make_limiters()
rows: Final = _batch_rows(("Hello",))
content_route: Final = _serve_file(openai_files, "file-abc123", rows)
usage_without_context: Final = await batch_limiter.count_input_file_usage(
file_id="file-abc123", custom_llm_provider="openai", user_api_key_dict=None
)
usage_with_context: Final = await batch_limiter.count_input_file_usage(
file_id="file-abc123",
custom_llm_provider="openai",
user_api_key_dict=UserAPIKeyAuth(api_key="test-key", user_id="test-user-123"),
)
assert content_route.call_count == 2
assert usage_without_context.request_count == usage_with_context.request_count == 1
assert usage_without_context.total_tokens == usage_with_context.total_tokens == _token_counter_total(rows)
@pytest.mark.asyncio
async def test_batch_input_without_a_model_is_read_through_the_team_deployment(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
from litellm import Router
from litellm.proxy import proxy_server
monkeypatch.setattr(
proxy_server,
"llm_router",
Router(
model_list=[
{
"model_name": "openai/*",
"litellm_params": {
"model": "openai/*",
"api_key": "sk-team",
"api_base": "https://team.example/v1",
},
"model_info": {"id": "team-openai", "team_id": "team-1"},
}
]
),
)
_, _, batch_limiter = _make_limiters()
rows: Final = _batch_rows(("Hello",))
environment_route: Final = _serve_file(openai_files, "file-abc123", rows)
team_route: Final = openai_files.get("https://team.example/v1/files/file-abc123/content").mock(
return_value=httpx.Response(200, content="\n".join(json.dumps(row) for row in rows).encode())
)
team_key: Final = UserAPIKeyAuth(api_key="sk", team_id="team-1", team_models=["openai/*"], models=[_BATCH_MODEL])
teamless_key: Final = UserAPIKeyAuth(api_key="sk")
team_usage: Final = await batch_limiter.count_input_file_usage(
file_id="file-abc123", custom_llm_provider="openai", user_api_key_dict=team_key, data={}
)
teamless_usage: Final = await batch_limiter.count_input_file_usage(
file_id="file-abc123", custom_llm_provider="openai", user_api_key_dict=teamless_key, data={}
)
assert team_route.call_count == 1
assert team_route.calls.last.request.headers["authorization"] == "Bearer sk-team"
assert environment_route.call_count == 1
assert environment_route.calls.last.request.headers["authorization"] == "Bearer sk-test"
assert team_usage.total_tokens == teamless_usage.total_tokens == _token_counter_total(rows)
forwarded_usage: Final = await batch_limiter.count_input_file_usage(
file_id="file-abc123",
custom_llm_provider="openai",
user_api_key_dict=team_key,
data={"api_key": "sk-forwarded"},
)
assert team_route.call_count == 2
assert team_route.calls.last.request.headers["authorization"] == "Bearer sk-forwarded"
assert environment_route.call_count == 1
assert forwarded_usage.total_tokens == _token_counter_total(rows)
_ROUTED_FILE_URL: Final = "https://routed.example/v1/files/file-abc123/content"
def _serve_file_to_the_deployment_key(rows: Sequence[_BatchLine]) -> Callable[[httpx.Request], httpx.Response]:
jsonl: Final = "\n".join(json.dumps(row) for row in rows).encode()
def respond(request: httpx.Request) -> httpx.Response:
if request.headers.get("authorization") != "Bearer sk-deployment":
return httpx.Response(401, json={"error": {"message": "Incorrect API key provided"}})
return httpx.Response(200, content=jsonl)
return respond
async def _model_routed_batch_data(
openai_files: respx.MockRouter,
monkeypatch: pytest.MonkeyPatch,
query_string: bytes,
routing_headers: tuple[tuple[bytes, bytes], ...],
user_api_key_dict: UserAPIKeyAuth,
) -> tuple[dict[str, object], respx.Route]:
from starlette.requests import Request
from litellm import Router
from litellm.proxy import proxy_server
from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
monkeypatch.setattr(
proxy_server,
"llm_router",
Router(
model_list=[
{
"model_name": "routed-batch-model",
"litellm_params": {
"model": f"openai/{_BATCH_MODEL}",
"api_key": "sk-deployment",
"api_base": "https://routed.example/v1",
},
"model_info": {"id": "routed-batch-deployment"},
}
]
),
)
file_route: Final = openai_files.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key(_batch_rows(("Hello " * 50,)))
)
request: Final = Request(
{
"type": "http",
"method": "POST",
"path": "/v1/batches",
"raw_path": b"/v1/batches",
"root_path": "",
"scheme": "http",
"server": ("proxy.test", 80),
"client": ("127.0.0.1", 50000),
"query_string": query_string,
"headers": [(b"content-type", b"application/json"), *routing_headers],
}
)
data: Final = await add_litellm_data_to_request(
data={
"input_file_id": "file-abc123",
"endpoint": "/v1/chat/completions",
"completion_window": "24h",
"api_key": "sk-not-the-deployment-key",
},
request=request,
user_api_key_dict=user_api_key_dict,
proxy_config=MagicMock(),
general_settings={},
)
return data, file_route
_MODEL_ROUTES: Final = pytest.mark.parametrize(
"query_string, routing_headers",
[(b"model=routed-batch-model", ()), (b"", ((b"x-litellm-model", b"routed-batch-model"),))],
ids=["query", "header"],
)
@pytest.mark.asyncio
@_MODEL_ROUTES
async def test_model_routed_batch_is_counted_with_the_deployment_key_not_the_request_key(
openai_files: respx.MockRouter,
monkeypatch: pytest.MonkeyPatch,
query_string: bytes,
routing_headers: tuple[tuple[bytes, bytes], ...],
):
user_api_key_dict: Final = UserAPIKeyAuth(api_key=hash_token("sk-batch"), tpm_limit=1)
data, file_route = await _model_routed_batch_data(
openai_files, monkeypatch, query_string, routing_headers, user_api_key_dict
)
_, _, batch_limiter = _make_limiters()
with pytest.raises(HTTPException) as exc:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict, cache=DualCache(), data=data, call_type="acreate_batch"
)
assert exc.value.status_code == 429
assert file_route.call_count == 1
@pytest.mark.asyncio
@_MODEL_ROUTES
async def test_model_routed_batch_is_charged_to_the_project_cap_of_the_model_it_routes_to(
openai_files: respx.MockRouter,
monkeypatch: pytest.MonkeyPatch,
query_string: bytes,
routing_headers: tuple[tuple[bytes, bytes], ...],
):
user_api_key_dict: Final = UserAPIKeyAuth(
api_key=hash_token("sk-batch"),
project_id="project-1",
project_metadata={"model_batch_enqueued_token_limit": {"routed-batch-model": 1}},
)
data, _ = await _model_routed_batch_data(
openai_files, monkeypatch, query_string, routing_headers, user_api_key_dict
)
_, _, batch_limiter = _make_limiters()
with pytest.raises(HTTPException) as exc:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict, cache=DualCache(), data=data, call_type="acreate_batch"
)
assert exc.value.status_code == 429
assert "project_model: project-1:routed-batch-model" in str(exc.value.detail)
async def _install_managed_file_hook(
openai_files: respx.MockRouter,
monkeypatch: pytest.MonkeyPatch,
rows: Sequence[_BatchLine],
file_id: str = _MANAGED_FILE_ID,
model_name: str = _BATCH_MODEL,
) -> tuple[respx.Route, respx.Route]:
from litellm_enterprise.proxy.hooks.managed_files import _PROXY_LiteLLMManagedFiles
from litellm import Router
from litellm.models.managed_files import LiteLLM_ManagedFileTable
from litellm.proxy import proxy_server
from litellm.proxy.openai_files_endpoints.common_utils import is_base64_encoded_unified_file_id
from litellm.proxy.utils import ProxyLogging
assert is_base64_encoded_unified_file_id(file_id)
provider_route: Final = _serve_file(openai_files, "file-provider-1", rows)
unrouted_managed_read: Final = _serve_file(openai_files, file_id, rows)
row: Final = LiteLLM_ManagedFileTable(
unified_file_id=file_id,
model_mappings={"deployment-1": "file-provider-1"},
flat_model_file_ids=["file-provider-1"],
created_by="test-user-regression",
team_id="team-owner",
)
file_cache: Final = InternalUsageCache(dual_cache=DualCache())
await file_cache.async_set_cache(key=file_id, value=row.model_dump(), litellm_parent_otel_span=None)
prisma_client: Final = MagicMock()
prisma_client.db.litellm_managedfiletable.find_first = AsyncMock(return_value=row)
proxy_logging: Final = ProxyLogging(user_api_key_cache=DualCache())
proxy_logging.proxy_hook_mapping["managed_files"] = _PROXY_LiteLLMManagedFiles(
internal_usage_cache=file_cache, prisma_client=prisma_client
)
router: Final = Router(
model_list=[
{
"model_name": model_name,
"litellm_params": {"model": f"openai/{_BATCH_MODEL}", "api_key": "sk-test"},
"model_info": {"id": "deployment-1"},
},
{
"model_name": _MANAGED_DEPLOYMENT_ALIAS,
"litellm_params": {"model": f"openai/{_BATCH_MODEL}", "api_key": "sk-test"},
"model_info": {"id": "deployment-1-alias"},
},
]
)
monkeypatch.setattr(proxy_server, "proxy_logging_obj", proxy_logging)
monkeypatch.setattr(proxy_server, "llm_router", router)
return provider_route, unrouted_managed_read
@pytest.mark.asyncio
async def test_a_managed_batch_file_charges_only_the_project_cap_of_the_model_it_routes_to(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
from litellm.proxy.hooks.parallel_request_limiter_v3 import get_request_stash
priority_group: Final = f"{_BATCH_MODEL}-priority"
managed_file_id: Final = base64.urlsafe_b64encode(
f"litellm_proxy:application/octet-stream;unified_id,priority-batch;target_model_names,{priority_group}".encode()
).decode()
await _install_managed_file_hook(
openai_files, monkeypatch, _batch_rows(("Hello",) * 3), file_id=managed_file_id, model_name=priority_group
)
_, _, batch_limiter = _make_limiters()
data: Final = {"input_file_id": managed_file_id}
result: Final = await batch_limiter.async_pre_call_hook(
user_api_key_dict=UserAPIKeyAuth(
api_key="test-key-regression",
user_id="test-user-regression",
team_id="team-owner",
project_id="priority-project",
project_metadata={"model_batch_enqueued_token_limit": {priority_group: 1000000, _BATCH_MODEL: 1}},
),
cache=DualCache(),
data=data,
call_type="acreate_batch",
)
assert result is data
stash: Final = get_request_stash()
assert stash is not None and stash.batch_enqueued_reservation is not None
assert [scope.value for scope in stash.batch_enqueued_reservation.scopes] == [f"priority-project:{priority_group}"]
@pytest.mark.asyncio
async def test_a_project_cap_on_the_routed_model_lifts_per_minute_limits_off_a_managed_batch_file(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
priority_group: Final = f"{_BATCH_MODEL}-priority"
managed_file_id: Final = base64.urlsafe_b64encode(
f"litellm_proxy:application/octet-stream;unified_id,priority-minute;target_model_names,{priority_group}".encode()
).decode()
await _install_managed_file_hook(
openai_files, monkeypatch, _batch_rows(("Hello",) * 3), file_id=managed_file_id, model_name=priority_group
)
_, _, batch_limiter = _make_limiters()
data: Final = {"input_file_id": managed_file_id}
result: Final = await batch_limiter.async_pre_call_hook(
user_api_key_dict=UserAPIKeyAuth(
api_key="test-key-regression",
user_id="test-user-regression",
team_id="team-owner",
tpm_limit=1,
project_id="priority-project",
project_metadata={"model_batch_enqueued_token_limit": {priority_group: 1000000}},
),
cache=DualCache(),
data=data,
call_type="acreate_batch",
)
assert result is data
@pytest.mark.asyncio
async def test_managed_file_is_read_through_the_managed_files_hook_with_user_context(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
rows: Final = _batch_rows(("Test message for regression",))
provider_route, unrouted_managed_read = await _install_managed_file_hook(openai_files, monkeypatch, rows)
standard_route: Final = _serve_file(openai_files, "file-abc123", rows)
_, _, batch_limiter = _make_limiters()
user_api_key_dict: Final = UserAPIKeyAuth(
api_key="test-key-regression", user_id="test-user-regression", tpm_limit=1000, rpm_limit=10
)
managed_usage: Final = await batch_limiter.count_input_file_usage(
file_id=_MANAGED_FILE_ID, custom_llm_provider="openai", user_api_key_dict=user_api_key_dict
)
standard_usage: Final = await batch_limiter.count_input_file_usage(
file_id="file-abc123", custom_llm_provider="openai", user_api_key_dict=user_api_key_dict
)
assert provider_route.call_count == 1
assert standard_route.call_count == 1
assert not unrouted_managed_read.called
assert managed_usage.request_count == standard_usage.request_count == 1
assert managed_usage.total_tokens == standard_usage.total_tokens == _token_counter_total(rows)
@pytest.mark.asyncio
async def test_managed_file_of_another_tenant_is_denied_before_it_is_read(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
rows: Final = _batch_rows(("Test message for regression",))
provider_route, unrouted_managed_read = await _install_managed_file_hook(openai_files, monkeypatch, rows)
_, _, batch_limiter = _make_limiters()
outsider: Final = UserAPIKeyAuth(api_key="test-key-outsider", user_id="outsider", team_id="team-other", tpm_limit=1)
with pytest.raises(HTTPException) as denied:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=outsider,
cache=DualCache(),
data=dict(_create_batch_data(_MANAGED_FILE_ID)),
call_type="acreate_batch",
)
assert denied.value.status_code == 403
assert not provider_route.called
assert not unrouted_managed_read.called
_BATCH_ALIAS: Final = "nano-batch-alias"
_DEPLOYMENT_MODEL: Final = "nano-deployment-model"
def _row_naming(model: str) -> _BatchLine:
return _BatchLine(
custom_id=model,
method="POST",
url="/v1/chat/completions",
body=_BatchBody(model=model, messages=(ChatCompletionUserMessage(role="user", content="hi"),)),
)
def _alias_router(model_group_alias: dict[str, str]) -> litellm.Router:
return litellm.Router(
model_list=[
{
"model_name": _BATCH_ALIAS,
"litellm_params": {
"model": f"openai/{_DEPLOYMENT_MODEL}",
"api_key": "sk-deployment",
"api_base": "https://routed.example/v1",
},
"model_info": {"id": "alias-deployment"},
}
],
model_group_alias=model_group_alias,
)
@pytest.fixture
def alias_routed_batch(openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch) -> respx.MockRouter:
from litellm.proxy import proxy_server
monkeypatch.setattr(proxy_server, "llm_router", _alias_router({}))
return openai_files
def _alias_routing(route: Literal["file id", "body"]) -> dict[str, str]:
from litellm.proxy.openai_files_endpoints.common_utils import encode_file_id_with_model
if route == "file id":
return {"input_file_id": encode_file_id_with_model("file-abc123", _BATCH_ALIAS)}
return {"input_file_id": "file-abc123", "model": _BATCH_ALIAS}
@pytest.mark.asyncio
@pytest.mark.parametrize("route", ["file id", "body"])
async def test_key_granted_only_the_alias_can_batch_rows_naming_its_deployment_model(
alias_routed_batch: respx.MockRouter, route: Literal["file id", "body"]
):
alias_routed_batch.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_DEPLOYMENT_MODEL),))
)
data: Final = _alias_routing(route)
_, _, batch_limiter = _make_limiters()
usage: Final = await batch_limiter.count_input_file_usage(
file_id=data["input_file_id"],
user_api_key_dict=UserAPIKeyAuth(api_key=hash_token("sk-batch"), models=[_BATCH_ALIAS]),
data=dict(data),
)
assert usage.per_model_usage[(_BATCH_ALIAS, _DEPLOYMENT_MODEL)]["request_count"] == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("limited_model", [_BATCH_ALIAS, _DEPLOYMENT_MODEL], ids=["alias", "deployment model"])
async def test_alias_routed_rows_naming_the_deployment_model_are_held_to_both_project_quotas(
alias_routed_batch: respx.MockRouter, limited_model: str
):
alias_routed_batch.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_DEPLOYMENT_MODEL),))
)
_, _, batch_limiter = _make_limiters()
with pytest.raises(HTTPException) as refused:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=UserAPIKeyAuth(
api_key=hash_token("sk-batch"),
models=[_BATCH_ALIAS],
project_id="project-1",
project_metadata={"model_itpm_limit": {limited_model: 1}},
),
cache=DualCache(),
data=dict(_alias_routing("body")),
call_type="acreate_batch",
)
assert refused.value.status_code == 429
assert f"project-1:{limited_model}" in str(refused.value.detail)
@pytest.mark.asyncio
async def test_alias_routed_row_is_charged_once_when_the_alias_and_deployment_model_share_a_quota_group(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
from litellm.proxy import proxy_server
monkeypatch.setattr(proxy_server, "llm_router", _alias_router({_DEPLOYMENT_MODEL: _BATCH_ALIAS}))
openai_files.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_DEPLOYMENT_MODEL),))
)
internal_usage_cache, rate_limiter, batch_limiter = _make_limiters()
api_key: Final = hash_token("sk-batch")
await batch_limiter.async_pre_call_hook(
user_api_key_dict=UserAPIKeyAuth(
api_key=api_key,
models=[_BATCH_ALIAS],
tpd_limit=1_000_000,
project_id="project-1",
project_metadata={"model_itpm_limit": {_BATCH_ALIAS: 1_000_000}},
),
cache=DualCache(),
data=dict(_alias_routing("body")),
call_type="acreate_batch",
)
key_tokens: Final = await _counter(internal_usage_cache, rate_limiter, "api_key_tpd", api_key, "tokens")
project_tokens: Final = await _counter(
internal_usage_cache, rate_limiter, PROJECT_ITPM_DESCRIPTOR_KEY, f"project-1:{_BATCH_ALIAS}", "tokens"
)
assert key_tokens > 0
assert project_tokens == key_tokens
@pytest.mark.asyncio
async def test_alias_quota_is_charged_every_row_routed_by_it_whichever_name_the_row_uses(
alias_routed_batch: respx.MockRouter,
):
alias_routed_batch.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_BATCH_ALIAS), _row_naming(_DEPLOYMENT_MODEL)))
)
_, _, batch_limiter = _make_limiters()
data: Final = _alias_routing("body")
user_api_key_dict: Final = UserAPIKeyAuth(api_key=hash_token("sk-batch"), models=[_BATCH_ALIAS])
usage: Final = await batch_limiter.count_input_file_usage(
file_id=data["input_file_id"], user_api_key_dict=user_api_key_dict, data=dict(data)
)
row_tokens: Final = tuple(model_usage["total_tokens"] for model_usage in usage.per_model_usage.values())
with pytest.raises(HTTPException) as refused:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict.model_copy(
update={
"project_id": "project-1",
"project_metadata": {"model_itpm_limit": {_BATCH_ALIAS: max(row_tokens) + 1}},
}
),
cache=DualCache(),
data=dict(data),
call_type="acreate_batch",
)
assert len(row_tokens) == 2
assert refused.value.status_code == 429
assert f"project-1:{_BATCH_ALIAS}. Batch contains {sum(row_tokens)} tokens" in str(refused.value.detail)
@pytest.mark.asyncio
async def test_a_counter_shared_by_alias_and_deployment_rows_is_held_to_the_stricter_of_their_limits(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
from litellm.proxy import proxy_server
monkeypatch.setattr(proxy_server, "llm_router", _alias_router({_DEPLOYMENT_MODEL: _BATCH_ALIAS}))
openai_files.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_BATCH_ALIAS), _row_naming(_DEPLOYMENT_MODEL)))
)
_, _, batch_limiter = _make_limiters()
data: Final = _alias_routing("body")
user_api_key_dict: Final = UserAPIKeyAuth(api_key=hash_token("sk-batch"), models=[_BATCH_ALIAS])
usage: Final = await batch_limiter.count_input_file_usage(
file_id=data["input_file_id"], user_api_key_dict=user_api_key_dict, data=dict(data)
)
batch_tokens: Final = sum(model_usage["total_tokens"] for model_usage in usage.per_model_usage.values())
with pytest.raises(HTTPException) as refused:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict.model_copy(
update={
"project_id": "project-1",
"project_metadata": {
"model_itpm_limit": {_BATCH_ALIAS: batch_tokens * 10, _DEPLOYMENT_MODEL: batch_tokens - 1}
},
}
),
cache=DualCache(),
data=dict(data),
call_type="acreate_batch",
)
assert refused.value.status_code == 429
assert f"project-1:{_BATCH_ALIAS}. Batch contains {batch_tokens} tokens" in str(refused.value.detail)
@pytest.mark.asyncio
async def test_alias_routed_rows_are_held_to_the_enqueued_token_cap_of_the_model_they_name(
alias_routed_batch: respx.MockRouter,
):
alias_routed_batch.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_DEPLOYMENT_MODEL),))
)
_, _, batch_limiter = _make_limiters()
with pytest.raises(HTTPException) as exc:
await batch_limiter.async_pre_call_hook(
user_api_key_dict=UserAPIKeyAuth(
api_key=hash_token("sk-batch"),
models=[_BATCH_ALIAS],
project_id="project-1",
project_metadata={"model_batch_enqueued_token_limit": {_DEPLOYMENT_MODEL: 1}},
),
cache=DualCache(),
data=dict(_alias_routing("body")),
call_type="acreate_batch",
)
assert exc.value.status_code == 429
assert f"project_model: project-1:{_DEPLOYMENT_MODEL}" in str(exc.value.detail)
@pytest.mark.asyncio
async def test_alias_routed_row_counts_once_toward_an_enqueued_token_cap_its_alias_shares(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
from litellm.proxy import proxy_server
monkeypatch.setattr(proxy_server, "llm_router", _alias_router({_DEPLOYMENT_MODEL: _BATCH_ALIAS}))
openai_files.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_DEPLOYMENT_MODEL),))
)
_, _, batch_limiter = _make_limiters()
data: Final = _alias_routing("body")
user_api_key_dict: Final = UserAPIKeyAuth(api_key=hash_token("sk-batch"), models=[_BATCH_ALIAS])
usage: Final = await batch_limiter.count_input_file_usage(
file_id=data["input_file_id"], user_api_key_dict=user_api_key_dict, data=dict(data)
)
result: Final = await batch_limiter.async_pre_call_hook(
user_api_key_dict=user_api_key_dict.model_copy(
update={
"project_id": "project-1",
"project_metadata": {"model_batch_enqueued_token_limit": {_BATCH_ALIAS: usage.total_tokens * 3 // 2}},
}
),
cache=DualCache(),
data=dict(data),
call_type="acreate_batch",
)
assert result["input_file_id"] == data["input_file_id"]
@pytest.mark.asyncio
async def test_key_granted_the_alias_cannot_smuggle_another_model_into_the_rows(
alias_routed_batch: respx.MockRouter,
):
alias_routed_batch.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_DEPLOYMENT_MODEL), _row_naming("another-model")))
)
data: Final = _alias_routing("body")
_, _, batch_limiter = _make_limiters()
with pytest.raises(HTTPException) as denied:
await batch_limiter.count_input_file_usage(
file_id=data["input_file_id"],
user_api_key_dict=UserAPIKeyAuth(api_key=hash_token("sk-batch"), models=[_BATCH_ALIAS]),
data=dict(data),
)
assert denied.value.status_code == 403
assert "another-model" in str(denied.value.detail)
@pytest.mark.asyncio
async def test_key_without_the_alias_cannot_batch_rows_naming_its_deployment_model(
alias_routed_batch: respx.MockRouter,
):
alias_routed_batch.get(_ROUTED_FILE_URL).mock(
side_effect=_serve_file_to_the_deployment_key((_row_naming(_DEPLOYMENT_MODEL),))
)
data: Final = _alias_routing("body")
_, _, batch_limiter = _make_limiters()
with pytest.raises(HTTPException) as denied:
await batch_limiter.count_input_file_usage(
file_id=data["input_file_id"],
user_api_key_dict=UserAPIKeyAuth(api_key=hash_token("sk-batch"), models=["a-different-model"]),
data=dict(data),
)
assert denied.value.status_code == 403
@pytest.mark.asyncio
async def test_managed_file_usage_stays_keyed_by_the_row_model(
openai_files: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
):
rows: Final = _batch_rows(("Test message for regression",))
await _install_managed_file_hook(openai_files, monkeypatch, rows)
_, _, batch_limiter = _make_limiters()
usage: Final = await batch_limiter.count_input_file_usage(
file_id=_MANAGED_FILE_ID,
custom_llm_provider="openai",
user_api_key_dict=UserAPIKeyAuth(api_key="test-key", user_id="test-user-regression", team_id="team-owner"),
data={"input_file_id": _MANAGED_FILE_ID, "model": _MANAGED_DEPLOYMENT_ALIAS},
)
assert set(usage.per_model_usage) == {(_BATCH_MODEL,)}
@pytest.mark.asyncio
async def test_batch_routed_by_a_model_missing_from_the_proxy_is_counted_under_the_row_model(
alias_routed_batch: respx.MockRouter,
):
_serve_file(alias_routed_batch, "file-abc123", (_row_naming(_DEPLOYMENT_MODEL),))
_, _, batch_limiter = _make_limiters()
usage: Final = await batch_limiter.count_input_file_usage(
file_id="file-abc123",
user_api_key_dict=UserAPIKeyAuth(api_key=hash_token("sk-batch"), models=[_DEPLOYMENT_MODEL]),
data={"input_file_id": "file-abc123", "model": "not-on-this-proxy"},
)
assert set(usage.per_model_usage) == {(_DEPLOYMENT_MODEL,)}