Upload 2 files
Browse files- app.py +115 -0
- requirements.txt +12 -0
app.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
from langchain.chains import RetrievalQA
|
| 5 |
+
from langchain_community.vectorstores import FAISS
|
| 6 |
+
from datasets import load_dataset
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import os
|
| 11 |
+
import subprocess
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
|
| 14 |
+
# Function to load model, tokenizer, and dataset only once
|
| 15 |
+
@st.cache_resource # This decorator caches the loading process
|
| 16 |
+
def load_resources():
|
| 17 |
+
load_dotenv()
|
| 18 |
+
|
| 19 |
+
# huggingface_token = st.secrets["huggingface"]["token"]
|
| 20 |
+
|
| 21 |
+
# Set the environment variable using os
|
| 22 |
+
huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
|
| 23 |
+
|
| 24 |
+
# Run the huggingface-cli login command from the Python script using subprocess
|
| 25 |
+
subprocess.run(["huggingface-cli", "login", "--token", huggingface_token])
|
| 26 |
+
# Load the pre-trained Llama3 model (or your fine-tuned model)
|
| 27 |
+
# model_name = "meta-llama/Meta-Llama-3-8B-Instruct" # Replace with your fine-tuned model path or model name from Hugging Face
|
| 28 |
+
# tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 29 |
+
# model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 30 |
+
|
| 31 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
|
| 32 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
|
| 33 |
+
# Load your dataset (this is just an example, replace with your actual dataset)
|
| 34 |
+
dataset = load_dataset('qiaojin/PubMedQA', 'pqa_artificial') # Replace with the Hugging Face dataset name
|
| 35 |
+
|
| 36 |
+
# Dataset preprocessing (assuming the dataset is a Q&A dataset with columns 'question', 'answer', 'context')
|
| 37 |
+
df = pd.DataFrame(dataset['train']) # Replace 'train' with your dataset split
|
| 38 |
+
df = df.sample(10000) # Sample a subset of the dataset for faster processing
|
| 39 |
+
# Embed the context (documents)
|
| 40 |
+
embedding_model_name = "sentence-transformers/all-MiniLM-L6-v2"
|
| 41 |
+
embedder = SentenceTransformer(embedding_model_name)
|
| 42 |
+
|
| 43 |
+
# Create embeddings for the context
|
| 44 |
+
document_embeddings = embedder.encode(df['context'].tolist(), convert_to_tensor=True)
|
| 45 |
+
|
| 46 |
+
# Create FAISS index
|
| 47 |
+
faiss_index = FAISS.from_embeddings(document_embeddings)
|
| 48 |
+
|
| 49 |
+
# Create the retrieval chain with LangChain
|
| 50 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 51 |
+
llm=model,
|
| 52 |
+
retriever=faiss_index.as_retriever(),
|
| 53 |
+
return_source_documents=True
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Return the loaded resources
|
| 57 |
+
return model, tokenizer, dataset, faiss_index, qa_chain
|
| 58 |
+
|
| 59 |
+
# Load resources only once and cache them
|
| 60 |
+
if "model" not in st.session_state:
|
| 61 |
+
with st.spinner("Loading the model and dataset... Please wait!"):
|
| 62 |
+
model, tokenizer, dataset, faiss_index, qa_chain = load_resources()
|
| 63 |
+
|
| 64 |
+
# Store the loaded resources in session state
|
| 65 |
+
st.session_state.model = model
|
| 66 |
+
st.session_state.tokenizer = tokenizer
|
| 67 |
+
st.session_state.dataset = dataset
|
| 68 |
+
st.session_state.faiss_index = faiss_index
|
| 69 |
+
st.session_state.qa_chain = qa_chain
|
| 70 |
+
|
| 71 |
+
# Initialize Streamlit session state for memory
|
| 72 |
+
if "conversation_history" not in st.session_state:
|
| 73 |
+
st.session_state.conversation_history = []
|
| 74 |
+
|
| 75 |
+
# Streamlit UI Setup
|
| 76 |
+
st.title("Llama3-based Chatbot with RAG and Contextual Memory")
|
| 77 |
+
st.write("Ask a question, and I will provide two possible answers for you to choose from.")
|
| 78 |
+
|
| 79 |
+
# User input for the query
|
| 80 |
+
user_query = st.text_input("Your Query:", "")
|
| 81 |
+
|
| 82 |
+
if user_query:
|
| 83 |
+
with st.spinner("Getting two possible answers..."):
|
| 84 |
+
# Retrieve context using FAISS (document retrieval)
|
| 85 |
+
result = st.session_state.qa_chain.run(user_query)
|
| 86 |
+
|
| 87 |
+
# Show two possible responses (you can adjust this to get two different answers)
|
| 88 |
+
possible_answers = [
|
| 89 |
+
result['result'], # First possible answer from model
|
| 90 |
+
result['result'] # Duplicate for simplicity - in real cases, generate two variations (use different methods or prompt variations)
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
# Save the current user query and model responses to the conversation history
|
| 94 |
+
st.session_state.conversation_history.append({"question": user_query, "answers": possible_answers})
|
| 95 |
+
|
| 96 |
+
# Show two responses for the user to choose from
|
| 97 |
+
st.write("Possible Answers:")
|
| 98 |
+
answer_1 = st.button("Answer 1: " + possible_answers[0], key="answer_1")
|
| 99 |
+
answer_2 = st.button("Answer 2: " + possible_answers[1], key="answer_2")
|
| 100 |
+
|
| 101 |
+
if answer_1:
|
| 102 |
+
st.write(f"You selected Answer 1: {possible_answers[0]}")
|
| 103 |
+
# Continue the conversation with the selected answer
|
| 104 |
+
st.session_state.conversation_history.append({"question": "Answer 1 selected", "answers": [possible_answers[0]]})
|
| 105 |
+
|
| 106 |
+
if answer_2:
|
| 107 |
+
st.write(f"You selected Answer 2: {possible_answers[1]}")
|
| 108 |
+
# Continue the conversation with the selected answer
|
| 109 |
+
st.session_state.conversation_history.append({"question": "Answer 2 selected", "answers": [possible_answers[1]]})
|
| 110 |
+
|
| 111 |
+
# Show the conversation history (for debug purposes, can be removed in production)
|
| 112 |
+
st.write("Conversation History:")
|
| 113 |
+
for conversation in st.session_state.conversation_history:
|
| 114 |
+
st.write(f"Question: {conversation['question']}")
|
| 115 |
+
st.write(f"Answers: {conversation['answers']}")
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
langchain
|
| 3 |
+
langchain-community
|
| 4 |
+
bitsandbytes
|
| 5 |
+
python-dotenv
|
| 6 |
+
transformers
|
| 7 |
+
torch
|
| 8 |
+
faiss-cpu
|
| 9 |
+
sentence-transformers
|
| 10 |
+
datasets
|
| 11 |
+
numpy
|
| 12 |
+
pandas
|