AI Hints
Home›LangChain Tutorial›Cache, Limits and Timeouts
LangChain · Lesson 84 of 120

Timeouts

Never wait forever.

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

Networks fail. Sometimes a request hangs, with no reply. Without a timeout, your customer waits, and waits. A timeout says, give up after this many seconds, so your app can do something else.

Timeouts
From the video: Timeouts
  • Requests can hang
  • Customers wait
  • Give up after a limit

Setting a timeout

Timeout is the number of seconds to wait. Max retries is how many times to try again. To see a timeout happen, we set an impossibly short one, a hundredth of a second, with no retries. Run it. The call fails quickly, with a timeout error, which our code catches, and handles politely.

timeout.pypython
from langchain.chat_models import init_chat_model

model = init_chat_model("google_genai:gemini-flash-lite-latest",
                        timeout=0.01, max_retries=0)
try:
    print(model.invoke("Hello").text)
except Exception as error:
    print("Gave up:", type(error).__name__)
    print("Sorry, the assistant is busy. Please try again.")
Output
Gave up: ConnectTimeout
Sorry, the assistant is busy. Please try again.

Sensible settings

Real timeouts are usually tens of seconds, because long answers take time. Allow a couple of retries, for brief network blips. And always catch the error, so the customer sees a friendly message, not a crash.

keyvalue
timeoute.g. 30 seconds
max_retriese.g. 2
Catch errorsfriendly message
Streamingfeels faster too

Summary

Set a timeout and retries on every model, and catch the error when it happens. Next, tracking how many tokens, and how much money, each request uses.

Key takeaways
  • timeout=
  • max_retries=
  • Catch and explain
Next up: Tracking Cost — tokens per request