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 RunnableLambdaattempts = {"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"))
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 RunnableLambdadef 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?
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.