Knowledge graphs plus LLMs: how entity-aware retrieval works

Retrieval-augmented generation usually means one thing: split documents into chunks, embed them, find the chunks closest to the question and paste them into the prompt. It works surprisingly well for many questions. It struggles with others, especially questions that depend on how people, places and events relate to each other across a large body of text. Graph RAG is the family of techniques that adds a knowledge graph to the retrieval step so the model can follow those relationships instead of guessing them.
Builders have shown graph RAG on everything from product catalogs to long epics with tens of thousands of entities and their family ties, alliances and journeys. This article explains the idea without hype: what a graph adds, how a typical pipeline looks, how a fast LLM API fits into both building and querying the graph, and when the extra complexity is not worth it. Examples use the OpenAI request format, so they work with Groq's API or the keyless free-ai model on this site.
Frequently asked questions
What is the difference between graph RAG and normal RAG?
Normal RAG retrieves text chunks by similarity to the question. Graph RAG also stores entities and their relationships as nodes and edges, then retrieves a neighbourhood of the graph or a path through it. The model receives structured facts about connections in addition to, or instead of, raw passages.
Do I need a graph database like Neo4j?
Not at first. Small graphs fit in memory with a library such as NetworkX, or in a relational table of triples. A dedicated graph database becomes useful when the graph is large, changes often or must be queried with complex path patterns.
Can an LLM build the knowledge graph for me?
It can extract candidate entities and relations from text, and this is a common approach. The output needs validation, deduplication and a fixed schema, otherwise the graph fills up with near-duplicate nodes and invented links.
Is graph RAG more accurate than vector search?
For multi-hop questions about relationships, it often is, because the path is explicit. For simple lookup questions, plain vector retrieval is usually just as good and far cheaper to maintain. Many systems combine both.
What does an ontology mean in this context?
It is the agreed list of entity types and relation types the graph may contain, such as Person, Place, Event and relations like PARENT_OF or LOCATED_IN. A clear ontology keeps extraction consistent and makes queries predictable.
How large a model is needed for entity extraction?
Mid-sized open models handle extraction from clear prose reasonably well when given a strict schema and examples. Ambiguous or archaic text benefits from larger models. Test on a sample and measure precision before processing a whole corpus.
Does graph RAG reduce hallucinations?
It reduces one kind: the model inventing relationships it was not shown. It does not stop the model from misreading the facts you supply, and a wrong edge in the graph will be repeated confidently. Quality of the graph matters more than the technique itself.
Can I run graph RAG with a free API?
Yes for experiments and small corpora. Extraction calls add up quickly, so check daily limits. The keyless endpoint here allows 10,000 requests or 10 million tokens per IP per day, which is enough to prototype on a few hundred documents.
Where similarity search runs out of road
Vector retrieval finds passages that look like the question. If someone asks who the teacher of a character's brother was, the passage about the brother and the passage about his teacher may be in different chapters and neither looks much like the question. The retriever returns something vaguely related, and the model fills the gap with a plausible guess. This is the classic multi-hop failure.
Aggregation questions are another weak spot. Asking which cities appear in more than three battles requires counting across the whole corpus. No single chunk contains the answer, so top-k similarity cannot surface it. A graph, where battles are nodes linked to places, can answer with a simple query.
Multi-hop questions
Any question that chains two or more relations, such as a friend of a rival of a ruler, benefits from explicit edges. The graph turns a fuzzy search into a short path traversal.
Global questions
Questions about themes or totals across the corpus need summaries or counts. Graph approaches can precompute community summaries or answer counts directly, which chunk retrieval cannot do reliably.
The building blocks of a graph RAG system
Most implementations share the same parts, even when the tools differ. There is an ingestion pipeline that reads documents and extracts entities and relations. There is a store for the graph, and usually a vector index for the original text as well. At query time, a planner decides which entities the question mentions, a retriever pulls the relevant subgraph and passages, and the LLM writes the answer from that context.
Entity resolution is the hidden hard part
Long texts refer to the same person by title, nickname and full name. Without a resolver the graph splits one character into five nodes and every query misses edges. Aliases lists, fuzzy matching and a second LLM pass to confirm merges are typical fixes.
- Ontology: the allowed entity and relation types
- Extractor: an LLM prompt that outputs triples as JSON
- Resolver: merges duplicates such as different spellings of one name
- Graph store: in-memory, relational or a graph database
- Query planner: maps the question to entities and a traversal
- Answer step: the model writes from retrieved facts and passages

Using an LLM to extract triples
Extraction is a natural job for a fast, inexpensive model: it is repetitive, the input is supplied and the output can be validated against a schema. The prompt should list the allowed types, demand JSON only and tell the model to skip anything not stated in the text. The example below sends one passage to the keyless endpoint and parses the triples. Point the client at Groq or another provider by changing the base URL, key and model name.
Validate before you store
Drop triples with unknown relation types, empty names or subjects that do not appear in the passage. A quick string check that both entity names occur in the source text removes a large share of invented edges.
Keep provenance
Store the source document and passage ID on every edge. When an answer cites a relationship, you can show where it came from, and when an edge turns out wrong, you can find every other edge from the same faulty passage.
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.apifreegroqkey.com/v1", api_key="free")
SCHEMA = """Entity types: Person, Place, Event.
Relations: PARENT_OF, SIBLING_OF, ALLY_OF, ENEMY_OF, LOCATED_IN, TOOK_PART_IN.
Return JSON: {"triples": [[subject, relation, object], ...]}.
Only include facts stated in the passage. No commentary."""
def extract(passage):
r = client.chat.completions.create(
model="free-ai",
messages=[
{"role": "system", "content": SCHEMA},
{"role": "user", "content": passage},
],
temperature=0,
)
text = r.choices[0].message.content.strip()
start, end = text.find("{"), text.rfind("}")
data = json.loads(text[start:end + 1])
allowed = {"PARENT_OF", "SIBLING_OF", "ALLY_OF", "ENEMY_OF", "LOCATED_IN", "TOOK_PART_IN"}
return [t for t in data.get("triples", []) if len(t) == 3 and t[1] in allowed]
print(extract("Lena and Marko were siblings. Marko fought at the siege of Varna."))Querying: from question to subgraph
At query time, the system first identifies which entities the question mentions. A small LLM call can do this, or you can match against the entity names in the graph. Then it expands outward one or two hops, collects the edges and turns them into short sentences such as "Marko SIBLING_OF Lena". Those facts, plus a few supporting passages from the vector index, become the context for the answer.
Some systems let the model write the graph query itself, for example in Cypher for Neo4j. That is powerful but brittle: generated queries can be syntactically wrong or too broad. A safer start is a fixed set of traversal templates that the model chooses from, with parameters filled from the identified entities.
Limit the neighbourhood
Popular nodes can have thousands of edges. Cap the number of neighbours per hop and rank them by relevance to the question, otherwise the context overflows and the answer gets worse, not better.

Costs and effort compared with vector RAG
The honest trade-off is effort. A vector pipeline can be running in an afternoon. A graph pipeline needs an ontology, an extraction pass over the whole corpus, resolution of duplicates and ongoing maintenance as documents change. Extraction alone means at least one LLM call per chunk, often more if you run a verification pass.
With a free keyless endpoint the money cost of extraction is zero, but rate limits set the pace: at one request per second, a corpus of five thousand chunks takes well over an hour for a single pass. Groq's free plan has its own per-model limits; check its current limits page and plan the batch accordingly. For a large corpus, paid capacity with higher throughput is the practical route. Our article on flat subscriptions versus pay-per-token pricing helps estimate that bill.
Quality of the extractor matters most
A larger model generally extracts cleaner triples from difficult text. If precision on your sample is poor, it is cheaper to pay for a stronger model for the one-time extraction than to clean up a messy graph by hand later.
When plain vector search is enough
Many projects do not need a graph. If most questions are answered by a single passage, such as looking up a policy, a function's documentation or a product spec, similarity search with good chunking and a reranker will match graph RAG at a fraction of the effort. Graphs pay off when your users ask relational questions often and the relationships are stable enough to be worth modelling.
Try a reranker before a graph
A cross-encoder or LLM reranker that reorders the top twenty chunks fixes many retrieval misses that look like graph problems. It is a small change and should be tested before committing to a full ontology.
- Use vectors only: FAQ bots, documentation search, single-document Q&A
- Add a graph: genealogies, org charts, supply chains, case law citations, story universes
- Hybrid: start with vectors, add a graph for the entity types users ask about most

Using free-ai and Groq in the same pipeline
Because both services speak the OpenAI format, you can split work between them. Bulk extraction is a good fit for a cheap or free model, while the final answer, which users read, may deserve a stronger one. The keyless endpoint serves free-ai, an independent open-weight model of about 35B parameters; it is not a Groq model, and this site is not affiliated with Groq. Groq hosts a catalog of open models, some considerably larger, which you access with your own key from its console.
Never use keys copied from forums or shared lists for a pipeline like this. They belong to someone else, get revoked without warning and can leave the owner with charges. Create your own key or use a service that needs none. For routing logic between models, see our guide to sending simple tasks to cheaper models.
Keep the context window in mind
The keyless model accepts up to 32,000 tokens of context. Subgraph facts are compact, so this is usually plenty, but long supporting passages can fill it fast. Prefer facts plus two or three passages over ten passages.
A sensible first prototype
Start small and measurable. Pick fifty documents and twenty real questions that people ask. Build a vector baseline and record how many answers are correct. Then extract a graph for the same documents with a strict ontology, answer the same questions with graph context and compare. If graph answers are clearly better on relational questions, expand; if not, you have saved yourself weeks of maintenance.
Write the evaluation set first
Questions written after you see the system tend to favour it. Collect them from users or colleagues before building anything, include a few multi-hop ones and note the expected answer and source for each.
Inspect the graph visually
Load a sample into a graph viewer and look at it. Duplicate nodes, orphaned entities and suspicious super-connected nodes jump out immediately, and fixing them early is far cheaper than debugging bad answers later.

Send a request to the keyless free-ai endpoint from the home page and see how it fits your project, no sign-up needed.
Read also
- LangChain vs the Plain OpenAI SDK: Which Should Your LLM App Use?
- Can an LLM Predict Markets or Conflicts? The Limits of AI Forecasts
- Should Simple Tasks Go to a Smaller Model? LLM Routing Explained
- Can a Fast LLM API Power Game NPC Dialogue in Real Time?
- What Are Pruned LLMs, and Are Expert-Pruned Models Worth Using?