
The retrieval step of most of the RAG techniques depends on how well we can get relevant documents from Vector databases. Though most of the vector databases out there have efficient algorithms to calculate similarity, and even though we apply the best possible chunking strategies, ranking, and reranking techniques, the baseline RAG still suffers from answering questions that don’t match the source verbatim (i.e., the query should be semantically similar to the corpus provided) as well as it doesn’t have the ability to answer global questions or draw high-level conclusions. It can’t understand the deeper meaning that forms the relationships between the data entities. Other RAG techniques all concentrate on what else to do when the corpus is larger than the LLM’s context window, while advanced RAG systems include steps like pre and post-retrieval strategies and improving the given query using techniques like query expansion, etc. This is where Microsoft’s GraphRAG comes in.
In this article, we will see what Knowledge Graphs are, how they’ve evolved and why there is a need for them in RAG. We shall implement baseline RAG, GraphRAG, on the popular Sherlock Holmes novel The Hound of the Baskervilles by Sir Arthur Conan Doyle (Project Gutenberg License) and compare the results to see how each strategy performs and finally see some things to keep in mind as well as drawbacks of GraphRAG.
What is RAG
RAG or Retrieval Augmented Generation is a technique to enhance LLM responses by integrating relevant information from external sources, thus augmenting the model’s pre-trained, parametric memory without having the need to retrain the model itself

The following code demonstrates the baseline RAG implementation. We have an Embedding Model to convert our novel into vectors and store them in Azure Vector Search. This can be used to perform a Hybrid search to get semantically relevant top k (=3) results for any query. We pass the results along with the query to LLM to generate an appropriate response.
import os
from langchain_openai import AzureChatOpenAI, AzureOpenAIEmbeddings
from langchain_community.vectorstores.azuresearch import AzureSearch
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter
from langchain_core.prompts import ChatPromptTemplate
llm = AzureChatOpenAI(
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
openai_api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
)
embeddings = AzureOpenAIEmbeddings(
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
azure_deployment=os.getenv("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME"),
openai_api_version=os.getenv("AZURE_OPENAI_EMBEDDING_API_VERSION"),
)
vector_store = AzureSearch(
index_name="hound-of-baskervilles",
embedding_function=embeddings.embed_query,
azure_search_endpoint=os.getenv("AZURE_SEARCH_ENDPOINT"),
azure_search_key=os.getenv("AZURE_SEARCH_KEY"),
)
loader = TextLoader(book_path, encoding="utf-8")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1200, chunk_overlap=100)
docs = text_splitter.split_documents(documents)
vector_store.add_documents(documents=docs)
def retrieve(query):
docs = vector_store.hybrid_search(query=query, k=3)
context = "\n\n".join(doc.page_content for doc in docs)
print(context)
return context
rag_prompt = ChatPromptTemplate.from_messages([
("human", """
You are an assistant for question-answering tasks.
Only use the following pieces of context to answer the question.
If you don't know the answer or the answer can't be derived from the given context, just say that you don't know.
Use three sentences maximum and keep the answer concise.
Question: {question}
Context: {context}
Answer:"""),
])
def get_response(query):
messages = rag_prompt.invoke({"context": retrieve(query), "question": query})
response = llm.invoke(messages)
return response.content
get_response("Who is Sir Henry Baskerville?")Output:
Sir Henry Baskerville is the young baronet,
about thirty years old, who is the last of the Baskerville family.
He is the nephew of the late Sir Charles Baskerville.
He has recently arrived in England from Central America.If you need a quick refresher on RAG, do check out my article below.
RAG 101: IntroductionWhat, Why and How of Naive RAGmemsranga.com
Evolution of Search Engines
In any RAG approach, there are two steps: retrieval and generation. Generation is more or less the same for all approaches, where we use LLMs to summarise all the data we’ve got from the retrieval step. Retrieval is where most of the strategies differ. It is this step that is crucial because if we fail to provide proper documents to LLM, the response generated will also suffer. Hence, there is a direct correlation between how well the retrieval step performs and how the overall response of the RAG performs.
Retrieval is nothing but performing a search on our documents, so essentially, we are to build a search engine just for our private data. Hence, it is no surprise that retrieval strategies are also following similar trends as a traditional Search Engine.
- Keyword Search — First, there is keyword-based search, where we look for the exact occurrence of keywords in the data. Even Synonyms or variants of the keywords might not be recognized, so the search text should exactly match the words that are in the corpus. On top of them, inverted indexes came — a data structure consisting of a vocabulary of all the unique words in the dataset and the positions of the words within the documents where they appear. Additionally, the frequency of words might also be stored, retrieving the documents matching the query as fast as possible
- Best Matching Algorithms — These ranking algorithms use word frequency, document frequency, and length of the documents to compute a document score for each query. BM25, the most commonly known ranking function, addresses a few of the pain points that a simple Keyword search can’t, thereby improving the quality of documents retrieved
- Page Rank — Initially developed by Google, it assigns a score to each page based on incoming and outgoing links and the quality of the content. Though the context relevancy slightly suffered and the chronology of pages mattered a lot in ranking, it was the next best step in terms of sorting millions of documents. Document ranking and re-ranking are also common strategies used to enhance the documents retrieved in baseline RAG
- Semantic Search — Until this step, all the other functions/algorithms/techniques are solely focused on what words to search for rather than genuinely understanding user queries. Semantic search interprets the intent behind the user query and considers the words in relation to one another. All the Search indexers nowadays offer pure keyword, Semantic, and Hybrid searches, which, as the name suggests, consider keywords as well as the semantic meaning of the query
- Knowledge Graphs — Though Knowledge Graphs existed for many decades before their use in searching, knowingly or unknowingly, the evolution of search has always been about building a connected graph. Page Rank and Semantic Search also heavily depend on data structures that resemble some sort of graph. Even used in Google to enhance the search results, a Knowledge Graph is represented as a directed labeled graph with Nodes representing entities and Edges representing relationships between the Nodes. So when a user query matches a specific Node or Edge, the corresponding highly connected Nodes/Edges can also add up to give more context for the response
Hence, it is only right that the retriever step of RAG also evolves into the Knowledge Graph phase.
What is a Knowledge Graph
It is the semantic representation of a relationship between two entities. It gives unstructured data a structure so that machines can understand how entities relate to one another and which attributes they share. All the entities in a Knowledge Graph are represented as Nodes, and all the relationships between the nodes are represented as Edges. A Node can be any object — a person, place, organization, or event. An Edge can be any attribute or property by which two Nodes are related.
Building a Knowledge Graph using LLM
Traditionally, building knowledge graphs is a manual and time-consuming task. It requires great collaboration between subject matter experts and data scientists, who review tons of data and understand how each entity corresponds to one another. But with the advent of LLMs, we can automate almost all the steps of building a knowledge graph. As we’ve seen before, the most important components of any knowledge graph are Nodes. Let’s write a simple prompt to extract names, places, organizations, and events.
Extracting Entities and their relationships
Let’s try out with a basic prompting for Names, Places, Organizations, and Events. Eventually, we would like to give the user flexibility to mention their entity types because they are very specific to domains and will greatly enhance the extraction process.
import os
from langchain_openai import AzureChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
llm = AzureChatOpenAI(
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
openai_api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
)
entity_extraction_prompt = """
Given a document identify all entities from the text.
Entity types can be one of : Name, Place, Organization or Event
Document: {text}"""
def extract_entities(text):
prompt = ChatPromptTemplate.from_messages([entity_extraction_prompt])
messages = prompt.invoke({"text": text})
response = llm.invoke(messages)
return response.contentUsing the first paragraph of the novel as input, we get the following entities identified.
extract_entities("""
Mr. Sherlock Holmes, who was usually very late in the mornings,
save upon those not infrequent occasions when he was up all
night, was seated at the breakfast table. I stood upon the
hearth-rug and picked up the stick which our visitor had left
behind him the night before. It was a fine, thick piece of wood,
bulbous-headed, of the sort which is known as a "Penang lawyer."
Just under the head was a broad silver band nearly an inch
across. "To James Mortimer, M.R.C.S., from his friends of the
C.C.H.," was engraved upon it, with the date "1884." It was just
such a stick as the old-fashioned family practitioner used to
carry—dignified, solid, and reassuring.
""")Output:
Entities identified in the text:
- Name: Sherlock Holmes
- Name: James Mortimer
- Organization: M.R.C.S.
- Organization: C.C.H.
- Event: 1885Not bad for a basic prompt. Let’s also add entity_types as a variable and give a few shot examples with the specified structure to get the output in the desired format. This is exactly what is being used in GraphRAG. From GraphRAG code, the prompt for extracting entities and the relationship between them is done using a single prompt:
-Goal-
Given a text document that is potentially relevant to this activity and a list of entity types, identify all entities of those types from the text and all relationships among the identified entities.
-Steps-
1. Identify all entities. For each identified entity, extract the following information:
- entity_name: Name of the entity, capitalized
- entity_type: One of the following types: [{entity_types}]
- entity_description: Comprehensive description of the entity's attributes and activities
Format each entity as ("entity"{tuple_delimiter}<entity_name>{tuple_delimiter}<entity_type>{tuple_delimiter}<entity_description>)
2. From the entities identified in step 1, identify all pairs of (source_entity, target_entity) that are *clearly related* to each other.
For each pair of related entities, extract the following information:
- source_entity: name of the source entity, as identified in step 1
- target_entity: name of the target entity, as identified in step 1
- relationship_description: explanation as to why you think the source entity and the target entity are related to each other
- relationship_strength: a numeric score indicating strength of the relationship between the source entity and target entity
Format each relationship as ("relationship"{tuple_delimiter}<source_entity>{tuple_delimiter}<target_entity>{tuple_delimiter}<relationship_description>{tuple_delimiter}<relationship_strength>)
3. Return output in English as a single list of all the entities and relationships identified in steps 1 and 2. Use **{record_delimiter}** as the list delimiter.
4. When finished, output {completion_delimiter}
######################
-Examples-
######################
Example 1:
Entity_types: ORGANIZATION,PERSON
Text:
The Verdantis's Central Institution is scheduled to meet on Monday and Thursday, with the institution planning to release its latest policy decision on Thursday at 1:30 p.m. PDT, followed by a press conference where Central Institution Chair Martin Smith will take questions. Investors expect the Market Strategy Committee to hold its benchmark interest rate steady in a range of 3.5%-3.75%.
######################
Output:
("entity"{tuple_delimiter}CENTRAL INSTITUTION{tuple_delimiter}ORGANIZATION{tuple_delimiter}The Central Institution is the Federal Reserve of Verdantis, which is setting interest rates on Monday and Thursday)
{record_delimiter}
("entity"{tuple_delimiter}MARTIN SMITH{tuple_delimiter}PERSON{tuple_delimiter}Martin Smith is the chair of the Central Institution)
{record_delimiter}
("entity"{tuple_delimiter}MARKET STRATEGY COMMITTEE{tuple_delimiter}ORGANIZATION{tuple_delimiter}The Central Institution committee makes key decisions about interest rates and the growth of Verdantis's money supply)
{record_delimiter}
("relationship"{tuple_delimiter}MARTIN SMITH{tuple_delimiter}CENTRAL INSTITUTION{tuple_delimiter}Martin Smith is the Chair of the Central Institution and will answer questions at a press conference{tuple_delimiter}9)
{completion_delimiter}
######################
Example 2:
Entity_types: ORGANIZATION
Text:
TechGlobal's (TG) stock skyrocketed in its opening day on the Global Exchange Thursday. But IPO experts warn that the semiconductor corporation's debut on the public markets isn't indicative of how other newly listed companies may perform.
TechGlobal, a formerly public company, was taken private by Vision Holdings in 2014. The well-established chip designer says it powers 85% of premium smartphones.
######################
Output:
("entity"{tuple_delimiter}TECHGLOBAL{tuple_delimiter}ORGANIZATION{tuple_delimiter}TechGlobal is a stock now listed on the Global Exchange which powers 85% of premium smartphones)
{record_delimiter}
("entity"{tuple_delimiter}VISION HOLDINGS{tuple_delimiter}ORGANIZATION{tuple_delimiter}Vision Holdings is a firm that previously owned TechGlobal)
{record_delimiter}
("relationship"{tuple_delimiter}TECHGLOBAL{tuple_delimiter}VISION HOLDINGS{tuple_delimiter}Vision Holdings formerly owned TechGlobal from 2014 until present{tuple_delimiter}5)
{completion_delimiter}
######################
Example 3:
Entity_types: ORGANIZATION,GEO,PERSON
Text:
Five Aurelians jailed for 8 years in Firuzabad and widely regarded as hostages are on their way home to Aurelia.
The swap orchestrated by Quintara was finalized when $8bn of Firuzi funds were transferred to financial institutions in Krohaara, the capital of Quintara.
The exchange initiated in Firuzabad's capital, Tiruzia, led to the four men and one woman, who are also Firuzi nationals, boarding a chartered flight to Krohaara.
They were welcomed by senior Aurelian officials and are now on their way to Aurelia's capital, Cashion.
The Aurelians include 39-year-old businessman Samuel Namara, who has been held in Tiruzia's Alhamia Prison, as well as journalist Durke Bataglani, 59, and environmentalist Meggie Tazbah, 53, who also holds Bratinas nationality.
######################
Output:
("entity"{tuple_delimiter}FIRUZABAD{tuple_delimiter}GEO{tuple_delimiter}Firuzabad held Aurelians as hostages)
{record_delimiter}
("entity"{tuple_delimiter}AURELIA{tuple_delimiter}GEO{tuple_delimiter}Country seeking to release hostages)
{record_delimiter}
("entity"{tuple_delimiter}QUINTARA{tuple_delimiter}GEO{tuple_delimiter}Country that negotiated a swap of money in exchange for hostages)
{record_delimiter}
("entity"{tuple_delimiter}TIRUZIA{tuple_delimiter}GEO{tuple_delimiter}Capital of Firuzabad where the Aurelians were being held)
{record_delimiter}
("entity"{tuple_delimiter}KROHAARA{tuple_delimiter}GEO{tuple_delimiter}Capital city in Quintara)
{record_delimiter}
("entity"{tuple_delimiter}CASHION{tuple_delimiter}GEO{tuple_delimiter}Capital city in Aurelia)
{record_delimiter}
("entity"{tuple_delimiter}SAMUEL NAMARA{tuple_delimiter}PERSON{tuple_delimiter}Aurelian who spent time in Tiruzia's Alhamia Prison)
{record_delimiter}
("entity"{tuple_delimiter}ALHAMIA PRISON{tuple_delimiter}GEO{tuple_delimiter}Prison in Tiruzia)
{record_delimiter}
("entity"{tuple_delimiter}DURKE BATAGLANI{tuple_delimiter}PERSON{tuple_delimiter}Aurelian journalist who was held hostage)
{record_delimiter}
("entity"{tuple_delimiter}MEGGIE TAZBAH{tuple_delimiter}PERSON{tuple_delimiter}Bratinas national and environmentalist who was held hostage)
{record_delimiter}
("relationship"{tuple_delimiter}FIRUZABAD{tuple_delimiter}AURELIA{tuple_delimiter}Firuzabad negotiated a hostage exchange with Aurelia{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}QUINTARA{tuple_delimiter}AURELIA{tuple_delimiter}Quintara brokered the hostage exchange between Firuzabad and Aurelia{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}QUINTARA{tuple_delimiter}FIRUZABAD{tuple_delimiter}Quintara brokered the hostage exchange between Firuzabad and Aurelia{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}SAMUEL NAMARA{tuple_delimiter}ALHAMIA PRISON{tuple_delimiter}Samuel Namara was a prisoner at Alhamia prison{tuple_delimiter}8)
{record_delimiter}
("relationship"{tuple_delimiter}SAMUEL NAMARA{tuple_delimiter}MEGGIE TAZBAH{tuple_delimiter}Samuel Namara and Meggie Tazbah were exchanged in the same hostage release{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}SAMUEL NAMARA{tuple_delimiter}DURKE BATAGLANI{tuple_delimiter}Samuel Namara and Durke Bataglani were exchanged in the same hostage release{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}MEGGIE TAZBAH{tuple_delimiter}DURKE BATAGLANI{tuple_delimiter}Meggie Tazbah and Durke Bataglani were exchanged in the same hostage release{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}SAMUEL NAMARA{tuple_delimiter}FIRUZABAD{tuple_delimiter}Samuel Namara was a hostage in Firuzabad{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}MEGGIE TAZBAH{tuple_delimiter}FIRUZABAD{tuple_delimiter}Meggie Tazbah was a hostage in Firuzabad{tuple_delimiter}2)
{record_delimiter}
("relationship"{tuple_delimiter}DURKE BATAGLANI{tuple_delimiter}FIRUZABAD{tuple_delimiter}Durke Bataglani was a hostage in Firuzabad{tuple_delimiter}2)
{completion_delimiter}
######################
-Real Data-
######################
Entity_types: {entity_types}
Text: {input_text}
######################
Output:We get the output in the format we specified:
'("entity"<|>SHERLOCK HOLMES<|>PERSON<|>Mr. Sherlock Holmes is a detective who often stays up all night and was seated at the breakfast table in the morning)\n##\n("entity"<|>JAMES MORTIMER<|>PERSON<|>James Mortimer is the owner of the stick, engraved "To James Mortimer, M.R.C.S., from his friends of the C.C.H.," with the date "1884")\n##\n("entity"<|>C.C.H.<|>ORGANIZATION<|>C.C.H. is an organization whose friends gifted James Mortimer a stick)\n|COMPLETE|'Using GraphRAG
To demonstrate the true value of GraphRAG, let’s remove the book’s last two chapters and then try using baseline RAG and GraphRAG to answer questions. To get started with GraphRAG let’s use the CLI command to index the book into parquet files and then load into memory
import requests
import os
from dotenv import find_dotenv, load_dotenv
book_path = "graphrag/input/book.txt"
response = requests.get("https://www.gutenberg.org/cache/epub/2852/pg2852.txt")
if response.status_code == 200:
if not os.path.isdir("graphrag/input"):
os.mkdir("graphrag/input")
with open(book_path, "wb") as file:
file.write(response.content)
print("File saved successfully")
else:
print("Failed to fetch the file")
load_dotenv(find_dotenv())python -m graphrag index --root ./graphrag
Things to keep in mind
- Though the default prompts extract basic entities like Person, Places and Organisation, it is better to provide few-shot examples to extract other entities that are related to your own domain.
- Though GraphRAG paper claims that missing entities will be picked up just because there is a prompt to identify yes/no first, then suggest that MANY entities are missing, and hence longer context is justified, there is still no guarantee that the LLM will identify all the entities, especially the ones that are non-noun like or are made of multiple words.
- There is no explicit entity de-duplication step. Even though an entity is misunderstood and duplicated as a separate node, they lie relatively close to each other and are also tightly connected to each other. And since GraphRAG generates community summaries, LLMs will eventually understand this and generate proper summaries.
- In order to distribute information across the entire graph, GraphRAG randomizes the community reports (removes reports with 0 weights and orders others according to relevancy score). Only the first n reports that fit the context window are taken; the same reports (if they have the same score) are not guaranteed every time; though the conclusion of the question might be the same, the source report might be different altogether.
Drawbacks of GraphRAG
- Evident from the number of calls it makes to LLMs, the indexing cost is very high to get started with, and eventually, at query time as well, the cost is comparatively higher than baseline RAG.
- It is a common practice to apply filters on metadata while retrieving the documents to exclude the ones that we know are not relevant in the context of the user or inaccessible to the user. This acts as a layer of security that users can search through only the documents they have permission to access. However, since GraphRAG does local summaries, this can become more complex in terms of what entities, relationships, or community reports need RBAC and how to build graphs for different roles.
- Embeddings are always the same as long as the text doesn’t change. So, no matter how many times we generate embeddings of the same documents, baseline RAG is going to give the same answers (or at least the retriever will always give the same documents) for the same query. On the other hand, since GraphRAG depends on LLM’s outputs for entity recognition and relationship labeling as well as to generate community summaries and reports, there are high chances that regenerating the graph on the same corpus might give different answers for the same query.
Conclusion
GraphRAG represents a new strategy in RAG evolution that integrates knowledge graphs to bridge semantic gaps and unlock deeper insights. While it introduces higher computational costs, its ability to handle complex queries and derive nuanced relationships makes it a powerful tool for advanced RAG workflows. This post introduces the concepts behind the evolution of knowledge graph based RAG and shows use cases where understanding interconnected entities is critical.
🚀 Explore the code on GitHub and show your support with a ⭐ if you find it helpful! 🙌✨
All images are by the author unless stated otherwise