How to test your LLM app against OpenAI and Anthropic failures

25 November 2026 · 8 min read

Your AI feature works in every demo. Then the provider has a bad afternoon: requests come back 429, Anthropic starts answering 529 overloaded_error, and a few streams simply stop halfway through a sentence. Users see half an answer, a spinner that never ends, or a tool call your code can't parse.

None of that shows up in tests that use a hand-written mock returning a canned JSON body. LLM APIs fail in their own formats, and they fail mid-stream, which is exactly where an ordinary mock can't follow. This guide shows what the official OpenAI and Anthropic TypeScript SDKs do in each failure, the code that catches the cases they let through, and how to reproduce every one of them on purpose with a mock OpenAI API (and a mock Anthropic API) in your tests.

Why an ordinary mock can't test an LLM app

A typical API mock answers a request with a status code and a body. That covers "the provider returned 500". It doesn't cover the failures that actually hurt LLM apps:

  • Errors in the provider's exact format. The SDKs map status codes and error bodies to classes like RateLimitError and OverloadedError, and read headers like retry-after. A generic {"error": "boom"} exercises a different code path than production does.
  • A slow first token. The response headers arrive at once, then nothing for 20 seconds. Your loading state, your timeout and your user's patience are all being tested here.
  • A stream that stops early. The connection drops after 40% of the answer. Depending on the transport, the SDK either throws or ends the stream quietly.
  • A stream that never says it's done. No [DONE], no message_stop. Some SDKs notice; one doesn't.
  • A malformed event in the middle of an otherwise fine stream.
  • Truncated tool-call arguments, which turn JSON.parse into your error handler.

To test these you need a fake that speaks Server-Sent Events the way the providers do, and that can break that stream at a chosen point.

What the OpenAI and Anthropic SDKs already handle

Before writing your own retry logic, know what you get for free. We read the source of openai@7.62.0 and @anthropic-ai/sdk@1.12.0; both clients share the same retry design:

Behavior OpenAI SDK Anthropic SDK
Default maxRetries 2 2
Statuses retried 408, 409, 429, any 5xx 408, 409, 429, any 5xx (so 529 too)
Server hints retry-after-ms, then retry-after, honored if 60 s or less Same
Backoff without a hint 0.5 s doubling to a cap of 8 s, minus up to 25% jitter Same
Default timeout 10 minutes 10 minutes
What timeout covers Until the response headers arrive Until the response headers arrive

Two rows deserve a second look.

The default timeout is 10 minutes. For a chat UI that's effectively "never". Set your own.

The timeout stops once headers arrive. In both SDKs the timer is cleared as soon as fetch resolves, which for a streamed response is the moment the status line comes back. A stream that then stalls for a minute is not covered by timeout at all. That's the slow-first-token case, and you need your own idle timer for it.

Retries also only happen before the response starts. Once tokens are flowing, a dropped connection is your problem, not the SDK's.

Seven failures and what the SDKs actually do

We run the real SDKs against every one of these cases in Jitterbox's own test suite (the results are in the LLM failure testing docs). Here's the summary:

Failure OpenAI SDK Anthropic SDK
429 or 529 twice, then OK Retries, honors retry-after, succeeds Same
Rate limited or overloaded every time RateLimitError after 2 retries RateLimitError / OverloadedError
Stream cut over HTTP/1.1 Iterating throws TypeError: terminated finalMessage() rejects (terminated)
Stream cut over HTTP/2 Ends early with no error finalMessage() rejects: stream ended without producing a Message
Malformed event SyntaxError (malformed server-sent event JSON) AnthropicError (JSON parse error)
Missing end event No error: the stream just ends finalMessage() rejects
Truncated tool arguments finish_reason: "length", arguments don't parse stop_reason: "max_tokens"

The bold cells are the dangerous ones. Node's fetch uses HTTP/2 when a server offers it over HTTPS, and the real providers do. So in production, a connection drop in the middle of an OpenAI stream can look exactly like a normal, short answer. Also notice that a cut over HTTP/1.1 throws a plain TypeError, not one of the SDK's error classes, so a catch that only checks instanceof OpenAI.APIError lets it through.

Point the SDKs at a mock OpenAI API in tests

Both SDKs take a baseURL. In tests, aim it at the fake; in production, leave it alone. With Jitterbox, the OpenAI base URL ends in /v1 and the Anthropic one doesn't, and any API key string works because nothing reaches the real provider:

import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";

// In tests, point both SDKs at your Jitterbox project instead of the real provider.
const base = process.env.JITTERBOX_BASE_URL; // e.g. https://<projectKey>.jitterbox.dev

export const openai = new OpenAI({
  apiKey: base ? "test" : process.env.OPENAI_API_KEY,
  baseURL: base ? `${base}/v1` : undefined,
  maxRetries: 2, // the default: retries 408, 409, 429 and 5xx, honoring retry-after up to 60 s
  timeout: 30_000, // the default is 10 minutes
});

export const anthropic = new Anthropic({
  apiKey: base ? "test" : process.env.ANTHROPIC_API_KEY,
  baseURL: base ?? undefined,
  maxRetries: 2,
  timeout: 30_000,
});

JITTERBOX_BASE_URL is the variable jitterbox run sets for your test command in CI, so the same client code works locally and in the pipeline.

Don't trust an OpenAI stream until it says it's finished

This is the single most useful check in an LLM app: a stream without a finish_reason is incomplete, however it ended. It catches the HTTP/2 cut, the missing [DONE], and your own idle timeout, all of which end the for await loop quietly (the OpenAI SDK treats an abort as a normal end of the stream rather than an error).

import OpenAI from "openai";
import { openai } from "./clients.js";

export class IncompleteStreamError extends Error {}

/** Streams a chat completion and refuses to return a partial answer. */
export async function streamAnswer(prompt: string, idleMs = 15_000): Promise<string> {
  const controller = new AbortController();
  let idle = setTimeout(() => controller.abort(), idleMs);

  const stream = await openai.chat.completions.create(
    { model: "gpt-5-mini", messages: [{ role: "user", content: prompt }], stream: true },
    { signal: controller.signal },
  );

  let text = "";
  let finish: string | null = null;
  try {
    for await (const chunk of stream) {
      clearTimeout(idle);
      idle = setTimeout(() => controller.abort(), idleMs);
      const choice = chunk.choices[0];
      text += choice?.delta?.content ?? "";
      finish = choice?.finish_reason ?? finish;
    }
  } catch (err) {
    // A drop over HTTP/1.1 surfaces as TypeError("terminated"), a bad event as SyntaxError.
    // Neither is a reason to show half an answer.
    throw new IncompleteStreamError(`stream failed after ${text.length} chars`, { cause: err });
  } finally {
    clearTimeout(idle);
  }

  // A cut over HTTP/2, a missing [DONE] and our own idle abort all end the loop quietly.
  // The missing finish_reason is how you find out.
  if (finish === null) throw new IncompleteStreamError("stream ended without a finish_reason");
  if (finish === "length") throw new IncompleteStreamError("answer hit max_tokens");
  return text;
}

export function isRetryable(err: unknown) {
  return (
    err instanceof IncompleteStreamError ||
    err instanceof OpenAI.RateLimitError ||
    err instanceof OpenAI.InternalServerError ||
    err instanceof OpenAI.APIConnectionError
  );
}

The idle timer resets on every chunk, so it limits the gap between tokens rather than the whole answer. That's the timeout a long, healthy response needs, and the one the SDK's timeout option can't give you. What you do with an IncompleteStreamError is a product decision: retry once, show what arrived with a clear "the answer was interrupted" message, or fall back. Silently presenting a fragment as the full answer is the one wrong choice.

Anthropic: let finalMessage() do the checking

The Anthropic SDK's streaming helper already rejects when a stream is cut or ends without message_stop, so the code is shorter. What's left for you is stop_reason and what to do about a provider that stays overloaded:

import Anthropic from "@anthropic-ai/sdk";
import { anthropic } from "./clients.js";

async function summarizeWith(model: string, text: string): Promise<string> {
  const stream = anthropic.messages.stream({
    model,
    max_tokens: 1024,
    messages: [{ role: "user", content: `Summarize:\n\n${text}` }],
  });
  // Rejects if the connection drops or the stream ends without message_stop.
  const message = await stream.finalMessage();
  if (message.stop_reason === "max_tokens") throw new Error("summary was cut off at max_tokens");
  return message.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
}

export async function summarize(text: string): Promise<string> {
  try {
    return await summarizeWith("claude-sonnet-5-5", text);
  } catch (err) {
    // Still overloaded (529) after the SDK's own retries: try a smaller model before giving up.
    if (err instanceof Anthropic.OverloadedError) return summarizeWith("claude-haiku-5-5", text);
    throw err;
  }
}

A 529 means the API is busy for everyone (Anthropic's error reference describes it as high traffic across all users), so after the SDK's two retries, another immediate retry of the same model rarely helps. Falling back to a different model, queueing the job or telling the user to try again shortly are all better options than a third hammering.

Tool calls: parse the arguments defensively

When a response runs out of tokens in the middle of a tool call, the arguments are a JSON string that stops mid-object. JSON.parse throws, and if that happens deep inside an agent loop the error message is rarely helpful. Check finish_reason first, then parse inside a try:

// res = await openai.chat.completions.create({ model, messages, tools })
const choice = res.choices[0];
const call = choice.message.tool_calls?.[0];
if (!call || call.type !== "function") return null;
if (choice.finish_reason === "length") throw new Error("tool call was truncated");

try {
  return { name: call.function.name, args: JSON.parse(call.function.arguments) as { location: string } };
} catch {
  throw new Error(`tool arguments are not valid JSON: ${call.function.arguments.slice(0, 80)}`);
}

On Anthropic the same situation shows up as stop_reason: "max_tokens" on a message whose last block is a tool_use. Either way, raising max_tokens or asking the model again is usually the fix; executing a tool with half its arguments never is.

Make the failures happen on purpose

Code like the above is only trustworthy if you've watched it handle each failure. Jitterbox gives you a fake OpenAI or Anthropic API at a real URL and breaks it in exactly the ways listed earlier.

1. Create an LLM endpoint. Pick the type (OpenAI Chat Completions, OpenAI Responses or Anthropic Messages). It answers with a reply text or a tool call you choose, echoes the requested model, and streams with the provider's real event sequence when the request asks for stream: true.

2. Add a failure scenario. The scenario editor has presets for the common cases:

  • Rate-limited at peak: a 429 on every third request.
  • Overloaded provider: 529 or 503 on 30% of requests, plus a slow first token.
  • Flaky stream: cuts, slow chunks and a malformed event.

Errors come back in the provider's own format, including retry-after on a 429, so the SDKs take the same code paths they take in production. Each fault can fire every time, on a percentage of requests, or in a sequence such as "fail twice, then succeed".

3. Or keep it in your repo. The same setup as code, applied with npx jitterbox apply:

project: my-ai-app
endpoints:
  - method: POST
    path: /v1/chat/completions
    kind: openai-chat
scenarios:
  - name: Flaky stream
    enabled: false
    endpoints: ["POST /v1/chat/completions"]
    faults:
      - stream_cut: 50%
        rate: 20%
      - slow_first_token: 5s
        rate: 1 in 5
  - name: Rate limited, then OK
    enabled: false
    faults:
      - error: 429
        pattern: xx.

4. Force one failure from a single test. The X-Jitterbox-Fault header overrides scenarios for that request, which makes for small, deterministic tests:

import { test } from "node:test";
import assert from "node:assert/strict";
import OpenAI from "openai";
import { openai } from "./clients.js";

test("gives up cleanly when the provider keeps rate-limiting", async () => {
  await assert.rejects(
    openai.chat.completions.create(
      { model: "gpt-5-mini", messages: [{ role: "user", content: "hi" }] },
      { headers: { "X-Jitterbox-Fault": "http_error=429" } },
    ),
    OpenAI.RateLimitError,
  );
});

Every request, retry and fault decision shows up in the live request log, so you can see that the SDK really made three attempts and how long it waited between them. The resilience report then grades the client: did it retry, respect Retry-After, back off, and eventually give up.

5. Run it in CI. Once the tests pass locally, keep them passing. jitterbox run switches a scenario on, runs your test command with JITTERBOX_BASE_URL set, switches it off again and grades the run:

npx jitterbox run --scenario "Flaky stream" -- npm test

There's a GitHub Action that does the same and writes the report card to the job summary; the setup is in Jitterbox in CI.

Where to start

Pick the one check you don't have yet. For most apps it's the finish_reason check on OpenAI streams, because the HTTP/2 cut makes a broken answer look like a finished one. Add it, then create a free Jitterbox project, make an OpenAI Chat Completions endpoint, switch on the Flaky stream preset and watch your UI handle a stream that stops at 50%. The SDK source is worth a read too: openai-node and anthropic-sdk-typescript both document their retry and timeout options in the README.

Questions people ask

How do I mock the OpenAI API for testing?

Point the official SDK at a fake server with the baseURL option, for example new OpenAI({ apiKey: "test", baseURL: "https://<projectKey>.jitterbox.dev/v1" }). The fake should answer in OpenAI's own format, including Server-Sent Events for streamed responses, so your code runs the same paths it runs in production. Jitterbox does this and can also return 429s, slow first tokens and cut streams on purpose.

Does the OpenAI Node SDK retry 429 errors automatically?

Yes. By default the OpenAI and Anthropic TypeScript SDKs retry twice (maxRetries: 2) on 408, 409, 429 and 5xx responses. They wait for the retry-after-ms or retry-after header when it is 60 seconds or less, and otherwise back off from 0.5 seconds, doubling up to 8 seconds with some jitter. After the last retry, the OpenAI SDK throws RateLimitError.

What does Anthropic error 529 overloaded_error mean?

A 529 means the Anthropic API is temporarily overloaded across all users, not that your request was wrong. The Anthropic SDK retries it like a 5xx (twice by default) and then throws OverloadedError. After that, falling back to another model, queueing the work or asking the user to retry later works better than retrying the same call again immediately.

How can I tell if an OpenAI stream was cut off?

Check the finish_reason. A complete Chat Completions stream ends with a chunk whose finish_reason is set (for example "stop" or "length"). If the loop ends and you never saw one, the stream is incomplete. This matters because over HTTP/2 a dropped connection can end the OpenAI SDK's stream with no error at all, and a missing [DONE] does the same.

Why doesn't the SDK timeout catch a stalled stream?

In both the OpenAI and Anthropic TypeScript SDKs, the timeout option covers the wait for the response headers. For a streamed response the headers arrive at once, so a stream that then stalls is not covered. Use your own idle timer: an AbortController whose timer resets on every chunk, passed as the signal request option.

Try it on your own code

Jitterbox gives you a fake version of the APIs you call, at a real URL, and makes them fail on purpose. Free during the beta.