Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py
|
| 2 |
import gradio as gr
|
| 3 |
from langchain.prompts import PromptTemplate
|
| 4 |
from langchain_community.embeddings import HuggingFaceBgeEmbeddings
|
|
@@ -7,68 +7,27 @@ from langchain.chains import RetrievalQA
|
|
| 7 |
from langchain_community.llms import LlamaCpp
|
| 8 |
from huggingface_hub import hf_hub_download
|
| 9 |
import os
|
|
|
|
| 10 |
|
| 11 |
-
# --- 1.
|
| 12 |
VECTOR_STORE_PATH = "vector_store"
|
| 13 |
EMBEDDING_MODEL = "BAAI/bge-large-zh-v1.5"
|
| 14 |
-
|
| 15 |
-
# 切换到 CapybaraHermes-2.5-Mistral-7B 模型
|
| 16 |
GGUF_MODEL_REPO = "TheBloke/CapybaraHermes-2.5-Mistral-7B-GGUF"
|
| 17 |
-
# 我们同样选择一个大小适中的4位量化版本
|
| 18 |
GGUF_MODEL_FILE = "capybarahermes-2.5-mistral-7b.Q4_K_M.gguf"
|
| 19 |
-
|
| 20 |
-
#
|
| 21 |
def load_rag_chain():
|
|
|
|
| 22 |
print("开始加载RAG管道...")
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
print(f"--> 正在加载Embedding模型: {EMBEDDING_MODEL}")
|
| 33 |
-
embeddings = HuggingFaceBgeEmbeddings(
|
| 34 |
-
model_name=EMBEDDING_MODEL,
|
| 35 |
-
model_kwargs={'device': 'cpu'},
|
| 36 |
-
encode_kwargs={'normalize_embeddings': True}
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
# 加载本地的FAISS向量数据库
|
| 40 |
-
print(f"--> 正在从 '{VECTOR_STORE_PATH}' 加载向量数据库...")
|
| 41 |
-
vector_store = FAISS.load_local(
|
| 42 |
-
VECTOR_STORE_PATH,
|
| 43 |
-
embeddings,
|
| 44 |
-
allow_dangerous_deserialization=True
|
| 45 |
-
)
|
| 46 |
-
|
| 47 |
-
# 从Hugging Face Hub下载GGUF模型文件
|
| 48 |
-
print(f"--> 开始下载/加载GGUF模型: {GGUF_MODEL_FILE} from {GGUF_MODEL_REPO}")
|
| 49 |
-
model_path = hf_hub_download(
|
| 50 |
-
repo_id=GGUF_MODEL_REPO,
|
| 51 |
-
filename=GGUF_MODEL_FILE,
|
| 52 |
-
local_dir="models", # 模型会下载到服务器的这个文件夹
|
| 53 |
-
local_dir_use_symlinks=False
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
# 初始化LlamaCpp模型加载器
|
| 57 |
-
print("--> 模型文件准备就绪,正在初始化LlamaCpp...")
|
| 58 |
-
llm = LlamaCpp(
|
| 59 |
-
model_path=model_path,
|
| 60 |
-
n_gpu_layers=0, # 强制在CPU上运行
|
| 61 |
-
n_batch=512, # 批处理大小
|
| 62 |
-
n_ctx=4096, # 上下文窗口大小
|
| 63 |
-
f16_kv=True, # 对性能有帮助
|
| 64 |
-
verbose=False # 设为False以保持日志干净
|
| 65 |
-
)
|
| 66 |
-
|
| 67 |
-
# 定义Prompt模板
|
| 68 |
-
prompt_template = """<|im_start|>systemYou are a helpful assistant named "粤小智". Answer the user's question based on the provided "Context".
|
| 69 |
-
Your answer should be in Chinese, clear, and step-by-step if it's an operation guide.
|
| 70 |
-
If you don't know the answer from the context, just say: "抱歉,关于您的问题,我的知识库暂时没有相关信息。". Do not make up answers.
|
| 71 |
-
<|im_end|>
|
| 72 |
<|im_start|>user
|
| 73 |
Context:
|
| 74 |
{context}
|
|
@@ -77,45 +36,60 @@ Question:
|
|
| 77 |
{question}<|im_end|>
|
| 78 |
<|im_start|>assistant
|
| 79 |
"""
|
| 80 |
-
|
| 81 |
PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
qa_chain = RetrievalQA.from_chain_type(
|
| 85 |
-
llm=llm,
|
| 86 |
-
chain_type="stuff",
|
| 87 |
-
retriever=vector_store.as_retriever(search_kwargs={"k": 3}), # 每次检索3个最相关的文档块
|
| 88 |
-
chain_type_kwargs={"prompt": PROMPT},
|
| 89 |
-
return_source_documents=False # 线上运行时不返回源文档
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
print("✅ RAG管道加载完毕,应用准备就绪!")
|
| 93 |
return qa_chain
|
| 94 |
|
| 95 |
-
# --- 3. Gradio应用逻辑 ---
|
| 96 |
-
# 在应用启动时,执行一次加载操作
|
| 97 |
RAG_CHAIN = load_rag_chain()
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
def
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
# --- 4.
|
| 110 |
-
with gr.Blocks(theme=gr.themes.Soft(), css="
|
| 111 |
gr.Markdown("# 粤政云服务智能向导 - 我是粤小智 🤖")
|
| 112 |
-
gr.
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
)
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
demo.launch()
|
|
|
|
| 1 |
+
# app.py (最终稳定版 - 使用 gr.Blocks)
|
| 2 |
import gradio as gr
|
| 3 |
from langchain.prompts import PromptTemplate
|
| 4 |
from langchain_community.embeddings import HuggingFaceBgeEmbeddings
|
|
|
|
| 7 |
from langchain_community.llms import LlamaCpp
|
| 8 |
from huggingface_hub import hf_hub_download
|
| 9 |
import os
|
| 10 |
+
import time
|
| 11 |
|
| 12 |
+
# --- 1. 配置 (保持不变) ---
|
| 13 |
VECTOR_STORE_PATH = "vector_store"
|
| 14 |
EMBEDDING_MODEL = "BAAI/bge-large-zh-v1.5"
|
|
|
|
|
|
|
| 15 |
GGUF_MODEL_REPO = "TheBloke/CapybaraHermes-2.5-Mistral-7B-GGUF"
|
|
|
|
| 16 |
GGUF_MODEL_FILE = "capybarahermes-2.5-mistral-7b.Q4_K_M.gguf"
|
| 17 |
+
|
| 18 |
+
# --- 2. 加载RAG管道 (保持不变) ---
|
| 19 |
def load_rag_chain():
|
| 20 |
+
# ... (这部分代码和之前完全一样,无需修改) ...
|
| 21 |
print("开始加载RAG管道...")
|
| 22 |
+
embeddings = HuggingFaceBgeEmbeddings(model_name=EMBEDDING_MODEL, model_kwargs={'device': 'cpu'}, encode_kwargs={'normalize_embeddings': True})
|
| 23 |
+
if not os.path.exists(VECTOR_STORE_PATH): raise FileNotFoundError(f"错误:向量数据库 '{VECTOR_STORE_PATH}' 不存在!")
|
| 24 |
+
vector_store = FAISS.load_local(VECTOR_STORE_PATH, embeddings, allow_dangerous_deserialization=True)
|
| 25 |
+
model_path = hf_hub_download(repo_id=GGUF_MODEL_REPO, filename=GGUF_MODEL_FILE, local_dir="models")
|
| 26 |
+
llm = LlamaCpp(model_path=model_path, n_gpu_layers=0, n_batch=512, n_ctx=4096, f16_kv=True, verbose=False)
|
| 27 |
+
prompt_template = """<|im_start|>system
|
| 28 |
+
You are a helpful assistant named "粤小智". Answer the user's question in Chinese based on the provided "Context".
|
| 29 |
+
If the context is not sufficient, just say: "抱歉,关于您的问题,我的知识库暂时没有相关信息。". Do not make up answers.
|
| 30 |
+
Your answer should be clear and step-by-step if it's an operation guide.<|im_end|>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
<|im_start|>user
|
| 32 |
Context:
|
| 33 |
{context}
|
|
|
|
| 36 |
{question}<|im_end|>
|
| 37 |
<|im_start|>assistant
|
| 38 |
"""
|
|
|
|
| 39 |
PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
| 40 |
+
qa_chain = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=vector_store.as_retriever(search_kwargs={"k": 3}), chain_type_kwargs={"prompt": PROMPT})
|
| 41 |
+
print("✅ RAG管道加载完毕!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
return qa_chain
|
| 43 |
|
| 44 |
+
# --- 3. Gradio应用逻辑 (修改以适配gr.Blocks) ---
|
|
|
|
| 45 |
RAG_CHAIN = load_rag_chain()
|
| 46 |
|
| 47 |
+
# history是Gradio自动管理的,格式为[ [user_msg1, bot_msg1], [user_msg2, bot_msg2], ... ]
|
| 48 |
+
def user(user_message, history):
|
| 49 |
+
# 将用户消息添加到聊天记录中,并返回一个空的输入框
|
| 50 |
+
return "", history + [[user_message, None]]
|
| 51 |
+
|
| 52 |
+
def bot(history):
|
| 53 |
+
# 获取最后一条用户消息
|
| 54 |
+
user_message = history[-1][0]
|
| 55 |
+
print(f"收到用户消息: '{user_message}'")
|
| 56 |
+
|
| 57 |
+
# 调用RAG链获取回答
|
| 58 |
+
result = RAG_CHAIN.invoke({"query": user_message})
|
| 59 |
+
bot_message = result.get('result', "处理出错").strip()
|
| 60 |
+
|
| 61 |
+
# 我们模拟打字效果,让体验更好
|
| 62 |
+
history[-1][1] = ""
|
| 63 |
+
for character in bot_message:
|
| 64 |
+
history[-1][1] += character
|
| 65 |
+
time.sleep(0.02) # 每个字之间暂停0.02秒
|
| 66 |
+
yield history
|
| 67 |
+
|
| 68 |
+
print(f"模型生成回答: '{history[-1][1]}'")
|
| 69 |
|
| 70 |
+
# --- 4. 搭建并启动界面 (使用gr.Blocks手动搭建) ---
|
| 71 |
+
with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}") as demo:
|
| 72 |
gr.Markdown("# 粤政云服务智能向导 - 我是粤小智 🤖")
|
| 73 |
+
chatbot = gr.Chatbot(
|
| 74 |
+
[],
|
| 75 |
+
elem_id="chatbot",
|
| 76 |
+
label="聊天窗口",
|
| 77 |
+
bubble_full_width=True,
|
| 78 |
+
height=600
|
| 79 |
+
)
|
| 80 |
+
with gr.Row():
|
| 81 |
+
txt = gr.Textbox(
|
| 82 |
+
scale=4,
|
| 83 |
+
show_label=False,
|
| 84 |
+
placeholder="在这里输入您的问题,然后按回车键...",
|
| 85 |
+
container=False,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# 定义回车或点击按钮后的事件流
|
| 89 |
+
txt.submit(user, [txt, chatbot], [txt, chatbot], queue=False).then(
|
| 90 |
+
bot, chatbot, chatbot
|
| 91 |
)
|
| 92 |
|
| 93 |
+
# 使用最简单的启动方式,但加入queue()来处理打字效果
|
| 94 |
+
demo.queue()
|
| 95 |
demo.launch()
|