CASELAW / app.py
talsen89's picture
Update app.py
e4f9452 verified
Raw History Blame Contribute Delete
5.46 kB
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.llms import HuggingFaceHub
from rank_bm25 import BM25Okapi
from sentence_transformers import util
import streamlit as st
import os
import dotenv
dotenv.load_dotenv()
class ChatBot():
DB_FAISS_PATH = r'db_faiss'
# Load HuggingFace Embeddings
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2",
model_kwargs={'device': 'cpu'}
)
# Load FAISS Vector Store
db = FAISS.load_local(
DB_FAISS_PATH,
embeddings,
allow_dangerous_deserialization=True
)
# Load LLM
repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
llm = HuggingFaceHub(
repo_id=repo_id,
model_kwargs={"temperature": 0.1, "top_p": 0.8, "top_k": 50},
huggingfacehub_api_token=os.getenv("")
)
# Prompt Template
from langchain.prompts import PromptTemplate
prompt_template = """
You are a teacher. The students will ask you a questions about their life. Use following piece of context to answer the question.
If you don't know the answer, just say you don't know.
You answer with LONG and concise answer and donot leave any sentence hanging.
Please also provide rulings where you get those answers from and also cite the case file while explaining.
Context: {context}
Question: {question}
Answer:
Answer:
"""
prompt = PromptTemplate(
template=prompt_template,
input_variables=["context", "question"]
)
def build_bm25_index(self):
"""
Build a BM25 index from documents stored in FAISS.
"""
# Retrieve all stored documents from FAISS
all_docs = self.db.docstore._dict.values()
self.doc_texts = [doc.page_content for doc in all_docs]
# Tokenize documents for BM25
self.tokenized_corpus = [doc.split() for doc in self.doc_texts]
self.bm25 = BM25Okapi(self.tokenized_corpus)
def hybrid_retrieve(self, query, top_k=5):
"""
Perform hybrid search using FAISS and BM25 and rank results.
"""
# FAISS (Vector) Search
faiss_retriever = self.db.as_retriever(search_kwargs={"k": 20})
faiss_docs = faiss_retriever.invoke(query)
faiss_doc_texts = [doc.page_content for doc in faiss_docs]
# BM25 (Keyword) Search
bm25_scores = self.bm25.get_scores(query.split())
# Create a dictionary of BM25 scores
bm25_dict = {self.doc_texts[i]: score for i, score in enumerate(bm25_scores)}
# Combine Scores (Weighted)
combined_scores = []
for doc_text in faiss_doc_texts:
# Vector Similarity (Cosine)
query_embedding = self.embeddings.embed_query(query)
doc_embedding = self.embeddings.embed_query(doc_text)
vector_score = util.cos_sim(query_embedding, doc_embedding).item()
# BM25 Score
keyword_score = bm25_dict.get(doc_text, 0)
# Weighted Combination
combined_score = (0.7 * vector_score) + (0.3 * keyword_score)
combined_scores.append((doc_text, combined_score))
# Rank by Combined Score
ranked_docs = sorted(combined_scores, key=lambda x: x[1], reverse=True)
# Return Top Results
best_contexts = [doc for doc, _ in ranked_docs[:top_k]]
return "\n".join(best_contexts)
def generate_answer(self, query):
"""
Generate an answer using hybrid search and the LLM.
"""
context = self.hybrid_retrieve(query)
if not context:
return "I don't know."
# Format the prompt
formatted_prompt = self.prompt.format(
context=context,
question=query
)
# Get LLM Response
response = self.llm.invoke(formatted_prompt)
return response
# Initialize Chatbot and Build BM25 Index
bot = ChatBot()
bot.build_bm25_index()
# ==============================
# Streamlit Chat Interface
# ==============================
st.set_page_config(page_title="Law Companion Assistant Chat Bot")
with st.sidebar:
st.title('📚 LAW GPT Chatbot')
# Function to generate a response
def generate_response(input_text):
return bot.generate_answer(input_text)
# Store conversation history
if "messages" not in st.session_state:
st.session_state.messages = [{"role": "assistant", "content": "Welcome, ask me anything!"}]
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
# User input and chatbot response
if input_text := st.chat_input("Ask your question..."):
st.session_state.messages.append({"role": "user", "content": input_text})
with st.chat_message("user"):
st.write(input_text)
# Generate response
with st.spinner("Thinking..."):
response = generate_response(input_text)
# Extract only answer
answer_index = response.find("Answer:")
answer = response[answer_index + len("Answer:"):].strip() if answer_index != -1 else response
# Store and display answer
st.session_state.messages.append({"role": "assistant", "content": answer})
with st.chat_message("assistant"):
st.write(answer)