How Deterministic Recorded HTTP Fixtures (VCR/Polly) Work for LLM Tests
Testing LLM orchestration code against live APIs in CI is slow, expensive, non-deterministic, and prone to rate limits or network flakiness. Recording and replaying HTTP traffic—using tools like Polly.JS in Node.js/TypeScript or VCR / pytest-recording in Python—captures real request/response payloads (including SSE streaming chunks and tool-call responses) as committed fixture files so CI runs offline with exact, reproducible wire responses.
- Real wire serialization vs. hand-rolled mocks: Hand-written mock objects often drift away from real SDK/provider shapes (such as SSE chunk framing,
usageblocks, ortool_callsIDs), whereas recorded fixtures preserve real HTTP headers, status codes, and payload structures while still exercising your actual SDK client and parser code. - Deterministic request matching: Because LLM requests include fields like timestamps, nonces, or dynamic IDs, fixture matchers must normalize or ignore volatile headers/fields (
Authorization,x-request-id, timestamps) while matching semantically meaningful inputs (model,messages,tools,stream). - Record-once, replay-in-CI workflow: Fixtures are recorded intentionally during development or schema upgrades, scrubbed of secrets (
Bearertokens,api-keyheaders), and replayed deterministically in CI without live API credentials.
Steps to Test LLM Integrations with Recorded HTTP Fixtures
- Choose a recorder matching your runtime and transport: Use Polly.JS (
/core,@pollyjs/node-httpor@pollyjs/adapter-fetch) for Node.js/TypeScriptfetch/HTTP clients (or MSW with recorded JSON/SSE fixtures), and VCR.py /pytest-recordingfor Python. - Configure secret scrubbing and deterministic request matchers: Strip API keys and cookies before writing fixture files to disk, and configure body/header matchers so
Authorizationheaders do not break fixture matching when keys rotate. - Record normal, streaming, tool-calling, and error fixtures: Capture real responses for standard completions, SSE streams (
stream: true),tool_callsresponses, and429/500/524error states so retry, rate-limit, and schema-validation logic are all tested deterministically. - Lock CI to replay mode (
replay/ fail on missing recording): Run CI with recording disabled so any unrecorded network call fails loudly instead of silently hitting a live endpoint or hanging.
TypeScript Example: Deterministic Fixture Replay with Polly.JS and Vitest/Jest
import { Polly } from "@pollyjs/core";
import NodeHttpAdapter from "@pollyjs/adapter-node-http";
import FetchAdapter from "@pollyjs/adapter-fetch";
import FSPersister from "@pollyjs/persister-fs";
import OpenAI from "openai";
import path from "node:path";
Polly.register(NodeHttpAdapter);
Polly.register(FetchAdapter);
Polly.register(FSPersister);
export interface CreatePollyOptions {
recordingName: string;
mode?: "replay" | "record";
fixturesDir?: string;
}
export function startLlmFixturePolly({
recordingName,
mode = process.env.RECORD_LLM_FIXTURES === "true" ? "record" : "replay",
fixturesDir = path.resolve(process.cwd(), "__fixtures__/llm"),
}: CreatePollyOptions): Polly {
const polly = new Polly(recordingName, {
mode,
adapters: ["node-http", "fetch"],
persister: "fs",
persisterOptions: {
fs: {
recordingsDir: fixturesDir,
},
},
matchRequestsBy: {
headers: false,
method: true,
url: true,
body(body) {
if (!body) return "";
try {
const parsed = JSON.parse(body);
// Strip volatile/non-semantic fields if any exist in wrapper payloads
delete parsed.request_id;
return JSON.stringify(parsed);
} catch {
return body;
}
},
},
});
// Scrub sensitive credentials and non-deterministic headers before persisting to disk
polly.server.any().on("beforePersist", (_req, recording) => {
recording.request.headers = recording.request.headers.filter(
(h: { name: string }) =>
!["authorization", "x-api-key", "api-key", "cookie"].includes(h.name.toLowerCase())
);
recording.response.headers = recording.response.headers.filter(
(h: { name: string }) => !["cf-ray", "x-request-id", "date"].includes(h.name.toLowerCase())
);
});
return polly;
}
export async function fetchOrderSummary(client: OpenAI, orderId: string): Promise<string> {
const res = await client.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0,
messages: [
{ role: "system", content: "Return a concise status string." },
{ role: "user", content: `Summarize order \${orderId}` },
],
});
return res.choices[0]?.message.content?.trim() ?? "";
}
// Example test usage (e.g. inside Vitest or Jest):
// const polly = startLlmFixturePolly({ recordingName: "order-summary/ord-1001" });
// const client = new OpenAI({ apiKey: "test-key-ignored-in-replay" });
// const summary = await fetchOrderSummary(client, "ORD-1001");
// await polly.stop();
Helpful Tips for Production LLM Fixture Testing
- Never commit raw API keys or PII into fixture files: Always sanitize
Authorizationheaders and scrub sensitive user/customer data inbeforePersistbefore pushing recordings to Git. - Verify SSE streaming chunks and timing-independent behavior: When recording streaming completions, ensure your adapter/persister preserves chunk boundaries and final
usagechunks so stream-assembly and token-reconciliation code run against realistic multi-chunk payloads. - Keep fixtures focused and refresh intentionally: Store small, readable fixtures per scenario (
success,tool-call,rate-limit-429,malformed-json) and re-record only when prompts, schemas, or SDK wire formats intentionally change.
You must log in or register to comment.
