Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,55 @@
|
|
|
|
1 |
from langchain.llms import HuggingFaceHub
|
2 |
from langchain.embeddings import SentenceTransformerEmbeddings
|
3 |
from langchain.vectorstores import FAISS
|
4 |
|
5 |
# 1. 初始化 Gemma 模型
|
6 |
-
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
# 2. 准备知识库数据
|
9 |
knowledge_base = [
|
10 |
"Gemma 是 Google 开发的大型语言模型。",
|
11 |
"Gemma 具有强大的自然语言处理能力。",
|
12 |
-
"Gemma 可以用于问答、对话、文本生成等任务。"
|
|
|
|
|
13 |
]
|
14 |
|
15 |
-
# 3. 构建向量数据库
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
18 |
|
19 |
# 4. 问答函数
|
20 |
def answer_question(question):
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
# 5.
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
from langchain.llms import HuggingFaceHub
|
3 |
from langchain.embeddings import SentenceTransformerEmbeddings
|
4 |
from langchain.vectorstores import FAISS
|
5 |
|
6 |
# 1. 初始化 Gemma 模型
|
7 |
+
try:
|
8 |
+
llm = HuggingFaceHub(repo_id="google/gemma-7b-it", model_kwargs={"temperature": 0.5, "max_length": 512})
|
9 |
+
except Exception as e:
|
10 |
+
st.error(f"Gemma 模型加载失败:{e}")
|
11 |
+
st.stop()
|
12 |
|
13 |
+
# 2. 准备知识库数据 (示例)
|
14 |
knowledge_base = [
|
15 |
"Gemma 是 Google 开发的大型语言模型。",
|
16 |
"Gemma 具有强大的自然语言处理能力。",
|
17 |
+
"Gemma 可以用于问答、对话、文本生成等任务。",
|
18 |
+
"Gemma 基于 Transformer 架构。",
|
19 |
+
"Gemma 支持多种语言。"
|
20 |
]
|
21 |
|
22 |
+
# 3. 构建向量数据库 (如果需要,仅构建一次)
|
23 |
+
try:
|
24 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-mpnet-base-v2")
|
25 |
+
db = FAISS.from_texts(knowledge_base, embeddings)
|
26 |
+
except Exception as e:
|
27 |
+
st.error(f"向量数据库构建失败:{e}")
|
28 |
+
st.stop()
|
29 |
|
30 |
# 4. 问答函数
|
31 |
def answer_question(question):
|
32 |
+
try:
|
33 |
+
question_embedding = embeddings.embed_query(question)
|
34 |
+
docs_and_scores = db.similarity_search_with_score(question_embedding)
|
35 |
+
context = "\n".join([doc.page_content for doc, _ in docs_and_scores])
|
36 |
+
prompt = f"请根据以下知识库回答问题:\n{context}\n问题:{question}"
|
37 |
+
answer = llm(prompt)
|
38 |
+
return answer
|
39 |
+
except Exception as e:
|
40 |
+
st.error(f"问答过程出错:{e}")
|
41 |
+
return "An error occurred during the answering process."
|
42 |
|
43 |
+
# 5. Streamlit 界面
|
44 |
+
st.title("Gemma 知识库问答系统")
|
45 |
+
|
46 |
+
question = st.text_area("请输入问题", height=100)
|
47 |
+
|
48 |
+
if st.button("提交"):
|
49 |
+
if not question:
|
50 |
+
st.warning("请输入问题!")
|
51 |
+
else:
|
52 |
+
with st.spinner("正在查询..."):
|
53 |
+
answer = answer_question(question)
|
54 |
+
st.write("答案:")
|
55 |
+
st.write(answer)
|