Integrating Multiple AI Providers with Automatic Fallbacks
Recently, I was working on an AI writing tool. The goal was to learn how AI powers so many online tools these days. So I started with text generation, which seemed like the perfect starting point.
Since this was a learning experiment, one of my main project requirements was to use free-tier AI APIs. I didn't want to spend unnecessarily on API usage costs while developing and testing the application, so I picked Google's Gemini.
During development, even with the correct configurations in place, I wasn't able to generate a single piece of text. I kept getting the following error:
The model is experiencing high traffic, please try again later.
I tried again later, but got the same error.
After waiting for quite some time, I decided to try a different provider: Groq. That worked initially, but not for long. I eventually encountered the same high-traffic error.
I understand that this can be expected when using free-tier services, but it was still very frustrating during development.
This whole experience made me rethink the architecture of my AI writing tool. I decided to make it independent of any single AI provider, allowing it to use multiple providers and automatically fall back to an alternative when certain failures occur.
So, here's how I integrated multiple AI providers with automatic fallbacks into my project.
Vercel AI SDK
The first problem I needed to solve was how to connect multiple AI providers without making the project unnecessarily complicated. I needed a solution that would let me integrate different providers without writing separate generation logic for each one.
That's when I came across AI SDK by Vercel.
It's a TypeScript toolkit that provides a unified interface for working with different AI models and providers. It allows us to generate text through a common function, generateText(), instead of having to implement the entire generation workflow separately for each provider.
I started by installing the toolkit through npm:
npm install ai Integrating Multiple Providers
The AI SDK provides a unified interface to work with AI providers and models, but you still need to configure and select those models.
For my project, I used Groq and Gemini by installing their respective AI SDK-compatible provider packages.
# Google AI npm install @ai-sdk/google # Groq npm install @ai-sdk/groq Configuring the providers was an easy task. I used the createGoogle() and createGroq() functions provided by their respective provider packages.
export function getLanguageModel(provider: AIProvider) { switch (provider) { case "gemini": { const apiKey = process.env.GOOGLE_GENERATIVE_AI_API_KEY; if (!apiKey) { throw new Error("Gemini API key is not configured."); } const google = createGoogle({ apiKey }); return google(process.env.GEMINI_MODEL || "gemini-3.5-flash-lite"); } case "groq": { const apiKey = process.env.GROQ_API_KEY; if (!apiKey) { throw new Error("Groq API key is not configured."); } const groq = createGroq({ apiKey }); return groq(process.env.GROQ_MODEL || "qwen/qwen3.8-27b"); } } } I created a helper function called getLanguageModel(provider). Its responsibility is to return the configured language model based on the provider passed to it.
This keeps the provider configurations in one place. Whenever I need a model, I can call this function to get the appropriate model based on the selected provider.
IMPORTANT: Never hardcode API keys or sensitive credentials in your source code. Always use environment variables or a
.envfile. Make sure your.envfiles are included in.gitignoreso you don't accidentally push them to a public repository.
Provider Priority Order
When working with multiple providers, the next natural step after configuring them is deciding their priority order.
Priority order allows me to define which provider to use as my default and which one to use as a fallback.
Since I was using only two providers, I decided to make Groq my primary provider and Gemini my fallback. This was mainly because I encountered fewer high-traffic errors when using Groq compared to Gemini.
// The order determines provider priority. const providers: AIProvider[] = ["groq", "gemini"]; Generating Text with Fallback
The last thing left to do was to generate the text output and, if the AI provider happened to fail, use the fallback provider to finish the job.
I had all the pieces of the puzzle:
-
providers: An array of available providers ordered by priority. -
getLanguageModel(provider): A helper function to retrieve the appropriate language model. -
generateText(): The common Vercel AI SDK function for generating text.
All that was left was to put them together.
for (const provider of providers) { try { console.info(`Attempting AI generation with ${provider}`); const model = getLanguageModel(provider); const result = await generateText({ model, // Language model for generation system, // Rules to follow while generating text prompt, // Client prompt for generation temperature: 0.7, // Controls randomness and creativity maxOutputTokens: 1000, // Token limit per generation maxRetries: 0, // Disable SDK retries; fallback is handled by the loop timeout: 45_000, abortSignal: request.signal, }); console.info(`Generation succeeded with ${provider}`); return Response.json({ result: result.text, provider, usage: result.usage, }); } catch (error) { console.error(`Generation failed with ${provider}:`, error); // Don't attempt another provider if the client has cancelled the request. if (request.signal.aborted) { return new Response(null, { status: 408 }); } // Stop if the error is not suitable for fallback. if (!shouldFallback(error)) { break; } } } Let's understand what I did step by step.
Since I had a providers array, I used a for loop to iterate through the providers, selecting one model at a time.
An important thing to notice here is that calling generateText() inside the loop does not mean the API will generate text from both providers simultaneously. The loop continues to the next provider only when the current iteration finishes without returning a successful result or breaking out of the loop.
Inside the loop, I first retrieve the model associated with the current provider and then try to generate the text using generateText().
During text generation, I intentionally set maxRetries to 0 (the default is 2). This disables the AI SDK's default retry mechanism.
Setting retries to zero does not itself trigger the fallback. Instead, the combination of the for loop and catch block allows my application to use the second provider as a fallback when an eligible failure occurs.
Selective Fallback: Don't Retry Every Error
Inside the catch block, you'll notice this condition:
if (!shouldFallback(error)) { break; } The main purpose of this condition is to ensure that we don't blindly proceed with the loop and retry using another AI provider without first understanding the error.
Why is this important?
A generation request can fail for several reasons. One of those reasons could be a failure within our own application.
It doesn't matter how many AI providers we have if our application itself has a bug. We'll just be wasting time and resources, shooting darts in the dark.
Let's have a look at what's inside shouldFallback(error).
function shouldFallback(error: unknown): boolean { if (!APICallError.isInstance(error)) { // Unknown errors are not automatically treated as provider failures. return false; } const status = error.statusCode; if (status === undefined) { // Network errors without an HTTP status may be recoverable. return true; } return [401, 403, 404, 408, 409, 429].includes(status) || (status >= 500 && status < 600); } The function returns a boolean based on the conditions I defined to decide when the application should fall back and when it should stop.
Let's understand those conditions one by one.
1. Not an APICallError
if (!APICallError.isInstance(error)) { // Unknown errors are not automatically treated as provider failures. return false; } The AI SDK provides APICallError, which I used to check the error type.
If the error isn't classified as an API call error, it could be an application bug or another unexpected error. That's why the function returns false, stopping the fallback process and breaking out of the loop.
2. No Status Code
const status = error.statusCode; if (status === undefined) { // Network errors without an HTTP status may be recoverable. return true; } This condition checks whether a status code is available.
A missing status code can potentially indicate a network or API communication failure. In these cases, the function returns true to allow the application to try the fallback provider.
3. Status Code Comparison
return [401, 403, 404, 408, 409, 429].includes(status) || (status >= 500 && status < 600); The final condition checks the status code against a set of codes and ranges that I decided to treat as eligible for fallback.
These aren't necessarily the only status codes you could check. For my application, however, I chose to treat the following as valid reasons to try another provider.
Here's what each status code represents:
| Code | What it means |
|---|---|
| 401 / 403 | Authentication or permission failure |
| 404 | Requested model or endpoint may not exist |
| 408 | Request timeout |
| 409 | Provider-side conflict |
| 429 | Rate-limit or quota-related failure |
| 5xx | Server-side failure |
Handling Cancelled Requests
There's another condition in the loop that is worth understanding:
if (request.signal.aborted) { return new Response(null, { status: 408 }); } This condition checks whether the incoming request has been aborted.
If the client has already cancelled the generation request, there's no reason to attempt generation with another provider. Doing so would only waste additional time and API resources.
Instead, the application immediately returns from the function, stopping the fallback process.
One thing worth noting: HTTP 408 represents a Request Timeout, not a dedicated client-cancellation status. In this implementation, I'm using it as the response status when the request has been aborted.
Handling Timeouts
You'll also notice timeout and abortSignal in the generateText() parameters.
timeout: 45_000, abortSignal: request.signal, timeout: 45_000 limits how long the application waits for an individual text-generation attempt. In this case, that's 45 seconds.
Since my application tries providers sequentially, if both configured providers take the full timeout to fail, the total waiting time could approach 90 seconds before the application concludes that generation has failed.
The abortSignal helps stop the generation if the incoming request is cancelled before it finishes.
Failure Handling
Setting up multiple AI providers helped make the tool more resilient, but it didn't make it failure-proof.
API failures are still possible, even when we have multiple AI providers. That's why I added a default 503 Service Unavailable response at the end of my API endpoint.
return Response.json( { error: "Our AI services are temporarily unavailable. Please try again in a little while.", }, { status: 503 }, ); This ensures that if all configured providers fail, the application returns a predictable error response instead of leaving the request without a proper response.
AI Writing Assistant
So, that's how I integrated multiple AI providers with automatic fallbacks into my AI writing assistant.
The tool allows users to improve, rewrite, summarize, fix grammar, expand, or generate text.
Users can perform these actions while configuring the writing tone, output length and format, along with custom instructions.
I built this project using Next.js, shadcn/ui, TypeScript, Upstash for rate limiting, and of course, the AI SDK by Vercel.
If you're interested in learning how the entire project works, check it out here.
Youtube Video: Build an AI Writing Assistant with Next.js, TypeScript & Free AI Models | Full Project by Modern Web
Check out project's source code with documentation: Source Code
Follow @modernweb on YouTube for more web development projects.



