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] LiteLLM x Cloudzero integration - Allow exporting spend to cloudzero (#12908)

Ishaan Jaff99ad24c6839f
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index 54cb491f826..1fd9c3e30bc 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -361,6 +361,9 @@ router_settings:
| CACHED_STREAMING_CHUNK_DELAY | Delay in seconds for cached streaming chunks. Default is 0.02
| CIRCLE_OIDC_TOKEN | OpenID Connect token for CircleCI
| CIRCLE_OIDC_TOKEN_V2 | Version 2 of the OpenID Connect token for CircleCI
+| CLOUDZERO_API_KEY | CloudZero API key for authentication
+| CLOUDZERO_CONNECTION_ID | CloudZero connection ID for data submission
+| CLOUDZERO_TIMEZONE | Timezone for date handling (default: UTC)
| CONFIG_FILE_PATH | File path for configuration file
| CONFIDENT_API_KEY | API key for DeepEval integration
| CUSTOM_TIKTOKEN_CACHE_DIR | Custom directory for Tiktoken cache
diff --git a/litellm/integrations/cloudzero/cloudzero.py b/litellm/integrations/cloudzero/cloudzero.py
new file mode 100644
index 00000000000..ab1de17b9f2
--- /dev/null
+++ b/litellm/integrations/cloudzero/cloudzero.py
@@ -0,0 +1,190 @@
+import os
+from typing import Optional
+
+from litellm._logging import verbose_logger
+from litellm.integrations.custom_logger import CustomLogger
+
+from .cz_stream_api import CloudZeroStreamer
+from .database import LiteLLMDatabase
+from .transform import CBFTransformer
+
+
+class CloudZeroLogger(CustomLogger):
+ """
+ CloudZero Logger for exporting LiteLLM usage data to CloudZero AnyCost API.
+
+ Environment Variables:
+ CLOUDZERO_API_KEY: CloudZero API key for authentication
+ CLOUDZERO_CONNECTION_ID: CloudZero connection ID for data submission
+ CLOUDZERO_TIMEZONE: Timezone for date handling (default: UTC)
+ """
+
+ def __init__(self, api_key: Optional[str] = None, connection_id: Optional[str] = None, timezone: Optional[str] = None, **kwargs):
+ """Initialize CloudZero logger with configuration from parameters or environment variables."""
+ super().__init__(**kwargs)
+
+ # Get configuration from parameters first, fall back to environment variables
+ self.api_key = api_key or os.getenv("CLOUDZERO_API_KEY")
+ self.connection_id = connection_id or os.getenv("CLOUDZERO_CONNECTION_ID")
+ self.timezone = timezone or os.getenv("CLOUDZERO_TIMEZONE", "UTC")
+
+ async def export_usage_data(self, limit: Optional[int] = None, operation: str = "replace_hourly"):
+ """
+ Exports the usage data to CloudZero.
+
+ - Reads data from the DB
+ - Transforms the data to the CloudZero format
+ - Sends the data to CloudZero
+
+ Args:
+ limit: Optional limit on number of records to export
+ operation: CloudZero operation type ("replace_hourly" or "sum")
+ """
+ try:
+ verbose_logger.debug("CloudZero Logger: Starting usage data export")
+
+ # Validate required configuration
+ if not self.api_key or not self.connection_id:
+ raise ValueError(
+ "CloudZero configuration missing. Please set CLOUDZERO_API_KEY and CLOUDZERO_CONNECTION_ID environment variables."
+ )
+
+ # Initialize database connection and load data
+ database = LiteLLMDatabase()
+ verbose_logger.debug("CloudZero Logger: Loading usage data from database")
+ data = await database.get_usage_data(limit=limit)
+
+ if data.is_empty():
+ verbose_logger.info("CloudZero Logger: No usage data found to export")
+ return
+
+ verbose_logger.debug(f"CloudZero Logger: Processing {len(data)} records")
+
+ # Transform data to CloudZero CBF format
+ transformer = CBFTransformer()
+ cbf_data = transformer.transform(data)
+
+ if cbf_data.is_empty():
+ verbose_logger.warning("CloudZero Logger: No valid data after transformation")
+ return
+
+ # Send data to CloudZero
+ streamer = CloudZeroStreamer(
+ api_key=self.api_key,
+ connection_id=self.connection_id,
+ user_timezone=self.timezone
+ )
+
+ verbose_logger.debug(f"CloudZero Logger: Transmitting {len(cbf_data)} records to CloudZero")
+ streamer.send_batched(cbf_data, operation=operation)
+
+ verbose_logger.info(f"CloudZero Logger: Successfully exported {len(cbf_data)} records to CloudZero")
+
+ except Exception as e:
+ verbose_logger.error(f"CloudZero Logger: Error exporting usage data: {str(e)}")
+ raise
+
+ async def dry_run_export_usage_data(self, limit: Optional[int] = 10000):
+ """
+ Only prints the data that would be exported to CloudZero.
+
+ Args:
+ limit: Limit number of records to display (default: 10000)
+ """
+ try:
+ verbose_logger.debug("CloudZero Logger: Starting dry run export")
+
+ # Initialize database connection and load data
+ database = LiteLLMDatabase()
+ verbose_logger.debug("CloudZero Logger: Loading usage data for dry run")
+ data = await database.get_usage_data(limit=limit)
+
+ if data.is_empty():
+ verbose_logger.warning("CloudZero Dry Run: No usage data found")
+ return
+
+ verbose_logger.debug(f"CloudZero Dry Run: Processing {len(data)} records...")
+
+ # Transform data to CloudZero CBF format
+ transformer = CBFTransformer()
+ cbf_data = transformer.transform(data)
+
+ if cbf_data.is_empty():
+ verbose_logger.warning("CloudZero Dry Run: No valid data after transformation")
+ return
+
+ # Display the transformed data on screen
+ self._display_cbf_data_on_screen(cbf_data)
+
+ verbose_logger.info(f"CloudZero Logger: Dry run completed for {len(cbf_data)} records")
+
+ except Exception as e:
+ verbose_logger.error(f"CloudZero Logger: Error in dry run export: {str(e)}")
+ verbose_logger.error(f"CloudZero Dry Run Error: {str(e)}")
+ raise
+
+ def _display_cbf_data_on_screen(self, cbf_data):
+ """Display CBF transformed data in a formatted table on screen."""
+ from rich.box import SIMPLE
+ from rich.console import Console
+ from rich.table import Table
+
+ console = Console()
+
+ if cbf_data.is_empty():
+ console.print("[yellow]No CBF data to display[/yellow]")
+ return
+
+ console.print(f"\n[bold green]💰 CloudZero CBF Transformed Data ({len(cbf_data)} records)[/bold green]")
+
+ # Convert to dicts for easier processing
+ records = cbf_data.to_dicts()
+
+ # Create main CBF table
+ cbf_table = Table(show_header=True, header_style="bold cyan", box=SIMPLE, padding=(0, 1))
+ cbf_table.add_column("time/usage_start", style="blue", no_wrap=False)
+ cbf_table.add_column("cost/cost", style="green", justify="right", no_wrap=False)
+ cbf_table.add_column("usage/amount", style="yellow", justify="right", no_wrap=False)
+ cbf_table.add_column("resource/id", style="magenta", no_wrap=False)
+ cbf_table.add_column("resource/service", style="cyan", no_wrap=False)
+ cbf_table.add_column("resource/account", style="white", no_wrap=False)
+ cbf_table.add_column("resource/region", style="dim", no_wrap=False)
+
+ for record in records:
+ # Use proper CBF field names
+ time_usage_start = str(record.get('time/usage_start', 'N/A'))
+ cost_cost = str(record.get('cost/cost', 0))
+ usage_amount = str(record.get('usage/amount', 0))
+ resource_id = str(record.get('resource/id', 'N/A'))
+ resource_service = str(record.get('resource/service', 'N/A'))
+ resource_account = str(record.get('resource/account', 'N/A'))
+ resource_region = str(record.get('resource/region', 'N/A'))
+
+ cbf_table.add_row(
+ time_usage_start,
+ cost_cost,
+ usage_amount,
+ resource_id,
+ resource_service,
+ resource_account,
+ resource_region
+ )
+
+ console.print(cbf_table)
+
+ # Show summary statistics
+ total_cost = sum(record.get('cost/cost', 0) for record in records)
+ unique_accounts = len(set(record.get('resource/account', '') for record in records if record.get('resource/account')))
+ unique_services = len(set(record.get('resource/service', '') for record in records if record.get('resource/service')))
+
+ # Count total tokens from usage metrics
+ total_tokens = sum(record.get('usage/amount', 0) for record in records)
+
+ console.print("\n[bold blue]📊 CBF Summary[/bold blue]")
+ console.print(f" Records: {len(records):,}")
+ console.print(f" Total Cost: ${total_cost:.2f}")
+ console.print(f" Total Tokens: {total_tokens:,}")
+ console.print(f" Unique Accounts: {unique_accounts}")
+ console.print(f" Unique Services: {unique_services}")
+
+ console.print("\n[dim]💡 This is the CloudZero CBF format ready for AnyCost ingestion[/dim]")
\ No newline at end of file
diff --git a/litellm/integrations/cloudzero/cz_resource_names.py b/litellm/integrations/cloudzero/cz_resource_names.py
new file mode 100644
index 00000000000..44147f9c210
--- /dev/null
+++ b/litellm/integrations/cloudzero/cz_resource_names.py
@@ -0,0 +1,153 @@
+# Copyright 2025 CloudZero
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# CHANGELOG: 2025-01-19 - Initial CZRN module for CloudZero Resource Names (erik.peterson)
+
+"""CloudZero Resource Names (CZRN) generation and validation for LiteLLM resources."""
+
+import re
+from typing import Any, cast
+
+import litellm
+
+
+class CZRNGenerator:
+ """Generate CloudZero Resource Names (CZRNs) for LiteLLM resources."""
+
+ CZRN_REGEX = re.compile(r'^czrn:([a-z0-9-]+):([a-zA-Z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):(.+)$')
+
+ def __init__(self):
+ """Initialize CZRN generator."""
+ pass
+
+ def create_from_litellm_data(self, row: dict[str, Any]) -> str:
+ """Create a CZRN from LiteLLM daily spend data.
+
+ CZRN format: czrn:<service-type>:<provider>:<region>:<owner-account-id>:<resource-type>:<cloud-local-id>
+
+ For LiteLLM resources, we map:
+ - service-type: 'litellm' (the service managing the LLM calls)
+ - provider: The custom_llm_provider (e.g., 'openai', 'anthropic', 'azure')
+ - region: 'cross-region' (LiteLLM operates across regions)
+ - owner-account-id: The team_id or user_id (entity_id)
+ - resource-type: 'llm-usage' (represents LLM usage/inference)
+ - cloud-local-id: model
+ """
+ service_type = 'litellm'
+ provider = self._normalize_provider(row.get('custom_llm_provider', 'unknown'))
+ region = 'cross-region'
+
+ # Use the actual entity_id (team_id or user_id) as the owner account
+ entity_id = row.get('entity_id', 'unknown')
+ owner_account_id = self._normalize_component(entity_id)
+
+ resource_type = 'llm-usage'
+
+ # Create a unique identifier with just the model (entity info already in owner_account_id)
+ model = row.get('model', 'unknown')
+
+ cloud_local_id = model
+
+ return self.create_from_components(
+ service_type=service_type,
+ provider=provider,
+ region=region,
+ owner_account_id=owner_account_id,
+ resource_type=resource_type,
+ cloud_local_id=cloud_local_id
+ )
+
+ def create_from_components(
+ self,
+ service_type: str,
+ provider: str,
+ region: str,
+ owner_account_id: str,
+ resource_type: str,
+ cloud_local_id: str
+ ) -> str:
+ """Create a CZRN from individual components."""
+ # Normalize components to ensure they meet CZRN requirements
+ service_type = self._normalize_component(service_type, allow_uppercase=True)
+ provider = self._normalize_component(provider)
+ region = self._normalize_component(region)
+ owner_account_id = self._normalize_component(owner_account_id)
+ resource_type = self._normalize_component(resource_type)
+ # cloud_local_id can contain pipes and other characters, so don't normalize it
+
+ czrn = f"czrn:{service_type}:{provider}:{region}:{owner_account_id}:{resource_type}:{cloud_local_id}"
+
+ if not self.is_valid(czrn):
+ raise ValueError(f"Generated CZRN is invalid: {czrn}")
+
+ return czrn
+
+ def is_valid(self, czrn: str) -> bool:
+ """Validate a CZRN string against the standard format."""
+ return bool(self.CZRN_REGEX.match(czrn))
+
+ def extract_components(self, czrn: str) -> tuple[str, str, str, str, str, str]:
+ """Extract all components from a CZRN.
+
+ Returns: (service_type, provider, region, owner_account_id, resource_type, cloud_local_id)
+ """
+ match = self.CZRN_REGEX.match(czrn)
+ if not match:
+ raise ValueError(f"Invalid CZRN format: {czrn}")
+
+ return cast(tuple[str, str, str, str, str, str], match.groups())
+
+ def _normalize_provider(self, provider: str) -> str:
+ """Normalize provider names to standard CZRN format."""
+ # Map common provider names to CZRN standards
+ provider_map = {
+ litellm.LlmProviders.AZURE.value: 'azure',
+ litellm.LlmProviders.AZURE_AI.value: 'azure',
+ litellm.LlmProviders.ANTHROPIC.value: 'anthropic',
+ litellm.LlmProviders.BEDROCK.value: 'aws',
+ litellm.LlmProviders.VERTEX_AI.value: 'gcp',
+ litellm.LlmProviders.GEMINI.value: 'google',
+ litellm.LlmProviders.COHERE.value: 'cohere',
+ litellm.LlmProviders.HUGGINGFACE.value: 'huggingface',
+ litellm.LlmProviders.REPLICATE.value: 'replicate',
+ litellm.LlmProviders.TOGETHER_AI.value: 'together-ai',
+ }
+
+ normalized = provider.lower().replace('_', '-')
+
+ # use litellm custom llm provider if not in provider_map
+ if normalized not in provider_map:
+ return normalized
+ return provider_map.get(normalized, normalized)
+
+ def _normalize_component(self, component: str, allow_uppercase: bool = False) -> str:
+ """Normalize a CZRN component to meet format requirements."""
+ if not component:
+ return 'unknown'
+
+ # Convert to lowercase unless uppercase is allowed
+ if not allow_uppercase:
+ component = component.lower()
+
+ # Replace invalid characters with hyphens
+ component = re.sub(r'[^a-zA-Z0-9-]', '-', component)
+
+ # Remove consecutive hyphens
+ component = re.sub(r'-+', '-', component)
+
+ # Remove leading/trailing hyphens
+ component = component.strip('-')
+
+ return component or 'unknown'
+
diff --git a/litellm/integrations/cloudzero/cz_stream_api.py b/litellm/integrations/cloudzero/cz_stream_api.py
new file mode 100644
index 00000000000..83b6e318ba7
--- /dev/null
+++ b/litellm/integrations/cloudzero/cz_stream_api.py
@@ -0,0 +1,227 @@
+# Copyright 2025 CloudZero
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# CHANGELOG: 2025-01-19 - Added pathlib for filesystem operations (erik.peterson)
+# CHANGELOG: 2025-01-19 - Migrated from pandas to polars and requests to httpx (erik.peterson)
+# CHANGELOG: 2025-01-19 - Initial output module for CSV and CloudZero API (erik.peterson)
+
+"""Output modules for writing CBF data to various destinations."""
+
+import zoneinfo
+from datetime import datetime, timezone
+from typing import Any, Optional, Union
+
+import httpx
+import polars as pl
+from rich.console import Console
+
+
+class CloudZeroStreamer:
+ """Stream CBF data to CloudZero AnyCost API with proper batching and timezone handling."""
+
+ def __init__(self, api_key: str, connection_id: str, user_timezone: Optional[str] = None):
+ """Initialize CloudZero streamer with credentials."""
+ self.api_key = api_key
+ self.connection_id = connection_id
+ self.base_url = "https://api.cloudzero.com"
+ self.console = Console()
+
+ # Set timezone - default to UTC
+ self.user_timezone: Union[zoneinfo.ZoneInfo, timezone]
+ if user_timezone:
+ try:
+ self.user_timezone = zoneinfo.ZoneInfo(user_timezone)
+ except zoneinfo.ZoneInfoNotFoundError:
+ self.console.print(f"[yellow]Warning: Unknown timezone '{user_timezone}', using UTC[/yellow]")
+ self.user_timezone = timezone.utc
+ else:
+ self.user_timezone = timezone.utc
+
+ def send_batched(self, data: pl.DataFrame, operation: str = "replace_hourly") -> None:
+ """Send CBF data in daily batches to CloudZero AnyCost API."""
+ if data.is_empty():
+ self.console.print("[yellow]No data to send to CloudZero[/yellow]")
+ return
+
+ # Group data by date and send each day as a batch
+ daily_batches = self._group_by_date(data)
+
+ if not daily_batches:
+ self.console.print("[yellow]No valid daily batches to send[/yellow]")
+ return
+
+ self.console.print(f"[blue]Sending {len(daily_batches)} daily batch(es) with operation '{operation}'[/blue]")
+
+ for batch_date, batch_data in daily_batches.items():
+ self._send_daily_batch(batch_date, batch_data, operation)
+
+ def _group_by_date(self, data: pl.DataFrame) -> dict[str, pl.DataFrame]:
+ """Group data by date, converting to UTC and validating dates."""
+ daily_batches: dict[str, list[dict[str, Any]]] = {}
+
+ # Ensure we have the required columns
+ if 'time/usage_start' not in data.columns:
+ self.console.print("[red]Error: Missing 'time/usage_start' column for date grouping[/red]")
+ return {}
+
+ timestamp_str: Optional[str] = None
+ for row in data.iter_rows(named=True):
+ try:
+ # Parse the timestamp and convert to UTC
+ timestamp_str = row.get('time/usage_start')
+ if not timestamp_str:
+ continue
+
+ # Parse timestamp and handle timezone conversion
+ dt = self._parse_and_convert_timestamp(timestamp_str)
+ batch_date = dt.strftime('%Y-%m-%d')
+
+ if batch_date not in daily_batches:
+ daily_batches[batch_date] = []
+
+ daily_batches[batch_date].append(row)
+
+ except Exception as e:
+ self.console.print(f"[yellow]Warning: Could not process timestamp '{timestamp_str}': {e}[/yellow]")
+ continue
+
+ # Convert lists back to DataFrames
+ return {date_key: pl.DataFrame(records) for date_key, records in daily_batches.items() if records}
+
+ def _parse_and_convert_timestamp(self, timestamp_str: str) -> datetime:
+ """Parse timestamp string and convert to UTC."""
+ # Try to parse the timestamp string
+ try:
+ # Handle various ISO 8601 formats
+ if timestamp_str.endswith('Z'):
+ dt = datetime.fromisoformat(timestamp_str.replace('Z', '+00:00'))
+ elif '+' in timestamp_str or timestamp_str.endswith(('-00:00', '-01:00', '-02:00', '-03:00',
+ '-04:00', '-05:00', '-06:00', '-07:00',
+ '-08:00', '-09:00', '-10:00', '-11:00',
+ '-12:00', '+01:00', '+02:00', '+03:00',
+ '+04:00', '+05:00', '+06:00', '+07:00',
+ '+08:00', '+09:00', '+10:00', '+11:00', '+12:00')):
+ dt = datetime.fromisoformat(timestamp_str)
+ else:
+ # Assume user timezone if no timezone info
+ dt = datetime.fromisoformat(timestamp_str)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=self.user_timezone)
+
+ # Convert to UTC
+ return dt.astimezone(timezone.utc)
+
+ except ValueError as e:
+ raise ValueError(f"Could not parse timestamp '{timestamp_str}': {e}")
+
+ def _send_daily_batch(self, batch_date: str, batch_data: pl.DataFrame, operation: str) -> None:
+ """Send a single daily batch to CloudZero API."""
+ if batch_data.is_empty():
+ return
+
+ headers = {
+ 'Authorization': f'Bearer {self.api_key}',
+ 'Content-Type': 'application/json'
+ }
+
+ # Use the correct API endpoint format from documentation
+ url = f"{self.base_url}/v2/connections/billing/anycost/{self.connection_id}/billing_drops"
+
+ # Prepare the batch payload according to AnyCost API format
+ payload = self._prepare_batch_payload(batch_date, batch_data, operation)
+
+ try:
+ with httpx.Client(timeout=30.0) as client:
+ self.console.print(f"[blue]Sending batch for {batch_date} ({len(batch_data)} records)[/blue]")
+
+ response = client.post(url, headers=headers, json=payload)
+ response.raise_for_status()
+
+ self.console.print(f"[green]✓ Successfully sent batch for {batch_date} ({len(batch_data)} records)[/green]")
+
+ except httpx.RequestError as e:
+ self.console.print(f"[red]✗ Network error sending batch for {batch_date}: {e}[/red]")
+ raise
+ except httpx.HTTPStatusError as e:
+ self.console.print(f"[red]✗ HTTP error sending batch for {batch_date}: {e.response.status_code} {e.response.text}[/red]")
+ raise
+
+ def _prepare_batch_payload(self, batch_date: str, batch_data: pl.DataFrame, operation: str) -> dict[str, Any]:
+ """Prepare batch payload according to CloudZero AnyCost API format."""
+ # Convert batch_date to month for the API (YYYY-MM format)
+ try:
+ date_obj = datetime.strptime(batch_date, '%Y-%m-%d')
+ month_str = date_obj.strftime('%Y-%m')
+ except ValueError:
+ # Fallback to current month
+ month_str = datetime.now().strftime('%Y-%m')
+
+ # Convert DataFrame rows to API format
+ data_records = []
+ for row in batch_data.iter_rows(named=True):
+ record = self._convert_cbf_to_api_format(row)
+ if record:
+ data_records.append(record)
+
+ payload = {
+ 'month': month_str,
+ 'operation': operation,
+ 'data': data_records
+ }
+
+ return payload
+
+ def _convert_cbf_to_api_format(self, row: dict[str, Any]) -> Optional[dict[str, Any]]:
+ """Convert CBF row to CloudZero API format - keeping CBF field names as CloudZero expects them."""
+ try:
+ # CloudZero expects CBF format field names directly, not converted names
+ api_record = {}
+
+ # Copy all CBF fields, converting numeric values to strings as required by CloudZero
+ for key, value in row.items():
+ if value is not None:
+ # CloudZero requires numeric values to be strings, but NOT in scientific notation
+ if isinstance(value, (int, float)):
+ # Format floats to avoid scientific notation
+ if isinstance(value, float):
+ # Use a reasonable precision that avoids scientific notation
+ api_record[key] = f"{value:.10f}".rstrip('0').rstrip('.')
+ else:
+ api_record[key] = str(value)
+ else:
+ api_record[key] = value
+
+ # Ensure timestamp is in UTC format
+ if 'time/usage_start' in api_record:
+ api_record['time/usage_start'] = self._ensure_utc_timestamp(api_record['time/usage_start'])
+
+ return api_record
+
+ except Exception as e:
+ self.console.print(f"[yellow]Warning: Could not convert record to API format: {e}[/yellow]")
+ return None
+
+ def _ensure_utc_timestamp(self, timestamp_str: str) -> str:
+ """Ensure timestamp is in UTC format for API."""
+ if not timestamp_str:
+ return datetime.now(timezone.utc).isoformat()
+
+ try:
+ dt = self._parse_and_convert_timestamp(timestamp_str)
+ return dt.isoformat().replace('+00:00', 'Z')
+ except Exception:
+ # Fallback to current time in UTC
+ return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
+
+
diff --git a/litellm/integrations/cloudzero/database.py b/litellm/integrations/cloudzero/database.py
new file mode 100644
index 00000000000..73a5c28e038
--- /dev/null
+++ b/litellm/integrations/cloudzero/database.py
@@ -0,0 +1,278 @@
+# Copyright 2025 CloudZero
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# CHANGELOG: 2025-01-19 - Refactored to use daily spend tables for proper CBF mapping (erik.peterson)
+# CHANGELOG: 2025-01-19 - Migrated from pandas to polars for database operations (erik.peterson)
+# CHANGELOG: 2025-01-19 - Initial database module for LiteLLM data extraction (erik.peterson)
+
+"""Database connection and data extraction for LiteLLM."""
+
+from typing import Any, Dict, Optional
+
+import polars as pl
+
+
+class LiteLLMDatabase:
+ """Handle LiteLLM PostgreSQL database connections and queries."""
+ def _ensure_prisma_client(self):
+ from litellm.proxy.proxy_server import prisma_client
+
+ """Ensure prisma client is available."""
+ if prisma_client is None:
+ raise Exception(
+ "Database not connected. Connect a database to your proxy - https://docs.litellm.ai/docs/simple_proxy#managing-auth---virtual-keys"
+ )
+ return prisma_client
+
+ async def get_usage_data(self, limit: Optional[int] = None) -> pl.DataFrame:
+ """Retrieve consolidated usage data from LiteLLM daily spend tables."""
+ client = self._ensure_prisma_client()
+
+ # Union query to combine user, team, and tag spend data
+ query = """
+ WITH consolidated_spend AS (
+ -- User spend data
+ SELECT
+ id,
+ date,
+ user_id as entity_id,
+ 'user' as entity_type,
+ api_key,
+ model,
+ model_group,
+ custom_llm_provider,
+ prompt_tokens,
+ completion_tokens,
+ spend,
+ api_requests,
+ successful_requests,
+ failed_requests,
+ cache_creation_input_tokens,
+ cache_read_input_tokens,
+ created_at,
+ updated_at
+ FROM "LiteLLM_DailyUserSpend"
+
+ UNION ALL
+
+ -- Team spend data
+ SELECT
+ id,
+ date,
+ team_id as entity_id,
+ 'team' as entity_type,
+ api_key,
+ model,
+ model_group,
+ custom_llm_provider,
+ prompt_tokens,
+ completion_tokens,
+ spend,
+ api_requests,
+ successful_requests,
+ failed_requests,
+ cache_creation_input_tokens,
+ cache_read_input_tokens,
+ created_at,
+ updated_at
+ FROM "LiteLLM_DailyTeamSpend"
+
+ UNION ALL
+
+ -- Tag spend data
+ SELECT
+ id,
+ date,
+ tag as entity_id,
+ 'tag' as entity_type,
+ api_key,
+ model,
+ model_group,
+ custom_llm_provider,
+ prompt_tokens,
+ completion_tokens,
+ spend,
+ api_requests,
+ successful_requests,
+ failed_requests,
+ cache_creation_input_tokens,
+ cache_read_input_tokens,
+ created_at,
+ updated_at
+ FROM "LiteLLM_DailyTagSpend"
+ )
+ SELECT * FROM consolidated_spend
+ ORDER BY date DESC, created_at DESC
+ """
+
+ if limit:
+ query += f" LIMIT {limit}"
+
+ try:
+ db_response = await client.db.query_raw(query)
+ # Convert the response to polars DataFrame
+ return pl.DataFrame(db_response)
+ except Exception as e:
+ raise Exception(f"Error retrieving usage data: {str(e)}")
+
+ async def get_table_info(self) -> Dict[str, Any]:
+ """Get information about the consolidated daily spend tables."""
+ client = self._ensure_prisma_client()
+
+ try:
+ # Get combined row count from both tables
+ user_count = await self._get_table_row_count('LiteLLM_DailyUserSpend')
+ team_count = await self._get_table_row_count('LiteLLM_DailyTeamSpend')
+ tag_count = await self._get_table_row_count('LiteLLM_DailyTagSpend')
+
+ # Get column structure from user spend table (representative)
+ query = """
+ SELECT column_name, data_type, is_nullable
+ FROM information_schema.columns
+ WHERE table_name = 'LiteLLM_DailyUserSpend'
+ ORDER BY ordinal_position;
+ """
+ columns_response = await client.db.query_raw(query)
+
+ return {
+ 'columns': columns_response,
+ 'row_count': user_count + team_count + tag_count,
+ 'table_breakdown': {
+ 'user_spend': user_count,
+ 'team_spend': team_count,
+ 'tag_spend': tag_count
+ }
+ }
+ except Exception as e:
+ raise Exception(f"Error getting table info: {str(e)}")
+
+ async def _get_table_row_count(self, table_name: str) -> int:
+ """Get row count from specified table."""
+ client = self._ensure_prisma_client()
+
+ try:
+ query = f'SELECT COUNT(*) as count FROM "{table_name}"'
+ response = await client.db.query_raw(query)
+
+ if response and len(response) > 0:
+ return response[0].get('count', 0)
+ return 0
+ except Exception:
+ return 0
+
+ async def discover_all_tables(self) -> Dict[str, Any]:
+ """Discover all tables in the LiteLLM database and their schemas."""
+ client = self._ensure_prisma_client()
+
+ try:
+ # Get all LiteLLM tables
+ litellm_tables_query = """
+ SELECT table_name
+ FROM information_schema.tables
+ WHERE table_schema = 'public'
+ AND table_name LIKE 'LiteLLM_%'
+ ORDER BY table_name;
+ """
+ tables_response = await client.db.query_raw(litellm_tables_query)
+ table_names = [row['table_name'] for row in tables_response]
+
+ # Get detailed schema for each table
+ tables_info = {}
+ for table_name in table_names:
+ # Get column information
+ columns_query = """
+ SELECT
+ column_name,
+ data_type,
+ is_nullable,
+ column_default,
+ character_maximum_length,
+ numeric_precision,
+ numeric_scale,
+ ordinal_position
+ FROM information_schema.columns
+ WHERE table_name = $1
+ AND table_schema = 'public'
+ ORDER BY ordinal_position;
+ """
+ columns_response = await client.db.query_raw(columns_query, table_name)
+
+ # Get primary key information
+ pk_query = """
+ SELECT a.attname
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = $1::regclass AND i.indisprimary;
+ """
+ pk_response = await client.db.query_raw(pk_query, f'"{table_name}"')
+ primary_keys = [row['attname'] for row in pk_response] if pk_response else []
+
+ # Get foreign key information
+ fk_query = """
+ SELECT
+ tc.constraint_name,
+ kcu.column_name,
+ ccu.table_name AS foreign_table_name,
+ ccu.column_name AS foreign_column_name
+ FROM information_schema.table_constraints AS tc
+ JOIN information_schema.key_column_usage AS kcu
+ ON tc.constraint_name = kcu.constraint_name
+ JOIN information_schema.constraint_column_usage AS ccu
+ ON ccu.constraint_name = tc.constraint_name
+ WHERE tc.constraint_type = 'FOREIGN KEY'
+ AND tc.table_name = $1;
+ """
+ fk_response = await client.db.query_raw(fk_query, table_name)
+ foreign_keys = fk_response if fk_response else []
+
+ # Get indexes
+ indexes_query = """
+ SELECT
+ i.relname AS index_name,
+ array_agg(a.attname ORDER BY a.attnum) AS column_names,
+ ix.indisunique AS is_unique
+ FROM pg_class t
+ JOIN pg_index ix ON t.oid = ix.indrelid
+ JOIN pg_class i ON i.oid = ix.indexrelid
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
+ WHERE t.relname = $1
+ AND t.relkind = 'r'
+ GROUP BY i.relname, ix.indisunique
+ ORDER BY i.relname;
+ """
+ indexes_response = await client.db.query_raw(indexes_query, table_name)
+ indexes = indexes_response if indexes_response else []
+
+ # Get row count
+ try:
+ row_count = await self._get_table_row_count(table_name)
+ except Exception:
+ row_count = 0
+
+ tables_info[table_name] = {
+ 'columns': columns_response,
+ 'primary_keys': primary_keys,
+ 'foreign_keys': foreign_keys,
+ 'indexes': indexes,
+ 'row_count': row_count
+ }
+
+ return {
+ 'tables': tables_info,
+ 'table_count': len(table_names),
+ 'table_names': table_names
+ }
+ except Exception as e:
+ raise Exception(f"Error discovering tables: {str(e)}")
+
diff --git a/litellm/integrations/cloudzero/transform.py b/litellm/integrations/cloudzero/transform.py
new file mode 100644
index 00000000000..c8aba5dbe66
--- /dev/null
+++ b/litellm/integrations/cloudzero/transform.py
@@ -0,0 +1,178 @@
+# Copyright 2025 CloudZero
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# CHANGELOG: 2025-01-19 - Updated CBF transformation for daily spend tables and proper CloudZero mapping (erik.peterson)
+# CHANGELOG: 2025-01-19 - Migrated from pandas to polars for data transformation (erik.peterson)
+# CHANGELOG: 2025-01-19 - Initial CBF transformation module (erik.peterson)
+
+"""Transform LiteLLM data to CloudZero AnyCost CBF format."""
+
+from datetime import datetime
+from typing import Any, Optional
+
+import polars as pl
+
+from ...types.integrations.cloudzero import CBFRecord
+from .cz_resource_names import CZRNGenerator
+
+
+class CBFTransformer:
+ """Transform LiteLLM usage data to CloudZero Billing Format (CBF)."""
+
+ def __init__(self):
+ """Initialize transformer with CZRN generator."""
+ self.czrn_generator = CZRNGenerator()
+
+ def transform(self, data: pl.DataFrame) -> pl.DataFrame:
+ """Transform LiteLLM data to CBF format, dropping records with zero successful_requests or invalid CZRNs."""
+ if data.is_empty():
+ return pl.DataFrame()
+
+ # Filter out records with zero successful_requests first
+ original_count = len(data)
+ if 'successful_requests' in data.columns:
+ filtered_data = data.filter(pl.col('successful_requests') > 0)
+ zero_requests_dropped = original_count - len(filtered_data)
+ else:
+ filtered_data = data
+ zero_requests_dropped = 0
+
+ cbf_data = []
+ czrn_dropped_count = 0
+ filtered_count = len(filtered_data)
+
+ for row in filtered_data.iter_rows(named=True):
+ try:
+ cbf_record = self._create_cbf_record(row)
+ # Only include the record if CZRN generation was successful
+ cbf_data.append(cbf_record)
+ except Exception:
+ # Skip records that fail CZRN generation
+ czrn_dropped_count += 1
+ continue
+
+ # Print summary of dropped records if any
+ from rich.console import Console
+ console = Console()
+
+ if zero_requests_dropped > 0:
+ console.print(f"[yellow]⚠️ Dropped {zero_requests_dropped:,} of {original_count:,} records with zero successful_requests[/yellow]")
+
+ if czrn_dropped_count > 0:
+ console.print(f"[yellow]⚠️ Dropped {czrn_dropped_count:,} of {filtered_count:,} filtered records due to invalid CZRNs[/yellow]")
+
+ if len(cbf_data) > 0:
+ console.print(f"[green]✓ Successfully transformed {len(cbf_data):,} records[/green]")
+
+ return pl.DataFrame(cbf_data)
+
+ def _create_cbf_record(self, row: dict[str, Any]) -> CBFRecord:
+ """Create a single CBF record from LiteLLM daily spend row."""
+
+ # Parse date (daily spend tables use date strings like '2025-04-19')
+ usage_date = self._parse_date(row.get('date'))
+
+ # Calculate total tokens
+ prompt_tokens = int(row.get('prompt_tokens', 0))
+ completion_tokens = int(row.get('completion_tokens', 0))
+ total_tokens = prompt_tokens + completion_tokens
+
+ # Create CloudZero Resource Name (CZRN) as resource_id
+ resource_id = self.czrn_generator.create_from_litellm_data(row)
+
+ # Build dimensions for CloudZero
+ entity_id = str(row.get('entity_id', ''))
+ model = str(row.get('model', ''))
+ api_key_hash = str(row.get('api_key', ''))[:8] # First 8 chars for identification
+
+ dimensions = {
+ 'entity_type': str(row.get('entity_type', '')), # 'user' or 'team'
+ 'entity_id': entity_id,
+ 'model': model,
+ 'model_group': str(row.get('model_group', '')),
+ 'provider': str(row.get('custom_llm_provider', '')),
+ 'api_key_prefix': api_key_hash,
+ 'api_requests': str(row.get('api_requests', 0)),
+ 'successful_requests': str(row.get('successful_requests', 0)),
+ 'failed_requests': str(row.get('failed_requests', 0)),
+ 'cache_creation_tokens': str(row.get('cache_creation_input_tokens', 0)),
+ 'cache_read_tokens': str(row.get('cache_read_input_tokens', 0)),
+ }
+
+ # Extract CZRN components to populate corresponding CBF columns
+ czrn_components = self.czrn_generator.extract_components(resource_id)
+ service_type, provider, region, owner_account_id, resource_type, cloud_local_id = czrn_components
+
+ # CloudZero CBF format with proper column names
+ cbf_record = {
+ # Required CBF fields
+ 'time/usage_start': usage_date.isoformat() if usage_date else None, # Required: ISO-formatted UTC datetime
+ 'cost/cost': float(row.get('spend', 0.0)), # Required: billed cost
+ 'resource/id': resource_id, # Required when resource tags are present
+
+ # Usage metrics for token consumption
+ 'usage/amount': total_tokens, # Numeric value of tokens consumed
+ 'usage/units': 'tokens', # Description of token units
+
+ # CBF fields that correspond to CZRN components
+ 'resource/service': service_type, # Maps to CZRN service-type (litellm)
+ 'resource/account': owner_account_id, # Maps to CZRN owner-account-id (entity_id)
+ 'resource/region': region, # Maps to CZRN region (cross-region)
+ 'resource/usage_family': resource_type, # Maps to CZRN resource-type (llm-usage)
+
+ # Line item details
+ 'lineitem/type': 'Usage', # Standard usage line item
+ }
+
+ # Add CZRN components that don't have direct CBF column mappings as resource tags
+ cbf_record['resource/tag:provider'] = provider # CZRN provider component
+ cbf_record['resource/tag:model'] = cloud_local_id # CZRN cloud-local-id component (model)
+
+ # Add resource tags for all dimensions (using resource/tag:<key> format)
+ for key, value in dimensions.items():
+ if value and value != 'N/A': # Only add non-empty tags
+ cbf_record[f'resource/tag:{key}'] = str(value)
+
+ # Add token breakdown as resource tags for analysis
+ if prompt_tokens > 0:
+ cbf_record['resource/tag:prompt_tokens'] = str(prompt_tokens)
+ if completion_tokens > 0:
+ cbf_record['resource/tag:completion_tokens'] = str(completion_tokens)
+ if total_tokens > 0:
+ cbf_record['resource/tag:total_tokens'] = str(total_tokens)
+
+ return CBFRecord(cbf_record)
+
+ def _parse_date(self, date_str) -> Optional[datetime]:
+ """Parse date string from daily spend tables (e.g., '2025-04-19')."""
+ if date_str is None:
+ return None
+
+ if isinstance(date_str, datetime):
+ return date_str
+
+ if isinstance(date_str, str):
+ try:
+ # Parse date string and set to midnight UTC for daily aggregation
+ return pl.Series([date_str]).str.to_datetime("%Y-%m-%d").item()
+ except Exception:
+ try:
+ # Fallback: try ISO format parsing
+ return pl.Series([date_str]).str.to_datetime().item()
+ except Exception:
+ return None
+
+ return None
+
+
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index f4053dde7bd..14183bbedd9 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -306,6 +306,7 @@ from litellm.proxy.public_endpoints import router as public_endpoints_router
from litellm.proxy.rerank_endpoints.endpoints import router as rerank_router
from litellm.proxy.response_api_endpoints.endpoints import router as response_router
from litellm.proxy.route_llm_request import route_request
+from litellm.proxy.spend_tracking.cloudzero_endpoints import router as cloudzero_router
from litellm.proxy.spend_tracking.spend_management_endpoints import (
router as spend_management_router,
)
@@ -8798,6 +8799,7 @@ app.include_router(scim_router)
app.include_router(organization_router)
app.include_router(customer_router)
app.include_router(spend_management_router)
+app.include_router(cloudzero_router)
app.include_router(caching_router)
app.include_router(analytics_router)
app.include_router(guardrails_router)
diff --git a/litellm/proxy/spend_tracking/cloudzero_endpoints.py b/litellm/proxy/spend_tracking/cloudzero_endpoints.py
new file mode 100644
index 00000000000..96e04ac5095
--- /dev/null
+++ b/litellm/proxy/spend_tracking/cloudzero_endpoints.py
@@ -0,0 +1,225 @@
+import json
+
+from fastapi import APIRouter, Depends, HTTPException
+
+from litellm._logging import verbose_proxy_logger
+from litellm.proxy._types import CommonProxyErrors, LitellmUserRoles, UserAPIKeyAuth
+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+from litellm.types.proxy.cloudzero_endpoints import (
+ CloudZeroExportRequest,
+ CloudZeroExportResponse,
+ CloudZeroInitRequest,
+ CloudZeroInitResponse,
+)
+
+router = APIRouter()
+
+
+ "/cloudzero/init",
+ tags=["CloudZero"],
+ dependencies=[Depends(user_api_key_auth)],
+ response_model=CloudZeroInitResponse,
+)
+async def init_cloudzero_settings(
+ request: CloudZeroInitRequest,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ Initialize CloudZero settings and store in the database.
+
+ This endpoint stores the CloudZero API key, connection ID, and timezone configuration
+ in the proxy database for use by the CloudZero logger.
+
+ Parameters:
+ - api_key: CloudZero API key for authentication
+ - connection_id: CloudZero connection ID for data submission
+ - timezone: Timezone for date handling (default: UTC)
+
+ Only admin users can configure CloudZero settings.
+ """
+ from litellm.proxy.proxy_server import prisma_client
+
+ # Validation
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=500,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": CommonProxyErrors.not_allowed_access.value},
+ )
+
+ try:
+ # Prepare CloudZero settings
+ cloudzero_settings = {
+ "api_key": request.api_key,
+ "connection_id": request.connection_id,
+ "timezone": request.timezone,
+ }
+
+ # Store in database
+ await prisma_client.db.litellm_config.upsert(
+ where={"param_name": "cloudzero_settings"},
+ data={
+ "create": {
+ "param_name": "cloudzero_settings",
+ "param_value": json.dumps(cloudzero_settings),
+ },
+ "update": {"param_value": json.dumps(cloudzero_settings)},
+ },
+ )
+
+ verbose_proxy_logger.info("CloudZero settings initialized successfully")
+
+ return CloudZeroInitResponse(
+ message="CloudZero settings initialized successfully",
+ status="success"
+ )
+
+ except Exception as e:
+ verbose_proxy_logger.error(f"Error initializing CloudZero settings: {str(e)}")
+ raise HTTPException(
+ status_code=500,
+ detail={"error": f"Failed to initialize CloudZero settings: {str(e)}"}
+ )
+
+
+ "/cloudzero/dry-run",
+ tags=["CloudZero"],
+ dependencies=[Depends(user_api_key_auth)],
+ response_model=CloudZeroExportResponse,
+)
+async def cloudzero_dry_run_export(
+ request: CloudZeroExportRequest,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ Perform a dry run export using the CloudZero logger.
+
+ This endpoint uses the CloudZero logger to perform a dry run export,
+ which displays the data that would be exported without actually sending it to CloudZero.
+
+ Parameters:
+ - limit: Optional limit on number of records to process (default: 10000)
+
+ Only admin users can perform CloudZero exports.
+ """
+ from litellm.proxy.proxy_server import prisma_client
+
+ # Validation
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=500,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": CommonProxyErrors.not_allowed_access.value},
+ )
+
+ try:
+ # Import and initialize CloudZero logger with credentials
+ from litellm.integrations.cloudzero.ll2cz.cloudzero import CloudZeroLogger
+
+ # Initialize logger with credentials directly
+ logger = CloudZeroLogger()
+ await logger.dry_run_export_usage_data(limit=request.limit)
+
+ verbose_proxy_logger.info("CloudZero dry run export completed successfully")
+
+ return CloudZeroExportResponse(
+ message="CloudZero dry run export completed successfully. Check logs for output.",
+ status="success"
+ )
+
+ except Exception as e:
+ verbose_proxy_logger.error(f"Error performing CloudZero dry run export: {str(e)}")
+ raise HTTPException(
+ status_code=500,
+ detail={"error": f"Failed to perform CloudZero dry run export: {str(e)}"}
+ )
+
+
+ "/cloudzero/export",
+ tags=["CloudZero"],
+ dependencies=[Depends(user_api_key_auth)],
+ response_model=CloudZeroExportResponse,
+)
+async def cloudzero_export(
+ request: CloudZeroExportRequest,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ Perform an actual export using the CloudZero logger.
+
+ This endpoint uses the CloudZero logger to export usage data to CloudZero AnyCost API.
+
+ Parameters:
+ - limit: Optional limit on number of records to export
+ - operation: CloudZero operation type ("replace_hourly" or "sum", default: "replace_hourly")
+
+ Only admin users can perform CloudZero exports.
+ """
+ from litellm.proxy.proxy_server import prisma_client
+
+ # Validation
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=500,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:
+ raise HTTPException(
+ status_code=403,
+ detail={"error": CommonProxyErrors.not_allowed_access.value},
+ )
+
+ try:
+ # Get CloudZero settings from database
+ cloudzero_config = await prisma_client.db.litellm_config.find_first(
+ where={"param_name": "cloudzero_settings"}
+ )
+
+ if not cloudzero_config or not cloudzero_config.param_value:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "CloudZero settings not configured. Please run /cloudzero/init first."}
+ )
+
+ settings = dict(cloudzero_config.param_value)
+
+ # Import and initialize CloudZero logger with credentials
+ from litellm.integrations.cloudzero.ll2cz.cloudzero import CloudZeroLogger
+
+ # Initialize logger with credentials directly
+ logger = CloudZeroLogger(
+ api_key=settings["api_key"],
+ connection_id=settings["connection_id"],
+ timezone=settings["timezone"]
+ )
+ await logger.export_usage_data(limit=request.limit, operation=request.operation)
+
+ verbose_proxy_logger.info("CloudZero export completed successfully")
+
+ return CloudZeroExportResponse(
+ message="CloudZero export completed successfully",
+ status="success"
+ )
+
+ except Exception as e:
+ verbose_proxy_logger.error(f"Error performing CloudZero export: {str(e)}")
+ raise HTTPException(
+ status_code=500,
+ detail={"error": f"Failed to perform CloudZero export: {str(e)}"}
+ )
+
+
diff --git a/litellm/types/integrations/cloudzero.py b/litellm/types/integrations/cloudzero.py
new file mode 100644
index 00000000000..aeda76aa5f9
--- /dev/null
+++ b/litellm/types/integrations/cloudzero.py
@@ -0,0 +1,31 @@
+from typing import Any, Dict, Optional
+
+
+class CBFRecord(Dict[str, Any]):
+ """CloudZero Billing Format (CBF) record structure.
+
+ This class represents a CBF record that is created from LiteLLM usage data
+ for CloudZero integration. Since CBF field names contain forward slashes
+ (e.g., 'time/usage_start', 'cost/cost'), we use a Dict base class rather
+ than TypedDict to accommodate the special characters in field names.
+
+ Expected CBF fields:
+ - time/usage_start: ISO-formatted UTC datetime (Optional[str])
+ - cost/cost: Billed cost (float)
+ - resource/id: CloudZero Resource Name (CZRN) (str)
+ - usage/amount: Numeric value of tokens consumed (int)
+ - usage/units: Description of units, e.g., 'tokens' (str)
+ - resource/service: Maps to CZRN service-type, e.g., 'litellm' (str)
+ - resource/account: Maps to CZRN owner-account-id (entity_id) (str)
+ - resource/region: Maps to CZRN region, e.g., 'cross-region' (str)
+ - resource/usage_family: Maps to CZRN resource-type, e.g., 'llm-usage' (str)
+ - lineitem/type: Standard usage line item, e.g., 'Usage' (str)
+ - resource/tag:provider: CZRN provider component (str)
+ - resource/tag:model: CZRN cloud-local-id component (model) (str)
+ - resource/tag:{key}: Various resource tags for dimensions and metrics (Optional[str])
+ """
+ pass
+
+
+# Type alias for better readability in function signatures
+CBFRecordDict = Dict[str, Any]
\ No newline at end of file
diff --git a/litellm/types/proxy/cloudzero_endpoints.py b/litellm/types/proxy/cloudzero_endpoints.py
new file mode 100644
index 00000000000..8ed535d60b3
--- /dev/null
+++ b/litellm/types/proxy/cloudzero_endpoints.py
@@ -0,0 +1,37 @@
+"""
+CloudZero endpoint types for LiteLLM Proxy
+"""
+
+from typing import Optional
+
+from pydantic import BaseModel, Field
+
+
+class CloudZeroInitRequest(BaseModel):
+ """Request model for initializing CloudZero settings"""
+
+ api_key: str = Field(..., description="CloudZero API key for authentication")
+ connection_id: str = Field(..., description="CloudZero connection ID for data submission")
+ timezone: str = Field(default="UTC", description="Timezone for date handling (default: UTC)")
+
+
+class CloudZeroInitResponse(BaseModel):
+ """Response model for CloudZero initialization"""
+
+ message: str
+ status: str
+
+
+class CloudZeroExportRequest(BaseModel):
+ """Request model for CloudZero export operations"""
+
+ limit: Optional[int] = Field(None, description="Optional limit on number of records to export")
+ operation: str = Field(default="replace_hourly", description="CloudZero operation type (replace_hourly or sum)")
+
+
+class CloudZeroExportResponse(BaseModel):
+ """Response model for CloudZero export operations"""
+
+ message: str
+ status: str
+ records_exported: Optional[int] = None
\ No newline at end of file
diff --git a/poetry.lock b/poetry.lock
index 09fad36f8a5..e78b82b0b8a 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -2769,6 +2769,51 @@ files = [
dev = ["pre-commit", "tox"]
testing = ["pytest", "pytest-benchmark"]
+[[package]]
+name = "polars"
+version = "1.31.0"
+description = "Blazingly fast DataFrame library"
+optional = true
+python-versions = ">=3.9"
+groups = ["main"]
+markers = "python_version >= \"3.10\" and extra == \"proxy\""
+files = [
+ {file = "polars-1.31.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:ccc68cd6877deecd46b13cbd2663ca89ab2a2cb1fe49d5cfc66a9cef166566d9"},
+ {file = "polars-1.31.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:a94c5550df397ad3c2d6adc212e59fd93d9b044ec974dd3653e121e6487a7d21"},
+ {file = "polars-1.31.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ada7940ed92bea65d5500ae7ac1f599798149df8faa5a6db150327c9ddbee4f1"},
+ {file = "polars-1.31.0-cp39-abi3-manylinux_2_24_aarch64.whl", hash = "sha256:b324e6e3e8c6cc6593f9d72fe625f06af65e8d9d47c8686583585533a5e731e1"},
+ {file = "polars-1.31.0-cp39-abi3-win_amd64.whl", hash = "sha256:3fd874d3432fc932863e8cceff2cff8a12a51976b053f2eb6326a0672134a632"},
+ {file = "polars-1.31.0-cp39-abi3-win_arm64.whl", hash = "sha256:62ef23bb9d10dca4c2b945979f9a50812ac4ace4ed9e158a6b5d32a7322e6f75"},
+ {file = "polars-1.31.0.tar.gz", hash = "sha256:59a88054a5fc0135386268ceefdbb6a6cc012d21b5b44fed4f1d3faabbdcbf32"},
+]
+
+[package.extras]
+adbc = ["adbc-driver-manager[dbapi]", "adbc-driver-sqlite[dbapi]"]
+all = ["polars[async,cloudpickle,database,deltalake,excel,fsspec,graph,iceberg,numpy,pandas,plot,pyarrow,pydantic,style,timezone]"]
+async = ["gevent"]
+calamine = ["fastexcel (>=0.9)"]
+cloudpickle = ["cloudpickle"]
+connectorx = ["connectorx (>=0.3.2)"]
+database = ["polars[adbc,connectorx,sqlalchemy]"]
+deltalake = ["deltalake (>=1.0.0)"]
+excel = ["polars[calamine,openpyxl,xlsx2csv,xlsxwriter]"]
+fsspec = ["fsspec"]
+gpu = ["cudf-polars-cu12"]
+graph = ["matplotlib"]
+iceberg = ["pyiceberg (>=0.7.1)"]
+numpy = ["numpy (>=1.16.0)"]
+openpyxl = ["openpyxl (>=3.0.0)"]
+pandas = ["pandas", "polars[pyarrow]"]
+plot = ["altair (>=5.4.0)"]
+polars-cloud = ["polars-cloud (>=0.0.1a1)"]
+pyarrow = ["pyarrow (>=7.0.0)"]
+pydantic = ["pydantic"]
+sqlalchemy = ["polars[pandas]", "sqlalchemy"]
+style = ["great-tables (>=0.8.0)"]
+timezone = ["tzdata ; platform_system == \"Windows\""]
+xlsx2csv = ["xlsx2csv (>=0.8.0)"]
+xlsxwriter = ["xlsxwriter"]
+
[[package]]
name = "priority"
version = "2.0.0"
@@ -5009,10 +5054,10 @@ type = ["pytest-mypy"]
[extras]
caching = ["diskcache"]
extra-proxy = ["azure-identity", "azure-keyvault-secrets", "google-cloud-kms", "prisma", "redisvl", "resend"]
-proxy = ["PyJWT", "apscheduler", "azure-identity", "azure-storage-blob", "backoff", "boto3", "cryptography", "fastapi", "fastapi-sso", "gunicorn", "litellm-enterprise", "litellm-proxy-extras", "mcp", "orjson", "pynacl", "python-multipart", "pyyaml", "rich", "rq", "uvicorn", "uvloop", "websockets"]
+proxy = ["PyJWT", "apscheduler", "azure-identity", "azure-storage-blob", "backoff", "boto3", "cryptography", "fastapi", "fastapi-sso", "gunicorn", "litellm-enterprise", "litellm-proxy-extras", "mcp", "orjson", "polars", "pynacl", "python-multipart", "pyyaml", "rich", "rq", "uvicorn", "uvloop", "websockets"]
utils = ["numpydoc"]
[metadata]
lock-version = "2.1"
python-versions = ">=3.8.1,<4.0, !=3.9.7"
-content-hash = "52ec359b5918015cbaf11a2564591691dd43ed0f90a1fd38c3529abc6722e9c2"
+content-hash = "23d4d980f91bcaabd62951675fe7e0b335bcc4805479228e019de38820ac042c"
diff --git a/pyproject.toml b/pyproject.toml
index 546133e471d..836f9853ebc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -61,6 +61,7 @@ litellm-proxy-extras = {version = "0.2.11", optional = true}
rich = {version = "13.7.1", optional = true}
litellm-enterprise = {version = "0.1.15", optional = true}
diskcache = {version = "^5.6.1", optional = true}
+polars = {version = "^1.31.0", optional = true, python = ">=3.10"}
[tool.poetry.extras]
proxy = [
@@ -86,6 +87,7 @@ proxy = [
"litellm-proxy-extras",
"litellm-enterprise",
"rich",
+ "polars",
]
extra_proxy = [
diff --git a/requirements.txt b/requirements.txt
index 24fc55b9a6a..b17abca504f 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -23,6 +23,7 @@ langfuse==2.59.7 # for langfuse self-hosted logging
prometheus_client==0.20.0 # for /metrics endpoint on proxy
ddtrace==2.19.0 # for advanced DD tracing / profiling
orjson==3.10.12 # fast /embedding responses
+polars==1.31.0 # for data processing
apscheduler==3.10.4 # for resetting budget in background
fastapi-sso==0.16.0 # admin UI, SSO
pyjwt[crypto]==2.9.0
diff --git a/tests/code_coverage_tests/liccheck.ini b/tests/code_coverage_tests/liccheck.ini
index a869fe9603f..f4931467b00 100644
--- a/tests/code_coverage_tests/liccheck.ini
+++ b/tests/code_coverage_tests/liccheck.ini
@@ -131,4 +131,5 @@ tenacity: >=8.2.3 # Unknown license
pydantic: >=2.10.2 # Unknown license
jsonschema: >=4.22.0 # Unknown license
websockets: >=13.1.0 # Unknown license
+polars: >=1.31.0 # Unknown license, the license.md allows free of charge use
diff --git a/tests/test_litellm/integrations/cloudzero/test_cz_stream_api.py b/tests/test_litellm/integrations/cloudzero/test_cz_stream_api.py
new file mode 100644
index 00000000000..7a0783c7fc4
--- /dev/null
+++ b/tests/test_litellm/integrations/cloudzero/test_cz_stream_api.py
@@ -0,0 +1,160 @@
+import os
+import sys
+import zoneinfo
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, Mock, patch
+
+import httpx
+import polars as pl
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../../.."))
+
+from litellm.integrations.cloudzero.cz_stream_api import CloudZeroStreamer
+
+
+class TestCloudZeroStreamer:
+ """Test suite for CloudZeroStreamer class."""
+
+ def test_init_with_defaults(self):
+ """Test CloudZeroStreamer initialization with default parameters."""
+ streamer = CloudZeroStreamer(
+ api_key="test-key",
+ connection_id="test-connection"
+ )
+
+ assert streamer.api_key == "test-key"
+ assert streamer.connection_id == "test-connection"
+ assert streamer.base_url == "https://api.cloudzero.com"
+ assert streamer.user_timezone == timezone.utc
+
+ def test_init_with_valid_timezone(self):
+ """Test CloudZeroStreamer initialization with valid timezone."""
+ streamer = CloudZeroStreamer(
+ api_key="test-key",
+ connection_id="test-connection",
+ user_timezone="America/New_York"
+ )
+
+ assert streamer.user_timezone == zoneinfo.ZoneInfo("America/New_York")
+
+ def test_send_batched_with_valid_data(self):
+ """Test send_batched method with valid data."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+ with patch.object(streamer, '_group_by_date') as mock_group, \
+ patch.object(streamer, '_send_daily_batch') as mock_send:
+
+ mock_group.return_value = {
+ '2025-01-19': pl.DataFrame({'test': ['data1']}),
+ '2025-01-20': pl.DataFrame({'test': ['data2']})
+ }
+
+ data = pl.DataFrame({'test': ['data']})
+ streamer.send_batched(data, "replace_hourly")
+
+ assert mock_send.call_count == 2
+
+ def test_group_by_date_valid_data(self):
+ """Test _group_by_date method with valid data."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+ with patch.object(streamer, '_parse_and_convert_timestamp') as mock_parse:
+ mock_parse.return_value = datetime(2025, 1, 19, 10, 30, 0, tzinfo=timezone.utc)
+
+ data = pl.DataFrame({
+ 'time/usage_start': ['2025-01-19T10:30:00Z'],
+ 'cost': [10.0]
+ })
+
+ result = streamer._group_by_date(data)
+
+ assert '2025-01-19' in result
+ assert len(result['2025-01-19']) == 1
+
+
+ def test_parse_and_convert_timestamp_utc(self):
+ """Test _parse_and_convert_timestamp method with UTC timestamp."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+
+ result = streamer._parse_and_convert_timestamp('2025-01-19T10:30:00Z')
+
+ assert result.year == 2025
+ assert result.month == 1
+ assert result.day == 19
+ assert result.hour == 10
+ assert result.minute == 30
+ assert result.tzinfo == timezone.utc
+
+ def test_parse_and_convert_timestamp_with_offset(self):
+ """Test _parse_and_convert_timestamp method with timezone offset."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+
+ result = streamer._parse_and_convert_timestamp('2025-01-19T10:30:00+05:00')
+
+ assert result.tzinfo == timezone.utc
+ assert result.hour == 5 # Converted to UTC
+
+ def test_parse_and_convert_timestamp_no_timezone(self):
+ """Test _parse_and_convert_timestamp method without timezone info."""
+ streamer = CloudZeroStreamer("test-key", "test-connection", user_timezone="America/New_York")
+
+ result = streamer._parse_and_convert_timestamp('2025-01-19T10:30:00')
+
+ assert result.tzinfo == timezone.utc
+
+ def test_parse_and_convert_timestamp_invalid(self):
+ """Test _parse_and_convert_timestamp method with invalid timestamp."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+
+ with pytest.raises(ValueError):
+ streamer._parse_and_convert_timestamp('invalid-timestamp')
+
+ def test_prepare_batch_payload(self):
+ """Test _prepare_batch_payload method."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+ with patch.object(streamer, '_convert_cbf_to_api_format') as mock_convert:
+ mock_convert.return_value = {'test': 'record'}
+
+ batch_data = pl.DataFrame({'cost': [10.0]})
+ result = streamer._prepare_batch_payload('2025-01-19', batch_data, 'replace_hourly')
+
+ assert result['month'] == '2025-01'
+ assert result['operation'] == 'replace_hourly'
+ assert len(result['data']) == 1
+
+
+
+ def test_convert_cbf_to_api_format_valid_data(self):
+ """Test _convert_cbf_to_api_format method with valid data."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+ with patch.object(streamer, '_ensure_utc_timestamp') as mock_ensure:
+ mock_ensure.return_value = '2025-01-19T10:30:00Z'
+
+ row = {
+ 'time/usage_start': '2025-01-19T10:30:00Z',
+ 'cost/cost': 10.5,
+ 'tokens': 100,
+ 'text_field': 'test'
+ }
+
+ result = streamer._convert_cbf_to_api_format(row)
+
+ assert result['cost/cost'] == '10.5'
+ assert result['tokens'] == '100'
+ assert result['text_field'] == 'test'
+
+ def test_convert_cbf_to_api_format_float_precision(self):
+ """Test _convert_cbf_to_api_format method handles float precision correctly."""
+ streamer = CloudZeroStreamer("test-key", "test-connection")
+
+ row = {
+ 'cost': 10.123456789012345,
+ 'large_float': 1234567890.0
+ }
+
+ result = streamer._convert_cbf_to_api_format(row)
+
+ # Should avoid scientific notation
+ assert 'e' not in result['cost'].lower()
+ assert 'e' not in result['large_float'].lower()
+
+
\ No newline at end of file
diff --git a/tests/test_litellm/integrations/cloudzero/test_transform.py b/tests/test_litellm/integrations/cloudzero/test_transform.py
new file mode 100644
index 00000000000..1f4db10cab8
--- /dev/null
+++ b/tests/test_litellm/integrations/cloudzero/test_transform.py
@@ -0,0 +1,183 @@
+import os
+import sys
+from datetime import datetime
+from unittest.mock import MagicMock, patch
+
+import polars as pl
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../../.."))
+
+from litellm.integrations.cloudzero.transform import CBFTransformer
+from litellm.types.integrations.cloudzero import CBFRecord
+
+
+class TestCBFTransformer:
+ """Test suite for CBFTransformer class."""
+
+ def test_init(self):
+ """Test CBFTransformer initialization."""
+ transformer = CBFTransformer()
+ assert hasattr(transformer, 'czrn_generator')
+ assert transformer.czrn_generator is not None
+
+ def test_transform_empty_dataframe(self):
+ """Test transform method with empty DataFrame."""
+ transformer = CBFTransformer()
+ empty_df = pl.DataFrame()
+
+ result = transformer.transform(empty_df)
+
+ assert result.is_empty()
+ assert isinstance(result, pl.DataFrame)
+
+ def test_transform_with_zero_successful_requests(self):
+ """Test transform method filters out records with zero successful_requests."""
+ transformer = CBFTransformer()
+ data = pl.DataFrame({
+ 'date': ['2025-01-19'],
+ 'successful_requests': [0],
+ 'spend': [10.0],
+ 'entity_id': ['test_entity'],
+ 'model': ['gpt-4']
+ })
+
+ result = transformer.transform(data)
+
+ assert result.is_empty()
+
+ def test_transform_with_valid_data(self):
+ """Test transform method with valid data."""
+ transformer = CBFTransformer()
+ with patch.object(transformer, '_create_cbf_record') as mock_create:
+ mock_create.return_value = CBFRecord({'test': 'data'})
+
+ data = pl.DataFrame({
+ 'date': ['2025-01-19'],
+ 'successful_requests': [5],
+ 'spend': [10.0],
+ 'entity_id': ['test_entity'],
+ 'model': ['gpt-4']
+ })
+
+ result = transformer.transform(data)
+
+ assert len(result) == 1
+ mock_create.assert_called_once()
+
+ def test_transform_handles_czrn_generation_failures(self):
+ """Test transform method handles CZRN generation failures gracefully."""
+ transformer = CBFTransformer()
+ with patch.object(transformer, '_create_cbf_record') as mock_create:
+ mock_create.side_effect = Exception("CZRN generation failed")
+
+ data = pl.DataFrame({
+ 'date': ['2025-01-19'],
+ 'successful_requests': [5],
+ 'spend': [10.0],
+ 'entity_id': ['test_entity'],
+ 'model': ['gpt-4']
+ })
+
+ result = transformer.transform(data)
+
+ assert result.is_empty()
+
+ def test_create_cbf_record(self):
+ """Test _create_cbf_record method with valid row data."""
+ transformer = CBFTransformer()
+ with patch.object(transformer.czrn_generator, 'create_from_litellm_data') as mock_czrn, \
+ patch.object(transformer.czrn_generator, 'extract_components') as mock_extract:
+
+ mock_czrn.return_value = 'test-czrn'
+ mock_extract.return_value = ('service', 'provider', 'region', 'account', 'resource', 'local_id')
+
+ row = {
+ 'date': '2025-01-19',
+ 'spend': 10.5,
+ 'prompt_tokens': 100,
+ 'completion_tokens': 50,
+ 'entity_id': 'test_entity',
+ 'model': 'gpt-4',
+ 'entity_type': 'user',
+ 'model_group': 'openai',
+ 'custom_llm_provider': 'openai',
+ 'api_key': 'sk-test123',
+ 'api_requests': 5,
+ 'successful_requests': 5,
+ 'failed_requests': 0
+ }
+
+ result = transformer._create_cbf_record(row)
+
+ assert isinstance(result, CBFRecord)
+ assert result['cost/cost'] == 10.5
+ assert result['usage/amount'] == 150 # 100 + 50
+ assert result['usage/units'] == 'tokens'
+ assert result['resource/id'] == 'test-czrn'
+
+ def test_create_cbf_record_minimal_data(self):
+ """Test _create_cbf_record method with minimal row data."""
+ transformer = CBFTransformer()
+ with patch.object(transformer.czrn_generator, 'create_from_litellm_data') as mock_czrn, \
+ patch.object(transformer.czrn_generator, 'extract_components') as mock_extract:
+
+ mock_czrn.return_value = 'test-czrn'
+ mock_extract.return_value = ('service', 'provider', 'region', 'account', 'resource', 'local_id')
+
+ row = {
+ 'date': '2025-01-19',
+ 'spend': 0.0
+ }
+
+ result = transformer._create_cbf_record(row)
+
+ assert isinstance(result, CBFRecord)
+ assert result['cost/cost'] == 0.0
+ assert result['usage/amount'] == 0 # no tokens
+ assert result['usage/units'] == 'tokens'
+
+ def test_parse_date_with_valid_string(self):
+ """Test _parse_date method with valid date string."""
+ transformer = CBFTransformer()
+
+ result = transformer._parse_date('2025-01-19')
+
+ assert isinstance(result, datetime)
+ assert result.year == 2025
+ assert result.month == 1
+ assert result.day == 19
+
+ def test_parse_date_with_datetime_object(self):
+ """Test _parse_date method with datetime object."""
+ transformer = CBFTransformer()
+ dt = datetime(2025, 1, 19)
+
+ result = transformer._parse_date(dt)
+
+ assert result == dt
+
+ def test_parse_date_with_none(self):
+ """Test _parse_date method with None."""
+ transformer = CBFTransformer()
+
+ result = transformer._parse_date(None)
+
+ assert result is None
+
+ def test_parse_date_with_invalid_string(self):
+ """Test _parse_date method with invalid date string."""
+ transformer = CBFTransformer()
+
+ result = transformer._parse_date('invalid-date')
+
+ assert result is None
+
+ def test_parse_date_with_iso_format(self):
+ """Test _parse_date method with ISO format string."""
+ transformer = CBFTransformer()
+
+ result = transformer._parse_date('2025-01-19T10:30:00Z')
+
+ assert isinstance(result, datetime)
+ assert result.year == 2025
\ No newline at end of file