Spaces:
Sleeping
Sleeping
File size: 1,792 Bytes
302186f | 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 | from langchain_groq import ChatGroq
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_retrieval_chain
from langchain_core.prompts import ChatPromptTemplate
from src.config import conf
class RAGEngine:
def __init__(self):
self.vectorstore = None
self.chain = None
self.embeddings = HuggingFaceEmbeddings(model_name=conf.EMBEDDING_MODEL)
def ingest(self, text_chunks: list):
"""Builds the Vector Index from text chunks."""
self.vectorstore = FAISS.from_texts(texts=text_chunks, embedding=self.embeddings)
self._build_chain()
def _build_chain(self):
"""Constructs the retrieval chain."""
llm = ChatGroq(
groq_api_key=conf.GROQ_API_KEY,
model_name=conf.LLM_MODEL
)
prompt = ChatPromptTemplate.from_template("""
You are an expert financial auditor.
Analyze the provided document context to answer the user's question strictly.
If the answer is not found in the context, state that clearly.
<context>
{context}
</context>
Question: {input}
""")
doc_chain = create_stuff_documents_chain(llm, prompt)
retriever = self.vectorstore.as_retriever()
self.chain = create_retrieval_chain(retriever, doc_chain)
def query(self, question: str):
if not self.chain:
raise ValueError("Knowledge Base not initialized.")
response = self.chain.invoke({"input": question})
return response.get("answer", "No answer generated.")
# Singleton Instance
engine = RAGEngine() |