🧠 Chat with Multiple PDFs: AI Financial Intelligence Agent
"The real world isn’t clean prompts. It’s messy documents. Long reports. Buried numbers. Hidden risks."
📖 The Story: Day 30 of 30
And this one hits different.
For the last 30 days, I didn’t just build AI agents. I built habits. I built discipline. I built proof — for myself.
To close this journey, I built something deeply practical:
Chat with Multiple PDFs — an AI Financial Intelligence Agent.
Because the real world isn’t clean prompts. It’s messy documents. Long reports. Buried numbers. Hidden risks.
This agent lets you upload multiple PDFs and talk to them.
Not keyword search.
Not Ctrl + F.
Actual reasoning.
What it can do:
- Read and understand multiple PDFs together
- Answer questions across documents
- Analyze annual reports & financial statements
- Flag unusual patterns and red flags
- Track related-party transactions
- Review managerial remuneration
- Export full chat history as CSV
This isn't just code. It's the foundation for what comes next.
🚀 Features at a Glance
| Feature | Description |
|---|---|
| Multi-PDF Support | Upload 1, 5, or 10 PDFs at once. The agent processes them all simultaneously. |
| Financial Focus | Optimized system prompts to understand financial jargon, balance sheets, and cash flow statements. |
| Vector Search | Uses FAISS for high-speed similarity search across thousands of document pages. |
| Google Gemini 1.5 | Powered by Google's latest gemini-1.5-flash model for fast, accurate, and context-aware responses. |
| Chat History Export | Download your entire analysis session as a .csv file for reporting or auditing. |
| Source Citation | (Implicit) The model uses retrieved context to answer, reducing hallucinations. |
| Secure & Local | Your files are processed in memory (or locally stored vectors), ensuring control over your data. |
| Interactive UI | Built with Streamlit for a chat-like experience that feels like using WhatsApp or ChatGPT. |
🛠️ System Architecture & Workflow
Understanding how the RAG (Retrieval-Augmented Generation) pipeline works under the hood.
The "Secret Sauce"
- Ingestion: We take raw PDF files, which are unstructured binary data.
- Chunking: We break them down into manageable pieces of text (e.g., 10,000 characters) to fit into the model's context window effectively.
- Embedding: We turn text into numbers (vectors) using Google's embedding model. This captures the semantic meaning of the text, not just keywords.
- Retrieval: When you ask a question, we find the most relevant chunks from your PDF.
- Synthesis: We send your question + the relevant PDF chunks to Gemini, which synthesizes a perfect answer.
💻 Tech Stack
We used the best-in-class open-source tools to build this agent.
| Component | Technology | Why we chose it? |
|---|---|---|
| Frontend | Streamlit | Fastest way to build data apps in Python. |
| LLM | Google Gemini 1.5 | Huge context window, fast, and cost-effective. |
| Embeddings | Google GenAI Embeddings | Native integration with the LLM. |
| Orchestration | LangChain | The standard for building LLM applications. |
| Vector DB | FAISS | Efficient dense vector similarity search by Meta. |
| PDF Parsing | PyPDF2 | Reliable PDF text extraction. |
| Environment | Python-Dotenv | Securely managing API keys. |
🏃♂️ Installation Guide
Follow these steps to get the agent running on your local machine.
Prerequisites
- Python 3.10 or higher installed.
- A Google Cloud Project with Gemini API enabled (it's free!).
Step 1: Clone the Repository
bashgit clone https://github.com/ujjwaltiwari01/pdf_rag_analyser.git cd pdf_rag_analyser
Step 2: Create a Virtual Environment (Recommended)
This keeps your global Python installation clean.
Windows:
powershellpython -m venv venv venv\Scripts\activate
Mac/Linux:
bashpython3 -m venv venv source venv/bin/activate
Step 3: Install Dependencies
We have listed all necessary libraries in requirements.txt.
bashpip install -r requirements.txt
Alternatively, if you use uv: uv sync
Step 4: Get your Google API Key
- Go to Google AI Studio.
- Click Create API Key.
- Copy the key.
Step 5: Run the Application
bashstreamlit run app.py
🕹️ Usage Guide
Once the app is running (usually at http://localhost:8501), follow these steps:
1. The Setup
On the Sidebar (left panel):
- Paste your Google API Key.
- Click Enter.
- You will see a success message:
API Key Accepted.
2. Upload Documents
- Click Browse files in the sidebar.
- Select one or more PDF files (e.g., "Apple 2023 Annual Report.pdf", "Tesla 10-K.pdf").
- Click Submit & Process.
- Wait for the magic... You'll see a spinner saying "Processing...". Once done, it will say "Processing Done".
3. Chat with your Data
In the main chat input box:
- Type your question.
- The agent will "think", search the documents, and provide a detailed answer.
4. Export Data
- Need to save the conversation? Click the Download Chat History button in the sidebar to get a CSV file.
🧪 Sample Financial Prompts
Try these prompts to test the financial intelligence of the agent:
- "What is the total revenue for the fiscal year 2023?"
- "List all related party transactions mentioned in the report."
- "Is there any significant increase in managerial remuneration compared to last year?"
- "Summarize the auditor's qualifications or emphasis of matter."
- "What are the contingent liabilities listed in the notes to accounts?"
- "Calculate the debt-to-equity ratio based on the balance sheet numbers."
- "Are there any red flags in the cash flow statement regarding operating activities?"
� Troubleshooting Common Indices
Even the best agents trip sometimes. Here is how to fix common issues:
| Issue | Possible Cause | Solution |
|---|---|---|
| "API Key Invalid" | Copy-paste error or expired key. | Re-generate key from Google AI Studio and ensure no extra spaces when pasting. |
| "Rate Limit Exceeded" | Hitting the free tier limits of Gemini. | Wait for a minute or upgrade to a paid tier (if available). The script has no built-in backoff yet. |
| "FAISS Index Not Found" | You haven't uploaded/processed any PDFs yet. | Upload a PDF and click "Submit & Process" to create the index first. |
| "Processing Forever..." | PDF might be corrupt or password-protected. | Try unlocking the PDF or using a smaller file to test. |
| "Empty Response" | The model couldn't find an answer in the context. | Try rephrasing your question or asking something more specific to the document. |
🧐 Deep Dive: How the Code Works
For the developers who want to understand the magic behind app.py.
1. The PDF Loader
We use PyPDF2 to iterate through every page of the uploaded PDF files.
pythonpdf_reader = PdfReader(pdf) text = "" for page in pdf_reader.pages: text += page.extract_text()
Why? It's lightweight and reliable for standard text PDFs.
2. The Chunker
Text is split using RecursiveCharacterTextSplitter.
pythontext_splitter = RecursiveCharacterTextSplitter( chunk_size=10000, chunk_overlap=1000 )
Why? We need chunks large enough to carry context (like a full financial table) but small enough to fit into the embedding model's limit. The overlap ensures we don't cut sentences in half.
3. The Vector Store (FAISS)
We treat the chunks as high-dimensional vectors.
pythonvector_store = FAISS.from_texts(text_chunks, embedding=embeddings) vector_store.save_local("faiss_index")
Why? FAISS (Facebook AI Similarity Search) is incredibly fast at finding the "nearest neighbor" (most similar text) to your query vector.
4. The Conversational Chain
We build a QA chain using LangChain.
pythonchain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
- Prompt: We inject a custom "Finance Expert" persona into the system prompt.
- Chain Type "Stuff": We "stuff" all the relevant retrieved chunks into the prompt context window and ask Gemini to answer based only on that context.
�📂 Project Structure
pdf_rag_analyser/ ├── app.py # The main application code ├── requirements.txt # List of python dependencies ├── README.md # Project documentation ├── .gitignore # Files to ignore in git └── faiss_index/ # (Generated) Local storage for vector embeddings ├── index.faiss └── index.pkl
🤝 Contributing
Contributions are welcome! If you have ideas for more "agents" or want to improve this one:
- Fork the repository.
- Create a new branch (
git checkout -b feature-branch). - Commit your changes (
git commit -m 'Add new feature'). - Push to the branch (
git push origin feature-branch). - Open a Pull Request.
📜 License
This project is licensed under the MIT License - see the LICENSE file for details.
🌟 Acknowledgements
- Framework: Streamlit
- LLM Power: Google DeepMind
- Inspiration: The #30Days30AIAgents challenge.
Built with ❤️ during the 30 Days of AI Agents Challenge
Star this Repo ⭐ • Follow on Twitter 🐦 • Connect on LinkedIn 💼