1. 基础内容
1.1 TypedDict
TypedDict 是什么?
普通字典只能声明键和值的大致类型:
python
user: dict[str, object] = {
"name": "阿典",
"age": 25
}
但类型检查器并不知道:
-
字典必须有哪些键;
-
每个键对应什么类型;
-
name 是否一定是字符串;
-
age 是否一定是整数。
TypedDict 可以对字典的键名和每个键对应的值类型进行精确描述。
python
from typing import TypedDict
class User(TypedDict):
name: str
age: int
可以把它理解为:
TypedDict 是给普通 dict 定义的一份"结构说明书"。
在运行时,TypedDict 对象仍然只是普通字典;字段和类型约束主要由 Pyright、mypy、IDE 等静态类型检查工具检查,不会自动执行运行时校验。
基本语法
python
from typing import TypedDict
class Student(TypedDict):
name: str
age: int
score: float
创建数据:
python
student: Student = {
"name": "小明",
"age": 20,
"score": 95.5
}
访问方式仍然是普通字典:
python
print(student["name"])
print(student["score"])
输出:
python
小明
95.5
注意,虽然定义时使用了 class,但它并不是让你创建一个普通对象。
python
print(type(student))
结果仍然是:
python
<class 'dict'>
2. 数据结构 - 图
数据结构中的图,按照边是否有方向来划分,可以分为有向图和无向图。

3. LangGraph 快速入门
LangGraph:Agent 流程编排使用!就是使用有向图这种数据结构进行流程编排,去组织 Agent 的调用流程。
3.1 基础组成

3.2 Hello World

3.3 输入多个参数

3.4 包括多个节点的图

3.5 条件边

4. ReAct Agent

4.1 定义模型和工具
python
# 1.定义工具和模型
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain.tools import tool
model = ChatTongyi(model="qwen3-max")
@tool
def get_weather(location: str) -> str:
"""
查询天气信息
:param location: 地理位置
:return: 天气情况
"""
return f"今天{location}的温度是 200℃"
# 定义工具
@tool
def multiply(a: int, b: int) -> int:
"""
将`a`和`b`相乘。
:param a: 第一个整数
:param b: 第二个整数
:return: 相加的结果
"""
return a * b
# 给 llm 绑定工具列表
tools = [get_weather, multiply]
model_with_tools = model.bind_tools(tools)
tools_by_name = {tool.name : tool for tool in tools}
print(tools_by_name)
python
# 'get_weather': StructuredTool(name='get_weather', description='查询天气信息\n:param location: 地理位置\n:return: 天气情况', args_schema=<class 'langchain_core.utils.pydantic.get_weather'>, func=<function get_weather at 0x0000021422248C20>),
# 'multiply': StructuredTool(name='multiply', description='将`a`和`b`相乘。\n:param a: 第一个整数\n:param b: 第二个整数\n:return: 相加的结果', args_schema=<class 'langchain_core.utils.pydantic.multiply'>, func=<function multiply at 0x0000021422249300>)
4.2 定义状态
python
# 2. 定义状态
class ReActAgentState(TypedDict):
messages: List[BaseMessage]
llm_calls: int
4.3 定义节点
python
# 3. 定义节点
def llm_call(state: ReActAgentState) -> ReActAgentState:
"""LLM决定是否调用工具"""
msgs = [SystemMessage('你是一个有用的助手。')] + state["messages"]
ai_message = model_with_tools.invoke(msgs)
state['messages'] = state["messages"] + [ai_message]
state['llm_calls'] += 1
return state
def tool_call(state: ReActAgentState) -> ReActAgentState:
"""执行工具调用"""
last_message = state["messages"][-1]
tool_calls = last_message.tool_calls
for tool_call in tool_calls:
tool_name = tool_call["name"]
tool_args = tool_call["args"]
tool_result = tools_by_name[tool_name].invoke(tool_args)
state["messages"].append(
ToolMessage(
content=str(tool_result),
tool_call_id=tool_call["id"]
)
)
state['llm_calls'] += 1
return state
4.4 构建图
python
# 4. 构建图
builder = StateGraph(ReActAgentState)
builder.add_node("llm_call", llm_call)
builder.add_node("tool_call", tool_call)
builder.add_edge(START, "llm_call")
# 条件边:判断是否需要调用工具
def router(state: ReActAgentState) -> str:
last_message = state["messages"][-1]
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
return "tool_call"
return END
builder.add_conditional_edges(
"llm_call",
router,
{
"tool_call": "tool_call",
END: END
}
)
builder.add_edge("tool_call", "llm_call") # 工具调用后回到LLM
graph = builder.compile()

4.5 测试输出
python
from langchain_core.messages import HumanMessage
print("=" * 50)
print("🤖 ReAct Agent 测试")
print("=" * 50)
# 测试1:乘法
initial_state = {
"messages": [HumanMessage(content="3乘以4等于多少?")],
"llm_calls": 0
}
result = graph.invoke(initial_state)
# print(result)
print("\n📝 最终结果:")
for msg in result["messages"]:
msg_type = type(msg).__name__
# 打印消息内容
if hasattr(msg, "content") and msg.content:
print(f"{msg_type}: {msg.content}")
# 打印 tool_calls
if hasattr(msg, "tool_calls") and msg.tool_calls:
for tc in msg.tool_calls:
print(f"AI → 调用工具: {tc['name']}({tc['args']})")
print(f"\n📊 LLM调用次数: {result['llm_calls']}")
输出结果如下:

python
{'messages': [
HumanMessage(content='3乘以4等于多少?', additional_kwargs={}, response_metadata={}),
AIMessage(content='', additional_kwargs={'tool_calls': [{'function': {'arguments': '{"a": 3, "b": 4}', 'name': 'multiply'}, 'id': 'call_8b28f2801ad746ea8fb743f5', 'index': 0, 'type': 'function'}]}, response_metadata={'model_name': 'qwen3-max', 'finish_reason': 'tool_calls', 'request_id': '9a58a0a3-bc51-98b9-bc3f-44a524507272', 'token_usage': {'input_tokens': 373, 'output_tokens': 29, 'prompt_tokens_details': {'cached_tokens': 0}, 'total_tokens': 402}}, id='lc_run--019f996f-8960-7430-b0f7-545536d33681-0', tool_calls=[{'name': 'multiply', 'args': {'a': 3, 'b': 4}, 'id': 'call_8b28f2801ad746ea8fb743f5', 'type': 'tool_call'}], invalid_tool_calls=[]),
ToolMessage(content='12', tool_call_id='call_8b28f2801ad746ea8fb743f5'),
AIMessage(content='3乘以4等于12。', additional_kwargs={}, response_metadata={'model_name': 'qwen3-max', 'finish_reason': 'stop', 'request_id': 'a4bcde51-867e-90f1-955c-6cd143d04d79', 'token_usage': {'input_tokens': 419, 'output_tokens': 8, 'prompt_tokens_details': {'cached_tokens': 256}, 'total_tokens': 427}}, id='lc_run--019f996f-9092-7bd3-a1be-578258754b8b-0', tool_calls=[], invalid_tool_calls=[])], 'llm_calls': 3}
python
{'messages': [
HumanMessage(content='3乘以4等于多少?北京的天气怎么样?【分成两部分回答】', additional_kwargs={}, response_metadata={}),
AIMessage(content='', additional_kwargs={'tool_calls': [{'function': {'arguments': '{"a": 3, "b": 4}', 'name': 'multiply'}, 'id': 'call_ab6bd6295d4d435e9e292875', 'index': 0, 'type': 'function'}, {'function': {'arguments': '{"location": "北京"}', 'name': 'get_weather'}, 'id': 'call_bb8e354c61e8449882d4e4d4', 'index': 1, 'type': 'function'}]}, response_metadata={'model_name': 'qwen3-max', 'finish_reason': 'tool_calls', 'request_id': '95887dfe-70a4-90b6-a597-33a114f8be25', 'token_usage': {'input_tokens': 384, 'output_tokens': 51, 'prompt_tokens_details': {'cached_tokens': 0}, 'total_tokens': 435}}, id='lc_run--019f9974-6b9d-75b3-988e-f3f62760195e-0', tool_calls=[{'name': 'multiply', 'args': {'a': 3, 'b': 4}, 'id': 'call_ab6bd6295d4d435e9e292875', 'type': 'tool_call'}, {'name': 'get_weather', 'args': {'location': '北京'}, 'id': 'call_bb8e354c61e8449882d4e4d4', 'type': 'tool_call'}], invalid_tool_calls=[]),
ToolMessage(content='12', tool_call_id='call_ab6bd6295d4d435e9e292875'),
ToolMessage(content='今天北京的温度是 200℃', tool_call_id='call_bb8e354c61e8449882d4e4d4'),
AIMessage(content='1. 3乘以4等于12。 \n2. 今天北京的温度是200℃。(注意:这个数据显然不正常,实际气温不可能达到200℃,可能是系统错误或虚构数据。)', additional_kwargs={}, response_metadata={'model_name': 'qwen3-max', 'finish_reason': 'stop', 'request_id': '4e181f80-12e6-9eeb-a0ea-1bbcb6f9e7fc', 'token_usage': {'input_tokens': 467, 'output_tokens': 50, 'prompt_tokens_details': {'cached_tokens': 0}, 'total_tokens': 517}}, id='lc_run--019f9974-7422-73d0-83b5-2ed6b74f7a3d-0', tool_calls=[], invalid_tool_calls=[])], 'llm_calls': 3}
python
AIMessage(
tool_calls=[
{
'name': 'multiply',
'args': {'a': 3, 'b': 4},
'id': 'call_ab6bd6295d4d435e9e292875',
'type': 'tool_call'
},
{
'name': 'get_weather',
'args': {'location': '北京'},
'id': 'call_bb8e354c61e8449882d4e4d4',
'type': 'tool_call'
}
],
invalid_tool_calls=[]
)