mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-03 01:38:46 +00:00
* fix(anthropic): keep tool_use ids for non-Anthropic backends on /v1/messages Since v1.91.0 every /v1/messages request rewrote tool ids to Anthropic's ^[a-zA-Z0-9_-]+$ pattern, so Kimi on vLLM got functions_Bash_0 back for its own functions.Bash:0 and stopped calling tools The anthropic provider now rewrites only for a Claude model or an api_base that serves Anthropic's API (api.anthropic.com or Foundry, explicit or from ANTHROPIC_API_BASE / ANTHROPIC_BASE_URL), in Python and Rust. Every other native provider keeps the rewrite. Chat-bridged providers send and return the provider's own tool call ids, with only the Gemini thought suffix stripped * fix(anthropic): rename tool_use ids on Bedrock and Azure AI, skip logins when deciding A Bedrock application inference profile ARN or an Azure AI deployment name can serve Claude without saying so, and Bedrock rejects ids like functions.Bash:0, so both providers always rename The check now resolves the provider the way request metadata does, so a github_copilot or chatgpt model never starts that provider's login just to decide whether to rename * fix(anthropic): keep caller tool_use ids unless the upstream rejects them Rename tool_use ids up front only for Anthropic's own hosts and Foundry, Bedrock, Azure AI and providers with a native messages config, in Python and Rust, with the claude model name shortcut removed When an upstream answers 400 with a tool_use id pattern mismatch, native /v1/messages (Python and Rust), the chat-bridged adapter and anthropic chat completions resend once with renamed ids. The retry fires only when renaming changes the request and composes with the thinking and strict tools retries, so the attempt cap is now 3 and the thinking retry also fires only when stripping changes the request Token counting follows the same per-deployment decision so counts match the ids that are sent * fix(anthropic): rename ids when counting tokens, allow four attempts, fill empty tool ids Token counting renames tool_use ids again for every deployment, as it did before this branch, since a count has no resend and a Claude gateway rejects the caller's ids there The messages retry cap is 4 in Python and Rust, so the strict-tools drop, the tool_use id resend and the thinking strip can all fire on one request A tool call that comes back without an id, or with only a thought signature, gets a generated id on the streamed and non-streamed paths, so two such calls never share one * test(anthropic): cover function results and an unresolvable model in the tool id decision * fix(anthropic): keep caller tool ids through guardrail rewrites and the global api_base * fix(anthropic): send an empty tool id as tool_use_id when keeping caller ids --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
188 lines
6.7 KiB
Python
188 lines
6.7 KiB
Python
from typing import Final
|
|
|
|
import pytest
|
|
|
|
import litellm
|
|
from litellm.types.utils import admin_api_key_secret_reference
|
|
from tests.test_litellm_rust.messages.data import MESSAGES, MESSAGES_RESPONSE, call
|
|
from tests.test_litellm_rust.support.recording_server import RecordingServer, ResponseSpec
|
|
from tests.test_litellm_rust.support.routing import assert_served_natively
|
|
|
|
pytestmark = pytest.mark.requires_rust_extension
|
|
|
|
CAPABILITY_MODEL: Final = "claude-test-runtime-capabilities"
|
|
|
|
|
|
def sent(server: RecordingServer) -> tuple[dict[str, object], dict[str, str]]:
|
|
assert_served_natively(server)
|
|
request: Final = server.requests[0]
|
|
assert isinstance(request.body, dict)
|
|
return request.body, request.headers
|
|
|
|
|
|
def capabilities(monkeypatch: pytest.MonkeyPatch, *, sampling: bool) -> None:
|
|
monkeypatch.setitem(
|
|
litellm.model_cost,
|
|
CAPABILITY_MODEL,
|
|
{"litellm_provider": "anthropic", "mode": "chat", "supports_sampling_params": sampling},
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("model", "sent_id"),
|
|
[
|
|
pytest.param("anthropic/claude-sonnet-5", "functions.Bash:0", id="claude-name"),
|
|
pytest.param("anthropic/kimi-k2", "functions.Bash:0", id="other-model"),
|
|
],
|
|
)
|
|
@pytest.mark.asyncio
|
|
async def test_replayed_tool_ids_are_kept_for_any_model_name_on_a_custom_base(
|
|
server: RecordingServer, model: str, sent_id: str
|
|
) -> None:
|
|
history: Final = [
|
|
{"role": "user", "content": "run it"},
|
|
{
|
|
"role": "assistant",
|
|
"content": [
|
|
{"type": "text", "text": ""},
|
|
{
|
|
"type": "tool_use",
|
|
"id": "functions.Bash:0",
|
|
"name": "Bash",
|
|
"input": {},
|
|
"provider_specific_fields": {"x": 1},
|
|
},
|
|
],
|
|
},
|
|
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "functions.Bash:0", "content": "ok"}]},
|
|
]
|
|
|
|
await call(server, model=model, messages=history)
|
|
|
|
body, _ = sent(server)
|
|
assert body["messages"] == [
|
|
{"role": "user", "content": "run it"},
|
|
{"role": "assistant", "content": [{"type": "tool_use", "id": sent_id, "name": "Bash", "input": {}}]},
|
|
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": sent_id, "content": "ok"}]},
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_success_body_that_is_not_a_message_passes_through(server: RecordingServer) -> None:
|
|
overloaded: Final = {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
|
|
server.default_response = ResponseSpec(body=overloaded)
|
|
|
|
response: Final = await call(server)
|
|
|
|
assert_served_natively(server, response)
|
|
assert isinstance(response, dict)
|
|
assert {name: value for name, value in response.items() if name != "_hidden_params"} == {
|
|
**overloaded,
|
|
"stop_sequence": None,
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_provider_specific_headers_scoped_to_anthropic_reach_the_wire(server: RecordingServer) -> None:
|
|
await call(
|
|
server,
|
|
provider_specific_header=[
|
|
{"custom_llm_provider": "anthropic, azure_ai", "extra_headers": {"x-scoped": "yes"}},
|
|
{"custom_llm_provider": "openai", "extra_headers": {"x-other": "no"}},
|
|
],
|
|
)
|
|
|
|
_, headers = sent(server)
|
|
assert headers["x-scoped"] == "yes"
|
|
assert "x-other" not in headers
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scoped_headers_override_extra_headers_which_override_forwarded_headers(server: RecordingServer) -> None:
|
|
await call(
|
|
server,
|
|
headers={"x-priority": "forwarded", "x-forwarded-only": "kept"},
|
|
extra_headers={"x-priority": "extra", "x-extra-only": "kept"},
|
|
provider_specific_header={"custom_llm_provider": "anthropic", "extra_headers": {"x-priority": "scoped"}},
|
|
)
|
|
|
|
_, headers = sent(server)
|
|
assert {name: headers.get(name) for name in ("x-priority", "x-forwarded-only", "x-extra-only")} == {
|
|
"x-priority": "scoped",
|
|
"x-forwarded-only": "kept",
|
|
"x-extra-only": "kept",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_model_capabilities_are_read_from_model_cost_at_call_time(
|
|
server: RecordingServer, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
server.expected_requests = 2
|
|
model: Final = f"anthropic/{CAPABILITY_MODEL}"
|
|
|
|
capabilities(monkeypatch, sampling=True)
|
|
await call(server, model=model, temperature=0.2, drop_params=True)
|
|
capabilities(monkeypatch, sampling=False)
|
|
await call(server, model=model, temperature=0.2, drop_params=True)
|
|
|
|
assert_served_natively(server, count=2)
|
|
first, second = (request.body for request in server.requests)
|
|
assert isinstance(first, dict)
|
|
assert first["temperature"] == 0.2
|
|
assert second == {name: value for name, value in first.items() if name != "temperature"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_global_drop_params_drops_unsupported_params(
|
|
server: RecordingServer, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
capabilities(monkeypatch, sampling=False)
|
|
monkeypatch.setattr(litellm, "drop_params", True)
|
|
|
|
await call(server, model=f"anthropic/{CAPABILITY_MODEL}", top_k=5)
|
|
|
|
body, _ = sent(server)
|
|
assert "top_k" not in body
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unsupported_params_are_rejected_before_io_without_drop_params(
|
|
server: RecordingServer, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
capabilities(monkeypatch, sampling=False)
|
|
monkeypatch.setattr(litellm, "drop_params", False)
|
|
server.expected_requests = 0
|
|
|
|
with pytest.raises(litellm.BadRequestError, match="top_k"):
|
|
await call(server, model=f"anthropic/{CAPABILITY_MODEL}", top_k=5)
|
|
|
|
assert server.requests == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_optional_positional_body_parameters_reach_the_wire(server: RecordingServer) -> None:
|
|
metadata: Final = {"user_id": "caller"}
|
|
args: Final = (16, list(MESSAGES), "anthropic/claude-test", metadata, None, False, "Be brief", 0.25)
|
|
|
|
response: Final = await litellm.anthropic_messages(*args, api_key="test-key", api_base=server.base_url)
|
|
|
|
assert isinstance(response, dict)
|
|
assert response["id"] == MESSAGES_RESPONSE["id"]
|
|
body, _ = sent(server)
|
|
assert (body["metadata"], body["system"], body["temperature"]) == (args[3], args[6], args[7])
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_the_secret_behind_an_admin_oidc_env_api_key_reaches_the_provider(
|
|
server: RecordingServer, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setenv("ANTHROPIC_SA_TOKEN", "env-token")
|
|
reference: Final = admin_api_key_secret_reference(
|
|
{"api_key": "oidc/env/ANTHROPIC_SA_TOKEN", "api_base": server.base_url}
|
|
)["api_key"]
|
|
|
|
await call(server, api_key=reference)
|
|
|
|
_, headers = sent(server)
|
|
assert headers["x-api-key"] == "env-token"
|