AI / LangGraph LangChain Interview questions
How do you handle errors in chains?
Error handling in LangChain chains operates at several levels: Python exception handling around .invoke(), chain-level fallbacks, parser-level retry, and output validation with Pydantic.
Basic try/except — handles transient API errors or rate limits:
from openai import RateLimitError
try:
result = chain.invoke({"question": user_input})
except RateLimitError as e:
result = "Service busy, please retry."
except Exception as e:
logger.error(f"Chain failed: {e}")
result = fallback_response
Chain fallbacks — declaratively try a backup chain if the primary fails:
# If gpt4_chain raises any exception, gpt35_chain is tried automatically
robust_chain = gpt4_chain.with_fallbacks([gpt35_chain])
Output parser errors — OutputFixingParser wraps another parser and uses a second LLM call to fix malformed output if parsing fails:
from langchain.output_parsers import OutputFixingParser
fixing_parser = OutputFixingParser.from_llm(
parser=json_parser, llm=ChatOpenAI()
)
chain = prompt | llm | fixing_parser
For structured output validation, using llm.with_structured_output(MyModel) raises a ValidationError if the model's response doesn't match the schema, making it easy to catch and handle type mismatches.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
