什么是LangChain
LangChain是一个帮助开发者快速构建智能体应用的工具框架。他能吧大模型(OpenAI、LLM API)、工具(搜索引擎、数据库)、记忆能力、链式调用等模块全部串联起来组成一个可交互、可记忆、有逻辑的智能体(Agent)
LangChain能做什么?
- 串联多个大模型对话任务,实现多轮对话
- 将大模型与外部工具链接(搜索引擎、计算器、代码解释器)
- 给大模型添加”记忆”
- 构建复杂的agent工作流,支持决策分支和任务规划
- 与文档、数据库结合,打造RAG检索增强系统
| 模块 | 说明 |
|---|---|
| Models | 支持OpenAI、Anthropic、LLama等多模型,封装调用细节与响应结构 |
| Prompts | 提供模板引擎和变量插值机制,让提示词更容易复用 |
| Indexes | 索引与检索接口,构建企业级知识库核心库能力 |
| Memory | 支持对话中记忆上下文(短期 + 长期),提升交互连贯性 |
| Chains | 串联多个步骤形成逻辑工作流 |
| Agents | 构建能自己调用工具的智能体 |
LangChain基础使用
安装@langchain/ollama库用用于调用本地模型
使用npm安装
npm install @langchain/ollama使用yarn安装
yarn add @langchain/ollama用pnpm安装
pnpm add @langchain/ollama模型基础调用
import { Ollama } from "@langchain/ollama";
// 创建模型实例const model = new Ollama({ model:"ornith:9b"})
const prompt = "请用中文写一首关于春天的诗,要求押韵,字数不少于20字。"
// 文本模式输出const res = await model.invoke(prompt);
console.log(res);也可以使用流式输出
import { Ollama } from "@langchain/ollama";
// 创建模型实例const model = new Ollama({ model:"ornith:9b"})
const prompt = "请用中文写一首关于春天的诗,要求押韵,字数不少于20字。"
// 流式输出const res = await model.stream(prompt);
for await (const chunk of res) { process.stdout.write(chunk);}对话模型(Chat Completion Models)
对话模型在能力上更进一步,他支持多轮上下文和角色区分,输入格式为一组带有身份标签的消息数组例如(system、user、assistant),模型能够根据对话历史生成更加自然的且连续的回复
langchain包结构
@langchain/core
langchain的内核,提供基础的抽象能力,比如Runnable(可执行单元)、Prompt(提示词模板)、OutPutParser(输出解析器)等,同时还包含LangChain Expression Lanuage,用于编排复杂的链式逻辑。
pnpm add @langchain/core@langchain/community
社区维护的扩展包,收录了大量第三方集成,例如各类向量数据库、模型api、文档加载器等。可以理解为LangChain的插件市场
pnpm add @langchain/communitylangchain
是在核心能力基础上的高阶封装、内置了常见的链式组件(Chains)、智能体模块(Agents)、工具调度(Tools)等,是大多数LangChain应用的默认入口包。
pnpm add langchain对话模型支持角色区分,可以使用 @langchain/core/prompts来快速编写多角色提示词
安装@langchain/core
pnpm add @langchain/core使用@langchain/core编写多角色提示词模板并且调用模型
// 从@langchain/ollama导入对话模型import { ChatOllama } from "@langchain/ollama";
// 导入提示词模板类import { SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate,} from "@langchain/core/prompts";
/** * 创建对话模型实例 * model: 模型名称 * temperature: 生成文本的随机性,值越高,生成的文本越随机 * stream: 是否开启流式输出 */const model = new ChatOllama({ model: "llama3.2", temperature: 0.7, stream: true,})
// 创建多角色提示词模板
// 1.系统提示词const systemPrompt = SystemMessagePromptTemplate.fromTemplate("你是一个翻译助手,请将用户输入的{input_language}翻译成{output_language}.");
// 2.创建用户提示词const userPrompt = HumanMessagePromptTemplate.fromTemplate("{text}");
// 3.合成提示词const chatPrompt = ChatPromptTemplate.fromMessages([systemPrompt, userPrompt])
// 4.填充变量const messages = await chatPrompt.formatMessages({ input_language: "中文", output_language: "英文", text: "今天天气怎么样?"})
// 使用流式传输const res = await model.stream(messages)
for await (const chunk of res) { process.stdout.write(chunk.content);}缓存
在实际开发ai应用中经常会遇到重复输入的情况
- 同一用户多次询问相同问题
- 刷新页面或误触按钮发送了相同请求
- 不同用户提出了高度相似的问题
如果每次都要让大模型重新生成响应,不仅效率低下,还会带来不必要的计算成本。为了解决这个问题我们可以引入缓存机制
缓存机制的好处
- 提升响应速度,重复问题无需从新调用模型,之际命中缓存结果
- 降低调用成本
- 避免冗余请求
使用缓存机制
import { Ollama } from "@langchain/ollama";
const model = new Ollama({ model: "llama3.2", temperature: 0.8, cache: true //开启缓存});
// 记录用时1const start1 = Date.now();const res = await model.invoke("讲一讲什么是langchain");console.log(res)const end1 = Date.now()console.log(`\n第一次请求用时${end1 - start1}\n`)
// 记录用时2const start2 = Date.now();const res2 = await model.invoke("讲一讲什么是langchain");console.log(res2)const end2 = Date.now()console.log(`\n第二次请求用时${end2 - start2}\n`)在流式传输模式下使用缓存模式
import { Ollama } from "@langchain/ollama";
// 使用自定义的哈希缓存加密const hashSecure = new SecureCatch()
const model = new Ollama({ model: "llama3.2", temperature: 0.8, stream: true, //开启流式 cache: true // 开启缓存});
async function StreamCache (prompt) { const start = Date.now() const stream = await model.stream(prompt); for await (const chunk of stream) { process.stdout.write(chunk); }
const end = Date.now() console.log(`\n本次耗时${end - start} `) return 0;}
console.log("未缓存")await StreamCache("讲一讲什么是langchain")
console.log("已缓存")await StreamCache("讲一讲什么是langchain")LangChain缓存机制目前的问题
在流式模式下没有缓存命中,目前LangChain的默认缓存机制只对同步接口如.invoke()``.predict()生效。这些方法会在调用前检查缓存结果,如果有就直接返回,没有才去调用模型
而.stream()方法返回的是一个异步迭代器(AsyncIterable),数据是一块块实时生成的。当前在LangChain.js的实现中,大多数模型对.stream()并未内建完整的缓存处理逻辑
总结
LangChain是目前主流的智能体应用开发库之一,他给开发者提供了一站式开发工具和封装好的智能体api大大减少了智能体开发难度且兼容多种编程语言。
@langchain/core是langchain的核心包,提供了Runnable(可执行单元)、Prompt(提示词模板)、OutPutParser(输出解析器)等API
LangChain还具备缓存机制,提升响应速度,重复问题无需从新调用模型,之际命中缓存结果,降低调用成本,避免冗余请求
部分信息可能已经过时