rag.ingest("document.txt"), the SDK transforms your raw text into a structured knowledge graph through a 9-step pipeline (steps 1-7 in sequence, steps 8 and 9 in parallel). Think of it as an assembly line: each step takes the output of the previous one, refines it, and passes it forward.
This document explains what each step does, why it exists, and how to tune it.
This pipeline is built for prose. A file ending in
.csv, .tsv, .psv or
.tab never reaches it: ingest() routes it by extension to the record path
described in Structured Ingestion, where you declare
what the columns mean and the graph is written deterministically, with no model
in the loop, into the same graph your documents live in. Pass
loader=TextLoader() to read such a file as prose instead.The Big Picture
Step-by-Step Explanation
Step 1 — Load
What it does: Reads raw text from a file, or takes the string you pass astext=.
How: The LoaderStrategy ABC handles this. When you pass no loader=, the SDK picks one from the file extension:
.pdfusesPdfLoader(PyMuPDF when it is installed viagraphrag-sdk[pdf-fast], otherwisepypdffromgraphrag-sdk[pdf]).mdusesMarkdownLoader, which also parses headers and paragraphs into structural elements (needsgraphrag-sdk[markdown]).csv,.tsv,.psvand.tableave this pipeline for the record path- Everything else uses
TextLoader(UTF-8 by default) - If you pass
text=directly, the loader step is skipped entirely
DocumentOutput containing the raw text and a DocumentInfo with the document’s id and path.
Document identity
Every document gets a stable id, which is the handleupdate() and delete_document() take later:
Pass
document_id= to choose your own. An id may not contain the reserved substring __pending__ (ValueError), and an id already bound to a different path is refused rather than silently rebound.
Because a text-mode id is derived from the text, two ingest(text=...) calls with identical text and no document_id address one document: the second call is a no-op. Pass a distinct document_id per call to store identical texts as separate documents.
Unchanged content is skipped
Before chunking, the pipeline hashes the loaded text (SHA-256). If the graph already holds a Document with this id and the samecontent_hash, ingest() returns at once: no chunking, NER, LLM calls or document writes (the indexes are still ensured and the graph’s config node is refreshed). The result says so:
RELATES or MENTIONED_IN edge the store dropped after a transient error, or a chunk left without an embedding all withhold it; result.metadata["incomplete_writes"] lists what came up short, and the next ingest() of the same file re-runs in full and repairs the document instead of skipping it. Deployments without an embedder are not penalised: no embedder means nothing was attempted, which still counts as complete.
To re-chunk or re-extract text that has not changed — after changing the ontology, chunker, extractor or model — use update(..., force=True). See Incremental Updates.
Code: LoaderStrategy.load() in ingestion/loaders/base.py
Step 2 — Chunk
What it does: Splits the document text into smaller pieces called chunks. Each chunk is small enough for the LLM to process, but large enough to contain meaningful context. How: The default isSentenceTokenCapChunking(max_tokens=384, overlap_sentences=2):
- Text is split at sentence endings (
.,!or?followed by whitespace), so a chunk never ends mid-sentence and never splits an entity name - Sentences are packed greedily into a chunk while its token count, measured with tiktoken’s
cl100k_baseencoding, stays withinmax_tokens - Consecutive chunks share
overlap_sentencessentences, so a fact that spans a boundary appears whole in at least one chunk - A single sentence longer than the cap becomes a chunk of its own
StructuralChunking, ContextualChunking and the documented CallableChunking example default to 384 tokens as well. StructuralChunking (in graphrag_sdk.ingestion.chunking_strategies) groups the headers and paragraphs MarkdownLoader parses, and update() hands it the same parsed structure that ingest() does.
Deterministic chunk ids
A chunk’s id is derived from the document id, its position and its text:chunk- followed by a SHA-256 prefix. Re-ingesting the same document therefore MERGEs onto the chunks already there instead of adding a second copy. ContextualChunking hashes the original chunk text, not the LLM-enriched one, so a differently worded summary does not mint a new id.
Because position is part of the id, inserting a paragraph into an edited document re-ids every chunk after it; only byte-identical files are a no-op. Use update() to replace an edited document cleanly. Chunks written by update() are keyed on its transient pending id, so the live and pending versions never share chunk nodes during the cutover.
Graphs written before chunk ids were deterministic hold random chunk ids. The first re-ingest of such a document adds one more copy of its chunk layer (it matches nothing); from the second re-ingest on it is stable.
TextChunks — a list of TextChunk objects, each with its id (uid), the text content, an index number and strategy metadata.
Code: ChunkingStrategy.chunk() in ingestion/chunking_strategies/base.py
Step 3 — Build Lexical Graph (Mandatory)
What it does: Creates the provenance backbone of the knowledge graph — this is how every answer traces back to its source document. Creates:- 1 Document node (with the file path and metadata)
- N Chunk nodes (one per text chunk, storing the chunk text and index)
- N PART_OF edges (Document → each Chunk)
- N-1 NEXT_CHUNK edges (Chunk → next Chunk, preserving reading order)
content_hash; the hash is added only at the end of a complete run (see Step 1).
Code: LexicalGraphWriter._build_lexical_graph() in ingestion/lexical_graph.py
Step 4 — Extract Entities & Relationships
What it does: The most important step — the text of each chunk is turned into structured knowledge: entities (people, places, organizations, etc.) and the relationships between them. How: The defaultGraphExtraction strategy uses a 2-step process:
-
Step 1 (NER): A pluggable entity extractor identifies entities in the text. Default:
GLiNERExtractor(a local transformer model, no API calls). Alternatives:LLMExtractor, the opt-inSpacyExtractor, or aCompositeExtractorthat runs several at once. -
Step 2 (Verify + Relationships): The LLM receives the pre-extracted entities and the original text. It verifies the entities (fixing errors, adding missed ones, re-typing or dropping low-confidence
Unknownones) and extracts the relationships between them, using the relation vocabulary it is given: required when the ontology declares relations, preferred otherwise.
GraphData containing nodes (entities), relationships, mention records, and a per-chunk report. A chunk whose extraction call fails does not fail the ingest: the report lands in result.metadata["extraction"] (chunks_attempted, chunks_skipped, failed_chunks, relation_failed_chunks, extraction_failed), and the content hash is withheld so the next ingest retries the document.
Code: ExtractionStrategy.extract() in ingestion/extraction_strategies/base.py
Step 4b — Quality Filter
What it does: Removes bad data that slipped through extraction — nodes with an empty id or label, and relationships whose endpoints don’t exist. Why: LLMs sometimes produce malformed output (empty entity names, references to entities that weren’t extracted). This step catches those before they reach the graph. Entity names have already passed the name checks described in Extraction by this point. Code:IngestionPipeline._filter_quality() in ingestion/pipeline.py
Step 5 — Prune Against Ontology
What it does: Filters extracted data to only keep entities and relationships that match the working ontology. How it works:- If the ontology declares entity types, only entities with those labels pass through, plus
Unknown(the NER model’s low-confidence band, which the step-2 LLM had the chance to re-type) - If the ontology declares relations, only edges whose
rel_typeis declared pass through, and a relation withpatternsalso keeps only edges whose(source label, target label)matches one. A pattern mismatch is logged as a WARNING naming the declared patterns and a sample of what was observed — usually an inverted direction - Relationships whose endpoints were pruned are also removed
GraphRAG created with no ontology on an empty graph seeds the 11 default entity types into its ontology, so entity pruning applies to those labels; with no declared relations, relationships are not pruned by type.
A table mapping’s
Link and a relationship-only table each declare a relation in
the ontology. Once a graph holds one, Ontology.relations is non-empty, so prose extraction is restricted to the
declared relations and this step prunes everything else. Declare the relations
your documents need alongside the ones your tables add.IngestionPipeline._prune() in ingestion/pipeline.py
What was pruned.
IngestionResult.metadata["pruned"] says what this step removed, so you can see what the ontology misses: entities (undeclared label → count), relations (undeclared type → count), pattern_mismatches (type → "Source->Target" → count), pattern_examples (type → "Source->Target" → one dropped fact, beside pattern_mismatches), dangling (relations whose endpoint was dropped) and unknown (entities kept as Unknown, which is how extraction stores a type outside the declared ones) and unknown_endpoints (type → count of relations dropped because an endpoint is an Unknown entity; no pattern can name Unknown, so these point at a missing entity type and are left out of pattern_mismatches). Only non-empty keys appear; {} means nothing was pruned.
Step 6 — Resolve Duplicates
What it does: Merges entities within the document that refer to the same real-world thing. When the extractor finds “Alice” in chunk 1 and ” alice ” in chunk 5, this step recognizes they’re the same entity and merges them. Default at ingest: ExactMatchResolution- Groups by
(normalized name, label)— the name lower-cased and trimmed. Same name but different labels stay separate (e.g., Person “Paris” vs Location “Paris”); the judge decides those atfinalize() - The survivor keeps every member’s description: each piece is kept once, joined with
" | "indescription(the one property search and prompts read), with the number of pieces indescription_piece_count.source_chunk_idsare unioned, and every relationship endpoint is re-pointed to the survivor before the write, so no edge is lost - No embeddings, no LLM calls; zero added cost
- Ingest is per document, so a resolver here can only compare one file’s entities with each other — the cross-document duplicates that matter (
Airbusin one file,Airbus SEin another) are handled once, atfinalize()
ExactMatchResolution(llm=None, cross_label_merge=False). Given an llm, ExactMatchResolution replaces the joined description with a single LLM-written summary once a group has force_summary_threshold (default 3) descriptions or more. Either way the descriptions live only in description (with description_piece_count); no separate descriptions list is written. cross_label_merge=True additionally puts same-name groups spanning two labels to the LLM, once they have cross_label_min_descriptions (default 3) descriptions between them.
Alternative: LLMVerifiedResolution
- Runs the same exact-match pass first, then embeds each surviving entity’s
name: description, finds candidate pairs by similarity (floorunified_threshold, default 0.65), merges same-label pairs at or abovehard_threshold(default 0.95) outright and asks the LLM about the rest (a cross-label pair always goes to the LLM, whatever it scores) - Pairs whose names are equal once digits are removed and different with them (
GPT-3/GPT-4,Q1 2024/Q2 2024) are never merged, without asking - Useful when the same entity is named inconsistently within a document (e.g., “Acme Corp” vs “Acme Corporation”). Costs embedding calls plus LLM calls for ambiguous pairs. See Strategies for its parameters
finalize(): incremental cross-document dedup
- Ingest writes a new entity without a name vector and marks nothing on it: having no vector is what makes it pending. A table row a re-sync renames or folds into another node loses its vector, so it is checked under its new name
finalize()checks only the pending entities, against the whole graph through FalkorDB indexes — it never reads every entity. It lists each one in a system record, then embeds its name once (stored ase.embedding, which vector search also uses), and the__Entity__vector index returns its nearest names (no LLM)- Same spelling once normalised, or a unique acronym of it, as a same-label table row → merged into the row by rule, no LLM (an extracted entity under a guessed label can also be adopted by a custom, non-built-in declared label of the same name). Same spelling between extracted mentions only, an acronym that spells several long forms, and the 5 nearest names at cosine ≥ 0.5, become candidate pairs; candidates form dense sets of ≤ 8
- The judge —
LLMJudgeby default, or anyDedupJudge— partitions each set once into same-referent groups, reading names, labels, descriptions, existing aliases and declared attribute values, and may name each merged group - Same → merge, by the same rules as every finalize merge: a table’s row survives a mention, every member’s description is kept as a piece of
description(joined with" | "; after dedup,finalize()summarises any entity holding more than 5 into one), other names kept inaliases, every edge moved in the same query that deletes the loser; the survivor gains every member’s label and takes the judge’s name for the group (a table row keeps its declared name). Groups chain: A = B and B = C become one node - Different → nothing is written; the pair is judged again only if a later new entity brings it into a set
- Every merge is decided before any is written, sealed in a merge plan, and applied one atomic query per merge — an interrupted
finalize()is finished by the next one - An entity’s check is cleared once it completes — except one that did not (a failed lookup or judge call, an answer that was not a clean partition, a group held for one, a merge an
update()changed), which stays pending; after 3 judged runs without a usable verdict it is reported indedup_unresolved— sofinalize()with nothing pending does no dedup work. Runfinalize(dedup_all=True)once to check every entity of a graph whose entity vectors were written outsidefinalize() - Two keyed rows of a table, and a mention two such rows could own, are never asked or grouped
- Every run has a judge:
finalize(judge=LLMJudge(other_llm))picks the model (gpt-4.1-class recommended),finalize(judge=MyJudge())plugs in your own; passresolver=LLMVerifiedResolution(...)toingest()to also resolve per document
ResolutionStrategy.resolve() in ingestion/resolution_strategies/base.py
Step 7 — Write to Graph
What it does: Persists all the extracted and resolved data into FalkorDB using batched Cypher queries. How:- Nodes are written via
UNWIND $batch AS item MERGE (n:Label {id: item.id}) SET n += item.properties - Relationships are written similarly, using label hints for efficient MATCH operations
- Batch size: 500 items per query
- Before writing into a label, the SDK creates range indexes on
idandentity_keyfor it; every label written gets them,Document,Chunkand__Entity__included. AMERGEcan only use an index on the label in its own pattern, so without these a large ingest grew quadratically; existing indexes are read once per store (GraphStoreinstance;delete_all()makes it read them again) and only missing ones are created - Writes that share a key within one batch are folded before sending, as if written one at a time: later properties win, an entity’s descriptions are joined, and a
RELATESedge’ssource_chunk_idsare combined. ARELATESedge’ssource_chunk_idson the graph is likewise a union across ingests, not the last writer’s list. An entity has no such list: itsMENTIONED_INedges say which chunks mention it - String values have control characters (other than tab, newline and carriage return) stripped,
Nonevalues are dropped, and dict values are stored as JSON strings - Entity nodes automatically get the
__Entity__secondary label (structural nodes like Chunk and Document do not).DocumentandChunkare reserved and refused as entity types
GraphStore.upsert_nodes() and GraphStore.upsert_relationships() in storage/graph_store.py
Steps 8 & 9 — Mentions + Index Chunks (Parallel)
These two steps run simultaneously since they’re independent. Both finish beforeingest() returns.
Step 8 — Write Mentions
What it does: CreatesMENTIONED_IN edges linking every entity to every chunk it was extracted from. These edges are critical for retrieval — they let the system find text passages for any entity.
Details: Uncapped — every entity-chunk pair gets an edge. Duplicates are deduplicated by (entity_id, chunk_id). Mentions are rewritten through the resolver’s merges first, so an entity merged in step 6 keeps its mentions on the survivor.
Step 9 — Index Chunks
What it does: Embeds each chunk’s text into a vector and stores it on the Chunk node. These embeddings power the vector similarity search during retrieval. How:- Batch-embed all chunk texts in one API call (
aembed_documents) - Write vectors to Chunk nodes via
SET c.embedding = vecf32(vector) - Falls back to sequential embedding if the batch call fails
incomplete_writes and withholds the content hash.
Code:
- Mentions:
LexicalGraphWriter._write_mentions()iningestion/lexical_graph.py - Chunk indexing:
VectorStore.index_chunks()instorage/vector_store.py
What ingest() Returns
ingest_sync() mirrors ingest() for synchronous code, tables included.
Post-Ingestion: finalize()
After all documents are ingested, callfinalize() to prepare the graph for querying. This is a separate step because some operations (like deduplication) work best when run globally across all documents, not per-document.
finalize() runs 6 steps in order:
finalize() after each document — call it once after all ingestion is complete: one run judges the whole batch’s new entities together, in fewer judge calls than a run per document.
Agentic Strategy Selection (auto=True)
By default ingest() uses fixed strategies (see Configuration Quick Reference). Pass auto=True to let a planner inspect a sample of each document and pick the chunker, entity-extraction backend, and resolver per document — the ingestion-side analogue of retrieval-side routing.
With
auto=True and no plan_limits, the default planner may pick only the cheap options, CHEAP_PLAN_LIMITS: sentence, fixed or structural chunking, gliner extraction and exact resolution, with at most 1,000 chunks per document. Pass plan_limits (the LLMIngestionPlanner limits: chunkers, extractors, resolvers, max_llm_pairs, tune_params, max_chunks) to allow more. It is merged over CHEAP_PLAN_LIMITS: a key you leave out keeps its cheap value, so max_chunks stays 1,000 and resolution stays exact unless you set them. A resolvers that allows llm_verified without a max_llm_pairs gets the resolver’s default budget (500), not the cheap 0. plan_limits and planner cannot be passed together: a planner you build carries its own limits.
The planner may also tune parameters inside the chosen strategy (e.g. max_tokens, the llm extractor’s threshold; GLiNER’s threshold is model-specific and is not tuned); all values are coerced and clamped to safe ranges, so the model can never produce an unsafe config. The ranges also bound cost: every chunk costs extraction LLM calls, so chunk sizes have floors (256 tokens for the sentence-based chunkers, with at most 4 sentences of overlap; 500 characters for fixed, with overlap at most a quarter of the size; a tuned sentence-based window repeats at most half its tokens, so it advances by at least half), and llm_verified’s hard_threshold stays at 0.8 or above, so candidate pairs between unified_threshold (0.65 by default) and hard_threshold are still checked by the LLM (pairs below unified_threshold are not candidates at all).
structural needs the document’s structure: .md files carry it, and Markdown-looking text (headings and lists in a .txt, or text mode) is parsed for it when the planner picks structural. Anything else falls back to sentence, and a note says so.
Safety guarantees:
- Explicit wins — any
chunker/extractor/resolveryou pass is kept as-is; the planner only fills the ones left unset. - Never silently broken — an empty/invalid plan or any planner error falls back to the default strategies (
sentence/gliner/exact), reproducing today’s behavior. The exceptions: aplannerthat is not an instance with an asyncplan()method raisesTypeErrorbefore anything is ingested, and an exhausted latency budget (LatencyBudgetExceededError, also when the planner call itself outlivesctx’s budget) is raised like everywhere else in the SDK. - Opt-in —
auto=Falseis the default; nothing changes unless you enable it. - Bounded blast radius on malicious content — the
LLMIngestionPlannerprompt includes a sample of the document itself, so adversarial document content could in principle try to steer the planner’s choice. The sample is quoted in a<document>block the prompt marks as data, with instructions inside it to be ignored, but the worst case is still one of the options you allow (cheap by default, below) with clamped parameters (seePARAM_SPECS) — never an arbitrary strategy or an out-of-range value.
LLMIngestionPlanner you build yourself may pick any option above unless you limit it, and the llm_verified pair budget it sets is capped at 500 (the resolver’s default; RuleBasedIngestionPlanner caps it at 500 too). To keep document text from choosing the strategies that add LLM calls, allow only the cheap options, pass tune_params=False so chunk sizes stay at their defaults, and set max_chunks to cap the chunks per document, which bounds its extraction calls (ingest(auto=True) does the first and last of these for you):
- The planner call.
LLMIngestionPlannermakes one LLM call per document;HeuristicIngestionPlannerandRuleBasedIngestionPlannermake none. - Extraction. Each chunk costs one extraction LLM call with
glinerand two with thellmbackend (entities, then verification and relations), before retries, so the chunk count sets the cost.max_chunksis a chunk limit, not a request ceiling:max_chunks=Nmeans at mostNextraction requests withglinerand about2Nwithllm, before retries. It refuses a document that splits into more thanNchunks before anything of it is written or extracted (ChunkBudgetExceededError, exported fromgraphrag_sdk, aChunkingError; in a batch, that file fails and the others go on). It wraps whatever chunker is used — the planner’s, yours or the default — andIngestionResult.metadata["plan"]["max_chunks"]records it. Forcontextualchunking the base chunks are counted before the per-chunk context calls, so a refused document costs none of them either. The default,None, sets no limit (ingest(auto=True)sets 1,000). - Resolution. A choice outside the allowed options falls back to the default (or the first allowed option) and is never built; the prompt only lists the allowed options.
max_llm_pairs=caps thellm_verifiedpair budget, also withtune_params=False, andmax_llm_pairs=0disallowsllm_verified. The cap applies per document: a plan’sLLMVerifiedResolutionruns its default unified stage, which compares every entity in one group and verifies up to that many candidate pairs, whatever their types. On top of it come a second ask for each confirmed match between two entity types, one check per name shared by entities of different types, and the description-summary calls. The separate 200-pair cross-label pass (cross_label_max_pairs) runs only withunified_stage=False, which plans do not set. Withresolvers=("exact",)resolution makes no LLM calls.
finalize() (embedding, and the LLM judge it uses for deduplication) or the questions you ask afterwards.
Three planners ship in the SDK:
RuleBasedIngestionPlanner is what the agent tools use for ingest(files=..., plan=[...]) (see Agentic retrieval). It takes the same chunkers / extractors / resolvers / max_llm_pairs / max_chunks limits; CHEAP_PLAN_LIMITS (exported from graphrag_sdk, read-only) holds the cheap ones, with max_chunks=1000 (about 380,000 tokens at the default chunk size).
What was chosen. With auto=True, each IngestionResult records the decision in metadata["plan"]:
slots says where each strategy came from: "caller" (you passed it), "planner" (built from the returned plan) or "default" (the planner raised or returned no plan, or that strategy could not be built — the other slots still follow the plan). LLMIngestionPlanner does not raise when its LLM call fails or its reply is not a plan: it returns the default plan, so the slots read "planner" and plan.reason starts with default:. Re-ingesting unchanged content skips the planner as well (a note says so). notes explains any fallback or adjustment, e.g. structural becoming sentence when the document has no structural elements (text mode). Planner failures are also logged at WARNING. Structured sources (.csv, .tsv, …) never run the planner: no chunker, extractor or resolver applies to them. A document that cannot be loaded is not planned either; its load error is raised as a LoaderError (a loader’s own IngestionError as is), so nothing was written.
Limitation: update() does not re-plan. The chosen strategies are recorded only in the ingest result’s metadata["plan"]; they are not stored on the Document. update() has no auto and re-ingests changed content with the strategies you pass (or the defaults), so a document ingested as structural + llm is re-chunked with sentence + gliner unless you pass those strategies to update() yourself. The update result’s metadata["plan_note"] says which strategies were defaulted, and after a planned ingest on the same GraphRAG it is also logged at WARNING.
Code: ingestion_planner.py · wired into GraphRAG.ingest() in api/main.py.
Configuration Quick Reference
Chunking
Extraction
Resolution
Performance Notes
- Slowest step: Extraction (Step 4) — involves LLM calls for every chunk. Expect ~2-5 seconds per chunk.
- Fastest step: Quality filter, prune, and resolve — all in-memory, sub-second.
- Unchanged documents: a re-ingest of byte-identical content makes no extraction or embedding calls for it; it still costs a few graph queries (the facade and the pipeline each look the document up, and the graph’s config node is rewritten).
- Parallelism: Steps 8-9 run in parallel. Step 1 NER uses a semaphore (default 12 concurrent chunks). One GLiNER model is loaded per model name and shared by every extractor in the process, and inference takes no lock, so concurrent ingests run NER in parallel without loading extra copies.