KIRA111B commited on
Commit
816e8cd
·
verified ·
1 Parent(s): bb0d667

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -88
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
- # --- 2. 加载RAG核心管道 ---
20
- # 将所有耗时操作封装起来,只在应用启动时执行一次
21
  def load_rag_chain():
 
22
  print("开始加载RAG管道...")
23
-
24
- # 检查向量数据库是否存在
25
- if not os.path.exists(VECTOR_STORE_PATH):
26
- raise FileNotFoundError(
27
- f"错误:向量数据库文件夹 '{VECTOR_STORE_PATH}' 未找到!"
28
- "请确保你已经将本地生成的 'vector_store' 文件夹与 'app.py' 一起上传。"
29
- )
30
-
31
- # 加载Embedding模型
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
- # 创建完整的RAG问答链
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
- # 定义与Gradio界面交互的函数
100
- def predict(message, history):
101
- print(f"收到用户消息: '{message}'")
102
- if not message:
103
- return ""
104
- result = RAG_CHAIN.invoke({"query": message})
105
- response = result.get('result', "抱歉,处理时出现内部错误。").strip()
106
- print(f"模型生成回答: '{response}'")
107
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- # --- 4. 搭建并启动Gradio界面 ---
110
- with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background: linear-gradient(to right, #74ebd5, #ACB6E5)}") as demo:
111
  gr.Markdown("# 粤政云服务智能向导 - 我是粤小智 🤖")
112
- gr.ChatInterface(
113
- predict,
114
- title="粤小智客服",
115
- description="您好!可以向我提问关于粤政云平台使用的问题。",
116
- examples=["我想建个网站,该怎么申请服务器?", "如何重置我的云主机密码?", "我的应用访问变慢了怎么办?"]
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  )
118
 
119
- print("正在启动Garamio界面...")
120
- # 使用queue()可以处理并发请求,让应用更稳定
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()