Spaces:
Runtime error
Runtime error
Create agent.py
Browse files
agent.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
3 |
+
from langchain.document_loaders import PyPDFLoader
|
4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
+
from langchain.vectorstores import FAISS
|
6 |
+
|
7 |
+
from langchain.chains import ConversationalRetrievalChain
|
8 |
+
from langchain.llms import OpenAI
|
9 |
+
|
10 |
+
|
11 |
+
class Agent:
|
12 |
+
def __init__(self, openai_api_key: str | None = None) -> None:
|
13 |
+
# if openai_api_key is None, then it will look the enviroment variable OPENAI_API_KEY
|
14 |
+
self.embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
|
15 |
+
self.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
16 |
+
|
17 |
+
self.llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
|
18 |
+
|
19 |
+
self.chat_history = None
|
20 |
+
self.chain = None
|
21 |
+
self.db = None
|
22 |
+
|
23 |
+
def ask(self, question: str) -> str:
|
24 |
+
if self.chain is None:
|
25 |
+
response = "Please, add a document."
|
26 |
+
else:
|
27 |
+
response = self.chain({"question": question, "chat_history": self.chat_history})
|
28 |
+
response = response["answer"].strip()
|
29 |
+
self.chat_history.append((question, response))
|
30 |
+
return response
|
31 |
+
|
32 |
+
def ingest(self, file_path: os.PathLike) -> None:
|
33 |
+
loader = PyPDFLoader(file_path)
|
34 |
+
documents = loader.load()
|
35 |
+
splitted_documents = self.text_splitter.split_documents(documents)
|
36 |
+
|
37 |
+
if self.db is None:
|
38 |
+
self.db = FAISS.from_documents(splitted_documents, self.embeddings)
|
39 |
+
self.chain = ConversationalRetrievalChain.from_llm(self.llm, self.db.as_retriever())
|
40 |
+
self.chat_history = []
|
41 |
+
else:
|
42 |
+
self.db.add_documents(splitted_documents)
|
43 |
+
|
44 |
+
def forget(self) -> None:
|
45 |
+
self.db = None
|
46 |
+
self.chain = None
|
47 |
+
self.chat_history = None
|