From 538c54ab5b86dcc69827f271379b31f42932e636 Mon Sep 17 00:00:00 2001 From: yanismiraoui Date: Tue, 2 Jun 2026 12:21:15 -0700 Subject: [PATCH 1/4] add inception as provider (chat, fim) --- litellm/__init__.py | 17 + litellm/_lazy_imports_registry.py | 7 + litellm/constants.py | 4 + .../get_llm_provider_logic.py | 10 + .../get_supported_openai_params.py | 4 + litellm/llms/inception/__init__.py | 0 litellm/llms/inception/chat/__init__.py | 0 litellm/llms/inception/chat/transformation.py | 49 ++ litellm/llms/inception/completion/__init__.py | 0 .../inception/completion/transformation.py | 43 ++ litellm/main.py | 56 +++ ...odel_prices_and_context_window_backup.json | 25 + litellm/types/utils.py | 2 + litellm/utils.py | 27 ++ model_prices_and_context_window.json | 25 + tests/llm_translation/test_inception.py | 456 ++++++++++++++++++ 16 files changed, 725 insertions(+) create mode 100644 litellm/llms/inception/__init__.py create mode 100644 litellm/llms/inception/chat/__init__.py create mode 100644 litellm/llms/inception/chat/transformation.py create mode 100644 litellm/llms/inception/completion/__init__.py create mode 100644 litellm/llms/inception/completion/transformation.py create mode 100644 tests/llm_translation/test_inception.py diff --git a/litellm/__init__.py b/litellm/__init__.py index bae15f0362cc..c954f5fd31ef 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -278,6 +278,7 @@ lemonade_key: Optional[str] = None sap_service_key: Optional[str] = None amazon_nova_api_key: Optional[str] = None +inception_key: Optional[str] = None common_cloud_provider_auth_params: dict = { "params": ["project", "region_name", "token"], "providers": ["vertex_ai", "bedrock", "watsonx", "azure", "vertex_ai_beta"], @@ -551,6 +552,7 @@ def identify(event_details): cohere_chat_models: Set = set() mistral_chat_models: Set = set() text_completion_codestral_models: Set = set() +text_completion_inception_models: Set = set() anthropic_models: Set = set() openrouter_models: Set = set() datarobot_models: Set = set() @@ -628,6 +630,7 @@ def identify(event_details): v0_models: Set = set() morph_models: Set = set() lambda_ai_models: Set = set() +inception_models: Set = set() hyperbolic_models: Set = set() black_forest_labs_models: Set = set() recraft_models: Set = set() @@ -792,6 +795,8 @@ def add_known_models(model_cost_map: Optional[Dict] = None): fireworks_ai_embedding_models.add(key) elif value.get("litellm_provider") == "text-completion-codestral": text_completion_codestral_models.add(key) + elif value.get("litellm_provider") == "text-completion-inception": + text_completion_inception_models.add(key) elif value.get("litellm_provider") == "xai": xai_models.add(key) elif value.get("litellm_provider") == "zai": @@ -878,6 +883,8 @@ def add_known_models(model_cost_map: Optional[Dict] = None): morph_models.add(key) elif value.get("litellm_provider") == "lambda_ai": lambda_ai_models.add(key) + elif value.get("litellm_provider") == "inception": + inception_models.add(key) elif value.get("litellm_provider") == "hyperbolic": hyperbolic_models.add(key) elif value.get("litellm_provider") == "black_forest_labs": @@ -980,6 +987,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): | watsonx_models | gemini_models | text_completion_codestral_models + | text_completion_inception_models | xai_models | zai_models | fal_ai_models @@ -1018,6 +1026,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): | v0_models | morph_models | lambda_ai_models + | inception_models | black_forest_labs_models | recraft_models | cometapi_models @@ -1074,6 +1083,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): "fireworks_ai": fireworks_ai_models | fireworks_ai_embedding_models, "aleph_alpha": aleph_alpha_models, "text-completion-codestral": text_completion_codestral_models, + "text-completion-inception": text_completion_inception_models, "xai": xai_models, "zai": zai_models, "fal_ai": fal_ai_models, @@ -1118,6 +1128,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): "v0": v0_models, "morph": morph_models, "lambda_ai": lambda_ai_models, + "inception": inception_models, "hyperbolic": hyperbolic_models, "black_forest_labs": black_forest_labs_models, "recraft": recraft_models, @@ -1869,6 +1880,9 @@ def set_global_gitlab_config(config: Dict[str, Any]) -> None: from .llms.codestral.completion.transformation import ( CodestralTextCompletionConfig as CodestralTextCompletionConfig, ) + from .llms.inception.completion.transformation import ( + InceptionTextCompletionConfig as InceptionTextCompletionConfig, + ) from .llms.azure.azure import ( AzureOpenAIAssistantsAPIConfig as AzureOpenAIAssistantsAPIConfig, ) @@ -1937,6 +1951,9 @@ def set_global_gitlab_config(config: Dict[str, Any]) -> None: from .llms.lambda_ai.chat.transformation import ( LambdaAIChatConfig as LambdaAIChatConfig, ) + from .llms.inception.chat.transformation import ( + InceptionChatConfig as InceptionChatConfig, + ) from .llms.hyperbolic.chat.transformation import ( HyperbolicChatConfig as HyperbolicChatConfig, ) diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py index 17eb66092924..4bd55dd59ad3 100644 --- a/litellm/_lazy_imports_registry.py +++ b/litellm/_lazy_imports_registry.py @@ -267,6 +267,7 @@ "AIMLChatConfig", "VolcEngineChatConfig", "CodestralTextCompletionConfig", + "InceptionTextCompletionConfig", "AzureOpenAIAssistantsAPIConfig", "HerokuChatConfig", "CometAPIConfig", @@ -310,6 +311,7 @@ "MorphChatConfig", "RAGFlowConfig", "LambdaAIChatConfig", + "InceptionChatConfig", "HyperbolicChatConfig", "VercelAIGatewayConfig", "OVHCloudChatConfig", @@ -1040,6 +1042,10 @@ ".llms.codestral.completion.transformation", "CodestralTextCompletionConfig", ), + "InceptionTextCompletionConfig": ( + ".llms.inception.completion.transformation", + "InceptionTextCompletionConfig", + ), "AzureOpenAIAssistantsAPIConfig": ( ".llms.azure.azure", "AzureOpenAIAssistantsAPIConfig", @@ -1154,6 +1160,7 @@ "MorphChatConfig": (".llms.morph.chat.transformation", "MorphChatConfig"), "RAGFlowConfig": (".llms.ragflow.chat.transformation", "RAGFlowConfig"), "LambdaAIChatConfig": (".llms.lambda_ai.chat.transformation", "LambdaAIChatConfig"), + "InceptionChatConfig": (".llms.inception.chat.transformation", "InceptionChatConfig"), "HyperbolicChatConfig": ( ".llms.hyperbolic.chat.transformation", "HyperbolicChatConfig", diff --git a/litellm/constants.py b/litellm/constants.py index df15050e6525..26e25d0cef38 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -585,6 +585,7 @@ "volcengine", "codestral", "text-completion-codestral", + "text-completion-inception", "deepseek", "sambanova", "maritalk", @@ -620,6 +621,7 @@ "oci", "morph", "lambda_ai", + "inception", "vercel_ai_gateway", "wandb", "ovhcloud", @@ -779,6 +781,7 @@ "https://api.v0.dev/v1", "https://api.morphllm.com/v1", "https://api.lambda.ai/v1", + "https://api.inceptionlabs.ai/v1", "https://api.hyperbolic.xyz/v1", "https://ai-gateway.helicone.ai/", "https://ai-gateway.vercel.sh/v1", @@ -835,6 +838,7 @@ "helicone", "morph", "lambda_ai", + "inception", "hyperbolic", "vercel_ai_gateway", "aiml", diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py index ba6d438f16c6..6eb5891b0862 100644 --- a/litellm/litellm_core_utils/get_llm_provider_logic.py +++ b/litellm/litellm_core_utils/get_llm_provider_logic.py @@ -353,6 +353,9 @@ def get_llm_provider( # noqa: PLR0915 elif endpoint == "https://api.lambda.ai/v1": custom_llm_provider = "lambda_ai" dynamic_api_key = get_secret_str("LAMBDA_API_KEY") + elif endpoint == "https://api.inceptionlabs.ai/v1": + custom_llm_provider = "inception" + dynamic_api_key = get_secret_str("INCEPTION_API_KEY") elif endpoint == "https://api.hyperbolic.xyz/v1": custom_llm_provider = "hyperbolic" dynamic_api_key = get_secret_str("HYPERBOLIC_API_KEY") @@ -931,6 +934,13 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 ) = litellm.LambdaAIChatConfig()._get_openai_compatible_provider_info( api_base, api_key ) + elif custom_llm_provider == "inception": + ( + api_base, + dynamic_api_key, + ) = litellm.InceptionChatConfig()._get_openai_compatible_provider_info( + api_base, api_key + ) elif custom_llm_provider == "hyperbolic": ( api_base, diff --git a/litellm/litellm_core_utils/get_supported_openai_params.py b/litellm/litellm_core_utils/get_supported_openai_params.py index b8cdc8210fcc..f389b2858a2e 100644 --- a/litellm/litellm_core_utils/get_supported_openai_params.py +++ b/litellm/litellm_core_utils/get_supported_openai_params.py @@ -179,6 +179,10 @@ def get_supported_openai_params( # noqa: PLR0915 return litellm.CodestralTextCompletionConfig().get_supported_openai_params( model=model ) + elif custom_llm_provider == "text-completion-inception": + return litellm.InceptionTextCompletionConfig().get_supported_openai_params( + model=model + ) elif custom_llm_provider == "sambanova": if request_type == "embeddings": litellm.SambaNovaEmbeddingConfig().get_supported_openai_params(model=model) diff --git a/litellm/llms/inception/__init__.py b/litellm/llms/inception/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/litellm/llms/inception/chat/__init__.py b/litellm/llms/inception/chat/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/litellm/llms/inception/chat/transformation.py b/litellm/llms/inception/chat/transformation.py new file mode 100644 index 000000000000..24c071c5fdcc --- /dev/null +++ b/litellm/llms/inception/chat/transformation.py @@ -0,0 +1,49 @@ +""" +Translate from OpenAI's `/v1/chat/completions` to Inception's `/v1/chat/completions` + +Inception Labs (https://www.inceptionlabs.ai) serves the Mercury family of +diffusion LLMs through an OpenAI-compatible API, so we only need to point the +OpenAI-like handler at the Inception API base and pick up the Inception API key. +""" + +from typing import List, Optional, Tuple + +import litellm +from litellm.secret_managers.main import get_secret_str + +from ...openai_like.chat.transformation import OpenAILikeChatConfig + + +class InceptionChatConfig(OpenAILikeChatConfig): + """ + Inception is OpenAI-compatible with standard endpoints + """ + + @property + def custom_llm_provider(self) -> Optional[str]: + return "inception" + + def get_supported_openai_params(self, model: str) -> List: + return [ + "max_tokens", + "max_completion_tokens", + "temperature", + "stop", + "tools", + "tool_choice", + "stream", + "stream_options", + "response_format", + "reasoning_effort", + "reasoning_summary", + "reasoning_summary_wait", + "diffusing", + "realtime", + ] + + def _get_openai_compatible_provider_info( + self, api_base: Optional[str], api_key: Optional[str] + ) -> Tuple[Optional[str], Optional[str]]: + api_base = api_base or get_secret_str("INCEPTION_API_BASE") or "https://api.inceptionlabs.ai/v1" # type: ignore + dynamic_api_key = api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") + return api_base, dynamic_api_key diff --git a/litellm/llms/inception/completion/__init__.py b/litellm/llms/inception/completion/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/litellm/llms/inception/completion/transformation.py b/litellm/llms/inception/completion/transformation.py new file mode 100644 index 000000000000..1035042f6bf0 --- /dev/null +++ b/litellm/llms/inception/completion/transformation.py @@ -0,0 +1,43 @@ +""" +Inception fill-in-the-middle (FIM) completions. + +Inception's FIM endpoint is OpenAI text-completion compatible: it takes a +`prompt` (prefix) plus an optional `suffix` and returns standard +`choices[].text`. It is served at `/v1/fim/completions` rather than +`/v1/completions`, so routing points the OpenAI client at the `/v1/fim` base +(see the `text-completion-inception` branch in `main.py`). +""" + +from typing import List + +from litellm.llms.openai.completion.transformation import OpenAITextCompletionConfig + + +class InceptionTextCompletionConfig(OpenAITextCompletionConfig): + def get_supported_openai_params(self, model: str) -> List: + return [ + "suffix", + "max_tokens", + "max_completion_tokens", + "top_p", + "frequency_penalty", + "presence_penalty", + "stop", + "stream", + "stream_options", + ] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + supported_params = self.get_supported_openai_params(model) + for param, value in non_default_params.items(): + if param == "max_completion_tokens": + optional_params["max_tokens"] = value + elif param in supported_params: + optional_params[param] = value + return optional_params diff --git a/litellm/main.py b/litellm/main.py index 09c70998cf7d..6bc77942aa1c 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -641,6 +641,7 @@ async def acompletion( # noqa: PLR0915 if ( custom_llm_provider == "text-completion-openai" or custom_llm_provider == "text-completion-codestral" + or custom_llm_provider == "text-completion-inception" ) and isinstance(response, TextCompletionResponse): response = litellm.OpenAITextCompletionConfig().convert_to_chat_model_response_object( response_object=response, @@ -3803,6 +3804,61 @@ def completion( # type: ignore # noqa: PLR0915 ): return _model_response response = _model_response + elif custom_llm_provider == "text-completion-inception": + api_base = ( + api_base + or optional_params.pop("api_base", None) + or optional_params.pop("base_url", None) + or get_secret_str("INCEPTION_API_BASE") + or "https://api.inceptionlabs.ai/v1" + ) + # FIM is served at `/v1/fim/completions`; the OpenAI client appends + # `/completions`, so point it at the `/v1/fim` base. + api_base = api_base.rstrip("/") + if not api_base.endswith("/fim"): + api_base += "/fim" + + api_key = ( + api_key + or litellm.api_key + or litellm.inception_key + or get_secret_str("INCEPTION_API_KEY") + ) + + _response = openai_text_completions.completion( + model=model, + messages=messages, + model_response=model_response, + print_verbose=print_verbose, + api_key=api_key, + custom_llm_provider="text-completion-inception", + api_base=api_base, + acompletion=acompletion, + client=client, + logging_obj=logging, + optional_params=optional_params, + litellm_params=litellm_params, + logger_fn=logger_fn, + timeout=timeout, # type: ignore + ) + + if ( + optional_params.get("stream", False) is False + and acompletion is False + and text_completion is False + ): + _response = litellm.OpenAITextCompletionConfig().convert_to_chat_model_response_object( + response_object=_response, model_response_object=model_response + ) + + if optional_params.get("stream", False) or acompletion is True: + logging.post_call( + input=messages, + api_key=api_key, + original_response=_response, + additional_args={"headers": headers}, + ) + response = _response elif custom_llm_provider in ("sagemaker_chat", "sagemaker_nova"): # boto3 reads keys from .env # sagemaker_chat: HF Messages API endpoints diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index a604aafa540f..b2d4fd1dc2c0 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -23420,6 +23420,31 @@ "supports_system_messages": true, "supports_tool_choice": true }, + "inception/mercury-2": { + "cache_read_input_token_cost": 2.5e-08, + "input_cost_per_token": 2.5e-07, + "litellm_provider": "inception", + "max_input_tokens": 128000, + "max_output_tokens": 50000, + "max_tokens": 50000, + "mode": "chat", + "output_cost_per_token": 7.5e-07, + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_response_schema": true, + "supports_system_messages": true, + "supports_tool_choice": true + }, + "text-completion-inception/mercury-edit-2": { + "cache_read_input_token_cost": 2.5e-08, + "input_cost_per_token": 2.5e-07, + "litellm_provider": "text-completion-inception", + "max_input_tokens": 32000, + "max_output_tokens": 8192, + "max_tokens": 8192, + "mode": "completion", + "output_cost_per_token": 7.5e-07 + }, "lambda_ai/deepseek-llama3.3-70b": { "input_cost_per_token": 2e-07, "litellm_provider": "lambda_ai", diff --git a/litellm/types/utils.py b/litellm/types/utils.py index d208eb29ac11..7ef08ef17e7d 100644 --- a/litellm/types/utils.py +++ b/litellm/types/utils.py @@ -3294,6 +3294,8 @@ class LlmProviders(str, Enum): V0 = "v0" MORPH = "morph" LAMBDA_AI = "lambda_ai" + INCEPTION = "inception" + TEXT_COMPLETION_INCEPTION = "text-completion-inception" DEEPSEEK = "deepseek" SAMBANOVA = "sambanova" MARITALK = "maritalk" diff --git a/litellm/utils.py b/litellm/utils.py index 68982ea2b35c..61bebd614072 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -4547,6 +4547,18 @@ def _check_valid_arg(supported_params: List[str]): ), ) + elif custom_llm_provider == "text-completion-inception": + optional_params = litellm.InceptionTextCompletionConfig().map_openai_params( + non_default_params=non_default_params, + optional_params=optional_params, + model=model, + drop_params=( + drop_params + if drop_params is not None and isinstance(drop_params, bool) + else False + ), + ) + elif custom_llm_provider == "databricks": optional_params = litellm.DatabricksConfig().map_openai_params( non_default_params=non_default_params, @@ -6637,6 +6649,14 @@ def validate_environment( # noqa: PLR0915 keys_in_environment = True else: missing_keys.append("CODESTRAL_API_KEY") + elif ( + custom_llm_provider == "inception" + or custom_llm_provider == "text-completion-inception" + ): + if "INCEPTION_API_KEY" in os.environ: + keys_in_environment = True + else: + missing_keys.append("INCEPTION_API_KEY") elif custom_llm_provider == "deepseek": if "DEEPSEEK_API_KEY" in os.environ: keys_in_environment = True @@ -8291,6 +8311,7 @@ def _build_provider_config_map() -> dict[LlmProviders, tuple[Callable, bool]]: LlmProviders.XAI: (lambda: litellm.XAIChatConfig(), False), LlmProviders.ZAI: (lambda: litellm.ZAIChatConfig(), False), LlmProviders.LAMBDA_AI: (lambda: litellm.LambdaAIChatConfig(), False), + LlmProviders.INCEPTION: (lambda: litellm.InceptionChatConfig(), False), LlmProviders.LLAMA: (lambda: litellm.LlamaAPIConfig(), False), LlmProviders.TEXT_COMPLETION_OPENAI: ( lambda: litellm.OpenAITextCompletionConfig(), @@ -8356,6 +8377,10 @@ def _build_provider_config_map() -> dict[LlmProviders, tuple[Callable, bool]]: lambda: litellm.CodestralTextCompletionConfig(), False, ), + LlmProviders.TEXT_COMPLETION_INCEPTION: ( + lambda: litellm.InceptionTextCompletionConfig(), + False, + ), LlmProviders.SAMBANOVA: (lambda: litellm.SambanovaConfig(), False), LlmProviders.MARITALK: (lambda: litellm.MaritalkConfig(), False), LlmProviders.VLLM: (lambda: litellm.VLLMConfig(), False), @@ -8917,6 +8942,8 @@ def get_provider_text_completion_config( return litellm.FireworksAITextCompletionConfig() elif LlmProviders.TOGETHER_AI == provider: return litellm.TogetherAITextCompletionConfig() + elif LlmProviders.TEXT_COMPLETION_INCEPTION == provider: + return litellm.InceptionTextCompletionConfig() return litellm.OpenAITextCompletionConfig() @staticmethod diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index b253235ec2a0..047be0376359 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -23228,6 +23228,31 @@ "supports_system_messages": true, "supports_tool_choice": true }, + "inception/mercury-2": { + "cache_read_input_token_cost": 2.5e-08, + "input_cost_per_token": 2.5e-07, + "litellm_provider": "inception", + "max_input_tokens": 128000, + "max_output_tokens": 50000, + "max_tokens": 50000, + "mode": "chat", + "output_cost_per_token": 7.5e-07, + "supports_function_calling": true, + "supports_prompt_caching": true, + "supports_response_schema": true, + "supports_system_messages": true, + "supports_tool_choice": true + }, + "text-completion-inception/mercury-edit-2": { + "cache_read_input_token_cost": 2.5e-08, + "input_cost_per_token": 2.5e-07, + "litellm_provider": "text-completion-inception", + "max_input_tokens": 32000, + "max_output_tokens": 8192, + "max_tokens": 8192, + "mode": "completion", + "output_cost_per_token": 7.5e-07 + }, "lambda_ai/deepseek-llama3.3-70b": { "input_cost_per_token": 2e-07, "litellm_provider": "lambda_ai", diff --git a/tests/llm_translation/test_inception.py b/tests/llm_translation/test_inception.py new file mode 100644 index 000000000000..82ed813e021b --- /dev/null +++ b/tests/llm_translation/test_inception.py @@ -0,0 +1,456 @@ +""" +Tests for Inception (Mercury) provider integration +""" + +import json +import os +from unittest import mock + +import httpx +import pytest + +import litellm +from litellm.llms.inception.chat.transformation import InceptionChatConfig +from litellm.llms.inception.completion.transformation import ( + InceptionTextCompletionConfig, +) + + +def test_inception_config_initialization(): + config = InceptionChatConfig() + assert config.custom_llm_provider == "inception" + + +def test_inception_chat_supports_diffusion_params(): + """The chat config must expose Inception's diffusion-LLM request controls""" + params = InceptionChatConfig().get_supported_openai_params("mercury-2") + for p in ( + "reasoning_effort", + "reasoning_summary", + "reasoning_summary_wait", + "diffusing", + "realtime", + "tools", + "tool_choice", + "response_format", + ): + assert p in params, f"{p} should be a supported chat param" + + +def test_inception_chat_sends_diffusion_params_in_body(): + """reasoning_effort (incl. `instant`) and the diffusion flags reach the request body""" + + captured = {} + + def fake_send(self, request, **kwargs): + captured["body"] = json.loads(request.content.decode()) + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "c-1", + "object": "chat.completion", + "created": 1, + "model": "mercury-2", + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": "hi"}, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 1, + "total_tokens": 6, + }, + } + ).encode(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + litellm.completion( + model="inception/mercury-2", + messages=[{"role": "user", "content": "hi"}], + api_key="sk-x", + reasoning_effort="instant", + reasoning_summary=True, + reasoning_summary_wait=True, + diffusing=True, + realtime=True, + max_completion_tokens=128, + ) + + body = captured["body"] + assert body["reasoning_effort"] == "instant" + assert body["reasoning_summary"] is True + assert body["reasoning_summary_wait"] is True + assert body["diffusing"] is True + assert body["realtime"] is True + assert body["max_tokens"] == 128 # max_completion_tokens mapped to max_tokens + + +def test_inception_chat_response_surfaces_reasoning_and_usage(): + """reasoning_summary / warning survive, and reasoning_tokens maps to usage details""" + + def fake_send(self, request, **kwargs): + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "c-1", + "object": "chat.completion", + "created": 1, + "model": "mercury-2", + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": "answer"}, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 2, + "total_tokens": 7, + "reasoning_tokens": 4, + "cached_input_tokens": 3, + }, + "reasoning_summary": { + "content": "step by step", + "status": "complete", + }, + "warning": "heads up", + } + ).encode(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + r = litellm.completion( + model="inception/mercury-2", + messages=[{"role": "user", "content": "hi"}], + api_key="sk-x", + ) + + assert r.reasoning_summary == {"content": "step by step", "status": "complete"} + assert r.warning == "heads up" + assert r.usage.completion_tokens_details.reasoning_tokens == 4 + assert r.usage.model_extra.get("cached_input_tokens") == 3 + + +def test_inception_fim_supported_params_match_schema(): + """FIM exposes the OpenAI subset of Inception's FIMCompletionRequest only""" + params = InceptionTextCompletionConfig().get_supported_openai_params("mercury-edit-2") + for p in ("suffix", "top_p", "frequency_penalty", "presence_penalty", "stop"): + assert p in params + # Chat-only sampling controls are not part of Inception's FIM schema + for p in ("temperature", "seed", "logprobs", "n", "user"): + assert p not in params + + +def test_inception_fim_extra_body_forwards_vllm_params(): + """top_k / repetition_penalty are reachable via extra_body (not OpenAI params)""" + + captured = {} + + def fake_send(self, request, **kwargs): + captured["body"] = json.loads(request.content.decode()) + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "f-1", + "object": "text_completion", + "created": 1, + "model": "mercury-edit-2", + "choices": [ + { + "text": "x", + "index": 0, + "finish_reason": "stop", + "logprobs": None, + } + ], + "usage": { + "prompt_tokens": 2, + "completion_tokens": 1, + "total_tokens": 3, + }, + } + ).encode(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + litellm.text_completion( + model="text-completion-inception/mercury-edit-2", + prompt="def f(", + suffix=")", + api_key="sk-x", + top_p=0.9, + extra_body={"top_k": 40, "repetition_penalty": 1.1}, + ) + + body = captured["body"] + assert body["top_p"] == 0.9 + assert body["top_k"] == 40 + assert body["repetition_penalty"] == 1.1 + + +def test_inception_get_openai_compatible_provider_info(): + config = InceptionChatConfig() + + with mock.patch.dict(os.environ, {}, clear=True): + with mock.patch.object(litellm, "inception_key", None): + api_base, api_key = config._get_openai_compatible_provider_info(None, None) + assert api_base == "https://api.inceptionlabs.ai/v1" + assert api_key is None + + with mock.patch.dict( + os.environ, + { + "INCEPTION_API_KEY": "test-key", + "INCEPTION_API_BASE": "https://custom.inceptionlabs.ai/v1", + }, + ): + api_base, api_key = config._get_openai_compatible_provider_info(None, None) + assert api_base == "https://custom.inceptionlabs.ai/v1" + assert api_key == "test-key" + + with mock.patch.dict( + os.environ, + { + "INCEPTION_API_KEY": "env-key", + "INCEPTION_API_BASE": "https://env.inceptionlabs.ai/v1", + }, + ): + api_base, api_key = config._get_openai_compatible_provider_info( + "https://param.inceptionlabs.ai/v1", "param-key" + ) + assert api_base == "https://param.inceptionlabs.ai/v1" + assert api_key == "param-key" + + +def test_inception_key_module_attr_fallback(): + """litellm.inception_key is used when no param/env key is provided""" + config = InceptionChatConfig() + with mock.patch.dict(os.environ, {}, clear=True): + with mock.patch.object(litellm, "inception_key", "module-attr-key"): + _, api_key = config._get_openai_compatible_provider_info(None, None) + assert api_key == "module-attr-key" + + +def test_get_llm_provider_inception(): + from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider + + model, provider, _, _ = get_llm_provider("inception/mercury-2") + assert model == "mercury-2" + assert provider == "inception" + + model, provider, _, api_base = get_llm_provider("mercury-2", api_base="https://api.inceptionlabs.ai/v1") + assert model == "mercury-2" + assert provider == "inception" + assert api_base == "https://api.inceptionlabs.ai/v1" + + +def test_inception_in_provider_lists(): + assert "inception" in litellm.openai_compatible_providers + assert "inception" in litellm.provider_list + assert "https://api.inceptionlabs.ai/v1" in litellm.openai_compatible_endpoints + + +def test_inception_model_configuration(): + from litellm import get_model_info + + os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" + litellm.model_cost = litellm.get_model_cost_map(url="") + litellm.inception_models = set() + litellm.add_known_models() + + info = get_model_info("inception/mercury-2") + assert info.get("litellm_provider") == "inception" + assert info.get("mode") == "chat" + assert info.get("max_input_tokens") == 128000 + assert info.get("input_cost_per_token") == 2.5e-07 + assert info.get("output_cost_per_token") == 7.5e-07 + assert info.get("cache_read_input_token_cost") == 2.5e-08 + assert info.get("supports_function_calling") is True + assert info.get("supports_tool_choice") is True + assert info.get("supports_response_schema") is True + + +def test_inception_model_list_populated(): + os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" + litellm.model_cost = litellm.get_model_cost_map(url="") + litellm.inception_models = set() + litellm.add_known_models() + + assert "inception/mercury-2" in litellm.inception_models + for model in litellm.inception_models: + assert model.startswith("inception/") + + +def test_inception_completion_targets_inception_endpoint(): + """ + End-to-end: a completion routed through the inception provider must hit + Inception's base URL and path, send a Bearer token, and strip the + `inception/` prefix from the model name. + """ + + captured = {} + + def fake_send(self, request, **kwargs): + captured["url"] = str(request.url) + captured["auth"] = request.headers.get("authorization") + captured["body"] = json.loads(request.content.decode()) + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "cmpl-1", + "object": "chat.completion", + "created": 1, + "model": "mercury-2", + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": "hi"}, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 1, + "total_tokens": 6, + }, + } + ).encode(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + response = litellm.completion( + model="inception/mercury-2", + messages=[{"role": "user", "content": "hello"}], + api_key="sk-test-fake-123", + ) + + assert captured["url"] == "https://api.inceptionlabs.ai/v1/chat/completions" + assert captured["auth"] == "Bearer sk-test-fake-123" + assert captured["body"]["model"] == "mercury-2" + assert response.choices[0].message.content == "hi" + + +@pytest.mark.asyncio +async def test_inception_completion_call(): + """Live smoke test (requires INCEPTION_API_KEY)""" + if not os.getenv("INCEPTION_API_KEY"): + pytest.skip("INCEPTION_API_KEY not set") + + response = await litellm.acompletion( + model="inception/mercury-2", + messages=[{"role": "user", "content": "Hello, this is a test"}], + max_tokens=10, + ) + assert response.choices[0].message.content + assert response.model + assert response.usage + + +def test_inception_fim_supports_suffix_param(): + """The FIM config must keep `suffix` (otherwise FIM requests lose context)""" + config = InceptionTextCompletionConfig() + assert "suffix" in config.get_supported_openai_params("mercury-edit-2") + + mapped = config.map_openai_params( + non_default_params={"suffix": "\n return x", "max_completion_tokens": 50}, + optional_params={}, + model="mercury-edit-2", + drop_params=False, + ) + assert mapped["suffix"] == "\n return x" + assert mapped["max_tokens"] == 50 + + +def test_text_completion_inception_in_provider_lists(): + from litellm.types.utils import LlmProviders + + assert LlmProviders.TEXT_COMPLETION_INCEPTION == "text-completion-inception" + assert "text-completion-inception" in litellm.provider_list + + +def test_inception_fim_model_configuration(): + from litellm import get_model_info + + os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" + litellm.model_cost = litellm.get_model_cost_map(url="") + litellm.text_completion_inception_models = set() + litellm.add_known_models() + + assert "text-completion-inception/mercury-edit-2" in litellm.text_completion_inception_models + info = get_model_info("text-completion-inception/mercury-edit-2") + assert info.get("litellm_provider") == "text-completion-inception" + assert info.get("mode") == "completion" + assert info.get("max_input_tokens") == 32000 + + +def test_inception_fim_targets_fim_endpoint(): + """ + End-to-end: a FIM request must hit `/v1/fim/completions` (NOT + `/v1/completions`), carry the `suffix`, and parse the standard `text` field. + """ + + captured = {} + + def fake_send(self, request, **kwargs): + captured["url"] = str(request.url) + captured["auth"] = request.headers.get("authorization") + captured["body"] = json.loads(request.content.decode()) + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "fim-1", + "object": "text_completion", + "created": 1, + "model": "mercury-edit-2", + "choices": [ + { + "text": "a + b", + "index": 0, + "finish_reason": "stop", + "logprobs": None, + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 3, + "total_tokens": 8, + }, + } + ).encode(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + response = litellm.text_completion( + model="text-completion-inception/mercury-edit-2", + prompt="def add(a, b):\n return ", + suffix="\n", + api_key="sk-fim-fake", + max_tokens=20, + ) + + assert captured["url"] == "https://api.inceptionlabs.ai/v1/fim/completions" + assert captured["auth"] == "Bearer sk-fim-fake" + assert captured["body"]["model"] == "mercury-edit-2" + assert captured["body"]["suffix"] == "\n" + assert "prompt" in captured["body"] + assert response.choices[0].text == "a + b" From 890a0a4d2accc75dd0630faf98252e684b712bd8 Mon Sep 17 00:00:00 2001 From: yanismiraoui Date: Tue, 2 Jun 2026 12:33:14 -0700 Subject: [PATCH 2/4] linting --- litellm/_lazy_imports_registry.py | 5 ++++- litellm/llms/inception/chat/transformation.py | 4 +++- provider_endpoints_support.json | 18 ++++++++++++++++++ tests/llm_translation/test_inception.py | 13 ++++++++++--- 4 files changed, 35 insertions(+), 5 deletions(-) diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py index 4bd55dd59ad3..bdc3289b87c9 100644 --- a/litellm/_lazy_imports_registry.py +++ b/litellm/_lazy_imports_registry.py @@ -1160,7 +1160,10 @@ "MorphChatConfig": (".llms.morph.chat.transformation", "MorphChatConfig"), "RAGFlowConfig": (".llms.ragflow.chat.transformation", "RAGFlowConfig"), "LambdaAIChatConfig": (".llms.lambda_ai.chat.transformation", "LambdaAIChatConfig"), - "InceptionChatConfig": (".llms.inception.chat.transformation", "InceptionChatConfig"), + "InceptionChatConfig": ( + ".llms.inception.chat.transformation", + "InceptionChatConfig", + ), "HyperbolicChatConfig": ( ".llms.hyperbolic.chat.transformation", "HyperbolicChatConfig", diff --git a/litellm/llms/inception/chat/transformation.py b/litellm/llms/inception/chat/transformation.py index 24c071c5fdcc..f67eb02bd0a1 100644 --- a/litellm/llms/inception/chat/transformation.py +++ b/litellm/llms/inception/chat/transformation.py @@ -45,5 +45,7 @@ def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: api_base = api_base or get_secret_str("INCEPTION_API_BASE") or "https://api.inceptionlabs.ai/v1" # type: ignore - dynamic_api_key = api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") + dynamic_api_key = ( + api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") + ) return api_base, dynamic_api_key diff --git a/provider_endpoints_support.json b/provider_endpoints_support.json index 1e8357a81378..f29e622a932c 100644 --- a/provider_endpoints_support.json +++ b/provider_endpoints_support.json @@ -1273,6 +1273,24 @@ "interactions": true } }, + "inception": { + "display_name": "Inception (`inception`)", + "url": "https://docs.litellm.ai/docs/providers/inception", + "endpoints": { + "chat_completions": true, + "messages": true, + "responses": true, + "embeddings": false, + "image_generations": false, + "audio_transcriptions": false, + "audio_speech": false, + "moderations": false, + "batches": false, + "rerank": false, + "a2a": true, + "interactions": true + } + }, "infinity": { "display_name": "Infinity (`infinity`)", "url": "https://docs.litellm.ai/docs/providers/infinity", diff --git a/tests/llm_translation/test_inception.py b/tests/llm_translation/test_inception.py index 82ed813e021b..fe46a7f64615 100644 --- a/tests/llm_translation/test_inception.py +++ b/tests/llm_translation/test_inception.py @@ -144,7 +144,9 @@ def fake_send(self, request, **kwargs): def test_inception_fim_supported_params_match_schema(): """FIM exposes the OpenAI subset of Inception's FIMCompletionRequest only""" - params = InceptionTextCompletionConfig().get_supported_openai_params("mercury-edit-2") + params = InceptionTextCompletionConfig().get_supported_openai_params( + "mercury-edit-2" + ) for p in ("suffix", "top_p", "frequency_penalty", "presence_penalty", "stop"): assert p in params # Chat-only sampling controls are not part of Inception's FIM schema @@ -252,7 +254,9 @@ def test_get_llm_provider_inception(): assert model == "mercury-2" assert provider == "inception" - model, provider, _, api_base = get_llm_provider("mercury-2", api_base="https://api.inceptionlabs.ai/v1") + model, provider, _, api_base = get_llm_provider( + "mercury-2", api_base="https://api.inceptionlabs.ai/v1" + ) assert model == "mercury-2" assert provider == "inception" assert api_base == "https://api.inceptionlabs.ai/v1" @@ -393,7 +397,10 @@ def test_inception_fim_model_configuration(): litellm.text_completion_inception_models = set() litellm.add_known_models() - assert "text-completion-inception/mercury-edit-2" in litellm.text_completion_inception_models + assert ( + "text-completion-inception/mercury-edit-2" + in litellm.text_completion_inception_models + ) info = get_model_info("text-completion-inception/mercury-edit-2") assert info.get("litellm_provider") == "text-completion-inception" assert info.get("mode") == "completion" From 58b9dc3fc96f42cb926a40724a1366d2220f2e18 Mon Sep 17 00:00:00 2001 From: yanismiraoui Date: Tue, 2 Jun 2026 12:41:49 -0700 Subject: [PATCH 3/4] seperate test suite for chat and fim --- litellm/main.py | 2 +- tests/test_litellm/llms/inception/__init__.py | 0 .../test_inception_chat_transformation.py} | 196 ++---------------- ...est_inception_completion_transformation.py | 172 +++++++++++++++ 4 files changed, 188 insertions(+), 182 deletions(-) create mode 100644 tests/test_litellm/llms/inception/__init__.py rename tests/{llm_translation/test_inception.py => test_litellm/llms/inception/test_inception_chat_transformation.py} (60%) create mode 100644 tests/test_litellm/llms/inception/test_inception_completion_transformation.py diff --git a/litellm/main.py b/litellm/main.py index 6bc77942aa1c..e0aa94ca144a 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -3822,7 +3822,7 @@ def completion( # type: ignore # noqa: PLR0915 api_key or litellm.api_key or litellm.inception_key - or get_secret_str("INCEPTION_API_KEY") + or get_secret("INCEPTION_API_KEY") ) _response = openai_text_completions.completion( diff --git a/tests/test_litellm/llms/inception/__init__.py b/tests/test_litellm/llms/inception/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/llm_translation/test_inception.py b/tests/test_litellm/llms/inception/test_inception_chat_transformation.py similarity index 60% rename from tests/llm_translation/test_inception.py rename to tests/test_litellm/llms/inception/test_inception_chat_transformation.py index fe46a7f64615..3f8e966cba44 100644 --- a/tests/llm_translation/test_inception.py +++ b/tests/test_litellm/llms/inception/test_inception_chat_transformation.py @@ -1,5 +1,5 @@ """ -Tests for Inception (Mercury) provider integration +Tests for Inception (Mercury) chat provider integration """ import json @@ -7,13 +7,9 @@ from unittest import mock import httpx -import pytest import litellm from litellm.llms.inception.chat.transformation import InceptionChatConfig -from litellm.llms.inception.completion.transformation import ( - InceptionTextCompletionConfig, -) def test_inception_config_initialization(): @@ -142,68 +138,6 @@ def fake_send(self, request, **kwargs): assert r.usage.model_extra.get("cached_input_tokens") == 3 -def test_inception_fim_supported_params_match_schema(): - """FIM exposes the OpenAI subset of Inception's FIMCompletionRequest only""" - params = InceptionTextCompletionConfig().get_supported_openai_params( - "mercury-edit-2" - ) - for p in ("suffix", "top_p", "frequency_penalty", "presence_penalty", "stop"): - assert p in params - # Chat-only sampling controls are not part of Inception's FIM schema - for p in ("temperature", "seed", "logprobs", "n", "user"): - assert p not in params - - -def test_inception_fim_extra_body_forwards_vllm_params(): - """top_k / repetition_penalty are reachable via extra_body (not OpenAI params)""" - - captured = {} - - def fake_send(self, request, **kwargs): - captured["body"] = json.loads(request.content.decode()) - return httpx.Response( - status_code=200, - request=request, - headers={"content-type": "application/json"}, - content=json.dumps( - { - "id": "f-1", - "object": "text_completion", - "created": 1, - "model": "mercury-edit-2", - "choices": [ - { - "text": "x", - "index": 0, - "finish_reason": "stop", - "logprobs": None, - } - ], - "usage": { - "prompt_tokens": 2, - "completion_tokens": 1, - "total_tokens": 3, - }, - } - ).encode(), - ) - - with mock.patch("httpx.Client.send", new=fake_send): - litellm.text_completion( - model="text-completion-inception/mercury-edit-2", - prompt="def f(", - suffix=")", - api_key="sk-x", - top_p=0.9, - extra_body={"top_k": 40, "repetition_penalty": 1.1}, - ) - - body = captured["body"] - assert body["top_p"] == 0.9 - assert body["top_k"] == 40 - assert body["repetition_penalty"] == 1.1 - - def test_inception_get_openai_compatible_provider_info(): config = InceptionChatConfig() @@ -302,8 +236,8 @@ def test_inception_model_list_populated(): def test_inception_completion_targets_inception_endpoint(): """ End-to-end: a completion routed through the inception provider must hit - Inception's base URL and path, send a Bearer token, and strip the - `inception/` prefix from the model name. + Inception's base URL and path, send a Bearer token, strip the + `inception/` prefix from the model name, and forward tool_choice. """ captured = {} @@ -338,126 +272,26 @@ def fake_send(self, request, **kwargs): ).encode(), ) + tools = [ + { + "type": "function", + "function": { + "name": "f", + "parameters": {"type": "object", "properties": {}}, + }, + } + ] with mock.patch("httpx.Client.send", new=fake_send): response = litellm.completion( model="inception/mercury-2", messages=[{"role": "user", "content": "hello"}], api_key="sk-test-fake-123", + tools=tools, + tool_choice="auto", ) assert captured["url"] == "https://api.inceptionlabs.ai/v1/chat/completions" assert captured["auth"] == "Bearer sk-test-fake-123" assert captured["body"]["model"] == "mercury-2" + assert captured["body"]["tool_choice"] == "auto" assert response.choices[0].message.content == "hi" - - -@pytest.mark.asyncio -async def test_inception_completion_call(): - """Live smoke test (requires INCEPTION_API_KEY)""" - if not os.getenv("INCEPTION_API_KEY"): - pytest.skip("INCEPTION_API_KEY not set") - - response = await litellm.acompletion( - model="inception/mercury-2", - messages=[{"role": "user", "content": "Hello, this is a test"}], - max_tokens=10, - ) - assert response.choices[0].message.content - assert response.model - assert response.usage - - -def test_inception_fim_supports_suffix_param(): - """The FIM config must keep `suffix` (otherwise FIM requests lose context)""" - config = InceptionTextCompletionConfig() - assert "suffix" in config.get_supported_openai_params("mercury-edit-2") - - mapped = config.map_openai_params( - non_default_params={"suffix": "\n return x", "max_completion_tokens": 50}, - optional_params={}, - model="mercury-edit-2", - drop_params=False, - ) - assert mapped["suffix"] == "\n return x" - assert mapped["max_tokens"] == 50 - - -def test_text_completion_inception_in_provider_lists(): - from litellm.types.utils import LlmProviders - - assert LlmProviders.TEXT_COMPLETION_INCEPTION == "text-completion-inception" - assert "text-completion-inception" in litellm.provider_list - - -def test_inception_fim_model_configuration(): - from litellm import get_model_info - - os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" - litellm.model_cost = litellm.get_model_cost_map(url="") - litellm.text_completion_inception_models = set() - litellm.add_known_models() - - assert ( - "text-completion-inception/mercury-edit-2" - in litellm.text_completion_inception_models - ) - info = get_model_info("text-completion-inception/mercury-edit-2") - assert info.get("litellm_provider") == "text-completion-inception" - assert info.get("mode") == "completion" - assert info.get("max_input_tokens") == 32000 - - -def test_inception_fim_targets_fim_endpoint(): - """ - End-to-end: a FIM request must hit `/v1/fim/completions` (NOT - `/v1/completions`), carry the `suffix`, and parse the standard `text` field. - """ - - captured = {} - - def fake_send(self, request, **kwargs): - captured["url"] = str(request.url) - captured["auth"] = request.headers.get("authorization") - captured["body"] = json.loads(request.content.decode()) - return httpx.Response( - status_code=200, - request=request, - headers={"content-type": "application/json"}, - content=json.dumps( - { - "id": "fim-1", - "object": "text_completion", - "created": 1, - "model": "mercury-edit-2", - "choices": [ - { - "text": "a + b", - "index": 0, - "finish_reason": "stop", - "logprobs": None, - } - ], - "usage": { - "prompt_tokens": 5, - "completion_tokens": 3, - "total_tokens": 8, - }, - } - ).encode(), - ) - - with mock.patch("httpx.Client.send", new=fake_send): - response = litellm.text_completion( - model="text-completion-inception/mercury-edit-2", - prompt="def add(a, b):\n return ", - suffix="\n", - api_key="sk-fim-fake", - max_tokens=20, - ) - - assert captured["url"] == "https://api.inceptionlabs.ai/v1/fim/completions" - assert captured["auth"] == "Bearer sk-fim-fake" - assert captured["body"]["model"] == "mercury-edit-2" - assert captured["body"]["suffix"] == "\n" - assert "prompt" in captured["body"] - assert response.choices[0].text == "a + b" diff --git a/tests/test_litellm/llms/inception/test_inception_completion_transformation.py b/tests/test_litellm/llms/inception/test_inception_completion_transformation.py new file mode 100644 index 000000000000..c412fdb38694 --- /dev/null +++ b/tests/test_litellm/llms/inception/test_inception_completion_transformation.py @@ -0,0 +1,172 @@ +""" +Tests for Inception (Mercury) fill-in-the-middle (FIM) provider integration +""" + +import json +import os +from unittest import mock + +import httpx + +import litellm +from litellm.llms.inception.completion.transformation import ( + InceptionTextCompletionConfig, +) + + +def test_inception_fim_supports_suffix_param(): + """The FIM config must keep `suffix` (otherwise FIM requests lose context)""" + config = InceptionTextCompletionConfig() + assert "suffix" in config.get_supported_openai_params("mercury-edit-2") + + mapped = config.map_openai_params( + non_default_params={"suffix": "\n return x", "max_completion_tokens": 50}, + optional_params={}, + model="mercury-edit-2", + drop_params=False, + ) + assert mapped["suffix"] == "\n return x" + assert mapped["max_tokens"] == 50 + + +def test_inception_fim_supported_params_match_schema(): + """FIM exposes the OpenAI subset of Inception's FIMCompletionRequest only""" + params = InceptionTextCompletionConfig().get_supported_openai_params( + "mercury-edit-2" + ) + for p in ("suffix", "top_p", "frequency_penalty", "presence_penalty", "stop"): + assert p in params + # Chat-only sampling controls are not part of Inception's FIM schema + for p in ("temperature", "seed", "logprobs", "n", "user"): + assert p not in params + + +def test_text_completion_inception_in_provider_lists(): + from litellm.types.utils import LlmProviders + + assert LlmProviders.TEXT_COMPLETION_INCEPTION == "text-completion-inception" + assert "text-completion-inception" in litellm.provider_list + + +def test_inception_fim_model_configuration(): + from litellm import get_model_info + + os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" + litellm.model_cost = litellm.get_model_cost_map(url="") + litellm.text_completion_inception_models = set() + litellm.add_known_models() + + assert ( + "text-completion-inception/mercury-edit-2" + in litellm.text_completion_inception_models + ) + info = get_model_info("text-completion-inception/mercury-edit-2") + assert info.get("litellm_provider") == "text-completion-inception" + assert info.get("mode") == "completion" + assert info.get("max_input_tokens") == 32000 + + +def test_inception_fim_targets_fim_endpoint(): + """ + End-to-end: a FIM request must hit `/v1/fim/completions` (NOT + `/v1/completions`), carry the `suffix`, and parse the standard `text` field. + """ + + captured = {} + + def fake_send(self, request, **kwargs): + captured["url"] = str(request.url) + captured["auth"] = request.headers.get("authorization") + captured["body"] = json.loads(request.content.decode()) + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "fim-1", + "object": "text_completion", + "created": 1, + "model": "mercury-edit-2", + "choices": [ + { + "text": "a + b", + "index": 0, + "finish_reason": "stop", + "logprobs": None, + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 3, + "total_tokens": 8, + }, + } + ).encode(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + response = litellm.text_completion( + model="text-completion-inception/mercury-edit-2", + prompt="def add(a, b):\n return ", + suffix="\n", + api_key="sk-fim-fake", + max_tokens=20, + ) + + assert captured["url"] == "https://api.inceptionlabs.ai/v1/fim/completions" + assert captured["auth"] == "Bearer sk-fim-fake" + assert captured["body"]["model"] == "mercury-edit-2" + assert captured["body"]["suffix"] == "\n" + assert "prompt" in captured["body"] + assert response.choices[0].text == "a + b" + + +def test_inception_fim_extra_body_forwards_vllm_params(): + """top_k / repetition_penalty are reachable via extra_body (not OpenAI params)""" + + captured = {} + + def fake_send(self, request, **kwargs): + captured["body"] = json.loads(request.content.decode()) + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=json.dumps( + { + "id": "f-1", + "object": "text_completion", + "created": 1, + "model": "mercury-edit-2", + "choices": [ + { + "text": "x", + "index": 0, + "finish_reason": "stop", + "logprobs": None, + } + ], + "usage": { + "prompt_tokens": 2, + "completion_tokens": 1, + "total_tokens": 3, + }, + } + ).encode(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + litellm.text_completion( + model="text-completion-inception/mercury-edit-2", + prompt="def f(", + suffix=")", + api_key="sk-x", + top_p=0.9, + extra_body={"top_k": 40, "repetition_penalty": 1.1}, + ) + + body = captured["body"] + assert body["top_p"] == 0.9 + assert body["top_k"] == 40 + assert body["repetition_penalty"] == 1.1 From c17ac4076aeb44b581c7b4e559e460dd3094a882 Mon Sep 17 00:00:00 2001 From: yanismiraoui Date: Tue, 2 Jun 2026 13:53:45 -0700 Subject: [PATCH 4/4] fix test coverage --- .../get_supported_openai_params.py | 4 - litellm/llms/inception/chat/transformation.py | 9 +- litellm/main.py | 23 +++-- .../test_inception_chat_transformation.py | 29 ++++++ ...est_inception_completion_transformation.py | 95 +++++++++++++++++++ 5 files changed, 145 insertions(+), 15 deletions(-) diff --git a/litellm/litellm_core_utils/get_supported_openai_params.py b/litellm/litellm_core_utils/get_supported_openai_params.py index f389b2858a2e..b8cdc8210fcc 100644 --- a/litellm/litellm_core_utils/get_supported_openai_params.py +++ b/litellm/litellm_core_utils/get_supported_openai_params.py @@ -179,10 +179,6 @@ def get_supported_openai_params( # noqa: PLR0915 return litellm.CodestralTextCompletionConfig().get_supported_openai_params( model=model ) - elif custom_llm_provider == "text-completion-inception": - return litellm.InceptionTextCompletionConfig().get_supported_openai_params( - model=model - ) elif custom_llm_provider == "sambanova": if request_type == "embeddings": litellm.SambaNovaEmbeddingConfig().get_supported_openai_params(model=model) diff --git a/litellm/llms/inception/chat/transformation.py b/litellm/llms/inception/chat/transformation.py index f67eb02bd0a1..d591f783a993 100644 --- a/litellm/llms/inception/chat/transformation.py +++ b/litellm/llms/inception/chat/transformation.py @@ -44,8 +44,11 @@ def get_supported_openai_params(self, model: str) -> List: def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: + passed_api_base = api_base api_base = api_base or get_secret_str("INCEPTION_API_BASE") or "https://api.inceptionlabs.ai/v1" # type: ignore - dynamic_api_key = ( - api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") - ) + dynamic_api_key = api_key + if passed_api_base is None or api_key: + dynamic_api_key = ( + api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") + ) return api_base, dynamic_api_key diff --git a/litellm/main.py b/litellm/main.py index e0aa94ca144a..098a48b1142e 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -3805,10 +3805,13 @@ def completion( # type: ignore # noqa: PLR0915 return _model_response response = _model_response elif custom_llm_provider == "text-completion-inception": - api_base = ( + passed_api_base = ( api_base or optional_params.pop("api_base", None) or optional_params.pop("base_url", None) + ) + api_base = ( + passed_api_base or get_secret_str("INCEPTION_API_BASE") or "https://api.inceptionlabs.ai/v1" ) @@ -3818,19 +3821,23 @@ def completion( # type: ignore # noqa: PLR0915 if not api_base.endswith("/fim"): api_base += "/fim" - api_key = ( - api_key - or litellm.api_key - or litellm.inception_key - or get_secret("INCEPTION_API_KEY") - ) + # Don't forward the server-managed Inception key to a caller-supplied + # api_base; only resolve it for the default/server base, or when the + # caller passes their own key. + if passed_api_base is None or api_key: + api_key = ( + api_key + or litellm.api_key + or litellm.inception_key + or get_secret("INCEPTION_API_KEY") + ) _response = openai_text_completions.completion( model=model, messages=messages, model_response=model_response, print_verbose=print_verbose, - api_key=api_key, + api_key=api_key, # type: ignore[arg-type] custom_llm_provider="text-completion-inception", api_base=api_base, acompletion=acompletion, diff --git a/tests/test_litellm/llms/inception/test_inception_chat_transformation.py b/tests/test_litellm/llms/inception/test_inception_chat_transformation.py index 3f8e966cba44..0750fb9e405e 100644 --- a/tests/test_litellm/llms/inception/test_inception_chat_transformation.py +++ b/tests/test_litellm/llms/inception/test_inception_chat_transformation.py @@ -181,6 +181,35 @@ def test_inception_key_module_attr_fallback(): assert api_key == "module-attr-key" +def test_inception_does_not_leak_key_to_caller_api_base(): + """ + The server-managed Inception key must not be forwarded to a caller-supplied + api_base. It is only resolved for the default/server base, or when the + caller also supplies their own key. + """ + config = InceptionChatConfig() + with mock.patch.dict( + os.environ, {"INCEPTION_API_KEY": "server-secret"}, clear=True + ): + with mock.patch.object(litellm, "inception_key", "module-secret"): + # caller overrides api_base without a key -> server key withheld + api_base, api_key = config._get_openai_compatible_provider_info( + "https://attacker.example/v1", None + ) + assert api_base == "https://attacker.example/v1" + assert api_key is None + + # caller overrides api_base AND supplies their own key -> used as-is + _, api_key = config._get_openai_compatible_provider_info( + "https://attacker.example/v1", "caller-key" + ) + assert api_key == "caller-key" + + # default/server base -> server-managed key resolved + _, api_key = config._get_openai_compatible_provider_info(None, None) + assert api_key == "module-secret" + + def test_get_llm_provider_inception(): from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider diff --git a/tests/test_litellm/llms/inception/test_inception_completion_transformation.py b/tests/test_litellm/llms/inception/test_inception_completion_transformation.py index c412fdb38694..0ecc8f94a075 100644 --- a/tests/test_litellm/llms/inception/test_inception_completion_transformation.py +++ b/tests/test_litellm/llms/inception/test_inception_completion_transformation.py @@ -7,6 +7,7 @@ from unittest import mock import httpx +import pytest import litellm from litellm.llms.inception.completion.transformation import ( @@ -14,6 +15,21 @@ ) +def _fim_response_bytes(): + return json.dumps( + { + "id": "fim-1", + "object": "text_completion", + "created": 1, + "model": "mercury-edit-2", + "choices": [ + {"text": "a + b", "index": 0, "finish_reason": "stop", "logprobs": None} + ], + "usage": {"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8}, + } + ).encode() + + def test_inception_fim_supports_suffix_param(): """The FIM config must keep `suffix` (otherwise FIM requests lose context)""" config = InceptionTextCompletionConfig() @@ -48,6 +64,85 @@ def test_text_completion_inception_in_provider_lists(): assert "text-completion-inception" in litellm.provider_list +def test_inception_get_supported_openai_params_dispatch(): + """litellm.get_supported_openai_params routes the FIM provider to our config""" + params = litellm.get_supported_openai_params( + model="mercury-edit-2", custom_llm_provider="text-completion-inception" + ) + assert "suffix" in params + assert "temperature" not in params + + +@pytest.mark.parametrize("provider", ["inception", "text-completion-inception"]) +def test_inception_validate_environment(provider): + model = ( + "inception/mercury-2" + if provider == "inception" + else "text-completion-inception/mercury-edit-2" + ) + + with mock.patch.dict(os.environ, {}, clear=True): + result = litellm.validate_environment(model) + assert result["keys_in_environment"] is False + assert "INCEPTION_API_KEY" in result["missing_keys"] + + with mock.patch.dict(os.environ, {"INCEPTION_API_KEY": "sk-x"}, clear=True): + result = litellm.validate_environment(model) + assert result["keys_in_environment"] is True + + +def test_inception_completion_endpoint_returns_chat_object(): + """ + Calling chat `completion()` with the FIM provider converts the text + completion result into a chat-shaped ModelResponse. + """ + + def fake_send(self, request, **kwargs): + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=_fim_response_bytes(), + ) + + with mock.patch("httpx.Client.send", new=fake_send): + r = litellm.completion( + model="text-completion-inception/mercury-edit-2", + messages=[{"role": "user", "content": "def add(a, b): return "}], + api_key="sk-x", + ) + + assert r.choices[0].message.content == "a + b" + + +@pytest.mark.asyncio +async def test_inception_fim_async(): + """async FIM path (acompletion) hits Inception's /v1/fim/completions""" + + captured = {} + + async def fake_asend(self, request, **kwargs): + captured["url"] = str(request.url) + return httpx.Response( + status_code=200, + request=request, + headers={"content-type": "application/json"}, + content=_fim_response_bytes(), + ) + + with mock.patch("httpx.AsyncClient.send", new=fake_asend): + r = await litellm.atext_completion( + model="text-completion-inception/mercury-edit-2", + prompt="def add(a, b): return ", + suffix="\n", + api_key="sk-x", + max_tokens=10, + ) + + assert captured["url"] == "https://api.inceptionlabs.ai/v1/fim/completions" + assert r.choices[0].text == "a + b" + + def test_inception_fim_model_configuration(): from litellm import get_model_info