30 Nov 2026 · 4 min read
An AI feature that never goes down: the five-step fallback in PillBridge
Groq, then Gemini, then OpenAI, then a local Llama model via Ollama, then plain rules. Why a health app's AI assistant should always answer, and how I structured the fallback.
PillBridge has an AI assistant that answers questions about a patient's medications, mood and health readings. A chat box that shows "Something went wrong" is annoying in most apps. In a health app used by elderly patients and their caregivers, it means someone doesn't get an answer they needed.
LLM APIs fail more often than you'd expect: rate limits on free tiers, expired keys, provider outages, slow responses. So I made the assistant work through a chain of providers until one of them answers.
The chain
Groq → Gemini → OpenAI → Ollama (local Llama) → offline rules
fast backup backup no internet needed always works
- Groq goes first because it's the fastest, which matters for chat.
- Gemini and OpenAI are hosted backups with separate quotas, so one rate limit doesn't take the feature down.
- Ollama runs a Llama model on my own machine or server. It needs no API key, has no quota, and sends no data to a third party.
- Offline rules are plain JavaScript, so they can't fail for network reasons.
The code
The Express route builds the prompt once, then tries each provider in order:
let aiResponse = null;
let serviceUsed = 'none';
if (groqService.isConfigured()) {
try {
aiResponse = await groqService.chat(messages, { max_tokens: 500 });
serviceUsed = 'groq';
} catch (err) {
console.warn('[AI] Groq failed:', err.message);
}
}
if (!aiResponse && geminiService.isConfigured()) {
try {
aiResponse = await geminiService.chat(messages, { max_tokens: 500 });
serviceUsed = 'gemini';
} catch (err) {
console.warn('[AI] Gemini failed:', err.message);
}
}
// ...OpenAI, then Ollama, in the same pattern...
if (!aiResponse) {
aiResponse = analyzeHealthDataOffline(latestHealthData, medications, moodEntries, name);
serviceUsed = 'offline';
}
res.json({ response: aiResponse, serviceUsed });
A few details that matter:
isConfigured()checks. If a key isn't set in an environment, that provider is skipped immediately instead of failing at request time.- Every step catches its own error. One provider failing is logged and the loop moves on. The user never sees it.
serviceUsedis returned and saved with the chat history. When answers look odd, I can see which model produced them, and the logs show how often each fallback is being used.- A short system prompt for all of them: "Give SHORT, DIRECT answers (2–4 sentences max)." Different models have very different default lengths, and this keeps the experience consistent whichever one answers.
The local model
Ollama exposes a simple HTTP API on port 11434. The service class is a thin wrapper around it, with everything configurable through env vars:
class OllamaService {
constructor() {
this.baseURL = process.env.OLLAMA_BASE_URL || 'http://localhost:11434';
this.model = process.env.OLLAMA_MODEL || 'llama3:8b';
this.timeout = parseInt(process.env.OLLAMA_TIMEOUT) || 30000;
}
async isAvailable() {
try {
const res = await this.client.get('/api/tags', { timeout: 5000 });
return res.status === 200;
} catch {
return false;
}
}
}
/api/tags lists the installed models, so the same call shows whether Ollama is running and whether the configured model has been pulled.
The last step: no AI at all
The offline fallback is just rules. It reads the latest readings and applies standard thresholds:
if (systolic >= 140 || diastolic >= 90) {
riskFactors.push('Elevated blood pressure detected');
}
if (fasting >= 126 || pp >= 200) {
riskFactors.push('Blood sugar levels indicate possible diabetes');
}
It then builds a structured Markdown report with diet suggestions based on those flags. It's less flexible than an LLM, but it's predictable, instant and free, and for a health app a correct, boring answer beats an error message.
What I'd improve
- Timeouts per provider. A provider that hangs for 30 seconds is worse than one that fails quickly. Each step should have a short timeout (for example 8 seconds) before moving on.
- A circuit breaker. If Groq has failed five times in a row, skip it for a few minutes instead of waiting for it to fail on every request.
- A shared interface. The providers return slightly different shapes (Ollama returns
{ success, response }). A commonchat(messages) → stringinterface would turn the five blocks into a loop over an array. - Telling the user. When the answer comes from the offline rules, the UI should say so, so nobody mistakes a rule-based report for a model's reasoning.
Takeaway
If an AI feature matters, treat the model like any other external dependency: expect it to fail, have a second option, and keep a last step that needs no network at all. The fallback code is short. The useful part is the habit of asking what happens when the API call fails.