abhinav0231 commited on
Commit
ab56328
·
verified ·
1 Parent(s): 28d9587

Update rag_agent.py

Browse files
Files changed (1) hide show
  1. rag_agent.py +93 -71
rag_agent.py CHANGED
@@ -1,71 +1,93 @@
1
- import os
2
- from langchain_community.document_loaders import PyPDFLoader, TextLoader
3
- from langchain.text_splitter import RecursiveCharacterTextSplitter
4
- from langchain_community.vectorstores import FAISS
5
- from langchain.prompts import PromptTemplate
6
- from langchain_core.output_parsers import StrOutputParser
7
- from llm_setup import llm, embeddings
8
-
9
- if not llm or not embeddings:
10
- raise ImportError("LLM or Embedding models could not be loaded. Please check llm_setup.py.")
11
-
12
- def get_document_context(file_path: str, query: str) -> str:
13
- """
14
- Loads a document, splits it, creates an in-memory FAISS vector store,
15
- and retrieves the most relevant context for a given query.
16
- """
17
- print("--- Using FAISS for document retrieval ---")
18
-
19
- if file_path.endswith(".pdf"):
20
- loader = PyPDFLoader(file_path)
21
- elif file_path.endswith(".txt"):
22
- loader = TextLoader(file_path)
23
- else:
24
- return "Error: Unsupported file format. Please upload a .pdf or .txt file."
25
-
26
- try:
27
- documents = loader.load()
28
- if not documents:
29
- return "Error: Document is empty or could not be read."
30
-
31
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
32
- docs = text_splitter.split_documents(documents)
33
-
34
- if not docs:
35
- return "Error: Could not extract text chunks from the document."
36
-
37
- db = FAISS.from_documents(docs, embeddings)
38
- retriever = db.as_retriever(search_kwargs={'k': 3})
39
- retrieved_docs = retriever.invoke(query)
40
-
41
- context = "\n\n".join([doc.page_content for doc in retrieved_docs])
42
- return context
43
- except Exception as e:
44
- print(f"An error occurred during document processing: {e}")
45
- return "Error: Failed to process the provided document."
46
-
47
-
48
- def run_rag_agent(user_prompt: str, file_path: str) -> str:
49
- """
50
- The main agentic function to retrieve context from a user-provided document.
51
- """
52
- print("--- RAG Agent Activated (Document-Only Mode) ---")
53
-
54
- prompt_template = PromptTemplate.from_template(
55
- """You are a research assistant. Based on the user's story idea, what is the single most
56
- important keyword or question to search for within their provided document to find relevant context?
57
-
58
- User's Story Idea: '{prompt}'
59
-
60
- Optimized Search Query for Document:"""
61
- )
62
-
63
- chain = prompt_template | llm | StrOutputParser()
64
-
65
- search_query = chain.invoke({"prompt": user_prompt})
66
- print(f"Generated Search Query: {search_query}")
67
-
68
- context = get_document_context(file_path, search_query)
69
-
70
- print("--- RAG Agent Finished ---")
71
- return context
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from sklearn.feature_extraction.text import TfidfVectorizer
3
+ from sklearn.metrics.pairwise import cosine_similarity
4
+ import numpy as np
5
+ import PyPDF2
6
+ from langchain_google_genai import ChatGoogleGenerativeAI
7
+ import streamlit as st
8
+
9
+ def load_document(file_path: str) -> str:
10
+ """Load document content from PDF or TXT file."""
11
+ try:
12
+ if file_path.endswith(".pdf"):
13
+ with open(file_path, 'rb') as file:
14
+ pdf_reader = PyPDF2.PdfReader(file)
15
+ text = ""
16
+ for page in pdf_reader.pages:
17
+ text += page.extract_text() + "\n"
18
+ return text
19
+ elif file_path.endswith(".txt"):
20
+ with open(file_path, 'r', encoding='utf-8') as file:
21
+ return file.read()
22
+ else:
23
+ return "Error: Unsupported file format."
24
+ except Exception as e:
25
+ return f"Error reading file: {str(e)}"
26
+
27
+ def simple_text_search(query: str, document_text: str, max_chunks: int = 3) -> str:
28
+ """Simple TF-IDF based text retrieval - much faster than FAISS."""
29
+
30
+ # Split document into chunks
31
+ chunks = []
32
+ words = document_text.split()
33
+ chunk_size = 200 # words per chunk
34
+
35
+ for i in range(0, len(words), chunk_size):
36
+ chunk = " ".join(words[i:i + chunk_size])
37
+ if chunk.strip():
38
+ chunks.append(chunk)
39
+
40
+ if not chunks:
41
+ return "No content found in document."
42
+
43
+ # Create TF-IDF vectors
44
+ vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
45
+
46
+ try:
47
+ # Vectorize chunks and query
48
+ chunk_vectors = vectorizer.fit_transform(chunks)
49
+ query_vector = vectorizer.transform([query])
50
+
51
+ # Calculate similarity
52
+ similarities = cosine_similarity(query_vector, chunk_vectors).flatten()
53
+
54
+ # Get top matching chunks
55
+ top_indices = similarities.argsort()[-max_chunks:][::-1]
56
+
57
+ relevant_chunks = [chunks[i] for i in top_indices if similarities[i] > 0.1]
58
+
59
+ return "\n\n".join(relevant_chunks[:max_chunks])
60
+
61
+ except Exception as e:
62
+ return f"Search error: {str(e)}"
63
+
64
+ def run_rag_agent(user_prompt: str, file_path: str) -> str:
65
+ """Simple but effective RAG implementation."""
66
+ print("--- RAG Agent Activated (Lightweight Version) ---")
67
+
68
+ # Load document
69
+ document_text = load_document(file_path)
70
+ if document_text.startswith("Error"):
71
+ return document_text
72
+
73
+ # Generate search query using LLM
74
+ api_key = st.secrets.get("GEMINI_API_KEY", os.getenv("GEMINI_API_KEY"))
75
+ llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", google_api_key=api_key)
76
+
77
+ search_prompt = f"""Based on this story idea: "{user_prompt}"
78
+
79
+ What are the 2-3 most important keywords to search for in a document to find relevant context?
80
+ Respond with just the keywords separated by spaces."""
81
+
82
+ try:
83
+ response = llm.invoke(search_prompt)
84
+ search_query = response.content.strip()
85
+ print(f"Generated Search Query: {search_query}")
86
+ except:
87
+ search_query = user_prompt # Fallback
88
+
89
+ # Retrieve relevant content
90
+ context = simple_text_search(search_query, document_text)
91
+
92
+ print("--- RAG Agent Finished ---")
93
+ return context