Skip to main content
This tutorial walks through installing GraphRAG SDK, starting FalkorDB, and building your first knowledge graph from documents so you can query it with natural language.

1. Prerequisites

  • Python 3.10+
  • FalkorDB 4.20 or later (easiest via Docker — see below). The 6.0.x line is supported too.
  • An LLM API key from one of the supported providers, for example:
    • OpenAI
    • Azure OpenAI
    • Anthropic

2. Installation

Install the SDK with the LiteLLM provider:
Optional extras add the rest: For a local editable install from a cloned repo:

3. Start FalkorDB

Run FalkorDB as a Docker container:
GraphRAG SDK needs a FalkorDB server 4.20 or later and refuses an older one at its first query, with FalkorDBVersionError. Keep the image tag: a bare falkordb/falkordb reuses whatever image Docker has cached, which may be older.
Verify it is running:

4. Configure Environment

Set the environment variable for your LLM provider. The examples below use OpenAI through LiteLLM:
If you use a .env file, load it yourself before importing the SDK (e.g., via python-dotenv). The SDK reads environment variables but does not auto-load .env files. For Azure OpenAI and other providers, see Providers.

5. Define an Ontology

An Ontology tells the extraction pipeline which entity and relationship types to look for in your documents. It is optional: without one, the SDK uses 11 general-purpose entity types and a default relation vocabulary.
Descriptions help the LLM decide when to extract each type. patterns are directional (source, target) pairs; an edge that does not fit a declared pattern is pruned. To draft an ontology from your corpus instead, see Ontology Discovery.

6. Initialize GraphRAG

Create a GraphRAG instance by providing a connection, LLM, embedder, and ontology:
The default embedding_dimension is 256 (matched-Matryoshka dimensions of text-embedding-3-large). If your embedding model produces a different dimensionality (e.g., 1024, 1536, or 3072), set embedding_dimension accordingly; a mismatch raises ConfigError before any extraction work. ConnectionConfig accepts additional parameters such as port, username, password, TLS settings and query_timeout_ms. See Configuration for the full list. GraphRAG is also an async context manager: async with GraphRAG(...) as rag: closes the connection on exit.

7. Ingest a Document

From a file path

.pdf files use PdfLoader (needs the pdf extra), .md files use MarkdownLoader (needs the markdown extra), and everything else is read as text. A .csv, .tsv, .psv or .tab file is read as a table instead; see Tables below.

From raw text

document_id is the handle you later pass to update() or delete_document(). Without one, text mode derives the id from a hash of the text.

Several files at once

Each entry is a result or the exception for that source; one bad file does not stop the batch.

Re-ingesting

Ingesting a file whose content has not changed is a no-op: nothing is re-chunked, re-extracted or re-embedded (result.metadata["skipped_unchanged"] is True). To re-process changed files, or unchanged ones after you change the ontology or chunker, see Incremental Updates. The prose pipeline runs 9 steps: Load, Chunk, Lexical Graph, Extract, Prune, Resolve, Write, then Mentions and Chunk Indexing in parallel. See Ingestion.

Tables

A CSV, TSV or similar file is read as records, not prose. Declare what its columns mean on the ontology and ingest it with the same call:
No model is involved, every column keeps its declared type, and a row and a prose mention of the same name share one node. A table with no declared mapping gets one proposed. See Structured Ingestion.

8. Finalize

After all documents and tables have been ingested, run finalize(). It deduplicates entities across documents (and embeds their names), embeds relationships, creates indexes, and gives chunks readable names:
Dedup merges duplicates such as a table row and a mention of its name (by rule), and spelling variants such as “Acme Ltd” and “Acme Limited”, or “J. Doe” and “Jane Doe”, when an LLM judge decides they are one entity. Without finalize(), a multi-document graph keeps its duplicates and entity- and relationship-level vector search returns nothing. finalize() is incremental: it checks only the entities added since the last call, so call it once after each batch of ingests, not once per file. It calls the LLM for the judge; a gpt-4.1-class judge model is recommended:
It also reports what it found, such as probable duplicates it did not merge, at WARNING and on the result. See Configuration.

9. Query the Knowledge Graph

Retrieve context only

Use retrieve() when you want to inspect the context or use your own LLM:
The default strategy returns one item per context section (entities, relationships, facts, passages, …).

Generate an answer

Use completion() for the full RAG pipeline: retrieval plus answer generation.

With context inspection

Pass return_context=True to see which sections the retriever used to build the answer:

Counting and aggregating

Questions such as “how many” or “what is the average” are answered by text-to-Cypher, which is off by default because it costs an extra LLM call per question (up to 3 when a generated query fails validation and is regenerated). Turn it on with GraphRAG(..., enable_cypher=True). See Retrieval.

Multi-turn conversations

completion() supports native multi-turn conversations. Messages are passed directly to the LLM’s chat API as structured messages:
You can also pass history as plain dicts:
Supported roles: "system", "user", "assistant". Invalid roles raise ValueError.

10. Inspect Graph Contents

Use get_statistics() to see a summary of what the graph contains:
Run your own Cypher with query(). It returns a list of rows, each a list of column values. Every extracted relationship is a RELATES edge with its type in rel_type:
query() runs exactly what you pass, with no read-only enforcement; pass values as parameters.

11. Next Steps


Synchronous API

If you are not in an async context, use the synchronous convenience methods:
update_sync(), delete_document_sync(), apply_changes_sync() and drop_table_sync() exist too. These wrap the async methods in asyncio.run() and are useful for scripts; do not call them from inside a running event loop. A Jupyter notebook already runs one, so await the async methods there instead.