Why LLM integrations pass tests and still break in production
A chat completion call never throws a type error when it gets worse. Swap a model name, tighten max_tokens, or append "be more concise" to a system prompt, and your test suite stays green while users get truncated JSON, three-paragraph "summaries," and a chatty "Sure! Here's the summary:" preamble wedged into a parser.
The mistake most teams make is trying to fix this with more string assertions. Exact-match tests on model output are brittle in both directions: they break when the model improves, and they stay silent when it degrades on inputs you didn't think to write down. What actually works is three separate layers, each with a different job and a different cost profile: mocks for the request contract, evals for output quality, and recorded cassettes for regression on a fixed corpus. Build them in that order — cheap and fast first, slow and expensive last.
Layer 1 — Mock the transport, not the prompt
The most common mocking mistake is patching the OpenAI class itself with monkeypatch. That couples every test to SDK internals and gives you nothing to assert against. Instead, make the client a function argument. Production passes the real client; tests pass a stub that mirrors the same attribute path (client.chat.completions.create) so the code under test never knows the difference.
# llm/summarize.py
import os
from openai import OpenAI
SYSTEM = "Summarize the user's text in exactly one sentence. No preamble, no quotes."
def build_client(api_key: str | None = None) -> OpenAI:
return OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=api_key or os.environ["AICREDITS_API_KEY"],
)
def summarize(text: str, client: OpenAI, model: str = "deepseek-v4-flash") -> str:
resp = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": text},
],
temperature=0,
max_tokens=200,
)
return resp.choices[0].message.content.strip()
# tests/fakes.py
"""Network-free stand-ins that mirror the OpenAI client's attribute path."""
class _Msg:
def __init__(self, content: str):
self.content = content
class _Choice:
def __init__(self, content: str):
self.message = _Msg(content)
class _Resp:
def __init__(self, content: str):
self.choices = [_Choice(content)]
class FakeClient:
"""Returns scripted replies and records every request body."""
def __init__(self, replies: list[str]):
self.replies = list(replies)
self.calls: list[dict] = []
self.chat = self
self.completions = self
def create(self, **kwargs):
self.calls.append(kwargs)
return _Resp(self.replies.pop(0))
# tests/test_summarize.py
from llm.summarize import summarize
from tests.fakes import FakeClient
def test_request_contract():
fake = FakeClient(["Refunds are allowed within 30 days for unused items."])
out = summarize("Our refund policy allows returns within 30 days.", client=fake)
assert out.startswith("Refunds are allowed")
sent = fake.calls[0]
assert sent["model"] == "deepseek-v4-flash"
assert sent["temperature"] == 0
assert [m["role"] for m in sent["messages"]] == ["system", "user"]
assert sent["max_tokens"] <= 200
Assert only things you control: model id, temperature, message order, token bounds, and the fact that a retry loop calls
createexactly once on success.Never assert the model's wording in a unit test. That belongs in an eval where you can see the pass rate move.
Keep
FakeClient.callsaround — it is the cheapest way to catch a refactor that silently starts sending the conversation twice.A mock proves your plumbing, not your prompt. Do not let a green unit suite convince you the feature works.
Layer 2 — Evals: assert properties, not exact strings
An eval is a unit test for output quality. The trick is to assert properties that should hold no matter how the model phrases things: required facts survived, length stayed inside a budget, no preamble leaked, JSON still parses. Those assertions survive a model upgrade.
# evals/run_evals.py
import sys
from llm.summarize import build_client, summarize
client = build_client()
CASES = [
{
"name": "refund-policy",
"text": "Our refund policy allows returns within 30 days of purchase. Items must be "
"unused and in original packaging. Shipping fees are non-refundable except "
"when the item arrived damaged.",
"must_include": ["30 days"],
"max_words": 40,
},
{
"name": "maintenance-window",
"text": "Server maintenance is scheduled for Tuesday 02:00-04:00 UTC. The API will "
"return 503 responses during the window.",
"must_include": ["503"],
"max_words": 40,
},
]
BANNED_PREFIXES = ("here", "sure", "certainly", "summary:")
def check(case: dict, output: str) -> list[str]:
problems = []
words = len(output.split())
if words > case["max_words"]:
problems.append(f"too verbose ({words} words)")
for kw in case["must_include"]:
if kw.lower() not in output.lower():
problems.append(f"dropped required fact {kw!r}")
if output.lower().startswith(BANNED_PREFIXES):
problems.append("preamble leaked into output")
return problems
def main() -> None:
failures = 0
for case in CASES:
output = summarize(case["text"], client=client)
problems = check(case, output)
print(f"[{'PASS' if not problems else 'FAIL'}] {case['name']}: {output!r}")
for p in problems:
print(f" - {p}")
failures += bool(problems)
sys.exit(1 if failures else 0)
if __name__ == "__main__":
main()
For qualities you cannot express as a predicate — faithfulness, tone, whether the summary invented a policy detail — add an LLM judge. Keep the judge strict and the candidate cheap: grade with deepseek-v4-flash for routine nightly runs, and reserve deepseek-v4-pro for pre-release grading where the extra reasoning is worth the higher cost per call. Never judge a model with itself on the release gate; the blind spots correlate.
# evals/judge.py
import json
from llm.summarize import build_client
JUDGE = """Grade the SUMMARY against the SOURCE. Reply with JSON only:
{"faithful": bool, "complete": bool, "reason": str}
Set faithful=false if the summary asserts anything the source does not support."""
def grade(source: str, summary: str, client, model: str = "deepseek-v4-flash") -> dict:
resp = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": JUDGE},
{"role": "user", "content": f"SOURCE:\n{source}\n\nSUMMARY:\n{summary}"},
],
temperature=0,
response_format={"type": "json_object"},
)
return json.loads(resp.choices[0].message.content)
Layer 3 — Regression suites with record/replay cassettes
Live evals are non-deterministic and cost money on every commit, so they are the wrong tool for pull requests. Record the real response once, commit it, and replay it in CI. Hash the entire request body as the cache key so a prompt edit invalidates every cassette automatically and you notice immediately.
# tests/cassettes.py
import hashlib, json, pathlib
from tests.fakes import _Resp
CASSETTES = pathlib.Path("tests/cassettes")
def _key(kwargs: dict) -> str:
blob = json.dumps(kwargs, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(blob.encode()).hexdigest()[:16]
class CassetteClient:
"""mode='record' hits the API and saves; mode='replay' serves saved bytes offline."""
def __init__(self, inner, mode: str = "replay"):
assert mode in {"record", "replay"}
self.inner, self.mode = inner, mode
self.chat = self
self.completions = self
CASSETTES.mkdir(parents=True, exist_ok=True)
def create(self, **kwargs):
path = CASSETTES / f"{_key(kwargs)}.json"
if self.mode == "replay":
if not path.exists():
raise FileNotFoundError(f"no cassette for {_key(kwargs)}; record it first")
return _Resp(json.loads(path.read_text(encoding="utf-8"))["content"])
resp = self.inner.chat.completions.create(**kwargs)
content = resp.choices[0].message.content
path.write_text(
json.dumps({"request": kwargs, "content": content}, ensure_ascii=False, indent=2),
encoding="utf-8",
)
return _Resp(content)
The honest tradeoff: cassettes capture whatever text you fed them, so they can leak real customer data into your repository. Record only from sanitized fixtures, and strip anything that looks like a name, email, or account id before committing. Also keep a version constant on your system prompt and log it with every request — when a cassette fails, you want to know in one glance whether the prompt or the model moved.
Wiring the layers into CI
| Layer | Catches | Runs on | Cost profile |
|---|---|---|---|
| Mocked unit tests | Request contract drift: wrong model id, dropped params, bad message order | Every commit | Free, milliseconds |
| Recorded cassettes | Output drift on a fixed corpus, parsing and post-processing bugs | Every pull request | Free after the first recording |
| Property evals | Verbosity creep, preamble leaks, dropped facts, broken JSON | Nightly and on any prompt change | Low — flash over a small corpus |
| LLM-judge evals | Tone, faithfulness, invented details | Pre-release | Highest — slowest and priciest per run |
Keep the golden set small and real: twenty to fifty cases pulled from actual traffic beats two thousand synthetic ones.
Track the pass rate as a number, not a boolean. A drop from 94% to 88% after a prompt edit is a signal even when CI is still green.
Treat case count as a tuning knob. Increase it only when a production incident slips past the current set.
Re-record cassettes deliberately and review the diff. A cassette update should be a reviewed commit, never a side effect of running tests.
Add one nightly live canary outside the cassette layer — it is the only thing that catches provider-side drift.
What this costs, and where AiCredits fits
Pricing here is qualitative but not mysterious: deepseek-v4-flash is the cheap workhorse that makes a nightly eval corpus affordable, deepseek-v4-pro costs more per call and belongs on the release gate or the judge seat, cache hits are cheaper than cold requests, and off-peak traffic costs less than peak. That shape is exactly why the layering above matters — you spend the expensive tokens only where they change a decision. Current rates are on the DeepSeek prices page.
If you are building this from outside China, AiCredits sells DeepSeek API credits payable by card or PayPal, with no Chinese phone number or bank account required — which matters when your CI runner needs a key that your finance team can actually pay for.
FAQ
Mock the transport for contract tests, not for quality tests. A mock proves your code sends the right model, parameters, and message order. It can never tell you whether the answer got worse — that requires cassettes or live evals.
No. It reduces variance but does not guarantee identical output across runs. That is exactly why evals should assert properties like required facts and length budgets instead of exact strings.
Fewer than you think. Twenty to fifty cases drawn from real failures catch most regressions. Grow the set when a production incident slips through, not on a schedule.
You can for cheap nightly runs, but expect correlated blind spots. For a release gate, grade with a stronger model than the one under test — for example a deepseek-v4-pro judge scoring deepseek-v4-flash output.
Hash the full request body into a cassette key. Any prompt or parameter edit invalidates the recording instantly, so the failing test names the change instead of hiding behind a stale snapshot.