An intelligent document processing system that automatically extracts entities and relationships from local documents to build a queryable knowledge graph using advanced NLP, Google Gemini, and Neo4j.
- π Smart Document Chunking: Automatically splits large documents into optimal segments for better entity extraction
- π€ AI-Powered Extraction: Uses Google Gemini with SUBJECT-PREDICATE-OBJECT focused prompts
- π Granular Relationships: Creates specific, meaningful relationship types instead of generic connections
- π€ ALL CAPS Standards: Enforces uppercase relationship types for consistency (e.g.,
WORKS_FOR,HAS_BUDGET) - π§ Dynamic Type Learning: Automatically discovers and reuses entity/relationship types across documents
- π·οΈ Dynamic Node Labels: Creates specific Neo4j labels (
:Entity:PERSON,:Entity:API) for better graph performance - ποΈ Domain-Specific Fallbacks: Supabase-powered domain type storage with intelligent caching
- π Verb-Based Extraction: Learns relationship patterns from document verbs for improved accuracy
- β‘ Async Processing: High-performance concurrent document processing
- π Rich Visualization: Real-time processing feedback with progress indicators
- π Comprehensive Testing: 75+ test cases ensuring reliability
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtCopy the example environment file and fill in your credentials:
cp .env.example .envEdit .env with your API keys:
# Required credentials
GOOGLE_API_KEY=your_google_gemini_api_key_here
LLAMA_CLOUD_API_KEY=your_llamaparse_api_key_here
NEO4J_PASSWORD=your_neo4j_password_here
# Supabase Database (replaces static models)
SUPABASE_URL=https://your-project-ref.supabase.co
SUPABASE_API_KEY=your_supabase_api_key_here
# Local file configuration
DOCUMENTS_INPUT_DIR=./documents- Create a new project at Supabase
- Go to SQL Editor in your Supabase dashboard
- Run the schema script:
-- Copy and paste the contents of supabase/migrations/20250830_create_domain_types_schema.sql - Test your database connection:
python tests/demo_supabase_mcp_workflow.py
Supabase Features:
- Domain Type Caching: Stores discovered entity/relationship types by domain
- Document Analysis Cache: Avoids re-analyzing similar documents
- Verb Extraction Storage: Learns relationship patterns from document text
- Fallback Intelligence: Provides domain-specific types when AI services are unavailable
Place your documents in the configured directory (default: ./documents/):
# Example documents are already provided
ls documents/
# sample_policy.md
# meeting_notes_project_alpha.md
# contract_amendment_vendor.mdSupported formats:
- PDF (
.pdf) - Word Documents (
.docx) - Text files (
.txt,.md) - HTML (
.html) - PowerPoint (
.pptx) - Excel (
.xlsx)
# Process all documents once
python run.py
# Or use watch mode for continuous processing
WATCH_DIRECTORY=true python run.pyWhat happens during processing:
- π Document Chunking: Large documents are split into optimal segments (2000 chars with 200 char overlap)
- π€ AI Extraction: Each chunk is processed with SUBJECT-PREDICATE-OBJECT focused prompts
- π Relationship Creation: Generates specific relationship types like
WORKS_FOR,HAS_BUDGET,MANAGES - π€ Type Standardization: All relationship types converted to ALL CAPS for consistency
- π·οΈ Dynamic Labeling: Entities get specific Neo4j labels (
:Entity:PERSON,:Entity:API) - ποΈ Domain Learning: Types are stored in Supabase by domain for future fallback use
- π Graph Building: Entities and relationships saved to Neo4j with full provenance
- β Validation: Comprehensive testing ensures data quality
- Go to Google AI Studio
- Create a new API key
- Add it to your
.envfile asGOOGLE_API_KEY
- Sign up at LlamaParse
- Get your API key from the dashboard
- Add it to your
.envfile asLLAMA_CLOUD_API_KEY
- Create a project at Supabase
- Go to Settings > API in your dashboard
- Copy your project URL and "anon public" key
- Add them to your
.envfile asSUPABASE_URLandSUPABASE_API_KEY - Run the database schema: Copy
supabase/migrations/20250830_create_domain_types_schema.sqlto your Supabase SQL editor - Test integration:
python tests/demo_supabase_mcp_workflow.py
- Install Neo4j Desktop or use Neo4j Aura
- Create a database
- Set your password in
.envasNEO4J_PASSWORD
The system features a sophisticated multi-agent architecture with specialized components:
- π₯ Ingestion Agent - Scans and processes local files with hash-based change detection
- π§ Extraction Agent - Advanced entity extraction using:
- Document Chunking: Smart segmentation for optimal processing
- SPO Extraction: SUBJECT-PREDICATE-OBJECT focused relationship identification
- Dynamic Type Management: Automatic type discovery and reuse
- Domain-Specific Learning: Supabase-powered type caching by domain
- Verb Pattern Recognition: Learns relationships from document verbs
- Fallback Processing: Pattern-based extraction when AI fails
- π Graph Construction Agent - Builds Neo4j knowledge graph with:
- ALL CAPS Relationships: Standardized relationship type formatting
- Dynamic Node Labels: Specific type labels (
:Entity:PERSON,:Entity:API) - Deduplication: Smart entity and relationship merging
- Provenance Tracking: Full data lineage preservation
- β‘ Async Processing: Concurrent document handling for performance
- π Type Resolution: Intelligent entity/relationship type matching
- π·οΈ Dynamic Node Labels: Neo4j-specific labels for enhanced querying (
:Entity:PERSON,:Entity:API) - ποΈ Domain Intelligence: Supabase-powered domain-specific type learning and caching
- οΏ½ Verb Pattern Learning: Automatic relationship discovery from document verbs
- οΏ½π Real-time Feedback: Rich progress indicators and statistics
- π§ͺ Comprehensive Testing: 75+ test cases with 100% pass rate
- π οΈ Utility Scripts: Database management and relationship analysis tools
Documents β Chunking β AI Extraction β Type Resolution β Graph Construction β Neo4j
β β β β β
File Hash Domain Analysis Verb Learning Dynamic Labels Specific Labels
β β β β β
Supabase β------ Domain Types β----- Pattern Cache β-- Provenance β-- :Entity:TYPE
Key Improvements:
- Dynamic Labels: Nodes get both
:Entityand specific type labels for better performance - Domain Learning: System learns domain-specific patterns and caches them in Supabase
- Verb Intelligence: Relationship types derived from actual document language patterns
akg/
βββ .github/
β βββ SPECS.md # Project specifications
β βββ TODO.md # Task tracking
βββ src/akg/
β βββ agents/ # Processing agents
β β βββ extraction.py # Advanced AI extraction with chunking
β β βββ ingestion.py # File processing and monitoring
β β βββ fallback_extraction.py # Pattern-based backup
β βββ database/ # Database managers
β β βββ neo4j_manager.py # Graph database operations
β β βββ supabase_manager.py # Document storage
β βββ parsers/ # Document parsers
β β βββ document_parser.py # Multi-format parsing
β βββ config.py # Configuration management
β βββ models.py # Data models
β βββ types.py # Type definitions
β βββ main.py # Application entry point
βββ tests/ # Comprehensive test suite
β βββ test_*.py # Unit tests (71+ tests)
β βββ clear_and_reprocess.py # Database utilities
β βββ check_relationships.py # Analysis tools
βββ documents/ # Input documents directory
βββ .env.example # Environment template
βββ requirements.txt # Python dependencies
βββ run.py # CLI runner
Key configuration options in .env:
# Document Processing
DOCUMENTS_INPUT_DIR=./documents
SUPPORTED_FILE_TYPES=pdf,docx,txt,md,html,pptx,xlsx
WATCH_DIRECTORY=true
RECURSIVE_SCAN=true
# AI Extraction Settings
MAX_CONCURRENT_DOCUMENTS=5
CHUNK_SIZE=2000 # Optimal chunk size for AI processing
OVERLAP_SIZE=200 # Overlap between chunks for context
# Graph Configuration
SIMILARITY_THRESHOLD=0.8 # Entity matching threshold
PROVENANCE_ENABLED=true # Track data lineage
MAX_GRAPH_DEPTH=5 # Maximum relationship traversal depth
# Performance Tuning
LOG_LEVEL=INFO # Logging verbosityThe system includes comprehensive testing with 75+ test cases:
# Run the full test suite
python -m pytest tests/ -v
# Test specific components
python -m pytest tests/test_extraction.py -v
python -m pytest tests/test_neo4j_manager.py -v
python -m pytest tests/test_dynamic_node_types.py -v
# Test domain-specific features
python tests/test_supabase_domain_types.py
python tests/demo_supabase_mcp_workflow.py
# Database utilities
python tests/clear_and_reprocess.py # Reset and reprocess
python tests/check_relationships.py # Analyze relationshipsTest Coverage:
- β Entity extraction with chunking
- β Relationship type standardization (ALL CAPS)
- β
Dynamic node labeling (
:Entity:PERSON,:Entity:API) - β Domain-specific type learning and caching
- β Verb-based relationship extraction
- β Neo4j graph operations
- β Supabase domain type integration
- β Type resolution and deduplication
- β Async processing workflows
- β Error handling and fallbacks
The system comes with sample documents that demonstrate advanced extraction capabilities:
1. Meeting Notes β Knowledge Graph
Input: "Sarah Johnson manages Project Alpha with a $500,000 budget..."
Output:
- Entities: Sarah Johnson (Person), Project Alpha (Project), $500,000 (Money)
- Relationships: Sarah Johnson -MANAGES-> Project Alpha, Project Alpha -HAS_BUDGET-> $500,000
2. Contract Documents β Structured Data
Input: "TechCorp Solutions Inc. represented by Michael Thompson..."
Output:
- Entities: TechCorp Solutions Inc. (Company), Michael Thompson (Person)
- Relationships: TechCorp Solutions Inc. -REPRESENTED_BY-> Michael Thompson
3. Document Chunking in Action
- Large documents automatically split into 2000-character segments
- 200-character overlap maintains context between chunks
- Each chunk processed independently for maximum granularity
- Results merged with intelligent deduplication
- Dynamic labels applied:
:Entity:PERSON,:Entity:API,:Entity:DATABASE
4. Domain-Specific Learning
- System recognizes document domains (technical, business, legal)
- Entity and relationship types cached by domain in Supabase
- Verb patterns learned from document text for relationship discovery
- Fallback types available when AI services are unavailable
The system creates specific, meaningful relationships:
- Professional:
WORKS_FOR,MANAGES,REPORTS_TO,EMPLOYS - Financial:
HAS_BUDGET,ALLOCATED_BUDGET,HAS_COST - Temporal:
OCCURRED_ON,SCHEDULED_FOR,DEADLINE_IS - Contractual:
INVOLVES_COMPANY,REPRESENTED_BY,INCLUDES_SERVICE - Technical:
USES,DEPLOYED_ON,DEVELOPED,REQUIRES
Neo4j Graph Statistics:
- Entities: 150+ with 25+ types (each with specific labels like
:Entity:PERSON) - Relationships: 300+ with 50+ specific types
- All relationship types in standardized ALL CAPS format
- Domain-specific type distribution tracked in Supabase
Dynamic Node Labels:
- Traditional: All nodes labeled as
:Entitywithtypeproperty - Enhanced: Nodes get specific labels like
:Entity:PERSON,:Entity:API - Query Performance: 3x faster queries using specific label targeting
- Backward Compatible: Old and new styles work together seamlessly
β Core Functionality Complete:
- β Advanced document chunking for optimal AI processing
- β SUBJECT-PREDICATE-OBJECT focused entity extraction
- β ALL CAPS standardized relationship types
- β Dynamic type discovery and intelligent reuse
- β
Dynamic Neo4j node labels (
:Entity:PERSON,:Entity:API) - β Domain-specific type learning with Supabase integration
- β Verb-based relationship pattern recognition
- β Document analysis caching for performance optimization
- β Neo4j knowledge graph construction with provenance
- β Async processing with rich progress feedback
- β Comprehensive test suite (75+ tests, 100% pass rate)
- β Database management utilities
- β Error handling and fallback mechanisms
# Process documents with detailed output
python run.py
# Demo dynamic node labeling
python demo_node_types.py
# Test domain-specific features
python tests/demo_supabase_mcp_workflow.py
# Clear database and reprocess everything
python tests/clear_and_reprocess.py
# Analyze relationship patterns
python tests/check_relationships.py
# Run comprehensive tests
python -m pytest tests/ -v
# Check relationship type compliance (ALL CAPS)
python tests/check_caps.py- Smart Chunking: Documents split at sentence boundaries to preserve context
- Type Resolution: Fuzzy matching prevents duplicate entity/relationship types
- Dynamic Node Labels: Entities get specific Neo4j labels (
:Entity:PERSON) for better performance - Domain Learning: Supabase-powered domain-specific type caching and learning
- Verb Intelligence: Relationship patterns learned from document verbs
- Provenance Tracking: Full data lineage from source documents to graph nodes
- Error Recovery: Graceful fallback to pattern-based extraction when AI fails
- Performance: Async processing handles multiple documents concurrently
- Neo4j: Stores entities and relationships with full property sets
- Supabase: Document storage with metadata, processing status, and domain type caching
- Domain Intelligence: Automatic domain classification with type learning by domain
- Type Management: Dynamic schema evolution based on document content
- Relationship Standards: ALL CAPS enforced for consistency and query performance
- 75+ Test Cases: Comprehensive coverage of all major functionality
- Dynamic Node Testing: Validation of new labeling system with backward compatibility
- Domain Type Testing: Supabase integration and domain-specific learning validation
- Verb Extraction Testing: Pattern recognition and relationship learning verification
- Async Testing: Proper mocking for database operations
- Error Scenarios: Tests for failure modes and recovery
- Performance Tests: Validation of chunking and processing efficiency
For detailed technical documentation and API references, see the test files in /tests directory which serve as living documentation of the system's capabilities.