How sopanmunde/ai-research-copilot works
1. Overall shape
- This repository is a full-stack AI research copilot with a clear split between a Next.js/React frontend and a FastAPI backend.
- The backend is the system of record and orchestration layer; the frontend is primarily a UI/client for chat, document management, dashboards, and settings.
- Core external dependencies that materially shape the design are Google Gemini for generation, Pinecone for vector retrieval, and MongoDB Atlas for persistent application data. An optional Redis cache is used for RAG acceleration.
2. Frontend boundary
- The frontend lives under frontend/app and uses the Next.js App Router for pages like dashboard, login, and settings.
- Key interaction components are in frontend/components, especially AIAssistantUI, ChatPane, Composer, Sidebar, and Message.
- Hooks such as use-chat, use-streaming, and use-upload encapsulate calls to the backend and manage SSE/chat state, so the UI stays thin and event-driven.
3. Backend entry and API surface
- The backend boots from backend/index.py into a FastAPI app defined in src/main.py.
- Route modules in src/api/routes partition the API into auth, chat, conversations, reports, uploads/documents, models, and health.
- This makes the backend a gateway: it exposes HTTP for standard requests and Server-Sent Events for live chat/research streaming.
4. Authentication and request protection
- Authentication is JWT-based, with routes for registration, login, and profile lookup.
- Cross-cutting controls include prompt_injection_guard.py and request_logger.py, showing that user input is screened before reaching the LLM workflow and requests are observable end-to-end.
- Security concerns are centralized in core/security.py, while shared config and constants are in core/config.py and core/constants.py.
5. Main AI orchestration path
- The heart of the system is the LangGraph research workflow in src/workflows/research_workflow.py plus the node implementations in src/agents/langgraph/nodes.
- The workflow is a 5-node pipeline: planner, retriever, citation, summarizer, and report generation.
- state.py holds the shared graph state, which lets each agent pass structured context forward instead of operating as isolated LLM calls.
6. Chat data flow
- A user message starts in the frontend composer, goes to the /api/chat endpoint, and enters the LangGraph stream.
- The planner decides whether retrieval is needed; if yes, the retriever and citation nodes gather and rank evidence before the summarizer generates the answer.
- The backend streams intermediate agent events and final text back to the frontend via SSE, enabling the “live agent activity” experience.
7. Document ingestion and RAG
- Uploaded documents enter through the upload/document routes and flow into the ingestion pipeline under src/rag/ingestion.
- Loaders support PDF, DOCX, and text, then chunking and metadata extraction prepare content for embedding.
- Embeddings are produced by hf_embeddings.py and written to Pinecone via vectorstores/pinecone_store.py, forming the searchable corpus used by later chat and report requests.
8. Retrieval and citation layer
- Retrieval is separated from generation: semantic_search.py, contextual_retriever.py, and citation_retriever.py handle document lookup and evidence selection.
- The system emphasizes citation-aware output, so the retrieval layer supplies source text, metadata, and confidence/scoring information to the graph.
- User-scoped filtering is part of the architecture, meaning retrieval is not global; it is constrained by user/document metadata.
9. Persistence model
- MongoDB stores application data such as users, conversations, chat messages, documents, and reports.
- Connection and indexing are isolated in src/database/mongodb, with repository classes for chat and document access.
- This means MongoDB is used for durable operational state, while Pinecone is used only for semantic search over indexed content.
10. Memory and conversation context
- The RAG layer includes conversation_memory.py and research_memory.py, which feed recent conversation turns and research context back into the agents.
- The README indicates a bounded history strategy, so the model gets short-term conversational context without requiring the entire transcript every time.
- This is an important boundary: long-term data lives in MongoDB, while short-term working memory is reconstructed per request.
11. Report generation and export
- Report generation has its own pipeline under src/rag/pipelines/report_pipeline.py and service layer in services/report_service.py.
- Generated reports are formatted for downstream use, including Markdown export via utils/markdown_export.py.
- Reports are therefore a first-class artifact, not just a chat response, and can be stored, listed, and exported independently.
12. Supporting backend layers
- services/llm_service.py, chat_service.py, and report_service.py act as business-logic facades over the graph, retrieval, and persistence layers.
- middleware and core provide shared runtime concerns: logging, exceptions, caching, validation, and configuration.
- utils contains small cross-cutting helpers such as token counting and input validation.
13. Auxiliary automation and deployment
- workflows/n8n contains external automations like research alerts, scheduled report generation, and a Slack bot, which sit outside the main request/response path.
- Deployment artifacts include docker-compose.yml, GitHub Actions workflows, render.yaml, and vercel.json, indicating the stack is designed for containerized backend deployment and separate frontend hosting.
- The repo also includes backend tests around RAG behavior, which suggests the AI/retrieval path is a primary correctness boundary.
14. How to diagram it
- Draw four main zones: frontend UI, FastAPI backend/API, LLM/RAG orchestration, and data services.
- The most important arrows are:
- UI chat/upload/report actions → FastAPI routes
- chat route → LangGraph workflow → SSE back to UI
- upload route → ingestion pipeline → embeddings → Pinecone and metadata → MongoDB
- workflow retrieval nodes → Pinecone/MongoDB memory
- report route → report pipeline → Markdown/export/storage
Main entry points: routes Route Layer · research_workflow.py Research Graph · ingestion Ingestion · nodes Graph Nodes
Components 20
Frontend
Next.js app and UI interaction layer
- Next.js App · App Router pages for dashboard, login, settings, and landing UI
frontend/app - Chat UI · Primary assistant, chat, composer, sidebar, and message components
frontend/components - UI Hooks · Chat, streaming, and upload hooks that keep the UI event-driven
frontend/hooks - API Client · Typed client and request helpers for backend calls
frontend/lib/api.ts
Backend
FastAPI API, orchestration, and business logic
- App Entry · Backend startup and FastAPI app assembly
backend/index.py - API App · Central application wiring and route registration
backend/src/main.py - Route Layer · Auth, chat, conversation, report, upload, model, and health endpoints
backend/src/api/routes - Services · Chat, LLM, and report facades over orchestration and persistence
backend/src/services - Core Security · Shared config, security, logging, cache, exceptions, and constants
backend/src/core - Middleware · Prompt injection guard and request logging
backend/src/middleware
RAG / Agents
Retrieval, memory, embedding, and LangGraph workflow
- Research Graph · Planner, retriever, citation, summarizer, and report pipeline
backend/src/workflows/research_workflow.py - Graph Nodes · Concrete LangGraph node implementations
backend/src/agents/langgraph/nodes - Retrieval · Semantic search, contextual ranking, and citation-aware evidence selection
backend/src/rag/retrieval - Ingestion · Loaders, chunking, metadata extraction, and embedding pipeline
backend/src/rag/ingestion - Memory · Conversation and research context reconstruction
backend/src/rag/memory
Data Layer
Durable storage and vector search
- Pinecone Store · Semantic corpus for retrieval over embedded document chunks
backend/src/rag/vectorstores/pinecone_store.py - MongoDB · Users, conversations, messages, documents, and reports
backend/src/database/mongodb - Gemini LLM · Primary generation and reasoning provider
- Redis Cache · Optional cache for RAG acceleration
Automation
External scheduled and event-driven workflows
- N8N Workflows · Scheduled reports, research alerts, and Slack bot automations
workflows/n8n
Connections 24
- Next.js App → Chat UI: renders · Pages compose the assistant and app screens
- Chat UI → UI Hooks: uses · UI components delegate chat, streaming, and upload state
- UI Hooks → API Client: calls · Hooks send requests and subscribe to backend streams
- API Client → Route Layer: HTTP/SSE · Frontend talks to the FastAPI route surface
- App Entry → API App: boots · Process entry initializes the app
- API App → Route Layer: registers · Main app mounts the API route modules
- Route Layer → Middleware: protects · Requests are screened and logged before orchestration
- Route Layer → Services: delegates · Routes hand off business logic to service facades
- Middleware → Core Security: uses · Shared runtime concerns and safeguards
- Services → Research Graph: orchestrates · Chat and report services invoke the graph and pipelines
- Research Graph → Graph Nodes: executes · Workflow runs planner, retriever, citation, summarizer, and report nodes
- Graph Nodes → Retrieval: retrieves · Nodes gather evidence and scored context
- Graph Nodes → Memory: loads · Nodes pull short-term conversation and research context
- Retrieval → Pinecone Store: searches · Semantic retrieval hits the vector index
- Retrieval → MongoDB: filters · User and document metadata scope retrieval
- Ingestion → Pinecone Store: indexes · Embedded chunks are written to Pinecone
- Ingestion → MongoDB: persists · Document metadata and operational records are stored durably
- Ingestion → Gemini LLM: embeds · Generation provider participates in embedding and related AI steps
- Research Graph → Gemini LLM: generates · Planner, summarizer, and report generation use the LLM
- Research Graph → Redis Cache: caches · Optional acceleration for repeated RAG access
- Route Layer → MongoDB: reads/writes · API persists auth, chats, conversations, documents, and reports
- Route Layer → Ingestion: uploads · Document routes feed the ingestion pipeline
- Route Layer → Research Graph: streams · Chat routes stream live agent events from the workflow
- Route Layer → N8N Workflows: triggers · Automation workflows run outside the main request path