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] AI Gateway - Add support for Platform Fee / Margins (#18427)

Ishaan Jaff1123cfa9283d
diff --git a/docs/my-website/docs/proxy/custom_pricing.md b/docs/my-website/docs/proxy/custom_pricing.md
index 4698889786b..f6762f5e45c 100644
--- a/docs/my-website/docs/proxy/custom_pricing.md
+++ b/docs/my-website/docs/proxy/custom_pricing.md
@@ -9,7 +9,8 @@ LiteLLM provides flexible cost tracking and pricing customization for all LLM pr
- **Custom Pricing** - Override default model costs or set pricing for custom models
- **Cost Per Token** - Track costs based on input/output tokens (most common)
- **Cost Per Second** - Track costs based on runtime (e.g., Sagemaker)
-- **Provider Discounts** - Apply percentage-based discounts to specific providers
+- **[Provider Discounts](./provider_discounts.md)** - Apply percentage-based discounts to specific providers
+- **[Provider Margins](./provider_margins.md)** - Add fees/margins to LLM costs for internal billing
- **Base Model Mapping** - Ensure accurate cost tracking for Azure deployments
By default, the response cost is accessible in the logging object via `kwargs["response_cost"]` on success (sync + async). [**Learn More**](../observability/custom_callback.md)
@@ -66,58 +67,6 @@ model_list:
output_cost_per_token: 0.000520 # 👈 ONLY to track cost per token
```
-## Provider-Specific Cost Discounts
-
-Apply percentage-based discounts to specific providers (e.g., negotiated enterprise pricing).
-
-#### Usage with LiteLLM Proxy Server
-
-**Step 1: Add discount config to config.yaml**
-
-```yaml
-# Apply 5% discount to all Vertex AI and Gemini costs
-cost_discount_config:
- vertex_ai: 0.05 # 5% discount
- gemini: 0.05 # 5% discount
- openrouter: 0.05 # 5% discount
- # openai: 0.10 # 10% discount (example)
-```
-
-**Step 2: Start proxy**
-
-```bash
-litellm /path/to/config.yaml
-```
-
-The discount will be automatically applied to all cost calculations for the configured providers.
-
-
-#### How Discounts Work
-
-- Discounts are applied **after** all other cost calculations (tokens, caching, tools, etc.)
-- The discount is a percentage (0.05 = 5%, 0.10 = 10%, etc.)
-- Discounts only apply to the configured providers
-- Original cost, discount amount, and final cost are tracked in cost breakdown logs
-- Discount information is returned in response headers:
- - `x-litellm-response-cost` - Final cost after discount
- - `x-litellm-response-cost-original` - Cost before discount
- - `x-litellm-response-cost-discount-amount` - Discount amount in USD
-
-#### Supported Providers
-
-You can apply discounts to all LiteLLM supported providers. Common examples:
-
-- `vertex_ai` - Google Vertex AI
-- `gemini` - Google Gemini
-- `openai` - OpenAI
-- `anthropic` - Anthropic
-- `azure` - Azure OpenAI
-- `bedrock` - AWS Bedrock
-- `cohere` - Cohere
-- `openrouter` - OpenRouter
-
-See the full list of providers in the [LlmProviders](https://github.com/BerriAI/litellm/blob/main/litellm/types/utils.py) enum.
-
## Override Model Cost Map
You can override [our model cost map](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json) with your own custom pricing for a mapped model.
diff --git a/docs/my-website/docs/proxy/provider_discounts.md b/docs/my-website/docs/proxy/provider_discounts.md
new file mode 100644
index 00000000000..b9a77fcc55e
--- /dev/null
+++ b/docs/my-website/docs/proxy/provider_discounts.md
@@ -0,0 +1,52 @@
+# Provider Discounts
+
+Apply percentage-based discounts to specific providers. This is useful for negotiated enterprise pricing with providers.
+
+## Usage with LiteLLM Proxy Server
+
+**Step 1: Add discount config to config.yaml**
+
+```yaml
+# Apply 5% discount to all Vertex AI and Gemini costs
+cost_discount_config:
+ vertex_ai: 0.05 # 5% discount
+ gemini: 0.05 # 5% discount
+ openrouter: 0.05 # 5% discount
+ # openai: 0.10 # 10% discount (example)
+```
+
+**Step 2: Start proxy**
+
+```bash
+litellm /path/to/config.yaml
+```
+
+The discount will be automatically applied to all cost calculations for the configured providers.
+
+
+## How Discounts Work
+
+- Discounts are applied **after** all other cost calculations (tokens, caching, tools, etc.)
+- The discount is a percentage (0.05 = 5%, 0.10 = 10%, etc.)
+- Discounts only apply to the configured providers
+- Original cost, discount amount, and final cost are tracked in cost breakdown logs
+- Discount information is returned in response headers:
+ - `x-litellm-response-cost` - Final cost after discount
+ - `x-litellm-response-cost-original` - Cost before discount
+ - `x-litellm-response-cost-discount-amount` - Discount amount in USD
+
+## Supported Providers
+
+You can apply discounts to all LiteLLM supported providers. Common examples:
+
+- `vertex_ai` - Google Vertex AI
+- `gemini` - Google Gemini
+- `openai` - OpenAI
+- `anthropic` - Anthropic
+- `azure` - Azure OpenAI
+- `bedrock` - AWS Bedrock
+- `cohere` - Cohere
+- `openrouter` - OpenRouter
+
+See the full list of providers in the [LlmProviders](https://github.com/BerriAI/litellm/blob/main/litellm/types/utils.py) enum.
+
diff --git a/docs/my-website/docs/proxy/provider_margins.md b/docs/my-website/docs/proxy/provider_margins.md
new file mode 100644
index 00000000000..d6da15d4f95
--- /dev/null
+++ b/docs/my-website/docs/proxy/provider_margins.md
@@ -0,0 +1,214 @@
+# Fee/Price Margin on LLM Costs
+
+Apply percentage-based or fixed-amount margins to specific providers or globally. This is useful for enterprises that need to add operational overhead costs to bill internal consumers.
+
+## When to Use This Feature
+
+If your Generative AI platform involves various operational and architectural overheads, along with infrastructure costs, you may need the capability to apply an additional fee or margin to the total LLM costs.
+
+**Common use cases:**
+- **Internal chargebacks** - Add operational overhead costs when billing internal teams
+- **Cost recovery** - Recover infrastructure, support, and platform maintenance costs
+
+## Setup Margins via UI
+
+This walkthrough shows how to add a provider margin and view the cost breakdown in the LiteLLM UI.
+
+### Step 1: Navigate to Settings
+
+From the LiteLLM dashboard, click on **Settings** in the left sidebar.
+
+![Click Settings](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/a9a42382-1c93-4338-8c7e-c0ebc4ee239f/ascreenshot.jpeg?tl_px=0,730&br_px=2064,1884&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=47,292)
+
+### Step 2: Open Cost Tracking
+
+Click on **Cost Tracking** to access the cost configuration options.
+
+![Click Cost Tracking](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/c3ad52c0-1c8d-4be5-bd04-1e37ce186c8e/ascreenshot.jpeg?tl_px=0,730&br_px=2064,1884&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=65,403)
+
+### Step 3: Select Fee/Price Margin
+
+Click on **Fee/Price Margin** - this section allows you to add fees or margins to LLM costs for internal billing and cost recovery.
+
+![Click Fee/Price Margin](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/0810c7bf-e927-4ab6-a55d-37c51d8c17af/ascreenshot.jpeg?tl_px=553,0&br_px=2618,1153&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=551,220)
+
+### Step 4: Add Provider Margin
+
+Click **+ Add Provider Margin** to create a new margin configuration.
+
+![Click Add Provider Margin](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/8762b7d9-74e5-45eb-acc3-be0d9c5b799d/ascreenshot.jpeg?tl_px=553,2&br_px=2618,1155&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=929,277)
+
+### Step 5: Select Provider
+
+Click the search field to select which provider to apply the margin to.
+
+![Click search field](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/7ff01cdc-2749-43f3-a46f-4fd5543446e3/ascreenshot.jpeg?tl_px=507,0&br_px=2572,1153&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=524,177)
+
+You can select **Global (All Providers)** to apply the margin to all providers, or choose a specific provider like Bedrock, OpenAI, or Anthropic.
+
+![Select Global](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/c9efe187-0995-45ae-9366-290cb20835a2/ascreenshot.jpeg?tl_px=0,0&br_px=2064,1153&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=485,182)
+
+In this example, we'll select **Bedrock** as the provider.
+
+![Select Bedrock](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/ea1524ed-7217-4ee6-9beb-797e3ff08b3a/ascreenshot.jpeg?tl_px=0,0&br_px=2617,1462&force_format=jpeg&q=100&width=1120.0)
+
+### Step 6: Choose Margin Type
+
+Select the margin type. You can choose between **Percentage-based** (e.g., 10% markup) or **Fixed Amount** (e.g., $0.001 per request).
+
+![Click Percentage-based](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/137ffea5-0a5e-445a-809f-a85d20701c87/ascreenshot.jpeg?tl_px=0,0&br_px=2064,1153&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=355,259)
+
+For this example, we'll select **Fixed Amount** to add a flat fee per request.
+
+![Click Fixed Amount](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/56828562-2bae-4f69-b68e-13b1b6a03aa6/ascreenshot.jpeg?tl_px=0,0&br_px=2064,1153&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=493,252)
+
+### Step 7: Enter Margin Value
+
+Enter the margin value. In this example, we're adding a $25 fixed fee per request.
+
+![Enter margin value](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/80018d4b-0205-43a3-a534-9a0e39ddf139/ascreenshot.jpeg?tl_px=0,0&br_px=2618,1462&force_format=jpeg&q=100&width=1120.0)
+
+### Step 8: Save the Margin
+
+Click **Add Provider Margin** to save your configuration.
+
+![Click Add Provider Margin](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/84a5bcb8-f475-4aef-83ec-f0b3b620613f/ascreenshot.jpeg?tl_px=553,206&br_px=2618,1359&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=636,276)
+
+### Step 9: Test the Margin in Playground
+
+Navigate to **Playground** to test your margin configuration by making a request.
+
+![Click Playground](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/cda7293a-2439-4301-bc44-211e6d6833a6/ascreenshot.jpeg?tl_px=0,0&br_px=2064,1153&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=37,106)
+
+Select a model and send a test message.
+
+![Send test message](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/48c3e28e-a01a-483c-838d-2d1643f44be7/ascreenshot.jpeg?tl_px=0,0&br_px=2617,1462&force_format=jpeg&q=100&width=1120.0)
+
+Enter your prompt in the message field and submit.
+
+![Enter prompt](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/88963dbe-6bad-4aac-8bd3-7f4eac0dd995/ascreenshot.jpeg?tl_px=243,730&br_px=2308,1884&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=524,451)
+
+You'll receive a response from the model.
+
+![View response](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/1d69ef9c-cc22-40ad-8f10-f14a359d2fb6/ascreenshot.jpeg?tl_px=553,17&br_px=2618,1170&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=549,276)
+
+### Step 10: View Cost Breakdown in Logs
+
+Navigate to **Logs** to view the detailed cost breakdown for your request.
+
+![Click Logs](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/5cf6dd8b-0783-41ee-b23a-32f3424c2092/ascreenshot.jpeg?tl_px=0,99&br_px=2064,1252&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=32,276)
+
+Click on the expand icon to view the request details.
+
+![Click expand icon](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/3ae2900f-1515-4bb9-a4aa-328b43f13b61/ascreenshot.jpeg?tl_px=0,12&br_px=2064,1165&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=187,277)
+
+### Step 11: View Cost Breakdown Details
+
+Click on **Cost Breakdown** to see how the total cost was calculated, including the margin.
+
+![Click Cost Breakdown](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/8bce9050-58ca-4860-9e18-1b704e086cf4/ascreenshot.jpeg?tl_px=392,575&br_px=2457,1728&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=524,276)
+
+The cost breakdown shows the margin amount that was added. In this example, you can see the **+$25.00** margin clearly displayed.
+
+![View margin amount](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/c4a65d38-a47a-4634-baf2-608447a7d711/ascreenshot.jpeg?tl_px=0,730&br_px=2064,1884&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=388,282)
+
+The total cost reflects the base LLM cost plus the margin, giving you full transparency into your cost structure.
+
+![View total cost](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-25/3b13550d-5255-4818-b3ee-3d4391991c13/ascreenshot.jpeg?tl_px=0,730&br_px=2064,1884&force_format=jpeg&q=100&width=1120.0&wat=1&wat_opacity=0.7&wat_gravity=northwest&wat_url=https://colony-recorder.s3.us-west-1.amazonaws.com/images/watermarks/FB923C_standard.png&wat_pad=384,323)
+
+## Setup Margins via Config
+
+You can also configure margins directly in your `config.yaml` file.
+
+**Step 1: Add margin config to config.yaml**
+
+```yaml
+# Apply margins to providers
+cost_margin_config:
+ global: 0.05 # 5% global margin on all providers
+ openai: 0.10 # 10% margin for OpenAI (overrides global)
+ anthropic:
+ fixed_amount: 0.001 # $0.001 fixed fee per request
+```
+
+**Step 2: Start proxy**
+
+```bash
+litellm /path/to/config.yaml
+```
+
+The margin will be automatically applied to all cost calculations for the configured providers.
+
+## How Margins Work
+
+- Margins are applied **after** discounts (if configured)
+- Margins are calculated independently from discounts
+- You can use:
+ - **Percentage-based**: `{"openai": 0.10}` = 10% margin
+ - **Fixed amount**: `{"openai": {"fixed_amount": 0.001}}` = $0.001 per request
+ - **Global**: `{"global": 0.05}` = 5% margin on all providers (unless provider-specific margin exists)
+- Provider-specific margins override global margins
+- Margin information is tracked in cost breakdown logs
+- Margin information is returned in response headers:
+ - `x-litellm-response-cost-margin-amount` - Total margin added in USD
+ - `x-litellm-response-cost-margin-percent` - Margin percentage applied
+
+## Margin Calculation Examples
+
+**Example 1: Percentage-only margin**
+```yaml
+cost_margin_config:
+ openai: 0.10 # 10% margin
+```
+If base cost is $1.00, final cost = $1.00 x 1.10 = $1.10
+
+**Example 2: Fixed amount only**
+```yaml
+cost_margin_config:
+ anthropic:
+ fixed_amount: 0.001 # $0.001 per request
+```
+If base cost is $1.00, final cost = $1.00 + $0.001 = $1.001
+
+**Example 3: Global margin with provider override**
+```yaml
+cost_margin_config:
+ global: 0.05 # 5% global margin
+ openai: 0.10 # 10% margin for OpenAI (overrides global)
+```
+- OpenAI requests: 10% margin applied
+- All other providers: 5% margin applied
+
+## Margins with Discounts
+
+Margins and discounts are calculated independently:
+
+1. Base cost is calculated
+2. Discount is applied (if configured)
+3. Margin is applied to the discounted cost
+
+**Example:**
+```yaml
+cost_discount_config:
+ openai: 0.05 # 5% discount
+cost_margin_config:
+ openai: 0.10 # 10% margin
+```
+
+If base cost is $1.00:
+- After discount: $1.00 x 0.95 = $0.95
+- After margin: $0.95 x 1.10 = $1.045
+
+## Supported Providers
+
+You can apply margins to all LiteLLM supported providers, or use `global` to apply to all providers. Common examples:
+
+- `global` - Applies to all providers (unless provider-specific margin exists)
+- `openai` - OpenAI
+- `anthropic` - Anthropic
+- `vertex_ai` - Google Vertex AI
+- `gemini` - Google Gemini
+- `azure` - Azure OpenAI
+- `bedrock` - AWS Bedrock
+
+See the full list of providers in the [LlmProviders](https://github.com/BerriAI/litellm/blob/main/litellm/types/utils.py) enum.
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index c1d8387ec58..2d3c9d8a650 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -390,6 +390,8 @@ const sidebars = {
items: [
"proxy/cost_tracking",
"proxy/custom_pricing",
+ "proxy/provider_margins",
+ "proxy/provider_discounts",
"proxy/sync_models_github",
"proxy/billing",
],
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 02d7fef749b..a32d2d3ef90 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -420,6 +420,13 @@ model_cost = get_model_cost_map(url=model_cost_map_url)
cost_discount_config: Dict[str, float] = (
{}
) # Provider-specific cost discounts {"vertex_ai": 0.05} = 5% discount
+cost_margin_config: Dict[str, Union[float, Dict[str, float]]] = (
+ {}
+) # Provider-specific or global cost margins. Examples:
+# Percentage: {"openai": 0.10} = 10% margin
+# Fixed: {"openai": {"fixed_amount": 0.001}} = $0.001 per request
+# Global: {"global": 0.05} = 5% global margin on all providers
+# Combined: {"vertex_ai": {"percentage": 0.08, "fixed_amount": 0.0005}}
custom_prompt_dict: Dict[str, dict] = {}
check_provider_endpoint = False
diff --git a/litellm/constants.py b/litellm/constants.py
index 8fd2e307555..e8524a87c41 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1200,6 +1200,8 @@ LITELLM_SETTINGS_SAFE_DB_OVERRIDES = [
"public_agent_groups",
"public_model_groups",
"public_model_groups_links",
+ "cost_discount_config",
+ "cost_margin_config",
]
SPECIAL_LITELLM_AUTH_TOKEN = ["ui-token"]
DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL = int(
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py
index 371e53283de..af7dd078107 100644
--- a/litellm/cost_calculator.py
+++ b/litellm/cost_calculator.py
@@ -708,6 +708,69 @@ def _apply_cost_discount(
return base_cost, discount_percent, discount_amount
+def _apply_cost_margin(
+ base_cost: float,
+ custom_llm_provider: Optional[str],
+) -> Tuple[float, float, float, float]:
+ """
+ Apply provider-specific or global cost margin from module-level config.
+
+ Args:
+ base_cost: The base cost before margin (after discount if applicable)
+ custom_llm_provider: The LLM provider name
+
+ Returns:
+ Tuple of (final_cost, margin_percent, margin_fixed_amount, margin_total_amount)
+ """
+ original_cost = base_cost
+ margin_percent = 0.0
+ margin_fixed_amount = 0.0
+ margin_total_amount = 0.0
+
+ # Get margin config - check provider-specific first, then global
+ margin_config = None
+ if custom_llm_provider and custom_llm_provider in litellm.cost_margin_config:
+ margin_config = litellm.cost_margin_config[custom_llm_provider]
+ verbose_logger.debug(
+ f"Found provider-specific margin config for {custom_llm_provider}: {margin_config}"
+ )
+ elif "global" in litellm.cost_margin_config:
+ margin_config = litellm.cost_margin_config["global"]
+ verbose_logger.debug(f"Using global margin config: {margin_config}")
+ else:
+ verbose_logger.debug(
+ f"No margin config found. Provider: {custom_llm_provider}, "
+ f"Available configs: {list(litellm.cost_margin_config.keys())}"
+ )
+
+ if margin_config is not None:
+ # Handle different margin config formats
+ if isinstance(margin_config, (int, float)):
+ # Simple percentage: {"openai": 0.10}
+ margin_percent = float(margin_config)
+ margin_total_amount = original_cost * margin_percent
+ elif isinstance(margin_config, dict):
+ # Complex config: {"percentage": 0.08, "fixed_amount": 0.0005}
+ if "percentage" in margin_config:
+ margin_percent = float(margin_config["percentage"])
+ margin_total_amount += original_cost * margin_percent
+ if "fixed_amount" in margin_config:
+ margin_fixed_amount = float(margin_config["fixed_amount"])
+ margin_total_amount += margin_fixed_amount
+
+ final_cost = original_cost + margin_total_amount
+
+ verbose_logger.debug(
+ f"Applied margin to {custom_llm_provider or 'global'}: "
+ f"${original_cost:.6f} -> ${final_cost:.6f} "
+ f"(margin: {margin_percent*100 if margin_percent > 0 else 0}% + ${margin_fixed_amount:.6f} = ${margin_total_amount:.6f})"
+ )
+
+ return final_cost, margin_percent, margin_fixed_amount, margin_total_amount
+
+ return base_cost, margin_percent, margin_fixed_amount, margin_total_amount
+
+
def _store_cost_breakdown_in_logging_obj(
litellm_logging_obj: Optional[LitellmLoggingObject],
prompt_tokens_cost_usd_dollar: float,
@@ -717,6 +780,9 @@ def _store_cost_breakdown_in_logging_obj(
original_cost: Optional[float] = None,
discount_percent: Optional[float] = None,
discount_amount: Optional[float] = None,
+ margin_percent: Optional[float] = None,
+ margin_fixed_amount: Optional[float] = None,
+ margin_total_amount: Optional[float] = None,
) -> None:
"""
Helper function to store cost breakdown in the logging object.
@@ -730,6 +796,9 @@ def _store_cost_breakdown_in_logging_obj(
original_cost: Cost before discount
discount_percent: Discount percentage applied (0.05 = 5%)
discount_amount: Discount amount in USD
+ margin_percent: Margin percentage applied (0.10 = 10%)
+ margin_fixed_amount: Fixed margin amount in USD
+ margin_total_amount: Total margin added in USD
"""
if litellm_logging_obj is None:
return
@@ -744,6 +813,9 @@ def _store_cost_breakdown_in_logging_obj(
original_cost=original_cost,
discount_percent=discount_percent,
discount_amount=discount_amount,
+ margin_percent=margin_percent,
+ margin_fixed_amount=margin_fixed_amount,
+ margin_total_amount=margin_total_amount,
)
except Exception as breakdown_error:
@@ -1106,6 +1178,17 @@ def completion_cost( # noqa: PLR0915
custom_llm_provider=custom_llm_provider,
)
+ # Apply margin from module-level config if configured
+ (
+ _final_cost,
+ margin_percent,
+ margin_fixed_amount,
+ margin_total_amount,
+ ) = _apply_cost_margin(
+ base_cost=_final_cost,
+ custom_llm_provider=custom_llm_provider,
+ )
+
# Store cost breakdown in logging object if available
_store_cost_breakdown_in_logging_obj(
litellm_logging_obj=litellm_logging_obj,
@@ -1116,6 +1199,9 @@ def completion_cost( # noqa: PLR0915
original_cost=original_cost,
discount_percent=discount_percent,
discount_amount=discount_amount,
+ margin_percent=margin_percent,
+ margin_fixed_amount=margin_fixed_amount,
+ margin_total_amount=margin_total_amount,
)
return _final_cost
@@ -1239,6 +1325,17 @@ def completion_cost( # noqa: PLR0915
custom_llm_provider=custom_llm_provider,
)
+ # Apply margin from module-level config if configured
+ (
+ _final_cost,
+ margin_percent,
+ margin_fixed_amount,
+ margin_total_amount,
+ ) = _apply_cost_margin(
+ base_cost=_final_cost,
+ custom_llm_provider=custom_llm_provider,
+ )
+
# Store cost breakdown in logging object if available
_store_cost_breakdown_in_logging_obj(
litellm_logging_obj=litellm_logging_obj,
@@ -1249,6 +1346,9 @@ def completion_cost( # noqa: PLR0915
original_cost=original_cost,
discount_percent=discount_percent,
discount_amount=discount_amount,
+ margin_percent=margin_percent,
+ margin_fixed_amount=margin_fixed_amount,
+ margin_total_amount=margin_total_amount,
)
return _final_cost
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 378c201f7a3..c0090d1c3e7 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1291,6 +1291,9 @@ class Logging(LiteLLMLoggingBaseClass):
original_cost: Optional[float] = None,
discount_percent: Optional[float] = None,
discount_amount: Optional[float] = None,
+ margin_percent: Optional[float] = None,
+ margin_fixed_amount: Optional[float] = None,
+ margin_total_amount: Optional[float] = None,
) -> None:
"""
Helper method to store cost breakdown in the logging object.
@@ -1303,6 +1306,9 @@ class Logging(LiteLLMLoggingBaseClass):
original_cost: Cost before discount
discount_percent: Discount percentage (0.05 = 5%)
discount_amount: Discount amount in USD
+ margin_percent: Margin percentage applied (0.10 = 10%)
+ margin_fixed_amount: Fixed margin amount in USD
+ margin_total_amount: Total margin added in USD
"""
self.cost_breakdown = CostBreakdown(
@@ -1320,6 +1326,14 @@ class Logging(LiteLLMLoggingBaseClass):
if discount_amount is not None:
self.cost_breakdown["discount_amount"] = discount_amount
+ # Store margin information if provided
+ if margin_percent is not None:
+ self.cost_breakdown["margin_percent"] = margin_percent
+ if margin_fixed_amount is not None:
+ self.cost_breakdown["margin_fixed_amount"] = margin_fixed_amount
+ if margin_total_amount is not None:
+ self.cost_breakdown["margin_total_amount"] = margin_total_amount
+
def _response_cost_calculator(
self,
result: Union[
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index e29d4301744..570a6bb9f3b 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -33,6 +33,7 @@ from litellm.types.router import RouterErrors, UpdateRouterConfig
from litellm.types.secret_managers.main import KeyManagementSystem
from litellm.types.utils import (
CallTypes,
+ CostBreakdown,
EmbeddingResponse,
GenericBudgetConfigType,
ImageResponse,
@@ -2738,6 +2739,9 @@ class SpendLogsMetadata(TypedDict):
litellm_overhead_time_ms: Optional[
float
] # LiteLLM overhead time in milliseconds
+ cost_breakdown: Optional[
+ CostBreakdown
+ ] # Detailed cost breakdown (input_cost, output_cost, margin, discount, etc.)
class SpendLogsPayload(TypedDict):
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index 302dd5639ed..34049a44c8c 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -179,24 +179,26 @@ async def create_streaming_response(
def _get_cost_breakdown_from_logging_obj(
litellm_logging_obj: Optional[LiteLLMLoggingObj],
-) -> Tuple[Optional[float], Optional[float]]:
+) -> Tuple[Optional[float], Optional[float], Optional[float], Optional[float]]:
"""
- Extract discount information from logging object's cost breakdown.
+ Extract discount and margin information from logging object's cost breakdown.
Returns:
- Tuple of (original_cost, discount_amount)
+ Tuple of (original_cost, discount_amount, margin_total_amount, margin_percent)
"""
if not litellm_logging_obj or not hasattr(litellm_logging_obj, "cost_breakdown"):
- return None, None
+ return None, None, None, None
cost_breakdown = litellm_logging_obj.cost_breakdown
if not cost_breakdown:
- return None, None
+ return None, None, None, None
original_cost = cost_breakdown.get("original_cost")
discount_amount = cost_breakdown.get("discount_amount")
+ margin_total_amount = cost_breakdown.get("margin_total_amount")
+ margin_percent = cost_breakdown.get("margin_percent")
- return original_cost, discount_amount
+ return original_cost, discount_amount, margin_total_amount, margin_percent
class ProxyBaseLLMRequestProcessing:
@@ -224,8 +226,8 @@ class ProxyBaseLLMRequestProcessing:
exclude_values = {"", None, "None"}
hidden_params = hidden_params or {}
- # Extract discount info from cost_breakdown if available
- original_cost, discount_amount = _get_cost_breakdown_from_logging_obj(
+ # Extract discount and margin info from cost_breakdown if available
+ original_cost, discount_amount, margin_total_amount, margin_percent = _get_cost_breakdown_from_logging_obj(
litellm_logging_obj=litellm_logging_obj
)
@@ -258,6 +260,12 @@ class ProxyBaseLLMRequestProcessing:
"x-litellm-response-cost-discount-amount": (
str(discount_amount) if discount_amount is not None else None
),
+ "x-litellm-response-cost-margin-amount": (
+ str(margin_total_amount) if margin_total_amount is not None else None
+ ),
+ "x-litellm-response-cost-margin-percent": (
+ str(margin_percent) if margin_percent is not None else None
+ ),
"x-litellm-key-tpm-limit": str(user_api_key_dict.tpm_limit),
"x-litellm-key-rpm-limit": str(user_api_key_dict.rpm_limit),
"x-litellm-key-max-budget": str(user_api_key_dict.max_budget),
diff --git a/litellm/proxy/management_endpoints/cost_tracking_settings.py b/litellm/proxy/management_endpoints/cost_tracking_settings.py
index 328dafc80db..86433a232c0 100644
--- a/litellm/proxy/management_endpoints/cost_tracking_settings.py
+++ b/litellm/proxy/management_endpoints/cost_tracking_settings.py
@@ -1,13 +1,15 @@
"""
COST TRACKING SETTINGS MANAGEMENT
-Endpoints for managing cost discount configuration
+Endpoints for managing cost discount and margin configuration
GET /config/cost_discount_config - Get current cost discount configuration
PATCH /config/cost_discount_config - Update cost discount configuration
+GET /config/cost_margin_config - Get current cost margin configuration
+PATCH /config/cost_margin_config - Update cost margin configuration
"""
-from typing import Dict
+from typing import Dict, Union
from fastapi import APIRouter, Depends, HTTPException
@@ -163,3 +165,185 @@ async def update_cost_discount_config(
detail={"error": f"Failed to update cost discount config: {str(e)}"}
)
+
+ "/config/cost_margin_config",
+ tags=["Cost Tracking"],
+ dependencies=[Depends(user_api_key_auth)],
+)
+async def get_cost_margin_config(
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ Get current cost margin configuration.
+
+ Returns the cost_margin_config from litellm_settings.
+ """
+ from litellm.proxy.proxy_server import prisma_client, proxy_config
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=500,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ try:
+ # Load config from DB
+ config = await proxy_config.get_config()
+
+ # Get cost_margin_config from litellm_settings
+ litellm_settings = config.get("litellm_settings", {})
+ cost_margin_config = litellm_settings.get("cost_margin_config", {})
+
+ return {"values": cost_margin_config}
+ except Exception as e:
+ verbose_proxy_logger.error(
+ f"Error fetching cost margin config: {str(e)}"
+ )
+ return {"values": {}}
+
+
+ "/config/cost_margin_config",
+ tags=["Cost Tracking"],
+ dependencies=[Depends(user_api_key_auth)],
+)
+async def update_cost_margin_config(
+ cost_margin_config: Dict[str, Union[float, Dict[str, float]]],
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ Update cost margin configuration.
+
+ Updates the cost_margin_config in litellm_settings.
+ Margins can be:
+ - Percentage: {"openai": 0.10} = 10% margin
+ - Fixed amount: {"openai": {"fixed_amount": 0.001}} = $0.001 per request
+ - Combined: {"vertex_ai": {"percentage": 0.08, "fixed_amount": 0.0005}}
+ - Global: {"global": 0.05} = 5% global margin on all providers
+
+ Example:
+ ```json
+ {
+ "global": 0.05,
+ "openai": 0.10,
+ "anthropic": {"fixed_amount": 0.001},
+ "vertex_ai": {"percentage": 0.08, "fixed_amount": 0.0005}
+ }
+ ```
+ """
+ from litellm.proxy.proxy_server import (
+ prisma_client,
+ proxy_config,
+ store_model_in_db,
+ )
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=500,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ if store_model_in_db is not True:
+ raise HTTPException(
+ status_code=500,
+ detail={
+ "error": "Set `'STORE_MODEL_IN_DB='True'` in your env to enable this feature."
+ },
+ )
+
+ # Validate that all providers are valid LiteLLM providers (except "global")
+ invalid_providers = []
+ for provider in cost_margin_config.keys():
+ if provider != "global" and provider not in LlmProvidersSet:
+ invalid_providers.append(provider)
+
+ if invalid_providers:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": f"Invalid provider(s): {', '.join(invalid_providers)}. Must be valid LiteLLM providers or 'global'. See https://docs.litellm.ai/docs/providers for the full list."
+ },
+ )
+
+ # Validate margin values
+ for provider, margin_value in cost_margin_config.items():
+ if isinstance(margin_value, (int, float)):
+ # Simple percentage format: {"openai": 0.10}
+ if not (0 <= margin_value <= 10): # Allow up to 1000% margin
+ raise HTTPException(
+ status_code=400,
+ detail=f"Margin percentage for {provider} must be between 0 and 10 (0% to 1000%)"
+ )
+ elif isinstance(margin_value, dict):
+ # Complex format: {"percentage": 0.08, "fixed_amount": 0.0005}
+ if "percentage" in margin_value:
+ percentage = margin_value["percentage"]
+ if not isinstance(percentage, (int, float)):
+ raise HTTPException(
+ status_code=400,
+ detail=f"Margin percentage for {provider} must be a number"
+ )
+ if not (0 <= percentage <= 10):
+ raise HTTPException(
+ status_code=400,
+ detail=f"Margin percentage for {provider} must be between 0 and 10 (0% to 1000%)"
+ )
+ if "fixed_amount" in margin_value:
+ fixed_amount = margin_value["fixed_amount"]
+ if not isinstance(fixed_amount, (int, float)):
+ raise HTTPException(
+ status_code=400,
+ detail=f"Fixed margin amount for {provider} must be a number"
+ )
+ if fixed_amount < 0:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Fixed margin amount for {provider} must be non-negative"
+ )
+ if not margin_value: # Empty dict
+ raise HTTPException(
+ status_code=400,
+ detail=f"Margin config for {provider} cannot be empty. Must include 'percentage' and/or 'fixed_amount'"
+ )
+ else:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Margin for {provider} must be a number (percentage) or dict with 'percentage' and/or 'fixed_amount'"
+ )
+
+ try:
+ # Load existing config
+ config = await proxy_config.get_config()
+
+ # Ensure litellm_settings exists
+ if "litellm_settings" not in config:
+ config["litellm_settings"] = {}
+
+ # Update cost_margin_config
+ config["litellm_settings"]["cost_margin_config"] = cost_margin_config
+
+ # Save the updated config to DB
+ await proxy_config.save_config(new_config=config)
+
+ # Update in-memory litellm.cost_margin_config
+ litellm.cost_margin_config = cost_margin_config
+
+ verbose_proxy_logger.info(
+ f"Updated cost_margin_config: {cost_margin_config}"
+ )
+
+ return {
+ "message": "Cost margin configuration updated successfully",
+ "status": "success",
+ "values": cost_margin_config
+ }
+ except Exception as e:
+ verbose_proxy_logger.error(
+ f"Error updating cost margin config: {str(e)}"
+ )
+ raise HTTPException(
+ status_code=500,
+ detail={"error": f"Failed to update cost margin config: {str(e)}"}
+ )
+
diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.py
index 687af8a4514..1861c44b699 100644
--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py
+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py
@@ -16,6 +16,7 @@ from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.proxy._types import SpendLogsMetadata, SpendLogsPayload
from litellm.proxy.utils import PrismaClient, hash_token
from litellm.types.utils import (
+ CostBreakdown,
StandardLoggingGuardrailInformation,
StandardLoggingMCPToolCall,
StandardLoggingModelInformation,
@@ -56,6 +57,7 @@ def _get_spend_logs_metadata(
model_map_information: Optional[StandardLoggingModelInformation] = None,
cold_storage_object_key: Optional[str] = None,
litellm_overhead_time_ms: Optional[float] = None,
+ cost_breakdown: Optional[CostBreakdown] = None,
) -> SpendLogsMetadata:
if metadata is None:
return SpendLogsMetadata(
@@ -80,6 +82,7 @@ def _get_spend_logs_metadata(
guardrail_information=None,
cold_storage_object_key=cold_storage_object_key,
litellm_overhead_time_ms=None,
+ cost_breakdown=None,
)
verbose_proxy_logger.debug(
"getting payload for SpendLogs, available keys in metadata: "
@@ -105,6 +108,7 @@ def _get_spend_logs_metadata(
clean_metadata["model_map_information"] = model_map_information
clean_metadata["cold_storage_object_key"] = cold_storage_object_key
clean_metadata["litellm_overhead_time_ms"] = litellm_overhead_time_ms
+ clean_metadata["cost_breakdown"] = cost_breakdown
return clean_metadata
@@ -353,6 +357,11 @@ def get_logging_payload( # noqa: PLR0915
else None
),
litellm_overhead_time_ms=litellm_overhead_time_ms,
+ cost_breakdown=(
+ standard_logging_payload.get("cost_breakdown", None)
+ if standard_logging_payload is not None
+ else None
+ ),
)
special_usage_fields = ["completion_tokens", "prompt_tokens", "total_tokens"]
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 6fe62d35000..144e503acdf 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -2564,6 +2564,9 @@ class CostBreakdown(TypedDict, total=False):
original_cost: float # Cost before discount (optional)
discount_percent: float # Discount percentage applied (e.g., 0.05 = 5%) (optional)
discount_amount: float # Discount amount in USD (optional)
+ margin_percent: float # Margin percentage applied (e.g., 0.10 = 10%) (optional)
+ margin_fixed_amount: float # Fixed margin amount in USD (optional)
+ margin_total_amount: float # Total margin added in USD (optional)
class StandardLoggingPayloadStatusFields(TypedDict, total=False):
diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.py
index 2e7046319ed..b5d44385698 100644
--- a/tests/test_litellm/proxy/test_common_request_processing.py
+++ b/tests/test_litellm/proxy/test_common_request_processing.py
@@ -271,6 +271,99 @@ class TestProxyBaseLLMRequestProcessing:
assert "x-litellm-response-cost-original" not in headers
assert "x-litellm-response-cost-discount-amount" not in headers
+ def test_get_custom_headers_with_margin_info(self):
+ """
+ Test that margin headers are included when margin is applied.
+ """
+ from litellm.litellm_core_utils.litellm_logging import (
+ Logging as LiteLLMLoggingObj,
+ )
+
+ # Create mock user API key dict
+ mock_user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)
+ mock_user_api_key_dict.tpm_limit = None
+ mock_user_api_key_dict.rpm_limit = None
+ mock_user_api_key_dict.max_budget = None
+ mock_user_api_key_dict.spend = 0
+
+ # Create logging object with margin
+ logging_obj = LiteLLMLoggingObj(
+ model="gpt-4",
+ messages=[],
+ stream=False,
+ call_type="completion",
+ start_time=None,
+ litellm_call_id="test-call-id-margin",
+ function_id="test-function",
+ )
+ logging_obj.set_cost_breakdown(
+ input_cost=0.00005,
+ output_cost=0.00005,
+ total_cost=0.00011,
+ cost_for_built_in_tools_cost_usd_dollar=0.0,
+ original_cost=0.0001,
+ margin_percent=0.10,
+ margin_total_amount=0.00001,
+ )
+
+ headers = ProxyBaseLLMRequestProcessing.get_custom_headers(
+ user_api_key_dict=mock_user_api_key_dict,
+ response_cost=0.00011,
+ litellm_logging_obj=logging_obj,
+ )
+
+ # Verify margin headers are present
+ assert "x-litellm-response-cost" in headers
+ assert float(headers["x-litellm-response-cost"]) == 0.00011
+
+ assert "x-litellm-response-cost-margin-amount" in headers
+ assert float(headers["x-litellm-response-cost-margin-amount"]) == 0.00001
+
+ assert "x-litellm-response-cost-margin-percent" in headers
+ assert float(headers["x-litellm-response-cost-margin-percent"]) == 0.10
+
+ def test_get_custom_headers_without_margin_info(self):
+ """
+ Test that when no margin is applied, margin headers are not included.
+ """
+ from litellm.litellm_core_utils.litellm_logging import (
+ Logging as LiteLLMLoggingObj,
+ )
+
+ # Create mock user API key dict
+ mock_user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)
+ mock_user_api_key_dict.tpm_limit = None
+ mock_user_api_key_dict.rpm_limit = None
+ mock_user_api_key_dict.max_budget = None
+ mock_user_api_key_dict.spend = 0
+
+ # Create logging object without margin
+ logging_obj = LiteLLMLoggingObj(
+ model="gpt-4",
+ messages=[],
+ stream=False,
+ call_type="completion",
+ start_time=None,
+ litellm_call_id="test-call-id-no-margin",
+ function_id="test-function",
+ )
+ logging_obj.set_cost_breakdown(
+ input_cost=0.00005,
+ output_cost=0.00005,
+ total_cost=0.0001,
+ cost_for_built_in_tools_cost_usd_dollar=0.0,
+ )
+
+ headers = ProxyBaseLLMRequestProcessing.get_custom_headers(
+ user_api_key_dict=mock_user_api_key_dict,
+ response_cost=0.0001,
+ litellm_logging_obj=logging_obj,
+ )
+
+ # Verify margin headers are not present
+ assert "x-litellm-response-cost-margin-amount" not in headers
+ assert "x-litellm-response-cost-margin-percent" not in headers
+
def test_get_cost_breakdown_from_logging_obj_helper(self):
"""
Test the helper function that extracts cost breakdown information.
@@ -299,11 +392,39 @@ class TestProxyBaseLLMRequestProcessing:
discount_amount=0.000005,
)
- original_cost, discount_amount = _get_cost_breakdown_from_logging_obj(logging_obj)
+ original_cost, discount_amount, margin_total_amount, margin_percent = _get_cost_breakdown_from_logging_obj(logging_obj)
assert original_cost == 0.0001
assert discount_amount == 0.000005
+ assert margin_total_amount is None
+ assert margin_percent is None
+
+ # Test with margin info
+ logging_obj_with_margin = LiteLLMLoggingObj(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "test"}],
+ stream=False,
+ call_type="completion",
+ start_time=None,
+ litellm_call_id="test-call-id-margin",
+ function_id="test-function-id-margin",
+ )
+ logging_obj_with_margin.set_cost_breakdown(
+ input_cost=0.00005,
+ output_cost=0.00005,
+ total_cost=0.00011,
+ cost_for_built_in_tools_cost_usd_dollar=0.0,
+ original_cost=0.0001,
+ margin_percent=0.10,
+ margin_total_amount=0.00001,
+ )
+
+ original_cost, discount_amount, margin_total_amount, margin_percent = _get_cost_breakdown_from_logging_obj(logging_obj_with_margin)
+ assert original_cost == 0.0001
+ assert discount_amount is None
+ assert margin_total_amount == 0.00001
+ assert margin_percent == 0.10
- # Test with no discount info
+ # Test with no discount or margin info
logging_obj_no_discount = LiteLLMLoggingObj(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "test"}],
@@ -320,14 +441,18 @@ class TestProxyBaseLLMRequestProcessing:
cost_for_built_in_tools_cost_usd_dollar=0.0,
)
- original_cost, discount_amount = _get_cost_breakdown_from_logging_obj(logging_obj_no_discount)
+ original_cost, discount_amount, margin_total_amount, margin_percent = _get_cost_breakdown_from_logging_obj(logging_obj_no_discount)
assert original_cost is None
assert discount_amount is None
+ assert margin_total_amount is None
+ assert margin_percent is None
# Test with None logging object
- original_cost, discount_amount = _get_cost_breakdown_from_logging_obj(None)
+ original_cost, discount_amount, margin_total_amount, margin_percent = _get_cost_breakdown_from_logging_obj(None)
assert original_cost is None
assert discount_amount is None
+ assert margin_total_amount is None
+ assert margin_percent is None
def test_get_custom_headers_key_spend_includes_response_cost(self):
"""
diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py
index 69e0f04e5e1..7036a953b83 100644
--- a/tests/test_litellm/test_cost_calculator.py
+++ b/tests/test_litellm/test_cost_calculator.py
@@ -837,6 +837,317 @@ def test_cost_discount_not_applied_to_other_providers():
print(f" - Cost remains unchanged: ${cost_with_selective_discount:.6f}")
+def test_cost_margin_percentage():
+ """
+ Test that percentage-based cost margin is applied correctly
+ """
+ from litellm import completion_cost
+ from litellm.types.utils import Usage
+
+ # Save original config
+ original_margin_config = litellm.cost_margin_config.copy()
+
+ # Create mock response
+ response = ModelResponse(
+ id="test-id",
+ choices=[],
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion",
+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),
+ )
+
+ # Calculate cost without margin
+ litellm.cost_margin_config = {}
+ cost_without_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Set 10% margin for openai
+ litellm.cost_margin_config = {"openai": 0.10}
+
+ # Calculate cost with margin
+ cost_with_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Restore original config
+ litellm.cost_margin_config = original_margin_config
+
+ # Verify margin is applied (10% margin means 110% of original cost)
+ expected_cost = cost_without_margin * 1.10
+ assert cost_with_margin == pytest.approx(expected_cost, rel=1e-9)
+
+ print(f"✓ Cost margin percentage test passed:")
+ print(f" - Original cost: ${cost_without_margin:.6f}")
+ print(f" - Cost with margin (10%): ${cost_with_margin:.6f}")
+ print(f" - Margin added: ${cost_with_margin - cost_without_margin:.6f}")
+
+
+def test_cost_margin_fixed_amount():
+ """
+ Test that fixed amount cost margin is applied correctly
+ """
+ from litellm import completion_cost
+ from litellm.types.utils import Usage
+
+ # Save original config
+ original_margin_config = litellm.cost_margin_config.copy()
+
+ # Create mock response
+ response = ModelResponse(
+ id="test-id",
+ choices=[],
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion",
+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),
+ )
+
+ # Calculate cost without margin
+ litellm.cost_margin_config = {}
+ cost_without_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Set $0.001 fixed margin for openai
+ litellm.cost_margin_config = {"openai": {"fixed_amount": 0.001}}
+
+ # Calculate cost with margin
+ cost_with_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Restore original config
+ litellm.cost_margin_config = original_margin_config
+
+ # Verify fixed margin is applied
+ expected_cost = cost_without_margin + 0.001
+ assert cost_with_margin == pytest.approx(expected_cost, rel=1e-9)
+
+ print(f"✓ Cost margin fixed amount test passed:")
+ print(f" - Original cost: ${cost_without_margin:.6f}")
+ print(f" - Cost with margin ($0.001): ${cost_with_margin:.6f}")
+ print(f" - Margin added: ${cost_with_margin - cost_without_margin:.6f}")
+
+
+def test_cost_margin_combined():
+ """
+ Test that combined percentage and fixed amount margin is applied correctly
+ """
+ from litellm import completion_cost
+ from litellm.types.utils import Usage
+
+ # Save original config
+ original_margin_config = litellm.cost_margin_config.copy()
+
+ # Create mock response
+ response = ModelResponse(
+ id="test-id",
+ choices=[],
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion",
+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),
+ )
+
+ # Calculate cost without margin
+ litellm.cost_margin_config = {}
+ cost_without_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Set 8% margin + $0.0005 fixed for openai
+ litellm.cost_margin_config = {"openai": {"percentage": 0.08, "fixed_amount": 0.0005}}
+
+ # Calculate cost with margin
+ cost_with_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Restore original config
+ litellm.cost_margin_config = original_margin_config
+
+ # Verify combined margin is applied
+ expected_cost = cost_without_margin * 1.08 + 0.0005
+ assert cost_with_margin == pytest.approx(expected_cost, rel=1e-9)
+
+ print(f"✓ Cost margin combined test passed:")
+ print(f" - Original cost: ${cost_without_margin:.6f}")
+ print(f" - Cost with margin (8% + $0.0005): ${cost_with_margin:.6f}")
+ print(f" - Margin added: ${cost_with_margin - cost_without_margin:.6f}")
+
+
+def test_cost_margin_global():
+ """
+ Test that global margin is applied when no provider-specific margin is configured
+ """
+ from litellm import completion_cost
+ from litellm.types.utils import Usage
+
+ # Save original config
+ original_margin_config = litellm.cost_margin_config.copy()
+
+ # Create mock response
+ response = ModelResponse(
+ id="test-id",
+ choices=[],
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion",
+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),
+ )
+
+ # Calculate cost without margin
+ litellm.cost_margin_config = {}
+ cost_without_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Set 5% global margin (no provider-specific margin)
+ litellm.cost_margin_config = {"global": 0.05}
+
+ # Calculate cost with global margin
+ cost_with_global_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Restore original config
+ litellm.cost_margin_config = original_margin_config
+
+ # Verify global margin is applied
+ expected_cost = cost_without_margin * 1.05
+ assert cost_with_global_margin == pytest.approx(expected_cost, rel=1e-9)
+
+ print(f"✓ Cost margin global test passed:")
+ print(f" - Original cost: ${cost_without_margin:.6f}")
+ print(f" - Cost with global margin (5%): ${cost_with_global_margin:.6f}")
+ print(f" - Margin added: ${cost_with_global_margin - cost_without_margin:.6f}")
+
+
+def test_cost_margin_provider_overrides_global():
+ """
+ Test that provider-specific margin overrides global margin
+ """
+ from litellm import completion_cost
+ from litellm.types.utils import Usage
+
+ # Save original config
+ original_margin_config = litellm.cost_margin_config.copy()
+
+ # Create mock response
+ response = ModelResponse(
+ id="test-id",
+ choices=[],
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion",
+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),
+ )
+
+ # Calculate cost without margin
+ litellm.cost_margin_config = {}
+ cost_without_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Set 5% global margin and 10% provider-specific margin
+ litellm.cost_margin_config = {"global": 0.05, "openai": 0.10}
+
+ # Calculate cost - should use provider-specific margin (10%), not global (5%)
+ cost_with_provider_margin = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Restore original config
+ litellm.cost_margin_config = original_margin_config
+
+ # Verify provider-specific margin is used (not global)
+ expected_cost = cost_without_margin * 1.10 # 10% from provider, not 5% from global
+ assert cost_with_provider_margin == pytest.approx(expected_cost, rel=1e-9)
+
+ print(f"✓ Cost margin provider override test passed:")
+ print(f" - Original cost: ${cost_without_margin:.6f}")
+ print(f" - Cost with provider margin (10%, overrides 5% global): ${cost_with_provider_margin:.6f}")
+ print(f" - Margin added: ${cost_with_provider_margin - cost_without_margin:.6f}")
+
+
+def test_cost_margin_with_discount():
+ """
+ Test that margin is applied after discount (independent calculation)
+ """
+ from litellm import completion_cost
+ from litellm.types.utils import Usage
+
+ # Save original configs
+ original_margin_config = litellm.cost_margin_config.copy()
+ original_discount_config = litellm.cost_discount_config.copy()
+
+ # Create mock response
+ response = ModelResponse(
+ id="test-id",
+ choices=[],
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion",
+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),
+ )
+
+ # Calculate base cost
+ litellm.cost_margin_config = {}
+ litellm.cost_discount_config = {}
+ base_cost = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Set 5% discount and 10% margin
+ litellm.cost_discount_config = {"openai": 0.05}
+ litellm.cost_margin_config = {"openai": 0.10}
+
+ # Calculate cost with both discount and margin
+ cost_with_both = completion_cost(
+ completion_response=response,
+ model="gpt-4",
+ custom_llm_provider="openai",
+ )
+
+ # Restore original configs
+ litellm.cost_margin_config = original_margin_config
+ litellm.cost_discount_config = original_discount_config
+
+ # Verify: discount applied first, then margin
+ # Base cost -> discount: base * 0.95 -> margin: (base * 0.95) * 1.10
+ expected_cost = base_cost * 0.95 * 1.10
+ assert cost_with_both == pytest.approx(expected_cost, rel=1e-9)
+
+ print(f"✓ Cost margin with discount test passed:")
+ print(f" - Base cost: ${base_cost:.6f}")
+ print(f" - Cost with 5% discount + 10% margin: ${cost_with_both:.6f}")
+ print(f" - Expected: ${expected_cost:.6f}")
+
+
def test_azure_image_generation_cost_calculator():
from unittest.mock import MagicMock
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/add_margin_form.tsx b/ui/litellm-dashboard/src/components/CostTrackingSettings/add_margin_form.tsx
new file mode 100644
index 00000000000..8c6237a0c9b
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/add_margin_form.tsx
@@ -0,0 +1,202 @@
+import React from "react";
+import { TextInput, Button } from "@tremor/react";
+import { Select as AntdSelect, Form, Tooltip, Radio } from "antd";
+import { InfoCircleOutlined } from "@ant-design/icons";
+import { Providers, provider_map, providerLogoMap } from "../provider_info_helpers";
+import { MarginConfig } from "./types";
+import { handleImageError } from "./provider_display_helpers";
+
+interface AddMarginFormProps {
+ marginConfig: MarginConfig;
+ selectedProvider: string | undefined;
+ marginType: "percentage" | "fixed";
+ percentageValue: string;
+ fixedAmountValue: string;
+ onProviderChange: (provider: string | undefined) => void;
+ onMarginTypeChange: (type: "percentage" | "fixed") => void;
+ onPercentageChange: (value: string) => void;
+ onFixedAmountChange: (value: string) => void;
+ onAddProvider: () => void;
+}
+
+const AddMarginForm: React.FC<AddMarginFormProps> = ({
+ marginConfig,
+ selectedProvider,
+ marginType,
+ percentageValue,
+ fixedAmountValue,
+ onProviderChange,
+ onMarginTypeChange,
+ onPercentageChange,
+ onFixedAmountChange,
+ onAddProvider,
+}) => {
+ return (
+ <div className="space-y-6">
+ <Form.Item
+ label={
+ <span className="text-sm font-medium text-gray-700 flex items-center">
+ Provider
+ <Tooltip title="Select 'Global' to apply margin to all providers, or select a specific provider">
+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
+ </Tooltip>
+ </span>
+ }
+ rules={[{ required: true, message: "Please select a provider" }]}
+ >
+ <AntdSelect
+ showSearch
+ placeholder="Select provider or 'Global'"
+ value={selectedProvider}
+ onChange={onProviderChange}
+ style={{ width: "100%" }}
+ size="large"
+ optionFilterProp="children"
+ filterOption={(input, option) =>
+ String(option?.label ?? "").toLowerCase().includes(input.toLowerCase())
+ }
+ >
+ <AntdSelect.Option key="global" value="global" label="Global (All Providers)">
+ <div className="flex items-center space-x-2">
+ <span className="font-medium">Global (All Providers)</span>
+ </div>
+ </AntdSelect.Option>
+ {Object.entries(Providers).map(([providerEnum, providerDisplayName]) => {
+ const providerValue = provider_map[providerEnum as keyof typeof provider_map];
+ // Only show providers that don't already have a margin configured
+ if (providerValue && marginConfig[providerValue]) {
+ return null;
+ }
+ return (
+ <AntdSelect.Option key={providerEnum} value={providerEnum} label={providerDisplayName}>
+ <div className="flex items-center space-x-2">
+ <img
+ src={providerLogoMap[providerDisplayName]}
+ alt={`${providerEnum} logo`}
+ className="w-5 h-5"
+ onError={(e) => handleImageError(e, providerDisplayName)}
+ />
+ <span>{providerDisplayName}</span>
+ </div>
+ </AntdSelect.Option>
+ );
+ })}
+ </AntdSelect>
+ </Form.Item>
+
+ <Form.Item
+ label={
+ <span className="text-sm font-medium text-gray-700 flex items-center">
+ Margin Type
+ <Tooltip title="Choose how to apply the margin: percentage-based or fixed amount">
+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
+ </Tooltip>
+ </span>
+ }
+ rules={[{ required: true, message: "Please select a margin type" }]}
+ >
+ <Radio.Group
+ value={marginType}
+ onChange={(e) => onMarginTypeChange(e.target.value)}
+ className="w-full"
+ >
+ <Radio value="percentage">Percentage-based</Radio>
+ <Radio value="fixed">Fixed Amount</Radio>
+ </Radio.Group>
+ </Form.Item>
+
+ {marginType === "percentage" && (
+ <Form.Item
+ label={
+ <span className="text-sm font-medium text-gray-700 flex items-center">
+ Margin Percentage
+ <Tooltip title="Enter a percentage value (e.g., 10 for 10% margin)">
+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
+ </Tooltip>
+ </span>
+ }
+ rules={[
+ { required: true, message: "Please enter a margin percentage" },
+ {
+ validator: (_, value) => {
+ if (!value) {
+ return Promise.reject(new Error("Please enter a margin percentage"));
+ }
+ const numValue = parseFloat(value);
+ if (isNaN(numValue) || numValue < 0 || numValue > 1000) {
+ return Promise.reject(new Error("Percentage must be between 0 and 1000"));
+ }
+ return Promise.resolve();
+ },
+ },
+ ]}
+ >
+ <div className="flex items-center gap-2">
+ <TextInput
+ placeholder="10"
+ value={percentageValue}
+ onValueChange={onPercentageChange}
+ className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500 flex-1"
+ />
+ <span className="text-gray-600">%</span>
+ </div>
+ </Form.Item>
+ )}
+
+ {marginType === "fixed" && (
+ <Form.Item
+ label={
+ <span className="text-sm font-medium text-gray-700 flex items-center">
+ Fixed Margin Amount
+ <Tooltip title="Enter a fixed amount in USD (e.g., 0.001 for $0.001 per request)">
+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
+ </Tooltip>
+ </span>
+ }
+ rules={[
+ { required: true, message: "Please enter a fixed amount" },
+ {
+ validator: (_, value) => {
+ if (!value) {
+ return Promise.reject(new Error("Please enter a fixed amount"));
+ }
+ const numValue = parseFloat(value);
+ if (isNaN(numValue) || numValue < 0) {
+ return Promise.reject(new Error("Fixed amount must be non-negative"));
+ }
+ return Promise.resolve();
+ },
+ },
+ ]}
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-gray-600">$</span>
+ <TextInput
+ placeholder="0.001"
+ value={fixedAmountValue}
+ onValueChange={onFixedAmountChange}
+ className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500 flex-1"
+ />
+ </div>
+ </Form.Item>
+ )}
+
+ <div className="flex items-center justify-end space-x-3 pt-6 border-t border-gray-100">
+ <Button
+ variant="primary"
+ onClick={onAddProvider}
+ disabled={
+ !selectedProvider ||
+ (marginType === "percentage" && !percentageValue) ||
+ (marginType === "fixed" && !fixedAmountValue)
+ }
+ >
+ Add Provider Margin
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+export default AddMarginForm;
+
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/add_provider_form.tsx b/ui/litellm-dashboard/src/components/CostTrackingSettings/add_provider_form.tsx
index 2d530be71eb..7f79a6848bb 100644
--- a/ui/litellm-dashboard/src/components/CostTrackingSettings/add_provider_form.tsx
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/add_provider_form.tsx
@@ -2,7 +2,6 @@ import React from "react";
import { TextInput, Button } from "@tremor/react";
import { Select as AntdSelect, Form, Tooltip } from "antd";
import { InfoCircleOutlined } from "@ant-design/icons";
-import Image from "next/image";
import { Providers, provider_map, providerLogoMap } from "../provider_info_helpers";
import { DiscountConfig } from "./types";
import { handleImageError } from "./provider_display_helpers";
@@ -58,11 +57,9 @@ const AddProviderForm: React.FC<AddProviderFormProps> = ({
return (
<AntdSelect.Option key={providerEnum} value={providerEnum} label={providerDisplayName}>
<div className="flex items-center space-x-2">
- <Image
+ <img
src={providerLogoMap[providerDisplayName]}
alt={`${providerEnum} logo`}
- width={20}
- height={20}
className="w-5 h-5"
onError={(e) => handleImageError(e, providerDisplayName)}
/>
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/cost_tracking_settings.tsx b/ui/litellm-dashboard/src/components/CostTrackingSettings/cost_tracking_settings.tsx
index c356982f189..32ffd55efa0 100644
--- a/ui/litellm-dashboard/src/components/CostTrackingSettings/cost_tracking_settings.tsx
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/cost_tracking_settings.tsx
@@ -1,16 +1,16 @@
-import React, { useState, useEffect, useCallback } from "react";
-import { Title, Text, Button, TabGroup, TabList, Tab, TabPanels, TabPanel } from "@tremor/react";
+import React, { useState, useEffect } from "react";
+import { Title, Text, Button, Accordion, AccordionHeader, AccordionBody, TabGroup, TabList, Tab, TabPanels, TabPanel } from "@tremor/react";
import { Modal, Form } from "antd";
-import { getProxyBaseUrl } from "@/components/networking";
-import NotificationsManager from "../molecules/notifications_manager";
-import { Providers } from "../provider_info_helpers";
-import { CostTrackingSettingsProps, DiscountConfig } from "./types";
-import { getProviderBackendValue } from "./provider_display_helpers";
+import { CostTrackingSettingsProps } from "./types";
import ProviderDiscountTable from "./provider_discount_table";
import AddProviderForm from "./add_provider_form";
+import ProviderMarginTable from "./provider_margin_table";
+import AddMarginForm from "./add_margin_form";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { DocsMenu } from "../HelpLink";
import HowItWorks from "./how_it_works";
+import { useDiscountConfig } from "./use_discount_config";
+import { useMarginConfig } from "./use_margin_config";
const DOCS_LINKS = [
{ label: "Custom pricing for models", href: "https://docs.litellm.ai/docs/proxy/custom_pricing" },
@@ -22,118 +22,51 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({
userRole,
accessToken
}) => {
- const [discountConfig, setDiscountConfig] = useState<DiscountConfig>({});
const [selectedProvider, setSelectedProvider] = useState<string | undefined>(undefined);
const [newDiscount, setNewDiscount] = useState<string>("");
const [isFetching, setIsFetching] = useState(true);
const [isModalVisible, setIsModalVisible] = useState(false);
+ const [isMarginModalVisible, setIsMarginModalVisible] = useState(false);
+ const [selectedMarginProvider, setSelectedMarginProvider] = useState<string | undefined>(undefined);
+ const [marginType, setMarginType] = useState<"percentage" | "fixed">("percentage");
+ const [percentageValue, setPercentageValue] = useState<string>("");
+ const [fixedAmountValue, setFixedAmountValue] = useState<string>("");
const [form] = Form.useForm();
+ const [marginForm] = Form.useForm();
const [modal, contextHolder] = Modal.useModal();
- const fetchDiscountConfig = useCallback(async () => {
- setIsFetching(true);
- try {
- const proxyBaseUrl = getProxyBaseUrl();
- const url = proxyBaseUrl
- ? `${proxyBaseUrl}/config/cost_discount_config`
- : "/config/cost_discount_config";
-
- const response = await fetch(url, {
- method: "GET",
- headers: {
- Authorization: `Bearer ${accessToken}`,
- "Content-Type": "application/json",
- },
- });
+ // Use custom hooks for discount and margin config
+ const {
+ discountConfig,
+ fetchDiscountConfig,
+ handleAddProvider: addProvider,
+ handleRemoveProvider: removeProvider,
+ handleDiscountChange,
+ } = useDiscountConfig({ accessToken });
- if (response.ok) {
- const data = await response.json();
- setDiscountConfig(data.values || {});
- } else {
- console.error("Failed to fetch discount config");
- }
- } catch (error) {
- console.error("Error fetching discount config:", error);
- NotificationsManager.fromBackend("Failed to fetch discount configuration");
- } finally {
- setIsFetching(false);
- }
- }, [accessToken]);
+ const {
+ marginConfig,
+ fetchMarginConfig,
+ handleAddMargin: addMargin,
+ handleRemoveMargin: removeMargin,
+ handleMarginChange,
+ } = useMarginConfig({ accessToken });
useEffect(() => {
if (accessToken) {
- fetchDiscountConfig();
- }
- }, [accessToken, fetchDiscountConfig]);
-
- const saveDiscountConfig = async (config: DiscountConfig) => {
- try {
- const proxyBaseUrl = getProxyBaseUrl();
- const url = proxyBaseUrl
- ? `${proxyBaseUrl}/config/cost_discount_config`
- : "/config/cost_discount_config";
-
- const response = await fetch(url, {
- method: "PATCH",
- headers: {
- Authorization: `Bearer ${accessToken}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify(config),
+ Promise.all([fetchDiscountConfig(), fetchMarginConfig()]).finally(() => {
+ setIsFetching(false);
});
-
- if (response.ok) {
- NotificationsManager.success("Discount configuration updated successfully");
- await fetchDiscountConfig();
- } else {
- const errorData = await response.json();
- const errorMessage = errorData.detail?.error || errorData.detail || "Failed to update settings";
- NotificationsManager.fromBackend(errorMessage);
- }
- } catch (error) {
- console.error("Error updating discount config:", error);
- NotificationsManager.fromBackend("Failed to update discount configuration");
}
- };
+ }, [accessToken, fetchDiscountConfig, fetchMarginConfig]);
const handleAddProvider = async () => {
- if (!selectedProvider || !newDiscount) {
- NotificationsManager.fromBackend("Please select a provider and enter discount percentage");
- return;
+ const success = await addProvider(selectedProvider, newDiscount);
+ if (success) {
+ setSelectedProvider(undefined);
+ setNewDiscount("");
+ setIsModalVisible(false);
}
-
- const percentageValue = parseFloat(newDiscount);
- if (isNaN(percentageValue) || percentageValue < 0 || percentageValue > 100) {
- NotificationsManager.fromBackend("Discount must be between 0% and 100%");
- return;
- }
-
- const providerValue = getProviderBackendValue(selectedProvider);
-
- if (!providerValue) {
- NotificationsManager.fromBackend("Invalid provider selected");
- return;
- }
-
- if (discountConfig[providerValue]) {
- NotificationsManager.fromBackend(
- `Discount for ${Providers[selectedProvider as keyof typeof Providers]} already exists. Edit it in the table above.`
- );
- return;
- }
-
- // Convert percentage to decimal for storage
- const discountValue = percentageValue / 100;
- const updatedConfig = {
- ...discountConfig,
- [providerValue]: discountValue,
- };
-
- setDiscountConfig(updatedConfig);
- await saveDiscountConfig(updatedConfig);
- setSelectedProvider(undefined);
- setNewDiscount("");
- setIsModalVisible(false);
};
const handleModalCancel = () => {
@@ -143,7 +76,7 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({
setNewDiscount("");
};
- const handleFormSubmit = (values: any) => {
+ const handleFormSubmit = () => {
handleAddProvider();
};
@@ -155,27 +88,47 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({
okText: 'Remove',
okType: 'danger',
cancelText: 'Cancel',
- onOk: async () => {
- const updatedConfig = { ...discountConfig };
- delete updatedConfig[provider];
- setDiscountConfig(updatedConfig);
- await saveDiscountConfig(updatedConfig);
- },
+ onOk: () => removeProvider(provider),
});
};
- const handleDiscountChange = async (provider: string, value: string) => {
- const discountValue = parseFloat(value);
- if (!isNaN(discountValue) && discountValue >= 0 && discountValue <= 1) {
- const updatedConfig = {
- ...discountConfig,
- [provider]: discountValue,
- };
- setDiscountConfig(updatedConfig);
- await saveDiscountConfig(updatedConfig);
+ const handleAddMargin = async () => {
+ const success = await addMargin({
+ selectedProvider: selectedMarginProvider,
+ marginType,
+ percentageValue,
+ fixedAmountValue,
+ });
+ if (success) {
+ setSelectedMarginProvider(undefined);
+ setPercentageValue("");
+ setFixedAmountValue("");
+ setMarginType("percentage");
+ setIsMarginModalVisible(false);
}
};
+ const handleMarginModalCancel = () => {
+ setIsMarginModalVisible(false);
+ marginForm.resetFields();
+ setSelectedMarginProvider(undefined);
+ setPercentageValue("");
+ setFixedAmountValue("");
+ setMarginType("percentage");
+ };
+
+ const handleRemoveMargin = async (provider: string, providerDisplayName: string) => {
+ modal.confirm({
+ title: 'Remove Provider Margin',
+ icon: <ExclamationCircleOutlined />,
+ content: `Are you sure you want to remove the margin for ${providerDisplayName}?`,
+ okText: 'Remove',
+ okType: 'danger',
+ cancelText: 'Cancel',
+ onOk: () => removeMargin(provider),
+ });
+ };
+
if (!accessToken) {
return null;
}
@@ -192,38 +145,113 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({
<DocsMenu items={DOCS_LINKS} />
</div>
<Text className="text-gray-500 mt-1">
- Configure cost discounts for different LLM providers. Changes are saved automatically.
+ Configure cost discounts and margins for different LLM providers. Changes are saved automatically.
</Text>
</div>
- <Button
- onClick={() => setIsModalVisible(true)}
- className="mt-4 md:mt-0"
- >
- + Add Provider Discount
- </Button>
</div>
- {/* Main Content Card with Tabs */}
- <div className="bg-white rounded-lg shadow w-full max-w-full">
- <TabGroup>
- <TabList className="px-6 pt-4">
- <Tab>Provider Discounts</Tab>
- <Tab>Test It</Tab>
- </TabList>
- <TabPanels>
- <TabPanel>
+ {/* Main Content Card with Accordions */}
+ <div className="bg-white rounded-lg shadow w-full max-w-full space-y-4">
+ {/* Accordion 1: Provider Discounts */}
+ <Accordion>
+ <AccordionHeader className="px-6 py-4">
+ <div className="flex flex-col items-start w-full">
+ <Text className="text-lg font-semibold text-gray-900">Provider Discounts</Text>
+ <Text className="text-sm text-gray-500 mt-1">
+ Apply percentage-based discounts to reduce costs for specific providers
+ </Text>
+ </div>
+ </AccordionHeader>
+ <AccordionBody className="px-0">
+ <TabGroup>
+ <TabList className="px-6 pt-4">
+ <Tab>Discounts</Tab>
+ <Tab>Test It</Tab>
+ </TabList>
+ <TabPanels>
+ <TabPanel>
+ <div className="p-6">
+ <div className="flex justify-end mb-4">
+ <Button
+ onClick={() => setIsModalVisible(true)}
+ >
+ + Add Provider Discount
+ </Button>
+ </div>
+ {isFetching ? (
+ <div className="py-12 text-center">
+ <Text className="text-gray-500">Loading configuration...</Text>
+ </div>
+ ) : Object.keys(discountConfig).length > 0 ? (
+ <ProviderDiscountTable
+ discountConfig={discountConfig}
+ onDiscountChange={handleDiscountChange}
+ onRemoveProvider={handleRemoveProvider}
+ />
+ ) : (
+ <div className="py-16 px-6 text-center">
+ <svg
+ className="mx-auto h-12 w-12 text-gray-400 mb-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={1.5}
+ d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
+ </svg>
+ <Text className="text-gray-700 font-medium mb-2">
+ No provider discounts configured
+ </Text>
+ <Text className="text-gray-500 text-sm">
+ Click &quot;Add Provider Discount&quot; to get started
+ </Text>
+ </div>
+ )}
+ </div>
+ </TabPanel>
+ <TabPanel>
+ <div className="px-6 pb-4">
+ <HowItWorks />
+ </div>
+ </TabPanel>
+ </TabPanels>
+ </TabGroup>
+ </AccordionBody>
+ </Accordion>
+
+ {/* Accordion 2: Fee/Price Margin */}
+ <Accordion>
+ <AccordionHeader className="px-6 py-4">
+ <div className="flex flex-col items-start w-full">
+ <Text className="text-lg font-semibold text-gray-900">Fee/Price Margin</Text>
+ <Text className="text-sm text-gray-500 mt-1">
+ Add fees or margins to LLM costs for internal billing and cost recovery
+ </Text>
+ </div>
+ </AccordionHeader>
+ <AccordionBody className="px-0">
+ <div className="p-6">
+ <div className="flex justify-end mb-4">
+ <Button
+ onClick={() => setIsMarginModalVisible(true)}
+ >
+ + Add Provider Margin
+ </Button>
+ </div>
{isFetching ? (
<div className="py-12 text-center">
<Text className="text-gray-500">Loading configuration...</Text>
</div>
- ) : Object.keys(discountConfig).length > 0 ? (
- <div className="p-6">
- <ProviderDiscountTable
- discountConfig={discountConfig}
- onDiscountChange={handleDiscountChange}
- onRemoveProvider={handleRemoveProvider}
- />
- </div>
+ ) : Object.keys(marginConfig).length > 0 ? (
+ <ProviderMarginTable
+ marginConfig={marginConfig}
+ onMarginChange={handleMarginChange}
+ onRemoveProvider={handleRemoveMargin}
+ />
) : (
<div className="py-16 px-6 text-center">
<svg
@@ -240,21 +268,16 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({
/>
</svg>
<Text className="text-gray-700 font-medium mb-2">
- No provider discounts configured
+ No provider margins configured
</Text>
<Text className="text-gray-500 text-sm">
- Click &quot;Add Provider Discount&quot; to get started
+ Click &quot;Add Provider Margin&quot; to get started
</Text>
</div>
)}
- </TabPanel>
- <TabPanel>
- <div className="px-6 pb-4">
- <HowItWorks />
- </div>
- </TabPanel>
- </TabPanels>
- </TabGroup>
+ </div>
+ </AccordionBody>
+ </Accordion>
</div>
<Modal
@@ -294,6 +317,47 @@ const CostTrackingSettings: React.FC<CostTrackingSettingsProps> = ({
</Form>
</div>
</Modal>
+
+ <Modal
+ title={
+ <div className="flex items-center space-x-3 pb-4 border-b border-gray-100">
+ <h2 className="text-xl font-semibold text-gray-900">Add Provider Margin</h2>
+ </div>
+ }
+ open={isMarginModalVisible}
+ width={1000}
+ onCancel={handleMarginModalCancel}
+ footer={null}
+ className="top-8"
+ styles={{
+ body: { padding: "24px" },
+ header: { padding: "24px 24px 0 24px", border: "none" },
+ }}
+ >
+ <div className="mt-6">
+ <Text className="text-sm text-gray-600 mb-6">
+ Select a provider (or &quot;Global&quot; for all providers) and configure the margin. You can use percentage-based or fixed amount.
+ </Text>
+ <Form
+ form={marginForm}
+ layout="vertical"
+ className="space-y-6"
+ >
+ <AddMarginForm
+ marginConfig={marginConfig}
+ selectedProvider={selectedMarginProvider}
+ marginType={marginType}
+ percentageValue={percentageValue}
+ fixedAmountValue={fixedAmountValue}
+ onProviderChange={setSelectedMarginProvider}
+ onMarginTypeChange={setMarginType}
+ onPercentageChange={setPercentageValue}
+ onFixedAmountChange={setFixedAmountValue}
+ onAddProvider={handleAddMargin}
+ />
+ </Form>
+ </div>
+ </Modal>
</div>
);
};
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/index.ts b/ui/litellm-dashboard/src/components/CostTrackingSettings/index.ts
index 11adc414664..feba943154b 100644
--- a/ui/litellm-dashboard/src/components/CostTrackingSettings/index.ts
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/index.ts
@@ -1,8 +1,12 @@
export { default as CostTrackingSettings } from "./cost_tracking_settings";
export { default as ProviderDiscountTable } from "./provider_discount_table";
export { default as AddProviderForm } from "./add_provider_form";
+export { default as ProviderMarginTable } from "./provider_margin_table";
+export { default as AddMarginForm } from "./add_margin_form";
export { default as HowItWorks } from "./how_it_works";
-export type { CostTrackingSettingsProps, DiscountConfig, CostDiscountResponse } from "./types";
+export type { CostTrackingSettingsProps, DiscountConfig, CostDiscountResponse, MarginConfig, CostMarginResponse } from "./types";
export type { ProviderDisplayInfo } from "./provider_display_helpers";
export * from "./provider_display_helpers";
+export { useDiscountConfig } from "./use_discount_config";
+export { useMarginConfig } from "./use_margin_config";
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/provider_margin_table.tsx b/ui/litellm-dashboard/src/components/CostTrackingSettings/provider_margin_table.tsx
new file mode 100644
index 00000000000..f75fefef3e1
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/provider_margin_table.tsx
@@ -0,0 +1,206 @@
+import React, { useState } from "react";
+import { TextInput, Icon, Text } from "@tremor/react";
+import { TrashIcon, PencilAltIcon, CheckIcon, XIcon } from "@heroicons/react/outline";
+import { SimpleTable } from "../common_components/simple_table";
+import { MarginConfig } from "./types";
+import { getProviderDisplayInfo, handleImageError } from "./provider_display_helpers";
+
+interface ProviderMarginTableProps {
+ marginConfig: MarginConfig;
+ onMarginChange: (provider: string, value: number | { percentage?: number; fixed_amount?: number }) => void;
+ onRemoveProvider: (provider: string, providerDisplayName: string) => void;
+}
+
+interface ProviderMarginRow {
+ provider: string;
+ margin: number | { percentage?: number; fixed_amount?: number };
+}
+
+const ProviderMarginTable: React.FC<ProviderMarginTableProps> = ({
+ marginConfig,
+ onMarginChange,
+ onRemoveProvider,
+}) => {
+ const [editingProvider, setEditingProvider] = useState<string | null>(null);
+ const [editPercentage, setEditPercentage] = useState<string>("");
+ const [editFixedAmount, setEditFixedAmount] = useState<string>("");
+
+ const handleStartEdit = (provider: string, currentMargin: number | { percentage?: number; fixed_amount?: number }) => {
+ setEditingProvider(provider);
+ if (typeof currentMargin === "number") {
+ // Simple percentage format
+ setEditPercentage((currentMargin * 100).toString());
+ setEditFixedAmount("");
+ } else {
+ // Complex format with percentage and/or fixed_amount
+ setEditPercentage(currentMargin.percentage ? (currentMargin.percentage * 100).toString() : "");
+ setEditFixedAmount(currentMargin.fixed_amount ? currentMargin.fixed_amount.toString() : "");
+ }
+ };
+
+ const handleSaveEdit = (provider: string) => {
+ const percentValue = editPercentage ? parseFloat(editPercentage) : undefined;
+ const fixedValue = editFixedAmount ? parseFloat(editFixedAmount) : undefined;
+
+ if (percentValue !== undefined && !isNaN(percentValue) && percentValue >= 0 && percentValue <= 1000) {
+ if (fixedValue !== undefined && !isNaN(fixedValue) && fixedValue >= 0) {
+ // Both percentage and fixed amount
+ onMarginChange(provider, { percentage: percentValue / 100, fixed_amount: fixedValue });
+ } else {
+ // Only percentage
+ onMarginChange(provider, percentValue / 100);
+ }
+ } else if (fixedValue !== undefined && !isNaN(fixedValue) && fixedValue >= 0) {
+ // Only fixed amount
+ onMarginChange(provider, { fixed_amount: fixedValue });
+ }
+ setEditingProvider(null);
+ setEditPercentage("");
+ setEditFixedAmount("");
+ };
+
+ const handleCancelEdit = () => {
+ setEditingProvider(null);
+ setEditPercentage("");
+ setEditFixedAmount("");
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent, provider: string) => {
+ if (e.key === 'Enter') {
+ handleSaveEdit(provider);
+ } else if (e.key === 'Escape') {
+ handleCancelEdit();
+ }
+ };
+
+ const formatMargin = (margin: number | { percentage?: number; fixed_amount?: number }): string => {
+ if (typeof margin === "number") {
+ return `${(margin * 100).toFixed(1)}%`;
+ }
+ const parts: string[] = [];
+ if (margin.percentage !== undefined) {
+ parts.push(`${(margin.percentage * 100).toFixed(1)}%`);
+ }
+ if (margin.fixed_amount !== undefined) {
+ parts.push(`$${margin.fixed_amount.toFixed(6)}`);
+ }
+ return parts.join(" + ") || "0%";
+ };
+
+ // Convert margin config to array and sort (global first, then alphabetically)
+ const data: ProviderMarginRow[] = Object.entries(marginConfig)
+ .map(([provider, margin]) => ({ provider, margin }))
+ .sort((a, b) => {
+ if (a.provider === "global") return -1;
+ if (b.provider === "global") return 1;
+ const displayA = getProviderDisplayInfo(a.provider).displayName;
+ const displayB = getProviderDisplayInfo(b.provider).displayName;
+ return displayA.localeCompare(displayB);
+ });
+
+ return (
+ <SimpleTable
+ data={data}
+ columns={[
+ {
+ header: "Provider",
+ cell: (row) => {
+ if (row.provider === "global") {
+ return (
+ <div className="flex items-center space-x-2">
+ <span className="font-medium">Global (All Providers)</span>
+ </div>
+ );
+ }
+ const { displayName, logo } = getProviderDisplayInfo(row.provider);
+ return (
+ <div className="flex items-center space-x-2">
+ {logo && (
+ <img
+ src={logo}
+ alt={`${displayName} logo`}
+ className="w-5 h-5"
+ onError={(e) => handleImageError(e, displayName)}
+ />
+ )}
+ <span className="font-medium">{displayName}</span>
+ </div>
+ );
+ },
+ },
+ {
+ header: "Margin",
+ cell: (row) => (
+ <div className="flex items-center gap-2">
+ {editingProvider === row.provider ? (
+ <>
+ <div className="flex items-center gap-2">
+ <TextInput
+ value={editPercentage}
+ onValueChange={setEditPercentage}
+ placeholder="10"
+ className="w-20"
+ autoFocus
+ />
+ <span className="text-gray-600">%</span>
+ <span className="text-gray-400">+</span>
+ <span className="text-gray-600">$</span>
+ <TextInput
+ value={editFixedAmount}
+ onValueChange={setEditFixedAmount}
+ placeholder="0.001"
+ className="w-24"
+ />
+ </div>
+ <Icon
+ icon={CheckIcon}
+ size="sm"
+ onClick={() => handleSaveEdit(row.provider)}
+ className="cursor-pointer text-green-600 hover:text-green-700"
+ />
+ <Icon
+ icon={XIcon}
+ size="sm"
+ onClick={handleCancelEdit}
+ className="cursor-pointer text-gray-600 hover:text-gray-700"
+ />
+ </>
+ ) : (
+ <>
+ <Text className="font-medium">{formatMargin(row.margin)}</Text>
+ <Icon
+ icon={PencilAltIcon}
+ size="sm"
+ onClick={() => handleStartEdit(row.provider, row.margin)}
+ className="cursor-pointer text-blue-600 hover:text-blue-700"
+ />
+ </>
+ )}
+ </div>
+ ),
+ width: "350px",
+ },
+ {
+ header: "Actions",
+ cell: (row) => {
+ const displayName = row.provider === "global" ? "Global" : getProviderDisplayInfo(row.provider).displayName;
+ return (
+ <Icon
+ icon={TrashIcon}
+ size="sm"
+ onClick={() => onRemoveProvider(row.provider, displayName)}
+ className="cursor-pointer hover:text-red-600"
+ />
+ );
+ },
+ width: "80px",
+ },
+ ]}
+ getRowKey={(row) => row.provider}
+ emptyMessage="No provider margins configured"
+ />
+ );
+};
+
+export default ProviderMarginTable;
+
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/types.ts b/ui/litellm-dashboard/src/components/CostTrackingSettings/types.ts
index 55d49ecffd9..1e79110dfb3 100644
--- a/ui/litellm-dashboard/src/components/CostTrackingSettings/types.ts
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/types.ts
@@ -12,3 +12,11 @@ export interface CostDiscountResponse {
values: DiscountConfig;
}
+export interface MarginConfig {
+ [provider: string]: number | { percentage?: number; fixed_amount?: number };
+}
+
+export interface CostMarginResponse {
+ values: MarginConfig;
+}
+
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/use_discount_config.ts b/ui/litellm-dashboard/src/components/CostTrackingSettings/use_discount_config.ts
new file mode 100644
index 00000000000..0ed57aa8cc2
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/use_discount_config.ts
@@ -0,0 +1,151 @@
+import { useState, useCallback } from "react";
+import { getProxyBaseUrl } from "@/components/networking";
+import NotificationsManager from "../molecules/notifications_manager";
+import { DiscountConfig } from "./types";
+import { getProviderBackendValue } from "./provider_display_helpers";
+import { Providers } from "../provider_info_helpers";
+
+export interface UseDiscountConfigProps {
+ accessToken: string | null;
+}
+
+export interface UseDiscountConfigReturn {
+ discountConfig: DiscountConfig;
+ setDiscountConfig: React.Dispatch<React.SetStateAction<DiscountConfig>>;
+ fetchDiscountConfig: () => Promise<void>;
+ saveDiscountConfig: (config: DiscountConfig) => Promise<void>;
+ handleAddProvider: (selectedProvider: string | undefined, newDiscount: string) => Promise<boolean>;
+ handleRemoveProvider: (provider: string) => Promise<void>;
+ handleDiscountChange: (provider: string, value: string) => Promise<void>;
+}
+
+export function useDiscountConfig({ accessToken }: UseDiscountConfigProps): UseDiscountConfigReturn {
+ const [discountConfig, setDiscountConfig] = useState<DiscountConfig>({});
+
+ const fetchDiscountConfig = useCallback(async () => {
+ try {
+ const proxyBaseUrl = getProxyBaseUrl();
+ const url = proxyBaseUrl
+ ? `${proxyBaseUrl}/config/cost_discount_config`
+ : "/config/cost_discount_config";
+
+ const response = await fetch(url, {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ setDiscountConfig(data.values || {});
+ } else {
+ console.error("Failed to fetch discount config");
+ }
+ } catch (error) {
+ console.error("Error fetching discount config:", error);
+ NotificationsManager.fromBackend("Failed to fetch discount configuration");
+ }
+ }, [accessToken]);
+
+ const saveDiscountConfig = useCallback(async (config: DiscountConfig) => {
+ try {
+ const proxyBaseUrl = getProxyBaseUrl();
+ const url = proxyBaseUrl
+ ? `${proxyBaseUrl}/config/cost_discount_config`
+ : "/config/cost_discount_config";
+
+ const response = await fetch(url, {
+ method: "PATCH",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(config),
+ });
+
+ if (response.ok) {
+ NotificationsManager.success("Discount configuration updated successfully");
+ await fetchDiscountConfig();
+ } else {
+ const errorData = await response.json();
+ const errorMessage = errorData.detail?.error || errorData.detail || "Failed to update settings";
+ NotificationsManager.fromBackend(errorMessage);
+ }
+ } catch (error) {
+ console.error("Error updating discount config:", error);
+ NotificationsManager.fromBackend("Failed to update discount configuration");
+ }
+ }, [accessToken, fetchDiscountConfig]);
+
+ const handleAddProvider = useCallback(async (
+ selectedProvider: string | undefined,
+ newDiscount: string
+ ): Promise<boolean> => {
+ if (!selectedProvider || !newDiscount) {
+ NotificationsManager.fromBackend("Please select a provider and enter discount percentage");
+ return false;
+ }
+
+ const percentageValue = parseFloat(newDiscount);
+ if (isNaN(percentageValue) || percentageValue < 0 || percentageValue > 100) {
+ NotificationsManager.fromBackend("Discount must be between 0% and 100%");
+ return false;
+ }
+
+ const providerValue = getProviderBackendValue(selectedProvider);
+
+ if (!providerValue) {
+ NotificationsManager.fromBackend("Invalid provider selected");
+ return false;
+ }
+
+ if (discountConfig[providerValue]) {
+ NotificationsManager.fromBackend(
+ `Discount for ${Providers[selectedProvider as keyof typeof Providers]} already exists. Edit it in the table above.`
+ );
+ return false;
+ }
+
+ const discountValue = percentageValue / 100;
+ const updatedConfig = {
+ ...discountConfig,
+ [providerValue]: discountValue,
+ };
+
+ setDiscountConfig(updatedConfig);
+ await saveDiscountConfig(updatedConfig);
+ return true;
+ }, [discountConfig, saveDiscountConfig]);
+
+ const handleRemoveProvider = useCallback(async (provider: string) => {
+ const updatedConfig = { ...discountConfig };
+ delete updatedConfig[provider];
+ setDiscountConfig(updatedConfig);
+ await saveDiscountConfig(updatedConfig);
+ }, [discountConfig, saveDiscountConfig]);
+
+ const handleDiscountChange = useCallback(async (provider: string, value: string) => {
+ const discountValue = parseFloat(value);
+ if (!isNaN(discountValue) && discountValue >= 0 && discountValue <= 1) {
+ const updatedConfig = {
+ ...discountConfig,
+ [provider]: discountValue,
+ };
+ setDiscountConfig(updatedConfig);
+ await saveDiscountConfig(updatedConfig);
+ }
+ }, [discountConfig, saveDiscountConfig]);
+
+ return {
+ discountConfig,
+ setDiscountConfig,
+ fetchDiscountConfig,
+ saveDiscountConfig,
+ handleAddProvider,
+ handleRemoveProvider,
+ handleDiscountChange,
+ };
+}
+
diff --git a/ui/litellm-dashboard/src/components/CostTrackingSettings/use_margin_config.ts b/ui/litellm-dashboard/src/components/CostTrackingSettings/use_margin_config.ts
new file mode 100644
index 00000000000..f443e1c121e
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/CostTrackingSettings/use_margin_config.ts
@@ -0,0 +1,176 @@
+import { useState, useCallback } from "react";
+import { getProxyBaseUrl } from "@/components/networking";
+import NotificationsManager from "../molecules/notifications_manager";
+import { MarginConfig } from "./types";
+import { getProviderBackendValue } from "./provider_display_helpers";
+import { Providers } from "../provider_info_helpers";
+
+export interface UseMarginConfigProps {
+ accessToken: string | null;
+}
+
+export interface UseMarginConfigReturn {
+ marginConfig: MarginConfig;
+ setMarginConfig: React.Dispatch<React.SetStateAction<MarginConfig>>;
+ fetchMarginConfig: () => Promise<void>;
+ saveMarginConfig: (config: MarginConfig) => Promise<void>;
+ handleAddMargin: (params: AddMarginParams) => Promise<boolean>;
+ handleRemoveMargin: (provider: string) => Promise<void>;
+ handleMarginChange: (
+ provider: string,
+ value: number | { percentage?: number; fixed_amount?: number }
+ ) => Promise<void>;
+}
+
+export interface AddMarginParams {
+ selectedProvider: string | undefined;
+ marginType: "percentage" | "fixed";
+ percentageValue: string;
+ fixedAmountValue: string;
+}
+
+export function useMarginConfig({ accessToken }: UseMarginConfigProps): UseMarginConfigReturn {
+ const [marginConfig, setMarginConfig] = useState<MarginConfig>({});
+
+ const fetchMarginConfig = useCallback(async () => {
+ try {
+ const proxyBaseUrl = getProxyBaseUrl();
+ const url = proxyBaseUrl
+ ? `${proxyBaseUrl}/config/cost_margin_config`
+ : "/config/cost_margin_config";
+
+ const response = await fetch(url, {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ setMarginConfig(data.values || {});
+ } else {
+ console.error("Failed to fetch margin config");
+ }
+ } catch (error) {
+ console.error("Error fetching margin config:", error);
+ NotificationsManager.fromBackend("Failed to fetch margin configuration");
+ }
+ }, [accessToken]);
+
+ const saveMarginConfig = useCallback(async (config: MarginConfig) => {
+ try {
+ const proxyBaseUrl = getProxyBaseUrl();
+ const url = proxyBaseUrl
+ ? `${proxyBaseUrl}/config/cost_margin_config`
+ : "/config/cost_margin_config";
+
+ const response = await fetch(url, {
+ method: "PATCH",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(config),
+ });
+
+ if (response.ok) {
+ NotificationsManager.success("Margin configuration updated successfully");
+ await fetchMarginConfig();
+ } else {
+ const errorData = await response.json();
+ const errorMessage = errorData.detail?.error || errorData.detail || "Failed to update settings";
+ NotificationsManager.fromBackend(errorMessage);
+ }
+ } catch (error) {
+ console.error("Error updating margin config:", error);
+ NotificationsManager.fromBackend("Failed to update margin configuration");
+ }
+ }, [accessToken, fetchMarginConfig]);
+
+ const handleAddMargin = useCallback(async (params: AddMarginParams): Promise<boolean> => {
+ const { selectedProvider, marginType, percentageValue, fixedAmountValue } = params;
+
+ if (!selectedProvider) {
+ NotificationsManager.fromBackend("Please select a provider");
+ return false;
+ }
+
+ let providerValue: string;
+ if (selectedProvider === "global") {
+ providerValue = "global";
+ } else {
+ const backendValue = getProviderBackendValue(selectedProvider);
+ if (!backendValue) {
+ NotificationsManager.fromBackend("Invalid provider selected");
+ return false;
+ }
+ providerValue = backendValue;
+ }
+
+ if (marginConfig[providerValue]) {
+ const displayName = providerValue === "global" ? "Global" : Providers[selectedProvider as keyof typeof Providers];
+ NotificationsManager.fromBackend(
+ `Margin for ${displayName} already exists. Edit it in the table above.`
+ );
+ return false;
+ }
+
+ let marginValue: number | { fixed_amount?: number };
+ if (marginType === "percentage") {
+ const percentValue = parseFloat(percentageValue);
+ if (isNaN(percentValue) || percentValue < 0 || percentValue > 1000) {
+ NotificationsManager.fromBackend("Percentage must be between 0% and 1000%");
+ return false;
+ }
+ marginValue = percentValue / 100;
+ } else {
+ const fixedValue = parseFloat(fixedAmountValue);
+ if (isNaN(fixedValue) || fixedValue < 0) {
+ NotificationsManager.fromBackend("Fixed amount must be non-negative");
+ return false;
+ }
+ marginValue = { fixed_amount: fixedValue };
+ }
+
+ const updatedConfig = {
+ ...marginConfig,
+ [providerValue]: marginValue,
+ };
+
+ setMarginConfig(updatedConfig);
+ await saveMarginConfig(updatedConfig);
+ return true;
+ }, [marginConfig, saveMarginConfig]);
+
+ const handleRemoveMargin = useCallback(async (provider: string) => {
+ const updatedConfig = { ...marginConfig };
+ delete updatedConfig[provider];
+ setMarginConfig(updatedConfig);
+ await saveMarginConfig(updatedConfig);
+ }, [marginConfig, saveMarginConfig]);
+
+ const handleMarginChange = useCallback(async (
+ provider: string,
+ value: number | { percentage?: number; fixed_amount?: number }
+ ) => {
+ const updatedConfig = {
+ ...marginConfig,
+ [provider]: value,
+ };
+ setMarginConfig(updatedConfig);
+ await saveMarginConfig(updatedConfig);
+ }, [marginConfig, saveMarginConfig]);
+
+ return {
+ marginConfig,
+ setMarginConfig,
+ fetchMarginConfig,
+ saveMarginConfig,
+ handleAddMargin,
+ handleRemoveMargin,
+ handleMarginChange,
+ };
+}
+
diff --git a/ui/litellm-dashboard/src/components/view_logs/CostBreakdownViewer.tsx b/ui/litellm-dashboard/src/components/view_logs/CostBreakdownViewer.tsx
new file mode 100644
index 00000000000..affe28e0b25
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/view_logs/CostBreakdownViewer.tsx
@@ -0,0 +1,158 @@
+import React from "react";
+import { Accordion, AccordionHeader, AccordionBody } from "@tremor/react";
+import { formatNumberWithCommas } from "@/utils/dataUtils";
+
+export interface CostBreakdown {
+ input_cost?: number;
+ output_cost?: number;
+ total_cost?: number;
+ tool_usage_cost?: number;
+ original_cost?: number;
+ discount_percent?: number;
+ discount_amount?: number;
+ margin_percent?: number;
+ margin_fixed_amount?: number;
+ margin_total_amount?: number;
+}
+
+interface CostBreakdownViewerProps {
+ costBreakdown: CostBreakdown | null | undefined;
+ totalSpend: number;
+}
+
+const formatCost = (cost: number | undefined): string => {
+ if (cost === undefined || cost === null) return "-";
+ return `$${formatNumberWithCommas(cost, 8)}`;
+};
+
+const formatPercent = (percent: number | undefined): string => {
+ if (percent === undefined || percent === null) return "-";
+ return `${(percent * 100).toFixed(2)}%`;
+};
+
+export const CostBreakdownViewer: React.FC<CostBreakdownViewerProps> = ({
+ costBreakdown,
+ totalSpend,
+}) => {
+ if (!costBreakdown) {
+ return null;
+ }
+
+ const hasDiscount =
+ (costBreakdown.discount_percent !== undefined && costBreakdown.discount_percent !== 0) ||
+ (costBreakdown.discount_amount !== undefined && costBreakdown.discount_amount !== 0);
+
+ const hasMargin =
+ (costBreakdown.margin_percent !== undefined && costBreakdown.margin_percent !== 0) ||
+ (costBreakdown.margin_fixed_amount !== undefined && costBreakdown.margin_fixed_amount !== 0) ||
+ (costBreakdown.margin_total_amount !== undefined && costBreakdown.margin_total_amount !== 0);
+
+ // Don't show if there's no meaningful breakdown data
+ const hasMeaningfulData =
+ costBreakdown.input_cost !== undefined ||
+ costBreakdown.output_cost !== undefined ||
+ hasDiscount ||
+ hasMargin;
+
+ if (!hasMeaningfulData) {
+ return null;
+ }
+
+ return (
+ <div className="bg-white rounded-lg shadow w-full max-w-full overflow-hidden">
+ <Accordion>
+ <AccordionHeader className="p-4 border-b hover:bg-gray-50 transition-colors text-left">
+ <div className="flex items-center justify-between w-full">
+ <h3 className="text-lg font-medium text-gray-900">Cost Breakdown</h3>
+ <div className="flex items-center space-x-2 mr-4">
+ <span className="text-sm text-gray-500">Total:</span>
+ <span className="text-sm font-semibold text-gray-900">{formatCost(totalSpend)}</span>
+ </div>
+ </div>
+ </AccordionHeader>
+ <AccordionBody className="px-0">
+ <div className="p-6 space-y-4">
+ {/* Step 1: Base Token Costs */}
+ <div className="space-y-2 max-w-2xl">
+ <div className="flex text-sm">
+ <span className="text-gray-600 font-medium w-1/3">Input Cost:</span>
+ <span className="text-gray-900">{formatCost(costBreakdown.input_cost)}</span>
+ </div>
+ <div className="flex text-sm">
+ <span className="text-gray-600 font-medium w-1/3">Output Cost:</span>
+ <span className="text-gray-900">{formatCost(costBreakdown.output_cost)}</span>
+ </div>
+ {costBreakdown.tool_usage_cost !== undefined && costBreakdown.tool_usage_cost > 0 && (
+ <div className="flex text-sm">
+ <span className="text-gray-600 font-medium w-1/3">Tool Usage Cost:</span>
+ <span className="text-gray-900">{formatCost(costBreakdown.tool_usage_cost)}</span>
+ </div>
+ )}
+ </div>
+
+ {/* Subtotal / Original Cost */}
+ <div className="pt-2 border-t border-gray-100 max-w-2xl">
+ <div className="flex text-sm font-semibold">
+ <span className="text-gray-900 w-1/3">Original LLM Cost:</span>
+ <span className="text-gray-900">{formatCost(costBreakdown.original_cost)}</span>
+ </div>
+ </div>
+
+ {/* Step 2: Adjustments (Discount & Margin) */}
+ {(hasDiscount || hasMargin) && (
+ <div className="pt-2 space-y-2 max-w-2xl">
+ {/* Discounts */}
+ {hasDiscount && (
+ <div className="space-y-2">
+ {costBreakdown.discount_percent !== undefined && costBreakdown.discount_percent !== 0 && (
+ <div className="flex text-sm text-gray-600">
+ <span className="font-medium w-1/3">Discount ({formatPercent(costBreakdown.discount_percent)}):</span>
+ <span className="text-gray-900">-{formatCost(costBreakdown.discount_amount)}</span>
+ </div>
+ )}
+ {costBreakdown.discount_amount !== undefined && costBreakdown.discount_percent === undefined && (
+ <div className="flex text-sm text-gray-600">
+ <span className="font-medium w-1/3">Discount Amount:</span>
+ <span className="text-gray-900">-{formatCost(costBreakdown.discount_amount)}</span>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Margins */}
+ {hasMargin && (
+ <div className="space-y-2">
+ {costBreakdown.margin_percent !== undefined && costBreakdown.margin_percent !== 0 && (
+ <div className="flex text-sm text-gray-600">
+ <span className="font-medium w-1/3">Margin ({formatPercent(costBreakdown.margin_percent)}):</span>
+ <span className="text-gray-900">+{formatCost((costBreakdown.margin_total_amount || 0) - (costBreakdown.margin_fixed_amount || 0))}</span>
+ </div>
+ )}
+ {costBreakdown.margin_fixed_amount !== undefined && costBreakdown.margin_fixed_amount !== 0 && (
+ <div className="flex text-sm text-gray-600">
+ <span className="font-medium w-1/3">Margin:</span>
+ <span className="text-gray-900">+{formatCost(costBreakdown.margin_fixed_amount)}</span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Final Summary */}
+ <div className="mt-4 pt-4 border-t border-gray-200 max-w-2xl">
+ <div className="flex items-center">
+ <span className="font-bold text-sm text-gray-900 w-1/3">Final Calculated Cost:</span>
+ <span className="text-sm font-bold text-gray-900">
+ {formatCost(costBreakdown.total_cost ?? totalSpend)}
+ </span>
+ </div>
+ </div>
+ </div>
+ </AccordionBody>
+ </Accordion>
+ </div>
+ );
+};
+
+export default CostBreakdownViewer;
diff --git a/ui/litellm-dashboard/src/components/view_logs/index.tsx b/ui/litellm-dashboard/src/components/view_logs/index.tsx
index 2cd113bfb61..34aa0ef3be8 100644
--- a/ui/litellm-dashboard/src/components/view_logs/index.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/index.tsx
@@ -18,6 +18,7 @@ import KeyInfoView from "../templates/key_info_view";
import { SessionView } from "./SessionView";
import { VectorStoreViewer } from "./VectorStoreViewer";
import GuardrailViewer from "@/components/view_logs/GuardrailViewer/GuardrailViewer";
+import { CostBreakdownViewer } from "./CostBreakdownViewer";
import FilterComponent from "../molecules/filter";
import { FilterOption } from "../molecules/filter";
import { useLogFilterLogic } from "./log_filter_logic";
@@ -966,6 +967,12 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {
</div>
</div>
+ {/* Cost Breakdown - Show if cost breakdown data is available */}
+ <CostBreakdownViewer
+ costBreakdown={row.original.metadata?.cost_breakdown}
+ totalSpend={row.original.spend || 0}
+ />
+
{/* Configuration Info Message - Show when data is missing */}
<ConfigInfoMessage show={missingData} />