Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,19 @@ def _should_route_to_responses_api(custom_llm_provider: Optional[str]) -> bool:
return custom_llm_provider in _RESPONSES_API_PROVIDERS


def _deployment_passes_through_anthropic_messages(model_info: object) -> bool:
"""Whether the deployment opted into forwarding /v1/messages untranslated.

The opt-in is ``model_info.supported_endpoints`` containing ``"/v1/messages"``,
declared per deployment in config.yaml and plumbed here as ``kwargs["model_info"]``
by the router.
"""
if not isinstance(model_info, dict):
return False
supported_endpoints = model_info.get("supported_endpoints")
return isinstance(supported_endpoints, (list, tuple)) and "/v1/messages" in supported_endpoints


####### ENVIRONMENT VARIABLES ###################
# Initialize any necessary instances or variables here
base_llm_http_handler = BaseLLMHTTPHandler()
Expand Down Expand Up @@ -456,6 +469,14 @@ def anthropic_messages_handler(
model=model,
provider=litellm.LlmProviders(custom_llm_provider),
)
if anthropic_messages_provider_config is None and _deployment_passes_through_anthropic_messages(
kwargs.get("model_info")
):
from litellm.llms.openai_like.messages.transformation import (
OpenAILikeAnthropicMessagesConfig,
)

anthropic_messages_provider_config = OpenAILikeAnthropicMessagesConfig()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if anthropic_messages_provider_config is None:
# Route to Responses API for OpenAI / Azure, chat/completions for everything else.
_shared_kwargs = dict(
Expand Down
Empty file.
75 changes: 75 additions & 0 deletions litellm/llms/openai_like/messages/transformation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from typing import Any, Optional

from litellm.llms.anthropic.experimental_pass_through.messages.transformation import (
AnthropicMessagesConfig,
)
from litellm.types.router import GenericLiteLLMParams

DEFAULT_ANTHROPIC_API_VERSION = "2023-06-01"


class OpenAILikeAnthropicMessagesConfig(AnthropicMessagesConfig):
"""
Forwards Anthropic /v1/messages requests to an OpenAI-compatible server that
also natively exposes the Anthropic Messages API, with no translation.

Opted into per deployment via ``model_info.supported_endpoints`` containing
``"/v1/messages"``. The inbound Anthropic payload (system, cache_control,
thinking, tools, ...) is forwarded essentially unchanged to
``{api_base}/v1/messages``, so Anthropic-only features that the
Anthropic->OpenAI translation would otherwise drop are preserved. Response
parsing and streaming are inherited from the native Anthropic config.
"""

def validate_anthropic_messages_environment(
self,
headers: dict[str, str],
model: str,
messages: list[Any],
optional_params: dict,
litellm_params: dict,
api_key: Optional[str] = None,
api_base: Optional[str] = None,
) -> tuple[dict[str, str], Optional[str]]:
present = {key.lower() for key in headers}
needs_auth = bool(api_key) and "authorization" not in present and "x-api-key" not in present
defaults: dict[str, str] = {
**({"authorization": f"Bearer {api_key}"} if needs_auth else {}),
**({"anthropic-version": DEFAULT_ANTHROPIC_API_VERSION} if "anthropic-version" not in present else {}),
**({"content-type": "application/json"} if "content-type" not in present else {}),
}
return {**headers, **defaults}, api_base
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

def get_complete_url(
self,
api_base: Optional[str],
api_key: Optional[str],
model: str,
optional_params: dict,
litellm_params: dict,
stream: Optional[bool] = None,
) -> str:
if not api_base:
raise ValueError("api_base is required to forward Anthropic /v1/messages to a native endpoint")
base = api_base.rstrip("/")
if base.endswith("/v1/messages"):
return base
if base.endswith("/v1"):
base = base[: -len("/v1")]
return f"{base}/v1/messages"

def transform_anthropic_messages_request(
self,
model: str,
messages: list[dict],
anthropic_messages_optional_request_params: dict,
litellm_params: GenericLiteLLMParams,
headers: dict,
) -> dict:
if anthropic_messages_optional_request_params.get("max_tokens") is None:
raise ValueError("max_tokens is required for the Anthropic /v1/messages API")
return {
"model": model,
"messages": messages,
**anthropic_messages_optional_request_params,
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -715,3 +715,109 @@ def fake_handler(*args, **kwargs):
assert spy.call_count == 1
assert captured["presanitized"] is True
assert [b["type"] for b in captured["messages"][0]["content"]] == ["tool_use"]


def _gate_stubs(monkeypatch):
"""Patch the gate's downstream dispatch targets so config selection can be
observed without making a network call.

Returns ``(captured, translation_calls)`` where ``captured["config"]`` is the
provider config handed to the native passthrough path and ``translation_calls``
counts hits on the Anthropic->OpenAI translation handlers.
"""
from litellm.llms.anthropic.experimental_pass_through.messages import handler

captured = {}
translation_calls = {"count": 0}

def fake_native(**kwargs):
captured["config"] = kwargs.get("anthropic_messages_provider_config")
return "native-passthrough"

def fake_translation(**kwargs):
translation_calls["count"] += 1
return "translated"

monkeypatch.setattr(handler.base_llm_http_handler, "anthropic_messages_handler", fake_native)
monkeypatch.setattr(
handler.LiteLLMMessagesToResponsesAPIHandler,
"anthropic_messages_handler",
staticmethod(fake_translation),
)
monkeypatch.setattr(
handler.LiteLLMMessagesToCompletionTransformationHandler,
"anthropic_messages_handler",
staticmethod(fake_translation),
)
return captured, translation_calls


def test_gate_passthrough_when_supported_endpoints_opts_in(monkeypatch):
"""provider=openai + model_info.supported_endpoints containing /v1/messages
must route to the native passthrough config, NOT the translation handlers."""
from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
anthropic_messages_handler,
)
from litellm.llms.openai_like.messages.transformation import (
OpenAILikeAnthropicMessagesConfig,
)

captured, translation_calls = _gate_stubs(monkeypatch)

result = anthropic_messages_handler(
max_tokens=100,
messages=[{"role": "user", "content": "Hello"}],
model="openai/some-model",
api_key="sk-test",
api_base="https://host/v1",
model_info={"supported_endpoints": ["/v1/chat/completions", "/v1/messages"]},
)

assert result == "native-passthrough"
assert isinstance(captured["config"], OpenAILikeAnthropicMessagesConfig)
assert translation_calls["count"] == 0


def test_gate_translates_when_supported_endpoints_absent(monkeypatch):
"""Default behavior is unchanged: without the /v1/messages opt-in, an openai
deployment is translated (Responses API), never passed through natively."""
from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
anthropic_messages_handler,
)

captured, translation_calls = _gate_stubs(monkeypatch)

result = anthropic_messages_handler(
max_tokens=100,
messages=[{"role": "user", "content": "Hello"}],
model="openai/some-model",
api_key="sk-test",
api_base="https://host/v1",
)

assert result == "translated"
assert translation_calls["count"] == 1
assert "config" not in captured


def test_gate_passthrough_skipped_when_only_chat_completions_supported(monkeypatch):
"""A deployment that lists only /v1/chat/completions is still translated;
the opt-in is specifically the /v1/messages entry."""
from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
anthropic_messages_handler,
)

captured, translation_calls = _gate_stubs(monkeypatch)

result = anthropic_messages_handler(
max_tokens=100,
messages=[{"role": "user", "content": "Hello"}],
model="openai/some-model",
api_key="sk-test",
api_base="https://host/v1",
model_info={"supported_endpoints": ["/v1/chat/completions"]},
)

assert result == "translated"
assert translation_calls["count"] == 1
assert "config" not in captured
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import pytest

from litellm.llms.openai_like.messages.transformation import (
OpenAILikeAnthropicMessagesConfig,
)
from litellm.types.router import GenericLiteLLMParams


@pytest.fixture
def config() -> OpenAILikeAnthropicMessagesConfig:
return OpenAILikeAnthropicMessagesConfig()


@pytest.mark.parametrize(
"api_base, expected",
[
("https://host/v1", "https://host/v1/messages"),
("https://host/v1/", "https://host/v1/messages"),
("https://host", "https://host/v1/messages"),
("https://host/v1/messages", "https://host/v1/messages"),
("https://api.deepseek.com/anthropic", "https://api.deepseek.com/anthropic/v1/messages"),
("https://api.deepseek.com/anthropic/v1", "https://api.deepseek.com/anthropic/v1/messages"),
],
)
def test_get_complete_url_handles_api_base_variants(config, api_base, expected):
url = config.get_complete_url(
api_base=api_base,
api_key="sk-test",
model="some-model",
optional_params={},
litellm_params={},
)
assert url == expected


def test_get_complete_url_requires_api_base(config):
with pytest.raises(ValueError, match="api_base is required"):
config.get_complete_url(
api_base=None,
api_key="sk-test",
model="some-model",
optional_params={},
litellm_params={},
)


def test_request_stays_in_anthropic_shape(config):
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Summarize this",
"cache_control": {"type": "ephemeral"},
}
],
}
]
optional_params = {
"max_tokens": 256,
"system": "You are a careful assistant",
"thinking": {"type": "enabled", "budget_tokens": 1024},
"temperature": 0.3,
"tools": [{"name": "lookup", "input_schema": {"type": "object"}}],
"stream": False,
}

payload = config.transform_anthropic_messages_request(
model="some-model",
messages=messages,
anthropic_messages_optional_request_params=optional_params,
litellm_params=GenericLiteLLMParams(),
headers={},
)

assert payload["model"] == "some-model"
assert payload["messages"] == messages
assert payload["messages"][0]["content"][0]["cache_control"] == {"type": "ephemeral"}
assert payload["system"] == "You are a careful assistant"
assert payload["thinking"] == {"type": "enabled", "budget_tokens": 1024}
assert payload["max_tokens"] == 256
assert payload["tools"] == optional_params["tools"]

openai_only_keys = {
"max_completion_tokens",
"stop",
"n",
"logprobs",
"response_format",
"frequency_penalty",
}
assert openai_only_keys.isdisjoint(payload.keys())


def test_request_requires_max_tokens(config):
with pytest.raises(ValueError, match="max_tokens is required"):
config.transform_anthropic_messages_request(
model="some-model",
messages=[{"role": "user", "content": "hi"}],
anthropic_messages_optional_request_params={"system": "s"},
litellm_params=GenericLiteLLMParams(),
headers={},
)


def test_validate_environment_sets_bearer_and_anthropic_defaults(config):
headers, api_base = config.validate_anthropic_messages_environment(
headers={},
model="some-model",
messages=[],
optional_params={},
litellm_params={},
api_key="sk-test",
api_base="https://host/v1",
)
assert headers["authorization"] == "Bearer sk-test"
assert headers["anthropic-version"] == "2023-06-01"
assert headers["content-type"] == "application/json"
assert api_base == "https://host/v1"


def test_validate_environment_does_not_overwrite_caller_headers(config):
headers, _ = config.validate_anthropic_messages_environment(
headers={
"authorization": "Bearer caller-token",
"anthropic-version": "2024-10-22",
"content-type": "application/json",
},
model="some-model",
messages=[],
optional_params={},
litellm_params={},
api_key="sk-test",
api_base="https://host/v1",
)
assert headers["authorization"] == "Bearer caller-token"
assert headers["anthropic-version"] == "2024-10-22"


def test_validate_environment_preserves_standard_cased_caller_headers(config):
headers, _ = config.validate_anthropic_messages_environment(
headers={
"Authorization": "Bearer caller-token",
"Anthropic-Version": "2024-10-22",
"Content-Type": "application/json",
},
model="some-model",
messages=[],
optional_params={},
litellm_params={},
api_key="sk-test",
api_base="https://host/v1",
)
lowercased = {key.lower() for key in headers}
assert len(lowercased) == len(headers)
assert headers["Authorization"] == "Bearer caller-token"
assert headers["Anthropic-Version"] == "2024-10-22"
assert headers["Content-Type"] == "application/json"


def test_validate_environment_honors_x_api_key_when_present(config):
headers, _ = config.validate_anthropic_messages_environment(
headers={"X-Api-Key": "caller-key"},
model="some-model",
messages=[],
optional_params={},
litellm_params={},
api_key="sk-test",
api_base="https://host/v1",
)
assert "authorization" not in {key.lower() for key in headers}
assert headers["X-Api-Key"] == "caller-key"
Loading