Skip to content

About

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.

Resources

Stars

10 stars

Watchers

0 watching

Forks

Latest commit

 

History

7 Commits

Folders and files

Repository files navigation

Knowledge Graph Builder

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.

Screenshots

Web UI - Interactive Graph Visualization

Graph Visualization Force-directed graph with color-coded entity types, interactive node dragging, and cyberpunk-themed dark UI.

Web UI - Graph Agent Chat with Highlighted Nodes

Graph Agent Chat Split layout with graph canvas (left) and Graph Reasoning Agent chat panel (right). Agent responses highlight referenced entities in the graph.

Knowledge Graph in Neo4j Desktop

Neo4j Desktop The extracted knowledge graph viewed in Neo4j Desktop, showing nodes, and relationships, and full schema with entity types and property keys.

Features

Core Pipeline

  • 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

Graph Reasoning Agent

  • 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

Web UI

  • 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

Requirements

  • 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)

Installation

# 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]"

Web UI Installation

cd web
npm install

Configuration

  1. Copy the environment template:
cp .env.example .env
  1. Edit .env with 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
  1. Customize config.yaml — this is the main configuration file that controls the entire pipeline, agent, and API server. All sections are described below.

config.yaml Reference

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.

llm — LLM Provider

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 endpoints

neo4j — Database Connection

neo4j:
  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 upload

documents — Input Files

documents:
  input_dir: "data/"         # Directory to scan for documents
  supported_extensions:      # File types to process
    - ".pdf"
    - ".docx"
    - ".txt"

pdf — PDF Processing

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 codes

chunking — Text Chunking

Controls 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"
    - ". "
    - " "

tokens — Token Management

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 estimate

domain — Domain Configuration

Controls 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 include

prompts — Prompt Templates

prompts:
  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 prompt

pipeline — Pipeline Steps

Controls 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 triples

graph — Provenance Structure

Configures 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"

embeddings — Vector Embeddings

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 — Graph Reasoning Agent

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 schema

api — API Server

api:
  host: "0.0.0.0"
  port: 8000
  cors_origins:               # Allowed origins for CORS
    - "http://localhost:5173"
    - "http://localhost:3000"

logging — Log Output

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

Usage

CLI - Pipeline Commands

# 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

CLI - Graph Agent & Web UI

# 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

Using the Web UI

  1. Start the API server: kg-builder serve
  2. Start the Web UI: kg-builder ui (or cd web && npm run dev)
  3. Open http://localhost:5173 in your browser
  4. Interact with the graph visualization on the left
  5. Chat with the reasoning agent on the right
  6. Click on node references in responses to highlight them in the graph

Python API

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()

Project Structure

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

Architecture

Document Processing Pipeline

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
└──────────────────────┘

Graph Agent & Web UI Architecture

                                    ┌──────────────────────┐
                                    │   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     │
                                   └─────────────────────────────┘

Dependencies

Core Pipeline

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

Graph Agent (pip install -e ".[agent]")

Package Version Purpose
langgraph >=1.0.7 Agent orchestration
langchain-neo4j >=0.1.1 Neo4j LangChain integration

API Server (pip install -e ".[api]")

Package Version Purpose
fastapi >=0.115.0 REST API framework
uvicorn >=0.32.0 ASGI server
sse-starlette >=2.2.1 Server-Sent Events

Web UI (npm packages)

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

Using Ollama (Local Models)

Run the entire pipeline locally without API keys using Ollama.

Setup

  1. Install Ollama from https://ollama.com
  2. 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
  1. 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"

Ollama Models

LLM models (for extraction pipeline and agent):

  • llama3.1 - Good general purpose, supports tool calling
  • qwen2.5 - Strong multilingual, supports tool calling
  • mistral - 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

API Endpoints

Chat Endpoints

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

Graph Endpoints

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

Schema Endpoint

Method Endpoint Description
GET /api/schema/ Get graph schema from APOC

SSE Event Types

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

Custom Domain Schemas

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: Disease

Then configure in config.yaml:

domain:
  mode: "schema"
  schema_file: "schemas/medical.yaml"

Provenance Queries

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

Development

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/

License

MIT

About

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.

Resources

Stars

10 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages