AI Agent 开发实战教程(一):概述与环境搭建
传统的 LLM 对话是这样的:fill:#333;important;important;fill:none;color:#333;color:#333;important;fill:none;fill:#333;height:1em;用户提问LLM 生成回答结束而 AI Agent 是这样的:fill:#333;important;important;fill:none;color:#333;c
·
目录
- 1. 什么是 AI Agent
- 2. Agent 的核心架构
- 3. LangChain 生态系统概览
- 4. 开发环境搭建
- 5. 多模型适配:LangChain Chat Models
- 6. 第一个 Chain:从零到一
- 7. 小结与下一步
1. 什么是 AI Agent
1.1 从 Chat 到 Agent
传统的 LLM 对话是这样的:
而 AI Agent 是这样的:
核心区别:Agent 不只是"回答问题",而是"解决问题"。它能够:
- 感知:理解用户的真实意图
- 规划:将复杂任务拆解为可执行的步骤
- 行动:调用外部工具(搜索、数据库、API 等)
- 记忆:记住上下文和历史交互
- 反思:根据执行结果调整策略
1.2 Agent 的应用场景
| 场景 | 说明 | 典型案例 |
|---|---|---|
| 智能客服 | 自动处理用户咨询,查询订单、退款等 | 电商售后机器人 |
| 数据分析 | 自然语言查询数据库,生成报表 | 数据分析助手 |
| 代码开发 | 理解需求、编写代码、运行测试 | AI 编程助手 |
| 内容创作 | 搜索资料、整理大纲、生成文章 | 自动写稿系统 |
| 知识问答 | 基于企业知识库回答专业问题 | 企业知识库助手 |
2. Agent 的核心架构
2.1 四大核心组件
组件详解:
| 组件 | 作用 | LangChain 对应 |
|---|---|---|
| LLM(大模型) | 理解指令、推理决策、生成内容 | langchain-openai, langchain-community |
| 规划引擎(Planner) | 拆解任务、制定执行步骤 | LangChain Chain, Agent |
| 记忆系统(Memory) | 存储对话历史、知识、经验 | langchain.memory |
| 工具集(Tools) | 与外部世界交互的能力 | langchain.tools |
2.2 Agent 的工作循环:ReAct 模式
目前最主流的 Agent 工作模式是 ReAct(Reasoning + Acting):
2.3 记忆的类型
| 类型 | 说明 | LangChain 组件 | 持久性 |
|---|---|---|---|
| 短期记忆 | 当前对话的上下文 | ConversationBufferMemory |
会话结束即消失 |
| 长期记忆 | 跨会话的用户偏好、历史摘要 | VectorStoreRetrieverMemory |
永久存储 |
| 工作记忆 | 任务执行过程中的中间状态 | Chain 状态变量 | 任务结束即消失 |
3. LangChain 生态系统概览
3.1 LangChain 架构图
3.2 核心包说明
| 包名 | 说明 | 安装命令 |
|---|---|---|
langchain-core |
核心抽象(BaseMessage, Chain 等) | pip install langchain-core |
langchain |
链、Agent、Memory 等 | pip install langchain |
langchain-openai |
OpenAI 模型集成 | pip install langchain-openai |
langchain-community |
第三方集成(向量库、工具等) | pip install langchain-community |
langchain-text-splitters |
文本分割器 | pip install langchain-text-splitters |
3.3 LangChain vs 原生开发对比
4. 开发环境搭建
4.1 基础环境
# 1. 创建项目目录
mkdir langchain-agent-tutorial && cd langchain-agent-tutorial
# 2. 创建虚拟环境(推荐 Python 3.10+)
python -m venv venv
# 3. 激活虚拟环境
# macOS / Linux:
source venv/bin/activate
# Windows:
# venv\Scripts\activate
# 4. 升级 pip
pip install --upgrade pip
4.2 安装 LangChain 核心依赖
# LangChain 核心
pip install langchain langchain-core
# 模型集成
pip install langchain-openai # OpenAI 兼容接口(支持国产模型)
pip install langchain-community # 社区集成
# 文本处理
pip install langchain-text-splitters
# 向量数据库
pip install langchain-chroma # ChromaDB 集成
# 工具依赖
pip install python-dotenv # 环境变量管理
pip install pydantic # 数据验证
4.3 项目结构
langchain-agent-tutorial/
├── .env # API 密钥(不要提交到 Git!)
├── .gitignore # Git 忽略文件
├── requirements.txt # 依赖清单
├── config.py # 配置管理
├── chains/ # Chain 实现
│ ├── __init__.py
│ └── basic_chain.py # 基础 Chain
├── agents/ # Agent 实现
│ ├── __init__.py
│ └── react_agent.py # ReAct Agent
├── tools/ # 工具函数
│ └── __init__.py
├── memory/ # 记忆系统
│ └── __init__.py
└── rag/ # RAG 管道
└── __init__.py
4.4 配置 API 密钥
创建 .env 文件:
# ===== 国产模型 =====
# DeepSeek(推荐入门,性价比最高)
DEEPSEEK_API_KEY=sk-your-deepseek-key
# Kimi(月之暗面)
MOONSHOT_API_KEY=sk-your-kimi-key
# 豆包(字节跳动/火山引擎)
ARK_API_KEY=your-ark-api-key
# 智谱 GLM
ZHIPUAI_API_KEY=your-glm-api-key
# ===== 海外模型 =====
OPENAI_API_KEY=sk-your-openai-key
# ===== 默认使用的模型提供商 =====
DEFAULT_LLM_PROVIDER=deepseek
5. 多模型适配:LangChain Chat Models
5.1 LangChain 统一模型接口
LangChain 提供了统一的 BaseChatModel 接口,所有模型都遵循相同的调用方式:
5.2 各模型配置一览
| 提供商 | Base URL | LangChain 类 | 模型示例 |
|---|---|---|---|
| OpenAI | https://api.openai.com/v1 |
ChatOpenAI |
gpt-4o |
| DeepSeek | https://api.deepseek.com |
ChatOpenAI (兼容) |
deepseek-chat |
| Kimi | https://api.moonshot.cn/v1 |
ChatOpenAI (兼容) |
moonshot-v1-8k |
| 豆包 | https://ark.cn-beijing.volces.com/api/v3 |
ChatOpenAI (兼容) |
doubao-seed-1-6-250615 |
| 智谱 GLM | https://open.bigmodel.cn/api/paas/v4 |
ChatOpenAI (兼容) |
glm-4-flash |
5.3 统一模型工厂
"""
models.py - 统一模型工厂
使用 LangChain ChatOpenAI 兼容接口适配所有模型
"""
import os
from typing import Optional
from langchain_openai import ChatOpenAI
from langchain_core.language_models import BaseChatModel
from dotenv import load_dotenv
load_dotenv()
# 模型配置注册表
MODEL_CONFIGS = {
"openai": {
"base_url": "https://api.openai.com/v1",
"api_key_env": "OPENAI_API_KEY",
"default_model": "gpt-4o",
},
"deepseek": {
"base_url": "https://api.deepseek.com",
"api_key_env": "DEEPSEEK_API_KEY",
"default_model": "deepseek-chat",
},
"kimi": {
"base_url": "https://api.moonshot.cn/v1",
"api_key_env": "MOONSHOT_API_KEY",
"default_model": "moonshot-v1-8k",
},
"doubao": {
"base_url": "https://ark.cn-beijing.volces.com/api/v3",
"api_key_env": "ARK_API_KEY",
"default_model": "doubao-seed-1-6-250615",
},
"zhipu": {
"base_url": "https://open.bigmodel.cn/api/paas/v4",
"api_key_env": "ZHIPUAI_API_KEY",
"default_model": "glm-4-flash",
},
}
def get_chat_model(
provider: Optional[str] = None,
model: Optional[str] = None,
temperature: float = 0.7,
**kwargs,
) -> BaseChatModel:
"""
获取 ChatModel 实例
Args:
provider: 模型提供商(openai/deepseek/kimi/doubao/zhipu)
model: 模型名称
temperature: 温度参数
**kwargs: 其他参数传递给 ChatOpenAI
Returns:
LangChain ChatModel 实例
示例:
# 使用 DeepSeek
llm = get_chat_model("deepseek")
# 使用 Kimi
llm = get_chat_model("kimi", temperature=0.3)
# 使用 OpenAI
llm = get_chat_model("openai", model="gpt-4o-mini")
"""
provider = provider or os.getenv("DEFAULT_LLM_PROVIDER", "deepseek")
if provider not in MODEL_CONFIGS:
raise ValueError(
f"不支持的提供商: '{provider}',可选: {list(MODEL_CONFIGS.keys())}"
)
config = MODEL_CONFIGS[provider]
api_key = os.getenv(config["api_key_env"])
if not api_key:
raise ValueError(
f"请设置 API Key:环境变量 {config['api_key_env']}"
)
return ChatOpenAI(
model=model or config["default_model"],
base_url=config["base_url"],
api_key=api_key,
temperature=temperature,
**kwargs,
)
# === 使用示例 ===
if __name__ == "__main__":
# 测试 DeepSeek
print("=== 测试 DeepSeek ===")
llm = get_chat_model("deepseek")
response = llm.invoke("用一句话介绍你自己")
print(f"回复: {response.content}")
# 测试 Kimi
print("\n=== 测试 Kimi ===")
llm = get_chat_model("kimi", temperature=0.3)
response = llm.invoke("你好")
print(f"回复: {response.content}")
# 测试智谱 GLM
print("\n=== 测试智谱 GLM ===")
llm = get_chat_model("zhipu")
response = llm.invoke("什么是RAG?")
print(f"回复: {response.content}")
5.4 流式输出
"""
stream_example.py - LangChain 流式输出示例
"""
from models import get_chat_model
llm = get_chat_model("deepseek", temperature=0.7)
# 方式一:使用 stream 方法
print("=== 流式输出 ===")
for chunk in llm.stream("讲一个简短的笑话"):
print(chunk.content, end="", flush=True)
print("\n")
# 方式二:使用 astream 异步流式
import asyncio
async def async_stream():
print("=== 异步流式输出 ===")
async for chunk in llm.astream("用50字介绍Python"):
print(chunk.content, end="", flush=True)
print("\n")
asyncio.run(async_stream())
6. 第一个 Chain:从零到一
6.1 什么是 Chain
Chain 是 LangChain 的核心概念,它将多个组件串联起来形成一个处理管道:
6.2 使用 LCEL(LangChain Expression Language)
LangChain 使用 LCEL 声明式语法来构建 Chain:
"""
chains/basic_chain.py - 基础 Chain 示例
使用 LCEL(LangChain Expression Language)构建处理管道
"""
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from models import get_chat_model
# ========================
# 示例 1:最简单的 Chain
# ========================
def simple_chain():
"""最简单的 Chain:Prompt → Model → Output"""
# 1. 定义 Prompt 模板
prompt = ChatPromptTemplate.from_template("给我讲一个关于{topic}的笑话")
# 2. 获取模型
model = get_chat_model("deepseek", temperature=0.7)
# 3. 定义输出解析器
output_parser = StrOutputParser()
# 4. 使用 LCEL 语法构建 Chain(使用 | 操作符)
chain = prompt | model | output_parser
# 5. 调用 Chain
result = chain.invoke({"topic": "程序员"})
print(f"笑话: {result}")
return chain
# ========================
# 示例 2:带系统提示的 Chain
# ========================
def chain_with_system_prompt():
"""带系统提示的 Chain"""
# 使用 from_messages 定义多角色 Prompt
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个专业的{role},请用专业但易懂的语言回答问题。"),
("human", "{question}"),
])
model = get_chat_model("deepseek", temperature=0.3)
output_parser = StrOutputParser()
chain = prompt | model | output_parser
# 调用
result = chain.invoke({
"role": "Python 工程师",
"question": "什么是装饰器?请举例说明。",
})
print(f"回答: {result}")
return chain
# ========================
# 示例 3:带对话历史的 Chain
# ========================
from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.prompts import MessagesPlaceholder
def chain_with_history():
"""带对话历史的 Chain"""
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个有帮助的AI助手。"),
MessagesPlaceholder(variable_name="history"), # 对话历史占位符
("human", "{input}"),
])
model = get_chat_model("deepseek")
output_parser = StrOutputParser()
chain = prompt | model | output_parser
# 模拟对话历史
history = [
HumanMessage(content="我叫张三"),
AIMessage(content="你好张三!很高兴认识你。"),
]
# 调用
result = chain.invoke({
"history": history,
"input": "我叫什么名字?",
})
print(f"回答: {result}")
return chain
# ========================
# 示例 4:链式调用(多个 Chain 串联)
# ========================
def chained_pipelines():
"""多个 Chain 串联:先生成大纲,再展开内容"""
# Chain 1: 生成大纲
outline_prompt = ChatPromptTemplate.from_template(
"为以下主题生成一个文章大纲:{topic}"
)
model = get_chat_model("deepseek", temperature=0.5)
outline_chain = outline_prompt | model | StrOutputParser()
# Chain 2: 根据大纲展开内容
content_prompt = ChatPromptTemplate.from_template(
"""根据以下大纲,写一篇完整的文章(约500字):
大纲:
{outline}
请开始写作:"""
)
content_chain = content_prompt | model | StrOutputParser()
# 组合两个 Chain
# 第一个 Chain 的输出作为第二个 Chain 的输入
from langchain_core.runnables import RunnablePassthrough
full_chain = (
{"outline": outline_chain, "topic": RunnablePassthrough()}
| content_prompt
| model
| StrOutputParser()
)
# 或者使用更简洁的方式
# 先生成大纲,再生成内容
topic = "AI Agent 的发展趋势"
outline = outline_chain.invoke({"topic": topic})
print(f"=== 大纲 ===\n{outline}\n")
content = content_chain.invoke({"outline": outline})
print(f"=== 文章 ===\n{content}")
return outline_chain, content_chain
# === 运行示例 ===
if __name__ == "__main__":
print("=" * 60)
print("示例 1:最简单的 Chain")
print("=" * 60)
simple_chain()
print("\n" + "=" * 60)
print("示例 2:带系统提示的 Chain")
print("=" * 60)
chain_with_system_prompt()
print("\n" + "=" * 60)
print("示例 3:带对话历史的 Chain")
print("=" * 60)
chain_with_history()
print("\n" + "=" * 60)
print("示例 4:链式调用")
print("=" * 60)
chained_pipelines()
6.3 LCEL 核心概念
LCEL 关键特性:
| 特性 | 说明 | 示例 |
|---|---|---|
| 管道操作符 | 使用 | 连接组件 |
prompt | model | parser |
| 统一接口 | 所有组件都实现 Runnable |
chain.invoke(), chain.stream() |
| 自动类型转换 | 自动处理输入输出类型 | dict → Prompt → Message → str |
| 流式支持 | 所有 Chain 都支持流式 | for chunk in chain.stream(): |
| 异步支持 | 所有 Chain 都支持异步 | await chain.ainvoke() |
6.4 Chain 的调用方式
"""
chain_invocation.py - Chain 的多种调用方式
"""
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from models import get_chat_model
# 构建 Chain
prompt = ChatPromptTemplate.from_template("告诉我关于{topic}的三个有趣事实")
model = get_chat_model("deepseek")
parser = StrOutputParser()
chain = prompt | model | parser
# 1. 同步调用
print("=== 同步调用 ===")
result = chain.invoke({"topic": "Python"})
print(result)
# 2. 流式调用
print("\n=== 流式调用 ===")
for chunk in chain.stream({"topic": "AI"}):
print(chunk, end="", flush=True)
print()
# 3. 批量调用
print("\n=== 批量调用 ===")
results = chain.batch([
{"topic": "Python"},
{"topic": "JavaScript"},
{"topic": "Go"},
])
for i, r in enumerate(results, 1):
print(f"\n--- {i} ---")
print(r[:100] + "...")
# 4. 异步调用
import asyncio
async def async_invoke():
print("\n=== 异步调用 ===")
result = await chain.ainvoke({"topic": "Rust"})
print(result[:100] + "...")
asyncio.run(async_invoke())
7. 小结与下一步
7.1 本篇回顾
| 知识点 | 掌握程度 |
|---|---|
| AI Agent 的概念和核心架构 | ✅ |
| ReAct 工作模式 | ✅ |
| LangChain 生态系统概览 | ✅ |
| 开发环境搭建 | ✅ |
| LangChain Chat Models 多模型适配 | ✅ |
| LCEL 语法构建 Chain | ✅ |
7.2 关键收获
- Agent = LLM + 工具 + 记忆 + 规划,LangChain 提供了完整的组件支持
- LCEL 语法让构建 Chain 变得简洁优雅,使用
|操作符串联组件 - ChatOpenAI 兼容接口可以适配所有国产模型和海外模型
7.3 下一篇预告
第二篇:Prompt 工程与工具调用 将深入讲解:
- LangChain PromptTemplate 高级用法
- LangChain Tools 定义和工具调用
- LangChain Agent 构建(ReAct Agent)
- 使用 LangChain 构建完整的工具调用流程
更多推荐




所有评论(0)