ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

RAG 索引文档简单使用

RAG 索引文档简单使用 https://aipath.buynao.com/#/lesson/28-build-rag当前这个网页给出的RAG是openAI版本我自己本地使用是采用的deepseek的API,本文给出的是本地使用DEEPSEEK-API配置的实战RAG首先 模型的配置模型的配置最好采用终端配置法 windows 版本terminal$env:DEEPSEEK_API_KEYsk-你的API密钥mac/linux 版本exportDEEPSEEK_API_KEYsk-你的API密钥接下来是代码中需要修改的地方首先是模型的配置部分。第一clientOpenAI(api_keyos.environ[API_KEY])改为 clientOpenAI(api_keyos.environ.get(DEEPSEEK_API_KEY),base_urlhttps://api.deepseek.com)第二DeepSeek 没有对应的 embedding 向量模型因此网页中对应的 embedding 向量模型也需要替换。bash加载本地BGE向量模型emb_modelSentenceTransformer(BAAI/bge-small-zh)def load_chunks(path,chunk_size200,overlap50): textopen(path,r,encodingutf-8).read()texttext.replace(\r\n,\n).replace(\n\n,\n).strip()chunks,start[],0whilestartlen(text): endstart chunk_size chunktext[start:end].strip()ifchunk: chunks.append(chunk)startchunk_size - overlapreturnchunks其余部分基本不变最终代码如下所示# 文本切分块importosimportmath from openaiimportOpenAI from sentence_transformersimportSentenceTransformer# 加载本地BGE向量模型emb_modelSentenceTransformer(BAAI/bge-small-zh)def load_chunks(path,chunk_size200,overlap50): textopen(path,r,encodingutf-8).read()texttext.replace(\r\n,\n).replace(\n\n,\n).strip()chunks, start[],0whilestartlen(text): endstart chunk_size chunktext[start:end].strip()ifchunk: chunks.append(chunk)startchunk_size - overlapreturnchunks# DeepSeek客户端只用于对话问答client_deepseekOpenAI(api_keyos.environ.get(DEEPSEEK_API_KEY),base_urlhttps://api.deepseek.com)# 向量本地BGE不再调用OpenAIdef embed(text):ifnot text.strip(): raise ValueError(val.txt)embeddingemb_model.encode(text,normalize_embeddingsTrue)returnembedding.tolist()# 余弦相似度def cos_sim(a, b): dotsum(x * yforx, yinzip(a, b))namath.sqrt(sum(x * xforxina))nbmath.sqrt(sum(x * xforxinb))ifna0or nb0:return0.0returndot /(na * nb)# 检索问题变向量排序取top-kdef search(query,k3): q_vecembed(query)scored[(cos_sim(q_vec,v), c)forv, cinzip(vectors, chunks)]scored.sort(keylambda t: t[0],reverseTrue)returnscored[:k]# prompt调用DeepSeekdef ask(question): scored_chunkssearch(question)pieces[cforscore, cinscored_chunks]content\n---\n.join(pieces)respclient_deepseek.chat.completions.create(modeldeepseek-chat,messages[{role:system,content:仅根据下面提供的资料回答问题。资料里没有的信息直接回答[我不知道]不要编造任何外部知识。},{role:user,content:f[资料]\n{content}\n\n[问题]{question}}])returnresp.choices[0].message.contentif__name____main__:# 离线构建索引只执行一次chunksload_chunks(val.txt)print(f共切出 {len(chunks)} 块)vectors[embed(c)forcinchunks]print(向量构建完成可以开始提问输入exit退出\n)# 在线问答循环whileTrue: qinput(问: )ifq.strip()exit:breakprint(答: , ask(q))
返回列表