Pudding48 commited on
Commit
80b4f3b
·
verified ·
1 Parent(s): 223af84

Initialize

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tinyllama-1.1b-chat-v1.0.Q8_0.gguf filter=lfs diff=lfs merge=lfs -text
backend.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend.py
2
+ from fastapi import FastAPI, Request
3
+ from pydantic import BaseModel
4
+ from qabot import llm_chain
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+
7
+ app = FastAPI()
8
+
9
+ # Allow CORS for local frontend testing
10
+ app.add_middleware(
11
+ CORSMiddleware,
12
+ allow_origins=["*"],
13
+ allow_methods=["*"],
14
+ allow_headers=["*"],
15
+ )
16
+
17
+ class Query(BaseModel):
18
+ query: str
19
+
20
+ @app.post("/ask")
21
+ async def ask_question(query: Query):
22
+ answer = llm_chain.invoke({"query": query.query})
23
+ return {"answer": answer["result"]}
prepare_vector_dp.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter
2
+ from langchain_community.document_loaders import PyPDFLoader, DirectoryLoader
3
+ from langchain_community.vectorstores import FAISS
4
+ from langchain_community.embeddings import GPT4AllEmbeddings
5
+
6
+ # Khai bao bien
7
+ pdf_data_path = "data"
8
+ vector_dp_path = "vectorstores/db_faiss"
9
+
10
+ # Ham 1. Tao ra vector DB tu 1 doan text
11
+ def create_db_from_text():
12
+ raw_text = "Trường Đại học Khoa học – Đại học Huế là một trong những cơ sở đào tạo và nghiên cứu hàng đầu tại khu vực miền Trung và Tây Nguyên. Được thành lập từ năm 1957, trường có bề dày truyền thống trong giảng dạy các ngành khoa học tự nhiên, xã hội và nhân văn. Với đội ngũ giảng viên giàu kinh nghiệm, cơ sở vật chất hiện đại và môi trường học tập năng động, Trường Đại học Khoa học luôn là lựa chọn uy tín của sinh viên trong và ngoài nước. Trường hiện tọa lạc tại số 77 Nguyễn Huệ, thành phố Huế – trung tâm văn hóa, giáo dục lớn của cả nước."
13
+
14
+ text_splitter = CharacterTextSplitter(
15
+ separator="\n",
16
+ chunk_size=512,
17
+ chunk_overlap=50,
18
+ length_function=len
19
+ )
20
+
21
+ chunks = text_splitter.split_text(raw_text)
22
+
23
+ # Embeding
24
+ embedding_model = GPT4AllEmbeddings(model_file= "model/tinyllama-1.1b-chat-v1.0.Q8_0.gguf")
25
+
26
+ # Dua vao Faiss Vector DB
27
+ db = FAISS.from_texts(texts=chunks, embedding=embedding_model)
28
+ db.save_local(vector_dp_path)
29
+ return db
30
+
31
+ def create_dp_from_files():
32
+ # Khai bao loader de quet toan bo thu muc data
33
+ loader = DirectoryLoader(pdf_data_path, glob="*.pdf",loader_cls=PyPDFLoader)
34
+ documents = loader.load()
35
+
36
+ text_splitter = CharacterTextSplitter(chunk_size = 512, chunk_overlap = 50)
37
+ chunks = text_splitter.split_documents(documents)
38
+
39
+ embedding_model = GPT4AllEmbeddings(model_file = "model/tinyllama-1.1b-chat-v1.0.Q8_0.gguf")
40
+ dp = FAISS.from_documents(chunks, embedding_model)
41
+ dp.save_local(vector_dp_path)
42
+ return dp
43
+
44
+ # create_db_from_text()
45
+ create_dp_from_files()
qabot.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.llms import CTransformers
2
+ from langchain.prompts import PromptTemplate
3
+ from langchain_core.runnables import RunnableSequence
4
+ from langchain.chains import RetrievalQA
5
+ from langchain_community.embeddings import GPT4AllEmbeddings
6
+ from langchain_community.vectorstores import FAISS
7
+
8
+ # Cấu hình
9
+ model_file = "model/tinyllama-1.1b-chat-v1.0.Q8_0.gguf"
10
+ vector_dp_path = "vectorstores/db_faiss"
11
+
12
+ # Load LLM
13
+ def load_llm(model_file):
14
+ llm = CTransformers(
15
+ model=model_file,
16
+ model_type="llama",
17
+ temperature=0.01,
18
+ config={'gpu_layers': 0},
19
+ max_new_tokens=128,
20
+ context_length=512
21
+ )
22
+ return llm
23
+
24
+ # Tạo prompt template
25
+ def creat_prompt(template):
26
+ prompt = PromptTemplate(template=template, input_variables=["context","question"])
27
+ return prompt
28
+
29
+ # Tạo pipeline chain (thay cho LLMChain)
30
+ def create_qa_chain(prompt, llm, db):
31
+ llm_chain = RetrievalQA.from_chain_type(
32
+ llm = llm,
33
+ chain_type = "stuff",
34
+ retriever =db.as_retriever(search_kwargs = {"k":1}),
35
+ return_source_documents = False,
36
+ chain_type_kwargs={'prompt':prompt}
37
+ )
38
+ return llm_chain
39
+
40
+ def read_vector_db():
41
+ embedding_model = GPT4AllEmbeddings(model_file = "model/all-minilm-l6-v2-q4_0.gguf")
42
+ db = FAISS.load_local(vector_dp_path, embedding_model,allow_dangerous_deserialization=True)
43
+ return db
44
+
45
+ db = read_vector_db()
46
+ llm = load_llm(model_file)
47
+ # Mẫu prompt
48
+ template = """<|im_start|>system\nSử dụng thông tin sau đây để trả lời câu hỏi. Nếu bạn không biết câu trả lời, hãy nói không biết, đừng cố tạo ra câu trả lời\n
49
+ {context}<|im_end|>\n<|im_start|>user\n{question}<|im_end|>\n<|im_start|>assistant"""
50
+
51
+ # Khởi tạo các thành phần
52
+ prompt = creat_prompt(template)
53
+ llm_chain =create_qa_chain(prompt, llm, db)
54
+
55
+ # Chạy thử chain
56
+ question = "Khoa công nghệ thông tin thành lập năm nào ?"
57
+ response = llm_chain.invoke({"query": question})
58
+ print(response)
tinyllama-1.1b-chat-v1.0.Q8_0.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4c9bb1dbaa372f6381a035fa5c02ef087aaa1ff1f843a56a22328114f03fc59
3
+ size 1170781568