Rethinking Knowledge Graphs -2
From a Solid Foundation to an Autonomous Agent
In Part-1, we solved our biggest problem: The brittle, unscalable text-to-cypher pipeline.
The solution was a Foundational GraphRAG Agent System using:
- A basic, prompt driven ingestor that creates a : (Doc) -> (Chunk) -> (Fact) -> (Entity) graph from text files/input.
- A foundation LangGraph based retriever agent that used “VectorRetriever” with multiple fallback mechanisms & a simple, structured : (Fact) -> (Entity) -> (Fact) hop.
Now this system works fine & is reliable to an extent. But it’s not really smart. It suffered from couple of bottlenecks :
- Context -Blind Ingestion: Generic handling of all document types irrespective of structure i.e. no concept of page breaks, document headers, or table handling etc.
- Limited Inter-Connectivity: Lack of horizontal connectivity between the graph nodes that aids in the more comprehensive traversal.
- Lacking Node Discovery: Since the primary node discovery is completely fact embedding dependent for now while in fallback we have options like section-fact text combination etc.(Vector search is great for semantic meaning but poor for specific keywords)
- Context Redundancy & Hallucination Risk: Although we have a context manager to keep the context under control but we can do more as to what value we extract from the context e.g. removing duplicate information & prioritizing context relevancy etc.
- On-Rails Retrieval: The “Level 1” retriever is “on rails” i.e. it can only hop via :
( Fact ) → ( Entity ) → ( Fact ) i.e. blind to relationships like parent/source nodes, horizontal nodes etc.
This article (Part 2) details our journey to a “Level 2” implementation: a dynamic, adaptive ingestion pipeline and an autonomous agentic retriever that truly gave the system agency.
From Flexible to Autonomous
Solution Part 1: The “Document-Context Aware” Ingestor
Our goal is to keep the good parts from the “Level-1” ingestor & add on top of it i.e.
- Dynamic text extraction setup
- Context-awareness i.e. dynamic, file-aware chunking & processing strategies
- Increased connectivity i.e. [ : NEXT] relationship capturing chunk sequencing
Thus, creating our advanced ingestor.
The “Dynamic” Ingestion Flow:
Our pipeline is designed to be versatile, accommodating various document formats and extraction strategies.
- Pre-processing & Extraction : Addition of a FileProcessor component (e.g., using PyPDF2 for PDFs or simple file reads for TXT/MD) extracts raw text from the input documents.
- Dynamic Chunking Strategy : Adapting chunking based on the document’s inherent structure to preserve context.
Logic: A DynamicStrategy component analyzes the document type (e.g., PDF, Markdown, Text) to determine the most appropriate chunking method.
Structured: Document-level chunking or field/element-specific chunking (e.g., for XML/JSON-like content).
Semi-structured: Document structure/context-aware chunking, page-level chunking, or hybrid strategies (combining structure and splitting).
Unstructured: Semantic chunking, recursive character chunking, or fixed-size chunking.
For example in our implementation , we have page-by-page strategy for PDFs ; header_aware strategy for Markdowns ; standard chunking for Texts.
3. Adding more relationships : Crucially, [:NEXT] relationships are added between sequential SectionChunk nodes to maintain document flow.
4. Idempotency & Standardization :
Before processing, we ensure that documents are not redundantly processed and that all chunks adhere to a uniform structure.
- Idempotency Check: A check is performed against the Neo4j database using fileName and hash to prevent re-ingestion of identical documents. If a document exists, its chunking_strategy is retrieved.
- Structure Standardization: Regardless of the initial chunking strategy, all chunks are transformed into a generic hierarchical JSON-based structure. Variations are captured as metadata, allowing for a “flattened” view later. This ensures consistency for downstream processing.(This standardization can be enforced via direct LLM prompting or by defining Pydantic models.)
Solution Part 2: The “Hybrid-Autonomous” Retriever
This is where our system becomes truly autonomous. We made 3 critical upgrades to our retrieval pipeline i.e.
- Hybrid Search for Smarter Node Discovery rather than fallback
- Omni-Traversal for Autonomous Exploration
- Context Relevance Optimization at Context Manager
Thus, creating our advanced retriever.
The “Autonomous” Retrieval Flow:
Our pipeline is designed to be autonomous, requiring minimal manual intervention & structure such that it handles both traversal & context well.
- Hybrid Retriever for Initial Node Discovery : Initially, in Part 1 we were leveraging Fact based Vector Retriever for the primary initial node discovery with Section based Vector Retriever & Full-text(Section-Fact) based Retriever as fallback.
But here in Part 2, we thought of making the primary initial node discovery with Hybrid(Vector Retriever + Full-text Retriever) alternative.
This retriever from neo4j-graphrag does both i.e. vector search & full- text search simultaneously & then re-ranks them according to the ranking algorithm (merging of scores).
This improves our ability to find perfect initial nodes, balancing semantic relevance with keyword precision.
Get Soumya Ranjan Das’s stories in your inbox
Join Medium for free to get updates from this writer.
2. Omni- Directional Traversal : Earlier version has a potent retriever but it had certain limitations like : Only single relationship based traversal
Older Hop:
MATCH (f : FactNode) — [ : HAS_ENTITY] → (e : EntityNode) <- [ : HAS_ENTITY] — ( neighbor : FactNode)
This is rigid. It’s an on-rails type mechanism.
New Hop:
MATCH p = (start) — [*1 . . 2] — (neighbor)
This is autonomous. It tells : “Start at the node(s) you just found (start), and explore any relationship ( — [*1 . . 2] — ) upto 2 hops away to find any new neighbor.”
This unlocks the full power of our graph i.e. it can autonomously decide to :
- Read the next paragraph/chunk
- Get the source context
- Find related facts
- Find other facts in the same chunk
- Find other chunks in the same document
We have added a check to exclude nodes already in its notebook, thus truly exploring the “unknowns” of the graph without any limitations.
3. Context Optimization : As we have realised by now that context handling is very critical to control the token usage . While in part 1 we were only doing summarization , we realized that :
Summarization is as good as the relevance of the information getting summarized.
Thus we implemented 2 stage context optimization trigger :
- Pruning: If the number of retrieved items exceeds a threshold (e.g., 20 items), an LLM is used to prune less relevant items, focusing on the core query.
- Summarization: If the total character length of the context exceeds a predefined limit (e.g., 4000 characters), the LLM summarizes the context to fit within token windows while preserving key information.
That’s how we ensured that the context remains relevant & manageable.
Now to summarize the complete implementation :
We now have a powerful, self-correcting retrieval loop i.e. embedded with Hybrid search, Omni-traversal hop, Better Context Handling Along with the already Adaptive Decision Making/Query Refinement Loop .
This loop runs with minimal human intervention, providing high-quality results by autonomously navigating, evaluating, replanning its own queries.
Potential Usecases :
(Where you don’t have a standard strategy or relationship base for retrieval)
- Complex Q&A over Large Knowledge Bases: Answering multi-faceted questions that require combining information from different sections or documents. E.g., “What are the key differences between Product A and Product B’s security features, and how do they impact compliance in Europe?”
- Investigative Research: Tracing relationships between entities, events, or concepts across a corpus. E.g., “Show me all research papers citing this specific methodology and the authors who frequently collaborate on this topic.”
- Internal Knowledge Management: Providing precise answers to employee queries across various internal documents, policies, and project specifications.
- Legal Discovery: Identifying interconnected facts, parties, and legal precedents in large document sets.
- Scientific Literature Review: Discovering connections between genes, proteins, diseases, and drugs across biomedical literature.
Key Benefits :
- Enhanced Contextual Understanding: Moving beyond keyword matching to grasp relationships between pieces of information.
- Reduced Hallucinations: By grounding answers directly in the interconnected facts of the graph, LLMs are less likely to generate fabricated information.
- Explainability & Trust: The graph structure provides an audit trail for how an answer was derived, increasing transparency and user trust.
- Adaptability to Document Types: The dynamic chunking and standardization handle diverse data inputs gracefully.
- Efficient Retrieval for Complex Queries: Graph traversals can be more efficient than repeated keyword or vector searches for intricate queries.
Is it the ultimate solution? Absolutely not!
Potential Improvements and Future Work
The described GraphRAG system is a powerful foundation, but several enhancements can further improve its capabilities:
- Custom Reranking: The Hybrid Retriever we utilised is reliant on standard re-ranking algorithms like NAIVE/LINEAR etc. We plan to implement better scoring-weightage mechanism to ensure relevant top-k retrievals.
- True Agentic Dynamicity (Tool Calling) : Rather than using functions directly as part of node we could make it more agentic/autonomous i.e. we attach them as tools to the agent node, thus giving it discretion to dynamically decide/plan which tools to use & order of use according to circumstances.
- Return of Cypher() : Cypher is a important way to navigate graphs. As the open-source llms get better at text-to-cypher or better way of addressing the reliability is found, we can integrate the text-to-cypher back but as an optional tool rather than a fragile dependency i.e. if the query is really structured & pointed, its better to generate the appropriate cypher query (run_cypher_query) & run it instead of omni-traversal
- Multi-Hop Reasoning: The agent can follow trails of information across the graph, mimicking human reasoning to answer questions that require multiple steps of inference.
Conclusion
Building a knowledge graph shouldn’t be months long custom code nightmare. It’s time we re-allign how we approach our graph pipelines.
Our Journey has taught us that the solution is an evolution.
- Level 0 : Skeletal Ingestion & Retrieval Structure based on Original Paper, But with fragile text-to-cypher.
- Level 1 : Solving the core problem with generic, prompt-driven ingestor and a foundational GraphRAG agent.
- Level 2 : Making it smart with dynamic, context-aware ingestion and autonomous, omni-traversal retrieval.
By embracing this evolution, we’ve moved from a system that is fragile, to one that is flexible and finally, to the one that can autonomously reason & explore.










