From 0a4719697e3e2d8181cf383ba5180fa25cd6c001 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sat, 12 Sep 2026 18:28:43 +0000 Subject: [PATCH 01/36] fix(ui): list every provider in the cache leakage by-model table Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../_components/CacheLeakageCard.test.tsx | 6 ++-- .../_components/costOptimizationUtils.test.ts | 36 ++++++------------- .../_components/costOptimizationUtils.ts | 3 -- 3 files changed, 14 insertions(+), 31 deletions(-) diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CacheLeakageCard.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CacheLeakageCard.test.tsx index f320d8e0f97..126011723dd 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CacheLeakageCard.test.tsx +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CacheLeakageCard.test.tsx @@ -122,11 +122,11 @@ describe("CacheLeakageCard", () => { expect(firstDataRow()).toHaveTextContent("alpha"); }); - it("switches to the model view and lists only Anthropic models", () => { + it("switches to the model view and lists models from every provider", () => { renderWith([ dayWithModels("2026-07-12", { "claude-sonnet-5": { prompt_tokens: 5000, cache_read_input_tokens: 0 }, - "gpt-4o": { prompt_tokens: 8000, cache_read_input_tokens: 0 }, + "vertex_ai/gemini-2.5-pro": { prompt_tokens: 8000, cache_read_input_tokens: 2000 }, }), ]); @@ -134,7 +134,7 @@ describe("CacheLeakageCard", () => { expect(screen.getByText("Cache leakage by model")).toBeInTheDocument(); expect(screen.getByText("claude-sonnet-5")).toBeInTheDocument(); - expect(screen.queryByText("gpt-4o")).not.toBeInTheDocument(); + expect(screen.getByText("vertex_ai/gemini-2.5-pro")).toBeInTheDocument(); }); it("shows an empty state when no key used tokens in the range", () => { diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.test.ts index 5d2c48e6440..9c3915c812f 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.test.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.test.ts @@ -10,7 +10,6 @@ import { classificationRatePer1kTurns, computeCacheLeakage, formatRangeLabel, - isAnthropicModel, localIsoDay, savingsSeriesOf, toCumulative, @@ -209,20 +208,21 @@ describe("computeCacheLeakage", () => { }); describe("computeCacheLeakage by model", () => { - it("aggregates only Anthropic models and ignores other providers", () => { + it("lists every provider's models, not only Anthropic", () => { const models: Record> = { "claude-sonnet-5": { prompt_tokens: 10000, cache_read_input_tokens: 0 }, - "anthropic/claude-haiku-4-5": { prompt_tokens: 4000, cache_read_input_tokens: 0 }, - "bedrock/anthropic.claude-3-5-sonnet": { prompt_tokens: 2000, cache_read_input_tokens: 0 }, - "gpt-4o": { prompt_tokens: 9000, cache_read_input_tokens: 0 }, - "deepseek-chat": { prompt_tokens: 8000, cache_read_input_tokens: 0 }, + "vertex_ai/gemini-2.5-pro": { prompt_tokens: 9000, cache_read_input_tokens: 3000 }, + "bedrock/openai.gpt-5.6-luna": { prompt_tokens: 8000, cache_read_input_tokens: 0 }, + "deepseek-chat": { prompt_tokens: 4000, cache_read_input_tokens: 0 }, }; const { rows } = computeCacheLeakage([modelDay("2026-07-01", models)], "model"); expect(rows.map((r) => r.id)).toEqual([ "claude-sonnet-5", - "anthropic/claude-haiku-4-5", - "bedrock/anthropic.claude-3-5-sonnet", + "bedrock/openai.gpt-5.6-luna", + "vertex_ai/gemini-2.5-pro", + "deepseek-chat", ]); + expect(rows.find((r) => r.id === "vertex_ai/gemini-2.5-pro")?.cacheHitRatio).toBeCloseTo(1 / 3, 6); }); it("labels model rows by model name with no sublabel", () => { @@ -232,34 +232,20 @@ describe("computeCacheLeakage by model", () => { expect(rows[0].sublabel).toBeNull(); }); - it("prices model leakage at the Anthropic realized cache-read discount", () => { + it("prices model leakage at the realized cache-read discount across providers", () => { const results = [ modelDay("2026-07-01", { "claude-sonnet-5": { prompt_tokens: 1000, cache_read_input_tokens: 1000, prompt_caching_savings_spend: 2.0 }, - "claude-haiku-4-5": { prompt_tokens: 500 }, + "gemini-2.5-flash": { prompt_tokens: 500 }, }), ]; const { rows, netSavingsPerCachedToken } = computeCacheLeakage(results, "model"); expect(netSavingsPerCachedToken).toBeCloseTo(0.002, 6); - expect(rows.map((r) => r.id)).toEqual(["claude-haiku-4-5"]); + expect(rows.map((r) => r.id)).toEqual(["gemini-2.5-flash"]); expect(rows[0].potentialSavings).toBeCloseTo(1.0, 6); }); }); -describe("isAnthropicModel", () => { - it("matches Claude-family models across providers and rejects others", () => { - const anthropic = [ - "claude-sonnet-5", - "anthropic/claude-haiku-4-5", - "bedrock/anthropic.claude-3-5-sonnet", - "vertex_ai/claude-opus-4-8", - ]; - const others = ["gpt-4o", "deepseek-chat", "gemini-2.5-pro", "mistral-large"]; - expect(anthropic.every(isAnthropicModel)).toBe(true); - expect(others.some(isAnthropicModel)).toBe(false); - }); -}); - describe("buildDailyToolSeries", () => { const daily: ToolSpendDailyEntry[] = [ { date: "2026-07-01", tool_name: "search", spend: 1.0, call_count: 1 }, diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.ts b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.ts index 464c779aa2b..2e6d8208989 100644 --- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.ts +++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.ts @@ -44,8 +44,6 @@ export interface CacheLeakageResult { netSavingsPerCachedToken: number | null; } -export const isAnthropicModel = (model: string): boolean => /claude|anthropic/i.test(model); - interface LeakageAccumulator { alias: string | null; teamId: string | null; @@ -96,7 +94,6 @@ const aggregateByModel = (results: readonly DailyData[]): Map(); for (const day of results) { for (const [model, entry] of Object.entries(day.breakdown?.models ?? {})) { - if (!isAnthropicModel(model)) continue; const acc = byModel.get(model) ?? emptyAccumulator(); byModel.set(model, addMetrics(acc, entry.metrics, null, null)); } From 302394edff7771eb73b4459fbba7e709730a1c00 Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 01:33:43 +0000 Subject: [PATCH 02/36] ci: gate hardcoded commercial AWS partition literals and test us-gov endpoint builders Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .github/workflows/test-code-quality.yml | 3 + .../check_aws_partition_hardcodes.py | 121 ++++++++++++++++++ .../litellm_core_utils/test_aws_partition.py | 116 ++++++++++++++++- 3 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 tests/code_coverage_tests/check_aws_partition_hardcodes.py diff --git a/.github/workflows/test-code-quality.yml b/.github/workflows/test-code-quality.yml index 987f66773f2..44c3e97db91 100644 --- a/.github/workflows/test-code-quality.yml +++ b/.github/workflows/test-code-quality.yml @@ -146,6 +146,9 @@ jobs: - name: check_migrations_no_data_rewrites run: uv run --no-sync python ./tests/code_coverage_tests/check_migrations_no_data_rewrites.py + - name: check_aws_partition_hardcodes + run: uv run --no-sync python ./tests/code_coverage_tests/check_aws_partition_hardcodes.py + - name: memory_test run: uv run --no-sync python ./tests/code_coverage_tests/memory_test.py diff --git a/tests/code_coverage_tests/check_aws_partition_hardcodes.py b/tests/code_coverage_tests/check_aws_partition_hardcodes.py new file mode 100644 index 00000000000..d7959ea59fe --- /dev/null +++ b/tests/code_coverage_tests/check_aws_partition_hardcodes.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Ban hardcoded commercial-partition AWS hosts and ARN prefixes under `litellm/`. + +An endpoint or ARN built with a literal `amazonaws.com` or `arn:aws:` works in every +commercial region and breaks only for GovCloud (`us-gov-*`, `arn:aws-us-gov:`) and +China (`amazonaws.com.cn`, `arn:aws-cn:`) deployments, so the failure never shows up +in CI or on a developer laptop. `litellm/litellm_core_utils/aws_partition.py` derives +both from the region and is the only place those literals belong. Build hosts with +`get_aws_dns_suffix(region)` and ARNs with `get_aws_arn_prefix(region)`. + +Every string constant in every `litellm/**/*.py` file is scanned, including the +literal parts of f-strings and the strings inside `.format()` calls and +concatenations. Docstrings and comments are not, since they never reach a request. +`amazonaws.com.cn` passes because it is already the China partition. + +`ALLOWED` holds the (file, token) pairs that are text rather than a request target: +a hosted logo, an IAM service principal, and hostnames quoted as examples inside +error messages and field descriptions. An entry only covers that exact token in that +exact file, so a second literal in an allowed file is still caught, and an entry +whose token is gone fails the check so the set only shrinks. +""" + +from __future__ import annotations + +import ast +import re +import sys +from pathlib import Path +from typing import Final, NamedTuple + +REPO_ROOT: Final = Path(__file__).resolve().parents[2] +SCAN_ROOT: Final = REPO_ROOT / "litellm" +PARTITION_HELPER: Final = "litellm/litellm_core_utils/aws_partition.py" + +COMMERCIAL_TOKEN: Final = re.compile(r"[A-Za-z0-9.-]*amazonaws\.com(?!\.cn)|arn:aws:[A-Za-z0-9:/_.*-]*") + + +class Allowance(NamedTuple): + file: str + token: str + + +ALLOWED: Final = frozenset( + { + Allowance("litellm/integrations/email_alerting.py", "litellm-listing.s3.amazonaws.com"), + Allowance("litellm/types/integrations/slack_alerting.py", "litellm-listing.s3.amazonaws.com"), + Allowance("litellm/rag/ingestion/bedrock_ingestion.py", "bedrock.amazonaws.com"), + Allowance( + "litellm/llms/bedrock/chat/agentcore/transformation.py", + "arn:aws:bedrock-agentcore:region:account:runtime/runtime_id", + ), + Allowance("litellm/llms/bedrock/search/transformation.py", ".amazonaws.com"), + Allowance( + "litellm/proxy/anthropic_endpoints/claude_code_endpoints/claude_code_marketplace.py", + "bucket.s3.amazonaws.com", + ), + Allowance("litellm/types/proxy/claude_code_endpoints.py", "bucket.s3.amazonaws.com"), + } +) + + +class Hit(NamedTuple): + file: str + line: int + token: str + + +def _docstring_ids(tree: ast.Module) -> frozenset[int]: + return frozenset( + id(statement.value) + for node in ast.walk(tree) + if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) + for statement in node.body + if isinstance(statement, ast.Expr) + and isinstance(statement.value, ast.Constant) + and isinstance(statement.value.value, str) + ) + + +def _hits_in_file(path: Path) -> tuple[Hit, ...]: + tree: Final = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + docstrings: Final = _docstring_ids(tree) + relative: Final = path.relative_to(REPO_ROOT).as_posix() + return tuple( + Hit(relative, node.lineno, match.group(0)) + for node in ast.walk(tree) + if isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings + for match in COMMERCIAL_TOKEN.finditer(node.value) + ) + + +def find_hits(scan_root: Path) -> tuple[Hit, ...]: + return tuple( + hit + for path in sorted(scan_root.rglob("*.py")) + if path.relative_to(REPO_ROOT).as_posix() != PARTITION_HELPER + for hit in _hits_in_file(path) + ) + + +def main() -> int: + hits: Final = find_hits(SCAN_ROOT) + seen: Final = frozenset(Allowance(hit.file, hit.token) for hit in hits) + violations: Final = tuple(hit for hit in hits if Allowance(hit.file, hit.token) not in ALLOWED) + stale: Final = ALLOWED - seen + for hit in violations: + print(f"{hit.file}:{hit.line}: hardcoded commercial AWS partition literal {hit.token!r}") + for allowance in sorted(stale): + print(f"{allowance.file}: ALLOWED entry {allowance.token!r} no longer matches anything, remove it") + if violations or stale: + print( + "\nBuild AWS hosts with get_aws_dns_suffix(region) and ARNs with get_aws_arn_prefix(region) " + "from litellm/litellm_core_utils/aws_partition.py so GovCloud and China regions resolve." + ) + return 1 + print(f"No hardcoded commercial AWS partition literals outside {PARTITION_HELPER}.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_litellm/litellm_core_utils/test_aws_partition.py b/tests/test_litellm/litellm_core_utils/test_aws_partition.py index 3594d3c354c..24a38268ae9 100644 --- a/tests/test_litellm/litellm_core_utils/test_aws_partition.py +++ b/tests/test_litellm/litellm_core_utils/test_aws_partition.py @@ -1,9 +1,11 @@ import ast from pathlib import Path +from types import MappingProxyType from typing import Final -from urllib.parse import urlparse +from urllib.parse import unquote, urlparse import pytest +from botocore.credentials import Credentials import litellm from litellm.integrations.s3_v2 import S3Logger @@ -20,8 +22,20 @@ from litellm.llms.aws_polly.text_to_speech.transformation import AWSPollyTextToS from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM from litellm.llms.bedrock.batches.transformation import BedrockBatchesConfig from litellm.llms.bedrock.chat.agentcore.transformation import AmazonAgentCoreConfig +from litellm.llms.bedrock.chat.invoke_agent.transformation import AmazonInvokeAgentConfig from litellm.llms.bedrock.common_utils import init_bedrock_client +from litellm.llms.bedrock.files.transformation import BedrockFilesConfig +from litellm.llms.bedrock.rerank.handler import BedrockRerankHandler +from litellm.llms.bedrock.vector_stores.transformation import BedrockVectorStoreConfig from litellm.llms.sagemaker.chat.transformation import SagemakerChatConfig +from litellm.llms.sagemaker.completion.handler import SagemakerLLM +from litellm.proxy.auth.rds_iam_token import init_rds_client +from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrail +from litellm.secret_managers.aws_secret_manager_v2 import AWSSecretsManagerV2 + +STATIC_AWS_CREDENTIALS: Final = MappingProxyType( + {"aws_access_key_id": "test-key", "aws_secret_access_key": "test-secret"} +) @pytest.mark.parametrize( @@ -106,6 +120,48 @@ def _s3_object_url(region: str) -> str: return logger._build_object_url("2025-01-01/key.json") +def _bedrock_job_arn(region: str) -> str: + return f"{get_aws_arn_prefix(region)}bedrock:{region}:111122223333:model-invocation-job/abc1234567" + + +def _bedrock_files_upload_url(region: str) -> str: + return BedrockFilesConfig().get_complete_file_url( + api_base=None, + api_key=None, + model="amazon.nova-pro-v1:0", + optional_params={}, + litellm_params={"s3_bucket_name": "batch-bucket", "s3_region_name": region}, + data={"file": ("batch.jsonl", b"{}", "application/jsonl"), "purpose": "batch"}, + ) + + +def _bedrock_files_download_url(region: str) -> str: + return ( + BedrockFilesConfig() + ._s3_request_target(optional_params={}, litellm_params={"s3_region_name": region}) + .endpoint_url + ) + + +def _bedrock_guardrail_url(region: str) -> str: + guardrail = BedrockGuardrail(guardrailIdentifier="guardrail-id", guardrailVersion="1") + return guardrail._prepare_request( + credentials=Credentials("test-key", "test-secret"), + data={"source": "INPUT", "content": []}, + optional_params={}, + aws_region_name=region, + ).url + + +def _secrets_manager_url(region: str) -> str: + endpoint_url, _headers, _body = AWSSecretsManagerV2(aws_region_name=region)._prepare_request( + action="GetSecretValue", + secret_name="my-secret", + optional_params=dict(STATIC_AWS_CREDENTIALS), + ) + return endpoint_url + + ENDPOINT_BUILDERS: Final = { "bedrock_runtime_default": lambda region: BaseAWSLLM()._select_default_endpoint_url("runtime", region), "bedrock_agent_default": lambda region: BaseAWSLLM()._select_default_endpoint_url("agent", region), @@ -124,6 +180,13 @@ ENDPOINT_BUILDERS: Final = { litellm_params={}, data={"input_file_id": "s3://bucket/key.jsonl"}, ), + "bedrock_batches_retrieve": lambda region: BedrockBatchesConfig().transform_retrieve_batch_request( + batch_id=_bedrock_job_arn(region), + optional_params=dict(STATIC_AWS_CREDENTIALS), + litellm_params={}, + )["url"], + "bedrock_files_upload": _bedrock_files_upload_url, + "bedrock_files_download": _bedrock_files_download_url, "bedrock_agentcore_invoke": lambda region: AmazonAgentCoreConfig().get_complete_url( api_base=None, api_key=None, @@ -131,6 +194,32 @@ ENDPOINT_BUILDERS: Final = { optional_params={}, litellm_params={}, ), + "bedrock_invoke_agent": lambda region: AmazonInvokeAgentConfig().get_complete_url( + api_base=None, + api_key=None, + model="agent/AGENT123/ALIAS456", + optional_params={"aws_region_name": region}, + litellm_params={}, + ), + "bedrock_guardrail_apply": _bedrock_guardrail_url, + "bedrock_rerank": lambda region: BedrockRerankHandler()._prepare_request( + model="amazon.rerank-v1:0", + api_base=None, + extra_headers=None, + data={"queries": [], "sources": []}, + optional_params={"aws_region_name": region, **STATIC_AWS_CREDENTIALS}, + )["endpoint_url"], + "bedrock_knowledgebase_search": lambda region: BedrockVectorStoreConfig().get_complete_url( + api_base=None, litellm_params={"aws_region_name": region} + ), + "secrets_manager": _secrets_manager_url, + "rds_iam_client": lambda region: ( + init_rds_client( + aws_region_name=region, + aws_access_key_id="test-key", + aws_secret_access_key="test-secret", + ).meta.endpoint_url + ), "polly": lambda region: AWSPollyTextToSpeechConfig().get_complete_url( model="polly/neural", api_base=None, @@ -152,6 +241,19 @@ ENDPOINT_BUILDERS: Final = { litellm_params={}, stream=True, ), + "sagemaker_completion": lambda region: ( + SagemakerLLM() + ._prepare_request( + credentials=Credentials("test-key", "test-secret"), + model="my-endpoint", + data={}, + messages=[], + litellm_params={}, + optional_params={}, + aws_region_name=region, + ) + .url + ), "s3_object_url": _s3_object_url, } @@ -182,6 +284,18 @@ def test_every_endpoint_builder_keeps_amazonaws_com_outside_cn(builder_name: str assert hostname.endswith(".amazonaws.com"), url +@pytest.mark.parametrize("region", ["us-gov-west-1", "us-gov-east-1"]) +@pytest.mark.parametrize("builder_name", sorted(ENDPOINT_BUILDERS)) +def test_every_endpoint_builder_respects_us_gov_partition(builder_name: str, region: str) -> None: + url = unquote(ENDPOINT_BUILDERS[builder_name](region)) + hostname = urlparse(url).hostname + assert hostname is not None + assert hostname.endswith(f".{region}.amazonaws.com"), url + assert "arn:aws:" not in url, url + if "arn:" in url: + assert "arn:aws-us-gov:" in url, url + + def _fstring_literal_offenders(needle: str) -> list[str]: litellm_root = Path(litellm.__file__).parent return [ From 6a9ae2bba290aaead3b7854715f4cc63f8d20bb6 Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 01:47:33 +0000 Subject: [PATCH 03/36] ci(aws-partition): count allowlisted literal occurrences so duplicates in allowed files fail Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../check_aws_partition_hardcodes.py | 49 +++++++++++++------ 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/tests/code_coverage_tests/check_aws_partition_hardcodes.py b/tests/code_coverage_tests/check_aws_partition_hardcodes.py index d7959ea59fe..0cbee4e7c80 100644 --- a/tests/code_coverage_tests/check_aws_partition_hardcodes.py +++ b/tests/code_coverage_tests/check_aws_partition_hardcodes.py @@ -13,11 +13,12 @@ literal parts of f-strings and the strings inside `.format()` calls and concatenations. Docstrings and comments are not, since they never reach a request. `amazonaws.com.cn` passes because it is already the China partition. -`ALLOWED` holds the (file, token) pairs that are text rather than a request target: -a hosted logo, an IAM service principal, and hostnames quoted as examples inside -error messages and field descriptions. An entry only covers that exact token in that -exact file, so a second literal in an allowed file is still caught, and an entry -whose token is gone fails the check so the set only shrinks. +`ALLOWED` holds the (file, token, count) triples that are text rather than a request +target: a hosted logo, an IAM service principal, and hostnames quoted as examples +inside error messages and field descriptions. An entry only covers that many +occurrences of that exact token in that exact file, so a second copy of an allowed +literal is still caught, and an entry whose token is gone or whose count has changed +fails the check so the set only shrinks. """ from __future__ import annotations @@ -25,7 +26,9 @@ from __future__ import annotations import ast import re import sys +from collections import Counter from pathlib import Path +from types import MappingProxyType from typing import Final, NamedTuple REPO_ROOT: Final = Path(__file__).resolve().parents[2] @@ -38,25 +41,29 @@ COMMERCIAL_TOKEN: Final = re.compile(r"[A-Za-z0-9.-]*amazonaws\.com(?!\.cn)|arn: class Allowance(NamedTuple): file: str token: str + occurrences: int ALLOWED: Final = frozenset( { - Allowance("litellm/integrations/email_alerting.py", "litellm-listing.s3.amazonaws.com"), - Allowance("litellm/types/integrations/slack_alerting.py", "litellm-listing.s3.amazonaws.com"), - Allowance("litellm/rag/ingestion/bedrock_ingestion.py", "bedrock.amazonaws.com"), + Allowance("litellm/integrations/email_alerting.py", "litellm-listing.s3.amazonaws.com", 1), + Allowance("litellm/types/integrations/slack_alerting.py", "litellm-listing.s3.amazonaws.com", 1), + Allowance("litellm/rag/ingestion/bedrock_ingestion.py", "bedrock.amazonaws.com", 1), Allowance( "litellm/llms/bedrock/chat/agentcore/transformation.py", "arn:aws:bedrock-agentcore:region:account:runtime/runtime_id", + 1, ), - Allowance("litellm/llms/bedrock/search/transformation.py", ".amazonaws.com"), + Allowance("litellm/llms/bedrock/search/transformation.py", ".amazonaws.com", 1), Allowance( "litellm/proxy/anthropic_endpoints/claude_code_endpoints/claude_code_marketplace.py", "bucket.s3.amazonaws.com", + 1, ), - Allowance("litellm/types/proxy/claude_code_endpoints.py", "bucket.s3.amazonaws.com"), + Allowance("litellm/types/proxy/claude_code_endpoints.py", "bucket.s3.amazonaws.com", 1), } ) +ALLOWED_COUNTS: Final = MappingProxyType({(entry.file, entry.token): entry.occurrences for entry in ALLOWED}) class Hit(NamedTuple): @@ -98,14 +105,26 @@ def find_hits(scan_root: Path) -> tuple[Hit, ...]: ) +def _violation_message(hit: Hit, found: int) -> str: + allowed: Final = ALLOWED_COUNTS.get((hit.file, hit.token)) + if allowed is None: + return f"{hit.file}:{hit.line}: hardcoded commercial AWS partition literal {hit.token!r}" + return ( + f"{hit.file}:{hit.line}: {hit.token!r} appears {found} times but ALLOWED covers {allowed}; " + "build it from the region helper or update the count" + ) + + def main() -> int: hits: Final = find_hits(SCAN_ROOT) - seen: Final = frozenset(Allowance(hit.file, hit.token) for hit in hits) - violations: Final = tuple(hit for hit in hits if Allowance(hit.file, hit.token) not in ALLOWED) - stale: Final = ALLOWED - seen + counts: Final = MappingProxyType(Counter((hit.file, hit.token) for hit in hits)) + violations: Final = tuple( + sorted(hit for hit in hits if Allowance(hit.file, hit.token, counts[hit.file, hit.token]) not in ALLOWED) + ) + stale: Final = tuple(entry for entry in sorted(ALLOWED) if (entry.file, entry.token) not in counts) for hit in violations: - print(f"{hit.file}:{hit.line}: hardcoded commercial AWS partition literal {hit.token!r}") - for allowance in sorted(stale): + print(_violation_message(hit, counts[hit.file, hit.token])) + for allowance in stale: print(f"{allowance.file}: ALLOWED entry {allowance.token!r} no longer matches anything, remove it") if violations or stale: print( From a57483d1c80032945ef2180707acfd71b6cc2548 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 05:24:05 +0000 Subject: [PATCH 04/36] fix(cost): price Azure PTU spillover requests at standard token rates Azure PTU deployments carry zeroed per-token pricing because the reservation is billed flat by the hour. When Azure spills a request onto pay-as-you-go capacity it returns x-ms-is-spilled-over: true, and that traffic was still priced at zero. The response cost calculator now detects the spillover header on the result's hidden params or the logged provider response headers and skips the zeroed custom pricing only for genuine PTU deployments while the feature flag is on. Azure sync streaming now also records response headers on the logging object, matching the async paths. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- litellm/litellm_core_utils/litellm_logging.py | 34 +++- litellm/litellm_core_utils/ptu_pricing.py | 20 +++ litellm/llms/azure/azure.py | 1 + .../test_litellm_logging.py | 152 ++++++++++++++++++ .../litellm_core_utils/test_ptu_pricing.py | 37 ++++- tests/test_litellm/llms/azure/test_azure.py | 54 +++++++ 6 files changed, 293 insertions(+), 5 deletions(-) create mode 100644 tests/test_litellm/llms/azure/test_azure.py diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 40621a2f68d..bbae3021677 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -90,6 +90,7 @@ from litellm.litellm_core_utils.logging_utils import ( truncate_base64_in_messages_async, ) from litellm.litellm_core_utils.model_param_helper import ModelParamHelper +from litellm.litellm_core_utils.ptu_pricing import is_spilled_over_ptu_request from litellm.litellm_core_utils.redact_messages import ( redact_message_input_output_from_custom_logger, redact_message_input_output_from_logging, @@ -1746,8 +1747,14 @@ class Logging(LiteLLMLoggingBaseClass): if transformed_result is not None: result = transformed_result + result_hidden_params: Final = getattr(result, "_hidden_params", None) or MappingProxyType({}) + result_additional_headers: Final = ( + result_hidden_params.get("additional_headers") + if isinstance(result_hidden_params, dict) + else getattr(result_hidden_params, "additional_headers", None) + ) if isinstance(result, (BaseModel, HttpxBinaryResponseContent)) and hasattr(result, "_hidden_params"): - hidden_params: Final = getattr(result, "_hidden_params", {}) + hidden_params: Final = result_hidden_params if ( "response_cost" in hidden_params and hidden_params["response_cost"] is not None ): # use cost if already calculated @@ -1762,8 +1769,17 @@ class Logging(LiteLLMLoggingBaseClass): router_model_id = self.get_router_model_id() ## RESPONSE COST ## - custom_pricing: Final = use_custom_pricing_for_model( - litellm_params=(self.litellm_params if hasattr(self, "litellm_params") else None) + spilled_over: Final = is_spilled_over_ptu_request( + model_info=_deployment_model_info(self.litellm_params if hasattr(self, "litellm_params") else None), + response_headers=self.model_call_details.get("response_headers"), + additional_headers=result_additional_headers, + ) + custom_pricing: Final = ( + False + if spilled_over + else use_custom_pricing_for_model( + litellm_params=(self.litellm_params if hasattr(self, "litellm_params") else None) + ) ) prompt = self._prompt_for_cost_calculation() @@ -5257,6 +5273,18 @@ def _get_custom_logger_settings_from_proxy_server(callback_name: str) -> dict: return {} +def _deployment_model_info(litellm_params: dict | None) -> Mapping[str, object]: + """The router-stamped deployment model_info from whichever metadata field carries it.""" + if litellm_params is None: + return MappingProxyType({}) + for metadata_key in ("metadata", "litellm_metadata"): + if not isinstance(metadata := litellm_params.get(metadata_key), Mapping): + continue + if model_info := metadata.get("model_info"): + return model_info + return MappingProxyType({}) + + def use_custom_pricing_for_model(litellm_params: dict | None) -> bool: """ Check if the model uses custom pricing diff --git a/litellm/litellm_core_utils/ptu_pricing.py b/litellm/litellm_core_utils/ptu_pricing.py index f545ba4aa3b..2cf86c30e9c 100644 --- a/litellm/litellm_core_utils/ptu_pricing.py +++ b/litellm/litellm_core_utils/ptu_pricing.py @@ -17,6 +17,7 @@ from litellm.types.router import ModelInfo from litellm.types.utils import CustomPricingLiteLLMParams, MirroredPricingParams PTU_COST_ATTRIBUTION_ENV_VAR: Final = "LITELLM_ENABLE_PTU_COST_ATTRIBUTION" +AZURE_SPILLOVER_HEADER: Final = "x-ms-is-spilled-over" def is_ptu_cost_attribution_enabled() -> bool: @@ -235,3 +236,22 @@ def zeroed_ptu_pricing( ), } ) + + +def is_spilled_over_ptu_request( + model_info: Mapping[str, object], + response_headers: Mapping[str, object] | None, + additional_headers: Mapping[str, object] | None, +) -> bool: + """Whether Azure served this request from pay-as-you-go capacity, so the zeroed PTU rates must not apply.""" + if ptu_terms(model_info) is None: + return False + if not is_ptu_cost_attribution_enabled(): + return False + for headers, key in ( + (response_headers, AZURE_SPILLOVER_HEADER), + (additional_headers, f"llm_provider-{AZURE_SPILLOVER_HEADER}"), + ): + if headers is not None and str(headers.get(key)).lower() == "true": + return True + return False diff --git a/litellm/llms/azure/azure.py b/litellm/llms/azure/azure.py index 587165e6991..3cb17259b93 100644 --- a/litellm/llms/azure/azure.py +++ b/litellm/llms/azure/azure.py @@ -561,6 +561,7 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): headers, response = self.make_sync_azure_openai_chat_completion_request( azure_client=azure_client, data=data, timeout=timeout ) + logging_obj.model_call_details["response_headers"] = headers streamwrapper: Final = CustomStreamWrapper( completion_stream=response, model=model, diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py index aaf44b8e918..e937142e046 100644 --- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py +++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py @@ -7229,3 +7229,155 @@ def test_add_dynamic_callback_registers_once_per_list_without_touching_the_calle assert logging_obj.dynamic_async_failure_callbacks == [callback] assert LitellmLogging._with_dynamic_callback(None, callback) == [callback] assert LitellmLogging._with_dynamic_callback((callback,), callback) == [callback] + + +class TestAzurePTUSpilloverCost: + """Azure PTU deployments price tokens at zero because the reservation is billed flat. + + A request Azure spills onto pay-as-you-go capacity must bill per token instead, so + the zeroed custom pricing has to be skipped when the provider reports spillover. + """ + + ROUTER_MODEL_ID: Final = "ptu-spill-router-model-id" + SERVED_MODEL: Final = "azure/spill-served-model-ptu" + PTU_MODEL_INFO: Final = { + "id": ROUTER_MODEL_ID, + "team_id": "team-1", + "ptu_count": 100, + "cost_per_ptu_per_hour": 1.0, + "ptu_effective_from": "2026-01-01", + "input_cost_per_token": 0.0, + "output_cost_per_token": 0.0, + } + EXPECTED_SPILL_COST: Final = 100 * 2e-6 + 50 * 8e-6 + + @staticmethod + def _register_models() -> None: + litellm.register_model( + model_cost={ + TestAzurePTUSpilloverCost.ROUTER_MODEL_ID: { + "input_cost_per_token": 0.0, + "output_cost_per_token": 0.0, + "litellm_provider": "azure", + "mode": "chat", + }, + TestAzurePTUSpilloverCost.SERVED_MODEL: { + "input_cost_per_token": 2e-6, + "output_cost_per_token": 8e-6, + "litellm_provider": "azure", + "mode": "chat", + }, + } + ) + + @staticmethod + def _unregister_models() -> None: + litellm.model_cost.pop(TestAzurePTUSpilloverCost.ROUTER_MODEL_ID, None) + litellm.model_cost.pop(TestAzurePTUSpilloverCost.SERVED_MODEL, None) + + def _logging_obj(self, model_info: dict, *, flag: str, litellm_rate: float, monkeypatch) -> LitellmLogging: + monkeypatch.setenv("LITELLM_ENABLE_PTU_COST_ATTRIBUTION", flag) + obj = LitellmLogging( + model=self.SERVED_MODEL, + messages=[{"role": "user", "content": "Hi"}], + stream=False, + call_type="completion", + start_time=time.time(), + litellm_call_id="ptu-spill-1", + function_id="f", + ) + obj.update_environment_variables( + model=self.SERVED_MODEL, + user="", + optional_params={}, + litellm_params={ + "api_base": "", + "metadata": {"model_info": model_info}, + "input_cost_per_token": litellm_rate, + "output_cost_per_token": litellm_rate, + }, + custom_llm_provider="azure", + ) + return obj + + @staticmethod + def _response() -> ModelResponse: + from litellm.types.utils import Usage + + return ModelResponse( + id="chatcmpl-spill-1", + created=1234567890, + model="spill-served-model-ptu", + choices=[ + { + "index": 0, + "message": {"role": "assistant", "content": "ok"}, + "finish_reason": "stop", + } + ], + usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150), + ) + + def test_spillover_via_response_additional_headers_bills_per_token(self, monkeypatch) -> None: + self._register_models() + try: + obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="True", litellm_rate=0.0, monkeypatch=monkeypatch) + response = self._response() + response._hidden_params["additional_headers"] = {"llm_provider-x-ms-is-spilled-over": "true"} + + assert obj._response_cost_calculator(result=response) == pytest.approx(self.EXPECTED_SPILL_COST) + finally: + self._unregister_models() + + def test_spillover_via_streaming_response_headers_bills_per_token(self, monkeypatch) -> None: + self._register_models() + try: + obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="True", litellm_rate=0.0, monkeypatch=monkeypatch) + obj.model_call_details["response_headers"] = { + "x-ms-is-spilled-over": "true", + "x-ms-spillover-from-deployment": "ptu-dep", + } + + assert obj._response_cost_calculator(result=self._response()) == pytest.approx(self.EXPECTED_SPILL_COST) + finally: + self._unregister_models() + + def test_non_spilled_ptu_request_stays_zero_priced(self, monkeypatch) -> None: + self._register_models() + try: + obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="True", litellm_rate=0.0, monkeypatch=monkeypatch) + + assert obj._response_cost_calculator(result=self._response()) == 0.0 + finally: + self._unregister_models() + + def test_spillover_header_without_the_flag_stays_zero_priced(self, monkeypatch) -> None: + self._register_models() + try: + obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="", litellm_rate=0.0, monkeypatch=monkeypatch) + response = self._response() + response._hidden_params["additional_headers"] = {"llm_provider-x-ms-is-spilled-over": "true"} + + assert obj._response_cost_calculator(result=response) == 0.0 + finally: + self._unregister_models() + + def test_spillover_header_does_not_touch_non_ptu_custom_pricing(self, monkeypatch) -> None: + self._register_models() + custom_model_id: Final = "non-ptu-custom-router-model-id" + litellm.model_cost[custom_model_id] = { + "input_cost_per_token": 1e-6, + "output_cost_per_token": 1e-6, + "litellm_provider": "azure", + "mode": "chat", + } + try: + model_info: Final = {"id": custom_model_id, "input_cost_per_token": 1e-6} + obj = self._logging_obj(model_info, flag="True", litellm_rate=1e-6, monkeypatch=monkeypatch) + response = self._response() + response._hidden_params["additional_headers"] = {"llm_provider-x-ms-is-spilled-over": "true"} + + assert obj._response_cost_calculator(result=response) == pytest.approx(150 * 1e-6) + finally: + litellm.model_cost.pop(custom_model_id, None) + self._unregister_models() diff --git a/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py b/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py index b8fb372d537..464c56d5132 100644 --- a/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py +++ b/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py @@ -7,13 +7,14 @@ from unittest.mock import patch import pytest from litellm.litellm_core_utils.ptu_pricing import ( - ptu_config_error, - ptu_identity_error, CUSTOM_PRICING_FIELDS, PTU_EMPTIED_PRICING_FIELDS, PTU_ZEROED_PRICING_FIELDS, PTU_ZEROED_TABLE_FIELDS, SEARCH_CONTEXT_SIZES, + is_spilled_over_ptu_request, + ptu_config_error, + ptu_identity_error, ptu_terms, zeroed_ptu_pricing, ) @@ -294,3 +295,35 @@ def test_an_empty_id_is_no_id(): assert error is not None assert error.startswith("model_info.id is required") + + +def test_the_spillover_header_marks_the_request_as_pay_as_you_go(): + with patch.dict(os.environ, {"LITELLM_ENABLE_PTU_COST_ATTRIBUTION": "True"}, clear=False): + assert ( + is_spilled_over_ptu_request( + model_info=_VALID, + response_headers={"x-ms-is-spilled-over": "True"}, + additional_headers=None, + ) + is True + ) + + +def test_no_spillover_marker_keeps_the_zeroed_ptu_rates(): + with patch.dict(os.environ, {"LITELLM_ENABLE_PTU_COST_ATTRIBUTION": "True"}, clear=False): + assert ( + is_spilled_over_ptu_request( + model_info=_VALID, + response_headers={"x-ms-is-spilled-over": "false"}, + additional_headers=None, + ) + is False + ) + assert ( + is_spilled_over_ptu_request( + model_info=_VALID, + response_headers=None, + additional_headers={"llm_provider-x-ms-is-spilled-over": "absent"}, + ) + is False + ) diff --git a/tests/test_litellm/llms/azure/test_azure.py b/tests/test_litellm/llms/azure/test_azure.py new file mode 100644 index 00000000000..6b6832f623c --- /dev/null +++ b/tests/test_litellm/llms/azure/test_azure.py @@ -0,0 +1,54 @@ +"""Tests for litellm/llms/azure/azure.py AzureChatCompletion handler behaviour.""" + +import time +from typing import Final + +from openai import AzureOpenAI + +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.azure.azure import AzureChatCompletion + + +class _FakeRawResponse: + headers: Final = {"x-ms-is-spilled-over": "true"} + + def parse(self): + return iter(()) + + +class _FakeRawCompletions: + def create(self, **kwargs): + return _FakeRawResponse() + + +def test_sync_streaming_stamps_response_headers_on_the_logging_obj() -> None: + """Sync streaming must mirror async_streaming and record the provider response + headers on model_call_details, or downstream consumers (spillover-aware cost + calculation) cannot see them.""" + client = AzureOpenAI(api_key="fake", api_version="2024-02-01", azure_endpoint="https://fake.openai.azure.com") + client.chat.completions.with_raw_response = _FakeRawCompletions() + + logging_obj = LiteLLMLoggingObj( + model="azure/gpt-4o-spill-test", + messages=[{"role": "user", "content": "Hi"}], + stream=True, + call_type="completion", + start_time=time.time(), + litellm_call_id="spill-sync-1", + function_id="f", + ) + + AzureChatCompletion().streaming( + logging_obj=logging_obj, + api_base="https://fake.openai.azure.com", + api_key="fake", + api_version="2024-02-01", + dynamic_params=False, + data={"messages": [{"role": "user", "content": "Hi"}], "stream": True}, + model="gpt-4o-spill-test", + timeout=30.0, + max_retries=0, + client=client, + ) + + assert logging_obj.model_call_details["response_headers"] == {"x-ms-is-spilled-over": "true"} From 7b855bd53f50f1a070abef1701d942fae503ac74 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 05:48:51 +0000 Subject: [PATCH 05/36] feat(spend-logs): record Azure spillover source deployment in spend log metadata SpendLogsMetadata gains a typed azure_spillover key so a request Azure served off pay-as-you-go capacity is visible in spend tracking, stamped from the provider response headers or the processed llm_provider- headers on the standard logging payload. The header parsing moves into a shared azure_spillover() helper that is_spilled_over_ptu_request() now wraps. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- litellm/litellm_core_utils/ptu_pricing.py | 26 ++++++--- litellm/proxy/_types.py | 2 + .../spend_tracking/spend_tracking_utils.py | 19 ++++++- litellm/types/utils.py | 6 ++ .../litellm_core_utils/test_ptu_pricing.py | 29 ++++++++++ .../test_spend_tracking_utils.py | 55 +++++++++++++++++++ 6 files changed, 129 insertions(+), 8 deletions(-) diff --git a/litellm/litellm_core_utils/ptu_pricing.py b/litellm/litellm_core_utils/ptu_pricing.py index 2cf86c30e9c..80f7a822b96 100644 --- a/litellm/litellm_core_utils/ptu_pricing.py +++ b/litellm/litellm_core_utils/ptu_pricing.py @@ -14,10 +14,11 @@ from typing import Final from litellm.secret_managers.main import get_secret_bool from litellm.types.router import ModelInfo -from litellm.types.utils import CustomPricingLiteLLMParams, MirroredPricingParams +from litellm.types.utils import AzureSpillover, CustomPricingLiteLLMParams, MirroredPricingParams PTU_COST_ATTRIBUTION_ENV_VAR: Final = "LITELLM_ENABLE_PTU_COST_ATTRIBUTION" AZURE_SPILLOVER_HEADER: Final = "x-ms-is-spilled-over" +AZURE_SPILLOVER_FROM_HEADER: Final = "x-ms-spillover-from-deployment" def is_ptu_cost_attribution_enabled() -> bool: @@ -248,10 +249,21 @@ def is_spilled_over_ptu_request( return False if not is_ptu_cost_attribution_enabled(): return False - for headers, key in ( - (response_headers, AZURE_SPILLOVER_HEADER), - (additional_headers, f"llm_provider-{AZURE_SPILLOVER_HEADER}"), + return azure_spillover(response_headers, additional_headers) is not None + + +def azure_spillover( + response_headers: Mapping[str, object] | None, + additional_headers: Mapping[str, object] | None, +) -> AzureSpillover | None: + """The spillover Azure reports in the response headers, else None.""" + for headers, prefix in ( + (response_headers, ""), + (additional_headers, "llm_provider-"), ): - if headers is not None and str(headers.get(key)).lower() == "true": - return True - return False + if headers is None or str(headers.get(f"{prefix}{AZURE_SPILLOVER_HEADER}")).lower() != "true": + continue + return AzureSpillover( + from_deployment=str(v) if (v := headers.get(f"{prefix}{AZURE_SPILLOVER_FROM_HEADER}")) is not None else None + ) + return None diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py index 680c63393e8..957f79d79d4 100644 --- a/litellm/proxy/_types.py +++ b/litellm/proxy/_types.py @@ -51,6 +51,7 @@ from litellm.types.router import RouterErrors, UpdateRouterConfig from litellm.types.router_weights import validate_router_settings_dict from litellm.types.secret_managers.main import KeyManagementSystem from litellm.types.utils import ( + AzureSpillover, CallTypes, CostBreakdown, EmbeddingResponse, @@ -3895,6 +3896,7 @@ class SpendLogsMetadata(TypedDict): autorouter_savings: ReadOnly[float | None] # stamped by the logging payload; None = not auto-routed litellm_gateway_injected_cache: ReadOnly[str | None] router_metadata: ReadOnly[SpendLogsRouterMetadata | None] # None = deployment not flagged internal_router_model + azure_spillover: ReadOnly[AzureSpillover | None] # None = Azure did not report spillover class SpendLogsPayload(TypedDict): diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.py index 52900c33745..f1a54841e3a 100644 --- a/litellm/proxy/spend_tracking/spend_tracking_utils.py +++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py @@ -39,6 +39,7 @@ from litellm.litellm_core_utils.litellm_logging import ( is_valid_sha256_hash, request_model_access_groups_from_litellm_params, ) +from litellm.litellm_core_utils.ptu_pricing import azure_spillover from litellm.litellm_core_utils.safe_json_dumps import safe_dumps, strip_null_bytes from litellm.proxy._types import SpendLogsMetadata, SpendLogsPayload, SpendLogsRouterMetadata from litellm.proxy.route_llm_request import ProxyModelNotFoundError @@ -47,6 +48,7 @@ from litellm.proxy.utils import PrismaClient, hash_token from litellm.types.router import DeploymentTypedDict, LiteLLM_Params from litellm.types.utils import ( PROMPT_CARRYING_GUARDRAIL_FIELDS, + AzureSpillover, CallTypes, CostBreakdown, LlmProviders, @@ -133,6 +135,9 @@ def _get_router_metadata_for_spend_log( ) +_STAMPED_METADATA_KEYS: Final = frozenset(("router_metadata", "azure_spillover")) + + def _get_spend_logs_metadata( metadata: dict | None, applied_guardrails: list[str] | None = None, @@ -150,6 +155,7 @@ def _get_spend_logs_metadata( litellm_call_id: str | None = None, autorouter_savings: float | None = None, router_metadata: SpendLogsRouterMetadata | None = None, + azure_spillover: AzureSpillover | None = None, ) -> SpendLogsMetadata: if metadata is None: return SpendLogsMetadata( @@ -191,6 +197,7 @@ def _get_spend_logs_metadata( litellm_gateway_injected_cache=None, litellm_call_id=litellm_call_id, router_metadata=router_metadata, + azure_spillover=azure_spillover, ) verbose_proxy_logger.debug( "getting payload for SpendLogs, available keys in metadata: " + str(list(metadata.keys())) @@ -198,8 +205,9 @@ def _get_spend_logs_metadata( # Filter the metadata dictionary to include only the specified keys clean_metadata: Final = SpendLogsMetadata( - **{key: metadata.get(key) for key in SpendLogsMetadata.__annotations__ if key != "router_metadata"}, + **{key: metadata.get(key) for key in SpendLogsMetadata.__annotations__ if key not in _STAMPED_METADATA_KEYS}, router_metadata=router_metadata, + azure_spillover=azure_spillover, ) _raw_key: Final = clean_metadata.get("user_api_key") _trusted_hash: Final = metadata.get("user_api_key_hash") @@ -570,6 +578,15 @@ def get_logging_payload( selected_provider=custom_llm_provider, router_correlation_id=litellm_call_id, ), + azure_spillover=azure_spillover( + response_headers=kwargs.get("response_headers") + if isinstance(kwargs.get("response_headers"), Mapping) + else None, + additional_headers=standard_logging_payload["hidden_params"].get("additional_headers") + if standard_logging_payload is not None + and isinstance(standard_logging_payload.get("hidden_params"), Mapping) + else None, + ), ) special_usage_fields: Final = ["completion_tokens", "prompt_tokens", "total_tokens"] diff --git a/litellm/types/utils.py b/litellm/types/utils.py index aaa16fd2d44..eee9288b9bb 100644 --- a/litellm/types/utils.py +++ b/litellm/types/utils.py @@ -3075,6 +3075,12 @@ class StandardLoggingMetadata(StandardLoggingUserAPIKeyMetadata): team_id: str | None +class AzureSpillover(TypedDict): + """Spillover Azure reports in its response headers for a request it served from pay-as-you-go capacity.""" + + from_deployment: ReadOnly[str | None] + + class StandardLoggingAdditionalHeaders(TypedDict, total=False): x_ratelimit_limit_requests: int x_ratelimit_limit_tokens: int diff --git a/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py b/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py index 464c56d5132..1689da2696f 100644 --- a/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py +++ b/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py @@ -12,6 +12,7 @@ from litellm.litellm_core_utils.ptu_pricing import ( PTU_ZEROED_PRICING_FIELDS, PTU_ZEROED_TABLE_FIELDS, SEARCH_CONTEXT_SIZES, + azure_spillover, is_spilled_over_ptu_request, ptu_config_error, ptu_identity_error, @@ -327,3 +328,31 @@ def test_no_spillover_marker_keeps_the_zeroed_ptu_rates(): ) is False ) + + +def test_azure_spillover_carries_the_source_deployment_from_raw_headers(): + assert azure_spillover( + response_headers={ + "x-ms-is-spilled-over": "true", + "x-ms-spillover-from-deployment": "my-ptu", + }, + additional_headers=None, + ) == {"from_deployment": "my-ptu"} + + +def test_azure_spillover_from_processed_headers_has_no_source_when_absent(): + assert azure_spillover( + response_headers=None, + additional_headers={"llm_provider-x-ms-is-spilled-over": "true"}, + ) == {"from_deployment": None} + + +def test_no_spillover_marker_returns_none(): + assert ( + azure_spillover( + response_headers={"x-ms-is-spilled-over": "false"}, + additional_headers=None, + ) + is None + ) + assert azure_spillover(response_headers=None, additional_headers=None) is None diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py index 1072e970094..2c86de40a8d 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py +++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py @@ -4829,3 +4829,58 @@ def test_spend_log_request_id_is_the_response_id_a_bridged_messages_caller_recei ) == "resp_01Lit6806Bridged" ) + + +def test_azure_spillover_stamped_from_response_headers(): + """Raw provider response headers on the logging kwargs mark the request as spilled.""" + kwargs: Final = { + **_routed_call_kwargs({"id": "mi-1"}), + "response_headers": { + "x-ms-is-spilled-over": "true", + "x-ms-spillover-from-deployment": "my-ptu", + }, + } + payload = get_logging_payload( + kwargs=kwargs, + response_obj=litellm.ModelResponse(id="chatcmpl-spill-raw", choices=[], usage=litellm.Usage()), + start_time=datetime.datetime.now(timezone.utc), + end_time=datetime.datetime.now(timezone.utc), + ) + metadata = json.loads(payload["metadata"]) + assert metadata["azure_spillover"] == {"from_deployment": "my-ptu"} + + +def test_azure_spillover_stamped_from_standard_logging_additional_headers(): + """Streaming requests carry the processed llm_provider- headers on the standard payload.""" + kwargs: Final = { + **_routed_call_kwargs({"id": "mi-1"}), + "standard_logging_object": { + "hidden_params": { + "additional_headers": { + "llm_provider-x-ms-is-spilled-over": "true", + "llm_provider-x-ms-spillover-from-deployment": "my-ptu", + } + }, + "metadata": {}, + "model_map_information": None, + }, + } + payload = get_logging_payload( + kwargs=kwargs, + response_obj=litellm.ModelResponse(id="chatcmpl-spill-sl", choices=[], usage=litellm.Usage()), + start_time=datetime.datetime.now(timezone.utc), + end_time=datetime.datetime.now(timezone.utc), + ) + metadata = json.loads(payload["metadata"]) + assert metadata["azure_spillover"] == {"from_deployment": "my-ptu"} + + +def test_azure_spillover_absent_without_spillover_headers(): + payload = get_logging_payload( + kwargs=_routed_call_kwargs({"id": "mi-1"}), + response_obj=litellm.ModelResponse(id="chatcmpl-no-spill", choices=[], usage=litellm.Usage()), + start_time=datetime.datetime.now(timezone.utc), + end_time=datetime.datetime.now(timezone.utc), + ) + metadata = json.loads(payload["metadata"]) + assert metadata["azure_spillover"] is None From 3406913ca0e386a40ce512da45f8ce6e5d268d68 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 05:58:19 +0000 Subject: [PATCH 06/36] test(spend-logs): expect azure_spillover in spend log metadata golden Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../proxy/spend_tracking/test_spend_management_endpoints.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py index 772c5f674d5..8d15fb094d5 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py +++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py @@ -3745,7 +3745,7 @@ class TestSpendLogsPayload: "model": "gpt-4o", "user": "", "team_id": "", - "metadata": '{"applied_guardrails": [], "attempted_fallbacks": null, "original_model_group": null, "batch_models": null, "batch_successful_requests": null, "batch_failed_requests": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "litellm_gateway_injected_cache": null, "router_metadata": null, "usage_object": {"completion_tokens": 20, "prompt_tokens": 10, "total_tokens": 30, "completion_tokens_details": null, "prompt_tokens_details": null}, "model_map_information": {"model_map_key": "gpt-4o", "model_map_value": {"key": "gpt-4o", "max_tokens": 16384, "max_input_tokens": 128000, "max_output_tokens": 16384, "input_cost_per_token": 2.5e-06, "cache_creation_input_token_cost": null, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": 1.25e-06, "output_cost_per_token_batches": 5e-06, "output_cost_per_token": 1e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_reasoning_token": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "openai", "mode": "chat", "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": false, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": false, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": true, "supports_reasoning": false, "search_context_cost_per_query": {"search_context_size_low": 0.03, "search_context_size_medium": 0.035, "search_context_size_high": 0.05}, "tpm": null, "rpm": null, "supported_openai_params": ["frequency_penalty", "logit_bias", "logprobs", "top_logprobs", "max_tokens", "max_completion_tokens", "modalities", "prediction", "n", "presence_penalty", "seed", "stop", "stream", "stream_options", "temperature", "top_p", "tools", "tool_choice", "function_call", "functions", "max_retries", "extra_headers", "parallel_tool_calls", "audio", "response_format", "user"]}}, "additional_usage_values": {"completion_tokens_details": null, "prompt_tokens_details": null}}', + "metadata": '{"applied_guardrails": [], "attempted_fallbacks": null, "original_model_group": null, "batch_models": null, "batch_successful_requests": null, "batch_failed_requests": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "litellm_gateway_injected_cache": null, "router_metadata": null, "azure_spillover": null, "usage_object": {"completion_tokens": 20, "prompt_tokens": 10, "total_tokens": 30, "completion_tokens_details": null, "prompt_tokens_details": null}, "model_map_information": {"model_map_key": "gpt-4o", "model_map_value": {"key": "gpt-4o", "max_tokens": 16384, "max_input_tokens": 128000, "max_output_tokens": 16384, "input_cost_per_token": 2.5e-06, "cache_creation_input_token_cost": null, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": 1.25e-06, "output_cost_per_token_batches": 5e-06, "output_cost_per_token": 1e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_reasoning_token": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "openai", "mode": "chat", "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": false, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": false, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": true, "supports_reasoning": false, "search_context_cost_per_query": {"search_context_size_low": 0.03, "search_context_size_medium": 0.035, "search_context_size_high": 0.05}, "tpm": null, "rpm": null, "supported_openai_params": ["frequency_penalty", "logit_bias", "logprobs", "top_logprobs", "max_tokens", "max_completion_tokens", "modalities", "prediction", "n", "presence_penalty", "seed", "stop", "stream", "stream_options", "temperature", "top_p", "tools", "tool_choice", "function_call", "functions", "max_retries", "extra_headers", "parallel_tool_calls", "audio", "response_format", "user"]}}, "additional_usage_values": {"completion_tokens_details": null, "prompt_tokens_details": null}}', "cache_key": "Cache OFF", "spend": 0.00022500000000000002, "total_tokens": 30, @@ -3841,7 +3841,7 @@ class TestSpendLogsPayload: "model": "claude-4-sonnet-20250514", "user": "", "team_id": "", - "metadata": '{"applied_guardrails": [], "attempted_fallbacks": null, "original_model_group": null, "batch_models": null, "batch_successful_requests": null, "batch_failed_requests": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "litellm_gateway_injected_cache": null, "router_metadata": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}', + "metadata": '{"applied_guardrails": [], "attempted_fallbacks": null, "original_model_group": null, "batch_models": null, "batch_successful_requests": null, "batch_failed_requests": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "litellm_gateway_injected_cache": null, "router_metadata": null, "azure_spillover": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}', "cache_key": "Cache OFF", "spend": 0.01383, "total_tokens": 2598, @@ -3935,7 +3935,7 @@ class TestSpendLogsPayload: "model": "claude-4-sonnet-20250514", "user": "", "team_id": "", - "metadata": '{"applied_guardrails": [], "attempted_fallbacks": 0, "original_model_group": "my-anthropic-model-group", "batch_models": null, "batch_successful_requests": null, "batch_failed_requests": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "litellm_gateway_injected_cache": null, "router_metadata": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}', + "metadata": '{"applied_guardrails": [], "attempted_fallbacks": 0, "original_model_group": "my-anthropic-model-group", "batch_models": null, "batch_successful_requests": null, "batch_failed_requests": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "litellm_gateway_injected_cache": null, "router_metadata": null, "azure_spillover": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}', "cache_key": "Cache OFF", "spend": 0.01383, "total_tokens": 2598, From 5451c38dcc93ec4a734cfea4499c1bb4d1e03757 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 07:50:36 +0000 Subject: [PATCH 07/36] feat(grafana): add all-metrics dashboard and fix stale dashboard_v2 gauges Fixes the litellm_remaining_requests and litellm_remaining_tokens queries in dashboard_v2 (renamed to *_metric in v1.80.15) and adds dashboard_all_metrics with a panel for every litellm_* family the proxy can emit, including the prometheus_system service metrics, admission control, Redis circuit breaker and spend log cleanup metrics. dashboard_1 charted a metric that is never emitted and is superseded, so it is removed. A test fails when a dashboard references a metric the proxy does not emit or when an emitted family has no panel Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../dashboard_1/grafana_dashboard.json | 614 -- .../grafana_dashboard/dashboard_1/readme.md | 6 - .../grafana_dashboard.json | 6312 +++++++++++++++++ .../dashboard_all_metrics/readme.md | 11 + .../dashboard_v2/grafana_dashboard.json | 4 +- .../grafana_dashboard/readme.md | 6 + ...test_prometheus_metric_name_consistency.py | 103 +- 7 files changed, 6433 insertions(+), 623 deletions(-) delete mode 100644 cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/grafana_dashboard.json delete mode 100644 cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/readme.md create mode 100644 cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json create mode 100644 cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/readme.md diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/grafana_dashboard.json b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/grafana_dashboard.json deleted file mode 100644 index 269c1ea5a43..00000000000 --- a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/grafana_dashboard.json +++ /dev/null @@ -1,614 +0,0 @@ -{ - "annotations": { - "list": [ - { - "builtIn": 1, - "datasource": { - "type": "grafana", - "uid": "-- Grafana --" - }, - "enable": true, - "hide": true, - "iconColor": "rgba(0, 211, 255, 1)", - "name": "Annotations & Alerts", - "target": { - "limit": 100, - "matchAny": false, - "tags": [], - "type": "dashboard" - }, - "type": "dashboard" - } - ] - }, - "description": "", - "editable": true, - "fiscalYearStartMonth": 0, - "graphTooltip": 0, - "id": 2039, - "links": [], - "liveNow": false, - "panels": [ - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 0, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "auto", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "s" - }, - "overrides": [] - }, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 0 - }, - "id": 10, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "single", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "editorMode": "code", - "expr": "histogram_quantile(0.99, sum(rate(litellm_self_latency_bucket{self=\"self\"}[1m])) by (le))", - "legendFormat": "Time to first token", - "range": true, - "refId": "A" - } - ], - "title": "Time to first token (latency)", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 0, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "auto", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "currencyUSD" - }, - "overrides": [ - { - "matcher": { - "id": "byName", - "options": "7e4b0627fd32efdd2313c846325575808aadcf2839f0fde90723aab9ab73c78f" - }, - "properties": [ - { - "id": "displayName", - "value": "Translata" - } - ] - } - ] - }, - "gridPos": { - "h": 8, - "w": 12, - "x": 0, - "y": 8 - }, - "id": 11, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "single", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "editorMode": "code", - "expr": "sum(increase(litellm_spend_metric_total[30d])) by (hashed_api_key)", - "legendFormat": "{{team}}", - "range": true, - "refId": "A" - } - ], - "title": "Spend by team", - "transformations": [], - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 0, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "auto", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 0, - "y": 16 - }, - "id": 2, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "single", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "editorMode": "code", - "expr": "sum by (model) (increase(litellm_requests_metric_total[5m]))", - "legendFormat": "{{model}}", - "range": true, - "refId": "A" - } - ], - "title": "Requests by model", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "noValue": "0", - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 7, - "w": 3, - "x": 0, - "y": 25 - }, - "id": 8, - "options": { - "colorMode": "value", - "graphMode": "area", - "justifyMode": "auto", - "orientation": "auto", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "textMode": "auto" - }, - "pluginVersion": "9.4.17", - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "editorMode": "code", - "expr": "sum(increase(litellm_llm_api_failed_requests_metric_total[1h]))", - "legendFormat": "__auto", - "range": true, - "refId": "A" - } - ], - "title": "Faild Requests", - "type": "stat" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 0, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "auto", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "currencyUSD" - }, - "overrides": [] - }, - "gridPos": { - "h": 7, - "w": 3, - "x": 3, - "y": 25 - }, - "id": 6, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "single", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "editorMode": "code", - "expr": "sum(increase(litellm_spend_metric_total[30d])) by (model)", - "legendFormat": "{{model}}", - "range": true, - "refId": "A" - } - ], - "title": "Spend", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 0, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "auto", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 7, - "w": 6, - "x": 6, - "y": 25 - }, - "id": 4, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "single", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "editorMode": "code", - "expr": "sum(increase(litellm_total_tokens_total[5m])) by (model)", - "legendFormat": "__auto", - "range": true, - "refId": "A" - } - ], - "title": "Tokens", - "type": "timeseries" - } - ], - "refresh": "1m", - "revision": 1, - "schemaVersion": 38, - "style": "dark", - "tags": [], - "templating": { - "list": [ - { - "current": { - "selected": false, - "text": "prometheus", - "value": "edx8memhpd9tsa" - }, - "hide": 0, - "includeAll": false, - "label": "datasource", - "multi": false, - "name": "DS_PROMETHEUS", - "options": [], - "query": "prometheus", - "queryValue": "", - "refresh": 1, - "regex": "", - "skipUrlSync": false, - "type": "datasource" - } - ] - }, - "time": { - "from": "now-1h", - "to": "now" - }, - "timepicker": {}, - "timezone": "", - "title": "LLM Proxy", - "uid": "rgRrHxESz", - "version": 15, - "weekStart": "" - } \ No newline at end of file diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/readme.md b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/readme.md deleted file mode 100644 index 1f193aba702..00000000000 --- a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_1/readme.md +++ /dev/null @@ -1,6 +0,0 @@ -## This folder contains the `json` for creating the following Grafana Dashboard - -### Pre-Requisites -- Setup LiteLLM Proxy Prometheus Metrics https://docs.litellm.ai/docs/proxy/prometheus - -![1716623265684](https://github.com/BerriAI/litellm/assets/29436595/0e12c57e-4a2d-4850-bd4f-e4294f87a814) diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json new file mode 100644 index 00000000000..9d7029ca464 --- /dev/null +++ b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json @@ -0,0 +1,6312 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "description": "Every litellm_* Prometheus metric the LiteLLM proxy emits, one panel per metric family, grouped by theme.", + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 1, + "id": null, + "links": [], + "panels": [ + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + }, + "id": 1, + "panels": [], + "title": "Proxy traffic", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of requests made to the proxy server - track number of client side requests", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 1 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_proxy_total_requests_metric_total[$__rate_interval])) by (status_code)", + "legendFormat": "{{status_code}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_proxy_total_requests_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of failed responses from proxy - the client did not get a success response from litellm proxy", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 1 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_proxy_failed_requests_metric_total[$__rate_interval])) by (exception_class)", + "legendFormat": "{{exception_class}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_proxy_failed_requests_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "deprecated - use litellm_proxy_total_requests_metric. Total number of LLM calls to litellm - track total per API Key, team, user", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 9 + }, + "id": 4, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_requests_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_requests_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "deprecated - use litellm_proxy_failed_requests_metric", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 9 + }, + "id": 5, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_llm_api_failed_requests_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_llm_api_failed_requests_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Number of HTTP requests currently in-flight on this uvicorn worker", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 17 + }, + "id": 6, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "litellm_in_flight_requests", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "litellm_in_flight_requests", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Time (seconds) from request arrival at the proxy to the start of pre-call processing -- includes authentication and any ASGI-level queueing", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 17 + }, + "id": 7, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_request_queue_time_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_request_queue_time_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_request_queue_time_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_request_queue_time_seconds p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Requests admitted by this worker (needs the admission control middleware enabled)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 25 + }, + "id": 8, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "litellm_admission_admitted_requests", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "litellm_admission_admitted_requests", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Requests queued by this worker (needs the admission control middleware enabled)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 25 + }, + "id": 9, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "litellm_admission_queued_requests", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "litellm_admission_queued_requests", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Requests rejected by this worker (needs the admission control middleware enabled)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 33 + }, + "id": 10, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_admission_rejected_requests_total[$__rate_interval])) by (reason)", + "legendFormat": "{{reason}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_admission_rejected_requests rate", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 41 + }, + "id": 11, + "panels": [], + "title": "Latency", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "End-to-end latency (seconds) for a request to LiteLLM Proxy Server, from the moment the request reached the proxy through the end of processing -- includes authentication, pre-call hooks, the LLM API call, and post-call processing", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 42 + }, + "id": 12, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_request_total_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_request_total_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_request_total_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_request_total_latency_metric p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total latency (seconds) for a models LLM API call", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 42 + }, + "id": 13, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_llm_api_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_llm_api_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_llm_api_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_llm_api_latency_metric p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Time to first token for a models LLM API call", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 50 + }, + "id": 14, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_llm_api_time_to_first_token_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_llm_api_time_to_first_token_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_llm_api_time_to_first_token_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_llm_api_time_to_first_token_metric p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Latency overhead (milliseconds) added by LiteLLM processing", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 50 + }, + "id": 15, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_overhead_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_overhead_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_overhead_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_overhead_latency_metric p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total internal latency (seconds) added by LiteLLM, including pre/post-call guardrails (excludes the LLM API call)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 58 + }, + "id": 16, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_overhead_with_guardrails_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_overhead_with_guardrails_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_overhead_with_guardrails_latency_metric_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_overhead_with_guardrails_latency_metric p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - Latency per output token", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 58 + }, + "id": 17, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_deployment_latency_per_output_token_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_deployment_latency_per_output_token_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_deployment_latency_per_output_token_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_deployment_latency_per_output_token p50 / p95 / p99", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 66 + }, + "id": 18, + "panels": [], + "title": "Spend and tokens", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total spend on LLM requests", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 67 + }, + "id": 19, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_spend_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_spend_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of input + output tokens from LLM requests", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 67 + }, + "id": 20, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_total_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_total_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of input tokens from LLM requests", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 75 + }, + "id": 21, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_input_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_input_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of output tokens from LLM requests", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 75 + }, + "id": 22, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_output_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_output_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Provider-side cached input tokens (e.g. OpenAI prompt_tokens_details.cached_tokens, Anthropic cache_read_input_tokens)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 83 + }, + "id": 23, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_input_cached_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_input_cached_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Provider-side input tokens written to prompt cache (e.g. Anthropic cache_creation_input_tokens)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 83 + }, + "id": 24, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_input_cache_creation_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_input_cache_creation_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Audio input tokens reported in prompt_tokens_details.audio_tokens", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 91 + }, + "id": 25, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_input_audio_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_input_audio_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Audio output tokens reported in completion_tokens_details.audio_tokens", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 91 + }, + "id": 26, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_output_audio_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_output_audio_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Reasoning tokens reported in completion_tokens_details.reasoning_tokens", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 99 + }, + "id": 27, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_output_reasoning_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_output_reasoning_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Number of images generated, from the image generation response", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 99 + }, + "id": 28, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_images_generated_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_images_generated_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Seconds of video generated, from usage.duration_seconds on video generation calls", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 107 + }, + "id": 29, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_video_duration_seconds_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_video_duration_seconds_metric rate", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 115 + }, + "id": 30, + "panels": [], + "title": "Cache", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of LiteLLM cache hits", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 116 + }, + "id": 31, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_cache_hits_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_cache_hits_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of LiteLLM cache misses", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 116 + }, + "id": 32, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_cache_misses_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_cache_misses_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total tokens served from LiteLLM cache", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 124 + }, + "id": 33, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_cached_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_cached_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total prompt/input tokens read from provider prompt cache (e.g. OpenAI/Anthropic/Gemini/Bedrock)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 124 + }, + "id": 34, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_provider_cache_read_input_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_provider_cache_read_input_tokens_metric rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total prompt/input tokens written to provider prompt cache (e.g. Anthropic/Bedrock)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 132 + }, + "id": 35, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_provider_cache_creation_input_tokens_metric_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_provider_cache_creation_input_tokens_metric rate", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 140 + }, + "id": 36, + "panels": [], + "title": "LLM API deployments", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - The state of the deployment: 0 = healthy, 1 = partial outage, 2 = complete outage", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 141 + }, + "id": 37, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (litellm_model_name, api_base) (litellm_deployment_state)", + "legendFormat": "{{litellm_model_name}} / {{api_base}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_state", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - Total number of LLM API calls via litellm - success + failure", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 141 + }, + "id": 38, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_deployment_total_requests_total[$__rate_interval])) by (requested_model)", + "legendFormat": "{{requested_model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_total_requests rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - Total number of successful LLM API calls via litellm", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 149 + }, + "id": 39, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_deployment_success_responses_total[$__rate_interval])) by (requested_model)", + "legendFormat": "{{requested_model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_success_responses rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - Total number of failed LLM API calls for a specific LLM deploymeny. exception_status is the status of the exception from the llm api", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 149 + }, + "id": 40, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_deployment_failure_responses_total[$__rate_interval])) by (litellm_model_name, exception_class)", + "legendFormat": "{{litellm_model_name}} / {{exception_class}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_failure_responses rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - Number of times a deployment has been cooled down by LiteLLM load balancing logic. exception_status is the status of the exception that caused the deployment to be cooled down", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 157 + }, + "id": 41, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_deployment_cooled_down_total[$__rate_interval])) by (litellm_model_name, exception_status)", + "legendFormat": "{{litellm_model_name}} / {{exception_status}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_cooled_down rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - Number of successful fallback requests from primary model -> fallback model", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 157 + }, + "id": 42, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_deployment_successful_fallbacks_total[$__rate_interval])) by (requested_model, fallback_model)", + "legendFormat": "{{requested_model}} / {{fallback_model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_successful_fallbacks rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - Number of failed fallback requests from primary model -> fallback model", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 165 + }, + "id": 43, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_deployment_failed_fallbacks_total[$__rate_interval])) by (requested_model, fallback_model)", + "legendFormat": "{{requested_model}} / {{fallback_model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_failed_fallbacks rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Deployment RPM limit found in config", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 165 + }, + "id": 44, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (litellm_model_name, api_base) (litellm_deployment_rpm_limit)", + "legendFormat": "{{litellm_model_name}} / {{api_base}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_rpm_limit", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Deployment TPM limit found in config", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 173 + }, + "id": 45, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (litellm_model_name, api_base) (litellm_deployment_tpm_limit)", + "legendFormat": "{{litellm_model_name}} / {{api_base}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_deployment_tpm_limit", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "LLM Deployment Analytics - remaining requests for model, returned from LLM API Provider", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 173 + }, + "id": 46, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (model_group, api_provider) (litellm_remaining_requests_metric)", + "legendFormat": "{{model_group}} / {{api_provider}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_requests_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "remaining tokens for model, returned from LLM API Provider", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 181 + }, + "id": 47, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (model_group, api_provider) (litellm_remaining_tokens_metric)", + "legendFormat": "{{model_group}} / {{api_provider}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_tokens_metric", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 189 + }, + "id": 48, + "panels": [], + "title": "Key and team rate limits", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining Requests API Key can make for model (model based rpm limit on key)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 190 + }, + "id": 49, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (api_key_alias, model) (litellm_remaining_api_key_requests_for_model)", + "legendFormat": "{{api_key_alias}} / {{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_api_key_requests_for_model", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining Tokens API Key can make for model (model based tpm limit on key)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 190 + }, + "id": 50, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (api_key_alias, model) (litellm_remaining_api_key_tokens_for_model)", + "legendFormat": "{{api_key_alias}} / {{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_api_key_tokens_for_model", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Configured rate limit for the API Key in the current window (rpm_limit / tpm_limit), by rate_limit_type", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 198 + }, + "id": 51, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (api_key_alias, rate_limit_type) (litellm_api_key_rate_limit_allowed_metric)", + "legendFormat": "{{api_key_alias}} / {{rate_limit_type}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_api_key_rate_limit_allowed_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Requests or tokens the API Key has consumed in the current rate limit window, by rate_limit_type", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 198 + }, + "id": 52, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (api_key_alias, rate_limit_type) (litellm_api_key_rate_limit_used_metric)", + "legendFormat": "{{api_key_alias}} / {{rate_limit_type}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_api_key_rate_limit_used_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Configured rate limit for the Team in the current window (team rpm_limit / tpm_limit), by rate_limit_type", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 206 + }, + "id": 53, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (team_alias, rate_limit_type) (litellm_team_rate_limit_allowed_metric)", + "legendFormat": "{{team_alias}} / {{rate_limit_type}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_team_rate_limit_allowed_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Requests or tokens the Team has consumed in the current rate limit window, by rate_limit_type", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 206 + }, + "id": 54, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (team_alias, rate_limit_type) (litellm_team_rate_limit_used_metric)", + "legendFormat": "{{team_alias}} / {{rate_limit_type}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_team_rate_limit_used_metric", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 214 + }, + "id": 55, + "panels": [], + "title": "Budgets", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining budget for team", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 215 + }, + "id": 56, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (team_alias) (litellm_remaining_team_budget_metric)", + "legendFormat": "{{team_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_team_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Maximum budget set for team", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 215 + }, + "id": 57, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (team_alias) (litellm_team_max_budget_metric)", + "legendFormat": "{{team_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_team_max_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining days for team budget to be reset", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "h" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 223 + }, + "id": 58, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (team_alias) (litellm_team_budget_remaining_hours_metric)", + "legendFormat": "{{team_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_team_budget_remaining_hours_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining budget for api key", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 223 + }, + "id": 59, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (api_key_alias) (litellm_remaining_api_key_budget_metric)", + "legendFormat": "{{api_key_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_api_key_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Maximum budget set for api key", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 231 + }, + "id": 60, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (api_key_alias) (litellm_api_key_max_budget_metric)", + "legendFormat": "{{api_key_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_api_key_max_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining hours for api key budget to be reset", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "h" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 231 + }, + "id": 61, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (api_key_alias) (litellm_api_key_budget_remaining_hours_metric)", + "legendFormat": "{{api_key_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_api_key_budget_remaining_hours_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining budget for user", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 239 + }, + "id": 62, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (user) (litellm_remaining_user_budget_metric)", + "legendFormat": "{{user}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_user_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Maximum budget set for user", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 239 + }, + "id": 63, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (user) (litellm_user_max_budget_metric)", + "legendFormat": "{{user}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_user_max_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining hours for user budget to be reset", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "h" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 247 + }, + "id": 64, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (user) (litellm_user_budget_remaining_hours_metric)", + "legendFormat": "{{user}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_user_budget_remaining_hours_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining budget for org", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 247 + }, + "id": 65, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (org_alias) (litellm_remaining_org_budget_metric)", + "legendFormat": "{{org_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_org_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Maximum budget set for org", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 255 + }, + "id": 66, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (org_alias) (litellm_org_max_budget_metric)", + "legendFormat": "{{org_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_org_max_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining hours for org budget to be reset", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "h" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 255 + }, + "id": 67, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (org_alias) (litellm_org_budget_remaining_hours_metric)", + "legendFormat": "{{org_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_org_budget_remaining_hours_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining budget for customer (end user)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 263 + }, + "id": 68, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "min by (end_user) (litellm_remaining_customer_budget_metric)", + "legendFormat": "{{end_user}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_remaining_customer_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Maximum budget set for customer (end user)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 263 + }, + "id": 69, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (end_user) (litellm_customer_max_budget_metric)", + "legendFormat": "{{end_user}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_customer_max_budget_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining hours for customer (end user) budget to be reset", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "h" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 271 + }, + "id": 70, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (end_user) (litellm_customer_budget_remaining_hours_metric)", + "legendFormat": "{{end_user}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_customer_budget_remaining_hours_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Remaining budget for provider - used when you set provider budget limits", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 271 + }, + "id": 71, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (api_provider) (litellm_provider_remaining_budget_metric)", + "legendFormat": "{{api_provider}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_provider_remaining_budget_metric", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 279 + }, + "id": 72, + "panels": [], + "title": "Guardrails", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of guardrail invocations", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 280 + }, + "id": 73, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_guardrail_requests_total[$__rate_interval])) by (guardrail_name, status)", + "legendFormat": "{{guardrail_name}} / {{status}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_guardrail_requests rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of errors encountered during guardrail execution", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 280 + }, + "id": 74, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_guardrail_errors_total[$__rate_interval])) by (guardrail_name, error_type)", + "legendFormat": "{{guardrail_name}} / {{error_type}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_guardrail_errors rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Latency (seconds) for guardrail execution", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 288 + }, + "id": 75, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_guardrail_latency_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_guardrail_latency_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_guardrail_latency_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_guardrail_latency_seconds p50 / p95 / p99", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 296 + }, + "id": 76, + "panels": [], + "title": "MCP", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total MCP tool calls, segmented by tool and server name", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 297 + }, + "id": 77, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_mcp_tool_calls_total[$__rate_interval])) by (mcp_server_name, mcp_tool_name)", + "legendFormat": "{{mcp_server_name}} / {{mcp_tool_name}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_mcp_tool_calls rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total spend on MCP tool calls, segmented by tool and server name", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "currencyUSD" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 297 + }, + "id": 78, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_mcp_tool_call_spend_metric_total[$__rate_interval])) by (mcp_server_name, mcp_tool_name)", + "legendFormat": "{{mcp_server_name}} / {{mcp_tool_name}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_mcp_tool_call_spend_metric rate", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 305 + }, + "id": 79, + "panels": [], + "title": "Managed files and batches", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of managed files created", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 306 + }, + "id": 80, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_managed_file_created_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_managed_file_created rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of managed file deletions (success or blocked)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 306 + }, + "id": 81, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_managed_file_deleted_total[$__rate_interval])) by (result)", + "legendFormat": "{{result}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_managed_file_deleted rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Size of the most recent managed batch file in bytes (last-seen value per label combination)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "bytes" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 314 + }, + "id": 82, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (purpose, model) (litellm_managed_file_size_bytes)", + "legendFormat": "{{purpose}} / {{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_managed_file_size_bytes", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of managed batches created", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 314 + }, + "id": 83, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_managed_batch_created_total[$__rate_interval])) by (model)", + "legendFormat": "{{model}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_managed_batch_created rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Duration of completed managed batches in seconds (completed_at - created_at)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 322 + }, + "id": 84, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_managed_batch_duration_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_managed_batch_duration_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_managed_batch_duration_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_managed_batch_duration_seconds p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Number of unprocessed batches found by the last CheckBatchCost poll", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 322 + }, + "id": 85, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "litellm_check_batch_cost_jobs_polled", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "litellm_check_batch_cost_jobs_polled", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of batches successfully cost-tracked by CheckBatchCost", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 330 + }, + "id": 86, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_check_batch_cost_jobs_processed_total[$__rate_interval])) by (model, api_provider)", + "legendFormat": "{{model}} / {{api_provider}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_check_batch_cost_jobs_processed rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of errors in CheckBatchCost by error type", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 330 + }, + "id": 87, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_check_batch_cost_errors_total[$__rate_interval])) by (error_type)", + "legendFormat": "{{error_type}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_check_batch_cost_errors rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Unix timestamp of the last CheckBatchCost job run", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 338 + }, + "id": 88, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "time() - litellm_check_batch_cost_last_run_timestamp", + "legendFormat": "seconds since last run", + "range": true, + "refId": "A" + } + ], + "title": "litellm_check_batch_cost_last_run_timestamp (seconds since last run)", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 346 + }, + "id": 89, + "panels": [], + "title": "Users, teams and callbacks", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of users in LiteLLM", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 347 + }, + "id": 90, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "litellm_total_users", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "litellm_total_users", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Number of billable users in LiteLLM (excludes SCIM-deactivated users)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 347 + }, + "id": 91, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "litellm_active_users", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "litellm_active_users", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of teams in LiteLLM", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 355 + }, + "id": 92, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "litellm_teams_count", + "legendFormat": "__auto", + "range": true, + "refId": "A" + } + ], + "title": "litellm_teams_count", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Number of members in a team", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 355 + }, + "id": 93, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (team_alias) (litellm_team_members_metric)", + "legendFormat": "{{team_alias}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_team_members_metric", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Total number of failures when emitting logs to callbacks (e.g. s3_v2, langfuse, etc)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 363 + }, + "id": 94, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_callback_logging_failures_metric_total[$__rate_interval])) by (callback_name)", + "legendFormat": "{{callback_name}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_callback_logging_failures_metric rate", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 371 + }, + "id": 95, + "panels": [], + "title": "Redis circuit breaker (needs a Redis cache)", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Number of Redis circuit breakers currently in each state", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 372 + }, + "id": 96, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (state) (litellm_redis_circuit_breaker_state)", + "legendFormat": "{{state}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_redis_circuit_breaker_state", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Redis circuit breaker state transitions", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 372 + }, + "id": 97, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_circuit_breaker_transitions_total[$__rate_interval])) by (state)", + "legendFormat": "{{state}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_redis_circuit_breaker_transitions rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Redis health failures counted by the circuit breaker", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 380 + }, + "id": 98, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_circuit_breaker_failures_total[$__rate_interval])) by (failure_class)", + "legendFormat": "{{failure_class}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_redis_circuit_breaker_failures rate", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 388 + }, + "id": 99, + "panels": [], + "title": "Spend log cleanup job (needs spend log retention enabled)", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Retention cleanup runs, labelled by why the run ended", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 389 + }, + "id": 100, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_spend_log_cleanup_runs_total[$__rate_interval])) by (outcome)", + "legendFormat": "{{outcome}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_spend_log_cleanup_runs rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Rows deleted by the spend-log retention cleanup job", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 389 + }, + "id": 101, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_spend_log_cleanup_rows_deleted_total[$__rate_interval])) by (table)", + "legendFormat": "{{table}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_spend_log_cleanup_rows_deleted rate", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Expired rows still awaiting deletion, counted only up to SPEND_LOG_CLEANUP_REMAINING_COUNT_CAP so the probe itself cannot scan a large table; a value equal to that cap means at least that many remain", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 397 + }, + "id": 102, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max by (table) (litellm_spend_log_cleanup_rows_remaining)", + "legendFormat": "{{table}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_spend_log_cleanup_rows_remaining", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Wall-clock duration of one retention cleanup delete batch", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 397 + }, + "id": 103, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.5, sum(rate(litellm_spend_log_cleanup_batch_duration_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p50", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_spend_log_cleanup_batch_duration_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p95", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(litellm_spend_log_cleanup_batch_duration_seconds_bucket[$__rate_interval])) by (le))", + "legendFormat": "p99", + "range": true, + "refId": "C" + } + ], + "title": "litellm_spend_log_cleanup_batch_duration_seconds p50 / p95 / p99", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Retention cleanup delete batches that raised", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 405 + }, + "id": 104, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_spend_log_cleanup_batch_failures_total[$__rate_interval])) by (table)", + "legendFormat": "{{table}}", + "range": true, + "refId": "A" + } + ], + "title": "litellm_spend_log_cleanup_batch_failures rate", + "type": "timeseries" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 413 + }, + "id": 105, + "panels": [], + "title": "Service callbacks (needs service_callback: prometheus_system)", + "type": "row" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "p95 latency per internal service: redis, postgres, router, auth, batch writes, budget reset, proxy pre-call hooks and the proxy itself (self)", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "s" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 414 + }, + "id": 106, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_auth_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "auth", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_batch_write_to_db_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "batch_write_to_db", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_postgres_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "postgres", + "range": true, + "refId": "C" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_proxy_pre_call_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "proxy_pre_call", + "range": true, + "refId": "D" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_redis_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "redis", + "range": true, + "refId": "E" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_redis_daily_org_spend_update_queue_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "redis_daily_org_spend_update_queue", + "range": true, + "refId": "F" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_redis_daily_tag_spend_update_queue_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "redis_daily_tag_spend_update_queue", + "range": true, + "refId": "G" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_redis_daily_team_spend_update_queue_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "redis_daily_team_spend_update_queue", + "range": true, + "refId": "H" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_redis_window_spend_update_queue_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "redis_window_spend_update_queue", + "range": true, + "refId": "I" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_reset_budget_job_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "reset_budget_job", + "range": true, + "refId": "J" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_router_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "router", + "range": true, + "refId": "K" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.95, sum(rate(litellm_self_latency_bucket[$__rate_interval])) by (le))", + "legendFormat": "self", + "range": true, + "refId": "L" + } + ], + "title": "Service latency p95 (litellm__latency)", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Requests per second handled by each internal service", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "reqps" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 414 + }, + "id": 107, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_auth_total_requests_total[$__rate_interval]))", + "legendFormat": "auth", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_batch_write_to_db_total_requests_total[$__rate_interval]))", + "legendFormat": "batch_write_to_db", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_postgres_total_requests_total[$__rate_interval]))", + "legendFormat": "postgres", + "range": true, + "refId": "C" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_proxy_pre_call_total_requests_total[$__rate_interval]))", + "legendFormat": "proxy_pre_call", + "range": true, + "refId": "D" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_total_requests_total[$__rate_interval]))", + "legendFormat": "redis", + "range": true, + "refId": "E" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_daily_org_spend_update_queue_total_requests_total[$__rate_interval]))", + "legendFormat": "redis_daily_org_spend_update_queue", + "range": true, + "refId": "F" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_daily_tag_spend_update_queue_total_requests_total[$__rate_interval]))", + "legendFormat": "redis_daily_tag_spend_update_queue", + "range": true, + "refId": "G" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_daily_team_spend_update_queue_total_requests_total[$__rate_interval]))", + "legendFormat": "redis_daily_team_spend_update_queue", + "range": true, + "refId": "H" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_window_spend_update_queue_total_requests_total[$__rate_interval]))", + "legendFormat": "redis_window_spend_update_queue", + "range": true, + "refId": "I" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_reset_budget_job_total_requests_total[$__rate_interval]))", + "legendFormat": "reset_budget_job", + "range": true, + "refId": "J" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_router_total_requests_total[$__rate_interval]))", + "legendFormat": "router", + "range": true, + "refId": "K" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_self_total_requests_total[$__rate_interval]))", + "legendFormat": "self", + "range": true, + "refId": "L" + } + ], + "title": "Service request rate (litellm__total_requests)", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Failed requests per second per internal service, split by exception class", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "reqps" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 422 + }, + "id": 108, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_auth_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "auth / {{error_class}}", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_batch_write_to_db_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "batch_write_to_db / {{error_class}}", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_postgres_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "postgres / {{error_class}}", + "range": true, + "refId": "C" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_proxy_pre_call_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "proxy_pre_call / {{error_class}}", + "range": true, + "refId": "D" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "redis / {{error_class}}", + "range": true, + "refId": "E" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_daily_org_spend_update_queue_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "redis_daily_org_spend_update_queue / {{error_class}}", + "range": true, + "refId": "F" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_daily_tag_spend_update_queue_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "redis_daily_tag_spend_update_queue / {{error_class}}", + "range": true, + "refId": "G" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_daily_team_spend_update_queue_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "redis_daily_team_spend_update_queue / {{error_class}}", + "range": true, + "refId": "H" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_redis_window_spend_update_queue_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "redis_window_spend_update_queue / {{error_class}}", + "range": true, + "refId": "I" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_reset_budget_job_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "reset_budget_job / {{error_class}}", + "range": true, + "refId": "J" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_router_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "router / {{error_class}}", + "range": true, + "refId": "K" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum(rate(litellm_self_failed_requests_total[$__rate_interval])) by (error_class)", + "legendFormat": "self / {{error_class}}", + "range": true, + "refId": "L" + } + ], + "title": "Service failure rate (litellm__failed_requests)", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "description": "Items waiting in the in-memory and Redis spend update queues plus the pod lock manager", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 1, + "showPoints": "never", + "spanNulls": false + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 422 + }, + "id": 109, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max(litellm_in_memory_daily_spend_update_queue_size)", + "legendFormat": "in_memory_daily_spend_update_queue", + "range": true, + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max(litellm_in_memory_spend_update_queue_size)", + "legendFormat": "in_memory_spend_update_queue", + "range": true, + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max(litellm_pod_lock_manager_size)", + "legendFormat": "pod_lock_manager", + "range": true, + "refId": "C" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max(litellm_redis_daily_agent_spend_update_queue_size)", + "legendFormat": "redis_daily_agent_spend_update_queue", + "range": true, + "refId": "D" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max(litellm_redis_daily_end_user_spend_update_queue_size)", + "legendFormat": "redis_daily_end_user_spend_update_queue", + "range": true, + "refId": "E" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max(litellm_redis_daily_spend_update_queue_size)", + "legendFormat": "redis_daily_spend_update_queue", + "range": true, + "refId": "F" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "max(litellm_redis_spend_update_queue_size)", + "legendFormat": "redis_spend_update_queue", + "range": true, + "refId": "G" + } + ], + "title": "Spend update queue sizes (litellm__size)", + "type": "timeseries" + } + ], + "preload": false, + "refresh": "30s", + "schemaVersion": 40, + "tags": [ + "litellm", + "prometheus" + ], + "templating": { + "list": [ + { + "current": { + "selected": false, + "text": "prometheus", + "value": "prometheus" + }, + "hide": 0, + "includeAll": false, + "label": "datasource", + "multi": false, + "name": "DS_PROMETHEUS", + "options": [], + "query": "prometheus", + "queryValue": "", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "type": "datasource" + } + ] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": {}, + "timezone": "browser", + "title": "LiteLLM All Prometheus Metrics", + "uid": "litellm-all-prometheus-metrics", + "version": 1, + "weekStart": "" +} diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/readme.md b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/readme.md new file mode 100644 index 00000000000..6c491153562 --- /dev/null +++ b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/readme.md @@ -0,0 +1,11 @@ +# LiteLLM All Prometheus Metrics dashboard + +Every `litellm_*` metric family the proxy can expose on `/metrics` (134 families across 95 panels), grouped into rows: proxy traffic, latency, spend and tokens, cache, LLM API deployments, key and team rate limits, budgets, guardrails, MCP, managed files and batches, users and teams, the Redis circuit breaker, the spend log cleanup job, and the `prometheus_system` service callback metrics (per-service latency, request and failure rates, spend update queue sizes). Panel titles are the metric names so you can grep the JSON for the metric you care about + +Import `grafana_dashboard.json` from **Dashboards > New > Import** and pick your Prometheus data source when prompted (the `DS_PROMETHEUS` variable). Counters are plotted as `rate()` over `$__rate_interval`, histograms as p50 / p95 / p99, gauges as the raw value grouped by the most useful label. Every query names the metric exactly as the proxy emits it (counters carry the `_total` suffix the Prometheus client adds), and `tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py` fails if a metric is renamed without updating this dashboard + +The first eleven rows need only `callbacks: ["prometheus"]`. The last three rows and the `litellm_admission_*` panels are emitted by other subsystems and stay empty until those are on: the service callback row needs `service_callback: ["prometheus_system"]` in `litellm_settings`, the circuit breaker row needs a Redis cache, the cleanup row needs spend log retention, and admission control needs its middleware enabled. Within the base rows, many panels only fill in once the matching feature is in use: budgets need keys, teams, users or orgs with `max_budget` set, cache panels need caching on, guardrail and MCP panels need those features configured, deployment health needs the router with more than one deployment or a failure to record, and `litellm_in_flight_requests` needs traffic at scrape time. An empty panel for a feature you do not use is expected + +## Pre-requisites + +Prometheus metrics on the proxy: https://docs.litellm.ai/docs/proxy/prometheus diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_v2/grafana_dashboard.json b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_v2/grafana_dashboard.json index 503364d8ff2..7a08cd5c5e9 100644 --- a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_v2/grafana_dashboard.json +++ b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_v2/grafana_dashboard.json @@ -476,7 +476,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "topk(5, sort(litellm_remaining_requests))", + "expr": "topk(5, sort(litellm_remaining_requests_metric))", "legendFormat": "__auto", "range": true, "refId": "A" @@ -573,7 +573,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "topk(5, sort(litellm_remaining_tokens))", + "expr": "topk(5, sort(litellm_remaining_tokens_metric))", "legendFormat": "__auto", "range": true, "refId": "A" diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/readme.md b/cookbook/litellm_proxy_server/grafana_dashboard/readme.md index a1564a406e0..f10235f0073 100644 --- a/cookbook/litellm_proxy_server/grafana_dashboard/readme.md +++ b/cookbook/litellm_proxy_server/grafana_dashboard/readme.md @@ -6,8 +6,14 @@ This folder contains the `json` for creating Grafana Dashboards Charts the `gen_ai.*` metrics from the OpenTelemetry v2 integration: spend, tokens, request rate, and latency percentiles by model. Separate from the dashboards below, which chart the `litellm_*` Prometheus metrics. +## [LiteLLM All Prometheus Metrics dashboard](./dashboard_all_metrics) + +Every `litellm_*` Prometheus metric family the proxy can emit (134 families, 95 panels) grouped by theme: traffic, latency, spend and tokens, cache, deployments, rate limits, budgets, guardrails, MCP, managed files and batches, users and teams, plus the Redis circuit breaker, spend log cleanup and `prometheus_system` service metrics. Start here if you want everything on one screen; see its [readme](./dashboard_all_metrics/readme.md) for import steps and which panels need a feature enabled before they show data + ## [LiteLLM v2 Dashboard](./dashboard_v2) +A compact view of proxy request rate, failures, latency and the top remaining-request / remaining-token gauges per model group + grafana_1 grafana_2 grafana_3 diff --git a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py index 0932925d810..61619945c50 100644 --- a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py +++ b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py @@ -8,9 +8,110 @@ configuration works correctly. Related issue: https://github.com/BerriAI/litellm/issues/18221 """ -from typing import get_args +import json +import re +from collections.abc import Iterator +from pathlib import Path +from typing import Final, get_args import pytest +from prometheus_client import REGISTRY +from prometheus_client.registry import Collector + +import litellm +from litellm.caching.redis_cache import _BreakerMetrics +from litellm.integrations.prometheus import PrometheusLogger +from litellm.integrations.prometheus_services import PrometheusServicesLogger +from litellm.proxy.db.db_transaction_queue.spend_log_cleanup_metrics import SpendLogCleanupMetrics +from litellm.proxy.middleware.admission_control_middleware import create_prometheus_admission_metrics +from litellm.proxy.middleware.in_flight_requests_middleware import InFlightRequestsMiddleware + +_GRAFANA_DIR: Final = Path(__file__).parents[3] / "cookbook" / "litellm_proxy_server" / "grafana_dashboard" +_ALL_METRICS_DASHBOARD: Final = _GRAFANA_DIR / "dashboard_all_metrics" / "grafana_dashboard.json" +_LITELLM_DASHBOARDS: Final = (_ALL_METRICS_DASHBOARD, _GRAFANA_DIR / "dashboard_v2" / "grafana_dashboard.json") +_METRIC_TOKEN_RE: Final = re.compile(r"\blitellm_[a-z0-9_]+") +_BY_CLAUSE_RE: Final = re.compile(r"\bby\s*\([^)]*\)") +_EXPOSITION_SUFFIXES: Final = ("", "_total", "_bucket", "_sum", "_count", "_created") + + +def _lazily_registered_collectors() -> tuple[Collector, ...]: + SpendLogCleanupMetrics._ensure_initialized() + collectors: Final = ( + InFlightRequestsMiddleware._get_gauge(), + SpendLogCleanupMetrics.rows_deleted, + SpendLogCleanupMetrics.batch_duration, + SpendLogCleanupMetrics.rows_remaining, + SpendLogCleanupMetrics.batch_failures, + SpendLogCleanupMetrics.runs, + ) + assert all(collector is not None for collector in collectors) + return tuple(collector for collector in collectors if collector is not None) + + +@pytest.fixture +def emitted_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterator[frozenset[str]]: + for collector in list(REGISTRY._collector_to_names.keys()): + REGISTRY.unregister(collector) + monkeypatch.setattr(litellm, "prometheus_metrics_config", None) + PrometheusLogger() + PrometheusServicesLogger() + _BreakerMetrics() + assert create_prometheus_admission_metrics() is not None + families: Final = frozenset( + metric.name for collector in (REGISTRY, *_lazily_registered_collectors()) for metric in collector.collect() + ) + yield families + for collector in list(REGISTRY._collector_to_names.keys()): + REGISTRY.unregister(collector) + + +def _dashboard_expressions(path: Path) -> tuple[str, ...]: + dashboard: Final = json.loads(path.read_text()) + return tuple(target["expr"] for panel in dashboard["panels"] for target in panel.get("targets", ())) + + +def _referenced_metric_tokens(path: Path) -> frozenset[str]: + return frozenset( + token + for expr in _dashboard_expressions(path) + for token in _METRIC_TOKEN_RE.findall(_BY_CLAUSE_RE.sub("", expr)) + ) + + +def _family_of(token: str, families: frozenset[str]) -> str | None: + candidates: Final = (token.removesuffix(suffix) for suffix in _EXPOSITION_SUFFIXES if token.endswith(suffix)) + return next((candidate for candidate in candidates if candidate in families), None) + + +def test_all_metrics_dashboard_charts_every_emitted_metric_family(emitted_metric_families: frozenset[str]): + referenced: Final = _referenced_metric_tokens(_ALL_METRICS_DASHBOARD) + charted: Final = frozenset( + family for token in referenced for family in (_family_of(token, emitted_metric_families),) if family + ) + assert emitted_metric_families - charted == frozenset() + + +@pytest.mark.parametrize("dashboard_path", _LITELLM_DASHBOARDS, ids=lambda p: p.parent.name) +def test_dashboards_only_reference_emitted_metrics(dashboard_path: Path, emitted_metric_families: frozenset[str]): + dead: Final = frozenset( + token + for token in _referenced_metric_tokens(dashboard_path) + if _family_of(token, emitted_metric_families) is None + ) + assert dead == frozenset() + + +@pytest.mark.parametrize("dashboard_path", _LITELLM_DASHBOARDS, ids=lambda p: p.parent.name) +def test_dashboards_use_templated_prometheus_datasource(dashboard_path: Path): + dashboard: Final = json.loads(dashboard_path.read_text()) + datasource_variables: Final = tuple( + variable["name"] for variable in dashboard["templating"]["list"] if variable["type"] == "datasource" + ) + assert datasource_variables == ("DS_PROMETHEUS",) + panel_datasource_uids: Final = frozenset( + panel["datasource"]["uid"] for panel in dashboard["panels"] if panel["type"] != "row" + ) + assert panel_datasource_uids == frozenset({"${DS_PROMETHEUS}"}) def test_remaining_requests_metric_name_in_defined_metrics(): From 184add7cee975a7293d3bf365d33e2294a438c32 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 08:13:31 +0000 Subject: [PATCH 08/36] fix(grafana): hide the batch cost last-run panel until the job has run once Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../dashboard_all_metrics/grafana_dashboard.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json index 9d7029ca464..230e1e788fc 100644 --- a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json +++ b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json @@ -4787,7 +4787,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "time() - litellm_check_batch_cost_last_run_timestamp", + "expr": "time() - (litellm_check_batch_cost_last_run_timestamp > 0)", "legendFormat": "seconds since last run", "range": true, "refId": "A" From aa1fedbfddc77e89421dcbae346585aac71c9d70 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 08:20:50 +0000 Subject: [PATCH 09/36] fix(grafana): reset lazy Prometheus collectors in the dashboard test fixture and state the overhead panel unit in seconds Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../grafana_dashboard.json | 2 +- ...test_prometheus_metric_name_consistency.py | 38 ++++++++----------- 2 files changed, 16 insertions(+), 24 deletions(-) diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json index 230e1e788fc..671ea14c220 100644 --- a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json +++ b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json @@ -825,7 +825,7 @@ "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, - "description": "Latency overhead (milliseconds) added by LiteLLM processing", + "description": "Latency overhead (seconds) added by LiteLLM processing", "fieldConfig": { "defaults": { "color": { diff --git a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py index 61619945c50..a6e32a3c98a 100644 --- a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py +++ b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py @@ -16,10 +16,9 @@ from typing import Final, get_args import pytest from prometheus_client import REGISTRY -from prometheus_client.registry import Collector import litellm -from litellm.caching.redis_cache import _BreakerMetrics +from litellm.caching.redis_cache import _breaker_metrics from litellm.integrations.prometheus import PrometheusLogger from litellm.integrations.prometheus_services import PrometheusServicesLogger from litellm.proxy.db.db_transaction_queue.spend_log_cleanup_metrics import SpendLogCleanupMetrics @@ -34,35 +33,28 @@ _BY_CLAUSE_RE: Final = re.compile(r"\bby\s*\([^)]*\)") _EXPOSITION_SUFFIXES: Final = ("", "_total", "_bucket", "_sum", "_count", "_created") -def _lazily_registered_collectors() -> tuple[Collector, ...]: - SpendLogCleanupMetrics._ensure_initialized() - collectors: Final = ( - InFlightRequestsMiddleware._get_gauge(), - SpendLogCleanupMetrics.rows_deleted, - SpendLogCleanupMetrics.batch_duration, - SpendLogCleanupMetrics.rows_remaining, - SpendLogCleanupMetrics.batch_failures, - SpendLogCleanupMetrics.runs, - ) - assert all(collector is not None for collector in collectors) - return tuple(collector for collector in collectors if collector is not None) +def _reset_default_registry() -> None: + for collector in list(REGISTRY._collector_to_names.keys()): + REGISTRY.unregister(collector) + SpendLogCleanupMetrics._initialized = False + InFlightRequestsMiddleware._gauge_init_attempted = False + InFlightRequestsMiddleware._gauge = None + _breaker_metrics.cache_clear() @pytest.fixture def emitted_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterator[frozenset[str]]: - for collector in list(REGISTRY._collector_to_names.keys()): - REGISTRY.unregister(collector) + _reset_default_registry() monkeypatch.setattr(litellm, "prometheus_metrics_config", None) PrometheusLogger() PrometheusServicesLogger() - _BreakerMetrics() + SpendLogCleanupMetrics._ensure_initialized() + assert SpendLogCleanupMetrics.runs is not None + assert InFlightRequestsMiddleware._get_gauge() is not None + assert _breaker_metrics()._state_gauge is not None assert create_prometheus_admission_metrics() is not None - families: Final = frozenset( - metric.name for collector in (REGISTRY, *_lazily_registered_collectors()) for metric in collector.collect() - ) - yield families - for collector in list(REGISTRY._collector_to_names.keys()): - REGISTRY.unregister(collector) + yield frozenset(metric.name for metric in REGISTRY.collect()) + _reset_default_registry() def _dashboard_expressions(path: Path) -> tuple[str, ...]: From 4aa8d06edad0ed2c5bea68f3a1f29e815c0d2481 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 08:45:46 +0000 Subject: [PATCH 10/36] test(prometheus): restore unrelated collectors after the dashboard consistency fixture Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- ...test_prometheus_metric_name_consistency.py | 61 ++++++++++++++++--- 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py index a6e32a3c98a..d78ddf32e4c 100644 --- a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py +++ b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py @@ -11,11 +11,14 @@ Related issue: https://github.com/BerriAI/litellm/issues/18221 import json import re from collections.abc import Iterator +from contextlib import contextmanager from pathlib import Path +from types import MappingProxyType from typing import Final, get_args import pytest -from prometheus_client import REGISTRY +from prometheus_client import REGISTRY, Gauge +from prometheus_client.registry import Collector import litellm from litellm.caching.redis_cache import _breaker_metrics @@ -33,8 +36,12 @@ _BY_CLAUSE_RE: Final = re.compile(r"\bby\s*\([^)]*\)") _EXPOSITION_SUFFIXES: Final = ("", "_total", "_bucket", "_sum", "_count", "_created") -def _reset_default_registry() -> None: - for collector in list(REGISTRY._collector_to_names.keys()): +def _registered_collectors() -> MappingProxyType[Collector, tuple[str, ...]]: + return MappingProxyType({collector: tuple(names) for collector, names in REGISTRY._collector_to_names.items()}) + + +def _clear_default_registry_and_lazy_owners() -> None: + for collector in tuple(REGISTRY._collector_to_names): REGISTRY.unregister(collector) SpendLogCleanupMetrics._initialized = False InFlightRequestsMiddleware._gauge_init_attempted = False @@ -42,19 +49,57 @@ def _reset_default_registry() -> None: _breaker_metrics.cache_clear() -@pytest.fixture -def emitted_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterator[frozenset[str]]: - _reset_default_registry() +@contextmanager +def _isolated_litellm_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterator[frozenset[str]]: + previous: Final = _registered_collectors() + _clear_default_registry_and_lazy_owners() monkeypatch.setattr(litellm, "prometheus_metrics_config", None) PrometheusLogger() PrometheusServicesLogger() + logger_collectors: Final = frozenset(REGISTRY._collector_to_names) SpendLogCleanupMetrics._ensure_initialized() assert SpendLogCleanupMetrics.runs is not None assert InFlightRequestsMiddleware._get_gauge() is not None assert _breaker_metrics()._state_gauge is not None assert create_prometheus_admission_metrics() is not None - yield frozenset(metric.name for metric in REGISTRY.collect()) - _reset_default_registry() + lazy_owner_names: Final = frozenset( + name + for collector, names in _registered_collectors().items() + if collector not in logger_collectors + for name in names + ) + try: + yield frozenset(metric.name for metric in REGISTRY.collect()) + finally: + _clear_default_registry_and_lazy_owners() + for collector, names in previous.items(): + if lazy_owner_names.isdisjoint(names): + REGISTRY.register(collector) + + +@pytest.fixture +def emitted_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterator[frozenset[str]]: + with _isolated_litellm_metric_families(monkeypatch) as families: + yield families + + +@pytest.fixture +def unrelated_gauge() -> Iterator[Gauge]: + gauge: Final = Gauge("litellm_unrelated_sentinel", "registered by a test outside the isolated block") + yield gauge + if gauge in REGISTRY._collector_to_names: + REGISTRY.unregister(gauge) + + +def test_isolated_metric_families_restore_unrelated_collectors_and_lazy_owners( + monkeypatch: pytest.MonkeyPatch, unrelated_gauge: Gauge +): + with _isolated_litellm_metric_families(monkeypatch) as families: + assert "litellm_unrelated_sentinel" not in families + assert unrelated_gauge not in REGISTRY._collector_to_names + assert unrelated_gauge in REGISTRY._collector_to_names + assert InFlightRequestsMiddleware._get_gauge() is not None + assert _breaker_metrics()._state_gauge is not None def _dashboard_expressions(path: Path) -> tuple[str, ...]: From 8ae2ebdfcf32c16bc901a88c08cc854840ce7e0c Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 09:00:22 +0000 Subject: [PATCH 11/36] test(prometheus): reset the admission control metric owner in the dashboard consistency fixture Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- ...test_prometheus_metric_name_consistency.py | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py index d78ddf32e4c..a81dc7cc4ad 100644 --- a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py +++ b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py @@ -25,7 +25,7 @@ from litellm.caching.redis_cache import _breaker_metrics from litellm.integrations.prometheus import PrometheusLogger from litellm.integrations.prometheus_services import PrometheusServicesLogger from litellm.proxy.db.db_transaction_queue.spend_log_cleanup_metrics import SpendLogCleanupMetrics -from litellm.proxy.middleware.admission_control_middleware import create_prometheus_admission_metrics +from litellm.proxy.middleware.admission_control_middleware import admission_control_state from litellm.proxy.middleware.in_flight_requests_middleware import InFlightRequestsMiddleware _GRAFANA_DIR: Final = Path(__file__).parents[3] / "cookbook" / "litellm_proxy_server" / "grafana_dashboard" @@ -47,6 +47,18 @@ def _clear_default_registry_and_lazy_owners() -> None: InFlightRequestsMiddleware._gauge_init_attempted = False InFlightRequestsMiddleware._gauge = None _breaker_metrics.cache_clear() + admission_control_state._metrics_init_attempted = False + admission_control_state._metrics = None + + +def _lazy_owner_collectors() -> tuple[Collector, ...]: + SpendLogCleanupMetrics._ensure_initialized() + assert SpendLogCleanupMetrics.runs is not None + in_flight: Final = InFlightRequestsMiddleware._get_gauge() + assert in_flight is not None + admission: Final = admission_control_state._get_metrics() + assert admission is not None + return (SpendLogCleanupMetrics.runs, in_flight, _breaker_metrics()._state_gauge, admission.admitted_gauge) @contextmanager @@ -57,11 +69,7 @@ def _isolated_litellm_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterat PrometheusLogger() PrometheusServicesLogger() logger_collectors: Final = frozenset(REGISTRY._collector_to_names) - SpendLogCleanupMetrics._ensure_initialized() - assert SpendLogCleanupMetrics.runs is not None - assert InFlightRequestsMiddleware._get_gauge() is not None - assert _breaker_metrics()._state_gauge is not None - assert create_prometheus_admission_metrics() is not None + _lazy_owner_collectors() lazy_owner_names: Final = frozenset( name for collector, names in _registered_collectors().items() @@ -94,12 +102,13 @@ def unrelated_gauge() -> Iterator[Gauge]: def test_isolated_metric_families_restore_unrelated_collectors_and_lazy_owners( monkeypatch: pytest.MonkeyPatch, unrelated_gauge: Gauge ): + stale: Final = _lazy_owner_collectors() with _isolated_litellm_metric_families(monkeypatch) as families: assert "litellm_unrelated_sentinel" not in families assert unrelated_gauge not in REGISTRY._collector_to_names assert unrelated_gauge in REGISTRY._collector_to_names - assert InFlightRequestsMiddleware._get_gauge() is not None - assert _breaker_metrics()._state_gauge is not None + assert all(collector not in REGISTRY._collector_to_names for collector in stale) + assert all(collector in REGISTRY._collector_to_names for collector in _lazy_owner_collectors()) def _dashboard_expressions(path: Path) -> tuple[str, ...]: From f89fb207093c86c59720622bc162c4497f21a37b Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 09:21:19 +0000 Subject: [PATCH 12/36] test(prometheus): restore the full registry and build admission metrics fresh in the dashboard fixture Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- ...test_prometheus_metric_name_consistency.py | 98 ++++++++++++------- 1 file changed, 63 insertions(+), 35 deletions(-) diff --git a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py index a81dc7cc4ad..d648afcd087 100644 --- a/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py +++ b/tests/test_litellm/integrations/test_prometheus_metric_name_consistency.py @@ -25,7 +25,7 @@ from litellm.caching.redis_cache import _breaker_metrics from litellm.integrations.prometheus import PrometheusLogger from litellm.integrations.prometheus_services import PrometheusServicesLogger from litellm.proxy.db.db_transaction_queue.spend_log_cleanup_metrics import SpendLogCleanupMetrics -from litellm.proxy.middleware.admission_control_middleware import admission_control_state +from litellm.proxy.middleware.admission_control_middleware import create_prometheus_admission_metrics from litellm.proxy.middleware.in_flight_requests_middleware import InFlightRequestsMiddleware _GRAFANA_DIR: Final = Path(__file__).parents[3] / "cookbook" / "litellm_proxy_server" / "grafana_dashboard" @@ -40,49 +40,68 @@ def _registered_collectors() -> MappingProxyType[Collector, tuple[str, ...]]: return MappingProxyType({collector: tuple(names) for collector, names in REGISTRY._collector_to_names.items()}) -def _clear_default_registry_and_lazy_owners() -> None: +def _unregister_everything() -> None: for collector in tuple(REGISTRY._collector_to_names): REGISTRY.unregister(collector) - SpendLogCleanupMetrics._initialized = False - InFlightRequestsMiddleware._gauge_init_attempted = False - InFlightRequestsMiddleware._gauge = None - _breaker_metrics.cache_clear() - admission_control_state._metrics_init_attempted = False - admission_control_state._metrics = None + + +def _register_if_absent(collectors: tuple[Collector, ...]) -> None: + for collector in collectors: + if collector not in REGISTRY._collector_to_names and not any( + name in REGISTRY._names_to_collectors for name in REGISTRY._get_names(collector) + ): + REGISTRY.register(collector) def _lazy_owner_collectors() -> tuple[Collector, ...]: SpendLogCleanupMetrics._ensure_initialized() + assert SpendLogCleanupMetrics.rows_deleted is not None + assert SpendLogCleanupMetrics.batch_duration is not None + assert SpendLogCleanupMetrics.rows_remaining is not None + assert SpendLogCleanupMetrics.batch_failures is not None assert SpendLogCleanupMetrics.runs is not None in_flight: Final = InFlightRequestsMiddleware._get_gauge() assert in_flight is not None - admission: Final = admission_control_state._get_metrics() + breaker: Final = _breaker_metrics() + assert breaker._state_gauge is not None + assert breaker._transitions is not None + assert breaker._failures is not None + return ( + SpendLogCleanupMetrics.rows_deleted, + SpendLogCleanupMetrics.batch_duration, + SpendLogCleanupMetrics.rows_remaining, + SpendLogCleanupMetrics.batch_failures, + SpendLogCleanupMetrics.runs, + in_flight, + breaker._state_gauge, + breaker._transitions, + breaker._failures, + ) + + +def _fresh_admission_collectors() -> tuple[Collector, ...]: + admission: Final = create_prometheus_admission_metrics() assert admission is not None - return (SpendLogCleanupMetrics.runs, in_flight, _breaker_metrics()._state_gauge, admission.admitted_gauge) + return (admission.admitted_gauge, admission.queued_gauge, admission.rejected_counter) @contextmanager def _isolated_litellm_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterator[frozenset[str]]: previous: Final = _registered_collectors() - _clear_default_registry_and_lazy_owners() + _unregister_everything() monkeypatch.setattr(litellm, "prometheus_metrics_config", None) PrometheusLogger() PrometheusServicesLogger() - logger_collectors: Final = frozenset(REGISTRY._collector_to_names) - _lazy_owner_collectors() - lazy_owner_names: Final = frozenset( - name - for collector, names in _registered_collectors().items() - if collector not in logger_collectors - for name in names - ) + lazy_owned: Final = _lazy_owner_collectors() + _register_if_absent(lazy_owned) + _fresh_admission_collectors() try: yield frozenset(metric.name for metric in REGISTRY.collect()) finally: - _clear_default_registry_and_lazy_owners() - for collector, names in previous.items(): - if lazy_owner_names.isdisjoint(names): - REGISTRY.register(collector) + _unregister_everything() + for collector in previous: + REGISTRY.register(collector) + _register_if_absent(lazy_owned) @pytest.fixture @@ -92,23 +111,32 @@ def emitted_metric_families(monkeypatch: pytest.MonkeyPatch) -> Iterator[frozens @pytest.fixture -def unrelated_gauge() -> Iterator[Gauge]: - gauge: Final = Gauge("litellm_unrelated_sentinel", "registered by a test outside the isolated block") - yield gauge - if gauge in REGISTRY._collector_to_names: - REGISTRY.unregister(gauge) +def gauges_registered_by_an_earlier_test() -> Iterator[tuple[Collector, Collector]]: + sentinel: Final = Gauge("litellm_unrelated_sentinel", "registered by a test outside the isolated block") + already_registered: Final = REGISTRY._names_to_collectors.get("litellm_admission_admitted_requests") + admission: Final = already_registered or Gauge( + "litellm_admission_admitted_requests", "registered directly, bypassing admission_control_state" + ) + yield (sentinel, admission) + for gauge in (sentinel,) if already_registered is not None else (sentinel, admission): + if gauge in REGISTRY._collector_to_names: + REGISTRY.unregister(gauge) -def test_isolated_metric_families_restore_unrelated_collectors_and_lazy_owners( - monkeypatch: pytest.MonkeyPatch, unrelated_gauge: Gauge +def test_isolated_metric_families_restore_the_registry_and_keep_lazy_owners_live( + monkeypatch: pytest.MonkeyPatch, gauges_registered_by_an_earlier_test: tuple[Collector, Collector] ): - stale: Final = _lazy_owner_collectors() + before: Final = _registered_collectors() with _isolated_litellm_metric_families(monkeypatch) as families: assert "litellm_unrelated_sentinel" not in families - assert unrelated_gauge not in REGISTRY._collector_to_names - assert unrelated_gauge in REGISTRY._collector_to_names - assert all(collector not in REGISTRY._collector_to_names for collector in stale) - assert all(collector in REGISTRY._collector_to_names for collector in _lazy_owner_collectors()) + assert "litellm_admission_admitted_requests" in families + assert "litellm_in_flight_requests" in families + assert not any(gauge in REGISTRY._collector_to_names for gauge in gauges_registered_by_an_earlier_test) + after: Final = _registered_collectors() + assert all(after[collector] == names for collector, names in before.items()) + lazy_owned: Final = _lazy_owner_collectors() + assert frozenset(after) - frozenset(before) <= frozenset(lazy_owned) + assert all(collector in after for collector in lazy_owned) def _dashboard_expressions(path: Path) -> tuple[str, ...]: From 880897826f9b582c17390486c8b6f2d5e6380574 Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 09:21:19 +0000 Subject: [PATCH 13/36] fix(grafana): aggregate provider remaining budget with min like the other remaining budget panels Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../dashboard_all_metrics/grafana_dashboard.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json index 671ea14c220..996bd137a9e 100644 --- a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json +++ b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json @@ -3906,7 +3906,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "max by (api_provider) (litellm_provider_remaining_budget_metric)", + "expr": "min by (api_provider) (litellm_provider_remaining_budget_metric)", "legendFormat": "{{api_provider}}", "range": true, "refId": "A" From 48b25e448d125cfbdd7c83210ff676e2c2e1c4ae Mon Sep 17 00:00:00 2001 From: yucheng Date: Thu, 17 Sep 2026 09:44:26 +0000 Subject: [PATCH 14/36] fix(grafana): sum redis circuit breaker state across workers instead of taking the max Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../dashboard_all_metrics/grafana_dashboard.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json index 996bd137a9e..d8cb122417a 100644 --- a/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json +++ b/cookbook/litellm_proxy_server/grafana_dashboard/dashboard_all_metrics/grafana_dashboard.json @@ -5155,7 +5155,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "max by (state) (litellm_redis_circuit_breaker_state)", + "expr": "sum by (state) (litellm_redis_circuit_breaker_state)", "legendFormat": "{{state}}", "range": true, "refId": "A" From 2dc9697381c14a7c599b5f726e4f54a4dec9b406 Mon Sep 17 00:00:00 2001 From: mateo Date: Thu, 17 Sep 2026 15:53:19 +0000 Subject: [PATCH 15/36] feat(proxy): add TypeSafe Jev passthrough spend tracking Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- ...odel_prices_and_context_window_backup.json | 21 +++ litellm/proxy/_lazy_features.py | 1 + litellm/proxy/_lazy_openapi_snapshot.json | 90 +++++++++++++ litellm/proxy/_types.py | 1 + .../llm_passthrough_endpoints.py | 47 +++++++ .../typesafe_passthrough_logging_handler.py | 116 ++++++++++++++++ .../pass_through_endpoints/success_handler.py | 22 +++ litellm/types/utils.py | 1 + model_prices_and_context_window.json | 21 +++ ...st_typesafe_passthrough_logging_handler.py | 127 ++++++++++++++++++ .../test_llm_pass_through_endpoints.py | 59 ++++++++ .../test_typesafe_model_metadata.py | 17 +++ 12 files changed, 523 insertions(+) create mode 100644 litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py create mode 100644 tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py create mode 100644 tests/test_litellm/test_typesafe_model_metadata.py diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index c565b6ecc4b..ed852bc490c 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -69158,5 +69158,26 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_vision": true + }, + "typesafe/jev-1.13.0": { + "input_cost_per_token": 4.2e-08, + "litellm_provider": "typesafe", + "mode": "evaluation", + "output_cost_per_token": 0.0, + "source": "https://docs.typesafe.ai/models" + }, + "typesafe/jev-latest": { + "input_cost_per_token": 4.2e-08, + "litellm_provider": "typesafe", + "mode": "evaluation", + "output_cost_per_token": 0.0, + "source": "https://docs.typesafe.ai/models" + }, + "typesafe/jev-preview": { + "input_cost_per_token": 4.2e-08, + "litellm_provider": "typesafe", + "mode": "evaluation", + "output_cost_per_token": 0.0, + "source": "https://docs.typesafe.ai/models" } } diff --git a/litellm/proxy/_lazy_features.py b/litellm/proxy/_lazy_features.py index faf95397fa5..2a28ea3763f 100644 --- a/litellm/proxy/_lazy_features.py +++ b/litellm/proxy/_lazy_features.py @@ -208,6 +208,7 @@ LAZY_FEATURES: Final[tuple[LazyFeature, ...]] = ( "/nvidia_nim/", "/openai/", "/openai_passthrough/", + "/typesafe/", "/vertex-ai/", "/vertex_ai/", "/vllm/", diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.json index 74f38b3ca6d..5e1b7c85760 100644 --- a/litellm/proxy/_lazy_openapi_snapshot.json +++ b/litellm/proxy/_lazy_openapi_snapshot.json @@ -20373,6 +20373,96 @@ ] } }, + "/typesafe/{endpoint}": { + "get": { + "description": "[Docs](https://docs.litellm.ai/docs/pass_through/typesafe)", + "operationId": "typesafe_proxy_route_typesafe__endpoint__get", + "parameters": [ + { + "in": "path", + "name": "endpoint", + "required": true, + "schema": { + "title": "Endpoint", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Typesafe Proxy Route", + "tags": [ + "llm_passthrough" + ] + }, + "post": { + "description": "[Docs](https://docs.litellm.ai/docs/pass_through/typesafe)", + "operationId": "typesafe_proxy_route_typesafe__endpoint__post", + "parameters": [ + { + "in": "path", + "name": "endpoint", + "required": true, + "schema": { + "title": "Endpoint", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Typesafe Proxy Route", + "tags": [ + "llm_passthrough" + ] + } + }, "/vertex_ai/discovery/{endpoint}": { "delete": { "description": "Call any vertex discovery endpoint using the proxy.\n\nJust use `{PROXY_BASE_URL}/vertex_ai/discovery/{endpoint:path}`\n\nTarget url: `https://discoveryengine.googleapis.com`", diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py index 680c63393e8..008cc8354b4 100644 --- a/litellm/proxy/_types.py +++ b/litellm/proxy/_types.py @@ -483,6 +483,7 @@ class LiteLLMRoutes(enum.Enum): "/eu.assemblyai", "/vllm", "/mistral", + "/typesafe", "/milvus", "/gigachat", "/watsonx", diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index b9b8cb3a22b..c75a3227366 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -525,6 +525,53 @@ async def mistral_proxy_route( return received_value +@router.api_route( + "/typesafe/{endpoint:path}", + methods=["GET", "POST"], + tags=["TypeSafe AI Pass-through", "pass-through"], +) +async def typesafe_proxy_route( + endpoint: str, + request: Request, + fastapi_response: Response, + user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), +): + """[Docs](https://docs.litellm.ai/docs/pass_through/typesafe)""" + if request.method == "POST": + try: + request_body: Final = await _json_request_body(request) + except Exception as e: + raise HTTPException(status_code=400, detail=str(e)) + if not isinstance(request_body, dict): + raise HTTPException(status_code=400, detail="Request body must be a JSON object") + if "stream" in request_body: + raise HTTPException(status_code=400, detail="'stream' is not a TypeSafe request member") + + base_target_url: Final = get_secret_str("TYPESAFE_API_BASE") or "https://api.typesafe.ai" + encoded_endpoint: Final = httpx.URL(endpoint).path + normalized_endpoint: Final = encoded_endpoint if encoded_endpoint.startswith("/") else f"/{encoded_endpoint}" + base_url: Final = httpx.URL(base_target_url) + updated_url: Final = base_url.copy_with( + path=HttpPassThroughEndpointHelpers.join_base_and_endpoint_path(base_url, normalized_endpoint), + params=request.query_params, + ) + typesafe_api_key: Final = passthrough_endpoint_router.get_credentials( + custom_llm_provider="typesafe", + region_name=None, + ) + endpoint_func: Final = create_pass_through_route( + endpoint=endpoint, + target=str(updated_url), + custom_headers={ + "Authorization": f"Bearer {typesafe_api_key}", + "Content-Type": "application/json", + }, + custom_llm_provider="typesafe", + is_streaming_request=False, + ) + return await endpoint_func(request, fastapi_response, user_api_key_dict) + + @router.api_route( "/milvus/{endpoint:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"], diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py new file mode 100644 index 00000000000..b9ba265044d --- /dev/null +++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py @@ -0,0 +1,116 @@ +from collections.abc import Mapping +from datetime import datetime +from typing import Final, cast + +import httpx +from pydantic import BaseModel, TypeAdapter, ValidationError + +import litellm +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.litellm_core_utils.litellm_logging import ( + get_standard_logging_object_payload, # pyright: ignore[reportUnknownVariableType] # legacy helper has an untyped signature +) +from litellm.proxy._types import PassThroughEndpointLoggingTypedDict +from litellm.types.utils import ModelResponse, StandardPassThroughResponseObject, Usage + + +class _TypeSafeUsage(BaseModel): + input_tokens: int = 0 + output_tokens: int = 0 + + +class _TypeSafeResponse(BaseModel): + model: str | None = None + usage: _TypeSafeUsage | None = None + + +_TYPESAFE_RESPONSE_ADAPTER: Final = TypeAdapter(_TypeSafeResponse) +_MODEL_COST_ENTRY_ADAPTER: Final = TypeAdapter(dict[str, object]) + + +def _parse_typesafe_response(response_body: Mapping[str, object]) -> _TypeSafeResponse: + try: + return _TYPESAFE_RESPONSE_ADAPTER.validate_python(response_body) + except ValidationError: + return _TypeSafeResponse() + + +def _get_model_cost_entry(model_key: str) -> Mapping[str, object] | None: + model_cost: Final[Mapping[str, object]] = cast(Mapping[str, object], litellm.model_cost) + entry: Final[object] = model_cost.get(model_key) + try: + return _MODEL_COST_ENTRY_ADAPTER.validate_python(entry) + except ValidationError: + return None + + +class TypeSafePassthroughLoggingHandler: + @staticmethod + def typesafe_passthrough_handler( + httpx_response: httpx.Response, + response_body: Mapping[str, object], + logging_obj: LiteLLMLoggingObj, + url_route: str, + result: str, + start_time: datetime, + end_time: datetime, + cache_hit: bool, + request_body: Mapping[str, object], + **kwargs: object, + ) -> PassThroughEndpointLoggingTypedDict: + response: Final = _parse_typesafe_response(response_body) + response_model: Final = response.model + request_model_value: Final = request_body.get("model") + request_model: Final = request_model_value if isinstance(request_model_value, str) else None + logged_model: Final = response_model or request_model or "jev-latest" + model_name: Final = f"typesafe/{logged_model}" + usage: Final = response.usage or _TypeSafeUsage() + input_tokens: Final = usage.input_tokens + output_tokens: Final = usage.output_tokens + candidate_model_keys: Final = tuple( + f"typesafe/{model}" for model in (response_model, request_model) if model is not None + ) + cost_entry: Final = next( + (entry for model_key in candidate_model_keys if (entry := _get_model_cost_entry(model_key)) is not None), + None, + ) + input_cost_per_token: Final = ( + cost_entry.get("input_cost_per_token", 0.0) if isinstance(cost_entry, Mapping) else 0.0 + ) + output_cost_per_token: Final = ( + cost_entry.get("output_cost_per_token", 0.0) if isinstance(cost_entry, Mapping) else 0.0 + ) + response_cost: Final = ( + input_tokens * float(input_cost_per_token) + output_tokens * float(output_cost_per_token) + if isinstance(input_cost_per_token, (int, float)) and isinstance(output_cost_per_token, (int, float)) + else 0.0 + ) + usage_object: Final = Usage( + prompt_tokens=input_tokens, + completion_tokens=output_tokens, + total_tokens=input_tokens + output_tokens, + ) + updated_kwargs: Final = { + **kwargs, + "model": model_name, + "custom_llm_provider": "typesafe", + "response_cost": response_cost, + "combined_usage_object": usage_object, + } + logging_obj.model_call_details.update( + model=model_name, + custom_llm_provider="typesafe", + response_cost=response_cost, + ) + standard_logging_object: Final = get_standard_logging_object_payload( + kwargs=updated_kwargs, + init_response_obj=ModelResponse(model=model_name, usage=usage_object), + start_time=start_time, + end_time=end_time, + logging_obj=logging_obj, + status="success", + ) + return { + "result": StandardPassThroughResponseObject(response=result), + "kwargs": {**updated_kwargs, "standard_logging_object": standard_logging_object}, + } diff --git a/litellm/proxy/pass_through_endpoints/success_handler.py b/litellm/proxy/pass_through_endpoints/success_handler.py index 76a471302f4..b4bfaf6ec9e 100644 --- a/litellm/proxy/pass_through_endpoints/success_handler.py +++ b/litellm/proxy/pass_through_endpoints/success_handler.py @@ -256,6 +256,25 @@ class PassThroughEndpointLogging: ) standard_logging_response_object = comprehend_medical_handler_result["result"] # rebind-ok: elif-chain kwargs = comprehend_medical_handler_result["kwargs"] # rebind-ok: elif-chain contract + elif self.is_typesafe_route(custom_llm_provider): + from .llm_provider_handlers.typesafe_passthrough_logging_handler import ( + TypeSafePassthroughLoggingHandler, + ) + + typesafe_handler_result: Final = TypeSafePassthroughLoggingHandler.typesafe_passthrough_handler( + httpx_response=httpx_response, + response_body=response_body if isinstance(response_body, dict) else {}, + logging_obj=logging_obj, + url_route=url_route, + result=result, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, + request_body=request_body, + **kwargs, + ) + standard_logging_response_object = typesafe_handler_result["result"] + kwargs = typesafe_handler_result["kwargs"] elif self.is_vertex_ai_live_route(url_route): from .llm_provider_handlers.vertex_ai_live_passthrough_logging_handler import ( VertexAILivePassthroughLoggingHandler, @@ -389,6 +408,9 @@ class PassThroughEndpointLogging: def is_comprehend_medical_route(self, custom_llm_provider: str | None) -> bool: return custom_llm_provider == "comprehendmedical" + def is_typesafe_route(self, custom_llm_provider: str | None) -> bool: + return custom_llm_provider == "typesafe" + def is_langfuse_route(self, url_route: str): parsed_url: Final = urlparse(url_route) for route in self.TRACKED_LANGFUSE_ROUTES: diff --git a/litellm/types/utils.py b/litellm/types/utils.py index aaa16fd2d44..c732a617c77 100644 --- a/litellm/types/utils.py +++ b/litellm/types/utils.py @@ -348,6 +348,7 @@ class ModelInfoBase(ProviderSpecificModelInfo, total=False): "audio_transcription", "audio_speech", "responses", + "evaluation", "ocr", "realtime", ] diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index c565b6ecc4b..ed852bc490c 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -69158,5 +69158,26 @@ "supports_prompt_caching": true, "supports_reasoning": true, "supports_vision": true + }, + "typesafe/jev-1.13.0": { + "input_cost_per_token": 4.2e-08, + "litellm_provider": "typesafe", + "mode": "evaluation", + "output_cost_per_token": 0.0, + "source": "https://docs.typesafe.ai/models" + }, + "typesafe/jev-latest": { + "input_cost_per_token": 4.2e-08, + "litellm_provider": "typesafe", + "mode": "evaluation", + "output_cost_per_token": 0.0, + "source": "https://docs.typesafe.ai/models" + }, + "typesafe/jev-preview": { + "input_cost_per_token": 4.2e-08, + "litellm_provider": "typesafe", + "mode": "evaluation", + "output_cost_per_token": 0.0, + "source": "https://docs.typesafe.ai/models" } } diff --git a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py new file mode 100644 index 00000000000..326b86654fe --- /dev/null +++ b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py @@ -0,0 +1,127 @@ +from datetime import datetime +from unittest.mock import MagicMock + +import httpx +import pytest + +import litellm +from litellm.proxy.pass_through_endpoints.llm_provider_handlers.typesafe_passthrough_logging_handler import ( + TypeSafePassthroughLoggingHandler, +) +from litellm.proxy.pass_through_endpoints.success_handler import PassThroughEndpointLogging + + +@pytest.fixture(autouse=True) +def local_model_cost_map(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) + + +def _response() -> httpx.Response: + return httpx.Response( + 200, + request=httpx.Request("POST", "https://api.typesafe.ai/v1/systemone"), + json={"model": "jev-1.13.0"}, + ) + + +def _logging_obj() -> MagicMock: + logging_obj = MagicMock() + logging_obj.model_call_details = {} + return logging_obj + + +def _handler_result(response_body: dict, request_body: dict) -> dict: + return TypeSafePassthroughLoggingHandler.typesafe_passthrough_handler( + httpx_response=_response(), + response_body=response_body, + logging_obj=_logging_obj(), + url_route="https://api.typesafe.ai/v1/systemone", + result='{"answers": {}}', + start_time=datetime.now(), + end_time=datetime.now(), + cache_hit=False, + request_body=request_body, + ) + + +def test_uses_registry_pricing_and_standard_usage(): + logging_obj = _logging_obj() + model_key = "typesafe/jev-1.13.0" + model_cost = litellm.model_cost[model_key] + response = TypeSafePassthroughLoggingHandler.typesafe_passthrough_handler( + httpx_response=_response(), + response_body={"model": "jev-1.13.0", "usage": {"input_tokens": 312, "output_tokens": 48}}, + logging_obj=logging_obj, + url_route="https://api.typesafe.ai/v1/systemone", + result='{"answers": {}}', + start_time=datetime.now(), + end_time=datetime.now(), + cache_hit=False, + request_body={"model": "jev-latest"}, + ) + + expected_cost = 312 * model_cost["input_cost_per_token"] + 48 * model_cost["output_cost_per_token"] + assert response["kwargs"]["response_cost"] == pytest.approx(expected_cost) + assert response["kwargs"]["combined_usage_object"].prompt_tokens == 312 + assert response["kwargs"]["combined_usage_object"].completion_tokens == 48 + assert response["kwargs"]["combined_usage_object"].total_tokens == 360 + + +def test_falls_back_to_request_model_when_response_model_is_missing(): + result = _handler_result( + {"usage": {"input_tokens": 10, "output_tokens": 2}}, + {"model": "jev-latest"}, + ) + + model_cost = litellm.model_cost["typesafe/jev-latest"] + expected_cost = 10 * model_cost["input_cost_per_token"] + 2 * model_cost["output_cost_per_token"] + assert result["kwargs"]["model"] == "typesafe/jev-latest" + assert result["kwargs"]["response_cost"] == pytest.approx(expected_cost) + + +def test_missing_usage_is_zero_cost(): + result = _handler_result({"model": "jev-1.13.0"}, {"model": "jev-latest"}) + + assert result["kwargs"]["response_cost"] == 0.0 + + +def test_records_model_provider_and_cost_on_logging_details(): + logging_obj = _logging_obj() + result = TypeSafePassthroughLoggingHandler.typesafe_passthrough_handler( + httpx_response=_response(), + response_body={"model": "jev-1.13.0", "usage": {"input_tokens": 1, "output_tokens": 0}}, + logging_obj=logging_obj, + url_route="https://api.typesafe.ai/v1/systemone", + result="{}", + start_time=datetime.now(), + end_time=datetime.now(), + cache_hit=False, + request_body={"model": "jev-latest"}, + ) + + assert result["kwargs"]["model"] == "typesafe/jev-1.13.0" + assert result["kwargs"]["custom_llm_provider"] == "typesafe" + assert result["kwargs"]["response_cost"] > 0 + assert logging_obj.model_call_details["model"] == "typesafe/jev-1.13.0" + assert logging_obj.model_call_details["custom_llm_provider"] == "typesafe" + assert logging_obj.model_call_details["response_cost"] == result["kwargs"]["response_cost"] + + +def test_success_handler_dispatches_to_typesafe_handler(): + logging_obj = _logging_obj() + normalized = PassThroughEndpointLogging().normalize_llm_passthrough_logging_payload( + httpx_response=_response(), + response_body={"model": "jev-1.13.0", "usage": {"input_tokens": 1, "output_tokens": 0}}, + request_body={"model": "jev-latest"}, + logging_obj=logging_obj, + url_route="https://api.typesafe.ai/v1/systemone", + result="{}", + start_time=datetime.now(), + end_time=datetime.now(), + cache_hit=False, + custom_llm_provider="typesafe", + ) + + assert normalized["kwargs"]["custom_llm_provider"] == "typesafe" + assert normalized["kwargs"]["model"] == "typesafe/jev-1.13.0" diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py index 6e82c90514d..13f4aae96b3 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py @@ -43,6 +43,7 @@ from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import ( mistral_proxy_route, relay_nvidia_nim_request, openai_proxy_route, + typesafe_proxy_route, vertex_discovery_proxy_route, vertex_proxy_route, vllm_proxy_route, @@ -6136,3 +6137,61 @@ class TestAzureRelayDeploymentSegment: ) assert [call["model"] for call in captured] == ["gpt", "gpt"] + + +class TestTypeSafePassthroughRoute: + @staticmethod + def _request(body: object, query_params: Mapping[str, str] | None = None) -> MagicMock: + request = MagicMock(spec=Request) + request.method = "POST" + request.query_params = query_params or {} + request.json = AsyncMock(return_value=body) + return request + + @pytest.mark.asyncio + async def test_forwards_target_auth_headers_provider_and_query(self, monkeypatch): + monkeypatch.setenv("TYPESAFE_API_KEY", "typesafe-test-key") + monkeypatch.setenv("TYPESAFE_API_BASE", "https://typesafe.example/base") + endpoint_func = AsyncMock(return_value={"ok": True}) + create_route = Mock(return_value=endpoint_func) + monkeypatch.setattr( + "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.create_pass_through_route", + create_route, + ) + + request = self._request({"state": "x"}, {"trace": "yes"}) + result = await typesafe_proxy_route( + endpoint="v1/systemone", + request=request, + fastapi_response=MagicMock(spec=Response), + user_api_key_dict=UserAPIKeyAuth(api_key="virtual-key"), + ) + + assert result == {"ok": True} + endpoint_func.assert_awaited_once() + create_route.assert_called_once_with( + endpoint="v1/systemone", + target="https://typesafe.example/base/v1/systemone?trace=yes", + custom_headers={ + "Authorization": "Bearer typesafe-test-key", + "Content-Type": "application/json", + }, + custom_llm_provider="typesafe", + is_streaming_request=False, + ) + assert request.json.await_count == 1 + + @pytest.mark.asyncio + async def test_rejects_stream_body(self, monkeypatch): + monkeypatch.setenv("TYPESAFE_API_KEY", "typesafe-test-key") + request = self._request({"stream": True}) + + with pytest.raises(HTTPException) as exc_info: + await typesafe_proxy_route( + endpoint="v1/systemone", + request=request, + fastapi_response=MagicMock(spec=Response), + user_api_key_dict=UserAPIKeyAuth(api_key="virtual-key"), + ) + + assert exc_info.value.status_code == 400 diff --git a/tests/test_litellm/test_typesafe_model_metadata.py b/tests/test_litellm/test_typesafe_model_metadata.py new file mode 100644 index 00000000000..a27180afbe9 --- /dev/null +++ b/tests/test_litellm/test_typesafe_model_metadata.py @@ -0,0 +1,17 @@ +import pytest + +import litellm + + +@pytest.fixture(autouse=True) +def local_model_cost_map(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) + + +def test_typesafe_models_share_pricing_and_provider_metadata(): + entries = [litellm.model_cost[f"typesafe/{model}"] for model in ("jev-1.13.0", "jev-latest", "jev-preview")] + + assert {entry["input_cost_per_token"] for entry in entries} == {entries[0]["input_cost_per_token"]} + assert {entry["output_cost_per_token"] for entry in entries} == {entries[0]["output_cost_per_token"]} + assert {entry["litellm_provider"] for entry in entries} == {"typesafe"} From 78eb92ca557dd152dee9508720dbc588ec2ac892 Mon Sep 17 00:00:00 2001 From: mateo Date: Thu, 17 Sep 2026 15:55:57 +0000 Subject: [PATCH 16/36] refactor(proxy): simplify TypeSafe passthrough pricing lookup and route Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../llm_passthrough_endpoints.py | 10 ----- .../typesafe_passthrough_logging_handler.py | 42 +++++++++---------- .../test_llm_pass_through_endpoints.py | 16 ------- 3 files changed, 20 insertions(+), 48 deletions(-) diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index c75a3227366..256f0eb0d1a 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -537,16 +537,6 @@ async def typesafe_proxy_route( user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """[Docs](https://docs.litellm.ai/docs/pass_through/typesafe)""" - if request.method == "POST": - try: - request_body: Final = await _json_request_body(request) - except Exception as e: - raise HTTPException(status_code=400, detail=str(e)) - if not isinstance(request_body, dict): - raise HTTPException(status_code=400, detail="Request body must be a JSON object") - if "stream" in request_body: - raise HTTPException(status_code=400, detail="'stream' is not a TypeSafe request member") - base_target_url: Final = get_secret_str("TYPESAFE_API_BASE") or "https://api.typesafe.ai" encoded_endpoint: Final = httpx.URL(endpoint).path normalized_endpoint: Final = encoded_endpoint if encoded_endpoint.startswith("/") else f"/{encoded_endpoint}" diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py index b9ba265044d..c4717b3bd7a 100644 --- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py +++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py @@ -1,6 +1,6 @@ from collections.abc import Mapping from datetime import datetime -from typing import Final, cast +from typing import Final import httpx from pydantic import BaseModel, TypeAdapter, ValidationError @@ -24,8 +24,13 @@ class _TypeSafeResponse(BaseModel): usage: _TypeSafeUsage | None = None +class _RegistryPricing(BaseModel): + input_cost_per_token: float = 0.0 + output_cost_per_token: float = 0.0 + + _TYPESAFE_RESPONSE_ADAPTER: Final = TypeAdapter(_TypeSafeResponse) -_MODEL_COST_ENTRY_ADAPTER: Final = TypeAdapter(dict[str, object]) +_REGISTRY_PRICING_ADAPTER: Final = TypeAdapter(_RegistryPricing) def _parse_typesafe_response(response_body: Mapping[str, object]) -> _TypeSafeResponse: @@ -35,13 +40,17 @@ def _parse_typesafe_response(response_body: Mapping[str, object]) -> _TypeSafeRe return _TypeSafeResponse() -def _get_model_cost_entry(model_key: str) -> Mapping[str, object] | None: - model_cost: Final[Mapping[str, object]] = cast(Mapping[str, object], litellm.model_cost) - entry: Final[object] = model_cost.get(model_key) - try: - return _MODEL_COST_ENTRY_ADAPTER.validate_python(entry) - except ValidationError: - return None +def _pricing_for(model_keys: tuple[str, ...]) -> _RegistryPricing: + for model_key in model_keys: + if model_key not in litellm.model_cost: # pyright: ignore[reportUnknownMemberType] # registry is dynamically typed + continue + try: + return _REGISTRY_PRICING_ADAPTER.validate_python( + litellm.model_cost[model_key] # pyright: ignore[reportUnknownMemberType] # registry is dynamically typed + ) + except ValidationError: + continue + return _RegistryPricing() class TypeSafePassthroughLoggingHandler: @@ -70,20 +79,9 @@ class TypeSafePassthroughLoggingHandler: candidate_model_keys: Final = tuple( f"typesafe/{model}" for model in (response_model, request_model) if model is not None ) - cost_entry: Final = next( - (entry for model_key in candidate_model_keys if (entry := _get_model_cost_entry(model_key)) is not None), - None, - ) - input_cost_per_token: Final = ( - cost_entry.get("input_cost_per_token", 0.0) if isinstance(cost_entry, Mapping) else 0.0 - ) - output_cost_per_token: Final = ( - cost_entry.get("output_cost_per_token", 0.0) if isinstance(cost_entry, Mapping) else 0.0 - ) + pricing: Final = _pricing_for(candidate_model_keys) response_cost: Final = ( - input_tokens * float(input_cost_per_token) + output_tokens * float(output_cost_per_token) - if isinstance(input_cost_per_token, (int, float)) and isinstance(output_cost_per_token, (int, float)) - else 0.0 + input_tokens * pricing.input_cost_per_token + output_tokens * pricing.output_cost_per_token ) usage_object: Final = Usage( prompt_tokens=input_tokens, diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py index 13f4aae96b3..bd022d97f44 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py @@ -6179,19 +6179,3 @@ class TestTypeSafePassthroughRoute: custom_llm_provider="typesafe", is_streaming_request=False, ) - assert request.json.await_count == 1 - - @pytest.mark.asyncio - async def test_rejects_stream_body(self, monkeypatch): - monkeypatch.setenv("TYPESAFE_API_KEY", "typesafe-test-key") - request = self._request({"stream": True}) - - with pytest.raises(HTTPException) as exc_info: - await typesafe_proxy_route( - endpoint="v1/systemone", - request=request, - fastapi_response=MagicMock(spec=Response), - user_api_key_dict=UserAPIKeyAuth(api_key="virtual-key"), - ) - - assert exc_info.value.status_code == 400 From 9470aa47f9f0767a52e04bf1dc510f870d7668cd Mon Sep 17 00:00:00 2001 From: mateo Date: Thu, 17 Sep 2026 16:01:27 +0000 Subject: [PATCH 17/36] fix(proxy): satisfy TypeSafe CI gates Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../proxy/pass_through_endpoints/llm_passthrough_endpoints.py | 2 +- model_prices_and_context_window.schema.json | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index 256f0eb0d1a..dd427bc07b3 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -534,7 +534,7 @@ async def typesafe_proxy_route( endpoint: str, request: Request, fastapi_response: Response, - user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), + user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)], ): """[Docs](https://docs.litellm.ai/docs/pass_through/typesafe)""" base_target_url: Final = get_secret_str("TYPESAFE_API_BASE") or "https://api.typesafe.ai" diff --git a/model_prices_and_context_window.schema.json b/model_prices_and_context_window.schema.json index 130cc6873fa..f924df1f1b2 100644 --- a/model_prices_and_context_window.schema.json +++ b/model_prices_and_context_window.schema.json @@ -427,6 +427,7 @@ "chat", "completion", "embedding", + "evaluation", "guardrail", "image_edit", "image_generation", From 7fca7fae373d7f7bcde36cb0cabda2fdf2764a3d Mon Sep 17 00:00:00 2001 From: mateo Date: Thu, 17 Sep 2026 16:20:47 +0000 Subject: [PATCH 18/36] fix(proxy): satisfy TypeSafe CI gates Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../llm_passthrough_endpoints.py | 6 +- .../typesafe_passthrough_logging_handler.py | 9 +- .../pass_through_endpoints/success_handler.py | 3 +- tests/test_litellm/test_utils.py | 1 + ui/litellm-dashboard/src/lib/http/schema.d.ts | 86 +++++++++++++++++++ 5 files changed, 98 insertions(+), 7 deletions(-) diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index dd427bc07b3..d86352e3ff6 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -527,8 +527,8 @@ async def mistral_proxy_route( @router.api_route( "/typesafe/{endpoint:path}", - methods=["GET", "POST"], - tags=["TypeSafe AI Pass-through", "pass-through"], + methods=["GET", "POST"], # mutable-ok: FastAPI route metadata requires a list + tags=["TypeSafe AI Pass-through", "pass-through"], # mutable-ok: FastAPI route metadata requires a list ) async def typesafe_proxy_route( endpoint: str, @@ -552,7 +552,7 @@ async def typesafe_proxy_route( endpoint_func: Final = create_pass_through_route( endpoint=endpoint, target=str(updated_url), - custom_headers={ + custom_headers={ # mutable-ok: pass-through request headers require a mutable mapping "Authorization": f"Bearer {typesafe_api_key}", "Content-Type": "application/json", }, diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py index c4717b3bd7a..cb6e72c6e3c 100644 --- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py +++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py @@ -88,7 +88,7 @@ class TypeSafePassthroughLoggingHandler: completion_tokens=output_tokens, total_tokens=input_tokens + output_tokens, ) - updated_kwargs: Final = { + updated_kwargs: Final = { # mutable-ok: pass-through logging contract requires mutable kwargs **kwargs, "model": model_name, "custom_llm_provider": "typesafe", @@ -108,7 +108,10 @@ class TypeSafePassthroughLoggingHandler: logging_obj=logging_obj, status="success", ) - return { + return { # mutable-ok: pass-through logging contract requires mutable result "result": StandardPassThroughResponseObject(response=result), - "kwargs": {**updated_kwargs, "standard_logging_object": standard_logging_object}, + "kwargs": { # mutable-ok: pass-through logging contract requires mutable kwargs + **updated_kwargs, + "standard_logging_object": standard_logging_object, + }, } diff --git a/litellm/proxy/pass_through_endpoints/success_handler.py b/litellm/proxy/pass_through_endpoints/success_handler.py index b4bfaf6ec9e..699caae819d 100644 --- a/litellm/proxy/pass_through_endpoints/success_handler.py +++ b/litellm/proxy/pass_through_endpoints/success_handler.py @@ -1,5 +1,6 @@ import json from datetime import datetime +from types import MappingProxyType from typing import Any, Final from urllib.parse import urlparse @@ -263,7 +264,7 @@ class PassThroughEndpointLogging: typesafe_handler_result: Final = TypeSafePassthroughLoggingHandler.typesafe_passthrough_handler( httpx_response=httpx_response, - response_body=response_body if isinstance(response_body, dict) else {}, + response_body=response_body if isinstance(response_body, dict) else MappingProxyType({}), logging_obj=logging_obj, url_route=url_route, result=result, diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index f219f26b353..e53d06176af 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -818,6 +818,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid(): "container", "image_edit", "embedding", + "evaluation", "guardrail", "image_generation", "video_generation", diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index 872875cc535..77fb9380b10 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -16437,6 +16437,30 @@ export interface paths { patch: operations["toolset_mcp_route_toolset__toolset_name__mcp_patch"]; trace?: never; }; + "/typesafe/{endpoint}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Typesafe Proxy Route + * @description [Docs](https://docs.litellm.ai/docs/pass_through/typesafe) + */ + get: operations["typesafe_proxy_route_typesafe__endpoint__get"]; + put?: never; + /** + * Typesafe Proxy Route + * @description [Docs](https://docs.litellm.ai/docs/pass_through/typesafe) + */ + post: operations["typesafe_proxy_route_typesafe__endpoint__post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/update/default_team_settings": { parameters: { query?: never; @@ -61441,6 +61465,68 @@ export interface operations { }; }; }; + typesafe_proxy_route_typesafe__endpoint__get: { + parameters: { + query?: never; + header?: never; + path: { + endpoint: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + typesafe_proxy_route_typesafe__endpoint__post: { + parameters: { + query?: never; + header?: never; + path: { + endpoint: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; update_default_team_settings_update_default_team_settings_patch: { parameters: { query?: never; From 4f3b90b5889ee5e94c5553275b359d611e96cf36 Mon Sep 17 00:00:00 2001 From: mateo Date: Thu, 17 Sep 2026 16:32:04 +0000 Subject: [PATCH 19/36] fix(proxy): expose TypeSafe passthrough on gateway Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- gateway/routes/allowlist.py | 1 + 1 file changed, 1 insertion(+) diff --git a/gateway/routes/allowlist.py b/gateway/routes/allowlist.py index 099c6d5179f..915ce1af219 100644 --- a/gateway/routes/allowlist.py +++ b/gateway/routes/allowlist.py @@ -96,6 +96,7 @@ GATEWAY_PATH_PREFIXES: tuple[str, ...] = ( "/langfuse/", "/vllm/", "/mistral/", + "/typesafe/", "/nvidia_nim/", "/groq/", "/voyage/", From b2ef8daee8208080ec65482dc2764d5a921a38f7 Mon Sep 17 00:00:00 2001 From: mateo Date: Thu, 17 Sep 2026 18:03:08 +0000 Subject: [PATCH 20/36] fix(proxy): stop duplicating query params on the TypeSafe passthrough Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../llm_passthrough_endpoints.py | 1 - .../test_llm_pass_through_endpoints.py | 13 ++++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index d86352e3ff6..f251b3b052c 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -543,7 +543,6 @@ async def typesafe_proxy_route( base_url: Final = httpx.URL(base_target_url) updated_url: Final = base_url.copy_with( path=HttpPassThroughEndpointHelpers.join_base_and_endpoint_path(base_url, normalized_endpoint), - params=request.query_params, ) typesafe_api_key: Final = passthrough_endpoint_router.get_credentials( custom_llm_provider="typesafe", diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py index bd022d97f44..901c5318442 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py @@ -9,6 +9,7 @@ from types import MappingProxyType, SimpleNamespace from typing import Final from unittest import mock from unittest.mock import AsyncMock, MagicMock, Mock, patch +from urllib.parse import parse_qs import httpx import pytest @@ -6152,7 +6153,13 @@ class TestTypeSafePassthroughRoute: async def test_forwards_target_auth_headers_provider_and_query(self, monkeypatch): monkeypatch.setenv("TYPESAFE_API_KEY", "typesafe-test-key") monkeypatch.setenv("TYPESAFE_API_BASE", "https://typesafe.example/base") - endpoint_func = AsyncMock(return_value={"ok": True}) + + async def fake_upstream(request, *_args): + target: Final = create_route.call_args.kwargs["target"] + upstream_url: Final = httpx.URL(target).copy_merge_params(request.query_params) + return {"upstream_query": parse_qs(upstream_url.query.decode())} + + endpoint_func = AsyncMock(side_effect=fake_upstream) create_route = Mock(return_value=endpoint_func) monkeypatch.setattr( "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.create_pass_through_route", @@ -6167,11 +6174,11 @@ class TestTypeSafePassthroughRoute: user_api_key_dict=UserAPIKeyAuth(api_key="virtual-key"), ) - assert result == {"ok": True} + assert result == {"upstream_query": {"trace": ["yes"]}} endpoint_func.assert_awaited_once() create_route.assert_called_once_with( endpoint="v1/systemone", - target="https://typesafe.example/base/v1/systemone?trace=yes", + target="https://typesafe.example/base/v1/systemone", custom_headers={ "Authorization": "Bearer typesafe-test-key", "Content-Type": "application/json", From fc35b78eb42b665c637d7b13969de57d88f2c6a0 Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 20:16:07 +0000 Subject: [PATCH 21/36] ci: drop aws partition hardcode gate Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .github/workflows/test-code-quality.yml | 3 - .../check_aws_partition_hardcodes.py | 140 ------------------ .../litellm_core_utils/test_aws_partition.py | 116 +-------------- 3 files changed, 1 insertion(+), 258 deletions(-) delete mode 100644 tests/code_coverage_tests/check_aws_partition_hardcodes.py diff --git a/.github/workflows/test-code-quality.yml b/.github/workflows/test-code-quality.yml index 44c3e97db91..987f66773f2 100644 --- a/.github/workflows/test-code-quality.yml +++ b/.github/workflows/test-code-quality.yml @@ -146,9 +146,6 @@ jobs: - name: check_migrations_no_data_rewrites run: uv run --no-sync python ./tests/code_coverage_tests/check_migrations_no_data_rewrites.py - - name: check_aws_partition_hardcodes - run: uv run --no-sync python ./tests/code_coverage_tests/check_aws_partition_hardcodes.py - - name: memory_test run: uv run --no-sync python ./tests/code_coverage_tests/memory_test.py diff --git a/tests/code_coverage_tests/check_aws_partition_hardcodes.py b/tests/code_coverage_tests/check_aws_partition_hardcodes.py deleted file mode 100644 index 0cbee4e7c80..00000000000 --- a/tests/code_coverage_tests/check_aws_partition_hardcodes.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/env python3 -"""Ban hardcoded commercial-partition AWS hosts and ARN prefixes under `litellm/`. - -An endpoint or ARN built with a literal `amazonaws.com` or `arn:aws:` works in every -commercial region and breaks only for GovCloud (`us-gov-*`, `arn:aws-us-gov:`) and -China (`amazonaws.com.cn`, `arn:aws-cn:`) deployments, so the failure never shows up -in CI or on a developer laptop. `litellm/litellm_core_utils/aws_partition.py` derives -both from the region and is the only place those literals belong. Build hosts with -`get_aws_dns_suffix(region)` and ARNs with `get_aws_arn_prefix(region)`. - -Every string constant in every `litellm/**/*.py` file is scanned, including the -literal parts of f-strings and the strings inside `.format()` calls and -concatenations. Docstrings and comments are not, since they never reach a request. -`amazonaws.com.cn` passes because it is already the China partition. - -`ALLOWED` holds the (file, token, count) triples that are text rather than a request -target: a hosted logo, an IAM service principal, and hostnames quoted as examples -inside error messages and field descriptions. An entry only covers that many -occurrences of that exact token in that exact file, so a second copy of an allowed -literal is still caught, and an entry whose token is gone or whose count has changed -fails the check so the set only shrinks. -""" - -from __future__ import annotations - -import ast -import re -import sys -from collections import Counter -from pathlib import Path -from types import MappingProxyType -from typing import Final, NamedTuple - -REPO_ROOT: Final = Path(__file__).resolve().parents[2] -SCAN_ROOT: Final = REPO_ROOT / "litellm" -PARTITION_HELPER: Final = "litellm/litellm_core_utils/aws_partition.py" - -COMMERCIAL_TOKEN: Final = re.compile(r"[A-Za-z0-9.-]*amazonaws\.com(?!\.cn)|arn:aws:[A-Za-z0-9:/_.*-]*") - - -class Allowance(NamedTuple): - file: str - token: str - occurrences: int - - -ALLOWED: Final = frozenset( - { - Allowance("litellm/integrations/email_alerting.py", "litellm-listing.s3.amazonaws.com", 1), - Allowance("litellm/types/integrations/slack_alerting.py", "litellm-listing.s3.amazonaws.com", 1), - Allowance("litellm/rag/ingestion/bedrock_ingestion.py", "bedrock.amazonaws.com", 1), - Allowance( - "litellm/llms/bedrock/chat/agentcore/transformation.py", - "arn:aws:bedrock-agentcore:region:account:runtime/runtime_id", - 1, - ), - Allowance("litellm/llms/bedrock/search/transformation.py", ".amazonaws.com", 1), - Allowance( - "litellm/proxy/anthropic_endpoints/claude_code_endpoints/claude_code_marketplace.py", - "bucket.s3.amazonaws.com", - 1, - ), - Allowance("litellm/types/proxy/claude_code_endpoints.py", "bucket.s3.amazonaws.com", 1), - } -) -ALLOWED_COUNTS: Final = MappingProxyType({(entry.file, entry.token): entry.occurrences for entry in ALLOWED}) - - -class Hit(NamedTuple): - file: str - line: int - token: str - - -def _docstring_ids(tree: ast.Module) -> frozenset[int]: - return frozenset( - id(statement.value) - for node in ast.walk(tree) - if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) - for statement in node.body - if isinstance(statement, ast.Expr) - and isinstance(statement.value, ast.Constant) - and isinstance(statement.value.value, str) - ) - - -def _hits_in_file(path: Path) -> tuple[Hit, ...]: - tree: Final = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) - docstrings: Final = _docstring_ids(tree) - relative: Final = path.relative_to(REPO_ROOT).as_posix() - return tuple( - Hit(relative, node.lineno, match.group(0)) - for node in ast.walk(tree) - if isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings - for match in COMMERCIAL_TOKEN.finditer(node.value) - ) - - -def find_hits(scan_root: Path) -> tuple[Hit, ...]: - return tuple( - hit - for path in sorted(scan_root.rglob("*.py")) - if path.relative_to(REPO_ROOT).as_posix() != PARTITION_HELPER - for hit in _hits_in_file(path) - ) - - -def _violation_message(hit: Hit, found: int) -> str: - allowed: Final = ALLOWED_COUNTS.get((hit.file, hit.token)) - if allowed is None: - return f"{hit.file}:{hit.line}: hardcoded commercial AWS partition literal {hit.token!r}" - return ( - f"{hit.file}:{hit.line}: {hit.token!r} appears {found} times but ALLOWED covers {allowed}; " - "build it from the region helper or update the count" - ) - - -def main() -> int: - hits: Final = find_hits(SCAN_ROOT) - counts: Final = MappingProxyType(Counter((hit.file, hit.token) for hit in hits)) - violations: Final = tuple( - sorted(hit for hit in hits if Allowance(hit.file, hit.token, counts[hit.file, hit.token]) not in ALLOWED) - ) - stale: Final = tuple(entry for entry in sorted(ALLOWED) if (entry.file, entry.token) not in counts) - for hit in violations: - print(_violation_message(hit, counts[hit.file, hit.token])) - for allowance in stale: - print(f"{allowance.file}: ALLOWED entry {allowance.token!r} no longer matches anything, remove it") - if violations or stale: - print( - "\nBuild AWS hosts with get_aws_dns_suffix(region) and ARNs with get_aws_arn_prefix(region) " - "from litellm/litellm_core_utils/aws_partition.py so GovCloud and China regions resolve." - ) - return 1 - print(f"No hardcoded commercial AWS partition literals outside {PARTITION_HELPER}.") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/test_litellm/litellm_core_utils/test_aws_partition.py b/tests/test_litellm/litellm_core_utils/test_aws_partition.py index 24a38268ae9..3594d3c354c 100644 --- a/tests/test_litellm/litellm_core_utils/test_aws_partition.py +++ b/tests/test_litellm/litellm_core_utils/test_aws_partition.py @@ -1,11 +1,9 @@ import ast from pathlib import Path -from types import MappingProxyType from typing import Final -from urllib.parse import unquote, urlparse +from urllib.parse import urlparse import pytest -from botocore.credentials import Credentials import litellm from litellm.integrations.s3_v2 import S3Logger @@ -22,20 +20,8 @@ from litellm.llms.aws_polly.text_to_speech.transformation import AWSPollyTextToS from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM from litellm.llms.bedrock.batches.transformation import BedrockBatchesConfig from litellm.llms.bedrock.chat.agentcore.transformation import AmazonAgentCoreConfig -from litellm.llms.bedrock.chat.invoke_agent.transformation import AmazonInvokeAgentConfig from litellm.llms.bedrock.common_utils import init_bedrock_client -from litellm.llms.bedrock.files.transformation import BedrockFilesConfig -from litellm.llms.bedrock.rerank.handler import BedrockRerankHandler -from litellm.llms.bedrock.vector_stores.transformation import BedrockVectorStoreConfig from litellm.llms.sagemaker.chat.transformation import SagemakerChatConfig -from litellm.llms.sagemaker.completion.handler import SagemakerLLM -from litellm.proxy.auth.rds_iam_token import init_rds_client -from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrail -from litellm.secret_managers.aws_secret_manager_v2 import AWSSecretsManagerV2 - -STATIC_AWS_CREDENTIALS: Final = MappingProxyType( - {"aws_access_key_id": "test-key", "aws_secret_access_key": "test-secret"} -) @pytest.mark.parametrize( @@ -120,48 +106,6 @@ def _s3_object_url(region: str) -> str: return logger._build_object_url("2025-01-01/key.json") -def _bedrock_job_arn(region: str) -> str: - return f"{get_aws_arn_prefix(region)}bedrock:{region}:111122223333:model-invocation-job/abc1234567" - - -def _bedrock_files_upload_url(region: str) -> str: - return BedrockFilesConfig().get_complete_file_url( - api_base=None, - api_key=None, - model="amazon.nova-pro-v1:0", - optional_params={}, - litellm_params={"s3_bucket_name": "batch-bucket", "s3_region_name": region}, - data={"file": ("batch.jsonl", b"{}", "application/jsonl"), "purpose": "batch"}, - ) - - -def _bedrock_files_download_url(region: str) -> str: - return ( - BedrockFilesConfig() - ._s3_request_target(optional_params={}, litellm_params={"s3_region_name": region}) - .endpoint_url - ) - - -def _bedrock_guardrail_url(region: str) -> str: - guardrail = BedrockGuardrail(guardrailIdentifier="guardrail-id", guardrailVersion="1") - return guardrail._prepare_request( - credentials=Credentials("test-key", "test-secret"), - data={"source": "INPUT", "content": []}, - optional_params={}, - aws_region_name=region, - ).url - - -def _secrets_manager_url(region: str) -> str: - endpoint_url, _headers, _body = AWSSecretsManagerV2(aws_region_name=region)._prepare_request( - action="GetSecretValue", - secret_name="my-secret", - optional_params=dict(STATIC_AWS_CREDENTIALS), - ) - return endpoint_url - - ENDPOINT_BUILDERS: Final = { "bedrock_runtime_default": lambda region: BaseAWSLLM()._select_default_endpoint_url("runtime", region), "bedrock_agent_default": lambda region: BaseAWSLLM()._select_default_endpoint_url("agent", region), @@ -180,13 +124,6 @@ ENDPOINT_BUILDERS: Final = { litellm_params={}, data={"input_file_id": "s3://bucket/key.jsonl"}, ), - "bedrock_batches_retrieve": lambda region: BedrockBatchesConfig().transform_retrieve_batch_request( - batch_id=_bedrock_job_arn(region), - optional_params=dict(STATIC_AWS_CREDENTIALS), - litellm_params={}, - )["url"], - "bedrock_files_upload": _bedrock_files_upload_url, - "bedrock_files_download": _bedrock_files_download_url, "bedrock_agentcore_invoke": lambda region: AmazonAgentCoreConfig().get_complete_url( api_base=None, api_key=None, @@ -194,32 +131,6 @@ ENDPOINT_BUILDERS: Final = { optional_params={}, litellm_params={}, ), - "bedrock_invoke_agent": lambda region: AmazonInvokeAgentConfig().get_complete_url( - api_base=None, - api_key=None, - model="agent/AGENT123/ALIAS456", - optional_params={"aws_region_name": region}, - litellm_params={}, - ), - "bedrock_guardrail_apply": _bedrock_guardrail_url, - "bedrock_rerank": lambda region: BedrockRerankHandler()._prepare_request( - model="amazon.rerank-v1:0", - api_base=None, - extra_headers=None, - data={"queries": [], "sources": []}, - optional_params={"aws_region_name": region, **STATIC_AWS_CREDENTIALS}, - )["endpoint_url"], - "bedrock_knowledgebase_search": lambda region: BedrockVectorStoreConfig().get_complete_url( - api_base=None, litellm_params={"aws_region_name": region} - ), - "secrets_manager": _secrets_manager_url, - "rds_iam_client": lambda region: ( - init_rds_client( - aws_region_name=region, - aws_access_key_id="test-key", - aws_secret_access_key="test-secret", - ).meta.endpoint_url - ), "polly": lambda region: AWSPollyTextToSpeechConfig().get_complete_url( model="polly/neural", api_base=None, @@ -241,19 +152,6 @@ ENDPOINT_BUILDERS: Final = { litellm_params={}, stream=True, ), - "sagemaker_completion": lambda region: ( - SagemakerLLM() - ._prepare_request( - credentials=Credentials("test-key", "test-secret"), - model="my-endpoint", - data={}, - messages=[], - litellm_params={}, - optional_params={}, - aws_region_name=region, - ) - .url - ), "s3_object_url": _s3_object_url, } @@ -284,18 +182,6 @@ def test_every_endpoint_builder_keeps_amazonaws_com_outside_cn(builder_name: str assert hostname.endswith(".amazonaws.com"), url -@pytest.mark.parametrize("region", ["us-gov-west-1", "us-gov-east-1"]) -@pytest.mark.parametrize("builder_name", sorted(ENDPOINT_BUILDERS)) -def test_every_endpoint_builder_respects_us_gov_partition(builder_name: str, region: str) -> None: - url = unquote(ENDPOINT_BUILDERS[builder_name](region)) - hostname = urlparse(url).hostname - assert hostname is not None - assert hostname.endswith(f".{region}.amazonaws.com"), url - assert "arn:aws:" not in url, url - if "arn:" in url: - assert "arn:aws-us-gov:" in url, url - - def _fstring_literal_offenders(needle: str) -> list[str]: litellm_root = Path(litellm.__file__).parent return [ From 5a5b18550cced0bc3e3af7b14e650172b42a6c46 Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 20:16:09 +0000 Subject: [PATCH 22/36] test(e2e): cover bedrock batch files in govcloud Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- tests/e2e/CONTRIBUTING.md | 4 + tests/e2e/batches/COVERAGE.md | 4 + tests/e2e/batches/test_batches_e2e.py | 84 +++++++++++++++++-- .../llm_nonconversational.yaml | 2 + tests/e2e/coverage_registry/schema.py | 1 + 5 files changed, 90 insertions(+), 5 deletions(-) diff --git a/tests/e2e/CONTRIBUTING.md b/tests/e2e/CONTRIBUTING.md index 20073e5d68f..75270250f30 100644 --- a/tests/e2e/CONTRIBUTING.md +++ b/tests/e2e/CONTRIBUTING.md @@ -23,6 +23,10 @@ The suites run against a live proxy, so bring one up first by running the litell OPENAI_API_KEY="sk-..." ANTHROPIC_API_KEY="sk-..." GEMINI_API_KEY="..." + AWS_GOVCLOUD_ACCESS_KEY_ID="..." + AWS_GOVCLOUD_SECRET_ACCESS_KEY="..." + AWS_GOVCLOUD_BATCH_S3_BUCKET="..." + AWS_GOVCLOUD_BATCH_ROLE_ARN="..." ``` 2. Bring up a Postgres and a Redis for the proxy to use. The repo-root `docker-compose.yml` already defines a Postgres on `5432`; a `docker run -p 6379:6379 redis:7` covers Redis. Point `DATABASE_URL` / `REDIS_HOST` / `REDIS_PORT` at whatever you run. Tests that read Redis directly default to the deployed shape (TLS + cluster mode) whenever `REDIS_HOST` is set, so for a local standalone Redis also set `REDIS_CLUSTER=false` and `REDIS_SSL=false` (plus `REDIS_PASSWORD` when your Redis requires auth) diff --git a/tests/e2e/batches/COVERAGE.md b/tests/e2e/batches/COVERAGE.md index 919c39f21a2..ad69031278b 100644 --- a/tests/e2e/batches/COVERAGE.md +++ b/tests/e2e/batches/COVERAGE.md @@ -21,6 +21,10 @@ failures are hard test failures (see `tests/e2e/CLAUDE.md`). | Vertex AI | yes | yes | yes | yes | yes (provider-transformed) | GCS (`gcs_bucket_name` / `GCS_BUCKET_NAME` on model) | | Bedrock | yes (unified only) | yes | yes | yes (unfiltered managed list) | yes (provider-transformed) | S3 (`s3_bucket_name` + `aws_*` + `AWS_BATCH_ROLE_ARN` on model) | +The GovCloud partition test requires `AWS_GOVCLOUD_ACCESS_KEY_ID`, +`AWS_GOVCLOUD_SECRET_ACCESS_KEY`, `AWS_GOVCLOUD_BATCH_S3_BUCKET`, and +`AWS_GOVCLOUD_BATCH_ROLE_ARN` in the proxy environment + Bedrock cancel maps to `StopModelInvocationJob` and comes back `cancelling`; the lifecycle asserts it the same way it does for OpenAI (`_CANCEL_ASSERTED_PROVIDERS`). Bedrock has no provider-side list, so list is the proxy's DB-backed managed view: the diff --git a/tests/e2e/batches/test_batches_e2e.py b/tests/e2e/batches/test_batches_e2e.py index c4b699190b8..adce2060ee8 100644 --- a/tests/e2e/batches/test_batches_e2e.py +++ b/tests/e2e/batches/test_batches_e2e.py @@ -21,21 +21,18 @@ import os import re import time from datetime import datetime, timedelta, timezone +from typing import Final import pytest -from pydantic import BaseModel - -from e2e_config import MASTER_KEY, PROXY_BASE_URL, unique_marker - from batch_cleanup import cleanup_batch, cleanup_file from batch_client import ( AZURE_FILE_EXPIRY_SECONDS, - batch_upload_form, UPLOAD_FILENAME, BatchClient, BatchCreateBody, BatchObject, FileObject, + batch_upload_form, is_model_access_denied, is_result_access_denied, ) @@ -57,6 +54,7 @@ from capabilities import ( openai_batch_params, raw_id_matches_provider, ) +from e2e_config import MASTER_KEY, PROXY_BASE_URL, unique_marker from e2e_http import ( FileUploadForm, Result, @@ -68,6 +66,7 @@ from e2e_http import ( ) from lifecycle import ResourceManager from models import KeyGenerateBody, KeyMetadata, LiteLLMParamsBody, SpendLogRow +from pydantic import BaseModel pytestmark = pytest.mark.e2e @@ -1006,6 +1005,81 @@ class TestBedrockBatchAssumeRole: assert fetched.id == batch.id +GOVCLOUD_REGION: Final = "us-gov-west-1" +GOVCLOUD_RAW_MODEL: Final = "bedrock/amazon.nova-lite-v1:0" + + +def _govcloud_params() -> LiteLLMParamsBody: + return LiteLLMParamsBody( + model=GOVCLOUD_RAW_MODEL, + aws_access_key_id="os.environ/AWS_GOVCLOUD_ACCESS_KEY_ID", + aws_secret_access_key="os.environ/AWS_GOVCLOUD_SECRET_ACCESS_KEY", + aws_region_name=GOVCLOUD_REGION, + s3_region_name=GOVCLOUD_REGION, + s3_bucket_name="os.environ/AWS_GOVCLOUD_BATCH_S3_BUCKET", + s3_access_key_id="os.environ/AWS_GOVCLOUD_ACCESS_KEY_ID", + s3_secret_access_key="os.environ/AWS_GOVCLOUD_SECRET_ACCESS_KEY", + aws_batch_role_arn="os.environ/AWS_GOVCLOUD_BATCH_ROLE_ARN", + ) + + +class TestBedrockBatchGovCloud: + """Bedrock batch lifecycle in the AWS GovCloud partition (us-gov-west-1). + + The deployment carries a GovCloud region for both Bedrock and S3, so the proxy has to + sign the file upload against the us-gov S3 endpoint and submit the job to the us-gov + Bedrock endpoint. Commercial-partition hostnames or arn:aws: ARNs reject the GovCloud + key, so a partition regression fails the upload instead of passing silently. + """ + + @pytest.mark.covers( + "llm.batches.bedrock.govcloud_partition.nonstream.works", + "llm.files.bedrock.govcloud_partition.nonstream.works", + exercised_on=["batches", "files"], + ) + def test_unified_file_upload_and_batch_create_in_govcloud( + self, client: BatchClient, resources: ResourceManager + ) -> None: + model_name: Final = batch_model_name("bedrock-govcloud-batch") + model_id: Final = client.create_model(model_name, _govcloud_params()) + resources.defer(lambda: client.delete_model(model_id)) + key: Final = resources.key() + file: Final = unwrap( + client.upload_file( + content=render_jsonl(GOVCLOUD_RAW_MODEL), + form=FileUploadForm(purpose="batch", target_model_names=model_name), + key=key, + ) + ) + resources.defer(lambda: cleanup_file(client, file.id, key=key)) + assert_file_object(file, provider="bedrock") + + downloaded: Final = client.proxy.transport.download( + f"/v1/files/{file.id}/content", + headers=client.proxy.transport.bearer(key), + ) + assert downloaded.status_code == 200, ( + f"GovCloud file content must be 200, got {downloaded.status_code}: {downloaded.body[:300]}" + ) + assert downloaded.body.strip(), "GovCloud file content download returned an empty body" + + created: Final = client.create_batch(body=BatchCreateBody(input_file_id=file.id), key=key) + require_successful_call(created) + batch: Final = BatchObject.model_validate_json(created.body) + resources.defer(lambda: cleanup_batch(client, batch.id, key=key)) + + assert is_managed_id(batch.id), ( + f"GovCloud create via target_model_names must return a managed batch id, got {batch.id!r}" + ) + assert batch.status in CREATED_BATCH_STATUSES, ( + f"GovCloud batch has non-transitional status {batch.status!r}" + ) + assert_batch_object(batch) + + fetched: Final = unwrap(client.retrieve_batch(batch.id, key=key)) + assert fetched.id == batch.id + + GEMINI_FILES_RAW_MODEL = "gemini-2.5-flash" diff --git a/tests/e2e/coverage_registry/llm_nonconversational.yaml b/tests/e2e/coverage_registry/llm_nonconversational.yaml index 635ea3f7ea5..50f9b9808b2 100644 --- a/tests/e2e/coverage_registry/llm_nonconversational.yaml +++ b/tests/e2e/coverage_registry/llm_nonconversational.yaml @@ -23,6 +23,7 @@ - {id: llm.batches.vertex.basic.nonstream.works, module: llm, tier: P0, subject_endpoint: batches, route: vertex, capability: basic, streaming: nonstream, assertions: [works], source: "batches/capabilities.py:98", rationale: "Vertex batches"} - {id: llm.batches.bedrock.basic.nonstream.works, module: llm, tier: P0, subject_endpoint: batches, route: bedrock_converse, capability: basic, streaming: nonstream, assertions: [works], source: "batches/capabilities.py:98", rationale: "Bedrock batches (encoded/unified only)"} - {id: llm.batches.bedrock.assume_role.nonstream.works, module: llm, tier: P0, subject_endpoint: batches, route: bedrock_converse, capability: assume_role, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "Bedrock batch create under STS assume-role credentials"} +- {id: llm.batches.bedrock.govcloud_partition.nonstream.works, module: llm, tier: P0, subject_endpoint: batches, route: bedrock_converse, capability: govcloud_partition, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "Bedrock batch create in the us-gov-west-1 partition"} - {id: llm.batches.bedrock.cancel.nonstream.works, module: llm, tier: P0, subject_endpoint: batches, route: bedrock_converse, capability: basic, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "Bedrock batch cancel (StopModelInvocationJob) returns the same id with a cancelling/cancelled status"} - {id: llm.batches.bedrock.list.nonstream.works, module: llm, tier: P0, subject_endpoint: batches, route: bedrock_converse, capability: basic, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "A Bedrock managed batch is present in the GET /v1/batches list envelope"} - {id: llm.batches.hosted_vllm.basic.nonstream.works, module: llm, tier: P1, subject_endpoint: batches, route: hosted_vllm, capability: basic, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "hosted_vllm OpenAI-compatible batch create"} @@ -45,6 +46,7 @@ - {id: llm.files.azure_openai.upload.nonstream.works, module: llm, tier: P0, subject_endpoint: files, route: azure_openai, capability: basic, streaming: nonstream, assertions: [works], source: "batches/capabilities.py:45", rationale: "Azure file upload managed backend"} - {id: llm.files.vertex.upload.nonstream.works, module: llm, tier: P0, subject_endpoint: files, route: vertex, capability: basic, streaming: nonstream, assertions: [works], source: "batches/capabilities.py:52", rationale: "Vertex file upload to GCS"} - {id: llm.files.bedrock.upload.nonstream.works, module: llm, tier: P0, subject_endpoint: files, route: bedrock_converse, capability: basic, streaming: nonstream, assertions: [works], source: "batches/capabilities.py:59", rationale: "Bedrock file upload to S3"} +- {id: llm.files.bedrock.govcloud_partition.nonstream.works, module: llm, tier: P0, subject_endpoint: files, route: bedrock_converse, capability: govcloud_partition, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "Bedrock file upload to an S3 bucket in the us-gov-west-1 partition"} - {id: llm.files.gemini.upload.nonstream.works, module: llm, tier: P1, subject_endpoint: files, route: gemini, capability: basic, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "Gemini Files API upload via proxy"} - {id: llm.files.hosted_vllm.upload.nonstream.works, module: llm, tier: P1, subject_endpoint: files, route: hosted_vllm, capability: basic, streaming: nonstream, assertions: [works], source: "test_batches_e2e.py", rationale: "hosted_vllm OpenAI-compatible file upload"} - {id: llm.files.openai.require_managed_files_upload.nonstream.works, module: llm, tier: P1, subject_endpoint: files, route: openai, capability: input_validation, streaming: nonstream, assertions: [works], source: "test_managed_files_enforcement_e2e.py / LIT-5902", rationale: "With require_managed_files enabled, an upload without target_model_names and an upload carrying a model param are both rejected 400; runs only in the sequential managed-files stack phase (E2E_MANAGED_FILES_STACK)"} diff --git a/tests/e2e/coverage_registry/schema.py b/tests/e2e/coverage_registry/schema.py index 03d15f532b8..fa6dad90126 100644 --- a/tests/e2e/coverage_registry/schema.py +++ b/tests/e2e/coverage_registry/schema.py @@ -64,6 +64,7 @@ LlmCapability = Literal[ "assume_role", "basic", "count_tokens", + "govcloud_partition", "input_validation", "long_context_1m", "mid_conversation_system", From 5aec6d7bb691a3a034983da123387f17a1ea634a Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 21:31:33 +0000 Subject: [PATCH 23/36] test(e2e): assert govcloud file content round-trips the uploaded record Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- tests/e2e/batches/test_batches_e2e.py | 33 +++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/tests/e2e/batches/test_batches_e2e.py b/tests/e2e/batches/test_batches_e2e.py index adce2060ee8..eff8f297f25 100644 --- a/tests/e2e/batches/test_batches_e2e.py +++ b/tests/e2e/batches/test_batches_e2e.py @@ -66,7 +66,7 @@ from e2e_http import ( ) from lifecycle import ResourceManager from models import KeyGenerateBody, KeyMetadata, LiteLLMParamsBody, SpendLogRow -from pydantic import BaseModel +from pydantic import BaseModel, Field pytestmark = pytest.mark.e2e @@ -74,6 +74,25 @@ CREATED_BATCH_STATUSES = {"validating", "in_progress", "finalizing"} BATCH_CANCEL_DELAY_SECONDS = 2 BATCH_TERMINAL_BEFORE_CANCEL = {"failed", "cancelled", "expired"} BATCH_OP_RETRIES = 5 + + +class _GovCloudBedrockContent(BaseModel): + text: str + + +class _GovCloudBedrockMessage(BaseModel): + content: tuple[_GovCloudBedrockContent, ...] + + +class _GovCloudBedrockInput(BaseModel): + messages: tuple[_GovCloudBedrockMessage, ...] + + +class _GovCloudBedrockRecord(BaseModel): + record_id: str = Field(alias="recordId") + model_input: _GovCloudBedrockInput = Field(alias="modelInput") + + # Azure / Vertex cancel and the pre-cancel re-retrieve are provider-side flakes # (connection refused, brief 500s) and the registry only has one basic cell per # provider (shared across scenarios). Create + retrieve already prove routing; @@ -1061,7 +1080,17 @@ class TestBedrockBatchGovCloud: assert downloaded.status_code == 200, ( f"GovCloud file content must be 200, got {downloaded.status_code}: {downloaded.body[:300]}" ) - assert downloaded.body.strip(), "GovCloud file content download returned an empty body" + downloaded_lines: Final = downloaded.body.strip().splitlines() + assert len(downloaded_lines) == 1, ( + f"GovCloud file content download must contain one JSONL record, got {len(downloaded_lines)}" + ) + downloaded_record: Final = _GovCloudBedrockRecord.model_validate(json.loads(downloaded_lines[0])) + assert downloaded_record.record_id == "req-1", ( + f"GovCloud file content must preserve the uploaded custom_id, got {downloaded_record.record_id!r}" + ) + assert downloaded_record.model_input.messages[0].content[0].text == "ping", ( + "GovCloud file content must preserve the uploaded message text" + ) created: Final = client.create_batch(body=BatchCreateBody(input_file_id=file.id), key=key) require_successful_call(created) From 4b45fd5f44a6a85b0475bf470a5abe14db3eb38a Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 21:47:21 +0000 Subject: [PATCH 24/36] docs(e2e): drop govcloud keys from the contributing starter env Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- tests/e2e/CONTRIBUTING.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/e2e/CONTRIBUTING.md b/tests/e2e/CONTRIBUTING.md index 75270250f30..20073e5d68f 100644 --- a/tests/e2e/CONTRIBUTING.md +++ b/tests/e2e/CONTRIBUTING.md @@ -23,10 +23,6 @@ The suites run against a live proxy, so bring one up first by running the litell OPENAI_API_KEY="sk-..." ANTHROPIC_API_KEY="sk-..." GEMINI_API_KEY="..." - AWS_GOVCLOUD_ACCESS_KEY_ID="..." - AWS_GOVCLOUD_SECRET_ACCESS_KEY="..." - AWS_GOVCLOUD_BATCH_S3_BUCKET="..." - AWS_GOVCLOUD_BATCH_ROLE_ARN="..." ``` 2. Bring up a Postgres and a Redis for the proxy to use. The repo-root `docker-compose.yml` already defines a Postgres on `5432`; a `docker run -p 6379:6379 redis:7` covers Redis. Point `DATABASE_URL` / `REDIS_HOST` / `REDIS_PORT` at whatever you run. Tests that read Redis directly default to the deployed shape (TLS + cluster mode) whenever `REDIS_HOST` is set, so for a local standalone Redis also set `REDIS_CLUSTER=false` and `REDIS_SSL=false` (plus `REDIS_PASSWORD` when your Redis requires auth) From bdd9335116441596a7a476b59d15babc6a358d02 Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 21:51:02 +0000 Subject: [PATCH 25/36] docs(e2e): list the govcloud bedrock test as a coverage matrix row Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- tests/e2e/batches/COVERAGE.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tests/e2e/batches/COVERAGE.md b/tests/e2e/batches/COVERAGE.md index ad69031278b..a98d771ffeb 100644 --- a/tests/e2e/batches/COVERAGE.md +++ b/tests/e2e/batches/COVERAGE.md @@ -20,10 +20,7 @@ failures are hard test failures (see `tests/e2e/CLAUDE.md`). | Azure | yes | yes | yes | yes | yes (byte-verbatim) | Azure Files | | Vertex AI | yes | yes | yes | yes | yes (provider-transformed) | GCS (`gcs_bucket_name` / `GCS_BUCKET_NAME` on model) | | Bedrock | yes (unified only) | yes | yes | yes (unfiltered managed list) | yes (provider-transformed) | S3 (`s3_bucket_name` + `aws_*` + `AWS_BATCH_ROLE_ARN` on model) | - -The GovCloud partition test requires `AWS_GOVCLOUD_ACCESS_KEY_ID`, -`AWS_GOVCLOUD_SECRET_ACCESS_KEY`, `AWS_GOVCLOUD_BATCH_S3_BUCKET`, and -`AWS_GOVCLOUD_BATCH_ROLE_ARN` in the proxy environment +| Bedrock GovCloud (`us-gov-west-1`) | yes (unified only) | yes | no | no | yes (provider-transformed) | S3 (`s3_bucket_name` + `aws_*` + `AWS_GOVCLOUD_*` on model) | Bedrock cancel maps to `StopModelInvocationJob` and comes back `cancelling`; the lifecycle asserts it the same way it does for OpenAI (`_CANCEL_ASSERTED_PROVIDERS`). From bbde2f8a3ae1290189e6f4707d82740cc4d4b5ca Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 22:07:50 +0000 Subject: [PATCH 26/36] docs(e2e): name the govcloud env vars in the coverage matrix row Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- tests/e2e/batches/COVERAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/batches/COVERAGE.md b/tests/e2e/batches/COVERAGE.md index a98d771ffeb..b36d8937ad0 100644 --- a/tests/e2e/batches/COVERAGE.md +++ b/tests/e2e/batches/COVERAGE.md @@ -20,7 +20,7 @@ failures are hard test failures (see `tests/e2e/CLAUDE.md`). | Azure | yes | yes | yes | yes | yes (byte-verbatim) | Azure Files | | Vertex AI | yes | yes | yes | yes | yes (provider-transformed) | GCS (`gcs_bucket_name` / `GCS_BUCKET_NAME` on model) | | Bedrock | yes (unified only) | yes | yes | yes (unfiltered managed list) | yes (provider-transformed) | S3 (`s3_bucket_name` + `aws_*` + `AWS_BATCH_ROLE_ARN` on model) | -| Bedrock GovCloud (`us-gov-west-1`) | yes (unified only) | yes | no | no | yes (provider-transformed) | S3 (`s3_bucket_name` + `aws_*` + `AWS_GOVCLOUD_*` on model) | +| Bedrock GovCloud (`us-gov-west-1`) | yes (unified only) | yes | no | no | yes (provider-transformed) | S3 (`s3_bucket_name` + `aws_*` on model, resolved from `AWS_GOVCLOUD_ACCESS_KEY_ID` / `AWS_GOVCLOUD_SECRET_ACCESS_KEY` / `AWS_GOVCLOUD_BATCH_S3_BUCKET` / `AWS_GOVCLOUD_BATCH_ROLE_ARN`) | Bedrock cancel maps to `StopModelInvocationJob` and comes back `cancelling`; the lifecycle asserts it the same way it does for OpenAI (`_CANCEL_ASSERTED_PROVIDERS`). From c2fbb11dcaea03c9bdf2ace580afac1d6e76fc0f Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 17 Sep 2026 15:08:09 -0700 Subject: [PATCH 27/36] fix(license): let a wildcard allowed_features license grant the auto_router feature --- litellm/proxy/auth/litellm_license.py | 19 ++++++---- .../proxy/auth/test_litellm_license.py | 35 ++++++++++++++++--- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/litellm/proxy/auth/litellm_license.py b/litellm/proxy/auth/litellm_license.py index 6a1090a0d3a..64608567f92 100644 --- a/litellm/proxy/auth/litellm_license.py +++ b/litellm/proxy/auth/litellm_license.py @@ -17,6 +17,7 @@ if TYPE_CHECKING: AUTO_ROUTER_LICENSE_FEATURE: Final = "auto_router" +LICENSE_ALL_FEATURES: Final = "*" AUTO_ROUTER_LICENSE_REMEDY: Final = "A LiteLLM license with the 'auto_router' feature lifts the limit." @@ -153,17 +154,21 @@ class LicenseCheck: return False return team_count > _max_teams_in_license + def grants_feature(self, feature: str) -> bool: + if self.airgapped_license_data is None: + return False + allowed_features: Final = self.airgapped_license_data.get("allowed_features") + granted: Final = allowed_features if isinstance(allowed_features, list) else (allowed_features,) + return feature in granted or LICENSE_ALL_FEATURES in granted + def auto_router_capability_limit(self) -> int | None: """ How many auto-routers may claim each gated classifier or customization capability: - unlimited (None) only when the signed license lists the auto_router - feature, otherwise one per capability. A license verified through the API carries no - feature list, so it does not lift the limit either. + unlimited (None) only when the signed license lists the auto_router feature or the + "*" wildcard that grants every feature, otherwise one per capability. A license verified + through the API carries no feature list, so it does not lift the limit either. """ - if self.airgapped_license_data is None: - return 1 - allowed_features: Final = self.airgapped_license_data.get("allowed_features") - if isinstance(allowed_features, list) and AUTO_ROUTER_LICENSE_FEATURE in allowed_features: + if self.grants_feature(AUTO_ROUTER_LICENSE_FEATURE): return None return 1 diff --git a/tests/test_litellm/proxy/auth/test_litellm_license.py b/tests/test_litellm/proxy/auth/test_litellm_license.py index d3f80982c7a..83e26968f97 100644 --- a/tests/test_litellm/proxy/auth/test_litellm_license.py +++ b/tests/test_litellm/proxy/auth/test_litellm_license.py @@ -35,8 +35,8 @@ def test_is_over_limit(): def test_auto_router_capability_limit() -> None: - """Only the signed license's auto_router feature lifts the one-router limit; an API-verified - license (no airgapped data) and an airgapped license without the feature keep it.""" + """The signed license's auto_router feature or its "*" wildcard lifts the one-router limit; an + API-verified license (no airgapped data) and an airgapped license without either keep it.""" license_check = LicenseCheck() license_check.airgapped_license_data = {"expiration_date": "2999-01-01", "allowed_features": ["auto_router"]} assert license_check.auto_router_capability_limit() is None @@ -47,9 +47,18 @@ def test_auto_router_capability_limit() -> None: } assert license_check.auto_router_capability_limit() is None + license_check.airgapped_license_data = {"expiration_date": "2999-01-01", "allowed_features": ["*"]} + assert license_check.auto_router_capability_limit() is None + + license_check.airgapped_license_data = {"expiration_date": "2999-01-01", "allowed_features": ["sso", "*"]} + assert license_check.auto_router_capability_limit() is None + license_check.airgapped_license_data = {"expiration_date": "2999-01-01", "allowed_features": ["sso"]} assert license_check.auto_router_capability_limit() == 1 + license_check.airgapped_license_data = {"expiration_date": "2999-01-01", "allowed_features": "*"} + assert license_check.auto_router_capability_limit() is None + license_check.airgapped_license_data = {"expiration_date": "2999-01-01"} assert license_check.auto_router_capability_limit() == 1 @@ -57,7 +66,9 @@ def test_auto_router_capability_limit() -> None: assert license_check.auto_router_capability_limit() == 1 -def _signed_license(expiration_date: str) -> tuple[RSAPublicKey, str]: +def _signed_license( + expiration_date: str, allowed_features: tuple[str, ...] = ("auto_router",) +) -> tuple[RSAPublicKey, str]: import base64 from cryptography.hazmat.primitives import hashes @@ -65,7 +76,7 @@ def _signed_license(expiration_date: str) -> tuple[RSAPublicKey, str]: private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) message = json.dumps( - {"expiration_date": expiration_date, "user_id": "u", "allowed_features": ["auto_router"]} + {"expiration_date": expiration_date, "user_id": "u", "allowed_features": list(allowed_features)} ).encode() signature = private_key.sign( message, @@ -99,3 +110,19 @@ def test_valid_signed_license_with_auto_router_lifts_the_limit() -> None: assert license_check.verify_license_without_api_request(public_key=public_key, license_key=license_key) is True assert license_check.auto_router_capability_limit() is None + + +def test_valid_signed_wildcard_license_lifts_the_limit() -> None: + """The license generator defaults allowed_features to ["*"], meaning every feature, so a wildcard + license grants auto_router the same way a license that names it does.""" + license_check = LicenseCheck() + public_key, license_key = _signed_license("2999-01-01", allowed_features=("*",)) + + assert license_check.verify_license_without_api_request(public_key=public_key, license_key=license_key) is True + assert license_check.grants_feature("auto_router") is True + assert license_check.auto_router_capability_limit() is None + + named_public_key, named_key = _signed_license("2999-01-01", allowed_features=("sso", "audit_logs")) + assert license_check.verify_license_without_api_request(public_key=named_public_key, license_key=named_key) is True + assert license_check.grants_feature("auto_router") is False + assert license_check.auto_router_capability_limit() == 1 From 909a30d6a18daea493030f8f04ba8e4f48484363 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 17 Sep 2026 15:17:00 -0700 Subject: [PATCH 28/36] fix(team): keep a forked member budget's reset window and audit bulk member budget writes Forking a shared budget row rebuilt budget_reset_at from the duration, so editing an unrelated limit restarted the member's window while their spend carried over: a tpm bump quietly handed them a fresh period. The fork now inherits the source row's deadline, and only recomputes when the patch actually sets budget_duration. The bulk member budget route now writes one audit entry per call, a team-scoped 'updated' row carrying every written member's limits before and after, matching what /team/member_add already records for membership changes. It honors the litellm-changed-by header like the other audited team routes. --- .../management_endpoints/common_utils.py | 30 +++--- .../management_v1/teams.py | 12 ++- .../bulk_team_member_budgets.py | 59 +++++++++++- .../test_upsert_budget_membership.py | 28 +++--- .../management_v1/test_teams.py | 93 +++++++++++++++++++ ui/litellm-dashboard/src/lib/http/schema.d.ts | 5 +- 6 files changed, 190 insertions(+), 37 deletions(-) diff --git a/litellm/proxy/management_endpoints/common_utils.py b/litellm/proxy/management_endpoints/common_utils.py index c498c186253..1fe2b0b0381 100644 --- a/litellm/proxy/management_endpoints/common_utils.py +++ b/litellm/proxy/management_endpoints/common_utils.py @@ -582,25 +582,25 @@ async def _upsert_budget_and_membership( ) return - create_data: Final[dict[str, Any]] = { + source_row: Final = ( + await tx.litellm_budgettable.find_unique(where={"budget_id": existing_budget_id}) if is_shared_default else None + ) + source: Final[Mapping[str, Any]] = source_row.model_dump() if source_row is not None else {} + + create_data: Final[dict[str, Any]] = { # mutable-ok: Prisma create payloads are dict-shaped "created_by": user_api_key_dict.user_id or "", "updated_by": user_api_key_dict.user_id or "", + **{f: source[f] for f in _TEAM_MEMBER_BUDGET_LIMIT_FIELDS if _is_set_budget_value(source.get(f))}, + **write_data, } - if is_shared_default: - default_budget_row: Final = await tx.litellm_budgettable.find_unique(where={"budget_id": existing_budget_id}) - if default_budget_row is not None: - default_budget_dict: Final = default_budget_row.model_dump() - for field in _TEAM_MEMBER_BUDGET_LIMIT_FIELDS: - value = default_budget_dict.get(field) - if _is_set_budget_value(value): - create_data[field] = value - - create_data.update(write_data) - - if create_data.get("budget_duration") is not None: - create_data["budget_reset_at"] = get_budget_reset_time(budget_duration=create_data["budget_duration"]) - else: + # A patch that leaves the reset cadence alone must not move the deadline: the clone + # inherits the source row's window instead of restarting it from now, which would + # silently grant a member a fresh period whenever any unrelated limit is edited. + carried: Final = source.get("budget_reset_at") if "budget_duration" not in budget_patch else None + if carried is not None: + create_data["budget_reset_at"] = carried + if create_data.get("budget_reset_at") is None: create_data.pop("budget_reset_at", None) if not _has_meaningful_budget_limit(create_data): diff --git a/litellm/proxy/management_endpoints/management_v1/teams.py b/litellm/proxy/management_endpoints/management_v1/teams.py index eee6f486a4f..eab641b2a27 100644 --- a/litellm/proxy/management_endpoints/management_v1/teams.py +++ b/litellm/proxy/management_endpoints/management_v1/teams.py @@ -2,7 +2,7 @@ from typing import Annotated, Final -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, Header from litellm._logging import verbose_proxy_logger from litellm.proxy._types import CommonProxyErrors, UserAPIKeyAuth @@ -108,6 +108,12 @@ async def bulk_update_team_member_budgets_action( team_id: str, data: BulkTeamMemberBudgetUpdateRequest, user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)], + litellm_changed_by: Annotated[ + str | None, + Header( + description="The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability", + ), + ] = None, ) -> BulkTeamMemberBudgetUpdateResponse: """ Set per-member limits for up to 500 members of one team in one call. Same @@ -135,7 +141,7 @@ async def bulk_update_team_member_budgets_action( ``` """ try: - from litellm.proxy.proxy_server import prisma_client, user_api_key_cache + from litellm.proxy.proxy_server import litellm_proxy_admin_name, prisma_client, user_api_key_cache if prisma_client is None: raise ManagementProblem( @@ -153,6 +159,8 @@ async def bulk_update_team_member_budgets_action( user_api_key_dict=user_api_key_dict, prisma_client=prisma_client, user_api_key_cache=user_api_key_cache, + litellm_proxy_admin_name=litellm_proxy_admin_name, + litellm_changed_by=litellm_changed_by, ) return BulkTeamMemberBudgetUpdateResponse(data=results) diff --git a/litellm/proxy/management_helpers/bulk_team_member_budgets.py b/litellm/proxy/management_helpers/bulk_team_member_budgets.py index b24712ab1b4..d34cb8dfb52 100644 --- a/litellm/proxy/management_helpers/bulk_team_member_budgets.py +++ b/litellm/proxy/management_helpers/bulk_team_member_budgets.py @@ -11,7 +11,14 @@ from datetime import timedelta from types import MappingProxyType from typing import TYPE_CHECKING, Final -from litellm.proxy._types import LiteLLM_TeamTable, LitellmUserRoles, Member, UserAPIKeyAuth +from litellm.litellm_core_utils.safe_json_dumps import safe_dumps +from litellm.proxy._types import ( + LiteLLM_TeamTable, + LitellmTableNames, + LitellmUserRoles, + Member, + UserAPIKeyAuth, +) from litellm.proxy.auth.auth_checks import invalidate_team_member_spend_state from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache from litellm.proxy.db.routing_prisma_wrapper import WriterPinnedClient @@ -21,6 +28,7 @@ from litellm.proxy.management_endpoints.common_utils import ( _upsert_budget_and_membership, # pyright: ignore[reportPrivateUsage] # the single-member write, shared so the two surfaces cannot drift member_budget_patch, ) +from litellm.proxy.management_helpers.audit_logs import create_object_audit_log from litellm.proxy.management_helpers.bulk_user_deletion import ( _duplicate_member_indexes, # pyright: ignore[reportPrivateUsage] # same duplicate rule as members/bulk_delete _eq_filter, # pyright: ignore[reportPrivateUsage] # same prisma filter shape as members/bulk_delete @@ -46,6 +54,14 @@ if TYPE_CHECKING: _BATCH_TX_TIMEOUT: Final = timedelta(seconds=60) _NO_METADATA: Final = MappingProxyType({}) _WITH_BUDGET: Final = MappingProxyType({"litellm_budget_table": True}) +_AUDITED_LIMITS: Final = ( + "max_budget", + "tpm_limit", + "rpm_limit", + "budget_duration", + "budget_reset_at", + "allowed_models", +) def _membership_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_TeamMembership]": @@ -77,6 +93,32 @@ async def _shared_budget_ids(tx: "Prisma", budget_ids: frozenset[str]) -> frozen return frozenset(budget_id for budget_id in budget_ids if sum(1 for row in rows if row.budget_id == budget_id) > 1) +def _limits_audit_value( + rows: "Sequence[prisma_models.LiteLLM_TeamMembership]", +) -> str: + """Serialize the members' limits for an audit-log value. + + The audit-log columns hold a JSON object, so the per-member list is nested under a + key rather than serialized as a top-level array. + """ + return safe_dumps( + { # mutable-ok: the audit-log JSON column rejects a top-level array, so this value must be an object + "team_member_budgets": tuple( + { + "user_id": row.user_id, + "budget_id": row.budget_id, + **{ + field: getattr(row.litellm_budget_table, field) + for field in _AUDITED_LIMITS + if row.litellm_budget_table is not None + }, + } + for row in sorted(rows, key=lambda row: row.user_id) + ) + } + ) + + def _result( member: TeamMemberBudgetPatch, user_id: str | None, @@ -114,6 +156,8 @@ async def bulk_update_team_member_budgets( user_api_key_dict: UserAPIKeyAuth, prisma_client: PrismaClient, user_api_key_cache: UserApiKeyCache, + litellm_proxy_admin_name: str, + litellm_changed_by: str | None = None, ) -> tuple[TeamMemberBudgetUpdateResult, ...]: """Apply one merge patch of per-member limits per requested member, in one transaction.""" team: Final = await TeamRepository(WriterPinnedClient(prisma_client.db)).find_by_id(team_id) @@ -151,7 +195,7 @@ async def bulk_update_team_member_budgets( team_members_filter: Final = _team_users_filter(team_id, user_ids) async with prisma_client.tx(timeout=_BATCH_TX_TIMEOUT) as tx: - memberships: Final = await _membership_tx_db(tx).find_many(where=team_members_filter) + memberships: Final = await _membership_tx_db(tx).find_many(where=team_members_filter, include=_WITH_BUDGET) budget_id_of: Final = MappingProxyType({m.user_id: m.budget_id for m in memberships}) shared: Final = await _shared_budget_ids( tx, frozenset(budget_id for budget_id in budget_id_of.values() if budget_id is not None) @@ -179,6 +223,17 @@ async def bulk_update_team_member_budgets( user_id=user_id, team_id=team_id, user_api_key_cache=user_api_key_cache ) + await create_object_audit_log( + object_id=team_id, + action="updated", + litellm_changed_by=litellm_changed_by, + user_api_key_dict=user_api_key_dict, + litellm_proxy_admin_name=litellm_proxy_admin_name, + table_name=LitellmTableNames.TEAM_TABLE_NAME, + before_value=_limits_audit_value(memberships), + after_value=_limits_audit_value(written), + ) + budget_of: Final = MappingProxyType({m.user_id: m.litellm_budget_table for m in written}) return tuple( _result( diff --git a/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py b/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py index e9b4f11e891..a56c7764763 100644 --- a/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py +++ b/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py @@ -1,6 +1,6 @@ # tests/litellm/proxy/common_utils/test_upsert_budget_membership.py import types -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from unittest.mock import AsyncMock, MagicMock import pytest @@ -27,9 +27,7 @@ def mock_tx(): budget = MagicMock() budget.update = AsyncMock() budget.find_unique = AsyncMock(return_value=None) - budget.create = AsyncMock( - return_value=types.SimpleNamespace(budget_id="new-budget-123") - ) + budget.create = AsyncMock(return_value=types.SimpleNamespace(budget_id="new-budget-123")) tx = MagicMock() tx.litellm_teammembership = membership @@ -83,9 +81,7 @@ async def test_empty_patch_is_noop(mock_tx, fake_user): # member falls back to the team default instead of keeping an empty private row. @pytest.mark.asyncio async def test_clearing_all_limits_disconnects(mock_tx, fake_user): - mock_tx.litellm_budgettable.find_unique = AsyncMock( - return_value=budget_row(max_budget=100.0) - ) + mock_tx.litellm_budgettable.find_unique = AsyncMock(return_value=budget_row(max_budget=100.0)) await _upsert_budget_and_membership( mock_tx, @@ -136,9 +132,7 @@ async def test_clear_one_field_keeps_others(mock_tx, fake_user): # budget_reset_at, so the budget rolls over without waiting for the reset cron. @pytest.mark.asyncio async def test_update_in_place_seeds_reset_at(mock_tx, fake_user): - mock_tx.litellm_budgettable.find_unique = AsyncMock( - return_value=budget_row(max_budget=20.0) - ) + mock_tx.litellm_budgettable.find_unique = AsyncMock(return_value=budget_row(max_budget=20.0)) await _upsert_budget_and_membership( mock_tx, @@ -163,9 +157,7 @@ async def test_update_in_place_seeds_reset_at(mock_tx, fake_user): # budget_duration must not get a (re)computed reset time. @pytest.mark.asyncio async def test_update_in_place_single_field_leaves_reset_at_alone(mock_tx, fake_user): - mock_tx.litellm_budgettable.find_unique = AsyncMock( - return_value=budget_row(max_budget=50.0) - ) + mock_tx.litellm_budgettable.find_unique = AsyncMock(return_value=budget_row(max_budget=50.0)) await _upsert_budget_and_membership( mock_tx, @@ -225,6 +217,7 @@ async def test_create_seeds_reset_at_and_links(mock_tx, fake_user): @pytest.mark.asyncio async def test_clone_on_write_from_shared_default(mock_tx, fake_user): shared_default_id = "team-default-budget-1" + shared_reset_at = datetime.now(timezone.utc) + timedelta(hours=3) mock_tx.litellm_budgettable.find_unique = AsyncMock( return_value=budget_row( budget_id=shared_default_id, @@ -235,6 +228,7 @@ async def test_clone_on_write_from_shared_default(mock_tx, fake_user): rpm_limit=None, model_max_budget=None, budget_duration="1d", + budget_reset_at=shared_reset_at, allowed_models=[], ) ) @@ -252,7 +246,9 @@ async def test_clone_on_write_from_shared_default(mock_tx, fake_user): mock_tx.litellm_budgettable.update.assert_not_called() mock_tx.litellm_budgettable.create.assert_awaited_once() create_data = mock_tx.litellm_budgettable.create.await_args.kwargs["data"] - assert_future_reset_time(create_data.pop("budget_reset_at")) + # The patch never touched budget_duration, so the fork keeps the window it + # inherited: restarting it here would hand the member a fresh period for free. + assert create_data.pop("budget_reset_at") == shared_reset_at assert create_data == { "created_by": fake_user.user_id, "updated_by": fake_user.user_id, @@ -318,9 +314,7 @@ async def test_clone_on_write_clears_duration(mock_tx, fake_user): # team default), we update it in place rather than forking another row. @pytest.mark.asyncio async def test_private_budget_updates_in_place(mock_tx, fake_user): - mock_tx.litellm_budgettable.find_unique = AsyncMock( - return_value=budget_row(max_budget=10.0) - ) + mock_tx.litellm_budgettable.find_unique = AsyncMock(return_value=budget_row(max_budget=10.0)) await _upsert_budget_and_membership( mock_tx, diff --git a/tests/test_litellm/proxy/management_endpoints/management_v1/test_teams.py b/tests/test_litellm/proxy/management_endpoints/management_v1/test_teams.py index 337d47f39da..9d69f52a834 100644 --- a/tests/test_litellm/proxy/management_endpoints/management_v1/test_teams.py +++ b/tests/test_litellm/proxy/management_endpoints/management_v1/test_teams.py @@ -7,6 +7,7 @@ table and the membership/budget relation the bulk budget writer needs. """ import copy +import json from collections.abc import Mapping, Sequence from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone @@ -244,6 +245,7 @@ def _budget( tpm_limit: int | None = None, rpm_limit: int | None = None, budget_duration: str | None = None, + budget_reset_at: datetime | None = None, ) -> _BudgetRow: return _BudgetRow( budget_id=budget_id, @@ -251,6 +253,7 @@ def _budget( tpm_limit=tpm_limit, rpm_limit=rpm_limit, budget_duration=budget_duration, + budget_reset_at=budget_reset_at, ) @@ -267,6 +270,7 @@ async def _bulk_update( user_api_key_dict=caller, prisma_client=prisma, # pyright: ignore[reportArgumentType] # fake stands in for PrismaClient user_api_key_cache=cache or UserApiKeyCache(), + litellm_proxy_admin_name="default_user_id", ) @@ -631,6 +635,95 @@ async def test_the_roster_authz_read_runs_on_the_writer_so_a_lagging_replica_can assert writer.db.litellm_budgettable.rows["priv-m1"].max_budget == 1.0 +@pytest.mark.asyncio +async def test_the_batch_writes_one_audit_entry_carrying_every_written_members_limits_before_and_after(monkeypatch): + import litellm + from litellm.proxy._types import LitellmTableNames + + monkeypatch.setattr(litellm, "store_audit_logs", True) + captured: list[object] = [] + + async def capture(request_data): + captured.append(request_data) + + monkeypatch.setattr("litellm.proxy.management_helpers.audit_logs.create_audit_log_for_update", capture) + prisma = _FakePrisma( + teams=[_team("m1", "m2")], + memberships=[_membership("m1", "priv-m1"), _membership("m2", "priv-m2")], + budgets=[_budget("priv-m1", max_budget=1.0), _budget("priv-m2", max_budget=2.0)], + ) + + await _bulk_update(prisma, [{"user_id": "m1", "max_budget_in_team": 10}]) + + assert len(captured) == 1 + entry = captured[0] + assert (entry.object_id, entry.action, entry.table_name) == ( + TEAM_ID, + "updated", + LitellmTableNames.TEAM_TABLE_NAME, + ) + before = {row["user_id"]: row for row in json.loads(entry.before_value)["team_member_budgets"]} + after = {row["user_id"]: row for row in json.loads(entry.updated_values)["team_member_budgets"]} + assert (before["m1"]["max_budget"], after["m1"]["max_budget"]) == (1.0, 10.0) + assert "m2" not in before and "m2" not in after + + +@pytest.mark.asyncio +async def test_no_audit_entry_is_written_when_audit_logging_is_off(monkeypatch): + import litellm + + monkeypatch.setattr(litellm, "store_audit_logs", False) + captured: list[object] = [] + + async def capture(request_data): + captured.append(request_data) + + monkeypatch.setattr("litellm.proxy.management_helpers.audit_logs.create_audit_log_for_update", capture) + prisma = _FakePrisma( + teams=[_team("m1")], + memberships=[_membership("m1", "priv-m1")], + budgets=[_budget("priv-m1", max_budget=1.0)], + ) + + await _bulk_update(prisma, [{"user_id": "m1", "max_budget_in_team": 10}]) + + assert captured == [] + assert _budget_of(prisma, "m1").max_budget == 10.0 + + +@pytest.mark.asyncio +async def test_forking_a_shared_row_keeps_its_reset_window_so_an_unrelated_limit_edit_grants_no_free_period(): + shared_reset_at = datetime.now(timezone.utc) + timedelta(days=3) + prisma = _FakePrisma( + teams=[_team("m1", "m2")], + memberships=[_membership("m1", "shared-b"), _membership("m2", "shared-b")], + budgets=[_budget("shared-b", max_budget=100.0, budget_duration="30d", budget_reset_at=shared_reset_at)], + ) + + results = await _bulk_update(prisma, [{"user_id": "m1", "tpm_limit": 9}]) + + assert [(r.success, r.budget_duration) for r in results] == [(True, "30d")] + assert _budget_id_of(prisma, "m1") not in (None, "shared-b") + assert _budget_of(prisma, "m1").budget_reset_at == shared_reset_at + assert prisma.db.litellm_budgettable.rows["shared-b"].budget_reset_at == shared_reset_at + + +@pytest.mark.asyncio +async def test_forking_a_shared_row_does_restart_the_window_when_the_patch_sets_a_new_duration(): + shared_reset_at = datetime.now(timezone.utc) + timedelta(days=3) + prisma = _FakePrisma( + teams=[_team("m1", "m2")], + memberships=[_membership("m1", "shared-b"), _membership("m2", "shared-b")], + budgets=[_budget("shared-b", max_budget=100.0, budget_duration="30d", budget_reset_at=shared_reset_at)], + ) + + await _bulk_update(prisma, [{"user_id": "m1", "budget_duration": "1d"}]) + + forked = _budget_of(prisma, "m1").budget_reset_at + assert forked is not None and forked != shared_reset_at + assert forked <= datetime.now(timezone.utc) + timedelta(days=1) + + app = FastAPI() diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index d21698df351..558c10e4f10 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -52186,7 +52186,10 @@ export interface operations { bulk_update_team_member_budgets_action_management_v1_teams__team_id__members_bulk_update_post: { parameters: { query?: never; - header?: never; + header?: { + /** @description The litellm-changed-by header enables tracking of actions performed by authorized users on behalf of other users, providing an audit trail for accountability */ + "litellm-changed-by"?: string | null; + }; path: { team_id: string; }; From 775b83bcf4aa80aca38310f978f588b1bd27630b Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 17 Sep 2026 15:19:35 -0700 Subject: [PATCH 29/36] refactor(team): drop null limits and ISO-format timestamps in the bulk budget audit payload --- .../management_helpers/bulk_team_member_budgets.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/litellm/proxy/management_helpers/bulk_team_member_budgets.py b/litellm/proxy/management_helpers/bulk_team_member_budgets.py index d34cb8dfb52..34b5c0c6a64 100644 --- a/litellm/proxy/management_helpers/bulk_team_member_budgets.py +++ b/litellm/proxy/management_helpers/bulk_team_member_budgets.py @@ -7,7 +7,7 @@ cap never moves another member's. """ from collections.abc import Sequence -from datetime import timedelta +from datetime import datetime, timedelta from types import MappingProxyType from typing import TYPE_CHECKING, Final @@ -93,6 +93,10 @@ async def _shared_budget_ids(tx: "Prisma", budget_ids: frozenset[str]) -> frozen return frozenset(budget_id for budget_id in budget_ids if sum(1 for row in rows if row.budget_id == budget_id) > 1) +def _audit_value(value: object) -> object: + return value.isoformat() if isinstance(value, datetime) else value + + def _limits_audit_value( rows: "Sequence[prisma_models.LiteLLM_TeamMembership]", ) -> str: @@ -108,9 +112,9 @@ def _limits_audit_value( "user_id": row.user_id, "budget_id": row.budget_id, **{ - field: getattr(row.litellm_budget_table, field) + field: _audit_value(getattr(row.litellm_budget_table, field)) for field in _AUDITED_LIMITS - if row.litellm_budget_table is not None + if row.litellm_budget_table is not None and getattr(row.litellm_budget_table, field) is not None }, } for row in sorted(rows, key=lambda row: row.user_id) From ca91751d5b10a1a600b480ab6cc518f8872a39d2 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 17 Sep 2026 15:35:11 -0700 Subject: [PATCH 30/36] fix(responses): keep the addressed response id off bridged provider requests The Responses id security hook keeps the id a client addressed under `_litellm_addressed_response_id` in the request body so internal retries can re-authorize it. On a model without a native Responses config that body is bridged into `completion()` kwargs, the key was treated as a provider param, and providers rejected it, so every follow-up turn carrying `previous_response_id` returned 400. Register the key in `all_litellm_params` so it is dropped before any provider request, and share one constant between the hook and the param list. --- litellm/proxy/hooks/responses_id_security.py | 7 +-- litellm/types/utils.py | 4 +- .../test_handler.py | 62 ++++++++++++++++++- tests/test_litellm/test_utils.py | 22 +++++++ 4 files changed, 89 insertions(+), 6 deletions(-) diff --git a/litellm/proxy/hooks/responses_id_security.py b/litellm/proxy/hooks/responses_id_security.py index 7e7f70d6f7e..d9050489095 100644 --- a/litellm/proxy/hooks/responses_id_security.py +++ b/litellm/proxy/hooks/responses_id_security.py @@ -22,7 +22,7 @@ from litellm.types.llms.openai import ( BaseLiteLLMOpenAIResponseObject, ResponsesAPIResponse, ) -from litellm.types.utils import CallTypesLiteral, LLMResponseTypes, SpecialEnums +from litellm.types.utils import ADDRESSED_RESPONSE_ID_FIELD, CallTypesLiteral, LLMResponseTypes, SpecialEnums if TYPE_CHECKING: from litellm.caching.caching import DualCache @@ -32,7 +32,6 @@ if TYPE_CHECKING: _RESPONSES_API_PROVIDER_PREFIX: Final = "/openai" _RESPONSES_API_CREATE_ROUTES: Final = frozenset({"/v1/responses", "/responses"}) -_ADDRESSED_RESPONSE_ID_KEY: Final = "_litellm_addressed_response_id" _UNMANAGED_RESPONSE_ID_DETAIL: Final = ( "Forbidden. This response id was not issued by this proxy, so the proxy cannot tell who owns it. " "To let keys address responses this proxy did not issue, set " @@ -132,7 +131,7 @@ class ResponsesIDSecurity(CustomLogger): if call_type not in responses_api_call_types: return None addressed_id_field: Final = "previous_response_id" if call_type == "aresponses" else "response_id" - retained_id: Final = data.get(_ADDRESSED_RESPONSE_ID_KEY) + retained_id: Final = data.get(ADDRESSED_RESPONSE_ID_FIELD) addressed_id: Final = ( retained_id if isinstance(retained_id, str) and retained_id else data.get(addressed_id_field) ) @@ -140,7 +139,7 @@ class ResponsesIDSecurity(CustomLogger): return data authorized_id: Final = self._authorize_response_id(addressed_id, user_api_key_dict) data[addressed_id_field] = authorized_id - data[_ADDRESSED_RESPONSE_ID_KEY] = addressed_id + data[ADDRESSED_RESPONSE_ID_FIELD] = addressed_id return data def _authorize_response_id( diff --git a/litellm/types/utils.py b/litellm/types/utils.py index aaa16fd2d44..63c97dbe3d5 100644 --- a/litellm/types/utils.py +++ b/litellm/types/utils.py @@ -3754,6 +3754,8 @@ agentic_loop_internal_litellm_params: Final = [ # the provider. TRUSTED_CALLBACK_VARS_FIELD: Final = "litellm_trusted_callback_vars" +ADDRESSED_RESPONSE_ID_FIELD: Final = "_litellm_addressed_response_id" + # Bedrock managed-batch deployment config, read from litellm_params by the batch and # files transformations. Listed for the same reason as the fields above: these sit on # a deployment that also serves chat, so leaking them into extra_body makes Bedrock @@ -3768,7 +3770,7 @@ bedrock_batch_litellm_params: Final = ( all_litellm_params = ( agentic_loop_internal_litellm_params - + [TRUSTED_CALLBACK_VARS_FIELD, *bedrock_batch_litellm_params] + + [TRUSTED_CALLBACK_VARS_FIELD, ADDRESSED_RESPONSE_ID_FIELD, *bedrock_batch_litellm_params] + [ "metadata", "litellm_metadata", diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py b/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py index b78dabbfe48..15def6f1130 100644 --- a/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py +++ b/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py @@ -12,14 +12,21 @@ capture the forwarded kwargs; if the flag-setting line is removed the captured kwargs lack the flag and these tests fail. """ +import json +from collections.abc import Mapping +from typing import Final from unittest.mock import patch +import httpx import pytest - +import litellm +from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler from litellm.responses.litellm_completion_transformation.handler import ( LiteLLMCompletionTransformationHandler, ) +from litellm.types.llms.openai import ResponsesAPIResponse +from litellm.types.utils import ADDRESSED_RESPONSE_ID_FIELD class _StopForwarding(Exception): @@ -170,3 +177,56 @@ async def test_async_fallback_returns_hoisted_nested_custom_tool_call_as_custom_ tool_calls = [(item.type, item.name, item.input) for item in response.output if item.type == "custom_tool_call"] assert tool_calls == [("custom_tool_call", "exec", "ls")] + + +class _RecordingAnthropicHandler: + def __init__(self, reply: Mapping[str, object]) -> None: + self.reply: Final = reply + self.request_body: Mapping[str, object] | None = None + + def __call__(self, request: httpx.Request) -> httpx.Response: + self.request_body = json.loads(request.content) + return httpx.Response(200, json=dict(self.reply), request=request) + + +_ANTHROPIC_MESSAGE_PAYLOAD: Final = { + "id": "msg_turn_two", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-6", + "content": [{"type": "text", "text": "14"}], + "stop_reason": "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 12, "output_tokens": 1}, +} + + +@pytest.mark.asyncio +async def test_bridged_follow_up_turn_keeps_the_addressed_response_id_off_the_provider_body(): + """The proxy's ResponsesIDSecurity hook rewrites `previous_response_id` and keeps the + id the client addressed under `_litellm_addressed_response_id` in the same request + body, so internal retries re-authorize it. On a model without a native Responses + config that body is bridged into `litellm.acompletion` kwargs, and Azure AI Claude + answered `_litellm_addressed_response_id: Extra inputs are not permitted` (400) on + every follow-up turn. The key is LiteLLM-internal and must never reach the provider. + """ + provider: Final = _RecordingAnthropicHandler(_ANTHROPIC_MESSAGE_PAYLOAD) + client: Final = AsyncHTTPHandler() + client.client = httpx.AsyncClient(transport=httpx.MockTransport(provider)) + + response = await litellm.aresponses( + model="azure_ai/claude-sonnet-4-6", + api_base="https://fake-foundry-resource.services.ai.azure.com", + api_key="fake-api-key", + input="Double it", + previous_response_id="resp_turn_one", + client=client, + **{ADDRESSED_RESPONSE_ID_FIELD: "resp_turn_one"}, + ) + + assert provider.request_body is not None, "the bridged turn never reached the provider" + assert ADDRESSED_RESPONSE_ID_FIELD not in provider.request_body, ( + f"the addressed response id reached the provider body: {sorted(provider.request_body)}" + ) + assert isinstance(response, ResponsesAPIResponse) + assert [item.type for item in response.output] == ["message"] diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index 0d5d507101a..ee5124ea3a6 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -46,6 +46,7 @@ from litellm.types.utils import ( PromptTokensDetailsWrapper, StreamingChoices, Usage, + ADDRESSED_RESPONSE_ID_FIELD, all_litellm_params, bedrock_batch_litellm_params, ) @@ -4787,6 +4788,27 @@ def test_get_litellm_params_keys_never_reach_the_provider(): ) +def test_addressed_response_id_never_reaches_the_provider(): + """The ResponsesIDSecurity hook keeps the id a client addressed under + `_litellm_addressed_response_id` in the request body so internal retries re-authorize + it. A bridged Responses call (no native Responses config, e.g. azure_ai Claude) + forwards that body as `completion()` kwargs, and the provider rejects the unknown + key: `_litellm_addressed_response_id: Extra inputs are not permitted`, a 400 on + every follow-up turn that carries `previous_response_id`. + """ + kwargs = { + "a_real_provider_specific_param": 1, + ADDRESSED_RESPONSE_ID_FIELD: "resp_addressed-by-the-client", + } + + non_default = get_non_default_completion_params(kwargs) + + assert non_default == {"a_real_provider_specific_param": 1}, ( + "the addressed response id leaked into the provider params: " + f"{sorted(set(non_default) - {'a_real_provider_specific_param'})}" + ) + + def test_bedrock_batch_params_never_reach_the_provider(): """A Bedrock managed-batch deployment carries aws_batch_role_arn / s3_* / bedrock_tags in its litellm_params, and the same deployment also serves chat. From 1feaa48705a6e475987397d0f7f4914acb07f33a Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 17 Sep 2026 15:37:00 -0700 Subject: [PATCH 31/36] fix(proxy): log TypeSafe calls that name no model as unknown --- .../typesafe_passthrough_logging_handler.py | 2 +- .../test_typesafe_passthrough_logging_handler.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py index cb6e72c6e3c..9b196660c2c 100644 --- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py +++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/typesafe_passthrough_logging_handler.py @@ -71,7 +71,7 @@ class TypeSafePassthroughLoggingHandler: response_model: Final = response.model request_model_value: Final = request_body.get("model") request_model: Final = request_model_value if isinstance(request_model_value, str) else None - logged_model: Final = response_model or request_model or "jev-latest" + logged_model: Final = response_model or request_model or "unknown" model_name: Final = f"typesafe/{logged_model}" usage: Final = response.usage or _TypeSafeUsage() input_tokens: Final = usage.input_tokens diff --git a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py index 326b86654fe..345eeeedc31 100644 --- a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py +++ b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_typesafe_passthrough_logging_handler.py @@ -80,6 +80,13 @@ def test_falls_back_to_request_model_when_response_model_is_missing(): assert result["kwargs"]["response_cost"] == pytest.approx(expected_cost) +def test_call_naming_no_model_is_logged_as_unknown_and_never_priced_as_a_registry_model(): + result = _handler_result({"usage": {"input_tokens": 10, "output_tokens": 2}}, {}) + + assert result["kwargs"]["model"] == "typesafe/unknown" + assert result["kwargs"]["response_cost"] == 0.0 + + def test_missing_usage_is_zero_cost(): result = _handler_result({"model": "jev-1.13.0"}, {"model": "jev-latest"}) From f04f0258f778d36cbeecef22ed6ab4de4e1ec802 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 17 Sep 2026 15:41:06 -0700 Subject: [PATCH 32/36] refactor(team): model the bulk budget audit payload as frozen types --- .../management_endpoints/common_utils.py | 10 +-- .../bulk_team_member_budgets.py | 74 +++++++++++-------- .../test_upsert_budget_membership.py | 2 - 3 files changed, 48 insertions(+), 38 deletions(-) diff --git a/litellm/proxy/management_endpoints/common_utils.py b/litellm/proxy/management_endpoints/common_utils.py index 1fe2b0b0381..29f24d2465f 100644 --- a/litellm/proxy/management_endpoints/common_utils.py +++ b/litellm/proxy/management_endpoints/common_utils.py @@ -585,18 +585,18 @@ async def _upsert_budget_and_membership( source_row: Final = ( await tx.litellm_budgettable.find_unique(where={"budget_id": existing_budget_id}) if is_shared_default else None ) - source: Final[Mapping[str, Any]] = source_row.model_dump() if source_row is not None else {} + source: Final[Mapping[str, Any]] = source_row.model_dump() if source_row is not None else MappingProxyType({}) create_data: Final[dict[str, Any]] = { # mutable-ok: Prisma create payloads are dict-shaped "created_by": user_api_key_dict.user_id or "", "updated_by": user_api_key_dict.user_id or "", - **{f: source[f] for f in _TEAM_MEMBER_BUDGET_LIMIT_FIELDS if _is_set_budget_value(source.get(f))}, + **MappingProxyType( + {f: source[f] for f in _TEAM_MEMBER_BUDGET_LIMIT_FIELDS if _is_set_budget_value(source.get(f))} + ), **write_data, } - # A patch that leaves the reset cadence alone must not move the deadline: the clone - # inherits the source row's window instead of restarting it from now, which would - # silently grant a member a fresh period whenever any unrelated limit is edited. + # Restarting an inherited window on an unrelated edit hands the member a free period. carried: Final = source.get("budget_reset_at") if "budget_duration" not in budget_patch else None if carried is not None: create_data["budget_reset_at"] = carried diff --git a/litellm/proxy/management_helpers/bulk_team_member_budgets.py b/litellm/proxy/management_helpers/bulk_team_member_budgets.py index 34b5c0c6a64..5ab00a76d2e 100644 --- a/litellm/proxy/management_helpers/bulk_team_member_budgets.py +++ b/litellm/proxy/management_helpers/bulk_team_member_budgets.py @@ -11,6 +11,8 @@ from datetime import datetime, timedelta from types import MappingProxyType from typing import TYPE_CHECKING, Final +from pydantic import BaseModel, ConfigDict + from litellm.litellm_core_utils.safe_json_dumps import safe_dumps from litellm.proxy._types import ( LiteLLM_TeamTable, @@ -54,14 +56,6 @@ if TYPE_CHECKING: _BATCH_TX_TIMEOUT: Final = timedelta(seconds=60) _NO_METADATA: Final = MappingProxyType({}) _WITH_BUDGET: Final = MappingProxyType({"litellm_budget_table": True}) -_AUDITED_LIMITS: Final = ( - "max_budget", - "tpm_limit", - "rpm_limit", - "budget_duration", - "budget_reset_at", - "allowed_models", -) def _membership_tx_db(tx: "Prisma") -> "TableActions[prisma_models.LiteLLM_TeamMembership]": @@ -93,33 +87,51 @@ async def _shared_budget_ids(tx: "Prisma", budget_ids: frozenset[str]) -> frozen return frozenset(budget_id for budget_id in budget_ids if sum(1 for row in rows if row.budget_id == budget_id) > 1) -def _audit_value(value: object) -> object: - return value.isoformat() if isinstance(value, datetime) else value +class _AuditedMemberBudget(BaseModel): + """One member's limits as the audit log's before/after values record them.""" + + model_config = ConfigDict(frozen=True) + + user_id: str + budget_id: str | None = None + max_budget: float | None = None + tpm_limit: int | None = None + rpm_limit: int | None = None + budget_duration: str | None = None + budget_reset_at: datetime | None = None + allowed_models: tuple[str, ...] | None = None -def _limits_audit_value( - rows: "Sequence[prisma_models.LiteLLM_TeamMembership]", -) -> str: - """Serialize the members' limits for an audit-log value. +class _AuditedMemberBudgets(BaseModel): + """The audit-log columns hold a JSON object, so the per-member list is nested under a key.""" - The audit-log columns hold a JSON object, so the per-member list is nested under a - key rather than serialized as a top-level array. - """ + model_config = ConfigDict(frozen=True) + + team_member_budgets: tuple[_AuditedMemberBudget, ...] + + +def _audited_member_budget(row: "prisma_models.LiteLLM_TeamMembership") -> _AuditedMemberBudget: + budget: Final = row.litellm_budget_table + if budget is None: + return _AuditedMemberBudget(user_id=row.user_id, budget_id=row.budget_id) + return _AuditedMemberBudget( + user_id=row.user_id, + budget_id=row.budget_id, + max_budget=budget.max_budget, + tpm_limit=budget.tpm_limit, + rpm_limit=budget.rpm_limit, + budget_duration=budget.budget_duration, + budget_reset_at=budget.budget_reset_at, + allowed_models=tuple(budget.allowed_models) if budget.allowed_models is not None else None, + ) + + +def _limits_audit_value(rows: "Sequence[prisma_models.LiteLLM_TeamMembership]") -> str: + """Serialize the members' limits for an audit-log value, dropping the limits they do not set.""" return safe_dumps( - { # mutable-ok: the audit-log JSON column rejects a top-level array, so this value must be an object - "team_member_budgets": tuple( - { - "user_id": row.user_id, - "budget_id": row.budget_id, - **{ - field: _audit_value(getattr(row.litellm_budget_table, field)) - for field in _AUDITED_LIMITS - if row.litellm_budget_table is not None and getattr(row.litellm_budget_table, field) is not None - }, - } - for row in sorted(rows, key=lambda row: row.user_id) - ) - } + _AuditedMemberBudgets( + team_member_budgets=tuple(_audited_member_budget(row) for row in sorted(rows, key=lambda row: row.user_id)) + ).model_dump(exclude_none=True, mode="json") ) diff --git a/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py b/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py index a56c7764763..2cc0d9f74f5 100644 --- a/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py +++ b/tests/test_litellm/proxy/common_utils/test_upsert_budget_membership.py @@ -246,8 +246,6 @@ async def test_clone_on_write_from_shared_default(mock_tx, fake_user): mock_tx.litellm_budgettable.update.assert_not_called() mock_tx.litellm_budgettable.create.assert_awaited_once() create_data = mock_tx.litellm_budgettable.create.await_args.kwargs["data"] - # The patch never touched budget_duration, so the fork keeps the window it - # inherited: restarting it here would hand the member a fresh period for free. assert create_data.pop("budget_reset_at") == shared_reset_at assert create_data == { "created_by": fake_user.user_id, From 79029d89f978fb3ceee6586b78a6f4020cbeadbe Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 17 Sep 2026 15:51:35 -0700 Subject: [PATCH 33/36] test(responses): drop the history docstrings from the bridge regression tests --- .../litellm_completion_transformation/test_handler.py | 7 ------- tests/test_litellm/test_utils.py | 7 ------- 2 files changed, 14 deletions(-) diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py b/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py index 15def6f1130..bb374b90f4e 100644 --- a/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py +++ b/tests/test_litellm/responses/litellm_completion_transformation/test_handler.py @@ -203,13 +203,6 @@ _ANTHROPIC_MESSAGE_PAYLOAD: Final = { @pytest.mark.asyncio async def test_bridged_follow_up_turn_keeps_the_addressed_response_id_off_the_provider_body(): - """The proxy's ResponsesIDSecurity hook rewrites `previous_response_id` and keeps the - id the client addressed under `_litellm_addressed_response_id` in the same request - body, so internal retries re-authorize it. On a model without a native Responses - config that body is bridged into `litellm.acompletion` kwargs, and Azure AI Claude - answered `_litellm_addressed_response_id: Extra inputs are not permitted` (400) on - every follow-up turn. The key is LiteLLM-internal and must never reach the provider. - """ provider: Final = _RecordingAnthropicHandler(_ANTHROPIC_MESSAGE_PAYLOAD) client: Final = AsyncHTTPHandler() client.client = httpx.AsyncClient(transport=httpx.MockTransport(provider)) diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index ee5124ea3a6..6f86ecc8f18 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -4789,13 +4789,6 @@ def test_get_litellm_params_keys_never_reach_the_provider(): def test_addressed_response_id_never_reaches_the_provider(): - """The ResponsesIDSecurity hook keeps the id a client addressed under - `_litellm_addressed_response_id` in the request body so internal retries re-authorize - it. A bridged Responses call (no native Responses config, e.g. azure_ai Claude) - forwards that body as `completion()` kwargs, and the provider rejects the unknown - key: `_litellm_addressed_response_id: Extra inputs are not permitted`, a 400 on - every follow-up turn that carries `previous_response_id`. - """ kwargs = { "a_real_provider_specific_param": 1, ADDRESSED_RESPONSE_ID_FIELD: "resp_addressed-by-the-client", From f16c4e7a223d786e86dc23d7a77333610c56fefe Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Thu, 17 Sep 2026 16:00:24 -0700 Subject: [PATCH 34/36] fix(team): drop a redundant None check on a non-nullable allowed_models column --- litellm/proxy/management_helpers/bulk_team_member_budgets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/litellm/proxy/management_helpers/bulk_team_member_budgets.py b/litellm/proxy/management_helpers/bulk_team_member_budgets.py index 5ab00a76d2e..8ca27d8d9ce 100644 --- a/litellm/proxy/management_helpers/bulk_team_member_budgets.py +++ b/litellm/proxy/management_helpers/bulk_team_member_budgets.py @@ -122,7 +122,7 @@ def _audited_member_budget(row: "prisma_models.LiteLLM_TeamMembership") -> _Audi rpm_limit=budget.rpm_limit, budget_duration=budget.budget_duration, budget_reset_at=budget.budget_reset_at, - allowed_models=tuple(budget.allowed_models) if budget.allowed_models is not None else None, + allowed_models=tuple(budget.allowed_models), ) From 99b83a2d52e286ce7109ea4c68b63f7e04700324 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Thu, 17 Sep 2026 16:39:31 -0700 Subject: [PATCH 35/36] fix(fireworks_ai): restore supports_vision on minimax-m3 in the cost map --- litellm/model_prices_and_context_window_backup.json | 4 ++-- model_prices_and_context_window.json | 4 ++-- .../chat/test_fireworks_ai_chat_transformation.py | 2 ++ tests/test_litellm/test_utils.py | 5 ++--- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 96cdbcffd90..2992efaebcd 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -23788,7 +23788,7 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_vision": false + "supports_vision": true }, "fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct-hf": { "input_cost_per_token": 1.2e-06, @@ -24114,7 +24114,7 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_vision": false + "supports_vision": true }, "fireworks_ai/qwen3p7-plus": { "cache_read_input_token_cost": 8e-08, diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index 96cdbcffd90..2992efaebcd 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -23788,7 +23788,7 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_vision": false + "supports_vision": true }, "fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct-hf": { "input_cost_per_token": 1.2e-06, @@ -24114,7 +24114,7 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_vision": false + "supports_vision": true }, "fireworks_ai/qwen3p7-plus": { "cache_read_input_token_cost": 8e-08, diff --git a/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py b/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py index f30263bebd5..db25c4307d2 100644 --- a/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py +++ b/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py @@ -978,6 +978,8 @@ def test_llama_vision_supports_vision_from_model_map(): for model in [ "fireworks_ai/accounts/fireworks/models/llama-v3p2-11b-vision-instruct", + "fireworks_ai/accounts/fireworks/models/minimax-m3", + "fireworks_ai/minimax-m3", ]: assert supports_vision(model=model, custom_llm_provider="fireworks_ai") is True assert config.get_provider_info(model)["supports_vision"] is True diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index 6f86ecc8f18..a3be0c37153 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -3547,7 +3547,7 @@ _FIREWORKS_MODELS = [ "accounts/fireworks/models/minimax-m3", 512000, 512000, - None, + True, True, ), ( @@ -3655,8 +3655,7 @@ def _assert_fireworks_entry( assert info["supports_tool_choice"] is True assert info["supports_reasoning"] is expected_reasoning assert info["supports_response_schema"] is True - if expected_vision is not None: - assert info["supports_vision"] is expected_vision + assert info["supports_vision"] is expected_vision @pytest.fixture From 76ae1bfa2f32fe2095e80a3a39e4c05480894c96 Mon Sep 17 00:00:00 2001 From: kerry Date: Thu, 17 Sep 2026 23:56:05 +0000 Subject: [PATCH 36/36] build(deps): bump soupsieve to 2.9.2 to clear the osv-scan advisories Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- uv.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/uv.lock b/uv.lock index 35eaa20c39e..a5e60c68515 100644 --- a/uv.lock +++ b/uv.lock @@ -10,7 +10,7 @@ resolution-markers = [ ] [options] -exclude-newer = "2026-09-14T20:32:38.482736111Z" +exclude-newer = "2026-09-14T23:55:55.024292355Z" exclude-newer-span = "P3D" [manifest] @@ -9262,11 +9262,11 @@ wheels = [ [[package]] name = "soupsieve" -version = "2.8.4" +version = "2.9.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/47/2c/0a5f6f8ee0d5589e48c7640213ed5175d52cf540a06725b628cc1a45d6ce/soupsieve-2.8.4.tar.gz", hash = "sha256:e121fd02e975c695e4e9e8774a5ee35d74714b59307868dcc5319ad2d9e3328e", size = 121110, upload-time = "2026-05-24T13:55:57.154Z" } +sdist = { url = "https://files.pythonhosted.org/packages/69/99/a6ca3beb3ccacb41fb3321d8a60e5566f9e6467601ef8eba6a17e1b89778/soupsieve-2.9.2.tar.gz", hash = "sha256:4a55d8cf158a9c2e587fa4922f1bbb91d68ac829e2d6f25403a85747c71daf74", size = 122445, upload-time = "2026-08-07T00:57:24.801Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5e/f5/0c41cb68dcae6b7de4fac4188a3a9589e21fb31df21ea3a2e888db95e6c9/soupsieve-2.8.4-py3-none-any.whl", hash = "sha256:e7e6b0769c8f51ed59acab6e994b00621096cfb1c640a7509295987388fbaf65", size = 37304, upload-time = "2026-05-24T13:55:55.406Z" }, + { url = "https://files.pythonhosted.org/packages/eb/dc/ad025c1ee131eba60c69f4dd5779b18fcf1e6b21a343e2162a84d5d133c7/soupsieve-2.9.2-py3-none-any.whl", hash = "sha256:8089a26fd974ca7a1f30276d3d8492ab266ab15af581642dfe8aa162e0c1c823", size = 37370, upload-time = "2026-08-07T00:57:23.524Z" }, ] [[package]]