Day 30Strategic IntelRAGFAISSFinTech

Financial IQ RAG System — AI Agent for annual report financial analysis

Deep-dives annual reports for risk, trends, and sentiment.

Impact

Deep-dives annual reports for risk, trends, and sentiment.

Mechanism

Multi-PDF RAG Analyzer

DAY 30
Full README · Case Study

🧠 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

FeatureDescription
Multi-PDF SupportUpload 1, 5, or 10 PDFs at once. The agent processes them all simultaneously.
Financial FocusOptimized system prompts to understand financial jargon, balance sheets, and cash flow statements.
Vector SearchUses FAISS for high-speed similarity search across thousands of document pages.
Google Gemini 1.5Powered by Google's latest gemini-1.5-flash model for fast, accurate, and context-aware responses.
Chat History ExportDownload 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 & LocalYour files are processed in memory (or locally stored vectors), ensuring control over your data.
Interactive UIBuilt 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 'Brain'

PyPDF2

RecursiveCharacterTextSplitter

GoogleGenerativeAIEmbeddings

FAISS

Input

Retrieve Top Context

Send to

Generates Answer

User Uploads PDFs

Text Extraction

Text Chunks

Vector Embeddings

Vector Store index

User Asks Question

Similarity Search

Context + Prompt

Gemini 1.5 Flash LLM

Final Response to User

The "Secret Sauce"

  1. Ingestion: We take raw PDF files, which are unstructured binary data.
  2. Chunking: We break them down into manageable pieces of text (e.g., 10,000 characters) to fit into the model's context window effectively.
  3. Embedding: We turn text into numbers (vectors) using Google's embedding model. This captures the semantic meaning of the text, not just keywords.
  4. Retrieval: When you ask a question, we find the most relevant chunks from your PDF.
  5. 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.

ComponentTechnologyWhy we chose it?
FrontendStreamlitFastest way to build data apps in Python.
LLMGoogle Gemini 1.5Huge context window, fast, and cost-effective.
EmbeddingsGoogle GenAI EmbeddingsNative integration with the LLM.
OrchestrationLangChainThe standard for building LLM applications.
Vector DBFAISSEfficient dense vector similarity search by Meta.
PDF ParsingPyPDF2Reliable PDF text extraction.
EnvironmentPython-DotenvSecurely 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

bash
git clone https://github.com/ujjwaltiwari01/pdf_rag_analyser.git
cd pdf_rag_analyser

This keeps your global Python installation clean.

Windows:

powershell
python -m venv venv
venv\Scripts\activate

Mac/Linux:

bash
python3 -m venv venv
source venv/bin/activate

Step 3: Install Dependencies

We have listed all necessary libraries in requirements.txt.

bash
pip install -r requirements.txt

Alternatively, if you use uv: uv sync

Step 4: Get your Google API Key

  1. Go to Google AI Studio.
  2. Click Create API Key.
  3. Copy the key.

Step 5: Run the Application

bash
streamlit 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:

IssuePossible CauseSolution
"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.

python
pdf_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.

python
text_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.

python
vector_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.

python
chain = 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:

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature-branch).
  3. Commit your changes (git commit -m 'Add new feature').
  4. Push to the branch (git push origin feature-branch).
  5. Open a Pull Request.

📜 License

This project is licensed under the MIT License - see the LICENSE file for details.


🌟 Acknowledgements


Built with ❤️ during the 30 Days of AI Agents Challenge

Star this Repo ⭐Follow on Twitter 🐦Connect on LinkedIn 💼

Explore more agents

30 open-source systems · full registry

Browse All 30 Agents