📚 为什么要迁移到 1.0?

LangChain 1.0 是一个重大更新,带来了:

💡 1.0 的主要优势
特性 0.x 版本 1.0 版本
API 稳定性 频繁变化 稳定的公共 API
Agent 创建 复杂的手动配置 简单的 create_agent()
中间件系统 不支持 完整的中间件架构
Runtime 上下文 有限支持 类型安全的依赖注入
持久化 基础功能 Checkpointer + Store 双系统
模型抽象 特定于提供商 统一的 init_chat_model()
⚠️ 重要提醒

LangChain 1.0 不向后兼容 0.x 的部分 API。 如果需要继续使用 0.x 的 API,可以安装 langchain-classic 包。

🗺️ 迁移流程

graph TB Start[开始迁移] --> Backup[备份现有代码] Backup --> Install[安装 LangChain 1.0] Install --> Evaluate{评估迁移策略} Evaluate -->|完全迁移| NewAPI[使用 1.0 新 API] Evaluate -->|渐进迁移| Classic[使用 langchain-classic] NewAPI --> Update1[更新导入语句] Update1 --> Update2[替换 API 调用] Update2 --> Update3[重构 Agent 创建] Update3 --> Test1[运行测试] Classic --> Install2[安装 langchain-classic] Install2 --> Update4[部分使用新 API] Update4 --> Test2[运行测试] Test1 --> Fix{有错误?} Test2 --> Fix Fix -->|是| Debug[调试和修复] Fix -->|否| Verify[验证功能] Debug --> Test1 Verify --> Deploy[部署到生产] Deploy --> End[迁移完成] style Start fill:#3b82f6,color:#fff style End fill:#10b981,color:#fff style Evaluate fill:#f59e0b,color:#fff style Fix fill:#f59e0b,color:#fff

🔄 主要 API 变化对照表

1. 模型初始化

0.x 版本 1.0 版本 说明
ChatOpenAI(...) init_chat_model("gpt-4o", ...) 推荐使用统一初始化函数
OpenAIEmbeddings(...) init_embeddings("text-embedding-3-small", ...) 统一的嵌入模型初始化
Python
# ❌ 0.x 版本
from langchain.chat_models import ChatOpenAI
model = ChatOpenAI(model_name="gpt-4", temperature=0.7)

# ✅ 1.0 版本(推荐)
from langchain import init_chat_model
model = init_chat_model("gpt-4o", model_provider="openai", temperature=0.7)

# ✅ 1.0 版本(仍然支持)
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0.7)

2. Agent 创建

0.x 版本 1.0 版本 说明
initialize_agent(...) create_agent(...) 全新的 Agent 创建 API
AgentExecutor.from_agent_and_tools(...) create_agent(...) 统一的创建方式
Python
# ❌ 0.x 版本
from langchain.agents import initialize_agent, AgentType

agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

# ✅ 1.0 版本
from langchain.agents import create_agent

agent = create_agent(
    model="gpt-4o",
    tools=tools,
    system_prompt="你是专业的 AI 助手"
)

3. 链(Chains)

0.x 版本 1.0 版本 说明
LLMChain LCEL 管道或 Agent 使用 LCEL 替代
SimpleSequentialChain LCEL | 操作符 使用管道操作符
RetrievalQA Agent + RAG 工具 使用 Agentic RAG
Python
# ❌ 0.x 版本
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

prompt = PromptTemplate.from_template("翻译: {text}")
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(text="Hello")

# ✅ 1.0 版本(LCEL)
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template("翻译: {text}")
chain = prompt | model
result = chain.invoke({"text": "Hello"})

4. 内存管理

0.x 版本 1.0 版本 说明
ConversationBufferMemory Checkpointer 使用持久化系统
ConversationSummaryMemory SummarizationMiddleware 使用中间件
Python
# ❌ 0.x 版本
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
agent = initialize_agent(tools, llm, memory=memory)

# ✅ 1.0 版本
from langgraph.checkpoint.memory import InMemorySaver

checkpointer = InMemorySaver()
agent = create_agent(
    model="gpt-4o",
    tools=tools,
    checkpointer=checkpointer
)

# 使用 thread_id 管理对话
config = {"configurable": {"thread_id": "user_001"}}
agent.invoke({"messages": [...]}, config=config)

🚫 废弃功能和替代方案

废弃功能(0.x) 替代方案(1.0) 迁移难度
LLMChain LCEL 管道 或 Agent 🟡 中等
initialize_agent() create_agent() 🟢 简单
ConversationBufferMemory Checkpointer 🟡 中等
RetrievalQA Agent + RAG 工具 🟡 中等
SimpleSequentialChain LCEL | 操作符 🟢 简单
VectorDBQA Agent + 检索工具 🟡 中等
旧的 Callback 系统 Middleware 系统 🔴 较难
✅ 迁移建议
  • 优先迁移简单的 API:先从模型初始化和 Agent 创建开始
  • 分模块迁移:不要一次性迁移所有代码
  • 保留测试:确保每次迁移后测试通过
  • 使用 langchain-classic:对于复杂的旧代码,可以暂时使用兼容包

📦 使用 langchain-classic

如果需要继续使用 0.x 的 API,可以安装 langchain-classic 包。 这允许你在迁移过程中逐步替换旧代码。

安装 langchain-classic

Bash
# 安装 langchain-classic
pip install langchain-classic

# 同时安装 LangChain 1.0
pip install langchain>=1.0.0

混合使用示例

Python
# 使用 1.0 的新 API
from langchain import init_chat_model
from langchain.agents import create_agent

model = init_chat_model("gpt-4o", model_provider="openai")

# 使用 langchain-classic 的旧 API
from langchain_classic.chains import LLMChain
from langchain_classic.prompts import PromptTemplate

prompt = PromptTemplate.from_template("翻译: {text}")
old_chain = LLMChain(llm=model, prompt=prompt)

# 在同一个项目中混合使用
result = old_chain.run(text="Hello")
⚠️ 注意事项

langchain-classic 仅用于过渡期,不会获得新功能更新。 建议尽快完成迁移到 1.0 API。

📝 详细迁移步骤

步骤 1: 准备工作

Bash
# 1. 备份现有代码
git commit -am "Backup before LangChain 1.0 migration"

# 2. 创建新分支
git checkout -b migration-to-v1

# 3. 升级到 LangChain 1.0
pip install --upgrade langchain langchain-openai langchain-anthropic

# 4. 查看当前版本
python -c "import langchain; print(langchain.__version__)"

步骤 2: 更新导入语句

Python
# ❌ 旧的导入(0.x)
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory

# ✅ 新的导入(1.0)
from langchain import init_chat_model
from langchain.agents import create_agent
from langchain_core.prompts import ChatPromptTemplate
from langgraph.checkpoint.memory import InMemorySaver

步骤 3: 替换 Agent 创建

Python
# ❌ 0.x 版本
llm = ChatOpenAI(model_name="gpt-4", temperature=0.7)
memory = ConversationBufferMemory()

agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    memory=memory,
    verbose=True
)

# ✅ 1.0 版本
checkpointer = InMemorySaver()

agent = create_agent(
    model="gpt-4o",
    tools=tools,
    checkpointer=checkpointer,
    system_prompt="你是专业的 AI 助手"
)

# 调用时传入 config
config = {"configurable": {"thread_id": "user_001"}}
result = agent.invoke({"messages": [...]}, config=config)

步骤 4: 替换链(Chains)

Python
# ❌ 0.x 版本
from langchain.chains import LLMChain, SimpleSequentialChain
from langchain.prompts import PromptTemplate

# 链 1:翻译
translate_prompt = PromptTemplate.from_template("翻译成英文: {text}")
translate_chain = LLMChain(llm=llm, prompt=translate_prompt)

# 链 2:总结
summarize_prompt = PromptTemplate.from_template("总结: {text}")
summarize_chain = LLMChain(llm=llm, prompt=summarize_prompt)

# 组合链
overall_chain = SimpleSequentialChain(
    chains=[translate_chain, summarize_chain]
)

# ✅ 1.0 版本(LCEL)
from langchain_core.prompts import ChatPromptTemplate

translate_prompt = ChatPromptTemplate.from_template("翻译成英文: {text}")
summarize_prompt = ChatPromptTemplate.from_template("总结: {text}")

# 使用管道操作符组合
chain = (
    translate_prompt
    | model
    | (lambda x: {"text": x.content})
    | summarize_prompt
    | model
)

result = chain.invoke({"text": "你好世界"})

步骤 5: 测试和验证

Python
# 运行现有测试
pytest tests/

# 手动测试关键功能
def test_migration():
    """测试迁移后的功能"""
    from langchain.agents import create_agent

    agent = create_agent(
        model="gpt-4o",
        tools=[],
        system_prompt="你是 AI 助手"
    )

    result = agent.invoke({
        "messages": [{"role": "user", "content": "你好"}]
    })

    assert len(result["messages"]) > 0
    print("✅ 迁移成功!")

if __name__ == "__main__":
    test_migration()

✅ 迁移检查清单

📋 完整检查清单
检查项 说明 状态
备份代码 使用 Git 提交当前状态
升级包 pip install --upgrade langchain
更新导入 替换所有 import 语句
替换模型初始化 使用 init_chat_model()
替换 Agent 创建 使用 create_agent()
替换链 使用 LCEL 或 Agent
替换内存管理 使用 Checkpointer
运行测试 确保所有测试通过
性能测试 验证性能没有退化
文档更新 更新内部文档和注释
部署测试 在测试环境验证
生产部署 逐步灰度发布

❓ 常见迁移问题

Q1: 必须立即迁移到 1.0 吗?

不是必须,但强烈推荐。LangChain 0.x 将逐步停止维护。 你可以:

  • 使用 langchain-classic 继续运行旧代码
  • 逐步迁移,而不是一次性全部迁移
  • 优先迁移新功能,旧功能可以暂缓

Q2: 迁移需要多长时间?

取决于代码规模:

项目规模 预估时间 建议策略
小型(< 1000 行) 1-2 天 一次性迁移
中型(1000-5000 行) 1-2 周 分模块迁移
大型(> 5000 行) 1-2 月 渐进式迁移 + langchain-classic

Q3: 性能会有变化吗?

一般情况下,1.0 版本性能更好

  • 更高效的状态管理
  • 更好的流式输出支持
  • 中间件带来的灵活性

Q4: 如何处理大量的 LLMChain?

策略 1:使用 LCEL 重写(推荐)

Python
# LCEL 更简洁、更强大
chain = prompt | model

策略 2:使用 langchain-classic 保留旧代码

Python
from langchain_classic.chains import LLMChain
# 保持原有代码不变

Q5: 1.0 有哪些新功能值得使用?

  • 中间件系统:PII 保护、摘要、日志等
  • Runtime 上下文:类型安全的依赖注入
  • Checkpointer + Store:更强大的持久化
  • 统一的模型接口:跨提供商兼容
  • 更好的流式输出:多种 stream_mode

📖 参考资源