financial-analyst-api / src /rag_engine.py
low-key-007's picture
Create rag_engine.py
302186f verified
Raw History Blame Contribute Delete
1.79 kB
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()