微信扫码
添加专属顾问
我要投稿
掌握RAG技术,构建高效智能助理。 核心内容: 1. RAG技术在动态领域的关键应用 2. RAG与微调、CAG的技术对比及机场场景选择 3. 生产级RAG管道的架构设计与代码实践
在人工智能领域,检索增强生成(Retrieval-Augmented Generation, RAG)正成为解决大语言模型(LLM)知识更新滞后、生成内容不可追溯等问题的关键技术。传统的微调(Fine-Tuning)方法将知识固化在模型参数中,难以应对动态领域的快速变化;而RAG通过将检索与生成解耦,实现了知识的实时更新与可追溯性,尤其适用于政策频繁变动、对准确性要求极高的场景,如医疗、法律和航空管理。
本文以构建机场智能助理为例,结合Google的Gemini多模态模型与Qdrant向量数据库,详细阐述如何设计并实现一个高可靠、可扩展的生产级RAG管道。内容涵盖架构设计原则、关键技术选型、数据管理策略及完整代码实现,旨在为开发者提供从理论到实践的全流程指导。
在启动RAG项目前,首先需要明确技术路线。图1对比了RAG、微调(Fine-Tuning)和缓存增强生成(CAG)三种方案的核心差异:
维度 | RAG | Fine-Tuning | CAG |
---|---|---|---|
知识更新 | |||
可追溯性 | |||
抗幻觉能力 | |||
适用场景 |
在机场场景中,安全协议、航班调度规则、海关政策等知识具有强时效性,且需严格遵循官方文件。因此:
机场智能助理需满足以下核心功能:
基于上述需求,设计如图2所示的五层架构:
rag:cache:{interactionId}:{queryHash}
,有效期设置为1小时。gemini-2.5-pro-preview
版本,支持同时生成两种响应:/ask
端点,接收包含message
、context
(位置、情绪等)和interactionId
的JSON请求,返回双模式响应。文档分块的粒度直接影响检索精度。采用滑动窗口分块法,设置块大小为1000-1500 tokens,重叠率20%,确保跨段落语义连贯。代码实现如下:
const chunkText = (text) => {
const cleanText = text.replace(/(\r\n|\n|\r)+/g, " ").replace(/\s+/g, " ").trim();
const maxSize = 1500; // 约等于500英文单词或1000中文字符
const regex = new RegExp(`.{1,${maxSize}}(\\s|$)`, "g");
return cleanText.match(regex) || [];
};
使用Gemini的专用嵌入模型gemini-embedding-exp-03-07
,针对检索场景优化。每个文档块生成3072维向量,代码如下:
const { GoogleGenAI } = require("@google/generative-ai");
const genAI = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const getEmbeddings = async (chunks) => {
const embeddings = [];
for (const chunk of chunks) {
const response = await genAI.embedContent({
model: "models/gemini-embedding-exp-03-07",
content: chunk,
taskType: "retrieval_document", // 明确任务类型为文档检索
});
embeddings.push(response.embedding);
}
return embeddings;
};
提示工程是控制Gemini输出的核心手段。针对机场场景设计两类提示模板:
This is an airport scenario. Provide protocol steps for: "${user_query}".
Context: ${retrieved_documents}
Conversation History: ${last_12_messages}
Guest Profile: ${profile}, Location: ${location}, Mood: ${mood}
Response Requirements:
1. Strictly based on provided context
2. Use numbered list
3. Under 300 words
This is an airport scenario. Help staff respond to: "${user_query}".
Focus on improving guest experience for ${profile} at ${location}.
Context: ${retrieved_documents}
Conversation History: ${last_12_messages}
Response Requirements:
1. Friendly tone with emojis
2. Highlight key actions in bold
3. Under 100 words
4. Use Markdown formatting
对于非实时场景(如每周知识库更新),采用消息队列(如RabbitMQ)解耦数据处理流程:
const { QdrantClient } = require("@qdrant/js-client-rest");
const client = new QdrantClient({ url: "http://localhost:6333" }); // 本地部署地址
// 确保集合存在,向量维度与Gemini输出一致
const ensureCollectionExists = async () => {
const exists = await client.collectionExists("airport-protocols");
if (!exists) {
await client.createCollection("airport-protocols", {
vectors: { size: 3072, distance: "Cosine" }, // 使用余弦相似度
sharding: { key: "document_id" }, // 按文档ID分片,提升多文档检索效率
});
}
};
// 批量插入向量(支持一次处理多个文档块)
const upsertVectors = async (documentId, chunks, embeddings) => {
await ensureCollectionExists();
const points = chunks.map((chunk, index) => ({
id: `${documentId}-${index}`, // 唯一标识符
vector: embeddings[index],
payload: { text: chunk, document_id: documentId, source: "official-sop" }, // 附加元数据
}));
await client.upsert("airport-protocols", { points, wait: true }); // wait=true确保操作完成
};
const fs = require("fs");
const pdf = require("pdf-parse");
// 解析PDF并生成向量存入Qdrant
const processPDF = async (filePath, documentId) => {
// 1. 解析PDF文本
const text = await extractTextFromPDF(filePath);
// 2. 分块处理
const chunks = chunkText(text);
// 3. 生成嵌入向量
const embeddings = await getEmbeddings(chunks);
// 4. 存入向量数据库
await upsertVectors(documentId, chunks, embeddings);
console.log(`Processed ${chunks.length} chunks for document ${documentId}`);
};
const extractTextFromPDF = async (filePath) => {
const data = fs.readFileSync(filePath);
const pdfData = await pdf(data);
if (!pdfData.text) throw new Error("Invalid PDF file");
return pdfData.text;
};
const queryGemini = async (userQuery, context, interactionId) => {
// 1. 生成查询向量
const queryEmbedding = (await getEmbeddings([userQuery]))[0];
// 2. 向量检索
const results = await client.query("airport-protocols", {
query: queryEmbedding,
limit: 3,
with_payload: true,
});
const relevantChunks = results.points.map(p => p.payload.text).join("\n\n");
// 3. 获取对话历史(最多12轮)
const history = await getConversationHistory(interactionId, 12);
// 4. 生成双模式提示
const protocolPrompt = buildProtocolPrompt(userQuery, relevantChunks, context, history);
const experiencePrompt = buildExperiencePrompt(userQuery, relevantChunks, context, history);
// 5. 并行调用Gemini(提升效率)
const [protocolResp, experienceResp] = await Promise.all([
genAI.generateContent({
model: "models/gemini-2.5-pro-preview",
contents: [{ role: "user", parts: [{ text: protocolPrompt }] }],
generationConfig: { temperature: 0.1 } // 低温度确保输出确定性
}),
genAI.generateContent({
model: "models/gemini-2.5-pro-preview",
contents: [{ role: "user", parts: [{ text: experiencePrompt }] }],
generationConfig: { temperature: 0.7 } // 高温度增加灵活性
})
]);
return {
protocol: protocolResp.text.trim(),
experience: experienceResp.text.trim(),
sources: results.points.map(p => p.payload.document_id) // 返回引用文档ID
};
};
document_id
字段创建payload索引,加速按文档过滤查询。指标 | 工具 | 阈值 | 报警策略 |
---|---|---|---|
对于多机场集团,可采用联邦学习模式:
通过机场智能助理的实践,总结生产级RAG系统的设计要点:
RAG技术的价值不仅在于解决LLM的固有缺陷,更在于构建可进化的智能系统——通过持续优化数据管道和提示策略,企业能够以更低成本适应业务需求的快速变化。随着Gemini等多模态模型的迭代,RAG将在更多垂直领域(如智能制造、智慧医疗)释放更大潜力。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-05-31
RAG(检索增强生成):提升大语言模型性能的终极指南
2025-05-31
DO-RAG:一种使用知识图谱增强检索辅助生成的领域特定问答框架 - 清华大学等
2025-05-30
2025年GitHub上十大RAG框架深度解析:从技术原理到实战应用
2025-05-30
90%企业不知道的RAG优化秘籍:Dify原生集成RAGflow (2)
2025-05-30
RAG其实并没有你想的那么简单,Late Chunking vs Contextual Retrieval解决上下文难题
2025-05-30
RAG和向量数据库之间有什么关系?
2025-05-30
RAG相关术语快速了解
2025-05-29
超越基础:Agentic Chunking 如何彻底改变 RAG?
2024-10-27
2024-09-04
2024-05-05
2024-07-18
2024-06-20
2024-06-13
2024-07-09
2024-07-09
2024-05-19
2024-07-07
2025-05-30
2025-05-29
2025-05-29
2025-05-23
2025-05-16
2025-05-15
2025-05-14
2025-05-14