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] New Logging Integration - Azure Sentinel Logger (#18146)

Ishaan Jaff539f629eff4b
diff --git a/docs/my-website/docs/observability/azure_sentinel.md b/docs/my-website/docs/observability/azure_sentinel.md
new file mode 100644
index 00000000000..6e7e0541795
--- /dev/null
+++ b/docs/my-website/docs/observability/azure_sentinel.md
@@ -0,0 +1,238 @@
+import Image from '@theme/IdealImage';
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Azure Sentinel
+
+<Image img={require('../../img/sentinel.png')} />
+
+LiteLLM supports logging to Azure Sentinel via the Azure Monitor Logs Ingestion API. Azure Sentinel uses Log Analytics workspaces for data storage, so logs sent to the workspace will be available in Sentinel for security monitoring and analysis.
+
+## Azure Sentinel Integration
+
+| Feature | Details |
+|---------|---------|
+| **What is logged** | [StandardLoggingPayload](../proxy/logging_spec) |
+| **Events** | Success + Failure |
+| **Product Link** | [Azure Sentinel](https://learn.microsoft.com/en-us/azure/sentinel/overview) |
+| **API Reference** | [Logs Ingestion API](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview) |
+
+We will use the `--config` to set `litellm.callbacks = ["azure_sentinel"]` this will log all successful and failed LLM calls to Azure Sentinel.
+
+**Step 1**: Create a `config.yaml` file and set `litellm_settings`: `callbacks`
+
+```yaml showLineNumbers title="config.yaml"
+model_list:
+ - model_name: gpt-3.5-turbo
+ litellm_params:
+ model: gpt-3.5-turbo
+litellm_settings:
+ callbacks: ["azure_sentinel"] # logs llm success + failure logs to Azure Sentinel
+```
+
+**Step 2**: Set Up Azure Resources
+
+Before using the Logs Ingestion API, you need to set up the following in Azure:
+
+1. **Create a Log Analytics Workspace** (if you don't have one)
+2. **Create a Custom Table** in your Log Analytics workspace (e.g., `LiteLLM_CL`)
+3. **Create a Data Collection Rule (DCR)** with:
+ - Stream declaration matching your data structure
+ - Transformation to map data to your custom table
+ - Access granted to your app registration
+4. **Register an Application** in Microsoft Entra ID (Azure AD) with:
+ - Client ID
+ - Client Secret
+ - Permissions to write to the DCR
+
+For detailed setup instructions, see the [Microsoft documentation on Logs Ingestion API](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview).
+
+**Step 3**: Set Required Environment Variables
+
+Set the following environment variables with your Azure credentials:
+
+```shell showLineNumbers title="Environment Variables"
+# Required: Data Collection Rule (DCR) configuration
+AZURE_SENTINEL_DCR_IMMUTABLE_ID="dcr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # DCR Immutable ID from Azure portal
+AZURE_SENTINEL_STREAM_NAME="Custom-LiteLLM_CL_CL" # Stream name from your DCR
+AZURE_SENTINEL_ENDPOINT="https://your-dcr-endpoint.eastus-1.ingest.monitor.azure.com" # DCR logs ingestion endpoint (NOT the DCE endpoint)
+
+# Required: OAuth2 Authentication (App Registration)
+AZURE_SENTINEL_TENANT_ID="your-tenant-id" # Azure Tenant ID
+AZURE_SENTINEL_CLIENT_ID="your-client-id" # Application (client) ID
+AZURE_SENTINEL_CLIENT_SECRET="your-client-secret" # Client secret value
+
+```
+
+**Note**: The `AZURE_SENTINEL_ENDPOINT` should be the DCR's logs ingestion endpoint (found in the DCR Overview page), NOT the Data Collection Endpoint (DCE). The DCR endpoint is associated with your specific DCR and looks like: `https://your-dcr-endpoint.{region}-1.ingest.monitor.azure.com`
+
+**Step 4**: Start the proxy and make a test request
+
+Start proxy
+
+```shell showLineNumbers title="Start Proxy"
+litellm --config config.yaml --debug
+```
+
+Test Request
+
+```shell showLineNumbers title="Test Request"
+curl --location 'http://0.0.0.0:4000/chat/completions' \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "model": "gpt-3.5-turbo",
+ "messages": [
+ {
+ "role": "user",
+ "content": "what llm are you"
+ }
+ ],
+ "metadata": {
+ "your-custom-metadata": "custom-field",
+ }
+}'
+```
+
+**Step 5**: View logs in Azure Sentinel
+
+1. Navigate to your Azure Sentinel workspace in the Azure portal
+2. Go to "Logs" and query your custom table (e.g., `LiteLLM_CL`)
+3. Run a query like:
+
+```kusto showLineNumbers title="KQL Query"
+LiteLLM_CL
+| where TimeGenerated > ago(1h)
+| project TimeGenerated, model, status, total_tokens, response_cost
+| order by TimeGenerated desc
+```
+
+You should see following logs in Azure Workspace.
+
+<Image img={require('../../img/sentinel.png')} />
+
+## Environment Variables
+
+| Environment Variable | Description | Default Value | Required |
+|---------------------|-------------|---------------|----------|
+| `AZURE_SENTINEL_DCR_IMMUTABLE_ID` | Data Collection Rule (DCR) Immutable ID | None | ✅ Yes |
+| `AZURE_SENTINEL_ENDPOINT` | DCR logs ingestion endpoint URL (from DCR Overview page) | None | ✅ Yes |
+| `AZURE_SENTINEL_STREAM_NAME` | Stream name from DCR (e.g., "Custom-LiteLLM_CL_CL") | "Custom-LiteLLM" | ❌ No |
+| `AZURE_SENTINEL_TENANT_ID` | Azure Tenant ID for OAuth2 authentication | None (falls back to `AZURE_TENANT_ID`) | ✅ Yes |
+| `AZURE_SENTINEL_CLIENT_ID` | Application (client) ID for OAuth2 authentication | None (falls back to `AZURE_CLIENT_ID`) | ✅ Yes |
+| `AZURE_SENTINEL_CLIENT_SECRET` | Client secret for OAuth2 authentication | None (falls back to `AZURE_CLIENT_SECRET`) | ✅ Yes |
+
+## How It Works
+
+The Azure Sentinel integration uses the [Azure Monitor Logs Ingestion API](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview) to send logs to your Log Analytics workspace. The integration:
+
+- Authenticates using OAuth2 client credentials flow with your app registration
+- Sends logs to the Data Collection Rule (DCR) endpoint
+- Batches logs for efficient transmission
+- Sends logs in the [StandardLoggingPayload](../proxy/logging_spec) format
+- Automatically handles both success and failure events
+- Caches OAuth2 tokens and refreshes them automatically
+
+Logs sent to the Log Analytics workspace are automatically available in Azure Sentinel for security monitoring, threat detection, and analysis.
+
+## Azure Sentinel Setup Guide
+
+Follow this step-by-step guide to set up Azure Sentinel with LiteLLM.
+
+### Step 1: Create a Log Analytics Workspace
+
+1. Navigate to [https://portal.azure.com/#home](https://portal.azure.com/#home)
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/5659f6f5-a166-4b26-a991-73352274e3bb/ascreenshot.jpeg?tl_px=0,210&br_px=2618,1673&force_format=jpeg&q=100&width=1120.0)
+
+2. Search for "Log Analytics workspaces" and click "Create"
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/a827ba10-a391-486a-a36a-51816c6255de/ascreenshot.jpeg?tl_px=0,0&br_px=2618,1463&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=21,106)
+
+3. Enter a name for your workspace (e.g., "litellm-sentinel-prod")
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/943458f1-fd4c-47dd-a273-ea5a04734ed9/ascreenshot.jpeg?tl_px=0,420&br_px=2618,1884&force_format=jpeg&q=100&width=1120.0)
+
+4. Click "Review + Create"
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/c54828fb-f895-4eb7-b810-cacf437617bd/ascreenshot.jpeg?tl_px=0,420&br_px=2618,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=40,564)
+
+### Step 2: Create a Custom Table
+
+1. Go to your Log Analytics workspace and click "Tables"
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/72d65f70-75c0-471f-95e9-947c72e173cc/ascreenshot.jpeg?tl_px=0,142&br_px=2618,1605&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=330,277)
+
+2. Click "Create" → "New custom log (Direct Ingest)"
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/863ad29b-2c3a-4b7c-9a6b-36d3a76c9f32/ascreenshot.jpeg?tl_px=0,0&br_px=2618,1463&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=526,146)
+
+3. Enter a table name (e.g., "LITELLM_PROD_CL")
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/ef2f1c52-aa36-46a1-91e6-9bd868891b15/ascreenshot.jpeg?tl_px=0,0&br_px=2618,1463&force_format=jpeg&q=100&width=1120.0)
+
+### Step 3: Create a Data Collection Rule (DCR)
+
+1. Click "Create a new data collection rule"
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/f2abc0d3-8be8-4057-9290-946d10cfd183/ascreenshot.jpeg?tl_px=0,420&br_px=2618,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=264,404)
+
+2. Enter a name for the DCR (e.g., "litellm-prod")
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/79bbebdc-e4d9-46ff-a270-1930619050a1/ascreenshot.jpeg?tl_px=0,8&br_px=2618,1471&force_format=jpeg&q=100&width=1120.0)
+
+3. Select a Data Collection Endpoint
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/f3112e9a-551e-415c-a7f9-55aad801bc8a/ascreenshot.jpeg?tl_px=0,420&br_px=2618,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=332,480)
+
+4. Upload the sample JSON file for schema (use the [example_standard_logging_payload.json](https://github.com/BerriAI/litellm/blob/main/litellm/integrations/azure_sentinel/example_standard_logging_payload.json) file)
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/703c0762-840a-4f1f-a60f-876dc24b7a03/ascreenshot.jpeg?tl_px=0,0&br_px=2618,1463&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=518,272)
+
+5. Click "Next" and then "Create"
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/0bca0200-5c64-4fbd-8061-9308aa6656b8/ascreenshot.jpeg?tl_px=0,420&br_px=2618,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=128,560)
+
+### Step 4: Get the DCR Immutable ID and Logs Ingestion Endpoint
+
+1. Go to "Data Collection Rules" and select your DCR
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/11c06a0d-584f-4d22-b36e-9c338d43812c/ascreenshot.jpeg?tl_px=0,0&br_px=2618,1463&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=94,258)
+
+2. Copy the **DCR Immutable ID** (starts with `dcr-`)
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/cd0ad69a-4d95-4b6a-9533-7720908ba809/ascreenshot.jpeg?tl_px=1160,92&br_px=2618,907&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=530,277)
+
+3. Copy the **Logs Ingestion Endpoint** URL
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/3d3752ed-08ea-4490-8c98-a97d33947ea7/ascreenshot.jpeg?tl_px=1160,464&br_px=2618,1279&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=532,277)
+
+### Step 5: Get the Stream Name
+
+1. Click "JSON View" in the DCR
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/fd8a5504-4769-4f23-983e-520f256ee308/ascreenshot.jpeg?tl_px=1160,0&br_px=2618,814&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=965,257)
+
+2. Find the **Stream Name** in the `streamDeclarations` section (e.g., "Custom-LITELLM_PROD_CL_CL")
+
+![](https://ajeuwbhvhr.cloudimg.io/https://colony-recorder.s3.amazonaws.com/files/2025-12-17/a4052b32-2028-4d12-8930-bfcdf6f47652/ascreenshot.jpeg?tl_px=405,270&br_px=2115,1225&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=523,277)
+
+### Step 6: Register an App and Grant Permissions
+
+1. Go to **Microsoft Entra ID** → **App registrations** → **New registration**
+2. Create a new app and note the **Client ID** and **Tenant ID**
+3. Go to **Certificates & secrets** → Create a new client secret and copy the **Secret Value**
+4. Go back to your DCR → **Access Control (IAM)** → **Add role assignment**
+5. Assign the **"Monitoring Metrics Publisher"** role to your app registration
+
+### Summary: Where to Find Each Value
+
+| Environment Variable | Where to Find It |
+|---------------------|------------------|
+| `AZURE_SENTINEL_DCR_IMMUTABLE_ID` | DCR Overview page → Immutable ID (starts with `dcr-`) |
+| `AZURE_SENTINEL_ENDPOINT` | DCR Overview page → Logs Ingestion Endpoint |
+| `AZURE_SENTINEL_STREAM_NAME` | DCR JSON View → `streamDeclarations` section |
+| `AZURE_SENTINEL_TENANT_ID` | App Registration → Overview → Directory (tenant) ID |
+| `AZURE_SENTINEL_CLIENT_ID` | App Registration → Overview → Application (client) ID |
+| `AZURE_SENTINEL_CLIENT_SECRET` | App Registration → Certificates & secrets → Secret Value |
+
+For more details, refer to the [Microsoft Logs Ingestion API documentation](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview).
diff --git a/docs/my-website/docs/proxy/logging.md b/docs/my-website/docs/proxy/logging.md
index cf36963b7e1..30ffa585130 100644
--- a/docs/my-website/docs/proxy/logging.md
+++ b/docs/my-website/docs/proxy/logging.md
@@ -16,6 +16,7 @@ Log Proxy input, output, and exceptions using:
- Custom Callbacks - Custom code and API endpoints
- Langsmith
- DataDog
+- Azure Sentinel
- DynamoDB
- etc.
@@ -1574,6 +1575,10 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \
👉 Go here for using [Datadog LLM Observability](../observability/datadog) with LiteLLM Proxy
+## [Azure Sentinel](../observability/azure_sentinel)
+
+👉 Go here for using [Azure Sentinel](../observability/azure_sentinel) with LiteLLM Proxy
+
## Lunary
#### Step1: Install dependencies and set your environment variables
diff --git a/docs/my-website/img/sentinel.png b/docs/my-website/img/sentinel.png
new file mode 100644
index 00000000000..66c097253c5
Binary files /dev/null and b/docs/my-website/img/sentinel.png differ
diff --git a/litellm/__init__.py b/litellm/__init__.py
index b71240777f9..c85441e26c1 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -134,6 +134,7 @@ _custom_logger_compatible_callbacks_literal = Literal[
"weave_otel",
"pagerduty",
"humanloop",
+ "azure_sentinel",
"gcs_pubsub",
"agentops",
"anthropic_cache_control_hook",
diff --git a/litellm/integrations/azure_sentinel/__init__.py b/litellm/integrations/azure_sentinel/__init__.py
new file mode 100644
index 00000000000..46f2fed0a97
--- /dev/null
+++ b/litellm/integrations/azure_sentinel/__init__.py
@@ -0,0 +1,4 @@
+from litellm.integrations.azure_sentinel.azure_sentinel import AzureSentinelLogger
+
+__all__ = ["AzureSentinelLogger"]
+
diff --git a/litellm/integrations/azure_sentinel/azure_sentinel.py b/litellm/integrations/azure_sentinel/azure_sentinel.py
new file mode 100644
index 00000000000..875432de876
--- /dev/null
+++ b/litellm/integrations/azure_sentinel/azure_sentinel.py
@@ -0,0 +1,304 @@
+"""
+Azure Sentinel Integration - sends logs to Azure Log Analytics using Logs Ingestion API
+
+Azure Sentinel uses Log Analytics workspaces for data storage. This integration sends
+LiteLLM logs to the Log Analytics workspace using the Azure Monitor Logs Ingestion API.
+
+Reference API: https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview
+
+`async_log_success_event` - used by litellm proxy to send logs to Azure Sentinel
+`async_log_failure_event` - used by litellm proxy to send failure logs to Azure Sentinel
+
+For batching specific details see CustomBatchLogger class
+"""
+
+import asyncio
+import os
+import traceback
+from typing import List, Optional
+
+from litellm._logging import verbose_logger
+from litellm.integrations.custom_batch_logger import CustomBatchLogger
+from litellm.llms.custom_httpx.http_handler import (
+ get_async_httpx_client,
+ httpxSpecialProvider,
+)
+from litellm.types.utils import StandardLoggingPayload
+
+
+class AzureSentinelLogger(CustomBatchLogger):
+ """
+ Logger that sends LiteLLM logs to Azure Sentinel via Azure Monitor Logs Ingestion API
+ """
+
+ def __init__(
+ self,
+ dcr_immutable_id: Optional[str] = None,
+ stream_name: Optional[str] = None,
+ endpoint: Optional[str] = None,
+ tenant_id: Optional[str] = None,
+ client_id: Optional[str] = None,
+ client_secret: Optional[str] = None,
+ **kwargs,
+ ):
+ """
+ Initialize Azure Sentinel logger using Logs Ingestion API
+
+ Args:
+ dcr_immutable_id (str, optional): Data Collection Rule (DCR) Immutable ID.
+ If not provided, will use AZURE_SENTINEL_DCR_IMMUTABLE_ID env var.
+ stream_name (str, optional): Stream name from DCR (e.g., "Custom-LiteLLM").
+ If not provided, will use AZURE_SENTINEL_STREAM_NAME env var or default to "Custom-LiteLLM".
+ endpoint (str, optional): Data Collection Endpoint (DCE) or DCR ingestion endpoint.
+ If not provided, will use AZURE_SENTINEL_ENDPOINT env var.
+ tenant_id (str, optional): Azure Tenant ID for OAuth2 authentication.
+ If not provided, will use AZURE_SENTINEL_TENANT_ID or AZURE_TENANT_ID env var.
+ client_id (str, optional): Azure Client ID (Application ID) for OAuth2 authentication.
+ If not provided, will use AZURE_SENTINEL_CLIENT_ID or AZURE_CLIENT_ID env var.
+ client_secret (str, optional): Azure Client Secret for OAuth2 authentication.
+ If not provided, will use AZURE_SENTINEL_CLIENT_SECRET or AZURE_CLIENT_SECRET env var.
+ """
+ self.async_httpx_client = get_async_httpx_client(
+ llm_provider=httpxSpecialProvider.LoggingCallback
+ )
+
+ self.dcr_immutable_id = (
+ dcr_immutable_id or os.getenv("AZURE_SENTINEL_DCR_IMMUTABLE_ID")
+ )
+ self.stream_name = stream_name or os.getenv(
+ "AZURE_SENTINEL_STREAM_NAME", "Custom-LiteLLM"
+ )
+ self.endpoint = endpoint or os.getenv("AZURE_SENTINEL_ENDPOINT")
+ self.tenant_id = tenant_id or os.getenv("AZURE_SENTINEL_TENANT_ID") or os.getenv(
+ "AZURE_TENANT_ID"
+ )
+ self.client_id = client_id or os.getenv("AZURE_SENTINEL_CLIENT_ID") or os.getenv(
+ "AZURE_CLIENT_ID"
+ )
+ self.client_secret = (
+ client_secret
+ or os.getenv("AZURE_SENTINEL_CLIENT_SECRET")
+ or os.getenv("AZURE_CLIENT_SECRET")
+ )
+
+ if not self.dcr_immutable_id:
+ raise ValueError(
+ "AZURE_SENTINEL_DCR_IMMUTABLE_ID is required. Set it as an environment variable or pass dcr_immutable_id parameter."
+ )
+ if not self.endpoint:
+ raise ValueError(
+ "AZURE_SENTINEL_ENDPOINT is required. Set it as an environment variable or pass endpoint parameter."
+ )
+ if not self.tenant_id:
+ raise ValueError(
+ "AZURE_SENTINEL_TENANT_ID or AZURE_TENANT_ID is required. Set it as an environment variable or pass tenant_id parameter."
+ )
+ if not self.client_id:
+ raise ValueError(
+ "AZURE_SENTINEL_CLIENT_ID or AZURE_CLIENT_ID is required. Set it as an environment variable or pass client_id parameter."
+ )
+ if not self.client_secret:
+ raise ValueError(
+ "AZURE_SENTINEL_CLIENT_SECRET or AZURE_CLIENT_SECRET is required. Set it as an environment variable or pass client_secret parameter."
+ )
+
+ # Build API endpoint: {Endpoint}/dataCollectionRules/{DCR Immutable ID}/streams/{Stream Name}?api-version=2023-01-01
+ self.api_endpoint = (
+ f"{self.endpoint.rstrip('/')}/dataCollectionRules/{self.dcr_immutable_id}/streams/{self.stream_name}?api-version=2023-01-01"
+ )
+
+ # OAuth2 scope for Azure Monitor
+ self.oauth_scope = "https://monitor.azure.com/.default"
+ self.oauth_token: Optional[str] = None
+ self.oauth_token_expires_at: Optional[float] = None
+
+ self.flush_lock = asyncio.Lock()
+ super().__init__(**kwargs, flush_lock=self.flush_lock)
+ asyncio.create_task(self.periodic_flush())
+ self.log_queue: List[StandardLoggingPayload] = []
+
+ async def _get_oauth_token(self) -> str:
+ """
+ Get OAuth2 Bearer token for Azure Monitor Logs Ingestion API
+
+ Returns:
+ Bearer token string
+ """
+ # Check if we have a valid cached token
+ import time
+
+ if (
+ self.oauth_token
+ and self.oauth_token_expires_at
+ and time.time() < self.oauth_token_expires_at - 60
+ ): # Refresh 60 seconds before expiry
+ return self.oauth_token
+
+ # Get new token using client credentials flow
+ assert self.tenant_id is not None, "tenant_id is required"
+ assert self.client_id is not None, "client_id is required"
+ assert self.client_secret is not None, "client_secret is required"
+
+ token_url = f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/v2.0/token"
+
+ token_data = {
+ "client_id": self.client_id,
+ "client_secret": self.client_secret,
+ "scope": self.oauth_scope,
+ "grant_type": "client_credentials",
+ }
+
+ response = await self.async_httpx_client.post(
+ url=token_url,
+ data=token_data,
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+
+ if response.status_code != 200:
+ raise Exception(
+ f"Failed to get OAuth2 token: {response.status_code} - {response.text}"
+ )
+
+ token_response = response.json()
+ self.oauth_token = token_response.get("access_token")
+ expires_in = token_response.get("expires_in", 3600)
+
+ if not self.oauth_token:
+ raise Exception("OAuth2 token response did not contain access_token")
+
+ # Cache token expiry time
+ import time
+
+ self.oauth_token_expires_at = time.time() + expires_in
+
+ return self.oauth_token
+
+ async def async_log_success_event(
+ self, kwargs, response_obj, start_time, end_time
+ ):
+ """
+ Async Log success events to Azure Sentinel
+
+ - Gets StandardLoggingPayload from kwargs
+ - Adds to batch queue
+ - Flushes based on CustomBatchLogger settings
+
+ Raises:
+ Raises a NON Blocking verbose_logger.exception if an error occurs
+ """
+ try:
+ verbose_logger.debug(
+ "Azure Sentinel: Logging - Enters logging function for model %s", kwargs
+ )
+ standard_logging_payload = kwargs.get("standard_logging_object", None)
+
+ if standard_logging_payload is None:
+ verbose_logger.warning(
+ "Azure Sentinel: standard_logging_object not found in kwargs"
+ )
+ return
+
+ self.log_queue.append(standard_logging_payload)
+
+ if len(self.log_queue) >= self.batch_size:
+ await self.async_send_batch()
+
+ except Exception as e:
+ verbose_logger.exception(
+ f"Azure Sentinel Layer Error - {str(e)}\n{traceback.format_exc()}"
+ )
+ pass
+
+ async def async_log_failure_event(
+ self, kwargs, response_obj, start_time, end_time
+ ):
+ """
+ Async Log failure events to Azure Sentinel
+
+ - Gets StandardLoggingPayload from kwargs
+ - Adds to batch queue
+ - Flushes based on CustomBatchLogger settings
+
+ Raises:
+ Raises a NON Blocking verbose_logger.exception if an error occurs
+ """
+ try:
+ verbose_logger.debug(
+ "Azure Sentinel: Logging - Enters failure logging function for model %s",
+ kwargs,
+ )
+ standard_logging_payload = kwargs.get("standard_logging_object", None)
+
+ if standard_logging_payload is None:
+ verbose_logger.warning(
+ "Azure Sentinel: standard_logging_object not found in kwargs"
+ )
+ return
+
+ self.log_queue.append(standard_logging_payload)
+
+ if len(self.log_queue) >= self.batch_size:
+ await self.async_send_batch()
+
+ except Exception as e:
+ verbose_logger.exception(
+ f"Azure Sentinel Layer Error - {str(e)}\n{traceback.format_exc()}"
+ )
+ pass
+
+ async def async_send_batch(self):
+ """
+ Sends the batch of logs to Azure Monitor Logs Ingestion API
+
+ Raises:
+ Raises a NON Blocking verbose_logger.exception if an error occurs
+ """
+ try:
+ if not self.log_queue:
+ return
+
+ verbose_logger.debug(
+ "Azure Sentinel - about to flush %s events", len(self.log_queue)
+ )
+
+ from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+
+ # Get OAuth2 token
+ bearer_token = await self._get_oauth_token()
+
+ # Convert log queue to JSON array format expected by Logs Ingestion API
+ # Each log entry should be a JSON object in the array
+ body = safe_dumps(self.log_queue)
+
+ # Set headers for Logs Ingestion API
+ headers = {
+ "Authorization": f"Bearer {bearer_token}",
+ "Content-Type": "application/json",
+ }
+
+ # Send the request
+ response = await self.async_httpx_client.post(
+ url=self.api_endpoint, data=body.encode("utf-8"), headers=headers
+ )
+
+ if response.status_code not in [200, 204]:
+ verbose_logger.error(
+ "Azure Sentinel API error: status_code=%s, response=%s",
+ response.status_code,
+ response.text,
+ )
+ raise Exception(
+ f"Failed to send logs to Azure Sentinel: {response.status_code} - {response.text}"
+ )
+
+ verbose_logger.debug(
+ "Azure Sentinel: Response from API status_code: %s",
+ response.status_code,
+ )
+
+ except Exception as e:
+ verbose_logger.exception(
+ f"Azure Sentinel Error sending batch API - {str(e)}\n{traceback.format_exc()}"
+ )
+ finally:
+ self.log_queue.clear()
diff --git a/litellm/integrations/azure_sentinel/example_standard_logging_payload.json b/litellm/integrations/azure_sentinel/example_standard_logging_payload.json
new file mode 100644
index 00000000000..a9ef7d8557b
--- /dev/null
+++ b/litellm/integrations/azure_sentinel/example_standard_logging_payload.json
@@ -0,0 +1,179 @@
+{
+ "id": "chatcmpl-2299b6a2-82a3-465a-b47c-04e685a2227f",
+ "trace_id": "97311c60-9a61-4f48-a814-70139ee57868",
+ "call_type": "acompletion",
+ "cache_hit": null,
+ "stream": true,
+ "status": "success",
+ "custom_llm_provider": "openai",
+ "saved_cache_cost": 0.0,
+ "startTime": 1766000068.28466,
+ "endTime": 1766000070.07935,
+ "completionStartTime": 1766000070.07935,
+ "response_time": 1.79468512535095,
+ "model": "gpt-4o",
+ "metadata": {
+ "user_api_key_hash": null,
+ "user_api_key_alias": null,
+ "user_api_key_team_id": null,
+ "user_api_key_org_id": null,
+ "user_api_key_user_id": null,
+ "user_api_key_team_alias": null,
+ "user_api_key_user_email": null,
+ "spend_logs_metadata": null,
+ "requester_ip_address": null,
+ "requester_metadata": null,
+ "user_api_key_end_user_id": null,
+ "prompt_management_metadata": null,
+ "applied_guardrails": [],
+ "mcp_tool_call_metadata": null,
+ "vector_store_request_metadata": null,
+ "guardrail_information": null
+ },
+ "cache_key": null,
+ "response_cost": 0.00022500000000000002,
+ "total_tokens": 30,
+ "prompt_tokens": 10,
+ "completion_tokens": 20,
+ "request_tags": [],
+ "end_user": "",
+ "api_base": "",
+ "model_group": "",
+ "model_id": "",
+ "requester_ip_address": null,
+ "messages": [
+ {
+ "role": "user",
+ "content": "Hello, world!"
+ }
+ ],
+ "response": {
+ "id": "chatcmpl-2299b6a2-82a3-465a-b47c-04e685a2227f",
+ "created": 1742855151,
+ "model": "gpt-4o",
+ "object": "chat.completion",
+ "system_fingerprint": null,
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {
+ "content": "hi",
+ "role": "assistant",
+ "tool_calls": null,
+ "function_call": null,
+ "provider_specific_fields": null
+ }
+ }
+ ],
+ "usage": {
+ "completion_tokens": 20,
+ "prompt_tokens": 10,
+ "total_tokens": 30,
+ "completion_tokens_details": null,
+ "prompt_tokens_details": null
+ }
+ },
+ "model_parameters": {},
+ "hidden_params": {
+ "model_id": null,
+ "cache_key": null,
+ "api_base": "https://api.openai.com",
+ "response_cost": 0.00022500000000000002,
+ "additional_headers": {},
+ "litellm_overhead_time_ms": null,
+ "batch_models": null,
+ "litellm_model_name": "gpt-4o"
+ },
+ "model_map_information": {
+ "model_map_key": "gpt-4o",
+ "model_map_value": {
+ "key": "gpt-4o",
+ "max_tokens": 16384,
+ "max_input_tokens": 128000,
+ "max_output_tokens": 16384,
+ "input_cost_per_token": 2.5e-06,
+ "cache_creation_input_token_cost": null,
+ "cache_read_input_token_cost": 1.25e-06,
+ "input_cost_per_character": null,
+ "input_cost_per_token_above_128k_tokens": null,
+ "input_cost_per_query": null,
+ "input_cost_per_second": null,
+ "input_cost_per_audio_token": null,
+ "input_cost_per_token_batches": 1.25e-06,
+ "output_cost_per_token_batches": 5e-06,
+ "output_cost_per_token": 1e-05,
+ "output_cost_per_audio_token": null,
+ "output_cost_per_character": null,
+ "output_cost_per_token_above_128k_tokens": null,
+ "output_cost_per_character_above_128k_tokens": null,
+ "output_cost_per_second": null,
+ "output_cost_per_image": null,
+ "output_vector_size": null,
+ "litellm_provider": "openai",
+ "mode": "chat",
+ "supports_system_messages": true,
+ "supports_response_schema": true,
+ "supports_vision": true,
+ "supports_function_calling": true,
+ "supports_tool_choice": true,
+ "supports_assistant_prefill": false,
+ "supports_prompt_caching": true,
+ "supports_audio_input": false,
+ "supports_audio_output": false,
+ "supports_pdf_input": false,
+ "supports_embedding_image_input": false,
+ "supports_native_streaming": null,
+ "supports_web_search": true,
+ "search_context_cost_per_query": {
+ "search_context_size_low": 0.03,
+ "search_context_size_medium": 0.035,
+ "search_context_size_high": 0.05
+ },
+ "tpm": null,
+ "rpm": null,
+ "supported_openai_params": [
+ "frequency_penalty",
+ "logit_bias",
+ "logprobs",
+ "top_logprobs",
+ "max_tokens",
+ "max_completion_tokens",
+ "modalities",
+ "prediction",
+ "n",
+ "presence_penalty",
+ "seed",
+ "stop",
+ "stream",
+ "stream_options",
+ "temperature",
+ "top_p",
+ "tools",
+ "tool_choice",
+ "function_call",
+ "functions",
+ "max_retries",
+ "extra_headers",
+ "parallel_tool_calls",
+ "audio",
+ "response_format",
+ "user"
+ ]
+ }
+ },
+ "error_str": null,
+ "error_information": {
+ "error_code": "",
+ "error_class": "",
+ "llm_provider": "",
+ "traceback": "",
+ "error_message": ""
+ },
+ "response_cost_failure_debug_info": null,
+ "guardrail_information": null,
+ "standard_built_in_tools_params": {
+ "web_search_options": null,
+ "file_search": null
+ }
+ }
diff --git a/litellm/interactions/http_handler.py b/litellm/interactions/http_handler.py
index 5555b1d7e32..4b4ed9be4db 100644
--- a/litellm/interactions/http_handler.py
+++ b/litellm/interactions/http_handler.py
@@ -4,7 +4,6 @@ HTTP Handler for Interactions API requests.
This module handles the HTTP communication for the Google Interactions API.
"""
-import json
from typing import (
Any,
AsyncIterator,
@@ -18,7 +17,6 @@ from typing import (
import httpx
import litellm
-from litellm._logging import verbose_logger
from litellm.constants import request_timeout
from litellm.interactions.streaming_iterator import (
InteractionsAPIStreamingIterator,
diff --git a/litellm/interactions/streaming_iterator.py b/litellm/interactions/streaming_iterator.py
index ad18477663c..f65d08d3ca9 100644
--- a/litellm/interactions/streaming_iterator.py
+++ b/litellm/interactions/streaming_iterator.py
@@ -8,11 +8,10 @@ from the Google Interactions API, similar to the responses API streaming iterato
import asyncio
import json
from datetime import datetime
-from typing import Any, Dict, Iterator, Optional
+from typing import Any, Dict, Optional
import httpx
-import litellm
from litellm._logging import verbose_logger
from litellm.constants import STREAM_SSE_DONE_STRING
from litellm.litellm_core_utils.asyncify import run_async_function
@@ -22,7 +21,6 @@ from litellm.litellm_core_utils.llm_response_utils.get_api_base import get_api_b
from litellm.litellm_core_utils.thread_pool_executor import executor
from litellm.llms.base_llm.interactions.transformation import BaseInteractionsAPIConfig
from litellm.types.interactions import (
- InteractionsAPIResponse,
InteractionsAPIStreamingResponse,
)
from litellm.utils import CustomStreamWrapper
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index ba516c1b78b..378c201f7a3 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -127,6 +127,7 @@ from litellm.utils import _get_base_model_from_metadata, executor, print_verbose
from ..integrations.argilla import ArgillaLogger
from ..integrations.arize.arize_phoenix import ArizePhoenixLogger
from ..integrations.athina import AthinaLogger
+from ..integrations.azure_sentinel.azure_sentinel import AzureSentinelLogger
from ..integrations.azure_storage.azure_storage import AzureBlobStorageLogger
from ..integrations.custom_prompt_management import CustomPromptManagement
from ..integrations.datadog.datadog import DataDogLogger
@@ -3550,6 +3551,14 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
_datadog_llm_obs_logger = DataDogLLMObsLogger()
_in_memory_loggers.append(_datadog_llm_obs_logger)
return _datadog_llm_obs_logger # type: ignore
+ elif logging_integration == "azure_sentinel":
+ for callback in _in_memory_loggers:
+ if isinstance(callback, AzureSentinelLogger):
+ return callback # type: ignore
+
+ _azure_sentinel_logger = AzureSentinelLogger()
+ _in_memory_loggers.append(_azure_sentinel_logger)
+ return _azure_sentinel_logger # type: ignore
elif logging_integration == "gcs_bucket":
for callback in _in_memory_loggers:
if isinstance(callback, GCSBucketLogger):
@@ -4054,6 +4063,10 @@ def get_custom_logger_compatible_class( # noqa: PLR0915
for callback in _in_memory_loggers:
if isinstance(callback, DataDogLLMObsLogger):
return callback
+ elif logging_integration == "azure_sentinel":
+ for callback in _in_memory_loggers:
+ if isinstance(callback, AzureSentinelLogger):
+ return callback
elif logging_integration == "gcs_bucket":
for callback in _in_memory_loggers:
if isinstance(callback, GCSBucketLogger):
diff --git a/litellm/proxy/google_endpoints/endpoints.py b/litellm/proxy/google_endpoints/endpoints.py
index cc0719235ac..569634ee140 100644
--- a/litellm/proxy/google_endpoints/endpoints.py
+++ b/litellm/proxy/google_endpoints/endpoints.py
@@ -1,6 +1,4 @@
-from typing import Optional
-
-from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
+from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import ORJSONResponse, StreamingResponse
from litellm.proxy._types import *
diff --git a/litellm/types/integrations/azure_sentinel.py b/litellm/types/integrations/azure_sentinel.py
new file mode 100644
index 00000000000..f821dc9733b
--- /dev/null
+++ b/litellm/types/integrations/azure_sentinel.py
@@ -0,0 +1,12 @@
+from typing import Optional
+
+from litellm.types.integrations.custom_logger import StandardCustomLoggerInitParams
+
+
+class AzureSentinelInitParams(StandardCustomLoggerInitParams):
+ """
+ Params for initializing an Azure Sentinel logger on litellm
+ """
+
+ pass
+
diff --git a/tests/test_litellm/integrations/test_azure_sentinel.py b/tests/test_litellm/integrations/test_azure_sentinel.py
new file mode 100644
index 00000000000..2f7cd883eac
--- /dev/null
+++ b/tests/test_litellm/integrations/test_azure_sentinel.py
@@ -0,0 +1,92 @@
+"""
+Test Azure Sentinel logging integration
+"""
+
+import datetime
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from litellm.integrations.azure_sentinel.azure_sentinel import AzureSentinelLogger
+from litellm.types.utils import StandardLoggingPayload
+
+
+async def test_azure_sentinel_oauth_and_send_batch():
+ """Test that Azure Sentinel logger gets OAuth token and sends batch to API"""
+ test_dcr_id = "dcr-test123456789"
+ test_endpoint = "https://test-dce.eastus-1.ingest.monitor.azure.com"
+ test_tenant_id = "test-tenant-id"
+ test_client_id = "test-client-id"
+ test_client_secret = "test-client-secret"
+
+ with patch("asyncio.create_task"):
+ logger = AzureSentinelLogger(
+ dcr_immutable_id=test_dcr_id,
+ endpoint=test_endpoint,
+ tenant_id=test_tenant_id,
+ client_id=test_client_id,
+ client_secret=test_client_secret,
+ )
+
+ # Create test payload
+ standard_payload = StandardLoggingPayload(
+ id="test_id",
+ call_type="completion",
+ model="gpt-3.5-turbo",
+ status="success",
+ messages=[{"role": "user", "content": "Hello"}],
+ response={"choices": [{"message": {"content": "Hi"}}]},
+ )
+
+ # Add to queue
+ logger.log_queue.append(standard_payload)
+
+ # Mock OAuth token response
+ from unittest.mock import MagicMock
+
+ mock_token_response = MagicMock()
+ mock_token_response.status_code = 200
+ mock_token_response.json = MagicMock(return_value={
+ "access_token": "test-bearer-token",
+ "expires_in": 3600,
+ })
+ mock_token_response.text = "Success"
+
+ # Mock API response
+ mock_api_response = MagicMock()
+ mock_api_response.status_code = 204
+ mock_api_response.text = "Success"
+
+ # Mock HTTP client - first call for token, second for API
+ async def mock_post(*args, **kwargs):
+ if "oauth2/v2.0/token" in kwargs.get("url", ""):
+ return mock_token_response
+ return mock_api_response
+
+ logger.async_httpx_client.post = AsyncMock(side_effect=mock_post)
+
+ # Send batch
+ await logger.async_send_batch()
+
+ # Verify OAuth token request was made
+ assert logger.async_httpx_client.post.called
+
+ # Verify API request was made
+ call_count = logger.async_httpx_client.post.call_count
+ assert call_count >= 2 # At least token + API call
+
+ # Get the API call (last call)
+ api_call_args = logger.async_httpx_client.post.call_args_list[-1]
+ assert test_dcr_id in api_call_args.kwargs["url"]
+ assert test_endpoint in api_call_args.kwargs["url"]
+
+ # Verify headers
+ headers = api_call_args.kwargs["headers"]
+ assert headers["Content-Type"] == "application/json"
+ assert "Authorization" in headers
+ assert headers["Authorization"].startswith("Bearer ")
+
+ # Verify queue is cleared
+ assert len(logger.log_queue) == 0
+
diff --git a/tests/test_litellm/router_utils/test_router_interactions_endpoints.py b/tests/test_litellm/router_utils/test_router_interactions_endpoints.py
new file mode 100644
index 00000000000..5c6163d7141
--- /dev/null
+++ b/tests/test_litellm/router_utils/test_router_interactions_endpoints.py
@@ -0,0 +1,143 @@
+"""
+Tests for Router interactions API endpoint initialization functions.
+"""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from litellm import Router
+
+
+class TestInitializeInteractionsEndpoints:
+ """Test cases for _initialize_interactions_endpoints method"""
+
+ def test_initialize_interactions_endpoints_creates_methods(self):
+ """Test that _initialize_interactions_endpoints creates the expected interaction methods on the router."""
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "gpt-4"},
+ }
+ ]
+ )
+
+ # Verify the interaction methods are created
+ assert hasattr(router, "acreate_interaction")
+ assert hasattr(router, "create_interaction")
+ assert hasattr(router, "aget_interaction")
+ assert hasattr(router, "get_interaction")
+ assert hasattr(router, "adelete_interaction")
+ assert hasattr(router, "delete_interaction")
+ assert hasattr(router, "acancel_interaction")
+ assert hasattr(router, "cancel_interaction")
+
+ # Verify they are callable
+ assert callable(router.acreate_interaction)
+ assert callable(router.create_interaction)
+ assert callable(router.aget_interaction)
+ assert callable(router.get_interaction)
+
+ def test_initialize_interactions_endpoints_can_be_called_directly(self):
+ """Test that _initialize_interactions_endpoints can be called directly to reinitialize endpoints."""
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "gpt-4"},
+ }
+ ]
+ )
+
+ # Call _initialize_interactions_endpoints directly
+ router._initialize_interactions_endpoints()
+
+ # Verify the interaction methods still exist after re-initialization
+ assert hasattr(router, "acreate_interaction")
+ assert hasattr(router, "create_interaction")
+ assert callable(router.acreate_interaction)
+
+
+class TestInitInteractionsApiEndpoints:
+ """Test cases for _init_interactions_api_endpoints method"""
+
+ @pytest.mark.asyncio
+ async def test_init_interactions_api_endpoints_passes_custom_llm_provider(self):
+ """Test that _init_interactions_api_endpoints passes custom_llm_provider to the original function."""
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "gpt-4"},
+ }
+ ]
+ )
+
+ mock_function = AsyncMock(return_value={"result": "success"})
+
+ result = await router._init_interactions_api_endpoints(
+ original_function=mock_function,
+ custom_llm_provider="gemini",
+ interaction_id="test-id",
+ )
+
+ mock_function.assert_called_once_with(
+ custom_llm_provider="gemini",
+ interaction_id="test-id",
+ )
+ assert result == {"result": "success"}
+
+ @pytest.mark.asyncio
+ async def test_init_interactions_api_endpoints_defaults_to_gemini(self):
+ """Test that _init_interactions_api_endpoints defaults to gemini when no custom_llm_provider is specified."""
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "gpt-4"},
+ }
+ ]
+ )
+
+ mock_function = AsyncMock(return_value={"result": "success"})
+
+ result = await router._init_interactions_api_endpoints(
+ original_function=mock_function,
+ interaction_id="test-id",
+ )
+
+ mock_function.assert_called_once_with(
+ custom_llm_provider="gemini",
+ interaction_id="test-id",
+ )
+ assert result == {"result": "success"}
+
+ @pytest.mark.asyncio
+ async def test_init_interactions_api_endpoints_does_not_override_existing_provider(
+ self,
+ ):
+ """Test that _init_interactions_api_endpoints does not override custom_llm_provider if already in kwargs."""
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "gpt-4"},
+ }
+ ]
+ )
+
+ mock_function = AsyncMock(return_value={"result": "success"})
+
+ # Pass custom_llm_provider in kwargs directly (not as separate param)
+ result = await router._init_interactions_api_endpoints(
+ original_function=mock_function,
+ custom_llm_provider="vertex_ai",
+ )
+
+ # Should use the provided custom_llm_provider
+ mock_function.assert_called_once_with(
+ custom_llm_provider="vertex_ai",
+ )
+ assert result == {"result": "success"}
+