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]

add support to parse metadata (#10832)

Jugal D. Bhatt468b881ec5e8
diff --git a/litellm/litellm_core_utils/safe_json_loads.py b/litellm/litellm_core_utils/safe_json_loads.py
new file mode 100644
index 00000000000..a7ab0d3e3b5
--- /dev/null
+++ b/litellm/litellm_core_utils/safe_json_loads.py
@@ -0,0 +1,14 @@
+"""
+Helper for safe JSON loading in LiteLLM.
+"""
+from typing import Any
+import json
+
+def safe_json_loads(data: str, default: Any = None) -> Any:
+ """
+ Safely parse a JSON string. If parsing fails, return the default value (None by default).
+ """
+ try:
+ return json.loads(data)
+ except Exception:
+ return default
\ No newline at end of file
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index e81501eebe3..84e154f759f 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -26,6 +26,7 @@ from litellm.types.utils import (
StandardLoggingUserAPIKeyMetadata,
SupportedCacheControls,
)
+from litellm.litellm_core_utils.safe_json_loads import safe_json_loads
service_logger_obj = ServiceLogging() # used for tracking latency on OTEL
@@ -533,8 +534,12 @@ async def add_litellm_data_to_request( # noqa: PLR0915
if data.get(_metadata_variable_name, None) is None:
data[_metadata_variable_name] = {}
- # We want to log the "metadata" from the client side request. Avoid circular reference by not directly assigning metadata to itself.
+ # Parse metadata if it's a string (e.g., from multipart/form-data)
if "metadata" in data and data["metadata"] is not None:
+ if isinstance(data["metadata"], str):
+ data["metadata"] = safe_json_loads(data["metadata"])
+ if not isinstance(data["metadata"], dict):
+ verbose_proxy_logger.warning(f"Failed to parse 'metadata' as JSON dict. Received value: {data['metadata']}")
data[_metadata_variable_name]["requester_metadata"] = copy.deepcopy(
data["metadata"]
)
diff --git a/tests/litellm/proxy/test_litellm_pre_call_utils.py b/tests/litellm/proxy/test_litellm_pre_call_utils.py
index 94f2c512ea9..a390c2e072a 100644
--- a/tests/litellm/proxy/test_litellm_pre_call_utils.py
+++ b/tests/litellm/proxy/test_litellm_pre_call_utils.py
@@ -4,11 +4,15 @@ import sys
from unittest.mock import MagicMock, patch
import pytest
+import asyncio
+import copy
+from fastapi import Request
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.litellm_pre_call_utils import (
_get_enforced_params,
check_if_token_is_service_account,
+ add_litellm_data_to_request,
)
sys.path.insert(
@@ -103,3 +107,111 @@ def test_get_enforced_params(
enforced_params = _get_enforced_params(general_settings, user_api_key_dict)
assert enforced_params == expected_enforced_params
+
+
+async def test_add_litellm_data_to_request_parses_string_metadata():
+ from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
+
+ # Setup
+ request_mock = MagicMock(spec=Request)
+ request_mock.url.path = "/v1/completions"
+ request_mock.url = MagicMock()
+ request_mock.url.__str__.return_value = "http://localhost/v1/completions"
+ request_mock.method = "POST"
+ request_mock.query_params = {}
+ request_mock.headers = {"Content-Type": "application/json"}
+ request_mock.client = MagicMock()
+ request_mock.client.host = "127.0.0.1"
+
+ # Simulate data with stringified metadata
+ fake_metadata = {"generation_name": "gen123"}
+ data = {"metadata": json.dumps(fake_metadata), "model": "gpt-3.5-turbo"}
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-key",
+ metadata={},
+ team_metadata={},
+ spend=0.0,
+ max_budget=100.0,
+ model_max_budget={}, # this one can be a dict
+ team_spend=0.0,
+ team_max_budget=200.0,
+ )
+
+ # Call
+ updated_data = await add_litellm_data_to_request(
+ data=data,
+ request=request_mock,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=MagicMock(),
+ general_settings={},
+ version="test-version",
+ )
+
+ # Assert
+ litellm_metadata = updated_data.get("metadata", {})
+ assert isinstance(litellm_metadata, dict)
+ assert updated_data["metadata"]["generation_name"] == "gen123"
+
+
+async def test_add_litellm_data_to_request_audio_transcription_multipart():
+ from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
+
+ # Setup request mock for /v1/audio/transcriptions
+ request_mock = MagicMock(spec=Request)
+ request_mock.url.path = "/v1/audio/transcriptions"
+ request_mock.url = MagicMock()
+ request_mock.url.__str__.return_value = "http://localhost/v1/audio/transcriptions"
+ request_mock.method = "POST"
+ request_mock.query_params = {}
+ request_mock.headers = {
+ "Content-Type": "multipart/form-data",
+ "Authorization": "Bearer sk-1234"
+ }
+ request_mock.client = MagicMock()
+ request_mock.client.host = "127.0.0.1"
+
+ # Simulate multipart data (metadata as string)
+ metadata_dict = {
+ "tags": [
+ "jobID:214590dsff09fds",
+ "taskName:run_page_classification"
+ ]
+ }
+ stringified_metadata = json.dumps(metadata_dict)
+
+ data = {
+ "model": "fake-openai-endpoint",
+ "metadata": stringified_metadata, # Simulating multipart-form field
+ "file": b"Fake audio bytes"
+ }
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-key",
+ metadata={},
+ team_metadata={},
+ spend=0.0,
+ max_budget=100.0,
+ model_max_budget={},
+ team_spend=0.0,
+ team_max_budget=200.0,
+ )
+
+ updated_data = await add_litellm_data_to_request(
+ data=data,
+ request=request_mock,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=MagicMock(),
+ general_settings={},
+ version="test-version",
+ )
+
+ # Assert metadata was parsed correctly
+ metadata_field = updated_data.get("metadata", {})
+ litellm_metadata = updated_data.get("litellm_metadata", {})
+
+ assert isinstance(metadata_field, dict)
+ assert "tags" in metadata_field
+ assert metadata_field["tags"] == ["jobID:214590dsff09fds", "taskName:run_page_classification"]