AI Hints
Home›LangChain Tutorial›Passthrough, Routing, Fallbacks
LangChain · Lesson 24 of 120

Fallbacks and Retries

When calls fail.

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

Model providers have bad moments. A call times out, or hits a rate limit. Runnables have two built in safety nets. Retries, and fallbacks.

Fallbacks and Retries
From the video: Fallbacks and Retries
  • Providers fail sometimes
  • Timeouts, rate limits
  • Two safety nets

with_retry

With retry wraps any runnable, so it tries again when it fails. To see it work without breaking a real model, we use a function that fails twice, then succeeds. Run it. The first two attempts fail, the third works, and our code just gets the answer.

retry.pypython
from langchain_core.runnables import RunnableLambda

attempts = {"n": 0}
def flaky(x):
    attempts["n"] += 1
    if attempts["n"] < 3:
        print(f"attempt {attempts['n']}: failed")
        raise TimeoutError("provider timed out")
    return f"attempt {attempts['n']}: ok -> {x}"

safe = RunnableLambda(flaky).with_retry(stop_after_attempt=3)
print(safe.invoke("hello"))
Output
attempt 1: failed
attempt 2: failed
attempt 3: ok -> hello

with_fallbacks

With fallbacks gives a backup. If the main runnable fails, the fallback runs instead. In real apps, the backup is usually a different model, or a different provider. Here the main step always fails. Run it. The fallback answers, and the user never sees an error.

fallback.pypython
from langchain_core.runnables import RunnableLambda

def main_model(q):
    raise ConnectionError("main provider is down")

def backup_model(q):
    return f"(backup) Here is an answer to: {q}"

chain = RunnableLambda(main_model).with_fallbacks([RunnableLambda(backup_model)])
print(chain.invoke("Do you sell gift cards?"))
Output
(backup) Here is an answer to: Do you sell gift cards?

Summary

With retry tries again after failures, and with fallbacks switches to a backup. Use both around model calls in real apps. Next, seeing what happens inside a chain.

Key takeaways
  • .with_retry()
  • .with_fallbacks([...])
  • Backup models
Next up: Seeing Inside a Chain — callbacks