FalkorDB server version
GraphRAG SDK requires FalkorDB 4.20 or later. The 4.x line from 4.20 and the 6.0.x line are both supported; the repository’sdocker-compose.yml, the README and the examples use falkordb/falkordb:v4.22.2:
FalkorDBVersionError (a DatabaseError), so ingest(), query(), finalize() and every other call that runs a query fail before anything is written. delete_all() drops the graphs with GRAPH.DELETE directly and is not checked. Earlier servers dropped vector-index entries on every write to a node holding a vector, so search and dedup missed entities.
- A server that refuses to report its version (an ACL without
MODULE LIST, or a managed server that disabled it) is let through with a warning. - Any other answer to the version check is handled as a query’s would be: a temporary error is retried, and a server that cannot be reached fails the call with
DatabaseUnavailableErrorand is asked again by the next one. close()makes the next query ask again.
1. ConnectionConfig
ConnectionConfig is a dataclass that defines how the SDK connects to a FalkorDB instance. It is passed to GraphRAG or used to create a FalkorDBConnection directly.
Fields
The TLS fields mirror
redis-py’s naming and have no effect unless ssl=True.
Creating from a URL
ConnectionConfig.from_url() parses a redis:// or rediss:// URL and returns a ConnectionConfig:
redis://[user:pass@]host[:port] (plaintext) or rediss://... (TLS); a /db path is ignored. Always include the scheme: without one, "host:6380" raises ValueError (the host is read as the scheme) and a bare "host" falls back to localhost:6379. Any other scheme raises ValueError. Keyword arguments override the values parsed from the URL.
Passing to GraphRAG
You can pass either aConnectionConfig or a pre-built FalkorDBConnection:
Timeouts
A query needing more than 5 s but less than
query_timeout_ms completes normally.
Retry Behavior
Each query is attempted up toretry_count times in total, the first try included, with exponential backoff and jitter between attempts (retry_delay * 2^attempt * random(0.5, 1.5), attempt counting from 0). Everything that is not a server reply is retried: a lost connection or socket timeout, LOADING, an error raised in the driver. Of the server’s replies only the temporary ones are: a full query queue, BUSY, NOREPLICAS, MISCONF, a cluster redirect or failover, a read-only replica, and out of memory. If one outlasts every attempt, the circuit breaker is open, or the first connection to the server fails, query() raises DatabaseUnavailableError.
On a server that stops answering queries once the connection is open, each attempt waits query_timeout_ms + 5 s for a reply, plus the backoff between attempts: about 48 s at the defaults (46–50 s, with the jitter) before DatabaseUnavailableError. A server that never answers at all fails at the driver’s first probe instead, which redis-py retries on its own (about 60 s; see Storage). Lower query_timeout_ms or retry_count to fail sooner. ping() still answers within 5 s.
Any other server reply means the query itself was rejected — a syntax error, an unknown variable, division by zero, a MERGE on a null key, a missing index, a procedure called with the wrong arguments. A read the server stops at its timeout (“Query timed out”) is treated the same way, since a retry would cost as much again. Both raise DatabaseError on the first attempt, and the circuit breaker counts them as a healthy answer, not a failure. FalkorDB applies no timeout to writes: a write slower than query_timeout_ms + 5 s is cut on the client as a socket timeout and re-sent, while the first attempt may still run.
DatabaseUnavailableError subclasses DatabaseError, so except DatabaseError catches both. If you catch DatabaseUnavailableError to detect an outage, a rejected or timed-out query does not reach that handler.
Circuit Breaker
Every connection has a circuit breaker. After 5 consecutive transient failures it opens and refuses every query at once, withDatabaseUnavailableError, for 30 seconds; then it lets one probe query through. A successful query, or a rejected one (the server answered), closes it again.
2. LLM Providers
The SDK defines an abstractLLMInterface base class. All LLM providers must implement invoke() for synchronous calls. Async calls (ainvoke) default to running invoke in a thread pool but can be overridden for true async support. See Providers for the full method list.
Common Parameters
TheLLMInterface base class accepts:
LiteLLM (Recommended)
LiteLLM supports 100+ LLM providers through a unified interface. Install withpip install graphrag-sdk[litellm].
Other keyword arguments are forwarded to LiteLLM.
OpenRouter
OpenRouter provides access to many models through a single API. Install withpip install graphrag-sdk[openrouter].
Azure OpenAI via Environment Variables
When using LiteLLM with Azure, you can read the settings from environment variables:Custom LLM Provider
Implement theLLMInterface abstract class:
Which model does what
Onellm serves every LLM call the SDK makes, unless you pass another for a specific job:
3. Embedder Providers
The SDK defines an abstractEmbedder base class with embed_query() (single text) and embed_documents() (batch). Batch embedding is critical for performance.
Performance Note: Batch Embedding
Individual embedding calls to Azure OpenAI take approximately 0.22 seconds each. A batch of 500 texts takes approximately 8 seconds. Always use batch embedding (embed_documents / aembed_documents) rather than looping over embed_query.
LiteLLMEmbedder
Supports OpenAI, Azure, Cohere, and other embedding models via LiteLLM.
Other keyword arguments (such as
dimensions) are forwarded to LiteLLM. For Azure OpenAI, set batch_size=500 to stay within the API rate limits. The default of 2048 works well for OpenAI’s direct API.
GraphRAG(embedding_dimension=...) defaults to 256 and must match the vectors your embedder produces; a mismatch raises ConfigError before any extraction work. The embedding model and dimension are stored in the graph, and a later session with a different model is refused.
OpenRouterEmbedder
Custom Embedder
Implement theEmbedder abstract class:
aembed_query and aembed_documents if your provider supports true async. The defaults run the sync methods in a thread pool via asyncio.to_thread.
Binary-Split Error Recovery
BothLiteLLMEmbedder and OpenRouterEmbedder implement binary-split error recovery for batch embedding. If a batch fails with a transient error, the batch is split in half and each half is retried recursively. Non-transient errors (401, 403, authentication failures) are raised immediately.
4. Ontology
AnOntology defines the structure of your knowledge graph. It constrains LLM extraction, powers the pruning step that filters non-conforming data, tells text-to-Cypher which labels and typed properties exist, and holds the mappings for tables.
Components
Entity — defines a node type:
Relation — defines a relationship type:
Attribute — defines a property on a node or relationship:
tables —
Ontology(tables=[TableMapping(...)]) declares how CSV/TSV files become nodes. See Structured Ingestion.
Example Ontology
name is managed by the SDK and need not be declared. The ontology is persisted in the paired <graph_name>__ontology graph; await rag.save_ontology("ontology.json") and Ontology.from_file("ontology.json") round-trip it as JSON.
No Ontology
With no entity types, relation types or tables (and no ontology stored for the graph yet), the first use seeds the 11 default entity types (Person, Organization, Technology, Product, Location, Date, Event, Concept, Law, Dataset, Method). No relation is enforced: the extraction prompt listsDEFAULT_RELATION_TYPES (31 labels) as preferred relationships and accepts any other UPPER_SNAKE_CASE label. See Pipeline Tuning.
GraphSchema, EntityType, RelationType and PropertyType are deprecated aliases of Ontology, Entity, Relation and Attribute, and GraphRAG(schema=...) of ontology=; each use emits a DeprecationWarning.
5. Pipeline Tuning
Chunking
The default chunker isSentenceTokenCapChunking: it splits at sentence boundaries and caps each chunk at 384 tokens, with 2 sentences of overlap.
StructuralChunking and ContextualChunking also default to 384 tokens.
Cost of the 384-token default. Smaller chunks mean more extraction calls. On the 11-document benchmark corpus, 384 tokens made 157 extraction LLM calls where 512 made 103 (+52 %); on a 53k-token corpus the increase was 35 %, with about 19 % more input tokens. In return, relation F1 and answer accuracy rose on the same corpus. Pass
chunker=SentenceTokenCapChunking(max_tokens=512) to keep the larger size.FixedSizeChunking splits into fixed-size character windows (chunk_size=1000, chunk_overlap=100 by default). Tables are not chunked: each row is one record chunk.
To re-chunk documents already in the graph after changing the chunker, use update(path, force=True); a plain ingest() of unchanged content is a no-op.
Extraction Strategy Parameters
GraphExtraction — composable 2-step extraction (GLiNER NER + LLM verification and relationship extraction):
Built-in entity extractors:
Custom Entity Types
Override the default 11 entity types with your own domain-specific types by declaring them in the ontology:ontology.entities > the entity_types parameter of GraphExtraction > defaults (Person, Organization, Technology, Product, Location, Date, Event, Concept, Law, Dataset, Method). Through GraphRAG, the working ontology has entity types unless it declares only relations without patterns (a pattern registers its endpoint types), because a graph with no ontology is seeded with the 11 defaults on first use, so GraphExtraction(entity_types=...) has no effect there. It applies only when you run GraphExtraction with an ontology that declares no entities, such as in your own IngestionPipeline.
LLM Concurrency
TheLLMInterface.max_concurrency parameter (default: 12) controls how many LLM calls run in parallel during abatch_invoke(). Set it lower to avoid rate limits:
GraphExtraction, you can also pass max_concurrency directly:
6. Retrieval Tuning
MultiPathRetrieval
MultiPathRetrieval is the default retrieval strategy. It combines multiple search paths with cosine reranking.
Text-to-Cypher
Text-to-Cypher answers the questions no passage contains: counts, averages, “how many of these”. It is off by default, because it costs an extra LLM call per question (up to 3 when a generated query fails validation). Turn it on for the default strategy with one flag:INTEGER age, a FLOAT revenue) reach the ontology so the generated query can aggregate over them. GraphRAG passes every ontology change to its retrieval strategy, so a column becomes visible to generated Cypher as soon as a table declares it. enable_cypher is ignored when you pass your own retrieval_strategy; set enable_cypher=True on that strategy instead.
Custom MultiPathRetrieval
GraphRAG(retrieval_strategy=...) receives every ontology change through set_ontology(). A strategy passed only per call (strategy=) without its own ontology= is lent the current one for that call; one given ontology= keeps it.
Retrieval Pipeline (9 Steps)
- Keyword extraction — stopword filtering + LLM proper-noun extraction.
- Embed question — single embedding API call for the query.
- RELATES edge vector search — finds fact strings and entity entry points via edge embeddings. Text-to-Cypher runs in parallel when enabled.
- Entity discovery — exact name or alias match (names first), then name or alias
CONTAINS(skipped for short acronyms), then fulltext search on the__Entity__index (name matches first). Merged with entities from step 3. Enumeration questions add sibling entities. - Relationship expansion — a walk over RELATES edges in both directions, in up to three rounds (15 entities with 10 edges each, then 8 and 5 far ends with 5 edges each), ranked by closeness to the question. Deeper links keep up to a third of
max_relationships, a relationship table’s unembedded edges up to a fifth; lines the facts section shows are left out. - Chunk retrieval (4 paths) — fulltext search, vector search, MENTIONED_IN traversal, and 2-hop entity-to-neighbor-to-chunk traversal. Table-row chunks (not embedded) keep slots of their own; chunks of a document being updated or deleted are skipped.
- Source document names — batch-fetch document paths via PART_OF edges.
- Cosine reranking — rerank candidate chunks against the question using their stored embeddings.
- Context assembly — structured sections: hint, Cypher results, entities, relationships, facts, passages.
7. Post-Ingestion
After all documents and tables have been ingested, callfinalize(). It deduplicates entities across documents, embeds entity names and relationships, and ensures every index exists.
finalize() — All-In-One
It bundles these steps in order:
- Remove NULL-name stub entities left by legacy writes (only nodes no mapping wrote).
deduplicate_entities()— incremental and crash-safe: the entities whose check is pending (added since the lastfinalize(), or left pending by it) get exact-name dedup, then one judge pass over their nearest names in the whole graph. Dedup also gives every entity its name embedding. Then every entity holding more than 5 description pieces gets one LLM summary of them in their place (descriptions_summarisedcounts them). A secondfinalize()with nothing pending does no dedup work. An entity whose check did not complete stays pending and is retried; after 3 judged runs without a usable verdict it is reported indedup_unresolvedand no longer retried. An interruptedfinalize()is finished by the next one.finalize(dedup_all=True)checks every entity.embed_relationships()— embed fact text on RELATES edges.ensure_indices()— create all standard indexes (idempotent) and wait until they are built.- Name the chunks — an unnamed
Chunkgets"<document id> · chunk <index>", except a table row and a chunk of a document being replaced byupdate()(its id carries__pending__).chunks_namedcounts them. Passname_chunks=Falseto leave chunks as written. - Report what it found (probable duplicates, property conflicts, proposed table mappings and more) at WARNING and on the result.
finalize() or deduplicate_entities() — from another process, or on the same GraphRAG — raises DedupRunActiveError when it reaches dedup, and the running one is left untouched. update() and deletes may run meanwhile.
FinalizeResult fields are listed in the API Reference.
Choosing the judge model
finalize() calls the LLM for the dedup judge, which decides which candidates are one entity, and for the description summaries. By default the judge is LLMJudge with the instance’s llm. Give it a gpt-4.1-class model: on the benchmark corpus a gpt-4.1-class judge made 9 wrong merges where gpt-4o-mini made 51.
To keep dedup free of LLM calls, pass a
DedupJudge of your own, such as one that groups by spelling; see Strategies. There is no run without a judge: judge=False raises TypeError.
deduplicate_entities() — Entity Deduplication
Call this when you need fine-grained control over deduplication.
Only the pending entities are checked: those with no name vector yet (ingest writes entities without one), and those a
pending system record lists — a run lists every entity before it embeds it, and clears it once its check completes. See Storage for the merge plan and crash safety.
Phase 1 (always runs): Exact name match. Groups the pending entities and their nearest names from the vector index by canonical name (case, accents, punctuation, & and a leading English article folded; A.I. = AI; Surname, Given un-inverted; common abbreviations expanded; one trailing legal form such as Ltd or Inc dropped; word order kept) and label, to prevent cross-type merging. An acronym joins its long form when exactly one same-label entity spells its initials. A group holding a table row merges by rule; a group of extracted mentions only goes to the judge instead, so two mentions named Paris, one the city in France and one the city in Texas, are judged rather than merged on the name.
Phase 2: judged match. Each pending entity’s nearest names from the vector index form small candidate sets; the judge partitions each set once, seeing names, labels, aliases, descriptions and the values of the attributes the ontology declares. Agreed groups merge by the Phase 1 rules. Every set is judged before anything merges. See Storage.
Lower-level steps
embed_relationships(), ensure_indices() and backfill_entity_embeddings() are VectorStore methods. GraphRAG keeps its VectorStore private and finalize() runs what it needs; call them on a VectorStore of your own only for special cases.
Separately, every write range-indexes
id and entity_key on each label it writes into, the first time it writes there. ensure_indices() is also called after each ingest() of a document; ingesting a table creates only those per-label range indexes (plus one on a table’s signed key column), and finalize() builds the rest. It waits until FalkorDB reports every index built (up to 10 minutes, logging progress every 10 s), since a vector search on an index still being built fails on FalkorDB 4.x and returns no or partial rows on 6.0.x; if the status query fails or the wait runs out, it returns anyway.