Qanoon-Bot / app.py
annas4421's picture
Upload 3 files
346b8db verified
raw
history blame
5.39 kB
from langchain_community.document_loaders import PyPDFLoader,DirectoryLoader
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
import os
from langchain.vectorstores import Chroma
loader = DirectoryLoader('/content/data', glob="./*.pdf", loader_cls=PyPDFLoader)
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=200)
texts = text_splitter.split_documents(documents)
embeddings = HuggingFaceEmbeddings(model_name="nomic-ai/nomic-embed-text-v1",model_kwargs={"trust_remote_code":True,"revision":"289f532e14dbbbd5a04753fa58739e9ba766f3c7"})
vectordb = Chroma.from_documents(texts, embedding=embeddings, persist_directory="./data")
from langchain.llms import HuggingFaceHub
from langchain.prompts import PromptTemplate
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain.prompts import PromptTemplate
from langchain_together import Together
import os
from langchain.memory import ConversationBufferWindowMemory
from langchain.chains import ConversationalRetrievalChain
import streamlit as st
import time
st.set_page_config(page_title="LawGPT")
col1, col2, col3 = st.columns([1,4,1])
with col2:
st.image("https://s3.ap-south-1.amazonaws.com/makerobosfastcdn/cms-assets/Legal_AI_Chatbot.png")
st.markdown(
"""
<style>
div.stButton > button:first-child {
background-color: #ffd0d0;
}
div.stButton > button:active {
background-color: #ff6262;
}
div[data-testid="stStatusWidget"] div button {
display: none;
}
.reportview-container {
margin-top: -2em;
}
#MainMenu {visibility: hidden;}
.stDeployButton {display:none;}
footer {visibility: hidden;}
#stDecoration {display:none;}
button[title="View fullscreen"]{
visibility: hidden;}
</style>
""",
unsafe_allow_html=True,
)
def reset_conversation():
st.session_state.messages = []
st.session_state.memory.clear()
if "messages" not in st.session_state:
st.session_state.messages = []
if "memory" not in st.session_state:
st.session_state.memory = ConversationBufferWindowMemory(k=2, memory_key="chat_history",return_messages=True)
embeddings = HuggingFaceEmbeddings(model_name="nomic-ai/nomic-embed-text-v1",model_kwargs={"trust_remote_code":True,"revision":"289f532e14dbbbd5a04753fa58739e9ba766f3c7"})
#db=FAISS.load_local("/content/ipc_vector_db", embeddings, allow_dangerous_deserialization=True)
db_retriever =vectordb.as_retriever(search_type="similarity",search_kwargs={'k':4})
prompt_template = """<s>[INST]This is a chat template and As a legal chat bot specializing in pakistan Penal Code queries and , your primary objective is to provide accurate and concise information based on the user's questions. Do not generate your own questions and answers. You will adhere strictly to the instructions provided, offering relevant context from the knowledge base while avoiding unnecessary details. Your responses will be brief, to the point, and in compliance with the established format. If a question falls outside the given context, you will refrain from utilizing the chat history and instead rely on your own knowledge base to generate an appropriate response. You will prioritize the user's query and refrain from posing additional questions. The aim is to deliver professional, precise, and contextually relevant information pertaining to the Indian Penal Code.
CONTEXT: {context}
CHAT HISTORY: {chat_history}
QUESTION: {question}
ANSWER:
</s>[INST]
"""
prompt = PromptTemplate(template=prompt_template,
input_variables=['context', 'question', 'chat_history'])
#llm=HuggingFaceHub(repo_id="mistralai/Mistral-7B-Instruct-v0.2", model_kwargs={"temperature":0.5, "max_length":1024})
# You can also use other LLMs options from https://python.langchain.com/docs/integrations/llms. Here I have used TogetherAI API
from config import together_api
llm = Together(
model="mistralai/Mistral-7B-Instruct-v0.2",
temperature=0.5,
max_tokens=1024,
together_api_key=together_api
)
qa = ConversationalRetrievalChain.from_llm(
llm=llm,
memory=st.session_state.memory,
retriever=db_retriever,
combine_docs_chain_kwargs={'prompt': prompt}
)
for message in st.session_state.messages:
with st.chat_message(message.get("role")):
st.write(message.get("content"))
input_prompt = st.chat_input("Say something")
if input_prompt:
with st.chat_message("user"):
st.write(input_prompt)
st.session_state.messages.append({"role":"user","content":input_prompt})
with st.chat_message("assistant"):
with st.status("Thinking πŸ’‘...",expanded=True):
result = qa.invoke(input=input_prompt)
message_placeholder = st.empty()
full_response = "⚠️ **_Note: Information provided may be inaccurate._** \n\n\n"
for chunk in result["answer"]:
full_response+=chunk
time.sleep(0.02)
message_placeholder.markdown(full_response+" β–Œ")
st.button('Reset All Chat πŸ—‘οΈ', on_click=reset_conversation)
st.session_state.messages.append({"role":"assistant","content":result["answer"]})