LangChain从入门到实战(2026版)
1. LangChain 简介与核心概念LangChain 是一个用于构建基于大语言模型LLM应用程序的开源框架。它通过提供模块化组件和链式调用机制简化了 LLM 应用开发的复杂性让开发者能够更高效地构建智能代理、问答系统、文档分析等应用。核心概念模型Models与各种 LLM如 OpenAI GPT、Claude、本地模型交互的抽象层。提示词Prompts管理、优化和模板化输入给模型的指令。链Chains将多个组件模型、提示词、工具等组合成可执行的工作流。记忆Memory在链或代理的多次调用之间保持状态和上下文。索引Indexes结合外部数据如文档、数据库与 LLM实现检索增强生成RAG。代理Agents让 LLM 自主决定调用哪些工具如搜索、计算、API来完成复杂任务。2. 环境搭建与快速开始首先确保你的 Python 环境版本在 3.8 或以上。# 使用 pip 安装 LangChain 核心包 pip install langchain 根据需求安装社区集成包例如 OpenAI pip install langchain-openai 安装常用的工具包如用于文档加载的包 pip install langchain-community安装完成后你可以通过一个简单的示例来验证环境from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate 初始化模型此处需要设置你的 OPENAI_API_KEY llm ChatOpenAI(modelgpt-4o-mini, temperature0) 创建提示词模板 prompt ChatPromptTemplate.from_messages([ (system, 你是一个乐于助人的助手。), (user, {input}) ]) 创建链 chain prompt | llm 调用链 response chain.invoke({input: 用一句话介绍 LangChain。}) print(response.content)3. 核心组件深度解析3.1 模型 I/O与 LLM 对话的基础LangChain 提供了统一的接口来调用不同的 LLM。除了 OpenAI还支持 Anthropic、Cohere、本地模型如通过 Ollama等。from langchain_anthropic import ChatAnthropic from langchain_community.llms import Ollama 使用 Claude 模型 claude_llm ChatAnthropic(modelclaude-3-5-sonnet-20241022) 使用本地 Ollama 模型 local_llm Ollama(modelllama3.2)3.2 提示词工程从简单到复杂好的提示词是获得高质量回答的关键。LangChain 提供了PromptTemplate、ChatPromptTemplate、FewShotPromptTemplate等工具来构建动态提示。from langchain_core.prompts import ChatPromptTemplate, FewShotPromptTemplate from langchain_core.prompts.example_selector import SemanticSimilarityExampleSelector 构建一个包含上下文和问题的复杂提示词 template 你是一个专业的{role}。请根据以下背景信息回答问题。 背景{context} 问题{question} 请给出详细、准确的回答。 prompt ChatPromptTemplate.from_template(template) 使用示例 formatted_prompt prompt.format(role软件架构师, context系统采用微服务架构..., question如何设计服务间的通信) print(formatted_prompt)3.3 链构建复杂工作流链Chain是 LangChain 的核心抽象允许你将多个步骤串联起来。最简单的链是LLMChain更复杂的可以使用SequentialChain或 LCELLangChain Expression Language。from langchain.chains import LLMChain, SimpleSequentialChain from langchain_core.prompts import PromptTemplate 定义第一个链生成博客标题 title_template PromptTemplate(input_variables[topic], template为{topic}写一个吸引人的博客标题。) title_chain LLMChain(llmllm, prompttitle_template) 定义第二个链根据标题生成大纲 outline_template PromptTemplate(input_variables[title], template为标题《{title}》生成详细的博客大纲。) outline_chain LLMChain(llmllm, promptoutline_template) 组合成顺序链 overall_chain SimpleSequentialChain(chains[title_chain, outline_chain], verboseTrue) 执行 result overall_chain.run(人工智能在医疗诊断中的应用) print(result)3.4 记忆让对话拥有上下文记忆组件使 LLM 能够记住之前的交互。常用的有ConversationBufferMemory保存所有历史、ConversationSummaryMemory保存摘要等。from langchain.memory import ConversationBufferMemory from langchain.chains import ConversationChain memory ConversationBufferMemory() conversation ConversationChain(llmllm, memorymemory, verboseTrue) conversation.predict(input你好我叫小明。) conversation.predict(input你还记得我的名字吗) 输出会包含之前的对话历史3.5 检索增强生成RAG实战RAG 通过检索外部知识库来增强 LLM 的回答使其能够提供更准确、更有时效性的信息。from langchain_community.document_loaders import TextLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_openai import OpenAIEmbeddings from langchain_community.vectorstores import Chroma from langchain.chains import RetrievalQA 1. 加载文档 loader TextLoader(knowledge_base.txt) documents loader.load() 2. 分割文本 text_splitter RecursiveCharacterTextSplitter(chunk_size500, chunk_overlap50) texts text_splitter.split_documents(documents) 3. 创建向量存储 embeddings OpenAIEmbeddings() vectorstore Chroma.from_documents(texts, embeddings) 4. 创建检索器 retriever vectorstore.as_retriever() 5. 创建问答链 qa_chain RetrievalQA.from_chain_type(llmllm, chain_typestuff, retrieverretriever) 6. 提问 answer qa_chain.run(LangChain 的主要优势是什么) print(answer)3.6 代理让 LLM 使用工具代理Agent赋予 LLM 使用外部工具如搜索、计算、执行代码的能力以完成更复杂的任务。from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain_community.utilities import SerpAPIWrapper from langchain.chains import LLMMathChain 定义工具 search SerpAPIWrapper() llm_math LLMMathChain(llmllm) tools [ Tool( nameSearch, funcsearch.run, description当需要回答关于当前事件或具体事实的问题时使用。 ), Tool( nameCalculator, funcllm_math.run, description当需要解决数学问题时使用。 ), ] 初始化代理 agent initialize_agent(tools, llm, agentAgentType.ZERO_SHOT_REACT_DESCRIPTION, verboseTrue) 运行代理 agent.run(截至2026年7月OpenAI GPT-5 的最新消息是什么另外计算 125 的平方根。)4. 2026 年最佳实践与进阶技巧4.1 性能优化与成本控制缓存使用langchain.cache如InMemoryCache、SQLiteCache缓存重复的模型调用结果。流式输出使用chain.stream()实现逐词输出提升用户体验。异步调用使用chain.ainvoke()或chain.abatch()提升高并发场景下的吞吐量。模型选择根据任务复杂度在“大模型高精度”和“小模型低成本”之间权衡。4.2 可观测性与调试启用verboseTrue查看链的详细执行步骤。使用langchain.callbacks记录日志、跟踪 token 使用量。利用 LangSmith 平台如可用进行全链路追踪、测试和评估。4.3 生产环境部署考量安全性对用户输入进行严格的清理和审查防止提示词注入攻击。稳定性为模型调用和工具调用添加重试和回退机制。可扩展性考虑使用消息队列如 Celery处理异步任务将向量数据库部署为独立服务。