LangGraph Chain Detailed interpretation
📚 Overview
This document explains in detail the basic concept of LangGraph's Chain (chain call). This is the first lesson developed in LangGraph and covers the core components of building an intelligent conversation system: messaging system, chat model, tool binding, and tool execution. Through this tutorial, you will master how to use the basic concepts of LangChain to build a simple but fully functional AI chain.
🎯 Core Concept
What is Chain?
In LangChain/LangGraph, a Chain is a sequence of operations performed sequentially. A simple Chain usually contains:
- Input processing: receiving user messages
- Model Call: Use LLM to generate responses
- Tool Execution (optional): Call external tools/functions
- Output Return: Return the final result
The four core concepts of this tutorial
- Messages: Use chat messages as graph state
- Chat Models: Using LLM in graph nodes
- Tool Binding: Bind tools to the chat model
- Tool Calling: Execute tool calling in graph nodes
System architecture diagram
用户输入 "Multiply 2 and 3"
↓
[tool_calling_llm]
↓
检测到需要调用工具
↓
返回工具调用信息
(工具名: multiply, 参数: {a:2, b:3})🔧 Detailed explanation of code implementation
1. Message system (Messages)
What is a message?
The chat model uses Messages to represent the different roles in the conversation. LangChain supports multiple message types:
| Message Type | Role | Purpose |
|---|---|---|
HumanMessage | User | Represents user input |
AIMessage | AI model | Represents model response |
SystemMessage | System | Guide model behavior |
ToolMessage | Tools | Result of tool call |
Components of the message
Each message can contain:
content(required): message contentname(optional): the name of the message senderresponse_metadata(optional): metadata dictionary (such as model response information)
Code Example
from langchain_core.messages import AIMessage, HumanMessage
# 创建消息列表
messages = [
AIMessage(content="So you said you were researching ocean mammals?", name="Model"),
HumanMessage(content="Yes, that's right.", name="Lance"),
AIMessage(content="Great, what would you like to learn about.", name="Model"),
HumanMessage(content="I want to learn about the best place to see Orcas in the US.", name="Lance")
]
# 打印消息
for m in messages:
m.pretty_print()Output:
================================== Ai Message ==================================
Name: Model
So you said you were researching ocean mammals?
================================ Human Message =================================
Name: Lance
Yes, that's right.
...Python knowledge points: for loop and method calling
for m in messages:
m.pretty_print()for m in messages: Iterate over each element in themessageslistm.pretty_print(): Call thepretty_print()method of each message object- This is a typical usage of Python object-oriented programming
2. Chat Models
What is a chat model?
Chat Model is an LLM that supports conversational interactions and can:
- Receives a list of messages as input
- Understand the context of the conversation
- Generate responses that fit your role
LangChain supports multiple chat model providers: OpenAI, Anthropic, Google, Ollama, etc.
Set API Key
import os, getpass
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")Python knowledge points: Environment variables and security
os.environ.get(var): Get environment variablesgetpass.getpass(): Enter password securely (typing will not be displayed)- This is the best practice for protecting API Keys
Using chat model
from langchain_openai import ChatOpenAI
# 初始化模型
llm = ChatOpenAI(model="gpt-4o")
# 调用模型
result = llm.invoke(messages)Output type:
type(result)
# langchain_core.messages.ai.AIMessageresult is a AIMessage object containing:
result.content # AI 生成的文本内容
result.response_metadata # 响应元数据Detailed explanation of response metadata
result.response_metadataOutput example:
{
'token_usage': {
'completion_tokens': 228, # 输出的 token 数
'prompt_tokens': 67, # 输入的 token 数
'total_tokens': 295 # 总 token 数
},
'model_name': 'gpt-4o-2024-08-06',
'finish_reason': 'stop', # 停止原因(正常结束)
'logprobs': None
}Importance:
- Ability to track API usage costs
- Learn the details of model generation
- Debugging and optimizing performance
3. Tools
What is a tool?
Tools allow LLM to interact with external systems. When you need:
- Call API
- perform calculations
- Query database
- Access external services
You can define these functions as "tools" and let the model know when and how to use them.
How the tool works
用户输入(自然语言)
↓
LLM 分析输入
↓
决定是否需要调用工具
↓
返回符合工具 schema 的调用信息
(包含工具名称和参数)Define tools
In LangChain, any Python function can be a tool!
def multiply(a: int, b: int) -> int:
"""Multiply a and b.
Args:
a: first int
b: second int
"""
return a * bKey Takeaways:
- Type annotation:
a: int, b: int -> intlets the model know the parameter type - Documentation string: Describes the function of the function and helps the model understand when to use it.
Python knowledge points: Type Hints
def multiply(a: int, b: int) -> int:
# ^^^^^^ ^^^^^^ ^^^
# 参数a 参数b 返回值
# 是int 是int 是int
return a * bThe role of type annotations:
- Provide IDE code tips
- Help LangChain generate tool schema
- Improve code readability
- Not enforced (Python is still a dynamically typed language)
Bind tool to model
llm_with_tools = llm.bind_tools([multiply])**what happened? **
bind_tools()tells the model: "You can call these tools"- LangChain automatically generates tool schema from function signatures
- The model now knows the existence, parameters and purpose of the
multiplytool
Tool call example
tool_call = llm_with_tools.invoke([
HumanMessage(content="What is 2 multiplied by 3", name="Lance")
])
tool_call.tool_callsOutput:
[{
'name': 'multiply', # 工具名称
'args': {'a': 2, 'b': 3}, # 工具参数
'id': 'call_lBBBNo5oYpHGRqwxNaNRbsiT', # 调用 ID
'type': 'tool_call' # 类型
}]IMPORTANT UNDERSTANDING:
- LLM not really executed
multiply(2, 3) - It just returns the call information
- Actual execution needs to be handled in subsequent steps
4. Use messages as state (Messages as State)
Why use messages as status?
In a dialogue system we need:
- Save conversation history
- Track multiple rounds of interactions
- Pass contextual information
Using message list as graph state is the most natural way.
Define status
Method 1: Manual definition
from typing_extensions import TypedDict
from langchain_core.messages import AnyMessage
class MessagesState(TypedDict):
messages: list[AnyMessage]Python knowledge points: TypedDict
TypedDict is Python's type annotation tool, used to define the structure of the dictionary:
class MessagesState(TypedDict):
messages: list[AnyMessage]
# ^^^^^^^^^^^^^^^^
# 值的类型:AnyMessage 对象的列表
# 使用
state = {"messages": [HumanMessage(content="Hi")]}Advantages:
- Provide IDE type checking and auto-completion
- Clearly define data structures
- Does not affect runtime performance (only for static analysis)
5. Reducers⭐
Problem: Status Override
By default, new values returned by nodes overwrite old values:
# 初始状态
state = {"messages": [message1, message2]}
# 节点返回
node_output = {"messages": [message3]}
# 结果:message1 和 message2 被丢弃!
new_state = {"messages": [message3]}**This is not what we want! ** We want to append the message, not overwrite it.
Solution: add_messages Reducer
Reducer is a function that specifies how to update the state.
from typing import Annotated
from langgraph.graph.message import add_messages
class MessagesState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
# ^^^^^^^^^ ^^^^^^^^^^^^^
# 基础类型 Reducer 函数Python knowledge points: Annotated
Annotated is a type annotation enhancement tool introduced in Python 3.9+:
from typing import Annotated
Annotated[类型, 元数据1, 元数据2, ...]
# ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
# 基础 额外信息(不影响类型检查)In LangGraph:
messages: Annotated[list[AnyMessage], add_messages]
# ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
# 类型:消息列表 元数据:reducer 函数LangGraph will read this metadata and know that it should use add_messages to update the state.
How add_messages works
from langgraph.graph.message import add_messages
# 初始消息
initial = [
AIMessage(content="Hello! How can I assist you?", name="Model"),
HumanMessage(content="I'm looking for information on marine biology.", name="Lance")
]
# 新消息
new_message = AIMessage(content="Sure, I can help with that.", name="Model")
# 使用 add_messages
result = add_messages(initial, new_message)
# 结果:[message1, message2, message3] ← 追加,不覆盖!Add_messages features:
- Automatically append new messages to the end of the list
- Support single message or message list
- Process message deduplication (based on ID)
- It is LangGraph’s built-in reducer
6. Use MessagesState (recommended method)
Since "message list" is such a common state structure, LangGraph provides the pre-built MessagesState:
from langgraph.graph import MessagesState
class MessagesState(MessagesState):
# 如果需要额外字段,在这里添加
passPre-built MessagesState contains:
messagesfield:list[AnyMessage]- Automatically use
add_messagesreducer - No need to define manually
If additional fields are required:
class ExtendedState(MessagesState):
user_id: str
session_id: str
# messages 字段已经自动包含7. Build the diagram
Now that we have all the components, we can build the graph!
from langgraph.graph import StateGraph, START, END
# 定义节点
def tool_calling_llm(state: MessagesState):
return {"messages": [llm_with_tools.invoke(state["messages"])]}
# 构建图
builder = StateGraph(MessagesState)
builder.add_node("tool_calling_llm", tool_calling_llm)
builder.add_edge(START, "tool_calling_llm")
builder.add_edge("tool_calling_llm", END)
graph = builder.compile()Detailed code explanation
1. Define node function
def tool_calling_llm(state: MessagesState):
# ^^^^^^^^^^^^^^^^^^^^^^
# 输入:当前图状态
result = llm_with_tools.invoke(state["messages"])
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 调用 LLM,传入对话历史
return {"messages": [result]}
# ^^^^^^^^^^^^^^^^^^^^^^^
# 返回新消息(会被 add_messages 追加)2. Create graph
builder = StateGraph(MessagesState)
# ^^^^^^^^^^^^^^
# 指定状态类型3. Add node
builder.add_node("tool_calling_llm", tool_calling_llm)
# ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^
# 节点名称 节点函数4. Add edges
builder.add_edge(START, "tool_calling_llm")
# ^^^^^ ^^^^^^^^^^^^^^^^^^
# 起点 目标节点
builder.add_edge("tool_calling_llm", END)
# ^^^^^^^^^^^^^^^^^^ ^^^
# 源节点 终点LangGraph knowledge points: START and END
START: special node, representing the entrance of the graphEND: special node, representing the exit of the graph- not a string, but a constant identifier
5. Compile graph
graph = builder.compile()The compiled graph can be executed (invoke, stream, etc.).
Visualization of graphs
from IPython.display import Image, display
display(Image(graph.get_graph().draw_mermaid_png()))Output:
┌─────────┐
│ __start__ │
└─────┬─────┘
│
↓
┌─────────────────┐
│ tool_calling_llm │
└─────────┬─────────┘
│
↓
┌─────────┐
│ __end__ │
└─────────┘8. Execution diagram
Scene 1: Normal conversation
messages = graph.invoke({"messages": HumanMessage(content="Hello!")})
for m in messages['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Hello!
================================== Ai Message ==================================
Hi there! How can I assist you today?Analysis:
- No tools are required for input, LLM will reply directly
- No tool call information
Scenario 2: Tool call
messages = graph.invoke({"messages": HumanMessage(content="Multiply 2 and 3")})
for m in messages['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Multiply 2 and 3
================================== Ai Message ==================================
Tool Calls:
multiply (call_Er4gChFoSGzU7lsuaGzfSGTQ)
Call ID: call_Er4gChFoSGzU7lsuaGzfSGTQ
Args:
a: 2
b: 3Analysis:
- LLM identifies the need to use the
multiplytool - Return tool call information, but not yet executed
- Parameter
a=2, b=3extracted from natural language
🎓 Summary of core knowledge points
LangGraph/LangChain unique concepts
1. Message system
| Message type | Purpose | Example |
|---|---|---|
HumanMessage | User input | HumanMessage(content="Hi") |
AIMessage | Model output | AIMessage(content="Hello!") |
SystemMessage | System command | SystemMessage(content="You are helpful") |
ToolMessage | Tool results | ToolMessage(content="6", tool_call_id="...") |
2. Tool binding
# 定义工具(普通 Python 函数)
def multiply(a: int, b: int) -> int:
"""Multiply two numbers"""
return a * b
# 绑定到模型
llm_with_tools = llm.bind_tools([multiply])Key Points:
- Function signature → Automatically generate tool schema
- Docstrings → Help models understand their purpose
- Type annotations → define parameter and return value types
3. Reducers
Function: Control status update method
# 默认行为:覆盖
messages: list[AnyMessage]
# 使用 reducer:追加
messages: Annotated[list[AnyMessage], add_messages]Commonly used reducers:
add_messages: append message (remove duplication)operator.add: list splicing- Custom functions: full control over update logic
4. Graph construction mode
# 1. 创建图
builder = StateGraph(StateClass)
# 2. 添加节点
builder.add_node("node_name", node_function)
# 3. 添加边
builder.add_edge(START, "node_name")
builder.add_edge("node_name", END)
# 4. 编译
graph = builder.compile()
# 5. 执行
result = graph.invoke(initial_state)Python-specific knowledge points
1. TypedDict
Function: Define the structure and type of the dictionary
from typing_extensions import TypedDict
class MyState(TypedDict):
name: str
age: int
# 使用
state: MyState = {"name": "Alice", "age": 30}Features:
- Used only for type checking (static analysis)
- Still a normal dictionary at runtime
- Provide IDE auto-completion
2. Type Hints (type annotations)
def greet(name: str) -> str:
# ^^^^^ ^^^^^
# 参数类型 返回值类型
return f"Hello, {name}"Use:
- Documented code
- IDE support
- static type checking (mypy)
- LangChain tool schema generation
3. Annotated
Function: Add metadata to the type
from typing import Annotated
# 基础类型 + 元数据
Age = Annotated[int, "Must be positive"]
# 在 LangGraph 中
messages: Annotated[list, add_messages]
# ^^^^ ^^^^^^^^^^^^^
# 类型 元数据(reducer)LangGraph usage scenarios:
class State(TypedDict):
# 会被覆盖
count: int
# 会被累加
scores: Annotated[list[int], operator.add]
# 会被追加(去重)
messages: Annotated[list[AnyMessage], add_messages]4. Environment variables
import os
# 设置
os.environ["KEY"] = "value"
# 获取
value = os.environ.get("KEY")
# 安全输入
import getpass
api_key = getpass.getpass("API Key: ")💡 Best Practices
1. Message management
✅ Good practice
# 明确指定消息角色和名称
messages = [
SystemMessage(content="You are a helpful assistant"),
HumanMessage(content="What's the weather?", name="User"),
AIMessage(content="I'll check that for you", name="Assistant")
]❌ Things to avoid
# 不要混用字符串和消息对象
messages = ["Hello", HumanMessage(content="Hi")] # 错误!2. Tool definition
✅ Good practice
def calculate_discount(price: float, discount_percent: float) -> float:
"""Calculate the discounted price.
Args:
price: Original price in dollars
discount_percent: Discount percentage (0-100)
Returns:
Final price after discount
"""
return price * (1 - discount_percent / 100)Features:
- Complete type annotations
- Detailed docstrings
- Clear parameter description
❌ Things to avoid
def calc(p, d): # 无类型注解,无文档
return p * (1 - d / 100)3. State design
✅ Good practice
class ChatState(MessagesState):
user_id: str
session_started_at: str
# messages 自动继承,带 add_messages reducer❌ Things to avoid
# 不要手动管理消息列表
class ChatState(TypedDict):
all_messages: list # 无类型,无 reducer4. Node function
✅ Good practice
def process_message(state: MessagesState) -> dict:
"""Process user message and generate response."""
try:
response = llm.invoke(state["messages"])
return {"messages": [response]}
except Exception as e:
logger.error(f"LLM error: {e}")
return {"messages": [AIMessage(content="Sorry, an error occurred")]}Features:
- Explicit type annotations
- error handling
- Returns the correct status format
❌ Things to avoid
def process(s): # 无类型,无错误处理
return llm.invoke(s["messages"]) # 返回格式错误🚀 Advanced skills
1. Custom Reducer
In addition to add_messages, you can define custom reducers:
def keep_last_n_messages(existing: list, new: list, n: int = 10) -> list:
"""只保留最近 N 条消息"""
combined = existing + new
return combined[-n:]
class State(TypedDict):
messages: Annotated[list, lambda x, y: keep_last_n_messages(x, y, 5)]2. Conditional tool call
def smart_node(state: MessagesState):
response = llm_with_tools.invoke(state["messages"])
if response.tool_calls:
# 有工具调用 → 执行工具
tool_name = response.tool_calls[0]["name"]
tool_args = response.tool_calls[0]["args"]
if tool_name == "multiply":
result = multiply(**tool_args)
return {"messages": [
response,
ToolMessage(content=str(result), tool_call_id=response.tool_calls[0]["id"])
]}
# 无工具调用 → 直接返回
return {"messages": [response]}3. Multi-model support
class ModelState(MessagesState):
current_model: str
def adaptive_node(state: ModelState):
# 根据状态选择不同模型
if state["current_model"] == "fast":
llm = ChatOpenAI(model="gpt-3.5-turbo")
else:
llm = ChatOpenAI(model="gpt-4o")
response = llm.invoke(state["messages"])
return {"messages": [response]}🔍 Frequently Asked Questions
Q1: Why do you need add_messages reducer?
Answer: Because the conversation needs to retain historical records.
# 没有 reducer(错误)
state = {"messages": [msg1, msg2]}
node_output = {"messages": [msg3]}
# 结果:msg1, msg2 丢失!
# 有 add_messages(正确)
state = {"messages": [msg1, msg2]}
node_output = {"messages": [msg3]}
# 结果:[msg1, msg2, msg3] ← 保留历史Q2: What is the difference between invoke() and stream()?
# invoke:等待全部完成,返回最终结果
result = graph.invoke({"messages": [HumanMessage(content="Hi")]})
# stream:流式返回中间结果
for chunk in graph.stream({"messages": [HumanMessage(content="Hi")]}):
print(chunk)Usage scenario:
invoke: When complete results are requiredstream: When real-time feedback is needed (such as chat interface)
Q3: How to execute the tool after calling it?
In this tutorial, LLM only returns tool call information and does not execute it. The complete tool execution process requires:
- Detect
response.tool_calls - Call the actual function
- Return the result as
ToolMessage - Call LLM again to generate the final answer
This will be covered in detail in subsequent tutorials.
Q4: How to choose between TypedDict and Pydantic BaseModel?
| Scenario | Usage |
|---|---|
| Define map status | TypedDict |
| LLM structured output | BaseModel |
| API request/response | BaseModel |
| Data verification required | BaseModel |
| Just type hint | TypedDict |
# 图状态
class State(TypedDict):
messages: list
# 工具输出
class ToolOutput(BaseModel):
result: int
status: str📊 Concept comparison
Chain vs Graph
| Features | Chain | Graph |
|---|---|---|
| Structure | Linear (A→B→C) | Arbitrary (can be looped, branched) |
| Complexity | Simple | Complex |
| Applicable scenarios | Simple process | Complex workflow |
| This tutorial | ✅ | ✅ (simple picture) |
This tutorial uses a simple linear graph (chain), but uses StateGraph to build the foundation for subsequent complex graphs.
Messages vs State
# 仅消息
def node1(messages: list[AnyMessage]) -> list[AnyMessage]:
return llm.invoke(messages)
# 使用状态(推荐)
def node2(state: MessagesState) -> dict:
return {"messages": [llm.invoke(state["messages"])]}Advantages of using status:
- Additional information can be added (user_id, metadata, etc.)
- Unified update mechanism (reducers)
- Better scalability
🎯 Practical application cases
Case 1: Simple customer service robot
from langgraph.graph import StateGraph, MessagesState, START, END
# 工具:查询订单
def check_order(order_id: str) -> str:
"""Check order status"""
return f"Order {order_id} is being processed"
# 节点
def customer_service(state: MessagesState):
llm_with_tools = ChatOpenAI(model="gpt-4o").bind_tools([check_order])
response = llm_with_tools.invoke(state["messages"])
return {"messages": [response]}
# 构建图
builder = StateGraph(MessagesState)
builder.add_node("service", customer_service)
builder.add_edge(START, "service")
builder.add_edge("service", END)
app = builder.compile()
# 使用
result = app.invoke({"messages": [HumanMessage(content="Check order #12345")]})Case 2: Multi-language translation assistant
def translate(text: str, target_language: str) -> str:
"""Translate text to target language"""
# 实际调用翻译 API
return f"[{target_language}] {text}"
def translator_bot(state: MessagesState):
llm_with_tools = ChatOpenAI(model="gpt-4o").bind_tools([translate])
response = llm_with_tools.invoke(state["messages"])
return {"messages": [response]}
# 使用
result = app.invoke({
"messages": [HumanMessage(content="Translate 'Hello' to Spanish")]
})📖 Next step to learn
This tutorial introduces the basic concepts of Chain. Next you will learn:
- Tool Execution: actually execute the tool call and return the results
- Conditional Edges: Dynamic routing based on status
- Cycles: Construct a graph that can interact in multiple rounds
- Memory: Persistent conversation history
🔗 Further reading
- LangChain Messages Documentation
- LangChain Chat Models Documentation
- LangChain Tools Documentation
- LangGraph Reducers Documentation
- Python Type Hints Guide
Summary: This tutorial introduces the four core concepts of building LangGraph Chain: message system, chat model, tool binding and state management. These are the foundations for building complex AI systems, and once you master these concepts, you can start building more powerful LangGraph applications!