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]

test(integration): cover anthropic_messages endpoint contracts (#44704)

devin-ai-integration[bot]60ee96688529
diff --git a/tests/integration/authorization/test_claude_code_gateway_oauth.py b/tests/integration/authorization/test_claude_code_gateway_oauth.py
new file mode 100644
index 00000000000..acab042bfc9
--- /dev/null
+++ b/tests/integration/authorization/test_claude_code_gateway_oauth.py
@@ -0,0 +1,520 @@
+import asyncio
+import base64
+import hashlib
+import html
+import json
+import os
+import re
+import uuid
+from collections import deque
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Final, Literal
+from urllib.parse import parse_qs, urlencode, urlsplit
+
+import httpx
+import pytest
+import yaml
+from anthropic.types import Message
+from integration._support import claude_code as cc
+from integration._support.client import Gateway, eventually, gateway_from_environment
+from integration._support.database import read_rows
+from integration._support.process import owned_proxy_process
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
+
+_CLIENT_ID: Final = "scripted-cli-client"
+_CLIENT_SECRET: Final = "scripted-cli-secret"
+_AUTHORIZATION_CODE: Final = "scripted-auth-code"
+_IDP_ACCESS_TOKEN: Final = "scripted-idp-access-token"
+_USER_ID: Final = "gateway-sso-user"
+_USER_EMAIL: Final = "[email protected]"
+_BACKEND: Final = "claude-sonnet-4-6"
+_API_KEY: Final = "synthetic-anthropic-key"
+_EXPECTED_BETA: Final = ",".join(
+ sorted(set((*cc.CLI_BETA.split(","), "context-management-2025-06-27", "prompt-caching-scope-2026-01-05")))
+)
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_MESSAGE: Final = TypeAdapter(Message)
+_BROWSER_TOKEN: Final = re.compile(r'name="browser_complete_token" value="([^"]+)"')
+
+
+class _DeviceAuthorization(BaseModel):
+ device_code: str
+ user_code: str
+ verification_uri: str
+ verification_uri_complete: str | None = None
+ expires_in: int
+ interval: int
+
+
+class _AccessToken(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ access_token: str
+ expires_in: int
+ token_type: Literal["Bearer"]
+ refresh_token: str
+ user_id: str
+ team_id: str | None
+
+
+def _owned_config(path: Path) -> Path:
+ config: Final = _JSON_OBJECT.validate_python(
+ yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
+ )
+ general_settings: Final = _JSON_OBJECT.validate_python(config.get("general_settings", {}))
+ path.write_text(
+ yaml.safe_dump(
+ {
+ **config,
+ "general_settings": {**general_settings, "enable_claude_code_gateway": True},
+ }
+ )
+ )
+ return path
+
+
+def _identity_provider(request: Request) -> Reply:
+ parsed_target: Final = urlsplit(request.target)
+ if request.method == "GET" and parsed_target.path == "/authorize":
+ query: Final = parse_qs(parsed_target.query)
+ assert query["client_id"] == [_CLIENT_ID], query
+ assert query["response_type"] == ["code"], query
+ assert query["scope"] == ["openid email profile"], query
+ assert query["code_challenge_method"] == ["S256"], query
+ assert len(query["code_challenge"][0]) == 43, query
+ callback: Final = query["redirect_uri"][0]
+ assert urlsplit(callback).path == "/sso/callback", query
+ state: Final = query["state"][0]
+ assert state.startswith("litellm-session-token:"), query
+ location: Final = f"{callback}?{urlencode({'code': _AUTHORIZATION_CODE, 'state': state})}"
+ return Reply(status=302, headers={"location": location})
+
+ if request.method == "POST" and parsed_target.path == "/token":
+ form: Final = parse_qs(request.body.decode())
+ encoded_credentials: Final = base64.b64encode(f"{_CLIENT_ID}:{_CLIENT_SECRET}".encode()).decode()
+ assert request.headers["authorization"] == f"Basic {encoded_credentials}", request.headers
+ assert request.headers["content-type"] == "application/x-www-form-urlencoded", request.headers
+ assert set(form) == {"code", "code_verifier", "grant_type", "redirect_uri"}, form
+ assert form["grant_type"] == ["authorization_code"], form
+ assert form["code"] == [_AUTHORIZATION_CODE], form
+ assert len(form["code_verifier"][0]) == 43, form
+ assert urlsplit(form["redirect_uri"][0]).path == "/sso/callback", form
+ return Reply(body=json.dumps({"access_token": _IDP_ACCESS_TOKEN, "token_type": "Bearer"}).encode())
+
+ if request.method == "GET" and parsed_target.path == "/userinfo":
+ assert request.headers["authorization"] == f"Bearer {_IDP_ACCESS_TOKEN}", request.headers
+ return Reply(body=json.dumps({"sub": _USER_ID, "email": _USER_EMAIL}).encode())
+
+ raise AssertionError(f"unexpected scripted IdP request: {request.method} {request.target}")
+
+
+_REPLY_CONTENT: Final = ({"type": "text", "text": "authorized"},)
+_REPLY_USAGE: Final = {"input_tokens": 5, "output_tokens": 1}
+
+
+def _anthropic_reply(request: Request, expected_body: dict[str, JsonValue], message_id: str) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert request.headers["anthropic-beta"] == _EXPECTED_BETA, request.headers
+ assert "authorization" not in request.headers, request.headers
+ body: Final = _JSON_OBJECT.validate_json(request.body)
+ streamed: Final = body.get("stream") is True
+ assert body == {**expected_body, "stream": streamed}, request.body
+ if streamed:
+ return Reply(
+ chunks=cc.message_stream(message_id, _BACKEND, _REPLY_CONTENT, _REPLY_USAGE),
+ content_type="text/event-stream",
+ )
+ return Reply(body=cc.message_reply(message_id, _BACKEND, _REPLY_CONTENT, _REPLY_USAGE))
+
+
[email protected](scope="module")
+def identity_provider() -> Iterator[Wire]:
+ with wire_server(_identity_provider) as wire:
+ yield wire
+
+
[email protected](scope="module")
+def enabled_gateway(identity_provider: Wire, tmp_path_factory: pytest.TempPathFactory) -> Iterator[Gateway]:
+ assert os.environ.get("LITELLM_LICENSE"), "LITELLM_LICENSE is required for the generic SSO integration test"
+ with gateway_from_environment() as base_gateway:
+ directory: Final = tmp_path_factory.mktemp("claude-code-gateway-oauth")
+ config: Final = _owned_config(directory / "gateway-oauth.yaml")
+ overrides: Final = {
+ "GENERIC_CLIENT_ID": _CLIENT_ID,
+ "GENERIC_CLIENT_SECRET": _CLIENT_SECRET,
+ "GENERIC_AUTHORIZATION_ENDPOINT": f"{identity_provider.url}/authorize",
+ "GENERIC_TOKEN_ENDPOINT": f"{identity_provider.url}/token",
+ "GENERIC_USERINFO_ENDPOINT": f"{identity_provider.url}/userinfo",
+ "GENERIC_USER_ID_ATTRIBUTE": "sub",
+ "GENERIC_USER_EMAIL_ATTRIBUTE": "email",
+ "GENERIC_CLIENT_USE_PKCE": "true",
+ "GENERIC_INCLUDE_CLIENT_ID": "false",
+ }
+ with owned_proxy_process(
+ base_gateway,
+ directory,
+ overrides,
+ config=config,
+ workers=2,
+ remove_environment=("GOOGLE_CLIENT_ID", "MICROSOFT_CLIENT_ID", "PROXY_BASE_URL"),
+ ) as owned:
+ yield owned.gateway
+
+
+def test_device_authorization_polls_complete_sso_and_mints_a_model_restricted_bearer(
+ enabled_gateway: Gateway, identity_provider: Wire
+) -> None:
+ request_template: Final = {
+ **cc.claude_code_request("oauth-model-restriction"),
+ "model": "",
+ "stream": False,
+ }
+ expected_body: Final = {**request_template, "model": _BACKEND}
+ run_id: Final = uuid.uuid4().hex
+ message_ids: Final = (f"msg_oauth_{run_id}_a", f"msg_oauth_{run_id}_a_stream", f"msg_oauth_{run_id}_c")
+ pending_message_ids: Final = deque(message_ids)
+
+ with enabled_gateway.scenario() as scenario:
+ with wire_server(
+ lambda request: _anthropic_reply(request, expected_body, pending_message_ids.popleft())
+ ) as upstream:
+ model_a: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=upstream.url, api_key=_API_KEY)
+ model_b: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=upstream.url, api_key=_API_KEY)
+ model_c: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=upstream.url, api_key=_API_KEY)
+ user_id: Final = scenario.user(
+ user_id=_USER_ID,
+ user_email=_USER_EMAIL,
+ user_role="internal_user",
+ models=[model_a, model_b],
+ )
+ team_id: Final = scenario.team(models=[model_a, model_c])
+ enabled_gateway.post(
+ "/team/member_add", {"team_id": team_id, "member": {"role": "user", "user_id": user_id}}
+ )
+
+ authorization_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/device_authorization",
+ data={"client_id": _CLIENT_ID},
+ )
+ assert authorization_response.status_code == 200, authorization_response.text
+ authorization: Final = _DeviceAuthorization.model_validate_json(authorization_response.content)
+ authorization_body: Final = _JSON_OBJECT.validate_json(authorization_response.content)
+ assert authorization_body == authorization.model_dump(exclude_none=True), authorization_response.text
+ assert authorization.expires_in > 0 and authorization.interval > 0, authorization_response.text
+ login_id, separator, poll_secret = authorization.device_code.partition(".")
+ assert separator == "." and login_id.startswith("cli-") and poll_secret, authorization_response.text
+
+ verification_parts: Final = urlsplit(authorization.verification_uri)
+ assert verification_parts.path == "/sso/key/generate", authorization.verification_uri
+ verification_query: Final = parse_qs(verification_parts.query)
+ assert verification_query == {"source": ["litellm-cli"], "key": [login_id]}, authorization.verification_uri
+
+ pending: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/token",
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": authorization.device_code,
+ "client_id": _CLIENT_ID,
+ },
+ )
+ assert pending.status_code == 400, pending.text
+ pending_body: Final = _JSON_OBJECT.validate_json(pending.content)
+ assert pending_body == {"error": "authorization_pending"}, pending.text
+
+ wrong_secret: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/token",
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": f"{login_id}.wrong-poll-secret",
+ "client_id": _CLIENT_ID,
+ },
+ )
+ assert wrong_secret.status_code == 400, wrong_secret.text
+ assert _JSON_OBJECT.validate_json(wrong_secret.content) == {"error": "expired_token"}, wrong_secret.text
+ assert "authorization_pending" not in wrong_secret.text, wrong_secret.text
+
+ verification_response: Final = enabled_gateway.client.get(
+ authorization.verification_uri,
+ follow_redirects=False,
+ )
+ assert verification_response.status_code == 303, verification_response.text
+ assert "litellm_oauth_state" in verification_response.headers.get("set-cookie", ""), (
+ verification_response.headers,
+ )
+ browser_state: Final = enabled_gateway.client.cookies.get("litellm_oauth_state")
+ assert browser_state, verification_response.headers
+
+ identity_provider_response: Final = enabled_gateway.client.get(
+ verification_response.headers["location"],
+ follow_redirects=False,
+ )
+ assert identity_provider_response.status_code == 302, identity_provider_response.text
+ callback_location: Final = identity_provider_response.headers["location"]
+ callback_parts: Final = urlsplit(callback_location)
+ assert callback_parts.path == "/sso/callback", callback_location
+ callback_query: Final = parse_qs(callback_parts.query)
+ assert callback_query["state"] == [browser_state], callback_location
+
+ callback_response: Final = enabled_gateway.client.get(callback_location, follow_redirects=False)
+ assert callback_response.status_code == 200, callback_response.text
+ browser_token_match: Final = _BROWSER_TOKEN.search(callback_response.text)
+ assert browser_token_match is not None, callback_response.text
+ browser_complete_token: Final = html.unescape(browser_token_match.group(1))
+
+ still_pending: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/token",
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": authorization.device_code,
+ "client_id": _CLIENT_ID,
+ },
+ )
+ assert still_pending.status_code == 400, still_pending.text
+ assert _JSON_OBJECT.validate_json(still_pending.content) == {"error": "authorization_pending"}, (
+ still_pending.text,
+ )
+
+ wrong_code_completion: Final = enabled_gateway.client.post(
+ f"/sso/cli/complete/{login_id}",
+ data={"user_code": "WRONG-CODE", "browser_complete_token": browser_complete_token},
+ )
+ assert wrong_code_completion.status_code == 400, wrong_code_completion.text
+ assert _JSON_OBJECT.validate_json(wrong_code_completion.content) == {
+ "detail": "Invalid verification code"
+ }, wrong_code_completion.text
+
+ pending_after_wrong_code: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/token",
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": authorization.device_code,
+ "client_id": _CLIENT_ID,
+ },
+ )
+ assert pending_after_wrong_code.status_code == 400, pending_after_wrong_code.text
+ assert _JSON_OBJECT.validate_json(pending_after_wrong_code.content) == {"error": "authorization_pending"}, (
+ pending_after_wrong_code.text
+ )
+
+ verification_complete: Final = enabled_gateway.client.post(
+ f"/sso/cli/complete/{login_id}",
+ data={"user_code": authorization.user_code, "browser_complete_token": browser_complete_token},
+ )
+ assert verification_complete.status_code == 200, verification_complete.text
+
+ async def poll_device_code() -> tuple[httpx.Response, ...]:
+ async with httpx.AsyncClient(
+ base_url=str(enabled_gateway.client.base_url),
+ timeout=30,
+ trust_env=False,
+ ) as client:
+ return tuple(
+ await asyncio.gather(
+ *(
+ client.post(
+ "/claude_code_gateway/oauth/token",
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": authorization.device_code,
+ "client_id": _CLIENT_ID,
+ },
+ )
+ for _ in range(8)
+ )
+ )
+ )
+
+ poll_responses: Final = asyncio.run(poll_device_code())
+ successful_polls: Final = tuple(response for response in poll_responses if response.status_code == 200)
+ assert len(successful_polls) == 1, (
+ f"Expected exactly one successful device_code poll, got {len(successful_polls)} "
+ f"with statuses {tuple(response.status_code for response in poll_responses)}"
+ )
+ token_response: Final = successful_polls[0]
+ losing_polls: Final = tuple(response for response in poll_responses if response is not token_response)
+ assert len(losing_polls) == 7, losing_polls
+ for losing_poll in losing_polls:
+ assert losing_poll.status_code == 400, losing_poll.text
+ assert _JSON_OBJECT.validate_json(losing_poll.content) == {"error": "expired_token"}, losing_poll.text
+
+ assert token_response.status_code == 200, token_response.text
+ access_token: Final = _AccessToken.model_validate_json(token_response.content)
+ access_token_body: Final = _JSON_OBJECT.validate_json(token_response.content)
+ assert access_token_body == access_token.model_dump(), token_response.text
+ assert set(access_token_body) == {
+ "access_token",
+ "expires_in",
+ "token_type",
+ "refresh_token",
+ "user_id",
+ "team_id",
+ }, token_response.text
+ assert access_token.token_type == "Bearer" and access_token.expires_in > 0, token_response.text
+ assert access_token.user_id == user_id, token_response.text
+ assert access_token.team_id == team_id, token_response.text
+
+ second_poll: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/token",
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": authorization.device_code,
+ "client_id": _CLIENT_ID,
+ },
+ )
+ assert second_poll.status_code == 400, second_poll.text
+ assert _JSON_OBJECT.validate_json(second_poll.content) == {"error": "expired_token"}, second_poll.text
+
+ unsupported: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/token",
+ data={"grant_type": "urn:unsupported"},
+ )
+ assert unsupported.status_code == 400, unsupported.text
+ assert _JSON_OBJECT.validate_json(unsupported.content) == {
+ "error": "unsupported_grant_type",
+ "error_description": "Unsupported grant_type: urn:unsupported",
+ }, unsupported.text
+
+ refresh: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/oauth/token",
+ data={"grant_type": "refresh_token"},
+ )
+ assert refresh.status_code == 400, refresh.text
+ assert _JSON_OBJECT.validate_json(refresh.content) == {
+ "error": "invalid_request",
+ "error_description": "refresh_token is required",
+ }, refresh.text
+
+ bearer_headers: Final = {
+ "authorization": f"Bearer {access_token.access_token}",
+ "anthropic-version": "2023-06-01",
+ "anthropic-beta": cc.CLI_BETA,
+ "x-claude-code-session-id": f"oauth-{user_id}",
+ }
+ request_body: Final = {**request_template, "model": model_a}
+ expected_message: Final = _MESSAGE.validate_python(
+ {
+ **_JSON_OBJECT.validate_json(
+ cc.message_reply(message_ids[0], _BACKEND, _REPLY_CONTENT, _REPLY_USAGE)
+ ),
+ "model": model_a,
+ }
+ )
+ model_a_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages", json=request_body, headers=bearer_headers
+ )
+ assert model_a_response.status_code == 200, model_a_response.text
+ parsed_message: Final = _MESSAGE.validate_json(model_a_response.content)
+ assert parsed_message.model_dump(mode="json") == expected_message.model_dump(mode="json"), (
+ model_a_response.text,
+ )
+
+ model_a_stream: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages?beta=true",
+ json={**request_body, "stream": True},
+ headers=bearer_headers,
+ )
+ assert model_a_stream.status_code == 200, model_a_stream.text
+ expected_stream_events: Final = tuple(
+ (
+ event,
+ {**data, "message": {**_JSON_OBJECT.validate_python(data["message"]), "model": model_a}}
+ if event == "message_start"
+ else data,
+ )
+ for event, data in cc.sse_events(
+ b"".join(cc.message_stream(message_ids[1], _BACKEND, _REPLY_CONTENT, _REPLY_USAGE)).decode()
+ )
+ )
+ assert cc.sse_events(model_a_stream.text) == expected_stream_events, model_a_stream.text
+
+ upstream_requests: Final = upstream.drain()
+ assert len(upstream_requests) == 2, upstream_requests
+ assert tuple(
+ (request.method, request.target, _JSON_OBJECT.validate_json(request.body))
+ for request in upstream_requests
+ ) == (
+ ("POST", "/v1/messages", expected_body),
+ ("POST", "/v1/messages", {**expected_body, "stream": True}),
+ ), upstream_requests
+
+ model_b_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages", json={**request_body, "model": model_b}, headers=bearer_headers
+ )
+ assert model_b_response.status_code == 403, model_b_response.text
+ assert _JSON_OBJECT.validate_json(model_b_response.content) == {
+ "error": {
+ "message": (
+ f"The requested model '{model_b}' is not available for this API key, or the model name is "
+ "invalid. Check the models available to you and try again."
+ ),
+ "type": "team_model_access_denied",
+ "param": "model",
+ "code": "403",
+ }
+ }, model_b_response.text
+ assert upstream.drain() == ()
+
+ model_c_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages", json={**request_body, "model": model_c}, headers=bearer_headers
+ )
+ assert model_c_response.status_code == 200, model_c_response.text
+ assert _MESSAGE.validate_json(model_c_response.content).model_dump(mode="json") == (
+ expected_message.model_copy(update={"id": message_ids[2], "model": model_c}).model_dump(mode="json")
+ ), model_c_response.text
+ assert tuple(
+ (request.method, request.target, _JSON_OBJECT.validate_json(request.body))
+ for request in upstream.drain()
+ ) == (("POST", "/v1/messages", expected_body),)
+
+ spend_rows: Final = eventually(
+ lambda: read_rows(
+ 'SELECT request_id, "user", team_id, model_group, call_type FROM "LiteLLM_SpendLogs" '
+ "WHERE team_id=%s AND status='success' ORDER BY \"startTime\"",
+ (team_id,),
+ ),
+ lambda rows: len(rows) == 3,
+ seconds=70,
+ return_last_on_timeout=True,
+ )
+ assert spend_rows == [
+ {
+ "request_id": message_id,
+ "user": _USER_ID,
+ "team_id": team_id,
+ "model_group": model,
+ "call_type": "anthropic_messages",
+ }
+ for message_id, model in zip(message_ids, (model_a, model_a, model_c), strict=True)
+ ], spend_rows
+ idp_requests: Final = identity_provider.drain()
+ assert len(idp_requests) == 3, idp_requests
+ (authorization_request, token_request, userinfo_request) = idp_requests
+ authorization_query: Final = parse_qs(urlsplit(authorization_request.target).query)
+ assert authorization_request.method == "GET" and urlsplit(authorization_request.target).path == "/authorize"
+ assert set(authorization_query) == {
+ "client_id",
+ "code_challenge",
+ "code_challenge_method",
+ "redirect_uri",
+ "response_type",
+ "scope",
+ "state",
+ }, authorization_query
+ assert authorization_query["client_id"] == [_CLIENT_ID], authorization_query
+ assert authorization_query["response_type"] == ["code"], authorization_query
+ assert authorization_query["scope"] == ["openid email profile"], authorization_query
+ assert authorization_query["code_challenge_method"] == ["S256"], authorization_query
+ token_form: Final = parse_qs(token_request.body.decode())
+ verifier: Final = token_form["code_verifier"][0]
+ expected_challenge: Final = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
+ assert authorization_query["code_challenge"] == [expected_challenge.rstrip(b"=").decode()], token_request
+ assert token_request.method == "POST" and urlsplit(token_request.target).path == "/token", token_request
+ assert token_request.headers["content-type"] == "application/x-www-form-urlencoded", token_request.headers
+ assert set(token_form) == {"code", "code_verifier", "grant_type", "redirect_uri"}, token_form
+ assert userinfo_request.method == "GET" and urlsplit(userinfo_request.target).path == "/userinfo"
+ assert user_id == _USER_ID
diff --git a/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_count_tokens_wire.py b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_count_tokens_wire.py
new file mode 100644
index 00000000000..92512a304bc
--- /dev/null
+++ b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_count_tokens_wire.py
@@ -0,0 +1,240 @@
+import json
+from collections.abc import Callable
+from typing import Final
+
+import anthropic
+import pytest
+from anthropic.types import MessageTokensCount
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+_BACKEND: Final = "claude-sonnet-4-6"
+_API_KEY: Final = "synthetic-anthropic-key"
+_COUNT_BETA: Final = "token-counting-2024-11-01"
+_CLIENT_BETA: Final = "client-future-beta-2099-01-01"
+_MERGED_BETA: Final = f"{_CLIENT_BETA},{_COUNT_BETA}"
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_MESSAGES: Final[list[JsonValue]] = [{"role": "user", "content": "Count this synthetic request."}]
+_SYSTEM: Final[list[JsonValue]] = [{"type": "text", "text": "Count the supplied message and tool."}]
+_TOOLS: Final[list[JsonValue]] = [
+ {
+ "name": "lookup",
+ "description": "Look up a synthetic record.",
+ "input_schema": {
+ "type": "object",
+ "properties": {"record_id": {"type": "string"}},
+ "required": ["record_id"],
+ },
+ }
+]
+_COUNTED_INPUT_TOKENS: Final = 73
+_UPSTREAM_ERROR: Final = {
+ "type": "error",
+ "error": {"type": "invalid_request_error", "message": "The scripted count request was rejected."},
+}
+
+
+def _client(gateway: Gateway, key: str) -> anthropic.Anthropic:
+ return anthropic.Anthropic(
+ api_key=key,
+ base_url=str(gateway.client.base_url),
+ max_retries=0,
+ http_client=gateway.client,
+ )
+
+
+def _count_peer(
+ expected_body: dict[str, JsonValue], result: Reply, expected_beta: str = _COUNT_BETA
+) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages/count_tokens", request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert request.headers["anthropic-beta"] == expected_beta, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_body, request.body
+ return result
+
+ return respond
+
+
+def _sdk_count(client: anthropic.Anthropic, model: str, spelling: str, beta: str) -> MessageTokensCount:
+ if spelling == "beta":
+ beta_result: Final = client.beta.messages.count_tokens(
+ model=model,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ betas=[beta],
+ )
+ return MessageTokensCount.model_validate(beta_result.model_dump(exclude_none=True))
+ return client.messages.count_tokens(
+ model=model,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ extra_headers={"anthropic-beta": beta},
+ )
+
+
[email protected]("spelling", ["messages", "beta"], ids=["messages_count_tokens", "beta_messages_count_tokens"])
+def test_anthropic_count_tokens_forwards_body_and_refuses_a_key_without_model_access(
+ gateway: Gateway, spelling: str
+) -> None:
+ with gateway.scenario() as scenario:
+ with wire_server(
+ _count_peer(
+ {"model": _BACKEND, "messages": _MESSAGES, "system": _SYSTEM, "tools": _TOOLS},
+ Reply(body=json.dumps({"input_tokens": _COUNTED_INPUT_TOKENS}).encode()),
+ )
+ ) as wire:
+ model: Final = scenario.model(
+ model=f"anthropic/{_BACKEND}",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ restricted_model: Final = scenario.model(
+ model="anthropic/claude-haiku-4-5-20251001",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ restricted_key: Final = scenario.key(models=[restricted_model])
+
+ client: Final = _client(gateway, gateway.key)
+ result: Final = _sdk_count(client, model, spelling, _COUNT_BETA)
+ assert result.model_dump() == {"input_tokens": _COUNTED_INPUT_TOKENS}
+ requests: Final = wire.drain()
+ assert len(requests) == 1, requests
+
+ restricted_client: Final = _client(gateway, restricted_key)
+ with pytest.raises(anthropic.PermissionDeniedError) as raised:
+ _sdk_count(restricted_client, model, spelling, _COUNT_BETA)
+ assert raised.value.status_code == 403, raised.value.response.text
+ assert model in raised.value.message, raised.value.message
+ assert wire.drain() == ()
+
+
+def test_anthropic_count_tokens_relays_an_upstream_server_error(gateway: Gateway) -> None:
+ with gateway.scenario() as scenario:
+ with wire_server(
+ _count_peer(
+ {"model": _BACKEND, "messages": _MESSAGES, "system": _SYSTEM, "tools": _TOOLS},
+ Reply(status=500, body=json.dumps(_UPSTREAM_ERROR).encode()),
+ )
+ ) as wire:
+ model: Final = scenario.model(
+ model=f"anthropic/{_BACKEND}",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ client: Final = _client(gateway, gateway.key)
+ with pytest.raises(anthropic.InternalServerError) as raised:
+ client.messages.count_tokens(
+ model=model,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ extra_headers={"anthropic-beta": _COUNT_BETA},
+ )
+ assert raised.value.status_code == 500
+ assert "The scripted count request was rejected." in raised.value.message
+ assert len(wire.drain()) == 1
+
+
+def test_anthropic_count_tokens_relays_an_upstream_client_error(gateway: Gateway) -> None:
+ with gateway.scenario() as scenario:
+ with wire_server(
+ _count_peer(
+ {"model": _BACKEND, "messages": _MESSAGES, "system": _SYSTEM, "tools": _TOOLS},
+ Reply(status=400, body=json.dumps(_UPSTREAM_ERROR).encode()),
+ )
+ ) as wire:
+ model: Final = scenario.model(
+ model=f"anthropic/{_BACKEND}",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ client: Final = _client(gateway, gateway.key)
+ with pytest.raises(anthropic.BadRequestError) as raised:
+ client.messages.count_tokens(
+ model=model,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ extra_headers={"anthropic-beta": _COUNT_BETA},
+ )
+ assert raised.value.status_code == 400
+ assert "The scripted count request was rejected." in raised.value.message
+ assert len(wire.drain()) == 1
+
+
+def test_anthropic_count_tokens_preserves_thinking_tool_choice_and_output_config(gateway: Gateway) -> None:
+ pytest.skip(
+ "BUG: /v1/messages/count_tokens drops thinking, tool_choice and output_config before the provider count call"
+ )
+
+ thinking: Final = {"type": "enabled", "budget_tokens": 1024}
+ tool_choice: Final = {"type": "auto", "disable_parallel_tool_use": True}
+ output_config: Final = {"effort": "medium"}
+ expected_body: Final = {
+ "model": _BACKEND,
+ "messages": _MESSAGES,
+ "system": _SYSTEM,
+ "tools": _TOOLS,
+ "thinking": thinking,
+ "tool_choice": tool_choice,
+ "output_config": output_config,
+ }
+
+ with gateway.scenario() as scenario:
+ with wire_server(
+ _count_peer(expected_body, Reply(body=json.dumps({"input_tokens": _COUNTED_INPUT_TOKENS}).encode()))
+ ) as wire:
+ model: Final = scenario.model(
+ model=f"anthropic/{_BACKEND}",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ client: Final = _client(gateway, gateway.key)
+ result: Final = client.messages.count_tokens(
+ model=model,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ thinking=thinking,
+ tool_choice=tool_choice,
+ output_config=output_config,
+ extra_headers={"anthropic-beta": _COUNT_BETA},
+ )
+ assert result.input_tokens == _COUNTED_INPUT_TOKENS
+ assert len(wire.drain()) == 1
+
+
[email protected]("spelling", ["messages", "beta"], ids=["messages_count_tokens", "beta_messages_count_tokens"])
+def test_anthropic_count_tokens_merges_the_client_beta_with_the_token_counting_beta(
+ gateway: Gateway, spelling: str
+) -> None:
+ pytest.skip("BUG: /v1/messages/count_tokens drops the client's anthropic-beta before the provider count call")
+
+ with gateway.scenario() as scenario:
+ with wire_server(
+ _count_peer(
+ {"model": _BACKEND, "messages": _MESSAGES, "system": _SYSTEM, "tools": _TOOLS},
+ Reply(body=json.dumps({"input_tokens": _COUNTED_INPUT_TOKENS}).encode()),
+ _MERGED_BETA,
+ )
+ ) as wire:
+ model: Final = scenario.model(
+ model=f"anthropic/{_BACKEND}",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ result: Final = _sdk_count(_client(gateway, gateway.key), model, spelling, _CLIENT_BETA)
+ assert result.model_dump() == {"input_tokens": _COUNTED_INPUT_TOKENS}
+ assert len(wire.drain()) == 1
diff --git a/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_gateway_wire.py b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_gateway_wire.py
new file mode 100644
index 00000000000..8a79d5c6a7a
--- /dev/null
+++ b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_gateway_wire.py
@@ -0,0 +1,359 @@
+import hashlib
+import uuid
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Final
+
+import pytest
+import yaml
+from anthropic.types import Message
+from integration._support import claude_code as cc
+from integration._support.client import Gateway, eventually, gateway_from_environment
+from integration._support.database import read_rows
+from integration._support.process import owned_proxy_process
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+_BACKEND: Final = "claude-sonnet-4-6"
+_API_KEY: Final = "synthetic-anthropic-key"
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_MESSAGE: Final = TypeAdapter(Message)
+
+
+def _expected_stream_events(
+ stream_reply: tuple[bytes, ...], model: str
+) -> tuple[tuple[str, dict[str, JsonValue]], ...]:
+ return tuple(
+ (
+ event,
+ {
+ **data,
+ **(
+ {
+ "message": {
+ **_JSON_OBJECT.validate_python(data["message"]),
+ "model": model,
+ }
+ }
+ if event == "message_start"
+ else {}
+ ),
+ },
+ )
+ for event, data in cc.sse_events(b"".join(stream_reply).decode())
+ )
+
+
+def _owned_config(path: Path) -> Path:
+ config: Final = _JSON_OBJECT.validate_python(
+ yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
+ )
+ general_settings: Final = _JSON_OBJECT.validate_python(config.get("general_settings", {}))
+ litellm_settings: Final = _JSON_OBJECT.validate_python(config.get("litellm_settings", {}))
+ path.write_text(
+ yaml.safe_dump(
+ {
+ **config,
+ "general_settings": {**general_settings, "enable_claude_code_gateway": True},
+ "litellm_settings": {**litellm_settings, "cache": False},
+ }
+ )
+ )
+ return path
+
+
+def _cli_bearer_headers(key: str) -> dict[str, str]:
+ return {
+ **{name: value for name, value in cc.cli_headers(key).items() if name != "x-api-key"},
+ "authorization": f"Bearer {key}",
+ }
+
+
[email protected](scope="module")
+def enabled_gateway(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Gateway]:
+ with gateway_from_environment() as base_gateway:
+ directory: Final = tmp_path_factory.mktemp("anthropic-gateway")
+ config: Final = _owned_config(directory / "gateway.yaml")
+ with owned_proxy_process(base_gateway, directory, {}, config=config, workers=2) as owned:
+ yield owned.gateway
+
+
+ "path",
+ ["/claude_code_gateway/v1/messages?beta=true", "/claude_code_gateway/v1/messages/count_tokens?beta=true"],
+ ids=["messages", "count_tokens"],
+)
+def test_shared_gateway_route_is_disabled_without_reaching_provider(gateway: Gateway, path: str) -> None:
+ def respond(request: Request) -> Reply:
+ raise AssertionError(f"disabled gateway must not reach the provider: {request.target}")
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)
+ response: Final = gateway.client.post(
+ path,
+ json={"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": "disabled control"}]},
+ headers=_cli_bearer_headers(gateway.key),
+ )
+ assert response.status_code == 404, response.text
+ assert _JSON_OBJECT.validate_json(response.content) == {"detail": "Claude Code gateway is not enabled"}, (
+ response.text
+ )
+ assert wire.drain() == ()
+
+
+def _restricted_model_responses(enabled_gateway: Gateway) -> tuple[int, str, int, str, str, tuple[Request, ...]]:
+ def respond(request: Request) -> Reply:
+ raise AssertionError(f"restricted model must not reach the provider: {request.target}")
+
+ with enabled_gateway.scenario() as scenario, wire_server(respond) as wire:
+ model_a: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)
+ model_b: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)
+ key: Final = scenario.key(models=[model_a])
+ request_body: Final = {**cc.claude_code_request("restricted-model"), "model": model_b}
+ gateway_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages?beta=true",
+ json=request_body,
+ headers=_cli_bearer_headers(key),
+ )
+ messages_response: Final = enabled_gateway.client.post(
+ "/v1/messages?beta=true",
+ json=request_body,
+ headers=cc.cli_headers(key),
+ )
+ return (
+ gateway_response.status_code,
+ gateway_response.text,
+ messages_response.status_code,
+ messages_response.text,
+ model_b,
+ wire.drain(),
+ )
+
+
[email protected]("stream", [False, True], ids=["non_stream", "stream"])
+def test_enabled_gateway_matches_native_messages_route(enabled_gateway: Gateway, stream: bool) -> None:
+ identity: Final = "msg_gateway_" + ("stream" if stream else "json")
+ usage: Final = {"input_tokens": 6, "output_tokens": 1}
+ content: Final = ({"type": "text", "text": "PONG"},)
+ request_body: Final = {
+ **cc.claude_code_request(f"cache-bust-{identity}"),
+ "model": "",
+ "stream": stream,
+ }
+ expected_stream: Final = cc.message_stream(identity, _BACKEND, content, usage)
+ expected_provider_body: Final = {**request_body, "model": _BACKEND}
+ client_betas: Final = sorted(cc.CLI_BETA.split(","))
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert sorted(request.headers["anthropic-beta"].split(",")) == client_betas, request.headers
+ assert "authorization" not in request.headers, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_provider_body, request.body
+ if stream:
+ return Reply(chunks=expected_stream, content_type="text/event-stream")
+ return Reply(body=cc.message_reply(identity, _BACKEND, content, usage))
+
+ with enabled_gateway.scenario() as scenario, wire_server(respond) as wire:
+ model_a: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)
+ key: Final = scenario.key(models=[model_a])
+ expected_message: Final = _MESSAGE.validate_python(
+ {**_JSON_OBJECT.validate_json(cc.message_reply(identity, _BACKEND, content, usage)), "model": model_a}
+ )
+ expected_stream_events: Final = _expected_stream_events(expected_stream, model_a)
+ body: Final = {**request_body, "model": model_a}
+ headers: Final = _cli_bearer_headers(key)
+ gateway_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages?beta=true",
+ json=body,
+ headers=headers,
+ )
+ assert gateway_response.status_code == 200, gateway_response.text
+ gateway_requests: Final = wire.drain()
+ assert len(gateway_requests) == 1, gateway_requests
+
+ messages_response: Final = enabled_gateway.client.post(
+ "/v1/messages?beta=true",
+ json=body,
+ headers=headers,
+ )
+ assert messages_response.status_code == 200, messages_response.text
+ messages_requests: Final = wire.drain()
+ assert len(messages_requests) == 1, messages_requests
+ if stream:
+ gateway_events: Final = cc.sse_events(gateway_response.text)
+ messages_events: Final = cc.sse_events(messages_response.text)
+ assert gateway_events == messages_events, (gateway_response.text, messages_response.text)
+ assert gateway_events == expected_stream_events, (gateway_response.text, messages_response.text)
+ else:
+ gateway_message: Final = _MESSAGE.validate_json(gateway_response.content)
+ messages_message: Final = _MESSAGE.validate_json(messages_response.content)
+ assert gateway_message.model_dump(mode="json") == expected_message.model_dump(mode="json"), (
+ gateway_response.text,
+ )
+ assert messages_message.model_dump(mode="json") == expected_message.model_dump(mode="json"), (
+ messages_response.text,
+ )
+
+ (gateway_request,) = gateway_requests
+ (messages_request,) = messages_requests
+ assert gateway_request.method == messages_request.method == "POST"
+ assert gateway_request.target == messages_request.target == "/v1/messages"
+ assert gateway_request.headers["x-api-key"] == messages_request.headers["x-api-key"] == _API_KEY
+ assert (
+ gateway_request.headers["anthropic-version"]
+ == messages_request.headers["anthropic-version"]
+ == "2023-06-01"
+ )
+ assert gateway_request.headers["anthropic-beta"] == messages_request.headers["anthropic-beta"]
+ assert sorted(gateway_request.headers["anthropic-beta"].split(",")) == client_betas
+ assert _JSON_OBJECT.validate_json(gateway_request.body) == expected_provider_body, gateway_request.body
+ assert _JSON_OBJECT.validate_json(messages_request.body) == expected_provider_body, messages_request.body
+
+
+def test_enabled_gateway_count_tokens_alias_matches_native_count_tokens_route(enabled_gateway: Gateway) -> None:
+ messages: Final = [{"role": "user", "content": "Count this gateway request."}]
+ system: Final = [{"type": "text", "text": "Count the gateway message and tool."}]
+ tools: Final = [
+ {
+ "name": "lookup",
+ "description": "Look up a synthetic record.",
+ "input_schema": {"type": "object", "properties": {"record_id": {"type": "string"}}},
+ }
+ ]
+ expected_provider_body: Final = {"model": _BACKEND, "messages": messages, "system": system, "tools": tools}
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages/count_tokens", request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert request.headers["anthropic-beta"] == "token-counting-2024-11-01", request.headers
+ assert "authorization" not in request.headers, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_provider_body, request.body
+ return Reply(body=b'{"input_tokens": 41}')
+
+ with enabled_gateway.scenario() as scenario, wire_server(respond) as wire:
+ model: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)
+ restricted_model: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)
+ key: Final = scenario.key(models=[model])
+ body: Final = {"model": model, "messages": messages, "system": system, "tools": tools}
+ headers: Final = {**_cli_bearer_headers(key), "anthropic-beta": "token-counting-2024-11-01"}
+ gateway_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages/count_tokens?beta=true", json=body, headers=headers
+ )
+ assert gateway_response.status_code == 200, gateway_response.text
+ assert _JSON_OBJECT.validate_json(gateway_response.content) == {"input_tokens": 41}, gateway_response.text
+ native_response: Final = enabled_gateway.client.post(
+ "/v1/messages/count_tokens?beta=true", json=body, headers=headers
+ )
+ assert native_response.status_code == 200, native_response.text
+ assert native_response.content == gateway_response.content, (native_response.text, gateway_response.text)
+ assert tuple((request.method, request.target) for request in wire.drain()) == (
+ ("POST", "/v1/messages/count_tokens"),
+ ("POST", "/v1/messages/count_tokens"),
+ )
+
+ restricted_response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages/count_tokens?beta=true",
+ json={**body, "model": restricted_model},
+ headers=headers,
+ )
+ assert restricted_response.status_code == 403, restricted_response.text
+ assert _JSON_OBJECT.validate_json(restricted_response.content) == {
+ "error": {
+ "message": (
+ f"The requested model '{restricted_model}' is not available for this API key, or the model name "
+ "is invalid. Check the models available to you and try again."
+ ),
+ "type": "key_model_access_denied",
+ "param": "model",
+ "code": "403",
+ }
+ }, restricted_response.text
+ assert wire.drain() == ()
+
+
+def test_enabled_gateway_refuses_model_outside_virtual_key(enabled_gateway: Gateway) -> None:
+ result: Final = _restricted_model_responses(enabled_gateway)
+ expected_body: Final = {
+ "error": {
+ "message": (
+ f"The requested model '{result[4]}' is not available for this API key, or the model name is invalid. "
+ "Check the models available to you and try again."
+ ),
+ "type": "key_model_access_denied",
+ "param": "model",
+ "code": "403",
+ }
+ }
+ assert result[0] == result[2] == 403, (result[1], result[3])
+ assert _JSON_OBJECT.validate_json(result[1]) == expected_body, result[1]
+ assert _JSON_OBJECT.validate_json(result[3]) == expected_body, result[3]
+ assert result[1] == result[3], (result[1], result[3])
+ assert result[5] == ()
+
+
+def test_enabled_gateway_attributes_spend_to_virtual_key(enabled_gateway: Gateway) -> None:
+ gateway_identity: Final = f"msg_gateway_spend_gateway_{uuid.uuid4().hex}"
+ native_identity: Final = f"msg_gateway_spend_native_{uuid.uuid4().hex}"
+ response_ids: Final = iter((gateway_identity, native_identity))
+ content: Final = ({"type": "text", "text": "PONG"},)
+ usage: Final = {"input_tokens": 6, "output_tokens": 1}
+ request_body: Final = {**cc.claude_code_request("cache-bust-msg-gateway-spend"), "model": "", "stream": False}
+ expected_provider_body: Final = {**request_body, "model": _BACKEND}
+ client_betas: Final = sorted(cc.CLI_BETA.split(","))
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert sorted(request.headers["anthropic-beta"].split(",")) == client_betas, request.headers
+ assert "authorization" not in request.headers, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_provider_body, request.body
+ return Reply(body=cc.message_reply(next(response_ids), _BACKEND, content, usage))
+
+ with enabled_gateway.scenario() as scenario, wire_server(respond) as wire:
+ model: Final = scenario.model(model=f"anthropic/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)
+ key: Final = scenario.key(models=[model])
+ native_key: Final = scenario.key(models=[model])
+ body: Final = {**request_body, "model": model}
+ response: Final = enabled_gateway.client.post(
+ "/claude_code_gateway/v1/messages?beta=true",
+ json=body,
+ headers=_cli_bearer_headers(key),
+ )
+ assert response.status_code == 200, response.text
+ native_response: Final = enabled_gateway.client.post(
+ "/v1/messages?beta=true",
+ json=body,
+ headers=cc.cli_headers(native_key),
+ )
+ assert native_response.status_code == 200, native_response.text
+ requests: Final = wire.drain()
+ assert tuple(request.target for request in requests) == ("/v1/messages", "/v1/messages"), requests
+ gateway_key_hash: Final = hashlib.sha256(key.encode()).hexdigest()
+ native_key_hash: Final = hashlib.sha256(native_key.encode()).hexdigest()
+ spend_rows: Final = eventually(
+ lambda: (
+ read_rows(
+ 'SELECT api_key, model_group FROM "LiteLLM_SpendLogs" WHERE api_key=%s',
+ (gateway_key_hash,),
+ ),
+ read_rows(
+ 'SELECT api_key, model_group FROM "LiteLLM_SpendLogs" WHERE api_key=%s',
+ (native_key_hash,),
+ ),
+ ),
+ lambda rows: len(rows[0]) == 1 and len(rows[1]) == 1,
+ seconds=70,
+ return_last_on_timeout=True,
+ )
+ assert spend_rows == (
+ [{"api_key": gateway_key_hash, "model_group": model}],
+ [{"api_key": native_key_hash, "model_group": model}],
+ ), spend_rows
diff --git a/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_wire.py b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_wire.py
index 7e9c5be227a..dcfd1d19ac2 100644
--- a/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_wire.py
+++ b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_wire.py
@@ -1,12 +1,20 @@
+import base64
import json
import time
import uuid
from typing import Final
+import anthropic
import pytest
+from anthropic.types import Message
+from integration._support import claude_code as cc
from integration._support.client import Gateway, eventually, object_value
from integration._support.database import read_rows
from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_MESSAGE: Final = TypeAdapter(Message)
@pytest.mark.covers(
@@ -204,3 +212,563 @@ def test_anthropic_messages_slow_upstream_is_cut_off_at_the_deployment_request_t
assert response.status_code == 408, response.text
assert "Timeout" in response.json()["error"]["message"], response.text
assert eventually(wire.drain, lambda requests: len(requests) == 1, seconds=5, return_last_on_timeout=True)
+
+
[email protected]("stream", [False, True], ids=["non_stream", "stream"])
+def test_anthropic_messages_preserves_cli_beta_safeguards_and_result(gateway: Gateway, stream: bool) -> None:
+ identity: Final = "anthropic-safeguards-" + uuid.uuid4().hex
+ beta: Final = cc.CLI_BETA + ",made-up-future-beta-2099-01-01"
+ safeguards: Final = {"mode": "strict", "policies": ["sensitive-data"]}
+ safeguard_results: Final = {"status": "allowed", "policy": "sensitive-data"}
+ system: Final = [{"type": "text", "text": "Synthetic policy.", "cache_control": {"type": "ephemeral"}}]
+ tools: Final = [
+ {
+ "name": "lookup",
+ "description": "Look up a synthetic record.",
+ "input_schema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},
+ },
+ {
+ "name": "update",
+ "description": "Update a synthetic record.",
+ "input_schema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},
+ },
+ ]
+ response_body: Final = {
+ "id": identity,
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-6",
+ "content": [{"type": "text", "text": "Record checked."}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 6, "output_tokens": 3},
+ "safeguard_results": safeguard_results,
+ }
+ stream_reply: Final = (
+ cc.sse_frame(
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ **response_body,
+ "content": [],
+ "stop_reason": None,
+ "usage": {"input_tokens": 6, "output_tokens": 0},
+ },
+ },
+ ),
+ cc.sse_frame(
+ "content_block_start",
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ ),
+ cc.sse_frame(
+ "content_block_delta",
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Record checked."}},
+ ),
+ cc.sse_frame("content_block_stop", {"type": "content_block_stop", "index": 0}),
+ cc.sse_frame(
+ "message_delta",
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
+ "usage": {"output_tokens": 3},
+ },
+ ),
+ cc.sse_frame("message_stop", {"type": "message_stop"}),
+ )
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == "synthetic-anthropic-key", request.headers
+ assert sorted(request.headers["anthropic-beta"].split(",")) == sorted(beta.split(",")), request.headers
+ expected_body: Final = {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 32,
+ "messages": [{"role": "user", "content": "Check the synthetic record."}],
+ "system": system,
+ "tools": tools,
+ "metadata": {"user_id": cc.METADATA_USER_ID},
+ "safeguards": safeguards,
+ "stream": stream,
+ }
+ assert _JSON_OBJECT.validate_json(request.body) == expected_body, request.body
+ if not stream:
+ return Reply(body=json.dumps(response_body).encode())
+ return Reply(chunks=stream_reply, content_type="text/event-stream")
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="anthropic/claude-sonnet-4-6",
+ api_base=wire.url,
+ api_key="synthetic-anthropic-key",
+ )
+ client_body: Final = {
+ "model": model,
+ "max_tokens": 32,
+ "messages": [{"role": "user", "content": "Check the synthetic record."}],
+ "system": system,
+ "tools": tools,
+ "metadata": {"user_id": cc.METADATA_USER_ID},
+ "safeguards": safeguards,
+ "stream": stream,
+ }
+ response: Final = gateway.client.post(
+ "/v1/messages?beta=true",
+ json=client_body,
+ headers=cc.cli_headers(gateway.key, beta=beta),
+ )
+ assert response.status_code == 200, response.text
+ (sent,) = wire.drain()
+ assert sent.target == "/v1/messages", sent.target
+
+ if stream:
+ expected_stream_events: Final = tuple(
+ (
+ event,
+ {
+ **data,
+ **(
+ {
+ "message": {
+ **_JSON_OBJECT.validate_python(data["message"]),
+ "model": model,
+ }
+ }
+ if event == "message_start"
+ else {}
+ ),
+ },
+ )
+ for event, data in cc.sse_events(b"".join(stream_reply).decode())
+ )
+ assert cc.sse_events(response.text) == expected_stream_events, response.text
+
+ typed_message: Final = (
+ _MESSAGE.validate_python(
+ next(data["message"] for event, data in cc.sse_events(response.text) if event == "message_start")
+ )
+ if stream
+ else _MESSAGE.validate_json(response.content)
+ )
+ assert typed_message.model_extra == {"safeguard_results": safeguard_results}, response.text
+
+
+ ("status", "error_type", "error_class", "litellm_error"),
+ [
+ pytest.param(429, "rate_limit_error", anthropic.RateLimitError, "RateLimitError", id="rate_limit"),
+ pytest.param(400, "invalid_request_error", anthropic.BadRequestError, "BadRequestError", id="invalid_request"),
+ ],
+)
+def test_anthropic_messages_preserves_upstream_error_status_and_body(
+ gateway: Gateway,
+ status: int,
+ error_type: str,
+ error_class: type[anthropic.APIStatusError],
+ litellm_error: str,
+) -> None:
+ message: Final = f"synthetic {error_type}"
+ expected_error: Final = {"type": "error", "error": {"type": error_type, "message": message}}
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == "synthetic-anthropic-key", request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Trigger the scripted error."}],
+ "stream": False,
+ }, request.body
+ return Reply(
+ status=status,
+ body=json.dumps(expected_error).encode(),
+ headers={"retry-after": "7"} if status == 429 else {},
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="anthropic/claude-sonnet-4-6",
+ api_base=wire.url,
+ api_key="synthetic-anthropic-key",
+ )
+ with (
+ anthropic.Anthropic(
+ base_url=str(gateway.client.base_url),
+ api_key=gateway.key,
+ max_retries=0,
+ ) as client,
+ pytest.raises(error_class) as caught,
+ ):
+ client.messages.create(
+ model=model,
+ max_tokens=16,
+ messages=[{"role": "user", "content": "Trigger the scripted error."}],
+ )
+ assert caught.value.status_code == status, caught.value.response.text
+ assert caught.value.response.json() == {
+ "type": "error",
+ "error": {
+ "type": error_type,
+ "message": (
+ f"litellm.{litellm_error}: AnthropicException - {json.dumps(expected_error)}\n\n"
+ f"LiteLLM: model group '{model}' failed with the error above. No fallback was attempted."
+ ),
+ },
+ }, caught.value.response.text
+ assert len(wire.drain()) == 1
+
+
+def test_anthropic_messages_preserves_upstream_rate_limit_retry_after(gateway: Gateway) -> None:
+ pytest.skip("BUG: /v1/messages drops the upstream retry-after header on 429")
+
+ message: Final = "synthetic rate_limit_error"
+ upstream_error: Final = {
+ "type": "error",
+ "error": {"type": "rate_limit_error", "message": message},
+ }
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == "synthetic-anthropic-key", request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Trigger the scripted error."}],
+ "stream": False,
+ }, request.body
+ return Reply(status=429, body=json.dumps(upstream_error).encode(), headers={"retry-after": "7"})
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="anthropic/claude-sonnet-4-6",
+ api_base=wire.url,
+ api_key="synthetic-anthropic-key",
+ )
+ with (
+ anthropic.Anthropic(
+ base_url=str(gateway.client.base_url),
+ api_key=gateway.key,
+ max_retries=0,
+ ) as client,
+ pytest.raises(anthropic.RateLimitError) as caught,
+ ):
+ client.messages.create(
+ model=model,
+ max_tokens=16,
+ messages=[{"role": "user", "content": "Trigger the scripted error."}],
+ )
+ assert caught.value.status_code == 429, caught.value.response.text
+ assert caught.value.response.headers.get("retry-after") == "7", caught.value.response.text
+ assert caught.value.response.json() == {
+ "type": "error",
+ "error": {
+ "type": "rate_limit_error",
+ "message": (
+ f"litellm.RateLimitError: AnthropicException - {json.dumps(upstream_error)}\n\n"
+ f"LiteLLM: model group '{model}' failed with the error above. No fallback was attempted."
+ ),
+ },
+ }, caught.value.response.text
+ assert len(wire.drain()) == 1
+
+
+def test_anthropic_messages_preserves_upstream_overloaded_error(gateway: Gateway) -> None:
+ pytest.skip("BUG: /v1/messages maps an upstream 529 overloaded_error to HTTP 500")
+
+ upstream_error: Final = {
+ "type": "error",
+ "error": {"type": "overloaded_error", "message": "synthetic overloaded error"},
+ }
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == "synthetic-anthropic-key", request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Trigger the scripted overload."}],
+ "stream": False,
+ }, request.body
+ return Reply(status=529, body=json.dumps(upstream_error).encode())
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="anthropic/claude-sonnet-4-6",
+ api_base=wire.url,
+ api_key="synthetic-anthropic-key",
+ )
+ with (
+ anthropic.Anthropic(
+ base_url=str(gateway.client.base_url),
+ api_key=gateway.key,
+ max_retries=0,
+ ) as client,
+ pytest.raises(anthropic.InternalServerError) as caught,
+ ):
+ client.messages.create(
+ model=model,
+ max_tokens=16,
+ messages=[{"role": "user", "content": "Trigger the scripted overload."}],
+ )
+ assert caught.value.status_code == 529, caught.value.response.text
+ response_body: Final = _JSON_OBJECT.validate_json(caught.value.response.content)
+ assert response_body == upstream_error, caught.value.response.text
+ assert len(wire.drain()) == 1
+
+
+def test_anthropic_messages_stream_surfaces_upstream_error_event(gateway: Gateway) -> None:
+ error: Final = {
+ "type": "error",
+ "error": {"type": "overloaded_error", "message": "synthetic stream overload"},
+ }
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == "synthetic-anthropic-key", request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Trigger the scripted stream error."}],
+ "stream": True,
+ }, request.body
+ return Reply(
+ chunks=(
+ cc.sse_frame(
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_stream_error",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-6",
+ "content": [],
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": {"input_tokens": 5, "output_tokens": 0},
+ },
+ },
+ ),
+ cc.sse_frame("error", error),
+ ),
+ content_type="text/event-stream",
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="anthropic/claude-sonnet-4-6",
+ api_base=wire.url,
+ api_key="synthetic-anthropic-key",
+ )
+ response: Final = gateway.client.post(
+ "/v1/messages",
+ json={
+ "model": model,
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Trigger the scripted stream error."}],
+ "stream": True,
+ },
+ headers=cc.cli_headers(gateway.key),
+ )
+ assert response.status_code == 200, response.text
+ assert cc.sse_events(response.text) == (
+ (
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_stream_error",
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": {"input_tokens": 5, "output_tokens": 0},
+ },
+ },
+ ),
+ ("error", error),
+ ), response.text
+ assert len(wire.drain()) == 1
+
+
+def test_anthropic_messages_stream_ending_without_message_stop_surfaces_an_error_event(gateway: Gateway) -> None:
+ pytest.skip("BUG: /v1/messages relays an upstream stream that closes before message_stop as a clean 200")
+ message_start: Final = {
+ "type": "message_start",
+ "message": {
+ "id": "msg_stream_truncated",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-6",
+ "content": [],
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": {"input_tokens": 5, "output_tokens": 0},
+ },
+ }
+ block_start: Final = {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
+ block_delta: Final = {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Partial"}}
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == "synthetic-anthropic-key", request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Trigger the scripted truncated stream."}],
+ "stream": True,
+ }, request.body
+ return Reply(
+ chunks=(
+ cc.sse_frame("message_start", message_start),
+ cc.sse_frame("content_block_start", block_start),
+ cc.sse_frame("content_block_delta", block_delta),
+ ),
+ content_type="text/event-stream",
+ )
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="anthropic/claude-sonnet-4-6",
+ api_base=wire.url,
+ api_key="synthetic-anthropic-key",
+ )
+ response: Final = gateway.client.post(
+ "/v1/messages",
+ json={
+ "model": model,
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Trigger the scripted truncated stream."}],
+ "stream": True,
+ },
+ headers=cc.cli_headers(gateway.key),
+ )
+ assert response.status_code == 200, response.text
+ assert cc.sse_events(response.text) == (
+ ("message_start", {**message_start, "message": {**message_start["message"], "model": model}}),
+ ("content_block_start", block_start),
+ ("content_block_delta", block_delta),
+ (
+ "error",
+ {
+ "type": "error",
+ "error": {
+ "type": "api_error",
+ "message": "Provider stream ended before emitting a message_stop event; the response is "
+ "incomplete and any partial content (e.g. tool_use input JSON) may be truncated.",
+ },
+ },
+ ),
+ ), response.text
+ assert len(wire.drain()) == 1
+
+
+def test_anthropic_messages_preserves_image_document_and_tool_result_blocks(gateway: Gateway) -> None:
+ image_data: Final = base64.b64encode(b"synthetic png bytes").decode()
+ pdf_data: Final = base64.b64encode(b"%PDF-1.7 synthetic document").decode()
+ messages: Final = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Inspect these attachments."},
+ {
+ "type": "image",
+ "source": {"type": "base64", "media_type": "image/png", "data": image_data},
+ },
+ {"type": "image", "source": {"type": "url", "url": "https://example.invalid/synthetic.png"}},
+ {
+ "type": "document",
+ "source": {"type": "base64", "media_type": "application/pdf", "data": pdf_data},
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "lookup-one", "name": "lookup", "input": {"id": "one"}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "lookup-one",
+ "is_error": True,
+ "content": [
+ {"type": "text", "text": "Synthetic lookup failed."},
+ {
+ "type": "image",
+ "source": {"type": "base64", "media_type": "image/png", "data": image_data},
+ },
+ ],
+ }
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "lookup-two", "name": "lookup", "input": {"id": "two"}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": "lookup-two", "content": "Synthetic lookup succeeded."},
+ {"type": "text", "text": "Continue with the first result."},
+ ],
+ },
+ ]
+ content: Final = [
+ {"type": "text", "text": "The requested blocks were preserved."},
+ {"type": "tool_use", "id": "lookup-three", "name": "lookup", "input": {"id": "three"}},
+ {"type": "thinking", "thinking": "The history contains two tool calls.", "signature": "synthetic-signature"},
+ ]
+ expected_response: Final = {
+ "id": "msg_anthropic_blocks",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-6",
+ "content": content,
+ "stop_reason": "tool_use",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 20, "output_tokens": 12},
+ }
+ tools: Final = [
+ {
+ "name": "lookup",
+ "description": "Look up a synthetic record.",
+ "input_schema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},
+ }
+ ]
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/messages", request.target
+ assert request.headers["x-api-key"] == "synthetic-anthropic-key", request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == {
+ "model": "claude-sonnet-4-6",
+ "max_tokens": 128,
+ "messages": messages,
+ "stream": False,
+ "tools": tools,
+ }, request.body
+ return Reply(body=json.dumps(expected_response).encode())
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="anthropic/claude-sonnet-4-6",
+ api_base=wire.url,
+ api_key="synthetic-anthropic-key",
+ )
+ with anthropic.Anthropic(
+ base_url=str(gateway.client.base_url),
+ api_key=gateway.key,
+ max_retries=0,
+ ) as client:
+ response: Final = client.messages.create(
+ model=model,
+ max_tokens=128,
+ messages=messages,
+ tools=tools,
+ )
+ expected_message: Final = _MESSAGE.validate_python({**expected_response, "model": model})
+ assert response.model_dump(mode="json") == expected_message.model_dump(mode="json"), response
+ assert len(wire.drain()) == 1
diff --git a/tests/integration/providers/test_anthropic_skills_create_wire.py b/tests/integration/providers/test_anthropic_skills_create_wire.py
new file mode 100644
index 00000000000..1499c278ffc
--- /dev/null
+++ b/tests/integration/providers/test_anthropic_skills_create_wire.py
@@ -0,0 +1,69 @@
+import json
+from email.message import Message
+from email.parser import BytesParser
+from email.policy import HTTP
+from typing import Final
+
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+
+from litellm.types.llms.anthropic_skills import Skill
+
+_API_KEY: Final = "synthetic-anthropic-key"
+_TITLE: Final = "Synthetic Skill"
+_SKILL_MD: Final = b"---\nname: synthetic-skill\ndescription: A synthetic skill.\n---\nUse the helper.\n"
+_HELPER: Final = b"print('synthetic helper')\n"
+_UPSTREAM_SKILL: Final = {
+ "id": "skill_synthetic_01",
+ "type": "skill",
+ "display_title": _TITLE,
+ "latest_version": "1759178010641129",
+ "source": "custom",
+ "created_at": "2025-10-02T00:00:00Z",
+ "updated_at": "2025-10-02T00:00:00Z",
+}
+
+
+def _multipart_parts(request: Request) -> tuple[Message, ...]:
+ envelope: Final = f"content-type: {request.headers['content-type']}\r\n\r\n".encode() + request.body
+ parsed: Final = BytesParser(policy=HTTP).parsebytes(envelope)
+ assert parsed.is_multipart(), request.headers["content-type"]
+ return tuple(parsed.iter_parts())
+
+
+def _part_summary(part: Message) -> tuple[str, str | None, bytes]:
+ return (
+ str(part.get_param("name", header="content-disposition")),
+ part.get_filename(),
+ bytes(part.get_payload(decode=True)),
+ )
+
+
+def test_anthropic_skill_create_forwards_repeated_files_as_file_parts(gateway: Gateway) -> None:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/v1/skills", request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert request.headers["anthropic-beta"] == "skills-2025-10-02", request.headers
+ assert "authorization" not in request.headers, request.headers
+ assert tuple(_part_summary(part) for part in _multipart_parts(request)) == (
+ ("display_title", None, _TITLE.encode()),
+ ("files[]", "synthetic-skill/SKILL.md", _SKILL_MD),
+ ("files[]", "synthetic-skill/helper.py", _HELPER),
+ ), request.body
+ return Reply(body=json.dumps(_UPSTREAM_SKILL).encode())
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(model="anthropic/claude-sonnet-4-6", api_base=wire.url, api_key=_API_KEY)
+ response: Final = gateway.client.post(
+ "/v1/skills?beta=true",
+ data={"display_title": _TITLE},
+ files=[
+ ("files[]", ("synthetic-skill/SKILL.md", _SKILL_MD, "text/markdown")),
+ ("files[]", ("synthetic-skill/helper.py", _HELPER, "text/x-python")),
+ ],
+ headers={"Authorization": f"Bearer {gateway.key}", "x-litellm-model": model},
+ )
+ assert response.status_code == 200, response.text
+ assert Skill.model_validate_json(response.content) == Skill.model_validate(_UPSTREAM_SKILL), response.text
+ assert [(request.method, request.target) for request in wire.drain()] == [("POST", "/v1/skills")]
diff --git a/tests/integration/providers/test_azure_ai_claude_messages_wire.py b/tests/integration/providers/test_azure_ai_claude_messages_wire.py
new file mode 100644
index 00000000000..c150de7520b
--- /dev/null
+++ b/tests/integration/providers/test_azure_ai_claude_messages_wire.py
@@ -0,0 +1,323 @@
+from typing import Final
+
+import anthropic
+import pytest
+from anthropic.types import Message
+from integration._support import claude_code as cc
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+_BACKEND: Final = "claude-sonnet-4-6"
+_API_KEY: Final = "synthetic-azure-ai-key"
+_SUPPORTED_BETA: Final = "interleaved-thinking-2025-05-14"
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_MESSAGE: Final = TypeAdapter(Message)
+_MESSAGES: Final[list[JsonValue]] = [{"role": "user", "content": "Read the synthetic record."}]
+_SYSTEM: Final = [{"type": "text", "text": "Use the supplied tool when relevant."}]
+_TOOLS: Final[list[JsonValue]] = [
+ {
+ "name": "lookup",
+ "description": "Look up a synthetic record.",
+ "input_schema": {
+ "type": "object",
+ "properties": {"record_id": {"type": "string"}},
+ "required": ["record_id"],
+ },
+ }
+]
+_CONTENT: Final[tuple[dict[str, JsonValue], ...]] = ({"type": "text", "text": "The record is ready."},)
+_USAGE: Final[dict[str, JsonValue]] = {"input_tokens": 8, "output_tokens": 4}
+
+
+def _without_none(value: JsonValue) -> JsonValue:
+ if isinstance(value, dict):
+ return {key: _without_none(item) for key, item in value.items() if item is not None}
+ if isinstance(value, list):
+ return [_without_none(item) for item in value]
+ return value
+
+
[email protected]("base_suffix", ["", "/anthropic"], ids=["base", "anthropic_base"])
[email protected]("stream", [False, True], ids=["non_stream", "stream"])
+def test_azure_ai_claude_messages_preserves_target_auth_beta_and_typed_response(
+ gateway: Gateway, base_suffix: str, stream: bool
+) -> None:
+ identity: Final = f"msg_azure_claude_{base_suffix.strip('/') or 'base'}_{stream}"
+ api_path: Final = "/anthropic/v1/messages"
+ reply_body: Final = cc.message_reply(identity, _BACKEND, _CONTENT, _USAGE)
+ stream_reply: Final = cc.message_stream(identity, _BACKEND, _CONTENT, _USAGE)
+ request_body_template: Final = {
+ "max_tokens": 1024,
+ "messages": _MESSAGES,
+ "model": "",
+ "stream": stream,
+ "system": _SYSTEM,
+ "tools": _TOOLS,
+ }
+ expected_provider_body: Final = {**request_body_template, "model": _BACKEND}
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == api_path, request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert request.headers.get("anthropic-beta") is None, request.headers
+ assert "authorization" not in request.headers and "api-key" not in request.headers, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_provider_body, request.body
+ if stream:
+ return Reply(content_type="text/event-stream", chunks=stream_reply)
+ return Reply(body=reply_body)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"azure_ai/{_BACKEND}",
+ api_base=f"{wire.url}{base_suffix}",
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ with anthropic.Anthropic(
+ api_key=gateway.key,
+ base_url=str(gateway.client.base_url),
+ max_retries=0,
+ ) as client:
+ if stream:
+ stream_response: Final = client.messages.create(
+ model=model,
+ max_tokens=1024,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ stream=True,
+ extra_headers={"anthropic-beta": "made-up-future-beta-2099-01-01"},
+ )
+ events: Final = tuple(stream_response)
+ expected_events: Final = tuple(
+ _JSON_OBJECT.validate_python(
+ _without_none(
+ {
+ **data,
+ **(
+ {
+ "message": {
+ **_JSON_OBJECT.validate_python(data["message"]),
+ "model": model,
+ }
+ }
+ if event_name == "message_start"
+ else {}
+ ),
+ }
+ )
+ )
+ for event_name, data in cc.sse_events(b"".join(stream_reply).decode())
+ )
+ actual_events: Final = tuple(
+ _JSON_OBJECT.validate_python(event.model_dump(mode="json", exclude_none=True)) for event in events
+ )
+ assert actual_events == expected_events, actual_events
+ started_message: Final = next(event.message for event in events if event.type == "message_start")
+ assert started_message.id == identity and started_message.model == model, actual_events
+ else:
+ response: Final = client.messages.create(
+ model=model,
+ max_tokens=1024,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ stream=False,
+ extra_headers={"anthropic-beta": "made-up-future-beta-2099-01-01"},
+ )
+ parsed_message: Final = _MESSAGE.validate_python(response)
+ expected_message: Final = _MESSAGE.validate_python(
+ {**_JSON_OBJECT.validate_json(reply_body), "model": model}
+ )
+ assert parsed_message.model_dump(mode="json") == expected_message.model_dump(mode="json"), (response,)
+
+ requests: Final = wire.drain()
+ assert len(requests) == 1, requests
+ provider_request: Final = requests[0]
+ assert provider_request.method == "POST" and provider_request.target == api_path, provider_request.target
+ assert provider_request.headers["x-api-key"] == _API_KEY, provider_request.headers
+ assert provider_request.headers["anthropic-version"] == "2023-06-01", provider_request.headers
+ assert provider_request.headers.get("anthropic-beta") is None, provider_request.headers
+ assert "authorization" not in provider_request.headers and "api-key" not in provider_request.headers
+ assert _JSON_OBJECT.validate_json(provider_request.body) == expected_provider_body, provider_request.body
+
+
[email protected]("stream", [False, True], ids=["non_stream", "stream"])
+def test_azure_ai_claude_messages_filters_auto_injected_betas_by_azure_support(gateway: Gateway, stream: bool) -> None:
+ identity: Final = f"msg_azure_claude_beta_filter_{stream}"
+ api_path: Final = "/anthropic/v1/messages"
+ reply_body: Final = cc.message_reply(identity, _BACKEND, _CONTENT, _USAGE)
+ stream_reply: Final = cc.message_stream(identity, _BACKEND, _CONTENT, _USAGE)
+ output_config: Final = {
+ "format": {
+ "type": "json_schema",
+ "schema": {
+ "type": "object",
+ "properties": {"record_id": {"type": "string"}},
+ "required": ["record_id"],
+ },
+ }
+ }
+ context_management: Final = {"edits": [{"type": "compact_20260112"}]}
+ request_body_template: Final = {
+ "max_tokens": 1024,
+ "messages": _MESSAGES,
+ "model": "",
+ "stream": stream,
+ "system": _SYSTEM,
+ "tools": _TOOLS,
+ "output_config": output_config,
+ "context_management": context_management,
+ }
+ expected_provider_body: Final = {**request_body_template, "model": _BACKEND}
+ expected_beta: Final = "structured-outputs-2025-11-13"
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == api_path, request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert request.headers.get("anthropic-beta") == expected_beta, request.headers
+ assert "authorization" not in request.headers and "api-key" not in request.headers, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_provider_body, request.body
+ if stream:
+ return Reply(content_type="text/event-stream", chunks=stream_reply)
+ return Reply(body=reply_body)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"azure_ai/{_BACKEND}",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ with anthropic.Anthropic(
+ api_key=gateway.key,
+ base_url=str(gateway.client.base_url),
+ max_retries=0,
+ ) as client:
+ if stream:
+ stream_response: Final = client.messages.create(
+ model=model,
+ max_tokens=1024,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ stream=True,
+ output_config=output_config,
+ extra_body={"context_management": context_management},
+ )
+ events: Final = tuple(stream_response)
+ expected_events: Final = tuple(
+ _JSON_OBJECT.validate_python(
+ _without_none(
+ {
+ **data,
+ **(
+ {
+ "message": {
+ **_JSON_OBJECT.validate_python(data["message"]),
+ "model": model,
+ }
+ }
+ if event_name == "message_start"
+ else {}
+ ),
+ }
+ )
+ )
+ for event_name, data in cc.sse_events(b"".join(stream_reply).decode())
+ )
+ actual_events: Final = tuple(
+ _JSON_OBJECT.validate_python(event.model_dump(mode="json", exclude_none=True)) for event in events
+ )
+ assert actual_events == expected_events, actual_events
+ started_message: Final = next(event.message for event in events if event.type == "message_start")
+ assert started_message.id == identity and started_message.model == model, actual_events
+ else:
+ response: Final = client.messages.create(
+ model=model,
+ max_tokens=1024,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ stream=False,
+ output_config=output_config,
+ extra_body={"context_management": context_management},
+ )
+ parsed_message: Final = _MESSAGE.validate_python(response)
+ expected_message: Final = _MESSAGE.validate_python(
+ {**_JSON_OBJECT.validate_json(reply_body), "model": model}
+ )
+ assert parsed_message.model_dump(mode="json") == expected_message.model_dump(mode="json"), (response,)
+
+ requests: Final = wire.drain()
+ assert len(requests) == 1, requests
+ provider_request: Final = requests[0]
+ assert provider_request.method == "POST" and provider_request.target == api_path, provider_request.target
+ assert provider_request.headers["x-api-key"] == _API_KEY, provider_request.headers
+ assert provider_request.headers["anthropic-version"] == "2023-06-01", provider_request.headers
+ assert provider_request.headers.get("anthropic-beta") == expected_beta, provider_request.headers
+ assert "authorization" not in provider_request.headers and "api-key" not in provider_request.headers
+ assert _JSON_OBJECT.validate_json(provider_request.body) == expected_provider_body, provider_request.body
+
+
+def test_azure_ai_claude_messages_forwards_supported_beta(gateway: Gateway) -> None:
+ pytest.skip(f"BUG: Azure AI Claude drops the supported beta header {_SUPPORTED_BETA}")
+
+ identity: Final = "msg_azure_claude_supported_beta"
+ reply_body: Final = cc.message_reply(identity, _BACKEND, _CONTENT, _USAGE)
+ request_body: Final = {
+ "max_tokens": 1024,
+ "messages": _MESSAGES,
+ "model": "",
+ "stream": False,
+ "system": _SYSTEM,
+ "tools": _TOOLS,
+ }
+ expected_provider_body: Final = {**request_body, "model": _BACKEND}
+
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST" and request.target == "/anthropic/v1/messages", request.target
+ assert request.headers["x-api-key"] == _API_KEY, request.headers
+ assert request.headers["anthropic-version"] == "2023-06-01", request.headers
+ assert request.headers.get("anthropic-beta") == _SUPPORTED_BETA, request.headers
+ assert "authorization" not in request.headers and "api-key" not in request.headers, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_provider_body, request.body
+ return Reply(body=reply_body)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=f"azure_ai/{_BACKEND}",
+ api_base=wire.url,
+ api_key=_API_KEY,
+ num_retries=0,
+ )
+ with anthropic.Anthropic(
+ api_key=gateway.key,
+ base_url=str(gateway.client.base_url),
+ max_retries=0,
+ ) as client:
+ response: Final = client.messages.create(
+ model=model,
+ max_tokens=1024,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ stream=False,
+ extra_headers={"anthropic-beta": f"{_SUPPORTED_BETA},made-up-future-beta-2099-01-01"},
+ )
+ parsed_message: Final = _MESSAGE.validate_python(response)
+ expected_message: Final = _MESSAGE.validate_python(
+ {**_JSON_OBJECT.validate_json(reply_body), "model": model}
+ )
+ assert parsed_message.model_dump(mode="json") == expected_message.model_dump(mode="json"), response
+
+ requests: Final = wire.drain()
+ assert len(requests) == 1, requests
+ provider_request: Final = requests[0]
+ assert provider_request.method == "POST" and provider_request.target == "/anthropic/v1/messages"
+ assert provider_request.headers["x-api-key"] == _API_KEY, provider_request.headers
+ assert provider_request.headers.get("anthropic-beta") == _SUPPORTED_BETA, provider_request.headers
+ assert _JSON_OBJECT.validate_json(provider_request.body) == expected_provider_body, provider_request.body
diff --git a/tests/integration/providers/test_vertex_partner_messages_wire.py b/tests/integration/providers/test_vertex_partner_messages_wire.py
new file mode 100644
index 00000000000..63629e11939
--- /dev/null
+++ b/tests/integration/providers/test_vertex_partner_messages_wire.py
@@ -0,0 +1,193 @@
+import json
+from collections.abc import Callable
+from typing import Final
+from urllib.parse import parse_qs
+
+import anthropic
+import pytest
+from anthropic.types import Message
+from integration._support import claude_code as cc
+from integration._support.client import Gateway, Scenario
+from integration._support.vertex import service_account_json
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+_BACKEND: Final = "claude-sonnet-4-6"
+_PROJECT: Final = "scripted-project"
+_LOCATION: Final = "us-east5"
+_MODEL_TARGET: Final = (
+ f"/v1/projects/{_PROJECT}/locations/{_LOCATION}/publishers/anthropic/models/{_BACKEND}:rawPredict"
+)
+_STREAM_TARGET: Final = (
+ f"/v1/projects/{_PROJECT}/locations/{_LOCATION}/publishers/anthropic/models/{_BACKEND}:streamRawPredict?alt=sse"
+)
+_VERTEX_TOKEN: Final = "scripted-vertex-access-token"
+_SUPPORTED_BETA: Final = "context-management-2025-06-27"
+_BETA_HEADER: Final = f"{_SUPPORTED_BETA},made-up-future-beta-2099-01-01"
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_MESSAGE: Final = TypeAdapter(Message)
+_SYSTEM: Final[list[JsonValue]] = [{"type": "text", "text": "Answer briefly and use the supplied tool when relevant."}]
+_MESSAGES: Final[list[JsonValue]] = [{"role": "user", "content": "Look up a synthetic record."}]
+_TOOLS: Final[list[JsonValue]] = [
+ {
+ "name": "lookup",
+ "description": "Look up a synthetic record.",
+ "input_schema": {
+ "type": "object",
+ "properties": {"record_id": {"type": "string"}},
+ "required": ["record_id"],
+ },
+ }
+]
+_THINKING: Final[dict[str, JsonValue]] = {"type": "enabled", "budget_tokens": 1024}
+_CONTENT: Final[tuple[dict[str, JsonValue], ...]] = ({"type": "text", "text": "The record is ready."},)
+_USAGE: Final[dict[str, JsonValue]] = {"input_tokens": 8, "output_tokens": 4}
+
+
+def _without_none(value: JsonValue) -> JsonValue:
+ if isinstance(value, dict):
+ return {key: _without_none(item) for key, item in value.items() if item is not None}
+ if isinstance(value, list):
+ return [_without_none(item) for item in value]
+ return value
+
+
+def _deployment(scenario: Scenario, api_base: str) -> str:
+ return scenario.model(
+ model=f"vertex_ai/{_BACKEND}",
+ api_base=api_base,
+ api_key=None,
+ vertex_project=_PROJECT,
+ vertex_location=_LOCATION,
+ vertex_credentials=service_account_json(_PROJECT, api_base),
+ num_retries=0,
+ )
+
+
+def _peer(
+ expected_body: dict[str, JsonValue],
+ target: str,
+ reply_body: bytes,
+ stream_reply: tuple[bytes, ...],
+) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ if request.target == "/_oauth/token":
+ form: Final = parse_qs(request.body.decode())
+ assert request.method == "POST", request.method
+ assert request.headers["content-type"] == "application/x-www-form-urlencoded", request.headers
+ assert set(form) == {"assertion", "grant_type"}, form
+ assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"], form
+ assert form["assertion"], form
+ return Reply(
+ body=json.dumps({"access_token": _VERTEX_TOKEN, "token_type": "Bearer", "expires_in": 3600}).encode()
+ )
+
+ assert request.method == "POST" and request.target == target, request.target
+ assert request.headers["authorization"] == f"Bearer {_VERTEX_TOKEN}", request.headers
+ assert request.headers["anthropic-beta"] == _SUPPORTED_BETA, request.headers
+ assert _JSON_OBJECT.validate_json(request.body) == expected_body, request.body
+ if target == _STREAM_TARGET:
+ return Reply(content_type="text/event-stream", chunks=stream_reply)
+ return Reply(body=reply_body)
+
+ return respond
+
+
[email protected]("stream", [False, True], ids=["non_stream", "stream"])
+def test_vertex_partner_messages_uses_raw_predict_contract_and_typed_response(gateway: Gateway, stream: bool) -> None:
+ identity: Final = f"msg_vertex_partner_{stream}"
+ reply_body: Final = cc.message_reply(identity, _BACKEND, _CONTENT, _USAGE)
+ stream_reply: Final = cc.message_stream(identity, _BACKEND, _CONTENT, _USAGE)
+
+ with gateway.scenario() as scenario:
+ with wire_server(
+ _peer(
+ {
+ "max_tokens": 1024,
+ "messages": _MESSAGES,
+ "system": _SYSTEM,
+ "tools": _TOOLS,
+ "thinking": _THINKING,
+ "stream": stream,
+ "anthropic_version": "vertex-2023-10-16",
+ },
+ _STREAM_TARGET if stream else _MODEL_TARGET,
+ reply_body,
+ stream_reply,
+ )
+ ) as wire:
+ model: Final = _deployment(scenario, wire.url)
+ with anthropic.Anthropic(
+ api_key=gateway.key,
+ base_url=str(gateway.client.base_url),
+ max_retries=0,
+ ) as client:
+ if stream:
+ stream_response: Final = client.messages.create(
+ model=model,
+ max_tokens=1024,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ thinking=_THINKING,
+ stream=True,
+ extra_headers={"anthropic-beta": _BETA_HEADER},
+ )
+ events: Final = tuple(stream_response)
+ expected_events: Final = tuple(
+ _JSON_OBJECT.validate_python(
+ _without_none(
+ {
+ **data,
+ **(
+ {
+ "message": {
+ **_JSON_OBJECT.validate_python(data["message"]),
+ "model": model,
+ }
+ }
+ if event_name == "message_start"
+ else {}
+ ),
+ }
+ )
+ )
+ for event_name, data in cc.sse_events(b"".join(stream_reply).decode())
+ )
+ actual_events: Final = tuple(
+ _JSON_OBJECT.validate_python(event.model_dump(mode="json", exclude_none=True))
+ for event in events
+ )
+ assert actual_events == expected_events, actual_events
+ started_message: Final = next(event.message for event in events if event.type == "message_start")
+ assert started_message.id == identity and started_message.model == model, actual_events
+ else:
+ response: Final = client.messages.create(
+ model=model,
+ max_tokens=1024,
+ messages=_MESSAGES,
+ system=_SYSTEM,
+ tools=_TOOLS,
+ thinking=_THINKING,
+ stream=False,
+ extra_headers={"anthropic-beta": _BETA_HEADER},
+ )
+ parsed_message: Final = _MESSAGE.validate_python(response)
+ expected_message: Final = _MESSAGE.validate_python(
+ {**_JSON_OBJECT.validate_json(reply_body), "model": model}
+ )
+ assert parsed_message.model_dump(mode="json") == expected_message.model_dump(mode="json"), (
+ response,
+ )
+
+ requests: Final = wire.drain()
+ assert tuple(request.target for request in requests) == (
+ "/_oauth/token",
+ _STREAM_TARGET if stream else _MODEL_TARGET,
+ ), requests
+ token_request: Final = requests[0]
+ assert token_request.method == "POST", token_request
+ assert token_request.headers["content-type"] == "application/x-www-form-urlencoded", token_request.headers
+ model_request: Final = requests[1]
+ assert model_request.method == "POST", model_request
+ assert model_request.headers["authorization"] == f"Bearer {_VERTEX_TOKEN}", model_request.headers