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]

Anthropic `/v1/messages` - Custom LLM Server support (#12016)

Krish Dholakia24c2cd1bd9f6
diff --git a/docs/my-website/docs/providers/azure/azure_responses.md b/docs/my-website/docs/providers/azure/azure_responses.md
index b17ef8a2853..34ec0e194f7 100644
--- a/docs/my-website/docs/providers/azure/azure_responses.md
+++ b/docs/my-website/docs/providers/azure/azure_responses.md
@@ -233,3 +233,63 @@ for event in response:
</TabItem>
</Tabs>
+
+## Calling via `/chat/completions`
+
+You can also call the Azure Responses API via the `/chat/completions` endpoint.
+
+
+<Tabs>
+<TabItem value="litellm-sdk" label="LiteLLM SDK">
+
+```python showLineNumbers
+from litellm import completion
+import os
+
+os.environ["AZURE_API_BASE"] = "https://my-endpoint-sweden-berri992.openai.azure.com/"
+os.environ["AZURE_API_VERSION"] = "2023-03-15-preview"
+os.environ["AZURE_API_KEY"] = "my-api-key"
+
+response = completion(
+ model="azure/responses/my-custom-o1-pro",
+ messages=[{"role": "user", "content": "Hello world"}],
+)
+
+print(response)
+```
+</TabItem>
+<TabItem value="proxy" label="OpenAI SDK with LiteLLM Proxy">
+
+1. Setup config.yaml
+
+```yaml showLineNumbers
+model_list:
+ - model_name: my-custom-o1-pro
+ litellm_params:
+ model: azure/responses/my-custom-o1-pro
+ api_key: os.environ/AZURE_API_KEY
+ api_base: https://my-endpoint-sweden-berri992.openai.azure.com/
+ api_version: 2023-03-15-preview
+```
+
+2. Start LiteLLM proxy
+```bash
+litellm --config /path/to/config.yaml
+
+# RUNNING on http://0.0.0.0:4000
+```
+
+3. Test it!
+
+```bash
+curl http://localhost:4000/v1/chat/completions \
+ -X POST \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $LITELLM_API_KEY" \
+ -d '{
+ "model": "my-custom-o1-pro",
+ "messages": [{"role": "user", "content": "Hello world"}]
+ }'
+```
+</TabItem>
+</Tabs>
\ No newline at end of file
diff --git a/docs/my-website/docs/providers/custom_llm_server.md b/docs/my-website/docs/providers/custom_llm_server.md
index 055b6906a9f..61099d1a358 100644
--- a/docs/my-website/docs/providers/custom_llm_server.md
+++ b/docs/my-website/docs/providers/custom_llm_server.md
@@ -13,11 +13,12 @@ Call your custom torch-serve / internal LLM APIs via LiteLLM
:::
Supported Routes:
-- `/v1/chat/completions` -> `litellm.completion`
-- `/v1/completions` -> `litellm.text_completion`
-- `/v1/embeddings` -> `litellm.embedding`
-- `/v1/images/generations` -> `litellm.image_generation`
+- `/v1/chat/completions` -> `litellm.acompletion`
+- `/v1/completions` -> `litellm.atext_completion`
+- `/v1/embeddings` -> `litellm.aembedding`
+- `/v1/images/generations` -> `litellm.aimage_generation`
+- `/v1/messages` -> `litellm.acompletion`
## Quick Start
@@ -262,6 +263,102 @@ Expected Response
}
```
+## Anthropic `/v1/messages`
+
+- Write the integration for .acompletion
+- litellm will transform it to /v1/messages
+
+1. Setup your `custom_handler.py` file
+
+```python
+import litellm
+from litellm import CustomLLM, completion, get_llm_provider
+
+
+class MyCustomLLM(CustomLLM):
+ async def acompletion(self, *args, **kwargs) -> litellm.ModelResponse:
+ return litellm.completion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hello world"}],
+ mock_response="Hi!",
+ ) # type: ignore
+
+
+my_custom_llm = MyCustomLLM()
+```
+
+2. Add to `config.yaml`
+
+In the config below, we pass
+
+python_filename: `custom_handler.py`
+custom_handler_instance_name: `my_custom_llm`. This is defined in Step 1
+
+custom_handler: `custom_handler.my_custom_llm`
+
+```yaml
+model_list:
+ - model_name: "test-model"
+ litellm_params:
+ model: "openai/text-embedding-ada-002"
+ - model_name: "my-custom-model"
+ litellm_params:
+ model: "my-custom-llm/my-model"
+
+litellm_settings:
+ custom_provider_map:
+ - {"provider": "my-custom-llm", "custom_handler": custom_handler.my_custom_llm}
+```
+
+```bash
+litellm --config /path/to/config.yaml
+```
+
+3. Test it!
+
+```bash
+curl -L -X POST 'http://0.0.0.0:4000/v1/messages' \
+-H 'anthropic-version: 2023-06-01' \
+-H 'content-type: application/json' \
+-H 'Authorization: Bearer sk-1234' \
+-d '{
+ "model": "my-custom-model",
+ "max_tokens": 1024,
+ "messages": [{
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "What are the key findings in this document 12?"
+ }]
+ }]
+}'
+```
+
+Expected Response
+
+```json
+{
+ "id": "chatcmpl-Bm4qEp4h4vCe7Zi4Gud1MAxTWgibO",
+ "type": "message",
+ "role": "assistant",
+ "model": "gpt-3.5-turbo-0125",
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 18,
+ "output_tokens": 44
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Without the specific document being provided, it is not possible to determine the key findings within it. If you can provide the content or a summary of document 12, I would be happy to help identify the key findings."
+ }
+ ],
+ "stop_reason": "end_turn"
+}
+```
+
+
## Additional Parameters
Additional parameters are passed inside `optional_params` key in the `completion` or `image_generation` function.
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
index ddb3eaed80b..37fd839b3c5 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
@@ -119,6 +119,8 @@ def anthropic_messages_handler(
"""
Makes Anthropic `/v1/messages` API calls In the Anthropic API Spec
"""
+ from litellm.types.utils import LlmProviders
+
local_vars = locals()
is_async = kwargs.pop("is_async", False)
# Use provided client or create a new one
@@ -141,12 +143,17 @@ def anthropic_messages_handler(
api_key=litellm_params.api_key,
)
- anthropic_messages_provider_config: Optional[
- BaseAnthropicMessagesConfig
- ] = ProviderConfigManager.get_provider_anthropic_messages_config(
- model=model,
- provider=litellm.LlmProviders(custom_llm_provider),
- )
+ anthropic_messages_provider_config: Optional[BaseAnthropicMessagesConfig] = None
+
+ if custom_llm_provider is not None and custom_llm_provider in [
+ provider.value for provider in LlmProviders
+ ]:
+ anthropic_messages_provider_config = (
+ ProviderConfigManager.get_provider_anthropic_messages_config(
+ model=model,
+ provider=litellm.LlmProviders(custom_llm_provider),
+ )
+ )
if anthropic_messages_provider_config is None:
# Handle non-Anthropic models using the adapter
return (
diff --git a/litellm/llms/volcengine.py b/litellm/llms/volcengine.py
index c569475b11c..58d2371af53 100644
--- a/litellm/llms/volcengine.py
+++ b/litellm/llms/volcengine.py
@@ -63,3 +63,26 @@ class VolcEngineConfig(OpenAILikeChatConfig):
"extra_headers",
"thinking",
] # works across all models
+
+ def map_openai_params(
+ self,
+ non_default_params: dict,
+ optional_params: dict,
+ model: str,
+ drop_params: bool,
+ replace_max_completion_tokens_with_max_tokens: bool = True,
+ ) -> dict:
+ optional_params = super().map_openai_params(
+ non_default_params,
+ optional_params,
+ model,
+ drop_params,
+ replace_max_completion_tokens_with_max_tokens,
+ )
+
+ if "thinking" in optional_params:
+ optional_params.setdefault("extra_body", {})["thinking"] = (
+ optional_params.pop("thinking")
+ )
+
+ return optional_params
diff --git a/litellm/main.py b/litellm/main.py
index d27411ad3b8..2a2ed517ebe 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -1297,6 +1297,12 @@ def completion( # type: ignore # noqa: PLR0915
except Exception as e:
verbose_logger.debug("Error getting model info: {}".format(e))
model_info = {}
+ if model.startswith(
+ "responses/"
+ ): # handle azure models - `azure/responses/<deployment-name>`
+ model = model.split("/")[1]
+ mode = "responses"
+ model_info["mode"] = mode
if model_info.get("mode") == "responses":
from litellm.completion_extras import responses_api_bridge
diff --git a/tests/llm_translation/test_azure_openai.py b/tests/llm_translation/test_azure_openai.py
index 039eb434f54..a27d0dd165d 100644
--- a/tests/llm_translation/test_azure_openai.py
+++ b/tests/llm_translation/test_azure_openai.py
@@ -594,6 +594,7 @@ async def test_azure_embedding_max_retries_0(
def test_azure_safety_result():
"""Bubble up safety result from Azure OpenAI"""
from litellm import completion
+
litellm._turn_on_debug()
response = completion(
@@ -602,4 +603,30 @@ def test_azure_safety_result():
)
print(f"response: {response}")
assert response.choices[0].message.content is not None
- assert response.choices[0].provider_specific_fields is not None
\ No newline at end of file
+ assert response.choices[0].provider_specific_fields is not None
+
+
+def test_azure_openai_responses_bridge():
+ from litellm import completion
+ import litellm
+
+ litellm._turn_on_debug()
+
+ with patch.object(litellm, "responses") as mock_responses:
+ try:
+ response = completion(
+ model="azure/responses/test-azure-computer-use-preview",
+ messages=[{"role": "user", "content": "Hello world"}],
+ api_base=os.getenv("AZURE_COMPUTER_USE_API_BASE"),
+ api_version="2025-04-01-preview",
+ api_key=os.getenv("AZURE_COMPUTER_USE_API_KEY"),
+ )
+ except Exception as e:
+ print(e)
+
+ mock_responses.assert_called_once()
+ assert (
+ mock_responses.call_args.kwargs["model"]
+ == "test-azure-computer-use-preview"
+ )
+ assert mock_responses.call_args.kwargs["custom_llm_provider"] == "azure"
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
index ac01e495184..7f97d208460 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
@@ -34,3 +34,33 @@ def test_anthropic_experimental_pass_through_messages_handler():
print(f"Error: {e}")
mock_completion.assert_called_once()
mock_completion.call_args.kwargs["api_key"] == "test-api-key"
+
+
+def test_anthropic_experimental_pass_through_messages_handler_custom_llm_provider():
+ """
+ Test that litellm.completion is called when a custom LLM provider is given
+ """
+ from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
+ anthropic_messages_handler,
+ )
+
+ with patch("litellm.completion", return_value="test-response") as mock_completion:
+ try:
+ anthropic_messages_handler(
+ max_tokens=100,
+ messages=[{"role": "user", "content": "Hello, how are you?"}],
+ model="my-custom-model",
+ custom_llm_provider="my-custom-llm",
+ api_key="test-api-key",
+ )
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # Assert that litellm.completion was called when using a custom LLM provider
+ mock_completion.assert_called_once()
+
+ # Verify that the custom provider was passed through
+ call_kwargs = mock_completion.call_args.kwargs
+ assert call_kwargs["custom_llm_provider"] == "my-custom-llm"
+ assert call_kwargs["model"] == "my-custom-llm/my-custom-model"
+ assert call_kwargs["api_key"] == "test-api-key"
diff --git a/tests/test_litellm/llms/test_volcengine.py b/tests/test_litellm/llms/test_volcengine.py
index cb9bc0f521c..4904124d37e 100644
--- a/tests/test_litellm/llms/test_volcengine.py
+++ b/tests/test_litellm/llms/test_volcengine.py
@@ -1,5 +1,6 @@
import os
import sys
+from unittest.mock import MagicMock, patch
from pydantic import BaseModel
@@ -23,7 +24,9 @@ class TestVolcEngineConfig:
)
assert mapped_params == {
- "thinking": {"type": "disabled"},
+ "extra_body": {
+ "thinking": {"type": "disabled"},
+ }
}
e2e_mapped_params = get_optional_params(
@@ -33,6 +36,48 @@ class TestVolcEngineConfig:
drop_params=False,
)
- assert "thinking" in e2e_mapped_params and e2e_mapped_params["thinking"] == {
+ assert "thinking" in e2e_mapped_params["extra_body"] and e2e_mapped_params[
+ "extra_body"
+ ]["thinking"] == {
"type": "enabled",
}
+
+ def test_e2e_completion(self):
+ from openai import OpenAI
+
+ from litellm import completion
+ from litellm.types.utils import ModelResponse
+
+ client = OpenAI(api_key="test_api_key")
+
+ mock_raw_response = MagicMock()
+ mock_raw_response.headers = {
+ "x-request-id": "123",
+ "openai-organization": "org-123",
+ "x-ratelimit-limit-requests": "100",
+ "x-ratelimit-remaining-requests": "99",
+ }
+ mock_raw_response.parse.return_value = ModelResponse()
+
+ with patch.object(
+ client.chat.completions.with_raw_response, "create", mock_raw_response
+ ) as mock_create:
+ completion(
+ model="volcengine/doubao-seed-1.6",
+ messages=[
+ {
+ "role": "system",
+ "content": "**Tell me your model detail information.**",
+ }
+ ],
+ user="guest",
+ stream=True,
+ thinking={"type": "disabled"},
+ client=client,
+ )
+
+ mock_create.assert_called_once()
+ print(mock_create.call_args.kwargs)
+ assert mock_create.call_args.kwargs["extra_body"] == {
+ "thinking": {"type": "disabled"},
+ }