Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Document Copilot

An intelligent AI-powered document analysis platform enabling users to query large document repositories in natural language and receive sourced, citable answers with full citation traceability.

Python FastAPI React TypeScript License


πŸ“Œ Overview

Document Copilot is a full-stack AI application designed for research professionals, analysts, and knowledge workers who spend significant time extracting insights from document repositories. The platform eliminates manual document intake workflows by enabling natural language queries across entire document corpora and providing intelligent, sourced answers with complete citation trails.

Primary Use Case

Research analysts at investment firms can query financial documents (10-Ks, 10-Qs, earnings reports) in plain English and receive citable answers, allowing them to skip tedious document review and jump directly to generating original research insights.


✨ Core Features

  • Natural Language Querying β€” Ask questions in conversational English; receive intelligent answers from document corpus
  • Citation & Traceability β€” Every response includes source document references and exact passage citations for verification
  • Hybrid Retrieval System β€” Combines vector-based semantic search (pgvector) with PostgreSQL full-text search for comprehensive results
  • Persistent Chat History β€” Maintain conversation threads with complete message history and citation metadata
  • Enterprise Authentication β€” Email-based authentication powered by Supabase Auth with JWT tokens
  • Streaming Chat Interface β€” Real-time streaming responses for responsive, interactive user experience
  • Type-Safe LLM Orchestration β€” Backend uses PydanticAI for robust, typed interactions with language models
  • Scalable Architecture β€” Clean separation of concerns with frontend SPA, Python backend, and managed database

πŸ—οΈ Architecture Overview

Document Copilot implements a three-layer architecture with clear separation of concerns:

System Layers

Layer Technology Responsibility
Frontend Vite + React + TypeScript User interface, local state, authenticated requests to backend
Backend Python 3.12+ + FastAPI Authorization, document retrieval, LLM orchestration, persistence
Database Supabase Postgres + pgvector Users, authentication, chat threads, documents, embeddings, citations

Key Architectural Principles

Frontend Responsibilities:

  • User authentication state management
  • Chat UI rendering and local message state
  • HTTP requests to backend with bearer tokens
  • Never holds service credentials or calls external APIs directly

Backend Responsibilities:

  • JWT token verification and authorization
  • Document retrieval and semantic search
  • LLM prompt construction and execution
  • Citation validation and response streaming
  • Durable persistence of messages and metadata

Database Responsibilities:

  • User authentication and session management
  • User-scoped data access control
  • Full-text search vector maintenance
  • Embedding storage for semantic search

Request Flow

1. User signs in with email β†’ Supabase Auth (JWT issued)
2. Frontend stores JWT from Supabase session
3. User opens chat thread β†’ Frontend loads history from FastAPI
4. User submits message β†’ Frontend sends to /chat/stream with JWT
5. Backend verifies JWT with Supabase Auth
6. FastAPI creates request context (user, thread, Supabase client, LLM settings)
7. PydanticAI agent retrieves relevant chunks via hybrid search
8. Agent generates grounded answer with citations
9. Backend streams response to browser in AI SDK format
10. Backend persists messages, citations, and usage metrics to Supabase

For detailed architecture documentation, see ARCHITECTURE.md.


πŸ› οΈ Technology Stack

Backend

Component Technology Purpose
Framework FastAPI + Uvicorn Async HTTP server with automatic OpenAPI docs
Validation Pydantic v2 + pydantic-settings Request/response validation and config management
LLM Orchestration PydanticAI + OpenAI SDK Type-safe agent framework for model interactions
Database ORM SQLAlchemy SQL toolkit and ORM for data models
Migrations Alembic Database schema versioning and migrations
Vector Search Supabase pgvector Semantic similarity search on embeddings
Full-Text Search PostgreSQL FTS Lexical keyword search for hybrid retrieval
Logging structlog Structured JSON logging for production monitoring
HTTP Client httpx Async HTTP client for outbound requests

Frontend

Component Technology Purpose
Framework React 18+ Component-based UI library
Language TypeScript Type-safe JavaScript development
Build Tool Vite Lightning-fast frontend development server
Routing React Router Client-side navigation and route management
UI Components shadcn/ui + Tailwind CSS Pre-built accessible components with utility CSS
Auth Client @supabase/supabase-js Browser-based Supabase authentication
Chat State Vercel AI SDK React hooks and streaming client for chat UX

Infrastructure & Data

Component Technology Purpose
Database Supabase Postgres Managed PostgreSQL with pgvector extension
Authentication Supabase Auth Email-based authentication with JWT
Embeddings OpenAI API Text embedding generation for semantic search
LLM Provider OpenAI API GPT models for answer generation
Hosting Railway Application deployment and management

πŸ“ Repository Structure

document-copilot/
β”‚
β”œβ”€β”€ πŸ“„ ARCHITECTURE.md           # Detailed system design & data flow diagrams
β”œβ”€β”€ πŸ“„ AGENTS.md                 # LLM agent instructions & prompt design
β”œβ”€β”€ πŸ“„ README.md                 # This file
β”‚
β”œβ”€β”€ πŸ“‚ data/                     # Document corpus management
β”‚   β”œβ”€β”€ download.py              # Script to fetch and process documents
β”‚   └── corpus/                  # Local document storage (gitignored)
β”‚
β”œβ”€β”€ πŸ“‚ docs/                     # Documentation
β”‚   β”œβ”€β”€ client-brief.md          # Client requirements & business context
β”‚   └── API.md                   # Backend API documentation
β”‚
β”œβ”€β”€ πŸ“‚ backend/                  # FastAPI application
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”‚   β”œβ”€β”€ chat.py          # Chat streaming & thread endpoints
β”‚   β”‚   β”‚   └── documents.py     # Document management endpoints
β”‚   β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   β”‚   └── dependencies.py  # Supabase JWT verification
β”‚   β”‚   β”œβ”€β”€ retrieval/
β”‚   β”‚   β”‚   β”œβ”€β”€ search.py        # Hybrid semantic + FTS search
β”‚   β”‚   β”‚   └── chunking.py      # Document chunking strategy
β”‚   β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”‚   β”œβ”€β”€ user.py          # User ORM model
β”‚   β”‚   β”‚   β”œβ”€β”€ chat.py          # Chat thread & message models
β”‚   β”‚   β”‚   └── document.py      # Document & chunk models
β”‚   β”‚   β”œβ”€β”€ schema/
β”‚   β”‚   β”‚   β”œβ”€β”€ chat.py          # Pydantic request/response models
β”‚   β”‚   β”‚   └── document.py      # Document schemas
β”‚   β”‚   β”œβ”€β”€ agents/
β”‚   β”‚   β”‚   └── answer_agent.py  # PydanticAI agent for answer generation
β”‚   β”‚   β”œβ”€β”€ settings.py          # Environment configuration
β”‚   β”‚   └── main.py              # FastAPI app initialization
β”‚   β”œβ”€β”€ migrations/              # Alembic database migrations
β”‚   β”œβ”€β”€ requirements.txt         # Python dependencies
β”‚   β”œβ”€β”€ .env.example             # Environment template
β”‚   └── pyproject.toml           # uv project configuration
β”‚
└── πŸ“‚ frontend/                 # React Vite SPA
    β”œβ”€β”€ src/
    β”‚   β”œβ”€β”€ lib/
    β”‚   β”‚   β”œβ”€β”€ env.ts           # Environment variable validation
    β”‚   β”‚   β”œβ”€β”€ supabase.ts      # Supabase client initialization
    β”‚   β”‚   β”œβ”€β”€ http.ts          # HTTP client with auth & error handling
    β”‚   β”‚   └── api.ts           # Product API calls (threads, messages)
    β”‚   β”œβ”€β”€ pages/
    β”‚   β”‚   β”œβ”€β”€ auth/            # Authentication pages
    β”‚   β”‚   └── chat/            # Chat interface pages
    β”‚   β”œβ”€β”€ components/
    β”‚   β”‚   β”œβ”€β”€ chat/            # Chat components (messages, input, citations)
    β”‚   β”‚   β”œβ”€β”€ common/          # Reusable components (buttons, modals)
    β”‚   β”‚   └── layout/          # Layout components (header, sidebar)
    β”‚   β”œβ”€β”€ hooks/
    β”‚   β”‚   └── useChat.ts       # Custom chat hook wrapper
    β”‚   β”œβ”€β”€ types/               # TypeScript type definitions
    β”‚   β”œβ”€β”€ styles/              # Global styles and Tailwind config
    β”‚   └── App.tsx              # Main app component
    β”œβ”€β”€ index.html               # HTML entry point
    β”œβ”€β”€ vite.config.ts           # Vite build configuration
    β”œβ”€β”€ tailwind.config.js       # Tailwind CSS configuration
    β”œβ”€β”€ .env.example             # Environment template
    └── package.json             # Node.js dependencies

πŸš€ Quick Start Guide

Prerequisites

Before starting, ensure you have the following installed:

Tool Version Purpose Installation
Python 3.12+ Backend runtime python.org or OS package manager
uv latest Python package manager curl -LsSf https://astral.sh/uv/install.sh | sh
Node.js 18+ Frontend tooling nodejs.org or nvm
Git latest Version control git-scm.com

Backend Setup

  1. Clone and navigate to backend:

    git clone <repository-url>
    cd document-copilot/backend
  2. Install dependencies with uv:

    uv sync
  3. Configure environment variables:

    cp .env.example .env

    Edit .env and add your credentials:

    # Supabase Configuration
    SUPABASE_URL=https://your-project.supabase.co
    SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIs...
    SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIs...
    
    # OpenAI Configuration
    OPENAI_API_KEY=sk-...
    OPENAI_EMBED_MODEL=text-embedding-3-small
    
    # Server Configuration
    API_BASE_URL=http://localhost:8000
    ENVIRONMENT=development
    LOG_LEVEL=INFO
  4. Run database migrations:

    uv run alembic upgrade head
  5. Start backend server:

    uv run uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

    βœ… Backend available at http://localhost:8000 πŸ“– API docs at http://localhost:8000/docs

Frontend Setup

  1. Navigate to frontend directory:

    cd document-copilot/frontend
  2. Install dependencies:

    npm install
    # or
    pnpm install
  3. Configure environment variables:

    cp .env.example .env.local

    Edit .env.local:

    VITE_API_BASE_URL=http://localhost:8000
    VITE_SUPABASE_URL=https://your-project.supabase.co
    VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIs...
  4. Start development server:

    npm run dev

    βœ… Frontend available at http://localhost:5173

Verification

  • Backend: Navigate to http://localhost:8000/docs and verify OpenAPI endpoints are available
  • Frontend: Navigate to http://localhost:5173 and verify the login page loads
  • Connection: Sign in with a test email and verify the chat interface renders

πŸ’¬ Usage

User Workflow

  1. Authentication

    • User navigates to app and clicks "Sign In"
    • Enters email address
    • Receives verification link
    • Clicks link and is authenticated
  2. Chat Interface

    • User creates new chat thread or opens existing conversation
    • Types question about documents in natural language
    • System retrieves relevant document chunks
    • LLM generates sourced answer with citations
    • User can click citations to view exact source passages
  3. Citation Verification

    • Each answer includes inline citations with source document
    • Click citation to view highlighted passage in original document
    • Track which documents supported which claims

Example Queries

Q: "What are the primary risk factors mentioned in recent filings?"
β†’ Returns answer from 10-K documents with citations

Q: "How has revenue changed year-over-year?"
β†’ Extracts financial metrics with source references

Q: "Summarize the management discussion for Q3"
β†’ Synthesizes MD&A sections with proper citations

πŸ” Security Considerations

Authentication Flow

  • All user endpoints require Supabase JWT token in Authorization: Bearer <token> header
  • Backend verifies token with Supabase before processing requests
  • Service role key used only for privileged operations with explicit user binding

Data Access Control

  • Frontend uses VITE_SUPABASE_ANON_KEY for limited browser access
  • Backend uses service role key only for server-side writes
  • All user-scoped queries filtered by authenticated user ID
  • Environment variables never leaked to frontend except public keys

Best Practices

  • Never commit .env files; use .env.example templates
  • Rotate API keys regularly in production
  • Use HTTPS in production environments
  • Implement rate limiting on backend endpoints
  • Monitor logs for suspicious authentication attempts

πŸ“Š Database Schema

Core Tables

  • users β€” User accounts with email and profile data
  • chat_threads β€” Conversation threads owned by users
  • chat_messages β€” Individual messages with role (user/assistant) and content
  • documents β€” Source documents with metadata and chunking info
  • document_chunks β€” Individual text chunks with embeddings
  • embeddings β€” Vector embeddings for semantic search (pgvector)
  • citations β€” Links between messages and source chunks for traceability

See ARCHITECTURE.md for detailed schema design.


πŸ€– LLM Configuration

Model Selection

  • Generation: GPT-4 / GPT-4 Turbo for answer generation (configurable)
  • Embeddings: text-embedding-3-small for semantic search
  • Context Window: Default 4K tokens (adjustable per request)

Agent Behavior

  • PydanticAI agent retrieves relevant chunks based on user query
  • Constructs prompt with chunk context and citation requirements
  • Generates structured output: answer text + cited passages
  • Validates citations exist in retrieved documents before responding

See AGENTS.md for detailed prompt engineering guidelines.


πŸ› οΈ Development

Running Tests

# Backend tests
cd backend
uv run pytest tests/ -v

# Frontend tests
cd frontend
npm run test

Code Standards

  • Backend: Follow PEP 8, use type hints, format with black
  • Frontend: Use Prettier for formatting, ESLint for linting
  • Database: Migrations tracked in Alembic with descriptive names
  • Commits: Use conventional commit messages (feat:, fix:, docs:, etc.)

Database Migrations

# Create new migration
uv run alembic revision --autogenerate -m "description"

# Review migration before applying
uv run alembic upgrade head

πŸ“ˆ Performance Considerations

Optimization Strategies

  • Retrieval: Hybrid search (vector + FTS) balances precision and recall
  • Streaming: Chat responses streamed to browser for perceived speed
  • Caching: Consider caching frequent document chunks and embeddings
  • Pagination: Load chat history in pages, not all at once

Monitoring

  • Backend logs all LLM calls, retrieval time, and token usage
  • Track citation accuracy and user satisfaction metrics
  • Monitor database query performance, especially on large corpora

πŸ“š Documentation


🀝 Contributing

We welcome contributions! Please follow these guidelines:

  1. Fork the repository and create a feature branch

    git checkout -b feature/your-feature-name
  2. Make your changes following code standards above

  3. Write tests for new functionality

  4. Submit a pull request with clear description of changes

  5. Code review β€” Address feedback from maintainers

Areas for Contribution

  • Additional LLM models and providers
  • Enhanced retrieval algorithms
  • Document processing improvements
  • Frontend UI/UX enhancements
  • Performance optimizations
  • Documentation and examples

πŸ› Known Issues & Limitations

  • Citation accuracy depends on chunking strategy and retrieval quality
  • Large document corpora may require optimization of vector indices
  • Streaming responses may timeout on very long answers
  • Email-only authentication (future: add OAuth providers)

πŸ“„ License

This project is licensed under the MIT License β€” see LICENSE file for details.


🎯 Roadmap

Phase 1 (Current)

  • βœ… Core chat interface
  • βœ… Hybrid retrieval system
  • βœ… Citation tracking
  • βœ… Supabase auth

Phase 2

  • πŸ“‹ Document upload UI
  • πŸ“‹ Advanced search filters
  • πŸ“‹ Conversation export
  • πŸ“‹ Multi-user collaboration

Phase 3

  • πŸ“‹ Custom LLM fine-tuning
  • πŸ“‹ Knowledge graph construction
  • πŸ“‹ Analytics dashboard
  • πŸ“‹ Enterprise SSO

πŸ€” FAQ

Q: Can I use different LLM providers? A: Yes. Modify the backend LLM client in app/agents/answer_agent.py to use Claude, Anthropic, or other providers.

Q: How do I add new documents? A: Use the document upload endpoint (frontend) or batch import via data/download.py script.

Q: What's the maximum document corpus size? A: No hard limit, but performance depends on embedding index optimization. Test with your scale.

Q: How are embeddings updated? A: Automatically when documents are chunked. See migration pipeline in backend.


πŸ“ž Support & Contact

For issues, feature requests, or questions:


πŸ™ Acknowledgments


Document Copilot β€” Turning documents into insights through AI. πŸš€

About

An intelligent AI-powered document analysis platform enabling users to query large document repositories in natural language and receive sourced, citable answers with full citation traceability.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages