Skip to content

Repository files navigation

🧙 Enchanto AI

Your Autonomous Wizard for Consumer Justice

Cast Spells of Fairness — Five autonomous agents that research, gather evidence, strategize, negotiate, review, and self-correct their own work — across 8 real-world dispute domains — without a human steering each step.

Google Gemini MongoDB Atlas Actian Neo4j FastAPI Next.js 15

"It's not magic, it's structured autonomy — but it feels like a spell."


Enchanto Banner

The Problem

Health insurers denied 19% of in-network claims in 2024 — roughly 85 million rejected claims across ACA marketplace plans alone — yet fewer than 1% of those denials were ever appealed. Insurance denials are rarely contested, largely because the appeals process is opaque and intimidating for the average patient. The frustrating part: when patients actually do appeal, overturn rates reach 70–80% or higher — meaning most people who get denied were probably entitled to win, but never even tried because they didn't know how.

This asymmetry is not unique to healthcare. The same dynamic exists in banking chargebacks, telecom billing disputes, airline refund claims, and e-commerce returns: a company denies you with a form letter, and fighting back requires knowledge, evidence, and effort that most people do not have.

Enchanto AI was created to solve this. It is your autonomous advocate — a digital wizard that has studied consumer regulations, recalls precedents, and automates evidence-backed escalations.

Beyond the LLM Wrapper

Enchanto's reliability and depth come from its structured, multi-agent architecture rather than simple API calls:

  1. Retrieval Grounding: Citations are grounded in real, pre-indexed vector and graph databases, rather than LLM memory.
  2. Multi-Agent Decomposition: Tasks are delegated to 5+ specialized agents orchestrated via a LangGraph state machine.
  3. Structured & Audited Output: Real-time review agents validate and self-correct drafted content before presenting it.
  4. Domain-Specific Workflows: Specialized prompts and schema definitions tailored to each consumer dispute domain.

What Enchanto AI Does

Provide a one-sentence description of your dispute in any language and optionally upload supporting documents (bills, policies, denial letters). Enchanto will automatically:

  1. 🎩 Sorting Hat Router: Classifies the query into one or more of the 8 dispute domains. Queries touching multiple domains (e.g., a delayed flight with a denied travel insurance claim) run in parallel and get merged.
  2. 🔍 Actian Vector Search: Retrieves relevant regulatory clauses and terms from a pre-indexed vector database.
  3. 📄 Evidence Extractor: Parses and structures uploaded evidence files (with multimodal OCR fallbacks for scanned images/PDFs), matching them against domain requirements.
  4. ⚡ Strategy Cast: Establishes a legal and procedural blueprint (success probability, escalation paths, and key arguments).
  5. 🔄 Self-Correction Gate: An independent Review Agent audits the drafted strategies for citation accuracy and logical consistency. If an issue is flagged, it triggers an autonomous retry before output delivery.
  6. 🌐 Multilingual Synthesis: Outputs highly detailed, localized, and actionable documents (appeal letters, emails, regulatory complaints) in the user's input language.

Architecture — The Enchanto Spell Engine

Multi-Agent Pipeline

flowchart TB
    subgraph Client["🖥️ Enchanto Portal"]
        UI["Next.js 15 · React 19<br/>3D Knowledge Graph · AI Assistant · Document Vault"]
    end

    subgraph API["⚙️ FastAPI Spell Router"]
        Router["Sorting Hat Router<br/>(multilingual classification via Gemini)"]
        Graph["LangGraph Multi-Agent Pipeline"]
    end

    subgraph Agents["🪄 Autonomous Enchanto Agent Pipeline"]
        direction TB
        Planner["Planner Wizard"] --> Retrieval["Retrieval Agent<br/>(Qdrant/JSONL Vector Search)"]
        Retrieval --> KGraph["Knowledge Graph Agent<br/>(Neo4j/JSONL Graph Store)"]
        KGraph --> WebSearch["Web Search Agent"]
        WebSearch --> Specialists["Domain Specialists<br/>(6 parallel JSON reasoners via Gemini)"]
        Specialists --> Negotiator["Negotiator Wizard"]
        Negotiator --> Evidence["Evidence Agent"]
        Evidence --> Strategy["Strategy Agent"]
        Strategy --> Appeal["Negotiation Agent<br/>(drafts real documents)"]
        Appeal --> Review["Review Agent<br/>(hallucination / citation gate)"]
        Review -. "spell misfired — retry" .-> Strategy
        Review -- "spell approved ✓" --> Response["Response Agent<br/>(synthesis + translation via Gemini)"]
    end

    subgraph Infra["🗄️ The Enchanted Infrastructure"]
        Qdrant[("Qdrant Vector DB<br/>(Actian Relevance)")]
        Neo4j[("Neo4j<br/>Knowledge Graph")]
        MongoDB[("MongoDB Atlas<br/>Cases, Storage & Runs")]
        Redis[("Redis<br/>Spell Cache")]
        Gemini["Google Gemini API<br/>LLM + Embeddings + OCR"]
    end

    UI -->|REST /api/v1| Router
    Router --> Graph
    Graph --> Agents
    Retrieval <--> Qdrant
    KGraph <--> Neo4j
    Specialists <--> Gemini
    Response <--> Gemini
    API <--> Redis
Loading

Self-Correction Loop

sequenceDiagram
    participant S as 🧙 Strategy Agent
    participant A as 📜 Negotiation Agent
    participant R as 🔍 Review Agent
    participant O as 🌐 Response Agent

    S->>A: proposed strategy + citations
    A->>R: drafted appeal / complaint
    R->>R: check for hallucinated claims<br/>and mis-cited clauses
    alt Spell misfired (capped at 1 retry)
        R-->>S: review_should_retry = true
        Note over S,R: Strategy re-runs autonomously —<br/>no human in the loop
        S->>A: revised strategy
        A->>R: revised draft
    end
    R->>O: approved output + review_history
    O->>O: synthesize, translate,<br/>never contradict the evidence
Loading

Agentic Capabilities vs. Basic Chatbots

Feature A Standard Chatbot Enchanto AI
Execution Flow One-shot prompt-response model 5+ specialist agents in a LangGraph state machine
Persistence & Context General session-restricted memory Persistent cross-user Knowledge Graph linking users, cases, and institutions
Output Integrity Blindly trusts its first generated draft Dedicated Review Agent verifying citations and enforcing corrections
Intelligence Sharing No shared intelligence across conversations Institution Accountability Radar: tracks institutional disputes across all citizens
Primary Engine General text generator Google Gemini 3.5 Flash-lite (optimized for low-latency reasoning and OCR)

Core Database Roles

To run efficiently both in development and production, Enchanto separates concerns across several databases:

  • MongoDB: Acts as the system's database of record. Stores citizen case metadata, accounts, document vault files, and detailed execution logs of agent runs.
  • Qdrant (referred to in the UI as Actian): Stores chunked regulations, consumer laws, and corporate policy vector embeddings. Enables high-dimensional semantic search and RAG retrieval.
  • Neo4j: Represents the relational knowledge graph mapping citizens, cases, institutions, and dispute outcomes. Powers graph visualizations and historical pattern matching.
  • Redis: Caches API routes, model outputs, prompt templates, and vector lookups to lower cost and bypass rate limits.

Note

For local development, Neo4j can fall back to lightweight local .jsonl databases to run the application with zero external dependencies.


8 Dispute Domains

Enchanto is preconfigured to handle disputes across eight major regulated sectors:

Domain Key Regulatory Bodies / Frameworks
🏥 Health Insurance IRDAI rules, Claim Denials, Pre-authorizations, Exclusions
🏦 Banking RBI guidelines, unauthorized chargebacks, card fraud, service disputes
📡 Telecom TRAI compliance, billing overcharges, broadband SLAs, contracts
✈️ Airlines DGCA rules, cancellation refunds, baggage loss, flight delays
🛒 E-commerce Consumer Protection (E-Commerce) Rules, warranty, defect returns
🏛️ Government RTI Act (Right to Information), state public services, grievances
🏠 Housing RERA (Real Estate Regulatory Authority) disputes, rental tenancies
🩺 Healthcare Patient rights, medical billing, clinical guideline references

Step-by-Step Installation Guide (Docker Setup)

For the easiest setup, run the entire Enchanto stack inside Docker. This spins up the API, Next.js frontend, MongoDB, Qdrant, Neo4j, and Redis in local containers.

Prerequisites

Make sure you have the following installed on your machine:


Step 1: Clone the Repository

Clone the repository and navigate to the project root:

git clone https://github.com/rajdeep13-coder/enchanto.git
cd enchanto

Step 2: Environment Configuration

Create a .env file in the root Enchanto/ directory by copying the example environment file:

cp .env.example .env

Open the .env file and fill in the required environment variables:

# Required credentials
GEMINI_API_KEY=your_gemini_api_key_here
TAVILY_API_KEY=your_tavily_api_key_here
JWT_SECRET=your_secure_jwt_secret_here

# Service Backends (Preconfigured to use Docker services)
VECTOR_STORE_BACKEND=qdrant
GRAPH_STORE_BACKEND=neo4j
MONGODB_URI=mongodb://mongodb:27017/enchanto

Step 3: Spin Up Containers

Run the Docker Compose command to build and launch all services in background detached mode:

docker-compose up --build -d

This builds and starts the following services:

  • api: FastAPI backend service at http://localhost:8000
  • frontend: Next.js client UI at http://localhost:3000
  • mongodb: Database storing case metadata at localhost:27017
  • qdrant: Vector database indexing regulations at localhost:6333
  • neo4j: Graph database tracking network associations at localhost:7687
  • redis: Key-value cache layer at localhost:6379

Step 4: Seed Knowledge Databases (Ingestion)

Once the containers are running and healthy, seed the local databases with the precompiled regulatory corpus. Execute the following command to trigger the ingestion scripts inside the running API container:

# Ingest the default health insurance regulations
docker-compose exec api python scripts/ingest_knowledge.py --domain health_insurance

# Ingest other domains (e.g., telecom, banking, e-commerce)
docker-compose exec api python scripts/ingest_knowledge.py --domain telecom
docker-compose exec api python scripts/ingest_knowledge.py --domain ecommerce

Step 5: Verification & Access

Verify that the services are online:

  1. Enchanto UI: Open http://localhost:3000 in your browser.
  2. API Docs: Access the FastAPI Swagger interface at http://localhost:8000/docs to test endpoints manually.
  3. Health Check: Query http://localhost:8000/health to check the connection status of the active databases and LLM provider.

Alternate Setup: Manual Local Execution (Without Docker)

If you prefer to run services natively on your host machine:

1. Setup Backend

cd backend
python -m venv .venv
source .venv/bin/activate  # On Windows use: .venv\Scripts\activate
pip install -r requirements.txt

To run without local database dependencies (falling back to JSONL local files):

# In your .env file:
VECTOR_STORE_BACKEND=jsonl
GRAPH_STORE_BACKEND=jsonl
DISABLE_EXTERNAL_LLM=false

Start the FastAPI server:

uvicorn app.main:app --reload --port 8000

2. Setup Frontend

Ensure you have Node.js 18+ installed:

cd frontend
npm install
npm run dev

Open http://localhost:3000 to access the application.


Seeding & Ingestion Scripts Directory

Enchanto contains custom data scraping and ingestion scripts located in scripts/ (and duplicated within backend/scripts/ for container access) to help bootstrap and maintain the knowledge database:

  • ingest_knowledge.py: The primary CLI tool to parse, chunk, embed, and index markdown documents from knowledge/<domain> into the active vector and graph databases.
  • collect_telecom_official_sources.py: Automated crawler that downloads official TRAI circulars, customer guidelines, and tariff regulations.
  • collect_ecommerce_official_sources.py: Scraping script for downloading consumer protection rules and return policies from marketplace platforms.
  • migrate_vectors_to_qdrant.py: Utility to copy local JSONL vectors generated during development into a live Qdrant container.
  • migrate_events_to_neo4j.py: Extracts event lists from local JSONL stores and creates corresponding nodes and relations in Neo4j.
  • check_health_stack.py: Quick sanity check that pings all configured databases and LLM endpoints.

Validation & Testing

Enchanto features a comprehensive backend test suite built with pytest that tests LLM providers (with mocked API requests), routers, databases, OCR, and state graph transitions.

Running Backend Tests

Ensure your backend virtual environment is active:

cd backend
pytest -v

Tip

The test configuration automatically overrides credentials to test offline configurations. No active external LLM connections or databases are required to run the unit tests.


Project Structure

Enchanto/
├── backend/
│   ├── app/
│   │   ├── agents/                  # LangGraph multi-agent pipeline
│   │   │   ├── orchestrator/        # Case analysis workflow orchestration
│   │   │   ├── domain_agents/       # Per-domain specialist agents
│   │   │   ├── research_agent/      # Regulatory research + RAG retrieval
│   │   │   ├── evidence_agent/      # Document evidence extraction
│   │   │   ├── strategy_agent/      # Appeal strategy generation
│   │   │   ├── negotiation_agent/   # Appeal letter + complaint drafting
│   │   │   ├── review_agent/        # Hallucination gate + self-correction
│   │   │   ├── final_report_agent/  # Case report synthesis
│   │   │   ├── graph_agent/         # Knowledge graph querying
│   │   │   ├── role_agents/         # Shared role-based agent primitives
│   │   │   ├── tools/               # Agent tool definitions
│   │   │   └── state.py             # Shared LangGraph state schema
│   │   ├── api/routes/              # FastAPI route handlers
│   │   ├── auth/                    # JWT authentication + dependencies
│   │   ├── core/                    # Config, logging, error handling, startup
│   │   ├── database/
│   │   │   ├── mongodb/             # MongoDB Atlas client + repositories
│   │   │   ├── postgres/            # Local JSONL-backed repository store
│   │   │   └── supabase/            # Supabase client (fallback client)
│   │   ├── knowledge_graph/         # Neo4j + JSONL-fallback graph stores
│   │   ├── llm/
│   │   │   ├── providers/           # Gemini + NVIDIA provider implementations
│   │   │   ├── router/              # Model router + circuit breaker
│   │   │   └── service.py           # Provider-agnostic LLM service
│   │   ├── middleware/              # Request context middleware
│   │   ├── models/                  # Domain model definitions
│   │   ├── prompts/                 # Per-domain prompt templates
│   │   ├── rag/
│   │   │   ├── chunking/            # Text chunking strategies
│   │   │   ├── indexing/            # Vector indexing service
│   │   │   └── retrieval/           # Qdrant + JSONL vector stores
│   │   ├── schemas/                 # Pydantic request/response schemas
│   │   ├── services/                # OCR, citation engine, web search, cache
│   │   ├── storage/                 # Document upload + storage service
│   │   └── workflows/               # LangGraph workflow definitions
│   ├── datasets/
│   │   ├── reindex_jobs/            # Per-domain reindex job configs (versioned)
│   │   └── vector_embeddings/       # Collection registry + local JSONL vector store
│   ├── scripts/                     # Data ingestion, scraping, seeding, migration scripts
│   ├── tests/                       # Pytest test suite
│   ├── Dockerfile
│   └── requirements.txt
├── frontend/
│   ├── app/
│   │   ├── (marketing)/             # Landing page + marketing layout
│   │   ├── dashboard/               # Dashboard shell + all feature pages
│   │   │   ├── analyses/            # Analysis history
│   │   │   ├── appeals/             # Appeals center
│   │   │   ├── assistant/           # AI assistant chat
│   │   │   ├── cases/               # Case management
│   │   │   ├── cross-domain-search/ # Cross-domain search
│   │   │   ├── documents/           # Document vault
│   │   │   ├── institution-radar/   # Institution accountability radar
│   │   │   ├── knowledge-graph/     # 3D knowledge graph viewer
│   │   │   ├── notifications/       # Notifications center
│   │   │   ├── reports/             # Case reports
│   │   │   ├── settings/            # User settings
│   │   │   └── upload/              # Document upload flow
│   │   ├── login/                   # Login page
│   │   └── signup/                  # Signup page
│   ├── components/
│   │   ├── 3d/                      # Shared Three.js scene components
│   │   ├── analyses/                # Analyses board UI
│   │   ├── appeals/                 # Appeals center UI
│   │   ├── chat/                    # AI assistant chat, reasoning trace, citations
│   │   ├── dashboard/               # Dashboard home + domain orbit
│   │   ├── documents/               # Document vault UI
│   │   ├── landing/                 # Landing page sections (Hero, HowItWorks, etc.)
│   │   ├── new-analysis/            # New analysis flow
│   │   ├── notifications/           # Notifications UI
│   │   ├── proxy-v2/                # Intelligence center + analysis widgets
│   │   ├── reports/             # Case report views + charts
│   │   ├── search/                  # Evidence score breakdown
│   │   └── settings/                # Settings center
│   ├── features/
│   │   └── knowledge-graph/         # Self-contained 3D graph feature
│   │       ├── components/          # Graph UI components
│   │       ├── modes/               # Reasoning trail, institution intelligence, footprint
│   │       ├── scene/               # Three.js scene setup
│   │       └── store.ts             # Zustand graph state
│   ├── lib/                         # API client, design tokens, utilities
│   ├── types/                       # TypeScript type declarations
│   ├── Dockerfile
│   └── package.json
├── docs/                            # Architecture, API, deployment, and RAG pipeline docs
├── k8s/                             # Kubernetes manifests (deployment, ingress, configmap)
├── knowledge/                       # Pre-indexed regulatory corpus (gitignored)
│   ├── airlines/                    # DGCA, AERA, airline policies
│   ├── banking/                     # RBI, ombudsman, regulations
│   ├── ecommerce/                   # Consumer Protection Act, marketplace policies
│   ├── government/                  # RTI, UIDAI, EPFO, administrative schemes
│   ├── health_insurance/            # IRDAI circulars, insurer policy documents
│   ├── healthcare/                  # WHO, patient rights, clinical guidelines
│   ├── housing/                     # RERA, rental laws, state RERA portals
│   └── telecom/                     # TRAI regulations, operator policies
├── scripts/                         # Root-level data collection + ingestion scripts
├── Dockerfile                       # Single-container build (frontend + backend)
├── docker-compose.yml               # Multi-service local development setup
└── architecture.md                  # Full system architecture document

Built for Hexafalls S2 · Wizarding Theme · Every claim in this README is backed by code in this repository.

Enchanto AI — Cast Spells of Fairness 🪄

About

Enchanto is not just another AI chatbot — it's your AI agent against unfair claim rejections. Drop in a rejection letter, and specialized agents research regulations and precedents, build an evidence-backed case, and draft a ready-to-send appeal — across insurance, banking, telecom, airlines and more.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages