graphrag_sdk. Some newer names (the ingestion planners, path routers, relationship mappings and agent toolkit) are documented on their own pages: Ingestion, Retrieval, Structured Ingestion and Agentic Retrieval. Everything listed in the package’s __all__ is importable from the top level (from graphrag_sdk import ...); a few supporting classes live in submodules, and their import path is given where they appear. graphrag_sdk.__version__ holds the package version string.
Table of Contents
- GraphRAG (Facade)
- Connection
- Providers
- Data Models
- Ontology
- Ingestion Strategies
- Ingestion Pipeline
- Structured Ingestion
- Deduplication Judges
- Ontology Evolution and Discovery Types
- Retrieval Strategies
- Reranking Strategies
- Storage
- Context
- Exceptions
- Deprecated and Removed Names
GraphRAG (Facade)
The main entry point. Three primary operations:ingest(), retrieve(), and completion(). Tables go through the same ingest(); see Structured Ingestion.
Constructor
Public attributes:
llm, embedder, ontology. The storage layer is private (_graph_store, _vector_store); use get_statistics(), query() and delete_all() instead of reaching into it. rag.schema still works as a deprecated alias of rag.ontology.
GraphRAG is an async context manager (async with GraphRAG(...) as rag:), which closes the connection on exit. It is single-entry: use one async with block per instance. await rag.close() closes the connection explicitly.
Every FalkorDB call goes through a connection that checks the server version once, before its first query, and raises FalkorDBVersionError for a server older than 4.20. See Configuration.
ingest()
source, one path or a list) and text mode (text). When a list of sources is provided, documents are ingested in parallel with bounded concurrency; one bad source does not abort the batch.
A .csv, .tsv, .psv or .tab is read as records, not prose: its mapping is looked up in the ontology by filename (see Structured Ingestion), no model extracts from it, and a StructuredIngestionResult is returned (a RelationshipIngestionResult for a relationship-only table). A table may not appear in a list (each is written on its own, so ValueError is raised before anything is ingested), and chunker, extractor and resolver are rejected for one; identity across sources is judged by finalize(). Pass loader=TextLoader() to read a CSV as prose anyway.
Re-ingesting a document whose text is byte-identical to what the graph already holds is a no-op: the call returns before chunking with chunks_indexed=0 and metadata["skipped_unchanged"] = True, and makes no extraction or embedding calls for the document (a new GraphRAG instance still sends its one-time embedder dimension probe). Chunk ids are derived from the document id, position and text, so re-ingesting the same file never duplicates its chunks. The content hash is recorded only when every write completed; if anything came up short, metadata["incomplete_writes"] lists it and the next ingest repairs the document instead of skipping it. To re-extract unchanged content (after changing the ontology, chunker, extractor or model), use update(..., force=True).
Returns:
IngestionResult for a single document, StructuredIngestionResult for an entity table, RelationshipIngestionResult for a relationship-only table, list[IngestionResult | Exception] (aligned by index) for a list of sources. Failures in a list are also logged at WARNING.
Text mode with no
document_id derives the id from the text, so two calls with the same text are one Document and the second is a no-op. Pass a distinct document_id per call to keep identical texts as separate documents.update()
MENTIONED_IN edge are removed with their RELATES edges. A table re-syncs as a snapshot: rows deleted from the export leave the graph. A Document records how it was written, so update() cannot re-read a table as prose or a document as records. A relationship-only table raises ValueError: call ingest() again instead (relationship writes are idempotent upserts). See Incremental Updates.
Returns:
UpdateResult. For a table, the structured counts (records, entities, references, edges, and the rest of StructuredIngestionResult.as_dict()) are in metadata.
delete_document()
RELATES facts whose only provenance was those chunks, and the entities only it mentioned. Entities other documents mention are kept. if_missing="ignore" returns an empty result for an unknown id instead of raising DocumentNotFoundError. A table is deleted by its name; for a table, prefer drop_table(), which also removes its signed properties and its mapping.
apply_changes()
deleted → delete_document(), modified → update(if_missing="ingest"), added → ingest(), in that order. Per-file failures are captured as BatchEntry entries; the batch never raises for one file. An id that appears in two of the lists raises ValueError before anything runs.
Tables are accepted in added and modified. Each table is written on its own through the structured path; prose files are batched as before. The chunker, extractor, resolver and cache_unchanged_chunks overrides apply to the prose in the batch, not to a table. A table’s entry is an IngestionResult (or UpdateResult) with the structured counts in result.metadata. Relationship tables in added and modified run last, after the entity tables they resolve against. An id in deleted that names no Document but names a relationship table removes that table’s edges and keeps its mapping (drop_table() removes both).
apply_changes() does not call finalize(). Call finalize() once after the batch. Leave update_concurrency at 1; see Incremental Updates.
retrieve()
MultiPathRetrieval still makes one LLM call for keyword extraction (and one more for text-to-Cypher when enabled).
Returns:
RetrieverResult
If documents were ingested without a deduplication pass since, the first read logs a one-time WARNING reminding you to call finalize().
completion()
LLMInterface.ainvoke_messages() as [system, *history, user].
Returns:
RagResult. metadata holds model, num_context_items, strategy (the strategy class name), has_history and retrieval_query (the query actually used for retrieval).
Conversation history:
History accepts a list of ChatMessage objects or plain dicts with role and content keys. Supported roles: "system", "user", "assistant". A dict with a missing key, an unknown role or non-string content raises ValueError; an entry that is neither a ChatMessage nor a dict raises TypeError. If the first message has role="system", it is used as the system prompt as-is; otherwise the SDK’s own system prompt is used.
query()
params ($name), never string formatting.
employees__age for employees.csv); see Structured Ingestion.
get_statistics() and delete_all()
get_statistics() returns node_count, edge_count, entity_types, relationship_types, relates_edge_count, mention_edge_count, embedded_relationship_count and graph_density. SDK system nodes (__GraphRAGConfig__, __GraphRAGProcessing__) are not counted.
delete_all() drops the data graph and its paired <graph_name>__ontology graph. Irreversible. A later ingest() on the same instance re-creates indexes and re-registers the ontology.
Ontology methods
<graph_name>__ontology. get_ontology() registers the constructor’s ontology on first use and returns the persisted one; refresh_ontology() reloads it (for changes another process made); set_ontology() swaps the working ontology between ingests (additive: new labels are accepted, an existing label that already holds data may not gain properties or patterns (OntologyModificationNotAllowedError), a retyped property raises OntologyContradictionError); save_ontology() writes it as JSON, for Ontology.from_file().
Every change to the working ontology (first load, set_ontology(), each evolution method, a table declaring typed columns) is passed to the configured retrieval strategy through RetrievalStrategy.set_ontology(), so generated Cypher always sees the current schema.
Ontology evolution methods
Change the ontology of a populated graph. Full semantics in Ontology Evolution.drop_table()
- its Document and record chunks, through
delete_document(), which also removes any entity only those rows mentioned; - every property it signed on entities that survive, and the identity it gave them (
entity_key,is_stub), unless another table still keys the node; - its stored mapping, so the next
ingest()of that filename is proposed a mapping afresh.
drop_entity() removes a label nothing uses. source is matched by its exact stored path first, then by basename. It is also how you refuse a mapping the SDK proposed. A relationship table’s name removes its edges, the properties it signed on them, and its mapping.
Raises: ValueError when no table of that name is in the ontology, or when a relationship table resolves an endpoint by a key this table signed (drop that relationship table first).
suggest_schema_extensions()
deduplicate_entities()
finalize() calls it. Every run has a judge: judge is any DedupJudge, and None is LLMJudge with the instance’s llm. Anything else, judge=False among them, raises TypeError before any work.
- Incremental. Only the pending entities are checked: those ingest wrote without a name vector, and those a
pendingsystem record lists. They are compared with the rest of the graph through the__Entity__vector index, never by reading every entity. A second call with nothing pending does no work and asks the judge nothing.dedup_all=Truechecks every entity and retries the unresolved ones. - Phase 1, exact name. Groups by canonical name and label (case, accents, punctuation,
&, inner dots, a leading English article,Surname, Giveninversion, common abbreviations and one trailing legal form are normalised; word order is not). An acronym joins its unique same-label long form. A group holding a table row merges by rule; a group of extracted mentions only goes to the judge. - Phase 2, judged. Each pending entity’s nearest names form small candidate sets; the judge partitions each set once, reading names, labels, aliases, descriptions and the values of the attributes the ontology declares. Agreed groups merge; a “different” answer writes nothing. Two keyed table rows, and a mention two such rows could own, are never put to the judge.
- Crash-safe. Every merge is decided before any is written, sealed in a merge plan, and applied one atomic query per merge, moving every relationship of every type. An interrupted run is finished by the next one.
- One run per graph. A second concurrent run raises
DedupRunActiveError; a run that stalls past its 10-minute heartbeat is taken over.update()and deletes may run meanwhile; a merge they affect is skipped and decided again next run. - An entity whose check did not complete stays pending; after 3 judged runs without a usable verdict it is unresolved (reported, never merged automatically).
finalize()
- Remove NULL-name stub entities left by legacy writes (only nodes no mapping wrote).
deduplicate_entities(judge=..., dedup_all=...): exact-name and acronym dedup of the pending entities, then one judge pass over their nearest names. Dedup writes each entity’s name embedding, listing the entity as pending first;entities_embeddedcounts them. Then every entity holding more than five descriptions gets one LLM summary of them, written by the instance’sllm.embed_relationships(): fact-text embeddings onRELATESedges.ensure_indices(): all indexes, waiting until FalkorDB reports them built (up to 10 minutes; it returns anyway if the wait runs out or the status query fails).- Name the chunks: a
Chunkwith nonamegets"<document id> · chunk <index>", so it is readable in a graph browser. A chunk that already has a name, a table-row chunk (its cells are its properties, so a column callednameisChunk.name) and a chunk of a documentupdate()is still replacing are left alone.chunks_namedcounts them. - A consistency report over the whole graph, logged at WARNING and returned on the result.
finalize() calls the LLM twice over: the default judge, and the description summaries in step 2, which always use the instance’s llm. A DedupJudge of your own keeps dedup LLM-free; the summary pass still runs on llm. finalize() does not call backfill_entity_embeddings().
Returns: FinalizeResult.
Sync Wrappers
Each wrapper has the same keyword arguments as its async counterpart and runs it inasyncio.run(), so it must not be called from inside a running event loop.
Connection
ConnectionConfig
from_url() accepts redis:// or rediss:// (TLS on); any other scheme raises ValueError. Always include the scheme: "host:6380" raises ValueError and a bare "host" falls back to localhost:6379. A /db path is ignored. Keyword arguments override parsed values. Field-by-field descriptions, timeouts and retry behaviour are in Configuration.
FalkorDBConnection
query() raises DatabaseUnavailableError when the server could not run the query (unreachable, circuit breaker open, a transient failure that outlasted every retry), DatabaseError when the server rejected the query or stopped it at its timeout (raised on the first attempt), and FalkorDBVersionError for a server older than 4.20. FalkorDBConnection is also an async context manager.
Providers
LLMInterface (ABC)
ainvoke_messages() is what completion() calls. The default implementation concatenates messages into a single prompt and calls ainvoke(), so custom providers work without changes. LiteLLM and OpenRouterLLM implement it natively. A per-call max_tokens keyword overrides the instance’s own limit in the SDK’s providers; LLMJudge uses that to give judge answers enough room.
Embedder (ABC)
LLMBatchItem
LiteLLM
LiteLLMEmbedder
dimensions=256) are forwarded to LiteLLM.
OpenRouterLLM
OpenRouterEmbedder
Data Models
All models extendDataModel (Pydantic BaseModel with extra="allow"), except where noted.
GraphNode
GraphRelationship
GraphData
IngestionResult.metadata["extraction"].
TextChunk / TextChunks
DocumentInfo / DocumentOutput / DocumentRecord
IngestionResult
metadata keys include extraction (the per-chunk report from GraphData), skipped_unchanged (re-ingest of identical content), and incomplete_writes (writes that came up short; the content hash was withheld).
UpdateResult
metadata["cache_stats"] is set when cache_unchanged_chunks=True.
DeleteDocumentResult
BatchEntry / ApplyChangesResult
FinalizeResult
Returned byfinalize(). Every non-empty report field is also logged at WARNING.
RagResult
RetrieverResult / RetrieverResultItem
ResolutionResult
ChatMessage
LLMMessage (in graphrag_sdk.core.models) is an alias of ChatMessage.
LLMResponse
SearchType
Extraction Models
Ingraphrag_sdk.core.models:
compute_entity_id()
paris__location). A table row with a declared name gets its id the same way, which is why a row and a prose mention of the same name share one node.
Ontology
Attribute
Entity
Relation
Ontology
tables and relationship_tables together): one mapping per source, no two sources with the same signature, and a mapping that adds a new label must connect it (a Link, an existing entity, a sibling mapping, or standalone=True). Document and Chunk are reserved: construction accepts them, but registering the ontology (on first use) and GraphExtraction refuse them as entity labels with ValueError. from_sources() is described in Ontology Discovery.
Ingestion Strategies
LoaderStrategy (ABC)
TextLoader(encoding="utf-8") (exported), PdfLoader() (graphrag_sdk.ingestion.loaders.pdf_loader, needs the pdf extra), MarkdownLoader(encoding="utf-8") (graphrag_sdk.ingestion.loaders.markdown_loader, needs the markdown extra). Tables are read by a RecordLoaderStrategy instead.
ChunkingStrategy (ABC)
SentenceTokenCapChunking(max_tokens=384, overlap_sentences=2, encoding_name="cl100k_base", max_overlap_fraction=None)(max_overlap_fractioncaps how much of a chunk the next one may repeat) (theingest()default)FixedSizeChunking(chunk_size=1000, chunk_overlap=100)(characters)ContextualChunking(llm, base_chunker=None, max_tokens=384, overlap_sentences=2, encoding_name="cl100k_base", max_document_tokens=16_000)StructuralChunking(fallback_chunker=None, max_tokens=384, encoding_name="cl100k_base", overlap_sentences=2)(graphrag_sdk.ingestion.chunking_strategies.structural_chunking)CallableChunking(fn, *, strategy_name="custom")
SentenceTokenCapChunking(max_tokens=512) to keep a larger chunk size. Smaller chunks mean more extraction calls; see Configuration.
ExtractionStrategy (ABC)
GraphExtraction(llm, *, entity_extractor=None, coref_resolver=None, entity_types=None, relation_types=None, max_concurrency=None).entity_types=NoneselectsDEFAULT_ENTITY_TYPES(11 labels);relation_types=NoneselectsDEFAULT_RELATION_TYPES, a 31-label UPPER_SNAKE_CASE vocabulary (LOCATED_IN,PART_OF,EMPLOYED_AT,AUTHORED, …) the step-2 prompt asks the LLM to prefer; off-list labels are still kept. Passrelation_types=[]for open-vocabulary labels.entity_typesis overridden by a declaredOntology’s entities andrelation_typesby its relations, which are enforced (off-pattern edges are pruned). ThroughGraphRAG, the working ontology has entity types unless it declares only relations without patterns (a pattern registers its endpoint types; a new graph given no ontology is seeded with the 11 defaults), soentity_typesis overridden there; declare custom entity types on theOntologyinstead.CachedChunkExtraction(inner, graph_store, document_id): the decorator behindupdate(cache_unchanged_chunks=True).
DEFAULT_RELATION_TYPES is exported at the top level.
Entity extractors (step 1 of GraphExtraction; subclass EntityExtractor and implement extract_entities(text, entity_types, source_chunk_id) for your own):
GLiNERExtractor(threshold=None, model_name=None, window_tokens=None, window_overlap=48, candidate_threshold=<25 % below threshold>): the default, local NER.model_name=Noneselectsurchade/gliner_medium-v2.1;threshold=Noneselects the measured per-model value (0.75 for that model).LLMExtractor(llm, threshold=0.75): LLM-based NER.SpacyExtractor(model_name=None, labels=None, confidence=None): spaCy NER (en_core_web_lgby default), needs thespacyextra. Best as the second half of aCompositeExtractor.CompositeExtractor(extractors, suppress_overlaps=True): runs several extractors in priority order.
coref_resolver=): CorefResolver (ABC), FastCorefResolver(model_name="biu-nlp/lingmess-coref") (needs the fastcoref extra).
ResolutionStrategy (ABC)
finalize().
Built-in:
ExactMatchResolution(resolve_property="name", *, llm=None, force_summary_threshold=3, max_summary_tokens=500, cross_label_merge=False, cross_label_min_descriptions=3).ingest()usesExactMatchResolution(llm=None, cross_label_merge=False).LLMVerifiedResolution(llm=None, embedder=None, *, hard_threshold=0.95, soft_threshold=0.65, max_llm_pairs=500, max_llm_concurrency=None, force_summary_threshold=3, max_summary_tokens=500, ann_top_k=50, batch_verification=True, verification_token_budget=4000, verification_max_pairs_per_call=5, cross_label_merge=True, cross_label_vector_door=0.60, cross_label_rank_floor=0.55, cross_label_max_pairs=200, cross_label_min_descriptions=3, unified_stage=True, unified_threshold=0.65, label_family_gate=True, cross_label_vote=True). Opt-in atingest(). A pair whose names are equal once digits are removed (GPT-3/GPT-4,Q1 2024/Q2 2024) is never merged.
SemanticResolution and DescriptionMergeResolution have been removed; see Deprecated and Removed Names.
Ingestion Pipeline
Structured Ingestion
ingest(). No model is involved in writing it: identity comes from a declared key, every property type is declared, and the same file always produces the same graph. A row and a prose mention of the same thing share one node from the first write. The full guide is Structured Ingestion; the runnable version is examples/11_structured_ingestion.py.
TableMapping
MappingError (a ValueError) is raised for a declaration that does not fit (an unknown column, a cell that does not parse as its type, a row with more fields than the header, a label the sanitiser would rewrite), and the graph is left untouched.
Column
1,234.56 and 1.234,56 both read as 1234.56); without one, only comma grouping is read (1,234,567), and dot grouping such as 1.234.567 is refused; a lone 1,234 is read as 1234 by INTEGER and refused as ambiguous by FLOAT; INTEGER refuses a fractional number; FLOAT refuses nan and inf; BOOLEAN reads true/false, yes/no, 1/0 and similar; DATE is stored as an ISO date string; LIST is parsed as a CSV row. A blank cell writes no property; a cell holding 0 is a value, not a blank.
Link
RELATES edge with rel_type=type, like every data edge. The target is keyed, never named: a missing target is created as a placeholder (is_stub: true) that is renamed in place, edges intact, when the owning table arrives; an existing target (another table’s row, or an entity a document mentioned) only gains the key. A foreign key that more than one existing node answers to stays on a placeholder and is reported in references_ambiguous. Two links of one table may not point at the same (to, by).
Record loaders
CsvRecordLoader is the default; delimiter=None sniffs comma, semicolon, tab or pipe, and the default encoding reads UTF-8 with or without the byte-order mark Excel writes. The file is read once before anything is written: a row with more fields than the header is refused with its row number rather than loaded shifted. Implement RecordLoaderStrategy for another format and pass it as ingest(..., record_loader=...).
StructuredIngestionResult
Returned byingest() for a table. It is a plain class in graphrag_sdk.ingestion.structured_pipeline (not a Pydantic model and not exported at the top level), with an as_dict() method that returns the fields worth reporting. It is not an IngestionResult: read records, not chunks_indexed.
How a table is written
- Re-ingesting is a re-sync. A table is a snapshot: a deleted row is removed, a blanked cell loses its column, a moved foreign key leaves its old target, and a node another source still mentions survives with the table’s signed columns and identity retracted. A row the export dropped but another row still points at becomes a placeholder. The content hash covers the mapping, so re-declaring a type rewrites the source.
- A Document records how it was written, so
update()cannot re-read a table as prose or a document as records.update(),delete_document()anddrop_table()all take the table’s name. - No mapping declared? With a model, one is proposed (one call per table, up to 3 when a proposal does not fit the data and is sent back; never per row) from the measured columns, the first rows and the current ontology, held to the data (unique key, existing columns, known link targets, types the file can hold), stored with
derived=Trueand reported byfinalize().proposed_mappings. Without a model, or when no proposal fits, the file is read as-is: types measured over the whole file, the label from the filename, the leftmost unique-and-complete column as key, no name column. A file with no such column is refused. Declare aTableMappingto replace a proposal, ordrop_table()to refuse it. - Ontology registration is additive. Declared types reach the ontology so text-to-Cypher sees
ageas anINTEGER; an existing label is extended, not redeclared, and a type contradiction raises.
Deduplication Judges
finalize()’s cross-document dedup are one real-world entity. The run nominates the candidates, checks every answer, and performs every merge; a judge never writes. Guide and examples: Strategies.
DedupJudge (ABC)
None for a set it could not decide. A call that raises, or returns a list of another length, answers none of its sets. retry=True marks sets asked again because no usable answer came back.
LLMJudge
min_output_tokens=None keeps the LLM’s own limit, for a server whose context window cannot hold a prompt plus 4,096 output tokens. usage() reports llm_calls and llm_failed. Use a gpt-4.1-class model.
Judge input and output
JudgeEntity field is document text: data to judge, never instructions.
Ontology Evolution and Discovery Types
BackfillExecutor is the worker pool behind the evolution methods. Details in Ontology Evolution and Ontology Discovery. The discovery pipeline (discover_ontology, discover_grounded, suggest_extensions, Catalog, DBpediaCatalog, DBpediaFetchError) is in graphrag_sdk.discovery.
Retrieval Strategies
RetrievalStrategy (ABC)
Uses the Template Method pattern:search() validates, logs, calls _execute() and formats. Errors other than RetrieverError and LatencyBudgetExceededError are wrapped in RetrieverError.
set_ontology() is called by the facade on its configured retrieval strategy (the default, or the one passed as GraphRAG(retrieval_strategy=...)) whenever the working ontology changes: an evolution call, set_ontology(), a table declaring typed columns. A no-op by default; MultiPathRetrieval overrides it so generated Cypher sees the current schema. A strategy passed per call (retrieve(strategy=...)) is not updated, but one built without ontology= is lent the current one for that call; one given ontology= keeps it.
LocalRetrieval
score and metadata["chunk_id"]. Chunks of a document being updated or deleted are skipped.
MultiPathRetrieval
enable_cypher=True adds the text-to-Cypher path (an extra LLM call per question (up to 3 when a generated query fails validation and is regenerated)); ontology is what that path generates against. Items are one per context section, with metadata["section"] in hint, cypher_results, entities, relationships, facts, passages. See Retrieval.
Reranking Strategies
RerankingStrategy (ABC)
CosineReranker
RetrieverResultItem.score.
Storage
GraphRAG uses internally. You rarely need them directly; GraphRAG keeps its own instances private.
GraphStore
VectorStore
embedding_dimension must be between 1 and 8192.
Vector search scores are similarities (
1 - cosine distance): higher means closer. Chunk and entity results are ordered by score, with ties broken by id, and search_relationships() results by score, then endpoint ids, type, description and fact, so the same query returns the same rows on every FalkorDB version.
OntologyStore
<data_graph_name>__ontology. load() returns the stored Ontology; register(ontology) validates and stores one (raising OntologyContradictionError or OntologyModificationNotAllowedError before anything persists); clear() drops it. The rest of its methods back the evolution API.
Context
Exceptions
Everything not exported at the top level is importable from
graphrag_sdk.core.exceptions. If you catch DatabaseUnavailableError to detect an outage, a rejected query does not reach that handler; catch DatabaseError for it.