Loading video...
Loading video...
检索增强生成 (RAG) 使大型语言模型能够访问、理解和推理专有数据,而无需进行昂贵的微调或模型重新训练,从而彻底改变企业部署 AI 的方式。
🎯 RAG 是什么?
RAG 结合了两种强大的 AI 功能:
- 检索:语义搜索以从数据中查找相关信息
- 生成:使用检索到的上下文生成 LLM 支持的响应
这种方法使 AI 系统能够提供准确、基于您的企业知识的最新答案,同时保持大型语言模型的灵活性和推理能力。
🏗️ RAG 系统架构
1. 文档处理管道
Documents → Chunking → Embedding → Vector Store
// Example: Processing enterprise documents
const chunks = documentSplitter.split(document, {
chunkSize: 1000,
overlap: 200,
preserveContext: true
});
const embeddings = await embeddingModel.embed(chunks);
await vectorDB.insert(embeddings, metadata);2. 查询处理
User Query → Embed → Vector Search → Retrieve Top-K → LLM + Context → Response
// Example: Query processing
const queryEmbedding = await embeddingModel.embed(userQuery);
const relevantDocs = await vectorDB.search(queryEmbedding, {
topK: 5,
filters: { department: 'engineering' }
});
const response = await llm.generate({
prompt: userQuery,
context: relevantDocs,
temperature: 0.7
});3. 响应生成
LLM 使用检索到的上下文生成响应,确保准确性和相关性,同时保持自然语言质量。
💡 生产 RAG
的关键组件 1. 矢量数据库
企业的热门选择 RAG:
- Pinecone:托管、可扩展、非常适合生产
- Weaviate:开源、GraphQL API、混合搜索
- Qdrant:快速、开源、专为生产规模而构建
- Milvus:开源、GPU 加速、手柄数十亿个向量
- pgvector:PostgreSQL 扩展,熟悉的工具
2. 嵌入模型
根据您的要求选择:
- OpenAI text-embedding-3:高品质,3072 尺寸
- Cohere 嵌入:多语言,针对搜索进行优化
- BGE (BAAI):开源,SOTA 性能
- E5:微软开放型号,强检索
3. 分块策略
有效分块对于 RAG 性能至关重要:
- 固定大小分块:简单、可预测(500-1000 个令牌)
- 语义分块:拆分主题/部分
- 滑动窗口:用于上下文保存的重叠块
- 分层分块:长文档的多级
🚀 高级 RAG 技术
1. 混合搜索
将矢量搜索与传统关键字搜索相结合以获得最佳结果:
// Hybrid search implementation
const vectorResults = await vectorDB.search(queryEmbedding, { topK: 10 });
const keywordResults = await fullTextSearch(query, { topK: 10 });
// Reciprocal Rank Fusion
const combinedResults = reciprocalRankFusion(
vectorResults,
keywordResults,
{ k: 60 }
);2. 重新排名
通过跨编码器重新排名提高相关性:
const rerankedResults = await reranker.rerank({
query: userQuery,
documents: retrievedDocs,
topK: 5
});3. 查询扩展
生成多个查询变体以更好地回忆:
const expandedQueries = await llm.generate({
prompt: `Generate 3 variations of: ${userQuery}`,
temperature: 0.8
});
const allResults = await Promise.all(
expandedQueries.map(q => vectorDB.search(embed(q)))
);
const deduplicatedResults = deduplicate(allResults);4. 上下文压缩
从检索到的文档中删除不相关信息:
const compressedDocs = await contextualCompressor.compress({
query: userQuery,
documents: retrievedDocs,
maxTokens: 2000
});🎯 实际用例
1. 客户支持知识库
挑战:代理需要即时访问产品文档、政策和过去的解决方案。
解决方案:RAG 系统索引所有支持文档,使 AI 能够立即回答 80% 的查询。
结果:
- 平均处理时间减少 65%
- 客户满意度提高至 4.8/5
- 代理生产力提高 3 倍
2. 法律文件分析
挑战:律师花费大量时间研究判例法和合同。
解决方案:RAG 对数百万份法律文档进行引文跟踪。
结果:
- 研究时间从几小时缩短至几分钟
- 自动合同审核为每位律师每周节省 40 个小时
- 提高来源引用的准确性
3. DevOps 文档
挑战:工程师需要有关基础架构、运行手册和最佳实践的快速答案。
解决方案:RAG 系统涵盖所有 DevOps 文档、Confluence 页面和事件报告。
结果:
- 查找答案的时间缩短 75%
- 入门时间缩短 60%
- 事件解决速度提高 50%
🔒 企业 RAG 最佳实践
1. 数据隐私和安全
- 实施基于角色的访问控制 (RBAC)
- 加密静态和传输中的向量
- 对敏感数据使用私有部署
- 对所有查询实施审核日志记录
2. 质量和准确性
- 使用混合搜索(矢量 + 关键字)
- 实施相关性重新排名
- 添加引文/来源跟踪
- 监控和评估答案质量
- 关键决策的人机交互
3. 性能和规模
- 缓存频繁查询
- 使用近似最近邻 (ANN) 搜索
- 实施查询批处理
- 监控延迟并优化慢速路径
- 水平缩放矢量 DB
4. 评估指标
跟踪这些 KPI:
- 检索精度/召回率:我们是否找到了正确的文档?
- 答案准确性:答案是否正确?
- 延迟:从查询到响应的时间(目标:<2s)
- 用户满意度:赞成/反对反馈
- 每次查询成本:嵌入 + LLM + 基础设施成本
📊 性能基准
大规模生产 RAG 系统:
- 检索延迟:向量搜索 50-200ms
- 端到端延迟:1-3 秒,包括 LLM 一代
- 准确度:与人类专家相比,提高 85-95%
- 规模:处理数百万个文档、数千个并发用户
- 成本:每次查询 0.001-0.01 美元(比微调便宜 10-100 倍)
🛠️ 实现示例
带 Pinecone 和 OpenAI 的完整 RAG 系统:
import { OpenAI } from 'openai';
import { Pinecone } from '@pinecone-database/pinecone';
class EnterpriseRAG {
constructor() {
this.openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
this.pinecone = new Pinecone({ apiKey: process.env.PINECONE_API_KEY });
this.index = this.pinecone.index('enterprise-kb');
}
async ingest(documents) {
// 1. Chunk documents
const chunks = documents.flatMap(doc =>
this.chunkDocument(doc, { size: 1000, overlap: 200 })
);
// 2. Generate embeddings
const embeddings = await this.openai.embeddings.create({
model: 'text-embedding-3-large',
input: chunks.map(c => c.text)
});
// 3. Store in vector DB
await this.index.upsert(
chunks.map((chunk, i) => ({
id: chunk.id,
values: embeddings.data[i].embedding,
metadata: {
text: chunk.text,
source: chunk.source,
timestamp: Date.now()
}
}))
);
}
async query(question, options = {}) {
// 1. Embed query
const queryEmbedding = await this.openai.embeddings.create({
model: 'text-embedding-3-large',
input: question
});
// 2. Search vector DB
const searchResults = await this.index.query({
vector: queryEmbedding.data[0].embedding,
topK: options.topK || 5,
includeMetadata: true
});
// 3. Build context
const context = searchResults.matches
.map(match => match.metadata.text)
.join('
');
// 4. Generate response
const completion = await this.openai.chat.completions.create({
model: 'gpt-4-turbo-preview',
messages: [
{
role: 'system',
content: 'Answer based on the provided context. Cite sources.'
},
{
role: 'user',
content: `Context:
${context}
Question: ${question}`
}
],
temperature: 0.7
});
return {
answer: completion.choices[0].message.content,
sources: searchResults.matches.map(m => m.metadata.source),
confidence: searchResults.matches[0].score
};
}
}
// Usage
const rag = new EnterpriseRAG();
// Ingest documents
await rag.ingest(myDocuments);
// Query
const result = await rag.query(
'What is our incident response procedure?'
);
console.log(result.answer);
console.log('Sources:', result.sources);🔮 RAG 的未来
RAG 系统的新兴趋势:
- 多模式 RAG:结合文本、图像和视频
- 代理 RAG:可查询多个源并进行推理的 AI 代理
- 图形 RAG:利用知识图更好地检索
- 自适应 RAG:从用户反馈中学习的系统
- 实时 RAG:交互式应用的亚秒级延迟
📚 资源
准备好将您的企业数据转化为 AI 驱动的见解了吗?RAG 系统是准确、可扩展且经济高效的 AI 应用的基础。

Click to open in new window

Click to open in new window