LLM Fallbacks with AI SDK: What Happens When the First Model Fails?
Your resume parser hits a rate limit. Can you safely send the same request to another model?

Your resume parser hits a rate limit. Can you safely send the same request to another model?
Fallback looks like a routing problem until the input contains personal data or the first model has already streamed half an answer. We'll begin with completed, structured resume extraction, where success has a clear shape, then look at what changes for local execution and streaming.
Use the documented fallback mechanism
Provider failover can improve availability, but it does not guarantee uptime, lower cost, or equivalent answers. A fallback is another disclosure of the same input to a different model or provider. Decide which destinations are authorized before configuring a chain.
Examples follow the primary sources below; they are not claims of measured production results.
Current AI SDK documentation describes AI Gateway fallbacks through providerOptions.gateway.models, not a built-in fallback([...]) export from ai. The example targets the current documented API. In a separate server-side project, install compatible releases of ai and zod, configure AI_GATEWAY_API_KEY, and supply real provider/model IDs from your enabled Gateway catalog. These packages and credentials are not required to render this portfolio.
Validate the final structured result
Use generateText with Output.object({ schema }); generateObject and streamObject are deprecated in the current documentation. The caller supplies an abort signal with its request deadline. maxRetries: 0 disables additional SDK retries, not Gateway failover. Failures propagate so the caller can return an explicit error. A validated schema proves shape, not factual accuracy: missing resume facts should stay unknown, not be invented.
import { gateway, generateText, Output } from "ai";
import { z } from "zod";
const ProfileSchema = z.object({
fullName: z.string().nullable(),
skills: z.array(z.string()),
yearsOfExperience: z.number().nonnegative().nullable(),
});
export async function extractProfile(
text: string,
primaryModel: string,
fallbackModels: string[],
signal: AbortSignal,
) {
if (!text.trim() || !primaryModel.trim()) {
throw new Error("Resume text and a configured primary model are required.");
}
const { output } = await generateText({
model: gateway(primaryModel),
prompt: "Extract only facts present in this resume. Use null for unknown values.\n\n" + text,
output: Output.object({ schema: ProfileSchema }),
providerOptions: {
gateway: { models: fallbackModels },
},
maxRetries: 0,
abortSignal: signal,
});
return output;
}The caller chooses the model destinations; the resume does not. Unknown experience stays null, and a failed extraction leaves through the error path. This gives the surrounding workflow a cleaner decision than trying to interpret a plausible-looking fallback string.
Local Ollama is a separate deployment choice
Ollama support is provided by community packages such as ollama-ai-provider-v2, not @ai-sdk/ollama. Install a release compatible with your AI SDK major version, start Ollama, and pull an appropriate model first. Call this only after your application explicitly chooses local execution; it is not an automatic offline fallback.
import { generateText } from "ai";
import { ollama } from "ollama-ai-provider-v2";
export async function runLocalPrompt(
prompt: string,
installedModelId: string,
signal: AbortSignal,
) {
const { text } = await generateText({
model: ollama(installedModelId),
prompt,
abortSignal: signal,
maxRetries: 0,
});
return text;
}By default the provider connects to localhost:11434 from the process executing this code. In a deployed Next.js server, that means the server or container, not the visitor's laptop. A remote server cannot turn its Ollama endpoint into browser-local inference. Do not silently send sensitive local input to a cloud fallback.
Context, streaming, and operational limits
- Choose models with compatible structured-output support and adequate context windows. Reserve capacity for system instructions, tools, history, and output; a word-count multiplier is not a reliable tokenizer.
- Gateway model failover, provider routing, and SDK retries are different mechanisms. Test their actual failure conditions, deadlines, and billing behavior.
streamTextcan report errors through the stream oronError; a surroundingtry/catchalone is insufficient. After emitting user-visible output, restarting on another provider can duplicate or contradict it.- A JSON schema validates completed data. Partial streamed objects may not yet satisfy it. Treat all output as untrusted before using it for actions.
- Record attempted destinations, success rates, timeouts, final model, and usage where available. Telemetry requires an actual exporter and privacy policy; never enable raw prompt logging by assumption.
Verify reliability rather than asserting it
Exercise rate limiting, unavailable models, invalid structured output, cancellation, and a failure after the first streamed chunk. Measure end-to-end latency and costs per successful task, including failed attempts. This article publishes no uptime, cost, or latency benchmark without a reproducible workload and recorded evidence.
Count successful tasks, not just successful HTTP responses. A fallback that meets the schema but invents experience has not rescued the parser. Test destination policy, output quality, deadlines, and the cost of failed attempts together.