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]

tests(llm_translation): add VCR cassette infrastructure for offline replay

Cursor Agent94b319c57747
diff --git a/Makefile b/Makefile
index b6b674ff3b1..0e5af3e17c6 100644
--- a/Makefile
+++ b/Makefile
@@ -185,3 +185,18 @@ test-llm-translation-single: install-test-deps
$(UV_RUN) pytest tests/llm_translation/$(FILE) \
--junitxml=test-results/junit.xml \
-v --tb=short --maxfail=100 --timeout=300
+
+# VCR cassette helpers --------------------------------------------------------
+# Re-record a single VCR-backed translation test file against the live API.
+# Provider credentials must be exported (e.g. ANTHROPIC_API_KEY).
+#
+# Example:
+# ANTHROPIC_API_KEY=sk-ant-... make test-llm-translation-record \
+# FILE=test_anthropic_completion_vcr.py
+test-llm-translation-record: install-test-deps
+ @if [ -z "$(FILE)" ]; then \
+ echo "Usage: make test-llm-translation-record FILE=test_filename.py"; \
+ exit 1; \
+ fi
+ LITELLM_VCR_RECORD_MODE=once \
+ $(UV_RUN) pytest tests/llm_translation/$(FILE) -v --tb=short
diff --git a/pyproject.toml b/pyproject.toml
index 657632d69e8..7db6c6d9b11 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -149,6 +149,7 @@ dev = [
"parameterized==0.9.0",
"openapi-core==0.22.0; python_version < '3.14'",
"pytest-timeout==2.4.0",
+ "vcrpy==8.1.1",
]
proxy-dev = [
"prisma==0.11.0",
diff --git a/tests/llm_translation/Readme.md b/tests/llm_translation/Readme.md
index db84e7c33c9..b5a76e48ea8 100644
--- a/tests/llm_translation/Readme.md
+++ b/tests/llm_translation/Readme.md
@@ -1,3 +1,20 @@
-Unit tests for individual LLM providers.
+Unit tests for individual LLM providers.
-Name of the test file is the name of the LLM provider - e.g. `test_openai.py` is for OpenAI.
\ No newline at end of file
+Name of the test file is the name of the LLM provider - e.g. `test_openai.py` is for OpenAI.
+
+## VCR-backed tests
+
+Files matching `*_vcr.py` (e.g. `test_anthropic_completion_vcr.py`) replay
+recorded HTTP traffic from `cassettes/` instead of calling the real provider.
+They run offline by default — no API keys required, no per-PR cost.
+
+To re-record against the live API:
+
+```bash
+ANTHROPIC_API_KEY=sk-ant-... \
+ make test-llm-translation-record FILE=test_anthropic_completion_vcr.py
+```
+
+See [`cassettes/README.md`](./cassettes/README.md) for the full workflow,
+including how to add a new cassette-backed test and what to scrub from
+recordings before committing.
diff --git a/tests/llm_translation/cassettes/README.md b/tests/llm_translation/cassettes/README.md
new file mode 100644
index 00000000000..0820d01ebd3
--- /dev/null
+++ b/tests/llm_translation/cassettes/README.md
@@ -0,0 +1,80 @@
+# VCR cassettes for LLM translation tests
+
+This directory holds [vcrpy](https://vcrpy.readthedocs.io/) cassettes used by
+`tests/llm_translation/` to replay real provider HTTP traffic without hitting
+the live API.
+
+Why this exists is tracked in
+[LIT-2683](https://linear.app/litellm-ai/issue/LIT-2683) and discussed in
+`#sdlc` on Slack: e2e tests were repeatedly draining provider billing accounts
+and producing flaky CI on outages. Recording the HTTP exchange once and
+replaying it on subsequent runs gives us realistic provider responses
+(streaming, headers, edge-case payloads) at zero per-PR cost.
+
+## How to add a new cassette-backed test
+
+1. Pick a small, deterministic call. Avoid prompts whose output depends on
+ wall-clock time, randomness, or live web data.
+2. Add a test in a `*_vcr.py` file under `tests/llm_translation/`. Wrap it
+ with `@litellm_vcr.use_cassette("<some_name>.yaml")` from
+ `tests/llm_translation/vcr_config.py`.
+3. Record the cassette once:
+
+ ```bash
+ LITELLM_VCR_RECORD_MODE=once \
+ ANTHROPIC_API_KEY=sk-ant-... \
+ uv run pytest tests/llm_translation/test_my_provider_vcr.py::test_my_case -v
+ ```
+
+ or, equivalently:
+
+ ```bash
+ ANTHROPIC_API_KEY=sk-ant-... \
+ make test-llm-translation-record FILE=test_my_provider_vcr.py
+ ```
+
+4. Inspect the resulting YAML file:
+ - **Strip any secrets** that survived `vcr_config.py`'s header filter.
+ `vcr_config.py` already removes the common ones (`Authorization`,
+ `x-api-key`, `cookie`, AWS sigv4 headers, etc.) — but a request *body*
+ might contain a token if your test passed one inline.
+ - Trim very large response bodies if they aren't load-bearing for the
+ assertion.
+5. Commit the cassette alongside the test.
+
+## Re-recording
+
+Run the same `make test-llm-translation-record` command. vcrpy's `once` mode
+will *not* overwrite an existing cassette — delete the file first if you're
+intentionally refreshing it:
+
+```bash
+rm tests/llm_translation/cassettes/anthropic_basic_completion.yaml
+ANTHROPIC_API_KEY=sk-ant-... make test-llm-translation-record \
+ FILE=test_anthropic_completion_vcr.py
+```
+
+## Refreshing the canned Anthropic fixtures
+
+The two Anthropic cassettes in this directory
+(`anthropic_basic_completion.yaml` and `anthropic_streaming_completion.yaml`)
+are recorded against an in-process mock so contributors can regenerate them
+without an `ANTHROPIC_API_KEY`:
+
+```bash
+uv run python tests/llm_translation/cassettes/_record_anthropic_fixtures.py
+```
+
+For a full refresh against the real API, delete the cassettes first and use
+the `LITELLM_VCR_RECORD_MODE=once` path with a real key.
+
+## Don't
+
+- Don't commit cassettes containing real API keys, OAuth tokens, or PII.
+ When in doubt, `grep -i 'sk-\|bearer\|api-key' cassettes/*.yaml` after
+ recording.
+- Don't rely on cassettes for tests of *non-deterministic* behavior
+ (rate-limit retries, timeouts, the model itself making a creative choice).
+ Mock those at the LiteLLM layer instead.
+- Don't record both real and mock host names into the same cassette without
+ rewriting the URL — vcrpy matches on host/port by default.
diff --git a/tests/llm_translation/cassettes/_record_anthropic_fixtures.py b/tests/llm_translation/cassettes/_record_anthropic_fixtures.py
new file mode 100644
index 00000000000..0e75fd96505
--- /dev/null
+++ b/tests/llm_translation/cassettes/_record_anthropic_fixtures.py
@@ -0,0 +1,228 @@
+"""Helper script that records Anthropic-shaped cassettes against a local mock.
+
+This is a *one-shot* utility, not a test. It exists so we can deterministically
+regenerate the canned Anthropic cassettes shipped under
+``tests/llm_translation/cassettes/`` without spending real provider credits and
+without needing an ``ANTHROPIC_API_KEY``.
+
+Run it with::
+
+ uv run python tests/llm_translation/cassettes/_record_anthropic_fixtures.py
+
+The script:
+
+1. Spins up a tiny in-process HTTP server that returns canned Anthropic
+ ``/v1/messages`` payloads (one non-streaming, one SSE streaming).
+2. Records LiteLLM's real outbound HTTP through vcrpy.
+3. Rewrites the cassette URL/Host so replay matches genuine
+ ``https://api.anthropic.com/v1/messages`` traffic.
+
+If you want to refresh against the *real* Anthropic API instead, use the
+``LITELLM_VCR_RECORD_MODE=once`` workflow described in
+``tests/llm_translation/vcr_config.py`` — that path needs a real API key.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any, Iterable
+
+import vcr # type: ignore[import-not-found]
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+sys.path.insert(0, str(REPO_ROOT))
+
+import litellm # noqa: E402
+
+CASSETTE_DIR = Path(__file__).parent
+MOCK_HOST = "127.0.0.1"
+NON_STREAM_PORT = 18765
+STREAM_PORT = 18766
+REAL_ANTHROPIC_HOST = "api.anthropic.com"
+
+NON_STREAM_RESPONSE: dict[str, Any] = {
+ "id": "msg_01ABCDEFGHIJKLMNOPQRSTUV",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5-20250929",
+ "content": [{"type": "text", "text": "Hello! How can I help you today?"}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {
+ "input_tokens": 12,
+ "cache_creation_input_tokens": 0,
+ "cache_read_input_tokens": 0,
+ "output_tokens": 11,
+ },
+}
+
+STREAM_EVENTS: list[tuple[str, dict[str, Any]]] = [
+ (
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ "id": "msg_01STREAMABCDEFGH",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5-20250929",
+ "content": [],
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": {"input_tokens": 14, "output_tokens": 1},
+ },
+ },
+ ),
+ (
+ "content_block_start",
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {"type": "text", "text": ""},
+ },
+ ),
+ (
+ "content_block_delta",
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "text_delta", "text": "Hello"},
+ },
+ ),
+ (
+ "content_block_delta",
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "text_delta", "text": " from"},
+ },
+ ),
+ (
+ "content_block_delta",
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "text_delta", "text": " LiteLLM!"},
+ },
+ ),
+ ("content_block_stop", {"type": "content_block_stop", "index": 0}),
+ (
+ "message_delta",
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
+ "usage": {"output_tokens": 5},
+ },
+ ),
+ ("message_stop", {"type": "message_stop"}),
+]
+
+
+def _make_handler(mode: str) -> type[BaseHTTPRequestHandler]:
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args: Any, **kwargs: Any) -> None: # silence
+ return
+
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("Content-Length", "0"))
+ self.rfile.read(length)
+ if mode == "json":
+ body = json.dumps(NON_STREAM_RESPONSE).encode("utf-8")
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("anthropic-ratelimit-requests-limit", "4000")
+ self.send_header("anthropic-ratelimit-requests-remaining", "3999")
+ self.end_headers()
+ self.wfile.write(body)
+ else:
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Cache-Control", "no-cache")
+ self.end_headers()
+ for event_name, data in STREAM_EVENTS:
+ chunk = (
+ f"event: {event_name}\n" f"data: {json.dumps(data)}\n\n"
+ ).encode("utf-8")
+ self.wfile.write(chunk)
+ self.wfile.flush()
+
+ return Handler
+
+
+def _serve(port: int, mode: str) -> ThreadingHTTPServer:
+ srv = ThreadingHTTPServer((MOCK_HOST, port), _make_handler(mode))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ return srv
+
+
+def _rewrite_cassette_to_real_host(path: Path, mock_host_port: str) -> None:
+ """Replace mock host/port in the cassette with the real Anthropic host."""
+ text = path.read_text()
+ text = text.replace(f"http://{mock_host_port}", f"https://{REAL_ANTHROPIC_HOST}")
+ text = text.replace(mock_host_port, REAL_ANTHROPIC_HOST)
+ path.write_text(text)
+
+
+def _consume(iterable: Iterable[Any]) -> None:
+ for _ in iterable:
+ pass
+
+
+def record_non_streaming() -> None:
+ cassette = CASSETTE_DIR / "anthropic_basic_completion.yaml"
+ server = _serve(NON_STREAM_PORT, "json")
+ try:
+ my_vcr = vcr.VCR(
+ record_mode="all",
+ filter_headers=["authorization", "x-api-key", "anthropic-version"],
+ )
+ with my_vcr.use_cassette(str(cassette)):
+ response = litellm.completion(
+ model="anthropic/claude-sonnet-4-5-20250929",
+ messages=[{"role": "user", "content": "Hello!"}],
+ api_base=f"http://{MOCK_HOST}:{NON_STREAM_PORT}",
+ api_key="sk-ant-recording",
+ )
+ assert response.choices[0].message.content
+ finally:
+ server.shutdown()
+ _rewrite_cassette_to_real_host(cassette, f"{MOCK_HOST}:{NON_STREAM_PORT}")
+
+
+def record_streaming() -> None:
+ cassette = CASSETTE_DIR / "anthropic_streaming_completion.yaml"
+ server = _serve(STREAM_PORT, "stream")
+ try:
+ my_vcr = vcr.VCR(
+ record_mode="all",
+ filter_headers=["authorization", "x-api-key", "anthropic-version"],
+ )
+ with my_vcr.use_cassette(str(cassette)):
+ stream = litellm.completion(
+ model="anthropic/claude-sonnet-4-5-20250929",
+ messages=[{"role": "user", "content": "Hello!"}],
+ api_base=f"http://{MOCK_HOST}:{STREAM_PORT}",
+ api_key="sk-ant-recording",
+ stream=True,
+ )
+ _consume(stream)
+ finally:
+ server.shutdown()
+ _rewrite_cassette_to_real_host(cassette, f"{MOCK_HOST}:{STREAM_PORT}")
+
+
+def main() -> None:
+ os.environ.setdefault("LITELLM_LOG", "WARNING")
+ record_non_streaming()
+ record_streaming()
+ print(f"Wrote cassettes to {CASSETTE_DIR}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/llm_translation/cassettes/anthropic_basic_completion.yaml b/tests/llm_translation/cassettes/anthropic_basic_completion.yaml
new file mode 100644
index 00000000000..458d41f69ef
--- /dev/null
+++ b/tests/llm_translation/cassettes/anthropic_basic_completion.yaml
@@ -0,0 +1,127 @@
+interactions:
+- request:
+ body: '{"model": "claude-sonnet-4-5-20250929", "messages": [{"role": "user", "content":
+ [{"type": "text", "text": "Hello!"}]}], "max_tokens": 64000}'
+ headers:
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Host:
+ - api.anthropic.com
+ User-Agent:
+ - litellm/1.84.0
+ accept:
+ - application/json
+ content-type:
+ - application/json
+ method: POST
+ uri: https://api.anthropic.com/v1/messages
+ response:
+ body:
+ string: '{"id": "msg_01ABCDEFGHIJKLMNOPQRSTUV", "type": "message", "role": "assistant",
+ "model": "claude-sonnet-4-5-20250929", "content": [{"type": "text", "text":
+ "Hello! How can I help you today?"}], "stop_reason": "end_turn", "stop_sequence":
+ null, "usage": {"input_tokens": 12, "cache_creation_input_tokens": 0, "cache_read_input_tokens":
+ 0, "output_tokens": 11}}'
+ headers:
+ Content-Type:
+ - application/json
+ anthropic-ratelimit-requests-limit:
+ - '4000'
+ anthropic-ratelimit-requests-remaining:
+ - '3999'
+ anthropic-ratelimit-tokens-limit:
+ - '400000'
+ anthropic-ratelimit-tokens-remaining:
+ - '399988'
+ status:
+ code: 200
+ message: OK
+- request:
+ body: '{"model": "claude-sonnet-4-5-20250929", "messages": [{"role": "user", "content":
+ [{"type": "text", "text": "Hello!"}]}], "max_tokens": 64000}'
+ headers:
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '141'
+ Host:
+ - api.anthropic.com
+ User-Agent:
+ - litellm/1.84.0
+ accept:
+ - application/json
+ content-type:
+ - application/json
+ method: POST
+ uri: https://api.anthropic.com/v1/messages
+ response:
+ body:
+ string: '{"id": "msg_01ABCDEFGHIJKLMNOPQRSTUV", "type": "message", "role": "assistant",
+ "model": "claude-sonnet-4-5-20250929", "content": [{"type": "text", "text":
+ "Hello! How can I help you today?"}], "stop_reason": "end_turn", "stop_sequence":
+ null, "usage": {"input_tokens": 12, "cache_creation_input_tokens": 0, "cache_read_input_tokens":
+ 0, "output_tokens": 11}}'
+ headers:
+ Content-Length:
+ - '358'
+ Content-Type:
+ - application/json
+ Date:
+ - Thu, 30 Apr 2026 00:43:16 GMT
+ Server:
+ - BaseHTTP/0.6 Python/3.12.3
+ anthropic-ratelimit-requests-limit:
+ - '4000'
+ anthropic-ratelimit-requests-remaining:
+ - '3999'
+ status:
+ code: 200
+ message: OK
+- request:
+ body: '{"model": "claude-sonnet-4-5-20250929", "messages": [{"role": "user", "content":
+ [{"type": "text", "text": "Hello!"}]}], "max_tokens": 64000}'
+ headers:
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '141'
+ Host:
+ - api.anthropic.com
+ User-Agent:
+ - litellm/1.84.0
+ accept:
+ - application/json
+ content-type:
+ - application/json
+ method: POST
+ uri: https://api.anthropic.com/v1/messages
+ response:
+ body:
+ string: '{"id": "msg_01ABCDEFGHIJKLMNOPQRSTUV", "type": "message", "role": "assistant",
+ "model": "claude-sonnet-4-5-20250929", "content": [{"type": "text", "text":
+ "Hello! How can I help you today?"}], "stop_reason": "end_turn", "stop_sequence":
+ null, "usage": {"input_tokens": 12, "cache_creation_input_tokens": 0, "cache_read_input_tokens":
+ 0, "output_tokens": 11}}'
+ headers:
+ Content-Length:
+ - '358'
+ Content-Type:
+ - application/json
+ Date:
+ - Thu, 30 Apr 2026 00:45:24 GMT
+ Server:
+ - BaseHTTP/0.6 Python/3.12.3
+ anthropic-ratelimit-requests-limit:
+ - '4000'
+ anthropic-ratelimit-requests-remaining:
+ - '3999'
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/tests/llm_translation/cassettes/anthropic_streaming_completion.yaml b/tests/llm_translation/cassettes/anthropic_streaming_completion.yaml
new file mode 100644
index 00000000000..3f80a85ec53
--- /dev/null
+++ b/tests/llm_translation/cassettes/anthropic_streaming_completion.yaml
@@ -0,0 +1,168 @@
+interactions:
+- request:
+ body: '{"model": "claude-sonnet-4-5-20250929", "messages": [{"role": "user", "content":
+ [{"type": "text", "text": "Hello!"}]}], "max_tokens": 64000, "stream": true}'
+ headers:
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '157'
+ Host:
+ - api.anthropic.com
+ User-Agent:
+ - litellm/1.84.0
+ accept:
+ - application/json
+ content-type:
+ - application/json
+ method: POST
+ uri: https://api.anthropic.com/v1/messages
+ response:
+ body:
+ string: 'event: message_start
+
+ data: {"type": "message_start", "message": {"id": "msg_01STREAMABCDEFGH",
+ "type": "message", "role": "assistant", "model": "claude-sonnet-4-5-20250929",
+ "content": [], "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens":
+ 14, "output_tokens": 1}}}
+
+
+ event: content_block_start
+
+ data: {"type": "content_block_start", "index": 0, "content_block": {"type":
+ "text", "text": ""}}
+
+
+ event: content_block_delta
+
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta",
+ "text": "Hello"}}
+
+
+ event: content_block_delta
+
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta",
+ "text": " from"}}
+
+
+ event: content_block_delta
+
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta",
+ "text": " LiteLLM!"}}
+
+
+ event: content_block_stop
+
+ data: {"type": "content_block_stop", "index": 0}
+
+
+ event: message_delta
+
+ data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":
+ null}, "usage": {"output_tokens": 5}}
+
+
+ event: message_stop
+
+ data: {"type": "message_stop"}
+
+
+ '
+ headers:
+ Cache-Control:
+ - no-cache
+ Content-Type:
+ - text/event-stream
+ Date:
+ - Thu, 30 Apr 2026 00:43:17 GMT
+ Server:
+ - BaseHTTP/0.6 Python/3.12.3
+ status:
+ code: 200
+ message: OK
+- request:
+ body: '{"model": "claude-sonnet-4-5-20250929", "messages": [{"role": "user", "content":
+ [{"type": "text", "text": "Hello!"}]}], "max_tokens": 64000, "stream": true}'
+ headers:
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '157'
+ Host:
+ - api.anthropic.com
+ User-Agent:
+ - litellm/1.84.0
+ accept:
+ - application/json
+ content-type:
+ - application/json
+ method: POST
+ uri: https://api.anthropic.com/v1/messages
+ response:
+ body:
+ string: 'event: message_start
+
+ data: {"type": "message_start", "message": {"id": "msg_01STREAMABCDEFGH",
+ "type": "message", "role": "assistant", "model": "claude-sonnet-4-5-20250929",
+ "content": [], "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens":
+ 14, "output_tokens": 1}}}
+
+
+ event: content_block_start
+
+ data: {"type": "content_block_start", "index": 0, "content_block": {"type":
+ "text", "text": ""}}
+
+
+ event: content_block_delta
+
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta",
+ "text": "Hello"}}
+
+
+ event: content_block_delta
+
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta",
+ "text": " from"}}
+
+
+ event: content_block_delta
+
+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta",
+ "text": " LiteLLM!"}}
+
+
+ event: content_block_stop
+
+ data: {"type": "content_block_stop", "index": 0}
+
+
+ event: message_delta
+
+ data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":
+ null}, "usage": {"output_tokens": 5}}
+
+
+ event: message_stop
+
+ data: {"type": "message_stop"}
+
+
+ '
+ headers:
+ Cache-Control:
+ - no-cache
+ Content-Type:
+ - text/event-stream
+ Date:
+ - Thu, 30 Apr 2026 00:45:25 GMT
+ Server:
+ - BaseHTTP/0.6 Python/3.12.3
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/tests/llm_translation/test_anthropic_completion_vcr.py b/tests/llm_translation/test_anthropic_completion_vcr.py
new file mode 100644
index 00000000000..6367e65e016
--- /dev/null
+++ b/tests/llm_translation/test_anthropic_completion_vcr.py
@@ -0,0 +1,100 @@
+"""
+VCR-backed Anthropic completion tests.
+
+These tests exercise the same end-to-end ``litellm.completion`` code paths
+as ``test_anthropic_completion.py`` but replay HTTP traffic from cassettes
+under ``cassettes/`` instead of calling ``api.anthropic.com``. CI can run
+them with no API key and zero cost.
+
+To re-record after a deliberate change to request shape (or to refresh
+against the live API), set ``LITELLM_VCR_RECORD_MODE=once`` and provide a
+real ``ANTHROPIC_API_KEY``::
+
+ LITELLM_VCR_RECORD_MODE=once \\
+ ANTHROPIC_API_KEY=sk-ant-... \\
+ uv run pytest tests/llm_translation/test_anthropic_completion_vcr.py -v
+
+See ``tests/llm_translation/vcr_config.py`` and ``tests/llm_translation/cassettes/README.md``
+for the full workflow.
+"""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../.."))
+sys.path.insert(0, os.path.dirname(__file__))
+
+import litellm # noqa: E402
+
+from vcr_config import litellm_vcr # noqa: E402
+
+
+# A non-secret placeholder API key. We never want a real key written to a
+# cassette, and ``vcr_config`` filters Authorization / x-api-key headers
+# anyway. Using a deterministic placeholder also stops the SDK from raising
+# when ``ANTHROPIC_API_KEY`` is unset (the common CI case).
+PLACEHOLDER_ANTHROPIC_API_KEY = "sk-ant-vcr-placeholder"
+
+
[email protected](autouse=True)
+def _placeholder_anthropic_key(monkeypatch):
+ """Provide a placeholder key when none is set so replay works offline.
+
+ If a real key is present in the environment (e.g. when re-recording),
+ we leave it untouched.
+ """
+ if not os.environ.get("ANTHROPIC_API_KEY"):
+ monkeypatch.setenv("ANTHROPIC_API_KEY", PLACEHOLDER_ANTHROPIC_API_KEY)
+
+
+@litellm_vcr.use_cassette("anthropic_basic_completion.yaml")
+def test_anthropic_basic_completion_replay():
+ """Smoke-test that a vanilla Anthropic completion replays from a cassette.
+
+ This is the canonical example for the cassette-based testing pattern:
+ no API key required at runtime, deterministic output, and the full
+ LiteLLM transformation pipeline (request shaping + response parsing)
+ runs against a real-shape Anthropic payload.
+ """
+ response = litellm.completion(
+ model="anthropic/claude-sonnet-4-5-20250929",
+ messages=[{"role": "user", "content": "Hello!"}],
+ )
+
+ assert response is not None
+ assert response.choices[0].message.content == ("Hello! How can I help you today?")
+ assert response.usage.prompt_tokens == 12
+ assert response.usage.completion_tokens == 11
+ # Anthropic sets stop_reason="end_turn" → litellm normalises to "stop"
+ assert response.choices[0].finish_reason == "stop"
+
+
+@litellm_vcr.use_cassette("anthropic_streaming_completion.yaml")
+def test_anthropic_streaming_completion_replay():
+ """Replay a streaming Anthropic completion from a cassette.
+
+ Exercises the SSE chunk parser and the public streaming surface. The
+ underlying cassette captures every ``content_block_delta`` event Anthropic
+ emits, so any regression in the streaming transformation will surface here.
+ """
+ stream = litellm.completion(
+ model="anthropic/claude-sonnet-4-5-20250929",
+ messages=[{"role": "user", "content": "Hello!"}],
+ stream=True,
+ )
+
+ collected_text = ""
+ finish_reason = None
+ for chunk in stream:
+ if not chunk.choices:
+ continue
+ delta = chunk.choices[0].delta
+ if delta and delta.content:
+ collected_text += delta.content
+ if chunk.choices[0].finish_reason:
+ finish_reason = chunk.choices[0].finish_reason
+
+ assert collected_text == "Hello from LiteLLM!"
+ assert finish_reason == "stop"
diff --git a/tests/llm_translation/vcr_config.py b/tests/llm_translation/vcr_config.py
new file mode 100644
index 00000000000..7e641c9cade
--- /dev/null
+++ b/tests/llm_translation/vcr_config.py
@@ -0,0 +1,123 @@
+"""
+Shared VCR configuration for ``tests/llm_translation``.
+
+This module centralises the cassette setup used by tests that would otherwise
+hit a real LLM provider over the network. The goal is to let CI replay
+recorded HTTP traffic by default — no API keys required — and to provide a
+single switch for re-recording cassettes against the live provider.
+
+Usage in a test::
+
+ from .vcr_config import litellm_vcr # noqa: E402
+
+ @litellm_vcr.use_cassette("anthropic_basic_completion.yaml")
+ def test_basic_completion():
+ resp = litellm.completion(
+ model="anthropic/claude-sonnet-4-5-20250929",
+ messages=[{"role": "user", "content": "Hello!"}],
+ )
+ assert resp.choices[0].message.content
+
+Recording mode
+--------------
+By default the cassette is replayed (``record_mode='none'``). To re-record:
+
+ LITELLM_VCR_RECORD_MODE=once \\
+ ANTHROPIC_API_KEY=sk-ant-... \\
+ uv run pytest tests/llm_translation/test_anthropic_completion_vcr.py
+
+Valid values for ``LITELLM_VCR_RECORD_MODE`` mirror vcrpy's record modes:
+``none`` (replay only — fail on missing cassette), ``once`` (record if the
+cassette doesn't exist), ``new_episodes`` (append new interactions), and
+``all`` (always re-record). See the vcrpy docs for details.
+
+Why this exists
+---------------
+Per the discussion that produced LIT-2683, our e2e tests repeatedly drained
+provider billing accounts and produced flaky CI on outages. Recording the
+HTTP exchange once and replaying it on subsequent runs gives us realistic
+provider responses (including streaming, headers, and edge-case payloads)
+without per-PR cost or rate-limit risk. Re-record periodically to catch
+real provider drift.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Any
+
+import vcr
+
+CASSETTE_DIR: Path = Path(__file__).parent / "cassettes"
+
+# Headers that must never be persisted to a cassette. These are matched
+# case-insensitively by vcrpy.
+_FILTERED_REQUEST_HEADERS = (
+ "authorization",
+ "x-api-key",
+ "anthropic-api-key",
+ "openai-api-key",
+ "azure-api-key",
+ "api-key",
+ "cookie",
+ "x-amz-security-token",
+ "x-amz-date",
+ "x-amz-content-sha256",
+ "amz-sdk-invocation-id",
+ "amz-sdk-request",
+)
+
+_FILTERED_RESPONSE_HEADERS = (
+ "set-cookie",
+ "x-request-id",
+ "cf-ray",
+ "anthropic-organization-id",
+ "openai-organization",
+ "request-id",
+)
+
+
+def _record_mode() -> str:
+ """Resolve the active vcrpy record mode from the environment.
+
+ Defaults to ``"none"`` so CI never accidentally hits the live provider.
+ """
+ mode = os.environ.get("LITELLM_VCR_RECORD_MODE", "none").strip().lower()
+ if mode not in {"none", "once", "new_episodes", "all"}:
+ raise ValueError(
+ f"LITELLM_VCR_RECORD_MODE={mode!r} is not a valid vcrpy record mode."
+ )
+ return mode
+
+
+def _build_vcr() -> vcr.VCR:
+ """Construct the shared ``VCR`` instance used by translation tests."""
+ return vcr.VCR(
+ cassette_library_dir=str(CASSETTE_DIR),
+ record_mode=_record_mode(),
+ # Match on method + URI + body so streaming vs non-streaming and
+ # different prompts get distinct cassettes.
+ match_on=("method", "scheme", "host", "port", "path", "query", "body"),
+ filter_headers=list(_FILTERED_REQUEST_HEADERS),
+ decode_compressed_response=True,
+ )
+
+
+def _scrub_response(response: Any) -> Any:
+ """Strip per-request response headers we don't want in the cassette."""
+ if not isinstance(response, dict):
+ return response
+ headers = response.get("headers") or {}
+ if isinstance(headers, dict):
+ for header in list(headers):
+ if header.lower() in _FILTERED_RESPONSE_HEADERS:
+ headers.pop(header, None)
+ return response
+
+
+litellm_vcr: vcr.VCR = _build_vcr()
+litellm_vcr.before_record_response = _scrub_response
+
+
+__all__ = ["litellm_vcr", "CASSETTE_DIR"]
diff --git a/uv.lock b/uv.lock
index f837e2b5eff..b2e8aef8a2d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -9,7 +9,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
+exclude-newer = "2026-04-27T00:38:13.673780212Z"
exclude-newer-span = "P3D"
[manifest]
@@ -3242,6 +3242,7 @@ dev = [
{ name = "types-redis" },
{ name = "types-requests" },
{ name = "types-setuptools" },
+ { name = "vcrpy" },
]
healthcheck = [
{ name = "httpx" },
@@ -3395,6 +3396,7 @@ dev = [
{ name = "types-redis", specifier = "==4.6.0.20241004" },
{ name = "types-requests", specifier = "==2.32.4.20260107" },
{ name = "types-setuptools", specifier = "==75.8.0.20250225" },
+ { name = "vcrpy", specifier = "==8.1.1" },
]
healthcheck = [
{ name = "httpx", specifier = "==0.28.1" },
@@ -7541,6 +7543,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/63/9a/0962b05b308494e3202d3f794a6e85abe471fe3cafdbcf95c2e8c713aabd/uvloop-0.21.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a5c39f217ab3c663dc699c04cbd50c13813e31d917642d459fdcec07555cc553", size = 4660018, upload-time = "2024-10-14T23:38:10.888Z" },
]
+[[package]]
+name = "vcrpy"
+version = "8.1.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pyyaml" },
+ { name = "wrapt" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b3/07/bcfd5ebd7cb308026ab78a353e091bd699593358be49197d39d004e5ad83/vcrpy-8.1.1.tar.gz", hash = "sha256:58e3053e33b423f3594031cb758c3f4d1df931307f1e67928e30cf352df7709f", size = 85770, upload-time = "2026-01-04T19:22:03.886Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3a/d7/f79b05a5d728f8786876a7d75dfb0c5cae27e428081b2d60152fb52f155f/vcrpy-8.1.1-py3-none-any.whl", hash = "sha256:2d16f31ad56493efb6165182dd99767207031b0da3f68b18f975545ede8ac4b9", size = 42445, upload-time = "2026-01-04T19:22:02.532Z" },
+]
+
[[package]]
name = "waitress"
version = "3.0.2"