This project implements a full-stack Graph-based Retrieval Augmented Generation (RAG) system using Neo4j, LangChain, and various LLM techniques to analyze and query Apple Inc.'s 2024 annual report data. It features a modern React frontend and FastAPI backend with chart generation capabilities. π
This project combines traditional vector-based retrieval with graph-based knowledge extraction to provide more accurate and contextual answers to queries about Apple's financial and business information. It uses a hybrid approach that leverages both structured (graph) and unstructured (vector) data for comprehensive information retrieval.
Key Highlights:
- π Web Interface: Modern React-based chat UI for interactive queries
- π REST API: FastAPI backend with two endpoints for text and chart queries
- π Chart Generation: Automatic visualization of financial data
- πΈοΈ Hybrid RAG: Combines graph and vector search for better accuracy
- π¬ Chat History: Context-aware conversations with memory
-
Document Processing: π
- PDF document ingestion and chunking
- Recursive text splitting with configurable chunk sizes
- Graph document transformation using LLMGraphTransformer
-
Knowledge Graph Construction: πΈοΈ
- Neo4j graph database integration
- Entity extraction and relationship mapping
- Graph document storage with source tracking
-
Vector Store Integration: π
- HuggingFace embeddings integration
- Hybrid search capabilities
- Vector indexing for efficient retrieval
-
Query Processing: π‘
- Natural language query understanding
- Entity extraction from queries
- Context-aware response generation
- Chat history management
-
Modern UI: π¨
- Professional financial-themed design
- Responsive layout (desktop, tablet, mobile)
- Real-time chat interface
- Image support for chart visualization
-
Chart Generation: π
- Automatic chart creation from queries
- Multiple chart types (bar, line, pie, area)
- Base64 image rendering in chat
- Smart data extraction from RAG responses
-
API Endpoints: π
/api/query- Text-based Q&A/api/chart- Chart generation endpoint- Automatic routing based on query content
-
Frontend (React)
- React 18 with functional components
- Axios for API communication
- Modern CSS with animations
- Port: 3000
-
Backend (FastAPI)
- RESTful API with CORS support
- RAG chain integration
- Chart generation service
- Port: 5000
-
Document Processing Pipeline
- PyPDFLoader for PDF ingestion
- RecursiveCharacterTextSplitter for text chunking
- LLMGraphTransformer for graph document creation
-
Storage Layer
- Neo4j Graph Database for structured data
- Vector store for embeddings
- Pickle-based document caching
-
Retrieval System
- Hybrid retrieval combining graph and vector search
- Entity-aware structured queries
- Context-based response generation
- Frontend: React, Axios, CSS3
- Backend: FastAPI, Uvicorn
- Databases: Neo4j ποΈ
- Embeddings: HuggingFace (sentence-transformers/all-mpnet-base-v2) π€
- LLM Integration: Gemini (gemini-2.5-flash) π§
- Framework: LangChain β‘
- Visualization: Matplotlib π
- Development: Python, Jupyter Notebook, Node.js π
- Python 3.8+ installed
- Node.js 14+ installed (for frontend)
- Neo4j Database (Aura or local instance)
- API Keys:
- Google Gemini API key
- Neo4j credentials
Create a .env file in the project root:
# Neo4j Configuration
NEO4J_URI=neo4j+s://xxxxxxxx.databases.neo4j.io
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
AURA_INSTANCEID=xxxxxxxx
AURA_INSTANCENAME=InstanceXX
# LLM API Keys
OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
groq_api_key=gsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxNote: The project uses Gemini by default. OPENAI_API_KEY and groq_api_key are optional depending on your LLM configuration.
Install all required Python packages:
pip install fastapi uvicorn python-dotenv langchain langchain-community langchain-google-genai langchain-neo4j langchain-experimental pydantic matplotlib numpy faiss-cpu sentence-transformers pypdfOr install individually:
fastapi- Web frameworkuvicorn- ASGI serverpython-dotenv- Environment variable managementlangchain- Core LangChain frameworklangchain-community- Community integrationslangchain-google-genai- Gemini integrationlangchain-neo4j- Neo4j integrationlangchain-experimental- Experimental features (LLMGraphTransformer)pydantic- Data validationmatplotlib- Chart generationnumpy- Numerical operationsfaiss-cpu- Vector similarity searchsentence-transformers- Embeddingspypdf- PDF processingneo4j- Neo4j driver
Navigate to the frontend directory and install:
cd frontend
npm installThis installs:
react&react-dom- React frameworkreact-scripts- Build toolsaxios- HTTP client
- Clone the repository
- Create
.envfile with your credentials (see Environment Variables above) - Install Python dependencies:
pip install -r requirements.txt # If available, or use pip install command above
- Ensure
graph_documents.pklis in the project root - Run the import script:
This loads the graph documents into your Neo4j database.
python import_data.py
Navigate to the backend_api directory:
cd backend_api
python backend_api.pyThe backend will start at http://localhost:5000
Verify: Visit http://localhost:5000 - you should see:
{"status": "Hybrid Graph RAG backend running successfully!"}Open a new terminal and navigate to the frontend directory:
cd frontend
npm install # First time only
npm startThe frontend will start at http://localhost:3000 and open automatically in your browser.
- Open
http://localhost:3000in your browser - Start asking questions about Apple's 2024 Annual Report
- For charts, include the word "chart" in your query (e.g., "Show me a chart of revenue trends")
-
Text Queries: Simply type your question and press Enter
- Example: "What is Apple's revenue for 2024?"
- Example: "What are the main risks mentioned?"
-
Chart Queries: Include "chart" in your question
- Example: "Show me a chart of capital expenditure evolution"
- Example: "Create a chart showing revenue trends"
- The system automatically routes to the chart endpoint
-
Chat History: The system maintains conversation context
- Follow-up questions work naturally
- Click "Clear" to start a new conversation
POST http://localhost:5000/api/query
Content-Type: application/json
{
"question": "What is Apple's revenue for 2024?",
"chat_history": []
}Response:
{
"answer": "Apple's revenue for 2024 was..."
}POST http://localhost:5000/api/chart
Content-Type: application/json
{
"question": "Show me a chart of revenue trends",
"chat_history": []
}Response:
{
"image": "base64_encoded_image_string",
"answer": "Chart generated successfully"
}from dotenv import load_dotenv
load_dotenv()
from hybrid_graph_rag import chain
# Query the system
response = chain.invoke({
"question": "Your question here",
"chat_history": []
})
print(response)- π "What is Apple's revenue for 2024?"
β οΈ "What are the main risks mentioned in the annual report?"- π± "What sustainability initiatives are mentioned?"
- π "What is the geographical revenue distribution?"
- π° "What is Apple's debt profile?"
- π "Show me a chart of capital expenditure evolution"
- π "Create a chart showing revenue trends"
- π "Generate a chart of geographical revenue distribution"
- π "Show me a chart of debt over time"
Hybrid-Graph-RAG-Financial-Analyser/
βββ backend_api/ # FastAPI backend
β βββ backend_api.py # Main API server
β βββ hybrid_graph_rag.py # RAG chain implementation
βββ frontend/ # React frontend
β βββ public/
β β βββ index.html
β βββ src/
β β βββ App.js # Main React component
β β βββ App.css # Styling
β β βββ index.js # Entry point
β β βββ index.css # Global styles
β βββ package.json # Frontend dependencies
β βββ README.md # Frontend documentation
βββ Annual Report/ # Source documents
β βββ NASDAQ_AAPL_2024_first_53_pages.pdf
β βββ NASDAQ_AAPL_2024.pdf
βββ graph_documents.pkl # Cached graph documents
βββ hybrid_graph_rag.py # Core RAG implementation
βββ hybrid_graph_rag.ipynb # Jupyter notebook
βββ import_data.py # Neo4j data import script
βββ test_chart_generation.py # Chart testing utilities
βββ verify_implementation.py # Verification scripts
βββ .env_example # Environment variables template
βββ README.md # This file
Health check endpoint.
Response:
{"status": "Hybrid Graph RAG backend running successfully!"}Text-based query endpoint.
Request:
{
"question": "string",
"chat_history": [["user msg", "ai msg"], ...]
}Response:
{
"answer": "string"
}Chart generation endpoint.
Request:
{
"question": "string (should contain 'chart')",
"chat_history": []
}Response (Success):
{
"image": "base64_encoded_string",
"answer": "Chart generated successfully"
}Response (Error):
{
"answer": "error message",
"error": "error message",
"image": null
}-
Document Processing: π
- Use appropriate chunk sizes based on document content
- Maintain overlap between chunks for context preservation
-
Query Formation: π
- Be specific with questions
- Provide context when needed
- Utilize chat history for follow-up questions
- For charts, clearly specify what data to visualize
-
System Maintenance: βοΈ
- Regularly update the knowledge graph
- Monitor embedding quality
- Validate response accuracy
- Keep Neo4j database optimized
-
Development: π»
- Always start backend before frontend
- Check backend logs for debugging
- Use browser console (F12) for frontend debugging
- Test chart generation with various query types
- Port 5000 already in use: Change port in
backend_api.pyor kill the process using port 5000 - Neo4j connection error: Verify
.envcredentials and Neo4j instance status - Import errors: Ensure all Python dependencies are installed
- Port 3000 already in use: Close other React apps or change port in
package.json - Cannot connect to backend: Verify backend is running at
http://localhost:5000 - Module not found: Run
npm installin the frontend directory
- No chart generated: Ensure query contains "chart" keyword
- Insufficient data: Try queries about data that exists in the annual report
- Chart errors: Check backend logs for detailed error messages
- Neo4j team for graph database capabilities
- LangChain community for the framework
- HuggingFace for embeddings model
- FastAPI team for the web framework
- React team for the frontend framework