Skip to content
pranav8764Public

About

An AI-powered industrial knowledge platform that ingests plant documents, extracts asset intelligence, and enables RAG-based querying, RCA, and compliance insights through OCR, knowledge graphs, and agentic workflows

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

13 Commits

Folders and files

Repository files navigation

🧠 PlantBrainAI

AI-Powered Industrial Knowledge Platform

Turn scattered plant documents into searchable, cited asset intelligence.

Quick Start β€’ Architecture β€’ HLD β€’ LLD β€’ API β€’ Deployment β€’ Contributing


πŸ“‹ Table of Contents


πŸ” Overview

PlantBrainAI is an AI-powered platform that transforms unstructured industrial plant documents β€” maintenance logs, work orders, inspection reports, OEM manuals, compliance checklists β€” into a connected knowledge layer. Engineers can upload documents, ask natural-language questions with cited answers, inspect asset profiles, generate root-cause analyses, and detect compliance gaps β€” all backed by evidence from their own plant data.

The Problem

Industrial plants generate thousands of documents across maintenance, safety, compliance, and operations. This critical knowledge is trapped in PDFs, scans, and spreadsheets β€” making it nearly impossible for engineers to find answers quickly, trace failure patterns, or verify compliance.

The Solution

PlantBrainAI ingests plant documents through OCR and text extraction, chunks and embeds them for semantic search, extracts entities and relationships into a knowledge graph, and exposes the intelligence through a RAG-powered copilot, asset profiles, RCA generator, and compliance gap detector.


✨ Key Features

Feature Description
Document Ingestion Upload PDFs, DOCX, Excel, CSVs, images, and text files. Automatic OCR fallback for scanned documents.
RAG Copilot Ask natural-language questions and receive cited answers with confidence scores, powered by a LangGraph state machine.
Asset Intelligence Auto-extracted asset profiles with tags, types, risk scores, failure timelines, and linked documents.
Root Cause Analysis AI-generated RCA reports with probable causes, recommendations, and document-backed citations.
Compliance Gap Detection Heuristic compliance scanning that identifies missing evidence, expired inspections, and uncovered requirements.
Knowledge Graph Extracted entities and relationships between assets, failure modes, parts, and procedures.
Report Generation Export asset summaries, compliance gaps, document inventories, RCA reports, and query answers as CSV, PDF, or DOCX.
RBAC & Document Access Control Role-based access with document-level sensitivity policies separating metadata visibility from source file access.
Stateful Conversations LangGraph checkpointer-backed memory with session persistence and conversation continuity.

πŸ— Architecture Overview

PlantBrainAI follows a consolidated microservice pattern β€” domain boundaries are explicit through PostgreSQL schemas and contracts, while the MVP runtime is streamlined into two backend services for simplicity and deployability.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                          Client Layer                               β”‚
β”‚                                                                     β”‚
β”‚                    Next.js Web App (:3000)                          β”‚
β”‚         Dashboard β”‚ Copilot β”‚ Assets β”‚ RCA β”‚ Compliance            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚ HTTPS / REST
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                       API / BFF Layer                               β”‚
β”‚                                                                     β”‚
β”‚                  Go API Service (:8080)                             β”‚
β”‚     Auth β”‚ Upload β”‚ Documents β”‚ Assets β”‚ Reports β”‚ Dashboard       β”‚
β”‚               RBAC Enforcement β”‚ Rate Limiting                     β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚            β”‚               β”‚            β”‚
       β–Ό            β–Ό               β–Ό            β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  MinIO  β”‚  β”‚ Python AI   β”‚  β”‚  Redis  β”‚  β”‚  PostgreSQL     β”‚
β”‚  Object β”‚  β”‚ Service     β”‚  β”‚  Cache  β”‚  β”‚  + pgvector     β”‚
β”‚  Store  β”‚  β”‚ (:8000)     β”‚  β”‚ & Queue β”‚  β”‚  (12 schemas)   β”‚
β”‚         β”‚  β”‚             β”‚  β”‚         β”‚  β”‚                 β”‚
β”‚ uploads β”‚  β”‚ OCRβ”‚RAGβ”‚RCA β”‚  β”‚ events  β”‚  β”‚ identityβ”‚asset  β”‚
β”‚ reports β”‚  β”‚ NLPβ”‚Graph   β”‚  β”‚ streams β”‚  β”‚ documentβ”‚graph  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚ ingestionβ”‚rag  β”‚
                    β”‚                       β”‚ rcaβ”‚compliance β”‚
                    β–Ό                       β”‚ reportβ”‚audit   β”‚
             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                 β”‚ notificationβ”‚aiβ”‚
             β”‚ LLM / Embedβ”‚                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚ Providers   β”‚
             β”‚ Geminiβ”‚Groq β”‚
             β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Service Topology

Service Language Port Role
apps/web TypeScript / Next.js 3000 Frontend SPA with SSR
services/api Go 8080 Public API / BFF β€” auth, uploads, assets, compliance, reports
services/ai Python / FastAPI 8000 Internal AI service β€” OCR, embeddings, RAG, RCA, graph
PostgreSQL + pgvector β€” 5432 Relational data + vector embeddings
Redis β€” 6379 Cache, future event streaming (Redis Streams)
MinIO β€” 9000/9001 S3-compatible object storage for uploads

Design Principle: External clients only call services/api. The AI service is internal to the Docker network and is never browser-facing.


πŸ“ High-Level Design

System Context

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Engineers │───────▢│  PlantBrain  │───────▢│  LLM Providers β”‚
β”‚ Operators │◀───────│    AI        │◀───────│  (Gemini/Groq) β”‚
β”‚ Managers  β”‚        β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
                   β”‚ Plant Documents β”‚
                   β”‚ PDFs, Scans,    β”‚
                   β”‚ Spreadsheets    β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Core Workflows

1. Document Processing Pipeline

Upload Request
  β†’ API validates auth, file type, plant, document type
  β†’ API stores metadata in document schema
  β†’ API writes original file to MinIO + shared volume
  β†’ API calls AI service /process-document
  β†’ AI extracts text (or OCR fallback for scanned documents)
  β†’ AI creates markdown, extracts tables, chunks content
  β†’ AI generates 1536-dimensional vector embeddings
  β†’ AI extracts entities (assets, parts, failure modes)
  β†’ AI upserts detected assets into asset schema
  β†’ AI writes graph entities and relationships
  β†’ AI marks document status COMPLETED or FAILED

2. RAG Copilot Pipeline (LangGraph State Machine)

User Question
  β†’ [guardrail_node]     Input validation & PII check
  β†’ [intent_router_node] LLM classifies intent (RAG_QUERY vs GENERAL)
  β†’ [retrieval_node]     Hybrid search: pgvector + keyword fallback
  β†’ [rbac_node]          Document-level role access filtering
  β†’ [generation_node]    LLM synthesizes cited response
  β†’ [validation_node]    Self-correcting citation verification (up to 3 retries)
  β†’ Final cited answer with confidence score

3. RCA Generation

RCA Request (asset tag + failure description)
  β†’ Retrieve relevant document chunks for the asset
  β†’ LLM analyzes failure patterns across maintenance history
  β†’ Generate: summary, probable causes, recommendations
  β†’ Return cited RCA report with confidence score

4. Compliance Gap Detection

Compliance Scan Request
  β†’ Load compliance requirements for the plant
  β†’ Check each asset for: missing evidence, expired inspections, uncovered requirements
  β†’ Generate gap records with severity and remediation hints
  β†’ Persist gaps for dashboard and report export

Logical Module Map

Logical Module Runtime Owner Responsibilities
Identity services/api Users, roles, memberships, auth, permissions
Documents services/api Uploads, versions, status, file pointers, duplicates
Ingestion services/ai Parsing, OCR, markdown, tables, chunks, embeddings
RAG api + ai Query routing, retrieval, cited answer generation
Assets api + ai Asset records, aliases, profiles, timelines, risk scoring
Graph services/ai Entity extraction, relationships, deduplication
RCA api + ai Failure context, probable causes, recommendations
Compliance api + ai Requirements, evidence matching, gap detection
Reports services/api Synchronous report jobs β€” CSV, PDF, DOCX exports
Audit services/api Audit events, document access logs

πŸ”¬ Low-Level Design

API Service (services/api) β€” Go

services/api/
β”œβ”€β”€ cmd/server/
β”‚   β”œβ”€β”€ main.go              # HTTP server, router, all public API routes
β”‚   └── seed.go              # Development data seeder
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ auth/                # Session/token validation, Better Auth integration
β”‚   β”œβ”€β”€ handlers/            # Domain-specific HTTP handlers
β”‚   β”‚   β”œβ”€β”€ assets.go        # Asset CRUD, profile aggregation
β”‚   β”‚   β”œβ”€β”€ compliance.go    # Compliance gaps, scan triggers
β”‚   β”‚   β”œβ”€β”€ copilot.go       # RAG query proxy to AI service
β”‚   β”‚   β”œβ”€β”€ dashboard.go     # Metrics aggregation for dashboard
β”‚   β”‚   β”œβ”€β”€ documents.go     # Upload, versioning, download, archive
β”‚   β”‚   β”œβ”€β”€ graph.go         # Knowledge graph reads
β”‚   β”‚   β”œβ”€β”€ me.go            # Current user context
β”‚   β”‚   β”œβ”€β”€ rca.go           # RCA generation proxy
β”‚   β”‚   └── reports.go       # Report job creation, CSV/PDF/DOCX generation
β”‚   β”œβ”€β”€ middleware/           # Auth middleware, rate limiting, CORS
β”‚   └── models/              # Go struct definitions
β”œβ”€β”€ go.mod / go.sum
└── Dockerfile

Key Design Decisions:

  • Single main.go router with handler functions extracted into internal/handlers/
  • Session-based auth via Better Auth with dev-token for local development
  • Configurable sliding-window rate limiters (API_RATE_LIMIT, API_AUTH_RATE_LIMIT)
  • Presigned MinIO URLs for secure document downloads (600s expiry)

AI Service (services/ai) β€” Python FastAPI

services/ai/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ main.py              # FastAPI app, lifespan, router registration
β”‚   β”œβ”€β”€ config.py            # Environment config, provider settings
β”‚   β”œβ”€β”€ database.py          # Async DB pool (asyncpg) lifecycle
β”‚   β”œβ”€β”€ schemas.py           # Pydantic request/response models
β”‚   β”œβ”€β”€ state.py             # LangGraph state definitions
β”‚   β”œβ”€β”€ graph.py             # LangGraph RAG state machine (compiled graph)
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ ingestion.py     # /process-document β€” OCR, chunking, embeddings
β”‚   β”‚   β”œβ”€β”€ query.py         # /query β€” RAG copilot
β”‚   β”‚   β”œβ”€β”€ rca.py           # /rca β€” Root cause analysis
β”‚   β”‚   └── compliance.py    # /compliance-scan β€” Gap detection
β”‚   └── utils/
β”‚       β”œβ”€β”€ ai_clients.py    # Gemini/Groq provider wrappers (google-genai)
β”‚       └── helpers.py       # Shared utility functions
β”œβ”€β”€ requirements.txt
└── Dockerfile

Key Design Decisions:

  • LangGraph compiled state machine for multi-step RAG with memory checkpointing
  • AsyncPostgresSaver for production session persistence, MemorySaver for testing
  • Token-bucket rate limiter middleware (AI_RATE_LIMIT_RPS, AI_RATE_LIMIT_BURST)
  • Graceful degradation: ingestion marked PARTIAL_SUCCESS when no API key is configured

Web Application (apps/web) β€” Next.js

apps/web/src/
β”œβ”€β”€ app/                     # Next.js App Router pages
β”‚   β”œβ”€β”€ page.tsx             # Dashboard (home)
β”‚   β”œβ”€β”€ login/               # Authentication page
β”‚   β”œβ”€β”€ copilot/             # RAG chat interface
β”‚   β”œβ”€β”€ assets/              # Asset explorer & profiles
β”‚   β”œβ”€β”€ documents/           # Document upload & management
β”‚   β”œβ”€β”€ compliance/          # Compliance gap dashboard
β”‚   β”œβ”€β”€ rca/                 # RCA generator
β”‚   β”œβ”€β”€ graph/               # Knowledge graph visualization
β”‚   β”œβ”€β”€ reports/             # Report generation & downloads
β”‚   β”œβ”€β”€ admin/               # Admin panel
β”‚   └── api/auth/[...all]/   # Better Auth route handler
β”œβ”€β”€ components/              # Reusable UI components
β”‚   └── NavigationShell.tsx   # App shell with sidebar navigation
β”œβ”€β”€ context/
β”‚   └── DataContext.tsx       # Global data provider
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ api.ts               # API client utilities
β”‚   β”œβ”€β”€ auth.ts              # Better Auth client setup
β”‚   └── normalizers.ts       # Data normalization helpers
β”œβ”€β”€ features/                # Feature-specific modules
└── styles/                  # Global CSS

Communication Patterns

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  Synchronous (HTTP)                    β”‚
β”‚                                                        β”‚
β”‚  Browser ──REST──▢ API ──REST──▢ AI Service            β”‚
β”‚  Browser ──REST──▢ API ──SQL───▢ PostgreSQL            β”‚
β”‚  Browser ──REST──▢ API ──S3────▢ MinIO                 β”‚
β”‚  AI Service ─────────────SQL───▢ PostgreSQL + pgvector β”‚
β”‚  AI Service ─────────────File──▢ Shared uploads volume β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚               Asynchronous (Planned)                   β”‚
β”‚                                                        β”‚
β”‚  API ──publish──▢ Redis Streams ──consume──▢ AI        β”‚
β”‚  Events: document.uploaded, document.indexed,          β”‚
β”‚          asset.upserted, compliance.gap_detected,      β”‚
β”‚          rca.report_generated                          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ›  Technology Stack

Layer Technology
Frontend Next.js 14+, TypeScript, React
API / BFF Go, net/http, pgx/v5, chi router
AI Service Python 3.11+, FastAPI, LangGraph, asyncpg
Database PostgreSQL 16 + pgvector extension
Vector Search pgvector (1536-dimensional embeddings)
Object Storage MinIO (S3-compatible) / AWS S3 / Cloudflare R2
Cache / Queue Redis 7 (future: Redis Streams for event bus)
LLM Providers Google Gemini, Groq (Llama 3.3)
Embeddings Google text-embedding-004 (1536-dim)
Auth Better Auth (session-based, email/password + OAuth)
Containerization Docker, Docker Compose
CI/CD GitHub Actions
Future Infra Kubernetes, Helm, Terraform
Observability OpenTelemetry (planned)

πŸ“ Repository Layout

ProjectX/
β”œβ”€β”€ apps/
β”‚   └── web/                          # Next.js frontend (TypeScript)
β”œβ”€β”€ contracts/
β”‚   β”œβ”€β”€ openapi/                      # REST API contracts (api.yaml, ai.yaml)
β”‚   β”œβ”€β”€ events/                       # AsyncAPI event contracts
β”‚   β”œβ”€β”€ schemas/                      # Shared JSON schemas
β”‚   └── proto/                        # Future gRPC/protobuf contracts
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ api/                          # Go API/BFF service
β”‚   └── ai/                           # Python FastAPI AI service
β”œβ”€β”€ packages/
β”‚   └── shared/                       # Shared types, schemas, constants
β”œβ”€β”€ infra/
β”‚   β”œβ”€β”€ db/                           # Migrations and seed data
β”‚   β”‚   β”œβ”€β”€ migrations/               # PostgreSQL schema DDL
β”‚   β”‚   └── seeds/                    # Demo data inserts
β”‚   β”œβ”€β”€ docker/                       # Docker helper files
β”‚   β”œβ”€β”€ k8s/                          # Kubernetes manifests (future)
β”‚   β”œβ”€β”€ helm/                         # Helm charts (future)
β”‚   β”œβ”€β”€ observability/                # Logs, metrics, tracing config
β”‚   └── terraform/                    # Cloud infrastructure (future)
β”œβ”€β”€ docs/                             # Architecture, API, data model docs
β”‚   β”œβ”€β”€ ARCHITECTURE.md
β”‚   β”œβ”€β”€ API_CONTRACTS.md
β”‚   β”œβ”€β”€ DATA_MODEL.md
β”‚   β”œβ”€β”€ MICROSERVICES.md
β”‚   β”œβ”€β”€ DEPLOYMENT.md
β”‚   β”œβ”€β”€ MVP_SCOPE.md
β”‚   └── adr/                          # Architecture Decision Records
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ sample-documents/             # Demo PDFs, scans, CSVs
β”‚   └── processed/                    # Local processing outputs
β”œβ”€β”€ scripts/                          # Developer and automation scripts
β”œβ”€β”€ tests/                            # Integration tests and fixtures
β”œβ”€β”€ docker-compose.yml                # Full local development stack
β”œβ”€β”€ Makefile                          # Developer workflow commands
β”œβ”€β”€ .env.example                      # Environment variable template
└── .github/workflows/ci.yml          # CI pipeline

πŸš€ Quick Start

Prerequisites

  • Docker & Docker Compose
  • Node.js 20+ and npm (for local web dev)
  • Git

1. Clone and Configure

git clone https://github.com/pranav8764/ProjectX.git
cd ProjectX
cp .env.example .env

Edit .env and fill in required values. For a fully local setup:

# Use the bundled local PostgreSQL
DATABASE_URL=postgresql://plantbrain:plantbrain@postgres:5432/plantbrain

# Generate auth secret
BETTER_AUTH_SECRET=$(openssl rand -base64 32)

# Optional: Add AI provider keys for real LLM responses
GOOGLE_API_KEY=your-gemini-api-key
GROQ_API_KEY=your-groq-api-key

Note: Without GOOGLE_API_KEY or GROQ_API_KEY, the AI service operates in fallback mode β€” ingestion is marked PARTIAL_SUCCESS and the copilot returns a no-evidence response.

2. Start the Stack

Option A: Full Docker Compose (Recommended)

# Start everything including the web app
docker compose --profile local-db up --build

# In a separate terminal, apply migrations and seed data
make db-migrate
make db-seed
make seed-demo-auth

Option B: Services + Local Web Dev

# Start backend services
make services-up
make db-seed

# Start the web app locally
npm --prefix apps/web ci
npm --prefix apps/web run dev

3. Verify

# Run smoke tests
make smoke

# Check service health
curl http://localhost:8080/health   # API
curl http://localhost:8000/health   # AI

4. Access

Service URL
Web App http://localhost:3000
API / BFF http://localhost:8080
AI Service http://localhost:8000
MinIO Console http://localhost:9001

Dev Token: The API automatically seeds a dev-token session when the database is empty and APP_ENV is not production. Use Authorization: Bearer dev-token for API requests.

Demo Personas

After running make seed-demo-auth, the following demo accounts are available (password: PlantBrain#2026):

Use these to test different RBAC roles through the login page at http://localhost:3000/login.


πŸ” Environment Variables

Required

Variable Description Example
DATABASE_URL PostgreSQL connection string (use session pooler for Supabase) postgresql://plantbrain:plantbrain@postgres:5432/plantbrain
BETTER_AUTH_SECRET Cryptographic signing key for Better Auth Generate with openssl rand -base64 32
MINIO_ROOT_USER MinIO admin username plantbrain
MINIO_ROOT_PASSWORD MinIO admin password (β‰₯ 8 chars) plantbrain-dev-secret

Optional β€” AI Providers

Variable Description How to Get
GOOGLE_API_KEY Gemini API key for LLM + embeddings Google AI Studio
GROQ_API_KEY Groq API key for fast inference Groq Console
GEMINI_MODEL Override Gemini model (default: gemini-2.0-flash) β€”
GEMINI_EMBED_MODEL Override embedding model (default: text-embedding-004) β€”
GROQ_MODEL Override Groq model (default: llama-3.3-70b-versatile) β€”

Optional β€” Tuning

Variable Default Description
APP_ENV development Environment (development, production, test)
CORS_ALLOWED_ORIGINS http://localhost:3000 Comma-separated allowed origins
API_RATE_LIMIT 300 API router rate limit (requests per window)
API_RATE_LIMIT_WINDOW 1m API rate limit window
AI_RATE_LIMIT_RPS 5.0 AI service requests/second per client
AI_RATE_LIMIT_BURST 20.0 AI service token bucket burst capacity
LOG_LEVEL info Log verbosity (debug, info, warn, error)

See .env.example for the complete variable reference.


πŸ“‘ API Reference

All authenticated endpoints use Authorization: Bearer <token>. Full contract details are in docs/API_CONTRACTS.md and the machine-readable OpenAPI specs at contracts/openapi/.

Public API (services/api β€” :8080)

Method Endpoint Description
GET /health Health check
GET /api/me Current user context
POST /api/documents/upload Upload a document (multipart)
GET /api/documents?plantId= List documents for a plant
GET /api/documents/:id Document detail with chunks & entities
GET /api/documents/:id/status Processing status
GET /api/documents/:id/download Presigned download URL
POST /api/documents/:id/versions Upload new document version
POST /api/documents/:id/retry-processing Retry failed processing
DELETE /api/documents/:id Archive document
POST /api/copilot/query Ask the RAG copilot
GET /api/assets?plantId= List assets
GET /api/assets/:id Asset profile
POST /api/rca/generate Generate root cause analysis
GET /api/compliance/gaps?plantId= List compliance gaps
POST /api/compliance/scan?plantId= Run compliance scan
GET /api/graph?plantId= Knowledge graph data
GET /api/dashboard/metrics?plantId= Dashboard metrics
POST /api/reports Create report job
GET /api/reports?plantId= List reports
GET /api/reports/:id/download Download generated report

Internal AI API (services/ai β€” :8000)

Method Endpoint Description
GET /health Health check
POST /process-document Document ingestion pipeline
POST /query RAG retrieval and answer generation
POST /rca Root cause analysis generation
POST /compliance-scan Compliance gap detection

Supported Upload Formats

.pdf, .docx, .doc, .xlsx, .xls, .csv, .png, .jpg, .jpeg, .txt, .md

Report Types & Formats

Report Type Formats
asset_summary CSV, PDF, DOCX
compliance_gap CSV, PDF, DOCX
document_inventory CSV, PDF, DOCX
rca_report CSV, PDF, DOCX
query_answers CSV, PDF, DOCX

πŸ—„ Data Model

PlantBrainAI uses a single PostgreSQL instance with 12 domain schemas. Schema boundaries are explicit to enable a future microservice split without data migration.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     PostgreSQL Instance                      β”‚
β”‚                                                              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”‚
β”‚  β”‚  identity    β”‚  β”‚ document β”‚  β”‚ ingestion β”‚              β”‚
β”‚  β”‚ orgs,users, β”‚  β”‚ docs,    β”‚  β”‚ jobs,     β”‚              β”‚
β”‚  β”‚ sessions,   β”‚  β”‚ versions,β”‚  β”‚ pages,    β”‚              β”‚
β”‚  β”‚ roles,      β”‚  β”‚ uploads  β”‚  β”‚ chunks    β”‚              β”‚
β”‚  β”‚ memberships β”‚  β”‚          β”‚  β”‚           β”‚              β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β”‚
β”‚                                                              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”‚
β”‚  β”‚  asset  β”‚  β”‚  graph  β”‚  β”‚  rag   β”‚  β”‚   rca    β”‚       β”‚
β”‚  β”‚ assets, β”‚  β”‚entities,β”‚  β”‚queries,β”‚  β”‚ reports  β”‚       β”‚
β”‚  β”‚ aliases β”‚  β”‚relationsβ”‚  β”‚citationsβ”‚ β”‚          β”‚       β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚
β”‚                                                              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”     β”‚
β”‚  β”‚ compliance β”‚  β”‚ report β”‚  β”‚ notification β”‚  β”‚ ai β”‚     β”‚
β”‚  β”‚ requiremts,β”‚  β”‚ jobs   β”‚  β”‚ alerts       β”‚  β”‚modelβ”‚    β”‚
β”‚  β”‚ gaps       β”‚  β”‚        β”‚  β”‚              β”‚  β”‚callsβ”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”˜     β”‚
β”‚                                                              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”                                                 β”‚
β”‚  β”‚ audit  β”‚  (future: event log)                            β”‚
β”‚  β”‚ events β”‚                                                 β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Schema Ownership

Schema Owner Key Tables
identity services/api organizations, plants, users, sessions, accounts, roles, memberships
document services/api documents, document_versions, upload_sessions
ingestion services/ai processing_jobs, document_pages, document_chunks
asset services/api assets, asset_aliases
graph services/ai entities, relationships
rag api + ai queries, citations
rca api + ai reports
compliance api + ai requirements, gaps
report services/api jobs
ai services/ai model_calls (latency, token usage auditing)
audit future events
notification future notifications

Authentication Schema (Better Auth)

  • identity.users β€” Extends Better Auth user with tenant fields (organization_id)
  • identity.sessions β€” Active login sessions, tokens, expiry, IP/user-agent
  • identity.accounts β€” Linked auth providers (credentials, GitHub, Google)
  • identity.verifications β€” Temporary tokens for email verification and password resets

Migrations are in infra/db/migrations/. Demo seed data is in infra/db/seeds/.


πŸ”’ Security & Access Control

RBAC Roles

Role Document Upload Source Download RCA Compliance Scan Reports Dashboard
Admin βœ… βœ… All βœ… βœ… βœ… βœ…
Plant Manager βœ… βœ… Restricted βœ… βœ… βœ… βœ…
Engineer βœ… βœ… Restricted βœ… ❌ βœ… βœ…
Compliance Officer βœ… βœ… Confidential ❌ βœ… βœ… βœ…
Technician βœ… βœ… Public/Internal ❌ ❌ ❌ ❌
Viewer ❌ βœ… Public only ❌ ❌ ❌ ❌

Document Access Levels

Level Visibility
public All authenticated users in the plant
internal All authenticated users in the plant
restricted Admin, Plant Manager, Engineer, Compliance Officer
confidential Admin, Compliance Officer only

Security Features

  • Rate Limiting β€” Configurable sliding-window (Go API) and token-bucket (Python AI) limiters
  • CORS β€” Origin allowlisting via CORS_ALLOWED_ORIGINS
  • Presigned URLs β€” Document downloads via 600-second expiring MinIO signed URLs
  • Plant Scoping β€” All endpoints verify plant membership within the user's organization
  • Metadata vs. Source Separation β€” Document metadata is visible separately from source file access

πŸ§ͺ Testing

Available Test Commands

# Run all tests (API + AI + Web build)
make test

# Go API tests
make test-api

# Python AI tests (mock mode by default)
make test-ai

# Next.js build validation
make test-web

# Live smoke test (requires running stack)
make smoke

CI Pipeline

The GitHub Actions CI pipeline (.github/workflows/ci.yml) runs on every push to main and on all PRs:

  1. Repository layout validation β€” Ensures required files exist
  2. Docker Compose validation β€” Runs make compose-config
  3. Go API tests β€” make test-api
  4. Python AI tests β€” make test-ai (mock mode)
  5. Web app build β€” make test-web

Git Hooks

Pre-commit and pre-push hooks run make test automatically. Bypass with --no-verify:

git commit -m "message" --no-verify
git push origin branch --no-verify

🚒 Deployment

Local Development (Docker Compose)

# Full stack (with local PostgreSQL)
docker compose --profile local-db up --build

# Without local DB (using Supabase or external PostgreSQL)
docker compose up --build

# Verify
make smoke

Production Strategy

Component Recommended Deployment
apps/web Vercel or Node.js container
services/api Go container, public HTTP entry point
services/ai Python container, internal HTTP (not browser-facing)
PostgreSQL Managed Postgres (Supabase, RDS, Cloud SQL)
Object Storage AWS S3, Cloudflare R2, or self-hosted MinIO
Redis Managed Redis (for event streaming when needed)

Makefile Reference

Command Description
make help Show all available commands
make infra-up Start Redis and MinIO only
make local-db-up Start bundled local PostgreSQL
make services-up Start entire backend stack
make services-down Stop the stack
make db-migrate Apply schema migrations
make db-seed Seed demo data
make seed-demo-auth Create demo login accounts
make compose-config Validate docker-compose.yml
make smoke Run live health and auth checks
make test Run all test suites
make ps Show running services
make logs Follow compose logs

For the complete deployment guide, see docs/DEPLOYMENT.md.


πŸ—Ί Roadmap

βœ… Implemented (MVP)

  • Document upload with multipart validation and duplicate detection
  • Text extraction with OCR fallback for scanned documents
  • Markdown normalization, table extraction, and content chunking
  • 1536-dimensional vector embeddings via Google text-embedding-004
  • RAG copilot with LangGraph state machine, citations, and confidence scores
  • Stateful conversations with PostgreSQL-backed memory checkpointing
  • Asset entity extraction and profile aggregation
  • Root cause analysis with probable causes and recommendations
  • Compliance gap detection (missing evidence, expired inspections)
  • Dashboard with core metrics
  • Report generation (CSV, PDF, DOCX) for 5 report types
  • RBAC with 6 role levels and document-level access control
  • Document versioning with evidence re-processing
  • Better Auth integration (email/password + OAuth)
  • Containerized full-stack deployment (Docker Compose)
  • CI pipeline with GitHub Actions

πŸ”œ Planned

  • Production-hardened JWT/provider auth flow
  • Per-section/per-page document ACLs
  • Advanced query filters (document type, date range)
  • Deep knowledge graph: relationship extraction, alias handling, graph expansion
  • Full RCA: timeline, missing-data analysis, page-level evidence, conflict handling
  • Regulatory rule ingestion for compliance
  • Redis Streams event bus for async document processing
  • OpenTelemetry tracing across all services
  • Service-to-service auth (signed tokens / mTLS)
  • Kubernetes + Helm deployment manifests

🚫 Out of Scope (Not in MVP)

  • Full ERP/SAP/Maximo integration
  • Real-time IoT/SCADA integration
  • Full CAD/P&ID symbol parsing
  • Production-grade regulatory certification
  • Offline mobile app
  • Custom LLM fine-tuning

πŸ“ Architecture Decision Records

ADR Title Status
ADR-0001 Domain Boundaries and Consolidated Runtime Accepted
ADR-0002 AI Service Modularization, Web Containerization, and Security Controls Accepted

Key Architectural Decisions:

  1. Consolidated Runtime β€” Domain boundaries are maintained through PostgreSQL schemas and contracts, not separate deployable services. A new service is only created when there's a concrete need (independent scaling, separate ownership, distinct deployment lifecycle).

  2. AI Service Modularization β€” The AI service was refactored from a monolithic main.py into modular components (config, schemas, database, routes, utils) for maintainability and testability.

  3. LangGraph for RAG β€” The RAG pipeline uses a compiled LangGraph state machine instead of procedural lookups, enabling stateful reasoning, intent classification, memory persistence, and self-correcting citation validation.


Team Workstreams

Workstream Folder(s) Focus
Frontend apps/web Dashboard, Upload UI, Copilot, Asset Profile, Reports
Backend API services/api Auth, uploads, document lifecycle, RBAC, reports
Retrieval & AI services/ai OCR, chunking, embeddings, RAG, citation validation
Asset & Graph services/api + services/ai Asset profiles, entity dedup, graph relationships
RCA & Compliance services/api + services/ai RCA agents, compliance rules, evidence matching
Database & Infra infra/ Schemas, migrations, Compose, Helm, observability
Demo & QA data/, tests/, docs/ Sample docs, test fixtures, evaluation checks

πŸ“š Further Documentation

Document Description
docs/ARCHITECTURE.md Detailed architecture and processing pipelines
docs/API_CONTRACTS.md Full API endpoint examples with request/response
docs/DATA_MODEL.md Complete database schema and table reference
docs/MICROSERVICES.md Service topology and communication rules
docs/DEPLOYMENT.md Local and production deployment guide
docs/MVP_SCOPE.md MVP scope, status, and remaining gaps
docs/EVENTS.md Event contracts and async messaging
docs/DEMO_FLOW.md Demo script and sample dataset
docs/SERVICE_CATALOG.md Service registry with ports and ownership
docs/TEAM_WORKSTREAMS.md Team ownership and workstream breakdown

πŸ“„ License

This project is proprietary. All rights reserved.


Built with ❀️ by the PlantBrainAI team

About

An AI-powered industrial knowledge platform that ingests plant documents, extracts asset intelligence, and enables RAG-based querying, RCA, and compliance insights through OCR, knowledge graphs, and agentic workflows

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages