Portfolio Tracker: Vault Document Embedding System Documentation
Table of Contents
- Overview
- System Architecture
- Database Schema
- Document Processing Pipeline
- User Interface Components
- API Endpoints
- Vector Search Implementation
- Chat Integration
- Security Considerations
- Performance Optimizations
- Troubleshooting
- Future Improvements
Overview
The Vault Document Embedding System is a comprehensive document management solution integrated into the Portfolio Tracker application. It enables users to upload, organize, and semantically search through their documents using advanced natural language processing techniques. The system processes various document types, extracts their text content, splits them into semantically meaningful chunks, generates high-quality vector embeddings, and stores them for efficient retrieval during chat interactions. All document content is securely encrypted at rest, ensuring the highest level of data privacy and security.Key Features
- Document Management: Upload, organize, rename, and delete documents
- Folder Organization: Create and manage folders to organize documents
- Document Processing: Extract text from various file formats (PDF, DOCX, TXT, CSV, HTML) with robust fallback mechanisms
- Content Encryption: All document content is encrypted using AES encryption with a dedicated vault document encryption key
- Decryption on Demand: Document content is only decrypted when needed for search results or display
- TLS Encryption: All data in transit is encrypted using TLS
- Database Encryption: Supabase provides encryption at rest for the database
- Storage Encryption: Uploaded documents are stored with encryption at rest
- API Key Protection: OpenAI API keys are stored server-side only, never exposed to the client
- Secure File Naming: Timestamps and sanitized filenames prevent information disclosure
- Natural Language Search: Find relevant document sections based on natural language queries with similarity threshold optimizations
- Chat Integration: Reference document content in chat conversations with proper citations and formatted displays
- Real-time Status Updates: Track document processing status with visual indicators
- Enhanced Markdown Rendering: Display document content with tables, code blocks, and other rich formatting
System Architecture
The Vault Document Embedding System follows a layered architecture with a strong focus on security and performance:- Presentation Layer: React components in the Next.js frontend with optimized hooks for document operations
- API Layer: Next.js API routes for handling document operations using hybrid processing approach
- Service Layer: Document processing and embedding generation logic with content encryption
- Data Layer: Supabase database with pgvector extension for vector storage and search
Hybrid Processing Approach
The system implements a hybrid client-server architecture that balances performance and security:-
Client-side Operations:
- Direct Supabase client access for status updates and document management
- Background processing status monitoring with polling
- UI state management with optimistic updates
-
Server-side Processing:
- Computationally intensive operations (text extraction, embedding generation)
- Secure handling of sensitive content with encryption
- Background processing for large documents
Technology Stack
- Frontend: Next.js 14+, React, TanStack Query, Tailwind CSS
- Backend: Next.js API routes, LangChain document loaders
- Database: Supabase with pgvector extension for similarity search
- Authentication: Clerk
- Storage: Supabase Storage with secure path generation
- Embeddings: OpenAI text-embedding-3-small model (1536 dimensions)
- Document Processing: LangChain, pdf-parse, mammoth
- Security: AES encryption for document content
- Markdown Rendering: react-markdown with remark-gfm for tables and react-syntax-highlighter for code blocks
Data Flow
- User uploads a document through the UI
- Document metadata is stored in the database and the file in Supabase Storage
- Document processing is initiated in the background
- Text is extracted, chunked, and embedded
- Embeddings are stored in the database
- UI reflects the processing status in real-time
- Documents become searchable in the chat interface
Database Schema
The system uses three primary tables in Supabase:vault_folders
Stores information about document folders for organization.vault_documents
Stores metadata about uploaded documents.vault_document_chunks
Stores the text chunks and their embeddings for semantic search.Document Processing Pipeline
The document processing pipeline is implemented in the central/app/api/document-processor/route.ts file and consists of several key stages:
1. Document Upload and Storage Path Architecture
When a user uploads a document, theuseUploadDocumentSync hook in /hooks/mutations/use-upload-document-sync.ts handles the process with an enhanced security-focused storage path architecture:
vault_documents table with initial processing_status set to ‘pending’.
2. Processing Initiation
After upload, the document processing is initiated via the/api/vault/process-document endpoint:
/app/api/vault/process-document/route.ts) initiates background processing:
2. Fallback Text Search Mechanism
The system includes a robust fallback text search mechanism to ensure search functionality even when vector search fails:3. Text Extraction
TheextractTextFromDocument function in /lib/document-processor.ts handles text extraction from various file types:
-
PDF: Primary extraction using PDFLoader from LangChain, with pdf-parse as a fallback mechanism. The system includes comprehensive error handling and detailed metadata extraction:
-
DOCX: Primary extraction using DocxLoader from LangChain, with mammoth as a fallback mechanism if DocxLoader fails. This dual approach ensures maximum compatibility with different Word document formats and structures:
- TXT: Direct text extraction with improved error handling
- CSV: Using CSVLoader from LangChain with direct text extraction as fallback
- HTML: Direct text extraction to preserve content
updateDocumentWithError and updateDocumentStatus functions to provide detailed status tracking and recovery mechanisms.
The system only allows users to upload file types that can be successfully processed, chunked, and embedded. This ensures that all documents in the vault can be properly searched and referenced in the chat interface.
4. Text Chunking
ThesplitDocumentsIntoChunks function divides documents into semantically meaningful chunks with comprehensive documentation and production-ready error handling:
- Semantic Chunking: Uses LangChain’s
RecursiveCharacterTextSplitterto create chunks that preserve semantic meaning - Configurable Parameters: Chunk size (1000 characters) and overlap (200 characters) are optimized for the embedding model
- Hierarchical Separators: Uses a hierarchy of separators (paragraphs, newlines, sentences, spaces) to preserve context
- Enhanced Metadata: Includes document name, folder information, page numbers, and source details for better citations
- Comprehensive Documentation: Detailed JSDoc comments explain the purpose and behavior of the function
- Robust Error Handling: Includes error recovery mechanisms and status tracking
5. Embedding Generation
ThegenerateEmbeddings function creates vector embeddings using OpenAI’s model:
text-embedding-3-small model because:
- It provides high-quality embeddings with 1536 dimensions
- Offers a good balance between quality and cost
- Has strong performance for semantic search applications
6. Storage in Database
ThestoreDocumentChunks function saves chunks and their embeddings to the database:
User Interface Components
The Vault UI is composed of several React components with enhanced rendering capabilities:Vault Page (/app/vault/page.tsx)
The main container component that orchestrates the vault experience:
Folder List (/app/vault/components/folder-list.tsx)
Displays and manages folders:
Document List (/app/vault/components/document-list.tsx)
Displays documents with processing status indicators:
Upload Document Dialog (/app/vault/components/upload-document.tsx)
Handles document uploads with drag-and-drop support for supported file types (PDF, DOCX, TXT, CSV, HTML):
Status Polling Mechanism
The document list implements a polling mechanism to update processing status:API Endpoints and Client-Side Data Access
The system uses a hybrid approach for data access, combining API endpoints for complex operations and direct client-side Supabase access for simpler operations:API Endpoints
These operations require server-side processing or access to service role keys:Document Management
- Document Processor:
/api/document-processor- Central API for document processing with text extraction, chunking, and embedding generation - Delete Document:
/api/vault/admin-delete- Admin endpoint to securely remove documents from storage - Download Document:
/api/vault/download-document- Retrieves files from storage
Deletion Process
Document deletion follows a secure two-step process:-
Client-Side Preparation:
-
Server-Side Deletion:
Folder Management
- Create Folder:
/api/vault/create-folder- Creates new folders - Delete Folder:
/api/vault/delete-folder- Removes folders and contained documents
Client-Side Data Access
The following operations use direct Supabase client access from React hooks, eliminating the need for API routes:User Preferences
- Mark Vault as Read: Updates the
has_read_vaultflag in the user’s profile via theuseUserInfohook
Search and Retrieval
- Search Documents: Uses the
useSearchDocumentshook to perform vector similarity search directly from the client- Includes automatic fallback to text search when vector search fails
- Provides loading states and error handling via React Query
- Maintains the same search capabilities as the previous API-based implementation
Document Processing Status
- Check Processing Status: Uses the
useDocumentProcessingStatushook to poll for document processing status- Automatically handles polling with configurable intervals
- Includes automatic fixing of inconsistent document states
- Provides detailed status information including counts by status type
- Stops polling automatically when all documents are processed
Document Management
- Rename Document: Updates document names directly via the
useRenameDocumenthook
Folder Management
- Rename Folder: Updates folder names directly via the
useRenameFolderhook
Process Document Endpoint
The/api/vault/process-document/route.ts endpoint is particularly important as it manages the document processing pipeline:
- Background Processing: Processing happens asynchronously to avoid blocking the API response
- Status Tracking: Document status is updated at each stage of processing
- Error Handling: Comprehensive error handling with status updates
Document Processing Status Hook
TheuseDocumentProcessingStatus hook provides client-side polling for document processing status:
Vector Search Implementation
The system uses Supabase’s pgvector extension for vector similarity search:SQL Function for Vector Search
A custom SQL functionmatch_documents is implemented in Supabase:
- Takes a query embedding vector and search parameters
- Performs cosine similarity search using the
<=>operator - Joins with document and folder tables to include metadata
- Filters by user ID for security
- Returns the most relevant chunks sorted by similarity
Document Search Implementation
ThesearchDocuments function in /lib/document-processor.ts has been optimized for production with improved error handling and fallback mechanisms:
Chat Integration
The document search is integrated with the chat system to provide document-based answers with enhanced formatting:Chat API Route
The/app/api/chat/route.ts file integrates document search into the chat with improved formatting and citation:
searchVaultDocuments function, which:
- Searches for relevant document chunks using vector similarity
- Formats the content with proper markdown for better readability
- Includes document and folder names for proper citation
- Returns the formatted results to the assistant
System Prompt Enhancement
The chat system prompt includes enhanced guidelines for document citations and response formatting:Direct Response Style
The system prompt also instructs the AI to provide direct answers without acknowledgment phrases:Security Considerations
Security is a paramount concern for the Vault Document System due to the sensitive nature of the stored documents. The system implements several advanced security measures:User-Based Access Control
- Document storage paths use folder UUIDs instead of user IDs for enhanced privacy
- Database RLS policies ensure users can only access their own documents
- Admin endpoints use service role keys to manage storage without exposing credentials to clients
Server-Side Validation
API endpoints validate requests on the server side:Secure Storage Access
Document storage uses Supabase Storage with proper access controls:Performance Optimizations
The system includes several optimizations to ensure responsive performance even with large document collections:Document Processing
- Hybrid Processing Model: Combines client-side operations for UI updates with server-side processing for computation-intensive tasks
- Background Processing: Documents are processed asynchronously to prevent UI blocking
- Batched Embedding Generation: Embeddings are generated in batches to avoid rate limits
- Chunking Strategy: Documents are split into optimal-sized chunks (1000 characters with 200 character overlap) for better semantic understanding
- Status Polling: Processing status is polled efficiently to provide real-time updates without overloading the server
- Production-Ready Logging: Console logs have been removed/commented for production environments
Vector Search
- pgvector Indexing: Utilizes pgvector’s HNSW indexing for faster search on large collections
- Custom RPC Function: Avoids multiple round trips by performing complex queries in a single database call
- Increased Similarity Threshold: Only returns results above a higher similarity threshold (0.6) for better precision
- Removed Fallback Complexity: Simplified fallback strategy for more reliable and predictable search behavior
- Result Limiting: Limits search results to the most relevant matches
- Efficient Content Handling: Only decrypts content for the specific chunks needed
Troubleshooting
Common issues and their solutions:Document Processing Issues
If document processing gets stuck or fails:- Check the document’s
processing_statusin the database - Verify file permissions in Supabase Storage
- Check server logs for errors during text extraction
- Ensure the document format is supported
Fallback Mechanism for DOCX and PDF Processing
The system implements a fallback mechanism for DOCX and PDF processing:- DOCX Fallback: If the primary DOCX processor (DocxLoader) fails, the system falls back to mammoth for text extraction.
- PDF Fallback: If the primary PDF processor (pdf-parse) fails, the system falls back to an alternative PDF parser.
Status Inconsistencies
If the UI shows incorrect processing status:- The check-processing-status endpoint includes automatic fixing of inconsistent states:
File Download Issues
If file downloads fail:- The document processor includes fallback mechanisms for file paths:
Document Extraction Issues
If text extraction from documents fails:- The system implements robust fallback mechanisms for different document types:
- Check if the document format is supported and properly formatted
- For complex documents, try simplifying them before upload
Future Improvements
Planned enhancements to the system include:Document Processing
- OCR Integration: Extract text from images and scanned documents
- Better PDF Handling: Improved extraction of structured content from PDFs
- Advanced Document Preprocessing: Text normalization and noise reduction techniques
- Additional Metadata Extraction: Enhanced extraction of document structure and metadata
- Improved Processing Status UI: More granular status reporting during processing
- Caching Mechanism: Add caching for frequently accessed documents and search results
- Batch Processing: Implement batch processing for multiple documents
- User Feedback Loop: Allow users to rate search result relevance to improve future searches
- Document Versioning: Track document versions and changes over time
- Enhanced Security: Add document-level access controls and sharing capabilities
This documentation provides a comprehensive overview of the Vault Document Embedding System in the Portfolio Tracker application. It covers the architecture, implementation details, and design decisions to help developers understand and extend the system.