Articles / ragpythongenai-system-design
Build a GraphRAG pipeline in Python: when a graph beats vector search
When graph retrieval beats vector search, how entity extraction and community summaries work, a runnable networkx pipeline, and what indexing costs.
Vector retrieval finds chunks that look like the question. That works when one chunk holds the answer. It breaks when the answer is a chain of facts spread over several documents that never mention each other, or when the question is about the whole corpus ("what are the main risks across these 900 audit reports?"). A knowledge graph handles both cases: you store entities and the relationships between them, walk the edges for chain questions, and summarize clusters of the graph for corpus-wide ones.
This post builds a small GraphRAG pipeline in Python with networkx: extraction, entity resolution, a multi-hop walk, Leiden communities, a map-reduce global search, and a retrieval check against a vector-style baseline. The LLM is stubbed behind two tiny interfaces so the code runs offline, and the post marks where the real model call goes. The last part works out what indexing costs, because that bill is the usual reason teams drop GraphRAG.
If you want the comparison of GraphRAG against naive, hybrid, agentic and multimodal RAG, read RAG architectures compared. This post stays on how to build one and when it pays off.
When a graph beats vector retrieval#
Two kinds of question favour a graph.
Multi-hop questions. "Which rental fleets are exposed to the fire at our aluminium supplier?" needs four facts: the fire hit supplier S, S supplies manufacturer M, M builds product P, P is sold to fleet F. Each fact lives in a different document. The question shares words with the first two documents and almost none with the last two, so a top-k similarity search tends to return the fire report and the supplier contract and stop there. A graph walk from the supplier node follows the edges whatever the wording.
Global questions. "What themes run through this corpus?" has no single matching chunk. Top-k retrieval returns k random-looking chunks and the model generalizes from them. Microsoft's GraphRAG answers these from pre-written summaries of graph communities instead, so the answer draws on the whole corpus (Edge et al., 2024).
For everything else, a graph is overhead. A lookup like "what is the notice period in contract 4471?" sits in one chunk, and hybrid search with a reranker gets it faster and cheaper. A corpus that changes every hour is also a poor fit, since the graph has to be rebuilt or patched on each change.
A quick test before you build anything: take 30 real user questions and label each as single-chunk, multi-hop or global. If fewer than one in five are multi-hop or global, improve your vector pipeline first.
How GraphRAG builds its index#
The GraphRAG indexing dataflow has these stages, with defaults from the project's defaults.py (graphrag 3.3.0):
documents
| chunk into TextUnits (1,200 tokens, 100 overlap)
v
TextUnits ----------------------------------------------+
| LLM: extract entities + relationships per unit |
| (1 extra "gleaning" pass by default) |
v |
raw entities / relationships |
| merge by name+type; LLM summarizes repeated |
| descriptions (max 500 output tokens each) |
v |
knowledge graph |
| hierarchical Leiden (max cluster size 10) |
v |
communities at several levels |
| LLM writes one report per community |
| (8,000 tokens in, 2,000 out, at most) |
v v
community reports + embeddings of entities, TextUnits, reports
A few details from the docs that matter when you build your own version:
- Entities are merged when their title and type match, and relationships when source and target match. Each merge piles up descriptions, which a second LLM call condenses.
- Claim extraction exists but is off by default, because the config docs say its prompts "really need user tuning" (config reference).
- The
fastindexing method replaces LLM extraction with noun phrases from NLTK or spaCy and links entities that co-occur in a text unit. The methods page estimates graph extraction at roughly 75% of indexing cost and warns the fast graph is "quite a bit noisier".
At query time there are four modes (query overview). Local search mixes graph data around the entities in the question with raw text chunks. Global search runs map-reduce over the community reports. DRIFT adds community information to local search and fans out follow-up questions. Basic search is plain vector RAG, kept as a baseline.
The mini pipeline#
The corpus is seven fictional one-line documents about an e-scooter supply chain. Small enough to check every edge by eye, but it has a real four-hop chain and a second, unrelated chain.
import re
from collections import Counter
from dataclasses import dataclass
import networkx as nx
DOCS = {
"d1": "Kestrel Metals supplies aluminium housings to Orion Motors. Kestrel Metals operates a plant in Pune.",
"d2": "Orion Motors builds the Vega e-scooter. Orion Motors buys battery cells from Lumen Cells.",
"d3": "The Vega e-scooter is sold to CityRide. CityRide runs a rental fleet in Bengaluru.",
"d4": "A fire shut down the Pune plant of Kestrel Metals Ltd in March.",
"d5": "Lumen Cells supplies battery cells to Nova Bikes. Nova Bikes builds the Zip bike.",
"d6": "The Zip bike is sold to MetroWheels. MetroWheels runs a delivery fleet in Mumbai.",
"d7": "Harbor Logistics ships parts for Lumen Cells. Harbor Logistics operates a depot in Chennai.",
}
Note that d4 says "Kestrel Metals Ltd" while d1 says "Kestrel Metals". That mismatch is deliberate.
Extraction behind an interface#
Every triple keeps the id of the chunk it came from. Without that you cannot cite sources, and you cannot find the chunk that produced a bad edge.
@dataclass(frozen=True)
class Triple:
head: str
relation: str
tail: str
source: str # chunk id, kept for citations
class Extractor:
def extract(self, chunk_id: str, text: str) -> list[Triple]:
raise NotImplementedError
class StubExtractor(Extractor):
"""Pattern matcher standing in for an LLM.
Real version: send the chunk with a prompt that asks for JSON
[{"head", "relation", "tail"}], e.g. client.messages.create(model=..., messages=[...]),
then validate every item before it touches the graph.
"""
PATTERNS = [
(r"^(?:The )?(.+?) supplies (.+?) to (.+)$", lambda m: [(m[1], "supplies", m[3]), (m[1], "makes", m[2])]),
(r"^(?:The )?(.+?) (builds|buys|ships parts for) (?:the )?(.+?)(?: from (.+))?$",
lambda m: [(m[1], m[2], m[3])] + ([(m[4], "supplies", m[1])] if m[4] else [])),
(r"^(?:The )?(.+?) is sold to (.+)$", lambda m: [(m[1], "sold_to", m[2])]),
(r"^(?:The )?(.+?) (?:operates|runs) an? (.+?) in (.+)$", lambda m: [(m[1], "located_in", m[3])]),
(r"^A fire shut down the (.+?) plant of (.+?) in .+$", lambda m: [("Fire", "disrupted", m[2])]),
]
def extract(self, chunk_id, text):
out = []
for sentence in re.split(r"(?<=\.)\s+", text.strip()):
s = sentence.rstrip(".")
for pattern, build in self.PATTERNS:
m = re.match(pattern, s)
if m:
out += [Triple(h.strip(), r.replace(" ", "_"), t.strip(), chunk_id) for h, r, t in build(m)]
break
return out
The regexes are there only so the example runs without a key. A real extractor sends each chunk to a model with a fixed list of entity types and a strict output format. For production, validate every item against a schema and drop relations whose head or tail is not in the chunk text. Models invent plausible edges, and an invented edge in a graph is worse than a wrong sentence in a chunk, because every walk through that node inherits it.
Entity resolution, then the graph#
SUFFIXES = re.compile(r"\s+(ltd|limited|inc|pvt)\.?$", re.I)
def canonical(name: str) -> str:
return SUFFIXES.sub("", name.strip())
def build_graph(triples: list[Triple]) -> nx.MultiDiGraph:
g = nx.MultiDiGraph()
for t in triples:
h, tl = canonical(t.head), canonical(t.tail)
g.add_edge(h, tl, relation=t.relation, source=t.source)
return g
A MultiDiGraph keeps direction and allows two different relations between the same pair. A plain DiGraph would silently overwrite the first relation with the second.
Resolution here is a suffix strip. Without it, "Kestrel Metals Ltd" becomes its own node, the fire attaches to that node, and the chain to CityRide breaks at the first hop. Real corpora need more: abbreviations, transliterations, two different people with the same name. Merge too eagerly and you join entities that should stay apart, which is the harder bug to spot. Log every merge so a person can review the list.
Local search: a bounded walk#
def link_entities(question: str, g: nx.MultiDiGraph) -> list[str]:
q = question.lower()
return [n for n in g.nodes if n.lower() in q]
def local_context(g: nx.MultiDiGraph, seeds: list[str], hops: int = 3, max_facts: int = 12, direction="both"):
"""direction='out' follows edges downstream only; 'both' ignores edge direction."""
walk = g if direction == "out" else g.to_undirected(as_view=True)
dist = {}
for s in seeds:
for node, d in nx.single_source_shortest_path_length(walk, s, cutoff=hops).items():
dist[node] = min(d, dist.get(node, d))
facts = []
for h, t, data in g.edges(data=True):
if h in dist and t in dist:
facts.append((min(dist[h], dist[t]), f"{h} {data['relation']} {t} [{data['source']}]"))
facts.sort()
return [f for _, f in facts[:max_facts]]
Entity linking by substring match is the crudest option. Production systems embed entity names and descriptions and match the question against them, which is what GraphRAG's local search does with its entity description embeddings.
Facts are sorted by hop distance and capped, so the closest evidence survives when the context budget runs out. The direction flag is there because the run below shows why it matters.
Communities and global search#
class Summarizer:
def summarize(self, nodes: list[str], facts: list[str]) -> str:
raise NotImplementedError
class StubSummarizer(Summarizer):
"""Real version: one LLM call per community with its facts, asking for a titled report."""
def summarize(self, nodes, facts):
return f"Community of {len(nodes)} entities: {', '.join(nodes)}. Facts: " + "; ".join(facts)
def community_reports(g, summarizer, seed=7):
und = nx.Graph(g.to_undirected())
comms = nx.community.leiden_communities(und, metric="modularity", seed=seed)
reports = []
for c in sorted(comms, key=lambda c: (-len(c), min(c))):
nodes = sorted(c, key=lambda n: (-und.degree(n), n))
facts = [f"{h} {d['relation']} {t}" for h, t, d in g.edges(data=True) if h in c and t in c]
reports.append(summarizer.summarize(nodes, facts))
return reports
def global_search(question, reports, top=3):
"""Map: score every report against the question. Reduce: keep the best few for the answer.
Real version: the map step is an LLM call per batch of reports that returns key points
with a 0-100 helpfulness score; the reduce step is one LLM call over the top points."""
words = set(re.findall(r"[a-z]+", question.lower())) - {"the", "a", "of", "which", "what", "are", "is", "in", "this"}
scored = sorted(((sum(w in r.lower() for w in words), r) for r in reports), key=lambda x: -x[0])
return [(score, r) for score, r in scored[:top] if score > 0]
networkx 3.7 ships leiden_communities. Its default metric is the Constant Potts Model with resolution 1.0, which on this graph returns 16 single-node communities, one per node. Pass metric="modularity" to get clusters you can summarize. GraphRAG uses a hierarchical Leiden instead, splitting large communities recursively until each fits under max_cluster_size, so it has reports at several levels of detail. Leiden itself is from Traag et al., 2019.
The vector-style baseline#
To compare like with like, the baseline uses bag-of-words cosine over the same chunks. It stands in for embedding similarity; it is weaker than a real embedding model, so treat its numbers as a lower bound.
def bow(text):
return Counter(re.findall(r"[a-z0-9-]+", text.lower()))
def cosine(a, b):
num = sum(a[k] * b[k] for k in a)
den = (sum(v * v for v in a.values()) ** 0.5) * (sum(v * v for v in b.values()) ** 0.5)
return num / den if den else 0.0
def vector_top_k(question, k=2):
q = bow(question)
return sorted(DOCS, key=lambda d: -cosine(q, bow(DOCS[d])))[:k]
Running it#
The driver builds the graph, asks the multi-hop question, writes community reports, runs one global question, then scores retrieval on three questions with hand-labelled gold chunks:
if __name__ == "__main__":
extractor = StubExtractor()
triples = [t for cid, text in DOCS.items() for t in extractor.extract(cid, text)]
g = build_graph(triples)
print(f"{len(triples)} triples -> {g.number_of_nodes()} nodes, {g.number_of_edges()} edges")
raw = {t.head for t in triples} | {t.tail for t in triples}
print("Merged by resolution:", sorted(raw - set(g.nodes)))
q = "Which rental or delivery fleets are exposed to the fire at Kestrel Metals?"
print("\nQ:", q)
print("Vector top-2 chunks:", vector_top_k(q))
seeds = link_entities(q, g)
print("Linked entities:", seeds)
both = local_context(g, seeds, hops=4)
print(f"Undirected 4-hop walk: {len(both)} facts, includes Lumen Cells: {any('Lumen' in f for f in both)}")
for fact in local_context(g, seeds, hops=4, direction="out"):
print(" ", fact)
print("\nCommunity reports:")
reports = community_reports(g, StubSummarizer())
for r in reports:
print(" -", r[:110] + ("..." if len(r) > 110 else ""))
gq = "What are the main supply chains: who supplies whom, and who builds what?"
print("\nGlobal Q:", gq)
for score, r in global_search(gq, reports):
print(f" score {score} ->", r[:70] + "...")
# gold = chunks a correct answer must rest on
evalset = [
("Which rental or delivery fleets are exposed to the fire at Kestrel Metals?", {"d4", "d1", "d2", "d3"}, 4, "out"),
("Who ships parts for the cell supplier of Nova Bikes?", {"d5", "d7"}, 2, "both"),
("Which city is MetroWheels based in?", {"d6"}, 1, "both"),
]
print("\nChunk recall (vector k=3 vs graph walk):")
for question, gold, hops, direction in evalset:
vec = set(vector_top_k(question, k=3))
facts = local_context(g, link_entities(question, g), hops=hops, direction=direction)
graph = {f.rsplit("[", 1)[1].rstrip("]") for f in facts}
print(f" vector {len(vec & gold)}/{len(gold)} graph {len(graph & gold)}/{len(gold)} "
f"(graph cited {len(graph)} chunks) {question}")
Output with Python 3.15 and networkx 3.7 (identical across repeated runs):
16 triples -> 16 nodes, 16 edges
Merged by resolution: ['Kestrel Metals Ltd']
Q: Which rental or delivery fleets are exposed to the fire at Kestrel Metals?
Vector top-2 chunks: ['d1', 'd4']
Linked entities: ['Kestrel Metals', 'Fire']
Undirected 4-hop walk: 12 facts, includes Lumen Cells: True
Fire disrupted Kestrel Metals [d4]
Kestrel Metals located_in Pune [d1]
Kestrel Metals makes aluminium housings [d1]
Kestrel Metals supplies Orion Motors [d1]
Orion Motors builds Vega e-scooter [d2]
Orion Motors buys battery cells [d2]
Vega e-scooter sold_to CityRide [d3]
CityRide located_in Bengaluru [d3]
Community reports:
- Community of 5 entities: Lumen Cells, Orion Motors, Harbor Logistics, battery cells, Chennai. Facts: Orion Mot...
- Community of 4 entities: Kestrel Metals, Fire, Pune, aluminium housings. Facts: Kestrel Metals makes aluminium...
- Community of 4 entities: MetroWheels, Nova Bikes, Zip bike, Mumbai. Facts: Nova Bikes builds Zip bike; Zip bik...
- Community of 3 entities: CityRide, Vega e-scooter, Bengaluru. Facts: Vega e-scooter sold_to CityRide; CityRide...
Global Q: What are the main supply chains: who supplies whom, and who builds what?
score 1 -> Community of 5 entities: Lumen Cells, Orion Motors, Harbor Logistics, ...
score 1 -> Community of 4 entities: MetroWheels, Nova Bikes, Zip bike, Mumbai. Fa...
Chunk recall (vector k=3 vs graph walk):
vector 3/4 graph 4/4 (graph cited 4 chunks) Which rental or delivery fleets are exposed to the fire at Kestrel Metals?
vector 2/2 graph 2/2 (graph cited 4 chunks) Who ships parts for the cell supplier of Nova Bikes?
vector 1/1 graph 1/1 (graph cited 1 chunks) Which city is MetroWheels based in?
What the run shows:
- Resolution held the chain together. "Kestrel Metals Ltd" was folded into "Kestrel Metals", so the fire edge and the supply edge share a node.
- Vector top-2 found the fire and the contract and nothing downstream. The documents naming Orion's product and CityRide share almost no words with the question.
- Direction matters. The undirected walk at four hops returned 12 facts and wandered upstream into Lumen Cells, a battery supplier that has nothing to do with a fire at the aluminium supplier. Following outgoing edges only gave eight facts that end at CityRide in Bengaluru, which is the answer. Exposure questions are downstream; "who does X depend on" questions are upstream. Pick per question type, or let an LLM pick the direction as part of query planning.
- The walk still carries noise. "Orion Motors buys battery cells" is one hop from the chain and irrelevant. In a real graph a hub node like a big customer has hundreds of edges, so cap facts per node, not only in total.
- The community reports split the corpus along its real seams. The Kestrel cluster and the CityRide cluster are separate, so the cross-community edge "Kestrel Metals supplies Orion Motors" appears in no report. Global search answers "what themes exist", not "what links to what".
- The global search stub is the weakest part. Keyword overlap ranked only two of four reports. The real map step asks a model to rate each report's usefulness for the question, which is why global search is the expensive mode.
- On the single-hop question the graph adds nothing. Both methods found
d6. That row is your reminder to route lookups to plain retrieval.
On seven documents the vector baseline scores 3/4 on the chain question because there are only seven chunks to choose from. On 50,000 chunks the downstream documents fall far below the top-k cut. Run this check on your own corpus before deciding; the measurement method (recall against hand-labelled gold chunks, retrieval scored apart from generation) is in Evaluate a RAG app in Python.
Replacing the stubs#
To go from this toy to a working system:
- Extractor. Send each chunk with a prompt listing your entity types (for a supply chain: company, plant, product, part, fleet, city) and ask for JSON. Validate with a schema, reject items whose names do not appear in the chunk, and retry once on a parse failure. Use temperature 0 or the lowest your model allows so re-indexing is repeatable.
- Resolution. Start with normalization rules, then embed entity names and send near-duplicates above a similarity threshold to a model or a person for a merge decision.
- Summarizer. One call per community, with the community's entities, relations and a sample of source chunks, asking for a title, a summary and the key findings with chunk ids.
- Answer step. Put the retrieved facts and their source chunks in the prompt and require citations by chunk id, so a reader can check each hop.
If you would rather not build this yourself, pip install graphrag gives you all of the above with tested prompts. Write your own when you need control over the schema, the graph store or the cost.
What indexing costs#
Indexing is where the money goes, so price it before you commit. The estimate below is for a 2-million-token corpus (about 1,000 reports of 2,000 tokens each) with GraphRAG's default chunking and one gleaning pass. The two prompt sizes were counted with tiktoken on the current GraphRAG prompt files. Every value marked "assumed" is a guess; replace it with numbers you measure on 50 of your own chunks.
import math
CORPUS_TOKENS = 2_000_000 # e.g. 1,000 reports of ~2,000 tokens
CHUNK, OVERLAP = 1200, 100 # GraphRAG defaults (ChunkingDefaults)
EXTRACT_PROMPT = 1_850 # extract_graph prompt template, counted with tiktoken o200k_base
REPORT_PROMPT = 1_950 # community_report prompt template, same method
GLEANINGS = 1 # ExtractGraphDefaults.max_gleanings
OUT_EXTRACT = 800 # assumed tokens emitted per first extraction
OUT_GLEAN = 400 # assumed tokens emitted per gleaning pass
SUMMARY_CALLS, SUMMARY_IN, SUMMARY_OUT = 4_000, 800, 150 # assumed: entities/relations with >1 description
REPORTS, REPORT_IN, REPORT_OUT = 1_500, 6_000, 1_500 # assumed; caps are 8,000 in / 2,000 out
PRICES = { # USD per million tokens (input, output), Claude API list price
"Claude Haiku 4.5": (1.0, 5.0),
"Claude Sonnet 4.6": (3.0, 15.0),
}
chunks = math.ceil((CORPUS_TOKENS - OVERLAP) / (CHUNK - OVERLAP))
first_in = EXTRACT_PROMPT + CHUNK
glean_in = first_in + OUT_EXTRACT + 50 # whole conversation is resent
stages = {
"extract": (chunks * first_in, chunks * OUT_EXTRACT),
"glean": (chunks * glean_in * GLEANINGS, chunks * OUT_GLEAN * GLEANINGS),
"summarize": (SUMMARY_CALLS * SUMMARY_IN, SUMMARY_CALLS * SUMMARY_OUT),
"reports": (REPORTS * (REPORT_PROMPT + REPORT_IN), REPORTS * REPORT_OUT),
}
print(f"chunks: {chunks:,} LLM calls: {chunks * (1 + GLEANINGS) + SUMMARY_CALLS + REPORTS:,}")
tot_in = sum(i for i, _ in stages.values())
tot_out = sum(o for _, o in stages.values())
for name, (i, o) in stages.items():
print(f"{name:<10} in {i/1e6:6.2f}M out {o/1e6:5.2f}M")
print(f"{'total':<10} in {tot_in/1e6:6.2f}M out {tot_out/1e6:5.2f}M")
ex = sum(stages[s][0] + stages[s][1] for s in ("extract", "glean"))
print(f"graph extraction share of tokens: {ex / (tot_in + tot_out):.0%}")
for model, (pi, po) in PRICES.items():
cost = tot_in / 1e6 * pi + tot_out / 1e6 * po
print(f"{model:<18} ${cost:7.2f} batch API (-50%) ${cost/2:7.2f}")
chunks: 1,819 LLM calls: 9,138
extract in 5.55M out 1.46M
glean in 7.09M out 0.73M
summarize in 3.20M out 0.60M
reports in 11.93M out 2.25M
total in 27.77M out 5.03M
graph extraction share of tokens: 45%
Claude Haiku 4.5 $ 52.93 batch API (-50%) $ 26.47
Claude Sonnet 4.6 $ 158.79 batch API (-50%) $ 79.40
Prices are the Claude API list prices on the pricing page as of 22 Nov 2026: Haiku 4.5 at $1 in and $5 out per million tokens, Sonnet 4.6 at $3 and $15, and half that through the Batch API.
How to read it:
- 2 million corpus tokens became about 33 million billed tokens, roughly 16 times the corpus. A vector index over the same corpus needs one embedding pass over 2 million tokens and no generation calls.
- The gleaning pass costs more input than the first pass because the whole conversation, including the first answer, is resent. Setting
max_gleanings: 0removes about a quarter of the input tokens. Measure the recall you lose on your labelled set before turning it off. - These assumptions put extraction at 45% of tokens, against the roughly 75% of cost that the GraphRAG methods page estimates. The gap means the report numbers here are probably high (fewer communities, or shorter inputs, in practice). Either way, extraction and reports are the two knobs worth measuring first.
- Re-indexing repeats the bill. If the corpus grows 10% a month and you rebuild from scratch, you pay this every month. GraphRAG has an incremental
graphrag updatecommand (CLI reference); check what it recomputes on your data before you rely on it. - Global search has its own cost per question. The map step reads every community report at the chosen level. If that level has 400 reports of 2,000 tokens, one global question reads 800,000 input tokens before any output, about $0.80 on Haiku 4.5. Cache answers to recurring global questions.
The fast method cuts the extraction stage to NLP and keeps LLM calls for reports only, which suits corpora where global questions matter more than precise relations.
Failure modes to test for#
- Bad merges and missed merges. Sample 50 merged entities and 50 near-duplicate pairs that were not merged, and count errors by hand.
- Invented edges. Sample 50 relationships and check each against its source chunk. Keep the chunk id on every edge or this check is impossible.
- Hub explosion. One node with thousands of edges (a country, a big customer, "the company") floods every walk that touches it. Cap edges per node in the walk, or drop generic entities at extraction time.
- Wrong walk direction or depth. Too shallow misses the answer; too deep pulls in unrelated clusters, as the undirected walk did above. Tune hops on labelled multi-hop questions.
- Stale graph. New documents are invisible until indexed. Show the index date next to answers.
What to do next#
Label 30 real questions by type and run the recall check from this post on your own corpus, with your current vector retriever as the baseline. Build the graph only if multi-hop or global questions are a real share of traffic and the baseline misses them. Then keep both: route lookups to vector or hybrid search and send chain and corpus-wide questions to the graph.
Sources#
- Edge et al., From Local to Global: A Graph RAG Approach to Query-Focused Summarization, 2024.
- Microsoft, GraphRAG repository and
defaults.py: chunk size 1,200, overlap 100,max_gleanings1,max_cluster_size10, report caps 8,000 in and 2,000 out; gleaning loop ingraph_extractor.py; prompt files inprompts/index. Checked 22 Nov 2026 against graphrag 3.3.0 on PyPI. - Microsoft, GraphRAG docs: indexing dataflow, indexing methods, query overview, local search, CLI, configuration reference.
- Traag, Waltman and van Eck, From Louvain to Leiden: guaranteeing well-connected communities, Scientific Reports, 2019.
- NetworkX,
leiden_communitiesandMultiDiGraph, version 3.7. - Anthropic, Pricing, checked 22 Nov 2026.
- OpenAI, tiktoken, used to count prompt tokens.