【AI】LangChain快速入门
简介
LangChain是一个用于开发由语言模型驱动的应用程序的框架。它旨在帮助开发者将大型语言模型(LLM)与其他计算资源或知识源连接起来,从而创建更强大、更实用的应用。

核心价值
- 模块化设计:提供可组合的构建块,简化复杂应用的开发
- 集成能力:支持多种语言模型、数据存储和外部工具的无缝集成
- 灵活性:适用于各种应用场景,从简单问答到复杂工作流
- 效率提升:减少样板代码,让开发者专注于业务逻辑
安装
具体来说,LangChain框架由以下开源库组成:
- L
angchain-core: 基础抽象和LangChain表达式 (LCEL)。该包包含不同组件的基本抽象以及将它们组合在一起的方法。 核心组件的接口,如大型语言模型、向量存储、检索器等在此定义。 此处未定义任何第三方集成。 - L
angchain: 组成应用程序认知架构的链、代理和检索策略。 - L
angchain-community: 第三方集成。 - 合作伙伴库(例如
langchain-openai、langchain-deepseek等):一些集成已进一步拆分为自己的轻量级库,仅依赖于langchain-core。: - LangGraph: 通过将步骤建模为图中的边和节点,构建强大且有状态的多参与者应用程序。与LangChain无缝集成,但也可以单独使用。
- LangServe: 将LangChain链部署为REST API
- LangSmith: 一个开发者平台,让您调试、测试、评估和监控LLM应用程
- Langchain-experimenta: 实验功能的包
# 安装LangChain核心库
pip install langchain
#集成包
pip install langchain-community
#可选 独立三方库 查看全部 https://python.langchain.com/api_reference/ 比如
pip install langchain-ollama langchain-milvus
pip install langchain-mcp-adapters
使用示例
from langgraph.graph import StateGraph, MessagesState, START, END
def mock_llm(state: MessagesState):
return {"messages": [{"role": "ai", "content": "hello world"}]}
graph = StateGraph(MessagesState)
graph.add_node(mock_llm)
graph.add_edge(START, "mock_llm")
graph.add_edge("mock_llm", END)
graph = graph.compile()
graph.invoke({"messages": [{"role": "user", "content": "hi!"}]})
核心组件介绍

Models(模型)
支持多种语言模型接口:
-
LLM:基础文本生成模型(适合一次性对话补全,文本生成等场景),返回字符串
-
Chat Models:对话优化模型(多轮聊天),返回聊天消息
- SystemMessage
- HumanMessage
- AIMessage
- ToolMessage
import { ChatOpenAI } from "langchain/chat_models/openai";
import { HumanChatMessage } from "langchain/schema";
export const run = async () => {
const chat = new ChatOpenAI();
// Pass in a list of messages to `call` to start a conversation. In this simple example, we only pass in one message.
const response = await chat.call([
new HumanChatMessage(
"What is a good name for a company that makes colorful socks?"
),
]);
console.log(response);
// AIChatMessage { text: '\n\nRainbow Sox Co.' }
};
-
Embeddings:文本向量化模型,返回向量列表
- 在线模型
- 本地模型
提示词模板
LangChain 提供了多种提示词模板(Prompt Template),可以帮助开发者更容易地构建提示词
-
Prompt Templates:字符串提示模板
-
ChatPromptTemplates:聊天提示词模板
-
MessagesPlaceholder:消息占位符
Chains(链)
链(Chain)是LangChain的核心组件之一。通过链技术,可以将多步骤任务整合成清晰的流程,将语言模型调用、数据处理和决策逻辑连接在一起,从而实现复杂的应用需求。链不仅帮助开发者组织逻辑,还能根据特定的业务需求创建定制化的生成流程,使得生成的内容更符合实际使用场景。
常用链
- LLMChain:基础模型调用链
- Sequential Chains:顺序执行多个链
- Router Chains:根据输入路由到不同链
- TransformChain:自定义转换链
- Document Chains:文档链
LangChain表达式 (LCEL)
LangChain表达式语言(LangChain Expression Language,LCEL)的引入,极大地简化了复杂任务的开发过程,并提升了系统的执行效率。LCEL通过流式处理、异步支持、多任务并行执行等特性,为LangChain的开发者提供了强大且灵活的工具,使得复杂任务的定义与执行变得更加高效。
Memory(记忆)
在构建智能对话系统中,记忆(Memory)模块是LangChain的关键组件之一。它使模型能够记住先前的对话内容,以实现上下文理解和多轮交互。
Agents(智能体)
-
Tools:代理可使用的函数,执行特定职责的函数。这可以是像:谷歌搜索(Google Search),数据库查找(Database lookup),代码REPL,其他链。工具的接口目前是预期具有字符串输入,和字符串输出的函数。
-
Toolkits:相关工具的集合
-
Agent Executors:运行代理的框架
-
为了让智能代理更加强大,我们需要使其迭代,即调用模型多次,直到达到最终答案。这就是 AgentExecutor 的工作。
-
class AgentExecutor { // a simplified implementation run(inputs: object) { const steps = []; while (true) { const step = await this.agent.plan(steps, inputs); if (step instanceof AgentFinish) { return step.returnValues; } steps.push(step); } } } -
Action Agents:决定下一步动作的代理。
import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { OpenAI } from "langchain/llms/openai";
import { SerpAPI } from "langchain/tools";
import { Calculator } from "langchain/tools/calculator";
const model = new OpenAI({ temperature: 0 });
const tools = [
new SerpAPI(process.env.SERPAPI_API_KEY, {
location: "Austin,Texas,United States",
hl: "en",
gl: "us",
}),
new Calculator(),
];
const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: "zero-shot-react-description",
verbose: true,
});
const input = `Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?`;
const result = await executor.call({ input });
总结
LangChain是一个强大的框架,旨在帮助开发人员使用语言模型构建端到端的应用程序,它提供了一套工具、组件和接口,可简化创建由大型语言模型 (LLM) 和聊天模型提供支持的应用程序的过程。提供了灵活的抽象和AI优先的工具,可帮助开发人员将LLM应用程序从原型转化为生产环境。 它还提供了一套工具,可帮助开发人员构建上下文感知、推理应用程序, LangChain的工具包括聊天机器人、文档分析、摘要、代码分析、工作流自动化、自定义搜索等。
更多推荐




所有评论(0)