# sopanmunde/ai-research-copilot architecture

> Architecture diagram of the GitHub repository sopanmunde/ai-research-copilot, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-30). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/sopanmunde/ai-research-copilot
- Repository: https://github.com/sopanmunde/ai-research-copilot

## Overview

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: [`backend/src/api/routes`](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/api/routes) (Route Layer), [`backend/src/workflows/research_workflow.py`](https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/src/workflows/research_workflow.py) (Research Graph), [`backend/src/rag/ingestion`](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/rag/ingestion) (Ingestion), [`backend/src/agents/langgraph/nodes`](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/agents/langgraph/nodes) (Graph Nodes)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_fe_app["Next.js App<br/>web app"]
  node_fe_ui["Chat UI<br/>react components"]
  node_fe_hooks["UI Hooks<br/>client state"]
  node_fe_api["API Client<br/>frontend service<br/>[api.ts]"]
end

subgraph group_backend["Backend"]
  node_be_entry["App Entry<br/>fastapi bootstrap<br/>[index.py]"]
  node_be_main["API App<br/>fastapi core<br/>[main.py]"]
  node_be_routes["Route Layer<br/>http api"]
  node_be_services["Services<br/>business logic"]
  node_be_security["Core Security<br/>runtime core"]
  node_be_middleware["Middleware<br/>request controls"]
end

subgraph group_rag["RAG / Agents"]
  node_rag_workflow["Research Graph<br/>langgraph workflow"]
  node_rag_nodes["Graph Nodes<br/>agent nodes"]
  node_rag_retrieval["Retrieval"]
  node_rag_ingestion["Ingestion<br/>document pipeline"]
  node_rag_memory["Memory<br/>context store"]
end

subgraph group_data["Data Layer"]
  node_rag_vector[("Pinecone Store<br/>vector index<br/>[pinecone_store.py]")]
  node_db_mongo[("MongoDB<br/>operational db")]
  node_ext_gemini(("Gemini LLM<br/>external model"))
  node_ext_redis(("Redis Cache<br/>external cache"))
end

subgraph group_automation["Automation"]
  node_auto_workflows["N8N Workflows<br/>automation"]
end

node_fe_app -->|"renders"| node_fe_ui
node_fe_ui -->|"uses"| node_fe_hooks
node_fe_hooks -->|"calls"| node_fe_api
node_fe_api -->|"HTTP/SSE"| node_be_routes
node_be_entry -->|"boots"| node_be_main
node_be_main -->|"registers"| node_be_routes
node_be_routes -->|"protects"| node_be_middleware
node_be_routes -->|"delegates"| node_be_services
node_be_middleware -->|"uses"| node_be_security
node_be_services -->|"orchestrates"| node_rag_workflow
node_rag_workflow -->|"executes"| node_rag_nodes
node_rag_nodes -->|"retrieves"| node_rag_retrieval
node_rag_nodes -->|"loads"| node_rag_memory
node_rag_retrieval -->|"searches"| node_rag_vector
node_rag_retrieval -->|"filters"| node_db_mongo
node_rag_ingestion -->|"indexes"| node_rag_vector
node_rag_ingestion -->|"persists"| node_db_mongo
node_rag_ingestion -->|"embeds"| node_ext_gemini
node_rag_workflow -->|"generates"| node_ext_gemini
node_rag_workflow -.->|"caches"| node_ext_redis
node_be_routes -->|"reads/writes"| node_db_mongo
node_be_routes -->|"uploads"| node_rag_ingestion
node_be_routes -->|"streams"| node_rag_workflow
node_be_routes -.->|"triggers"| node_auto_workflows

click node_fe_app "https://github.com/sopanmunde/ai-research-copilot/tree/main/frontend/app"
click node_fe_ui "https://github.com/sopanmunde/ai-research-copilot/tree/main/frontend/components"
click node_fe_hooks "https://github.com/sopanmunde/ai-research-copilot/tree/main/frontend/hooks"
click node_fe_api "https://github.com/sopanmunde/ai-research-copilot/blob/main/frontend/lib/api.ts"
click node_be_entry "https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/index.py"
click node_be_main "https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/src/main.py"
click node_be_routes "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/api/routes"
click node_be_services "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/services"
click node_be_security "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/core"
click node_be_middleware "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/middleware"
click node_rag_workflow "https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/src/workflows/research_workflow.py"
click node_rag_nodes "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/agents/langgraph/nodes"
click node_rag_retrieval "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/rag/retrieval"
click node_rag_ingestion "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/rag/ingestion"
click node_rag_memory "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/rag/memory"
click node_rag_vector "https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/src/rag/vectorstores/pinecone_store.py"
click node_db_mongo "https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/database/mongodb"
click node_auto_workflows "https://github.com/sopanmunde/ai-research-copilot/tree/main/workflows/n8n"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_fe_app,node_fe_ui,node_fe_hooks,node_fe_api toneBlue
class node_be_entry,node_be_main,node_be_routes,node_be_services,node_be_security,node_be_middleware toneAmber
class node_rag_workflow,node_rag_nodes,node_rag_retrieval,node_rag_ingestion,node_rag_memory toneMint
class node_rag_vector,node_db_mongo,node_ext_gemini,node_ext_redis toneRose
class node_auto_workflows toneIndigo
```

## Components

### Frontend

Next.js app and UI interaction layer

- [Next.js App](https://github.com/sopanmunde/ai-research-copilot/tree/main/frontend/app): web app · App Router pages for dashboard, login, settings, and landing UI · `frontend/app`
- [Chat UI](https://github.com/sopanmunde/ai-research-copilot/tree/main/frontend/components): react components · Primary assistant, chat, composer, sidebar, and message components · `frontend/components`
- [UI Hooks](https://github.com/sopanmunde/ai-research-copilot/tree/main/frontend/hooks): client state · Chat, streaming, and upload hooks that keep the UI event-driven · `frontend/hooks`
- [API Client](https://github.com/sopanmunde/ai-research-copilot/blob/main/frontend/lib/api.ts): frontend service · Typed client and request helpers for backend calls · `frontend/lib/api.ts`

### Backend

FastAPI API, orchestration, and business logic

- [App Entry](https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/index.py): fastapi bootstrap · Backend startup and FastAPI app assembly · `backend/index.py`
- [API App](https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/src/main.py): fastapi core · Central application wiring and route registration · `backend/src/main.py`
- [Route Layer](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/api/routes): http api · Auth, chat, conversation, report, upload, model, and health endpoints · `backend/src/api/routes`
- [Services](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/services): business logic · Chat, LLM, and report facades over orchestration and persistence · `backend/src/services`
- [Core Security](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/core): runtime core · Shared config, security, logging, cache, exceptions, and constants · `backend/src/core`
- [Middleware](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/middleware): request controls · Prompt injection guard and request logging · `backend/src/middleware`

### RAG / Agents

Retrieval, memory, embedding, and LangGraph workflow

- [Research Graph](https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/src/workflows/research_workflow.py): langgraph workflow · Planner, retriever, citation, summarizer, and report pipeline · `backend/src/workflows/research_workflow.py`
- [Graph Nodes](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/agents/langgraph/nodes): agent nodes · Concrete LangGraph node implementations · `backend/src/agents/langgraph/nodes`
- [Retrieval](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/rag/retrieval): rag retrieval · Semantic search, contextual ranking, and citation-aware evidence selection · `backend/src/rag/retrieval`
- [Ingestion](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/rag/ingestion): document pipeline · Loaders, chunking, metadata extraction, and embedding pipeline · `backend/src/rag/ingestion`
- [Memory](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/rag/memory): context store · Conversation and research context reconstruction · `backend/src/rag/memory`

### Data Layer

Durable storage and vector search

- [Pinecone Store](https://github.com/sopanmunde/ai-research-copilot/blob/main/backend/src/rag/vectorstores/pinecone_store.py): vector index · Semantic corpus for retrieval over embedded document chunks · `backend/src/rag/vectorstores/pinecone_store.py`
- [MongoDB](https://github.com/sopanmunde/ai-research-copilot/tree/main/backend/src/database/mongodb): operational db · Users, conversations, messages, documents, and reports · `backend/src/database/mongodb`
- **Gemini LLM**: external model · Primary generation and reasoning provider
- **Redis Cache**: external cache · Optional cache for RAG acceleration

### Automation

External scheduled and event-driven workflows

- [N8N Workflows](https://github.com/sopanmunde/ai-research-copilot/tree/main/workflows/n8n): automation · Scheduled reports, research alerts, and Slack bot automations · `workflows/n8n`

## Connections

- 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
