用途
LangChain 是构建 LLM 驱动应用的框架,资料中列出的典型使用场景包括:构建带工具调用与推理(ReAct 模式)的智能体;实现 RAG(检索增强生成)流水线;需要方便地切换 LLM 提供商(OpenAI、Anthropic、Google);创建带对话记忆的聊天机器人;LLM 应用的快速原型;以及借助 LangSmith 可观测性进行生产部署。
资料同时给出替代方案建议:LlamaIndex 更偏 RAG、适合文档问答;LangGraph 适合复杂有状态工作流、控制更细;Haystack 用于生产搜索流水线;Semantic Kernel 面向微软生态。
主要能力
- 模型抽象:通过 ChatOpenAI、ChatAnthropic、ChatGoogleGenerativeAI 等类切换提供商,并支持流式输出(llm.stream)。
- 链(Chains):使用 PromptTemplate 与 LLMChain 组合顺序操作。
- 智能体(Agents):基于 ReAct(推理+行动)模式,通过 create_agent、create_tool_calling_agent、AgentExecutor 构建工具调用智能体,支持自定义工具与错误处理。
- 记忆(Memory):ConversationBufferMemory 与 ConversationChain 跟踪多轮对话。
- RAG:文档加载(Web、PDF、GitHub、CSV 等)、文本切分(递归、代码感知、语义)、向量存储(Chroma、Pinecone、FAISS)、检索与 RetrievalQA / ConversationalRetrievalChain 问答链。
- 高级模式:结构化输出(with_structured_output)、并行工具执行、流式智能体执行、多文档带来源问答。
- 可观测性:通过环境变量启用 LangSmith 追踪。
使用方式
安装(Python 3.10+):
pip install -U langchain
pip install langchain-openai
pip install langchain-anthropic
pip install langchain-community
pip install langchain-chroma
基础调用示例:
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
response = llm.invoke("Explain quantum computing in 2 sentences")
print(response.content)
创建智能体示例:
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
def get_weather(city: str) -> str:
"""Get current weather for a city."""
return f"It's sunny in {city}, 72°F"
def search_web(query: str) -> str:
"""Search the web for information."""
return f"Search results for: {query}"
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[get_weather, search_web],
system_prompt="You are a helpful assistant. Use tools when needed."
)
result = agent.invoke({"messages": [{"role": "user", "content": "What's the weather in Paris?"}]})
print(result["messages"][-1].content)
RAG 基本流程:加载文档 → 切分 → 生成嵌入并存入向量库 → 创建检索器 → 构建 RetrievalQA 链 → 查询并返回来源。
适用场景
快速原型、聊天机器人、文档问答、多提供商模型切换、带工具推理的智能体、生产部署(配合 LangSmith)。
限制与注意事项
资料建议:从简单开始(多数情况用 create_agent());启用流式以改善体验;为工具添加错误处理;使用 LangSmith 调试;RAG 分块大小建议 500-1000 字符;对提示词做版本管理;缓存嵌入;监控成本。性能方面,简单 LLM 调用约 1-2 秒,单工具智能体约 3-5 秒,RAG 检索约 0.5-1 秒,嵌入 1000 篇文档约 10-30 秒(均取决于提供商与模型)。LangChain 与 LangGraph 的取舍:LangChain 适合快速智能体与 RAG、抽象层级高、启动代码少于 10 行;LangGraph 适合复杂工作流、控制更细、原生支持有状态与循环图、高级人机协同。
资源
GitHub:https://github.com/langchain-ai/langchain (119,000+ 星标) 文档:https://docs.langchain.com API 参考:https://reference.langchain.com/python LangSmith:https://smith.langchain.com 版本:0.3+(稳定);许可证:MIT。
暂未提供
资料未提供具体收费与价格信息、各平台支持细节、以及除上述指标外的效果数据。