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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Add Vantage integration for FOCUS CSV export
Harshit28j69a94a873c1a
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex 4fc71e12700..2334858a053 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -143,6 +143,7 @@ _custom_logger_compatible_callbacks_literal = Literal["gitlab","cloudzero","focus",+ "vantage","posthog","levo",]diff --git a/litellm/integrations/focus/destinations/__init__.py b/litellm/integrations/focus/destinations/__init__.pyindex 233f1da0c9b..775d3a259d2 100644--- a/litellm/integrations/focus/destinations/__init__.py+++ b/litellm/integrations/focus/destinations/__init__.py@@ -3,10 +3,12 @@from .base import FocusDestination, FocusTimeWindowfrom .factory import FocusDestinationFactoryfrom .s3_destination import FocusS3Destination+from .vantage_destination import FocusVantageDestination__all__ = ["FocusDestination","FocusDestinationFactory","FocusTimeWindow","FocusS3Destination",+ "FocusVantageDestination",]diff --git a/litellm/integrations/focus/destinations/factory.py b/litellm/integrations/focus/destinations/factory.pyindex cb7696a11de..01ea6ca9cb4 100644--- a/litellm/integrations/focus/destinations/factory.py+++ b/litellm/integrations/focus/destinations/factory.py@@ -7,6 +7,7 @@ from typing import Any, Dict, Optionalfrom .base import FocusDestinationfrom .s3_destination import FocusS3Destination+from .vantage_destination import FocusVantageDestinationclass FocusDestinationFactory:@@ -26,6 +27,8 @@ class FocusDestinationFactory:)if provider_lower == "s3":return FocusS3Destination(prefix=prefix, config=normalized_config)+ if provider_lower == "vantage":+ return FocusVantageDestination(prefix=prefix, config=normalized_config)raise NotImplementedError(f"Provider '{provider}' not supported for Focus export")@@ -54,6 +57,24 @@ class FocusDestinationFactory:if not resolved.get("bucket_name"):raise ValueError("FOCUS_S3_BUCKET_NAME must be provided for S3 exports")return {k: v for k, v in resolved.items() if v is not None}+ if provider == "vantage":+ resolved = {+ "api_key": overrides.get("api_key")+ or os.getenv("VANTAGE_API_KEY"),+ "integration_token": overrides.get("integration_token")+ or os.getenv("VANTAGE_INTEGRATION_TOKEN"),+ "base_url": overrides.get("base_url")+ or os.getenv("VANTAGE_BASE_URL", "https://api.vantage.sh"),+ }+ if not resolved.get("api_key"):+ raise ValueError(+ "VANTAGE_API_KEY must be provided for Vantage exports"+ )+ if not resolved.get("integration_token"):+ raise ValueError(+ "VANTAGE_INTEGRATION_TOKEN must be provided for Vantage exports"+ )+ return {k: v for k, v in resolved.items() if v is not None}raise NotImplementedError(f"Provider '{provider}' not supported for Focus export configuration")diff --git a/litellm/integrations/focus/destinations/vantage_destination.py b/litellm/integrations/focus/destinations/vantage_destination.pynew file mode 100644index 00000000000..5612a513d66--- /dev/null+++ b/litellm/integrations/focus/destinations/vantage_destination.py@@ -0,0 +1,136 @@+"""Vantage API destination for Focus export."""++from __future__ import annotations++from typing import Any, Optional++import httpx++from litellm._logging import verbose_logger++from .base import FocusDestination, FocusTimeWindow++# Vantage enforces a 10,000-row / 2 MB limit per upload.+VANTAGE_MAX_ROWS_PER_UPLOAD = 10_000+VANTAGE_MAX_BYTES_PER_UPLOAD = 2 * 1024 * 1024 # 2 MB+++class FocusVantageDestination(FocusDestination):+ """Upload FOCUS CSV exports to the Vantage cost-import API."""++ def __init__(+ self,+ *,+ prefix: str,+ config: Optional[dict[str, Any]] = None,+ ) -> None:+ config = config or {}+ api_key = config.get("api_key")+ integration_token = config.get("integration_token")+ if not api_key:+ raise ValueError(+ "api_key must be provided for Vantage destination "+ "(set VANTAGE_API_KEY env var or pass in destination_config)"+ )+ if not integration_token:+ raise ValueError(+ "integration_token must be provided for Vantage destination "+ "(set VANTAGE_INTEGRATION_TOKEN env var or pass in destination_config)"+ )+ self.api_key = api_key+ self.integration_token = integration_token+ self.base_url = config.get(+ "base_url", "https://api.vantage.sh"+ )+ self.prefix = prefix++ async def deliver(+ self,+ *,+ content: bytes,+ time_window: FocusTimeWindow,+ filename: str,+ ) -> None:+ """Upload CSV content to the Vantage API, batching if needed."""+ if not content:+ verbose_logger.debug("Vantage destination: empty content, skipping upload")+ return++ # If the payload is within limits, send in one shot+ if len(content) <= VANTAGE_MAX_BYTES_PER_UPLOAD:+ await self._upload_csv(content, filename)+ return++ # Otherwise split into chunks by line count+ await self._upload_batched(content, filename)++ async def _upload_csv(self, csv_bytes: bytes, filename: str) -> None:+ url = (+ f"{self.base_url}/v2/integrations/"+ f"{self.integration_token}/costs.csv"+ )+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ }++ async with httpx.AsyncClient(timeout=60.0) as client:+ response = await client.post(+ url,+ headers=headers,+ files={"file": (filename, csv_bytes, "text/csv")},+ )+ response.raise_for_status()++ verbose_logger.debug(+ "Vantage destination: uploaded %d bytes (%s)",+ len(csv_bytes),+ filename,+ )++ async def _upload_batched(self, csv_bytes: bytes, filename: str) -> None:+ """Split the CSV into batches and upload each."""+ lines = csv_bytes.split(b"\n")+ header = lines[0]+ data_lines = [line for line in lines[1:] if line.strip()]++ batch_num = 0+ for start in range(0, len(data_lines), VANTAGE_MAX_ROWS_PER_UPLOAD):+ batch_lines = data_lines[start : start + VANTAGE_MAX_ROWS_PER_UPLOAD]+ batch_csv = header + b"\n" + b"\n".join(batch_lines) + b"\n"++ # If a single batch still exceeds 2 MB, split further by size+ if len(batch_csv) > VANTAGE_MAX_BYTES_PER_UPLOAD:+ await self._upload_size_limited(header, batch_lines, filename, batch_num)+ else:+ batch_filename = f"{filename}.part{batch_num}" if batch_num > 0 else filename+ await self._upload_csv(batch_csv, batch_filename)+ batch_num += 1++ async def _upload_size_limited(+ self,+ header: bytes,+ data_lines: list[bytes],+ filename: str,+ batch_offset: int,+ ) -> None:+ """Upload lines in chunks that stay under the 2 MB size limit."""+ current_chunk: list[bytes] = []+ current_size = len(header) + 1 # header + newline+ sub_batch = 0++ for line in data_lines:+ line_size = len(line) + 1 # line + newline+ if current_size + line_size > VANTAGE_MAX_BYTES_PER_UPLOAD and current_chunk:+ batch_csv = header + b"\n" + b"\n".join(current_chunk) + b"\n"+ batch_filename = f"{filename}.part{batch_offset}_{sub_batch}"+ await self._upload_csv(batch_csv, batch_filename)+ current_chunk = []+ current_size = len(header) + 1+ sub_batch += 1+ current_chunk.append(line)+ current_size += line_size++ if current_chunk:+ batch_csv = header + b"\n" + b"\n".join(current_chunk) + b"\n"+ batch_filename = f"{filename}.part{batch_offset}_{sub_batch}"+ await self._upload_csv(batch_csv, batch_filename)diff --git a/litellm/integrations/focus/export_engine.py b/litellm/integrations/focus/export_engine.pyindex 22ebce2a168..a9361d0e988 100644--- a/litellm/integrations/focus/export_engine.py+++ b/litellm/integrations/focus/export_engine.py@@ -10,7 +10,7 @@ from litellm._logging import verbose_loggerfrom .database import FocusLiteLLMDatabasefrom .destinations import FocusDestinationFactory, FocusTimeWindow-from .serializers import FocusParquetSerializer, FocusSerializer+from .serializers import FocusCsvSerializer, FocusParquetSerializer, FocusSerializerfrom .transformer import FocusTransformer@@ -38,9 +38,13 @@ class FocusExportEngine:self._database = FocusLiteLLMDatabase()def _init_serializer(self) -> FocusSerializer:- if self.export_format != "parquet":- raise NotImplementedError("Only parquet export supported currently")- return FocusParquetSerializer()+ if self.export_format == "csv":+ return FocusCsvSerializer()+ if self.export_format == "parquet":+ return FocusParquetSerializer()+ raise NotImplementedError(+ f"Export format '{self.export_format}' not supported. Use 'parquet' or 'csv'."+ )async def dry_run_export_usage_data(self, limit: Optional[int]) -> Dict[str, Any]:data = await self._database.get_usage_data(limit=limit)diff --git a/litellm/integrations/focus/schema.py b/litellm/integrations/focus/schema.pyindex ac2f33dad0a..6ad725f367d 100644--- a/litellm/integrations/focus/schema.py+++ b/litellm/integrations/focus/schema.py@@ -43,7 +43,7 @@ FOCUS_NORMALIZED_SCHEMA = pl.Schema(("SubAccountId", pl.String),("SubAccountName", pl.String),("SubAccountType", pl.String),- ("Tags", pl.Object),+ ("Tags", pl.String),])diff --git a/litellm/integrations/focus/serializers/__init__.py b/litellm/integrations/focus/serializers/__init__.pyindex 18187bf73e5..bdbf5204540 100644--- a/litellm/integrations/focus/serializers/__init__.py+++ b/litellm/integrations/focus/serializers/__init__.py@@ -1,6 +1,7 @@"""Serializer package exports for Focus integration."""from .base import FocusSerializer+from .csv import FocusCsvSerializerfrom .parquet import FocusParquetSerializer-__all__ = ["FocusSerializer", "FocusParquetSerializer"]+__all__ = ["FocusSerializer", "FocusCsvSerializer", "FocusParquetSerializer"]diff --git a/litellm/integrations/focus/serializers/csv.py b/litellm/integrations/focus/serializers/csv.pynew file mode 100644index 00000000000..30e7f3283db--- /dev/null+++ b/litellm/integrations/focus/serializers/csv.py@@ -0,0 +1,22 @@+"""CSV serializer for Focus export."""++from __future__ import annotations++import io++import polars as pl++from .base import FocusSerializer+++class FocusCsvSerializer(FocusSerializer):+ """Serialize normalized Focus frames to CSV bytes."""++ extension = "csv"++ def serialize(self, frame: pl.DataFrame) -> bytes:+ """Encode the provided frame as a CSV payload."""+ target = frame if not frame.is_empty() else pl.DataFrame(schema=frame.schema)+ buffer = io.BytesIO()+ target.write_csv(buffer)+ return buffer.getvalue()diff --git a/litellm/integrations/focus/transformer.py b/litellm/integrations/focus/transformer.pyindex cac12b7be14..1e4a17796db 100644--- a/litellm/integrations/focus/transformer.py+++ b/litellm/integrations/focus/transformer.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonfrom datetime import timedeltaimport polars as pl@@ -9,6 +10,29 @@ import polars as plfrom .schema import FOCUS_NORMALIZED_SCHEMA+def _build_tags_json(row: dict) -> str:+ """Build a JSON string of metadata tags from a DB row.++ Vantage uses this for Token Allocation — enriching billing data with+ team, user, and API key metadata.+ """+ tags: dict[str, str] = {}+ for key in (+ "team_id",+ "team_alias",+ "user_id",+ "user_email",+ "api_key_alias",+ "model",+ "model_group",+ "custom_llm_provider",+ ):+ val = row.get(key)+ if val is not None:+ tags[key] = str(val)+ return json.dumps(tags) if tags else "{}"++class FocusTransformer:"""Transforms LiteLLM DB rows into Focus-compatible schema."""@@ -19,6 +43,20 @@ class FocusTransformer:if frame.is_empty():return pl.DataFrame(schema=self.schema)+ # Build Tags JSON from metadata columns+ tag_col = "Tags"+ tag_keys = [+ "team_id", "team_alias", "user_id", "user_email",+ "api_key_alias", "model", "model_group", "custom_llm_provider",+ ]+ available_keys = [k for k in tag_keys if k in frame.columns]+ if available_keys:+ tags_series = frame.select(available_keys).to_dicts()+ tags_json = [_build_tags_json(row) for row in tags_series]+ frame = frame.with_columns(pl.Series(tag_col, tags_json))+ else:+ frame = frame.with_columns(pl.lit("{}").alias(tag_col))+# derive period start/end from usage dateframe = frame.with_columns(pl.col("date")@@ -86,5 +124,5 @@ class FocusTransformer:pl.col("team_id").cast(pl.String).alias("SubAccountId"),pl.col("team_alias").cast(pl.String).alias("SubAccountName"),none_str.alias("SubAccountType"),- none_str.alias("Tags"),+ pl.col(tag_col).cast(pl.String).alias("Tags"),)diff --git a/litellm/integrations/vantage/__init__.py b/litellm/integrations/vantage/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/litellm/integrations/vantage/vantage_logger.py b/litellm/integrations/vantage/vantage_logger.pynew file mode 100644index 00000000000..01529d537f7--- /dev/null+++ b/litellm/integrations/vantage/vantage_logger.py@@ -0,0 +1,105 @@+"""Vantage logger — thin wrapper around the Focus export pipeline.++Configures FocusLogger to use the Vantage API destination with CSV format+so users can simply set ``success_callback: ["vantage"]`` in their proxy config.+"""++from __future__ import annotations++import os+from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast++import litellm+from litellm._logging import verbose_logger+from litellm.integrations.custom_logger import CustomLogger+from litellm.integrations.focus.focus_logger import FocusLogger++if TYPE_CHECKING:+ from apscheduler.schedulers.asyncio import AsyncIOScheduler+else:+ AsyncIOScheduler = Any++VANTAGE_USAGE_DATA_JOB_NAME = "vantage_export_usage_data"+++class VantageLogger(FocusLogger):+ """FocusLogger pre-configured for Vantage (CSV format, Vantage API destination).++ Environment Variables:+ VANTAGE_API_KEY: Vantage API key for authentication+ VANTAGE_INTEGRATION_TOKEN: Vantage integration token for the cost-import endpoint+ VANTAGE_BASE_URL: Optional base URL override (default: https://api.vantage.sh)+ VANTAGE_EXPORT_FREQUENCY: Export frequency — "hourly" (default), "daily", or "interval"+ VANTAGE_EXPORT_INTERVAL_SECONDS: Interval in seconds when frequency is "interval"+ """++ def __init__(+ self,+ *,+ api_key: Optional[str] = None,+ integration_token: Optional[str] = None,+ base_url: Optional[str] = None,+ frequency: Optional[str] = None,+ interval_seconds: Optional[int] = None,+ **kwargs: Any,+ ) -> None:+ resolved_api_key = api_key or os.getenv("VANTAGE_API_KEY")+ resolved_token = integration_token or os.getenv("VANTAGE_INTEGRATION_TOKEN")+ resolved_base_url = base_url or os.getenv(+ "VANTAGE_BASE_URL", "https://api.vantage.sh"+ )+ resolved_frequency = (+ frequency or os.getenv("VANTAGE_EXPORT_FREQUENCY") or "hourly"+ ).lower()++ raw_interval = interval_seconds or os.getenv("VANTAGE_EXPORT_INTERVAL_SECONDS")+ resolved_interval = int(raw_interval) if raw_interval is not None else None++ destination_config: Dict[str, Any] = {}+ if resolved_api_key:+ destination_config["api_key"] = resolved_api_key+ if resolved_token:+ destination_config["integration_token"] = resolved_token+ if resolved_base_url:+ destination_config["base_url"] = resolved_base_url++ super().__init__(+ provider="vantage",+ export_format="csv",+ frequency=resolved_frequency,+ interval_seconds=resolved_interval,+ prefix="vantage_exports",+ destination_config=destination_config,+ **kwargs,+ )++ verbose_logger.debug(+ "VantageLogger initialized (integration_token=%s)",+ resolved_token[:8] + "..." if resolved_token else "None",+ )++ @staticmethod+ async def init_vantage_background_job(+ scheduler: AsyncIOScheduler,+ ) -> None:+ """Register the Vantage export job with the provided scheduler."""+ vantage_loggers: List[+ CustomLogger+ ] = litellm.logging_callback_manager.get_custom_loggers_for_type(+ callback_type=VantageLogger+ )+ if not vantage_loggers:+ verbose_logger.debug(+ "No Vantage logger registered; skipping scheduler"+ )+ return++ vantage_logger = cast(VantageLogger, vantage_loggers[0])+ trigger_kwargs = vantage_logger._build_scheduler_trigger()+ scheduler.add_job(+ vantage_logger.initialize_focus_export_job,+ **trigger_kwargs,+ )+++__all__ = ["VantageLogger"]diff --git a/litellm/litellm_core_utils/custom_logger_registry.py b/litellm/litellm_core_utils/custom_logger_registry.pyindex 2d483f78613..f873bfeece5 100644--- a/litellm/litellm_core_utils/custom_logger_registry.py+++ b/litellm/litellm_core_utils/custom_logger_registry.py@@ -24,6 +24,7 @@ from litellm.integrations.datadog.datadog_metrics import DatadogMetricsLoggerfrom litellm.integrations.deepeval import DeepEvalLoggerfrom litellm.integrations.dotprompt import DotpromptManagerfrom litellm.integrations.focus.focus_logger import FocusLogger+from litellm.integrations.vantage.vantage_logger import VantageLoggerfrom litellm.integrations.galileo import GalileoObservefrom litellm.integrations.gcs_bucket.gcs_bucket import GCSBucketLoggerfrom litellm.integrations.gcs_pubsub.pub_sub import GcsPubSubLogger@@ -99,6 +100,7 @@ class CustomLoggerRegistry:"gitlab": GitLabPromptManager,"cloudzero": CloudZeroLogger,"focus": FocusLogger,+ "vantage": VantageLogger,"posthog": PostHogLogger,}diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex f3bc4b08037..91196ce5b9a 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -473,6 +473,7 @@ from litellm.proxy.search_endpoints.search_tool_management import (router as search_tool_management_router,)from litellm.proxy.spend_tracking.cloudzero_endpoints import router as cloudzero_router+from litellm.proxy.spend_tracking.vantage_endpoints import router as vantage_routerfrom litellm.proxy.spend_tracking.spend_management_endpoints import (router as spend_management_router,)@@ -6127,6 +6128,15 @@ class ProxyStartupEvent:########################################################await FocusLogger.init_focus_export_background_job(scheduler=scheduler)+ ########################################################+ # Vantage Background Job+ ########################################################+ from litellm.integrations.vantage.vantage_logger import VantageLogger+ from litellm.proxy.spend_tracking.vantage_endpoints import is_vantage_setup++ if await is_vantage_setup():+ await VantageLogger.init_vantage_background_job(scheduler=scheduler)+######################################################### Prometheus Background Job########################################################@@ -13180,6 +13190,7 @@ app.include_router(project_router)app.include_router(customer_router)app.include_router(spend_management_router)app.include_router(cloudzero_router)+app.include_router(vantage_router)app.include_router(caching_router)app.include_router(analytics_router)app.include_router(guardrails_router)diff --git a/litellm/proxy/spend_tracking/vantage_endpoints.py b/litellm/proxy/spend_tracking/vantage_endpoints.pynew file mode 100644index 00000000000..842ca9a258f--- /dev/null+++ b/litellm/proxy/spend_tracking/vantage_endpoints.py@@ -0,0 +1,488 @@+import json++from fastapi import APIRouter, Depends, HTTPException++from litellm._logging import verbose_proxy_logger+from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker+from litellm.proxy._types import CommonProxyErrors, LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.common_utils.encrypt_decrypt_utils import (+ decrypt_value_helper,+ encrypt_value_helper,+)+from litellm.types.proxy.vantage_endpoints import (+ VantageExportRequest,+ VantageExportResponse,+ VantageInitRequest,+ VantageInitResponse,+ VantageSettingsUpdate,+ VantageSettingsView,+)++router = APIRouter()++_sensitive_masker = SensitiveDataMasker()++VANTAGE_SETTINGS_PARAM_NAME = "vantage_settings"+++async def _set_vantage_settings(+ api_key: str, integration_token: str, base_url: str+):+ """Store Vantage settings in the database with encrypted API key."""+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ raise HTTPException(+ status_code=500,+ detail={"error": CommonProxyErrors.db_not_connected_error.value},+ )++ encrypted_api_key = encrypt_value_helper(api_key)++ vantage_settings = {+ "api_key": encrypted_api_key,+ "integration_token": integration_token,+ "base_url": base_url,+ }++ await prisma_client.db.litellm_config.upsert(+ where={"param_name": VANTAGE_SETTINGS_PARAM_NAME},+ data={+ "create": {+ "param_name": VANTAGE_SETTINGS_PARAM_NAME,+ "param_value": json.dumps(vantage_settings),+ },+ "update": {"param_value": json.dumps(vantage_settings)},+ },+ )+++async def _get_vantage_settings():+ """Retrieve Vantage settings from the database with decrypted API key."""+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ raise HTTPException(+ status_code=500,+ detail={"error": CommonProxyErrors.db_not_connected_error.value},+ )++ vantage_config = await prisma_client.db.litellm_config.find_first(+ where={"param_name": VANTAGE_SETTINGS_PARAM_NAME}+ )+ if vantage_config is None or vantage_config.param_value is None:+ return {}++ if isinstance(vantage_config.param_value, dict):+ settings = vantage_config.param_value+ elif isinstance(vantage_config.param_value, str):+ settings = json.loads(vantage_config.param_value)+ else:+ settings = dict(vantage_config.param_value)++ encrypted_api_key = settings.get("api_key")+ if encrypted_api_key:+ decrypted_api_key = decrypt_value_helper(+ encrypted_api_key, key="vantage_api_key", exception_type="error"+ )+ if decrypted_api_key is None:+ raise HTTPException(+ status_code=500,+ detail={+ "error": "Failed to decrypt Vantage API key. Check your salt key configuration."+ },+ )+ settings["api_key"] = decrypted_api_key++ return settings+++ "/vantage/settings",+ tags=["Vantage"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=VantageSettingsView,+)+async def get_vantage_settings(+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ View current Vantage settings.++ Returns the current Vantage configuration with the API key masked for security.+ Only admin users can view Vantage settings.+ """+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail={"error": CommonProxyErrors.not_allowed_access.value},+ )++ try:+ settings = await _get_vantage_settings()++ if not settings:+ return VantageSettingsView(+ api_key_masked=None,+ integration_token=None,+ base_url=None,+ status=None,+ )++ masked_settings = _sensitive_masker.mask_dict(settings)++ return VantageSettingsView(+ api_key_masked=masked_settings.get("api_key"),+ integration_token=settings.get("integration_token"),+ base_url=settings.get("base_url"),+ status="configured",+ )++ except HTTPException:+ raise+ except Exception as e:+ verbose_proxy_logger.error(f"Error retrieving Vantage settings: {str(e)}")+ raise HTTPException(+ status_code=500,+ detail={"error": f"Failed to retrieve Vantage settings: {str(e)}"},+ )+++ "/vantage/settings",+ tags=["Vantage"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=VantageInitResponse,+)+async def update_vantage_settings(+ request: VantageSettingsUpdate,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Update existing Vantage settings.++ Allows updating individual Vantage configuration fields without requiring all fields.+ Only admin users can update Vantage settings.+ """+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail={"error": CommonProxyErrors.not_allowed_access.value},+ )++ if not any([request.api_key, request.integration_token, request.base_url]):+ raise HTTPException(+ status_code=400,+ detail={"error": "At least one field must be provided for update"},+ )++ try:+ current_settings = await _get_vantage_settings()++ updated_api_key = (+ request.api_key+ if request.api_key is not None+ else current_settings["api_key"]+ )+ updated_token = (+ request.integration_token+ if request.integration_token is not None+ else current_settings["integration_token"]+ )+ updated_base_url = (+ request.base_url+ if request.base_url is not None+ else current_settings["base_url"]+ )++ await _set_vantage_settings(+ api_key=updated_api_key,+ integration_token=updated_token,+ base_url=updated_base_url,+ )++ verbose_proxy_logger.info("Vantage settings updated successfully")++ return VantageInitResponse(+ message="Vantage settings updated successfully", status="success"+ )++ except HTTPException as e:+ if e.status_code == 400:+ raise HTTPException(+ status_code=404,+ detail={+ "error": "Vantage settings not found. Please initialize settings first using /vantage/init"+ },+ )+ raise+ except Exception as e:+ verbose_proxy_logger.error(f"Error updating Vantage settings: {str(e)}")+ raise HTTPException(+ status_code=500,+ detail={"error": f"Failed to update Vantage settings: {str(e)}"},+ )+++async def is_vantage_setup_in_db() -> bool:+ """Check if Vantage is setup in the database."""+ try:+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ return False++ vantage_config = await prisma_client.db.litellm_config.find_first(+ where={"param_name": VANTAGE_SETTINGS_PARAM_NAME}+ )++ return vantage_config is not None and vantage_config.param_value is not None++ except Exception as e:+ verbose_proxy_logger.error(f"Error checking Vantage status: {str(e)}")+ return False+++def is_vantage_setup_in_config() -> bool:+ """Check if Vantage is setup in config.yaml or environment variables."""+ import litellm++ return "vantage" in litellm.callbacks+++async def is_vantage_setup() -> bool:+ """Check if Vantage is setup in either config or database."""+ try:+ if is_vantage_setup_in_config():+ return True+ if await is_vantage_setup_in_db():+ return True+ return False+ except Exception as e:+ verbose_proxy_logger.error(f"Error checking Vantage setup: {str(e)}")+ return False+++ "/vantage/init",+ tags=["Vantage"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=VantageInitResponse,+)+async def init_vantage_settings(+ request: VantageInitRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Initialize Vantage settings and store in the database.++ Parameters:+ - api_key: Vantage API key for authentication+ - integration_token: Vantage integration token for the cost-import endpoint+ - base_url: Vantage API base URL (default: https://api.vantage.sh)++ Only admin users can configure Vantage settings.+ """+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail={"error": CommonProxyErrors.not_allowed_access.value},+ )++ try:+ await _set_vantage_settings(+ api_key=request.api_key,+ integration_token=request.integration_token,+ base_url=request.base_url,+ )++ verbose_proxy_logger.info("Vantage settings initialized successfully")++ return VantageInitResponse(+ message="Vantage settings initialized successfully", status="success"+ )++ except Exception as e:+ verbose_proxy_logger.error(+ f"Error initializing Vantage settings: {str(e)}"+ )+ raise HTTPException(+ status_code=500,+ detail={"error": f"Failed to initialize Vantage settings: {str(e)}"},+ )+++ "/vantage/dry-run",+ tags=["Vantage"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=VantageExportResponse,+)+async def vantage_dry_run_export(+ request: VantageExportRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Perform a dry run export using the Vantage logger.++ Returns the data that would be exported without actually sending it to Vantage.++ Parameters:+ - limit: Optional limit on number of records to process (default: 500)++ Only admin users can perform Vantage exports.+ """+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail={"error": CommonProxyErrors.not_allowed_access.value},+ )++ try:+ from litellm.integrations.vantage.vantage_logger import VantageLogger++ logger = VantageLogger()+ dry_run_result = await logger.dry_run_export_usage_data(+ limit=request.limit+ )++ verbose_proxy_logger.info("Vantage dry run export completed successfully")++ return VantageExportResponse(+ message="Vantage dry run export completed successfully.",+ status="success",+ dry_run_data=dry_run_result,+ summary=dry_run_result.get("summary") if dry_run_result else None,+ )++ except Exception as e:+ verbose_proxy_logger.error(+ f"Error performing Vantage dry run export: {str(e)}"+ )+ raise HTTPException(+ status_code=500,+ detail={+ "error": f"Failed to perform Vantage dry run export: {str(e)}"+ },+ )+++ "/vantage/export",+ tags=["Vantage"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=VantageExportResponse,+)+async def vantage_export(+ request: VantageExportRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Perform an actual export using the Vantage logger.++ Exports usage data in FOCUS CSV format to the Vantage API.++ Parameters:+ - limit: Optional limit on number of records to export+ - start_time_utc: Optional start time for data export+ - end_time_utc: Optional end time for data export++ Only admin users can perform Vantage exports.+ """+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail={"error": CommonProxyErrors.not_allowed_access.value},+ )++ try:+ settings = await _get_vantage_settings()++ from litellm.integrations.vantage.vantage_logger import VantageLogger++ logger = VantageLogger(+ api_key=settings.get("api_key"),+ integration_token=settings.get("integration_token"),+ base_url=settings.get("base_url"),+ )+ await logger.export_usage_data(+ limit=request.limit,+ start_time_utc=request.start_time_utc,+ end_time_utc=request.end_time_utc,+ )++ verbose_proxy_logger.info("Vantage export completed successfully")++ return VantageExportResponse(+ message="Vantage export completed successfully",+ status="success",+ dry_run_data=None,+ summary=None,+ )++ except Exception as e:+ verbose_proxy_logger.error(f"Error performing Vantage export: {str(e)}")+ raise HTTPException(+ status_code=500,+ detail={"error": f"Failed to perform Vantage export: {str(e)}"},+ )+++ "/vantage/delete",+ tags=["Vantage"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=VantageInitResponse,+)+async def delete_vantage_settings(+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Delete Vantage settings from the database.++ Only admin users can delete Vantage settings.+ """+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail={"error": CommonProxyErrors.not_allowed_access.value},+ )++ try:+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ raise HTTPException(+ status_code=500,+ detail={"error": CommonProxyErrors.db_not_connected_error.value},+ )++ vantage_config = await prisma_client.db.litellm_config.find_first(+ where={"param_name": VANTAGE_SETTINGS_PARAM_NAME}+ )++ if vantage_config is None:+ raise HTTPException(+ status_code=404,+ detail={"error": "Vantage settings not found"},+ )++ await prisma_client.db.litellm_config.delete(+ where={"param_name": VANTAGE_SETTINGS_PARAM_NAME}+ )++ verbose_proxy_logger.info("Vantage settings deleted successfully")++ return VantageInitResponse(+ message="Vantage settings deleted successfully", status="success"+ )++ except HTTPException:+ raise+ except Exception as e:+ verbose_proxy_logger.error(f"Error deleting Vantage settings: {str(e)}")+ raise HTTPException(+ status_code=500,+ detail={"error": f"Failed to delete Vantage settings: {str(e)}"},+ )diff --git a/litellm/types/proxy/vantage_endpoints.py b/litellm/types/proxy/vantage_endpoints.pynew file mode 100644index 00000000000..394677d1e8f--- /dev/null+++ b/litellm/types/proxy/vantage_endpoints.py@@ -0,0 +1,81 @@+"""+Vantage endpoint types for LiteLLM Proxy+"""++from datetime import datetime+from typing import Any, Dict, Optional++from pydantic import BaseModel, Field+++class VantageInitRequest(BaseModel):+ """Request model for initializing Vantage settings"""++ api_key: str = Field(..., description="Vantage API key for authentication")+ integration_token: str = Field(+ ..., description="Vantage integration token for the cost-import endpoint"+ )+ base_url: str = Field(+ default="https://api.vantage.sh",+ description="Vantage API base URL (default: https://api.vantage.sh)",+ )+++class VantageInitResponse(BaseModel):+ """Response model for Vantage initialization"""++ message: str+ status: str+++class VantageExportRequest(BaseModel):+ """Request model for Vantage export operations"""++ limit: Optional[int] = Field(+ None, description="Optional limit on number of records to export"+ )+ start_time_utc: Optional[datetime] = Field(+ None, description="Start time for data export in UTC"+ )+ end_time_utc: Optional[datetime] = Field(+ None, description="End time for data export in UTC"+ )+++class VantageExportResponse(BaseModel):+ """Response model for Vantage export operations"""++ message: str+ status: str+ dry_run_data: Optional[Dict[str, Any]] = Field(+ None, description="Dry run data including usage data and FOCUS transformed data"+ )+ summary: Optional[Dict[str, Any]] = Field(+ None, description="Summary statistics for dry run"+ )+++class VantageSettingsView(BaseModel):+ """Response model for viewing Vantage settings with masked API key"""++ api_key_masked: Optional[str] = Field(+ None,+ description="Masked API key showing only first 4 and last 4 characters",+ )+ integration_token: Optional[str] = Field(+ None, description="Vantage integration token"+ )+ base_url: Optional[str] = Field(None, description="Vantage API base URL")+ status: Optional[str] = Field(None, description="Configuration status")+++class VantageSettingsUpdate(BaseModel):+ """Request model for updating Vantage settings"""++ api_key: Optional[str] = Field(+ None, description="New Vantage API key for authentication"+ )+ integration_token: Optional[str] = Field(+ None, description="New Vantage integration token"+ )+ base_url: Optional[str] = Field(None, description="New Vantage API base URL")diff --git a/tests/test_litellm/integrations/focus/test_csv_serializer.py b/tests/test_litellm/integrations/focus/test_csv_serializer.pynew file mode 100644index 00000000000..f527a9dceb1--- /dev/null+++ b/tests/test_litellm/integrations/focus/test_csv_serializer.py@@ -0,0 +1,34 @@+"""Tests for FocusCsvSerializer."""++from __future__ import annotations++import polars as pl++from litellm.integrations.focus.serializers.csv import FocusCsvSerializer+++def test_should_serialize_dataframe_to_csv():+ frame = pl.DataFrame({"BilledCost": [1.5, 2.0], "ServiceName": ["openai", "anthropic"]})+ serializer = FocusCsvSerializer()+ result = serializer.serialize(frame)++ assert isinstance(result, bytes)+ lines = result.decode("utf-8").strip().split("\n")+ assert lines[0] == "BilledCost,ServiceName"+ assert len(lines) == 3 # header + 2 data rows+++def test_should_return_header_only_for_empty_frame():+ frame = pl.DataFrame(+ schema={"BilledCost": pl.Float64, "ServiceName": pl.Utf8}+ )+ serializer = FocusCsvSerializer()+ result = serializer.serialize(frame)++ lines = result.decode("utf-8").strip().split("\n")+ assert lines[0] == "BilledCost,ServiceName"+ assert len(lines) == 1 # header only+++def test_extension_should_be_csv():+ assert FocusCsvSerializer.extension == "csv"diff --git a/tests/test_litellm/integrations/focus/test_destination_factory.py b/tests/test_litellm/integrations/focus/test_destination_factory.pynew file mode 100644index 00000000000..4888e8231b1--- /dev/null+++ b/tests/test_litellm/integrations/focus/test_destination_factory.py@@ -0,0 +1,48 @@+"""Tests for FocusDestinationFactory with vantage provider."""++from __future__ import annotations++import pytest++from litellm.integrations.focus.destinations.factory import FocusDestinationFactory+from litellm.integrations.focus.destinations.vantage_destination import (+ FocusVantageDestination,+)+++def test_should_create_vantage_destination():+ dest = FocusDestinationFactory.create(+ provider="vantage",+ prefix="exports",+ config={+ "api_key": "test-key",+ "integration_token": "test-token",+ },+ )+ assert isinstance(dest, FocusVantageDestination)+++def test_should_raise_when_vantage_missing_api_key():+ with pytest.raises(ValueError, match="VANTAGE_API_KEY"):+ FocusDestinationFactory.create(+ provider="vantage",+ prefix="exports",+ config={"integration_token": "tok"},+ )+++def test_should_raise_when_vantage_missing_token():+ with pytest.raises(ValueError, match="VANTAGE_INTEGRATION_TOKEN"):+ FocusDestinationFactory.create(+ provider="vantage",+ prefix="exports",+ config={"api_key": "key"},+ )+++def test_should_raise_for_unsupported_provider():+ with pytest.raises(NotImplementedError):+ FocusDestinationFactory.create(+ provider="unknown_provider",+ prefix="exports",+ )diff --git a/tests/test_litellm/integrations/focus/test_vantage_destination.py b/tests/test_litellm/integrations/focus/test_vantage_destination.pynew file mode 100644index 00000000000..181d3d13811--- /dev/null+++ b/tests/test_litellm/integrations/focus/test_vantage_destination.py@@ -0,0 +1,138 @@+"""Tests for FocusVantageDestination behavior."""++from __future__ import annotations++from datetime import datetime, timezone+from typing import Any, Dict, List+from unittest.mock import AsyncMock, patch++import pytest++from litellm.integrations.focus.destinations.base import FocusTimeWindow+from litellm.integrations.focus.destinations.vantage_destination import (+ FocusVantageDestination,+ VANTAGE_MAX_BYTES_PER_UPLOAD,+)+++def _window(freq: str = "hourly", hour: int = 5) -> FocusTimeWindow:+ start = datetime(2024, 1, 2, hour, tzinfo=timezone.utc)+ end = start.replace(hour=hour + 1)+ return FocusTimeWindow(start_time=start, end_time=end, frequency=freq)+++def _config(**overrides: Any) -> dict[str, Any]:+ base = {+ "api_key": "test-api-key",+ "integration_token": "test-token-123",+ }+ base.update(overrides)+ return base+++def test_should_require_api_key():+ with pytest.raises(ValueError, match="api_key"):+ FocusVantageDestination(+ prefix="exports",+ config={"integration_token": "tok"},+ )+++def test_should_require_integration_token():+ with pytest.raises(ValueError, match="integration_token"):+ FocusVantageDestination(+ prefix="exports",+ config={"api_key": "key"},+ )+++def test_should_initialize_with_valid_config():+ dest = FocusVantageDestination(prefix="exports", config=_config())+ assert dest.api_key == "test-api-key"+ assert dest.integration_token == "test-token-123"+ assert dest.base_url == "https://api.vantage.sh"+++def test_should_use_custom_base_url():+ dest = FocusVantageDestination(+ prefix="exports",+ config=_config(base_url="https://custom.vantage.sh"),+ )+ assert dest.base_url == "https://custom.vantage.sh"+++async def test_should_skip_empty_content():+ dest = FocusVantageDestination(prefix="exports", config=_config())+ # Should not raise+ await dest.deliver(content=b"", time_window=_window(), filename="usage.csv")+++async def test_should_upload_csv_to_correct_url():+ dest = FocusVantageDestination(prefix="exports", config=_config())+ captured: Dict[str, Any] = {}++ mock_response = AsyncMock()+ mock_response.raise_for_status = lambda: None++ mock_client = AsyncMock()+ mock_client.post = AsyncMock(return_value=mock_response)+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=False)++ with patch("litellm.integrations.focus.destinations.vantage_destination.httpx.AsyncClient", return_value=mock_client):+ await dest.deliver(+ content=b"header\nrow1\n",+ time_window=_window(),+ filename="usage.csv",+ )++ mock_client.post.assert_called_once()+ call_args = mock_client.post.call_args+ assert "test-token-123" in call_args[0][0]+ assert "costs.csv" in call_args[0][0]+ assert call_args[1]["headers"]["Authorization"] == "Bearer test-api-key"+++async def test_should_batch_large_content():+ dest = FocusVantageDestination(prefix="exports", config=_config())++ # Create content larger than 2 MB+ header = b"col1,col2,col3"+ row = b"a" * 100 + b"," + b"b" * 100 + b"," + b"c" * 100+ num_rows = (VANTAGE_MAX_BYTES_PER_UPLOAD // len(row)) + 100+ large_content = header + b"\n" + b"\n".join([row] * num_rows) + b"\n"++ assert len(large_content) > VANTAGE_MAX_BYTES_PER_UPLOAD++ upload_calls: List[bytes] = []++ mock_response = AsyncMock()+ mock_response.raise_for_status = lambda: None++ mock_client = AsyncMock()+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=False)++ async def capture_post(url, **kwargs):+ files = kwargs.get("files", {})+ if "file" in files:+ upload_calls.append(files["file"][1])+ return mock_response++ mock_client.post = capture_post++ with patch("litellm.integrations.focus.destinations.vantage_destination.httpx.AsyncClient", return_value=mock_client):+ await dest.deliver(+ content=large_content,+ time_window=_window(),+ filename="usage.csv",+ )++ # Should have made multiple uploads+ assert len(upload_calls) > 1+ # Each upload should be within limits+ for chunk in upload_calls:+ assert len(chunk) <= VANTAGE_MAX_BYTES_PER_UPLOAD