选二改吧from langchain_community.vectorstores import FAISS from langchain_huggingface import HuggingFaceEmbeddings from langchain_core.documents import Document from langchain.chains import ConversationalRetrievalChain from langchain.prompts import PromptTemplate from langchain_community.llms import HuggingFacePipeline import torch from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline from langchain.memory import ConversationBufferMemory # ========== 1. 加载嵌入模型 ========== embeddings = HuggingFaceEmbeddings( model_name=r"C:\Users\Lenovo\rag_scrapydb\src\local_embeddings_cache\all-MiniLM-L6-v2" ) # ========== 2. 加载 FAISS 向量库 ========== VECTOR_STORE_PATH = r"C:\Users\Lenovo\rag_scrapydb\src\my_vectorstore" vectorstore = FAISS.load_local(VECTOR_STORE_PATH, embeddings=embeddings, allow_dangerous_deserialization=True) retriever = vectorstore.as_retriever(search_kwargs={"k": 3}) # 检索 top-3 文档 # ========== 3. 加载本地 LLM(以 ChatGLM 为例)========== model_path = r"C:\Users\Lenovo\rag_scrapydb\local_embeddings_cache\all-MiniLM-L6-v2" # 修改为你自己的模型路径 tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True).half().cuda() pipe = pipeline( "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=200, device=0, pad_token_id=tokenizer.eos_token_id # 避免警告 ) llm = HuggingFacePipeline(pipeline=pipe) # ========== 4. 定义 Prompt Template ========== prompt_template = """请基于以下提供的背景信息,回答用户的问题。如果无法找到相关信息,请说明原因。 历史对话: {chat_history} 背景信息: {context} 问题: {question} 请确保回答简洁清晰,并在回答末尾列出引用来源(网址)。 """ PROMPT = PromptTemplate( template=prompt_template, input_variables=["context", "question", "chat_history"] ) # ========== 5. 创建带记忆的 RAG Chain ========== memory = ConversationBufferMemory(memory_key="chat_history", input_key="question") qa_chain = ConversationalRetrievalChain.from_llm( llm=llm, retriever=retriever, combine_docs_chain_kwargs={"prompt": PROMPT}, memory=memory ) # ========== 6. 运行聊天交互 ========== def chat(): print("开始与 RAG 系统对话吧!输入 '退出' 结束程序。") while True: user_input = input("你:") if user_input.lower() in ['退出', 'exit', 'q']: break result = qa_chain.invoke({"question": user_input}) answer = result["answer"] # 提取引用链接 sources = set(doc.metadata.get('source', '') for doc in result["source_documents"] if doc.metadata.get('source')) source_str = "\n".join([f"[{i+1}] {s}" for i, s in enumerate(sources)]) print(f"助手:{answer}\n\n参考链接:\n{source_str}") if __name__ == "__main__": chat()
时间: 2025-08-31 16:19:04 AIGC 浏览: 23
你当前的代码中存在两个关键问题:
---
## ❌ 问题一:错误地将 Embedding 模型路径用作 LLM 模型
```python
model_path = r"C:\Users\Lenovo\rag_scrapydb\src\local_embeddings_cache\all-MiniLM-L6-v2"
```
你使用的是 **Sentence-BERT 类的嵌入模型**(`all-MiniLM-L6-v2`),它不能用于生成回答(LLM)。这类模型是为 FAISS 向量化检索服务的,不能作为语言模型进行文本生成。
---
## ❌ 问题二:`.half().cuda()` 导致 CUDA 错误
你尝试调用 `.cuda()`,但你的 PyTorch 不支持 CUDA,导致如下报错:
```
AssertionError: Torch not compiled with CUDA enabled
```
---
## ✅ 解决方案:只修改与 LLM 相关的部分(选二改)
我们保留你的 embedding、FAISS 和 prompt 部分不变,**只修改 LLM 加载部分**。以下是修正后的完整代码段:
---
## ✅ 改进后的 LLM 加载方式(使用 CPU + 本地 ChatGLM-6B)
### 前提条件:
你需要下载 `chatglm-6b` 模型,并将其放在以下路径(或你自己指定):
```
C:\models\chatglm-6b
```
该目录应包含:
```
chatglm-6b/
├── config.json
├── pytorch_model.bin
├── tokenizer_config.json
├── vocab.txt
└── ...其他文件
```
如果你还没有这个模型,请先下载(见最后相关问题)。
---
## ✅ 修改后的代码段(替换原第3部分)
```python
# ========== 3. 加载本地 LLM(以 ChatGLM-6B 为例)==========
model_path = r"C:\models\chatglm-6b" # 替换为你自己的 ChatGLM 模型路径
# 如果你没有 GPU,可以去掉 .half().cuda()
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
# 使用 CPU 加载模型
model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
max_new_tokens=200,
device=-1, # 强制使用 CPU
pad_token_id=tokenizer.eos_token_id
)
llm = HuggingFacePipeline(pipeline=pipe)
```
---
## 🧠 说明:
| 参数 | 说明 |
|------|------|
| `device=-1` | 表示使用 CPU |
| `max_new_tokens=200` | 控制输出长度 |
| `pad_token_id=tokenizer.eos_token_id` | 避免警告信息 |
---
## ✅ 完整流程图
```
用户输入 → 检索器从 FAISS 中查找 top-3 文档 → 结合历史对话和背景信息 → 交给 LLM 回答 → 输出答案 + 来源链接
```
---
## ✅ 测试运行结果示例
```
开始与 RAG 系统对话吧!输入 '退出' 结束程序。
你:什么是量子计算?
助手:量子计算是一种利用量子比特(qubit)进行计算的方法,能够并行处理大量数据...
参考链接:
[1] https://example.com/quantum-computing-intro
[2] https://example.com/quantum-bits
```
---
## ✅ 总结
| 原因 | 解决方法 |
|------|----------|
| 使用了 embedding 模型作为 LLM | 改用真正的 LLM 模型(如 ChatGLM-6B) |
| 缺少 CUDA 支持 | 改用 CPU 模式加载模型(`device=-1`) |
| 没有正确设置 tokenizer | 设置 `pad_token_id=tokenizer.eos_token_id` 避免警告 |
---
###
阅读全文
相关推荐


















