Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LangChain 完整教程

一个按章节组织的 LangChain 生态系统 (v1.x) 全面教程。每章包含:

  • 可运行的 Python 代码 — 每个概念都有对应的演示函数
  • 详细的 Markdown 文档 — 含架构图、对比表、最佳实践

前置要求

  • Python 3.11+
  • uv — 极速 Python 包管理器
  • DeepSeek API 密钥(或兼容端点
  • Git — 版本管理

免费/低成本替代方案:

  • DeepSeek本教程默认,¥1/1M tokens,极低费用
  • Ollama — 本地运行 Llama 3.2、Mistral 等模型(完全免费)

快速开始

# 1. 克隆仓库
git clone <this-repo> langchain-tutorial
cd langchain-tutorial

# 2. 配置环境变量
cp .env.example .env
# 编辑 .env,填入你的 OPENAI_API_KEY

# 3. 安装依赖(uv 自动创建虚拟环境)
uv sync

# 4. 运行第一章
uv run python chapters/chapter_01_intro/chapter_01_intro.py

# 5. 按顺序学习每一章
uv run python chapters/chapter_02_llms/chapter_02_llms.py
uv run python chapters/chapter_03_prompts/chapter_03_prompts.py
# ... 依次到 chapter_12_production

环境配置

本教程使用 python-dotenv.env 文件加载 API 密钥:

# 必需 — 你的 DeepSeek API 密钥
# 在 https://platform.deepseek.com/api_keys 获取
DEEPSEEK_API_KEY=sk-your-deepseek-key-here

# 可选 — DeepSeek 模型选择
# DEEPSEEK_MODEL=deepseek-chat       # DeepSeek-V3(默认)
# DEEPSEEK_MODEL=deepseek-reasoner   # DeepSeek-R1(推理增强)

# 可选 — 使用 OpenAI 替代(设置此项可切换回 OpenAI)
# OPENAI_API_KEY=sk-your-openai-key-here
# OPENAI_BASE_URL=https://api.openai.com/v1

# 可选 — LangSmith 追踪
# LANGCHAIN_TRACING_V2=true
# LANGCHAIN_API_KEY=ls__your-key-here
# LANGCHAIN_PROJECT=langchain-tutorial

⚠️ 绝对不要提交 .env 文件! 它已在 .gitignore 中。


章节概览

标题 核心概念 时间 代码 文档
1 入门与环境配置 uv、LangChain 生态、Runnable 接口、第一个 Chain 15 分钟 .py .md
2 LLM 与 Chat Model invoke/stream/batch、Token 追踪、消息类型、异步 20 分钟 .py .md
3 Prompt 工程 PromptTemplate、ChatPromptTemplate、Few-Shot、partial 25 分钟 .py .md
4 LCEL 与 Chain 管道操作符、RunnableParallel、RunnableBranch、结构化输出 30 分钟 .py .md
5 文档处理 TextLoader、RecursiveCharacterTextSplitter、分块策略 20 分钟 .py .md
6 Embedding 与向量存储 Embedding 模型、Chroma、FAISS、语义搜索、MMR 25 分钟 .py .md
7 RAG 检索增强生成 create_retrieval_chain、多查询检索、重排序 30 分钟 .py .md
8 Agent 与工具 @tool 装饰器、ReAct Agent、工具错误处理 30 分钟 .py .md
9 Memory 对话记忆 RunnableWithMessageHistory、缓存/窗口/摘要记忆、持久化 25 分钟 .py .md
10 Callback 与可观测性 自定义回调处理器、成本/延迟追踪、LangSmith 20 分钟 .py .md
11 进阶:LangGraph StateGraph、条件边、循环、Human-in-the-Loop、多 Agent 35 分钟 .py .md
12 生产部署 FastAPI、SSE 流式、限流、Docker、最佳实践 25 分钟 .py .md

预估总时长:约 5 小时(不含 API 调用延迟)


项目结构

langchain-tutorial/
├── pyproject.toml                    # uv 项目配置和依赖
├── README.md                         # 本文件
├── .env.example                      # API 密钥模板
├── .gitignore                        # Git 忽略规则
│
├── utils/
│   ├── __init__.py
│   └── config.py                     # 共享模型工厂和辅助函数
│
├── chapters/                         # 教程章节(每章独立子目录)
│   ├── __init__.py
│   ├── chapter_01_intro/             # 第 1 章:入门与环境配置
│   │   ├── chapter_01_intro.py       #   可运行代码
│   │   └── chapter_01_intro.md       #   教程文档
│   ├── chapter_02_llms/              # 第 2 章:LLM 与 Chat Model
│   │   ├── chapter_02_llms.py
│   │   └── chapter_02_llms.md
│   ├── chapter_03_prompts/           # 第 3 章:Prompt 工程
│   │   ├── chapter_03_prompts.py
│   │   └── chapter_03_prompts.md
│   ├── chapter_04_lcel/              # 第 4 章:LCEL 与 Chain
│   │   ├── chapter_04_lcel.py
│   │   └── chapter_04_lcel.md
│   ├── chapter_05_documents/         # 第 5 章:文档处理
│   │   ├── chapter_05_documents.py
│   │   └── chapter_05_documents.md
│   ├── chapter_06_embeddings/        # 第 6 章:Embedding 与向量存储
│   │   ├── chapter_06_embeddings.py
│   │   └── chapter_06_embeddings.md
│   ├── chapter_07_rag/               # 第 7 章:RAG
│   │   ├── chapter_07_rag.py
│   │   └── chapter_07_rag.md
│   ├── chapter_08_agents/            # 第 8 章:Agent 与工具
│   │   ├── chapter_08_agents.py
│   │   └── chapter_08_agents.md
│   ├── chapter_09_memory/            # 第 9 章:Memory
│   │   ├── chapter_09_memory.py
│   │   └── chapter_09_memory.md
│   ├── chapter_10_callbacks/         # 第 10 章:Callback 与可观测性
│   │   ├── chapter_10_callbacks.py
│   │   └── chapter_10_callbacks.md
│   ├── chapter_11_langgraph/         # 第 11 章:LangGraph
│   │   ├── chapter_11_langgraph.py
│   │   └── chapter_11_langgraph.md
│   └── chapter_12_production/        # 第 12 章:生产部署
│       ├── chapter_12_production.py
│       └── chapter_12_production.md
│
└── data/
    ├── sample_article.txt            # AI 发展史文章(第 5-7 章)
    ├── faq.txt                       # CloudSync FAQ(第 6-7 章)
    └── product_docs.txt              # EventFlow 产品文档(第 5+ 章)

学习路线

章节按依赖关系组织,建议按顺序学习:

第 1 章(入门)
    │
第 2 章(LLM)→ 第 3 章(Prompt)→ 第 4 章(LCEL)
    │                                      │
    ├──────────────────────────────────────┤
    │                                      │
第 5 章(文档)                       第 8 章(Agent)
    │                                      │
第 6 章(向量)                       第 9 章(Memory)
    │                                      │
第 7 章(RAG)                        第 10 章(Callback)
    │                                      │
    └────────────┬─────────────────────────┘
                 │
         第 11 章(LangGraph)
                 │
         第 12 章(生产部署)

快速通道(核心 LangChain):1 → 2 → 3 → 4 → 7 RAG 专家方向:再加上 5 → 6 → 7 Agent 工程师方向:再加上 8 → 11 生产工程师方向:再加上 9 → 10 → 12


切换 LLM 提供商

本教程默认使用 DeepSeek V3deepseek-chat),通过 ChatOpenAI 客户端调用(DeepSeek API 完全兼容 OpenAI 格式)。要更换提供商:

OpenAI

# .env 中配置:
OPENAI_API_KEY=sk-your-openai-key
OPENAI_BASE_URL=https://api.openai.com/v1
LLM_MODEL=gpt-4o-mini

Anthropic Claude

uv add langchain-anthropic

# 在 config.py 的 get_model() 中:
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-sonnet-4-6")

Google Gemini

uv add langchain-google-genai

# 在 config.py 的 get_model() 中:
from langchain_google_genai import ChatGoogleGenerativeAI
model = ChatGoogleGenerativeAI(model="gemini-2.0-flash")

本地 Ollama(完全免费!)

# 安装 Ollama: https://ollama.com
ollama pull llama3.2

# .env 中配置:
OPENAI_BASE_URL=http://localhost:11434/v1
LLM_MODEL=llama3.2

费用估算

使用默认模型 deepseek-chat(DeepSeek-V3),完整运行 12 章的费用:

项目 大约费用
LLM 调用(全部章节) 约 ¥0.50
Embedding(第 6-7 章) 约 ¥0.07

总计:不到 ¥1(约 $0.10 USD) 🎉

DeepSeek 的定价极低(¥1/1M input tokens, ¥2/1M output tokens), 整个教程的费用几乎可以忽略。如果使用 OpenAI 的 gpt-4o,费用约为 50 倍。


Git 版本历史

项目按章节逐步构建,每个提交对应一个逻辑分组:

fdfc9d1  重组章节:每章的 .py 和 .md 放入独立子目录
9c2dd10  Markdown 教程文档 5-12 + README 更新
f07e260  Markdown 教程文档 1-4
a1287c2  补充 README.md
f29d6fd  第 11-12 章:LangGraph 进阶与生产部署
a689d4e  第 8-10 章:Agent 与工具、Memory、Callback
251d7f5  第 5-7 章:文档处理、Embedding、RAG
86a540d  第 1-4 章:入门、LLM、Prompt、LCEL
733b36d  样本数据文件
6184991  初始化项目骨架

可以通过 git checkout <commit> 回退到任意阶段查看当时的代码。


常见问题

"DEEPSEEK_API_KEY not set"

复制 .env.example.env 并填入你的 DeepSeek API 密钥。 在 platform.deepseek.com/api_keys 获取。

速率限制错误 (429)

  • DeepSeek API 的速率限制较为宽松
  • 如果遇到限制,在调用之间添加 time.sleep(2) 或升级套餐
  • 第 2 章专门讲解了模型回退机制来优雅处理此问题

找不到模块: 'langchain_xxx'

运行 uv sync 安装所有依赖。如果缺少特定集成包,手动安装:

uv add langchain-<provider>

Windows 上 Chroma/SQLite 报错

Chroma 内部使用 SQLite。确保安装了最新的 Visual C++ Redistributable。 本教程已在 Windows 10/11 上测试通过。

FAISS 反序列化警告

第 6 章加载 FAISS 索引时使用了 allow_dangerous_deserialization=True。 这对教程数据是安全的,但在生产环境中处理不可信来源时应禁用。

如何查看某章的执行输出?

uv run python chapters/chapter_07_rag/chapter_07_rag.py

每章的输出包含概念解释、代码演示和"关键要点"总结。


每章文件说明

每章在独立子目录中包含两个文件:

文件类型 作用
.py 可运行代码,每个函数演示一个概念,执行后打印结果和关键要点
.md 详细教程文档,包含架构图、对比表、最佳实践、参数选择指南

建议学习方式:

  1. 先阅读 .md 文档理解概念
  2. 再运行 .py 代码看实际效果
  3. 修改代码中的参数做实验

参考资料


许可协议

MIT — 自由用于学习、教学和项目开发。

About

LangChain 完整教程(12章)— 含可运行 Python 代码和详细 Markdown 文档,使用 uv 管理环境,DeepSeek API 驱动

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages