`chat({ stream: false })` and `chat({ outputSchema })` reject with an Error that drops `retryAfterMs` (and the HTTP status) #2294
Disclaimer: I used Opus 5.5 to help report this issue. I ran into it while migrating my company's repo from Vercel AI to Tanstack AI.
TanStack AI version#
@tanstack/ai 1.10.1, @tanstack/ai-openai 1.2.1
Framework/Library version#
Node 26, zod 4.6.7
Describe the bug and the steps to reproduce it#
When the provider answers with a 429 and a retry-after header, the RUN_ERROR event has the wait: retryAfterMs in onModelError, then metadata.tanstack.retryAfterMs on the stream (stream-events docs). But the non-streaming forms of chat() reject with an Error that has none of it:
chat({ stream: false })goes throughstreamToText(), which throwsrunErrorEventToError(chunk). That keeps onlymessage,codeandrawEvent, soretryAfterMs,errorTypeandrequestIdare lost.chat({ outputSchema })throws the engine's finalization error, which keeps onlymessageandcode(not evenrawEvent).
So a caller that awaits chat() can't honor Retry-After without adding a middleware just to capture it. chat({ retry }) doesn't cover this: it doesn't retry the structured-output call, and when the wait is longer than maxWaitMs (for example a daily quota), the caller still needs the wait to schedule its own retry.
A related gap: the thrown error has no HTTP status either. code comes from the provider body first and the status only as a fallback (extractCode in activities/error-payload.ts). OpenAI rate-limit bodies usually carry "code": "rate_limit_exceeded", so the thrown error then has code: "rate_limit_exceeded" and nothing says it was a 429. The RunErrorEvent.errorType doc says "code stays the HTTP status", which doesn't match.
Repro (no network, no API key): npm i @tanstack/ai @tanstack/ai-openai zod, save as repro.ts, run with node repro.ts.
import { chat, type ChatMiddleware } from "@tanstack/ai";
import { createOpenaiChat } from "@tanstack/ai-openai";
import { z } from "zod";
// Every request gets a 429 with `retry-after: 42`.
globalThis.fetch = async () =>
new Response(
JSON.stringify({
error: { message: "Rate limit reached", type: "requests", param: null, code: null },
}),
{ status: 429, headers: { "content-type": "application/json", "retry-after": "42" } },
);
const adapter = createOpenaiChat("gpt-6-luna", "sk-dummy", { maxRetries: 0 });
let seenByMiddleware: number | undefined;
const spy: ChatMiddleware = {
name: "retry-after-spy",
onModelError: (_ctx, event) => {
seenByMiddleware = event.retryAfterMs;
},
};
const runs = {
"stream: false": () =>
chat({
adapter,
threadId: "t-1",
messages: [{ role: "user", content: "hi" }],
stream: false,
middleware: [spy],
}),
outputSchema: () =>
chat({
adapter,
threadId: "t-2",
messages: [{ role: "user", content: "hi" }],
outputSchema: z.object({ answer: z.string() }),
middleware: [spy],
}),
};
for (const [label, run] of Object.entries(runs)) {
seenByMiddleware = undefined;
try {
await run();
} catch (error) {
console.log(`--- ${label} ---`);
console.log("thrown:", JSON.stringify(error));
console.log("onModelError saw retryAfterMs:", seenByMiddleware);
}
}
Output:
--- stream: false ---
thrown: {"code":"429","rawEvent":{"message":"Rate limit reached","type":"requests","param":null,"code":null}}
onModelError saw retryAfterMs: 42000
--- outputSchema ---
thrown: {"code":"429"}
onModelError saw retryAfterMs: 42000
With "code": "rate_limit_exceeded" in the mocked body (what OpenAI usually sends), the thrown code is "rate_limit_exceeded" instead of "429", and the error has no status at all.
Expected behavior#
The rejected error carries what the RUN_ERROR carried, so a caller can do:
try {
await chat({ adapter, threadId, messages, stream: false });
} catch (error) {
if (error.status === 429) scheduleRetry(error.retryAfterMs);
}
Suggested fix#
Build both thrown errors from the RUN_ERROR and copy its details: retryAfterMs, errorType and requestId from metadata.tanstack, plus rawEvent, and the HTTP status as its own field (for example status) so it's there even when code holds the provider's code. A small exported error class (for example ChatRunError with these typed fields and the event as cause) would let callers narrow with instanceof instead of duck typing. The structured-output path could reuse the same helper as streamToText().
Workaround#
A middleware that records the wait in onModelError, then attaches it to the error the call throws:
let retryAfterMs: number | undefined;
const tracker: ChatMiddleware = {
name: "rate-limit-tracker",
onModelError: (_ctx, event) => {
retryAfterMs = event.metadata?.tanstack?.retryAfterMs ?? event.retryAfterMs ?? retryAfterMs;
},
};
try {
await chat({ adapter, threadId, messages, stream: false, middleware: [tracker] });
} catch (error) {
throw Object.assign(error as Error, { retryAfterMs });
}
Screenshots or Videos (Optional)#
No response
Do you intend to try to help solve this bug with your own PR?#
None
Terms & Code of Conduct#
- I agree to follow this project's Code of Conduct
- I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
tanstack-source added labelsbug
pcbeingused33(GitHub profile, opens in a new tab) linked this to #2301
github-actions[bot](GitHub profile, opens in a new tab) assignedjherr
github-actions[bot](GitHub profile, opens in a new tab) added labelshas-pr
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
Sign in to join this conversation.