LLM-powered Knowledge Graph Builder that extracts entities and relationships from documents (PDF, DOCX, TXT) and builds a Neo4j knowledge graph with full provenance tracking. Includes a Graph Reasoning Agent for intelligent querying and a futuristic Web UI for visualization.
Force-directed graph with color-coded entity types, interactive node dragging, and cyberpunk-themed dark UI.
Split layout with graph canvas (left) and Graph Reasoning Agent chat panel (right). Agent responses highlight referenced entities in the graph.
The extracted knowledge graph viewed in Neo4j Desktop, showing nodes, and relationships, and full schema with entity types and property keys.
- Multi-format Document Support: PDF (with OCR and table extraction), DOCX, TXT
- Multiple LLM Providers: OpenAI (GPT-4o), Anthropic (Claude), and Ollama (local models)
- Provenance Tracking: Document → Chunk → Entity chain stored in Neo4j
- Domain Flexibility: Auto-detection or custom domain schemas
- Entity Resolution: Type disambiguation, name resolution, and property enrichment
- Configuration-driven: YAML config with environment variable support
- CLI and Python API: Both interfaces available
- Sequential Reasoning: LangGraph-powered ReAct agent with multi-step reasoning
- APOC Schema Integration: Dynamic schema context from Neo4j for accurate queries
- Hybrid Search: Combines Cypher queries with vector similarity search
- Reference Tracking: Citations to documents, chunks, and entities in responses
- Short-term Memory: Conversation context with entity tracking
- Streaming Responses: Real-time SSE streaming for reasoning steps and results
- Futuristic Cyberpunk Theme: Dark theme with cyan/magenta accents
- Interactive Graph Visualization: react-force-graph-2d with D3.js physics
- Split Layout: Graph canvas (left) + Chat panel (right)
- Real-time Streaming: Live reasoning steps and response chunks
- Node Interaction: Click to view details, expand neighborhoods, drag nodes
- Smart Entity Highlighting: Agent responses highlight exact referenced entities with provenance
- Markdown Chat Responses: AI messages rendered with full markdown (headings, lists, code blocks, tables)
- Live Search: Type to highlight matching nodes instantly with match count
- Box Selection: Shift+drag to select multiple nodes at once
- Configurable Node Limit: Settings panel to adjust graph size (50-10,000 nodes)
- Clear Highlights: Easy reset button for highlighted nodes
- Auto-expanding Input: Chat textarea grows with content up to a max height
- Python 3.11+
- Neo4j database (with APOC plugin for Graph Agent)
- OpenAI API key, Anthropic API key, or Ollama (for local models)
- Node.js 18+ (for Web UI)
# Clone the repository
git clone https://github.com/fab679/kg_builder.git
cd kg_builder
# Create virtual environment
python -m venv venv
source venv/bin/activate # Linux/macOS
# or: venv\Scripts\activate # Windows
# Install the package (core only)
pip install -e .
# For OCR support (optional)
pip install -e ".[ocr]"
# For Ollama (local models) support
pip install -e ".[ollama]"
# For Graph Agent + API server
pip install -e ".[agent,api]"
# For everything (includes Ollama support)
pip install -e ".[all]"cd web
npm install- Copy the environment template:
cp .env.example .env- Edit
.envwith your credentials:
OPENAI_API_KEY=sk-your-openai-api-key
ANTHROPIC_API_KEY=sk-ant-your-anthropic-api-key
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASSWORD=your-password- Customize
config.yaml— this is the main configuration file that controls the entire pipeline, agent, and API server. All sections are described below.
The config file uses YAML syntax and supports environment variable interpolation with ${VAR_NAME} (e.g. ${NEO4J_URI}). Variables are resolved from your .env file or shell environment at runtime.
Controls which language model is used for entity/relationship extraction.
llm:
provider: "openai" # "openai", "anthropic", or "ollama"
model: "gpt-4o" # Model name (provider-specific)
temperature: 0.0 # 0.0 = deterministic, higher = more creative
max_tokens: 4096 # Max tokens per LLM response
# base_url: "http://localhost:11434" # Only needed for Ollama or custom endpointsneo4j:
uri: "${NEO4J_URI}" # Bolt URI (from .env)
user: "${NEO4J_USER}"
password: "${NEO4J_PASSWORD}"
database: "neo4j" # Neo4j database name
batch_size: 200 # Nodes/relationships per batch uploaddocuments:
input_dir: "data/" # Directory to scan for documents
supported_extensions: # File types to process
- ".pdf"
- ".docx"
- ".txt"pdf:
mode: "page" # "page" (one doc per page) or "single" (entire PDF as one doc)
extract_images: true # Extract images and run OCR
extract_tables: "markdown" # Table format: "markdown", "html", "csv", or false
image_parser: "tesseract" # OCR engine: "tesseract", "rapidocr", or "none"
ocr_languages:
- "eng" # Tesseract language codesControls how documents are split into chunks before extraction.
chunking:
chunk_size: 2000 # Max characters per chunk
chunk_overlap: 200 # Overlap between adjacent chunks
splitter: "recursive" # "recursive", "character", or "token"
separators: # Split priority (recursive splitter only)
- "\n\n"
- "\n"
- ". "
- " "Guards against exceeding the model's context window.
tokens:
model_context_limit: 128000 # Model's max context window
reserved_tokens: 6000 # Reserved for system prompt + schema + response
chars_per_token: 3 # Conservative chars-per-token estimateControls how entity/relationship types are determined.
domain:
mode: "auto" # "auto" (detect from content), "manual" (preset), or "schema" (custom file)
preset: null # For "manual" mode: "tech", "medical", "legal", "finance"
schema_file: null # For "schema" mode: path to custom schema YAML
additional_entity_types: [] # Extra entity types to always include
additional_relationship_types: [] # Extra relationship types to always includeprompts:
dir: "prompts/" # Directory containing prompt template files
extraction: null # Override extraction prompt (path or null for default)
domain_detection: null # Override domain detection prompt
disambiguation: null # Override disambiguation promptControls which steps run and in what order.
pipeline:
steps:
- load_documents
- chunk_documents
- extract_triples
- disambiguate_types
- merge_entities
- update_triples
- upload_graph
extraction:
batch_by_page: false # true = process per page, false = per chunk
triple_update:
deduplicate_property_rels: true # Remove redundant property-as-relationship triplesConfigures the node labels and relationship types used for provenance tracking in Neo4j.
graph:
document_label: "Document"
chunk_label: "Chunk"
relationships:
chunk_to_document: "FROM_DOCUMENT"
next_chunk: "NEXT_CHUNK"
entity_to_chunk: "EXTRACTED_FROM"
entity_to_document: "MENTIONED_IN"Controls embedding generation for vector similarity search (RAG).
embeddings:
enabled: true
provider: "openai" # "openai" or "ollama"
model: "text-embedding-3-small"
dimensions: 1536 # Must match the model's output dimensions
batch_size: 100 # Embeddings per API call
embed_chunks: true # Generate embeddings for chunks
embed_entities: true # Generate embeddings for entities
vector_index:
similarity_function: "cosine" # "cosine" or "euclidean"
chunk_index_name: "chunk_embeddings"
entity_index_name: "entity_embeddings"agent:
enabled: true
llm_provider: "openai" # "openai", "anthropic", or "ollama"
llm_model: "gpt-4o"
temperature: 0.0
max_reasoning_steps: 10 # Max tool-calling iterations per query
schema_cache_ttl_minutes: 5 # How long to cache the APOC schemaapi:
host: "0.0.0.0"
port: 8000
cors_origins: # Allowed origins for CORS
- "http://localhost:5173"
- "http://localhost:3000"logging:
level: "INFO" # "DEBUG", "INFO", "WARNING", "ERROR"
format: "simple" # "structured" (JSON) or "simple" (plain text)
file: null # Log file path, or null for stdout only# Run pipeline on all files in data/
kg-builder run
# Run on specific file
kg-builder run --file data/document.pdf
# Use different LLM provider
kg-builder run --provider anthropic --model claude-3-5-sonnet-20241022
# Validate configuration
kg-builder validate-config
# List available domain schemas
kg-builder list-schemas
# Show Neo4j graph statistics
kg-builder stats# Start the Graph Agent API server
kg-builder serve --port 8000
# Start with auto-reload for development
kg-builder serve --port 8000 --reload
# Start the Web UI development server
kg-builder ui
# Or run the Web UI manually
cd web && npm run dev- Start the API server:
kg-builder serve - Start the Web UI:
kg-builder ui(orcd web && npm run dev) - Open http://localhost:5173 in your browser
- Interact with the graph visualization on the left
- Chat with the reasoning agent on the right
- Click on node references in responses to highlight them in the graph
from kg_builder import KGPipeline
# Basic usage
pipeline = KGPipeline("config.yaml")
results = pipeline.run("data/")
print(f"Extracted {results['entities']} entities")
print(f"Created {results['triples']} relationships")
# With custom options
results = pipeline.run(
"data/report.pdf",
skip_upload=False # Set True to skip Neo4j upload
)
# Clean up
pipeline.close()kg_builder/
├── config.yaml # Main configuration
├── cli.py # CLI interface
├── data/ # Input documents (PDF, DOCX, TXT)
├── prompts/ # Editable prompt templates
├── schemas/ # Custom domain schemas
├── web/ # React Web UI
│ ├── src/
│ │ ├── components/ # React components
│ │ │ ├── GraphCanvas.tsx # Force-directed graph
│ │ │ ├── ChatPanel.tsx # Streaming chat UI
│ │ │ ├── NodeDetails.tsx # Node info panel
│ │ │ ├── Legend.tsx # Graph type legend
│ │ │ └── SearchBar.tsx # Entity search
│ │ ├── hooks/ # React hooks
│ │ │ ├── useGraph.ts # Graph state (zustand)
│ │ │ └── useChat.ts # SSE chat hook
│ │ ├── styles/ # CSS with Tailwind v4
│ │ └── utils/ # API utilities
│ └── package.json
└── src/kg_builder/
├── config/ # Configuration management
├── loaders/ # Document loaders (PDF, DOCX, TXT)
├── chunking/ # Text chunking with provenance
├── extraction/ # LLM-based triple extraction
├── resolution/ # Type disambiguation, name resolution
├── enrichment/ # Property enrichment
├── embeddings/ # Vector embeddings & retrieval
├── graph/ # Neo4j upload with provenance
├── llm/ # LLM provider abstraction
├── pipeline/ # Pipeline orchestration
├── prompts/ # Prompt template loading
├── utils/ # Utilities (logging, sanitizers)
├── agent/ # Graph Reasoning Agent
│ ├── graph_agent.py # LangGraph ReAct agent
│ ├── tools.py # Agent tools (Cypher, Vector, etc.)
│ ├── memory.py # Conversation memory
│ ├── schema.py # APOC schema loader
│ └── prompts.py # Agent system prompts
└── api/ # FastAPI REST API
├── app.py # Application factory
├── dependencies.py # Shared dependencies
├── models.py # Pydantic models
└── routes/
├── chat.py # SSE streaming chat
├── graph.py # Graph query endpoints
└── schema.py # Schema introspection
Document Input (PDF/DOCX/TXT)
│
▼
┌──────────────────────┐
│ Document Loading │ PyMuPDF, docx2txt
│ + OCR (optional) │
└──────────────────────┘
│
▼
┌──────────────────────┐
│ Text Chunking │ RecursiveCharacterTextSplitter
│ (with provenance) │
└──────────────────────┘
│
▼
┌──────────────────────┐
│ Triple Extraction │ GPT-4o / Claude / Ollama
│ (LLM structured) │
└──────────────────────┘
│
▼
┌──────────────────────┐
│ Type Disambiguation │ Normalize entity types
│ + Name Resolution │ Merge name variants
└──────────────────────┘
│
▼
┌──────────────────────┐
│ Property Enrichment │ Infer from context
└──────────────────────┘
│
▼
┌──────────────────────┐
│ Neo4j Upload │ Nodes + Relationships
│ (with provenance) │ Document → Chunk → Entity
└──────────────────────┘
┌──────────────────────┐
│ React Web UI │
│ (Futuristic Theme) │
│ - GraphCanvas │
│ - ChatPanel │
└──────────┬───────────┘
│
SSE/REST │
▼
┌──────────────────────┐ ┌───────────────────────────┐
│ Neo4j Graph │◄─────────►│ FastAPI Backend │
│ (APOC enabled) │ │ - /api/chat/stream (SSE) │
│ - Entities │ │ - /api/graph/* │
│ - Chunks │ │ - /api/schema │
│ - Documents │ └─────────────┬─────────────┘
└──────────────────────┘ │
┌─────────────────────────────┐
│ Graph Reasoning Agent │
│ (LangGraph ReAct) │
│ - CypherQueryTool │
│ - VectorSearchTool │
│ - EntityNavigationTool │
│ - ChunkContextTool │
│ - Short-term Memory │
│ - APOC Schema Context │
└─────────────────────────────┘
| Package | Version | Purpose |
|---|---|---|
| langchain | >=1.2.7 | LLM orchestration |
| langchain-openai | >=1.1.7 | OpenAI integration |
| langchain-anthropic | >=1.3.1 | Anthropic integration |
| langchain-ollama | >=0.3.0 | Ollama integration (optional) |
| PyMuPDF | >=1.26.7 | PDF processing |
| pydantic | >=2.12.0 | Data validation |
| neo4j | >=6.1.0 | Graph database |
| pillow | >=12.1.0 | Image processing |
| click | >=8.3.1 | CLI framework |
| Package | Version | Purpose |
|---|---|---|
| langgraph | >=1.0.7 | Agent orchestration |
| langchain-neo4j | >=0.1.1 | Neo4j LangChain integration |
| Package | Version | Purpose |
|---|---|---|
| fastapi | >=0.115.0 | REST API framework |
| uvicorn | >=0.32.0 | ASGI server |
| sse-starlette | >=2.2.1 | Server-Sent Events |
| Package | Version | Purpose |
|---|---|---|
| react | ^19.0.0 | UI framework |
| react-force-graph-2d | ^1.29.0 | D3.js graph visualization |
| zustand | ^5.0.3 | State management |
| react-markdown | ^10.1.0 | Markdown rendering |
| remark-gfm | ^4.0.1 | GitHub-flavored markdown |
| lucide-react | ^0.468.0 | Icons |
| tailwindcss | ^4.0.0 | CSS framework |
| vite | ^6.0.0 | Build tool |
Run the entire pipeline locally without API keys using Ollama.
- Install Ollama from https://ollama.com
- Pull the models you want to use:
# LLM for extraction and agent (must support tool calling for agent)
ollama pull llama3.1
# Embedding model
ollama pull nomic-embed-text- Configure
config.yaml:
llm:
provider: "ollama"
model: "llama3.1"
# base_url: "http://localhost:11434" # default
embeddings:
provider: "ollama"
model: "nomic-embed-text"
dimensions: 768 # must match the model's output dimensions
# base_url: "http://localhost:11434"
agent:
llm_provider: "ollama"
llm_model: "llama3.1"LLM models (for extraction pipeline and agent):
llama3.1- Good general purpose, supports tool callingqwen2.5- Strong multilingual, supports tool callingmistral- Fast and capable, supports tool calling
Embedding models (for vector search):
nomic-embed-text(768 dimensions)mxbai-embed-large(1024 dimensions)all-minilm(384 dimensions)
Note: The Graph Reasoning Agent requires a model that supports tool calling. Models with tool calling support: Llama 3.1+, Qwen 2.5+, Mistral, Granite 3.2+. See the full list at https://ollama.com/search?c=tools
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/chat/stream |
SSE streaming chat with reasoning |
| POST | /api/chat/ |
Non-streaming chat response |
| POST | /api/chat/clear |
Clear conversation memory |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/graph/ |
Get graph data with optional filtering |
| GET | /api/graph/node/{id} |
Get node details with provenance |
| GET | /api/graph/search |
Search entities by name |
| GET | /api/graph/neighbors/{id} |
Get node neighborhood |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/schema/ |
Get graph schema from APOC |
The streaming chat endpoint sends these event types:
| Event | Description |
|---|---|
reasoning |
Agent's thinking process |
tool_call |
Tool invocation details |
chunk |
Text response chunk |
citation |
Document/chunk reference |
node_reference |
Referenced entity |
done |
Stream complete |
error |
Error occurred |
Create custom schemas in schemas/ directory:
# schemas/medical.yaml
name: "Medical Research"
entity_types:
- name: Drug
properties: [dosage, mechanism]
- name: Disease
properties: [icd_code, severity]
relationship_types:
- name: TREATS
source: Drug
target: DiseaseThen configure in config.yaml:
domain:
mode: "schema"
schema_file: "schemas/medical.yaml"Query the provenance chain in Neo4j:
-- Find source text for an entity
MATCH (e:Person {name: "John Smith"})-[:EXTRACTED_FROM]->(c:Chunk)
RETURN c.text, c.page_numbers
-- Full provenance chain
MATCH path = (e)-[:EXTRACTED_FROM]->(c:Chunk)-[:FROM_DOCUMENT]->(d:Document)
WHERE e.name = "Apple Inc."
RETURN path# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest tests/MIT