Wintersmith commited on
Commit
eb707f3
·
verified ·
1 Parent(s): 86a0805

Delete main_class.py

Browse files
Files changed (1) hide show
  1. main_class.py +0 -93
main_class.py DELETED
@@ -1,93 +0,0 @@
1
- from langchain_community.document_loaders import PyPDFLoader
2
- from langchain_text_splitters import RecursiveCharacterTextSplitter
3
- from langchain_openai import OpenAIEmbeddings
4
- from langchain_community.vectorstores import FAISS
5
- from langchain_openai import ChatOpenAI
6
- from langchain.retrievers import ContextualCompressionRetriever
7
- from langchain.retrievers.document_compressors import LLMChainExtractor
8
- from langchain.tools.retriever import create_retriever_tool
9
- from langchain import hub
10
- from langchain.agents import AgentExecutor, create_openai_tools_agent
11
- import os
12
- import gradio as gr
13
-
14
- # The Agent retriever is based on: https://python.langchain.com/docs/use_cases/question_answering/conversational_retrieval_agents?ref=blog.langchain.dev
15
- # The chat history is based on: https://python.langchain.com/docs/use_cases/question_answering/chat_history
16
- # Inspired by https://github.com/Niez-Gharbi/PDF-RAG-with-Llama2-and-Gradio/tree/master
17
- # Inspired by https://github.com/mirabdullahyaser/Retrieval-Augmented-Generation-Engine-with-LangChain-and-Streamlit/tree/master
18
-
19
-
20
- class PDFChatBot:
21
- # Initialize the class with the api_key and the model_name
22
- def __init__(self, api_key):
23
- self.processed = False
24
- self.final_agent = None
25
- self.chat_history = []
26
- self.api_key = api_key
27
- self.llm = ChatOpenAI(openai_api_key=self.api_key, temperature=0, model_name="gpt-3.5-turbo-0125")
28
-
29
- # add text to Gradio text block (not needed without Gradio)
30
- def add_text(self, history, text):
31
- if not text:
32
- raise gr.Error("Please enter text.")
33
- history.append((text, ''))
34
- return history
35
-
36
- # Load a pdf document with langchain textloader
37
- def load_document(self, file_name):
38
- loader = PyPDFLoader(file_name)
39
- raw_document = loader.load()
40
- return raw_document
41
-
42
- # Split the document
43
- def split_documents(self, raw_document):
44
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000,
45
- chunk_overlap=100,
46
- length_function=len,
47
- is_separator_regex=False,
48
- separators=["\n\n", "\n", " ", ""])
49
- chunks = text_splitter.split_documents(raw_document)
50
- return chunks
51
-
52
- # Embed the document with OpenAI Embeddings & store it to vectorstore
53
- def create_retriever(self, chunks):
54
- embedding_func = OpenAIEmbeddings(openai_api_key=self.api_key)
55
- # Create a new vectorstore from the chunks
56
- vectorstore = FAISS.from_documents(chunks, embedding_func)
57
-
58
- # Create a retriever
59
- basic_retriever = vectorstore.as_retriever()
60
- compressor = LLMChainExtractor.from_llm(self.llm)
61
- compression_retriever = ContextualCompressionRetriever(base_compressor=compressor,
62
- base_retriever=basic_retriever)
63
- return basic_retriever # or compression_retriever
64
-
65
- # Create an agent
66
- def create_agent(self, retriever):
67
- tool = create_retriever_tool(retriever,
68
- f"search_document",
69
- f"Searches and returns excerpts from the provided document.")
70
- tools = [tool]
71
- prompt = hub.pull("hwchase17/openai-tools-agent")
72
- agent = create_openai_tools_agent(self.llm, tools, prompt)
73
- self.final_agent = AgentExecutor(agent=agent, tools=tools)
74
-
75
- #Process files
76
- def process_file(self, file_name):
77
- documents = self.load_document(file_name)
78
- texts = self.split_documents(documents)
79
- db = self.create_retriever(texts)
80
- self.create_agent(db)
81
- print("Files successfully processed")
82
-
83
- # Generate a response and write to memory
84
- def generate_response(self, history, query, path):
85
- if not self.processed:
86
- self.process_file(path)
87
- self.processed = True
88
- result = self.final_agent.invoke({'input': query, 'chat_history': self.chat_history})['output']
89
- self.chat_history.extend((query, result))
90
- for char in result: # history argument and the subsequent code is only for the purpose of Gradio
91
- history[-1][1] += char
92
- return history, " "
93
-