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]

Merge branch 'main' into litellm_e2e_provider_sdk_clients

mateo-berri98ed5939b143
diff --cc pyproject.toml
index f152a6a73cd,62ce4b4fd61..20240425c22
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -198,7 -222,8 +222,9 @@@ e2e-dev =
"playwright==1.61.0",
"websockets>=15.0.1,<16.0",
"locust==2.45.0",
+ "anthropic==0.84.0",
+ "psutil==7.2.2",
+ "mcp>=1.28.1,<2.0",
]
proxy-dev = [
"prisma==0.11.0",
diff --cc tests/e2e/CONTRIBUTING.md
index e542c123988,53a05931ca7..d0d01562c0b
--- a/tests/e2e/CONTRIBUTING.md
+++ b/tests/e2e/CONTRIBUTING.md
@@@ -35,10 -43,42 +43,42 @@@ The suites run against a live proxy, s
curl -fs http://localhost:4000/health/liveliness
```
+ The tests reach Keycloak at `E2E_KEYCLOAK_URL` (default `http://127.0.0.1:8480`) and provision their identities through its admin API, so they also need `E2E_KEYCLOAK_ADMIN_USER` and `E2E_KEYCLOAK_ADMIN_PASSWORD` (`admin` / `admin` for the throwaway container above; the deployed stacks take theirs from a secret). JWT auth is an enterprise feature, so the proxy needs `LITELLM_LICENSE` in its environment, and its config needs the JWT block below. `enable_jwt_auth` only routes bearer tokens with three dot-separated segments into the JWT path, so `sk-` virtual keys and the master key keep working for every other suite. `proxy_batch_write_at` is lowered so the JWT spend-attribution test sees its row well inside the poll deadline:
+
+ ```yaml
+ general_settings:
+ proxy_batch_write_at: 5
+ enable_jwt_auth: true
+ litellm_jwtauth:
+ user_id_jwt_field: sub
+ user_email_jwt_field: email
+ team_ids_jwt_field: groups
+ user_id_upsert: true
+ ```
+
+ Set `JWT_ISSUER` to the exact realm URL used by the test runner and `JWT_AUDIENCE=litellm-e2e`. The realm explicitly maps this audience, `sub`, `email`, and `groups`; the proxy fetches real signing keys from its JWKS endpoint. The rejection tests obtain signed tokens with a different audience or issuer and verify the corresponding rejection reason. The issuer test uses a different HTTP Host when requesting a token from the isolated, dynamically named test IdP.
+
+ Keycloak's password grant is a test-only provisioning shortcut, not a production login recommendation. The `litellm-e2e-admin` client adds the proxy's admin scope; the normal client does not. Never reuse this permissive realm outside an isolated test stack.
+
+ Management tests can bind a credential once with `client.with_caller(Caller(...))`; direct calls, delegated helpers and replica read-backs then retain that caller. Explicit `caller_key` arguments override the binding. Keep the original master-backed client for bootstrap and cleanup. `actor_factory` lazily provisions database roles and tenant memberships, with `database_role` tokens carrying no groups and `group_scoped` actors retaining the existing team route gate. Token minting is explicit through `actor.mint_caller(idp)`. The factory runs requests without backend retries and reports cleanup failures. `coverage_registry/management_cases.py` records exact canary nodes and non-secret actor labels; the CI execution assertion rejects a missing or skipped actor row
+
+ For the opt-in browser profile, start the existing IdP first, then run `.github/e2e-stack/oidc-profile.sh "$PROXY_BASE_URL" <server-command>`. The wrapper creates a confidential client with an exact `/sso/callback` redirect and S256 PKCE, passes the client secret only through the child process environment, and removes the client on exit. It uses the existing generic OIDC handler with `GENERIC_USER_ID_ATTRIBUTE=sub`. Preserve the IdP's PostgreSQL data across restarts
+
+ `tests/e2e/ui/playwright.oidc.config.ts` uses an already running OIDC stack and separate storage/output files. Supply `E2E_OIDC_UI_URL`, `JWT_ISSUER`, `E2E_OIDC_USERNAME` and `E2E_OIDC_PASSWORD` for a seeded actor. Its setup follows the real login and callback path. The current Python canary qualifies browser-client configuration and token/userinfo identity mapping; browser journey specs under `ui/oidc/` are a separate coverage step
+
+ Every successful IdP create immediately registers cleanup, including partial setup failures. Cleanup failures emit warnings. Tokens are minted on demand, and the expiration test waits relative to the token's actual `exp` with a bounded clock-drift check. To check first-attempt behavior locally, run both files with `--reruns 0`:
+
+ ```bash
+ E2E_KEYCLOAK_ADMIN_USER=admin E2E_KEYCLOAK_ADMIN_PASSWORD=admin \
+ uv run pytest tests/e2e/other/test_jwt_auth_e2e.py tests/e2e/management/test_jwt_management_e2e.py --reruns 0 -v
+ ```
+
+ Buildkite runs this suite against a Keycloak deployed beside the ephemeral stack by project-releaser. It fetches the realm from the test-runner revision even when it reuses a gateway image from another commit. The GitHub Actions changed-test stack starts the same digest-pinned Keycloak through `.github/e2e-stack/start-idp.sh`, imports the checked-out realm, and exports the IdP URL and credentials in `stack.env`. Both runners configure issuer/audience validation and store the realm, keys and users in a separate schema in the stack's PostgreSQL, so replacing Keycloak preserves token validity. Both wait for realm discovery before running tests. Losing the whole ephemeral database invalidates the stack. Keycloak skips imports into an existing realm, so changes to the realm export require a fresh stack (or deliberately replacing the local data volume). A stack without it fails the JWT tests rather than skipping them
+
-4. Run a suite against it; the harness reads `LITELLM_PROXY_URL` (default `http://localhost:4000`):
+4. Run a suite against it; the harness reads `LITELLM_PROXY_URL` (default `http://localhost:4000`). The suites' client dependencies (the provider SDKs, websockets) live in the `e2e-dev` dependency group; `make bootstrap` installs it, and naming the group on the run keeps the command working from any environment state:
```bash
- uv run pytest tests/e2e/llm_translation/ -v
+ uv run --group e2e-dev pytest tests/e2e/llm_translation/ -v
```
The browser tests in the `management/` suite drive the dashboard the proxy serves at `/ui` through playwright, an optional dependency behind `importorskip` (the suite's API tests run without it). It lives in the `e2e-dev` dependency group; install it along with its browser:
diff --cc tests/e2e/llm_translation/test_audio_speech_e2e.py
index 859292ecc7b,784007ec789..c3b6fddb632
--- a/tests/e2e/llm_translation/test_audio_speech_e2e.py
+++ b/tests/e2e/llm_translation/test_audio_speech_e2e.py
@@@ -1,81 -1,130 +1,141 @@@
"""Live e2e: POST /v1/audio/speech returns audio, non-streamed and streamed.
- Both calls go through the real OpenAI SDK (LIT-4577). The non-streamed call
- asserts an audio (not JSON) body. The streamed call consumes the response the
- way a player would and asserts customer-observable streaming: chunked transfer
- encoding (a buffered body would carry a content-length) with non-zero audio
- bytes.
-The non-streamed call asserts an audio (not JSON) body. The streamed call consumes
-the response the way a player would and asserts customer-observable streaming:
-chunked transfer encoding (a buffered body would carry a content-length) with
-non-zero audio bytes.
++Both positive calls go through the real OpenAI SDK (LIT-4577). The non-streamed
++call asserts an audio (not JSON) body. The streamed call consumes the response
++the way a player would and asserts customer-observable streaming: chunked
++transfer encoding (a buffered body would carry a content-length) with non-zero
++audio bytes. The malformed-body negatives stay on the shared transport because
++the SDK refuses to send a request missing its required fields.
"""
from __future__ import annotations
import pytest
-
from e2e_config import unique_marker
-from e2e_http import assert_client_error, require_successful_call
-from endpoints_client import EndpointsClient
++from e2e_http import assert_client_error
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
+from proxy_client import ProxyClient
+ from pydantic import BaseModel
+from sdk_clients import SdkClients, response_header
pytestmark = pytest.mark.e2e
- def _register(proxy: ProxyClient, resources: ResourceManager, prefix: str) -> str:
- model = f"{prefix}-{unique_marker()}"
+ class _OptionalSpeechBody(BaseModel):
+ model: str | None = None
+ input: str | None = None
+ voice: str | None = None
+
+
-def _register_tts(
- endpoints_client: EndpointsClient, resources: ResourceManager
-) -> tuple[str, str]:
++def _register_tts(proxy: ProxyClient, resources: ResourceManager) -> tuple[str, str]:
+ model = f"e2e-speech-{unique_marker()}"
- model_id = endpoints_client.create_model(
+ model_id = proxy.create_model(
model,
LiteLLMParamsBody(model="openai/gpt-4o-mini-tts", api_key="os.environ/OPENAI_API_KEY"),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
+ resources.defer(lambda: proxy.delete_model(model_id))
- return model
+ return model, resources.key()
class TestAudioSpeech:
@pytest.mark.covers("llm.audio_speech.openai.basic.nonstream.works")
def test_audio_speech_returns_audio(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = _register(proxy, resources, "e2e-speech")
- client = sdk.openai(resources.key())
- model, key = _register_tts(endpoints_client, resources)
- result = endpoints_client.audio_speech(key, model, "Hello!")
- require_successful_call(result)
- assert "audio" in (result.content_type or ""), (
- f"/audio/speech content-type is not audio: {result.content_type!r}"
++ model, key = _register_tts(proxy, resources)
++ client = sdk.openai(key)
+
+ response = client.audio.speech.with_raw_response.create(
+ model=model, voice="alloy", input="Hello!"
+ )
+ content_type = response_header(response.headers, "content-type")
+ assert "audio" in (content_type or ""), (
+ f"/audio/speech content-type is not audio: {content_type!r}"
)
- assert result.body, "/audio/speech returned an empty body"
+ assert response.content, "/audio/speech returned an empty body"
@pytest.mark.covers("llm.audio_speech.openai.basic.stream.works")
def test_audio_speech_streams_audio_chunks(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = _register(proxy, resources, "e2e-speech-stream")
- client = sdk.openai(resources.key())
- model, key = _register_tts(endpoints_client, resources)
- result = endpoints_client.audio_speech_stream(
- key,
- model,
- "Streaming speech should arrive in several audio chunks so a client can "
- "begin playback well before the whole clip has finished generating.",
- )
- assert result.ok, (
- f"/audio/speech stream failed (status {result.status_code}); body={result.error_body}"
- )
- assert "audio" in (result.content_type or ""), (
- f"/audio/speech content-type is not audio: {result.content_type!r}"
++ model, key = _register_tts(proxy, resources)
++ client = sdk.openai(key)
+
+ with client.audio.speech.with_streaming_response.create(
+ model=model,
+ voice="alloy",
+ input=(
+ "Streaming speech should arrive in several audio chunks so a client can "
+ "begin playback well before the whole clip has finished generating."
+ ),
+ ) as response:
+ content_type = response_header(response.headers, "content-type")
+ transfer_encoding = response_header(response.headers, "transfer-encoding")
+ content_length = response_header(response.headers, "content-length")
+ total_bytes = sum(len(chunk) for chunk in response.iter_bytes(chunk_size=8192))
+
+ assert "audio" in (content_type or ""), (
+ f"/audio/speech content-type is not audio: {content_type!r}"
)
- assert result.chunked, (
- f"/audio/speech did not stream: transfer-encoding={result.transfer_encoding!r}, "
- f"content-length={result.content_length!r} (a buffered body is not a stream)"
+ assert "chunked" in (transfer_encoding or ""), (
+ f"/audio/speech did not stream: transfer-encoding={transfer_encoding!r}, "
+ f"content-length={content_length!r} (a buffered body is not a stream)"
)
- assert result.content_length is None, (
- f"/audio/speech advertised content-length={result.content_length!r} on a "
+ assert content_length is None, (
+ f"/audio/speech advertised content-length={content_length!r} on a "
f"streamed response (a buffered body is not a stream)"
)
- assert result.total_bytes > 0, "/audio/speech stream returned no audio bytes"
+ assert total_bytes > 0, "/audio/speech stream returned no audio bytes"
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/audio/speech 500s on missing input instead of 400")
+ @pytest.mark.covers("llm.audio_speech.openai.input_validation.nonstream.works")
+ def test_missing_input_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
- model, key = _register_tts(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ model, key = _register_tts(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/audio/speech",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalSpeechBody(model=model, voice="alloy"),
+ )
+ assert_client_error(result, "speech missing input")
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/audio/speech 500s on missing model instead of 400")
+ @pytest.mark.covers("llm.audio_speech.openai.input_validation.nonstream.works")
+ def test_missing_model_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
- _, key = _register_tts(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ _, key = _register_tts(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/audio/speech",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalSpeechBody(input="hello", voice="alloy"),
+ )
+ assert_client_error(result, "speech missing model")
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/audio/speech 500s on invalid voice instead of surfacing the provider 4xx")
+ @pytest.mark.covers("llm.audio_speech.openai.input_validation.nonstream.works")
+ def test_invalid_voice_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
- model, key = _register_tts(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ model, key = _register_tts(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/audio/speech",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalSpeechBody(model=model, input="hello", voice="invalid_voice_xyz"),
+ )
+ assert_client_error(result, "speech invalid voice")
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/audio/speech 500s on empty input instead of surfacing the provider 4xx")
+ @pytest.mark.covers("llm.audio_speech.openai.input_validation.nonstream.works")
+ def test_empty_input_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
- model, key = _register_tts(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ model, key = _register_tts(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/audio/speech",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalSpeechBody(model=model, input="", voice="alloy"),
+ )
+ assert_client_error(result, "speech empty input")
diff --cc tests/e2e/llm_translation/test_audio_transcriptions_e2e.py
index 617192f88c7,735f1a4a703..0ef73653835
--- a/tests/e2e/llm_translation/test_audio_transcriptions_e2e.py
+++ b/tests/e2e/llm_translation/test_audio_transcriptions_e2e.py
@@@ -1,22 -1,26 +1,28 @@@
- """Live e2e: POST /v1/audio/transcriptions turns speech into text.
+ """Live e2e: POST /v1/audio/transcriptions turns speech into text (vendor §9.7 / LIT-4778).
Registers an OpenAI speech-to-text deployment at runtime and uploads a spoken
-weather question (the realtime suite's 24kHz WAV fixture) as multipart, asserting
-the returned transcript is non-empty and mentions the word it was asked about.
-Also pins missing file/model negatives. A model-less request comes back as one of
-two 400s depending on whether any wildcard deployment happens to be registered on
-the shared proxy, so the assertion accepts either phrasing and holds both to naming
-the model as the problem.
+weather question (the realtime suite's 24kHz WAV fixture) through the real
+OpenAI SDK (LIT-4577), asserting the returned transcript is non-empty and
- mentions the word it was asked about.
++mentions the word it was asked about. Also pins missing file/model negatives on
++the shared multipart transport, since the SDK refuses to send them. A model-less
++request comes back as one of two 400s depending on whether any wildcard
++deployment happens to be registered on the shared proxy, so the assertion
++accepts either phrasing and holds both to naming the model as the problem.
"""
from __future__ import annotations
from pathlib import Path
+ from typing import Final
import pytest
-
from e2e_config import unique_marker
-from e2e_http import UnknownApiError, unwrap
-from endpoints_client import EndpointsClient, TranscriptionForm, TranscriptionResult
++from e2e_http import UnknownApiError
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
+from proxy_client import ProxyClient
+ from pydantic import BaseModel
+from sdk_clients import SdkClients
pytestmark = pytest.mark.e2e
@@@ -24,27 -28,90 +30,92 @@@ WEATHER_WAV =
Path(__file__).resolve().parent / "realtime" / "fixtures" / "weather_question_24k.wav"
)
+ MISSING_MODEL_PHRASES: Final = ("model=none", "invalid model", "model is required")
+
+
+ class _OptionalTranscriptionForm(BaseModel):
+ model: str | None = None
+ response_format: str = "json"
+
+
-def _register(
- endpoints_client: EndpointsClient, resources: ResourceManager
-) -> tuple[str, str]:
++class _TranscriptionResult(BaseModel):
++ text: str = ""
++
++
++def _register(proxy: ProxyClient, resources: ResourceManager) -> tuple[str, str]:
+ model = f"e2e-transcribe-{unique_marker()}"
- model_id = endpoints_client.create_model(
++ model_id = proxy.create_model(
+ model,
+ LiteLLMParamsBody(
+ model="openai/gpt-4o-mini-transcribe", api_key="os.environ/OPENAI_API_KEY"
+ ),
+ )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
++ resources.defer(lambda: proxy.delete_model(model_id))
+ return model, resources.key()
+
class TestAudioTranscriptions:
@pytest.mark.covers("llm.audio_transcriptions.openai.basic.nonstream.works")
def test_audio_transcriptions_returns_text(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-transcribe-{unique_marker()}"
- model_id = proxy.create_model(
- model,
- LiteLLMParamsBody(
- model="openai/gpt-4o-mini-transcribe", api_key="os.environ/OPENAI_API_KEY"
- ),
- )
- resources.defer(lambda: proxy.delete_model(model_id))
- client = sdk.openai(resources.key())
- model, key = _register(endpoints_client, resources)
- result = unwrap(
- endpoints_client.transcribe(
- key, model, filename=WEATHER_WAV.name, content=WEATHER_WAV.read_bytes()
- )
++ model, key = _register(proxy, resources)
++ client = sdk.openai(key)
+
+ transcription = client.audio.transcriptions.create(
+ model=model, file=(WEATHER_WAV.name, WEATHER_WAV.read_bytes(), "audio/wav")
)
- text = result.text.strip()
+ text = transcription.text.strip()
assert text, "/audio/transcriptions returned an empty transcript"
assert "weather" in text.lower(), (
f"transcript of a spoken weather question does not mention weather: {text!r}"
)
+
+ @pytest.mark.covers("llm.audio_transcriptions.openai.input_validation.nonstream.works")
+ def test_missing_file_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
- model, key = _register(endpoints_client, resources)
- result = endpoints_client.proxy.transport.upload(
++ model, key = _register(proxy, resources)
++ result = proxy.transport.upload(
+ "/v1/audio/transcriptions",
- headers=endpoints_client.proxy.transport.bearer(key),
- form=TranscriptionForm(model=model),
++ headers=proxy.transport.bearer(key),
++ form=_OptionalTranscriptionForm(model=model),
+ filename="empty.wav",
+ content=b"",
+ file_content_type="audio/wav",
- response_type=TranscriptionResult,
++ response_type=_TranscriptionResult,
+ )
+ match result:
+ case UnknownApiError(status_code=400, body=body):
+ assert "OpenAIException" in body, (
+ f"the rejection must relay the provider's own error rather than a "
+ f"litellm-internal failure that hides why the upload was refused: {body[:300]}"
+ )
+ assert "invalid_request_error" in body, (
+ f"an unusable upload must be typed as a client input error: {body[:300]}"
+ )
+ case other:
+ pytest.fail(f"empty audio expected a file-specific 400, got {other!r}")
+
+ @pytest.mark.covers("llm.audio_transcriptions.openai.input_validation.nonstream.works")
+ def test_missing_model_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
- _, key = _register(endpoints_client, resources)
- result = endpoints_client.proxy.transport.upload(
++ _, key = _register(proxy, resources)
++ result = proxy.transport.upload(
+ "/v1/audio/transcriptions",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ form=_OptionalTranscriptionForm(),
+ filename=WEATHER_WAV.name,
+ content=WEATHER_WAV.read_bytes(),
+ file_content_type="audio/wav",
- response_type=TranscriptionResult,
++ response_type=_TranscriptionResult,
+ )
+ match result:
+ case UnknownApiError(status_code=400, body=body):
+ lowered: Final = body.lower()
+ assert any(phrase in lowered for phrase in MISSING_MODEL_PHRASES), (
+ f"missing model error must name the model as the problem: {body[:300]}"
+ )
+ case other:
+ pytest.fail(f"missing model expected a model-specific 400, got {other!r}")
diff --cc tests/e2e/llm_translation/test_bedrock_web_search_server_tool_e2e.py
index 00000000000,43461239e5f..d44e9ba43f7
mode 000000,100644..100644
--- a/tests/e2e/llm_translation/test_bedrock_web_search_server_tool_e2e.py
+++ b/tests/e2e/llm_translation/test_bedrock_web_search_server_tool_e2e.py
@@@ -1,0 -1,108 +1,98 @@@
+ """Live e2e: the Anthropic web_search server tool over Bedrock Invoke.
+
+ Bedrock hosts none of Anthropic's ``web_search_*`` server tools, so a
+ ``/v1/messages`` request carrying one is rejected outright with
+ 400 "The provided request is not valid" if it reaches AWS unchanged. What makes
+ it work is web-search interception: the hooks rewrite the native tool into
+ LiteLLM's own search tool before the upstream call, Bedrock calls that tool, the
+ gateway runs the search, and the agentic loop feeds the results back for the
+ model to synthesize. The response is then rebuilt in the native shape, so a
+ client's citations panel sees ``server_tool_use`` and ``web_search_tool_result``
+ exactly as it would from Anthropic direct.
+
+ This cell pins that whole path. Nothing else covers it: the ``web_search`` cells
+ in the Claude Code compat matrix drive the CLI's *client-side* ``WebSearch``
+ tool, an ordinary custom tool the CLI executes and feeds back as a
+ ``tool_result``, and the CLI never emits a ``web_search_20250305`` definition.
+
+ Prerequisites beyond AWS credentials: the proxy config must switch interception
+ on and declare a search backend. The callback entry is load-bearing; the params
+ block alone does not activate it.
+
+ litellm_settings:
+ callbacks: ["websearch_interception"]
+ websearch_interception_params:
+ enabled_providers: ["bedrock"]
+ search_tool_name: e2e-search
+ search_tools:
+ - search_tool_name: e2e-search
+ litellm_params:
+ search_provider: searxng
+ api_base: http://127.0.0.1:8391
+ """
+
+ from __future__ import annotations
+
+ import pytest
-
++from anthropic.types import WebSearchTool20250305Param
+ from e2e_config import unique_marker
-from e2e_http import unwrap
-from endpoints_client import EndpointsClient
+ from lifecycle import ResourceManager
-from models import (
- AnthropicMessagesBody,
- AnthropicWebSearchTool,
- ChatMessage,
- LiteLLMParamsBody,
-)
++from models import LiteLLMParamsBody
++from proxy_client import ProxyClient
++from sdk_clients import SdkClients
+
+ pytestmark = pytest.mark.e2e
+
+ BEDROCK_INVOKE_BACKEND = "bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0"
+
-WEB_SEARCH_TOOL = AnthropicWebSearchTool(
- type="web_search_20250305",
- name="web_search",
- max_uses=3,
-)
++WEB_SEARCH_TOOL: WebSearchTool20250305Param = {
++ "type": "web_search_20250305",
++ "name": "web_search",
++ "max_uses": 3,
++}
+
+ SEARCH_PROMPT = "Use web search to tell me one recent news headline about Anthropic."
+
+
+ class TestBedrockWebSearchServerTool:
+ @pytest.mark.skip(
+ reason="stage red: environment gap, the e2e stack neither enables the "
+ "websearch_interception callback nor declares a search backend, so the request "
+ "reaches bedrock's transformation and takes its by-design 400. Unskip once the "
+ "ephemeral stack ships the config in this module's docstring."
+ )
+ @pytest.mark.covers("llm.messages.bedrock_invoke.web_search_server_tool.nonstream.works")
+ def test_web_search_server_tool_is_served(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
+ ) -> None:
+ """A bedrock deployment must answer a web_search server-tool request
+ instead of handing the tool to AWS and returning its 400."""
+ model = f"e2e-bedrock-websearch-{unique_marker()}"
- model_id = endpoints_client.create_model(
++ model_id = proxy.create_model(
+ model,
+ LiteLLMParamsBody(
+ model=BEDROCK_INVOKE_BACKEND,
+ aws_region_name="us-east-1",
+ ),
+ )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
++ resources.defer(lambda: proxy.delete_model(model_id))
++ client = sdk.anthropic(resources.key())
+
- response = unwrap(
- endpoints_client.proxy.messages(
- key,
- AnthropicMessagesBody(
- model=model,
- max_tokens=512,
- tools=[WEB_SEARCH_TOOL],
- messages=[ChatMessage(role="user", content=SEARCH_PROMPT)],
- ),
- )
++ response = client.messages.create(
++ model=model,
++ max_tokens=512,
++ tools=[WEB_SEARCH_TOOL],
++ messages=[{"role": "user", "content": SEARCH_PROMPT}],
+ )
+
- assert response.content, f"no content blocks in response: {response}"
++ assert response.content, f"no content blocks in response: {response!r}"
+ block_types = [block.type for block in response.content]
+ assert "web_search_tool_result" in block_types, (
+ "the answer carries no web_search_tool_result block, so the search "
+ "either never ran or its results were not returned in the native shape "
+ f"a citations panel reads. blocks={block_types}"
+ )
+ assert "text" in block_types, (
+ "the model never synthesized an answer over the search results, so the "
+ f"agentic loop stopped early. blocks={block_types}"
+ )
diff --cc tests/e2e/llm_translation/test_cache_control.py
index 888cbb422eb,a18e03c982b..f467bae98f5
--- a/tests/e2e/llm_translation/test_cache_control.py
+++ b/tests/e2e/llm_translation/test_cache_control.py
@@@ -26,9 -37,10 +37,9 @@@ import pytes
from pydantic import BaseModel
from e2e_config import unique_marker
- from e2e_http import Result, unwrap
+ from e2e_http import Result, UnknownApiError, unwrap
-from endpoints_client import CacheControl, RichMessage, TextBlock
from lifecycle import ResourceManager
- from models import CacheControl, ChatResponse, LiteLLMParamsBody, RichMessage, TextBlock, Usage
-from models import ChatBody, ChatMessage, ChatResponse, LiteLLMParamsBody, Usage
++from models import CacheControl, ChatBody, ChatMessage, ChatResponse, LiteLLMParamsBody, RichMessage, TextBlock, Usage
from passthrough_client import PassthroughClient
import os
diff --cc tests/e2e/llm_translation/test_completions_endpoint_e2e.py
index 00000000000,3fc506e4de9..c6415ce7f29
mode 000000,100644..100644
--- a/tests/e2e/llm_translation/test_completions_endpoint_e2e.py
+++ b/tests/e2e/llm_translation/test_completions_endpoint_e2e.py
@@@ -1,0 -1,46 +1,46 @@@
+ """Live e2e: POST /v1/completions returns a real text completion.
+
+ The legacy text-completion endpoint (prompt-style, non-chat) is the second-busiest
+ route in production yet was previously uncovered; the rest of the "completions"
+ surface is chat only. Registers an OpenAI instruct deployment at runtime (deleted
-on teardown), drives /v1/completions through the gateway, and asserts real
-generated text came back so a regression that empties the completion fails here.
++on teardown), drives /v1/completions through the gateway with the real OpenAI SDK
++(LIT-4577), and asserts real generated text came back so a regression that empties
++the completion fails here.
+ """
+
+ from __future__ import annotations
+
+ import pytest
-
+ from e2e_config import unique_marker
-from e2e_http import require_successful_call
-from endpoints_client import CompletionsResult, EndpointsClient
+ from lifecycle import ResourceManager
+ from models import LiteLLMParamsBody
++from proxy_client import ProxyClient
++from sdk_clients import SdkClients
+
+ pytestmark = pytest.mark.e2e
+
+
+ class TestCompletionsEndpoint:
+ @pytest.mark.covers("llm.completions.openai.basic.nonstream.works")
+ def test_text_completion_returns_text(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
+ ) -> None:
+ model = f"e2e-completions-{unique_marker()}"
- model_id = endpoints_client.create_model(
++ model_id = proxy.create_model(
+ model,
+ LiteLLMParamsBody(
+ model="text-completion-openai/gpt-3.5-turbo-instruct",
+ api_key="os.environ/OPENAI_API_KEY",
+ ),
+ )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
++ resources.defer(lambda: proxy.delete_model(model_id))
++ client = sdk.openai(resources.key())
+
- result = endpoints_client.text_completions(
- key, model, "Finish this sentence in a few words: the capital of France is"
++ completion = client.completions.create(
++ model=model,
++ prompt="Finish this sentence in a few words: the capital of France is",
++ max_tokens=32,
+ )
- require_successful_call(result)
- parsed = CompletionsResult.model_validate_json(result.body)
- assert parsed.choices, f"/v1/completions returned no choices: {result.body[:300]}"
- completion = (parsed.choices[0].text or "").strip()
- assert completion, f"/v1/completions returned an empty completion: {result.body[:300]}"
++ assert completion.choices, f"/v1/completions returned no choices: {completion!r}"
++ text = (completion.choices[0].text or "").strip()
++ assert text, f"/v1/completions returned an empty completion: {completion!r}"
diff --cc tests/e2e/llm_translation/test_embeddings_endpoint_e2e.py
index dac69591341,5520ca0cee5..c46b10e25d2
--- a/tests/e2e/llm_translation/test_embeddings_endpoint_e2e.py
+++ b/tests/e2e/llm_translation/test_embeddings_endpoint_e2e.py
@@@ -1,85 -1,184 +1,148 @@@
- """Live e2e: POST /embeddings returns a real vector across OpenAI, Bedrock, Vertex.
+ """Live e2e: POST /embeddings returns a real vector across OpenAI, Bedrock, Vertex, Cohere.
-Each test registers the deployment it needs at runtime (deleted on teardown) and
-asserts a non-empty, non-zero vector came back. The LIT-3167 guard in
-tests/e2e/embeddings/ covers the Gemini embedding path; embeddings cost tracking is
-covered by tests/e2e/quota_management/spend_tracking/.
+Each test registers the deployment it needs at runtime (deleted on teardown),
+drives the endpoint with the real OpenAI SDK (LIT-4577), and asserts a
+non-empty, non-zero vector came back. The LIT-3167 guard in
+tests/e2e/embeddings/ covers the Gemini embedding path; embeddings cost tracking
- is covered by tests/e2e/quota_management/spend_tracking/.
++is covered by tests/e2e/quota_management/spend_tracking/. Malformed bodies the
++SDK refuses to build stay on the shared transport.
"""
from __future__ import annotations
import pytest
-
- from e2e_config import unique_marker
+ from e2e_config import provider_edge_base, unique_marker
-from e2e_http import (
- assert_client_error,
- require_successful_call,
-)
-from endpoints_client import EmbeddingsResult, EndpointsClient
++from e2e_http import assert_client_error
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
+from proxy_client import ProxyClient
+ from pydantic import BaseModel
+from sdk_clients import SdkClients
pytestmark = pytest.mark.e2e
+ class _OptionalEmbeddingsBody(BaseModel):
+ model: str | None = None
+ input: str | list[str] | None = None
+
+
+ def _openai_embeddings_params() -> LiteLLMParamsBody:
+ """The OpenAI embeddings deployment, wired through the record/replay edge when a
+ fixture mode is active and straight at OpenAI otherwise (LIT-5974). Bedrock and
+ Vertex stay live: SigV4 signs the Host header, and neither has an edge mount."""
+ base = provider_edge_base("openai")
+ return LiteLLMParamsBody(
+ model="openai/text-embedding-3-small",
+ api_key="os.environ/OPENAI_API_KEY",
+ api_base=None if base is None else f"{base}/v1",
+ )
+
+
++def _register(proxy: ProxyClient, resources: ResourceManager, prefix: str, params: LiteLLMParamsBody) -> tuple[str, str]:
++ model = f"{prefix}-{unique_marker()}"
++ model_id = proxy.create_model(model, params)
++ resources.defer(lambda: proxy.delete_model(model_id))
++ return model, resources.key()
++
++
+def _assert_embedding_vector(
+ proxy: ProxyClient,
+ resources: ResourceManager,
+ sdk: SdkClients,
+ prefix: str,
+ params: LiteLLMParamsBody,
+) -> None:
- model = f"{prefix}-{unique_marker()}"
- model_id = proxy.create_model(model, params)
- resources.defer(lambda: proxy.delete_model(model_id))
- client = sdk.openai(resources.key())
++ model, key = _register(proxy, resources, prefix, params)
++ client = sdk.openai(key)
+
+ embeddings = client.embeddings.create(model=model, input="Say this is a test!")
+ assert embeddings.data, f"/embeddings returned no data: {embeddings!r}"
+ vector = embeddings.data[0].embedding
+ assert vector, f"/embeddings returned no vector: {embeddings!r}"
+ assert any(component != 0.0 for component in vector), "embedding vector is all zeros"
+
+
class TestEmbeddingsEndpoint:
+ @pytest.mark.replayable
@pytest.mark.covers("llm.embeddings.openai.basic.nonstream.works")
def test_embeddings_returns_vector(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
+ ) -> None:
- model = f"e2e-embeddings-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- _openai_embeddings_params(),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- result = endpoints_client.embeddings(key, model, "Say this is a test!")
- require_successful_call(result)
- parsed = EmbeddingsResult.model_validate_json(result.body)
- assert parsed.first_vector, f"/embeddings returned no vector: {result.body[:300]}"
- assert any(component != 0.0 for component in parsed.first_vector), (
- f"embedding vector is all zeros: {result.body[:300]}"
- )
++ _assert_embedding_vector(proxy, resources, sdk, "e2e-embeddings", _openai_embeddings_params())
+
+ @pytest.mark.covers("llm.embeddings.bedrock.basic.nonstream.works")
+ def test_bedrock_embeddings_returns_vector(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-embeddings-bedrock-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
+ _assert_embedding_vector(
+ proxy,
+ resources,
+ sdk,
- "e2e-embeddings",
++ "e2e-embeddings-bedrock",
LiteLLMParamsBody(
- model="openai/text-embedding-3-small", api_key="os.environ/OPENAI_API_KEY"
+ model="bedrock/amazon.titan-embed-text-v2:0",
+ aws_access_key_id="os.environ/AWS_ACCESS_KEY_ID",
+ aws_secret_access_key="os.environ/AWS_SECRET_ACCESS_KEY",
+ aws_region_name="os.environ/AWS_REGION",
),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- result = endpoints_client.embeddings(key, model, "Say this is a test!")
- require_successful_call(result)
- parsed = EmbeddingsResult.model_validate_json(result.body)
- assert parsed.first_vector, f"/embeddings returned no vector: {result.body[:300]}"
- assert any(component != 0.0 for component in parsed.first_vector), (
- f"embedding vector is all zeros: {result.body[:300]}"
- )
- @pytest.mark.covers("llm.embeddings.bedrock.basic.nonstream.works")
- def test_bedrock_embeddings_returns_vector(
+ @pytest.mark.covers("llm.embeddings.cohere.basic.nonstream.works")
+ def test_cohere_embeddings_returns_vector(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-embeddings-cohere-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
+ _assert_embedding_vector(
+ proxy,
+ resources,
+ sdk,
- "e2e-embeddings-bedrock",
- LiteLLMParamsBody(
- model="bedrock/amazon.titan-embed-text-v2:0", aws_region_name="us-west-2"
- ),
++ "e2e-embeddings-cohere",
+ LiteLLMParamsBody(model="cohere/embed-v4.0", api_key="os.environ/COHERE_API_KEY"),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- result = endpoints_client.embeddings(key, model, "Say this is a test!")
- require_successful_call(result)
- parsed = EmbeddingsResult.model_validate_json(result.body)
- assert parsed.first_vector, f"/embeddings returned no vector: {result.body[:300]}"
- assert any(component != 0.0 for component in parsed.first_vector), (
- f"embedding vector is all zeros: {result.body[:300]}"
- )
@pytest.mark.covers("llm.embeddings.vertex.basic.nonstream.works")
def test_vertex_embeddings_returns_vector(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-embeddings-vertex-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
+ _assert_embedding_vector(
+ proxy,
+ resources,
+ sdk,
+ "e2e-embeddings-vertex",
LiteLLMParamsBody(
- model="vertex_ai/gemini-embedding-2",
+ model="vertex_ai/text-embedding-005",
vertex_project="os.environ/VERTEXAI_PROJECT",
vertex_location="us-central1",
),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- result = endpoints_client.embeddings(key, model, "Say this is a test!")
- require_successful_call(result)
- parsed = EmbeddingsResult.model_validate_json(result.body)
- assert parsed.first_vector, f"/embeddings returned no vector: {result.body[:300]}"
- assert any(component != 0.0 for component in parsed.first_vector), (
- f"embedding vector is all zeros: {result.body[:300]}"
- )
+
+ @pytest.mark.replayable
+ @pytest.mark.covers("llm.embeddings.openai.basic.nonstream.works")
+ def test_array_input_returns_vectors(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
+ ) -> None:
- model = f"e2e-embeddings-array-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- _openai_embeddings_params(),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
- result = endpoints_client.proxy.transport.send(
- "/embeddings",
- headers=endpoints_client.proxy.transport.bearer(key),
- json=_OptionalEmbeddingsBody(model=model, input=["Hello", "World", "Test"]),
- )
- require_successful_call(result)
- parsed = EmbeddingsResult.model_validate_json(result.body)
- assert len(parsed.data) == 3, f"expected 3 vectors: {result.body[:300]}"
++ model, key = _register(proxy, resources, "e2e-embeddings-array", _openai_embeddings_params())
++ embeddings = sdk.openai(key).embeddings.create(model=model, input=["Hello", "World", "Test"])
++ assert len(embeddings.data) == 3, f"expected 3 vectors: {embeddings!r}"
+
+ @pytest.mark.replayable
+ @pytest.mark.covers("llm.embeddings.openai.input_validation.nonstream.works")
- def test_missing_model_returns_client_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
++ def test_missing_model_returns_client_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
+ key = resources.key()
- result = endpoints_client.proxy.transport.send(
++ result = proxy.transport.send(
+ "/embeddings",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalEmbeddingsBody(input="hello"),
+ )
+ assert_client_error(result, "embeddings missing model")
+
+ @pytest.mark.replayable
+ @pytest.mark.covers("llm.embeddings.openai.input_validation.nonstream.works")
- def test_missing_input_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model = f"e2e-embeddings-missin-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- _openai_embeddings_params(),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
- result = endpoints_client.proxy.transport.send(
++ def test_missing_input_returns_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model, key = _register(proxy, resources, "e2e-embeddings-missin", _openai_embeddings_params())
++ result = proxy.transport.send(
+ "/embeddings",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalEmbeddingsBody(model=model),
+ )
+ assert_client_error(result, "embeddings missing input")
diff --cc tests/e2e/llm_translation/test_google_native_e2e.py
index 00000000000,40fd6eca765..6910519c6df
mode 000000,100644..100644
--- a/tests/e2e/llm_translation/test_google_native_e2e.py
+++ b/tests/e2e/llm_translation/test_google_native_e2e.py
@@@ -1,0 -1,107 +1,139 @@@
++"""Live e2e: the Gemini-native generateContent routes through the gateway.
++
++Google's own SDKs read these routes, and the streaming test asserts the exact SSE
++framing they expect (no doubled ``data:`` prefix, no bytes literal, no OpenAI
++``[DONE]`` sentinel), which an SDK would hide, so this passthrough surface stays on
++the shared transport.
++"""
++
+ from __future__ import annotations
+
-import pytest
-from pydantic import BaseModel
++from typing import Literal
+
++import pytest
+ from e2e_config import unique_marker
+ from e2e_http import StreamingResponse, require_successful_call
-from endpoints_client import EndpointsClient
+ from lifecycle import ResourceManager
+ from models import LiteLLMParamsBody
++from proxy_client import ProxyClient
++from pydantic import BaseModel
+
+ pytestmark = pytest.mark.e2e
+
+ UPSTREAM_MODEL = "gemini/gemini-2.5-flash"
+
+
++class _GenerateContentPart(BaseModel):
++ text: str
++
++
++class _GenerateContentContent(BaseModel):
++ role: Literal["user"] = "user"
++ parts: tuple[_GenerateContentPart, ...]
++
++
++class _GenerateContentBody(BaseModel):
++ contents: tuple[_GenerateContentContent, ...]
++
++
+ class _StreamPart(BaseModel):
+ text: str | None = None
+
+
+ class _StreamContent(BaseModel):
+ parts: tuple[_StreamPart, ...] = ()
+
+
+ class _StreamCandidate(BaseModel):
+ content: _StreamContent | None = None
+
+
+ class _StreamEvent(BaseModel):
+ candidates: tuple[_StreamCandidate, ...] = ()
+
+
-def _managed_deployment(client: EndpointsClient, resources: ResourceManager) -> str:
++def _managed_deployment(proxy: ProxyClient, resources: ResourceManager) -> str:
+ model = f"e2e-google-native-{unique_marker()}"
- model_id = client.create_model(
++ model_id = proxy.create_model(
+ model,
+ LiteLLMParamsBody(model=UPSTREAM_MODEL, api_key="os.environ/GEMINI_API_KEY"),
+ )
- resources.defer(lambda: client.delete_model(model_id))
++ resources.defer(lambda: proxy.delete_model(model_id))
+ return model
+
+
++def _generate_content(proxy: ProxyClient, key: str, model: str, text: str, *, stream: bool = False) -> StreamingResponse:
++ operation = "streamGenerateContent" if stream else "generateContent"
++ body = _GenerateContentBody(contents=(_GenerateContentContent(parts=(_GenerateContentPart(text=text),)),))
++ return proxy.transport.send(
++ f"/v1beta/models/{model}:{operation}",
++ headers=proxy.transport.bearer(key),
++ json=body,
++ stream=stream,
++ )
++
++
+ def _streamed_text(result: StreamingResponse) -> str:
+ return "".join(
+ part.text
+ for event in result.stream_events
+ for candidate in _StreamEvent.model_validate_json(event).candidates
+ for part in (candidate.content.parts if candidate.content else ())
+ if part.text
+ )
+
+
+ class TestGoogleNativeGenerateContent:
+ @pytest.mark.covers("llm.google_native.gemini.basic.nonstream.cost_logged")
+ def test_generate_content_returns_response_cost_header(
+ self,
- endpoints_client: EndpointsClient,
++ proxy: ProxyClient,
+ resources: ResourceManager,
+ scoped_key: str,
+ ) -> None:
- model = _managed_deployment(endpoints_client, resources)
++ model = _managed_deployment(proxy, resources)
+
- result = endpoints_client.generate_content(
- scoped_key, model, f"Reply with the single word ok. {unique_marker()}"
- )
++ result = _generate_content(proxy, scoped_key, model, f"Reply with the single word ok. {unique_marker()}")
+
+ require_successful_call(result)
+ assert result.call_id, "generateContent must stamp x-litellm-call-id"
+ assert result.response_cost is not None, (
+ "generateContent returned no x-litellm-response-cost header; "
+ "google-native traffic cannot be reconciled against spend without it"
+ )
+ assert result.response_cost > 0, f"x-litellm-response-cost must be a real cost, got {result.response_cost}"
+
+ @pytest.mark.covers("llm.google_native.gemini.basic.stream.works")
+ def test_stream_generate_content_frames_sse_the_way_google_sdks_expect(
+ self,
- endpoints_client: EndpointsClient,
++ proxy: ProxyClient,
+ resources: ResourceManager,
+ scoped_key: str,
+ ) -> None:
- model = _managed_deployment(endpoints_client, resources)
++ model = _managed_deployment(proxy, resources)
+
- result = endpoints_client.generate_content(
++ result = _generate_content(
++ proxy,
+ scoped_key,
+ model,
+ f"Count from one to five, one number per line. {unique_marker()}",
+ stream=True,
+ )
+
+ require_successful_call(result)
+ assert result.is_streaming, f"expected text/event-stream, got content-type {result.content_type!r}"
+ assert result.stream_error is None, f"stream carried an error: {result.stream_error}"
+ assert result.stream_events, f"stream delivered no data events (chunks={result.chunks})"
+
+ doubled = tuple(event for event in result.stream_events if event.lstrip().startswith("data:"))
+ assert not doubled, (
+ f"{len(doubled)} event(s) carry a second data: prefix, so the proxy re-wrapped "
+ f"already-framed SSE; first offender: {doubled[0][:120]!r}"
+ )
+ leaked = tuple(event for event in result.stream_events if event.startswith("b'"))
+ assert not leaked, f"event serialized as a Python bytes literal instead of text: {leaked[0][:120]!r}"
+ assert _streamed_text(result).strip(), "stream delivered events but no candidate text"
+ assert not result.stream_done, (
+ "google-native stream emitted the OpenAI [DONE] sentinel; Google never sends it "
+ "and the Vertex Java SDK rejects the stream when it appears"
+ )
diff --cc tests/e2e/llm_translation/test_image_edits_e2e.py
index 00000000000,0197c8739fd..e95b054862e
mode 000000,100644..100644
--- a/tests/e2e/llm_translation/test_image_edits_e2e.py
+++ b/tests/e2e/llm_translation/test_image_edits_e2e.py
@@@ -1,0 -1,78 +1,82 @@@
+ """Live e2e: POST /v1/images/edits returns an edited image.
+
-Registers an OpenAI image model, then sends a small PNG plus an edit prompt as a
-multipart request to /v1/images/edits and asserts the response carries an image
-(url or base64). /images/edits is a distinct native route from
-/images/generations: it is multipart file upload with the image sent as the
-`image` part, not a JSON body. The fixture image is a small generated 64x64 PNG,
-so no external asset is needed.
++Registers an OpenAI image model, then sends a small PNG plus an edit prompt
++through the real OpenAI SDK (LIT-4577) to /v1/images/edits and asserts the
++response carries an image (url or base64). /images/edits is a distinct native
++route from /images/generations: it is multipart file upload with the image sent
++as the `image` part, not a JSON body. The fixture image is a small generated
++64x64 PNG, so no external asset is needed.
+ """
+
+ from __future__ import annotations
+
+ import base64
+
++import openai
+ import pytest
-from e2e_config import unique_marker
-from e2e_http import Result, UnknownApiError, unwrap
-from endpoints_client import EndpointsClient, ImageEditForm, ImagesResult
++from e2e_config import SLOW_PROVIDER_TIMEOUT_SECONDS, unique_marker
+ from lifecycle import ResourceManager
+ from models import LiteLLMParamsBody
++from proxy_client import ProxyClient
++from sdk_clients import SdkClients
+
+ pytestmark = pytest.mark.e2e
+
+ _TEST_PNG = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAS0lEQVR42u3PMQ0AAAwDoPo3"
+ "3UrYvQQckD4XAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB"
+ "AYHLAMpT0sIcNbcEAAAAAElFTkSuQmCC"
+ )
+
+
-def _register_image_model(endpoints_client: EndpointsClient, resources: ResourceManager) -> tuple[str, str]:
++def _register_image_model(proxy: ProxyClient, resources: ResourceManager) -> tuple[str, str]:
+ model = f"e2e-image-edit-{unique_marker()}"
- model_id = endpoints_client.create_model(
++ model_id = proxy.create_model(
+ model,
+ LiteLLMParamsBody(model="openai/gpt-image-1", api_key="os.environ/OPENAI_API_KEY"),
+ )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
++ resources.defer(lambda: proxy.delete_model(model_id))
+ return model, resources.key()
+
+
-def _assert_client_error(result: Result[ImagesResult], context: str) -> None:
- match result:
- case UnknownApiError(status_code=status) if 400 <= status < 500:
- return
- case other:
- pytest.fail(f"{context}: expected 4xx, got {other!r}")
++def _image_part(content: bytes) -> tuple[str, bytes, str]:
++ return ("image.png", content, "image/png")
++
++
++def _assert_client_error(error: openai.APIStatusError, context: str) -> None:
++ assert 400 <= error.status_code < 500, f"{context}: expected 4xx, got {error.status_code}: {error.message}"
+
+
+ class TestImageEdit:
+ @pytest.mark.covers("llm.images_edits.openai.basic.nonstream.works")
- def test_image_edit_returns_image(self, endpoints_client: EndpointsClient, resources: ResourceManager) -> None:
- model, key = _register_image_model(endpoints_client, resources)
++ def test_image_edit_returns_image(self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients) -> None:
++ model, key = _register_image_model(proxy, resources)
++ client = sdk.openai(key)
+
- edited = unwrap(endpoints_client.image_edit(key, model, "Add a small red circle in the center", _TEST_PNG))
- assert edited.data, f"/images/edits returned no data: {edited}"
++ edited = client.images.edit(
++ model=model,
++ image=_image_part(_TEST_PNG),
++ prompt="Add a small red circle in the center",
++ timeout=SLOW_PROVIDER_TIMEOUT_SECONDS,
++ )
++ assert edited.data, f"/images/edits returned no data: {edited!r}"
+ first = edited.data[0]
- assert first.b64_json or first.url, f"edited image has neither b64_json nor url: {first}"
++ assert first.b64_json or first.url, f"edited image has neither b64_json nor url: {first!r}"
+
+ @pytest.mark.covers("llm.images_edits.openai.input_validation.nonstream.works")
- def test_empty_prompt_returns_error(self, endpoints_client: EndpointsClient, resources: ResourceManager) -> None:
- model, key = _register_image_model(endpoints_client, resources)
- result = endpoints_client.image_edit(key, model, "", _TEST_PNG)
- _assert_client_error(result, "empty image-edit prompt")
++ def test_empty_prompt_returns_error(self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients) -> None:
++ model, key = _register_image_model(proxy, resources)
++ client = sdk.openai(key)
++
++ with pytest.raises(openai.APIStatusError) as raised:
++ client.images.edit(model=model, image=_image_part(_TEST_PNG), prompt="")
++ _assert_client_error(raised.value, "empty image-edit prompt")
+
+ @pytest.mark.covers("llm.images_edits.openai.input_validation.nonstream.works")
- def test_empty_image_returns_error(self, endpoints_client: EndpointsClient, resources: ResourceManager) -> None:
- model, key = _register_image_model(endpoints_client, resources)
- result = endpoints_client.proxy.transport.upload(
- "/v1/images/edits",
- headers=endpoints_client.proxy.transport.bearer(key),
- form=ImageEditForm(model=model, prompt="add a red circle"),
- filename="image.png",
- content=b"",
- file_content_type="image/png",
- file_field="image",
- response_type=ImagesResult,
- )
- _assert_client_error(result, "empty image-edit file")
++ def test_empty_image_returns_error(self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients) -> None:
++ model, key = _register_image_model(proxy, resources)
++ client = sdk.openai(key)
++
++ with pytest.raises(openai.APIStatusError) as raised:
++ client.images.edit(model=model, image=_image_part(b""), prompt="add a red circle")
++ _assert_client_error(raised.value, "empty image-edit file")
diff --cc tests/e2e/llm_translation/test_image_generation_e2e.py
index c5204162501,3b0d7da635f..1db40e7e15a
--- a/tests/e2e/llm_translation/test_image_generation_e2e.py
+++ b/tests/e2e/llm_translation/test_image_generation_e2e.py
@@@ -1,70 -1,130 +1,120 @@@
"""Live e2e: POST /v1/images/generations returns an image.
-Registers an OpenAI image deployment at runtime and asserts the response carries a
-generated image (url or base64). Migrated from
-litellm-regression-tests/tests/test_inference_endpoints.py.
+Registers an image deployment at runtime, drives it through the real OpenAI SDK
+(LIT-4577), and asserts the response carries a generated image (url or base64).
++Malformed bodies the SDK refuses to build stay on the shared transport. Migrated
++from litellm-regression-tests/tests/test_inference_endpoints.py.
"""
from __future__ import annotations
import pytest
-
- from e2e_config import require_env, unique_marker
+ from e2e_config import unique_marker
-from e2e_http import (
- assert_client_error,
- require_successful_call,
-)
-from endpoints_client import EndpointsClient, ImagesResult
++from e2e_http import assert_client_error
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
++from openai.types import ImagesResponse
+from proxy_client import ProxyClient
+ from pydantic import BaseModel
+from sdk_clients import SdkClients
pytestmark = pytest.mark.e2e
- def _assert_image_returned(
- proxy: ProxyClient,
- resources: ResourceManager,
- sdk: SdkClients,
- prefix: str,
- params: LiteLLMParamsBody,
- ) -> None:
- model = f"{prefix}-{unique_marker()}"
- model_id = proxy.create_model(model, params)
- resources.defer(lambda: proxy.delete_model(model_id))
- client = sdk.openai(resources.key())
+ class _OptionalImageBody(BaseModel):
+ model: str | None = None
+ prompt: str | None = None
+ n: int | None = None
+ size: str | None = None
- images = client.images.generate(model=model, prompt="Draw a cute cat", n=1, size="1024x1024")
+
-def _assert_image_returned(body: str) -> None:
- parsed = ImagesResult.model_validate_json(body)
- assert parsed.data, f"/images/generations returned no data: {body[:300]}"
- first = parsed.data[0]
- assert first.b64_json or first.url, (
- f"generated image has neither b64_json nor url: {body[:300]}"
- )
++def _assert_image_returned(images: ImagesResponse) -> None:
+ data = images.data or []
+ assert data, f"/images/generations returned no data: {images!r}"
+ first = data[0]
- assert first.b64_json or first.url, "generated image has neither b64_json nor url"
++ assert first.b64_json or first.url, f"generated image has neither b64_json nor url: {first!r}"
++
+
++def _register(proxy: ProxyClient, resources: ResourceManager, prefix: str, params: LiteLLMParamsBody) -> tuple[str, str]:
++ model = f"{prefix}-{unique_marker()}"
++ model_id = proxy.create_model(model, params)
++ resources.defer(lambda: proxy.delete_model(model_id))
++ return model, resources.key()
+
-def _register_openai_image(
- endpoints_client: EndpointsClient, resources: ResourceManager
-) -> tuple[str, str]:
- model = f"e2e-image-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
++
++def _register_openai_image(proxy: ProxyClient, resources: ResourceManager) -> tuple[str, str]:
++ return _register(
++ proxy,
++ resources,
++ "e2e-image",
+ LiteLLMParamsBody(model="openai/gpt-image-1-mini", api_key="os.environ/OPENAI_API_KEY"),
+ )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- return model, resources.key()
class TestImageGeneration:
@pytest.mark.covers("llm.images_generations.openai.basic.nonstream.works")
def test_image_generation_returns_image(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- _assert_image_returned(
- proxy,
- resources,
- sdk,
- "e2e-image",
- LiteLLMParamsBody(model="openai/gpt-image-1-mini", api_key="os.environ/OPENAI_API_KEY"),
- )
- model, key = _register_openai_image(endpoints_client, resources)
- result = endpoints_client.images(key, model, "Draw a cute cat")
- require_successful_call(result)
- _assert_image_returned(result.body)
++ model, key = _register_openai_image(proxy, resources)
++ images = sdk.openai(key).images.generate(model=model, prompt="Draw a cute cat", n=1, size="1024x1024")
++ _assert_image_returned(images)
- @pytest.mark.covers(
- "llm.images_generations.bedrock.basic.nonstream.works", exercised_on=["images_generations"]
- )
+ @pytest.mark.covers("llm.images_generations.bedrock.basic.nonstream.works", exercised_on=["images_generations"])
def test_bedrock_image_generation_returns_image(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- require_env("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION")
- _assert_image_returned(
- model = f"e2e-bedrock-image-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
++ model, key = _register(
+ proxy,
+ resources,
- sdk,
+ "e2e-bedrock-image",
LiteLLMParamsBody(
- model="bedrock/amazon.titan-image-generator-v2:0",
+ model="bedrock/amazon.nova-canvas-v1:0",
aws_access_key_id="os.environ/AWS_ACCESS_KEY_ID",
aws_secret_access_key="os.environ/AWS_SECRET_ACCESS_KEY",
aws_region_name="os.environ/AWS_REGION",
),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- result = endpoints_client.images(key, model, "Draw a cute cat")
- require_successful_call(result)
- _assert_image_returned(result.body)
++ images = sdk.openai(key).images.generate(model=model, prompt="Draw a cute cat", n=1, size="1024x1024")
++ _assert_image_returned(images)
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/images/generations 500s (aimage_generation TypeError) on missing prompt instead of 400")
+ @pytest.mark.covers("llm.images_generations.openai.input_validation.nonstream.works")
- def test_missing_prompt_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model, key = _register_openai_image(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ def test_missing_prompt_returns_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model, key = _register_openai_image(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/images/generations",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalImageBody(model=model),
+ )
+ assert_client_error(result, "images missing prompt")
+
+ @pytest.mark.covers("llm.images_generations.openai.input_validation.nonstream.works")
- def test_empty_prompt_returns_client_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model, key = _register_openai_image(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ def test_empty_prompt_returns_client_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model, key = _register_openai_image(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/images/generations",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalImageBody(model=model, prompt=""),
+ )
+ assert_client_error(result, "images empty prompt")
+
+ @pytest.mark.covers("llm.images_generations.openai.input_validation.nonstream.works")
- def test_invalid_size_returns_client_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model, key = _register_openai_image(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ def test_invalid_size_returns_client_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model, key = _register_openai_image(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/images/generations",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalImageBody(model=model, prompt="a blue square", size="999x999"),
+ )
+ assert_client_error(result, "images invalid size")
+
+ @pytest.mark.covers("llm.images_generations.openai.input_validation.nonstream.works")
- def test_invalid_n_returns_client_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model, key = _register_openai_image(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ def test_invalid_n_returns_client_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model, key = _register_openai_image(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/images/generations",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalImageBody(model=model, prompt="a blue square", n=0),
+ )
+ assert_client_error(result, "images invalid n")
diff --cc tests/e2e/llm_translation/test_messages_e2e.py
index 0c5734bc299,ca58c30d40c..caac0bec869
--- a/tests/e2e/llm_translation/test_messages_e2e.py
+++ b/tests/e2e/llm_translation/test_messages_e2e.py
@@@ -1,35 -1,79 +1,63 @@@
"""Live e2e: POST /v1/messages (Anthropic Messages API) returns a real completion.
- Registers an Anthropic deployment at runtime and drives the Messages endpoint
- through the gateway with the real Anthropic SDK, the client customers actually
- use (LIT-4577), asserting an assistant message with text came back, both
- non-streaming and streamed.
+ Registers an Anthropic deployment at runtime, drives the Messages endpoint through
-the gateway, and asserts an assistant message with text came back, both
-non-streaming and streamed. Migrated from
++the gateway with the real Anthropic SDK, the client customers actually use
++(LIT-4577), and asserts an assistant message with text came back, both
++non-streaming and streamed. Malformed bodies the SDK refuses to build stay on the
++shared transport. Migrated from
+ litellm-regression-tests/tests/test_inference_endpoints.py.
"""
from __future__ import annotations
- import pytest
- from anthropic.types import Message, ToolParam
++import time
+ from typing import Final
- from e2e_config import require_env, unique_marker
+ import pytest
-from e2e_config import (
- STREAM_MIN_LEAD_SECONDS,
- provider_edge_base,
- provider_paces_stream,
- unique_marker,
++from anthropic import Anthropic
++from anthropic.types import (
++ InputJSONDelta,
++ Message,
++ MessageParam,
++ RawContentBlockDeltaEvent,
++ RawContentBlockStartEvent,
++ RawContentBlockStopEvent,
++ RawMessageDeltaEvent,
++ RawMessageStreamEvent,
++ TextBlock,
++ TextDelta,
++ ToolChoiceParam,
++ ToolParam,
++ ToolUseBlock,
+ )
-from e2e_http import assert_client_error, require_successful_call, unwrap
-from endpoints_client import EndpointsClient, MessagesResult
++from e2e_config import STREAM_MIN_LEAD_SECONDS, provider_edge_base, provider_paces_stream, unique_marker
++from e2e_http import assert_client_error
from lifecycle import ResourceManager
- from models import LiteLLMParamsBody, SpendLogRow
-from models import (
- AnthropicAssistantTurn,
- AnthropicContentBlock,
- AnthropicCustomTool,
- AnthropicToolChoice,
- AnthropicToolResultBlock,
- AnthropicToolResultTurn,
- AnthropicMessagesBody,
- ChatMessage,
- JsonSchemaProperty,
- LiteLLMParamsBody,
- SpendLogRow,
- ToolInputSchema,
-)
++from models import ChatMessage, LiteLLMParamsBody, SpendLogRow
+from proxy_client import ProxyClient
+ from pydantic import BaseModel, ConfigDict
+from sdk_clients import SdkClients, response_header
- pytestmark = pytest.mark.e2e
+ pytestmark = [pytest.mark.e2e, pytest.mark.replayable]
+
+
+ class _OptionalMessagesBody(BaseModel):
+ model: str | None = None
+ messages: list[ChatMessage] | None = None
+ max_tokens: int | None = None
+
-class _MessagesEventDelta(BaseModel):
- text: str = ""
-
-
-class _MessagesEventUsage(BaseModel):
- output_tokens: int | None = None
-
-
-class _MessagesStreamEvent(BaseModel):
- """One Anthropic SSE event, keeping only what the stream's shape is asserted on.
-
- ``delta.text`` is populated on ``content_block_delta`` and absent on the
- ``message_delta`` that closes the turn, which is the event carrying ``usage``."""
-
- type: str
- delta: _MessagesEventDelta | None = None
- usage: _MessagesEventUsage | None = None
-
-
ANTHROPIC_BACKEND = "anthropic/claude-haiku-4-5"
-WEATHER_TOOL = AnthropicCustomTool(
- name="get_weather",
- description="Get the current weather for a city.",
- input_schema=ToolInputSchema(
- properties={"city": JsonSchemaProperty(type="string")},
- required=["city"],
- ),
-)
+WEATHER_TOOL: ToolParam = {
+ "name": "get_weather",
+ "description": "Get the current weather for a city.",
+ "input_schema": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+}
def _approx_equal(actual: float, expected: float) -> bool:
@@@ -37,67 -81,66 +65,72 @@@
return abs(actual - expected) <= max(1e-9, abs(expected) * 1e-2)
+ def _anthropic_params() -> LiteLLMParamsBody:
+ """The Anthropic deployment, wired through the record/replay edge when a fixture
+ mode is active (LIT-5974). The mount base carries no ``/v1``: litellm's Anthropic
+ handler appends ``/v1/messages`` to ``api_base`` itself, where the OpenAI handler
+ appends only ``/chat/completions``."""
+ base = provider_edge_base("anthropic")
- return LiteLLMParamsBody(
- model=ANTHROPIC_BACKEND, api_key="os.environ/ANTHROPIC_API_KEY", api_base=base
- )
++ return LiteLLMParamsBody(model=ANTHROPIC_BACKEND, api_key="os.environ/ANTHROPIC_API_KEY", api_base=base)
+
+
-class TestAnthropicMessages:
- def _register(
- self,
- endpoints_client: EndpointsClient,
- resources: ResourceManager,
- params: LiteLLMParamsBody | None = None,
- ) -> tuple[str, str]:
- model = f"e2e-messages-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model, _anthropic_params() if params is None else params
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- return model, resources.key()
++def _register(
++ proxy: ProxyClient,
++ resources: ResourceManager,
++ params: LiteLLMParamsBody | None = None,
++ prefix: str = "e2e-messages",
++) -> tuple[str, str]:
++ model = f"{prefix}-{unique_marker()}"
++ model_id = proxy.create_model(model, _anthropic_params() if params is None else params)
++ resources.defer(lambda: proxy.delete_model(model_id))
++ return model, resources.key()
++
++
+def _text(message: Message) -> str:
- return "".join(block.text for block in message.content if block.type == "text")
++ return "".join(block.text for block in message.content if isinstance(block, TextBlock))
+
- class TestAnthropicMessages:
- def _register(
- self, proxy: ProxyClient, resources: ResourceManager, prefix: str = "e2e-messages"
- ) -> str:
- model = f"{prefix}-{unique_marker()}"
- model_id = proxy.create_model(
- model,
- LiteLLMParamsBody(model=ANTHROPIC_BACKEND, api_key="os.environ/ANTHROPIC_API_KEY"),
- )
- resources.defer(lambda: proxy.delete_model(model_id))
- return model
++def _user_turn(text: str) -> MessageParam:
++ return {"role": "user", "content": text}
++
+
++class TestAnthropicMessages:
@pytest.mark.covers("llm.messages.anthropic.basic.nonstream.works")
def test_messages_returns_completion(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = self._register(proxy, resources)
- client = sdk.anthropic(resources.key())
- model, key = self._register(endpoints_client, resources)
++ model, key = _register(proxy, resources)
++ client = sdk.anthropic(key)
- message = client.messages.create(
- model=model,
- max_tokens=64,
- messages=[{"role": "user", "content": "reply with one word"}],
- )
- result = endpoints_client.messages(key, model, "reply with one word")
- require_successful_call(result)
- parsed = MessagesResult.model_validate_json(result.body)
- assert parsed.role == "assistant", f"unexpected role: {result.body[:300]}"
- assert parsed.text.strip(), f"/v1/messages returned no text: {result.body[:300]}"
++ message = client.messages.create(model=model, max_tokens=64, messages=[_user_turn("reply with one word")])
+ assert message.role == "assistant", f"unexpected role: {message.role!r}"
+ assert _text(message).strip(), f"/v1/messages returned no text: {message.content!r}"
@pytest.mark.covers("llm.messages.anthropic.basic.nonstream.cost_logged")
def test_messages_logs_cost_matching_the_response_header(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- require_env("ANTHROPIC_API_KEY")
- model = self._register(proxy, resources, prefix="e2e-messages-cost")
- model = f"e2e-messages-cost-{unique_marker()}"
- model_id = endpoints_client.create_model(model, _anthropic_params())
- resources.defer(lambda: endpoints_client.delete_model(model_id))
-- key = resources.key()
-
- result = endpoints_client.messages(key, model, f"reply with one word {unique_marker()}")
- require_successful_call(result)
- parsed = MessagesResult.model_validate_json(result.body)
- assert parsed.role == "assistant" and parsed.text.strip(), (
- f"/v1/messages returned no assistant text: {result.body[:300]}"
++ model, key = _register(proxy, resources, prefix="e2e-messages-cost")
+ client = sdk.anthropic(key)
+
+ raw = client.messages.with_raw_response.create(
+ model=model,
+ max_tokens=64,
- messages=[{"role": "user", "content": f"reply with one word {unique_marker()}"}],
++ messages=[_user_turn(f"reply with one word {unique_marker()}")],
+ )
+ message = raw.parse()
+ assert message.role == "assistant" and _text(message).strip(), (
+ f"/v1/messages returned no assistant text: {message.content!r}"
)
# The customer reads per-request cost off the response header (LIT-4076), so
# it must be present and positive on /v1/messages, not only /chat/completions.
- header_cost = result.response_cost
- assert header_cost is not None and header_cost > 0, (
- "x-litellm-response-cost header missing or non-positive on /v1/messages; "
- f"headers={result.headers}"
+ raw_header_cost = response_header(raw.headers, "x-litellm-response-cost")
+ assert raw_header_cost is not None, (
- "x-litellm-response-cost header missing on /v1/messages; "
- f"headers={dict(raw.headers)}"
++ f"x-litellm-response-cost header missing on /v1/messages; headers={dict(raw.headers)}"
)
+ header_cost = float(raw_header_cost)
- assert header_cost > 0, (
- f"x-litellm-response-cost header non-positive on /v1/messages: {header_cost}"
- )
++ assert header_cost > 0, f"x-litellm-response-cost header non-positive on /v1/messages: {header_cost}"
# Correlate the spend row by the unique scoped key, not the Anthropic response
# id: on /v1/messages the spend-log request_id is the proxy's own call id, which
@@@ -107,11 -150,11 +140,9 @@@
def _priced(rows: list[SpendLogRow]) -> bool:
return any(r.spend is not None and r.spend > 0 for r in rows)
- rows = endpoints_client.proxy.poll_logs_for_key(key, predicate=_priced)
+ rows = proxy.poll_logs_for_key(key, predicate=_priced)
priced = [r for r in rows if r.spend is not None and r.spend > 0]
-- assert priced, (
-- f"no priced /spend/logs row landed for key {key} within the poll window; got {rows}"
-- )
++ assert priced, f"no priced /spend/logs row landed for key {key} within the poll window; got {rows}"
row = priced[0]
assert (row.prompt_tokens or 0) > 0 and (row.completion_tokens or 0) > 0, (
f"messages spend row missing token counts, so the cost is not real usage: {row}"
@@@ -123,36 -166,262 +154,217 @@@
@pytest.mark.covers("llm.messages.anthropic.basic.stream.works")
def test_messages_streams_completion(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = self._register(proxy, resources)
- client = sdk.anthropic(resources.key())
+ """Edge-wired like its non-streaming siblings, so record and replay both
+ carry the streamed response.
+ Asserts what the proxy controls: the event grammar (usage between the last
+ content delta and ``message_stop``) and, on the clock, that the relay is
+ incremental. How many deltas a reply is split into is the provider's choice, so
+ the first content delta must instead reach the client well before
+ ``message_stop``, which a buffered response cannot do. Replay serves chunks back
+ to back, so only live and record runs judge the timing."""
- model, key = self._register(endpoints_client, resources)
-
- result = endpoints_client.proxy.messages_stream(
- key,
- AnthropicMessagesBody(
- model=model,
- max_tokens=800,
- stream=True,
- messages=[ChatMessage(role="user", content="Count from 1 to 200, one number per line.")],
- ),
++ model, key = _register(proxy, resources)
++ client = sdk.anthropic(key)
++
++ started: Final = time.monotonic()
+ stream = client.messages.create(
+ model=model,
- max_tokens=64,
++ max_tokens=800,
+ stream=True,
- messages=[{"role": "user", "content": "Count from one to three."}],
++ messages=[_user_turn("Count from 1 to 200, one number per line.")],
)
- event_types = [event.type for event in stream]
- assert event_types, "stream produced no SSE events"
- assert "content_block_delta" in event_types, "stream carried no content deltas"
- assert "message_stop" in event_types, "stream never reached message_stop"
- require_successful_call(result)
- assert result.is_streaming, f"response was not streamed: {result.headers}"
- assert not result.stream_error, f"stream errored: {result.stream_error}"
- assert result.stream_events, "stream produced no SSE events"
-
- events = [
- _MessagesStreamEvent.model_validate_json(event) for event in result.stream_events
- ]
- types = [event.type for event in events]
- delta_positions = [
++ arrivals: Final = tuple((event, time.monotonic() - started) for event in stream)
++ assert arrivals, "stream produced no SSE events"
++
++ events: Final = tuple(event for event, _ in arrivals)
++ types: Final = tuple(event.type for event in events)
++ delta_positions: Final = tuple(
+ index for index, event in enumerate(events) if event.type == "content_block_delta"
- ]
++ )
+ assert delta_positions, f"stream carried no content deltas: {types}"
- text = "".join(
++ text: Final = "".join(
+ event.delta.text
+ for event in events
- if event.type == "content_block_delta" and event.delta is not None
++ if isinstance(event, RawContentBlockDeltaEvent) and isinstance(event.delta, TextDelta)
+ )
- assert text.strip(), f"content deltas assembled to no text: {result.stream_events[:5]}"
++ assert text.strip(), f"content deltas assembled to no text: {events[:5]}"
+
- usage_positions = [
- index
- for index, event in enumerate(events)
- if event.type == "message_delta" and event.usage is not None
- ]
++ usage_positions: Final = tuple(
++ index for index, event in enumerate(events) if isinstance(event, RawMessageDeltaEvent)
++ )
+ assert usage_positions, f"stream never reported usage: {types}"
+ assert "message_stop" in types, f"stream never reached message_stop: {types}"
- stop_position = types.index("message_stop")
++ stop_position: Final = types.index("message_stop")
+ assert delta_positions[-1] < usage_positions[0] < stop_position, (
+ f"usage did not land between the last content delta and message_stop: {types}"
+ )
+
- first_delta_at: Final = result.stream_event_arrivals[delta_positions[0]]
- stop_at: Final = result.stream_event_arrivals[stop_position]
++ first_delta_at: Final = arrivals[delta_positions[0]][1]
++ stop_at: Final = arrivals[stop_position][1]
+ if provider_paces_stream():
+ assert stop_at - first_delta_at >= STREAM_MIN_LEAD_SECONDS, (
+ f"first content delta reached the client {first_delta_at:.2f}s after the request "
+ f"and message_stop {stop_at:.2f}s after it; a relayed stream shows the first delta "
+ f"at least {STREAM_MIN_LEAD_SECONDS}s before the end, so the response was buffered"
+ )
@pytest.mark.covers("llm.messages.anthropic.tool_use.nonstream.works")
-- def test_messages_tool_use(
- self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
- self, endpoints_client: EndpointsClient, resources: ResourceManager
-- ) -> None:
- model = self._register(proxy, resources)
- client = sdk.anthropic(resources.key())
- model, key = self._register(endpoints_client, resources)
-
- response = unwrap(
- endpoints_client.proxy.messages(
- key,
- AnthropicMessagesBody(
- model=model,
- max_tokens=256,
- tools=[WEATHER_TOOL],
- messages=[
- ChatMessage(role="user", content="What is the weather in Paris? Use the tool.")
- ],
- ),
- )
++ def test_messages_tool_use(self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients) -> None:
++ model, key = _register(proxy, resources)
++ client = sdk.anthropic(key)
+
+ message = client.messages.create(
+ model=model,
+ max_tokens=256,
+ tools=[WEATHER_TOOL],
- messages=[{"role": "user", "content": "What is the weather in Paris? Use the tool."}],
++ messages=[_user_turn("What is the weather in Paris? Use the tool.")],
)
- assert response.content, f"no content blocks in response: {response}"
- assert any(block.type == "tool_use" for block in response.content), (
- f"model did not call the tool: {response}"
+ assert message.content, f"no content blocks in response: {message!r}"
- assert any(block.type == "tool_use" for block in message.content), (
++ assert any(isinstance(block, ToolUseBlock) for block in message.content), (
+ f"model did not call the tool: {message.content!r}"
)
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/messages 500s (anthropic_messages TypeError) on missing messages instead of 400")
+ @pytest.mark.covers("llm.messages.anthropic.input_validation.nonstream.works")
- def test_missing_messages_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model, key = self._register(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ def test_missing_messages_returns_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model, key = _register(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/messages",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalMessagesBody(model=model, max_tokens=50),
+ )
+ assert_client_error(result, "messages missing messages")
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/messages 500s (anthropic_messages TypeError) on missing max_tokens instead of 400")
+ @pytest.mark.covers("llm.messages.anthropic.input_validation.nonstream.works")
- def test_missing_max_tokens_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model, key = self._register(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ def test_missing_max_tokens_returns_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model, key = _register(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/messages",
- headers=endpoints_client.proxy.transport.bearer(key),
- json=_OptionalMessagesBody(
- model=model, messages=[ChatMessage(role="user", content="hi")]
- ),
++ headers=proxy.transport.bearer(key),
++ json=_OptionalMessagesBody(model=model, messages=[ChatMessage(role="user", content="hi")]),
+ )
+ assert_client_error(result, "messages missing max_tokens")
+
+ @pytest.mark.covers("llm.messages.anthropic.input_validation.nonstream.works")
- def test_missing_model_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- _, key = self._register(endpoints_client, resources)
- result = endpoints_client.proxy.transport.send(
++ def test_missing_model_returns_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ _, key = _register(proxy, resources)
++ result = proxy.transport.send(
+ "/v1/messages",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalMessagesBody(messages=[ChatMessage(role="user", content="hi")], max_tokens=50),
+ )
+ assert_client_error(result, "messages missing model")
+
+
-class _BridgeDelta(BaseModel):
- type: str | None = None
- partial_json: str | None = None
- stop_reason: str | None = None
-
-
-class _BridgeEvent(BaseModel):
- type: str
- index: int | None = None
- content_block: AnthropicContentBlock | None = None
- delta: _BridgeDelta | None = None
-
-
+ class _ParcelInput(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+ parcel: str
+ shelf: int
+
+
-def _tool_from_stream(events: tuple[_BridgeEvent, ...]) -> AnthropicContentBlock:
++def _tool_from_stream(events: tuple[RawMessageStreamEvent, ...]) -> ToolUseBlock:
+ starts: Final = tuple(
- event
- for event in events
- if event.type == "content_block_start"
- and event.content_block is not None
- and event.content_block.type == "tool_use"
++ (index, event.index, event.content_block)
++ for index, event in enumerate(events)
++ if isinstance(event, RawContentBlockStartEvent) and isinstance(event.content_block, ToolUseBlock)
+ )
+ assert len(starts) == 1, "expected exactly one tool call"
- start: Final = starts[0]
- block: Final = start.content_block
- assert block is not None and block.id and start.index is not None
++ start_position, block_index, block = starts[0]
++ assert block.id
+ fragments: Final = tuple(
- event
- for event in events
- if event.type == "content_block_delta" and event.delta is not None and event.delta.type == "input_json_delta"
++ (index, event.index, event.delta.partial_json)
++ for index, event in enumerate(events)
++ if isinstance(event, RawContentBlockDeltaEvent) and isinstance(event.delta, InputJSONDelta)
+ )
+ assert fragments, "tool stream contained no argument fragments"
- assert all(event.index == start.index for event in fragments), "tool fragments changed index"
- positions: Final = tuple(i for i, event in enumerate(events) if event in fragments)
++ assert all(fragment_block == block_index for _, fragment_block, _ in fragments), "tool fragments changed index"
++ positions: Final = tuple(index for index, _, _ in fragments)
+ stops: Final = tuple(
- i for i, event in enumerate(events) if event.type == "content_block_stop" and event.index == start.index
++ index
++ for index, event in enumerate(events)
++ if isinstance(event, RawContentBlockStopEvent) and event.index == block_index
++ )
++ assert len(stops) == 1 and start_position < positions[0] <= positions[-1] < stops[0]
++ terminal_positions: Final = tuple(
++ index for index, event in enumerate(events) if isinstance(event, RawMessageDeltaEvent)
+ )
- assert len(stops) == 1 and events.index(start) < positions[0] <= positions[-1] < stops[0]
- assert tuple(
- event.delta.stop_reason for event in events if event.type == "message_delta" and event.delta is not None
- ) == ("tool_use",)
- terminal_positions: Final = tuple(i for i, event in enumerate(events) if event.type == "message_delta")
++ stop_reasons: Final = tuple(
++ event.delta.stop_reason for event in events if isinstance(event, RawMessageDeltaEvent)
++ )
++ assert stop_reasons == ("tool_use",)
+ assert len(terminal_positions) == 1 and stops[0] < terminal_positions[0] < len(events) - 1
- assert tuple(i for i, event in enumerate(events) if event.type == "message_stop") == (len(events) - 1,), (
++ assert tuple(index for index, event in enumerate(events) if event.type == "message_stop") == (len(events) - 1,), (
+ "tool stream did not terminate exactly once"
+ )
- arguments: Final = _ParcelInput.model_validate_json(
- "".join(event.delta.partial_json or "" for event in fragments if event.delta is not None)
- )
- return AnthropicContentBlock(type="tool_use", id=block.id, name=block.name, input=arguments.model_dump())
-
++ arguments: Final = _ParcelInput.model_validate_json("".join(partial for _, _, partial in fragments))
++ return ToolUseBlock(type="tool_use", id=block.id, name=block.name, input=arguments.model_dump())
+
-def _parcel_result(tool: AnthropicContentBlock, result: AnthropicToolResultBlock) -> AnthropicToolResultTurn:
- assert tool.id and result.tool_use_id == tool.id, "tool result ID does not match the emitted call"
- return AnthropicToolResultTurn(content=[result])
+
-
-def _request_tool(
- client: EndpointsClient, key: str, request: AnthropicMessagesBody, stream: bool
-) -> AnthropicContentBlock:
++def _request_tool(client: Anthropic, model: str, question: MessageParam, tool: ToolParam, stream: bool) -> ToolUseBlock:
++ tool_choice: Final[ToolChoiceParam] = {"type": "tool", "name": tool["name"]}
+ if stream:
- response: Final = client.proxy.messages_stream(key, request)
- require_successful_call(response)
- assert response.is_streaming and not response.stream_error
- return _tool_from_stream(tuple(_BridgeEvent.model_validate_json(event) for event in response.stream_events))
- response_body: Final = unwrap(client.proxy.messages(key, request))
- blocks: Final = tuple(block for block in response_body.content or () if block.type == "tool_use")
++ events: Final = tuple(
++ client.messages.create(
++ model=model, max_tokens=2048, messages=[question], tools=[tool], tool_choice=tool_choice, stream=True
++ )
++ )
++ return _tool_from_stream(events)
++ message: Final = client.messages.create(
++ model=model, max_tokens=2048, messages=[question], tools=[tool], tool_choice=tool_choice
++ )
++ blocks: Final = tuple(block for block in message.content if isinstance(block, ToolUseBlock))
+ assert len(blocks) == 1
+ return blocks[0]
+
+
+ class TestOpenAIMessagesToolContinuation:
+ @pytest.mark.parametrize("stream", [True, False], ids=["stream", "nonstream"])
+ def test_required_tool_arguments_and_correlated_result(
- self, endpoints_client: EndpointsClient, resources: ResourceManager, stream: bool
++ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients, stream: bool
+ ) -> None:
+ model: Final = f"e2e-bridge-tool-{unique_marker()}"
+ base: Final = provider_edge_base("openai")
- model_id: Final = endpoints_client.create_model(
++ model_id: Final = proxy.create_model(
+ model,
+ LiteLLMParamsBody(
+ model="openai/gpt-5.6", api_key="os.environ/OPENAI_API_KEY", api_base=f"{base}/v1" if base else None
+ ),
+ )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key: Final = resources.key(models=[model])
- tool: Final = AnthropicCustomTool(
- name="locate_parcel",
- description="Look up the receipt for a parcel on a shelf. Return the receipt verbatim.",
- input_schema=ToolInputSchema(
- properties={"parcel": JsonSchemaProperty(type="string"), "shelf": JsonSchemaProperty(type="integer")},
- required=["parcel", "shelf"],
- ),
- )
- question: Final = ChatMessage(
- role="user",
- content="Call locate_parcel with parcel exactly amber-kite and shelf exactly 7. After the tool result, reply with only the receipt returned by the tool.",
- )
- request: Final = AnthropicMessagesBody(
- model=model,
- max_tokens=2048,
- messages=[question],
- tools=[tool],
- tool_choice=AnthropicToolChoice(type="tool", name=tool.name),
- stream=stream,
++ resources.defer(lambda: proxy.delete_model(model_id))
++ client: Final = sdk.anthropic(resources.key(models=[model]))
++ tool: Final[ToolParam] = {
++ "name": "locate_parcel",
++ "description": "Look up the receipt for a parcel on a shelf. Return the receipt verbatim.",
++ "input_schema": {
++ "type": "object",
++ "properties": {"parcel": {"type": "string"}, "shelf": {"type": "integer"}},
++ "required": ["parcel", "shelf"],
++ },
++ }
++ question: Final = _user_turn(
++ "Call locate_parcel with parcel exactly amber-kite and shelf exactly 7. "
++ "After the tool result, reply with only the receipt returned by the tool."
+ )
- emitted: Final = _request_tool(endpoints_client, key, request, stream)
++ emitted: Final = _request_tool(client, model, question, tool, stream)
+ assert emitted.id and emitted.name == "locate_parcel"
+ assert emitted.input == {"parcel": "amber-kite", "shelf": 7}, "required tool arguments were lost or changed"
+ receipt: Final = f"receipt-{unique_marker()}"
- result_turn: Final = _parcel_result(emitted, AnthropicToolResultBlock(tool_use_id=emitted.id, content=receipt))
- continuation: Final = unwrap(
- endpoints_client.proxy.messages(
- key,
- AnthropicMessagesBody(
- model=model,
- max_tokens=2048,
- tools=[tool],
- tool_choice=AnthropicToolChoice(type="none"),
- messages=[question, AnthropicAssistantTurn(content=[emitted]), result_turn],
- ),
- )
++ continuation: Final = client.messages.create(
++ model=model,
++ max_tokens=2048,
++ tools=[tool],
++ tool_choice={"type": "none"},
++ messages=[
++ question,
++ {
++ "role": "assistant",
++ "content": [{"type": "tool_use", "id": emitted.id, "name": emitted.name, "input": emitted.input}],
++ },
++ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": emitted.id, "content": receipt}]},
++ ],
+ )
- answer: Final = "".join(block.text or "" for block in continuation.content or ())
- assert answer.strip() == receipt, "continuation did not consume the correlated tool result"
- assert all(block.type != "tool_use" for block in continuation.content or ())
++ assert _text(continuation).strip() == receipt, "continuation did not consume the correlated tool result"
++ assert all(not isinstance(block, ToolUseBlock) for block in continuation.content)
diff --cc tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py
index b79f3027692,557a2cb64e9..730d19749ba
--- a/tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py
+++ b/tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py
@@@ -27,18 -22,22 +27,18 @@@ test
from __future__ import annotations
import time
++from collections.abc import Sequence
+from typing import cast
import pytest
-from pydantic import BaseModel
-
+from anthropic import Anthropic
+from anthropic.types import Message, MessageParam, TextBlockParam
- from pydantic import BaseModel
-
from e2e_config import unique_marker
-from e2e_http import Result, unwrap
-from endpoints_client import (
- CacheControl,
- EndpointsClient,
- MessagesResult,
- RichMessage,
- RichMessagesRequest,
- TextBlock,
-)
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
+from proxy_client import ProxyClient
++from pydantic import BaseModel
+from sdk_clients import SdkClients
pytestmark = pytest.mark.e2e
@@@ -47,53 -46,57 +47,53 @@@ UNFLAGGED_INVOKE_MODEL = "bedrock/invok
AWS_REGION = "us-east-1"
CACHE_PRIMING_DEADLINE_SECONDS = 60.0
CACHE_PRIMING_INTERVAL_SECONDS = 3.0
+ CACHE_WARM_CONSECUTIVE_READS = 3
-def _cacheable_system_block(marker: str) -> TextBlock:
+def _cacheable_system_block(marker: str) -> TextBlockParam:
- """A system prompt comfortably above Sonnet's 1024-token minimum cacheable
- size, unique per run so no other run's cache entry can satisfy the read."""
- text = " ".join(
- f"Reference paragraph {index} for run {marker}." for index in range(300)
- )
+ """A system prompt at roughly twice the 4096-token minimum cacheable size of
+ Haiku 4.5 (the smallest model here), unique per run so no other run's cache
+ entry can satisfy the read. The marker appears once instead of in every
+ paragraph: repeating it swung the block's size by ~1800 tokens with the
+ marker's own tokenization and left it under the minimum on ~15% of runs, so
+ the system breakpoint went uncached and the priming loop never saw a read."""
- text = f"Run {marker}.\n" + " ".join(
- f"Reference paragraph {index}." for index in range(1500)
- )
- return TextBlock(text=text, cache_control=CacheControl())
++ text = f"Run {marker}.\n" + " ".join(f"Reference paragraph {index}." for index in range(1500))
+ return {"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}
-def _user_turn(text: str, *, cached: bool = False) -> RichMessage:
- block = TextBlock(text=text, cache_control=CacheControl() if cached else None)
- return RichMessage(role="user", content=[block])
+def _user_turn(text: str, *, cached: bool = False) -> MessageParam:
+ block: TextBlockParam = (
- {"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}
- if cached
- else {"type": "text", "text": text}
++ {"type": "text", "text": text, "cache_control": {"type": "ephemeral"}} if cached else {"type": "text", "text": text}
+ )
+ return {"role": "user", "content": [block]}
-def _system_reminder_turn() -> RichMessage:
- return RichMessage(
- role="system",
- content=[
- TextBlock(
- text="<system-reminder>Answer with exactly one word.</system-reminder>"
- )
- ],
+def _system_reminder_turn() -> MessageParam:
+ return cast(
+ "MessageParam",
+ {
+ "role": "system",
- "content": [
- {
- "type": "text",
- "text": "<system-reminder>Answer with exactly one word.</system-reminder>",
- }
- ],
++ "content": [{"type": "text", "text": "<system-reminder>Answer with exactly one word.</system-reminder>"}],
+ },
)
-def _post_messages(
- client: EndpointsClient, key: str, body: RichMessagesRequest
-) -> Result[MessagesResult]:
- return client.proxy.transport.post(
- "/v1/messages",
- headers=client.proxy.transport.bearer(key),
- json=body,
- response_type=MessagesResult,
- )
++def _assistant_turn(text: str) -> MessageParam:
++ return {"role": "assistant", "content": [{"type": "text", "text": text}]}
++
++
+def _text(message: Message) -> str:
+ return "".join(block.text for block in message.content if block.type == "text")
--def _register_invoke_deployment(
- proxy: ProxyClient, resources: ResourceManager, bedrock_model: str
- client: EndpointsClient, resources: ResourceManager, bedrock_model: str
--) -> str:
++def _send(client: Anthropic, model: str, system_block: TextBlockParam, messages: Sequence[MessageParam]) -> Message:
++ return client.messages.create(model=model, max_tokens=64, system=[system_block], messages=messages)
++
++
++def _register_invoke_deployment(proxy: ProxyClient, resources: ResourceManager, bedrock_model: str) -> str:
model = f"e2e-midsys-{unique_marker()}"
- model_id = proxy.create_model(
- model_id = client.create_model(
-- model, LiteLLMParamsBody(model=bedrock_model, aws_region_name=AWS_REGION)
-- )
- resources.defer(lambda: client.delete_model(model_id))
++ model_id = proxy.create_model(model, LiteLLMParamsBody(model=bedrock_model, aws_region_name=AWS_REGION))
+ resources.defer(lambda: proxy.delete_model(model_id))
return model
@@@ -115,70 -118,109 +115,108 @@@ class PrimedCache(BaseModel)
return self.prefix_read_tokens + self.first_turn_creation_tokens
--def _prime_prompt_cache(
- client: Anthropic, model: str, system_block: TextBlockParam
- client: EndpointsClient, key: str, model: str, system_block: TextBlock
--) -> PrimedCache:
++def _prime_prompt_cache(client: Anthropic, model: str, system_block: TextBlockParam) -> PrimedCache:
"""Send first-turn calls (fresh cache-marked user turn each attempt,
identical system prefix) until one both reads the system prefix back from
- cache and writes its own user-turn chunk, proving the cache is live in both
- directions. Only the pre-reminder turn is ever retried here, so retries can
- never warm a mutated-prefix cache entry and mask the regression the second
- turn asserts on."""
+ cache and writes its own user-turn chunk, then re-send that exact turn until
+ its own chunk reads back on three sends in a row, proving the cache is live
+ in both directions before the reminder turn goes out (a freshly written entry
+ can take a few seconds to become readable). Only the pre-reminder turn is
+ ever retried here, so retries can never warm a mutated-prefix cache entry and
+ mask the regression the second turn asserts on."""
deadline = time.monotonic() + CACHE_PRIMING_DEADLINE_SECONDS
while True:
user_text = _first_turn_user_text(unique_marker())
- usage = client.messages.create(
- body = RichMessagesRequest(
-- model=model,
- max_tokens=64,
-- system=[system_block],
-- messages=[_user_turn(user_text, cached=True)],
- ).usage
- )
- usage = unwrap(_post_messages(client, key, body)).usage
- if usage.cache_read_input_tokens > 0 and usage.cache_creation_input_tokens > 0:
++ first_turn = (_user_turn(user_text, cached=True),)
++ usage = _send(client, model, system_block, first_turn).usage
+ read_tokens = usage.cache_read_input_tokens or 0
+ creation_tokens = usage.cache_creation_input_tokens or 0
+ if read_tokens > 0 and creation_tokens > 0:
- return PrimedCache(
+ primed = PrimedCache(
first_user_text=user_text,
- prefix_read_tokens=usage.cache_read_input_tokens,
- first_turn_creation_tokens=usage.cache_creation_input_tokens,
+ prefix_read_tokens=read_tokens,
+ first_turn_creation_tokens=creation_tokens,
)
- if _first_turn_reads_back(client, key, body, primed.full_prefix_tokens, deadline):
++ if _first_turn_reads_back(client, model, system_block, first_turn, primed.full_prefix_tokens, deadline):
+ return primed
if time.monotonic() >= deadline:
pytest.fail(
- f"{model}: prompt cache never became readable within "
+ f"{model}: prompt cache never became readable in full within "
f"{CACHE_PRIMING_DEADLINE_SECONDS}s (last usage: {usage})"
)
time.sleep(CACHE_PRIMING_INTERVAL_SECONDS)
+ def _reads_full_prefix(
- client: EndpointsClient, key: str, body: RichMessagesRequest, full_prefix_tokens: int
++ client: Anthropic,
++ model: str,
++ system_block: TextBlockParam,
++ messages: Sequence[MessageParam],
++ full_prefix_tokens: int,
+ ) -> bool:
- return unwrap(_post_messages(client, key, body)).usage.cache_read_input_tokens >= full_prefix_tokens
++ return (_send(client, model, system_block, messages).usage.cache_read_input_tokens or 0) >= full_prefix_tokens
+
+
+ def _first_turn_reads_back(
- client: EndpointsClient,
- key: str,
- body: RichMessagesRequest,
++ client: Anthropic,
++ model: str,
++ system_block: TextBlockParam,
++ messages: Sequence[MessageParam],
+ full_prefix_tokens: int,
+ deadline: float,
+ ) -> bool:
+ """True once the full prefix reads back on CACHE_WARM_CONSECUTIVE_READS sends in
+ a row. Some providers' global endpoints serve the prompt cache per region, so a
+ fresh entry can be missing from the region the next request lands on; each miss
+ re-creates the entry there, so the streak converges as the regions warm up."""
+ while time.monotonic() < deadline:
- if all(_reads_full_prefix(client, key, body, full_prefix_tokens) for _ in range(CACHE_WARM_CONSECUTIVE_READS)):
++ if all(
++ _reads_full_prefix(client, model, system_block, messages, full_prefix_tokens)
++ for _ in range(CACHE_WARM_CONSECUTIVE_READS)
++ ):
+ return True
+ time.sleep(CACHE_PRIMING_INTERVAL_SECONDS)
+ return False
+
+
++def _reminder_turn_messages(primed: PrimedCache) -> tuple[MessageParam, ...]:
++ return (
++ _user_turn(primed.first_user_text, cached=True),
++ _system_reminder_turn(),
++ _assistant_turn("OK."),
++ _user_turn("Reply with one word again.", cached=True),
++ )
++
++
+ #: Kept in sync with the copy in test_messages_mid_conversation_system_native_providers_e2e.py;
+ #: the e2e suites stay self-contained rather than importing across test modules.
+ MID_CONVERSATION_CACHE_SKIP_REASON = (
+ "LIT-4873: a mid-conversation role='system' reminder invalidates the prompt cache on the "
+ "vertex_ai / azure_ai / bedrock_invoke Messages paths, while the same request preserves it "
+ "both direct to Anthropic and through litellm's first-party anthropic path. Product bug, not "
+ "a test defect: the assertion here is correct and must be restored unchanged with the fix"
+ )
+
+
class TestBedrockInvokeMidConversationSystem:
+ @pytest.mark.skip(reason=MID_CONVERSATION_CACHE_SKIP_REASON)
@pytest.mark.covers(
"llm.messages.bedrock_invoke.mid_conversation_system.nonstream.cache_hit",
exercised_on=[],
)
def test_flagged_model_keeps_prompt_cache_across_system_reminder(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = _register_invoke_deployment(
- endpoints_client, resources, FLAGGED_INVOKE_MODEL
- )
- key = resources.key(models=[model])
+ model = _register_invoke_deployment(proxy, resources, FLAGGED_INVOKE_MODEL)
+ client = sdk.anthropic(resources.key(models=[model]))
system_block = _cacheable_system_block(unique_marker())
- primed = _prime_prompt_cache(endpoints_client, key, model, system_block)
-
- reminder_turn_body = RichMessagesRequest(
- model=model,
- system=[system_block],
- messages=[
- _user_turn(primed.first_user_text, cached=True),
- _system_reminder_turn(),
- RichMessage(role="assistant", content=[TextBlock(text="OK.")]),
- _user_turn("Reply with one word again.", cached=True),
- ],
- )
- second = unwrap(_post_messages(endpoints_client, key, reminder_turn_body))
+ primed = _prime_prompt_cache(client, model, system_block)
- second = client.messages.create(
- model=model,
- max_tokens=64,
- system=[system_block],
- messages=[
- _user_turn(primed.first_user_text, cached=True),
- _system_reminder_turn(),
- {"role": "assistant", "content": [{"type": "text", "text": "OK."}]},
- _user_turn("Reply with one word again.", cached=True),
- ],
- assert second.text.strip(), (
- f"{model}: reminder turn returned no completion text"
-- )
- assert second.usage.cache_read_input_tokens >= primed.full_prefix_tokens, (
++ second = _send(client, model, system_block, _reminder_turn_messages(primed))
+
- assert _text(second).strip(), (
- f"{model}: reminder turn returned no completion text"
- )
++ assert _text(second).strip(), f"{model}: reminder turn returned no completion text"
+ assert (second.usage.cache_read_input_tokens or 0) >= primed.full_prefix_tokens, (
f"{model}: turn with a mid-conversation system reminder read "
f"{second.usage.cache_read_input_tokens} cached tokens, expected at "
f"least the {primed.full_prefix_tokens} cached on turn one "
@@@ -192,29 -234,43 +230,29 @@@
"llm.messages.bedrock_invoke.mid_conversation_system.nonstream.works",
exercised_on=[],
)
- def test_unflagged_model_hoists_system_reminder_and_succeeds(
+ def test_unflagged_model_converts_system_reminder_and_succeeds(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = _register_invoke_deployment(
- endpoints_client, resources, UNFLAGGED_INVOKE_MODEL
- )
- key = resources.key(models=[model])
+ model = _register_invoke_deployment(proxy, resources, UNFLAGGED_INVOKE_MODEL)
+ client = sdk.anthropic(resources.key(models=[model]))
+ system_block = _cacheable_system_block(unique_marker())
- completion = client.messages.create(
- primed = _prime_prompt_cache(endpoints_client, key, model, system_block)
-
- reminder_turn_body = RichMessagesRequest(
-- model=model,
- max_tokens=64,
- system=[{"type": "text", "text": "You are terse."}],
- system=[system_block],
-- messages=[
- _user_turn(f"Say hi. Run {unique_marker()}."),
- _user_turn(primed.first_user_text, cached=True),
-- _system_reminder_turn(),
- {"role": "assistant", "content": [{"type": "text", "text": "Hi."}]},
- _user_turn("Say bye."),
- RichMessage(role="assistant", content=[TextBlock(text="OK.")]),
- _user_turn("Reply with one word again.", cached=True),
-- ],
-- )
- second = unwrap(_post_messages(endpoints_client, key, reminder_turn_body))
++ primed = _prime_prompt_cache(client, model, system_block)
- assert completion.role == "assistant", (
- f"{model}: unexpected role {completion.role!r}"
- assert second.role == "assistant", (
- f"{model}: unexpected role {second.role!r}"
-- )
- assert _text(completion).strip(), (
- assert second.text.strip(), (
++ second = _send(client, model, system_block, _reminder_turn_messages(primed))
++
++ assert second.role == "assistant", f"{model}: unexpected role {second.role!r}"
++ assert _text(second).strip(), (
f"{model}: conversation with a mid-conversation system reminder "
f"returned no text; the reminder was forwarded in place to a model "
- f"that rejects role 'system' inside messages instead of being hoisted"
+ f"that rejects role 'system' inside messages instead of being converted to a user turn"
+ )
- assert second.usage.cache_read_input_tokens >= primed.full_prefix_tokens, (
++ assert (second.usage.cache_read_input_tokens or 0) >= primed.full_prefix_tokens, (
+ f"{model}: reminder turn read {second.usage.cache_read_input_tokens} "
+ f"cached tokens, expected at least the {primed.full_prefix_tokens} "
+ f"cached on turn one ({primed.prefix_read_tokens} system prefix + "
+ f"{primed.first_turn_creation_tokens} first user turn); the reminder "
+ f"was hoisted into the top-level system field instead of being "
+ f"converted to a user turn in place, mutating the cached prefix and "
+ f"re-billing the conversation at cache-write pricing"
)
diff --cc tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py
index 9a0af34fb5d,8c448399be1..e95bc60d7cc
--- a/tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py
+++ b/tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py
@@@ -34,18 -29,22 +34,18 @@@ test
from __future__ import annotations
import time
++from collections.abc import Sequence
+from typing import cast
import pytest
-from pydantic import BaseModel
-
+from anthropic import Anthropic
+from anthropic.types import Message, MessageParam, TextBlockParam
- from pydantic import BaseModel
-
from e2e_config import unique_marker
-from e2e_http import Result, unwrap
-from endpoints_client import (
- CacheControl,
- EndpointsClient,
- MessagesResult,
- RichMessage,
- RichMessagesRequest,
- TextBlock,
-)
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
+from proxy_client import ProxyClient
++from pydantic import BaseModel
+from sdk_clients import SdkClients
pytestmark = pytest.mark.e2e
@@@ -69,47 -69,46 +70,50 @@@ def _vertex_params(model: str, location
)
-def _cacheable_system_block(marker: str) -> TextBlock:
+def _cacheable_system_block(marker: str) -> TextBlockParam:
- """A system prompt comfortably above the 1024-token minimum cacheable size,
- unique per run so no other run's cache entry can satisfy the read."""
- text = " ".join(f"Reference paragraph {index} for run {marker}." for index in range(300))
+ """A system prompt at roughly twice the 4096-token minimum cacheable size of
+ Haiku 4.5 (the smallest model here), unique per run so no other run's cache
+ entry can satisfy the read. The marker appears once instead of in every
+ paragraph: repeating it swung the block's size by ~1800 tokens with the
+ marker's own tokenization and left it under the minimum on ~15% of runs, so
+ the system breakpoint went uncached and the priming loop never saw a read."""
- text = f"Run {marker}.\n" + " ".join(
- f"Reference paragraph {index}." for index in range(1500)
- )
- return TextBlock(text=text, cache_control=CacheControl())
++ text = f"Run {marker}.\n" + " ".join(f"Reference paragraph {index}." for index in range(1500))
+ return {"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}
-def _user_turn(text: str, *, cached: bool = False) -> RichMessage:
- block = TextBlock(text=text, cache_control=CacheControl() if cached else None)
- return RichMessage(role="user", content=[block])
+def _user_turn(text: str, *, cached: bool = False) -> MessageParam:
+ block: TextBlockParam = (
- {"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}
- if cached
- else {"type": "text", "text": text}
++ {"type": "text", "text": text, "cache_control": {"type": "ephemeral"}} if cached else {"type": "text", "text": text}
+ )
+ return {"role": "user", "content": [block]}
-def _system_reminder_turn() -> RichMessage:
- return RichMessage(
- role="system",
- content=[TextBlock(text="<system-reminder>Answer with exactly one word.</system-reminder>")],
+def _system_reminder_turn() -> MessageParam:
+ return cast(
+ "MessageParam",
+ {
+ "role": "system",
- "content": [
- {
- "type": "text",
- "text": "<system-reminder>Answer with exactly one word.</system-reminder>",
- }
- ],
++ "content": [{"type": "text", "text": "<system-reminder>Answer with exactly one word.</system-reminder>"}],
+ },
)
-def _post_messages(client: EndpointsClient, key: str, body: RichMessagesRequest) -> Result[MessagesResult]:
- return client.proxy.transport.post(
- "/v1/messages",
- headers=client.proxy.transport.bearer(key),
- json=body,
- response_type=MessagesResult,
- )
++def _assistant_turn(text: str) -> MessageParam:
++ return {"role": "assistant", "content": [{"type": "text", "text": text}]}
++
++
+def _text(message: Message) -> str:
+ return "".join(block.text for block in message.content if block.type == "text")
+
+
- def _register_deployment(
- proxy: ProxyClient, resources: ResourceManager, params: LiteLLMParamsBody
- ) -> str:
++def _send(client: Anthropic, model: str, system_block: TextBlockParam, messages: Sequence[MessageParam]) -> Message:
++ return client.messages.create(model=model, max_tokens=64, system=[system_block], messages=messages)
+
+
-def _register_deployment(
- client: EndpointsClient, resources: ResourceManager, params: LiteLLMParamsBody
-) -> str:
++def _register_deployment(proxy: ProxyClient, resources: ResourceManager, params: LiteLLMParamsBody) -> str:
model = f"e2e-midsys-{unique_marker()}"
- model_id = client.create_model(model, params)
- resources.defer(lambda: client.delete_model(model_id))
+ model_id = proxy.create_model(model, params)
+ resources.defer(lambda: proxy.delete_model(model_id))
return model
@@@ -131,66 -130,107 +135,110 @@@ class PrimedCache(BaseModel)
return self.prefix_read_tokens + self.first_turn_creation_tokens
--def _prime_prompt_cache(
- client: Anthropic, model: str, system_block: TextBlockParam
- client: EndpointsClient, key: str, model: str, system_block: TextBlock
--) -> PrimedCache:
++def _prime_prompt_cache(client: Anthropic, model: str, system_block: TextBlockParam) -> PrimedCache:
"""Send first-turn calls (fresh cache-marked user turn each attempt,
identical system prefix) until one both reads the system prefix back from
- cache and writes its own user-turn chunk, proving the cache is live in both
- directions. Only the pre-reminder turn is ever retried here, so retries can
- never warm a mutated-prefix cache entry and mask the regression the second
- turn asserts on."""
+ cache and writes its own user-turn chunk, then re-send that exact turn until
+ its own chunk reads back on three sends in a row, proving the cache is live
+ in both directions before the reminder turn goes out (a freshly written entry
+ can take a few seconds to become readable). Only the pre-reminder turn is
+ ever retried here, so retries can never warm a mutated-prefix cache entry and
+ mask the regression the second turn asserts on."""
deadline = time.monotonic() + CACHE_PRIMING_DEADLINE_SECONDS
while True:
user_text = _first_turn_user_text(unique_marker())
- usage = client.messages.create(
- body = RichMessagesRequest(
-- model=model,
- max_tokens=64,
-- system=[system_block],
-- messages=[_user_turn(user_text, cached=True)],
- ).usage
- )
- usage = unwrap(_post_messages(client, key, body)).usage
- if usage.cache_read_input_tokens > 0 and usage.cache_creation_input_tokens > 0:
++ first_turn = (_user_turn(user_text, cached=True),)
++ usage = _send(client, model, system_block, first_turn).usage
+ read_tokens = usage.cache_read_input_tokens or 0
+ creation_tokens = usage.cache_creation_input_tokens or 0
+ if read_tokens > 0 and creation_tokens > 0:
- return PrimedCache(
+ primed = PrimedCache(
first_user_text=user_text,
- prefix_read_tokens=usage.cache_read_input_tokens,
- first_turn_creation_tokens=usage.cache_creation_input_tokens,
+ prefix_read_tokens=read_tokens,
+ first_turn_creation_tokens=creation_tokens,
)
- if _first_turn_reads_back(client, key, body, primed.full_prefix_tokens, deadline):
++ if _first_turn_reads_back(client, model, system_block, first_turn, primed.full_prefix_tokens, deadline):
+ return primed
if time.monotonic() >= deadline:
pytest.fail(
- f"{model}: prompt cache never became readable within "
+ f"{model}: prompt cache never became readable in full within "
f"{CACHE_PRIMING_DEADLINE_SECONDS}s (last usage: {usage})"
)
time.sleep(CACHE_PRIMING_INTERVAL_SECONDS)
+ def _reads_full_prefix(
- client: EndpointsClient, key: str, body: RichMessagesRequest, full_prefix_tokens: int
++ client: Anthropic,
++ model: str,
++ system_block: TextBlockParam,
++ messages: Sequence[MessageParam],
++ full_prefix_tokens: int,
+ ) -> bool:
- return unwrap(_post_messages(client, key, body)).usage.cache_read_input_tokens >= full_prefix_tokens
++ return (_send(client, model, system_block, messages).usage.cache_read_input_tokens or 0) >= full_prefix_tokens
+
+
+ def _first_turn_reads_back(
- client: EndpointsClient,
- key: str,
- body: RichMessagesRequest,
++ client: Anthropic,
++ model: str,
++ system_block: TextBlockParam,
++ messages: Sequence[MessageParam],
+ full_prefix_tokens: int,
+ deadline: float,
+ ) -> bool:
+ """True once the full prefix reads back on CACHE_WARM_CONSECUTIVE_READS sends in
+ a row. Some providers' global endpoints serve the prompt cache per region, so a
+ fresh entry can be missing from the region the next request lands on; each miss
+ re-creates the entry there, so the streak converges as the regions warm up."""
+ while time.monotonic() < deadline:
- if all(_reads_full_prefix(client, key, body, full_prefix_tokens) for _ in range(CACHE_WARM_CONSECUTIVE_READS)):
++ if all(
++ _reads_full_prefix(client, model, system_block, messages, full_prefix_tokens)
++ for _ in range(CACHE_WARM_CONSECUTIVE_READS)
++ ):
+ return True
+ time.sleep(CACHE_PRIMING_INTERVAL_SECONDS)
+ return False
+
+
++def _reminder_turn_messages(primed: PrimedCache) -> tuple[MessageParam, ...]:
++ return (
++ _user_turn(primed.first_user_text, cached=True),
++ _system_reminder_turn(),
++ _assistant_turn("OK."),
++ _user_turn("Reply with one word again.", cached=True),
++ )
++
++
+ #: Why the flagged-model cache checks are skipped rather than failing. The
+ #: assertions below are correct and must be restored unchanged when the bug is
+ #: fixed; they are the regression guard for a real billing cost.
+ #:
+ #: Measured cache_read_input_tokens on the reminder turn, same conversation shape:
+ #: direct to api.anthropic.com 7013 preserved
+ #: litellm -> anthropic/claude-opus-4-8 7013 preserved
+ #: litellm -> vertex_ai/claude-opus-4-8 0 destroyed
+ #: and the Vertex control with the same added turns but no reminder reads 7013,
+ #: so it is the reminder on the non-first-party paths, not the extra turns.
+ MID_CONVERSATION_CACHE_SKIP_REASON = (
+ "LIT-4873: a mid-conversation role='system' reminder invalidates the prompt cache on the "
+ "vertex_ai / azure_ai / bedrock_invoke Messages paths, while the same request preserves it "
+ "both direct to Anthropic and through litellm's first-party anthropic path. Product bug, not "
+ "a test defect: the assertion here is correct and must be restored unchanged with the fix"
+ )
+
+
def _assert_flagged_model_keeps_cache(
- proxy: ProxyClient,
- resources: ResourceManager,
- sdk: SdkClients,
- params: LiteLLMParamsBody,
- client: EndpointsClient, resources: ResourceManager, params: LiteLLMParamsBody
++ proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients, params: LiteLLMParamsBody
) -> None:
- model = _register_deployment(client, resources, params)
- key = resources.key(models=[model])
+ model = _register_deployment(proxy, resources, params)
+ client = sdk.anthropic(resources.key(models=[model]))
system_block = _cacheable_system_block(unique_marker())
- primed = _prime_prompt_cache(client, key, model, system_block)
+ primed = _prime_prompt_cache(client, model, system_block)
- second = client.messages.create(
- reminder_turn_body = RichMessagesRequest(
-- model=model,
- max_tokens=64,
-- system=[system_block],
-- messages=[
-- _user_turn(primed.first_user_text, cached=True),
-- _system_reminder_turn(),
- {"role": "assistant", "content": [{"type": "text", "text": "OK."}]},
- RichMessage(role="assistant", content=[TextBlock(text="OK.")]),
-- _user_turn("Reply with one word again.", cached=True),
-- ],
-- )
- second = unwrap(_post_messages(client, key, reminder_turn_body))
++ second = _send(client, model, system_block, _reminder_turn_messages(primed))
- assert second.text.strip(), f"{model}: reminder turn returned no completion text"
- assert second.usage.cache_read_input_tokens >= primed.full_prefix_tokens, (
+ assert _text(second).strip(), f"{model}: reminder turn returned no completion text"
+ assert (second.usage.cache_read_input_tokens or 0) >= primed.full_prefix_tokens, (
f"{model}: turn with a mid-conversation system reminder read "
f"{second.usage.cache_read_input_tokens} cached tokens, expected at "
f"least the {primed.full_prefix_tokens} cached on turn one "
@@@ -201,32 -241,41 +249,31 @@@
)
- def _assert_unflagged_model_hoists_and_succeeds(
- proxy: ProxyClient,
- resources: ResourceManager,
- sdk: SdkClients,
- params: LiteLLMParamsBody,
+ def _assert_unflagged_model_converts_and_succeeds(
- client: EndpointsClient, resources: ResourceManager, params: LiteLLMParamsBody
++ proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients, params: LiteLLMParamsBody
) -> None:
- model = _register_deployment(client, resources, params)
- key = resources.key(models=[model])
+ model = _register_deployment(proxy, resources, params)
+ client = sdk.anthropic(resources.key(models=[model]))
+ system_block = _cacheable_system_block(unique_marker())
- completion = client.messages.create(
- model=model,
- max_tokens=64,
- system=[{"type": "text", "text": "You are terse."}],
- messages=[
- _user_turn(f"Say hi. Run {unique_marker()}."),
- _system_reminder_turn(),
- {"role": "assistant", "content": [{"type": "text", "text": "Hi."}]},
- _user_turn("Say bye."),
- ],
- )
- primed = _prime_prompt_cache(client, key, model, system_block)
++ primed = _prime_prompt_cache(client, model, system_block)
- assert completion.role == "assistant", f"{model}: unexpected role {completion.role!r}"
- assert _text(completion).strip(), (
- reminder_turn_body = RichMessagesRequest(
- model=model,
- system=[system_block],
- messages=[
- _user_turn(primed.first_user_text, cached=True),
- _system_reminder_turn(),
- RichMessage(role="assistant", content=[TextBlock(text="OK.")]),
- _user_turn("Reply with one word again.", cached=True),
- ],
- )
- second = unwrap(_post_messages(client, key, reminder_turn_body))
++ second = _send(client, model, system_block, _reminder_turn_messages(primed))
+
+ assert second.role == "assistant", f"{model}: unexpected role {second.role!r}"
- assert second.text.strip(), (
++ assert _text(second).strip(), (
f"{model}: conversation with a mid-conversation system reminder returned "
f"no text; the reminder was forwarded in place to a model that rejects "
- f"role 'system' inside messages instead of being hoisted"
+ f"role 'system' inside messages instead of being converted to a user turn"
+ )
- assert second.usage.cache_read_input_tokens >= primed.full_prefix_tokens, (
++ assert (second.usage.cache_read_input_tokens or 0) >= primed.full_prefix_tokens, (
+ f"{model}: reminder turn read {second.usage.cache_read_input_tokens} cached "
+ f"tokens, expected at least the {primed.full_prefix_tokens} cached on turn "
+ f"one ({primed.prefix_read_tokens} system prefix + "
+ f"{primed.first_turn_creation_tokens} first user turn); the reminder was "
+ f"hoisted into the top-level system field instead of being converted to a "
+ f"user turn in place, mutating the cached prefix and re-billing the "
+ f"conversation at cache-write pricing"
)
@@@ -247,12 -297,12 +295,10 @@@ class TestAzureFoundryMidConversationSy
"llm.messages.azure_foundry.mid_conversation_system.nonstream.works",
exercised_on=[],
)
- def test_unflagged_model_hoists_system_reminder_and_succeeds(
+ def test_unflagged_model_converts_system_reminder_and_succeeds(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- _assert_unflagged_model_hoists_and_succeeds(
- proxy, resources, sdk, _azure_params(self.UNFLAGGED_MODEL)
- _assert_unflagged_model_converts_and_succeeds(
- endpoints_client, resources, _azure_params(self.UNFLAGGED_MODEL)
-- )
++ _assert_unflagged_model_converts_and_succeeds(proxy, resources, sdk, _azure_params(self.UNFLAGGED_MODEL))
class TestVertexMidConversationSystem:
@@@ -264,17 -323,19 +319,19 @@@
exercised_on=[],
)
def test_flagged_model_keeps_prompt_cache_across_system_reminder(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- _assert_flagged_model_keeps_cache(proxy, resources, sdk, _vertex_params(self.FLAGGED_MODEL))
+ _assert_flagged_model_keeps_cache(
- endpoints_client, resources, _vertex_params(self.FLAGGED_MODEL, self.FLAGGED_LOCATION)
++ proxy, resources, sdk, _vertex_params(self.FLAGGED_MODEL, self.FLAGGED_LOCATION)
+ )
@pytest.mark.covers(
"llm.messages.vertex.mid_conversation_system.nonstream.works",
exercised_on=[],
)
- def test_unflagged_model_hoists_system_reminder_and_succeeds(
+ def test_unflagged_model_converts_system_reminder_and_succeeds(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- _assert_unflagged_model_hoists_and_succeeds(
- proxy, resources, sdk, _vertex_params(self.UNFLAGGED_MODEL)
+ _assert_unflagged_model_converts_and_succeeds(
- endpoints_client, resources, _vertex_params(self.UNFLAGGED_MODEL, self.UNFLAGGED_LOCATION)
++ proxy, resources, sdk, _vertex_params(self.UNFLAGGED_MODEL, self.UNFLAGGED_LOCATION)
)
diff --cc tests/e2e/llm_translation/test_moderations_e2e.py
index bc26d79dcab,0395a4b2848..e936f7b335a
--- a/tests/e2e/llm_translation/test_moderations_e2e.py
+++ b/tests/e2e/llm_translation/test_moderations_e2e.py
@@@ -1,22 -1,19 +1,23 @@@
"""Live e2e: POST /v1/moderations classifies content against the provider policy.
-Registers OpenAI's omni moderation model at runtime and asserts the product
-promise on both sides of the decision: clearly violent text comes back flagged
-with at least one policy category tripped, and benign text comes back not flagged.
+Registers OpenAI's omni moderation model at runtime, drives it through the real
+OpenAI SDK (LIT-4577), and asserts the product promise on both sides of the
+decision: clearly violent text comes back flagged with at least one policy
- category tripped, and benign text comes back not flagged.
++category tripped, and benign text comes back not flagged. The malformed-body
++negative stays on the shared transport, since the SDK refuses to send it.
"""
from __future__ import annotations
import pytest
- from openai.types import Moderation
- from pydantic import TypeAdapter
-
from e2e_config import unique_marker
-from e2e_http import assert_client_error, unwrap
-from endpoints_client import EndpointsClient
++from e2e_http import assert_client_error
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
-from pydantic import BaseModel
++from openai.types import Moderation
+from proxy_client import ProxyClient
++from pydantic import BaseModel, TypeAdapter
+from sdk_clients import SdkClients
pytestmark = pytest.mark.e2e
@@@ -24,9 -21,16 +25,14 @@@ VIOLENT_TEXT = "I am going to find you
BENIGN_TEXT = "I enjoyed the sunny afternoon and a relaxing walk in the park today."
+ class _OptionalModerationBody(BaseModel):
+ model: str | None = None
+ input: str | None = None
+
+
-def _register_moderation_model(
- endpoints_client: EndpointsClient, resources: ResourceManager
-) -> str:
+def _register_moderation_model(proxy: ProxyClient, resources: ResourceManager) -> str:
model = f"e2e-moderation-{unique_marker()}"
- model_id = endpoints_client.create_model(
+ model_id = proxy.create_model(
model,
LiteLLMParamsBody(
model="openai/omni-moderation-latest", api_key="os.environ/OPENAI_API_KEY"
@@@ -47,26 -43,42 +53,40 @@@ def _flagged_categories(item: Moderatio
class TestModerations:
@pytest.mark.covers("llm.moderations.openai.basic.nonstream.works")
def test_moderations_flags_violent_content(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = _register_moderation_model(endpoints_client, resources)
- key = resources.key()
+ model = _register_moderation_model(proxy, resources)
+ client = sdk.openai(resources.key())
- result = unwrap(endpoints_client.moderations(key, model, VIOLENT_TEXT))
- item = result.first
- assert item is not None, f"/moderations returned no results: {result}"
- assert item.flagged, f"violent text was not flagged: {item}"
- assert item.flagged_categories, (
- f"flagged result reported no true category: {item}"
- )
+ moderation = client.moderations.create(model=model, input=VIOLENT_TEXT)
+ assert moderation.results, f"/moderations returned no results: {moderation!r}"
+ item = moderation.results[0]
+ assert item.flagged, f"violent text was not flagged: {item!r}"
+ assert _flagged_categories(item), f"flagged result reported no true category: {item!r}"
def test_moderations_passes_benign_content(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = _register_moderation_model(endpoints_client, resources)
- key = resources.key()
+ model = _register_moderation_model(proxy, resources)
+ client = sdk.openai(resources.key())
- result = unwrap(endpoints_client.moderations(key, model, BENIGN_TEXT))
- item = result.first
- assert item is not None, f"/moderations returned no results: {result}"
+ moderation = client.moderations.create(model=model, input=BENIGN_TEXT)
+ assert moderation.results, f"/moderations returned no results: {moderation!r}"
+ item = moderation.results[0]
assert not item.flagged, (
- f"benign text was flagged as {item.flagged_categories}: {item}"
+ f"benign text was flagged as {_flagged_categories(item)}: {item!r}"
)
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/moderations 500s (KeyError 'input') on missing input instead of 400")
+ @pytest.mark.covers("llm.moderations.openai.input_validation.nonstream.works")
+ def test_missing_input_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
- model = _register_moderation_model(endpoints_client, resources)
++ model = _register_moderation_model(proxy, resources)
+ key = resources.key()
- result = endpoints_client.proxy.transport.send(
++ result = proxy.transport.send(
+ "/v1/moderations",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalModerationBody(model=model),
+ )
+ assert_client_error(result, "moderations missing input")
diff --cc tests/e2e/llm_translation/test_ocr_rust_e2e.py
index 986ac675e98,e83920111c7..c2560b199af
--- a/tests/e2e/llm_translation/test_ocr_rust_e2e.py
+++ b/tests/e2e/llm_translation/test_ocr_rust_e2e.py
@@@ -19,12 -19,12 +19,12 @@@ from dataclasses import dataclas
from typing import Protocol
import pytest
-
from e2e_config import unique_marker
- from e2e_http import unwrap
+ from e2e_http import assert_client_error, unwrap
-from endpoints_client import EndpointsClient
from lifecycle import ResourceManager
from models import LiteLLMParamsBody, OcrBody, OcrDocument, OcrResponse
+from proxy_client import ProxyClient
+ from pydantic import BaseModel
pytestmark = pytest.mark.e2e
@@@ -143,14 -149,29 +149,29 @@@ def _assert_ocr_document(response: OcrR
class TestRustOcrGateway:
@pytest.mark.parametrize("case", RUST_OCR_CASES, ids=_CASE_IDS)
def test_rust_ocr_response(
- self, endpoints_client: EndpointsClient, resources: ResourceManager, case: _OcrCase
+ self, proxy: ProxyClient, resources: ResourceManager, case: _OcrCase
) -> None:
model = f"rust-ocr-{case.suffix}-{unique_marker()}"
- model_id = endpoints_client.create_model(model, case.provider.litellm_params())
- resources.defer(lambda: endpoints_client.delete_model(model_id))
+ model_id = proxy.create_model(model, case.provider.litellm_params())
+ resources.defer(lambda: proxy.delete_model(model_id))
key = resources.key()
- response = unwrap(endpoints_client.proxy.ocr(key, OcrBody(model=model, document=case.document)))
+ response = unwrap(proxy.ocr(key, OcrBody(model=model, document=case.document)))
_assert_ocr_document(response)
+ @pytest.mark.skip(reason="stage red: product gap, /v1/ocr 500s (aocr TypeError) on missing document instead of 400")
+ @pytest.mark.covers("llm.ocr.openai.input_validation.nonstream.works")
+ def test_missing_document_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
++ self, proxy: ProxyClient, resources: ResourceManager
+ ) -> None:
+ model = f"rust-ocr-val-{unique_marker()}"
- model_id = endpoints_client.create_model(model, MistralOcr().litellm_params())
- resources.defer(lambda: endpoints_client.delete_model(model_id))
++ model_id = proxy.create_model(model, MistralOcr().litellm_params())
++ resources.defer(lambda: proxy.delete_model(model_id))
+ key = resources.key()
- result = endpoints_client.proxy.transport.send(
++ result = proxy.transport.send(
+ "/v1/ocr",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalOcrBody(model=model),
+ )
+ assert_client_error(result, "ocr missing document")
diff --cc tests/e2e/llm_translation/test_rerank_e2e.py
index c0e4d7def42,c9f58b2c03c..87b8618e6fb
--- a/tests/e2e/llm_translation/test_rerank_e2e.py
+++ b/tests/e2e/llm_translation/test_rerank_e2e.py
@@@ -1,20 -1,19 +1,20 @@@
"""Live e2e: POST /v1/rerank ranks documents by relevance.
--Registers a Cohere rerank deployment at runtime and asserts the endpoint returns
- scored results within the requested top_n. No official OpenAI/Anthropic SDK
- covers /v1/rerank, so the call rides the shared typed transport via
- ProxyClient.rerank.
-scored results within the requested top_n. Migrated from
++Registers Cohere and Bedrock rerank deployments at runtime and asserts the
++endpoint returns scored results within the requested top_n. No official
++OpenAI/Anthropic SDK covers /v1/rerank, so the call rides the shared typed
++transport via ProxyClient.rerank. Migrated from
+ litellm-regression-tests/tests/test_inference_endpoints.py.
"""
from __future__ import annotations
import pytest
--
- from e2e_config import require_env, unique_marker
+ from e2e_config import unique_marker
-from e2e_http import require_successful_call
-from endpoints_client import EndpointsClient, RerankResult
+from e2e_http import unwrap
from lifecycle import ResourceManager
-from models import LiteLLMParamsBody
+from models import LiteLLMParamsBody, RerankBody, RerankResponse
+from proxy_client import ProxyClient
pytestmark = pytest.mark.e2e
@@@ -27,51 -26,49 +27,48 @@@ DOCUMENTS =
QUERY = "What is the capital of the United States?"
-def _assert_top_n_scored(body: str) -> None:
- parsed = RerankResult.model_validate_json(body)
- assert parsed.results, f"/rerank returned no results: {body[:300]}"
- assert len(parsed.results) <= 3, f"top_n=3 not honored: {body[:300]}"
- assert parsed.results[0].relevance_score is not None, (
- f"top rerank result has no relevance_score: {body[:300]}"
+def _assert_top_n_scored(response: RerankResponse) -> None:
+ assert response.results, f"/rerank returned no results: {response!r}"
+ assert len(response.results) <= 3, f"top_n=3 not honored: {response!r}"
+ assert response.results[0].relevance_score is not None, (
+ f"top rerank result has no relevance_score: {response!r}"
+ )
+
+
++def _rerank_top_3(proxy: ProxyClient, key: str, model: str) -> RerankResponse:
++ return unwrap(
++ proxy.rerank(key, RerankBody(model=model, query=QUERY, documents=DOCUMENTS, top_n=3))
+ )
+
+
class TestRerank:
@pytest.mark.covers("llm.rerank.cohere.basic.nonstream.works")
-- def test_rerank_scores_top_n(
- self, proxy: ProxyClient, resources: ResourceManager
- self, endpoints_client: EndpointsClient, resources: ResourceManager
-- ) -> None:
++ def test_rerank_scores_top_n(self, proxy: ProxyClient, resources: ResourceManager) -> None:
model = f"e2e-rerank-{unique_marker()}"
- model_id = endpoints_client.create_model(
+ model_id = proxy.create_model(
model,
LiteLLMParamsBody(model="cohere/rerank-v3.5", api_key="os.environ/COHERE_API_KEY"),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
+ resources.defer(lambda: proxy.delete_model(model_id))
key = resources.key()
- response = unwrap(
- proxy.rerank(key, RerankBody(model=model, query=QUERY, documents=DOCUMENTS, top_n=3))
- )
- _assert_top_n_scored(response)
- result = endpoints_client.rerank(key, model, QUERY, DOCUMENTS, top_n=3)
- require_successful_call(result)
- _assert_top_n_scored(result.body)
++ _assert_top_n_scored(_rerank_top_3(proxy, key, model))
@pytest.mark.covers("llm.rerank.bedrock.basic.nonstream.works", exercised_on=["rerank"])
def test_bedrock_rerank_scores_top_n(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager
) -> None:
- require_env("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION")
model = f"e2e-bedrock-rerank-{unique_marker()}"
- model_id = endpoints_client.create_model(
+ model_id = proxy.create_model(
model,
LiteLLMParamsBody(
- model="bedrock/amazon.rerank-v1:0",
+ model="bedrock/arn:aws:bedrock:us-east-1::foundation-model/cohere.rerank-v3-5:0",
aws_access_key_id="os.environ/AWS_ACCESS_KEY_ID",
aws_secret_access_key="os.environ/AWS_SECRET_ACCESS_KEY",
aws_region_name="os.environ/AWS_REGION",
),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
+ resources.defer(lambda: proxy.delete_model(model_id))
key = resources.key()
- response = unwrap(
- proxy.rerank(key, RerankBody(model=model, query=QUERY, documents=DOCUMENTS, top_n=3))
- )
- _assert_top_n_scored(response)
- result = endpoints_client.rerank(key, model, QUERY, DOCUMENTS, top_n=3)
- require_successful_call(result)
- _assert_top_n_scored(result.body)
++ _assert_top_n_scored(_rerank_top_3(proxy, key, model))
diff --cc tests/e2e/llm_translation/test_responses_e2e.py
index 93f844505d0,3fcf2d1ac05..db951ea0403
--- a/tests/e2e/llm_translation/test_responses_e2e.py
+++ b/tests/e2e/llm_translation/test_responses_e2e.py
@@@ -1,8 -1,8 +1,10 @@@
"""Live e2e: POST /v1/responses returns a real completion.
-Registers an OpenAI deployment at runtime, drives the Responses API through the
-gateway, and asserts output text came back. Migrated from
+Registers an OpenAI deployment at runtime and drives the Responses API through
+the gateway with the real OpenAI SDK, the client customers actually use
- (LIT-4577), asserting output text came back.
++(LIT-4577), asserting output text came back. Malformed bodies the SDK refuses
++to build stay on the shared transport. Migrated from
+ litellm-regression-tests/tests/test_inference_endpoints.py.
"""
from __future__ import annotations
@@@ -11,45 -11,43 +13,52 @@@ import jso
from typing import cast
import pytest
+ from e2e_config import unique_marker
-from e2e_http import (
- assert_client_error,
- require_successful_call,
-)
-from endpoints_client import (
- EndpointsClient,
- FunctionParameterProperty,
- FunctionParameters,
- ResponsesFunctionTool,
- ResponsesOutputTextDeltaEvent,
- ResponsesResult,
- ResponsesStreamEventType,
-)
++from e2e_http import assert_client_error
+ from lifecycle import ResourceManager
+ from models import LiteLLMParamsBody
-from pydantic import BaseModel, ValidationError
+from openai.types.responses import (
+ FunctionToolParam,
+ Response,
+ ResponseFunctionToolCall,
+ ResponseInputParam,
+)
- from pydantic import BaseModel
-
- from e2e_config import require_env, unique_marker
- from lifecycle import ResourceManager
- from models import LiteLLMParamsBody
+from proxy_client import ProxyClient
++from pydantic import BaseModel
+from sdk_clients import SdkClients
pytestmark = pytest.mark.e2e
+
+ class _OptionalResponsesBody(BaseModel):
+ model: str | None = None
+ input: str | None = None
+ max_output_tokens: int | None = None
+
+
BEDROCK_CONVERSE_BACKEND = "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0"
+INSTRUCTIONS = "You are a helpful assistant"
+CAT_IMAGE_URL = "https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg"
-WEATHER_TOOL = ResponsesFunctionTool(
- name="get_weather",
- description="Get the weather for a location",
- parameters=FunctionParameters(
- properties={"location": FunctionParameterProperty(type="string")},
- required=["location"],
- ),
-)
+WEATHER_TOOL: FunctionToolParam = {
+ "type": "function",
+ "name": "get_weather",
+ "description": "Get the weather for a location",
+ "parameters": {
+ "type": "object",
+ "properties": {"location": {"type": "string"}},
+ "required": ["location"],
+ },
+ "strict": False,
+}
+
+
+def _openai_params() -> LiteLLMParamsBody:
+ return LiteLLMParamsBody(model="openai/gpt-4o-mini", api_key="os.environ/OPENAI_API_KEY")
+
+
+def _anthropic_params() -> LiteLLMParamsBody:
+ return LiteLLMParamsBody(model="anthropic/claude-haiku-4-5", api_key="os.environ/ANTHROPIC_API_KEY")
def _bedrock_params() -> LiteLLMParamsBody:
@@@ -61,25 -59,6 +70,27 @@@
)
- def _register(proxy: ProxyClient, resources: ResourceManager, params: LiteLLMParamsBody) -> str:
- model = f"e2e-responses-{unique_marker()}"
++def _register(
++ proxy: ProxyClient, resources: ResourceManager, params: LiteLLMParamsBody, prefix: str = "e2e-responses"
++) -> str:
++ model = f"{prefix}-{unique_marker()}"
+ model_id = proxy.create_model(model, params)
+ resources.defer(lambda: proxy.delete_model(model_id))
+ return model
+
+
+def _function_calls(response: Response) -> tuple[ResponseFunctionToolCall, ...]:
+ return tuple(item for item in response.output if isinstance(item, ResponseFunctionToolCall))
+
+
+def _assert_weather_call(response: Response) -> None:
+ function_call = next((call for call in _function_calls(response) if call.name == "get_weather"), None)
+ assert function_call is not None, f"no get_weather function call: {response.output!r}"
+ raw_arguments = cast(object, json.loads(function_call.arguments))
+ arguments = WeatherArguments.model_validate(raw_arguments)
+ assert arguments.location, f"function call arguments missing location: {function_call.arguments}"
+
+
class WeatherArguments(BaseModel):
location: str
@@@ -87,33 -66,47 +98,31 @@@
class TestResponses:
@pytest.mark.covers("llm.responses.openai.basic.nonstream.works")
def test_responses_returns_completion(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-responses-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- LiteLLMParamsBody(model="openai/gpt-4o-mini", api_key="os.environ/OPENAI_API_KEY"),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
+ model = _register(proxy, resources, _openai_params())
+ client = sdk.openai(resources.key())
- response = client.responses.create(
- model=model, input="reply with one word", instructions=INSTRUCTIONS
- )
- result = endpoints_client.responses(key, model, "reply with one word")
- require_successful_call(result)
- parsed = ResponsesResult.model_validate_json(result.body)
- assert parsed.text.strip(), f"/responses returned no output text: {result.body[:300]}"
++ response = client.responses.create(model=model, input="reply with one word", instructions=INSTRUCTIONS)
+ assert response.output_text.strip(), f"/responses returned no output text: {response.output!r}"
@pytest.mark.covers("llm.responses.openai.basic.stream.works")
def test_responses_streaming_returns_completion(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-responses-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- LiteLLMParamsBody(model="openai/gpt-4o-mini", api_key="os.environ/OPENAI_API_KEY"),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
+ model = _register(proxy, resources, _openai_params())
+ client = sdk.openai(resources.key())
- result = endpoints_client.responses(key, model, "reply with one word", stream=True)
- require_successful_call(result)
- delta_events = tuple(
- parsed
- for event in result.stream_events
- if (parsed := _parse_stream_event(event)) is not None
+ stream = client.responses.create(
+ model=model, input="reply with one word", instructions=INSTRUCTIONS, stream=True
+ )
- events = list(stream)
++ events = tuple(stream)
+ assert events, "responses stream returned no events"
- deltas = [event.delta for event in events if event.type == "response.output_text.delta"]
++ deltas = tuple(event.delta for event in events if event.type == "response.output_text.delta")
+ assert any(delta for delta in deltas), "responses stream returned no text deltas"
+ assert events[-1].type == "response.completed", (
+ f"responses stream did not terminate with response.completed: {events[-1].type}"
)
-
- assert any(event.delta for event in delta_events), "responses stream returned no text deltas"
- assert result.stream_events, "responses stream returned no events"
- assert (
- ResponsesStreamEventType.model_validate_json(result.stream_events[-1]).type
- == "response.completed"
- ), "responses stream did not terminate with response.completed"
@pytest.mark.covers("llm.responses.openai.basic.nonstream.cost_logged")
def test_responses_logs_cost(
@@@ -156,45 -175,49 +165,40 @@@
@pytest.mark.covers("llm.responses.openai.vision.nonstream.works")
def test_responses_vision_describes_image(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-responses-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
+ model = _register(
+ proxy,
+ resources,
LiteLLMParamsBody(model="openai/gpt-4o", api_key="os.environ/OPENAI_API_KEY"),
)
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- result = endpoints_client.responses_vision(
- key,
- model,
- "What animal is shown in this image? Answer in one word",
- "https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg",
+ client = sdk.openai(resources.key())
+
+ vision_input: ResponseInputParam = [
+ {
+ "role": "user",
+ "content": [
- {
- "type": "input_text",
- "text": "What animal is shown in this image? Answer in one word",
- },
++ {"type": "input_text", "text": "What animal is shown in this image? Answer in one word"},
+ {"type": "input_image", "image_url": CAT_IMAGE_URL, "detail": "auto"},
+ ],
+ }
+ ]
+ response = client.responses.create(model=model, input=vision_input, instructions=INSTRUCTIONS)
+ text = response.output_text.strip().lower()
+ assert text, f"/responses vision returned no output text: {response.output!r}"
+ assert any(keyword in text for keyword in ("cat", "feline")), (
+ f"vision response did not describe the image: {text[:300]}"
)
- require_successful_call(result)
- parsed = ResponsesResult.model_validate_json(result.body)
- text = parsed.text.strip().lower()
- assert text, f"/responses vision returned no output text: {result.body[:300]}"
- assert any(
- keyword in text
- for keyword in ("cat", "feline")
- ), f"vision response did not describe the image: {parsed.text[:300]}"
@pytest.mark.covers("llm.responses.anthropic.basic.nonstream.works")
def test_responses_anthropic_returns_completion(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- model = f"e2e-responses-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- LiteLLMParamsBody(
- model="anthropic/claude-haiku-4-5", api_key="os.environ/ANTHROPIC_API_KEY"
- ),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
+ model = _register(proxy, resources, _anthropic_params())
+ client = sdk.openai(resources.key())
- response = client.responses.create(
- model=model, input="reply with one word", instructions=INSTRUCTIONS
- )
- result = endpoints_client.responses(key, model, "reply with one word")
- require_successful_call(result)
- parsed = ResponsesResult.model_validate_json(result.body)
- assert parsed.text.strip(), f"/responses returned no output text: {result.body[:300]}"
++ response = client.responses.create(model=model, input="reply with one word", instructions=INSTRUCTIONS)
+ assert response.output_text.strip(), f"/responses returned no output text: {response.output!r}"
@pytest.mark.covers("llm.responses.anthropic.tool_use.nonstream.works")
def test_responses_anthropic_returns_function_call(
@@@ -213,31 -262,92 +217,58 @@@
@pytest.mark.covers("llm.responses.bedrock_converse.basic.nonstream.works")
def test_responses_bedrock_returns_completion(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- require_env("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION")
- model = f"e2e-responses-{unique_marker()}"
- model_id = endpoints_client.create_model(model, _bedrock_params())
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
+ model = _register(proxy, resources, _bedrock_params())
+ client = sdk.openai(resources.key())
- response = client.responses.create(
- model=model, input="reply with one word", instructions=INSTRUCTIONS
- )
- assert response.output_text.strip(), (
- f"/responses over bedrock returned no output text: {response.output!r}"
- )
- result = endpoints_client.responses(key, model, "reply with one word")
- require_successful_call(result)
- parsed = ResponsesResult.model_validate_json(result.body)
- assert parsed.text.strip(), f"/responses over bedrock returned no output text: {result.body[:300]}"
++ response = client.responses.create(model=model, input="reply with one word", instructions=INSTRUCTIONS)
++ assert response.output_text.strip(), f"/responses over bedrock returned no output text: {response.output!r}"
@pytest.mark.covers("llm.responses.bedrock_converse.tool_use.nonstream.works")
def test_responses_bedrock_returns_function_call(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
+ self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
- require_env("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION")
- model = f"e2e-responses-{unique_marker()}"
- model_id = endpoints_client.create_model(model, _bedrock_params())
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- result = endpoints_client.responses_with_tools(
- key, model, "What is the weather in San Francisco? Use the get_weather tool.", [WEATHER_TOOL]
+ model = _register(proxy, resources, _bedrock_params())
+ client = sdk.openai(resources.key())
+
+ response = client.responses.create(
+ model=model,
+ input="What is the weather in San Francisco? Use the get_weather tool.",
+ instructions=INSTRUCTIONS,
+ tools=[WEATHER_TOOL],
)
- require_successful_call(result)
- parsed = ResponsesResult.model_validate_json(result.body)
- function_call = next((call for call in parsed.function_calls if call.name == "get_weather"), None)
- assert function_call is not None, f"no get_weather function call over bedrock: {result.body[:500]}"
- assert function_call.arguments is not None
- raw_arguments = cast(object, json.loads(function_call.arguments))
- arguments = WeatherArguments.model_validate(raw_arguments)
- assert arguments.location, f"function call arguments missing location: {function_call.arguments}"
+ _assert_weather_call(response)
+
+ @pytest.mark.skip(reason="stage red: product gap, /v1/responses 500s (aresponses TypeError) on missing input instead of 400")
+ @pytest.mark.covers("llm.responses.openai.input_validation.nonstream.works")
- def test_missing_input_returns_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model = f"e2e-responses-val-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- LiteLLMParamsBody(model="openai/gpt-4o-mini", api_key="os.environ/OPENAI_API_KEY"),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
++ def test_missing_input_returns_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model = _register(proxy, resources, _openai_params(), prefix="e2e-responses-val")
+ key = resources.key()
- result = endpoints_client.proxy.transport.send(
++ result = proxy.transport.send(
+ "/v1/responses",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalResponsesBody(model=model),
+ )
+ assert_client_error(result, "responses missing input")
+
+ @pytest.mark.covers("llm.responses.openai.input_validation.nonstream.works")
- def test_missing_model_returns_client_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
++ def test_missing_model_returns_client_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
+ key = resources.key()
- result = endpoints_client.proxy.transport.send(
++ result = proxy.transport.send(
+ "/v1/responses",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalResponsesBody(input="ping"),
+ )
+ assert_client_error(result, "responses missing model")
+
+ @pytest.mark.covers("llm.responses.openai.input_validation.nonstream.works")
- def test_empty_input_returns_client_error(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- model = f"e2e-responses-val-{unique_marker()}"
- model_id = endpoints_client.create_model(
- model,
- LiteLLMParamsBody(model="openai/gpt-4o-mini", api_key="os.environ/OPENAI_API_KEY"),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
++ def test_empty_input_returns_client_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
++ model = _register(proxy, resources, _openai_params(), prefix="e2e-responses-val")
+ key = resources.key()
- result = endpoints_client.proxy.transport.send(
++ result = proxy.transport.send(
+ "/v1/responses",
- headers=endpoints_client.proxy.transport.bearer(key),
++ headers=proxy.transport.bearer(key),
+ json=_OptionalResponsesBody(model=model, input=""),
+ )
+ assert_client_error(result, "responses empty input")
-
-def _parse_stream_event(
- event: str,
-) -> ResponsesOutputTextDeltaEvent | None:
- try:
- return ResponsesOutputTextDeltaEvent.model_validate_json(event)
- except ValidationError:
- return None
diff --cc tests/e2e/proxy_client.py
index 234c37d2f77,48a6110dc0b..1fa7eb9f88f
--- a/tests/e2e/proxy_client.py
+++ b/tests/e2e/proxy_client.py
@@@ -291,18 -898,9 +900,19 @@@ class ProxyClient
headers=self.transport.bearer(key),
json=body,
response_type=OcrResponse,
+ timeout=SLOW_PROVIDER_TIMEOUT_SECONDS,
)
+ def rerank(self, key: str, body: RerankBody) -> Result[RerankResponse]:
+ """POST /v1/rerank (Cohere-format). No official OpenAI/Anthropic SDK
+ covers this route, so it stays on the shared typed transport."""
+ return self.transport.post(
+ "/v1/rerank",
+ headers=self.transport.bearer(key),
+ json=body,
+ response_type=RerankResponse,
+ )
+
def count_tokens(self, key: str, body: CountTokensBody) -> Result[CountTokensResponse]:
"""POST /v1/messages/count_tokens (Anthropic-native). Sends the
anthropic-version header so the native path accepts it; harmless on the
diff --cc uv.lock
index caf976b9202,eb4cdef76f1..e88439116d0
--- a/uv.lock
+++ b/uv.lock
@@@ -10,7 -10,7 +10,7 @@@ resolution-markers =
]
[options]
- exclude-newer = "2026-07-20T03:20:37.107777782Z"
-exclude-newer = "2026-09-09T21:39:49.468411Z"
++exclude-newer = "2026-09-12T12:26:39.445785Z"
exclude-newer-span = "P3D"
[manifest]
@@@ -4300,9 -4558,10 +4558,11 @@@ dev =
{ name = "vcrpy" },
]
e2e-dev = [
+ { name = "anthropic" },
{ name = "locust" },
+ { name = "mcp" },
{ name = "playwright" },
+ { name = "psutil" },
{ name = "websockets" },
]
healthcheck = [
@@@ -4478,9 -4749,10 +4750,11 @@@ dev =
{ name = "vcrpy", specifier = "==8.2.1" },
]
e2e-dev = [
+ { name = "anthropic", specifier = "==0.84.0" },
{ name = "locust", specifier = "==2.45.0" },
+ { name = "mcp", specifier = ">=1.28.1,<2.0" },
{ name = "playwright", specifier = "==1.61.0" },
+ { name = "psutil", specifier = "==7.2.2" },
{ name = "websockets", specifier = ">=15.0.1,<16.0" },
]
healthcheck = [