ssd-2k3's picture
updated faiss prompt
a5f18ee verified
Raw History Blame Contribute Delete
16.2 kB
import os
from dotenv import load_dotenv
import streamlit as st
import base64
from langchain.output_parsers import ResponseSchema
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader, DirectoryLoader
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import Chroma
from langchain.document_loaders.pdf import PyMuPDFLoader
from langchain_core.output_parsers.string import StrOutputParser
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import StructuredOutputParser
from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain.vectorstores import FAISS
from langchain_community.embeddings.sentence_transformer import (
SentenceTransformerEmbeddings,
)
from pydantic import BaseModel, Field
from langchain.output_parsers import ResponseSchema
from langchain.chains import ConversationalRetrievalChain
import chromadb
# from profanity_check import predict
# # from guardrails.validators import Validator, register_validator
# from typing import Dict
# from guardrails import Guard
from pydantic import v1 as pydantic_v1
from huggingface_hub import InferenceClient
from datasets import Dataset
import pandas as pd
# Streamlit code
st.set_page_config(layout="wide", page_title='Info App')
# using personal hf token
# Load environment variables from .env file
# load_dotenv()
# Access the variables
# hf_token = os.getenv('HF_TOKEN')
hf_token = st.secrets['hf_token']
endpoint_url = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
client = InferenceClient(endpoint_url)
# "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
@st.cache_resource
def return_llm():
models = {
"mistral_7B": "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2",
}
endpoint_url = models.get('mistral_7B')
if not endpoint_url:
raise ValueError(f"Model mistral_7B not found. Available models are: {list(models.keys())}")
llm = HuggingFaceEndpoint(
endpoint_url="https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2",
max_new_tokens = 4096, #original val 512 or 4096
huggingfacehub_api_token=hf_token,
request_timeout=120, # 120 giving error
temperature=0.3, #presence penalty , top_k=10, top_p=0.95,typical_p=0.95, do-sample
task="question-answering",
top_k = 10
# model_kwargs={
# 'min_length': 100, # Minimum length of the generated response
# 'max_length': 2000, # Maximum length of the generated response
# 'num_return_sequences': 1 # Number of sequences to return
# }
)
return llm
@st.cache_resource
# Returns the old db that stores the 100 docs (as a data storage)
def return_db():
# Initializing the loader
loader = DirectoryLoader(
'data',
glob="./*.pdf",
loader_cls=PyMuPDFLoader,
show_progress=True,
)
# Loading the docs
docs = loader.load()
# For persist_dir
chroma_dir = 'chroma_embeddings'
# Splitting and chunking the doc
text_splitter = RecursiveCharacterTextSplitter(chunk_size=3000, chunk_overlap=50)
texts = text_splitter.split_documents(docs)
# Initializing the embedding model
embedding_model = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
# Creating collection-like structure from the doc as a better medium to store the embeddings
vectordb = Chroma.from_documents(documents=texts, persist_directory=chroma_dir, embedding=embedding_model)
# disk storing using persist (vectordv storage)
vectordb.persist()
vectordb = None
# Now we can load the persisted database from disk, and use it as normal
vectordb = Chroma(persist_directory=chroma_dir, embedding_function=embedding_model)
# return db with 100 docs
return vectordb
# Main model initialization
def return_response(vectordb, user_query):
#template for model prompt
template = f"""
You are a financial analyst specializing in providing detailed answers by analyzing finance-related documents.
You have access to a vector database containing up to 100 documents.
Thoroughly review the stored documents to answer the {user_query} accurately and elaborate each and every new point.
If the information is not available, say that you don't know.
Answer only based on the user's query.
DO NOT RESPOND IF the uploaded document is not a financial document.
Query Validation:
If the user's query does not make sense or is invalid, do not attempt to answer.
Simply inform the user to enter a valid query.
If the user asks for summarization of a particular document, then summarize the contents of that document.
Elaborated Answer:
"""
# Formatting the written prompt
given_prompt = ChatPromptTemplate.from_template(template)
#initliaizing mistral model
mist_llm = return_llm()
# Retriever initialization
retriever = vectordb.as_retriever(search_kwargs={"k": 5})
# Initializing the chain with retriever, prompt and llm
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| given_prompt
| mist_llm
| StrOutputParser()
)
response = chain.invoke(user_query)
# Returning the response to be accessed by the streamlit app
return response
def run_faiss(texts,user_query):
template = f"""
You are a financial analyst specializing in providing detailed answers by analyzing finance-related documents.
You accept and analyze a new document uploaded by the user.
Remember:
Answer the {user_query} accurately and elaborate each and every new point if not asked to summarize.Answer only based on the user's query.
If summary or summarize is the user query , then give a summary of the document.
If the information is not available, say that you don't know.
DO NOT RESPOND IF the uploaded document is not a financial document.
NEVER provide the example use case as a response.
Elaborated Answer:
"""
# Formatting the written prompt
given_prompt = ChatPromptTemplate.from_template(template)
embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
# Create vectors
vectorstore = FAISS.from_documents(texts, embedding_function)
retriever = vectorstore.as_retriever()
#initliaizing mistral model
mist_llm = return_llm()
# initializing the chain
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| given_prompt
| mist_llm
# | StrOutputParser()
)
# rag_chain = (
# RunnableParallel(context = retriever , question = RunnablePassthrough() ) |
# given_prompt |
# mist_llm
# )
response = chain.invoke(user_query)
# Returning the response to be accessed by the streamlit app
return response
class FinancialOutputStruct(BaseModel):
in_brief: str = Field(
description="Provide a concise answer to the user's financial query, ensuring no critical information is omitted."
)
elaborate: str = Field(
description="Provide a detailed answer to the user's financial query. Use bullet points, tables, and other descriptive methods where necessary to elaborate the information comprehensively."
)
def response_schema(user_query):
# Response Schema for Metadata
metadata_schema = ResponseSchema(
name='Metadata',
description=(
"Metadata about the document where the information was retrieved from.\n"
"The name of the document, insinuating what the document is about (e.g., 'Fact Sheet').\n"
"The company from which the facts were obtained.\n"
"The publication date of the document.\n"
"The title of the financial document.\n"
"The page number where the relevant information is found.\n"
"The author of the document, if given.\n"
"The URL where the document can be accessed.\n"
"A unique identifier for the document, if available.\n"
"The date when the document was accessed.\n"
)
)
respose_schema = [metadata_schema]
#formatting the new instructions for metadata inclusion
output_parser = StructuredOutputParser.from_response_schemas(respose_schema)
format_instructions = output_parser.get_format_instructions()
# print(format_instructions)
new_given_prompt = f"""
You are a financial analyst specializing in providing detailed answers by analyzing finance-related documents.
You accept and analyze a new document uploaded by the user.
Thoroughly review the new document and the stored documents to answer the {user_query} accurately and elaborate each and every new point.
If the information is not available, say that you don't know.
Answer only based on the user's query.
DO NOT RESPOND IF the uploaded document is not a financial document.
Never provide the example use case as a response.
Elaborated Answer:
{format_instructions}
"""
new_prompt = ChatPromptTemplate.from_template(template = new_given_prompt)
print("new prompt",new_prompt)
formatted_prompt = new_prompt.format(question=user_query)
print('formatted response',formatted_prompt)
new_response = return_llm().invoke(formatted_prompt)
print('new response = ', new_response)
return new_response
# def return_guard(user_query):
# template = f"""
# You are a financial analyst specializing in providing detailed answers by analyzing finance-related documents.
# You accept and analyze a new document uploaded by the user.
# Thoroughly review the new document and the stored documents to answer the {user_query} accurately and elaborate each and every new point.
# If the information is not available, say that you don't know.
# Answer only based on the user's query.
# DO NOT RESPOND IF the uploaded document is not a financial document.
# Never provide the example use case as a response.
# Elaborated Answer:
# """
# guard = Guard.from_pydantic(output_class=FinancialOutputStruct, prompt=template)
# print("Guard and type of guard",guard, type(guard))
# return guard
#MAIN FUNCTION
@st.cache_data
# Function to display the PDF of a given file
def displayPDF(file):
# Opening file from file path
with open(file, "rb") as f:
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
st.markdown(pdf_display, unsafe_allow_html=True)
# Function to generate texts that can be added to vectordb to update itwith user uploaded file
def tempfile_text(filepath):
loader = PyMuPDFLoader(filepath)
pages = loader.load_and_split()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)
texts = text_splitter.split_documents(pages)
return texts
#main function for streamlit
def main():
st.title('Financial Document Info Provider using Language Model')
#ask if it should be used with st.echo?
st.sidebar.header('Generate Response with or without uploading Document')
with st.sidebar:
# option = st.multiselect(
# 'How would you like to generate the response?',
# ['Response Without Document', 'Response With Document'])
option = st.radio(
"",
["Without Document", "With Document"],
captions = ["Generate the response from the pre-exisiting database","Upload required document to generate the response"])
#Response generation without user upload
# if 'Response Without Document' in option:
if 'Without Document'==option:
# Enter user query
temp_query = st.text_input("Input Query", "Write here...")
if temp_query != "Write here...": #if query is entered and not left blank.
#button to submit and load the query and generate a response
if st.button('Submit'):
st.info("Generated Reponse")
# Old db returned with 100 files
temp_db = return_db()
#response from data storage-100 files
final_response = return_response(temp_db, temp_query)
#display response
st.success(final_response)
#download response button
st.download_button("Download Response",final_response)
#when user does not enter query
else:
st.write("Enter valid query, press Enter, and click Submit.")
#Response generation with user upload
# if 'Response With Document' in option:
if 'With Document'==option:
#user upload document
uploaded_file = st.file_uploader('Upload the PDF File', type=['pdf'])
# Enter user query
temp_query = st.text_input("Enter Query", "Write here...")
if temp_query != "Write here...":#if query is entered and not left blank
if st.button('Submit'):
if uploaded_file is not None:
# Save uploaded file to the folder
folder_path = 'Folder-PDF'
#Formulating the folderpath.
if not os.path.exists(folder_path):
os.makedirs(folder_path)
#formatting the file_path
file_path = os.path.join(folder_path, secure_filename(uploaded_file.name))
# Write uploaded file to the directory
with open(file_path, 'wb') as f:
f.write(uploaded_file.read())
#accessing the texts from user uploaded file
texts = tempfile_text(file_path)
col1, col2 = st.columns(2)
with col1:
st.info("Uploaded PDF File")
displayPDF(file_path)
with col2:
st.info("Generated Information")
#response - faiss vectorstore
faiss_response = run_faiss(texts, temp_query)
#display response
st.success(faiss_response)
# guard, new_response = response_schema(temp_query)
# guard = return_guard(temp_query)
# # GUARDRAIL CODE - ERROR HERE
# raw_llm_response, validated_response, *rest = guard(
# llm_api = client,
# fn=run_faiss(texts, temp_query),
# max_tokens=2048,
# temperature=0,
# prompt_params={"statement_to_be_translated": temp_query}
# )
# st.success(validated_response)
#download response button
st.download_button("Download Response", faiss_response)
#when user does not enter query
else:
st.write("Enter valid query, press Enter, and click Submit.")
if __name__ == '__main__':
main()