LangChain 教程¶
LangChain 是开发大语言模型(LLM)应用的框架,本教程基于 LangChain 最新版本,使用全新的 create_agent API 和 Middleware 中间件架构。
目录¶
- 第一章:LangChain 简介
- 第二章:快速开始
- 第三章:模型 I/O
- 第四章:提示词模板
- 第五章:LCEL 链式调用
- 第六章:记忆系统
- 第七章:Agent 代理系统 ⭐ 最新 API
- 第八章:RAG 系统
- 第九章:Agent 进阶 ⭐ 新增
重要更新¶
新 API(推荐)¶
| 废弃 API | 新 API | 说明 |
|---|---|---|
initialize_agent() |
create_agent() |
统一的 agent 创建函数 |
AgentExecutor |
create_agent() 返回的 Runnable |
内置 LangGraph 图执行 |
ConversationBufferMemory |
checkpointer + state |
基于图的状态管理 |
新特性¶
- Middleware 中间件:日志记录、重试、降级、人工审核、PII 检测等
- 状态管理:短期记忆(checkpointer)和长期记忆(store)
- 流式输出:原生支持 streaming
- 多模型支持:统一接口支持 OpenAI、Anthropic、Google 等
快速开始¶
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_openai import ChatOpenAI
@tool
def get_weather(city: str) -> str:
"""获取城市天气"""
return f"{city}: 晴天,25°C"
agent = create_agent(
model=ChatOpenAI(model="gpt-4.1"),
tools=[get_weather],
system_prompt="你是一个智能助手。"
)
result = agent.invoke({
"messages": [{"role": "user", "content": "北京天气怎么样?"}]
})
print(result["messages"][-1].content)