PrepStack › AI › LangChain & LangGraph

LangChain & LangGraph interview cheat sheet

LCEL, tools, agents, RAG, memory, graphs, checkpoints and LangSmith

GenAI interviews use LangChain to check that you can build real LLM apps, not just call an API. Expect questions on the package layout, LCEL and Runnables, structured output, tool calling, create_agent and middleware, RAG, and memory. For agent roles they go deeper into LangGraph: state and reducers, conditional edges, checkpointers and threads, interrupts, streaming and multi-agent design. All code targets LangChain 1.x / LangGraph 1.x. Snippets marked with output are small stdlib Python models of the idea, so you can see what the framework does under the hood. Read the 15-minute list first, then use Quiz mode.

15-minute revision

  1. LangChain = standard interfaces (chat models, tools, retrievers) + create_agent. LangGraph = low-level runtime for stateful graphs (state, loops, checkpoints, interrupts). LangSmith = tracing, evals and deployment.
  2. Packages: langchain-core (base abstractions, LCEL), langchain (agents, init_chat_model), partner packages like langchain-openai, langchain-community (third-party integrations), langchain-text-splitters, and langchain-classic for legacy chains.
  3. v1 (Oct 2025) slimmed langchain down: old chains, LLMChain, ConversationChain, memory classes and langchain.retrievers moved to langchain-classic. Python 3.10+ is required.
  4. Chat models take a list of messages (SystemMessage, HumanMessage, AIMessage, ToolMessage) and return an AIMessage. init_chat_model("provider:model") picks a provider from a string.
  5. Everything is a Runnable with invoke / batch / stream and async twins ainvoke / abatch / astream. The | operator builds a RunnableSequence (LCEL).
  6. A dict inside a chain becomes RunnableParallel. RunnablePassthrough forwards the input; .assign(...) adds keys; RunnableLambda wraps a plain function.
  7. Prefer model.with_structured_output(PydanticModel) over prompt-based parsing. It uses native tool calling or JSON schema mode, and include_raw=True keeps the raw message.
  8. Tool calling: @tool turns a typed function plus docstring into a schema. bind_tools sends schemas; the model returns ai.tool_calls; you run them and send back ToolMessages.
  9. create_agent(model, tools, system_prompt=...) is the v1 agent. It replaces langgraph.prebuilt.create_react_agent (prompt= became system_prompt=). It runs on LangGraph.
  10. Middleware hooks: before_agent, before_model, wrap_model_call, wrap_tool_call, after_model, after_agent. Built-ins include summarization, HITL, PII, call limits, fallbacks and retries.
  11. RAG pipeline: load → split (RecursiveCharacterTextSplitter) → embed → store (vector store) → retrieve (as_retriever) → generate with context and citations.
  12. Memory today = graph state + checkpointer + thread_id (short-term) and a Store with namespaces (long-term). The old ConversationBufferMemory family is legacy.
  13. LangGraph: StateGraph(State) → add_node → add_edge / add_conditional_edges from START to END → compile(checkpointer=...). Nodes return partial updates; reducers merge them.
  14. Checkpoints are saved after every super-step per thread. They give memory, get_state_history time travel, fault tolerance and interrupt() human-in-the-loop (resume with Command(resume=...)).
  15. Stream modes: values (full state), updates (node deltas), messages (LLM tokens), custom (your events), plus checkpoints, tasks, debug. Use subgraphs=True to see nested graphs.
  16. Criticism: heavy abstractions, fast API churn and hard debugging. For one prompt plus one API call, the plain provider SDK is often better. Use LangGraph when you need state, loops, persistence or HITL.

Foundations

What LangChain is & package layout

LangChain is a framework of standard interfaces for LLM apps and agents; LangGraph is the runtime underneath, and LangSmith is the observability platform.

  • LangChain gives one interface over many model providers, tools, vector stores and retrievers, plus a ready agent (create_agent). Swap OpenAI for Anthropic by changing one string.
  • LangGraph is a lower-level orchestration runtime. You model an app as a graph of nodes sharing state, with loops, branching, persistence, streaming and human-in-the-loop.
  • LangSmith is a separate (framework-agnostic) platform for tracing, evaluation, prompt management and deployment.
  • v1.0 (Oct 2025) focused langchain on agents: langchain.agents, langchain.messages, langchain.tools, langchain.chat_models, langchain.embeddings. Legacy code moved to langchain-classic.
  • Deep Agents (deepagents) is a higher-level harness on top of create_agent with planning, a virtual file system and subagents. Mention it only if asked about long-running agents.

Interview questions

  • What is LangChain and why would you use it?
  • Difference between LangChain, LangGraph and LangSmith?
  • What changed in LangChain 1.0?
  • Why are integrations split into separate packages like langchain-openai?

Chat models & messages

A chat model takes a list of typed messages and returns an AIMessage; every provider looks the same through this interface.

  • Message types: SystemMessage (instructions), HumanMessage (user), AIMessage (model output, may hold tool_calls), ToolMessage (tool result, linked by tool_call_id).
  • init_chat_model("anthropic:claude-sonnet-4-6", temperature=0) builds a model from a string. Or construct a class like ChatOpenAI(model=...) directly.
  • AIMessage carries content, tool_calls, usage_metadata (token counts) and response_metadata (provider details). In v1, .content_blocks gives a provider-neutral view (text, reasoning, tool calls, citations).
  • stream() yields AIMessageChunks that can be added (a + b) to rebuild the full message. .text gives the text part.
  • Chat models are Runnables, so they also have batch, ainvoke and work inside LCEL chains.
  • Plain dicts ({"role": "user", "content": "..."}) and (role, text) tuples are accepted as message input.

Interview questions

  • What are the main message types in LangChain?
  • What does init_chat_model give you over ChatOpenAI(...)?
  • How do you get token usage from a call?

Prompt templates

A prompt template turns a dict of variables into a list of messages, and it is a Runnable you can pipe into a model.

  • ChatPromptTemplate.from_messages([("system", "...{x}..."), ("human", "{q}")]) is the common form. PromptTemplate is the plain-string version.
  • MessagesPlaceholder("history") splices a list of earlier messages (chat history, agent scratchpad) into the prompt.
  • .partial(lang="English") pre-fills some variables. input_variables tells you what is still needed.
  • Invoking a template returns a PromptValue; .to_messages() or .to_string() converts it.
  • Templates use Python str.format syntax by default, so literal braces in JSON examples must be doubled: {{ and }}.

Interview questions

  • Why use a prompt template instead of an f-string?
  • What is MessagesPlaceholder used for?

Output parsers & structured output

Use with_structured_output(Schema) to get validated objects from the model; output parsers are the older, prompt-based way.

  • model.with_structured_output(Schema) accepts a Pydantic model, TypedDict or JSON schema and returns parsed objects. It uses the provider's native tool calling or JSON-schema mode.
  • method="json_schema" uses strict provider schema mode where supported; include_raw=True returns {raw, parsed, parsing_error} for debugging.
  • Output parsers (StrOutputParser, JsonOutputParser, PydanticOutputParser) parse text after the call. They rely on format instructions in the prompt, so they fail more often.
  • StrOutputParser is still everywhere: it turns an AIMessage into a plain string at the end of an LCEL chain and streams text chunks.
  • In agents, pass response_format=Schema to create_agent. The result lands in result["structured_response"], generated in the main loop (no extra LLM call).
  • Repair parsers like OutputFixingParser and RetryOutputParser moved to langchain-classic in v1.

Interview questions

  • Difference between an output parser and with_structured_output?
  • How do you debug a structured output call that sometimes fails?
  • What does StrOutputParser actually do?

LCEL & Runnables

LCEL & the Runnable interface

LCEL composes Runnables with |; every piece shares invoke, batch, stream and their async versions.

  • Runnable is the common interface: invoke, batch, stream, ainvoke, abatch, astream, astream_events. Prompts, models, parsers, retrievers, tools and graphs all implement it.
  • LCEL (LangChain Expression Language) is the | syntax. a | b | c builds a RunnableSequence; output of one step is input of the next.
  • Python functions and dicts are coerced: a function becomes RunnableLambda, a dict becomes RunnableParallel.
  • batch runs inputs concurrently (thread pool for sync, asyncio for async). Control it with config={"max_concurrency": n}.
  • Streaming passes chunks through steps that support it (model → StrOutputParser). A step that needs its full input (like a plain function) blocks the stream until it is done.
  • config carries tags, metadata, callbacks, run_name and configurable. It flows to every child run, which is how LangSmith shows nested traces.

Interview questions

  • What is LCEL and why was it introduced?
  • Difference between invoke, batch and stream?
  • What is a Runnable?
  • When does streaming break in a chain?

RunnableParallel, Passthrough, Lambda & resilience

The building blocks for non-trivial chains: fan out, pass input through, add keys, wrap functions, retry and fall back.

  • RunnableParallel runs branches on the same input and returns a dict. A dict literal in a chain is turned into one.
  • RunnablePassthrough returns its input unchanged; typical use is forwarding the question next to retrieved context.
  • .assign(key=runnable) keeps the input dict and adds computed keys, useful to return answer and sources.
  • RunnableLambda wraps a normal function (sync or async) so it can be piped and traced.
  • with_retry(stop_after_attempt=3) retries transient errors; with_fallbacks([backup]) tries other Runnables in order when one fails.
  • RunnableBranch and routing functions exist, but complex routing is clearer as a LangGraph conditional edge.

Interview questions

  • How do you return the retrieved sources together with the answer?
  • Difference between RunnablePassthrough and RunnableLambda?
  • How do you handle a provider outage in a chain?

Tools & agents

Tools & tool calling

A tool is a function with a name, description and argument schema; the model asks for calls, your code runs them.

  • @tool (from langchain.tools) builds a tool from a typed function: name from the function, description from the docstring, args schema from type hints.
  • model.bind_tools([...]) sends the schemas with each request. The model replies with an AIMessage whose tool_calls list has name, args and id.
  • The model never executes anything. Your code runs the tool and appends a ToolMessage with the matching tool_call_id, then calls the model again.
  • Invoking a tool with a whole ToolCall dict returns a ready ToolMessage.
  • tool_choice can force a specific tool or require any tool. Parallel tool calls are allowed by most providers.
  • In v1, a parameter typed ToolRuntime is hidden from the model and gives the tool access to state, context, store and stream writer.

Interview questions

  • How does tool calling work end to end?
  • Does the LLM execute the tool?
  • How does a tool get the current user id without the model seeing it?

create_agent (LangChain v1)

create_agent is the standard tool-calling agent: model + tools + system prompt, running as a LangGraph graph.

  • Signature basics: create_agent(model, tools, system_prompt=..., middleware=[...], response_format=..., state_schema=..., context_schema=..., checkpointer=..., store=...).
  • It runs the ReAct-style loop: call model → if tool_calls, run tools → feed results back → stop when the model answers without tool calls.
  • Input and output are state: {"messages": [...]}. Read the answer from result["messages"][-1].
  • Because it is a compiled LangGraph graph, you get streaming, checkpointers, interrupts and time travel for free.
  • Migration: langgraph.prebuilt.create_react_agent → langchain.agents.create_agent; prompt= → system_prompt=; pre_model_hook/post_model_hook → middleware; config["configurable"] context → context= with context_schema.
  • Older AgentExecutor + create_tool_calling_agent patterns are legacy (now in langchain-classic).

Interview questions

  • What is create_agent and what does it replace?
  • What is the ReAct pattern?
  • When would you write a custom StateGraph instead of using create_agent?

Agent middleware

Middleware hooks into the agent loop before/after/around model and tool calls, which is how you do context engineering, guardrails and HITL.

  • Node-style hooks run at points and can return state updates: before_agent, before_model, after_model, after_agent. They can also jump_to "end", "tools" or "model".
  • Wrap-style hooks surround a call and control the handler: wrap_model_call (swap model, tools, prompt; retry; cache) and wrap_tool_call (log, retry, block).
  • Write them as decorators (@before_model, @wrap_model_call, @dynamic_prompt) or as an AgentMiddleware subclass with several hooks and config.
  • Built-ins: SummarizationMiddleware, HumanInTheLoopMiddleware, PIIMiddleware, ModelCallLimitMiddleware, ToolCallLimitMiddleware, ModelFallbackMiddleware, ModelRetryMiddleware, ToolRetryMiddleware, LLMToolSelectorMiddleware, TodoListMiddleware, ContextEditingMiddleware.
  • Middleware can add state fields (state_schema) and tools. Runtime context (user role, tenant) comes from context_schema + invoke(..., context=...).
  • Order matters: before_* hooks run in list order, after_* in reverse, and wrap hooks nest like onion layers (first in the list is outermost).

Interview questions

  • What is middleware in LangChain v1 and why does it exist?
  • Difference between node-style and wrap-style hooks?
  • How would you add human approval before an agent sends an email?
  • How do you keep a long-running agent inside the context window?

Retrieval, RAG & memory

Loaders, splitters, embeddings & vector stores

Indexing turns files into searchable chunks: load Documents, split them, embed them, and store vectors behind a retriever.

  • A Document has page_content and metadata (source, page, ids). Loaders (PyPDFLoader, WebBaseLoader, CSVLoader, ...) return lists of Documents.
  • Text splitters chunk long text. RecursiveCharacterTextSplitter tries \n\n, then \n, then spaces, then characters, so it keeps paragraphs whole when possible. chunk_overlap repeats a tail so ideas are not cut in half.
  • Embeddings map text to vectors (OpenAIEmbeddings, init_embeddings("provider:model")). Use the same model for indexing and querying.
  • Vector stores (InMemory, Chroma, FAISS, PGVector, Pinecone, Qdrant, ...) share one interface: add_documents, similarity_search, similarity_search_with_score, as_retriever.
  • A retriever is a Runnable: string in, list[Document] out. search_type="mmr" adds diversity; search_kwargs sets k and metadata filters.
  • Other splitters exist for Markdown headers, code and tokens. Chunk size is a tuning knob: small chunks are precise, big ones keep context.

Interview questions

  • Why do we split documents before embedding?
  • Difference between a vector store and a retriever?
  • How do you choose chunk size and overlap?

Building RAG with LangChain

RAG retrieves relevant chunks at query time and gives them to the model as context, either in a fixed two-step chain or as an agent tool.

  • Two-step RAG chain: always retrieve once, then one model call. Fast and predictable; built with LCEL ({context, question} | prompt | model | parser).
  • Agentic RAG: retrieval is a tool; the agent decides whether to search, can reformulate and search several times. Better for multi-hop questions, but slower and costlier.
  • Prompt the model to answer only from context, cite sources and say "I don't know" when the context lacks the answer.
  • Quality levers: chunking, hybrid search, metadata filters, re-ranking (cross-encoder), query rewriting, and keeping k small.
  • @tool(response_format="content_and_artifact") returns text for the model and the raw Documents as an artifact for your UI.
  • Evaluate retrieval (did the right chunk come back?) separately from generation (faithful, relevant answer), for example with LangSmith datasets.

Interview questions

  • Walk me through building a RAG app in LangChain.
  • Your RAG bot gives confident wrong answers. How do you debug it?
  • When would you choose agentic RAG over a simple chain?

Memory: legacy classes vs LangGraph persistence

Old LangChain memory classes are legacy; today short-term memory is checkpointed graph state per thread, and long-term memory is a Store.

  • Legacy: ConversationBufferMemory, ConversationBufferWindowMemory, ConversationSummaryMemory plugged into ConversationChain/LLMChain. Deprecated in 0.3 and moved to langchain-classic in v1.
  • Interim: RunnableWithMessageHistory wrapped an LCEL chain with a session-keyed history store. Still works, but agents now use checkpointers.
  • Short-term memory = the messages list in graph state, saved by a checkpointer after each step and loaded by thread_id.
  • Long-term memory = a Store (InMemoryStore, Postgres store) with namespaces like ("users", user_id), shared across threads. Tools reach it via ToolRuntime.
  • Control context size with trim_messages, SummarizationMiddleware, or deleting messages with RemoveMessage.
  • Memory types people ask about: semantic (facts), episodic (past examples), procedural (instructions/prompt updates).

Interview questions

  • How is memory handled in modern LangChain?
  • Difference between short-term and long-term memory?
  • Why were ConversationBufferMemory and friends deprecated?

LangGraph

StateGraph: state, reducers, nodes & edges

A LangGraph app is a graph of nodes that read shared state and return partial updates; reducers decide how updates merge.

  • State schema: a TypedDict, dataclass or Pydantic model. MessagesState is a ready one with a messages key.
  • Reducers via Annotated[type, reducer]: add_messages appends and updates by message id; operator.add concatenates lists. No reducer means last write wins.
  • Nodes are functions (state) -> dict that return only the keys they change. They can also be compiled graphs or Runnables.
  • Edges: add_edge(a, b) is a fixed transition. START and END are the virtual entry and exit nodes.
  • compile() validates the graph and returns a Runnable (invoke, stream, batch), optionally with a checkpointer, store and interrupt points.
  • Execution follows a Pregel/BSP model: nodes scheduled in the same super-step run in parallel, then all updates are applied together.

Interview questions

  • What is a reducer in LangGraph?
  • Why do nodes return partial updates instead of the full state?
  • What does compile() do?
  • Difference between LCEL chains and LangGraph?

Conditional edges, Command & Send

Routing functions pick the next node from state; Command lets a node update state and route at once; Send fans out work dynamically.

  • add_conditional_edges(source, router, path_map): the router reads state and returns a node name, a list of names (run in parallel) or END.
  • Declaring the possible targets (list, dict or Literal return type) lets LangGraph draw the graph and validate names.
  • The classic agent loop: agent → (tool_calls? tools : END), tools → agent. ToolNode and tools_condition in langgraph.prebuilt implement it.
  • Command(update=..., goto=...) returned from a node combines a state update with routing; graph=Command.PARENT hands off to a node in the parent graph (multi-agent handoffs).
  • Send(node, payload) from a conditional edge creates one task per item with its own input: the map-reduce pattern (summarise N docs in parallel, reduce with a reducer key).
  • Every run has a recursion_limit on super-steps; exceeding it raises GraphRecursionError. Old versions defaulted to 25; recent 1.x releases default much higher, so set your own for agents.

Interview questions

  • How do you implement a loop in LangGraph?
  • Difference between conditional edges and Command?
  • How would you summarise 50 documents in parallel and combine them?

Checkpointers, threads & time travel

A checkpointer saves graph state after every super-step under a thread id, which gives memory, fault tolerance, time travel and human-in-the-loop.

  • Compile with a checkpointer: InMemorySaver (dev), SqliteSaver, PostgresSaver (separate langgraph-checkpoint-* packages), Redis and others.
  • A thread is a sequence of checkpoints identified by config["configurable"]["thread_id"]. Each checkpoint has a checkpoint_id.
  • get_state(config) returns a StateSnapshot (values, next, tasks, config, metadata). get_state_history(config) lists past checkpoints, newest first.
  • Time travel: invoke with a past checkpoint's config to replay from there, or update_state it to fork a new branch.
  • Fault tolerance: after a crash you re-invoke the thread and it continues from the last checkpoint; pending writes of finished parallel nodes are reused.
  • durability ("exit", "async", "sync") trades write overhead against how much progress survives a crash.

Interview questions

  • What is a checkpointer and what features depend on it?
  • What is a thread in LangGraph?
  • How does time travel work and when would you use it?
  • Your agent runs on 4 pods behind a load balancer. How do you keep conversations working?

Interrupts & human-in-the-loop

interrupt(payload) pauses a node and saves a checkpoint; the caller resumes later with Command(resume=value), which becomes the return value of interrupt.

  • Requirements: a checkpointer, a thread_id, and a JSON-serialisable payload.
  • With invoke, the payload comes back under result["__interrupt__"]; with version="v2" it is on result.interrupts. The graph waits indefinitely.
  • Resume with graph.invoke(Command(resume=...), same_config). The node restarts from its first line, and interrupt() now returns the resume value.
  • So code before interrupt() runs twice: keep it idempotent (no double charges or emails before the pause).
  • Patterns: approve/reject an action, edit a tool call or draft, ask for missing info, validate input in a loop.
  • Static breakpoints (interrupt_before=[...], interrupt_after=[...] at compile) exist mainly for debugging; prefer dynamic interrupt() in apps.

Interview questions

  • How does human-in-the-loop work in LangGraph?
  • Why must code before interrupt() be idempotent?
  • How would you build an approval flow for refunds over 100 USD?

Streaming modes & subgraphs

LangGraph streams state, node updates, LLM tokens and custom events; subgraphs let you nest graphs as nodes with their own state.

  • stream_mode="values" emits the full state after each step; "updates" emits only what each node returned.
  • "messages" emits (token_chunk, metadata) from any LLM call inside nodes, with the node name in metadata, for chat UIs.
  • "custom" emits whatever a node writes with get_stream_writer(), such as progress bars. "checkpoints", "tasks" and "debug" are for tooling.
  • Pass a list of modes to get (mode, chunk) tuples. version="v2" (LangGraph 1.1+) gives a uniform {type, ns, data} dict for every chunk.
  • Subgraphs: add a compiled graph directly as a node when it shares state keys; otherwise call it inside a node function and map state in and out.
  • subgraphs=True includes nested events with a namespace tuple. A subgraph uses the parent's checkpointer automatically.

Interview questions

  • Difference between stream_mode values and updates?
  • How do you stream LLM tokens from inside a graph?
  • When would you use a subgraph?

Multi-agent patterns

Split work across specialised agents only when one agent with good tools is not enough; the main patterns are subagents, handoffs, router and custom workflows.

  • Subagents (supervisor): a main agent calls specialists as tools. Only their final summary returns, which keeps the main context clean. Easy to parallelise.
  • Handoffs (swarm-style): the active agent changes via tool calls that update state (often Command(goto=..., graph=Command.PARENT)), so specialists talk to the user directly.
  • Router: a classification step sends the input to one or more agents and merges results.
  • Skills: one agent loads specialised prompts and knowledge on demand instead of spawning agents.
  • Custom workflow: a LangGraph graph mixing deterministic steps and agent nodes; any pattern can be a node.
  • Main reasons for multi-agent: context management, independent team ownership, and parallelism. Costs: more LLM calls, latency and harder debugging.

Interview questions

  • When do you need a multi-agent system?
  • Difference between the supervisor (subagents) and handoff patterns?
  • Design a customer-support system with billing and tech specialists.

Production & judgment

LangSmith tracing & evals

LangSmith records every run as a trace tree and lets you test prompts and agents against datasets with evaluators.

  • Turn on tracing with env vars LANGSMITH_TRACING=true and LANGSMITH_API_KEY (optional LANGSMITH_PROJECT). LangChain and LangGraph runs are traced automatically.
  • Each trace shows nested runs: prompts, model inputs and outputs, tool calls, latency, token usage and cost, errors.
  • @traceable traces any Python function, so it works with plain SDK code too.
  • Evals: build a dataset of inputs (and reference outputs), write evaluators (code checks or LLM-as-judge), and run client.evaluate(target, data=..., evaluators=[...]) to create an experiment you can compare.
  • Online evaluation scores production traces; feedback (thumbs up/down) can be attached to runs.
  • Also: prompt hub/versioning, annotation queues for human review, and deployment of LangGraph apps.

Interview questions

  • What is LangSmith used for?
  • How would you evaluate a RAG chatbot?
  • What is LLM-as-a-judge and its risks?

LangChain vs LlamaIndex vs plain SDK, and when not to use it

Pick the lightest tool that fits: plain SDK for simple calls, LlamaIndex for data-heavy RAG, LangChain/LangGraph for agents and stateful workflows.

  • Common criticism: too many abstractions, frequent breaking changes (0.1 → 0.2 → 0.3 → 1.0), confusing docs across versions, deep stack traces, and hidden prompts inside old chains.
  • v1 answered some of this: smaller langchain package, one agent API, legacy split into langchain-classic, stable 1.x promise (no breaking changes until 2.0).
  • Use it for multi-provider portability, tool-calling agents, RAG with many integrations, and with LangGraph for durable, stateful, human-in-the-loop workflows.
  • Skip it for one prompt and one API call, latency-critical paths where you want full control, or when your team prefers small explicit code.
  • You can mix: use LangGraph for orchestration with plain SDK calls inside nodes, and LangSmith with no LangChain at all.
  • Alternatives interviewers mention: LlamaIndex (data/RAG), Haystack (pipelines), OpenAI Agents SDK, Pydantic AI, CrewAI and AutoGen (multi-agent), DSPy (prompt optimisation).

Interview questions

  • What are the main criticisms of LangChain?
  • When would you not use LangChain?
  • LangChain vs LlamaIndex: how do you choose?
  • How would you migrate an old LLMChain/ConversationChain app to LangChain 1.x?