Runoob Tutorial ArchiveEnglish

GraphRAG Introduction Tutorial

GraphRAG Introduction Tutorial

GraphRAG is an open-source structured and hierarchical Retrieval-Augmented Generation (RAG) system from Microsoft Research. Unlike traditional RAG which uses pure text vector retrieval, GraphRAG first extracts entities and relationships from original documents using a large model to build a knowledge graph, and then performs retrieval and Q&A based on the graph structure.

This tutorial is for readers with no prior experience, guiding you through the entire process from installation to completing the full workflow of Document -> Knowledge Graph -> Query and Answer. The model used is qwen-plus, and the Embedding used is Alibaba Cloud Tongyi's text-embedding-v4.

1f 9417e fd9e 4919 8b3f 9 1e3c7384b8


What is GraphRAG

To understand GraphRAG, first understand how it is better than traditional RAG.

Limitations of traditional RAG

The workflow of traditional RAG (Baseline RAG) is: chunk documents into small pieces -> generate vectors -> when a question comes, retrieve the most relevant few chunks using vector similarity -> send to the model to generate an answer.

This approach performs well for "precise retrieval" type questions, but performs poorly in two scenarios:

How GraphRAG solves these two problems

The core idea of GraphRAG is:Instead of directly retrieving text chunks, first build a knowledge graph, and then retrieve based on the graph structure.

The entire process is divided into two stages:

Stage What to do What to output
Index Read documents with LLM to extract entities (people, locations, organizations, etc.) and relationships, build a knowledge graph; then use the Leiden algorithm to perform hierarchical clustering on the graph and generate a summary for each community Knowledge Graph + Community Summary + Vector Index
Query When a user asks a question, select a different retrieval strategy based on the question type, inject graph data, community summaries, and original text snippets into the LLM context, and generate an answer Structured answers with source citations

The indexing phase of GraphRAG requires calling a large number of LLM APIs to perform entity extraction and summarization for every text segmentToken consumption is much higher than traditional RAG. It is recommended to test the process with small documents (within a few thousand words) during the first use, and then process large-scale corpora after confirmation.

Comparison of four query modes

Query mode Retrieval strategy Suitable question types Resource consumption
Global Search Map-Reduce iterates over all community summaries Global, summarizing questions, such as "What is the core theme of this batch of documents?" High (multiple concurrent LLM calls)
Local Search Expand neighbors and associated texts starting from relevant entities Questions targeting specific entities, such as "The main relationship network of a certain person" Medium
DRIFT Search Iterative questioning guided by Local Search + Community Information Entity-related questions requiring broad context, balancing depth and breadth Medium-high
Basic Search Standard vector similarity (same as traditional RAG) Simple exact retrieval for comparison Low

Environmental requirements

Before starting, please ensure that your environment meets the following requirements.

Dependencies Version requirements Description
Python 3.10 ~ 3.12 Officially supported range, 3.13 is not yet supported
pip Latest version It is recommended to firstpip install --upgrade pip
Alibaba Cloud Bailian API Key — Apply at bailian.console.aliyun.com/
Disk space ≥ 2GB Index artifacts (Parquet files, vector databases) will occupy a significant amount of space

Install

GraphRAG is published on PyPI; it is recommended to install it in a Python virtual environment to avoid polluting the system environment.

Create the project directory and initialize the virtual environment



mkdir graphrag_demo

cd graphrag_demo

python -m venv .venv

You can also use uv command to specify the Python version:

uv venv --python 3.12

Activate the virtual environment

macOS / Linux:



source .venv/bin/activate

Windows:



.venv\Scripts\activate

Install GraphRAG



pip install graphrag

Verify after installation:



graphrag --help

It will output some graphrag command information, similar to:

runoob 1781351784984

GraphRAG will automatically install dependencies such as LiteLLM, LanceDB, pandas, and numpy. The first installation may take a long time (usually 1-3 minutes), so please wait patiently.


Initialize workspace

Rungraphrag initThe command will generate configuration files and directory structures in the current directory.



graphrag init

It will prompt us to set up the model; pressing Enter for the default is fine for now, and you can modify it later:

Specify the default chat model to use [gpt-4.1]: 

Specify the default embedding model to use [text-embedding-3-large]: 

During initialization, you will be prompted to enter the default Chat model and Embedding model; you can temporarily skip by pressing Enter, and we will modify it manually later.settings.yaml.

After initialization, the directory structure is as follows:

Original prompt (Chinese, left untranslated)



graphrag_demo/

├── .env                  # 存放 API Key 环境变量

├── settings.yaml         # 核心配置文件

├── input/                # 存放待处理的文本文件

├── output/               # 索引产物输出目录(自动生成)

└── prompts/              # Prompt 模板目录(自动生成)

After upgrading GraphRAG to a minor version, it is recommended to re-rungraphrag init --forceRefresh the configuration format, otherwise, it may result in runtime errors due to configuration structure changes. Note that this command will overwrite the existingsettings.yamland prompts, so it is recommended to back them up first.


Prepare test documents

GraphRAG supports.txt,.csv,.jsondocuments in the format, place all files toinput/directory.

We use the officially recommended test document—Charles Dickens' A Christmas Carol, downloaded directly from Project Gutenberg:



curl https://static.jyshare.com/download/pg24022.txt -o ./input/book.txt

If the network is unavailable, you can also create your own Chinese test text; the richer the content (including a large number of characters, locations, and event relationships), the more obvious the knowledge graph effect of GraphRAG will be:

Place the file in the input directory and name it demo.txt:

Original prompt (Chinese, left untranslated)

SpaceX 太空探索技术公司成立于 2002 年,由埃隆·马斯克(Elon Musk)在美国加利福尼亚州霍桑市创办。

公司目标是大幅降低太空运输成本,最终实现人类移民火星。



马斯克早年联合创立了 PayPal,2002 年以 15 亿美元出售给 eBay,随后将个人资产投入 SpaceX。

联合创始人中,汤姆·穆勒(Tom Mueller)担任推进系统首席设计师,主导了 Merlin 和 Raptor 发动机的研发。

格温·肖特维尔(Gwynne Shotwell)于 2002 年加入,2008 年起担任总裁兼 COO,负责公司日常运营和商业拓展。



2008 年,猎鹰 1 号(Falcon 1)在经历三次失败后首次成功入轨,成为首个由私营公司研制的液体轨道火箭。

2010 年,猎鹰 9 号(Falcon 9)首飞成功,同年龙飞船(Dragon)完成首次商业发射与回收。

2012 年,龙飞船成为首个对接国际空间站的商业航天器。



2015 年 12 月,猎鹰 9 号一级火箭首次实现陆地垂直回收,开创了火箭重复使用的新纪元。

此后 SpaceX 累计完成超过 200 次火箭回收,单枚助推器最高复用次数达到 20 次以上。



2020 年,载人龙飞船(Crew Dragon)将 NASA 宇航员送入国际空间站,标志着商业载人航天时代的开始。

Starlink 星链项目自 2019 年启动,截至 2024 年已在轨部署超过 5000 颗卫星,覆盖全球超过 60 个国家和地区。



Starship 星舰是 SpaceX 正在研发的超重型运载系统,由超重助推器(Super Heavy)和星舰飞船组成,

设计目标为完全可重复使用,近地轨道运力超过 100 吨,是 NASA 阿尔忒弥斯登月计划的指定着陆器。



竞争对手方面,SpaceX 主要面临来自蓝色起源(Blue Origin)和联合发射联盟(ULA)的压力。

蓝色起源由亚马逊创始人杰夫·贝索斯创立,专注亚轨道旅游和重型火箭 New Glenn 的研发。

ULA 由洛克希德·马丁和波音合资成立,长期承担美国军方卫星发射任务。

runoob 178135 153 83


Configure qwen-plus and the Embedding model

This is the most critical step in this entire tutorial and requires modification.envandsettings.yamltwo files.

Step 1: Configure API Key

Open.envthe file and fill in your API Key:

Instance

File path: .env

Alibaba Cloud Bailian API Key

DASHSCOPE_API_KEY

=sk-your-dashscope-api-key-here

Step 2: Modify settings.yaml

Opensettings.yamland replace the entire content with the following configuration.

GraphRAG 2.x uses LiteLLM to uniformly call various models,model_provider: openaicombined withapi_baseto forward requests to any OpenAI compatible interface:

Original prompt (Chinese, left untranslated)



completion_models:

  default_completion_model:

    model_provider: openai

    model: qwen-plus                              # 中文抽取稳定,成本低于 qwen-plus

    auth_method: api_key

    api_key: ${DASHSCOPE_API_KEY}

    api_base: https://dashscope.aliyuncs.com/compatible-mode/v1

    call_args:

      temperature: 0                              # 提高结构化稳定性

      max_tokens: 4096

    retry:

      type: exponential_backoff

      max_retries: 5

      base_delay: 2



embedding_models:

  default_embedding_model:

    model_provider: openai

    model: text-embedding-v4                      # 通义向量模型

    auth_method: api_key

    api_key: ${DASHSCOPE_API_KEY}

    api_base: https://dashscope.aliyuncs.com/compatible-mode/v1

    retry:

      type: exponential_backoff

      max_retries: 5



input:

  type: text



input_storage:

  type: file

  base_dir: input



chunking:

  type: tokens

  size: 600                                       # 中文推荐 500~800

  overlap: 100

  encoding_model: o200k_base



output_storage:

  type: file

  base_dir: output



reporting:

  type: file

  base_dir: logs



cache:

  type: json

  storage:

    type: file

    base_dir: cache



vector_store:

  type: lancedb

  db_uri: output/lancedb



embed_text:

  embedding_model_id: default_embedding_model    # 注意不要带逗号

  batch_size: 10                                 # 百炼 embedding 单次最多10条

  batch_max_tokens: 6000

  concurrency: 1                                 # 避免并发触发限流



extract_graph:

  completion_model_id: default_completion_model

  entity_types: []                               # 自动识别实体

  max_gleanings: 3                               # 提高关系补抽成功率



summarize_descriptions:

  completion_model_id: default_completion_model

  max_length: 500



cluster_graph:

  max_cluster_size: 20                           # 降低社区数量



extract_claims:

  enabled: false



community_reports:

  completion_model_id: default_completion_model

  max_length: 1500

  max_input_length: 4000                         # 防止生成阶段过慢



snapshots:

  graphml: true                                  # 导出图结构

  embeddings: false



local_search:

  completion_model_id: default_completion_model

  embedding_model_id: default_embedding_model

  top_k_entities: 10



global_search:

  completion_model_id: default_completion_model

  map_max_length: 500

  reduce_max_length: 1500

Regarding Qwen's JSON output:GraphRAG requires the model to stably return JSON format during the entity extraction phase. Qwen supports JSON mode, sotemperatureSetting it to 0 can further improve output stability and reduce the probability of parsing failures. If JSON parsing errors still occur, you can try addingcall_argsinresponse_format: {type: json_object}.


Start indexing

After configuration is complete, run the indexing command. GraphRAG will automatically read all files in the directory, call qwen-plus for entity extraction, relationship recognition, and summary generation, and finally build a complete knowledge graph.input/You will see progress output similar to the following:



graphrag index

After indexing is complete,



⠹ GraphRAG Indexer

├── Loading Input (text) - 1 files loaded

├── create_base_text_units

├── extract_graph

│   └── Entity Extraction: 100%|████████████| 12/12 [02:34<00:00]

├── summarize_descriptions

├── cluster_graph

├── community_reports

└── generate_text_embeddings

All workflows completed successfully.

After indexing,output/A series of Parquet files will be generated in the directory:

File Content
entities.parquet All extracted entities (name, type, description, vector)
relationships.parquet Relationships between entities (source entity, target entity, relationship description, weight)
communities.parquet Communities generated by Leiden clustering (hierarchical structure)
community_reports.parquet Summary report for each community (core data for Global Search)
text_units.parquet Original text chunks (reference source for Local Search)
lancedb/ Vector database, stores vectors of various entities and text chunks

Indexing time reference:For a Chinese document of a few thousand words (about 10-20 text chunks), using qwen-plus takes about 3-10 minutes; for large document sets over 100,000 words, it may take several hours. It is recommended to first run the process with small documents before processing large-scale data.


Execute query

After indexing is complete, you can query the knowledge graph. GraphRAG provides both CLI and Python API methods.

CLI query

Global search (suitable for macroscopic questions):

Original prompt (Chinese, left untranslated)



graphrag query "文档中涉及的主要组织和人物有哪些?它们之间有什么关系?"

Local search (suitable for questions targeting specific entities), add--method local:

Original prompt (Chinese, left untranslated)



graphrag query "SpaceX 公司的主要业务和合作伙伴有哪些?" --method local

DRIFT Search (Balancing Depth and Breadth):

Original prompt (Chinese, left untranslated)



graphrag query "埃隆·马斯克的职业背景和主要贡献是什么?" --method drift

Basic Vector Search (Compared to Traditional RAG):

Original prompt (Chinese, left untranslated)



graphrag query "Starship 星舰的设计目标和能力是什么?" --method basic

Python API Query

Calling GraphRAG queries in code, suitable for integration into applications.

Example

File path: query_demo.py

Querying with the GraphRAG Python API

import

asyncio

from

graphrag.

api

import

GraphRagConfig

,

search

async

def

run_query

(

)

:

   

Load configuration file (read settings.yaml from the current directory)

config

=

GraphRagConfig.

from_yaml

(

"settings.yaml"

)

   

── Global Search Example ──────────────────────────────

   

print

(

"="

60

)

   

print

(

"【Global Search】Global Issues"

)

   

print

(

"="

60

)

global_result

=

await search

(

config

=

config

,

query

=

What is the main company and personnel relationship network involved in the document?

,

method

=

"global"

,

           

Use Global Search

   

)

   

print

(

global_result.

response

)

   

print

(

)

   

── Local Search Example ──────────────────────────────

   

print

(

"="

60

)

   

print

(

"【Local Search】Questions targeting specific entities"

)

   

print

(

"="

60

)

local_result

=

await search

(

config

=

config

,

query

=

"What is the background of the founding team and the main products of SpaceX?"

,

method

=

"local"

,

           

Use Local Search

   

)

   

print

(

local_result.

response

)

   

print

(

)

   

View the retrieved source information (optional)

   

if

hasattr

(

local_result

,

"context_data"

)

:

entities

=

local_result.

context_data

.

get

(

"entities"

,

[

]

)

       

print

(

f

"Number of related entities found: {len(entities)}"

)

if

name

==

"main"

:

    asyncio.

run

(

run_query

(

)

)



python query_demo.py

Original prompt (Chinese, left untranslated)



============================================================

【Global Search】全局性问题

============================================================

According to the document content, the main companies and personnel relationship networks involved are:



Company level:

- SpaceX 公司:主要角色,覆盖商业发射、载人航天、卫星互联网三大方向

- NASA:重要合作伙伴,阿尔忒弥斯登月计划 Starship 着陆器供应商

- 蓝色起源 / 联合发射联盟:主要竞争对手



Character level:

- 马斯克(创始人):PayPal 联合创始人,SpaceX CEO 兼首席工程师

- 汤姆·穆勒(联合创始人):推进系统首席设计师,Merlin 和 Raptor 发动机之父

- 格温·肖特维尔:总裁兼 COO,负责公司商业运营



Key relationships:

SpaceX 与 NASA 于 2020 年建立战略合作关系,

三家公司(SpaceX、蓝色起源、ULA)在商业航天发射市场形成竞争格局...



============================================================

【Local Search】针对特定实体的问题

============================================================

SpaceX was founded in 2002, the founding team includes:

- 马斯克:PayPal 联合创始人,SpaceX CEO 兼首席工程师,航天领域超二十年经验

- 汤姆·穆勒:推进系统首席设计师,主导 Merlin 和 Raptor 发动机研发



Main products:

1. 猎鹰 9 号:全球首个实现垂直回收的轨道级火箭,已完成 200 次以上回收

2. Starship 星舰:超重型运载系统,近地轨道运力超 100 吨,完全可重复使用



检索到相关实体数量:12


Prompt Auto-tuning

GraphRAG strongly recommends running Prompt Auto-tuning before processing your own data.

Auto-tuning allows the LLM to read some of your documents and then generate an entity extraction Prompt customized for your data domain, resulting in higher knowledge graph construction quality.



graphrag prompt-tune --config settings.yaml --root . --language Chinese

After tuning,prompts/the Prompt files in the directory will be automatically updated. If your documents are in Chinese, adding--language Chineseparameters allows the generated Prompt to also use Chinese, improving the accuracy of Chinese entity extraction.

Prompt tuning itself consumes LLM Tokens (roughly equivalent to a quick indexing of a small amount of documents), so it is recommended to retune every time you change the dataset instead of always using the default Prompt.


Quick reference for common CLI commands

The following are the most commonly used commands in daily GraphRAG usage.

Command Description
graphrag init Initialize workspace, generate.env,settings.yaml,input/
graphrag init --force Force re-initialize (use after upgrading), will overwrite existing configuration
graphrag index Perform a full indexing process on the documents in theinput/directory
graphrag index --resume Resume indexing from the last interruption point (LLM calls are cached and will not consume tokens repeatedly)
graphrag index --update Incremental indexing, only process newly added documents
graphrag query "问题" Global Search Query (Default Mode)
graphrag query "问题" --method local Local Search Query
graphrag query "问题" --method drift DRIFT Search Query
graphrag query "问题" --method basic Basic Search (Vector Retrieval)
graphrag prompt-tune Auto-tuning Prompt (Recommended to run before processing new datasets)

Full description of settings.yaml fields

The following describessettings.yamlthe most commonly used configuration items in detail to facilitate further adjustments.

Model related

Field Type Description
model_provider string Model provider, fill when using OpenAI compatible interfaceopenai
model string Model name, fill for Qwenqwen-plus 或 qwen-max
api_key string API Key, recommended to use${ENV_VAR}Reference environment variables
api_base string API endpoint, Qwen ishttps://dashscope.aliyuncs.com/compatible-mode/v1
call_args.temperature float Generation temperature, set to 0 in the indexing stage for better stability
call_args.max_tokens int Maximum tokens per generation
retry.max_retries int Maximum number of retries when the request fails

Chunking related

Field Description Suggested value
chunking.size Maximum tokens per text chunk English: 1200~1500; Chinese: 600~1000
chunking.overlap The number of overlapping tokens between adjacent blocks to avoid entities being truncated at boundaries 50~150
chunking.type tokens(Chunk by Token) orsentence(Chunk by Sentence) Generally usedtokens

Related to entity extraction

Field Description Suggestion
extract_graph.entity_types List of entity types to prioritize in the model Customized according to your own business domain, such asperson, company, product, technology
extract_graph.max_gleanings Maximum number of follow-up questions per text block (follow-up can increase recall but consumes more Tokens) Set to 1 for balancing cost, and 2 for pursuing quality

FAQ

What if the index fails midway?

GraphRAG caches the results of each LLM call. It reruns directly after failure.graphrag indexText chunks that have been successfully processed are read from the cache and will not consume tokens again.

If you want to restart from a certain step, use--resumeparameter:



graphrag index --resume

How to handle JSON parsing errors?

The entity extraction stage requires the model to strictly return JSON format. IfJSONDecodeError, you can try the following methods:

How to choose Global Search or Local Search?

Problem type Recommended mode Example
Summarizing, global Global Search "What is the core theme of this set of documents?" "The complete picture of all character relationships"
Targeting a specific entity Local Search "What is Musk's career history?" "What are the main technical features of the Falcon 9 rocket?"
Requires both depth and breadth DRIFT Search "Analysis of the relationship between a certain person and the surrounding ecosystem"
Simple and precise lookup Basic Search "In what year was SpaceX founded?"

How to control high token consumption?

GraphRAG provides an "asymmetric model configuration" strategy:completion_modelsDefine multiple models in [426], using a low-cost model in the indexing phase and a more capable model for key queries in the querying phase, balancing cost and quality.

How to handle Chinese documents?

The following points need attention when processing Chinese documents:


Further Reading

Topic Description Link
Official full documentation Detailed description of all configuration items microsoft.github.io/graphrag
Configuration reference Full field description of settings.yaml microsoft.github.io/graphrag/config/yaml/
Model selection guide How to integrate various LLMs (including LiteLLM usage) microsoft.github.io/graphrag/config/models/
Query Engine Details Principles and parameter tuning of four query modes microsoft.github.io/graphrag/query/overview/
Prompt Tuning Guide Complete explanation of automatic and manual Prompt tuning microsoft.github.io/graphrag/prompt_tuning/overview/
Visualization Guide Visualize knowledge graph using official tools microsoft.github.io/graphrag/visualization_guide/
GraphRAG Paper Original paper from Microsoft Research to understand the underlying principles arxiv.org/pdf/2404.16130