Create rag.py
Browse files
rag.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sentence_transformers import SentenceTransformer
|
| 2 |
+
import faiss
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
embed_model = SentenceTransformer("BAAI/bge-small-zh-v1.5")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
index = faiss.read_index("index/family.faiss")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
with open("index/blocks.txt", "r", encoding="utf-8") as f:
|
| 14 |
+
raw = f.read()
|
| 15 |
+
blocks = raw.split("===")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
llm_name = "Qwen/Qwen2.5-1.5B"
|
| 19 |
+
tokenizer = AutoTokenizer.from_pretrained(llm_name)
|
| 20 |
+
model = AutoModelForCausalLM.from_pretrained(llm_name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
SYSTEM_PROMPT = "你是冯氏家谱机器人,只能根据给定资料回答,没有记载就说未记载。"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def ask(question):
|
| 27 |
+
q_emb = embed_model.encode([question], normalize_embeddings=True)
|
| 28 |
+
_, I = index.search(q_emb, 1)
|
| 29 |
+
context = blocks[I[0][0]]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
prompt = f"{SYSTEM_PROMPT}\n\n【家谱资料】\n{context}\n\n【问题】{question}\n回答:"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 36 |
+
outputs = model.generate(**inputs, max_new_tokens=200)
|
| 37 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|