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
fix(openrouter): register OpenRouter as native Responses API provider (#22355)
Shivaang213799282b7d
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex f00b816be5c..84b8e47c462 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -1441,6 +1441,7 @@ if TYPE_CHECKING:from .llms.manus.responses.transformation import ManusResponsesAPIConfig as ManusResponsesAPIConfigfrom .llms.perplexity.responses.transformation import PerplexityResponsesConfig as PerplexityResponsesConfigfrom .llms.databricks.responses.transformation import DatabricksResponsesAPIConfig as DatabricksResponsesAPIConfig+ from .llms.openrouter.responses.transformation import OpenRouterResponsesAPIConfig as OpenRouterResponsesAPIConfigfrom .llms.gemini.interactions.transformation import GoogleAIStudioInteractionsConfig as GoogleAIStudioInteractionsConfigfrom .llms.openai.chat.o_series_transformation import OpenAIOSeriesConfig as OpenAIOSeriesConfig, OpenAIOSeriesConfig as OpenAIO1Configfrom .llms.anthropic.skills.transformation import AnthropicSkillsConfig as AnthropicSkillsConfigdiff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.pyindex 6ff997b4531..4bb336a4d77 100644--- a/litellm/_lazy_imports_registry.py+++ b/litellm/_lazy_imports_registry.py@@ -231,6 +231,7 @@ LLM_CONFIG_NAMES = ("VolcEngineResponsesAPIConfig","PerplexityResponsesConfig","DatabricksResponsesAPIConfig",+ "OpenRouterResponsesAPIConfig","GoogleAIStudioInteractionsConfig","OpenAIOSeriesConfig","AnthropicSkillsConfig",@@ -923,6 +924,10 @@ _LLM_CONFIGS_IMPORT_MAP = {".llms.databricks.responses.transformation","DatabricksResponsesAPIConfig",),+ "OpenRouterResponsesAPIConfig": (+ ".llms.openrouter.responses.transformation",+ "OpenRouterResponsesAPIConfig",+ ),"GoogleAIStudioInteractionsConfig": (".llms.gemini.interactions.transformation","GoogleAIStudioInteractionsConfig",diff --git a/litellm/llms/openrouter/responses/transformation.py b/litellm/llms/openrouter/responses/transformation.pynew file mode 100644index 00000000000..ddce6fd3844--- /dev/null+++ b/litellm/llms/openrouter/responses/transformation.py@@ -0,0 +1,77 @@+"""+OpenRouter Responses API Configuration.++OpenRouter supports the Responses API at https://openrouter.ai/api/v1/responses+with OpenAI-compatible request/response format, including reasoning with+encrypted_content for multi-turn stateless workflows.++Docs: https://openrouter.ai/docs/api/reference/responses/overview+"""++from typing import Optional++import litellm+from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig+from litellm.secret_managers.main import get_secret_str+from litellm.types.router import GenericLiteLLMParams+from litellm.types.utils import LlmProviders+++class OpenRouterResponsesAPIConfig(OpenAIResponsesAPIConfig):+ """+ Configuration for OpenRouter's Responses API.++ Inherits from OpenAIResponsesAPIConfig since OpenRouter's Responses API+ is compatible with OpenAI's Responses API specification.++ Key difference from direct OpenAI:+ - Uses https://openrouter.ai/api/v1 as the API base+ - Uses OPENROUTER_API_KEY for authentication+ """++ @property+ def custom_llm_provider(self) -> LlmProviders:+ return LlmProviders.OPENROUTER++ def validate_environment(+ self,+ headers: dict,+ model: str,+ litellm_params: Optional[GenericLiteLLMParams],+ ) -> dict:+ litellm_params = litellm_params or GenericLiteLLMParams()+ api_key = (+ litellm_params.api_key+ or litellm.api_key+ or get_secret_str("OPENROUTER_API_KEY")+ or get_secret_str("OR_API_KEY")+ )++ if not api_key:+ raise ValueError(+ "OpenRouter API key is required. Set OPENROUTER_API_KEY "+ "environment variable or pass api_key parameter."+ )++ headers.update(+ {+ "Authorization": f"Bearer {api_key}",+ }+ )+ return headers++ def get_complete_url(+ self,+ api_base: Optional[str],+ litellm_params: dict,+ ) -> str:+ api_base = (+ api_base+ or litellm.api_base+ or get_secret_str("OPENROUTER_API_BASE")+ or "https://openrouter.ai/api/v1"+ )++ api_base = api_base.rstrip("/")++ return f"{api_base}/responses"diff --git a/litellm/utils.py b/litellm/utils.pyindex cbe6aa8e793..d192609eead 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -8312,6 +8312,8 @@ class ProviderConfigManager:if model and "gpt" in model.lower():return litellm.DatabricksResponsesAPIConfig()return None+ elif litellm.LlmProviders.OPENROUTER == provider:+ return litellm.OpenRouterResponsesAPIConfig()elif litellm.LlmProviders.HOSTED_VLLM == provider:return litellm.HostedVLLMResponsesAPIConfig()return Nonediff --git a/tests/test_litellm/llms/openrouter/responses/test_openrouter_responses_transformation.py b/tests/test_litellm/llms/openrouter/responses/test_openrouter_responses_transformation.pynew file mode 100644index 00000000000..544ec1ec719--- /dev/null+++ b/tests/test_litellm/llms/openrouter/responses/test_openrouter_responses_transformation.py@@ -0,0 +1,112 @@+"""+Tests for OpenRouter Responses API configuration.++Validates that OpenRouter is registered as a native Responses API provider,+routing requests directly to https://openrouter.ai/api/v1/responses instead+of falling back to the chat completion bridge. This is required to preserve+reasoning.encrypted_content for multi-turn stateless workflows.++Related issue: https://github.com/BerriAI/litellm/issues/22189+"""++import litellm+from litellm.llms.openrouter.responses.transformation import (+ OpenRouterResponsesAPIConfig,+)+from litellm.types.utils import LlmProviders+from litellm.utils import ProviderConfigManager+++class TestOpenRouterResponsesAPIConfig:+ """Test OpenRouter Responses API configuration."""++ def test_custom_llm_provider(self):+ """custom_llm_provider should return OPENROUTER."""+ config = OpenRouterResponsesAPIConfig()+ assert config.custom_llm_provider == LlmProviders.OPENROUTER++ def test_get_complete_url_default(self):+ """Default URL should point to OpenRouter's Responses API endpoint."""+ config = OpenRouterResponsesAPIConfig()+ url = config.get_complete_url(api_base=None, litellm_params={})+ assert url == "https://openrouter.ai/api/v1/responses"++ def test_get_complete_url_custom_base(self):+ """Custom api_base should be respected."""+ config = OpenRouterResponsesAPIConfig()+ url = config.get_complete_url(+ api_base="https://custom.openrouter.ai/api/v1",+ litellm_params={},+ )+ assert url == "https://custom.openrouter.ai/api/v1/responses"++ def test_get_complete_url_strips_trailing_slash(self):+ """Trailing slashes on api_base should be stripped."""+ config = OpenRouterResponsesAPIConfig()+ url = config.get_complete_url(+ api_base="https://openrouter.ai/api/v1/",+ litellm_params={},+ )+ assert url == "https://openrouter.ai/api/v1/responses"++ def test_validate_environment_sets_auth_header(self):+ """validate_environment should set the Authorization header."""+ config = OpenRouterResponsesAPIConfig()+ from litellm.types.router import GenericLiteLLMParams++ params = GenericLiteLLMParams(api_key="sk-or-test-key")+ headers = config.validate_environment(+ headers={}, model="openai/o4-mini", litellm_params=params+ )+ assert headers["Authorization"] == "Bearer sk-or-test-key"++ def test_validate_environment_raises_without_key(self):+ """validate_environment should raise when no API key is available."""+ config = OpenRouterResponsesAPIConfig()+ from litellm.types.router import GenericLiteLLMParams++ try:+ config.validate_environment(+ headers={},+ model="openai/o4-mini",+ litellm_params=GenericLiteLLMParams(),+ )+ assert False, "Should have raised ValueError"+ except ValueError as e:+ assert "OpenRouter API key is required" in str(e)+++class TestOpenRouterResponsesAPIRegistration:+ """Test that OpenRouter is properly registered as a native Responses API provider."""++ def test_provider_config_manager_returns_openrouter_config(self):+ """+ ProviderConfigManager.get_provider_responses_api_config should return+ OpenRouterResponsesAPIConfig for the OPENROUTER provider, NOT None.++ When it returns None, requests fall through to the completion bridge,+ which loses encrypted_content (the bug in issue #22189).+ """+ config = ProviderConfigManager.get_provider_responses_api_config(+ provider=LlmProviders.OPENROUTER,+ )+ assert config is not None, (+ "OpenRouter must be registered as a native Responses API provider "+ "to preserve reasoning.encrypted_content"+ )+ assert isinstance(config, OpenRouterResponsesAPIConfig)++ def test_openrouter_not_using_completion_bridge(self):+ """+ Verify that OpenRouter does NOT fall through to the completion bridge.+ The completion bridge drops encrypted_content because chat completions+ use a different format (reasoning_details) than the Responses API.+ """+ config = ProviderConfigManager.get_provider_responses_api_config(+ provider=LlmProviders.OPENROUTER,+ )+ # If config is not None, the native Responses API path is used+ assert config is not None+ # The URL should point to OpenRouter's responses endpoint+ url = config.get_complete_url(api_base=None, litellm_params={})+ assert "/responses" in url