Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(proxy): add /team/daily/activity/aggregated and switch the Usage team tab to it (#36562)

ryan-crabbe-berri9ec01459864b
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 9a118f57f39..97b7bf97a4e 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -287,6 +287,7 @@ class KeyManagementRoutes(str, enum.Enum):
# team usage routes
TEAM_DAILY_ACTIVITY = "/team/daily/activity"
+ TEAM_DAILY_ACTIVITY_AGGREGATED = "/team/daily/activity/aggregated"
# team spend-log viewing
SPEND_LOGS = "/spend/logs"
@@ -612,6 +613,7 @@ class LiteLLMRoutes(enum.Enum):
KeyManagementRoutes.KEY_BULK_UPDATE.value,
KeyManagementRoutes.TEAM_KEY_BULK_UPDATE.value,
KeyManagementRoutes.TEAM_DAILY_ACTIVITY.value,
+ KeyManagementRoutes.TEAM_DAILY_ACTIVITY_AGGREGATED.value,
KeyManagementRoutes.SPEND_LOGS.value,
KeyManagementRoutes.SPEND_LOGS_V2.value,
KeyManagementRoutes.KEY_RESET_SPEND.value,
@@ -646,6 +648,7 @@ class LiteLLMRoutes(enum.Enum):
"/team/permissions_update",
"/team/permissions_bulk_update",
"/team/daily/activity",
+ "/team/daily/activity/aggregated",
# gateway request counts (SGR); deployment-wide, admin-only
"/gateway/daily/activity",
# model
@@ -801,6 +804,7 @@ class LiteLLMRoutes(enum.Enum):
"/team/permissions_list",
"/team/permissions_update",
"/team/daily/activity",
+ "/team/daily/activity/aggregated",
"/team/{team_id}/members/me",
"/model/new",
"/model/update",
@@ -863,6 +867,7 @@ class LiteLLMRoutes(enum.Enum):
"/user/available_roles",
"/user/daily/activity",
"/team/daily/activity",
+ "/team/daily/activity/aggregated",
"/tag/daily/activity",
"/tag/list",
"/audit",
diff --git a/litellm/proxy/management_endpoints/common_daily_activity.py b/litellm/proxy/management_endpoints/common_daily_activity.py
index d1542b38996..8edb3b42dce 100644
--- a/litellm/proxy/management_endpoints/common_daily_activity.py
+++ b/litellm/proxy/management_endpoints/common_daily_activity.py
@@ -1,5 +1,6 @@
import asyncio
from collections.abc import Awaitable, Callable, Mapping, Sequence
+from collections.abc import Set as AbstractSet
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from typing import TYPE_CHECKING, Final, Protocol
@@ -142,6 +143,11 @@ class _GroupingSetsRow(SimpleNamespace):
failed_requests: int | None
+class _EntityRollupRow(_GroupingSetsRow):
+ entity_id: str | None
+ api_key_rolled: int
+
+
def _reported_flat_cost(record: DailySpendRecord | _GroupingSetsRow) -> float:
"""Flat cost a daily row reports, which is zero unless PTU cost attribution is enabled.
@@ -224,6 +230,15 @@ def compute_tag_metadata_totals(records: Sequence[DailySpendRecord]) -> SpendMet
return metadata_metrics
+def _entity_metadata(
+ entity_metadata_field: Mapping[str, dict[str, object]] | None,
+ entity_id: str,
+) -> dict[str, object]:
+ """The metadata payload for one entity breakdown bucket, empty when the caller passed none."""
+ stored: Final = entity_metadata_field.get(entity_id) if entity_metadata_field else None
+ return stored if stored is not None else {} # mutable-ok: payload pydantic validates into its own dict
+
+
def update_breakdown_metrics(
breakdown: BreakdownMetrics,
record: DailySpendRecord,
@@ -395,7 +410,7 @@ def update_breakdown_metrics(
if entity_value not in breakdown.entities:
breakdown.entities[entity_value] = MetricWithMetadata(
metrics=SpendMetrics(),
- metadata=(entity_metadata_field.get(entity_value, {}) if entity_metadata_field else {}),
+ metadata=_entity_metadata(entity_metadata_field, entity_value),
)
breakdown.entities[entity_value].metrics = update_metrics(breakdown.entities[entity_value].metrics, record)
@@ -419,7 +434,7 @@ def update_breakdown_metrics(
async def get_api_key_metadata(
prisma_client: PrismaClient,
- api_keys: set[str],
+ api_keys: AbstractSet[str],
) -> dict[str, _KeyMetadataDict]:
"""Get api key metadata, falling back to deleted keys table for keys not found in active table.
@@ -555,34 +570,17 @@ def _build_where_conditions(
return where_conditions
-def _build_aggregated_sql_query(
+def _build_aggregated_where_clause(
*,
- table_name: str,
entity_id_field: str,
entity_id: str | list[str] | None,
- start_date: str,
- end_date: str,
+ adjusted_start: str,
+ adjusted_end: str,
model: str | None,
- api_key: str | None,
- exclude_entity_ids: list[str] | None = None,
- timezone_offset_minutes: int | None = None,
+ api_key: str | list[str] | None, # mutable-ok: filter union shared with the paginated path
+ exclude_entity_ids: list[str] | None, # mutable-ok: filter union shared with the paginated path
) -> tuple[str, list[str]]:
- """Build a parameterized SQL GROUP BY query for aggregated daily activity.
-
- Groups by (date, api_key, model, model_group, custom_llm_provider,
- mcp_namespaced_tool_name, endpoint) with SUMs on all metric columns.
- The entity_id column is intentionally omitted from GROUP BY to collapse
- rows across entities — this is where the biggest row reduction comes from.
-
- Returns:
- Tuple of (sql_query, params_list) ready for prisma_client.db.query_raw().
- """
- pg_table: Final = _PRISMA_TO_PG_TABLE.get(table_name)
- if pg_table is None:
- raise ValueError(f"Unknown table name: {table_name}")
-
- adjusted_start, adjusted_end = _adjust_dates_for_timezone(start_date, end_date, timezone_offset_minutes)
-
+ """Build the WHERE clause and $N params shared by the aggregated queries."""
sql_conditions: Final[list[str]] = []
sql_params: Final[list[str]] = []
p = 1 # parameter index (1-based for PostgreSQL $N placeholders)
@@ -621,13 +619,68 @@ def _build_aggregated_sql_query(
sql_params.append(model)
p += 1
- # Optional api_key filter
- if api_key:
+ # Optional api_key filter; an empty list must match nothing, not everything
+ if isinstance(api_key, list):
+ if api_key:
+ placeholders = ", ".join(f"${p + i}" for i in range(len(api_key)))
+ sql_conditions.append(f"api_key IN ({placeholders})")
+ sql_params.extend(api_key)
+ p += len(api_key)
+ else:
+ sql_conditions.append("FALSE")
+ elif api_key:
sql_conditions.append(f"api_key = ${p}")
sql_params.append(api_key)
p += 1
- where_clause: Final = " AND ".join(sql_conditions)
+ return " AND ".join(sql_conditions), sql_params
+
+
+def _ptu_flat_cost_select(table_name: str) -> str:
+ """Only LiteLLM_DailyTeamSpend carries ptu_flat_cost; other daily tables emit a
+ constant zero so the SpendMetrics.flat_cost response shape stays uniform."""
+ if table_name == "litellm_dailyteamspend":
+ return "SUM(ptu_flat_cost)::float AS ptu_flat_cost"
+ return "0::float AS ptu_flat_cost"
+
+
+def _build_aggregated_sql_query(
+ *,
+ table_name: str,
+ entity_id_field: str,
+ entity_id: str | list[str] | None, # mutable-ok: filter union shared with the paginated path
+ start_date: str,
+ end_date: str,
+ model: str | None,
+ api_key: str | list[str] | None, # mutable-ok: filter union shared with the paginated path
+ exclude_entity_ids: list[str] | None = None, # mutable-ok: filter union shared with the paginated path
+ timezone_offset_minutes: int | None = None,
+) -> tuple[str, list[str]]: # mutable-ok: SQL text plus its ordered $N params
+ """Build a parameterized SQL GROUP BY query for aggregated daily activity.
+
+ Groups by (date, api_key, model, model_group, custom_llm_provider,
+ mcp_namespaced_tool_name, endpoint) with SUMs on all metric columns.
+ The entity_id column is intentionally omitted from GROUP BY to collapse
+ rows across entities — this is where the biggest row reduction comes from.
+
+ Returns:
+ Tuple of (sql_query, params_list) ready for prisma_client.db.query_raw().
+ """
+ pg_table: Final = _PRISMA_TO_PG_TABLE.get(table_name)
+ if pg_table is None:
+ raise ValueError(f"Unknown table name: {table_name}")
+
+ adjusted_start, adjusted_end = _adjust_dates_for_timezone(start_date, end_date, timezone_offset_minutes)
+
+ where_clause, sql_params = _build_aggregated_where_clause(
+ entity_id_field=entity_id_field,
+ entity_id=entity_id,
+ adjusted_start=adjusted_start,
+ adjusted_end=adjusted_end,
+ model=model,
+ api_key=api_key,
+ exclude_entity_ids=exclude_entity_ids,
+ )
# Postgres computes every rollup level the response needs — per-date
# totals, per-(date, model), per-(date, model, api_key), per-provider,
@@ -641,14 +694,6 @@ def _build_aggregated_sql_query(
# total_successful_requests metadata they feed) once the admin UI reads SGR
# only from LiteLLM_DailyGatewayRequests. The remaining spend, token and
# api_requests rollups are still served from here.
- #
- # Only LiteLLM_DailyTeamSpend carries ptu_flat_cost; other daily tables emit a
- # constant zero so the SpendMetrics.flat_cost response shape stays uniform.
- ptu_flat_cost_select: Final = (
- "SUM(ptu_flat_cost)::float AS ptu_flat_cost"
- if table_name == "litellm_dailyteamspend"
- else "0::float AS ptu_flat_cost"
- )
sql_query: Final = f"""
SELECT
date,
@@ -662,7 +707,7 @@ def _build_aggregated_sql_query(
custom_llm_provider, mcp_namespaced_tool_name,
endpoint) AS group_level,
SUM(spend)::float AS spend,
- {ptu_flat_cost_select},
+ {_ptu_flat_cost_select(table_name)},
SUM(prompt_tokens)::bigint AS prompt_tokens,
SUM(completion_tokens)::bigint AS completion_tokens,
SUM(cache_read_input_tokens)::bigint AS cache_read_input_tokens,
@@ -696,6 +741,70 @@ def _build_aggregated_sql_query(
return sql_query, sql_params
+def _build_entity_rollup_sql_query(
+ *,
+ table_name: str,
+ entity_id_field: str,
+ entity_id: str | list[str] | None, # mutable-ok: filter union shared with the paginated path
+ start_date: str,
+ end_date: str,
+ model: str | None,
+ api_key: str | list[str] | None, # mutable-ok: filter union shared with the paginated path
+ exclude_entity_ids: list[str] | None = None, # mutable-ok: filter union shared with the paginated path
+ timezone_offset_minutes: int | None = None,
+) -> tuple[str, list[str]]: # mutable-ok: SQL text plus its ordered $N params
+ """Per-entity companion to _build_aggregated_sql_query.
+
+ Two rollup levels over the same WHERE clause — (date, entity) and
+ (date, entity, api_key) — told apart by GROUPING(api_key): 1 when the
+ api_key column is rolled up, 0 when it is part of the key.
+ """
+ pg_table: Final = _PRISMA_TO_PG_TABLE.get(table_name)
+ if pg_table is None:
+ raise ValueError(f"Unknown table name: {table_name}")
+
+ adjusted_start, adjusted_end = _adjust_dates_for_timezone(start_date, end_date, timezone_offset_minutes)
+
+ where_clause, sql_params = _build_aggregated_where_clause(
+ entity_id_field=entity_id_field,
+ entity_id=entity_id,
+ adjusted_start=adjusted_start,
+ adjusted_end=adjusted_end,
+ model=model,
+ api_key=api_key,
+ exclude_entity_ids=exclude_entity_ids,
+ )
+
+ sql_query: Final = f"""
+ SELECT
+ "{entity_id_field}" AS entity_id,
+ date,
+ api_key,
+ GROUPING(api_key) AS api_key_rolled,
+ SUM(spend)::float AS spend,
+ {_ptu_flat_cost_select(table_name)},
+ SUM(prompt_tokens)::bigint AS prompt_tokens,
+ SUM(completion_tokens)::bigint AS completion_tokens,
+ SUM(cache_read_input_tokens)::bigint AS cache_read_input_tokens,
+ SUM(cache_creation_input_tokens)::bigint AS cache_creation_input_tokens,
+ SUM(compression_saved_tokens)::bigint AS compression_saved_tokens,
+ SUM(compression_savings_spend)::float AS compression_savings_spend,
+ SUM(prompt_caching_savings_spend)::float AS prompt_caching_savings_spend,
+ SUM(autorouter_savings_spend)::float AS autorouter_savings_spend,
+ SUM(api_requests)::bigint AS api_requests,
+ SUM(successful_requests)::bigint AS successful_requests,
+ SUM(failed_requests)::bigint AS failed_requests
+ FROM "{pg_table}"
+ WHERE {where_clause}
+ GROUP BY GROUPING SETS (
+ (date, "{entity_id_field}"),
+ (date, "{entity_id_field}", api_key)
+ )
+ """
+
+ return sql_query, sql_params
+
+
def _aggregate_spend_records_sync(
*,
records: Sequence[DailySpendRecord],
@@ -1097,6 +1206,40 @@ async def get_daily_activity(
)
+def _fold_entity_rollups_sync(
+ *,
+ results: Sequence[DailySpendData],
+ entity_rows: Sequence[_EntityRollupRow],
+ api_key_metadata: Mapping[str, _KeyMetadataDict],
+ entity_metadata_field: Mapping[str, dict[str, object]] | None, # mutable-ok: shared field shape
+) -> None:
+ """Write breakdown.entities onto the already-built per-day results."""
+ by_date: Final = {day.date.strftime("%Y-%m-%d"): day for day in results} # mutable-ok: local fold index
+
+ for row in entity_rows:
+ day = by_date.get(row.date)
+ if day is None:
+ continue
+
+ entities = day.breakdown.entities
+ entity_id = row.entity_id or "Unassigned"
+ bucket = entities.get(entity_id)
+ if bucket is None:
+ bucket = MetricWithMetadata(
+ metrics=SpendMetrics(),
+ metadata=_entity_metadata(entity_metadata_field, entity_id),
+ )
+ entities[entity_id] = bucket
+
+ metrics = _record_to_spend_metrics(row)
+ if row.api_key_rolled:
+ bucket.metrics = metrics
+ elif row.api_key and row.api_key != PTU_SENTINEL_API_KEY:
+ bucket.api_key_breakdown[row.api_key] = KeyMetricWithMetadata(
+ metrics=metrics, metadata=_key_metadata(api_key_metadata, row.api_key)
+ )
+
+
async def get_daily_activity_aggregated(
prisma_client: PrismaClient | None,
table_name: str,
@@ -1106,9 +1249,10 @@ async def get_daily_activity_aggregated(
start_date: str | None,
end_date: str | None,
model: str | None,
- api_key: str | None,
+ api_key: str | list[str] | None, # mutable-ok: filter union shared with the paginated path
exclude_entity_ids: list[str] | None = None,
timezone_offset_minutes: int | None = None,
+ include_entity_breakdown: bool = False,
) -> SpendAnalyticsPaginatedResponse:
"""Aggregated variant that returns the full result set (no pagination).
@@ -1116,6 +1260,9 @@ async def get_daily_activity_aggregated(
all individual rows into Python. This collapses rows across entities
(users/teams/orgs), reducing ~150k rows to ~2-3k grouped rows.
+ include_entity_breakdown runs a small companion rollup query and folds
+ `breakdown.entities` onto the response, as entity-scoped views like Team Usage need.
+
Matches the response model of the paginated endpoint so the UI does not need to transform.
"""
if prisma_client is None:
@@ -1143,12 +1290,34 @@ async def get_daily_activity_aggregated(
timezone_offset_minutes=timezone_offset_minutes,
)
- # Execute GROUPING SETS query — returns one row per rollup level.
- rows = await prisma_client.db.query_raw(sql_query, *sql_params)
- if rows is None:
- rows = []
+ entity_query: Final = (
+ _build_entity_rollup_sql_query(
+ table_name=table_name,
+ entity_id_field=entity_id_field,
+ entity_id=entity_id,
+ start_date=start_date,
+ end_date=end_date,
+ model=model,
+ api_key=api_key,
+ exclude_entity_ids=exclude_entity_ids,
+ timezone_offset_minutes=timezone_offset_minutes,
+ )
+ if include_entity_breakdown
+ else None
+ )
- records: Final = [_GroupingSetsRow(**row) for row in rows]
+ # Execute the GROUPING SETS query (one row per rollup level), alongside
+ # the per-entity companion rollup when the caller wants entities.
+ raw_rows, raw_entity_rows = (
+ await asyncio.gather(
+ prisma_client.db.query_raw(sql_query, *sql_params),
+ prisma_client.db.query_raw(entity_query[0], *entity_query[1]),
+ )
+ if entity_query is not None
+ else (await prisma_client.db.query_raw(sql_query, *sql_params), None)
+ )
+
+ records: Final = [_GroupingSetsRow(**row) for row in (raw_rows or [])]
# The grouping-sets dispatcher places each row directly in its bucket
# using the row's GROUPING() bitmask. No Python-side summing needed.
@@ -1157,6 +1326,24 @@ async def get_daily_activity_aggregated(
records=records,
)
+ if raw_entity_rows:
+ entity_records: Final = tuple(_EntityRollupRow(**row) for row in raw_entity_rows)
+ entity_api_keys: Final = frozenset(
+ r.api_key for r in entity_records if r.api_key and r.api_key != PTU_SENTINEL_API_KEY
+ )
+ entity_key_metadata: Final = (
+ await get_api_key_metadata(prisma_client, entity_api_keys)
+ if entity_api_keys
+ else {} # mutable-ok: matches the helper's dict return
+ )
+ await asyncio.to_thread(
+ _fold_entity_rollups_sync,
+ results=aggregated["results"],
+ entity_rows=entity_records,
+ api_key_metadata=entity_key_metadata,
+ entity_metadata_field=entity_metadata_field,
+ )
+
return SpendAnalyticsPaginatedResponse(
results=aggregated["results"],
metadata=DailySpendMetadata(
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index 3d7f0808fb9..95632d7cb35 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -16,7 +16,7 @@ import traceback
from collections.abc import Mapping, Sequence
from datetime import datetime, timezone
from types import MappingProxyType
-from typing import Annotated, Final, Protocol, TypedDict, TypeVar, cast
+from typing import Annotated, Final, NamedTuple, Protocol, TypedDict, TypeVar, cast
import fastapi
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
@@ -90,6 +90,9 @@ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.callback_utils import encrypt_callback_vars
from litellm.proxy.common_utils.json_merge_patch import apply_json_merge_patch
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+from litellm.proxy.management_endpoints.common_daily_activity import (
+ get_daily_activity_aggregated,
+)
from litellm.proxy.management_endpoints.common_utils import (
_check_passthrough_routes_caller_permission,
_is_user_org_admin_for_team,
@@ -5679,49 +5682,32 @@ async def _append_permissions_to_all_teams(prisma_client: PrismaClient, permissi
return teams_updated
- "/team/daily/activity",
- response_model=SpendAnalyticsPaginatedResponse,
- tags=["team management"],
-)
-async def get_team_daily_activity(
- team_ids: str | None = None,
- start_date: str | None = None,
- end_date: str | None = None,
- model: str | None = None,
- api_key: str | None = None,
- page: int = 1,
- page_size: int = 10,
- exclude_team_ids: str | None = None,
- user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
-):
- """
- Get daily activity for specific teams or all teams.
+def _daily_activity_error(*, status_code: int, message: str) -> HTTPException:
+ """Single construction site for the `{"error": ...}` detail shape the
+ /team/daily/activity endpoints have always returned."""
+ return HTTPException(status_code=status_code, detail={"error": message}) # mutable-ok: FastAPI JSON detail
- Args:
- team_ids (Optional[str]): Comma-separated list of team IDs to filter by. If not provided, returns data for all teams.
- start_date (Optional[str]): Start date for the activity period (YYYY-MM-DD).
- end_date (Optional[str]): End date for the activity period (YYYY-MM-DD).
- model (Optional[str]): Filter by model name.
- api_key (Optional[str]): Filter by API key.
- page (int): Page number for pagination.
- page_size (int): Number of items per page.
- exclude_team_ids (Optional[str]): Comma-separated list of team IDs to exclude.
- Returns:
- SpendAnalyticsPaginatedResponse: Paginated response containing daily activity data.
- """
- from litellm.proxy.proxy_server import (
- prisma_client,
- proxy_logging_obj,
- user_api_key_cache,
- )
- if prisma_client is None:
- raise HTTPException(
- status_code=500,
- detail={"error": CommonProxyErrors.db_not_connected_error.value},
- )
+class _TeamDailyActivityScope(NamedTuple):
+ team_ids: list[str] | None # mutable-ok: downstream daily-activity signatures take str | list unions
+ exclude_team_ids: list[str] | None # mutable-ok: downstream daily-activity signatures take str | list unions
+ team_alias_metadata: dict[str, dict[str, object]] # mutable-ok: entity_metadata_field shape
+ api_key_filter: str | list[str] | None # mutable-ok: downstream daily-activity signatures take str | list unions
+
+async def _resolve_team_daily_activity_scope(
+ *,
+ team_ids: str | None,
+ exclude_team_ids: str | None,
+ api_key: str | None,
+ user_api_key_dict: UserAPIKeyAuth,
+ prisma_client: PrismaClient,
+ user_api_key_cache: UserApiKeyCache,
+ proxy_logging_obj: ProxyLogging,
+) -> _TeamDailyActivityScope:
+ """Resolve which teams the caller may see and whether results must be
+ narrowed to their own API keys. Shared by the paginated and aggregated
+ /team/daily/activity endpoints so both enforce identical permissions."""
# Convert comma-separated tags string to list if provided
team_ids_list = team_ids.split(",") if team_ids else None
exclude_team_ids_list: list[str] | None = None
@@ -5740,10 +5726,7 @@ async def get_team_daily_activity(
check_db_only=True,
)
if user_info is None:
- raise HTTPException(
- status_code=404,
- detail={"error": f"User= {user_api_key_dict.user_id} not found"},
- )
+ raise _daily_activity_error(status_code=404, message=f"User= {user_api_key_dict.user_id} not found")
if team_ids_list is None:
team_ids_list = user_info.teams
@@ -5751,11 +5734,9 @@ async def get_team_daily_activity(
# check if all team_ids are in user_info.teams
for team_id in team_ids_list:
if team_id not in user_info.teams:
- raise HTTPException(
+ raise _daily_activity_error(
status_code=404,
- detail={
- "error": f"User does not belong to Team= {team_id}. Call `/user/info` to see user's teams"
- },
+ message=f"User does not belong to Team= {team_id}. Call `/user/info` to see user's teams",
)
## Fetch team aliases and check team admin status
@@ -5804,17 +5785,167 @@ async def get_team_daily_activity(
if final_api_key_filter is None and user_api_keys is not None:
final_api_key_filter = user_api_keys
+ return _TeamDailyActivityScope(
+ team_ids=team_ids_list,
+ exclude_team_ids=exclude_team_ids_list,
+ team_alias_metadata=team_alias_metadata,
+ api_key_filter=final_api_key_filter,
+ )
+
+
+ "/team/daily/activity",
+ response_model=SpendAnalyticsPaginatedResponse,
+ tags=["team management"],
+)
+async def get_team_daily_activity(
+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
+ team_ids: str | None = None,
+ start_date: str | None = None,
+ end_date: str | None = None,
+ model: str | None = None,
+ api_key: str | None = None,
+ page: int = 1,
+ page_size: int = 10,
+ exclude_team_ids: str | None = None,
+):
+ """
+ Get daily activity for specific teams or all teams.
+
+ Args:
+ team_ids (Optional[str]): Comma-separated list of team IDs to filter by. If not provided, returns data for all teams.
+ start_date (Optional[str]): Start date for the activity period (YYYY-MM-DD).
+ end_date (Optional[str]): End date for the activity period (YYYY-MM-DD).
+ model (Optional[str]): Filter by model name.
+ api_key (Optional[str]): Filter by API key.
+ page (int): Page number for pagination.
+ page_size (int): Number of items per page.
+ exclude_team_ids (Optional[str]): Comma-separated list of team IDs to exclude.
+ Returns:
+ SpendAnalyticsPaginatedResponse: Paginated response containing daily activity data.
+ """
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
+ )
+
+ if prisma_client is None:
+ raise _daily_activity_error(status_code=500, message=CommonProxyErrors.db_not_connected_error.value)
+
+ scope: Final = await _resolve_team_daily_activity_scope(
+ team_ids=team_ids,
+ exclude_team_ids=exclude_team_ids,
+ api_key=api_key,
+ user_api_key_dict=user_api_key_dict,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
return await get_daily_activity(
prisma_client=prisma_client,
table_name="litellm_dailyteamspend",
entity_id_field="team_id",
- entity_id=team_ids_list,
- entity_metadata_field=team_alias_metadata,
- exclude_entity_ids=exclude_team_ids_list,
+ entity_id=scope.team_ids,
+ entity_metadata_field=scope.team_alias_metadata,
+ exclude_entity_ids=scope.exclude_team_ids,
start_date=start_date,
end_date=end_date,
model=model,
- api_key=final_api_key_filter,
+ api_key=scope.api_key_filter,
page=page,
page_size=page_size,
)
+
+
+_MAX_AGGREGATED_RANGE_DAYS: Final = 400
+
+
+def _aggregated_date_range_error(start_date: str | None, end_date: str | None) -> str | None:
+ """The aggregated endpoint has no pagination to bound its work, so malformed
+ dates and ranges wider than the UI ever requests are rejected before querying."""
+ if start_date is None or end_date is None:
+ return "Please provide start_date and end_date"
+ try:
+ parsed_start: Final = datetime.strptime(start_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
+ parsed_end: Final = datetime.strptime(end_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
+ except ValueError:
+ return "start_date and end_date must be valid YYYY-MM-DD dates"
+ if parsed_end < parsed_start:
+ return "end_date must be on or after start_date"
+ if (parsed_end - parsed_start).days > _MAX_AGGREGATED_RANGE_DAYS:
+ return f"Date range must be at most {_MAX_AGGREGATED_RANGE_DAYS} days"
+ return None
+
+
+ "/team/daily/activity/aggregated",
+ response_model=SpendAnalyticsPaginatedResponse,
+ tags=["team management"],
+)
+async def get_team_daily_activity_aggregated(
+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
+ team_ids: str | None = None,
+ start_date: str | None = None,
+ end_date: str | None = None,
+ model: str | None = None,
+ api_key: str | None = None,
+ exclude_team_ids: str | None = None,
+ timezone: int | None = None,
+):
+ """
+ Aggregated daily activity for teams without pagination, including per-team breakdown.
+
+ One SQL GROUPING SETS pass returns every day in the range regardless of row
+ volume, so callers never reassemble pages. Same response shape as the
+ paginated endpoint with page metadata pinned to a single page.
+
+ Args:
+ team_ids (Optional[str]): Comma-separated list of team IDs to filter by. If not provided, returns data for all teams.
+ start_date (Optional[str]): Start date for the activity period (YYYY-MM-DD).
+ end_date (Optional[str]): End date for the activity period (YYYY-MM-DD).
+ model (Optional[str]): Filter by model name.
+ api_key (Optional[str]): Filter by API key.
+ exclude_team_ids (Optional[str]): Comma-separated list of team IDs to exclude.
+ timezone (Optional[int]): Timezone offset in minutes from UTC, matching JavaScript's Date.getTimezoneOffset() convention.
+ Returns:
+ SpendAnalyticsPaginatedResponse: Response containing all daily activity data for the range.
+ """
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_logging_obj,
+ user_api_key_cache,
+ )
+
+ if prisma_client is None:
+ raise _daily_activity_error(status_code=500, message=CommonProxyErrors.db_not_connected_error.value)
+
+ range_error: Final = _aggregated_date_range_error(start_date, end_date)
+ if range_error is not None:
+ raise _daily_activity_error(status_code=400, message=range_error)
+
+ scope: Final = await _resolve_team_daily_activity_scope(
+ team_ids=team_ids,
+ exclude_team_ids=exclude_team_ids,
+ api_key=api_key,
+ user_api_key_dict=user_api_key_dict,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ return await get_daily_activity_aggregated(
+ prisma_client=prisma_client,
+ table_name="litellm_dailyteamspend",
+ entity_id_field="team_id",
+ entity_id=scope.team_ids,
+ entity_metadata_field=scope.team_alias_metadata,
+ start_date=start_date,
+ end_date=end_date,
+ model=model,
+ api_key=scope.api_key_filter,
+ exclude_entity_ids=scope.exclude_team_ids,
+ timezone_offset_minutes=timezone,
+ include_entity_breakdown=True,
+ )
diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json
index ffbb8dc2332..4a6ff6af902 100644
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@ -36,7 +36,7 @@
"limit": 178
},
"B008": {
- "limit": 505
+ "limit": 503
},
"B009": {
"limit": 59
diff --git a/tests/proxy_behavior/management/test_team_daily_activity.py b/tests/proxy_behavior/management/test_team_daily_activity.py
index 7a1e70b91fc..d84cc4c94af 100644
--- a/tests/proxy_behavior/management/test_team_daily_activity.py
+++ b/tests/proxy_behavior/management/test_team_daily_activity.py
@@ -5,11 +5,12 @@ from .actors import Actor
pytestmark = pytest.mark.asyncio(loop_scope="session")
-# GET /team/daily/activity. A proxy admin (admin view) sees activity for any
-# team. A non-admin is scoped to user_info.teams: a bare query defaults to its
-# own teams (200), and an explicit team_ids filter naming a team it does not
-# belong to is 404 (the VERIA-43 fix). Org admins have no team memberships, so
-# they behave like a non-member for any specific team.
+# GET /team/daily/activity and its /aggregated variant (same shared scope
+# resolver, so the matrix must hold for both). A proxy admin (admin view) sees
+# activity for any team. A non-admin is scoped to user_info.teams: a bare query
+# defaults to its own teams (200), and an explicit team_ids filter naming a
+# team it does not belong to is 404 (the VERIA-43 fix). Org admins have no
+# team memberships, so they behave like a non-member for any specific team.
_MEMBERS = {
"alpha": {
Actor.TEAM_ADMIN,
@@ -40,13 +41,18 @@ _CASES = [
_DATES = "start_date=2024-01-01&end_date=2024-12-31"
+ "endpoint",
+ ("/team/daily/activity", "/team/daily/activity/aggregated"),
+ ids=("paginated", "aggregated"),
+)
@pytest.mark.parametrize(
"actor,team,expected_status",
[(a, t, s) for (_id, a, t, s) in _CASES],
ids=[c[0] for c in _CASES],
)
async def test_team_daily_activity_matrix(
- actor: Actor, team: str, expected_status: int, proxy_client, world
+ actor: Actor, team: str, expected_status: int, endpoint: str, proxy_client, world
):
query = _DATES
if team == "alpha":
@@ -55,7 +61,7 @@ async def test_team_daily_activity_matrix(
query += f"&team_ids={world.team_beta_id}"
resp = await proxy_client.get(
- f"/team/daily/activity?{query}",
+ f"{endpoint}?{query}",
headers={"Authorization": f"Bearer {world.keys[actor].cleartext}"},
)
assert (
diff --git a/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py b/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py
index ab9b4bc3922..412e6f0f83c 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py
@@ -1719,3 +1719,156 @@ class TestFlagIsNotReadOnTheHotPath:
reads = self._count_flag_reads([_spend_record(PTU_SENTINEL_API_KEY, spend=0.0, ptu_flat_cost=240.0)])
assert reads > 0
+
+
+def test_entity_rollup_sql_query_and_api_key_list_filter():
+ """The entity rollup companion query keeps its own two grouping sets keyed
+ by GROUPING(api_key), shares the WHERE builder (list api_key becomes a
+ parameterized IN, an empty list must match nothing), and the main
+ aggregated query stays entity-free."""
+ from litellm.proxy.management_endpoints.common_daily_activity import (
+ _build_entity_rollup_sql_query,
+ )
+
+ sql, params = _build_entity_rollup_sql_query(
+ table_name="litellm_dailyteamspend",
+ entity_id_field="team_id",
+ entity_id=None,
+ start_date="2024-01-01",
+ end_date="2024-01-31",
+ model=None,
+ api_key=["key-1", "key-2"],
+ )
+ assert '"team_id" AS entity_id' in sql
+ assert "GROUPING(api_key) AS api_key_rolled" in sql
+ assert '(date, "team_id"),' in sql
+ assert '(date, "team_id", api_key)' in sql
+ assert "api_key IN ($3, $4)" in sql
+ assert "SUM(ptu_flat_cost)::float" in sql
+ assert params == ["2024-01-01", "2024-01-31", "key-1", "key-2"]
+
+ plain_sql, _ = _build_aggregated_sql_query(
+ table_name="litellm_dailyteamspend",
+ entity_id_field="team_id",
+ entity_id=None,
+ start_date="2024-01-01",
+ end_date="2024-01-31",
+ model=None,
+ api_key=None,
+ )
+ assert "entity_id" not in plain_sql
+ assert "GROUPING(date" in plain_sql
+
+ empty_sql, empty_params = _build_aggregated_sql_query(
+ table_name="litellm_dailyteamspend",
+ entity_id_field="team_id",
+ entity_id=None,
+ start_date="2024-01-01",
+ end_date="2024-01-31",
+ model=None,
+ api_key=[],
+ )
+ assert "FALSE" in empty_sql
+ assert empty_params == ["2024-01-01", "2024-01-31"]
+
+
+async def test_get_daily_activity_aggregated_with_entity_breakdown():
+ """include_entity_breakdown must run the companion entity rollup query and
+ fold breakdown.entities onto the response, without disturbing the main
+ query's rollup dispatch."""
+ mock_prisma = MagicMock()
+ mock_prisma.db = MagicMock()
+
+ base = {
+ "model": None,
+ "model_group": None,
+ "custom_llm_provider": None,
+ "mcp_namespaced_tool_name": None,
+ "endpoint": None,
+ "api_key": None,
+ "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0,
+ "compression_saved_tokens": 0,
+ "compression_savings_spend": 0.0,
+ "prompt_caching_savings_spend": 0.0,
+ "autorouter_savings_spend": 0.0,
+ "failed_requests": 0,
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "api_requests": 0,
+ "successful_requests": 0,
+ }
+ main_rows = [
+ {**base, "date": None, "group_level": 127, "spend": 18.0},
+ {**base, "date": "2024-01-01", "group_level": 63, "spend": 18.0},
+ {**base, "date": "2024-01-01", "model": "gpt-4o", "group_level": 47, "spend": 18.0},
+ {**base, "date": "2024-01-01", "api_key": "key-1", "group_level": 31, "spend": 12.0},
+ ]
+ entity_base = {
+ key: value
+ for key, value in base.items()
+ if key not in ("model", "model_group", "custom_llm_provider", "mcp_namespaced_tool_name", "endpoint")
+ }
+ entity_rows = [
+ {**entity_base, "date": "2024-01-01", "entity_id": "team-a", "api_key_rolled": 1, "spend": 12.0},
+ {**entity_base, "date": "2024-01-01", "entity_id": "team-b", "api_key_rolled": 1, "spend": 6.0},
+ {
+ **entity_base,
+ "date": "2024-01-01",
+ "entity_id": "team-a",
+ "api_key": "key-1",
+ "api_key_rolled": 0,
+ "spend": 12.0,
+ },
+ {
+ **entity_base,
+ "date": "2024-01-01",
+ "entity_id": "team-b",
+ "api_key": "key-2",
+ "api_key_rolled": 0,
+ "spend": 6.0,
+ },
+ ]
+
+ mock_prisma.db.query_raw = AsyncMock(side_effect=[main_rows, entity_rows])
+ mock_prisma.db.litellm_verificationtoken = MagicMock()
+ mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
+
+ result = await get_daily_activity_aggregated(
+ prisma_client=mock_prisma,
+ table_name="litellm_dailyteamspend",
+ entity_id_field="team_id",
+ entity_id=None,
+ entity_metadata_field={"team-a": {"team_alias": "Alpha"}},
+ start_date="2024-01-01",
+ end_date="2024-01-01",
+ model=None,
+ api_key=None,
+ include_entity_breakdown=True,
+ )
+
+ assert mock_prisma.db.query_raw.call_count == 2
+ main_sql = mock_prisma.db.query_raw.call_args_list[0][0][0]
+ entity_sql = mock_prisma.db.query_raw.call_args_list[1][0][0]
+ assert "entity_id" not in main_sql
+ assert '"team_id" AS entity_id' in entity_sql
+ assert '(date, "team_id"),' in entity_sql
+
+ assert result.metadata.total_spend == 18.0
+ assert len(result.results) == 1
+ daily = result.results[0]
+ assert daily.metrics.spend == 18.0
+
+ entities = daily.breakdown.entities
+ assert set(entities) == {"team-a", "team-b"}
+ assert entities["team-a"].metrics.spend == 12.0
+ assert entities["team-a"].metadata == {"team_alias": "Alpha"}
+ assert entities["team-a"].api_key_breakdown["key-1"].metrics.spend == 12.0
+ assert entities["team-b"].metrics.spend == 6.0
+ assert entities["team-b"].metadata == {}
+ assert entities["team-b"].api_key_breakdown["key-2"].metrics.spend == 6.0
+
+ # Rollups with the entity bit set must still land in their usual buckets
+ assert daily.breakdown.models["gpt-4o"].metrics.spend == 18.0
+ assert daily.breakdown.api_keys["key-1"].metrics.spend == 12.0
diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
index c6960ecda5a..db39fcd3799 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@@ -11649,6 +11649,127 @@ async def test_new_team_output_token_estimate_rejected_for_non_admin():
assert "on a team" in str(exc.value.message)
+async def test_get_team_daily_activity_aggregated_scopes_and_flags(mock_db_client):
+ """The aggregated endpoint must apply the same non-admin key scoping as the
+ paginated one and request the per-team entity breakdown with the caller's
+ timezone, so the Team Usage UI gets every day in one response."""
+ from litellm.proxy.management_endpoints.team_endpoints import (
+ get_team_daily_activity_aggregated,
+ )
+
+ user_id = "test_user_123"
+ team_id = "test_team_456"
+ user_api_key_dict = UserAPIKeyAuth(
+ user_id=user_id, user_role=LitellmUserRoles.INTERNAL_USER
+ )
+
+ mock_user_info = LiteLLM_UserTable(
+ user_id=user_id,
+ teams=[team_id],
+ max_budget=1000.0,
+ spend=0.0,
+ user_email="[email protected]",
+ user_role="internal_user",
+ )
+
+ mock_team_member = Member(user_id=user_id, role="user")
+ mock_team = MagicMock(spec=LiteLLM_TeamTable)
+ mock_team.team_id = team_id
+ mock_team.team_alias = "Test Team"
+ mock_team.members_with_roles = [mock_team_member]
+ mock_team.model_dump.return_value = {
+ "team_id": team_id,
+ "team_alias": "Test Team",
+ "members_with_roles": [{"user_id": user_id, "role": "user"}],
+ }
+
+ user_api_key_1 = MagicMock()
+ user_api_key_1.token = "user_key_1"
+
+ mock_db_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[mock_team])
+ mock_db_client.db.litellm_verificationtoken.find_many = AsyncMock(
+ return_value=[user_api_key_1]
+ )
+
+ with patch(
+ "litellm.proxy.management_endpoints.team_endpoints.get_user_object",
+ new_callable=AsyncMock,
+ ) as mock_get_user_object:
+ mock_get_user_object.return_value = mock_user_info
+
+ with patch(
+ "litellm.proxy.management_endpoints.team_endpoints.get_daily_activity_aggregated",
+ new_callable=AsyncMock,
+ ) as mock_aggregated:
+ mock_aggregated.return_value = MagicMock()
+
+ await get_team_daily_activity_aggregated(
+ team_ids=team_id,
+ start_date="2024-01-01",
+ end_date="2024-01-31",
+ model=None,
+ api_key=None,
+ exclude_team_ids=None,
+ timezone=480,
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ mock_aggregated.assert_called_once()
+ call_kwargs = mock_aggregated.call_args[1]
+ assert call_kwargs["api_key"] == ["user_key_1"]
+ assert call_kwargs["entity_id"] == [team_id]
+ assert call_kwargs["entity_metadata_field"] == {
+ team_id: {"team_alias": "Test Team"}
+ }
+ assert call_kwargs["include_entity_breakdown"] is True
+ assert call_kwargs["timezone_offset_minutes"] == 480
+ assert call_kwargs["table_name"] == "litellm_dailyteamspend"
+
+
+ "start_date,end_date,expected_error",
+ [
+ ("2020-01-01", "2026-12-31", "at most 400 days"),
+ ("0000-01-01", "9999-12-31", "valid YYYY-MM-DD"),
+ ("2024-06-01", "2024-01-01", "on or after"),
+ ("not-a-date", "2024-01-31", "valid YYYY-MM-DD"),
+ (None, "2024-01-31", "start_date and end_date"),
+ ],
+)
+async def test_get_team_daily_activity_aggregated_rejects_bad_ranges(
+ mock_db_client, start_date, end_date, expected_error
+):
+ """The aggregated endpoint has no pagination bounding its work, so an
+ unbounded or malformed range must 400 before any query runs."""
+ from litellm.proxy.management_endpoints.team_endpoints import (
+ get_team_daily_activity_aggregated,
+ )
+
+ with patch(
+ "litellm.proxy.management_endpoints.team_endpoints.get_daily_activity_aggregated",
+ new_callable=AsyncMock,
+ ) as mock_aggregated:
+ with pytest.raises(HTTPException) as exc_info:
+ await get_team_daily_activity_aggregated(
+ team_ids=None,
+ start_date=start_date,
+ end_date=end_date,
+ model=None,
+ api_key=None,
+ exclude_team_ids=None,
+ timezone=None,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN
+ ),
+ )
+
+ assert exc_info.value.status_code == 400
+ assert expected_error in str(exc_info.value.detail)
+ mock_aggregated.assert_not_called()
+
+
def _wire_new_team_prisma(mock_db_client):
mock_db_client.jsonify_team_object = lambda db_data: db_data
mock_db_client.get_data = AsyncMock(return_value=None)
diff --git a/type-discipline-budget.json b/type-discipline-budget.json
index 3d2923c39ac..b5c07de8cd3 100644
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@ -3,7 +3,7 @@
"limit": 22900
},
"LIT002": {
- "limit": 26893
+ "limit": 26889
},
"LIT003": {
"limit": 269
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx
index 046f187e4bc..7055e36b194 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.test.tsx
@@ -20,6 +20,7 @@ beforeAll(() => {
vi.mock("@/components/networking", () => ({
tagDailyActivityCall: vi.fn(),
teamDailyActivityCall: vi.fn(),
+ teamDailyActivityAggregatedCall: vi.fn(),
organizationDailyActivityCall: vi.fn(),
customerDailyActivityCall: vi.fn(),
agentDailyActivityCall: vi.fn(),
@@ -93,6 +94,7 @@ vi.mock("@/app/(dashboard)/hooks/useTeams", () => ({
describe("EntityUsage", () => {
const mockTagDailyActivityCall = vi.mocked(networking.tagDailyActivityCall);
const mockTeamDailyActivityCall = vi.mocked(networking.teamDailyActivityCall);
+ const mockTeamDailyActivityAggregatedCall = vi.mocked(networking.teamDailyActivityAggregatedCall);
const mockOrganizationDailyActivityCall = vi.mocked(networking.organizationDailyActivityCall);
const mockCustomerDailyActivityCall = vi.mocked(networking.customerDailyActivityCall);
const mockAgentDailyActivityCall = vi.mocked(networking.agentDailyActivityCall);
@@ -394,12 +396,14 @@ describe("EntityUsage", () => {
beforeEach(() => {
mockTagDailyActivityCall.mockClear();
mockTeamDailyActivityCall.mockClear();
+ mockTeamDailyActivityAggregatedCall.mockClear();
mockOrganizationDailyActivityCall.mockClear();
mockCustomerDailyActivityCall.mockClear();
mockAgentDailyActivityCall.mockClear();
mockUserDailyActivityCall.mockClear();
mockTagDailyActivityCall.mockResolvedValue(mockSpendData);
mockTeamDailyActivityCall.mockResolvedValue(mockSpendData);
+ mockTeamDailyActivityAggregatedCall.mockResolvedValue(mockSpendData);
mockOrganizationDailyActivityCall.mockResolvedValue(mockSpendData);
mockCustomerDailyActivityCall.mockResolvedValue(mockSpendData);
mockAgentDailyActivityCall.mockResolvedValue(mockAgentSpendData);
@@ -435,7 +439,7 @@ describe("EntityUsage", () => {
render(<EntityUsage {...defaultProps} entityType="team" />);
await waitFor(() => {
- expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ expect(mockTeamDailyActivityAggregatedCall).toHaveBeenCalled();
});
// Check that it shows team-specific label
@@ -586,7 +590,7 @@ describe("EntityUsage", () => {
render(<EntityUsage {...defaultProps} entityType="team" />);
await waitFor(() => {
- expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ expect(mockTeamDailyActivityAggregatedCall).toHaveBeenCalled();
});
act(() => {
@@ -739,7 +743,7 @@ describe("EntityUsage", () => {
render(<EntityUsage {...defaultProps} entityType="team" />);
await waitFor(() => {
- expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ expect(mockTeamDailyActivityAggregatedCall).toHaveBeenCalled();
});
expect(screen.getByText("Agent Activity")).toBeInTheDocument();
@@ -759,7 +763,7 @@ describe("EntityUsage", () => {
render(<EntityUsage {...defaultProps} entityType="team" />);
await waitFor(() => {
- expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ expect(mockTeamDailyActivityAggregatedCall).toHaveBeenCalled();
});
expect(screen.getByText("Top Agents Driving Spend")).toBeInTheDocument();
@@ -803,7 +807,7 @@ describe("EntityUsage", () => {
render(<EntityUsage {...defaultProps} entityType="team" />);
await waitFor(() => {
- expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ expect(mockTeamDailyActivityAggregatedCall).toHaveBeenCalled();
});
const agentActivityTab = screen.getByText("Agent Activity");
@@ -939,7 +943,7 @@ describe("EntityUsage", () => {
render(<EntityUsage {...defaultProps} entityType="team" userRole="Internal User" />);
await waitFor(() => {
- expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ expect(mockTeamDailyActivityAggregatedCall).toHaveBeenCalled();
});
expect(screen.getByText("Team Spend Overview")).toBeInTheDocument();
@@ -996,7 +1000,7 @@ describe("EntityUsage", () => {
cache_read_input_tokens: 0,
cache_creation_input_tokens: 0,
};
- mockTeamDailyActivityCall.mockResolvedValue({
+ mockTeamDailyActivityAggregatedCall.mockResolvedValue({
...mockSpendData,
results: [
{
@@ -1019,6 +1023,33 @@ describe("EntityUsage", () => {
expect(screen.getByText(/^top-models:Code Review Agent=/)).toBeInTheDocument();
});
+ it("uses the aggregated team endpoint and never drains paginated pages for teams", async () => {
+ render(<EntityUsage {...defaultProps} entityType="team" />);
+
+ await waitFor(() => {
+ expect(mockTeamDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+ expect(mockTeamDailyActivityCall).not.toHaveBeenCalled();
+
+ await waitFor(() => {
+ expect(screen.getAllByText("$100.50").length).toBeGreaterThan(0);
+ });
+ });
+
+ it("falls back to the paginated team endpoint when the aggregated call fails", async () => {
+ mockTeamDailyActivityAggregatedCall.mockRejectedValue(new Error("aggregated unavailable"));
+
+ render(<EntityUsage {...defaultProps} entityType="team" />);
+
+ await waitFor(() => {
+ expect(mockTeamDailyActivityCall).toHaveBeenCalled();
+ });
+
+ await waitFor(() => {
+ expect(screen.getAllByText("$100.50").length).toBeGreaterThan(0);
+ });
+ });
+
describe("user filter (LIT-5654)", () => {
const userDropdown = (): HTMLElement => screen.getByTestId("user-dropdown");
const userCombobox = (): HTMLElement => within(userDropdown()).getByRole("combobox");
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx
index 66265fb41d8..7343dcaaec5 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx
@@ -32,6 +32,7 @@ import {
customerDailyActivityCall,
organizationDailyActivityCall,
tagDailyActivityCall,
+ teamDailyActivityAggregatedCall,
teamDailyActivityCall,
userDailyActivityCall,
} from "@/components/networking";
@@ -96,6 +97,12 @@ const ENTITY_FETCH_FNS: Record<EntityType, (...args: any[]) => Promise<any>> = {
user: userDailyActivityCall,
};
+// Single-shot endpoints returning the whole range in one response; entity types
+// without one fall back to page-draining the paginated endpoint.
+const ENTITY_AGGREGATED_FETCH_FNS: Partial<Record<EntityType, (...args: any[]) => Promise<any>>> = {
+ team: teamDailyActivityAggregatedCall,
+};
+
const ENTITY_CAPABILITIES: Partial<Record<EntityType, Capability>> = {
organization: "viewOrganizationUsage",
agent: "viewAgentUsage",
@@ -126,6 +133,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({
}, [entityType, selectedTags]);
const fetchFn = ENTITY_FETCH_FNS[entityType];
+ const aggregatedFetchFn = ENTITY_AGGREGATED_FETCH_FNS[entityType];
const entityCapability = ENTITY_CAPABILITIES[entityType];
const canViewEntity = entityCapability === undefined || hasCapability(userRole, entityCapability);
const showAgentBreakdown = entityType === "team" && hasCapability(userRole, "viewAgentUsage");
@@ -142,6 +150,7 @@ const EntityUsage: React.FC<EntityUsageProps> = ({
fetchFn,
args: [accessToken, startTime, endTime, entityFilterArg],
enabled,
+ aggregatedFetchFn,
});
const spendData = spendDataRaw as unknown as EntitySpendData;
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/hooks/usePaginatedDailyActivity.ts b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/hooks/usePaginatedDailyActivity.ts
index a8bfee5be2f..453c9fae8e4 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/hooks/usePaginatedDailyActivity.ts
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/hooks/usePaginatedDailyActivity.ts
@@ -40,6 +40,13 @@ interface UsePaginatedDailyActivityParams {
args: any[];
/** Whether the hook should fetch. Set to false to disable. */
enabled: boolean;
+ /**
+ * Optional single-shot endpoint returning the whole range at once (e.g.
+ * teamDailyActivityAggregatedCall). Called with `args` as-is (no page).
+ * On success pagination is skipped entirely; on failure the hook falls
+ * back to the paginated flow.
+ */
+ aggregatedFetchFn?: (...args: any[]) => Promise<DailyActivityResponse>;
}
interface UsePaginatedDailyActivityReturn {
@@ -96,6 +103,7 @@ export function usePaginatedDailyActivity({
fetchFn,
args,
enabled,
+ aggregatedFetchFn,
}: UsePaginatedDailyActivityParams): UsePaginatedDailyActivityReturn {
const [data, setData] = useState<DailyActivityResponse>(EMPTY_DATA);
const [loading, setLoading] = useState(false);
@@ -159,6 +167,20 @@ export function usePaginatedDailyActivity({
setIsFetchingMore(false);
setProgress({ currentPage: 1, totalPages: 1 });
+ if (aggregatedFetchFn) {
+ try {
+ const aggregated = await aggregatedFetchFn(...currentArgs);
+ if (isStale()) return;
+ setData(aggregated);
+ setProgress({ currentPage: 1, totalPages: 1 });
+ setLoading(false);
+ return;
+ } catch (error) {
+ if (isStale()) return;
+ console.error("Aggregated daily activity failed, falling back to pagination:", error);
+ }
+ }
+
try {
// Inject page=1 as the 4th argument.
const argsWithPage = [...currentArgs.slice(0, 3), 1, ...currentArgs.slice(3)];
@@ -239,7 +261,7 @@ export function usePaginatedDailyActivity({
};
// argsKey is a stable JSON string so the effect only re-fires when arg values change.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [enabled, fetchFn, argsKey]);
+ }, [enabled, fetchFn, aggregatedFetchFn, argsKey]);
return { data, loading, isFetchingMore, progress, cancelled, cancel };
}
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index a4ea85519eb..cc074d84948 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -1469,6 +1469,32 @@ export const teamDailyActivityCall = async (
});
};
+export const teamDailyActivityAggregatedCall = async (
+ accessToken: string,
+ startTime: Date,
+ endTime: Date,
+ teamIds: string[] | null = null,
+) => {
+ /**
+ * Get aggregated daily team activity with per-team breakdown (no pagination)
+ */
+ try {
+ return await apiClient.get(`/team/daily/activity/aggregated`, {
+ accessToken,
+ query: {
+ start_date: formatDate(startTime),
+ end_date: formatDate(endTime),
+ timezone: new Date().getTimezoneOffset().toString(),
+ team_ids: teamIds && teamIds.length > 0 ? teamIds.join(",") : undefined,
+ exclude_team_ids: "litellm-dashboard",
+ },
+ });
+ } catch (error) {
+ console.error("Failed to fetch aggregated team daily activity:", error);
+ throw error;
+ }
+};
+
export const organizationDailyActivityCall = async (
accessToken: string,
startTime: Date,
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index ca3974f24de..a3a461edca0 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -14058,6 +14058,41 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/team/daily/activity/aggregated": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Team Daily Activity Aggregated
+ * @description Aggregated daily activity for teams without pagination, including per-team breakdown.
+ *
+ * One SQL GROUPING SETS pass returns every day in the range regardless of row
+ * volume, so callers never reassemble pages. Same response shape as the
+ * paginated endpoint with page metadata pinned to a single page.
+ *
+ * Args:
+ * team_ids (Optional[str]): Comma-separated list of team IDs to filter by. If not provided, returns data for all teams.
+ * start_date (Optional[str]): Start date for the activity period (YYYY-MM-DD).
+ * end_date (Optional[str]): End date for the activity period (YYYY-MM-DD).
+ * model (Optional[str]): Filter by model name.
+ * api_key (Optional[str]): Filter by API key.
+ * exclude_team_ids (Optional[str]): Comma-separated list of team IDs to exclude.
+ * timezone (Optional[int]): Timezone offset in minutes from UTC, matching JavaScript's Date.getTimezoneOffset() convention.
+ * Returns:
+ * SpendAnalyticsPaginatedResponse: Response containing all daily activity data for the range.
+ */
+ get: operations["get_team_daily_activity_aggregated_team_daily_activity_aggregated_get"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/team/delete": {
parameters: {
query?: never;
@@ -26142,7 +26177,7 @@ export interface components {
* @description Enum for key management routes
* @enum {string}
*/
- KeyManagementRoutes: "/key/generate" | "/key/update" | "/key/delete" | "/key/regenerate" | "/key/service-account/generate" | "/key/{key_id}/regenerate" | "/key/block" | "/key/unblock" | "/key/bulk_update" | "/team/key/bulk_update" | "/key/{key_id}/reset_spend" | "/key/access_group_assignment" | "/key/info" | "/key/health" | "/key/list" | "/key/aliases" | "/team/daily/activity" | "/spend/logs" | "/spend/logs/v2";
+ KeyManagementRoutes: "/key/generate" | "/key/update" | "/key/delete" | "/key/regenerate" | "/key/service-account/generate" | "/key/{key_id}/regenerate" | "/key/block" | "/key/unblock" | "/key/bulk_update" | "/team/key/bulk_update" | "/key/{key_id}/reset_spend" | "/key/access_group_assignment" | "/key/info" | "/key/health" | "/key/list" | "/key/aliases" | "/team/daily/activity" | "/team/daily/activity/aggregated" | "/spend/logs" | "/spend/logs/v2";
/**
* KeyManagementSystem
* @enum {string}
@@ -53779,6 +53814,43 @@ export interface operations {
};
};
};
+ get_team_daily_activity_aggregated_team_daily_activity_aggregated_get: {
+ parameters: {
+ query?: {
+ team_ids?: string | null;
+ start_date?: string | null;
+ end_date?: string | null;
+ model?: string | null;
+ api_key?: string | null;
+ exclude_team_ids?: string | null;
+ timezone?: number | null;
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SpendAnalyticsPaginatedResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
delete_team_team_delete_post: {
parameters: {
query?: never;