AI Hints
Home›LangChain Tutorial›Reliability
LangChain · Lesson 94 of 120

Model Fallbacks

A backup model.

⏱ 2 min read▶ Video at 1:46:50🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Even the best model providers have outages. If your only model is down, so is your app. A fallback is a backup model, tried automatically when the main one fails.

Model Fallbacks
From the video: Model Fallbacks
  • Providers have outages
  • One model, one point of failure
  • A backup model

With fallbacks

Our primary model has a name that doesn't exist, to pretend it's down. With fallbacks wraps it with a list of backups. When the primary fails, the next one is tried. Run it. The primary fails, the backup answers, and the response metadata shows which model actually replied.

fallbacks.pypython
from langchain.chat_models import init_chat_model

primary = init_chat_model("google_genai:gemini-retired-model")   # pretend it's down
backup = init_chat_model("google_genai:gemini-flash-lite-latest")
model = primary.with_fallbacks([backup])

reply = model.invoke("Say OK.")
print(reply.text.strip())
print("answered by:", reply.response_metadata["model_name"])
Output
OK.
answered by: gemini-3.5-flash-lite

Good fallbacks

The best backup is often a different provider, so one outage can't take down both. Make sure your prompt works well on the backup too. Fallbacks work on any runnable, so you can give a whole chain a backup chain. For agents, there's model fallback middleware.

keyvalue
Different providersurvives outages
Test the prompton the backup too
Any runnablechains too
AgentsModelFallbackMiddleware

Summary

With fallbacks tries backup models when the main one fails, so your app keeps running. Next, stopping agents that run away.

Key takeaways
  • .with_fallbacks([backup])
  • Different provider
  • Test both
Next up: Limiting Agent Calls — no runaway loops