mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-29 01:03:17 +00:00
* refactor(bedrock): parameterise the invoke messages request transform for mantle reuse * fix(bedrock_mantle): split the mantle messages adapter into bedrock/mantle and bedrock_mantle configs on the invoke transform * test(bedrock_mantle): assert python's url, region, auth, shaping and usage behaviour on both mantle routes * docs(bedrock_mantle): note the shared invoke transform and the bedrock/mantle deprecation plan * test(bedrock_mantle): satisfy clippy on the wire body key order check * fix(bedrock_mantle): resolve the api key and model as python does on both mantle routes bedrock/mantle/ now reads an explicit empty api_key as given, so it signs with SigV4 instead of reading AWS_BEARER_TOKEN_BEDROCK. bedrock_mantle/ splits a region prefix only for python's BEDROCK_REGIONS list and logs the model without it. Both routes run the invoke transform on the model id python sends, so its rejection texts name that model. * fix(bedrock_mantle): project the bedrock params and capabilities python reads on both mantle routes bedrock_mantle/ now gets the guardrailConfig, request metadata and bedrock-keyed model capabilities that the inherited invoke transform reads in python, and both mantle routes get aws_bedrock_project_id so the anthropic-workspace-id header is sent. Capabilities are looked up for the model id python hands the invoke transform. * fix(bedrock_mantle): raise python's errors and shape tools on the mantle routes in the host The host now replays python's provider resolution, url and signing for a mantle call rust refused before sending it, so an invalid region and an upper-case public host raise python's BadRequestError or ValueError. A bedrock_mantle/ credential failure raises the Mantle ValueError, the invoke web_search rejection stays raw with llm_provider bedrock, caller tools are shaped in place, and the connect-failure text uses the mantle url. * feat(messages): serve bedrock mantle messages on rust only Both Mantle Messages configs, bedrock_mantle/<claude> and bedrock/mantle/<model>, now resolve to Target.BEDROCK_MANTLE, which the catalog makes RUST_REQUIRED for the bedrock and bedrock_mantle providers. Non-Claude bedrock_mantle models keep their chat or responses bridge on Python, and the Rust provider match only gives bedrock_mantle a Messages config for Claude models, as Python does. * fix(bedrock_mantle): resolve invoke helper capabilities under bedrock on the mantle routes Python's Mantle configs run the shared Anthropic transform on capabilities resolved under the route's provider and the Bedrock Invoke helpers (adaptive thinking, effort support) under bedrock, both for the model id the route sends. Rust now carries the Invoke helpers' flags in BedrockCapabilities, and the Python host and the router probe the keys mantle_capability_lookup names on bedrock_mantle/ and bedrock/mantle/. Every other route keeps its lookup unchanged. * style(rust_bridge): keep the typing noqa on the cast import line * test(bedrock_mantle): pin the python reference and send the mantle wire tests through rust Mantle Messages is served by Rust only now, so the unit wire tests call the Python handler directly as the invoke tests do, and the same requests run through the native route against the recording server and must match what Python sends and answers. * test(rust_bridge): cover the mantle error replay when python would not sign or refuse the call * refactor(bedrock_mantle): model mantle betas and usage as typed json instead of python truthiness Betas are read as an optional list of strings, so an absent or empty list sends no header and anything else is a transform bug. Usage is zero filled only when it is an object. * refactor(bedrock_mantle): rename first_truthy to first_non_empty * fix(rust_bridge): raise mantle region and credential failures natively instead of replaying python Rust now reports an invalid Mantle region as a typed error naming where Python refuses it. A region bedrock_mantle/ rejects while resolving the provider raises get_llm_provider's BadRequestError with an empty llm_provider, and a region refused later (bedrock/mantle/, or an upper-case Mantle host on SigV4) raises the bare ValueError. A bedrock_mantle/ credential failure raises litellm's own Mantle auth ValueError, keeping AwsAuthError for web identity failures. The host no longer re-runs Python's provider resolution, URL building or signing for these errors, so no STS call happens on the error path. * fix(bedrock_mantle): escape control characters in the invalid region message * fix(bedrock_mantle): refuse a reply whose usage is not an object instead of billing zero tokens A Mantle reply whose usage is present but is a list, string or number now raises litellm's APIError 500 rather than zero-filling the usage. Absent or null usage still bills zero tokens. * fix(bedrock_mantle): raise the botocore class for STS credential failures the Mantle signer lets through Rust now names why an STS call failed (rejected with a code, invalid web identity token, or unreachable) and the host raises the same class Python's credential code lets through on bedrock_mantle/: botocore ClientError, AwsAuthError 401 or EndpointConnectionError. Only the four failures the Mantle signer wraps keep its ValueError. Nothing is replayed through botocore and STS is not called again on the error path. * fix(rust_bridge): name the origin Rust could not connect to instead of rebuilding the bedrock URL in Python A connect failure now carries the scheme://host:port the client tried, and the host reads it for both bedrock routes rather than asking the Python config's get_complete_url for the URL Rust already sent to. * fix(bedrock_mantle): log the tools Rust shapes instead of reshaping the caller's tools in Python The Mantle configs now log their requested params with the tools shaped by Rust's invoke helpers, and Rust tells the host when a call is a Bedrock invoke call whose caller tools Python still shapes in place. The host no longer re-detects the Mantle route or its region prefix: the model id a Mantle rejection names comes from Rust too. * fix(bedrock_mantle): log and raise the model id Rust names for a Mantle call refused before sending A bedrock/mantle/ call refused before it was sent logged the model and raised it with its mantle/ prefix, where Python's handler names the model id. The host now takes the model Rust attaches to the failure for the logger and the raised error, with no route detection on the Python side. * fix(bedrock_mantle): zero-fill usage on a Mantle reply that is not a message A 200 reply that does not parse as a message, such as an error envelope, skipped the Mantle usage normalisation, so it billed no usage where Python bills zero input and output tokens. Configs now get a hook for such unchecked replies and both Mantle routes zero-fill the usage there, through a typed usage struct shared with the message path. A usage object with mistyped token counts is now refused as unbillable, like a non-object usage. * fix(bedrock_mantle): hand the agentic hooks the requested stream flag on Mantle routes The agentic loop hook read the call's params back from the wire body, which on the Mantle routes leaves out stream unless it is true. Python's hooks see the params from before its Mantle transform, stream false included. The hook now restores the requested stream flag on the two Mantle routes. * fix(bedrock_mantle): warn when a Mantle route drops a disabled thinking Both Mantle routes dropped thinking type disabled on an always-thinking model without the warning Python logs about the thinking tokens still being billed as output tokens. The shared Anthropic thinking translation now logs it when the route asks, and only the two Mantle configs ask, so other providers keep their behaviour. * fix(bedrock_mantle): build the Mantle URL with the url crate and stop copying Python on odd values Both Mantle routes now parse the base with the url crate, put the Messages route on the path and keep the caller's query string after it, where Python's string join could land the route inside the query. Odd inputs follow plain Rust rules instead of Python's quirks. A blank api_base or api_key counts as unset, an upper-case public Mantle host is sent and signed lowercased, and only a boolean true stream flag streams, so a stream string no longer waits on an SSE reply the request never asked for. A base that is not a URL is refused before sending. * test(bedrock_mantle): check the Rust Mantle route against captured Python output and drop dead Python Messages code The Rust Mantle tests no longer run Python's Messages handler beside Rust. The wire requests, signing scopes and usage Python's Mantle configs produced are captured once in a JSON fixture, and error tests check the class and status only. The Python unit tests that drove Python's Mantle Messages handler end to end are gone, keeping the URL, chat and request transform tests. Python's Mantle Messages configs lose the methods only that handler called: the environment validation, the response transform and the stream iterator, and the bedrock_mantle Messages config no longer mixes in the Mantle signer. The request transform stays because count_tokens reads its options through it. * fix(bedrock_mantle): map a Mantle route credential failure from Rust's kind instead of signing again in Python A bedrock/mantle/ call whose credentials Rust could not acquire made the host run Python's sign_request again to find the exception, which could reach STS on the error path. Rust now names the failure unavailable on both Mantle routes and the host raises botocore's NoCredentialsError, or the STS class Rust names, from a fixed list. The Bedrock invoke route keeps its replay. The GetLLMProvider wording copied from Python for a region refused while resolving bedrock_mantle/ is gone with its marker. The refusal stays a 400 BadRequestError. * refactor(bedrock_mantle): read Mantle capabilities from the Rust catalog and type the project id A Mantle call asked Python's capability probes up to three times per request. The host now reads them from the Rust catalog of the live model map through messages_route_capabilities, as the router already does, so a Mantle call makes no capability host call. aws_bedrock_project_id is a typed litellm_params field every host projects, replacing the Mantle-only passthrough projection. * refactor(bedrock_mantle): read the Mantle betas and wire body through typed structs The betas now come off the request's own anthropic_beta field instead of a serialization of the whole request, and the Mantle wire body is a typed struct that drops the version and betas, puts model and stream last and keeps stream only when it is a boolean true. * docs(bedrock_mantle): document the Mantle Messages configs and say Rust instead of native in the new tests Both Mantle transformation files get a file doc, the two config structs and the model id helper get docs, and mantle_capabilities is private now that only messages_route_capabilities composes it. The tests this port added name the Rust host's error rust_error rather than native. The Mantle wire body struct also stops tripping clippy on its dropped fields. * fix(bedrock_mantle): log the route model for a bedrock/mantle call refused before sending Python's handler logs the route model (mantle/<id>) before the Mantle config's transform refuses the call; only the raised error carries the bare model id. * fix(bedrock_mantle): name no provider and the requested model for a region refused resolving bedrock_mantle Python's get_llm_provider refuses an invalid bedrock_mantle region before any provider resolves, so its BadRequestError has llm_provider "" and the request's model. The Rust host now attaches that provider and model for the refusal. * fix(bedrock_mantle): raise botocore ProfileNotFound for an AWS profile no profile file defines Rust names a missing AWS profile as its own credential failure kind with the profile name, and the host raises botocore's ProfileNotFound for it from its fixed class list instead of NoCredentialsError. bedrock_mantle/ keeps wrapping it in the Mantle auth ValueError, as Python does. * docs(rust_bridge): mark the bedrock invoke signing replay for removal * fix(rust_bridge): build ProfileNotFound only when Rust names the profile * test(health_check): answer the Mantle Claude probes from a local server now that Rust sends them * fix(bedrock_mantle): read a region path segment from the model on the bedrock/mantle route * style(bedrock_mantle): format the region_from_model import * test(rust_bridge): cover a connect failure with no known base on the messages route A provider outside anthropic, azure_ai and bedrock with no api_base has no base to reword a connect failure against, so the host keeps Rust's text. * fix(rust_bridge): name the origin Rust dialed in a bedrock connect failure A Bedrock or Mantle connect failure reworded the caller's api_base, but Rust can send elsewhere: Mantle rebuilds a public host on https in the resolved region, and a blank api_base counts as unset. Prefer the connect origin Rust reports whenever it set one. * fix(bedrock_mantle): log and raise the model Python names on Mantle refusals A refused Mantle call logged the request model with only the provider prefix removed, so a bedrock_mantle/ region prefix stayed in the failure log (us-west-2/anthropic.claude-x), where Python's handler logs the model get_llm_provider resolves. Rust now names that model on the error as messages_logged_model. The unbillable-usage APIError names the model id Rust sent (messages_provider_model), the one the failure log carries. * test(rust_bridge): cover the refused-reply mapping to APIError 500 Rust marks a Mantle reply whose usage litellm cannot bill with messages_refused_reply, and the host raises it as litellm.APIError 500. Cover both halves: errors.rs sets the marker only for an UnbillableUsage response, and the host maps it naming the model Rust sent. * refactor(bedrock_mantle): have Rust name bedrock on a Mantle invoke bad request The host decided in Python that a bedrock_mantle refusal the Bedrock invoke transform raises as BadRequestError names llm_provider=bedrock. Rust now sets messages_provider=bedrock on that error for both Mantle routes, and the host only reads it. The raised error is unchanged.
1132 lines
45 KiB
Python
1132 lines
45 KiB
Python
import inspect
|
|
from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
|
|
from typing import Final, cast # noqa: TID251 # narrows legacy callable signatures for inspect
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
import litellm
|
|
from litellm.caching.caching import Cache
|
|
from litellm.constants import COMPLETION_HTTP_FALLBACK_SECONDS
|
|
from litellm.exceptions import UnsupportedParamsError
|
|
from litellm.integrations.custom_logger import CustomLogger
|
|
from litellm.integrations.websearch_interception.handler import WebSearchInterceptionLogger
|
|
from litellm.llms.anthropic.messages.native import handler as python_messages
|
|
from litellm.llms.anthropic.messages.native import interceptors as messages_interceptors
|
|
from litellm.llms.anthropic.messages.native.interceptors import MessagesInterceptor
|
|
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
|
|
from litellm.messages import dispatch
|
|
from litellm.messages.dispatch import (
|
|
_ADISPATCH, # pyright: ignore[reportPrivateUsage] # tests configured dispatch
|
|
_DISPATCH, # pyright: ignore[reportPrivateUsage] # tests configured dispatch
|
|
)
|
|
from litellm.proxy import proxy_server
|
|
from litellm.rust_bridge import catalog
|
|
from litellm.rust_bridge.bindings import NativeBinding
|
|
from litellm.rust_bridge.catalog import MESSAGES_PYTHON_FEATURES, RULES, Feature, Route, RouteRule, Rules, Target
|
|
from litellm.rust_bridge.configuration import Rollout
|
|
from litellm.rust_bridge.messages.entrypoints import NATIVE_AMESSAGES, NATIVE_MESSAGES, NativeAmessages, NativeMessages
|
|
from litellm.rust_bridge.public_call import NativeCall
|
|
from litellm.types.llms.anthropic import ANTHROPIC_ADVISOR_TOOL_TYPE
|
|
from litellm.types.llms.anthropic_messages.anthropic_response import AnthropicMessagesResponse
|
|
from tests.test_litellm_rust.support.isolation import rebound
|
|
from tests.test_litellm_rust.support.routing import routed
|
|
|
|
MESSAGES: Final = [{"role": "user", "content": "hi"}]
|
|
PYTHON_RULES: Final[Rules] = ()
|
|
RUST_RULES: Final[Rules] = (RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),)
|
|
|
|
|
|
def messages_binding(native: NativeMessages | None) -> NativeBinding[NativeMessages]:
|
|
binding: Final[NativeBinding[NativeMessages]] = NativeBinding("anthropic_messages_handler", validate=lambda _: None)
|
|
binding.override(native)
|
|
return binding
|
|
|
|
|
|
def amessages_binding(native: NativeAmessages | None) -> NativeBinding[NativeAmessages]:
|
|
binding: Final[NativeBinding[NativeAmessages]] = NativeBinding("anthropic_messages", validate=lambda _: None)
|
|
binding.override(native)
|
|
return binding
|
|
|
|
|
|
def response(model: str = "claude-sonnet-4-5") -> AnthropicMessagesResponse:
|
|
return AnthropicMessagesResponse(id="msg_test", type="message", role="assistant", model=model, content=[])
|
|
|
|
|
|
def test_public_signature_is_the_legacy_signature() -> None:
|
|
public_messages: Final = cast(Callable[..., object], litellm.anthropic_messages_handler)
|
|
legacy_messages: Final = cast(Callable[..., object], python_messages.anthropic_messages_handler)
|
|
public_amessages: Final = cast(Callable[..., object], litellm.anthropic_messages)
|
|
legacy_amessages: Final = cast(Callable[..., object], python_messages.anthropic_messages)
|
|
assert inspect.signature(public_messages) == inspect.signature(legacy_messages)
|
|
assert inspect.signature(public_amessages) == inspect.signature(legacy_amessages)
|
|
|
|
|
|
def test_python_route_forwards_original_call_shape() -> None:
|
|
metadata: Final = {"user_id": "u"}
|
|
args: Final[tuple[object, ...]] = (16, MESSAGES, "claude-sonnet-4-5")
|
|
kwargs: Final[Mapping[str, object]] = {"temperature": 0.1, "litellm_metadata": metadata}
|
|
captured: Final[list[tuple[tuple[object, ...], Mapping[str, object]]]] = []
|
|
expected: Final = response()
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: records call shape
|
|
captured.append((call_args, call_kwargs))
|
|
return expected
|
|
|
|
def native(
|
|
request: NativeCall,
|
|
) -> AnthropicMessagesResponse:
|
|
pytest.fail("Python-only dispatch must not call native")
|
|
|
|
result: Final = _DISPATCH.run(
|
|
args,
|
|
kwargs,
|
|
python=python,
|
|
binding=messages_binding(native),
|
|
native=lambda hook, request, call_args, call_kwargs: hook(request),
|
|
rules=PYTHON_RULES,
|
|
)
|
|
assert result is expected
|
|
call_args, call_kwargs = captured[0]
|
|
assert call_args == args
|
|
assert call_args[1] is MESSAGES
|
|
assert call_kwargs == kwargs
|
|
assert call_kwargs["litellm_metadata"] is metadata
|
|
assert kwargs == {"temperature": 0.1, "litellm_metadata": metadata}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_python_route_forwards_original_call_shape() -> None:
|
|
metadata: Final = {"user_id": "u"}
|
|
args: Final[tuple[object, ...]] = (16, MESSAGES, "claude-sonnet-4-5")
|
|
kwargs: Final[Mapping[str, object]] = {"temperature": 0.1, "litellm_metadata": metadata}
|
|
captured: Final[list[tuple[tuple[object, ...], Mapping[str, object]]]] = []
|
|
expected: Final = response()
|
|
|
|
async def python(
|
|
*call_args: object,
|
|
**call_kwargs: object, # kwargs-ok: records call shape
|
|
) -> AnthropicMessagesResponse:
|
|
captured.append((call_args, call_kwargs))
|
|
return expected
|
|
|
|
async def native(
|
|
request: NativeCall,
|
|
) -> AnthropicMessagesResponse:
|
|
pytest.fail("Python-only dispatch must not call native")
|
|
|
|
result: Final = await _ADISPATCH.arun(
|
|
args,
|
|
kwargs,
|
|
python=python,
|
|
binding=amessages_binding(native),
|
|
native=lambda hook, request, call_args, call_kwargs: hook(request),
|
|
rules=PYTHON_RULES,
|
|
)
|
|
assert result is expected
|
|
call_args, call_kwargs = captured[0]
|
|
assert call_args == args
|
|
assert call_args[1] is MESSAGES
|
|
assert call_kwargs == kwargs
|
|
assert call_kwargs["litellm_metadata"] is metadata
|
|
assert kwargs == {"temperature": 0.1, "litellm_metadata": metadata}
|
|
|
|
|
|
def test_native_receives_normalized_request_and_original_call_shape() -> None:
|
|
metadata: Final = {"user_id": "u"}
|
|
args: Final[tuple[object, ...]] = (16, MESSAGES, "anthropic/claude-sonnet-4-5")
|
|
kwargs: Final[Mapping[str, object]] = {
|
|
"stream": True,
|
|
"api_key": "sk-test",
|
|
"api_base": "https://example.invalid",
|
|
"custom_llm_provider": "anthropic",
|
|
"litellm_metadata": metadata,
|
|
}
|
|
captured: Final[list[tuple[NativeCall, tuple[object, ...], Mapping[str, object]]]] = []
|
|
expected: Final = response("anthropic/claude-sonnet-4-5")
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("Required Rust dispatch must not call Python")
|
|
|
|
def native(
|
|
request: NativeCall,
|
|
) -> AnthropicMessagesResponse:
|
|
args: Final = request.args
|
|
kwargs: Final = request.kwargs
|
|
captured.append((request, args, kwargs))
|
|
return expected
|
|
|
|
result: Final = _DISPATCH.run(
|
|
args,
|
|
kwargs,
|
|
python=python,
|
|
binding=messages_binding(native),
|
|
native=lambda hook, request, call_args, call_kwargs: hook(request),
|
|
rules=RUST_RULES,
|
|
)
|
|
assert result is expected
|
|
request, call_args, call_kwargs = captured[0]
|
|
assert request.resolved["model"] == "anthropic/claude-sonnet-4-5"
|
|
assert request.resolved["messages"] is MESSAGES
|
|
assert request.resolved["max_tokens"] == 16
|
|
assert request.resolved["stream"] is True
|
|
assert request.resolved["api_key"] == "sk-test"
|
|
assert request.resolved["api_base"] == "https://example.invalid"
|
|
assert request.resolved["custom_llm_provider"] == "anthropic"
|
|
assert request.kwargs == kwargs
|
|
assert request.kwargs["litellm_metadata"] is metadata
|
|
assert call_args == args
|
|
assert call_args[1] is MESSAGES
|
|
assert call_kwargs == kwargs
|
|
assert call_kwargs["litellm_metadata"] is metadata
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("kwargs", "expected_timeout"),
|
|
(
|
|
pytest.param({"stream": True, "timeout": 30.0, "stream_timeout": 0.5}, 0.5, id="stream-timeout-bounds-stream"),
|
|
pytest.param(
|
|
{"stream": False, "timeout": 30.0, "stream_timeout": 0.5}, 30.0, id="stream-timeout-ignored-unary"
|
|
),
|
|
pytest.param({"request_timeout": 5}, 5.0, id="request-timeout"),
|
|
pytest.param({"timeout": 30.0, "request_timeout": 5}, 30.0, id="timeout-before-request-timeout"),
|
|
pytest.param(
|
|
{"stream": True, "request_timeout": 5, "stream_timeout": 0.5}, 0.5, id="stream-timeout-over-request"
|
|
),
|
|
pytest.param({"timeout": httpx.Timeout(60.0, connect=2.0)}, 60.0, id="httpx-timeout-read"),
|
|
pytest.param(
|
|
{"timeout": httpx.Timeout(None, connect=2.0)}, COMPLETION_HTTP_FALLBACK_SECONDS, id="httpx-timeout-no-read"
|
|
),
|
|
),
|
|
)
|
|
def test_native_timeout_resolves_like_python(kwargs: Mapping[str, object], expected_timeout: float) -> None:
|
|
captured: Final[list[NativeCall]] = []
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("Required Rust dispatch must not call Python")
|
|
|
|
def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
captured.append(request)
|
|
return response()
|
|
|
|
_ = _DISPATCH.run(
|
|
(16, MESSAGES, "anthropic/claude-sonnet-4-5"),
|
|
kwargs,
|
|
python=python,
|
|
binding=messages_binding(native),
|
|
native=lambda hook, request, call_args, call_kwargs: hook(request),
|
|
rules=RUST_RULES,
|
|
)
|
|
assert captured[0].resolved["timeout"] == expected_timeout
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("model", "kwargs", "passes_through"),
|
|
(
|
|
("vertex_ai/claude-sonnet-4-5@20250929", {}, True),
|
|
("claude-sonnet-4-5@20250929", {"custom_llm_provider": "vertex_ai"}, True),
|
|
("deepseek/deepseek-v4-flash", {}, True),
|
|
("azure_ai/claude-sonnet-4-5", {"model_info": {"supported_endpoints": ["/v1/messages"]}}, True),
|
|
("openai/gpt-5", {"model_info": {"supported_endpoints": ["/v1/messages"]}}, False),
|
|
("azure_ai/Phi-4", {"model_info": {"supported_endpoints": ["/v1/messages"]}}, False),
|
|
("vertex_ai/gemini-2.5-pro", {}, False),
|
|
("gemini-2.5-pro", {"custom_llm_provider": "vertex_ai"}, False),
|
|
("openai/gpt-5", {}, False),
|
|
("groq/llama-3.3-70b-versatile", {}, False),
|
|
("unknown-provider/unknown-model", {}, False),
|
|
),
|
|
)
|
|
def test_only_requests_a_provider_messages_config_serves_reach_a_messages_target_rule(
|
|
model: str, kwargs: Mapping[str, object], passes_through: bool
|
|
) -> None:
|
|
python_result: Final = response(model)
|
|
native_result: Final = response(model)
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: fallback
|
|
return python_result
|
|
|
|
result: Final = _DISPATCH.run(
|
|
(16, MESSAGES, model),
|
|
kwargs,
|
|
python=python,
|
|
binding=messages_binding(lambda request: native_result),
|
|
native=lambda hook, request, call_args, call_kwargs: hook(request),
|
|
rules=(RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED, targets=frozenset({Target.MESSAGES})),),
|
|
)
|
|
assert result is (native_result if passes_through else python_result)
|
|
|
|
|
|
BEDROCK_INVOKE_MODEL: Final = "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("model", "target"),
|
|
(
|
|
pytest.param(BEDROCK_INVOKE_MODEL, Target.BEDROCK_INVOKE, id="invoke"),
|
|
pytest.param(
|
|
"bedrock/invoke/us.anthropic.claude-sonnet-4-5-20250929-v1:0", Target.BEDROCK_INVOKE, id="explicit-invoke"
|
|
),
|
|
pytest.param(
|
|
"bedrock/us-west-2/us.anthropic.claude-sonnet-4-5-20250929-v1:0", Target.BEDROCK_INVOKE, id="regional"
|
|
),
|
|
pytest.param("bedrock/claude_platform/claude-sonnet-4-5", Target.MESSAGES, id="claude-platform"),
|
|
pytest.param("bedrock/mantle/anthropic.claude-sonnet-5", Target.BEDROCK_MANTLE, id="mantle"),
|
|
pytest.param("bedrock_mantle/anthropic.claude-sonnet-5", Target.BEDROCK_MANTLE, id="bedrock-mantle"),
|
|
pytest.param(
|
|
"bedrock_mantle/us-east-1/anthropic.claude-sonnet-5", Target.BEDROCK_MANTLE, id="bedrock-mantle-regional"
|
|
),
|
|
pytest.param("bedrock_mantle/openai.gpt-oss-120b", Target.CHAT_COMPLETIONS, id="bedrock-mantle-non-claude"),
|
|
pytest.param(
|
|
"bedrock/converse/us.anthropic.claude-sonnet-4-5-20250929-v1:0", Target.CHAT_COMPLETIONS, id="converse"
|
|
),
|
|
pytest.param("bedrock/us.meta.llama3-2-11b-instruct-v1:0", Target.CHAT_COMPLETIONS, id="non-claude"),
|
|
),
|
|
)
|
|
def test_only_claude_on_bedrock_invoke_model_reaches_a_bedrock_invoke_target_rule(model: str, target: Target) -> None:
|
|
python_result: Final = response(model)
|
|
native_result: Final = response(model)
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: fallback
|
|
return python_result
|
|
|
|
result: Final = _DISPATCH.run(
|
|
(16, MESSAGES, model),
|
|
{},
|
|
python=python,
|
|
binding=messages_binding(lambda request: native_result),
|
|
native=lambda hook, request, call_args, call_kwargs: hook(request),
|
|
rules=(RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED, targets=frozenset({Target.BEDROCK_INVOKE})),),
|
|
)
|
|
|
|
assert dispatch.messages_target(model, None, None, None) is target
|
|
assert result is (native_result if target is Target.BEDROCK_INVOKE else python_result)
|
|
|
|
|
|
DANGEROUS_TOOL_USE: Final = [{"type": "dangerous_tool_use", "classifier_context": {"permission_mode": "auto"}}]
|
|
CLASSIFIER_SETTINGS: Final = {"safeguards_classifier_model": "gpt-oss-120b"}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("args", "kwargs"),
|
|
(
|
|
((16, MESSAGES, "claude-sonnet-4-5"), {"model": "duplicate"}),
|
|
((), {}),
|
|
),
|
|
)
|
|
def test_binding_errors_delegate_to_python(args: tuple[object, ...], kwargs: Mapping[str, object]) -> None:
|
|
captured: Final[list[tuple[tuple[object, ...], Mapping[str, object]]]] = []
|
|
expected: Final = response()
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse:
|
|
captured.append((call_args, call_kwargs))
|
|
return expected
|
|
|
|
def native(
|
|
request: NativeCall,
|
|
) -> AnthropicMessagesResponse:
|
|
pytest.fail("Binding failures must be delegated to Python")
|
|
|
|
result: Final = _DISPATCH.run(
|
|
args,
|
|
kwargs,
|
|
python=python,
|
|
binding=messages_binding(native),
|
|
native=lambda hook, request, call_args, call_kwargs: hook(request),
|
|
rules=RUST_RULES,
|
|
)
|
|
assert result is expected
|
|
assert captured == [(args, kwargs)]
|
|
|
|
|
|
def test_anthropic_create_routes_through_dispatch() -> None:
|
|
captured: Final[list[NativeCall]] = []
|
|
expected: Final = response()
|
|
|
|
def native(
|
|
request: NativeCall,
|
|
) -> AnthropicMessagesResponse:
|
|
captured.append(request)
|
|
return expected
|
|
|
|
NATIVE_MESSAGES.override(native)
|
|
public_create: Final = cast(Callable[..., AnthropicMessagesResponse], litellm.anthropic.create)
|
|
try:
|
|
result: Final = public_create(max_tokens=16, messages=MESSAGES, model="claude-sonnet-4-5")
|
|
finally:
|
|
NATIVE_MESSAGES.reset()
|
|
assert result is expected
|
|
assert [request.resolved["model"] for request in captured] == ["claude-sonnet-4-5"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_anthropic_acreate_routes_through_dispatch() -> None:
|
|
captured: Final[list[NativeCall]] = []
|
|
expected: Final = response()
|
|
|
|
async def native(
|
|
request: NativeCall,
|
|
) -> AnthropicMessagesResponse:
|
|
captured.append(request)
|
|
return expected
|
|
|
|
NATIVE_AMESSAGES.override(native)
|
|
public_acreate: Final = cast(Callable[..., Awaitable[AnthropicMessagesResponse]], litellm.anthropic.acreate)
|
|
try:
|
|
result: Final = await public_acreate(max_tokens=16, messages=MESSAGES, model="claude-sonnet-4-5")
|
|
finally:
|
|
NATIVE_AMESSAGES.reset()
|
|
assert result is expected
|
|
assert [request.resolved["model"] for request in captured] == ["claude-sonnet-4-5"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_truthy_is_async_hands_off_to_the_async_entry_like_true() -> None:
|
|
captured: Final[list[NativeCall]] = []
|
|
expected: Final = response()
|
|
|
|
async def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
captured.append(request)
|
|
return expected
|
|
|
|
def sync_native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
pytest.fail("a truthy is_async must hand off to the async entry, as the Python handler does")
|
|
|
|
NATIVE_AMESSAGES.override(native)
|
|
NATIVE_MESSAGES.override(sync_native)
|
|
public_create: Final = cast(Callable[..., object], litellm.anthropic.create)
|
|
try:
|
|
pending: Final = public_create(max_tokens=16, messages=MESSAGES, model="claude-sonnet-4-5", is_async=1)
|
|
assert inspect.isawaitable(pending)
|
|
assert await pending is expected
|
|
reference: Final = public_create(max_tokens=16, messages=MESSAGES, model="claude-sonnet-4-5", is_async=True)
|
|
assert inspect.isawaitable(reference)
|
|
assert await reference is expected
|
|
finally:
|
|
NATIVE_AMESSAGES.reset()
|
|
NATIVE_MESSAGES.reset()
|
|
assert [dict(request.resolved) for request in captured] == [dict(captured[1].resolved)] * 2
|
|
|
|
|
|
def test_sync_messages_request_projects_public_arguments() -> None:
|
|
rules: Final[Rules] = (RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),)
|
|
expected: Final = AnthropicMessagesResponse(model="claude-test")
|
|
|
|
def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
assert request.resolved["model"] == "claude-test"
|
|
assert request.resolved["messages"] == MESSAGES
|
|
assert request.resolved["max_tokens"] == 10
|
|
assert request.resolved["custom_llm_provider"] == "anthropic"
|
|
return expected
|
|
|
|
binding: Final[NativeBinding[NativeMessages]] = NativeBinding("messages", validate=lambda _: None)
|
|
binding.override(native)
|
|
response: Final = dispatch._DISPATCH.run( # pyright: ignore[reportPrivateUsage] # test an explicit route decision
|
|
(),
|
|
{
|
|
"model": "claude-test",
|
|
"messages": MESSAGES,
|
|
"max_tokens": 10,
|
|
"custom_llm_provider": "anthropic",
|
|
},
|
|
python=lambda *args, **kwargs: pytest.fail("required native route must handle this call"),
|
|
binding=binding,
|
|
native=lambda hook, request, args, kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
|
|
assert response is expected
|
|
|
|
|
|
def test_messages_binding_error_delegates_unchanged_to_python() -> None:
|
|
rules: Final[Rules] = (RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),)
|
|
expected: Final = AnthropicMessagesResponse(model="claude-test")
|
|
|
|
def python(*args: object, **kwargs: object) -> AnthropicMessagesResponse:
|
|
return expected
|
|
|
|
def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
pytest.fail("a call without max_tokens cannot project a request and must stay on Python")
|
|
|
|
binding: Final[NativeBinding[NativeMessages]] = NativeBinding("messages", validate=lambda _: None)
|
|
binding.override(native)
|
|
response: Final = dispatch._DISPATCH.run( # pyright: ignore[reportPrivateUsage] # test an explicit route decision
|
|
(),
|
|
{"model": "claude-test", "messages": MESSAGES, "custom_llm_provider": "anthropic"},
|
|
python=python,
|
|
binding=binding,
|
|
native=lambda hook, request, args, kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
|
|
assert response is expected
|
|
|
|
|
|
class _Rewrite(CustomLogger):
|
|
async def async_pre_request_hook(self, model: str, messages: list, kwargs: dict) -> dict | None: # pyright: ignore[reportMissingTypeArgument] # mirrors the CustomLogger signature
|
|
return kwargs
|
|
|
|
|
|
class _Agentic(CustomLogger):
|
|
async def async_should_run_agentic_loop(self, *args: object, **kwargs: object) -> tuple[bool, dict]: # pyright: ignore[reportIncompatibleMethodOverride, reportMissingTypeArgument] # test double only needs the override
|
|
return False, {}
|
|
|
|
|
|
class _ShortCircuit(WebSearchInterceptionLogger):
|
|
async def try_short_circuit_search(self, *args: object, **kwargs: object) -> dict[str, object] | None: # pyright: ignore[reportIncompatibleMethodOverride] # test double only needs the override
|
|
return None
|
|
|
|
|
|
ADVISOR_TOOL: Final = {"type": ANTHROPIC_ADVISOR_TOOL_TYPE, "name": "advisor", "model": "claude-opus-5-5"}
|
|
STRICT_TOOL: Final = {"name": "a", "input_schema": {"type": "object"}, "strict": True}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"kwargs",
|
|
(
|
|
pytest.param({"shared_session": object()}, id="proxy-shared-session"),
|
|
pytest.param({"stream": True, "timeout": 600.0, "stream_timeout": 600.0}, id="proxy-stream-timeout"),
|
|
pytest.param({"request_timeout": 5}, id="request-timeout"),
|
|
pytest.param({"timeout": httpx.Timeout(60.0, connect=2.0)}, id="httpx-timeout"),
|
|
),
|
|
)
|
|
def test_proxy_request_shape_stays_native(kwargs: Mapping[str, object]) -> None:
|
|
rules: Final[Rules] = (
|
|
RouteRule(
|
|
Route.MESSAGES, Rollout.PYTHON_ONLY, features=frozenset({Feature.CALLER_CLIENT, Feature.TIMEOUT_VARIANTS})
|
|
),
|
|
RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),
|
|
)
|
|
native_result: Final = response()
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("A proxy-shaped request must not fall back to Python")
|
|
|
|
served: Final = _DISPATCH.run(
|
|
(16, MESSAGES, "anthropic/claude-sonnet-4-5"),
|
|
kwargs,
|
|
python=python,
|
|
binding=messages_binding(lambda request: native_result),
|
|
native=lambda hook, request, call_args, native_kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
assert served is native_result
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"block",
|
|
(
|
|
pytest.param({"type": "thinking", "thinking": "x", "signature": "s"}, id="thinking"),
|
|
pytest.param({"type": "redacted_thinking", "data": "x"}, id="redacted-thinking"),
|
|
),
|
|
)
|
|
async def test_replayed_thinking_is_served_natively_under_the_shipped_rules(
|
|
monkeypatch: pytest.MonkeyPatch, block: Mapping[str, object]
|
|
) -> None:
|
|
monkeypatch.setenv("LITELLM_RUST", "1")
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
monkeypatch.setattr(litellm, "cache", None)
|
|
replay: Final = [
|
|
{"role": "user", "content": "hi"},
|
|
{"role": "assistant", "content": [block, {"type": "text", "text": "hello"}]},
|
|
{"role": "user", "content": "again"},
|
|
]
|
|
native_result: Final = response()
|
|
python_result: Final = response()
|
|
|
|
async def python(*call_args: object, **python_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
async def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
return native_result
|
|
|
|
served: Final = await _ADISPATCH.arun(
|
|
(16, replay, "anthropic/claude-sonnet-4-5"),
|
|
{"api_key": "sk-ant-test"},
|
|
python=python,
|
|
binding=amessages_binding(native),
|
|
native=lambda hook, request, call_args, native_kwargs: hook(request),
|
|
rules=RULES,
|
|
)
|
|
|
|
assert served is native_result
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("kwargs", "global_drop_params"),
|
|
(
|
|
pytest.param({"drop_params": True, "tools": [STRICT_TOOL]}, False, id="drop-params-kwarg"),
|
|
pytest.param({"tools": [STRICT_TOOL]}, True, id="drop-params-global"),
|
|
pytest.param({"tools": [STRICT_TOOL]}, False, id="drop-params-unset"),
|
|
),
|
|
)
|
|
async def test_strict_tools_are_served_natively_under_the_shipped_rules(
|
|
monkeypatch: pytest.MonkeyPatch, kwargs: Mapping[str, object], global_drop_params: bool
|
|
) -> None:
|
|
monkeypatch.setenv("LITELLM_RUST", "1")
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
monkeypatch.setattr(litellm, "cache", None)
|
|
monkeypatch.setattr(litellm, "drop_params", global_drop_params)
|
|
native_result: Final = response()
|
|
|
|
async def python(*call_args: object, **python_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
pytest.fail("strict tools stay on the native path")
|
|
|
|
async def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
return native_result
|
|
|
|
served: Final = await _ADISPATCH.arun(
|
|
(16, MESSAGES, "anthropic/claude-sonnet-4-5"),
|
|
kwargs,
|
|
python=python,
|
|
binding=amessages_binding(native),
|
|
native=lambda hook, request, call_args, native_kwargs: hook(request),
|
|
rules=RULES,
|
|
)
|
|
|
|
assert served is native_result
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"kwargs",
|
|
(
|
|
pytest.param({}, id="reads-and-writes"),
|
|
pytest.param({"cache": {"no-store": True}}, id="no-store"),
|
|
pytest.param({"cache": {"ttl": 60, "namespace": "team"}}, id="ttl-and-namespace"),
|
|
pytest.param({"stream": True}, id="stream"),
|
|
),
|
|
)
|
|
async def test_a_configured_response_cache_stays_native(
|
|
monkeypatch: pytest.MonkeyPatch, kwargs: Mapping[str, object]
|
|
) -> None:
|
|
rules: Final[Rules] = (
|
|
RouteRule(Route.MESSAGES, Rollout.PYTHON_ONLY, features=MESSAGES_PYTHON_FEATURES),
|
|
RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),
|
|
)
|
|
native_result: Final = response()
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
monkeypatch.setattr(litellm, "cache", Cache())
|
|
|
|
async def python(*call_args: object, **python_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
pytest.fail("Rust reads and writes the configured response cache")
|
|
|
|
async def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
return native_result
|
|
|
|
served: Final = await _ADISPATCH.arun(
|
|
(16, MESSAGES, "anthropic/claude-sonnet-4-5"),
|
|
kwargs,
|
|
python=python,
|
|
binding=amessages_binding(native),
|
|
native=lambda hook, request, call_args, native_kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
|
|
assert served is native_result
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_modify_params_stays_native(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
rules: Final[Rules] = (
|
|
RouteRule(Route.MESSAGES, Rollout.PYTHON_ONLY, features=catalog.MESSAGES_PYTHON_FEATURES),
|
|
RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),
|
|
)
|
|
native_result: Final = response()
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
monkeypatch.setattr(litellm, "modify_params", True)
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("modify_params must not fall back to Python")
|
|
|
|
async def apython(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
pytest.fail("modify_params must not fall back to Python")
|
|
|
|
async def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
return native_result
|
|
|
|
call_args: Final = (200_000, MESSAGES, "anthropic/claude-sonnet-4-5")
|
|
served: Final = _DISPATCH.run(
|
|
call_args,
|
|
{},
|
|
python=python,
|
|
binding=messages_binding(lambda request: native_result),
|
|
native=lambda hook, request, args, kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
aserved: Final = await _ADISPATCH.arun(
|
|
call_args,
|
|
{},
|
|
python=apython,
|
|
binding=amessages_binding(native),
|
|
native=lambda hook, request, args, kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
|
|
assert (served, aserved) == (native_result, native_result)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"kwargs",
|
|
(
|
|
pytest.param({"mock_response": "hi"}, id="unary"),
|
|
pytest.param({"mock_response": "hi", "stream": True}, id="streamed"),
|
|
),
|
|
)
|
|
async def test_mock_response_is_served_natively(monkeypatch: pytest.MonkeyPatch, kwargs: Mapping[str, object]) -> None:
|
|
rules: Final[Rules] = (
|
|
RouteRule(Route.MESSAGES, Rollout.PYTHON_ONLY, features=frozenset({Feature.MOCK_RESPONSE})),
|
|
RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),
|
|
)
|
|
python_result: Final = response()
|
|
native_result: Final = response()
|
|
|
|
async def python(*call_args: object, **python_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
async def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
return native_result
|
|
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
served_async: Final = await _ADISPATCH.arun(
|
|
(16, MESSAGES, "anthropic/claude-sonnet-4-5"),
|
|
kwargs,
|
|
python=python,
|
|
binding=amessages_binding(native),
|
|
native=lambda hook, request, args, native_kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
served_sync: Final = _DISPATCH.run(
|
|
(16, MESSAGES, "anthropic/claude-sonnet-4-5"),
|
|
kwargs,
|
|
python=lambda *call_args, **python_kwargs: python_result,
|
|
binding=messages_binding(lambda request: native_result),
|
|
native=lambda hook, request, args, native_kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
assert served_async is native_result
|
|
assert served_sync is native_result
|
|
|
|
|
|
class _Claims(MessagesInterceptor):
|
|
def can_handle(self, tools: Sequence[Mapping[str, object]] | None, custom_llm_provider: str | None) -> bool:
|
|
return custom_llm_provider == "anthropic"
|
|
|
|
async def handle(self, **kwargs: object) -> AnthropicMessagesResponse: # pyright: ignore[reportIncompatibleMethodOverride] # kwargs-ok: test double only needs the override
|
|
return response()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_call_a_registered_interceptor_owns_runs_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str]
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
monkeypatch.setattr(messages_interceptors, "_interceptors", [_Claims()])
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("Rust hands the call to the interceptor itself")
|
|
|
|
with rebound(dispatch, "_PYTHON_AMESSAGES", python):
|
|
result: Final = await _public(True, "anthropic/claude-sonnet-4-5", {"tools": [ADVISOR_TOOL]})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async"]
|
|
|
|
|
|
def test_a_federated_request_stays_native(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"):
|
|
monkeypatch.delenv(name, raising=False)
|
|
rules: Final[Rules] = (
|
|
RouteRule(Route.MESSAGES, Rollout.PYTHON_ONLY, features=frozenset({Feature.WORKLOAD_IDENTITY})),
|
|
RouteRule(Route.MESSAGES, Rollout.RUST_REQUIRED),
|
|
)
|
|
native_result: Final = response()
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("Rust mints the federation token itself")
|
|
|
|
served: Final = _DISPATCH.run(
|
|
(16, MESSAGES, "anthropic/claude-sonnet-4-5"),
|
|
{"anthropic_federation_rule_id": "rule-1", "anthropic_organization_id": "org-1"},
|
|
python=python,
|
|
binding=messages_binding(lambda request: native_result),
|
|
native=lambda hook, request, call_args, native_kwargs: hook(request),
|
|
rules=rules,
|
|
)
|
|
assert served is native_result
|
|
|
|
|
|
def _shipped_native(calls: list[str]) -> None: # mutable-ok: records which native entry ran
|
|
def native(request: NativeCall) -> AnthropicMessagesResponse:
|
|
calls.append("sync")
|
|
return response()
|
|
|
|
async def anative(request: NativeCall) -> AnthropicMessagesResponse:
|
|
calls.append("async")
|
|
return response()
|
|
|
|
NATIVE_MESSAGES.override(native)
|
|
NATIVE_AMESSAGES.override(anative)
|
|
|
|
|
|
@pytest.fixture
|
|
def shipped_native() -> Iterator[list[str]]:
|
|
calls: Final[list[str]] = []
|
|
_shipped_native(calls)
|
|
with routed(*RULES):
|
|
yield calls
|
|
NATIVE_MESSAGES.reset()
|
|
NATIVE_AMESSAGES.reset()
|
|
|
|
|
|
async def _public(asynchronous: bool, model: str, kwargs: Mapping[str, object]) -> object:
|
|
call: Final = {"max_tokens": 16, "messages": MESSAGES, "model": model, "api_key": "sk-test", **kwargs}
|
|
if asynchronous:
|
|
return await dispatch.anthropic_messages(**call)
|
|
return dispatch.anthropic_messages_handler(**call)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
async def test_anthropic_runs_on_rust_without_the_opt_in(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool
|
|
) -> None:
|
|
monkeypatch.setenv("LITELLM_RUST", "0")
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
|
|
result: Final = await _public(asynchronous, "anthropic/claude-sonnet-4-5", {})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
@pytest.mark.parametrize(
|
|
"model",
|
|
(
|
|
pytest.param(BEDROCK_INVOKE_MODEL, id="invoke"),
|
|
pytest.param("bedrock/mantle/anthropic.claude-sonnet-5", id="mantle-route"),
|
|
pytest.param("bedrock_mantle/anthropic.claude-sonnet-5", id="bedrock-mantle"),
|
|
),
|
|
)
|
|
async def test_bedrock_messages_run_on_rust_without_the_opt_in(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool, model: str
|
|
) -> None:
|
|
monkeypatch.setenv("LITELLM_RUST", "0")
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail(f"{model} has no Python Messages path")
|
|
|
|
with rebound(dispatch, "_PYTHON_MESSAGES", python), rebound(dispatch, "_PYTHON_AMESSAGES", python):
|
|
result: Final = await _public(asynchronous, model, {})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"model",
|
|
(
|
|
pytest.param("bedrock/claude_platform/claude-sonnet-4-5", id="claude-platform"),
|
|
pytest.param("bedrock/converse/us.anthropic.claude-sonnet-4-5-20250929-v1:0", id="converse"),
|
|
),
|
|
)
|
|
async def test_other_bedrock_messages_keep_python(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], model: str
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
python_result: Final = response(model)
|
|
|
|
async def apython(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
with rebound(dispatch, "_PYTHON_AMESSAGES", apython):
|
|
result: Final = await _public(True, model, {})
|
|
|
|
assert result is python_result
|
|
assert shipped_native == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
@pytest.mark.parametrize(
|
|
"model", ("anthropic/parity-tool-model", "anthropic/claude-sonnet-4-5"), ids=("non-claude", "claude")
|
|
)
|
|
async def test_proxy_classified_safeguards_run_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool, model: str
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
monkeypatch.setattr(proxy_server, "general_settings", CLASSIFIER_SETTINGS)
|
|
|
|
result: Final = await _public(asynchronous, model, {"safeguards": DANGEROUS_TOOL_USE})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
@pytest.mark.parametrize(
|
|
"thread",
|
|
(
|
|
pytest.param({"type": "create"}, id="create"),
|
|
pytest.param({"type": "continue", "previous_message_id": "msg_1"}, id="continue"),
|
|
),
|
|
)
|
|
async def test_a_message_thread_runs_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool, thread: Mapping[str, str]
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
|
|
result: Final = await _public(asynchronous, "anthropic/claude-sonnet-4-5", {"thread": dict(thread)})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_anthropic_runs_pre_request_hooks_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str]
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [_Rewrite()])
|
|
|
|
result: Final = await _public(True, "anthropic/claude-sonnet-4-5", {})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
async def test_anthropic_runs_a_web_search_short_circuit_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [_ShortCircuit()])
|
|
|
|
result: Final = await _public(asynchronous, "anthropic/claude-sonnet-4-5", {})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
@pytest.mark.parametrize(
|
|
("kwargs", "settings"),
|
|
(
|
|
pytest.param({"client": object()}, {}, id="caller-client"),
|
|
pytest.param({"client": AsyncHTTPHandler()}, {}, id="caller-async-handler"),
|
|
pytest.param({}, {"ssl_security_level": "DEFAULT@SECLEVEL=1"}, id="tls-security-level"),
|
|
pytest.param({}, {"ssl_ecdh_curve": "secp521r1"}, id="tls-ecdh-curve"),
|
|
),
|
|
)
|
|
async def test_anthropic_serves_the_http_transport_features_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
shipped_native: list[str],
|
|
asynchronous: bool,
|
|
kwargs: Mapping[str, object],
|
|
settings: Mapping[str, object],
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
for name in ("SSL_SECURITY_LEVEL", "SSL_ECDH_CURVE"):
|
|
monkeypatch.delenv(name, raising=False)
|
|
for name, value in settings.items():
|
|
monkeypatch.setattr(litellm, name, value)
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("anthropic has no Python Messages path")
|
|
|
|
with rebound(dispatch, "_PYTHON_MESSAGES", python), rebound(dispatch, "_PYTHON_AMESSAGES", python):
|
|
result: Final = await _public(asynchronous, "anthropic/claude-sonnet-4-5", kwargs)
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
@pytest.mark.parametrize(
|
|
"callbacks",
|
|
(
|
|
pytest.param([_Agentic()], id="agentic-loop"),
|
|
pytest.param([WebSearchInterceptionLogger(enabled_providers=["anthropic"])], id="websearch-interception"),
|
|
),
|
|
)
|
|
async def test_anthropic_serves_agentic_loop_callbacks_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool, callbacks: list[object]
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", callbacks)
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("anthropic has no Python Messages path")
|
|
|
|
with rebound(dispatch, "_PYTHON_MESSAGES", python), rebound(dispatch, "_PYTHON_AMESSAGES", python):
|
|
result: Final = await _public(asynchronous, "anthropic/claude-sonnet-4-5", {})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
@pytest.mark.parametrize(
|
|
"server_url",
|
|
(
|
|
pytest.param("litellm_proxy", id="whole-gateway"),
|
|
pytest.param("litellm_proxy/mcp/deepwiki", id="one-server"),
|
|
pytest.param("https://gateway.example/mcp/deepwiki", id="proxy-path"),
|
|
),
|
|
)
|
|
async def test_anthropic_serves_gateway_mcp_tools_on_rust(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool, server_url: str
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
tools: Final = [{"type": "mcp", "server_label": "gateway", "server_url": server_url, "require_approval": "never"}]
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback
|
|
pytest.fail("anthropic has no Python Messages path")
|
|
|
|
with rebound(dispatch, "_PYTHON_MESSAGES", python), rebound(dispatch, "_PYTHON_AMESSAGES", python):
|
|
result: Final = await _public(asynchronous, "anthropic/claude-sonnet-4-5", {"tools": tools})
|
|
|
|
assert isinstance(result, dict)
|
|
assert shipped_native == ["async" if asynchronous else "sync"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
async def test_other_providers_keep_python_for_the_same_features(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
python_result: Final = response("deepseek/deepseek-v4-flash")
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
async def apython(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
with rebound(dispatch, "_PYTHON_MESSAGES", python), rebound(dispatch, "_PYTHON_AMESSAGES", apython):
|
|
result: Final = await _public(asynchronous, "deepseek/deepseek-v4-flash", {"client": object()})
|
|
|
|
assert result is python_result
|
|
assert shipped_native == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
@pytest.mark.parametrize(
|
|
("model", "model_info", "native"),
|
|
(
|
|
pytest.param("azure_ai/Phi-4", {"supported_endpoints": ["/v1/messages"]}, False, id="non-claude-passthrough"),
|
|
pytest.param("azure_ai/Phi-4", None, False, id="non-claude-chat-bridge"),
|
|
pytest.param("azure_ai/sonnet-prod", None, False, id="alias-without-claude"),
|
|
pytest.param(
|
|
"azure_ai/claude-sonnet-4-5",
|
|
{"supported_endpoints": ["/v1/messages"]},
|
|
True,
|
|
id="claude-passthrough-opt-in",
|
|
),
|
|
pytest.param("azure_ai/Claude-Sonnet-4-5", None, True, id="claude-mixed-case"),
|
|
),
|
|
)
|
|
async def test_azure_ai_runs_on_rust_only_where_its_claude_config_serves_the_call(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
shipped_native: list[str],
|
|
asynchronous: bool,
|
|
model: str,
|
|
model_info: Mapping[str, object] | None,
|
|
native: bool,
|
|
) -> None:
|
|
monkeypatch.setenv("LITELLM_RUST", "0")
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
python_result: Final = response(model)
|
|
|
|
def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
async def apython(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
with rebound(dispatch, "_PYTHON_MESSAGES", python), rebound(dispatch, "_PYTHON_AMESSAGES", apython):
|
|
result: Final = await _public(
|
|
asynchronous,
|
|
model,
|
|
{"api_base": "https://fuzz.services.ai.azure.com/models", "model_info": model_info},
|
|
)
|
|
|
|
assert (shipped_native, result is python_result) == (
|
|
(["async" if asynchronous else "sync"], False) if native else ([], True)
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("model", "kwargs", "refused"),
|
|
(
|
|
pytest.param("anthropic/claude-sonnet-4-5", {}, True, id="anthropic"),
|
|
pytest.param("azure_ai/claude-sonnet-4-5", {}, True, id="azure-ai-claude"),
|
|
pytest.param(
|
|
"azure_ai/Phi-4",
|
|
{"model_info": {"supported_endpoints": ["/v1/messages"]}},
|
|
False,
|
|
id="azure-ai-non-claude-passthrough",
|
|
),
|
|
pytest.param(BEDROCK_INVOKE_MODEL, {}, True, id="bedrock-invoke"),
|
|
pytest.param("bedrock/mantle/anthropic.claude-sonnet-5", {}, True, id="bedrock-mantle-route"),
|
|
pytest.param("bedrock_mantle/anthropic.claude-sonnet-5", {}, True, id="bedrock-mantle"),
|
|
pytest.param("bedrock_mantle/openai.gpt-oss-120b", {}, False, id="bedrock-mantle-non-claude"),
|
|
pytest.param("deepseek/deepseek-v4-flash", {}, False, id="deepseek"),
|
|
),
|
|
)
|
|
async def test_a_failing_detector_refuses_only_the_rust_only_provider(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
shipped_native: list[str],
|
|
model: str,
|
|
kwargs: Mapping[str, object],
|
|
refused: bool,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
python_result: Final = response(model)
|
|
|
|
def failing(request: NativeCall) -> bool:
|
|
raise RuntimeError("detector failed")
|
|
|
|
async def apython(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: stub
|
|
return python_result
|
|
|
|
with (
|
|
rebound(dispatch, "_FEATURES", {Feature.MOCK_RESPONSE: failing}),
|
|
rebound(dispatch, "_PYTHON_AMESSAGES", apython),
|
|
):
|
|
if not refused:
|
|
assert await _public(True, model, kwargs) is python_result
|
|
return
|
|
with pytest.raises(UnsupportedParamsError, match="does not support this call"):
|
|
await _public(True, model, kwargs)
|
|
assert shipped_native == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", (False, True), ids=("sync", "async"))
|
|
async def test_an_anthropic_call_its_signature_rejects_keeps_python_s_type_error(
|
|
monkeypatch: pytest.MonkeyPatch, shipped_native: list[str], asynchronous: bool
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [])
|
|
call: Final = {"messages": MESSAGES, "model": "anthropic/claude-sonnet-4-5", "api_key": "sk-test"}
|
|
|
|
async def attempt() -> object:
|
|
if asynchronous:
|
|
return await dispatch.anthropic_messages(**call)
|
|
return dispatch.anthropic_messages_handler(**call)
|
|
|
|
with pytest.raises(TypeError, match="max_tokens"):
|
|
await attempt()
|
|
|
|
assert shipped_native == []
|