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.

  1. Question 1Core Runtime: Runnables, Models and Prompts

    With with_structured_output, which method produces 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_schema uses the provider's structured-output feature with your schema. function_calling forces a tool call shaped by the schema. json_mode is 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, ChatOpenAI defaults to json_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.

  2. 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.

  3. Question 3Production: Streaming, Observability and Testing

    A teammate's handler implements only on_llm_start and on_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_start fires, with the input messages converted to strings

    • C

      The call fails with NotImplementedError from on_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_start raises NotImplementedError by default. The callback manager catches it and calls on_llm_start with each message list rendered as a string. Once you implement on_chat_model_start, you get the structured messages and on_llm_start no longer fires for chat models. on_llm_end fires 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_start is not called as well.

  4. 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 ToolMessage with a randomly generated tool_call_id

    • D

      It returns "hi via remember", using the tool name as the id

    Show the answer and explanation

    Answer: B

    InjectedToolCallId injects the id of the current tool call, which is useful when a tool builds its own ToolMessage or a Command. The argument is hidden from the model, and invoking with plain arguments raises ValueError. With tc = {"name": "remember", "args": {"note": "hi"}, "id": "c42", "type": "tool_call"} it returns a ToolMessage reading hi via c42. In 1.x the docs prefer runtime.tool_call_id via ToolRuntime.

    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.

  5. 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 KeyError for the missing history

    • D

      1, because the placeholder swallows the human turn

    Show the answer and explanation

    Answer: A

    ("placeholder", "{history}") is shorthand for MessagesPlaceholder("history", optional=True). With no history, the prompt has only the system and human messages, so it prints 2. A plain MessagesPlaceholder("history") is required and raises a missing-variable KeyError.

    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 sets optional=True.

    • D. Each entry is formatted on its own; the human message is always produced.

  6. 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.

  7. 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

    InMemoryRateLimiter is 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. Keep max_retries with 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.

  8. 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_choice is passed to the provider.

    • C. Forcing a tool call does not mean calling all of them.

    • D. That is the default behaviour when tool_choice is not set.

  9. Question 9Core Runtime: Runnables, Models and Prompts

    What does this RunnableBranch return for 0, 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) returns None

    • 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

    RunnableBranch takes (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.

  10. Question 10Retrieval and Memory

    Your splitter uses chunk_size=2000 with the default length_function=len. The embedding model accepts at most 512 tokens per input. What is the risk, and the direct fix?

    • A

      None: chunk_size is 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_size to 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. TextSplitter exposes this through length_function, plus the from_tiktoken_encoder and from_huggingface_tokenizer constructors, which just install a token-counting length function.

    Why the other options are wrong

    • A. The default length_function is len, 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.

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.

Go to LangChain