Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from langchain.vectorstores import FAISS
|
| 3 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 4 |
+
from langchain.chains import RetrievalQA
|
| 5 |
+
from langchain.llms import HuggingFacePipeline
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
|
| 8 |
+
# ---------------- LOAD EMBEDDINGS ----------------
|
| 9 |
+
embeddings = HuggingFaceEmbeddings(
|
| 10 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
# ---------------- LOAD VECTOR STORE ----------------
|
| 14 |
+
db = FAISS.load_local(
|
| 15 |
+
"vectorstore/faiss_index",
|
| 16 |
+
embeddings,
|
| 17 |
+
allow_dangerous_deserialization=True
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
# ---------------- LOAD LLM ----------------
|
| 21 |
+
generator = pipeline(
|
| 22 |
+
"text-generation",
|
| 23 |
+
model="mistralai/Mistral-7B-Instruct-v0.2",
|
| 24 |
+
max_new_tokens=512,
|
| 25 |
+
temperature=0.2,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
llm = HuggingFacePipeline(pipeline=generator)
|
| 29 |
+
|
| 30 |
+
# ---------------- RAG CHAIN ----------------
|
| 31 |
+
qa = RetrievalQA.from_chain_type(
|
| 32 |
+
llm=llm,
|
| 33 |
+
retriever=db.as_retriever(search_kwargs={"k": 3}),
|
| 34 |
+
chain_type="stuff",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# ---------------- CHAT FUNCTION ----------------
|
| 38 |
+
def chat(query, history):
|
| 39 |
+
if not query.strip():
|
| 40 |
+
return history
|
| 41 |
+
|
| 42 |
+
answer = qa.run(query)
|
| 43 |
+
|
| 44 |
+
history.append((query, answer))
|
| 45 |
+
return history
|
| 46 |
+
|
| 47 |
+
# ---------------- GRADIO UI ----------------
|
| 48 |
+
with gr.Blocks(title="RAG Document Chatbot") as demo:
|
| 49 |
+
gr.Markdown(
|
| 50 |
+
"""
|
| 51 |
+
# 📚 RAG Document Chatbot
|
| 52 |
+
Answers are **strictly based on the provided documents**.
|
| 53 |
+
"""
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
chatbot = gr.Chatbot(height=400)
|
| 57 |
+
query_box = gr.Textbox(
|
| 58 |
+
placeholder="Ask a question from the documents...",
|
| 59 |
+
label="Your Question",
|
| 60 |
+
)
|
| 61 |
+
clear = gr.Button("Clear Chat")
|
| 62 |
+
|
| 63 |
+
query_box.submit(chat, [query_box, chatbot], chatbot)
|
| 64 |
+
clear.click(lambda: [], None, chatbot)
|
| 65 |
+
|
| 66 |
+
demo.launch()
|