AI / LangGraph LangChain Interview questions
1. What is LangChain?
LangChain is an open-source framework for building applications powered by large language models ( LLMs ). It provides composable abstractions - Models, Prompts, Chains, Agents, Memory, and Tools - that make it practical to connect LLMs with external data and systems without writing all the integ...
2. What is LCEL (LangChain Expression Language)?
LCEL (LangChain Expression Language) is a declarative syntax for composing chains in LangChain using the pipe operator | . It connects Runnable objects so the output of one becomes the input of the next, making multi-step LLM workflows readable and concise. The core building block is the Runnable...
3. What are the key components of LangChain?
LangChain is organised around six core abstractions that cover the full lifecycle of an LLM application: Models — A unified interface to LLMs (text-in/text-out) and Chat Models (message-in/message-out), as well as Embedding models for vector representations. Supported providers include OpenAI, An...
4. How does LangChain differ from traditional LLM integration?
Traditional LLM integration means calling an LLM's HTTP API directly: you construct a prompt string by hand, send a requests.post() , parse the JSON response, and manage conversation history as a list you track yourself. Each provider has a different SDK, different error codes, and different retr...
5. What are LangChain Runnables?
A Runnable is the core interface in LangChain that every composable component implements. If something is a Runnable, it can be connected with | , batched, streamed, retried, and traced — regardless of whether it's a prompt template, an LLM, a retriever, or a custom Python function. Every Runnabl...
6. How do you install and set up LangChain?
LangChain is distributed as several pip packages. The minimal install for OpenAI-backed applications is: pip install langchain langchain-openai # For community integrations (vector stores, loaders, etc.): pip install langchain-community # For serving with REST API: pip install langserve fastapi u...
7. How do you use ChatModels in LangChain?
ChatModels in LangChain are LLM wrappers that communicate using a message-based format. Instead of passing a raw string, you pass a list of typed messages: SystemMessage , HumanMessage , and AIMessage . This maps directly to the roles used by OpenAI, Anthropic, and similar APIs. from langchain_op...
8. What are PromptTemplates in LangChain?
PromptTemplates are objects that format dynamic inputs into the correct structure before passing them to a model. Instead of building prompt strings with f-strings scattered across your codebase, templates give you reusable, testable, versionable prompt construction with named variables. There ar...
9. What are output parsers in LangChain?
Output parsers sit at the end of a chain and transform the raw text or message returned by an LLM into a more structured or usable form. Without a parser, chain.invoke() returns an AIMessage object; with a parser, you get a plain string, a Python dict, a validated Pydantic model, or a list — what...
10. What is the LangSmith platform?
LangSmith is LangChain's hosted observability and evaluation platform for LLM applications. It automatically captures traces — the full execution tree of every chain, agent step, LLM call, retriever hit, and tool invocation — so you can inspect exactly what happened during a run, including prompt...
11. What is LangChain Hub?
LangChain Hub is a public repository at smith.langchain.com/hub for sharing and versioning prompts. Teams use it to store prompts outside of application code, iterate on them without deployments, and pull specific versions into chains at runtime. To use Hub prompts in code, install langchainhub a...
12. What is LangServe?
LangServe is a library that turns any LCEL chain into a production-ready REST API in a few lines of code. It wraps FastAPI and exposes standard endpoints — /invoke , /batch , /stream , and /stream_log — so clients can call your chain over HTTP without any custom FastAPI code. pip install langserv...
13. How do callbacks work in LangChain?
Callbacks in LangChain are hooks that fire at specific lifecycle events during chain, model, and agent execution. You implement a BaseCallbackHandler subclass and override only the methods you care about. Each method receives context about what just happened — which model was called, what the pro...
14. How do you implement streaming in LangChain?
Streaming in LangChain means receiving model output token-by-token rather than waiting for the full response. This dramatically improves perceived responsiveness in user-facing applications. LCEL chains support streaming out of the box through three methods: stream() , astream() , and astream_eve...
15. How does LangChain handle versioning?
LangChain follows a modular package structure that allows different parts of the ecosystem to evolve at different speeds without breaking stable core interfaces. As of 2024, the main packages are: langchain-core — Stable base abstractions: Runnable, BaseMessage, BasePromptTemplate, BaseOutputPars...
16. What are Chains in LangChain?
A Chain in LangChain is any sequence of processing steps that takes an input, passes it through one or more components (prompts, models, retrievers, tools), and produces an output. Chains are the fundamental unit of composition — everything from a single prompt+model call to a multi-step RAG pipe...
17. What is the difference between sequential and parallel chains?
In a sequential chain , components run one after another: the output of step N becomes the input of step N+1. This is the default LCEL pipe behaviour — chain = step1 | step2 | step3 means step2 cannot start until step1 finishes. In a parallel chain , multiple branches run concurrently on the same...
18. How do you use the pipe operator in LCEL?
The pipe operator | in LCEL connects two Runnable objects so that the output of the left side becomes the input of the right side. It is syntactic sugar for RunnableSequence(left, right) and works because LangChain overloads Python's __or__ and __ror__ dunder methods on the Runnable base class. B...
19. What are RunnablePassthrough and RunnableLambda?
RunnablePassthrough and RunnableLambda are utility Runnables that solve two common chain-building problems: passing input data unchanged to a later step, and wrapping arbitrary Python logic as a Runnable step. RunnablePassthrough simply passes whatever it receives as input directly to its output....
20. What are common chain composition patterns?
Beyond simple prompt | model | parser pipes, a handful of patterns appear repeatedly in production LangChain applications: RAG pattern — retrieve relevant documents, inject them into a prompt, generate an answer. The retriever and passthrough run in parallel so both context and question reach the...
21. How do you implement a ConversationChain?
A ConversationChain maintains multi-turn dialogue by storing conversation history and injecting it into each new prompt invocation. The legacy approach uses ConversationChain with a memory object; the LCEL approach manages history explicitly in the chain state using MessagesPlaceholder . LCEL app...
22. How does routing work in LCEL?
Routing in LCEL means directing an input to one of several sub-chains based on a condition. The two main tools are RunnableBranch (declarative) and a plain Python function returning a Runnable (imperative). RunnableBranch — takes a list of (condition, runnable) pairs and a default. The first cond...
23. 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 : resul...
24. What are chain fallbacks and retries?
Fallbacks and retries are resilience mechanisms built into LangChain Runnables that make production chains tolerant of transient failures and model quality issues. Fallbacks — .with_fallbacks() attaches one or more backup Runnables that are tried in order if the primary raises an exception. You c...
25. How do you do batch processing with LCEL?
The .batch() method on any LCEL chain processes a list of inputs and returns a list of outputs. Under the hood, LangChain runs the inputs concurrently using a thread pool (synchronous) or asyncio tasks (async), subject to an optional concurrency limit. from langchain_openai import ChatOpenAI from...
26. What are LangChain Agents?
A LangChain Agent is a system where an LLM acts as the reasoning engine that decides, at each step, which action to take. Unlike a fixed chain where the sequence of operations is defined by the developer, an agent dynamically determines the order and selection of tool calls based on the user's in...
27. What are the different agent types in LangChain?
LangChain provides several agent types, each suited to different LLM capabilities and task requirements: Agent Type How it works Best for OpenAI Tools Agent Uses OpenAI's native tool/function calling API to select and call tools OpenAI models (gpt-4o, gpt-4-turbo); most reliable structured tool u...
28. How do you create custom agents?
The easiest way to create a custom agent is with the factory functions create_react_agent() or create_openai_tools_agent() , which combine a custom prompt, an LLM, and a list of tools. Most customisation needs are met by adjusting the prompt and tool list. from langchain import hub from langchain...
29. What is AgentExecutor?
AgentExecutor is the runtime loop that drives an agent to completion. It takes an agent (which decides actions) and a list of tools (which execute those actions), and repeatedly calls the agent, executes the selected tool, feeds the observation back, and repeats until the agent returns an AgentFi...
30. How do tools work in LangChain agents?
A Tool in LangChain is a callable that an agent can invoke when it needs to interact with the outside world. Every tool has three required attributes: a name (how the LLM refers to it), a description (what it does and when to use it — the LLM reads this to decide), and an input schema (the parame...
31. How do you create custom tools?
There are three ways to create custom tools in LangChain, in order of increasing complexity: the @tool decorator, StructuredTool.from_function() , and subclassing BaseTool . @tool decorator — simplest approach for single-string input tools: from langchain_core.tools import tool @tool def get_word...
32. What are multi-action agents?
A multi-action agent returns a list of AgentAction objects per reasoning step rather than a single action. This enables the agent to call multiple tools simultaneously within a single turn, which is useful when several tool calls are independent and don't need to be serialised. Multi-action agent...
33. How do agents plan and reason?
LangChain agents use the ReAct (Reasoning + Acting) framework to plan and reason. The model is prompted to produce interleaved Thought, Action, and Observation sequences. The Thought is the model's explicit reasoning about what to do next; the Action is the tool call decision; the Observation is ...
34. How do you integrate memory with agents?
By default, AgentExecutor has no memory — each invocation is stateless. To give an agent conversation memory, pass a memory object to AgentExecutor . This is distinct from return_intermediate_steps (which stores tool call history within a single run); memory stores the dialogue across multiple se...
35. How do you debug LangChain agents?
Debugging LangChain agents requires visibility into the agent's reasoning steps, tool inputs, and tool outputs — not just the final answer. Several tools address this at different levels of depth. verbose=True — prints every Thought, Action, and Observation to stdout during execution. Quick and z...
36. What is LangGraph?
LangGraph is a library for building stateful, multi-actor applications with LLMs using a directed graph model. Where LangChain chains are linear (or at most tree-shaped), LangGraph graphs can have cycles — a node can route back to an earlier node, making it possible to express iterative agent loo...
37. What are the differences between LangGraph and LangChain Agents?
LangChain Agents (via AgentExecutor) and LangGraph both implement agent behaviour, but they differ significantly in how much control you have over the execution flow: Dimension LangChain AgentExecutor LangGraph Execution flow Black-box loop; you can't see or modify the flow between steps Explicit...
38. What is StateGraph in LangGraph?
StateGraph is the main graph class in LangGraph. You instantiate it with a state type (a TypedDict class), add nodes and edges to it, then compile it into an executable app. The state type defines all the fields that are shared across nodes and how those fields are updated when a node returns a p...
39. How do nodes and edges work in LangGraph?
In LangGraph, nodes are Python functions that contain the logic of your application, and edges are the connections that define execution flow between nodes. Nodes receive the current state dict and return a partial state update (a dict containing only the keys they want to change). LangGraph merg...
40. How do you implement conditional edges in LangGraph?
Conditional edges implement branching logic in LangGraph. A router function takes the current state and returns a string key. That key is looked up in a mapping dict to determine which node to execute next. from langgraph.graph import StateGraph, START, END def should_continue (state: AgentState)...
41. How does state management work in LangGraph?
State in LangGraph is a TypedDict that is shared across all nodes in a graph run. Every time a node executes, it can return a partial update — a dict containing only the keys it wants to change. LangGraph merges the update into the current state using reducers . The default reducer is last-write-...
42. What is the difference between MessageGraph and StateGraph?
MessageGraph is a specialised version of StateGraph where the entire state is a single list of messages (using the add_messages reducer). Nodes receive the message list and return new messages to append. StateGraph is the general-purpose graph where you define any TypedDict as the state, with ful...
43. How does checkpointing work in LangGraph?
LangGraph's checkpointing system saves the full graph state after every node execution to a persistent store. This enables resuming interrupted runs, time-travel debugging (replay from any past state), and human-in-the-loop workflows (pause, inspect, modify state, then continue). To enable checkp...
44. How do you implement human-in-the-loop with LangGraph?
Human-in-the-loop (HITL) in LangGraph means pausing graph execution at a specified point so a human can inspect the current state, approve an action, or modify a value before the graph continues. This is a first-class LangGraph feature built on top of checkpointing. Step 1: Compile the graph with...
45. How do you build multi-agent systems with LangGraph?
Multi-agent systems in LangGraph are built by representing each agent as a node (or subgraph) and connecting them with edges that define how work is handed off. The most common architecture is the supervisor pattern : one supervisor agent receives the user request, decides which specialist agent ...
46. What are subgraphs in LangGraph?
A subgraph in LangGraph is a compiled graph that is used as a node inside a parent graph. Subgraphs allow you to encapsulate complex, reusable agent logic and compose multiple graphs hierarchically — exactly like functions in programming, where a subgraph is the 'function' and the parent graph is...
47. How do streaming and callbacks work in LangGraph?
LangGraph's .stream() and .astream() methods yield events as each node finishes executing, rather than waiting for the full graph to complete. The stream_mode parameter controls what is yielded. The three main stream modes: stream_mode='updates' (default) — yields the state update returned by eac...
48. What are persistence patterns in LangGraph?
Persistence in LangGraph means saving graph state so it survives process restarts, can be resumed after interrupts, and can be inspected or replayed at any past checkpoint. All persistence goes through the checkpointer interface, so the storage backend is swappable without changing application co...
49. How do you handle errors in LangGraph?
Error handling in LangGraph is explicit — errors in nodes are not automatically caught or retried. If a node raises an unhandled exception, the graph execution stops and the exception propagates to the caller. This is intentional: LangGraph wants you to be explicit about failure modes rather than...
50. How do you deploy LangGraph applications?
LangGraph applications can be deployed in three main ways: LangGraph Cloud (managed service), self-hosted with Docker + FastAPI , and embedded in a larger application . The right choice depends on your team's infrastructure requirements and SLA needs. LangGraph Cloud — LangChain's managed deploym...