In Part 1: LangChain Fundamentals, we explored linear chains (Prompt | Model | OutputParser). However, real-world tasks require reasoning loops: an AI must query APIs, inspect files, check if retrieved data answers the question, and dynamically self-correct.
This guide explores how to build autonomous agentic loops using LangChain Tools and LangGraph.
[!NOTE] Architecture Update: LangGraph as the Agent Standard While legacy LangChain relied on
AgentExecutor, LangChain officially designates LangGraph as the foundation for stateful, multi-actor, and cyclical agent workflows.
1. Defining Custom Capabilities with @tool
Tools expose Python functions to language models via schema generation. Clear docstrings and type annotations directly guide the model's tool selection:
from langchain_core.tools import tool
@tool
def calculate_growth_rate(initial: float, final: float, periods: int) -> float:
"""Calculates the Compound Annual Growth Rate (CAGR) across periods.
Args:
initial: Starting value.
final: Ending value.
periods: Number of elapsed periods/years.
"""
if initial <= 0 or periods <= 0:
raise ValueError("Initial value and periods must be positive.")
return round(((final / initial) ** (1 / periods) - 1) * 100, 2)
2. Dynamic Tool Calling Agents
Modern models natively support function calling. You bind available tools directly to the chat model:
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
tools = [calculate_growth_rate]
llm = ChatOpenAI(model="gpt-4o-mini").bind_tools(tools)
# The model decides whether to respond directly or emit tool_calls
response = llm.invoke([
HumanMessage(content="Revenue was 100k in 2021 and grew to 250k in 2024. What was the CAGR?")
])
print(response.tool_calls)
# [{'name': 'calculate_growth_rate', 'args': {'initial': 100.0, 'final': 250.0, 'periods': 3}, 'id': '...'}]
3. Controlling Agent Flow with LangGraph
Linear chains fail when an agent needs conditional branching (e.g., Is the search result sufficient? If not, reformulate query and search again). LangGraph models workflows as directed graphs composed of Nodes (actions), Edges (transitions), and State.
Defining Workflow State
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph, END
from langgraph.graph.message import add_messages
class AgentState(TypedDict):
# add_messages appends new messages rather than overwriting existing history
messages: Annotated[list, add_messages]
needs_clarification: bool
Implementing Graph Nodes
from langchain_core.messages import SystemMessage
def analyze_query(state: AgentState) -> dict:
last_message = state["messages"][-1].content
# Flag ambiguous queries
if len(last_message.split()) < 3:
return {"needs_clarification": True}
return {"needs_clarification": False}
def ask_user(state: AgentState) -> dict:
return {
"messages": [SystemMessage(content="Could you provide more context or specify details?")]
}
def call_tools_or_model(state: AgentState) -> dict:
response = llm.invoke(state["messages"])
return {"messages": [response]}
Building the Graph
workflow = StateGraph(AgentState)
# Register nodes
workflow.add_node("analyze", analyze_query)
workflow.add_node("clarify", ask_user)
workflow.add_node("agent", call_tools_or_model)
# Set entry point
workflow.set_entry_point("analyze")
# Conditional edge routing based on state inspection
def route_clarification(state: AgentState):
if state["needs_clarification"]:
return "clarify"
return "agent"
workflow.add_conditional_edges(
"analyze",
route_clarification,
{"clarify": "clarify", "agent": "agent"}
)
workflow.add_edge("clarify", END)
workflow.add_edge("agent", END)
# Compile into an executable application
app = workflow.compile()
Visualizing and Executing
LangGraph supports native Mermaid diagram generation:
print(app.get_graph().draw_mermaid())
flowchart TD
__start__([__start__]) --> analyze[analyze]
analyze -.-> clarify[clarify]
analyze -.-> agent[agent]
clarify --> __end__([__end__])
agent --> __end__
Execute with a specific conversational turn:
final_state = app.invoke({
"messages": [HumanMessage(content="Calculate CAGR from 50 to 120 in 4 years.")]
})
print(final_state["messages"][-1].content)
Summary
- Use
@toolwith rigorous type hints and docstrings for safe API integrations. - Bind tools to foundation models via
.bind_tools(). - Use LangGraph for production agents that require cycle handling, persistent memory checkpoints, and conditional multi-step branching.