What control flow does this LangGraph graph implement?
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
class State(TypedDict):
messages: Annotated[list, add_messages]
def call_model(state: State) -> dict:
return {"messages": [llm_with_tools.invoke(state["messages"])]}
def should_continue(state: State) -> str:
last = state["messages"][-1]
return "tools" if last.tool_calls else END
builder = StateGraph(State)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", should_continue, ["tools", END])
builder.add_edge("tools", "agent")
graph = builder.compile()Show the answer and explanation
Correct answer: A, A cycle: agent runs, and if its last message has tool calls the tools node runs them and returns to agent; this repeats until the model replies without tool calls, then END.
Explanation LangGraph
This is the canonical tool-calling agent written as a LangGraph StateGraph:
- State: a
messageslist with theadd_messagesreducer, so messages returned by a node are appended (or merged by id) instead of overwriting the list. - Nodes:
agentcalls the model;tools(the prebuiltToolNode) executes every tool call in the last AI message and returns tool messages. - Edges:
START → agent; a conditional edge fromagentusesshould_continueto choosetoolsorEND; a normal edgetools → agentcloses the loop.
The run is therefore agent → tools → agent → tools → … → agent → END, stopping when the model answers without tool calls. This cycle is the main thing LangGraph adds over DAG-style chains such as LCEL pipelines, where data flows one way and there is no native loop back.
Why the other readings are wrong:
- Edges may point to earlier nodes; cycles are a core feature, not something the compiler drops.
- Only
agentis connected toSTART;toolsruns only when the conditional edge selects it. - The
tools → agentedge fires after tools, not after agent. The exit lives in the conditional edge.
The recursion limit (configurable per run) is still a useful safety net: if the model keeps requesting tools, LangGraph raises an error once the limit is hit, which you should catch and handle gracefully.
Interview tip: be ready to extend this graph: a human-approval node before tools for risky calls, a checkpointer for persistence, or a summarisation node when messages grows too long. LangGraph's prebuilt agent helpers build essentially this graph for you.