-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_qa_chain.py
More file actions
77 lines (63 loc) · 2.47 KB
/
document_qa_chain.py
File metadata and controls
77 lines (63 loc) · 2.47 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
68
69
70
71
72
73
74
75
76
77
from langchain_groq import ChatGroq
from langchain.prompts import PromptTemplate
from langchain.chains import RetrievalQA
from langchain.indexes import VectorstoreIndexCreator
from langchain_community.document_loaders import PyPDFLoader
from langchain.vectorstores import DocArrayInMemorySearch
from langchain_huggingface import HuggingFaceEmbeddings
from dotenv import load_dotenv
import os
load_dotenv()
class DocumentQAChain:
def __init__(self, session_id, document_path):
self.session_id = session_id
self.document_path = document_path
self.chain = self.create_chain()
def create_chain(self):
llm = ChatGroq(
groq_api_key=os.getenv("GROQ_API_KEY"),
model_name="llama-3.3-70b-versatile",
temperature=0.7,
max_tokens=1000,
streaming=False
)
prompt_template = """
Use the following context from the PDF to answer the question.
If you don't know the answer based on the context, say so clearly.
Context: {context}
Question: {question}
Answer:"""
prompt = PromptTemplate(
template=prompt_template,
input_variables=["context", "question"]
)
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
loader = PyPDFLoader(file_path=self.document_path)
index = VectorstoreIndexCreator(
embedding=embeddings,
vectorstore_cls=DocArrayInMemorySearch
).from_loaders([loader])
# Create RetrievalQA chain
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=index.vectorstore.as_retriever(),
return_source_documents=True,
chain_type_kwargs={"prompt": prompt}
)
return qa_chain
def ask_question(self, question):
try:
response = self.chain({"query": question})
return {
"answer": response["result"],
"source_documents": response.get("source_documents", [])
}
except Exception as e:
return {
"error": f"Error processing question: {str(e)}",
"answer": None,
"source_documents": []
}