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.
More Related questions...