← Back to list

How I Built a Knowledge Graph of the Ramayana (and Made an AI That Actually Understands It)

From 18,632 ancient verses to 20,000+ nodes, 30,000+ relationships, and an AI that can trace Rama’s family tree in milliseconds here’s the…

Codehimanshu · 2026-03-01 04:31 · 140 claps · 7.9 min read
#knowledge-graph #ramayana #agentic-ai #graphrag #valmiki-ramayana
Open on Medium ↗
Wiki topics: RAG · RAG & Retrieval AGT · AI Agents SOC · Sociology & Politics 💑 · Relationships 👨‍👩‍👧 · Family & Parenting

How I Built a Knowledge Graph of the Ramayana (and Made an AI That Actually Understands It)

From 18,632 ancient verses to 20,000+ nodes, 30,000+ relationships, and an AI that can trace Rama’s family tree in milliseconds here’s the full story.

Why the Ramayana?

Let me be real when most people think “knowledge graph project,” they think about movie databases or corporate org charts. Boring.

I wanted something epic. Literally.

The Ramayana is one of the largest and oldest narrative poems in human history. Written by the sage Valmiki, it spans 6 Kandas (books), 534 chapters, and 18,632 verses. It has hundreds of characters — gods, demons, humans, monkey warriors, celestial beings all intertwined through family bonds, battles, alliances, curses, and blessings.

In other words: it’s a graph problem.

Every character is a node. Every relationship father, enemy, ally, killer is an edge. Every event is a junction where multiple edges converge. If you can model this as a graph, you can ask questions that would take a human scholar hours to answer:

  • “Who are all the characters that fought in the Battle of Lanka AND are related to Ravana by blood?”
  • “Trace the chain of events from Surpanakha’s encounter to Sita’s abduction.”
  • “Which characters embody Dharma, and what events demonstrate it?”

That’s the kind of thing a Knowledge Graph can answer in seconds.

What Even Is a Knowledge Graph?

Before we dive into the build, let’s get the basics straight.

A Knowledge Graph (KG) is a way of storing information as entities (nodes) and relationships (edges) between them. Instead of rows and columns in a table, you get a web of connected data.

[Rama] --SPOUSE_OF--> [Sita]
[Rama] --SON_OF--> [Dasharatha]
[Rama] --KILLS--> [Ravana]
[Ravana] --ABDUCTS--> [Sita]
[Hanuman] --DEVOTEE_OF--> [Rama]

Each node has labels (Character, Location, Event, Weapon) and properties (name, type, description). Each edge has a type (KILLS, FATHER_OF, TRAVELS_TO) and can also carry properties.

The magic? Traversals. You can ask: “Start at Rama. Walk 3 hops. What do you find?” and the database (Neo4j in our case) will give you Rama’s family, his allies, the weapons he used, the events he participated in, and the locations he visited. All in one query.

Compare this with a traditional SQL database where you’d need 14 JOIN operations to answer the same question. Yeah, no thanks.

Traditional RAG vs. Graph RAG — It’s Not a Fight

Here’s a take that might surprise you: Graph RAG is NOT a replacement for traditional RAG. It’s a different tool for a different job. Or better yet — they’re teammates, not competitors.

Traditional RAG (Retrieval-Augmented Generation)

User Query → Embed query → Search vector DB → Get top-K chunks → Feed to LLM → Answer

Traditional RAG is brilliant when you have unstructured text — documents, articles, PDFs. You chunk them up, embed them into vectors, and use semantic similarity to find relevant passages. It works great for:

  • “Summarize what happened in Chapter 5”
  • “What does the text say about Hanuman’s strength?”
  • Questions where the answer lives inside a paragraph somewhere

Graph RAG (What We Built)

User Query → Extract entities → Query knowledge graph → Build structured context → Feed to LLM → Answer

Graph RAG shines when you need relational understanding — connections, paths, multi-hop reasoning:

  • “How are Rama and Ravana connected through 3 degrees?”
  • “What events involve both Sita and Hanuman?”
  • “Show me all SPOUSE_OF relationships in the Ikshvaku dynasty”

The Hybrid Dream

The real power move? Use both together.

Graph RAG provides the structure the entities, relationships, and logical connections. Traditional RAG adds the richness the narrative detail, context, and textual depth. Together, they create a complete and coherent understanding.

The Architecture How It All Fits Together

Here’s the full system architecture. Take a deep breath.

Phase 1: Data Collection & The 10-Phase Pipeline

The data comes from the Ramayanam project — a structured dataset of the Griffith translation of the Valmiki Ramayana. We’re talking:

  • 6 JSON files (one per Kanda): BalaKanda, AyodhyaKanda, AranyaKanda, KishkindhaKanda, SundaraKanda, YuddhaKanda — containing all 18,632 verses with translations
  • CSV files: Character lists, co-occurrence matrices (who appears with whom, per book and per chapter), VADER sentiment scores for each character pair, character clustering/importance scores, and full chapter text

The Pipeline (build_kg.py — 893 lines of Python)

The pipeline runs in 10 sequential phases, each building on the last:

The curated relationships in Phase 8 are the secret sauce. This is where we manually mapped out(Using the Agents and a litte bit of Steering):

  • Rama’s entire family tree — Dasharatha → Rama, Kausalya → Rama, Rama ↔ Sita, etc.
  • Ravana’s lineage — his parents, siblings, sons like Indrajit and Aksha
  • The Vanara alliance — Sugriva, Hanuman, Angada and their relationships
  • Divine incarnations — Rama as INCARNATION_OF Vishnu
  • 30+ distinct relationship types — from FATHER_OF to WIELDS to CURSES

Phase 2: The Graph RAG Engine

This is where things get really cool. Here’s how the “Ask Ramayana” chat feature works under the hood:

Step 1: Entity Extraction

When you type “What role did Sita play in the Ramayana?”, the system first extracts entity names. We maintain a list of 44 known characters and an alias map (because the Ramayana calls the same character by many names):

// "Raghava" = Rama, "Janaki" = Sita, "Anjaneya" = Hanuman
const ALIASES = {
  raghava: "Rama", janaki: "Sita", vaidehi: "Sita",
  anjaneya: "Hanuman", dashagriva: "Ravana", ...
};

From the query “What role did Sita play?”, it extracts: ["Sita"].

Step 2: Graph Traversal (Cypher Queries)

For each extracted entity, we fire two Cypher queries against Neo4j:

Query 1 — Character info + all outgoing relationships:

MATCH (ch:Character {name: "Sita"})
OPTIONAL MATCH (ch)-[r]->(t)
WHERE NOT type(r) IN ['SIMILAR_TO','INTERACTS_IN_CHAPTER','CO_OCCURS_WITH']
RETURN ch.name, ch.type, collect(DISTINCT {rel: type(r), target: t.name})

Query 2 — Events involving the character:

MATCH (ch:Character {name: "Sita"})-[:PARTICIPATES_IN]->(e:Event)
RETURN e.name, e.type, e.description

If multiple entities are found, we also query the co-occurrence edge between them (weight + sentiment).

Step 3: Context Building

All the graph data gets formatted into a structured context string:

Character: Sita (Human)
  - SPOUSE_OF: Rama (Character)
  - PARTICIPATES_IN: Sita Swayamvara (Event)
  - PARTICIPATES_IN: Sita's Abduction (Event)
  - EMBODIES: Pativrata (Concept)
Events involving Sita:
  - Sita Swayamvara (Ceremony): Rama breaks Shiva's bow to win Sita
  - Sita's Abduction (Abduction): Ravana abducts Sita using Maricha's deer disguise
  - Agni Pariksha (Ceremony): Sita's trial by fire to prove her purity

Step 4: LLM Synthesis

This structured context gets passed to Groq’s LLaMA 3.3–70B model with a system prompt that says: “You are a Ramayana scholar AI. Answer using ONLY the provided Knowledge Graph context.”

The LLM takes the dry graph data and turns it into a fluent, narrative answer complete with markdown formatting, numbered lists, and bold highlights.

Step 5: Transparent Results

The frontend shows three things:

  1. The answer — rendered with full markdown (bold, lists, headings)
  2. Entity badges — which entities were found (“Rama”, “Sita”)
  3. Collapsible Graph RAG Context — the raw graph data, so you can see exactly what the AI was working with. Full transparency.

What We Actually Built — The Numbers

Let’s take a step back and appreciate what we pulled off:

What Needs Improvement (A Lot, Honestly)

Let’s be real — this is v1. It works, it’s cool, but it has rough edges the size of Ravana’s ten heads. Here’s the honest improvement roadmap:

1. LLM-Powered Entity Extraction (Currently Rule-Based)

Right now, we use a hardcoded list of 44 characters + an alias map to extract entities. It works for known characters but completely misses:

  • Locations mentioned in queries (“What happened at Chitrakoot?”)
  • Events mentioned directly (“Tell me about Agni Pariksha”)
  • Weapons, concepts, or dynasties

Fix: Use an LLM or NER model for entity extraction. Feed the extracted entities to the graph lookup.

2. More Sophisticated Graph Traversal

Currently, we do 2–3 simple Cypher queries per entity. We’re barely scratching the surface of what Neo4j can do:

  • Multi-hop queries“Find all characters connected to Rama through exactly 3 relationships”
  • Path finding“What’s the shortest path between Hanuman and Ravana?”
  • Subgraph extraction — Pull entire neighborhoods for richer context

3. Vector + Graph Hybrid RAG

We have chapter text stored in the graph (Phase 7 of the pipeline), but we’re not using vector embeddings yet. The dream:

  • Embed all verse translations
  • Use semantic search for relevant verses
  • Combine verse text with graph relationships for incredibly rich context

4. Agentic Workflows

The current system is a single-shot pipeline: query → extract → search → answer. An agentic approach would:

  • Break complex queries into sub-questions
  • Iteratively refine graph traversals based on intermediate results
  • Decide when to use text search vs. graph traversal
  • Self-verify answers against the graph

5. More Data, Better Data

  • The co-occurrence data is from the Griffith translation only — we could add multiple translations
  • Character descriptions could be much richer
  • We could add verse-level sentiment analysis
  • NLP-extracted events from the actual verse text (not just manually curated ones)

6. Graph Visualization Performance

The Galaxy 3D view with thousands of nodes can get slow on lower-end machines. WebGPU rendering, level-of-detail culling, or server-side graph layout pre-computation would help.

7. The Ontology Could Be Deeper

We have 30+ relationship types, but the Ramayana has nuances we haven’t captured:

  • Temporal ordering of events
  • Character emotional arcs across Kandas
  • Philosophical themes per verse
  • Regional variations of the story

The bottom line: This is an agentic knowledge graph that works, but with time and effort, it can become something truly remarkable. The foundation is solid — 20K nodes, 30K edges, a working RAG pipeline, and a beautiful frontend. Everything from here is iteration.

Final Thoughts

Building this project taught me a few things:

  1. Knowledge Graphs make you think differently about data. Instead of “what fields does this record have?”, you ask “how is this entity connected to everything else?” That shift in mindset is powerful.
  2. Graph RAG and Traditional RAG aren’t competitors — they’re complements. Use graph when you need structure, relationships, and multi-hop reasoning. Use vectors when you need semantic similarity and unstructured text retrieval. Use both when you want the best of both worlds.
  3. The Ramayana is an incredible dataset. The depth of relationships, the narrative complexity, the emotional arcs — it’s the kind of data that makes you wish every dataset was this rich.
  4. v1 is never v-final. This project has enormous room to grow — better extraction, hybrid search, agentic workflows, deeper ontology. But that’s the beauty of building in public. Ship it, share it, improve it.

DEMO VIDEO

You can see the Live Demo of the Whole system!!

[embed]

Connect with me : *LinkedIn*


메타데이터
post_id
63a8f2c98673
slug
how-i-built-a-knowledge-graph-of-the-ramayana-and-made-an-ai-that-actually-understands-it-63a8f2c98673
url
https://medium.com/@codehimanshu24/how-i-built-a-knowledge-graph-of-the-ramayana-and-made-an-ai-that-actually-understands-it-63a8f2c98673
canonical_url
https://medium.com/@codehimanshu24/how-i-built-a-knowledge-graph-of-the-ramayana-and-made-an-ai-that-actually-understands-it-63a8f2c98673
author_url
https://medium.com/@codehimanshu24
status
ok
fetched_at
2026-06-22 07:15:07