LangChain interview questions and answers
10 questions from the LangChain Interview Mock practice bank, spread across its domains. Pick your answer, then open the explanation to see why each option is right or wrong.
- Question 1Core Runtime: Runnables, Models and Prompts
With
with_structured_output, whichmethodproduces syntactically valid JSON but leaves it to you to describe the schema in the prompt?- A
method="json_schema" - B
method="function_calling" - C
method="json_mode" - D
include_raw=True
Show the answer and explanation
Answer: C
json_schemauses the provider's structured-output feature with your schema.function_callingforces a tool call shaped by the schema.json_modeis the older option some providers offer: valid JSON, but the schema has to be in the prompt. Supported methods and defaults vary by provider; for example,ChatOpenAIdefaults tojson_schema.Why the other options are wrong
A. This uses the provider's native structured output and sends your schema, so the model is guided by it.
B. This forces a tool call whose argument schema is your schema.
D. That is not a method. It returns the raw message alongside the parsed result.
- A
- Question 2Retrieval and Memory
You are building an internal FAQ bot that must answer within a tight, predictable latency budget, and every question needs the knowledge base. Which design fits best?
- A
An agent with a retriever tool, so the model decides when and how often to search
- B
A two-step chain that always retrieves, then makes one model call with the retrieved context
- C
A hybrid design with query rewriting, retrieval grading and answer validation loops
- D
No retrieval; put the whole FAQ in the system prompt on every call
Show the answer and explanation
Answer: B
The docs compare three RAG architectures: two-step (high control, low flexibility, fast), agentic (low control, high flexibility, variable latency) and hybrid (medium on both, with validation steps). Choose agentic RAG when the model must decide whether to search, search several sources or iterate; choose two-step when every query needs retrieval and latency must be bounded.
Why the other options are wrong
A. Agentic RAG adds flexibility but makes the number of model calls and the latency variable.
C. The validation loops add quality checks, but they also add variable latency.
D. This may work for a tiny FAQ but scales poorly in cost and context, and it is not a retrieval design.
- A
- Question 3Production: Streaming, Observability and Testing
A teammate's handler implements only
on_llm_startandon_llm_end. It is attached to a chat model call (not a text-completion LLM). What happens at the start of the call?- A
Nothing: chat models fire only
on_chat_model_start, so the handler misses the start - B
on_llm_startfires, with the input messages converted to strings - C
The call fails with
NotImplementedErrorfromon_chat_model_start - D
Both hooks fire, so implementing both would log the start twice
Show the answer and explanation
Answer: B
BaseCallbackHandler.on_chat_model_startraisesNotImplementedErrorby default. The callback manager catches it and callson_llm_startwith each message list rendered as a string. Once you implementon_chat_model_start, you get the structured messages andon_llm_startno longer fires for chat models.on_llm_endfires for both kinds of model.Why the other options are wrong
A. LangChain falls back when a handler does not implement
on_chat_model_start.C. The manager catches that error and uses the fallback; the call itself is unaffected.
D. If the handler implements
on_chat_model_start, only that hook fires;on_llm_startis not called as well.
- A
- Question 4Tools and Agents
What happens on the last line?
from typing import Annotated from langchain.tools import tool, InjectedToolCallId @tool def remember(note: str, tool_call_id: Annotated[str, InjectedToolCallId]) -> str: """Remember a note.""" return f"{note} via {tool_call_id}" remember.invoke({"note": "hi"})- A
It returns
"hi via None" - B
ValueError: it needs a full tool call to get the id - C
It returns a
ToolMessagewith a randomly generatedtool_call_id - D
It returns
"hi via remember", using the tool name as the id
Show the answer and explanation
Answer: B
InjectedToolCallIdinjects the id of the current tool call, which is useful when a tool builds its ownToolMessageor aCommand. The argument is hidden from the model, and invoking with plain arguments raisesValueError. Withtc = {"name": "remember", "args": {"note": "hi"}, "id": "c42", "type": "tool_call"}it returns aToolMessagereadinghi via c42. In 1.x the docs preferruntime.tool_call_idviaToolRuntime.Why the other options are wrong
A. The id is not defaulted to
None; the tool refuses to run without one.C. LangChain does not invent ids; the call must come from a model tool call.
D. The tool name is never used as a call id.
- A
- Question 5Core Runtime: Runnables, Models and Prompts
What does this print?
prompt = ChatPromptTemplate.from_messages([ ("system", "S"), ("placeholder", "{history}"), ("human", "{q}"), ]) print(len(prompt.invoke({"q": "hi"}).to_messages()))- A
2 - B
3, because an empty placeholder message is inserted - C
It raises
KeyErrorfor the missinghistory - D
1, because the placeholder swallows the human turn
Show the answer and explanation
Answer: A
("placeholder", "{history}")is shorthand forMessagesPlaceholder("history", optional=True). With nohistory, the prompt has only the system and human messages, so it prints 2. A plainMessagesPlaceholder("history")is required and raises a missing-variableKeyError.Why the other options are wrong
B. An optional placeholder with no value adds nothing at all, not an empty message.
C. That is what
MessagesPlaceholder("history")does by default; the tuple shorthand setsoptional=True.D. Each entry is formatted on its own; the human message is always produced.
- A
- Question 6Retrieval and Memory
Your index was built with embedding model A. A teammate changes the app to embed queries with model B, which happens to produce vectors of the same length. What do you expect?
- A
A dimension-mismatch error on the first query
- B
No error, but retrieval quality silently collapses
- C
Results stay the same, because cosine similarity normalises the vectors
- D
LangChain detects the change and re-embeds the stored documents with model B
Show the answer and explanation
Answer: B
Documents and queries must be embedded by the same model (and the same settings). With different dimensions you at least get an error; with equal dimensions you get silently wrong results. Recovery means re-embedding the corpus with the new model into a fresh index, or reverting the query model.
Why the other options are wrong
A. The lengths match, so nothing fails; that is what makes this bug dangerous.
C. Normalising only fixes length; it cannot align two different embedding spaces.
D. Vector stores store whatever vectors you gave them; nothing re-embeds automatically.
- A
- Question 7Production: Streaming, Observability and Testing
Gunicorn runs your API with 8 worker processes on one machine. Each process builds its model with
rate_limiter=InMemoryRateLimiter(requests_per_second=5). The provider allows 10 requests per second for your key. What happens at peak?- A
The app stays at 5 requests per second, because the limiter is thread safe
- B
Up to about 40 per second, so 429s continue; use a shared limiter or gateway
- C
Exactly 10 per second, because the limiter reads the provider's rate-limit headers
- D
About 5 per second in total, because the processes share the bucket through the OS
Show the answer and explanation
Answer: B
InMemoryRateLimiteris thread safe and works in sync or async code, but it is not designed to coordinate across processes or machines. Divide the budget per process, or put a shared limiter (for example in Redis or an API gateway) in front. Keepmax_retrieswith backoff as the safety net for the 429s that still happen.Why the other options are wrong
A. Thread safety covers threads within one process; each worker has its own bucket.
C. It knows nothing about the provider; it only counts its own requests.
D. In-memory state is not shared between processes.
- A
- Question 8Tools and Agents
You bind three tools with
model.bind_tools(tools, tool_choice="any"). What does that change on each call?- A
It must call one of the bound tools, but may pick which
- B
LangChain picks a random tool and executes it
- C
The model must call every bound tool once
- D
The model may answer in text or call a tool, as it prefers
Show the answer and explanation
Answer: A
By default the model decides whether to call a tool.
tool_choice="any"forces some tool call;tool_choice="<tool name>"forces that specific tool. Forcing is useful for extraction-style steps, but in a loop it can stop the model from ever giving a final text answer, so it is usually applied to one step only.Why the other options are wrong
B. LangChain does not choose or run tools;
tool_choiceis passed to the provider.C. Forcing a tool call does not mean calling all of them.
D. That is the default behaviour when
tool_choiceis not set.
- A
- Question 9Core Runtime: Runnables, Models and Prompts
What does this
RunnableBranchreturn for0, and what would happen if you deleted its last argument?br = RunnableBranch( (lambda x: x > 0, RunnableLambda(lambda x: "pos")), (lambda x: x < 0, RunnableLambda(lambda x: "neg")), RunnableLambda(lambda x: "zero"), )- A
"zero"; without the last argument, construction fails because a default branch is required - B
"zero"; without the last argument,invoke(0)returnsNone - C
None; the default only runs when a condition raises an exception - D
"neg", because the last condition checked wins
Show the answer and explanation
Answer: A
RunnableBranchtakes(condition, runnable)pairs followed by a mandatory default. It checks conditions in order, runs only the first match on the original input and falls back to the default when nothing matches.Why the other options are wrong
B. There is no silent
None; the branch cannot even be constructed without a default.C. The default runs when no condition is true, which is the case for
0.D. Conditions are checked in order, and only a true condition selects a branch.
- A
- Question 10Retrieval and Memory
Your splitter uses
chunk_size=2000with the defaultlength_function=len. The embedding model accepts at most 512 tokens per input. What is the risk, and the direct fix?- A
None:
chunk_sizeis already counted in tokens, so the chunks fit - B
The splitter raises an error once a chunk exceeds the model limit, so just catch it
- C
A chunk can exceed 512 tokens; size chunks with a token-counting
length_function - D
Chunks will be too small; double
chunk_sizeto use the model fully
Show the answer and explanation
Answer: C
Characters and tokens do not map one to one, and the ratio changes with language and content. The docs advise counting tokens with the same tokenizer the model uses.
TextSplitterexposes this throughlength_function, plus thefrom_tiktoken_encoderandfrom_huggingface_tokenizerconstructors, which just install a token-counting length function.Why the other options are wrong
A. The default
length_functionislen, so the size is in characters.B. The splitter knows nothing about the embedding model and raises nothing.
D. 2,000 characters is roughly several hundred tokens and can exceed 512 for dense text, code or non-English scripts.
- A
Practise all 450 LangChain questions
Start with the free 15-question diagnostic. It shows where to focus, and your results carry over if you sign up.