Skip to content
ImagineWorld

Graph-Based RAG

node_idnode-book_llm-design-patterns_chapter-26-graph-based-rag
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num26
chapter_titleGraph-Based RAG
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we’ll learn how to leverage graph-structured knowledge in RAG for LLMs. You’ll learn about graph-based knowledge representation and how to design RAG architectures that can utilize this structured information.

A graph-based knowledge representation structures information as nodes and edges in a graph, where nodes represent concepts or facts and edges capture their relationships. When used with RAG, this approach enables richer information retrieval by leveraging both the individual pieces of information and their interconnections, allowing for more contextual and relationship-aware responses.

We’ll cover graph embedding techniques for retrieval, query expansion using graph structures, and methods for integrating graph information into LLM generation. You’ll also explore various applications and use cases of graph RAG in LLMs.

By the end of this chapter, you’ll be able to implement advanced RAG systems that can leverage the rich relationships in graph-structured data.

In this chapter, we’ll be covering the following topics:

  • Introduction to graph-based knowledge representation for LLMs
  • Designing graph RAG architectures for LLMs
  • Graph embedding techniques for LLM retrieval
  • Query expansion using graph structures in LLMs
  • Integrating graph information into LLM generation
  • Applications and use cases of graph RAG in LLMs
  • Challenges and future directions in graph-based RAG

Introduction to graph-based knowledge representation for LLMs

Section titled “Introduction to graph-based knowledge representation for LLMs”

Graph-based knowledge representation allows complex relationships to be encoded between concepts and facts, which can significantly enhance the contextual understanding of LLMs. In a graph, nodes represent entities, and edges represent relationships between them.

Figure 27.1 – Graph-based knowledge representation for LLMs

The following are the key benefits of graph-based knowledge for LLMs:

  • Captures complex relationships
  • Enables multi-hop reasoning
  • Provides structured context for generation
  • Facilitates domain-specific knowledge integration

Let’s start by implementing a simple graph structure:

from typing import Dict, List, Tuple
class KnowledgeGraph:
def __init__(self):
self.nodes: Dict[str, Dict] = {}
self.edges: Dict[str, List[Tuple[str, str]]] = {}
def add_node(self, node_id: str, properties: Dict):
self.nodes[node_id] = properties
def add_edge(self, source: str, target: str, relation: str):
if source not in self.edges:
self.edges[source] = []
self.edges[source].append((target, relation))
def get_neighbors(
self, node_id: str) -> List[Tuple[str, str]
]:
return self.edges.get(node_id, [])
# Example usage
kg = KnowledgeGraph()
kg.add_node("Paris", {"type": "City", "country": "France"})
kg.add_node("France", {"type": "Country", "continent": "Europe"})
kg.add_edge("Paris", "France", "capital_of")
print(kg.get_neighbors("Paris"))

This code implements a foundational KnowledgeGraph class in Python, allowing knowledge to be represented as a network of interconnected entities. The class uses dictionaries to store nodes and edges, where nodes are identified by unique IDs and hold associated properties, and edges define relationships between nodes through source, target, and relation labels. The add_node method populates the nodes dictionary, while add_edge establishes connections within the edges dictionary. The get_neighbors method allows nodes directly connected to a given node to be retrieved, along with the corresponding relationship types.

This example demonstrates how to create a graph, add nodes representing Paris and France, define the capital_of relationship between them, and then query the graph to find neighbors of Paris. This structure provides a basis for encoding complex relationships and facilitating knowledge-aware applications.

Next, we’ll discuss how to design graph RAG architecture.

Designing graph RAG architectures for LLMs

Section titled “Designing graph RAG architectures for LLMs”

To design a graph RAG system, we need to integrate our knowledge graph with the retrieval and generation components:

import networkx as nx
from sentence_transformers import SentenceTransformer
import torch
class GraphRAG:
def __init__(self, kg: KnowledgeGraph, model_name: str):
self.kg = kg
self.model = SentenceTransformer(model_name)
self.graph = self.build_networkx_graph()
self.node_embeddings = self.compute_node_embeddings()
def build_networkx_graph(self):
G = nx.DiGraph()
for node_id, properties in self.kg.nodes.items():
G.add_node(node_id, properties)
for source, edges in self.kg.edges.items():
for target, relation in edges:
G.add_edge(source, target, relation=relation)
return G
def compute_node_embeddings(self):
embeddings = {}
for node_id, properties in self.kg.nodes.items():
text = f"{node_id} {' '.join(properties.values())}"
embedding = self.model.encode(text)
embeddings[node_id] = embedding
return embeddings
def retrieve(self, query: str, k: int = 5) -> List[str]:
query_embedding = self.model.encode(query)
similarities = {
node_id: torch.cosine_similarity(
torch.tensor(query_embedding),
torch.tensor(emb), dim=0
)
for node_id, emb in self.node_embeddings.items()}
return sorted(
similarities, key=similarities.get, reverse=True
)[:k]
# Example usage
kg = KnowledgeGraph()
# Add more nodes and edges to the knowledge graph
graph_rag = GraphRAG(kg, "all-MiniLM-L6-v2")
retrieved_nodes = graph_rag.retrieve("What is the capital of France?")
print("Retrieved nodes:", retrieved_nodes)

In the preceding code, we used the NetworkX Python package. The NetworkX package is designed for creating, manipulating, and studying the structure, dynamics, and functions of complex networks. It provides tools for working with graphs, which are collections of nodes (vertices) and edges (connections between nodes), and offers a wide range of algorithms for analyzing network properties, making it invaluable for fields such as social network analysis, biology, and infrastructure studies.

This code defines a GraphRAG class that combines a KnowledgeGraph object with a Sentence Transformer model to enable context-aware information retrieval. The class initializes with a KnowledgeGraph object and a Sentence Transformer model name, which it uses to build a networkx graph representation of the knowledge graph and compute embeddings for each node based on its ID and properties. The build_networkx_graph method converts the custom KnowledgeGraph object into a networkx directed graph, preserving node properties and edge relationships. The compute_node_embeddings method generates embeddings for each node by concatenating its ID and properties into a text string and encoding it using the Sentence Transformer model.

The retrieve method takes a query, encodes it using the same Sentence Transformer, calculates the cosine similarity between the query embedding and each node embedding, and returns the top k most similar node IDs. This architecture leverages graph structure and semantic embeddings to retrieve relevant knowledge based on query context, bridging the gap between symbolic knowledge representation and neural information retrieval.

Now, let’s explore more advanced techniques for representing our graph data to further enhance the performance of our LLM retrieval system. Specifically, we’ll delve into graph embedding techniques for LLM retrieval.

Graph embedding techniques for LLM retrieval

Section titled “Graph embedding techniques for LLM retrieval”

Graph embedding techniques aim to represent the nodes of a graph in a low-dimensional vector space, capturing the graph’s structural properties and relationships. Several methods exist, each with its own approach – for instance, Node2Vec explores neighborhoods through biased random walks, balancing breadth-first and depth-first exploration. DeepWalk is another random-walk-based approach but performs walks uniformly. Graph convolutional networks (GCNs) aggregate information from a node’s neighbors using convolutional operations, learning node embeddings based on the graph’s structure and node features. Graph attention networks (GATs) extend GCNs by incorporating an attention mechanism to weigh the importance of different neighbors when aggregating information. Translating Embeddings for Knowledge Graphs (TransE) is specifically designed for knowledge graphs, representing entities and relations as vectors such that if (h, r, t) holds (head, relation, tail), then h + r ≈ t.

Let’s focus on Node2Vec as an example. Node2Vec aims to create embeddings that preserve network neighborhoods. It achieves this by employing biased random walks that balance breadth-first search (BFS) and depth-first search (DFS). BFS prioritizes exploring immediate neighbors and capturing local structural information, while DFS explores distant nodes, thereby capturing higher-order dependencies and community structures. The bias is controlled by two parameters, p (return parameter) and q (in-out parameter), which influence the likelihood of revisiting the previous node or exploring distant nodes, respectively. By learning embeddings that reflect these biased random walks, Node2Vec captures both local and global network structures, allowing for effective node classification, link prediction, and community detection:

from node2vec import Node2Vec
class AdvancedGraphRAG(GraphRAG):
def __init__(self, kg: KnowledgeGraph, model_name: str):
super().__init__(kg, model_name)
self.node2vec_embeddings = self.compute_node2vec_embeddings()
def compute_node2vec_embeddings(self):
node2vec = Node2Vec(
self.graph, dimensions=64, walk_length=30,
num_walks=200, workers=4
)
model = node2vec.fit(window=10, min_count=1)
return {node: model.wv[node]
for node in self.graph.nodes()
}
def retrieve(self, query: str, k: int = 5) -> List[str]:
query_embedding = self.model.encode(query)
combined_similarities = {}
for node_id in self.graph.nodes():
text_sim = torch.cosine_similarity(
torch.tensor(query_embedding),
torch.tensor(self.node_embeddings[node_id]),
dim=0
)
graph_sim = torch.cosine_similarity(
torch.tensor(query_embedding),
torch.tensor(self.node2vec_embeddings[node_id]),
dim=0
)
combined_similarities[node_id] = \
0.5 * text_sim + 0.5 * graph_sim
return sorted(
combined_similarities,
key=combined_similarities.get,
reverse=True
)[:k]
# Example usage
advanced_graph_rag = AdvancedGraphRAG(kg, "all-MiniLM-L6-v2")
retrieved_nodes = advanced_graph_rag.retrieve("What is the capital of France?")
print("Retrieved nodes:", retrieved_nodes)

This code builds upon the GraphRAG class by incorporating Node2Vec embeddings for enhanced retrieval performance. It introduces an AdvancedGraphRAG class that inherits from GraphRAG and computes Node2Vec embeddings during initialization. The compute_node2vec_embeddings method utilizes the node2vec library to generate these embeddings, creating a Node2Vec object with specified dimensions, walk length, number of walks, and worker threads; it then trains the Node2Vec model by using random walks on the graph structure and extracts the learned node embeddings. The retrieve method is overridden to combine both the original text-based embeddings and the Node2Vec embeddings for similarity calculation. For each node, it computes the cosine similarity between the query embedding and both the text-based embedding and the Node2Vec embedding, then averages these two similarity scores with equal weights to produce a combined similarity score. Finally, it returns the top k nodes with the highest combined similarity scores, leveraging both semantic and structural information for more effective retrieval.

Now, let’s explore how we can further improve retrieval by leveraging the graph structure to refine our queries. In the next section, we’ll implement a simple yet effective technique to broaden the scope of our search.

Query expansion using graph structures in LLMs

Section titled “Query expansion using graph structures in LLMs”

We can leverage graph structures to expand queries and improve retrieval. Let’s implement a simple query expansion technique:

import random
class QueryExpansionGraphRAG(AdvancedGraphRAG):
def expand_query(
self, query: str, num_expansions: int = 2
) -> List[str]:
initial_nodes = super().retrieve(query, k=3)
expanded_queries = [query]
for node in initial_nodes:
neighbors = list(self.graph.neighbors(node))
if neighbors:
random_neighbor = random.choice(neighbors)
expanded_query = (
f"{query}"
f"{self.graph.nodes[random_neighbor].
get('type', '')}"
f"{random_neighbor}"
)
expanded_queries.append(expanded_query)
if len(expanded_queries) >= num_expansions + 1:
break
return expanded_queries
def retrieve(self, query: str, k: int = 5) -> List[str]:
expanded_queries = self.expand_query(query)
all_retrieved = []
for q in expanded_queries:
all_retrieved.extend(super().retrieve(q, k))
return list(dict.fromkeys(all_retrieved))[:k]
# Example usage
query_expansion_rag = QueryExpansionGraphRAG(kg, "all-MiniLM-L6-v2")
retrieved_nodes = query_expansion_rag.retrieve("What is the capital of France?")
print("Retrieved nodes:", retrieved_nodes)

This code implements query expansion within a graph-based RAG system to enhance retrieval performance. The QueryExpansionGraphRAG class inherits from AdvancedGraphRAG and introduces an expand_query method that takes a query and the desired number of expansions as input. First, this method retrieves the top three most relevant nodes based on the initial query using the base class’s retrieve method. It then iterates through these initial nodes, selecting a random neighbor for each and constructing an expanded query by appending the neighbor’s type (if available) and the neighbor’s ID to the original query. The retrieve method is overridden to first expand the input query using the expand_query method. It then retrieves results for each expanded query using the base class’s retrieve method, concatenates the results, removes duplicates while preserving order, and returns the top k unique nodes. This approach leverages the graph structure to explore related concepts and broaden the search scope, potentially capturing more relevant information than a direct query alone.

Query expansion is particularly useful when the initial query is too narrow or underspecified, resulting in low recall. In graph-based retrieval settings, this often occurs when the query does not explicitly mention related entities or concepts that are semantically or structurally linked in the graph. By incorporating neighboring nodes into the query formulation, the system can uncover relevant content that would otherwise be overlooked, making query expansion especially beneficial in exploratory search scenarios or domains with sparse or highly interconnected data.

Now that we’ve explored techniques to enhance retrieval, let’s shift our focus to improving the generation phase. We’ll now delve into the process of integrating graph information into LLM generation, examining how we can incorporate graph knowledge directly into the generation process to create more informed and coherent responses.Integrating graph information into LLM generation

To integrate graph information into LLM generation, we can create a prompt that incorporates the retrieved graph context:

from transformers import AutoModelForCausalLM, AutoTokenizer
class GenerativeGraphRAG(QueryExpansionGraphRAG):
def __init__(
self, kg: KnowledgeGraph, retriever_model:
str, generator_model: str
):
super().__init__(kg, retriever_model)
self.generator = \
AutoModelForCausalLM.from_pretrained(generator_model)
self.generator_tokenizer = \
AutoTokenizer.from_pretrained(generator_model)
def generate_response(
self, query: str, max_length: int = 100
) -> str:
retrieved_nodes = self.retrieve(query)
context = self.build_graph_context(retrieved_nodes)
prompt = f"Graph Context:\n{context}\n\nQuestion: {query}\nAnswer:"
inputs = self.generator_tokenizer(
prompt, return_tensors="pt"
)
outputs = self.generator.generate(
inputs, max_length=max_length
)
return self.generator_tokenizer.decode(
outputs[0], skip_special_tokens=True
)
def build_graph_context(self, nodes: List[str]) -> str:
context = []
for node in nodes:
context.append(f"Node: {node}")
context.append(f"Properties: {self.graph.nodes[node]}")
for neighbor, edge_data in self.graph[node].items():
context.append(
f" Related to {neighbor} by
{edge_data['relation']}")
return "\n".join(context)
# Example usage
generative_graph_rag = GenerativeGraphRAG(
kg, "all-MiniLM-L6-v2", "gpt2-medium"
)
response = generative_graph_rag.generate_response("What is the capital of France?")
print("Generated response:", response)

This code integrates an LLM for response generation within the graph-based RAG framework. The GenerativeGraphRAG class inherits from QueryExpansionGraphRAG and initializes with KnowledgeGraph, a retriever model name, and a generator model name. It loads a pre-trained causal language model and its corresponding tokenizer using transformers. The generate_response method orchestrates the entire process: first, it retrieves relevant nodes from the knowledge graph using the retrieve method inherited from the parent class. Then, it constructs a context string by calling build_graph_context, which formats the retrieved nodes, their properties, and their relationships to other nodes into a readable text. This context is then incorporated into a prompt alongside the original query, which is fed into the pre-trained language model. The language model generates a response based on the prompt, and the generated tokens are decoded back into a human-readable string, effectively leveraging the graph structure to inform the language model’s response generation. The build_graph_context method formats retrieved graph information into the prompt, including node IDs, properties, and relationships to neighbors, providing a structured representation of the relevant knowledge to the LLM.

Now that we’ve explored how to integrate graph information into the generation process, let’s consider the broader applications and potential uses of this approach.

Applications and use cases of graph RAG in LLMs

Section titled “Applications and use cases of graph RAG in LLMs”

Graph-based RAG can be particularly effective in various applications:

  • Question-answering over knowledge graphs
  • Personalized recommendation systems
  • Scientific literature analysis
  • Drug discovery and biomedical research
  • Social network analysis

Here’s an example of how graph RAG could be used for a recommendation system:

class RecommendationGraphRAG(GenerativeGraphRAG):
def get_recommendations(
self, user_id: str, num_recommendations: int = 5
) -> List[str]:
user_node = self.retrieve(f"User {user_id}", k=1)[0]
user_interests = self.graph.nodes[user_node].
get('interests', [])
potential_recommendations = set()
for interest in user_interests:
related_items = self.retrieve(interest, k=3)
potential_recommendations.update(related_items)
recommendations = list(
potential_recommendations - set(user_interests)
)[:num_recommendations]
return recommendations
def explain_recommendation(
self, user_id: str, item_id: str
) -> str:
query = f"Why would User {user_id} be interested in {item_id}?"
return self.generate_response(query)
# Example usage
recommendation_rag = RecommendationGraphRAG(
kg, "all-MiniLM-L6-v2", "gpt2-medium"
)
user_id = "12345"
recommendations = recommendation_rag.get_recommendations(user_id)
print(f"Recommendations for User {user_id}:", recommendations)
for item in recommendations[:2]:
explanation = recommendation_rag.explain_recommendation(user_id,
item)
print(f"Explanation for recommending {item}:", explanation)

This example demonstrates how graph RAG can be used to generate personalized recommendations and explain those recommendations using the graph structure.

Challenges and future directions in graph-based RAG

Section titled “Challenges and future directions in graph-based RAG”

Let’s consider some key challenges and future research directions in graph-based RAG:

  • Scalability to very large graphs
  • Handling dynamic and evolving graph structures
  • Incorporating uncertainty and probabilistic relationships
  • Improving the interpretability of graph-based retrievals and generations
  • Developing more sophisticated graph-aware language models

These are fascinating and complex research topics. In this chapter, we’ll focus on the scalability aspect of graph-based RAG. You are encouraged to read the research paper titled Graph Retrieval-Augmented Generation: A Survey at https://arxiv.org/abs/2408.08921 for more information on other challenges and research directions.

Real-world knowledge graphs can contain millions or even billions of nodes and edges. Querying and traversing such massive graphs can be computationally expensive, especially when incorporated into a real-time RAG pipeline. Furthermore, providing a huge subgraph as context to the LLM can exceed its context window limit and dilute the relevant information with noise.

Several factors contribute to this scalability bottleneck:

  • Graph traversal complexity: Finding relevant nodes and their connections within a large graph can be time consuming. Standard graph algorithms such as BFS or DFS can become inefficient as the graph grows.
  • Embedding storage and retrieval: Storing and retrieving node embeddings for a massive graph requires significant memory and computational resources. Computing similarity scores between the query embedding and all node embeddings becomes a bottleneck.
  • Context window limitations: LLMs have a limited context window, meaning they can only process a fixed amount of text at a time. A large graph context can easily exceed this limit, forcing truncation and potentially resulting in the loss of important information.
  • Noise in context: Including too much irrelevant information from the graph as context can confuse the LLM and degrade the quality of the generated response.

To address these scalability challenges, several strategies can be employed. One such strategy, which we will implement, is subgraph sampling. This involves extracting a smaller, more manageable subgraph from the overall knowledge graph that is most relevant to the user’s query. This reduces the computational cost of graph traversal and embedding retrieval, while also ensuring that the LLM receives a focused and informative context. Other techniques for improving scalability include the following:

  • Graph databases: Using specialized graph databases such as Neo4j or Amazon Neptune can significantly improve query performance and scalability compared to general-purpose databases
  • Approximate nearest neighbor (ANN) search: Using ANN algorithms for embedding retrieval can significantly speed up the search process by sacrificing some accuracy
  • Knowledge graph summarization: Condensing the knowledge graph into a smaller, more manageable representation while preserving its essential information
  • Hardware acceleration: Utilizing GPUs or specialized hardware accelerators can speed up graph computations and embedding operations
  • Context distillation: Techniques such as selective context injection or hierarchical retrieval can filter and prioritize the most relevant information for the LLM

Now, let’s proceed with implementing subgraph sampling to see how it helps address scalability concerns:

import networkx as nx
class ScalableGraphRAG(GenerativeGraphRAG):
def __init__(
self, kg: KnowledgeGraph, retriever_model: str,
generator_model: str, max_subgraph_size: int = 1000
):
super().__init__(kg, retriever_model, generator_model)
self.max_subgraph_size = max_subgraph_size
def retrieve(self, query: str, k: int = 5) -> List[str]:
initial_nodes = super().retrieve(query, k=k)
subgraph = self.sample_subgraph(initial_nodes)
return self.rank_nodes_in_subgraph(subgraph, query)[:k]
def sample_subgraph(self, seed_nodes: List[str]) -> nx.Graph:
subgraph = nx.Graph()
frontier = set(seed_nodes)
while len(subgraph) < self.max_subgraph_size and frontier:
node = frontier.pop()
if node not in subgraph:
subgraph.add_node(node, self.graph.nodes[node])
neighbors = list(self.graph.neighbors(node))
for neighbor in neighbors:
if len(subgraph) < self.max_subgraph_size:
subgraph.add_edge(
node, neighbor,
self.graph[node][neighbor]
)
frontier.add(neighbor)
else:
break
return subgraph
def rank_nodes_in_subgraph(
self, subgraph: nx.Graph, query: str
) -> List[str]:
query_embedding = self.model.encode(query)
node_scores = {}
for node in subgraph.nodes():
node_embedding = self.node_embeddings[node]
score = torch.cosine_similarity(
torch.tensor(query_embedding),
torch.tensor(node_embedding), dim=0
)
node_scores[node] = score
return sorted(node_scores, key=node_scores.get, reverse=True)
# Example usage
scalable_graph_rag = ScalableGraphRAG(
kg, "all-MiniLM-L6-v2", "gpt2-medium"
)
retrieved_nodes = scalable_graph_rag.retrieve("What is the capital of France?")
print("Retrieved nodes:", retrieved_nodes)

This code introduces a ScalableGraphRAG class, which is designed to address the scalability challenges of graph-based RAG systems by implementing a subgraph sampling technique. Inheriting from GenerativeGraphRAG, it incorporates a max_subgraph_size parameter to limit the size of the extracted subgraph.

The overridden retrieve method first identifies an initial set of relevant nodes using the base class’s retrieval mechanism. It then calls the sample_subgraph method to construct a subgraph centered around these initial nodes, limiting its growth to the specified max_subgraph_size.

The sample_subgraph method performs a breadth-first expansion from the seed nodes, adding nodes and edges to the subgraph until the size limit is reached, prioritizing nodes closer to the seed.

Subgraph sampling can be tuned by adjusting the max_subgraph_size parameter so that it balances context richness and computational efficiency. A smaller size results in faster processing but potentially misses crucial contextual information, while a larger size captures more context but increases computational cost. Additionally, the algorithm’s node selection criteria during subgraph expansion can be tuned – for example, prioritizing nodes with higher semantic similarity to the query or nodes with stronger connectivity to the seed nodes. Experimenting with these parameters is useful for optimizing the RAG system’s performance for specific applications and graph structures.

Finally, the rank_nodes_in_subgraph method calculates the relevance of each node within the subgraph to the query by computing the cosine similarity between the query embedding and the node’s pre-computed embedding. Then, it returns a ranked list of nodes based on their similarity scores, ensuring that only the most relevant nodes within the sampled subgraph are considered for context augmentation.

Graph-based RAG extends the capabilities of traditional RAG systems by leveraging the rich structure of knowledge graphs. By implementing the techniques and approaches discussed in this chapter, you can create more sophisticated LLM systems capable of reasoning over complex relationships and generating more contextually appropriate responses. In the next chapter, we will explore advanced RAG patterns for LLMs. This will build upon the graph-based techniques we’ve discussed here so that you can create even more powerful and flexible RAG systems.

Get This Book's PDF Version and Exclusive Extras