Skip to content

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:

  1. Input processing: receiving user messages
  2. Model Call: Use LLM to generate responses
  3. Tool Execution (optional): Call external tools/functions
  4. Output Return: Return the final result

The four core concepts of this tutorial ​

  1. Messages: Use chat messages as graph state
  2. Chat Models: Using LLM in graph nodes
  3. Tool Binding: Bind tools to the chat model
  4. 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 TypeRolePurpose
HumanMessageUserRepresents user input
AIMessageAI modelRepresents model response
SystemMessageSystemGuide model behavior
ToolMessageToolsResult of tool call

Components of the message ​

Each message can contain:

  • content (required): message content
  • name (optional): the name of the message sender
  • response_metadata (optional): metadata dictionary (such as model response information)

Code Example ​

python
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

python
for m in messages:
    m.pretty_print()
  • for m in messages: Iterate over each element in the messages list
  • m.pretty_print(): Call the pretty_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 ​

python
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 variables
  • getpass.getpass(): Enter password securely (typing will not be displayed)
  • This is the best practice for protecting API Keys

Using chat model ​

python
from langchain_openai import ChatOpenAI

# 初始化模型
llm = ChatOpenAI(model="gpt-4o")

# 调用模型
result = llm.invoke(messages)

Output type:

python
type(result)
# langchain_core.messages.ai.AIMessage

result is a AIMessage object containing:

python
result.content  # AI 生成的文本内容
result.response_metadata  # 响应元数据

Detailed explanation of response metadata ​

python
result.response_metadata

Output example:

python
{
    '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!

python
def multiply(a: int, b: int) -> int:
    """Multiply a and b.

    Args:
        a: first int
        b: second int
    """
    return a * b

Key Takeaways:

  1. Type annotation: a: int, b: int -> int lets the model know the parameter type
  2. Documentation string: Describes the function of the function and helps the model understand when to use it.

Python knowledge points: Type Hints

python
def multiply(a: int, b: int) -> int:
    #          ^^^^^^  ^^^^^^    ^^^
    #          参数a   参数b     返回值
    #          是int   是int     是int
    return a * b

The 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 ​

python
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 multiply tool

Tool call example ​

python
tool_call = llm_with_tools.invoke([
    HumanMessage(content="What is 2 multiplied by 3", name="Lance")
])

tool_call.tool_calls

Output:

python
[{
    '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

python
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:

python
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:

python
# 初始状态
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.

python
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+:

python
from typing import Annotated

Annotated[类型, 元数据1, 元数据2, ...]
#         ^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^
#         基础  额外信息(不影响类型检查)

In LangGraph:

python
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 ​

python
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:

  1. Automatically append new messages to the end of the list
  2. Support single message or message list
  3. Process message deduplication (based on ID)
  4. It is LangGraph’s built-in reducer

Since "message list" is such a common state structure, LangGraph provides the pre-built MessagesState:

python
from langgraph.graph import MessagesState

class MessagesState(MessagesState):
    # 如果需要额外字段,在这里添加
    pass

Pre-built MessagesState contains:

  • messages field: list[AnyMessage]
  • Automatically use add_messages reducer
  • No need to define manually

If additional fields are required:

python
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!

python
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

python
def tool_calling_llm(state: MessagesState):
    #                  ^^^^^^^^^^^^^^^^^^^^^^
    #                  输入:当前图状态

    result = llm_with_tools.invoke(state["messages"])
    #        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    #        调用 LLM,传入对话历史

    return {"messages": [result]}
    #      ^^^^^^^^^^^^^^^^^^^^^^^
    #      返回新消息(会被 add_messages 追加)

2. Create graph

python
builder = StateGraph(MessagesState)
#                    ^^^^^^^^^^^^^^
#                    指定状态类型

3. Add node

python
builder.add_node("tool_calling_llm", tool_calling_llm)
#                ^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^
#                节点名称            节点函数

4. Add edges

python
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 graph
  • END: special node, representing the exit of the graph
  • not a string, but a constant identifier

5. Compile graph

python
graph = builder.compile()

The compiled graph can be executed (invoke, stream, etc.).

Visualization of graphs ​

python
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 ​

python
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 ​

python
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: 3

Analysis:

  • LLM identifies the need to use the multiply tool
  • Return tool call information, but not yet executed
  • Parameter a=2, b=3 extracted from natural language

🎓 Summary of core knowledge points ​

LangGraph/LangChain unique concepts ​

1. Message system ​

Message typePurposeExample
HumanMessageUser inputHumanMessage(content="Hi")
AIMessageModel outputAIMessage(content="Hello!")
SystemMessageSystem commandSystemMessage(content="You are helpful")
ToolMessageTool resultsToolMessage(content="6", tool_call_id="...")

2. Tool binding ​

python
# 定义工具(普通 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

python
# 默认行为:覆盖
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 ​

python
# 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

python
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) ​

python
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

python
from typing import Annotated

# 基础类型 + 元数据
Age = Annotated[int, "Must be positive"]

# 在 LangGraph 中
messages: Annotated[list, add_messages]
#                   ^^^^  ^^^^^^^^^^^^^
#                   类型  元数据(reducer)

LangGraph usage scenarios:

python
class State(TypedDict):
    # 会被覆盖
    count: int

    # 会被累加
    scores: Annotated[list[int], operator.add]

    # 会被追加(去重)
    messages: Annotated[list[AnyMessage], add_messages]

4. Environment variables ​

python
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 ​

python
# 明确指定消息角色和名称
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 ​

python
# 不要混用字符串和消息对象
messages = ["Hello", HumanMessage(content="Hi")]  # 错误!

2. Tool definition ​

✅ Good practice ​

python
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 ​

python
def calc(p, d):  # 无类型注解,无文档
    return p * (1 - d / 100)

3. State design ​

✅ Good practice ​

python
class ChatState(MessagesState):
    user_id: str
    session_started_at: str
    # messages 自动继承,带 add_messages reducer

❌ Things to avoid ​

python
# 不要手动管理消息列表
class ChatState(TypedDict):
    all_messages: list  # 无类型,无 reducer

4. Node function ​

✅ Good practice ​

python
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 ​

python
def process(s):  # 无类型,无错误处理
    return llm.invoke(s["messages"])  # 返回格式错误

🚀 Advanced skills ​

1. Custom Reducer ​

In addition to add_messages, you can define custom reducers:

python
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 ​

python
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 ​

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

python
# 没有 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()? ​

python
# 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 required
  • stream: 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:

  1. Detect response.tool_calls
  2. Call the actual function
  3. Return the result as ToolMessage
  4. 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? ​

ScenarioUsage
Define map statusTypedDict
LLM structured outputBaseModel
API request/responseBaseModel
Data verification requiredBaseModel
Just type hintTypedDict
python
# 图状态
class State(TypedDict):
    messages: list

# 工具输出
class ToolOutput(BaseModel):
    result: int
    status: str

📊 Concept comparison ​

Chain vs Graph ​

FeaturesChainGraph
StructureLinear (A→B→C)Arbitrary (can be looped, branched)
ComplexitySimpleComplex
Applicable scenariosSimple processComplex 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 ​

python
# 仅消息
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 ​

python
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 ​

python
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:

  1. Tool Execution: actually execute the tool call and return the results
  2. Conditional Edges: Dynamic routing based on status
  3. Cycles: Construct a graph that can interact in multiple rounds
  4. Memory: Persistent conversation history

🔗 Further reading ​


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!

English translation of community learning materials. MIT licensed.