别再把 LangChain 当「AI 胶水」了!30 分钟带你做出第一个智能应用
从「调用 API」到「构建 AI 产品」,这篇文让你真正看懂 LangChain 的核心价值,附完整实战项目
🎯 前言:为什么你需要 LangChain?
想象一下这个场景:
你想做一个「智能客服机器人」,需要:
- 🤖 连接大模型(LLM)
- 📚 读取公司文档知识库
- 💬 记住用户对话历史
- 🔍 根据问题搜索相关知识
- 📊 分析用户反馈数据
没有 LangChain 时:
// 代码像意大利面一样缠绕...
const response = await fetch('https://api.openai.com/v1/chat/completions', {
// 100 行请求代码
});
const history = await db.query('SELECT * FROM conversations...'); // 50 行
const docs = await searchDocs(query); // 80 行
const context = combine(history, docs); // 60 行
const prompt = buildPrompt(context, query); // 40 行
const answer = await callLLM(prompt); // 30 行
// 总共 360+ 行代码,还容易出错...
使用 LangChain 后:
// 10 行代码搞定!
const chain = new ConversationChain({
llm,
memory: new BufferMemory(),
retriever: knowledgeBase.asRetriever()
});
const response = await chain.call({ input: userQuestion });
LangChain 是什么?
简单说:AI 应用开发的「乐高积木」
它帮你把复杂的 AI 功能模块化,让你像搭积木一样构建智能应用。
📚 一、LangChain 核心概念(10 分钟速成)
1. LangChain 解决了什么问题?
| 问题 | 传统方案 | LangChain 方案 |
|---|---|---|
| Prompt 管理 | 硬编码在代码里 | 模板化、可复用 |
| 数据获取 | 手动写 API 调用 | 内置多种工具(Tools) |
| 记忆管理 | 自己维护对话历史 | 内置 Memory 模块 |
| 链式调用 | 手动串联多个步骤 | Chain 自动编排 |
| Agent 决策 | 复杂的状态机 | 自动规划任务 |
2. 核心模块详解
🧩 LLM(大语言模型)
LangChain 支持 50+ 种模型,统一接口:
import { OpenAI } from 'langchain/llms/openai';
const llm = new OpenAI({
temperature: 0.7,
model: 'gpt-4'
});
📝 Prompt(提示词)
模板化提示词,支持变量替换:
import { PromptTemplate } from 'langchain/prompts';
const template = `你是一名{role},请用{tone}的语气回答以下问题:
问题:{question}
回答:`;
const prompt = new PromptTemplate({
template,
inputVariables: ['role', 'tone', 'question']
});
🔗 Chain(链)
将多个步骤串联起来:
用户输入 → Prompt 模板 → LLM → 后处理 → 输出
💾 Memory(记忆)
记住对话历史:
import { BufferMemory } from 'langchain/memory';
const memory = new BufferMemory({
memoryKey: 'chat_history',
returnMessages: true
});
🛠️ Tools(工具)
让 AI 调用外部功能:
import { Calculator } from 'langchain/tools/calculator';
const tools = [
new Calculator(),
new SearchTool(),
new DatabaseTool()
];
🤖 Agent(智能体)
让 AI 自主规划任务:
import { initializeAgentExecutor } from 'langchain/agents';
const executor = await initializeAgentExecutor(tools, llm);
const result = await executor.run('帮我计算 25*48,然后搜索这个结果的意义');
🚀 二、环境准备(5 分钟)
1. 安装依赖
# 创建项目
mkdir langchain-demo
cd langchain-demo
npm init -y
# 安装核心库
npm install langchain @langchain/core @langchain/openai
# 安装其他依赖
npm install dotenv axios
2. 配置环境变量
创建 .env 文件:
OPENAI_API_KEY=sk-your-api-key-here
3. 基础配置
// config.js
import dotenv from 'dotenv';
dotenv.config();
export const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
🎮 三、实战项目:智能产品助手
让我们做一个**「智能产品推荐助手」**,它能:
- 📚 学习产品知识库
- 💬 记住用户偏好
- 🔍 根据需求推荐产品
- 📊 分析推荐理由
项目结构
langchain-demo/
├── src/
│ ├── index.js # 入口文件
│ ├── config.js # 配置
│ ├── knowledge.js # 知识库
│ ├── recommender.js # 推荐引擎
│ └── utils.js # 工具函数
├── data/
│ └── products.json # 产品数据
├── .env
└── package.json
1. 准备产品数据
// data/products.json
[
{
"id": 1,
"name": "MacBook Pro 16\"",
"category": "笔记本电脑",
"price": 14999,
"features": ["M3 芯片", "16GB 内存", "512GB SSD", "16 英寸 Liquid 视网膜屏"],
"suitable_for": ["专业开发", "视频编辑", "3D 渲染", "重度办公"],
"pros": ["性能强大", "屏幕优秀", "续航长"],
"cons": ["价格高", "重量大"]
},
{
"id": 2,
"name": "iPad Air",
"category": "平板",
"price": 4799,
"features": ["M2 芯片", "10.9 英寸", "支持 Apple Pencil", "5G 可选"],
"suitable_for": ["学习笔记", "绘画创作", "轻度办公", "娱乐"],
"pros": ["便携", "生态好", "屏幕优秀"],
"cons": ["生产力有限", "需要配件"]
},
{
"id": 3,
"name": "iPhone 15 Pro",
"category": "手机",
"price": 7999,
"features": ["A17 Pro 芯片", "钛金属边框", "4800 万像素", "Action 按钮"],
"suitable_for": ["日常使用", "摄影", "游戏", "商务"],
"pros": ["性能强", "拍照好", "系统流畅"],
"cons": ["价格高", "电池一般"]
},
{
"id": 4,
"name": "AirPods Pro 2",
"category": "耳机",
"price": 1899,
"features": ["主动降噪", "空间音频", "6 小时续航", "防水"],
"suitable_for": ["通勤", "运动", "办公", "听音乐"],
"pros": ["降噪强", "音质好", "佩戴舒适"],
"cons": ["价格高", "续航一般"]
},
{
"id": 5,
"name": "Dell XPS 15",
"category": "笔记本电脑",
"price": 11999,
"features": ["Intel i7", "16GB 内存", "1TB SSD", "4K OLED 屏"],
"suitable_for": ["办公", "设计", "编程", "多媒体"],
"pros": ["屏幕优秀", "性能均衡", "Windows 生态"],
"cons": ["续航一般", "风扇噪音"]
}
]
2. 构建知识库
// src/knowledge.js
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';
import { HNSWLib } from 'langchain/vectorstores/hnswlib';
import { OpenAIEmbeddings } from 'langchain/embeddings/openai';
import fs from 'fs';
import path from 'path';
class ProductKnowledgeBase {
constructor() {
this.products = JSON.parse(
fs.readFileSync(path.join(__dirname, '../data/products.json'), 'utf-8')
);
this.vectorStore = null;
}
// 将产品数据转换为文本
productsToText() {
return this.products.map(product => {
return `
产品名称:${product.name}
类别:${product.category}
价格:¥${product.price}
特性:${product.features.join('、')}
适合场景:${product.suitable_for.join('、')}
优点:${product.pros.join('、')}
缺点:${product.cons.join('、')}
`.trim();
}).join('\n\n---\n\n');
}
// 创建向量数据库
async createVectorStore() {
const text = this.productsToText();
// 分割文本
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 500,
chunkOverlap: 50
});
const documents = await splitter.createDocuments([text]);
// 创建 embeddings
const embeddings = new OpenAIEmbeddings();
// 创建向量存储
this.vectorStore = await HNSWLib.fromDocuments(documents, embeddings);
return this.vectorStore;
}
// 搜索相关产品
async search(query, k = 3) {
if (!this.vectorStore) {
await this.createVectorStore();
}
const similarDocs = await this.vectorStore.similaritySearch(query, k);
return similarDocs;
}
// 获取所有产品
getAllProducts() {
return this.products;
}
}
export default ProductKnowledgeBase;
3. 构建推荐引擎
// src/recommender.js
import { ChatOpenAI } from '@langchain/openai';
import { PromptTemplate } from 'langchain/prompts';
import { BufferMemory } from 'langchain/memory';
import { LLMChain } from 'langchain/chains';
import ProductKnowledgeBase from './knowledge.js';
class ProductRecommender {
constructor() {
this.llm = new ChatOpenAI({
temperature: 0.7,
model: 'gpt-4'
});
this.knowledgeBase = new ProductKnowledgeBase();
this.memory = new BufferMemory({
memoryKey: 'chat_history',
returnMessages: true
});
this.init();
}
async init() {
await this.knowledgeBase.createVectorStore();
}
// 创建推荐提示词
createPromptTemplate() {
return new PromptTemplate({
template: `你是一名专业的产品推荐顾问,名叫"小智"。
你的任务是根据用户的需求,从知识库中推荐最合适的产品。
对话历史:
{chat_history}
相关知识:
{context}
用户当前需求:
{input}
请按照以下格式回答:
## 🎯 推荐产品
**产品名称:** [产品名称]
**推荐理由:**
1. [理由 1]
2. [理由 2]
3. [理由 3]
**产品详情:**
- 价格:¥[价格]
- 核心特性:[列出 3 个核心特性]
- 适合场景:[列出适合的使用场景]
**优缺点分析:**
✅ 优点:[列出优点]
⚠️ 注意:[列出需要注意的地方]
**其他建议:**
[给出 1-2 个额外的购买建议或使用建议]
请用友好、专业的语气回答,让用户感受到你的诚意和专业性。`,
inputVariables: ['chat_history', 'context', 'input']
});
}
// 推荐产品
async recommend(userInput) {
// 1. 搜索相关知识
const relevantDocs = await this.knowledgeBase.search(userInput, 3);
const context = relevantDocs.map(doc => doc.pageContent).join('\n\n');
// 2. 获取对话历史
const history = await this.memory.loadMemoryVariables({});
const chatHistory = history.chat_history
.map(msg => `${msg.getType()}: ${msg.content}`)
.join('\n');
// 3. 构建提示词
const prompt = this.createPromptTemplate();
// 4. 创建链
const chain = new LLMChain({
llm: this.llm,
prompt,
memory: this.memory
});
// 5. 调用链
const response = await chain.call({
input: userInput,
context: context || '暂无相关知识',
chat_history: chatHistory || '暂无对话历史'
});
return response.text;
}
// 重置记忆
resetMemory() {
this.memory.clear();
}
}
export default ProductRecommender;
4. 主程序入口
// src/index.js
import ProductRecommender from './recommender.js';
import readline from 'readline';
const recommender = new ProductRecommender();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log('🤖 欢迎使用智能产品推荐助手!');
console.log('💡 输入"退出"结束对话,输入"清空"重置记忆\n');
async function main() {
while (true) {
const question = await new Promise(resolve => {
rl.question('👤 你:', resolve);
});
if (question.toLowerCase() === '退出') {
console.log('\n👋 感谢使用,再见!');
rl.close();
process.exit(0);
}
if (question.toLowerCase() === '清空') {
recommender.resetMemory();
console.log('🧹 记忆已清空\n');
continue;
}
try {
console.log('\n🤖 小智:正在思考...\n');
const answer = await recommender.recommend(question);
console.log(answer + '\n');
} catch (error) {
console.error('❌ 出错了:', error.message);
}
}
}
// 等待知识库初始化
recommender.init().then(() => {
main();
}).catch(error => {
console.error('初始化失败:', error);
process.exit(1);
});
5. 运行项目
# 添加 shebang 或配置 package.json
npm start
package.json:
{
"type": "module",
"scripts": {
"start": "node src/index.js"
}
}
🎯 四、项目亮点解析
1. 核心功能实现
| 功能 | LangChain 模块 | 作用 |
|---|---|---|
| 知识库检索 | VectorStore + Embeddings | 语义搜索相关产品 |
| 对话记忆 | BufferMemory | 记住用户偏好和历史 |
| 智能推荐 | LLMChain | 结合知识生成推荐 |
| 提示词管理 | PromptTemplate | 结构化输出 |
2. 关键代码解析
向量检索(RAG):
// 将产品描述转换为向量
const embeddings = new OpenAIEmbeddings();
const vectorStore = await HNSWLib.fromDocuments(documents, embeddings);
// 语义搜索
const similarDocs = await vectorStore.similaritySearch('我需要一台适合编程的电脑', 3);
记忆管理:
// 自动维护对话历史
const memory = new BufferMemory({
memoryKey: 'chat_history',
returnMessages: true
});
// 每次对话后自动更新
await chain.call({ input: question });
链式调用:
// 串联多个步骤
const chain = new LLMChain({
llm: this.llm, // 1. 选择模型
prompt, // 2. 使用提示词模板
memory: this.memory // 3. 维护记忆
});
🔧 五、进阶功能扩展
1. 添加工具(Tools)
让 AI 能调用外部功能:
import { Tool } from 'langchain/tools';
// 价格比较工具
class PriceComparisonTool extends Tool {
name = 'price_comparison';
description = '比较不同产品的价格';
async _call(input) {
const products = this.knowledgeBase.getAllProducts();
const sorted = products.sort((a, b) => a.price - b.price);
return sorted.map(p => `${p.name}: ¥${p.price}`).join('\n');
}
}
const tools = [new PriceComparisonTool(knowledgeBase)];
2. 使用 Agent 自主决策
import { initializeAgentExecutor } from 'langchain/agents';
const executor = await initializeAgentExecutor(
tools,
this.llm,
{ agentType: 'zero-shot-react-description' }
);
// Agent 会自动决定使用哪个工具
const result = await executor.run('帮我找最便宜的笔记本电脑,并比较它们的配置');
3. 添加多轮对话优化
import { ConversationSummaryMemory } from 'langchain/memory';
// 总结式记忆(适合长对话)
const memory = new ConversationSummaryMemory({
llm: this.llm,
memoryKey: 'chat_history'
});
4. 部署为 Web 服务
// 使用 Express 提供 API
import express from 'express';
const app = express();
app.post('/api/recommend', async (req, res) => {
const { question } = req.body;
const answer = await recommender.recommend(question);
res.json({ answer });
});
app.listen(3000, () => {
console.log('API 服务运行在 http://localhost:3000');
});
📊 六、LangChain vs 其他方案
| 方案 | 适用场景 | 复杂度 | 灵活性 |
|---|---|---|---|
| LangChain | 复杂 AI 应用 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 直接调用 API | 简单问答 | ⭐⭐ | ⭐⭐ |
| LlamaIndex | 数据密集型 RAG | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Haystack | 企业级搜索 | ⭐⭐⭐⭐ | ⭐⭐⭐ |
🎓 七、学习资源
✅ 总结
通过这个项目,我们学会了:
- ✅ LangChain 核心概念(LLM、Prompt、Chain、Memory、Tools、Agent)
- ✅ 构建 RAG 应用(向量检索 + 大模型)
- ✅ 对话记忆管理(BufferMemory)
- ✅ 提示词工程(PromptTemplate)
- ✅ 完整项目实战(智能产品推荐助手)
LangChain 不是「AI 胶水」,而是 AI 应用开发的「操作系统」!
它让你专注于业务逻辑,而不是重复造轮子。
🚀 下一步
- 尝试其他 Chain 类型(SequentialChain、RouterChain)
- 集成更多 Tools(搜索、计算器、数据库)
- 部署到生产环境(Docker + API)
- 添加用户认证(JWT + 数据库)
- 优化性能(缓存、批处理)
现在,轮到你动手实践了!🎉
如果觉得这篇文章对你有帮助,欢迎点赞、收藏、评论!也欢迎关注我,获取更多 AI 开发实战经验。
参考资料
作者:一名热爱 AI 应用开发的前端工程师
本文项目代码已开源,欢迎 Star 和 Fork!