Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain.llms import HuggingFaceHub
|
| 2 |
+
from langchain.embeddings import SentenceTransformerEmbeddings
|
| 3 |
+
from langchain.vectorstores import FAISS
|
| 4 |
+
|
| 5 |
+
# 1. 初始化 Gemma 模型
|
| 6 |
+
llm = HuggingFaceHub(repo_id="google/gemma-7b-it", model_kwargs={"temperature": 0.5, "max_length": 512})
|
| 7 |
+
|
| 8 |
+
# 2. 准备知识库数据
|
| 9 |
+
knowledge_base = [
|
| 10 |
+
"Gemma 是 Google 开发的大型语言模型。",
|
| 11 |
+
"Gemma 具有强大的自然语言处理能力。",
|
| 12 |
+
"Gemma 可以用于问答、对话、文本生成等任务。"
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
# 3. 构建向量数据库
|
| 16 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-mpnet-base-v2")
|
| 17 |
+
db = FAISS.from_texts(knowledge_base, embeddings)
|
| 18 |
+
|
| 19 |
+
# 4. 问答函数
|
| 20 |
+
def answer_question(question):
|
| 21 |
+
question_embedding = embeddings.embed_query(question)
|
| 22 |
+
docs_and_scores = db.similarity_search_with_score(question_embedding)
|
| 23 |
+
context = "\n".join([doc.page_content for doc, _ in docs_and_scores])
|
| 24 |
+
prompt = f"请根据以下知识库回答问题:\n{context}\n问题:{question}"
|
| 25 |
+
answer = llm(prompt)
|
| 26 |
+
return answer
|
| 27 |
+
|
| 28 |
+
# 5. 测试
|
| 29 |
+
question = "Gemma 有哪些特点?"
|
| 30 |
+
answer = answer_question(question)
|
| 31 |
+
print(answer)
|