The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Bedrock + MCP - working MCP calls to bedrock via Responses API + Log hidden params for OTEL calls (#15677)
Krish Dholakia302f55c7db6d
diff --git a/docs/my-website/docs/completion/knowledgebase.md b/docs/my-website/docs/completion/knowledgebase.mdindex e772f4fe955..3040f7f1cc0 100644--- a/docs/my-website/docs/completion/knowledgebase.md+++ b/docs/my-website/docs/completion/knowledgebase.md@@ -18,7 +18,7 @@ LiteLLM integrates with vector stores, allowing your models to access your organ## Supported Vector Stores- [Bedrock Knowledge Bases](https://aws.amazon.com/bedrock/knowledge-bases/)- [OpenAI Vector Stores](https://platform.openai.com/docs/api-reference/vector-stores/search)-- [Azure Vector Stores](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/file-search?tabs=python#vector-stores)+- [Azure Vector Stores](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/file-search?tabs=python#vector-stores) (Cannot be directly queried. Only available for calling in Assistants messages. We will be adding Azure AI Search Vector Store API support soon.)- [Vertex AI RAG API](https://cloud.google.com/vertex-ai/generative-ai/docs/rag-overview)## Quick Startdiff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.pyindex e825f89f56e..a8cf106b61c 100644--- a/litellm/integrations/opentelemetry.py+++ b/litellm/integrations/opentelemetry.py@@ -247,12 +247,12 @@ class OpenTelemetry(CustomLogger):metrics.set_meter_provider(meter_provider)self._operation_duration_histogram = meter.create_histogram(- name="gen_ai.client.operation.duration", # Replace with semconv constant in otel 1.38+ name="gen_ai.client.operation.duration", # Replace with semconv constant in otel 1.38description="GenAI operation duration",unit="s",)self._token_usage_histogram = meter.create_histogram(- name="gen_ai.client.token.usage", # Replace with semconv constant in otel 1.38+ name="gen_ai.client.token.usage", # Replace with semconv constant in otel 1.38description="GenAI token usage",unit="{token}",)@@ -480,9 +480,9 @@ class OpenTelemetry(CustomLogger):def _get_dynamic_otel_headers_from_kwargs(self, kwargs) -> Optional[dict]:"""Extract dynamic headers from kwargs if available."""- standard_callback_dynamic_params: Optional[- StandardCallbackDynamicParams- ] = kwargs.get("standard_callback_dynamic_params")+ standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = (+ kwargs.get("standard_callback_dynamic_params")+ )if not standard_callback_dynamic_params:return None@@ -543,7 +543,7 @@ class OpenTelemetry(CustomLogger):# 4. Metrics & cost recordingself._record_metrics(kwargs, response_obj, start_time, end_time)- # 5. Semantic logs.+ # 5. Semantic logs.if self.config.enable_events:self._emit_semantic_logs(kwargs, response_obj, span)@@ -581,7 +581,6 @@ class OpenTelemetry(CustomLogger):raw_span_name = generation_name if generation_name else RAW_REQUEST_SPAN_NAME-otel_tracer: Tracer = self.get_tracer_to_use_for_request(kwargs)raw_span = otel_tracer.start_span(name=raw_span_name,@@ -626,6 +625,13 @@ class OpenTelemetry(CustomLogger):if md.get(key) is not None:common_attrs[f"metadata.{key}"] = str(md[key])+ # get hidden params+ hidden_params = getattr(std_log, "hidden_params", None) or (std_log or {}).get(+ "hidden_params", {}+ )+ if hidden_params:+ common_attrs["hidden_params"] = safe_dumps(hidden_params)+if self._operation_duration_histogram:self._operation_duration_histogram.record(duration_s, attributes=common_attrs@@ -653,6 +659,7 @@ class OpenTelemetry(CustomLogger):returnfrom opentelemetry._logs import LogRecord, get_logger+otel_logger = get_logger(LITELLM_LOGGER_NAME)parent_ctx = span.get_span_context()@@ -708,7 +715,6 @@ class OpenTelemetry(CustomLogger):))-def _create_guardrail_span(self, kwargs: Optional[dict], context: Optional[Context]):@@ -920,6 +926,14 @@ class OpenTelemetry(CustomLogger):span=span, key="metadata.{}".format(key), value=value)+ # get hidden params+ hidden_params = getattr(+ standard_logging_payload, "hidden_params", None+ ) or (standard_logging_payload or {}).get("hidden_params", {})+ if hidden_params:+ self.safe_set_attribute(+ span=span, key="hidden_params", value=safe_dumps(hidden_params)+ )####################################################### LLM Request Attributes ########################################################diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.pyindex d2cad0abd93..a5a4ab6cbf2 100644--- a/litellm/litellm_core_utils/prompt_templates/factory.py+++ b/litellm/litellm_core_utils/prompt_templates/factory.py@@ -364,17 +364,19 @@ def phind_codellama_pt(messages):return prompt-def _render_chat_template(env, chat_template: str, bos_token: str, eos_token: str, messages: list) -> str:+def _render_chat_template(+ env, chat_template: str, bos_token: str, eos_token: str, messages: list+) -> str:"""Shared template rendering logic for both sync and async hf_chat_template-+Args:env: Jinja2 environmentchat_template: Chat template stringbos_token: Beginning of sequence tokeneos_token: End of sequence tokenmessages: Messages to render-+Returns:Rendered template string"""@@ -456,7 +458,7 @@ async def _afetch_and_extract_template() -> Tuple[str, str, str]:"""Async version: Fetch template and tokens from HuggingFace.-+Returns: (chat_template, bos_token, eos_token)"""from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (@@ -518,7 +520,7 @@ def _fetch_and_extract_template() -> Tuple[str, str, str]:"""Sync version: Fetch template and tokens from HuggingFace.-+Returns: (chat_template, bos_token, eos_token)"""from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (@@ -604,9 +606,7 @@ async def ahf_chat_template()-def hf_chat_template(- model: str, messages: list, chat_template: Optional[Any] = None-):+def hf_chat_template(model: str, messages: list, chat_template: Optional[Any] = None):"""HuggingFace chat template (sync version)"""from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (_get_chat_template_file,@@ -1205,10 +1205,10 @@ def convert_to_gemini_tool_call_invoke(if tool_calls is not None:for tool in tool_calls:if "function" in tool:- gemini_function_call: Optional[- VertexFunctionCall- ] = _gemini_tool_call_invoke_helper(- function_call_params=tool["function"]+ gemini_function_call: Optional[VertexFunctionCall] = (+ _gemini_tool_call_invoke_helper(+ function_call_params=tool["function"]+ ))if gemini_function_call is not None:_parts_list.append(@@ -1727,9 +1727,9 @@ def anthropic_messages_pt( # noqa: PLR0915)if "cache_control" in _content_element:- _anthropic_content_element[- "cache_control"- ] = _content_element["cache_control"]+ _anthropic_content_element["cache_control"] = (+ _content_element["cache_control"]+ )user_content.append(_anthropic_content_element)elif m.get("type", "") == "text":m = cast(ChatCompletionTextObject, m)@@ -1767,9 +1767,9 @@ def anthropic_messages_pt( # noqa: PLR0915)if "cache_control" in _content_element:- _anthropic_content_text_element[- "cache_control"- ] = _content_element["cache_control"]+ _anthropic_content_text_element["cache_control"] = (+ _content_element["cache_control"]+ )user_content.append(_anthropic_content_text_element)@@ -3964,9 +3964,11 @@ def _bedrock_tools_pt(tools: List) -> List[BedrockToolBlock]:# related issue: https://github.com/BerriAI/litellm/issues/5007# Bedrock tool names must satisfy regular expression pattern: [a-zA-Z][a-zA-Z0-9_]* ensure this is truename = make_valid_bedrock_tool_name(input_tool_name=name)- description = tool.get("function", {}).get(- "description", name- ) # converse api requires a description+ _tool_description = tool.get("function", {}).get("description", None)+ if _tool_description: # bedrock doesn't accept empty "" or None descriptions+ description = _tool_description+ else:+ description = namedefs = parameters.pop("$defs", {})defs_copy = copy.deepcopy(defs)@@ -4171,8 +4173,11 @@ def prompt_factory(return azure_text_pt(messages=messages)elif custom_llm_provider == "watsonx":from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig- return IBMWatsonXChatConfig.apply_prompt_template(model=model, messages=messages)-++ return IBMWatsonXChatConfig.apply_prompt_template(+ model=model, messages=messages+ )+try:if "meta-llama/llama-2" in model and "chat" in model:return llama_2_chat_pt(messages=messages)diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex f92c2eeb3af..c0a369cbc25 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -1,14 +1,7 @@-model_list:- - model_name: gpt-5-mini- litellm_params:- model: gpt-5-mini+model_list:+ - model_name: bedrock-anthropic-claude-sonnet-4-5-20250929-v1+ litellm_params:+ model: bedrock/global.anthropic.claude-sonnet-4-5-20250929-v1:0-mcp_servers:- github_mcp:- url: "https://api.githubcopilot.com/mcp"- auth_type: oauth2- authorization_url: https://github.com/login/oauth/authorize- token_url: https://github.com/login/oauth/access_token- client_id: os.environ/GITHUB_OAUTH_CLIENT_ID- client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET- scopes: ["public_repo", "user:email"]+litellm_settings:+ callbacks: ["otel"]\ No newline at end of filediff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.pyindex a4fb2d96032..0582780e87d 100644--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py@@ -86,7 +86,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):"status": "in_progress","error": None,"incomplete_details": None,- "instructions": self.request_input,+ "instructions": self.responses_api_request.get("instructions", None),"max_output_tokens": None,"model": self.model,"output": [],diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.pyindex 8801e561915..dcc660f0380 100644--- a/litellm/responses/mcp/mcp_streaming_iterator.py+++ b/litellm/responses/mcp/mcp_streaming_iterator.py@@ -436,7 +436,11 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):value # Copy all params as-is since tools are already processed)- tools_count = len(params_for_llm.get("tools", []))+ tools_count = (+ len(params_for_llm.get("tools", []))+ if params_for_llm.get("tools")+ else 0+ )verbose_logger.debug(f"Making LLM call with {tools_count} tools")response = await aresponses(**params_for_llm)diff --git a/litellm/vector_stores/vector_store_registry.py b/litellm/vector_stores/vector_store_registry.pyindex 680200ca179..bdd14cb2d99 100644--- a/litellm/vector_stores/vector_store_registry.py+++ b/litellm/vector_stores/vector_store_registry.py@@ -127,21 +127,21 @@ class VectorStoreRegistry:if vector_store.get("vector_store_id") == vector_store_id:return vector_storereturn None-+def get_litellm_managed_vector_store_from_registry(self, vector_store_id: str) -> Optional[LiteLLM_ManagedVectorStore]:"""Returns the vector store from the registry"""- for vector_store in self.vector_stores:+ for vector_store in self.vector_stores:if vector_store.get("vector_store_id") == vector_store_id:return vector_storereturn None-+def pop_vector_stores_to_run(self, non_default_params: Dict, tools: Optional[List[Dict]] = None- ) -> List[LiteLLM_ManagedVectorStore]:+ ) -> List[LiteLLM_ManagedVectorStore]:"""Pops the vector stores to run@@ -197,6 +197,7 @@ class VectorStoreRegistry:litellm_managed_vector_store = LiteLLM_ManagedVectorStore(vector_store_id=vector_store_id,custom_llm_provider=custom_llm_provider,+ litellm_params=vector_store_litellm_params,vector_store_name=vector_store_name,vector_store_description=vector_store_litellm_params.get("vector_store_description"diff --git a/tests/logging_callback_tests/test_otel_logging.py b/tests/logging_callback_tests/test_otel_logging.pyindex edf9683b94e..ecbcc8734f5 100644--- a/tests/logging_callback_tests/test_otel_logging.py+++ b/tests/logging_callback_tests/test_otel_logging.py@@ -277,11 +277,15 @@ def validate_redacted_message_span_attributes(span):# Check that all required attributes are presentrequired_set = set(required_attributes)- assert required_set.issubset(_all_attributes), f"Missing required attributes: {required_set - _all_attributes}"-+ assert required_set.issubset(+ _all_attributes+ ), f"Missing required attributes: {required_set - _all_attributes}"+# Check that any additional attributes are metadata fields (start with "metadata.")non_required_attrs = _all_attributes - required_setfor attr in non_required_attrs:- assert attr.startswith("metadata."), f"Non-metadata attribute found: {attr}"+ assert attr.startswith("metadata.") or attr.startswith(+ "hidden_params"+ ), f"Non-metadata attribute found: {attr}"passdiff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.pyindex e3ca7101c6c..a40c94af1d9 100644--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py@@ -148,40 +148,38 @@ def test_bedrock_validate_format_image_or_video():}for mime, expected in valid_document_formats.items():print("testing mime", mime, "expected", expected)- result = BedrockImageProcessor._validate_format(- mime, mime.split("/")[1]- )+ result = BedrockImageProcessor._validate_format(mime, mime.split("/")[1])assert result == expected, f"Expected {expected}, got {result}"def test_bedrock_get_document_format_fallback_mimes():"""Test the _get_document_format method with fallback MIME types for DOCX and XLSX.-+This tests the fallback mechanism when mimetypes.guess_all_extensions returns empty results,which can happen in Docker containers where mimetypes depends on OS-installed MIME types."""from unittest.mock import patch# Test DOCX fallback- docx_mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ docx_mime = (+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ )supported_formats = ["pdf", "docx", "xlsx", "csv"]-+# Mock mimetypes.guess_all_extensions to return empty list (simulating Docker container scenario)- with patch('mimetypes.guess_all_extensions', return_value=[]):+ with patch("mimetypes.guess_all_extensions", return_value=[]):result = BedrockImageProcessor._get_document_format(- mime_type=docx_mime,- supported_doc_formats=supported_formats+ mime_type=docx_mime, supported_doc_formats=supported_formats)assert result == "docx", f"Expected 'docx', got '{result}'"-- # Test XLSX fallback++ # Test XLSX fallbackxlsx_mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"-- with patch('mimetypes.guess_all_extensions', return_value=[]):++ with patch("mimetypes.guess_all_extensions", return_value=[]):result = BedrockImageProcessor._get_document_format(- mime_type=xlsx_mime,- supported_doc_formats=supported_formats+ mime_type=xlsx_mime, supported_doc_formats=supported_formats)assert result == "xlsx", f"Expected 'xlsx', got '{result}'"@@ -190,20 +188,18 @@ def test_bedrock_get_document_format_mimetypes_success():"""Test the _get_document_format method when mimetypes.guess_all_extensions works normally."""- docx_mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ docx_mime = (+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ )supported_formats = ["pdf", "docx", "xlsx", "csv"]-+# Test normal mimetypes behavior (should not hit fallback)result = BedrockImageProcessor._get_document_format(- mime_type=docx_mime,- supported_doc_formats=supported_formats+ mime_type=docx_mime, supported_doc_formats=supported_formats)assert result == "docx", f"Expected 'docx', got '{result}'"---# def test_ollama_pt_consecutive_system_messages():# """Test handling consecutive system messages"""# messages = [@@ -571,3 +567,42 @@ def test_bedrock_tools_unpack_defs():_bedrock_tools_pt(tools=tools)+def test_bedrock_tools_pt_empty_description():+ """+ Test that _bedrock_tools_pt handles empty string descriptions correctly.++ When a tool has an empty string description, Bedrock doesn't accept it,+ so the function should fall back to using the function name as the description.+ """+ from litellm.litellm_core_utils.prompt_templates.factory import _bedrock_tools_pt++ tools = [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "", # Empty string description+ "parameters": {+ "type": "object",+ "properties": {+ "location": {+ "type": "string",+ "description": "The city and state, e.g. San Francisco, CA",+ }+ },+ "required": ["location"],+ },+ },+ }+ ]++ result = _bedrock_tools_pt(tools=tools)++ # Verify that the result is a list with one tool+ assert len(result) == 1++ # Verify that the description falls back to the function name+ tool_spec = result[0].get("toolSpec")+ assert tool_spec is not None+ assert tool_spec.get("name") == "get_weather"+ assert tool_spec.get("description") == "get_weather"