-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgent.py
More file actions
67 lines (57 loc) · 2.61 KB
/
Copy pathAgent.py
File metadata and controls
67 lines (57 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain_community.document_loaders import PyMuPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import faiss
from langchain.chains import ConversationalRetrievalChain
from langchain_community.llms import openai
class DocumentAgent:
def __init__(self, openai_api_key: str) -> None:
"""
Initialize the document interaction agent with necessary configurations.
Parameters:
- openai_api_key (str): API key for OpenAI services.
"""
self.embedder = OpenAIEmbeddings(openai_api_key=openai_api_key)
self.document_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
self.language_model = openai.OpenAI(temperature=0, openai_api_key=openai_api_key)
self.conversation_history = []
self.interaction_chain = None
self.vector_storage = None
def respond_to_query(self, query: str) -> str:
"""
Respond to a user query based on loaded documents.
Parameters:
- query (str): User's query.
Returns:
- str: Response generated by the agent.
"""
if self.interaction_chain is None:
return "Please upload a document first."
else:
response = self.interaction_chain({"question": query, "chat_history": self.conversation_history})
response_text = response["answer"].strip()
self.conversation_history.append((query, response_text))
return response_text
def load_document(self, document_path: str) -> None:
"""
Load and process a document for interaction.
Parameters:
- document_path (str): Path to the document file.
"""
loader = PyMuPDFLoader(document_path)
documents = loader.load()
processed_documents = self.document_splitter.split_documents(documents)
if self.vector_storage is None:
self.vector_storage = faiss.FAISS.from_documents(processed_documents, self.embedder)
self.interaction_chain = ConversationalRetrievalChain.from_llm(self.language_model, self.vector_storage.as_retriever())
self.conversation_history = []
else:
self.vector_storage.add_documents(processed_documents)
def reset_agent(self) -> None:
"""
Reset the agent's state, clearing all loaded documents and history.
"""
self.vector_storage = None
self.interaction_chain = None
self.conversation_history = []