diff --git a/examples_notebooks/global_search/index.html b/examples_notebooks/global_search/index.html index dfd58213e9..587b437a12 100644 --- a/examples_notebooks/global_search/index.html +++ b/examples_notebooks/global_search/index.html @@ -2248,7 +2248,7 @@
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) -/tmp/ipykernel_2116/1512985616.py in ?() +/tmp/ipykernel_2110/1512985616.py in ?() 2 entity_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_TABLE}.parquet") 3 report_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_REPORT_TABLE}.parquet") 4 entity_embedding_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_EMBEDDING_TABLE}.parquet") diff --git a/examples_notebooks/global_search_with_dynamic_community_selection/index.html b/examples_notebooks/global_search_with_dynamic_community_selection/index.html index 5327ce1fb3..81c0b5dc77 100644 --- a/examples_notebooks/global_search_with_dynamic_community_selection/index.html +++ b/examples_notebooks/global_search_with_dynamic_community_selection/index.html @@ -2156,7 +2156,7 @@Load community repo
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) -/tmp/ipykernel_2146/2760368953.py in ?() +/tmp/ipykernel_2143/2760368953.py in ?() 2 entity_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_TABLE}.parquet") 3 report_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_REPORT_TABLE}.parquet") 4 entity_embedding_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_EMBEDDING_TABLE}.parquet") diff --git a/examples_notebooks/index_migration/index.html b/examples_notebooks/index_migration/index.html index b1fb986c2a..65d4cb3ac5 100644 --- a/examples_notebooks/index_migration/index.html +++ b/examples_notebooks/index_migration/index.html @@ -2324,9 +2324,8 @@Index Migration
from datashaper import NoopVerbCallbacks - -from graphrag.cache.factory import create_cache +-from graphrag.cache.factory import create_cache +from graphrag.callbacks.noop_verb_callbacks import NoopVerbCallbacks from graphrag.index.flows.generate_text_embeddings import generate_text_embeddings # We only need to re-run the embeddings workflow, to ensure that embeddings for all required search fields are in place @@ -2355,9 +2354,8 @@Index Migrationsnapshot_embeddings_enabled=False, )
from datashaper import NoopVerbCallbacks - -from graphrag.cache.factory import create_cache +from graphrag.cache.factory import create_cache +from graphrag.callbacks.noop_verb_callbacks import NoopVerbCallbacks from graphrag.index.flows.generate_text_embeddings import generate_text_embeddings # We only need to re-run the embeddings workflow, to ensure that embeddings for all required search fields are in place @@ -2399,12 +2397,10 @@diff --git a/index/architecture/index.html b/index/architecture/index.html index d01f53c0c1..578e5cb653 100644 --- a/index/architecture/index.html +++ b/index/architecture/index.html @@ -628,27 +628,9 @@Index Migration--------------------------------------------------------------------------- ImportError Traceback (most recent call last) -Cell In[7], line 3 - 1 from datashaper import NoopVerbCallbacks -----> 3 from graphrag.cache.factory import create_cache - 4 from graphrag.index.flows.generate_text_embeddings import generate_text_embeddings - 6 # We only need to re-run the embeddings workflow, to ensure that embeddings for all required search fields are in place - 7 # We'll construct the context and run this function flow directly to avoid everything else +Cell In[7], line 1 +----> 1 from graphrag.cache.factory import create_cache + 2 from graphrag.callbacks.noop_verb_callbacks import NoopVerbCallbacks + 3 from graphrag.index.flows.generate_text_embeddings import generate_text_embeddings ImportError: cannot import name 'create_cache' from 'graphrag.cache.factory' (/home/runner/work/graphrag/graphrag/graphrag/cache/factory.py)
- + - DataShaper Workflows - - - - - -- - - LLM-based Workflow Steps - - - - - -- - - Workflow Graphs + Workflows @@ -1493,27 +1475,9 @@ - - - DataShaper Workflows - - - - - -- + - LLM-based Workflow Steps - - - - - -- - - Workflow Graphs + Workflows @@ -1566,24 +1530,8 @@ Knowledge Model
In order to support the GraphRAG system, the outputs of the indexing engine (in the Default Configuration Mode) are aligned to a knowledge model we call the GraphRAG Knowledge Model. This model is designed to be an abstraction over the underlying data storage technology, and to provide a common interface for the GraphRAG system to interact with. In normal use-cases the outputs of the GraphRAG Indexer would be loaded into a database system, and the GraphRAG's Query Engine would interact with the database using the knowledge model data-store types.
-DataShaper Workflows
-GraphRAG's Indexing Pipeline is built on top of our open-source library, DataShaper. -DataShaper is a data processing library that allows users to declaratively express data pipelines, schemas, and related assets using well-defined schemas. -DataShaper has implementations in JavaScript and Python, and is designed to be extensible to other languages.
-One of the core resource types within DataShaper is a Workflow. -Workflows are expressed as sequences of steps, which we call verbs. -Each step has a verb name and a configuration object. -In DataShaper, these verbs model relational concepts such as SELECT, DROP, JOIN, etc.. Each verb transforms an input data table, and that table is passed down the pipeline.
----- -title: Sample Workflow ---- -flowchart LR - input[Input Table] --> select[SELECT] --> join[JOIN] --> binarize[BINARIZE] --> output[Output Table]
LLM-based Workflow Steps
-GraphRAG's Indexing Pipeline implements a handful of custom verbs on top of the standard, relational verbs that our DataShaper library provides. These verbs give us the ability to augment text documents with rich, structured data using the power of LLMs such as GPT-4. We utilize these verbs in our standard workflow to extract entities, relationships, claims, community structures, and community reports and summaries. This behavior is customizable and can be extended to support many kinds of AI-based data enrichment and extraction tasks.
-Workflow Graphs
-Because of the complexity of our data indexing tasks, we needed to be able to express our data pipeline as series of multiple, interdependent workflows. -In the GraphRAG Indexing Pipeline, each workflow may define dependencies on other workflows, effectively forming a directed acyclic graph (DAG) of workflows, which is then used to schedule processing.
+Workflows
+Because of the complexity of our data indexing tasks, we needed to be able to express our data pipeline as series of multiple, interdependent workflows.
--- title: Sample Workflow DAG --- @@ -1599,7 +1547,7 @@
Dataframe Message Format
The primary unit of communication between workflows, and between workflow steps is an instance of
+Our underlying dataframe technology may change over time, but our primary goal is to support the workflow schema while retaining single-machine ease of use and developer ergonomics.pandas.DataFrame
. Although side-effects are possible, our goal is to be data-centric and table-centric in our approach to data processing. This allows us to easily reason about our data, and to leverage the power of dataframe-based ecosystems. -Our underlying dataframe technology may change over time, but our primary goal is to support the DataShaper workflow schema while retaining single-machine ease of use and developer ergonomics.LLM Caching
The GraphRAG library was designed with LLM interactions in mind, and a common setback when working with LLM APIs is various errors due to network latency, throttling, etc.. Because of these potential error cases, we've added a cache layer around LLM interactions. diff --git a/search/search_index.json b/search/search_index.json index 1c8c995a8e..2641d067af 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config": {"lang": ["en"], "separator": "[\\s\\-]+", "pipeline": ["stopWordFilter"]}, "docs": [{"location": "", "title": "Welcome to GraphRAG", "text": "
\ud83d\udc49 Microsoft Research Blog Post \ud83d\udc49 GraphRAG Accelerator \ud83d\udc49 GraphRAG Arxiv
Figure 1: An LLM-generated knowledge graph built using GPT-4 Turbo.
GraphRAG is a structured, hierarchical approach to Retrieval Augmented Generation (RAG), as opposed to naive semantic-search approaches using plain text snippets. The GraphRAG process involves extracting a knowledge graph out of raw text, building a community hierarchy, generating summaries for these communities, and then leveraging these structures when perform RAG-based tasks.
To learn more about GraphRAG and how it can be used to enhance your LLMs ability to reason about your private data, please visit the Microsoft Research Blog Post.
"}, {"location": "#solution-accelerator", "title": "Solution Accelerator \ud83d\ude80", "text": "To quickstart the GraphRAG system we recommend trying the Solution Accelerator package. This provides a user-friendly end-to-end experience with Azure resources.
"}, {"location": "#get-started-with-graphrag", "title": "Get Started with GraphRAG \ud83d\ude80", "text": "To start using GraphRAG, check out the Get Started guide. For a deeper dive into the main sub-systems, please visit the docpages for the Indexer and Query packages.
"}, {"location": "#graphrag-vs-baseline-rag", "title": "GraphRAG vs Baseline RAG \ud83d\udd0d", "text": "Retrieval-Augmented Generation (RAG) is a technique to improve LLM outputs using real-world information. This technique is an important part of most LLM-based tools and the majority of RAG approaches use vector similarity as the search technique, which we call Baseline RAG. GraphRAG uses knowledge graphs to provide substantial improvements in question-and-answer performance when reasoning about complex information. RAG techniques have shown promise in helping LLMs to reason about private datasets - data that the LLM is not trained on and has never seen before, such as an enterprise\u2019s proprietary research, business documents, or communications. Baseline RAG was created to help solve this problem, but we observe situations where baseline RAG performs very poorly. For example:
- Baseline RAG struggles to connect the dots. This happens when answering a question requires traversing disparate pieces of information through their shared attributes in order to provide new synthesized insights.
- Baseline RAG performs poorly when being asked to holistically understand summarized semantic concepts over large data collections or even singular large documents.
To address this, the tech community is working to develop methods that extend and enhance RAG. Microsoft Research\u2019s new approach, GraphRAG, uses LLMs to create a knowledge graph based on an input corpus. This graph, along with community summaries and graph machine learning outputs, are used to augment prompts at query time. GraphRAG shows substantial improvement in answering the two classes of questions described above, demonstrating intelligence or mastery that outperforms other approaches previously applied to private datasets.
"}, {"location": "#the-graphrag-process", "title": "The GraphRAG Process \ud83e\udd16", "text": "GraphRAG builds upon our prior research and tooling using graph machine learning. The basic steps of the GraphRAG process are as follows:
"}, {"location": "#index", "title": "Index", "text": ""}, {"location": "#query", "title": "Query", "text": "
- Slice up an input corpus into a series of TextUnits, which act as analyzable units for the rest of the process, and provide fine-grained references in our outputs.
- Extract all entities, relationships, and key claims from the TextUnits using an LLM.
- Perform a hierarchical clustering of the graph using the Leiden technique. To see this visually, check out Figure 1 above. Each circle is an entity (e.g., a person, place, or organization), with the size representing the degree of the entity, and the color representing its community.
- Generate summaries of each community and its constituents from the bottom-up. This aids in holistic understanding of the dataset.
At query time, these structures are used to provide materials for the LLM context window when answering a question. The primary query modes are:
"}, {"location": "#prompt-tuning", "title": "Prompt Tuning", "text": "
- Global Search for reasoning about holistic questions about the corpus by leveraging the community summaries.
- Local Search for reasoning about specific entities by fanning-out to their neighbors and associated concepts.
- DRIFT Search for reasoning about specific entities by fanning-out to their neighbors and associated concepts, but with the added context of community information.
Using GraphRAG with your data out of the box may not yield the best possible results. We strongly recommend to fine-tune your prompts following the Prompt Tuning Guide in our documentation.
"}, {"location": "blog_posts/", "title": "Microsoft Research Blog", "text": "
GraphRAG: Unlocking LLM discovery on narrative private data
Published February 13, 2024
By Jonathan Larson, Senior Principal Data Architect; Steven Truitt, Principal Program Manager
GraphRAG: New tool for complex data discovery now on GitHub
Published July 2, 2024
By Darren Edge, Senior Director; Ha Trinh, Senior Data Scientist; Steven Truitt, Principal Program Manager; Jonathan Larson, Senior Principal Data Architect
GraphRAG auto-tuning provides rapid adaptation to new domains
Published September 9, 2024
By Alonso Guevara Fern\u00e1ndez, Sr. Software Engineer; Katy Smith, Data Scientist II; Joshua Bradley, Senior Data Scientist; Darren Edge, Senior Director; Ha Trinh, Senior Data Scientist; Sarah Smith, Senior Program Manager; Ben Cutler, Senior Director; Steven Truitt, Principal Program Manager; Jonathan Larson, Senior Principal Data Architect
Introducing DRIFT Search: Combining global and local search methods to improve quality and efficiency
Published October 31, 2024
By Julian Whiting, Senior Machine Learning Engineer; Zachary Hills , Senior Software Engineer; Alonso Guevara Fern\u00e1ndez, Sr. Software Engineer; Ha Trinh, Senior Data Scientist; Adam Bradley , Managing Partner, Strategic Research; Jonathan Larson, Senior Principal Data Architect
GraphRAG: Improving global search via dynamic community selection
Published November 15, 2024
By Bryan Li, Research Intern; Ha Trinh, Senior Data Scientist; Darren Edge, Senior Director; Jonathan Larson, Senior Principal Data Architect
LazyGraphRAG: Setting a new standard for quality and cost
Published November 25, 2024
By Darren Edge, Senior Director; Ha Trinh, Senior Data Scientist; Jonathan Larson, Senior Principal Data Architect
Moving to GraphRAG 1.0 \u2013 Streamlining ergonomics for developers and users
Published December 16, 2024
By Nathan Evans, Principal Software Architect; Alonso Guevara Fern\u00e1ndez, Senior Software Engineer; Joshua Bradley, Senior Data Scientist
"}, {"location": "cli/", "title": "CLI Reference", "text": "This page documents the command-line interface of the graphrag library.
"}, {"location": "cli/#graphrag", "title": "graphrag", "text": "GraphRAG: A graph-based retrieval-augmented generation (RAG) system.
Usage:
[OPTIONS] COMMAND [ARGS]...\n
Options:
"}, {"location": "cli/#index", "title": "index", "text": "--install-completion Install completion for the current shell.\n --show-completion Show completion for the current shell, to copy it or\n customize the installation.\n
Build a knowledge graph index.
Usage:
index [OPTIONS]\n
Options:
"}, {"location": "cli/#init", "title": "init", "text": "--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --verbose / --no-verbose Run the indexing pipeline with verbose\n logging \\[default: no-verbose]\n --memprofile / --no-memprofile Run the indexing pipeline with memory\n profiling \\[default: no-memprofile]\n --resume TEXT Resume a given indexing run\n --logger [rich|print|none] The progress logger to use. \\[default:\n rich]\n --dry-run / --no-dry-run Run the indexing pipeline without executing\n any steps to inspect and validate the\n configuration. \\[default: no-dry-run]\n --cache / --no-cache Use LLM cache. \\[default: cache]\n --skip-validation / --no-skip-validation\n Skip any preflight validation. Useful when\n running no LLM steps. \\[default: no-skip-\n validation]\n --output PATH Indexing pipeline output directory.\n Overrides storage.base_dir in the\n configuration file.\n
Generate a default configuration file.
Usage:
init [OPTIONS]\n
Options:
"}, {"location": "cli/#prompt-tune", "title": "prompt-tune", "text": "--root PATH The project root directory. \\[required]\n
Generate custom graphrag prompts with your own data (i.e. auto templating).
Usage:
prompt-tune [OPTIONS]\n
Options:
"}, {"location": "cli/#query", "title": "query", "text": "--root PATH The project root directory. \\[default: .]\n --config PATH The configuration to use.\n --domain TEXT The domain your input data is related to.\n For example 'space science', 'microbiology',\n 'environmental news'. If not defined, a\n domain will be inferred from the input data.\n --selection-method [all|random|top|auto]\n The text chunk selection method. \\[default:\n random]\n --n-subset-max INTEGER The number of text chunks to embed when\n --selection-method=auto. \\[default: 300]\n --k INTEGER The maximum number of documents to select\n from each centroid when --selection-\n method=auto. \\[default: 15]\n --limit INTEGER The number of documents to load when\n --selection-method={random,top}. \\[default:\n 15]\n --max-tokens INTEGER The max token count for prompt generation.\n \\[default: 2000]\n --min-examples-required INTEGER\n The minimum number of examples to\n generate/include in the entity extraction\n prompt. \\[default: 2]\n --chunk-size INTEGER The max token count for prompt generation.\n \\[default: 200]\n --language TEXT The primary language used for inputs and\n outputs in graphrag prompts.\n --discover-entity-types / --no-discover-entity-types\n Discover and extract unspecified entity\n types. \\[default: discover-entity-types]\n --output PATH The directory to save prompts to, relative\n to the project root directory. \\[default:\n prompts]\n
Query a knowledge graph index.
Usage:
query [OPTIONS]\n
Options:
"}, {"location": "cli/#update", "title": "update", "text": "--method [local|global|drift|basic]\n The query algorithm to use. \\[required]\n --query TEXT The query to execute. \\[required]\n --config PATH The configuration to use.\n --data PATH Indexing pipeline output directory (i.e.\n contains the parquet files).\n --root PATH The project root directory. \\[default: .]\n --community-level INTEGER The community level in the Leiden community\n hierarchy from which to load community\n reports. Higher values represent reports\n from smaller communities. \\[default: 2]\n --dynamic-community-selection / --no-dynamic-community-selection\n Use global search with dynamic community\n selection. \\[default: no-dynamic-community-\n selection]\n --response-type TEXT Free form text describing the response type\n and format, can be anything, e.g. Multiple\n Paragraphs, Single Paragraph, Single\n Sentence, List of 3-7 Points, Single Page,\n Multi-Page Report. Default: Multiple\n Paragraphs \\[default: Multiple Paragraphs]\n --streaming / --no-streaming Print response in a streaming manner.\n \\[default: no-streaming]\n
Update an existing knowledge graph index.
Applies a default storage configuration (if not provided by config), saving the new index to the local file system in the
update_output
folder.Usage:
update [OPTIONS]\n
Options:
"}, {"location": "developing/", "title": "Development Guide", "text": ""}, {"location": "developing/#requirements", "title": "Requirements", "text": "Name Installation Purpose Python 3.10-3.12 Download The library is Python-based. Poetry Instructions Poetry is used for package management and virtualenv management in Python codebases"}, {"location": "developing/#getting-started", "title": "Getting Started", "text": ""}, {"location": "developing/#install-dependencies", "title": "Install Dependencies", "text": "--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --verbose / --no-verbose Run the indexing pipeline with verbose\n logging \\[default: no-verbose]\n --memprofile / --no-memprofile Run the indexing pipeline with memory\n profiling \\[default: no-memprofile]\n --logger [rich|print|none] The progress logger to use. \\[default:\n rich]\n --cache / --no-cache Use LLM cache. \\[default: cache]\n --skip-validation / --no-skip-validation\n Skip any preflight validation. Useful when\n running no LLM steps. \\[default: no-skip-\n validation]\n --output PATH Indexing pipeline output directory.\n Overrides storage.base_dir in the\n configuration file.\n
"}, {"location": "developing/#execute-the-indexing-engine", "title": "Execute the Indexing Engine", "text": "# Install Python dependencies.\npoetry install\n
"}, {"location": "developing/#executing-queries", "title": "Executing Queries", "text": "poetry run poe index <...args>\n
"}, {"location": "developing/#azurite", "title": "Azurite", "text": "poetry run poe query <...args>\n
Some unit and smoke tests use Azurite to emulate Azure resources. This can be started by running:
./scripts/start-azurite.sh\n
or by simply running
"}, {"location": "developing/#lifecycle-scripts", "title": "Lifecycle Scripts", "text": "azurite
in the terminal if already installed globally. See the Azurite documentation for more information about how to install and use Azurite.Our Python package utilizes Poetry to manage dependencies and poethepoet to manage build scripts.
Available scripts are:
"}, {"location": "developing/#troubleshooting", "title": "Troubleshooting", "text": ""}, {"location": "developing/#runtimeerror-llvm-config-failed-executing-please-point-llvm_config-to-the-path-for-llvm-config-when-running-poetry-install", "title": "\"RuntimeError: llvm-config failed executing, please point LLVM_CONFIG to the path for llvm-config\" when running poetry install", "text": "
poetry run poe index
- Run the Indexing CLIpoetry run poe query
- Run the Query CLIpoetry build
- This invokespoetry build
, which will build a wheel file and other distributable artifacts.poetry run poe test
- This will execute all tests.poetry run poe test_unit
- This will execute unit tests.poetry run poe test_integration
- This will execute integration tests.poetry run poe test_smoke
- This will execute smoke tests.poetry run poe check
- This will perform a suite of static checks across the package, including:- formatting
- documentation formatting
- linting
- security patterns
- type-checking
poetry run poe fix
- This will apply any available auto-fixes to the package. Usually this is just formatting fixes.poetry run poe fix_unsafe
- This will apply any available auto-fixes to the package, including those that may be unsafe.poetry run poe format
- Explicitly run the formatter across the package.Make sure llvm-9 and llvm-9-dev are installed:
sudo apt-get install llvm-9 llvm-9-dev
and then in your bashrc, add
"}, {"location": "developing/#numba_pymoduleh610-fatal-error-pythonh-no-such-file-or-directory-when-running-poetry-install", "title": "\"numba/_pymodule.h:6:10: fatal error: Python.h: No such file or directory\" when running poetry install", "text": "
export LLVM_CONFIG=/usr/bin/llvm-config-9
Make sure you have python3.10-dev installed or more generally
python<version>-dev
"}, {"location": "developing/#llm-call-constantly-exceeds-tpm-rpm-or-time-limits", "title": "LLM call constantly exceeds TPM, RPM or time limits", "text": "
sudo apt-get install python3.10-dev
"}, {"location": "get_started/", "title": "Getting Started", "text": ""}, {"location": "get_started/#requirements", "title": "Requirements", "text": "
GRAPHRAG_LLM_THREAD_COUNT
andGRAPHRAG_EMBEDDING_THREAD_COUNT
are both set to 50 by default. You can modify these values to reduce concurrency. Please refer to the Configuration DocumentsPython 3.10-3.12
To get started with the GraphRAG system, you have a few options:
\ud83d\udc49 Use the GraphRAG Accelerator solution \ud83d\udc49 Install from pypi. \ud83d\udc49 Use it from source
"}, {"location": "get_started/#quickstart", "title": "Quickstart", "text": "To get started with the GraphRAG system we recommend trying the Solution Accelerator package. This provides a user-friendly end-to-end experience with Azure resources.
"}, {"location": "get_started/#overview", "title": "Overview", "text": "The following is a simple end-to-end example for using the GraphRAG system. It shows how to use the system to index some text, and then use the indexed data to answer questions about the documents.
"}, {"location": "get_started/#install-graphrag", "title": "Install GraphRAG", "text": "pip install graphrag\n
The graphrag library includes a CLI for a no-code approach to getting started. Please review the full CLI documentation for further detail.
"}, {"location": "get_started/#running-the-indexer", "title": "Running the Indexer", "text": "We need to set up a data project and some initial configuration. First let's get a sample dataset ready:
mkdir -p ./ragtest/input\n
Get a copy of A Christmas Carol by Charles Dickens from a trusted source:
"}, {"location": "get_started/#set-up-your-workspace-variables", "title": "Set Up Your Workspace Variables", "text": "curl https://www.gutenberg.org/cache/epub/24022/pg24022.txt -o ./ragtest/input/book.txt\n
To initialize your workspace, first run the
graphrag init
command. Since we have already configured a directory named./ragtest
in the previous step, run the following command:graphrag init --root ./ragtest\n
This will create two files:
.env
andsettings.yaml
in the./ragtest
directory."}, {"location": "get_started/#openai-and-azure-openai", "title": "OpenAI and Azure OpenAI", "text": "
.env
contains the environment variables required to run the GraphRAG pipeline. If you inspect the file, you'll see a single environment variable defined,GRAPHRAG_API_KEY=<API_KEY>
. This is the API key for the OpenAI API or Azure OpenAI endpoint. You can replace this with your own API key. If you are using another form of authentication (i.e. managed identity), please delete this file.settings.yaml
contains the settings for the pipeline. You can modify this file to change the settings for the pipeline.If running in OpenAI mode, update the value of
"}, {"location": "get_started/#azure-openai", "title": "Azure OpenAI", "text": "GRAPHRAG_API_KEY
in the.env
file with your OpenAI API key.In addition, Azure OpenAI users should set the following variables in the settings.yaml file. To find the appropriate sections, just search for the
llm:
configuration, you should see two sections, one for the chat endpoint and one for the embeddings endpoint. Here is an example of how to configure the chat endpoint:type: azure_openai_chat # Or azure_openai_embedding for embeddings\napi_base: https://<instance>.openai.azure.com\napi_version: 2024-02-15-preview # You can customize this for other versions\ndeployment_name: <azure_model_deployment_name>\n
"}, {"location": "get_started/#running-the-indexing-pipeline", "title": "Running the Indexing pipeline", "text": "
- For more details about configuring GraphRAG, see the configuration documentation.
- To learn more about Initialization, refer to the Initialization documentation.
- For more details about using the CLI, refer to the CLI documentation.
Finally we'll run the pipeline!
graphrag index --root ./ragtest\n
This process will take some time to run. This depends on the size of your input data, what model you're using, and the text chunk size being used (these can be configured in your
"}, {"location": "get_started/#using-the-query-engine", "title": "Using the Query Engine", "text": ""}, {"location": "get_started/#running-the-query-engine", "title": "Running the Query Engine", "text": "settings.yml
file). Once the pipeline is complete, you should see a new folder called./ragtest/output
with a series of parquet files.Now let's ask some questions using this dataset.
Here is an example using Global search to ask a high-level question:
graphrag query \\\n--root ./ragtest \\\n--method global \\\n--query \"What are the top themes in this story?\"\n
Here is an example using Local search to ask a more specific question about a particular character:
graphrag query \\\n--root ./ragtest \\\n--method local \\\n--query \"Who is Scrooge and what are his main relationships?\"\n
Please refer to Query Engine docs for detailed information about how to leverage our Local and Global search mechanisms for extracting meaningful insights from data after the Indexer has wrapped up execution.
"}, {"location": "get_started/#visualizing-the-graph", "title": "Visualizing the Graph", "text": "Check out our visualization guide for a more interactive experience in debugging and exploring the knowledge graph.
"}, {"location": "visualization_guide/", "title": "Visualizing and Debugging Your Knowledge Graph", "text": "The following step-by-step guide walks through the process to visualize a knowledge graph after it's been constructed by graphrag. Note that some of the settings recommended below are based on our own experience of what works well. Feel free to change and explore other settings for a better visualization experience!
"}, {"location": "visualization_guide/#1-run-the-pipeline", "title": "1. Run the Pipeline", "text": "Before building an index, please review your
settings.yaml
configuration file and ensure that graphml snapshots is enabled.(Optional) To support other visualization tools and exploration, additional parameters can be enabled that provide access to vector embeddings.snapshots:\n graphml: true\n
After running the indexing pipeline over your data, there will be an output folder (defined by theembed_graph:\n enabled: true # will generate node2vec embeddings for nodes\numap:\n enabled: true # will generate UMAP embeddings for nodes\n
storage.base_dir
setting)."}, {"location": "visualization_guide/#2-locate-the-knowledge-graph", "title": "2. Locate the Knowledge Graph", "text": "
- Output Folder: Contains artifacts from the LLM\u2019s indexing pass.
In the output folder, look for a file named
"}, {"location": "visualization_guide/#3-open-the-graph-in-gephi", "title": "3. Open the Graph in Gephi", "text": "merged_graph.graphml
. graphml is a standard file format supported by many visualization tools. We recommend trying Gephi."}, {"location": "visualization_guide/#4-install-the-leiden-algorithm-plugin", "title": "4. Install the Leiden Algorithm Plugin", "text": "
- Install and open Gephi
- Navigate to the
output
folder containing the various parquet files.- Import the
merged_graph.graphml
file into Gephi. This will result in a fairly plain view of the undirected graph nodes and edges."}, {"location": "visualization_guide/#5-run-statistics", "title": "5. Run Statistics", "text": "
- Go to
Tools
->Plugins
.- Search for \"Leiden Algorithm\".
- Click
Install
and restart Gephi.
- In the
Statistics
tab on the right, clickRun
forAverage Degree
andLeiden Algorithm
."}, {"location": "visualization_guide/#6-color-the-graph-by-clusters", "title": "6. Color the Graph by Clusters", "text": "
- For the Leiden Algorithm, adjust the settings:
- Quality function: Modularity
- Resolution: 1
- Go to the
Appearance
pane in the upper left side of Gephi."}, {"location": "visualization_guide/#7-resize-nodes-by-degree-centrality", "title": "7. Resize Nodes by Degree Centrality", "text": "
- Select
Nodes
, thenPartition
, and click the color palette icon in the upper right.- Choose
Cluster
from the dropdown.- Click the
Palette...
hyperlink, thenGenerate...
.- Uncheck
Limit number of colors
, clickGenerate
, and thenOk
.- Click
Apply
to color the graph. This will color the graph based on the partitions discovered by Leiden."}, {"location": "visualization_guide/#8-layout-the-graph", "title": "8. Layout the Graph", "text": "
- In the
Appearance
pane in the upper left, selectNodes
->Ranking
- Select the
Sizing
icon in the upper right.- Choose
Degree
and set:- Min: 10
- Max: 150
- Click
Apply
.
- In the
Layout
tab in the lower left, selectOpenORD
."}, {"location": "visualization_guide/#9-run-forceatlas2", "title": "9. Run ForceAtlas2", "text": "
- Set
Liquid
andExpansion
stages to 50, and everything else to 0.- Click
Run
and monitor the progress.
- Select
Force Atlas 2
in the layout options."}, {"location": "visualization_guide/#10-add-text-labels-optional", "title": "10. Add Text Labels (Optional)", "text": "
- Adjust the settings:
- Scaling: 15
- Dissuade Hubs: checked
- LinLog mode: uncheck
- Prevent Overlap: checked
- Click
Run
and wait.- Press
Stop
when it looks like the graph nodes have settled and no longer change position significantly.
- Turn on text labels in the appropriate section.
- Configure and resize them as needed.
Your final graph should now be visually organized and ready for analysis!
"}, {"location": "config/env_vars/", "title": "Default Configuration Mode (using Env Vars)", "text": ""}, {"location": "config/env_vars/#text-embeddings-customization", "title": "Text-Embeddings Customization", "text": "By default, the GraphRAG indexer will only export embeddings required for our query methods. However, the model has embeddings defined for all plaintext fields, and these can be generated by setting the
GRAPHRAG_EMBEDDING_TARGET
environment variable toall
.If the embedding target is
"}, {"location": "config/env_vars/#embedded-fields", "title": "Embedded Fields", "text": "all
, and you want to only embed a subset of these fields, you may specify which embeddings to skip using theGRAPHRAG_EMBEDDING_SKIP
argument described below."}, {"location": "config/env_vars/#input-data", "title": "Input Data", "text": "
text_unit.text
document.text
entity.title
entity.description
relationship.description
community.title
community.summary
community.full_content
Our pipeline can ingest .csv or .txt data from an input folder. These files can be nested within subfolders. To configure how input data is handled, what fields are mapped over, and how timestamps are parsed, look for configuration values starting with
"}, {"location": "config/env_vars/#base-llm-settings", "title": "Base LLM Settings", "text": "GRAPHRAG_INPUT_
below. In general, CSV-based data provides the most customizability. Each CSV should at least contain atext
field (which can be mapped with environment variables), but it's helpful if they also havetitle
,timestamp
, andsource
fields. Additional fields can be included as well, which will land as extra fields on theDocument
table.These are the primary settings for configuring LLM connectivity.
Parameter Required? Description Type Default ValueGRAPHRAG_API_KEY
Yes for OpenAI. Optional for AOAI The API key. (Note:OPENAI_API_KEY is also used as a fallback). If not defined when using AOAI, managed identity will be used. |
str|
None`GRAPHRAG_API_BASE
For AOAI The API Base URLstr
None
GRAPHRAG_API_VERSION
For AOAI The AOAI API version.str
None
GRAPHRAG_API_ORGANIZATION
The AOAI organization.str
None
GRAPHRAG_API_PROXY
The AOAI proxy.str
None
"}, {"location": "config/env_vars/#text-generation-settings", "title": "Text Generation Settings", "text": "These settings control the text generation model used by the pipeline. Any settings with a fallback will use the base LLM settings, if available.
Parameter Required? Description Type Default ValueGRAPHRAG_LLM_TYPE
For AOAI The LLM operation type. Eitheropenai_chat
orazure_openai_chat
str
openai_chat
GRAPHRAG_LLM_DEPLOYMENT_NAME
For AOAI The AOAI model deployment name.str
None
GRAPHRAG_LLM_API_KEY
Yes (uses fallback) The API key. If not defined when using AOAI, managed identity will be used.str
None
GRAPHRAG_LLM_API_BASE
For AOAI (uses fallback) The API Base URLstr
None
GRAPHRAG_LLM_API_VERSION
For AOAI (uses fallback) The AOAI API version.str
None
GRAPHRAG_LLM_API_ORGANIZATION
For AOAI (uses fallback) The AOAI organization.str
None
GRAPHRAG_LLM_API_PROXY
The AOAI proxy.str
None
GRAPHRAG_LLM_MODEL
The LLM model.str
gpt-4-turbo-preview
GRAPHRAG_LLM_MAX_TOKENS
The maximum number of tokens.int
4000
GRAPHRAG_LLM_REQUEST_TIMEOUT
The maximum number of seconds to wait for a response from the chat client.int
180
GRAPHRAG_LLM_MODEL_SUPPORTS_JSON
Indicates whether the given model supports JSON output mode.True
to enable.str
None
GRAPHRAG_LLM_THREAD_COUNT
The number of threads to use for LLM parallelization.int
50GRAPHRAG_LLM_THREAD_STAGGER
The time to wait (in seconds) between starting each thread.float
0.3GRAPHRAG_LLM_CONCURRENT_REQUESTS
The number of concurrent requests to allow for the embedding client.int
25GRAPHRAG_LLM_TOKENS_PER_MINUTE
The number of tokens per minute to allow for the LLM client. 0 = Bypassint
0GRAPHRAG_LLM_REQUESTS_PER_MINUTE
The number of requests per minute to allow for the LLM client. 0 = Bypassint
0GRAPHRAG_LLM_MAX_RETRIES
The maximum number of retries to attempt when a request fails.int
10GRAPHRAG_LLM_MAX_RETRY_WAIT
The maximum number of seconds to wait between retries.int
10GRAPHRAG_LLM_SLEEP_ON_RATE_LIMIT_RECOMMENDATION
Whether to sleep on rate limit recommendation. (Azure Only)bool
True
GRAPHRAG_LLM_TEMPERATURE
The temperature to use generation.float
0GRAPHRAG_LLM_TOP_P
The top_p to use for sampling.float
1GRAPHRAG_LLM_N
The number of responses to generate.int
1"}, {"location": "config/env_vars/#text-embedding-settings", "title": "Text Embedding Settings", "text": "These settings control the text embedding model used by the pipeline. Any settings with a fallback will use the base LLM settings, if available.
Parameter Required ? Description Type DefaultGRAPHRAG_EMBEDDING_TYPE
For AOAI The embedding client to use. Eitheropenai_embedding
orazure_openai_embedding
str
openai_embedding
GRAPHRAG_EMBEDDING_DEPLOYMENT_NAME
For AOAI The AOAI deployment name.str
None
GRAPHRAG_EMBEDDING_API_KEY
Yes (uses fallback) The API key to use for the embedding client. If not defined when using AOAI, managed identity will be used.str
None
GRAPHRAG_EMBEDDING_API_BASE
For AOAI (uses fallback) The API base URL.str
None
GRAPHRAG_EMBEDDING_API_VERSION
For AOAI (uses fallback) The AOAI API version to use for the embedding client.str
None
GRAPHRAG_EMBEDDING_API_ORGANIZATION
For AOAI (uses fallback) The AOAI organization to use for the embedding client.str
None
GRAPHRAG_EMBEDDING_API_PROXY
The AOAI proxy to use for the embedding client.str
None
GRAPHRAG_EMBEDDING_MODEL
The model to use for the embedding client.str
text-embedding-3-small
GRAPHRAG_EMBEDDING_BATCH_SIZE
The number of texts to embed at once. (Azure limit is 16)int
16GRAPHRAG_EMBEDDING_BATCH_MAX_TOKENS
The maximum tokens per batch (Azure limit is 8191)int
8191GRAPHRAG_EMBEDDING_TARGET
The target fields to embed. Eitherrequired
orall
.str
required
GRAPHRAG_EMBEDDING_SKIP
A comma-separated list of fields to skip embeddings for . (e.g. 'relationship.description')str
None
GRAPHRAG_EMBEDDING_THREAD_COUNT
The number of threads to use for parallelization for embeddings.int
GRAPHRAG_EMBEDDING_THREAD_STAGGER
The time to wait (in seconds) between starting each thread for embeddings.float
50GRAPHRAG_EMBEDDING_CONCURRENT_REQUESTS
The number of concurrent requests to allow for the embedding client.int
25GRAPHRAG_EMBEDDING_TOKENS_PER_MINUTE
The number of tokens per minute to allow for the embedding client. 0 = Bypassint
0GRAPHRAG_EMBEDDING_REQUESTS_PER_MINUTE
The number of requests per minute to allow for the embedding client. 0 = Bypassint
0GRAPHRAG_EMBEDDING_MAX_RETRIES
The maximum number of retries to attempt when a request fails.int
10GRAPHRAG_EMBEDDING_MAX_RETRY_WAIT
The maximum number of seconds to wait between retries.int
10GRAPHRAG_EMBEDDING_SLEEP_ON_RATE_LIMIT_RECOMMENDATION
Whether to sleep on rate limit recommendation. (Azure Only)bool
True
"}, {"location": "config/env_vars/#input-settings", "title": "Input Settings", "text": "These settings control the data input used by the pipeline. Any settings with a fallback will use the base LLM settings, if available.
"}, {"location": "config/env_vars/#plaintext-input-data-graphrag_input_file_typetext", "title": "Plaintext Input Data (GRAPHRAG_INPUT_FILE_TYPE
=text)", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_INPUT_FILE_PATTERN
The file pattern regexp to use when reading input files from the input directory.str
optional.*\\.txt$
"}, {"location": "config/env_vars/#csv-input-data-graphrag_input_file_typecsv", "title": "CSV Input Data (GRAPHRAG_INPUT_FILE_TYPE
=csv)", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_INPUT_TYPE
The input storage type to use when reading files. (file
orblob
)str
optionalfile
GRAPHRAG_INPUT_FILE_PATTERN
The file pattern regexp to use when reading input files from the input directory.str
optional.*\\.txt$
GRAPHRAG_INPUT_SOURCE_COLUMN
The 'source' column to use when reading CSV input files.str
optionalsource
GRAPHRAG_INPUT_TIMESTAMP_COLUMN
The 'timestamp' column to use when reading CSV input files.str
optionalNone
GRAPHRAG_INPUT_TIMESTAMP_FORMAT
The timestamp format to use when parsing timestamps in the timestamp column.str
optionalNone
GRAPHRAG_INPUT_TEXT_COLUMN
The 'text' column to use when reading CSV input files.str
optionaltext
GRAPHRAG_INPUT_DOCUMENT_ATTRIBUTE_COLUMNS
A list of CSV columns, comma-separated, to incorporate as document fields.str
optionalid
GRAPHRAG_INPUT_TITLE_COLUMN
The 'title' column to use when reading CSV input files.str
optionaltitle
GRAPHRAG_INPUT_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optionalNone
GRAPHRAG_INPUT_CONNECTION_STRING
The connection string to use when reading CSV input files from Azure Blob Storage.str
optionalNone
GRAPHRAG_INPUT_CONTAINER_NAME
The container name to use when reading CSV input files from Azure Blob Storage.str
optionalNone
GRAPHRAG_INPUT_BASE_DIR
The base directory to read input files from.str
optionalNone
"}, {"location": "config/env_vars/#data-mapping-settings", "title": "Data Mapping Settings", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_INPUT_FILE_TYPE
The type of input data,csv
ortext
str
optionaltext
GRAPHRAG_INPUT_ENCODING
The encoding to apply when reading CSV/text input files.str
optionalutf-8
"}, {"location": "config/env_vars/#data-chunking", "title": "Data Chunking", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_CHUNK_SIZE
The chunk size in tokens for text-chunk analysis windows.str
optional 1200GRAPHRAG_CHUNK_OVERLAP
The chunk overlap in tokens for text-chunk analysis windows.str
optional 100GRAPHRAG_CHUNK_BY_COLUMNS
A comma-separated list of document attributes to groupby when performing TextUnit chunking.str
optionalid
GRAPHRAG_CHUNK_ENCODING_MODEL
The encoding model to use for chunking.str
optional The top-level encoding model."}, {"location": "config/env_vars/#prompting-overrides", "title": "Prompting Overrides", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_ENTITY_EXTRACTION_PROMPT_FILE
The path (relative to the root) of an entity extraction prompt template text file.str
optionalNone
GRAPHRAG_ENTITY_EXTRACTION_MAX_GLEANINGS
The maximum number of redrives (gleanings) to invoke when extracting entities in a loop.int
optional 1GRAPHRAG_ENTITY_EXTRACTION_ENTITY_TYPES
A comma-separated list of entity types to extract.str
optionalorganization,person,event,geo
GRAPHRAG_ENTITY_EXTRACTION_ENCODING_MODEL
The encoding model to use for entity extraction.str
optional The top-level encoding model.GRAPHRAG_SUMMARIZE_DESCRIPTIONS_PROMPT_FILE
The path (relative to the root) of an description summarization prompt template text file.str
optionalNone
GRAPHRAG_SUMMARIZE_DESCRIPTIONS_MAX_LENGTH
The maximum number of tokens to generate per description summarization.int
optional 500GRAPHRAG_CLAIM_EXTRACTION_ENABLED
Whether claim extraction is enabled for this pipeline.bool
optionalFalse
GRAPHRAG_CLAIM_EXTRACTION_DESCRIPTION
The claim_description prompting argument to utilize.string
optional \"Any claims or facts that could be relevant to threat analysis.\"GRAPHRAG_CLAIM_EXTRACTION_PROMPT_FILE
The claim extraction prompt to utilize.string
optionalNone
GRAPHRAG_CLAIM_EXTRACTION_MAX_GLEANINGS
The maximum number of redrives (gleanings) to invoke when extracting claims in a loop.int
optional 1GRAPHRAG_CLAIM_EXTRACTION_ENCODING_MODEL
The encoding model to use for claim extraction.str
optional The top-level encoding modelGRAPHRAG_COMMUNITY_REPORTS_PROMPT_FILE
The community reports extraction prompt to utilize.string
optionalNone
GRAPHRAG_COMMUNITY_REPORTS_MAX_LENGTH
The maximum number of tokens to generate per community reports.int
optional 1500"}, {"location": "config/env_vars/#storage", "title": "Storage", "text": "This section controls the storage mechanism used by the pipeline used for exporting output tables.
Parameter Description Type Required or Optional DefaultGRAPHRAG_STORAGE_TYPE
The type of storage to use. Options arefile
,memory
, orblob
str
optionalfile
GRAPHRAG_STORAGE_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optional NoneGRAPHRAG_STORAGE_CONNECTION_STRING
The Azure Storage connection string to use when inblob
mode.str
optional NoneGRAPHRAG_STORAGE_CONTAINER_NAME
The Azure Storage container name to use when inblob
mode.str
optional NoneGRAPHRAG_STORAGE_BASE_DIR
The base path to data outputs outputs.str
optional None"}, {"location": "config/env_vars/#cache", "title": "Cache", "text": "This section controls the cache mechanism used by the pipeline. This is used to cache LLM invocation results.
Parameter Description Type Required or Optional DefaultGRAPHRAG_CACHE_TYPE
The type of cache to use. Options arefile
,memory
,none
orblob
str
optionalfile
GRAPHRAG_CACHE_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optional NoneGRAPHRAG_CACHE_CONNECTION_STRING
The Azure Storage connection string to use when inblob
mode.str
optional NoneGRAPHRAG_CACHE_CONTAINER_NAME
The Azure Storage container name to use when inblob
mode.str
optional NoneGRAPHRAG_CACHE_BASE_DIR
The base path to the cache files.str
optional None"}, {"location": "config/env_vars/#reporting", "title": "Reporting", "text": "This section controls the reporting mechanism used by the pipeline, for common events and error messages. The default is to write reports to a file in the output directory. However, you can also choose to write reports to the console or to an Azure Blob Storage container.
Parameter Description Type Required or Optional DefaultGRAPHRAG_REPORTING_TYPE
The type of reporter to use. Options arefile
,console
, orblob
str
optionalfile
GRAPHRAG_REPORTING_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optional NoneGRAPHRAG_REPORTING_CONNECTION_STRING
The Azure Storage connection string to use when inblob
mode.str
optional NoneGRAPHRAG_REPORTING_CONTAINER_NAME
The Azure Storage container name to use when inblob
mode.str
optional NoneGRAPHRAG_REPORTING_BASE_DIR
The base path to the reporting outputs.str
optional None"}, {"location": "config/env_vars/#node2vec-parameters", "title": "Node2Vec Parameters", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_NODE2VEC_ENABLED
Whether to enable Node2Vecbool
optional FalseGRAPHRAG_NODE2VEC_NUM_WALKS
The Node2Vec number of walks to performint
optional 10GRAPHRAG_NODE2VEC_WALK_LENGTH
The Node2Vec walk lengthint
optional 40GRAPHRAG_NODE2VEC_WINDOW_SIZE
The Node2Vec window sizeint
optional 2GRAPHRAG_NODE2VEC_ITERATIONS
The number of iterations to run node2vecint
optional 3GRAPHRAG_NODE2VEC_RANDOM_SEED
The random seed to use for node2vecint
optional 597832"}, {"location": "config/env_vars/#data-snapshotting", "title": "Data Snapshotting", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_SNAPSHOT_EMBEDDINGS
Whether to enable embeddings snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_GRAPHML
Whether to enable GraphML snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_RAW_ENTITIES
Whether to enable raw entity snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_TOP_LEVEL_NODES
Whether to enable top-level node snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_TRANSIENT
Whether to enable transient table snapshots.bool
optional False"}, {"location": "config/env_vars/#miscellaneous-settings", "title": "Miscellaneous Settings", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_ASYNC_MODE
Which async mode to use. Eitherasyncio
orthreaded
.str
optionalasyncio
GRAPHRAG_ENCODING_MODEL
The text encoding model, used in tiktoken, to encode text.str
optionalcl100k_base
GRAPHRAG_MAX_CLUSTER_SIZE
The maximum number of entities to include in a single Leiden cluster.int
optional 10GRAPHRAG_SKIP_WORKFLOWS
A comma-separated list of workflow names to skip.str
optionalNone
GRAPHRAG_UMAP_ENABLED
Whether to enable UMAP layoutsbool
optional False"}, {"location": "config/init/", "title": "Configuring GraphRAG Indexing", "text": "To start using GraphRAG, you must generate a configuration file. The
"}, {"location": "config/init/#usage", "title": "Usage", "text": "init
command is the easiest way to get started. It will create a.env
andsettings.yaml
files in the specified directory with the necessary configuration settings. It will also output the default LLM prompts used by GraphRAG."}, {"location": "config/init/#options", "title": "Options", "text": "graphrag init [--root PATH]\n
"}, {"location": "config/init/#example", "title": "Example", "text": "
--root PATH
- The project root directory to initialize graphrag at. Default is the current directory."}, {"location": "config/init/#output", "title": "Output", "text": "graphrag init --root ./ragtest\n
The
init
command will create the following files in the specified directory:"}, {"location": "config/init/#next-steps", "title": "Next Steps", "text": "
settings.yaml
- The configuration settings file. This file contains the configuration settings for GraphRAG..env
- The environment variables file. These are referenced in thesettings.yaml
file.prompts/
- The LLM prompts folder. This contains the default prompts used by GraphRAG, you can modify them or run the Auto Prompt Tuning command to generate new prompts adapted to your data.After initializing your workspace, you can either run the Prompt Tuning command to adapt the prompts to your data or even start running the Indexing Pipeline to index your data. For more information on configuring GraphRAG, see the Configuration documentation.
"}, {"location": "config/overview/", "title": "Configuring GraphRAG Indexing", "text": "The GraphRAG system is highly configurable. This page provides an overview of the configuration options available for the GraphRAG indexing engine.
"}, {"location": "config/overview/#default-configuration-mode", "title": "Default Configuration Mode", "text": "The default configuration mode is the simplest way to get started with the GraphRAG system. It is designed to work out-of-the-box with minimal configuration. The primary configuration sections for the Indexing Engine pipelines are described below. The main ways to set up GraphRAG in Default Configuration mode are via:
"}, {"location": "config/yaml/", "title": "Default Configuration Mode (using YAML/JSON)", "text": "
- Init command (recommended)
- Using YAML for deeper control
- Purely using environment variables
The default configuration mode may be configured by using a
settings.yml
orsettings.json
file in the data project root. If a.env
file is present along with this config file, then it will be loaded, and the environment variables defined therein will be available for token replacements in your configuration document using${ENV_VAR}
syntax. We initialize with YML by default ingraphrag init
but you may use the equivalent JSON form if preferred.Many of these config values have defaults. Rather than replicate them here, please refer to the constants in the code directly.
For example:
"}, {"location": "config/yaml/#config-sections", "title": "Config Sections", "text": ""}, {"location": "config/yaml/#indexing", "title": "Indexing", "text": ""}, {"location": "config/yaml/#llm", "title": "llm", "text": "# .env\nGRAPHRAG_API_KEY=some_api_key\n\n# settings.yml\nllm: \n api_key: ${GRAPHRAG_API_KEY}\n
This is the base LLM configuration section. Other steps may override this configuration with their own LLM configuration.
"}, {"location": "config/yaml/#fields", "title": "Fields", "text": ""}, {"location": "config/yaml/#parallelization", "title": "parallelization", "text": ""}, {"location": "config/yaml/#fields_1", "title": "Fields", "text": "
api_key
str - The OpenAI API key to use.type
openai_chat|azure_openai_chat|openai_embedding|azure_openai_embedding - The type of LLM to use.model
str - The model name.max_tokens
int - The maximum number of output tokens.request_timeout
float - The per-request timeout.api_base
str - The API base url to use.api_version
str - The API versionorganization
str - The client organization.proxy
str - The proxy URL to use.audience
str - (Azure OpenAI only) The URI of the target Azure resource/service for which a managed identity token is requested. Used ifapi_key
is not defined. Default=https://cognitiveservices.azure.com/.default
deployment_name
str - The deployment name to use (Azure).model_supports_json
bool - Whether the model supports JSON-mode output.tokens_per_minute
int - Set a leaky-bucket throttle on tokens-per-minute.requests_per_minute
int - Set a leaky-bucket throttle on requests-per-minute.max_retries
int - The maximum number of retries to use.max_retry_wait
float - The maximum backoff time.sleep_on_rate_limit_recommendation
bool - Whether to adhere to sleep recommendations (Azure).concurrent_requests
int The number of open requests to allow at once.temperature
float - The temperature to use.top_p
float - The top-p value to use.n
int - The number of completions to generate."}, {"location": "config/yaml/#async_mode", "title": "async_mode", "text": "
stagger
float - The threading stagger value.num_threads
int - The maximum number of work threads.asyncio|threaded The async mode to use. Either
"}, {"location": "config/yaml/#embeddings", "title": "embeddings", "text": ""}, {"location": "config/yaml/#fields_2", "title": "Fields", "text": "asyncio
or `threaded."}, {"location": "config/yaml/#input", "title": "input", "text": ""}, {"location": "config/yaml/#fields_3", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)batch_size
int - The maximum batch size to use.batch_max_tokens
int - The maximum batch # of tokens.target
required|all|none - Determines which set of embeddings to export.skip
list[str] - Which embeddings to skip. Only useful if target=all to customize the list.vector_store
dict - The vector store to use. Configured for lancedb by default.
type
str -lancedb
orazure_ai_search
. Default=lancedb
db_uri
str (only for lancedb) - The database uri. Default=storage.base_dir/lancedb
url
str (only for AI Search) - AI Search endpointapi_key
str (optional - only for AI Search) - The AI Search api key to use.audience
str (only for AI Search) - Audience for managed identity token if managed identity authentication is used.overwrite
bool (only used at index creation time) - Overwrite collection if it exist. Default=True
container_name
str - The name of a vector container. This stores all indexes (tables) for a given dataset ingest. Default=default
strategy
dict - Fully override the text-embedding strategy."}, {"location": "config/yaml/#chunks", "title": "chunks", "text": ""}, {"location": "config/yaml/#fields_4", "title": "Fields", "text": "
type
file|blob - The input type to use. Default=file
file_type
text|csv - The type of input data to load. Eithertext
orcsv
. Default istext
base_dir
str - The base directory to read input from, relative to the root.connection_string
str - (blob only) The Azure Storage connection string.storage_account_blob_url
str - The storage account blob URL to use.container_name
str - (blob only) The Azure Storage container name.file_encoding
str - The encoding of the input file. Default isutf-8
file_pattern
str - A regex to match input files. Default is.*\\.csv$
if in csv mode and.*\\.txt$
if in text mode.file_filter
dict - Key/value pairs to filter. Default is None.source_column
str - (CSV Mode Only) The source column name.timestamp_column
str - (CSV Mode Only) The timestamp column name.timestamp_format
str - (CSV Mode Only) The source format.text_column
str - (CSV Mode Only) The text column name.title_column
str - (CSV Mode Only) The title column name.document_attribute_columns
list[str] - (CSV Mode Only) The additional document attributes to include."}, {"location": "config/yaml/#cache", "title": "cache", "text": ""}, {"location": "config/yaml/#fields_5", "title": "Fields", "text": "
size
int - The max chunk size in tokens.overlap
int - The chunk overlap in tokens.group_by_columns
list[str] - group documents by fields before chunking.encoding_model
str - The text encoding model to use. Default is to use the top-level encoding model.strategy
dict - Fully override the chunking strategy."}, {"location": "config/yaml/#storage", "title": "storage", "text": ""}, {"location": "config/yaml/#fields_6", "title": "Fields", "text": "
type
file|memory|none|blob - The cache type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write cache to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#update_index_storage", "title": "update_index_storage", "text": ""}, {"location": "config/yaml/#fields_7", "title": "Fields", "text": "
type
file|memory|blob - The storage type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write output artifacts to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#reporting", "title": "reporting", "text": ""}, {"location": "config/yaml/#fields_8", "title": "Fields", "text": "
type
file|memory|blob - The storage type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write output artifacts to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#entity_extraction", "title": "entity_extraction", "text": ""}, {"location": "config/yaml/#fields_9", "title": "Fields", "text": "
type
file|console|blob - The reporting type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write reports to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#summarize_descriptions", "title": "summarize_descriptions", "text": ""}, {"location": "config/yaml/#fields_10", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.entity_types
list[str] - The entity types to identify.max_gleanings
int - The maximum number of gleaning cycles to use.encoding_model
str - The text encoding model to use. By default, this will use the top-level encoding model.strategy
dict - Fully override the entity extraction strategy."}, {"location": "config/yaml/#claim_extraction", "title": "claim_extraction", "text": ""}, {"location": "config/yaml/#fields_11", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.max_length
int - The maximum number of output tokens per summarization.strategy
dict - Fully override the summarize description strategy."}, {"location": "config/yaml/#community_reports", "title": "community_reports", "text": ""}, {"location": "config/yaml/#fields_12", "title": "Fields", "text": "
enabled
bool - Whether to enable claim extraction. Off by default, because claim prompts really need user tuning.llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.description
str - Describes the types of claims we want to extract.max_gleanings
int - The maximum number of gleaning cycles to use.encoding_model
str - The text encoding model to use. By default, this will use the top-level encoding model.strategy
dict - Fully override the claim extraction strategy."}, {"location": "config/yaml/#cluster_graph", "title": "cluster_graph", "text": ""}, {"location": "config/yaml/#fields_13", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.max_length
int - The maximum number of output tokens per report.max_input_length
int - The maximum number of input tokens to use when generating reports.strategy
dict - Fully override the community reports strategy."}, {"location": "config/yaml/#embed_graph", "title": "embed_graph", "text": ""}, {"location": "config/yaml/#fields_14", "title": "Fields", "text": "
max_cluster_size
int - The maximum cluster size to export.strategy
dict - Fully override the cluster_graph strategy."}, {"location": "config/yaml/#umap", "title": "umap", "text": ""}, {"location": "config/yaml/#fields_15", "title": "Fields", "text": "
enabled
bool - Whether to enable graph embeddings.num_walks
int - The node2vec number of walks.walk_length
int - The node2vec walk length.window_size
int - The node2vec window size.iterations
int - The node2vec number of iterations.random_seed
int - The node2vec random seed.strategy
dict - Fully override the embed graph strategy."}, {"location": "config/yaml/#snapshots", "title": "snapshots", "text": ""}, {"location": "config/yaml/#fields_16", "title": "Fields", "text": "
enabled
bool - Whether to enable UMAP layouts."}, {"location": "config/yaml/#encoding_model", "title": "encoding_model", "text": "
embeddings
bool - Export embeddings snapshots to parquet.graphml
bool - Export graph snapshots to GraphML.transient
bool - Export transient workflow tables snapshots to parquet.str - The text encoding model to use. Default=
"}, {"location": "config/yaml/#skip_workflows", "title": "skip_workflows", "text": "cl100k_base
.list[str] - Which workflow names to skip.
"}, {"location": "config/yaml/#query", "title": "Query", "text": ""}, {"location": "config/yaml/#local_search", "title": "local_search", "text": ""}, {"location": "config/yaml/#fields_17", "title": "Fields", "text": ""}, {"location": "config/yaml/#global_search", "title": "global_search", "text": ""}, {"location": "config/yaml/#fields_18", "title": "Fields", "text": "
prompt
str - The prompt file to use.text_unit_prop
float - The text unit proportion.community_prop
float - The community proportion.conversation_history_max_turns
int - The conversation history maximum turns.top_k_entities
int - The top k mapped entities.top_k_relationships
int - The top k mapped relations.temperature
float | None - The temperature to use for token generation.top_p
float | None - The top-p value to use for token generation.n
int | None - The number of completions to generate.max_tokens
int - The maximum tokens.llm_max_tokens
int - The LLM maximum tokens."}, {"location": "config/yaml/#drift_search", "title": "drift_search", "text": ""}, {"location": "config/yaml/#fields_19", "title": "Fields", "text": "
map_prompt
str - The mapper prompt file to use.reduce_prompt
str - The reducer prompt file to use.knowledge_prompt
str - The knowledge prompt file to use.map_prompt
str | None - The global search mapper prompt to use.reduce_prompt
str | None - The global search reducer to use.knowledge_prompt
str | None - The global search general prompt to use.temperature
float | None - The temperature to use for token generation.top_p
float | None - The top-p value to use for token generation.n
int | None - The number of completions to generate.max_tokens
int - The maximum context size in tokens.data_max_tokens
int - The data llm maximum tokens.map_max_tokens
int - The map llm maximum tokens.reduce_max_tokens
int - The reduce llm maximum tokens.concurrency
int - The number of concurrent requests.dynamic_search_llm
str - LLM model to use for dynamic community selection.dynamic_search_threshold
int - Rating threshold in include a community report.dynamic_search_keep_parent
bool - Keep parent community if any of the child communities are relevant.dynamic_search_num_repeats
int - Number of times to rate the same community report.dynamic_search_use_summary
bool - Use community summary instead of full_context.dynamic_search_concurrent_coroutines
int - Number of concurrent coroutines to rate community reports.dynamic_search_max_level
int - The maximum level of community hierarchy to consider if none of the processed communities are relevant."}, {"location": "data/operation_dulce/ABOUT/", "title": "About", "text": "
prompt
str - The prompt file to use.temperature
float - The temperature to use for token generation.\",top_p
float - The top-p value to use for token generation.n
int - The number of completions to generate.max_tokens
int - The maximum context size in tokens.data_max_tokens
int - The data llm maximum tokens.concurrency
int - The number of concurrent requests.drift_k_followups
int - The number of top global results to retrieve.primer_folds
int - The number of folds for search priming.primer_llm_max_tokens
int - The maximum number of tokens for the LLM in primer.n_depth
int - The number of drift search steps to take.local_search_text_unit_prop
float - The proportion of search dedicated to text units.local_search_community_prop
float - The proportion of search dedicated to community properties.local_search_top_k_mapped_entities
int - The number of top K entities to map during local search.local_search_top_k_relationships
int - The number of top K relationships to map during local search.local_search_max_data_tokens
int - The maximum context size in tokens for local search.local_search_temperature
float - The temperature to use for token generation in local search.local_search_top_p
float - The top-p value to use for token generation in local search.local_search_n
int - The number of completions to generate in local search.local_search_llm_max_gen_tokens
int - The maximum number of generated tokens for the LLM in local search.This document (Operation Dulce) is an AI-generated science fiction novella, included here for the purposes of integration testing.
"}, {"location": "index/architecture/", "title": "Indexing Architecture", "text": ""}, {"location": "index/architecture/#key-concepts", "title": "Key Concepts", "text": ""}, {"location": "index/architecture/#knowledge-model", "title": "Knowledge Model", "text": "In order to support the GraphRAG system, the outputs of the indexing engine (in the Default Configuration Mode) are aligned to a knowledge model we call the GraphRAG Knowledge Model. This model is designed to be an abstraction over the underlying data storage technology, and to provide a common interface for the GraphRAG system to interact with. In normal use-cases the outputs of the GraphRAG Indexer would be loaded into a database system, and the GraphRAG's Query Engine would interact with the database using the knowledge model data-store types.
"}, {"location": "index/architecture/#datashaper-workflows", "title": "DataShaper Workflows", "text": "GraphRAG's Indexing Pipeline is built on top of our open-source library, DataShaper. DataShaper is a data processing library that allows users to declaratively express data pipelines, schemas, and related assets using well-defined schemas. DataShaper has implementations in JavaScript and Python, and is designed to be extensible to other languages.
One of the core resource types within DataShaper is a Workflow. Workflows are expressed as sequences of steps, which we call verbs. Each step has a verb name and a configuration object. In DataShaper, these verbs model relational concepts such as SELECT, DROP, JOIN, etc.. Each verb transforms an input data table, and that table is passed down the pipeline.
"}, {"location": "index/architecture/#llm-based-workflow-steps", "title": "LLM-based Workflow Steps", "text": "---\ntitle: Sample Workflow\n---\nflowchart LR\n input[Input Table] --> select[SELECT] --> join[JOIN] --> binarize[BINARIZE] --> output[Output Table]
GraphRAG's Indexing Pipeline implements a handful of custom verbs on top of the standard, relational verbs that our DataShaper library provides. These verbs give us the ability to augment text documents with rich, structured data using the power of LLMs such as GPT-4. We utilize these verbs in our standard workflow to extract entities, relationships, claims, community structures, and community reports and summaries. This behavior is customizable and can be extended to support many kinds of AI-based data enrichment and extraction tasks.
"}, {"location": "index/architecture/#workflow-graphs", "title": "Workflow Graphs", "text": "Because of the complexity of our data indexing tasks, we needed to be able to express our data pipeline as series of multiple, interdependent workflows. In the GraphRAG Indexing Pipeline, each workflow may define dependencies on other workflows, effectively forming a directed acyclic graph (DAG) of workflows, which is then used to schedule processing.
"}, {"location": "index/architecture/#dataframe-message-format", "title": "Dataframe Message Format", "text": "---\ntitle: Sample Workflow DAG\n---\nstateDiagram-v2\n [*] --> Prepare\n Prepare --> Chunk\n Chunk --> ExtractGraph\n Chunk --> EmbedDocuments\n ExtractGraph --> GenerateReports\n ExtractGraph --> EmbedEntities\n ExtractGraph --> EmbedGraph
The primary unit of communication between workflows, and between workflow steps is an instance of
"}, {"location": "index/architecture/#llm-caching", "title": "LLM Caching", "text": "pandas.DataFrame
. Although side-effects are possible, our goal is to be data-centric and table-centric in our approach to data processing. This allows us to easily reason about our data, and to leverage the power of dataframe-based ecosystems. Our underlying dataframe technology may change over time, but our primary goal is to support the DataShaper workflow schema while retaining single-machine ease of use and developer ergonomics.The GraphRAG library was designed with LLM interactions in mind, and a common setback when working with LLM APIs is various errors due to network latency, throttling, etc.. Because of these potential error cases, we've added a cache layer around LLM interactions. When completion requests are made using the same input set (prompt and tuning parameters), we return a cached result if one exists. This allows our indexer to be more resilient to network issues, to act idempotently, and to provide a more efficient end-user experience.
"}, {"location": "index/default_dataflow/", "title": "Indexing Dataflow", "text": ""}, {"location": "index/default_dataflow/#the-graphrag-knowledge-model", "title": "The GraphRAG Knowledge Model", "text": "The knowledge model is a specification for data outputs that conform to our data-model definition. You can find these definitions in the python/graphrag/graphrag/model folder within the GraphRAG repository. The following entity types are provided. The fields here represent the fields that are text-embedded by default.
"}, {"location": "index/default_dataflow/#the-default-configuration-workflow", "title": "The Default Configuration Workflow", "text": "
Document
- An input document into the system. These either represent individual rows in a CSV or individual .txt file.TextUnit
- A chunk of text to analyze. The size of these chunks, their overlap, and whether they adhere to any data boundaries may be configured below. A common use case is to setCHUNK_BY_COLUMNS
toid
so that there is a 1-to-many relationship between documents and TextUnits instead of a many-to-many.Entity
- An entity extracted from a TextUnit. These represent people, places, events, or some other entity-model that you provide.Relationship
- A relationship between two entities. These are generated from the covariates.Covariate
- Extracted claim information, which contains statements about entities which may be time-bound.Community
- Once the graph of entities and relationships is built, we perform hierarchical community detection on them to create a clustering structure.Community Report
- The contents of each community are summarized into a generated report, useful for human reading and downstream search.Node
- This table contains layout information for rendered graph-views of the Entities and Documents which have been embedded and clustered.Let's take a look at how the default-configuration workflow transforms text documents into the GraphRAG Knowledge Model. This page gives a general overview of the major steps in this process. To fully configure this workflow, check out the configuration documentation.
"}, {"location": "index/default_dataflow/#phase-1-compose-textunits", "title": "Phase 1: Compose TextUnits", "text": "---\ntitle: Dataflow Overview\n---\nflowchart TB\n subgraph phase1[Phase 1: Compose TextUnits]\n documents[Documents] --> chunk[Chunk]\n chunk --> embed[Embed] --> textUnits[Text Units]\n end\n subgraph phase2[Phase 2: Graph Extraction]\n textUnits --> graph_extract[Entity & Relationship Extraction]\n graph_extract --> graph_summarize[Entity & Relationship Summarization]\n graph_summarize --> claim_extraction[Claim Extraction]\n claim_extraction --> graph_outputs[Graph Tables]\n end\n subgraph phase3[Phase 3: Graph Augmentation]\n graph_outputs --> community_detect[Community Detection]\n community_detect --> graph_embed[Graph Embedding]\n graph_embed --> augmented_graph[Augmented Graph Tables]\n end\n subgraph phase4[Phase 4: Community Summarization]\n augmented_graph --> summarized_communities[Community Summarization]\n summarized_communities --> embed_communities[Community Embedding]\n embed_communities --> community_outputs[Community Tables]\n end\n subgraph phase5[Phase 5: Document Processing]\n documents --> link_to_text_units[Link to TextUnits]\n textUnits --> link_to_text_units\n link_to_text_units --> embed_documents[Document Embedding]\n embed_documents --> document_graph[Document Graph Creation]\n document_graph --> document_outputs[Document Tables]\n end\n subgraph phase6[Phase 6: Network Visualization]\n document_outputs --> umap_docs[Umap Documents]\n augmented_graph --> umap_entities[Umap Entities]\n umap_docs --> combine_nodes[Nodes Table]\n umap_entities --> combine_nodes\n end
The first phase of the default-configuration workflow is to transform input documents into TextUnits. A TextUnit is a chunk of text that is used for our graph extraction techniques. They are also used as source-references by extracted knowledge items in order to empower breadcrumbs and provenance by concepts back to their original source tex.
The chunk size (counted in tokens), is user-configurable. By default this is set to 300 tokens, although we've had positive experience with 1200-token chunks using a single \"glean\" step. (A \"glean\" step is a follow-on extraction). Larger chunks result in lower-fidelity output and less meaningful reference texts; however, using larger chunks can result in much faster processing time.
The group-by configuration is also user-configurable. By default, we align our chunks to document boundaries, meaning that there is a strict 1-to-many relationship between Documents and TextUnits. In rare cases, this can be turned into a many-to-many relationship. This is useful when the documents are very short and we need several of them to compose a meaningful analysis unit (e.g. Tweets or a chat log)
Each of these text-units are text-embedded and passed into the next phase of the pipeline.
"}, {"location": "index/default_dataflow/#phase-2-graph-extraction", "title": "Phase 2: Graph Extraction", "text": "---\ntitle: Documents into Text Chunks\n---\nflowchart LR\n doc1[Document 1] --> tu1[TextUnit 1]\n doc1 --> tu2[TextUnit 2]\n doc2[Document 2] --> tu3[TextUnit 3]\n doc2 --> tu4[TextUnit 4]\n
In this phase, we analyze each text unit and extract our graph primitives: Entities, Relationships, and Claims. Entities and Relationships are extracted at once in our entity_extract verb, and claims are extracted in our claim_extract verb. Results are then combined and passed into following phases of the pipeline.
"}, {"location": "index/default_dataflow/#entity-relationship-extraction", "title": "Entity & Relationship Extraction", "text": "---\ntitle: Graph Extraction\n---\nflowchart LR\n tu[TextUnit] --> ge[Graph Extraction] --> gs[Graph Summarization]\n tu --> ce[Claim Extraction]
In this first step of graph extraction, we process each text-unit in order to extract entities and relationships out of the raw text using the LLM. The output of this step is a subgraph-per-TextUnit containing a list of entities with a name, type, and description, and a list of relationships with a source, target, and description.
These subgraphs are merged together - any entities with the same name and type are merged by creating an array of their descriptions. Similarly, any relationships with the same source and target are merged by creating an array of their descriptions.
"}, {"location": "index/default_dataflow/#entity-relationship-summarization", "title": "Entity & Relationship Summarization", "text": "Now that we have a graph of entities and relationships, each with a list of descriptions, we can summarize these lists into a single description per entity and relationship. This is done by asking the LLM for a short summary that captures all of the distinct information from each description. This allows all of our entities and relationships to have a single concise description.
"}, {"location": "index/default_dataflow/#claim-extraction-emission", "title": "Claim Extraction & Emission", "text": "Finally, as an independent workflow, we extract claims from the source TextUnits. These claims represent positive factual statements with an evaluated status and time-bounds. These get exported as a primary artifact called Covariates.
Note: claim extraction is optional and turned off by default. This is because claim extraction generally requires prompt tuning to be useful.
"}, {"location": "index/default_dataflow/#phase-3-graph-augmentation", "title": "Phase 3: Graph Augmentation", "text": "Now that we have a usable graph of entities and relationships, we want to understand their community structure and augment the graph with additional information. This is done in two steps: Community Detection and Graph Embedding. These give us explicit (communities) and implicit (embeddings) ways of understanding the topological structure of our graph.
"}, {"location": "index/default_dataflow/#community-detection", "title": "Community Detection", "text": "---\ntitle: Graph Augmentation\n---\nflowchart LR\n cd[Leiden Hierarchical Community Detection] --> ge[Node2Vec Graph Embedding] --> ag[Graph Table Emission]
In this step, we generate a hierarchy of entity communities using the Hierarchical Leiden Algorithm. This method will apply a recursive community-clustering to our graph until we reach a community-size threshold. This will allow us to understand the community structure of our graph and provide a way to navigate and summarize the graph at different levels of granularity.
"}, {"location": "index/default_dataflow/#graph-embedding", "title": "Graph Embedding", "text": "In this step, we generate a vector representation of our graph using the Node2Vec algorithm. This will allow us to understand the implicit structure of our graph and provide an additional vector-space in which to search for related concepts during our query phase.
"}, {"location": "index/default_dataflow/#graph-tables-emission", "title": "Graph Tables Emission", "text": "Once our graph augmentation steps are complete, the final Entities and Relationships tables are exported after their text fields are text-embedded.
"}, {"location": "index/default_dataflow/#phase-4-community-summarization", "title": "Phase 4: Community Summarization", "text": "---\ntitle: Community Summarization\n---\nflowchart LR\n sc[Generate Community Reports] --> ss[Summarize Community Reports] --> ce[Community Embedding] --> co[Community Tables Emission]
At this point, we have a functional graph of entities and relationships, a hierarchy of communities for the entities, as well as node2vec embeddings.
Now we want to build on the communities data and generate reports for each community. This gives us a high-level understanding of the graph at several points of graph granularity. For example, if community A is the top-level community, we'll get a report about the entire graph. If the community is lower-level, we'll get a report about a local cluster.
"}, {"location": "index/default_dataflow/#generate-community-reports", "title": "Generate Community Reports", "text": "In this step, we generate a summary of each community using the LLM. This will allow us to understand the distinct information contained within each community and provide a scoped understanding of the graph, from either a high-level or a low-level perspective. These reports contain an executive overview and reference the key entities, relationships, and claims within the community sub-structure.
"}, {"location": "index/default_dataflow/#summarize-community-reports", "title": "Summarize Community Reports", "text": "In this step, each community report is then summarized via the LLM for shorthand use.
"}, {"location": "index/default_dataflow/#community-embedding", "title": "Community Embedding", "text": "In this step, we generate a vector representation of our communities by generating text embeddings of the community report, the community report summary, and the title of the community report.
"}, {"location": "index/default_dataflow/#community-tables-emission", "title": "Community Tables Emission", "text": "At this point, some bookkeeping work is performed and we export the Communities and CommunityReports tables.
"}, {"location": "index/default_dataflow/#phase-5-document-processing", "title": "Phase 5: Document Processing", "text": "In this phase of the workflow, we create the Documents table for the knowledge model.
"}, {"location": "index/default_dataflow/#augment-with-columns-csv-only", "title": "Augment with Columns (CSV Only)", "text": "---\ntitle: Document Processing\n---\nflowchart LR\n aug[Augment] --> dp[Link to TextUnits] --> de[Avg. Embedding] --> dg[Document Table Emission]
If the workflow is operating on CSV data, you may configure your workflow to add additional fields to Documents output. These fields should exist on the incoming CSV tables. Details about configuring this can be found in the configuration documentation.
"}, {"location": "index/default_dataflow/#link-to-textunits", "title": "Link to TextUnits", "text": "In this step, we link each document to the text-units that were created in the first phase. This allows us to understand which documents are related to which text-units and vice-versa.
"}, {"location": "index/default_dataflow/#document-embedding", "title": "Document Embedding", "text": "In this step, we generate a vector representation of our documents using an average embedding of document slices. We re-chunk documents without overlapping chunks, and then generate an embedding for each chunk. We create an average of these chunks weighted by token-count and use this as the document embedding. This will allow us to understand the implicit relationship between documents, and will help us generate a network representation of our documents.
"}, {"location": "index/default_dataflow/#documents-table-emission", "title": "Documents Table Emission", "text": "At this point, we can export the Documents table into the knowledge Model.
"}, {"location": "index/default_dataflow/#phase-6-network-visualization", "title": "Phase 6: Network Visualization", "text": "In this phase of the workflow, we perform some steps to support network visualization of our high-dimensional vector spaces within our existing graphs. At this point there are two logical graphs at play: the Entity-Relationship graph and the Document graph.
---\ntitle: Network Visualization Workflows\n---\nflowchart LR\n nv[Umap Documents] --> ne[Umap Entities] --> ng[Nodes Table Emission]
For each of the logical graphs, we perform a UMAP dimensionality reduction to generate a 2D representation of the graph. This will allow us to visualize the graph in a 2D space and understand the relationships between the nodes in the graph. The UMAP embeddings are then exported as a table of Nodes. The rows of this table include a discriminator indicating whether the node is a document or an entity, and the UMAP coordinates.
"}, {"location": "index/outputs/", "title": "Outputs", "text": "The default pipeline produces a series of output tables that align with the conceptual knowledge model. This page describes the detailed output table schemas. By default we write these tables out as parquet files on disk.
"}, {"location": "index/outputs/#shared-fields", "title": "Shared fields", "text": "All tables have two identifier fields:
name type description id str Generated UUID, assuring global uniqueness human_readable_id int This is an incremented short ID created per-run. For example, we use this short ID with generated summaries that print citations so they are easy to cross-reference visually."}, {"location": "index/outputs/#create_final_communities", "title": "create_final_communities", "text": "This is a list of the final communities generated by Leiden. Communities are strictly hierarchical, subdividing into children as the cluster affinity is narrowed.
name type description community int Leiden-generated cluster ID for the community. Note that these increment with depth, so they are unique through all levels of the community hierarchy. For this table, human_readable_id is a copy of the community ID rather than a plain increment. parent int Parent community ID. level int Depth of the community in the hierarchy. title str Friendly name of the community. entity_ids str[] List of entities that are members of the community. relationship_ids str[] List of relationships that are wholly within the community (source and target are both in the community). text_unit_ids str[] List of text units represented within the community. period str Date of ingest, used for incremental update merges. ISO8601 size int Size of the community (entity count), used for incremental update merges."}, {"location": "index/outputs/#create_final_community_reports", "title": "create_final_community_reports", "text": "This is the list of summarized reports for each community.
name type description community int Short ID of the community this report applies to. parent int Parent community ID. level int Level of the community this report applies to. title str LM-generated title for the report. summary str LM-generated summary of the report. full_content str LM-generated full report. rank float LM-derived relevance ranking of the report based on member entity salience rank_explanation str LM-derived explanation of the rank. findings dict LM-derived list of the top 5-10 insights from the community. Containssummary
andexplanation
values. full_content_json json Full JSON output as returned by the LM. Most fields are extracted into columns, but this JSON is sent for query summarization so we leave it to allow for prompt tuning to add fields/content by end users. period str Date of ingest, used for incremental update merges. ISO8601 size int Size of the community (entity count), used for incremental update merges."}, {"location": "index/outputs/#create_final_covariates", "title": "create_final_covariates", "text": "(Optional) If claim extraction is turned on, this is a list of the extracted covariates. Note that claims are typically oriented around identifying malicious behavior such as fraud, so they are not useful for all datasets.
name type description covariate_type str This is always \"claim\" with our default covariates. type str Nature of the claim type. description str LM-generated description of the behavior. subject_id str Name of the source entity (that is performing the claimed behavior). object_id str Name of the target entity (that the claimed behavior is performed on). status str LM-derived assessment of the correctness of the claim. One of [TRUE, FALSE, SUSPECTED] start_date str LM-derived start of the claimed activity. ISO8601 end_date str LM-derived end of the claimed activity. ISO8601 source_text str Short string of text containing the claimed behavior. text_unit_id str ID of the text unit the claim text was extracted from."}, {"location": "index/outputs/#create_final_documents", "title": "create_final_documents", "text": "List of document content after import.
name type description title str Filename, unless otherwise configured during CSV import. text str Full text of the document. text_unit_ids str[] List of text units (chunks) that were parsed from the document. attributes dict (optional) If specified during CSV import, this is a dict of attributes for the document."}, {"location": "index/outputs/#create_final_entities", "title": "create_final_entities", "text": "List of all entities found in the data by the LM.
name type description title str Name of the entity. type str Type of the entity. By default this will be \"organization\", \"person\", \"geo\", or \"event\" unless configured differently or auto-tuning is used. description str Textual description of the entity. Entities may be found in many text units, so this is an LM-derived summary of all descriptions. text_unit_ids str[] List of the text units containing the entity."}, {"location": "index/outputs/#create_final_nodes", "title": "create_final_nodes", "text": "This is graph-related information for the entities. It contains only information relevant to the graph such as community. There is an entry for each entity at every community level it is found within, so you may see \"duplicate\" entities.
Note that the ID fields match those in create_final_entities and can be used for joining if additional information about a node is required.
name type description title str Name of the referenced entity. Duplicated from create_final_entities for convenient cross-referencing. community int Leiden community the node is found within. Entities are not always assigned a community (they may not be close enough to any), so they may have a ID of -1. level int Level of the community the entity is in. degree int Node degree (connectedness) in the graph. x float X position of the node for visual layouts. If graph embeddings and UMAP are not turned on, this will be 0. y float Y position of the node for visual layouts. If graph embeddings and UMAP are not turned on, this will be 0."}, {"location": "index/outputs/#create_final_relationships", "title": "create_final_relationships", "text": "List of all entity-to-entity relationships found in the data by the LM. This is also the edge list for the graph.
name type description source str Name of the source entity. target str Name of the target entity. description str LM-derived description of the relationship. Also see note for entity descriptions. weight float Weight of the edge in the graph. This is summed from an LM-derived \"strength\" measure for each relationship instance. combined_degree int Sum of source and target node degrees. text_unit_ids str[] List of text units the relationship was found within."}, {"location": "index/outputs/#create_final_text_units", "title": "create_final_text_units", "text": "List of all text chunks parsed from the input documents.
name type description text str Raw full text of the chunk. n_tokens int Number of tokens in the chunk. This should normally match thechunk_size
config parameter, except for the last chunk which is often shorter. document_ids str[] List of document IDs the chunk came from. This is normally only 1 due to our default groupby, but for very short text documents (e.g., microblogs) it can be configured so text units span multiple documents. entity_ids str[] List of entities found in the text unit. relationships_ids str[] List of relationships found in the text unit. covariate_ids str[] Optional list of covariates found in the text unit."}, {"location": "index/overview/", "title": "GraphRAG Indexing \ud83e\udd16", "text": "The GraphRAG indexing package is a data pipeline and transformation suite that is designed to extract meaningful, structured data from unstructured text using LLMs.
Indexing Pipelines are configurable. They are composed of workflows, standard and custom steps, prompt templates, and input/output adapters. Our standard pipeline is designed to:
- extract entities, relationships and claims from raw text
- perform community detection in entities
- generate community summaries and reports at multiple levels of granularity
- embed entities into a graph vector space
- embed text chunks into a textual vector space
The outputs of the pipeline can be stored in a variety of formats, including JSON and Parquet - or they can be handled manually via the Python API.
"}, {"location": "index/overview/#getting-started", "title": "Getting Started", "text": ""}, {"location": "index/overview/#requirements", "title": "Requirements", "text": "See the requirements section in Get Started for details on setting up a development environment.
The Indexing Engine can be used in either a default configuration mode or with a custom pipeline. To configure GraphRAG, see the configuration documentation. After you have a config file you can run the pipeline using the CLI or the Python API.
"}, {"location": "index/overview/#usage", "title": "Usage", "text": ""}, {"location": "index/overview/#cli", "title": "CLI", "text": ""}, {"location": "index/overview/#python-api", "title": "Python API", "text": "# Via Poetry\npoetry run poe cli --root <data_root> # default config mode\npoetry run poe cli --config your_pipeline.yml # custom config mode\n\n# Via Node\nyarn run:index --root <data_root> # default config mode\nyarn run:index --config your_pipeline.yml # custom config mode\n
Please see the examples folder for a handful of functional pipelines illustrating how to create and run via a custom settings.yml or through custom python scripts.
"}, {"location": "index/overview/#further-reading", "title": "Further Reading", "text": ""}, {"location": "prompt_tuning/auto_prompt_tuning/", "title": "Auto Prompt Tuning \u2699\ufe0f", "text": "
- To start developing within the GraphRAG project, see getting started
- To understand the underlying concepts and execution model of the indexing library, see the architecture documentation
- To get running with a series of examples, see the examples documentation
- To read more about configuring the indexing engine, see the configuration documentation
GraphRAG provides the ability to create domain adapted prompts for the generation of the knowledge graph. This step is optional, though it is highly encouraged to run it as it will yield better results when executing an Index Run.
These are generated by loading the inputs, splitting them into chunks (text units) and then running a series of LLM invocations and template substitutions to generate the final prompts. We suggest using the default values provided by the script, but in this page you'll find the detail of each in case you want to further explore and tweak the prompt tuning algorithm.
Figure 1: Auto Tuning Conceptual Diagram.
"}, {"location": "prompt_tuning/auto_prompt_tuning/#prerequisites", "title": "Prerequisites", "text": "Before running auto tuning, ensure you have already initialized your workspace with the
"}, {"location": "prompt_tuning/auto_prompt_tuning/#usage", "title": "Usage", "text": "graphrag init
command. This will create the necessary configuration files and the default prompts. Refer to the Init Documentation for more information about the initialization process.You can run the main script from the command line with various options:
"}, {"location": "prompt_tuning/auto_prompt_tuning/#command-line-options", "title": "Command-Line Options", "text": "graphrag prompt-tune [--root ROOT] [--config CONFIG] [--domain DOMAIN] [--selection-method METHOD] [--limit LIMIT] [--language LANGUAGE] \\\n[--max-tokens MAX_TOKENS] [--chunk-size CHUNK_SIZE] [--n-subset-max N_SUBSET_MAX] [--k K] \\\n[--min-examples-required MIN_EXAMPLES_REQUIRED] [--discover-entity-types] [--output OUTPUT]\n
"}, {"location": "prompt_tuning/auto_prompt_tuning/#example-usage", "title": "Example Usage", "text": "
--config
(required): The path to the configuration file. This is required to load the data and model settings.
--root
(optional): The data project root directory, including the config files (YML, JSON, or .env). Defaults to the current directory.
--domain
(optional): The domain related to your input data, such as 'space science', 'microbiology', or 'environmental news'. If left empty, the domain will be inferred from the input data.
--method
(optional): The method to select documents. Options are all, random, auto or top. Default is random.
--limit
(optional): The limit of text units to load when using random or top selection. Default is 15.
--language
(optional): The language to use for input processing. If it is different from the inputs' language, the LLM will translate. Default is \"\" meaning it will be automatically detected from the inputs.
--max-tokens
(optional): Maximum token count for prompt generation. Default is 2000.
--chunk-size
(optional): The size in tokens to use for generating text units from input documents. Default is 200.
--n-subset-max
(optional): The number of text chunks to embed when using auto selection method. Default is 300.
--k
(optional): The number of documents to select when using auto selection method. Default is 15.
--min-examples-required
(optional): The minimum number of examples required for entity extraction prompts. Default is 2.
--discover-entity-types
(optional): Allow the LLM to discover and extract entities automatically. We recommend using this when your data covers a lot of topics or it is highly randomized.
--output
(optional): The folder to save the generated prompts. Default is \"prompts\".python -m graphrag prompt-tune --root /path/to/project --config /path/to/settings.yaml --domain \"environmental news\" \\\n--method random --limit 10 --language English --max-tokens 2048 --chunk-size 256 --min-examples-required 3 \\\n--no-entity-types --output /path/to/output\n
or, with minimal configuration (suggested):
"}, {"location": "prompt_tuning/auto_prompt_tuning/#document-selection-methods", "title": "Document Selection Methods", "text": "python -m graphrag prompt-tune --root /path/to/project --config /path/to/settings.yaml --no-entity-types\n
The auto tuning feature ingests the input data and then divides it into text units the size of the chunk size parameter. After that, it uses one of the following selection methods to pick a sample to work with for prompt generation:
"}, {"location": "prompt_tuning/auto_prompt_tuning/#modify-env-vars", "title": "Modify Env Vars", "text": "
random
: Select text units randomly. This is the default and recommended option.top
: Select the head n text units.all
: Use all text units for the generation. Use only with small datasets; this option is not usually recommended.auto
: Embed text units in a lower-dimensional space and select the k nearest neighbors to the centroid. This is useful when you have a large dataset and want to select a representative sample.After running auto tuning, you should modify the following environment variables (or config variables) to pick up the new prompts on your index run. Note: Please make sure to update the correct path to the generated prompts, in this example we are using the default \"prompts\" path.
GRAPHRAG_ENTITY_EXTRACTION_PROMPT_FILE
= \"prompts/entity_extraction.txt\"
GRAPHRAG_COMMUNITY_REPORT_PROMPT_FILE
= \"prompts/community_report.txt\"
GRAPHRAG_SUMMARIZE_DESCRIPTIONS_PROMPT_FILE
= \"prompts/summarize_descriptions.txt\"or in your yaml config file:
"}, {"location": "prompt_tuning/manual_prompt_tuning/", "title": "Manual Prompt Tuning \u2699\ufe0f", "text": "entity_extraction:\n prompt: \"prompts/entity_extraction.txt\"\n\nsummarize_descriptions:\n prompt: \"prompts/summarize_descriptions.txt\"\n\ncommunity_reports:\n prompt: \"prompts/community_report.txt\"\n
The GraphRAG indexer, by default, will run with a handful of prompts that are designed to work well in the broad context of knowledge discovery. However, it is quite common to want to tune the prompts to better suit your specific use case. We provide a means for you to do this by allowing you to specify a custom prompt file, which will each use a series of token-replacements internally.
Each of these prompts may be overridden by writing a custom prompt file in plaintext. We use token-replacements in the form of
"}, {"location": "prompt_tuning/manual_prompt_tuning/#indexing-prompts", "title": "Indexing Prompts", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#entityrelationship-extraction", "title": "Entity/Relationship Extraction", "text": "{token_name}
, and the descriptions for the available tokens can be found below.Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#summarize-entityrelationship-descriptions", "title": "Summarize Entity/Relationship Descriptions", "text": "
- {input_text} - The input text to be processed.
- {entity_types} - A list of entity types
- {tuple_delimiter} - A delimiter for separating values within a tuple. A single tuple is used to represent an individual entity or relationship.
- {record_delimiter} - A delimiter for separating tuple instances.
- {completion_delimiter} - An indicator for when generation is complete.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_1", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#claim-extraction", "title": "Claim Extraction", "text": "
- {entity_name} - The name of the entity or the source/target pair of the relationship.
- {description_list} - A list of descriptions for the entity or relationship.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_2", "title": "Tokens", "text": "
- {input_text} - The input text to be processed.
- {tuple_delimiter} - A delimiter for separating values within a tuple. A single tuple is used to represent an individual entity or relationship.
- {record_delimiter} - A delimiter for separating tuple instances.
- {completion_delimiter} - An indicator for when generation is complete.
- {entity_specs} - A list of entity types.
- {claim_description} - Description of what claims should look like. Default is:
\"Any claims or facts that could be relevant to information discovery.\"
See the configuration documentation for details on how to change this.
"}, {"location": "prompt_tuning/manual_prompt_tuning/#generate-community-reports", "title": "Generate Community Reports", "text": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_3", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#query-prompts", "title": "Query Prompts", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#local-search", "title": "Local Search", "text": "
- {input_text} - The input text to generate the report with. This will contain tables of entities and relationships.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_4", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#global-search", "title": "Global Search", "text": "
- {response_type} - Describe how the response should look. We default to \"multiple paragraphs\".
- {context_data} - The data tables from GraphRAG's index.
Mapper Prompt Source
Reducer Prompt Source
Knowledge Prompt Source
Global search uses a map/reduce approach to summarization. You can tune these prompts independently. This search also includes the ability to adjust the use of general knowledge from the model's training.
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_5", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#drift-search", "title": "Drift Search", "text": "
- {response_type} - Describe how the response should look (reducer only). We default to \"multiple paragraphs\".
- {context_data} - The data tables from GraphRAG's index.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_6", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/overview/", "title": "Prompt Tuning \u2699\ufe0f", "text": "
- {response_type} - Describe how the response should look. We default to \"multiple paragraphs\".
- {context_data} - The data tables from GraphRAG's index.
- {community_reports} - The most relevant community reports to include in the summarization.
- {query} - The query text as injected into the context.
This page provides an overview of the prompt tuning options available for the GraphRAG indexing engine.
"}, {"location": "prompt_tuning/overview/#default-prompts", "title": "Default Prompts", "text": "The default prompts are the simplest way to get started with the GraphRAG system. It is designed to work out-of-the-box with minimal configuration. More details about each of the default prompts for indexing and query can be found on the manual tuning page.
"}, {"location": "prompt_tuning/overview/#auto-tuning", "title": "Auto Tuning", "text": "Auto Tuning leverages your input data and LLM interactions to create domain adapted prompts for the generation of the knowledge graph. It is highly encouraged to run it as it will yield better results when executing an Index Run. For more details about how to use it, please refer to the Auto Tuning documentation.
"}, {"location": "prompt_tuning/overview/#manual-tuning", "title": "Manual Tuning", "text": "Manual tuning is an advanced use-case. Most users will want to use the Auto Tuning feature instead. Details about how to use manual configuration are available in the manual tuning documentation.
"}, {"location": "query/drift_search/", "title": "DRIFT Search \ud83d\udd0e", "text": ""}, {"location": "query/drift_search/#combining-local-and-global-search", "title": "Combining Local and Global Search", "text": "GraphRAG is a technique that uses large language models (LLMs) to create knowledge graphs and summaries from unstructured text documents and leverages them to improve retrieval-augmented generation (RAG) operations on private datasets. It offers comprehensive global overviews of large, private troves of unstructured text documents while also enabling exploration of detailed, localized information. By using LLMs to create comprehensive knowledge graphs that connect and describe entities and relationships contained in those documents, GraphRAG leverages semantic structuring of the data to generate responses to a wide variety of complex user queries.
DRIFT search (Dynamic Reasoning and Inference with Flexible Traversal) builds upon Microsoft\u2019s GraphRAG technique, combining characteristics of both global and local search to generate detailed responses in a method that balances computational costs with quality outcomes using our drift search method.
"}, {"location": "query/drift_search/#methodology", "title": "Methodology", "text": "Figure 1. An entire DRIFT search hierarchy highlighting the three core phases of the DRIFT search process. A (Primer): DRIFT compares the user\u2019s query with the top K most semantically relevant community reports, generating a broad initial answer and follow-up questions to steer further exploration. B (Follow-Up): DRIFT uses local search to refine queries, producing additional intermediate answers and follow-up questions that enhance specificity, guiding the engine towards context-rich information. A glyph on each node in the diagram shows the confidence the algorithm has to continue the query expansion step. C (Output Hierarchy): The final output is a hierarchical structure of questions and answers ranked by relevance, reflecting a balanced mix of global insights and local refinements, making the results adaptable and comprehensive.
DRIFT Search introduces a new approach to local search queries by including community information in the search process. This greatly expands the breadth of the query\u2019s starting point and leads to retrieval and usage of a far higher variety of facts in the final answer. This addition expands the GraphRAG query engine by providing a more comprehensive option for local search, which uses community insights to refine a query into detailed follow-up questions.
"}, {"location": "query/drift_search/#configuration", "title": "Configuration", "text": "Below are the key parameters of the DRIFTSearch class:
"}, {"location": "query/drift_search/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from community reports and query informationconfig
: model to define the DRIFT Search hyperparameters. DRIFT Config modeltoken_encoder
: token encoder for tracking the budget for the algorithm.query_state
: a state object as defined in Query State that allows to track execution of a DRIFT Search instance, alongside follow ups and DRIFT actions.An example of a drift search scenario can be found in the following notebook.
"}, {"location": "query/drift_search/#learn-more", "title": "Learn More", "text": "For a more in-depth look at the DRIFT search method, please refer to our DRIFT Search blog post
"}, {"location": "query/global_search/", "title": "Global Search \ud83d\udd0e", "text": ""}, {"location": "query/global_search/#whole-dataset-reasoning", "title": "Whole Dataset Reasoning", "text": "Baseline RAG struggles with queries that require aggregation of information across the dataset to compose an answer. Queries such as \u201cWhat are the top 5 themes in the data?\u201d perform terribly because baseline RAG relies on a vector search of semantically similar text content within the dataset. There is nothing in the query to direct it to the correct information.
However, with GraphRAG we can answer such questions, because the structure of the LLM-generated knowledge graph tells us about the structure (and thus themes) of the dataset as a whole. This allows the private dataset to be organized into meaningful semantic clusters that are pre-summarized. Using our global search method, the LLM uses these clusters to summarize these themes when responding to a user query.
"}, {"location": "query/global_search/#methodology", "title": "Methodology", "text": "---\ntitle: Global Search Dataflow\n---\n%%{ init: { 'flowchart': { 'curve': 'step' } } }%%\nflowchart LR\n\n uq[User Query] --- .1\n ch1[Conversation History] --- .1\n\n subgraph RIR\n direction TB\n ri1[Rated Intermediate<br/>Response 1]~~~ri2[Rated Intermediate<br/>Response 2] -.\"{1..N}\".-rin[Rated Intermediate<br/>Response N]\n end\n\n .1--Shuffled Community<br/>Report Batch 1-->RIR\n .1--Shuffled Community<br/>Report Batch 2-->RIR---.2\n .1--Shuffled Community<br/>Report Batch N-->RIR\n\n .2--Ranking +<br/>Filtering-->agr[Aggregated Intermediate<br/>Responses]-->res[Response]\n\n\n\n classDef green fill:#26B653,stroke:#333,stroke-width:2px,color:#fff;\n classDef turquoise fill:#19CCD3,stroke:#333,stroke-width:2px,color:#fff;\n classDef rose fill:#DD8694,stroke:#333,stroke-width:2px,color:#fff;\n classDef orange fill:#F19914,stroke:#333,stroke-width:2px,color:#fff;\n classDef purple fill:#B356CD,stroke:#333,stroke-width:2px,color:#fff;\n classDef invisible fill:#fff,stroke:#fff,stroke-width:0px,color:#fff, width:0px;\n class uq,ch1 turquoise;\n class ri1,ri2,rin rose;\n class agr orange;\n class res purple;\n class .1,.2 invisible;\n
Given a user query and, optionally, the conversation history, the global search method uses a collection of LLM-generated community reports from a specified level of the graph's community hierarchy as context data to generate response in a map-reduce manner. At the
map
step, community reports are segmented into text chunks of pre-defined size. Each text chunk is then used to produce an intermediate response containing a list of point, each of which is accompanied by a numerical rating indicating the importance of the point. At thereduce
step, a filtered set of the most important points from the intermediate responses are aggregated and used as the context to generate the final response.The quality of the global search\u2019s response can be heavily influenced by the level of the community hierarchy chosen for sourcing community reports. Lower hierarchy levels, with their detailed reports, tend to yield more thorough responses, but may also increase the time and LLM resources needed to generate the final response due to the volume of reports.
"}, {"location": "query/global_search/#configuration", "title": "Configuration", "text": "Below are the key parameters of the GlobalSearch class:
"}, {"location": "query/global_search/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from community reportsmap_system_prompt
: prompt template used in themap
stage. Default template can be found at map_system_promptreduce_system_prompt
: prompt template used in thereduce
stage, default template can be found at reduce_system_promptresponse_type
: free-form text describing the desired response type and format (e.g.,Multiple Paragraphs
,Multi-Page Report
)allow_general_knowledge
: setting this to True will include additional instructions to thereduce_system_prompt
to prompt the LLM to incorporate relevant real-world knowledge outside of the dataset. Note that this may increase hallucinations, but can be useful for certain scenarios. Default is False *general_knowledge_inclusion_prompt
: instruction to add to thereduce_system_prompt
ifallow_general_knowledge
is enabled. Default instruction can be found at general_knowledge_instructionmax_data_tokens
: token budget for the context datamap_llm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to be passed to the LLM call at themap
stagereduce_llm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to passed to the LLM call at thereduce
stagecontext_builder_params
: a dictionary of additional parameters to be passed to thecontext_builder
object when building context window for themap
stage.concurrent_coroutines
: controls the degree of parallelism in themap
stage.callbacks
: optional callback functions, can be used to provide custom event handlers for LLM's completion streaming eventsAn example of a global search scenario can be found in the following notebook.
"}, {"location": "query/local_search/", "title": "Local Search \ud83d\udd0e", "text": ""}, {"location": "query/local_search/#entity-based-reasoning", "title": "Entity-based Reasoning", "text": "The local search method combines structured data from the knowledge graph with unstructured data from the input documents to augment the LLM context with relevant entity information at query time. It is well-suited for answering questions that require an understanding of specific entities mentioned in the input documents (e.g., \u201cWhat are the healing properties of chamomile?\u201d).
"}, {"location": "query/local_search/#methodology", "title": "Methodology", "text": "---\ntitle: Local Search Dataflow\n---\n%%{ init: { 'flowchart': { 'curve': 'step' } } }%%\nflowchart LR\n\n uq[User Query] ---.1\n ch1[Conversation<br/>History]---.1\n\n .1--Entity<br/>Description<br/>Embedding--> ee[Extracted Entities]\n\n ee[Extracted Entities] ---.2--Entity-Text<br/>Unit Mapping--> ctu[Candidate<br/>Text Units]--Ranking + <br/>Filtering -->ptu[Prioritized<br/>Text Units]---.3\n .2--Entity-Report<br/>Mapping--> ccr[Candidate<br/>Community Reports]--Ranking + <br/>Filtering -->pcr[Prioritized<br/>Community Reports]---.3\n .2--Entity-Entity<br/>Relationships--> ce[Candidate<br/>Entities]--Ranking + <br/>Filtering -->pe[Prioritized<br/>Entities]---.3\n .2--Entity-Entity<br/>Relationships--> cr[Candidate<br/>Relationships]--Ranking + <br/>Filtering -->pr[Prioritized<br/>Relationships]---.3\n .2--Entity-Covariate<br/>Mappings--> cc[Candidate<br/>Covariates]--Ranking + <br/>Filtering -->pc[Prioritized<br/>Covariates]---.3\n ch1 -->ch2[Conversation History]---.3\n .3-->res[Response]\n\n classDef green fill:#26B653,stroke:#333,stroke-width:2px,color:#fff;\n classDef turquoise fill:#19CCD3,stroke:#333,stroke-width:2px,color:#fff;\n classDef rose fill:#DD8694,stroke:#333,stroke-width:2px,color:#fff;\n classDef orange fill:#F19914,stroke:#333,stroke-width:2px,color:#fff;\n classDef purple fill:#B356CD,stroke:#333,stroke-width:2px,color:#fff;\n classDef invisible fill:#fff,stroke:#fff,stroke-width:0px,color:#fff, width:0px;\n class uq,ch1 turquoise\n class ee green\n class ctu,ccr,ce,cr,cc rose\n class ptu,pcr,pe,pr,pc,ch2 orange\n class res purple\n class .1,.2,.3 invisible\n\n
Given a user query and, optionally, the conversation history, the local search method identifies a set of entities from the knowledge graph that are semantically-related to the user input. These entities serve as access points into the knowledge graph, enabling the extraction of further relevant details such as connected entities, relationships, entity covariates, and community reports. Additionally, it also extracts relevant text chunks from the raw input documents that are associated with the identified entities. These candidate data sources are then prioritized and filtered to fit within a single context window of pre-defined size, which is used to generate a response to the user query.
"}, {"location": "query/local_search/#configuration", "title": "Configuration", "text": "Below are the key parameters of the LocalSearch class:
"}, {"location": "query/local_search/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from collections of knowledge model objectssystem_prompt
: prompt template used to generate the search response. Default template can be found at system_promptresponse_type
: free-form text describing the desired response type and format (e.g.,Multiple Paragraphs
,Multi-Page Report
)llm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to be passed to the LLM callcontext_builder_params
: a dictionary of additional parameters to be passed to thecontext_builder
object when building context for the search promptcallbacks
: optional callback functions, can be used to provide custom event handlers for LLM's completion streaming eventsAn example of a local search scenario can be found in the following notebook.
"}, {"location": "query/overview/", "title": "Query Engine \ud83d\udd0e", "text": "The Query Engine is the retrieval module of the Graph RAG Library. It is one of the two main components of the Graph RAG library, the other being the Indexing Pipeline (see Indexing Pipeline). It is responsible for the following tasks:
"}, {"location": "query/overview/#local-search", "title": "Local Search", "text": "
- Local Search
- Global Search
- DRIFT Search
- Question Generation
Local search method generates answers by combining relevant data from the AI-extracted knowledge-graph with text chunks of the raw documents. This method is suitable for questions that require an understanding of specific entities mentioned in the documents (e.g. What are the healing properties of chamomile?).
For more details about how Local Search works please refer to the Local Search documentation.
"}, {"location": "query/overview/#global-search", "title": "Global Search", "text": "Global search method generates answers by searching over all AI-generated community reports in a map-reduce fashion. This is a resource-intensive method, but often gives good responses for questions that require an understanding of the dataset as a whole (e.g. What are the most significant values of the herbs mentioned in this notebook?).
More about this can be checked at the Global Search documentation.
"}, {"location": "query/overview/#drift-search", "title": "DRIFT Search", "text": "DRIFT Search introduces a new approach to local search queries by including community information in the search process. This greatly expands the breadth of the query\u2019s starting point and leads to retrieval and usage of a far higher variety of facts in the final answer. This addition expands the GraphRAG query engine by providing a more comprehensive option for local search, which uses community insights to refine a query into detailed follow-up questions.
To learn more about DRIFT Search, please refer to the DRIFT Search documentation.
"}, {"location": "query/overview/#question-generation", "title": "Question Generation", "text": "This functionality takes a list of user queries and generates the next candidate questions. This is useful for generating follow-up questions in a conversation or for generating a list of questions for the investigator to dive deeper into the dataset.
Information about how question generation works can be found at the Question Generation documentation page.
"}, {"location": "query/question_generation/", "title": "Question Generation \u2754", "text": ""}, {"location": "query/question_generation/#entity-based-question-generation", "title": "Entity-based Question Generation", "text": "The question generation method combines structured data from the knowledge graph with unstructured data from the input documents to generate candidate questions related to specific entities.
"}, {"location": "query/question_generation/#methodology", "title": "Methodology", "text": "Given a list of prior user questions, the question generation method uses the same context-building approach employed in local search to extract and prioritize relevant structured and unstructured data, including entities, relationships, covariates, community reports and raw text chunks. These data records are then fitted into a single LLM prompt to generate candidate follow-up questions that represent the most important or urgent information content or themes in the data.
"}, {"location": "query/question_generation/#configuration", "title": "Configuration", "text": "Below are the key parameters of the Question Generation class:
"}, {"location": "query/question_generation/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from collections of knowledge model objects, using the same context builder class as in local searchsystem_prompt
: prompt template used to generate candidate questions. Default template can be found at system_promptllm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to be passed to the LLM callcontext_builder_params
: a dictionary of additional parameters to be passed to thecontext_builder
object when building context for the question generation promptcallbacks
: optional callback functions, can be used to provide custom event handlers for LLM's completion streaming eventsAn example of the question generation function can be found in the following notebook.
"}, {"location": "query/notebooks/overview/", "title": "API Notebooks", "text": ""}, {"location": "query/notebooks/overview/#query-engine-notebooks", "title": "Query Engine Notebooks", "text": "
- API Overview Notebook
For examples about running Query please refer to the following notebooks:
- Global Search Notebook
- Local Search Notebook
- DRIFT Search Notebook
The test dataset for these notebooks can be found in dataset.zip.
"}]} \ No newline at end of file +{"config": {"lang": ["en"], "separator": "[\\s\\-]+", "pipeline": ["stopWordFilter"]}, "docs": [{"location": "", "title": "Welcome to GraphRAG", "text": "\ud83d\udc49 Microsoft Research Blog Post \ud83d\udc49 GraphRAG Accelerator \ud83d\udc49 GraphRAG Arxiv
Figure 1: An LLM-generated knowledge graph built using GPT-4 Turbo.
GraphRAG is a structured, hierarchical approach to Retrieval Augmented Generation (RAG), as opposed to naive semantic-search approaches using plain text snippets. The GraphRAG process involves extracting a knowledge graph out of raw text, building a community hierarchy, generating summaries for these communities, and then leveraging these structures when perform RAG-based tasks.
To learn more about GraphRAG and how it can be used to enhance your LLMs ability to reason about your private data, please visit the Microsoft Research Blog Post.
"}, {"location": "#solution-accelerator", "title": "Solution Accelerator \ud83d\ude80", "text": "To quickstart the GraphRAG system we recommend trying the Solution Accelerator package. This provides a user-friendly end-to-end experience with Azure resources.
"}, {"location": "#get-started-with-graphrag", "title": "Get Started with GraphRAG \ud83d\ude80", "text": "To start using GraphRAG, check out the Get Started guide. For a deeper dive into the main sub-systems, please visit the docpages for the Indexer and Query packages.
"}, {"location": "#graphrag-vs-baseline-rag", "title": "GraphRAG vs Baseline RAG \ud83d\udd0d", "text": "Retrieval-Augmented Generation (RAG) is a technique to improve LLM outputs using real-world information. This technique is an important part of most LLM-based tools and the majority of RAG approaches use vector similarity as the search technique, which we call Baseline RAG. GraphRAG uses knowledge graphs to provide substantial improvements in question-and-answer performance when reasoning about complex information. RAG techniques have shown promise in helping LLMs to reason about private datasets - data that the LLM is not trained on and has never seen before, such as an enterprise\u2019s proprietary research, business documents, or communications. Baseline RAG was created to help solve this problem, but we observe situations where baseline RAG performs very poorly. For example:
- Baseline RAG struggles to connect the dots. This happens when answering a question requires traversing disparate pieces of information through their shared attributes in order to provide new synthesized insights.
- Baseline RAG performs poorly when being asked to holistically understand summarized semantic concepts over large data collections or even singular large documents.
To address this, the tech community is working to develop methods that extend and enhance RAG. Microsoft Research\u2019s new approach, GraphRAG, uses LLMs to create a knowledge graph based on an input corpus. This graph, along with community summaries and graph machine learning outputs, are used to augment prompts at query time. GraphRAG shows substantial improvement in answering the two classes of questions described above, demonstrating intelligence or mastery that outperforms other approaches previously applied to private datasets.
"}, {"location": "#the-graphrag-process", "title": "The GraphRAG Process \ud83e\udd16", "text": "GraphRAG builds upon our prior research and tooling using graph machine learning. The basic steps of the GraphRAG process are as follows:
"}, {"location": "#index", "title": "Index", "text": ""}, {"location": "#query", "title": "Query", "text": "
- Slice up an input corpus into a series of TextUnits, which act as analyzable units for the rest of the process, and provide fine-grained references in our outputs.
- Extract all entities, relationships, and key claims from the TextUnits using an LLM.
- Perform a hierarchical clustering of the graph using the Leiden technique. To see this visually, check out Figure 1 above. Each circle is an entity (e.g., a person, place, or organization), with the size representing the degree of the entity, and the color representing its community.
- Generate summaries of each community and its constituents from the bottom-up. This aids in holistic understanding of the dataset.
At query time, these structures are used to provide materials for the LLM context window when answering a question. The primary query modes are:
"}, {"location": "#prompt-tuning", "title": "Prompt Tuning", "text": "
- Global Search for reasoning about holistic questions about the corpus by leveraging the community summaries.
- Local Search for reasoning about specific entities by fanning-out to their neighbors and associated concepts.
- DRIFT Search for reasoning about specific entities by fanning-out to their neighbors and associated concepts, but with the added context of community information.
Using GraphRAG with your data out of the box may not yield the best possible results. We strongly recommend to fine-tune your prompts following the Prompt Tuning Guide in our documentation.
"}, {"location": "blog_posts/", "title": "Microsoft Research Blog", "text": "
GraphRAG: Unlocking LLM discovery on narrative private data
Published February 13, 2024
By Jonathan Larson, Senior Principal Data Architect; Steven Truitt, Principal Program Manager
GraphRAG: New tool for complex data discovery now on GitHub
Published July 2, 2024
By Darren Edge, Senior Director; Ha Trinh, Senior Data Scientist; Steven Truitt, Principal Program Manager; Jonathan Larson, Senior Principal Data Architect
GraphRAG auto-tuning provides rapid adaptation to new domains
Published September 9, 2024
By Alonso Guevara Fern\u00e1ndez, Sr. Software Engineer; Katy Smith, Data Scientist II; Joshua Bradley, Senior Data Scientist; Darren Edge, Senior Director; Ha Trinh, Senior Data Scientist; Sarah Smith, Senior Program Manager; Ben Cutler, Senior Director; Steven Truitt, Principal Program Manager; Jonathan Larson, Senior Principal Data Architect
Introducing DRIFT Search: Combining global and local search methods to improve quality and efficiency
Published October 31, 2024
By Julian Whiting, Senior Machine Learning Engineer; Zachary Hills , Senior Software Engineer; Alonso Guevara Fern\u00e1ndez, Sr. Software Engineer; Ha Trinh, Senior Data Scientist; Adam Bradley , Managing Partner, Strategic Research; Jonathan Larson, Senior Principal Data Architect
GraphRAG: Improving global search via dynamic community selection
Published November 15, 2024
By Bryan Li, Research Intern; Ha Trinh, Senior Data Scientist; Darren Edge, Senior Director; Jonathan Larson, Senior Principal Data Architect
LazyGraphRAG: Setting a new standard for quality and cost
Published November 25, 2024
By Darren Edge, Senior Director; Ha Trinh, Senior Data Scientist; Jonathan Larson, Senior Principal Data Architect
Moving to GraphRAG 1.0 \u2013 Streamlining ergonomics for developers and users
Published December 16, 2024
By Nathan Evans, Principal Software Architect; Alonso Guevara Fern\u00e1ndez, Senior Software Engineer; Joshua Bradley, Senior Data Scientist
"}, {"location": "cli/", "title": "CLI Reference", "text": "This page documents the command-line interface of the graphrag library.
"}, {"location": "cli/#graphrag", "title": "graphrag", "text": "GraphRAG: A graph-based retrieval-augmented generation (RAG) system.
Usage:
[OPTIONS] COMMAND [ARGS]...\n
Options:
"}, {"location": "cli/#index", "title": "index", "text": "--install-completion Install completion for the current shell.\n --show-completion Show completion for the current shell, to copy it or\n customize the installation.\n
Build a knowledge graph index.
Usage:
index [OPTIONS]\n
Options:
"}, {"location": "cli/#init", "title": "init", "text": "--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --verbose / --no-verbose Run the indexing pipeline with verbose\n logging \\[default: no-verbose]\n --memprofile / --no-memprofile Run the indexing pipeline with memory\n profiling \\[default: no-memprofile]\n --resume TEXT Resume a given indexing run\n --logger [rich|print|none] The progress logger to use. \\[default:\n rich]\n --dry-run / --no-dry-run Run the indexing pipeline without executing\n any steps to inspect and validate the\n configuration. \\[default: no-dry-run]\n --cache / --no-cache Use LLM cache. \\[default: cache]\n --skip-validation / --no-skip-validation\n Skip any preflight validation. Useful when\n running no LLM steps. \\[default: no-skip-\n validation]\n --output PATH Indexing pipeline output directory.\n Overrides storage.base_dir in the\n configuration file.\n
Generate a default configuration file.
Usage:
init [OPTIONS]\n
Options:
"}, {"location": "cli/#prompt-tune", "title": "prompt-tune", "text": "--root PATH The project root directory. \\[required]\n
Generate custom graphrag prompts with your own data (i.e. auto templating).
Usage:
prompt-tune [OPTIONS]\n
Options:
"}, {"location": "cli/#query", "title": "query", "text": "--root PATH The project root directory. \\[default: .]\n --config PATH The configuration to use.\n --domain TEXT The domain your input data is related to.\n For example 'space science', 'microbiology',\n 'environmental news'. If not defined, a\n domain will be inferred from the input data.\n --selection-method [all|random|top|auto]\n The text chunk selection method. \\[default:\n random]\n --n-subset-max INTEGER The number of text chunks to embed when\n --selection-method=auto. \\[default: 300]\n --k INTEGER The maximum number of documents to select\n from each centroid when --selection-\n method=auto. \\[default: 15]\n --limit INTEGER The number of documents to load when\n --selection-method={random,top}. \\[default:\n 15]\n --max-tokens INTEGER The max token count for prompt generation.\n \\[default: 2000]\n --min-examples-required INTEGER\n The minimum number of examples to\n generate/include in the entity extraction\n prompt. \\[default: 2]\n --chunk-size INTEGER The max token count for prompt generation.\n \\[default: 200]\n --language TEXT The primary language used for inputs and\n outputs in graphrag prompts.\n --discover-entity-types / --no-discover-entity-types\n Discover and extract unspecified entity\n types. \\[default: discover-entity-types]\n --output PATH The directory to save prompts to, relative\n to the project root directory. \\[default:\n prompts]\n
Query a knowledge graph index.
Usage:
query [OPTIONS]\n
Options:
"}, {"location": "cli/#update", "title": "update", "text": "--method [local|global|drift|basic]\n The query algorithm to use. \\[required]\n --query TEXT The query to execute. \\[required]\n --config PATH The configuration to use.\n --data PATH Indexing pipeline output directory (i.e.\n contains the parquet files).\n --root PATH The project root directory. \\[default: .]\n --community-level INTEGER The community level in the Leiden community\n hierarchy from which to load community\n reports. Higher values represent reports\n from smaller communities. \\[default: 2]\n --dynamic-community-selection / --no-dynamic-community-selection\n Use global search with dynamic community\n selection. \\[default: no-dynamic-community-\n selection]\n --response-type TEXT Free form text describing the response type\n and format, can be anything, e.g. Multiple\n Paragraphs, Single Paragraph, Single\n Sentence, List of 3-7 Points, Single Page,\n Multi-Page Report. Default: Multiple\n Paragraphs \\[default: Multiple Paragraphs]\n --streaming / --no-streaming Print response in a streaming manner.\n \\[default: no-streaming]\n
Update an existing knowledge graph index.
Applies a default storage configuration (if not provided by config), saving the new index to the local file system in the
update_output
folder.Usage:
update [OPTIONS]\n
Options:
"}, {"location": "developing/", "title": "Development Guide", "text": ""}, {"location": "developing/#requirements", "title": "Requirements", "text": "Name Installation Purpose Python 3.10-3.12 Download The library is Python-based. Poetry Instructions Poetry is used for package management and virtualenv management in Python codebases"}, {"location": "developing/#getting-started", "title": "Getting Started", "text": ""}, {"location": "developing/#install-dependencies", "title": "Install Dependencies", "text": "--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --verbose / --no-verbose Run the indexing pipeline with verbose\n logging \\[default: no-verbose]\n --memprofile / --no-memprofile Run the indexing pipeline with memory\n profiling \\[default: no-memprofile]\n --logger [rich|print|none] The progress logger to use. \\[default:\n rich]\n --cache / --no-cache Use LLM cache. \\[default: cache]\n --skip-validation / --no-skip-validation\n Skip any preflight validation. Useful when\n running no LLM steps. \\[default: no-skip-\n validation]\n --output PATH Indexing pipeline output directory.\n Overrides storage.base_dir in the\n configuration file.\n
"}, {"location": "developing/#execute-the-indexing-engine", "title": "Execute the Indexing Engine", "text": "# Install Python dependencies.\npoetry install\n
"}, {"location": "developing/#executing-queries", "title": "Executing Queries", "text": "poetry run poe index <...args>\n
"}, {"location": "developing/#azurite", "title": "Azurite", "text": "poetry run poe query <...args>\n
Some unit and smoke tests use Azurite to emulate Azure resources. This can be started by running:
./scripts/start-azurite.sh\n
or by simply running
"}, {"location": "developing/#lifecycle-scripts", "title": "Lifecycle Scripts", "text": "azurite
in the terminal if already installed globally. See the Azurite documentation for more information about how to install and use Azurite.Our Python package utilizes Poetry to manage dependencies and poethepoet to manage build scripts.
Available scripts are:
"}, {"location": "developing/#troubleshooting", "title": "Troubleshooting", "text": ""}, {"location": "developing/#runtimeerror-llvm-config-failed-executing-please-point-llvm_config-to-the-path-for-llvm-config-when-running-poetry-install", "title": "\"RuntimeError: llvm-config failed executing, please point LLVM_CONFIG to the path for llvm-config\" when running poetry install", "text": "
poetry run poe index
- Run the Indexing CLIpoetry run poe query
- Run the Query CLIpoetry build
- This invokespoetry build
, which will build a wheel file and other distributable artifacts.poetry run poe test
- This will execute all tests.poetry run poe test_unit
- This will execute unit tests.poetry run poe test_integration
- This will execute integration tests.poetry run poe test_smoke
- This will execute smoke tests.poetry run poe check
- This will perform a suite of static checks across the package, including:- formatting
- documentation formatting
- linting
- security patterns
- type-checking
poetry run poe fix
- This will apply any available auto-fixes to the package. Usually this is just formatting fixes.poetry run poe fix_unsafe
- This will apply any available auto-fixes to the package, including those that may be unsafe.poetry run poe format
- Explicitly run the formatter across the package.Make sure llvm-9 and llvm-9-dev are installed:
sudo apt-get install llvm-9 llvm-9-dev
and then in your bashrc, add
"}, {"location": "developing/#numba_pymoduleh610-fatal-error-pythonh-no-such-file-or-directory-when-running-poetry-install", "title": "\"numba/_pymodule.h:6:10: fatal error: Python.h: No such file or directory\" when running poetry install", "text": "
export LLVM_CONFIG=/usr/bin/llvm-config-9
Make sure you have python3.10-dev installed or more generally
python<version>-dev
"}, {"location": "developing/#llm-call-constantly-exceeds-tpm-rpm-or-time-limits", "title": "LLM call constantly exceeds TPM, RPM or time limits", "text": "
sudo apt-get install python3.10-dev
"}, {"location": "get_started/", "title": "Getting Started", "text": ""}, {"location": "get_started/#requirements", "title": "Requirements", "text": "
GRAPHRAG_LLM_THREAD_COUNT
andGRAPHRAG_EMBEDDING_THREAD_COUNT
are both set to 50 by default. You can modify these values to reduce concurrency. Please refer to the Configuration DocumentsPython 3.10-3.12
To get started with the GraphRAG system, you have a few options:
\ud83d\udc49 Use the GraphRAG Accelerator solution \ud83d\udc49 Install from pypi. \ud83d\udc49 Use it from source
"}, {"location": "get_started/#quickstart", "title": "Quickstart", "text": "To get started with the GraphRAG system we recommend trying the Solution Accelerator package. This provides a user-friendly end-to-end experience with Azure resources.
"}, {"location": "get_started/#overview", "title": "Overview", "text": "The following is a simple end-to-end example for using the GraphRAG system. It shows how to use the system to index some text, and then use the indexed data to answer questions about the documents.
"}, {"location": "get_started/#install-graphrag", "title": "Install GraphRAG", "text": "pip install graphrag\n
The graphrag library includes a CLI for a no-code approach to getting started. Please review the full CLI documentation for further detail.
"}, {"location": "get_started/#running-the-indexer", "title": "Running the Indexer", "text": "We need to set up a data project and some initial configuration. First let's get a sample dataset ready:
mkdir -p ./ragtest/input\n
Get a copy of A Christmas Carol by Charles Dickens from a trusted source:
"}, {"location": "get_started/#set-up-your-workspace-variables", "title": "Set Up Your Workspace Variables", "text": "curl https://www.gutenberg.org/cache/epub/24022/pg24022.txt -o ./ragtest/input/book.txt\n
To initialize your workspace, first run the
graphrag init
command. Since we have already configured a directory named./ragtest
in the previous step, run the following command:graphrag init --root ./ragtest\n
This will create two files:
.env
andsettings.yaml
in the./ragtest
directory."}, {"location": "get_started/#openai-and-azure-openai", "title": "OpenAI and Azure OpenAI", "text": "
.env
contains the environment variables required to run the GraphRAG pipeline. If you inspect the file, you'll see a single environment variable defined,GRAPHRAG_API_KEY=<API_KEY>
. This is the API key for the OpenAI API or Azure OpenAI endpoint. You can replace this with your own API key. If you are using another form of authentication (i.e. managed identity), please delete this file.settings.yaml
contains the settings for the pipeline. You can modify this file to change the settings for the pipeline.If running in OpenAI mode, update the value of
"}, {"location": "get_started/#azure-openai", "title": "Azure OpenAI", "text": "GRAPHRAG_API_KEY
in the.env
file with your OpenAI API key.In addition, Azure OpenAI users should set the following variables in the settings.yaml file. To find the appropriate sections, just search for the
llm:
configuration, you should see two sections, one for the chat endpoint and one for the embeddings endpoint. Here is an example of how to configure the chat endpoint:type: azure_openai_chat # Or azure_openai_embedding for embeddings\napi_base: https://<instance>.openai.azure.com\napi_version: 2024-02-15-preview # You can customize this for other versions\ndeployment_name: <azure_model_deployment_name>\n
"}, {"location": "get_started/#running-the-indexing-pipeline", "title": "Running the Indexing pipeline", "text": "
- For more details about configuring GraphRAG, see the configuration documentation.
- To learn more about Initialization, refer to the Initialization documentation.
- For more details about using the CLI, refer to the CLI documentation.
Finally we'll run the pipeline!
graphrag index --root ./ragtest\n
This process will take some time to run. This depends on the size of your input data, what model you're using, and the text chunk size being used (these can be configured in your
"}, {"location": "get_started/#using-the-query-engine", "title": "Using the Query Engine", "text": ""}, {"location": "get_started/#running-the-query-engine", "title": "Running the Query Engine", "text": "settings.yml
file). Once the pipeline is complete, you should see a new folder called./ragtest/output
with a series of parquet files.Now let's ask some questions using this dataset.
Here is an example using Global search to ask a high-level question:
graphrag query \\\n--root ./ragtest \\\n--method global \\\n--query \"What are the top themes in this story?\"\n
Here is an example using Local search to ask a more specific question about a particular character:
graphrag query \\\n--root ./ragtest \\\n--method local \\\n--query \"Who is Scrooge and what are his main relationships?\"\n
Please refer to Query Engine docs for detailed information about how to leverage our Local and Global search mechanisms for extracting meaningful insights from data after the Indexer has wrapped up execution.
"}, {"location": "get_started/#visualizing-the-graph", "title": "Visualizing the Graph", "text": "Check out our visualization guide for a more interactive experience in debugging and exploring the knowledge graph.
"}, {"location": "visualization_guide/", "title": "Visualizing and Debugging Your Knowledge Graph", "text": "The following step-by-step guide walks through the process to visualize a knowledge graph after it's been constructed by graphrag. Note that some of the settings recommended below are based on our own experience of what works well. Feel free to change and explore other settings for a better visualization experience!
"}, {"location": "visualization_guide/#1-run-the-pipeline", "title": "1. Run the Pipeline", "text": "Before building an index, please review your
settings.yaml
configuration file and ensure that graphml snapshots is enabled.(Optional) To support other visualization tools and exploration, additional parameters can be enabled that provide access to vector embeddings.snapshots:\n graphml: true\n
After running the indexing pipeline over your data, there will be an output folder (defined by theembed_graph:\n enabled: true # will generate node2vec embeddings for nodes\numap:\n enabled: true # will generate UMAP embeddings for nodes\n
storage.base_dir
setting)."}, {"location": "visualization_guide/#2-locate-the-knowledge-graph", "title": "2. Locate the Knowledge Graph", "text": "
- Output Folder: Contains artifacts from the LLM\u2019s indexing pass.
In the output folder, look for a file named
"}, {"location": "visualization_guide/#3-open-the-graph-in-gephi", "title": "3. Open the Graph in Gephi", "text": "merged_graph.graphml
. graphml is a standard file format supported by many visualization tools. We recommend trying Gephi."}, {"location": "visualization_guide/#4-install-the-leiden-algorithm-plugin", "title": "4. Install the Leiden Algorithm Plugin", "text": "
- Install and open Gephi
- Navigate to the
output
folder containing the various parquet files.- Import the
merged_graph.graphml
file into Gephi. This will result in a fairly plain view of the undirected graph nodes and edges."}, {"location": "visualization_guide/#5-run-statistics", "title": "5. Run Statistics", "text": "
- Go to
Tools
->Plugins
.- Search for \"Leiden Algorithm\".
- Click
Install
and restart Gephi.
- In the
Statistics
tab on the right, clickRun
forAverage Degree
andLeiden Algorithm
."}, {"location": "visualization_guide/#6-color-the-graph-by-clusters", "title": "6. Color the Graph by Clusters", "text": "
- For the Leiden Algorithm, adjust the settings:
- Quality function: Modularity
- Resolution: 1
- Go to the
Appearance
pane in the upper left side of Gephi."}, {"location": "visualization_guide/#7-resize-nodes-by-degree-centrality", "title": "7. Resize Nodes by Degree Centrality", "text": "
- Select
Nodes
, thenPartition
, and click the color palette icon in the upper right.- Choose
Cluster
from the dropdown.- Click the
Palette...
hyperlink, thenGenerate...
.- Uncheck
Limit number of colors
, clickGenerate
, and thenOk
.- Click
Apply
to color the graph. This will color the graph based on the partitions discovered by Leiden."}, {"location": "visualization_guide/#8-layout-the-graph", "title": "8. Layout the Graph", "text": "
- In the
Appearance
pane in the upper left, selectNodes
->Ranking
- Select the
Sizing
icon in the upper right.- Choose
Degree
and set:- Min: 10
- Max: 150
- Click
Apply
.
- In the
Layout
tab in the lower left, selectOpenORD
."}, {"location": "visualization_guide/#9-run-forceatlas2", "title": "9. Run ForceAtlas2", "text": "
- Set
Liquid
andExpansion
stages to 50, and everything else to 0.- Click
Run
and monitor the progress.
- Select
Force Atlas 2
in the layout options."}, {"location": "visualization_guide/#10-add-text-labels-optional", "title": "10. Add Text Labels (Optional)", "text": "
- Adjust the settings:
- Scaling: 15
- Dissuade Hubs: checked
- LinLog mode: uncheck
- Prevent Overlap: checked
- Click
Run
and wait.- Press
Stop
when it looks like the graph nodes have settled and no longer change position significantly.
- Turn on text labels in the appropriate section.
- Configure and resize them as needed.
Your final graph should now be visually organized and ready for analysis!
"}, {"location": "config/env_vars/", "title": "Default Configuration Mode (using Env Vars)", "text": ""}, {"location": "config/env_vars/#text-embeddings-customization", "title": "Text-Embeddings Customization", "text": "By default, the GraphRAG indexer will only export embeddings required for our query methods. However, the model has embeddings defined for all plaintext fields, and these can be generated by setting the
GRAPHRAG_EMBEDDING_TARGET
environment variable toall
.If the embedding target is
"}, {"location": "config/env_vars/#embedded-fields", "title": "Embedded Fields", "text": "all
, and you want to only embed a subset of these fields, you may specify which embeddings to skip using theGRAPHRAG_EMBEDDING_SKIP
argument described below."}, {"location": "config/env_vars/#input-data", "title": "Input Data", "text": "
text_unit.text
document.text
entity.title
entity.description
relationship.description
community.title
community.summary
community.full_content
Our pipeline can ingest .csv or .txt data from an input folder. These files can be nested within subfolders. To configure how input data is handled, what fields are mapped over, and how timestamps are parsed, look for configuration values starting with
"}, {"location": "config/env_vars/#base-llm-settings", "title": "Base LLM Settings", "text": "GRAPHRAG_INPUT_
below. In general, CSV-based data provides the most customizability. Each CSV should at least contain atext
field (which can be mapped with environment variables), but it's helpful if they also havetitle
,timestamp
, andsource
fields. Additional fields can be included as well, which will land as extra fields on theDocument
table.These are the primary settings for configuring LLM connectivity.
Parameter Required? Description Type Default ValueGRAPHRAG_API_KEY
Yes for OpenAI. Optional for AOAI The API key. (Note:OPENAI_API_KEY is also used as a fallback). If not defined when using AOAI, managed identity will be used. |
str|
None`GRAPHRAG_API_BASE
For AOAI The API Base URLstr
None
GRAPHRAG_API_VERSION
For AOAI The AOAI API version.str
None
GRAPHRAG_API_ORGANIZATION
The AOAI organization.str
None
GRAPHRAG_API_PROXY
The AOAI proxy.str
None
"}, {"location": "config/env_vars/#text-generation-settings", "title": "Text Generation Settings", "text": "These settings control the text generation model used by the pipeline. Any settings with a fallback will use the base LLM settings, if available.
Parameter Required? Description Type Default ValueGRAPHRAG_LLM_TYPE
For AOAI The LLM operation type. Eitheropenai_chat
orazure_openai_chat
str
openai_chat
GRAPHRAG_LLM_DEPLOYMENT_NAME
For AOAI The AOAI model deployment name.str
None
GRAPHRAG_LLM_API_KEY
Yes (uses fallback) The API key. If not defined when using AOAI, managed identity will be used.str
None
GRAPHRAG_LLM_API_BASE
For AOAI (uses fallback) The API Base URLstr
None
GRAPHRAG_LLM_API_VERSION
For AOAI (uses fallback) The AOAI API version.str
None
GRAPHRAG_LLM_API_ORGANIZATION
For AOAI (uses fallback) The AOAI organization.str
None
GRAPHRAG_LLM_API_PROXY
The AOAI proxy.str
None
GRAPHRAG_LLM_MODEL
The LLM model.str
gpt-4-turbo-preview
GRAPHRAG_LLM_MAX_TOKENS
The maximum number of tokens.int
4000
GRAPHRAG_LLM_REQUEST_TIMEOUT
The maximum number of seconds to wait for a response from the chat client.int
180
GRAPHRAG_LLM_MODEL_SUPPORTS_JSON
Indicates whether the given model supports JSON output mode.True
to enable.str
None
GRAPHRAG_LLM_THREAD_COUNT
The number of threads to use for LLM parallelization.int
50GRAPHRAG_LLM_THREAD_STAGGER
The time to wait (in seconds) between starting each thread.float
0.3GRAPHRAG_LLM_CONCURRENT_REQUESTS
The number of concurrent requests to allow for the embedding client.int
25GRAPHRAG_LLM_TOKENS_PER_MINUTE
The number of tokens per minute to allow for the LLM client. 0 = Bypassint
0GRAPHRAG_LLM_REQUESTS_PER_MINUTE
The number of requests per minute to allow for the LLM client. 0 = Bypassint
0GRAPHRAG_LLM_MAX_RETRIES
The maximum number of retries to attempt when a request fails.int
10GRAPHRAG_LLM_MAX_RETRY_WAIT
The maximum number of seconds to wait between retries.int
10GRAPHRAG_LLM_SLEEP_ON_RATE_LIMIT_RECOMMENDATION
Whether to sleep on rate limit recommendation. (Azure Only)bool
True
GRAPHRAG_LLM_TEMPERATURE
The temperature to use generation.float
0GRAPHRAG_LLM_TOP_P
The top_p to use for sampling.float
1GRAPHRAG_LLM_N
The number of responses to generate.int
1"}, {"location": "config/env_vars/#text-embedding-settings", "title": "Text Embedding Settings", "text": "These settings control the text embedding model used by the pipeline. Any settings with a fallback will use the base LLM settings, if available.
Parameter Required ? Description Type DefaultGRAPHRAG_EMBEDDING_TYPE
For AOAI The embedding client to use. Eitheropenai_embedding
orazure_openai_embedding
str
openai_embedding
GRAPHRAG_EMBEDDING_DEPLOYMENT_NAME
For AOAI The AOAI deployment name.str
None
GRAPHRAG_EMBEDDING_API_KEY
Yes (uses fallback) The API key to use for the embedding client. If not defined when using AOAI, managed identity will be used.str
None
GRAPHRAG_EMBEDDING_API_BASE
For AOAI (uses fallback) The API base URL.str
None
GRAPHRAG_EMBEDDING_API_VERSION
For AOAI (uses fallback) The AOAI API version to use for the embedding client.str
None
GRAPHRAG_EMBEDDING_API_ORGANIZATION
For AOAI (uses fallback) The AOAI organization to use for the embedding client.str
None
GRAPHRAG_EMBEDDING_API_PROXY
The AOAI proxy to use for the embedding client.str
None
GRAPHRAG_EMBEDDING_MODEL
The model to use for the embedding client.str
text-embedding-3-small
GRAPHRAG_EMBEDDING_BATCH_SIZE
The number of texts to embed at once. (Azure limit is 16)int
16GRAPHRAG_EMBEDDING_BATCH_MAX_TOKENS
The maximum tokens per batch (Azure limit is 8191)int
8191GRAPHRAG_EMBEDDING_TARGET
The target fields to embed. Eitherrequired
orall
.str
required
GRAPHRAG_EMBEDDING_SKIP
A comma-separated list of fields to skip embeddings for . (e.g. 'relationship.description')str
None
GRAPHRAG_EMBEDDING_THREAD_COUNT
The number of threads to use for parallelization for embeddings.int
GRAPHRAG_EMBEDDING_THREAD_STAGGER
The time to wait (in seconds) between starting each thread for embeddings.float
50GRAPHRAG_EMBEDDING_CONCURRENT_REQUESTS
The number of concurrent requests to allow for the embedding client.int
25GRAPHRAG_EMBEDDING_TOKENS_PER_MINUTE
The number of tokens per minute to allow for the embedding client. 0 = Bypassint
0GRAPHRAG_EMBEDDING_REQUESTS_PER_MINUTE
The number of requests per minute to allow for the embedding client. 0 = Bypassint
0GRAPHRAG_EMBEDDING_MAX_RETRIES
The maximum number of retries to attempt when a request fails.int
10GRAPHRAG_EMBEDDING_MAX_RETRY_WAIT
The maximum number of seconds to wait between retries.int
10GRAPHRAG_EMBEDDING_SLEEP_ON_RATE_LIMIT_RECOMMENDATION
Whether to sleep on rate limit recommendation. (Azure Only)bool
True
"}, {"location": "config/env_vars/#input-settings", "title": "Input Settings", "text": "These settings control the data input used by the pipeline. Any settings with a fallback will use the base LLM settings, if available.
"}, {"location": "config/env_vars/#plaintext-input-data-graphrag_input_file_typetext", "title": "Plaintext Input Data (GRAPHRAG_INPUT_FILE_TYPE
=text)", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_INPUT_FILE_PATTERN
The file pattern regexp to use when reading input files from the input directory.str
optional.*\\.txt$
"}, {"location": "config/env_vars/#csv-input-data-graphrag_input_file_typecsv", "title": "CSV Input Data (GRAPHRAG_INPUT_FILE_TYPE
=csv)", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_INPUT_TYPE
The input storage type to use when reading files. (file
orblob
)str
optionalfile
GRAPHRAG_INPUT_FILE_PATTERN
The file pattern regexp to use when reading input files from the input directory.str
optional.*\\.txt$
GRAPHRAG_INPUT_SOURCE_COLUMN
The 'source' column to use when reading CSV input files.str
optionalsource
GRAPHRAG_INPUT_TIMESTAMP_COLUMN
The 'timestamp' column to use when reading CSV input files.str
optionalNone
GRAPHRAG_INPUT_TIMESTAMP_FORMAT
The timestamp format to use when parsing timestamps in the timestamp column.str
optionalNone
GRAPHRAG_INPUT_TEXT_COLUMN
The 'text' column to use when reading CSV input files.str
optionaltext
GRAPHRAG_INPUT_DOCUMENT_ATTRIBUTE_COLUMNS
A list of CSV columns, comma-separated, to incorporate as document fields.str
optionalid
GRAPHRAG_INPUT_TITLE_COLUMN
The 'title' column to use when reading CSV input files.str
optionaltitle
GRAPHRAG_INPUT_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optionalNone
GRAPHRAG_INPUT_CONNECTION_STRING
The connection string to use when reading CSV input files from Azure Blob Storage.str
optionalNone
GRAPHRAG_INPUT_CONTAINER_NAME
The container name to use when reading CSV input files from Azure Blob Storage.str
optionalNone
GRAPHRAG_INPUT_BASE_DIR
The base directory to read input files from.str
optionalNone
"}, {"location": "config/env_vars/#data-mapping-settings", "title": "Data Mapping Settings", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_INPUT_FILE_TYPE
The type of input data,csv
ortext
str
optionaltext
GRAPHRAG_INPUT_ENCODING
The encoding to apply when reading CSV/text input files.str
optionalutf-8
"}, {"location": "config/env_vars/#data-chunking", "title": "Data Chunking", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_CHUNK_SIZE
The chunk size in tokens for text-chunk analysis windows.str
optional 1200GRAPHRAG_CHUNK_OVERLAP
The chunk overlap in tokens for text-chunk analysis windows.str
optional 100GRAPHRAG_CHUNK_BY_COLUMNS
A comma-separated list of document attributes to groupby when performing TextUnit chunking.str
optionalid
GRAPHRAG_CHUNK_ENCODING_MODEL
The encoding model to use for chunking.str
optional The top-level encoding model."}, {"location": "config/env_vars/#prompting-overrides", "title": "Prompting Overrides", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_ENTITY_EXTRACTION_PROMPT_FILE
The path (relative to the root) of an entity extraction prompt template text file.str
optionalNone
GRAPHRAG_ENTITY_EXTRACTION_MAX_GLEANINGS
The maximum number of redrives (gleanings) to invoke when extracting entities in a loop.int
optional 1GRAPHRAG_ENTITY_EXTRACTION_ENTITY_TYPES
A comma-separated list of entity types to extract.str
optionalorganization,person,event,geo
GRAPHRAG_ENTITY_EXTRACTION_ENCODING_MODEL
The encoding model to use for entity extraction.str
optional The top-level encoding model.GRAPHRAG_SUMMARIZE_DESCRIPTIONS_PROMPT_FILE
The path (relative to the root) of an description summarization prompt template text file.str
optionalNone
GRAPHRAG_SUMMARIZE_DESCRIPTIONS_MAX_LENGTH
The maximum number of tokens to generate per description summarization.int
optional 500GRAPHRAG_CLAIM_EXTRACTION_ENABLED
Whether claim extraction is enabled for this pipeline.bool
optionalFalse
GRAPHRAG_CLAIM_EXTRACTION_DESCRIPTION
The claim_description prompting argument to utilize.string
optional \"Any claims or facts that could be relevant to threat analysis.\"GRAPHRAG_CLAIM_EXTRACTION_PROMPT_FILE
The claim extraction prompt to utilize.string
optionalNone
GRAPHRAG_CLAIM_EXTRACTION_MAX_GLEANINGS
The maximum number of redrives (gleanings) to invoke when extracting claims in a loop.int
optional 1GRAPHRAG_CLAIM_EXTRACTION_ENCODING_MODEL
The encoding model to use for claim extraction.str
optional The top-level encoding modelGRAPHRAG_COMMUNITY_REPORTS_PROMPT_FILE
The community reports extraction prompt to utilize.string
optionalNone
GRAPHRAG_COMMUNITY_REPORTS_MAX_LENGTH
The maximum number of tokens to generate per community reports.int
optional 1500"}, {"location": "config/env_vars/#storage", "title": "Storage", "text": "This section controls the storage mechanism used by the pipeline used for exporting output tables.
Parameter Description Type Required or Optional DefaultGRAPHRAG_STORAGE_TYPE
The type of storage to use. Options arefile
,memory
, orblob
str
optionalfile
GRAPHRAG_STORAGE_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optional NoneGRAPHRAG_STORAGE_CONNECTION_STRING
The Azure Storage connection string to use when inblob
mode.str
optional NoneGRAPHRAG_STORAGE_CONTAINER_NAME
The Azure Storage container name to use when inblob
mode.str
optional NoneGRAPHRAG_STORAGE_BASE_DIR
The base path to data outputs outputs.str
optional None"}, {"location": "config/env_vars/#cache", "title": "Cache", "text": "This section controls the cache mechanism used by the pipeline. This is used to cache LLM invocation results.
Parameter Description Type Required or Optional DefaultGRAPHRAG_CACHE_TYPE
The type of cache to use. Options arefile
,memory
,none
orblob
str
optionalfile
GRAPHRAG_CACHE_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optional NoneGRAPHRAG_CACHE_CONNECTION_STRING
The Azure Storage connection string to use when inblob
mode.str
optional NoneGRAPHRAG_CACHE_CONTAINER_NAME
The Azure Storage container name to use when inblob
mode.str
optional NoneGRAPHRAG_CACHE_BASE_DIR
The base path to the cache files.str
optional None"}, {"location": "config/env_vars/#reporting", "title": "Reporting", "text": "This section controls the reporting mechanism used by the pipeline, for common events and error messages. The default is to write reports to a file in the output directory. However, you can also choose to write reports to the console or to an Azure Blob Storage container.
Parameter Description Type Required or Optional DefaultGRAPHRAG_REPORTING_TYPE
The type of reporter to use. Options arefile
,console
, orblob
str
optionalfile
GRAPHRAG_REPORTING_STORAGE_ACCOUNT_BLOB_URL
The Azure Storage blob endpoint to use when inblob
mode and using managed identity. Will have the formathttps://<storage_account_name>.blob.core.windows.net
str
optional NoneGRAPHRAG_REPORTING_CONNECTION_STRING
The Azure Storage connection string to use when inblob
mode.str
optional NoneGRAPHRAG_REPORTING_CONTAINER_NAME
The Azure Storage container name to use when inblob
mode.str
optional NoneGRAPHRAG_REPORTING_BASE_DIR
The base path to the reporting outputs.str
optional None"}, {"location": "config/env_vars/#node2vec-parameters", "title": "Node2Vec Parameters", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_NODE2VEC_ENABLED
Whether to enable Node2Vecbool
optional FalseGRAPHRAG_NODE2VEC_NUM_WALKS
The Node2Vec number of walks to performint
optional 10GRAPHRAG_NODE2VEC_WALK_LENGTH
The Node2Vec walk lengthint
optional 40GRAPHRAG_NODE2VEC_WINDOW_SIZE
The Node2Vec window sizeint
optional 2GRAPHRAG_NODE2VEC_ITERATIONS
The number of iterations to run node2vecint
optional 3GRAPHRAG_NODE2VEC_RANDOM_SEED
The random seed to use for node2vecint
optional 597832"}, {"location": "config/env_vars/#data-snapshotting", "title": "Data Snapshotting", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_SNAPSHOT_EMBEDDINGS
Whether to enable embeddings snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_GRAPHML
Whether to enable GraphML snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_RAW_ENTITIES
Whether to enable raw entity snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_TOP_LEVEL_NODES
Whether to enable top-level node snapshots.bool
optional FalseGRAPHRAG_SNAPSHOT_TRANSIENT
Whether to enable transient table snapshots.bool
optional False"}, {"location": "config/env_vars/#miscellaneous-settings", "title": "Miscellaneous Settings", "text": "Parameter Description Type Required or Optional DefaultGRAPHRAG_ASYNC_MODE
Which async mode to use. Eitherasyncio
orthreaded
.str
optionalasyncio
GRAPHRAG_ENCODING_MODEL
The text encoding model, used in tiktoken, to encode text.str
optionalcl100k_base
GRAPHRAG_MAX_CLUSTER_SIZE
The maximum number of entities to include in a single Leiden cluster.int
optional 10GRAPHRAG_SKIP_WORKFLOWS
A comma-separated list of workflow names to skip.str
optionalNone
GRAPHRAG_UMAP_ENABLED
Whether to enable UMAP layoutsbool
optional False"}, {"location": "config/init/", "title": "Configuring GraphRAG Indexing", "text": "To start using GraphRAG, you must generate a configuration file. The
"}, {"location": "config/init/#usage", "title": "Usage", "text": "init
command is the easiest way to get started. It will create a.env
andsettings.yaml
files in the specified directory with the necessary configuration settings. It will also output the default LLM prompts used by GraphRAG."}, {"location": "config/init/#options", "title": "Options", "text": "graphrag init [--root PATH]\n
"}, {"location": "config/init/#example", "title": "Example", "text": "
--root PATH
- The project root directory to initialize graphrag at. Default is the current directory."}, {"location": "config/init/#output", "title": "Output", "text": "graphrag init --root ./ragtest\n
The
init
command will create the following files in the specified directory:"}, {"location": "config/init/#next-steps", "title": "Next Steps", "text": "
settings.yaml
- The configuration settings file. This file contains the configuration settings for GraphRAG..env
- The environment variables file. These are referenced in thesettings.yaml
file.prompts/
- The LLM prompts folder. This contains the default prompts used by GraphRAG, you can modify them or run the Auto Prompt Tuning command to generate new prompts adapted to your data.After initializing your workspace, you can either run the Prompt Tuning command to adapt the prompts to your data or even start running the Indexing Pipeline to index your data. For more information on configuring GraphRAG, see the Configuration documentation.
"}, {"location": "config/overview/", "title": "Configuring GraphRAG Indexing", "text": "The GraphRAG system is highly configurable. This page provides an overview of the configuration options available for the GraphRAG indexing engine.
"}, {"location": "config/overview/#default-configuration-mode", "title": "Default Configuration Mode", "text": "The default configuration mode is the simplest way to get started with the GraphRAG system. It is designed to work out-of-the-box with minimal configuration. The primary configuration sections for the Indexing Engine pipelines are described below. The main ways to set up GraphRAG in Default Configuration mode are via:
"}, {"location": "config/yaml/", "title": "Default Configuration Mode (using YAML/JSON)", "text": "
- Init command (recommended)
- Using YAML for deeper control
- Purely using environment variables
The default configuration mode may be configured by using a
settings.yml
orsettings.json
file in the data project root. If a.env
file is present along with this config file, then it will be loaded, and the environment variables defined therein will be available for token replacements in your configuration document using${ENV_VAR}
syntax. We initialize with YML by default ingraphrag init
but you may use the equivalent JSON form if preferred.Many of these config values have defaults. Rather than replicate them here, please refer to the constants in the code directly.
For example:
"}, {"location": "config/yaml/#config-sections", "title": "Config Sections", "text": ""}, {"location": "config/yaml/#indexing", "title": "Indexing", "text": ""}, {"location": "config/yaml/#llm", "title": "llm", "text": "# .env\nGRAPHRAG_API_KEY=some_api_key\n\n# settings.yml\nllm: \n api_key: ${GRAPHRAG_API_KEY}\n
This is the base LLM configuration section. Other steps may override this configuration with their own LLM configuration.
"}, {"location": "config/yaml/#fields", "title": "Fields", "text": ""}, {"location": "config/yaml/#parallelization", "title": "parallelization", "text": ""}, {"location": "config/yaml/#fields_1", "title": "Fields", "text": "
api_key
str - The OpenAI API key to use.type
openai_chat|azure_openai_chat|openai_embedding|azure_openai_embedding - The type of LLM to use.model
str - The model name.max_tokens
int - The maximum number of output tokens.request_timeout
float - The per-request timeout.api_base
str - The API base url to use.api_version
str - The API versionorganization
str - The client organization.proxy
str - The proxy URL to use.audience
str - (Azure OpenAI only) The URI of the target Azure resource/service for which a managed identity token is requested. Used ifapi_key
is not defined. Default=https://cognitiveservices.azure.com/.default
deployment_name
str - The deployment name to use (Azure).model_supports_json
bool - Whether the model supports JSON-mode output.tokens_per_minute
int - Set a leaky-bucket throttle on tokens-per-minute.requests_per_minute
int - Set a leaky-bucket throttle on requests-per-minute.max_retries
int - The maximum number of retries to use.max_retry_wait
float - The maximum backoff time.sleep_on_rate_limit_recommendation
bool - Whether to adhere to sleep recommendations (Azure).concurrent_requests
int The number of open requests to allow at once.temperature
float - The temperature to use.top_p
float - The top-p value to use.n
int - The number of completions to generate."}, {"location": "config/yaml/#async_mode", "title": "async_mode", "text": "
stagger
float - The threading stagger value.num_threads
int - The maximum number of work threads.asyncio|threaded The async mode to use. Either
"}, {"location": "config/yaml/#embeddings", "title": "embeddings", "text": ""}, {"location": "config/yaml/#fields_2", "title": "Fields", "text": "asyncio
or `threaded."}, {"location": "config/yaml/#input", "title": "input", "text": ""}, {"location": "config/yaml/#fields_3", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)batch_size
int - The maximum batch size to use.batch_max_tokens
int - The maximum batch # of tokens.target
required|all|none - Determines which set of embeddings to export.skip
list[str] - Which embeddings to skip. Only useful if target=all to customize the list.vector_store
dict - The vector store to use. Configured for lancedb by default.
type
str -lancedb
orazure_ai_search
. Default=lancedb
db_uri
str (only for lancedb) - The database uri. Default=storage.base_dir/lancedb
url
str (only for AI Search) - AI Search endpointapi_key
str (optional - only for AI Search) - The AI Search api key to use.audience
str (only for AI Search) - Audience for managed identity token if managed identity authentication is used.overwrite
bool (only used at index creation time) - Overwrite collection if it exist. Default=True
container_name
str - The name of a vector container. This stores all indexes (tables) for a given dataset ingest. Default=default
strategy
dict - Fully override the text-embedding strategy."}, {"location": "config/yaml/#chunks", "title": "chunks", "text": ""}, {"location": "config/yaml/#fields_4", "title": "Fields", "text": "
type
file|blob - The input type to use. Default=file
file_type
text|csv - The type of input data to load. Eithertext
orcsv
. Default istext
base_dir
str - The base directory to read input from, relative to the root.connection_string
str - (blob only) The Azure Storage connection string.storage_account_blob_url
str - The storage account blob URL to use.container_name
str - (blob only) The Azure Storage container name.file_encoding
str - The encoding of the input file. Default isutf-8
file_pattern
str - A regex to match input files. Default is.*\\.csv$
if in csv mode and.*\\.txt$
if in text mode.file_filter
dict - Key/value pairs to filter. Default is None.source_column
str - (CSV Mode Only) The source column name.timestamp_column
str - (CSV Mode Only) The timestamp column name.timestamp_format
str - (CSV Mode Only) The source format.text_column
str - (CSV Mode Only) The text column name.title_column
str - (CSV Mode Only) The title column name.document_attribute_columns
list[str] - (CSV Mode Only) The additional document attributes to include."}, {"location": "config/yaml/#cache", "title": "cache", "text": ""}, {"location": "config/yaml/#fields_5", "title": "Fields", "text": "
size
int - The max chunk size in tokens.overlap
int - The chunk overlap in tokens.group_by_columns
list[str] - group documents by fields before chunking.encoding_model
str - The text encoding model to use. Default is to use the top-level encoding model.strategy
dict - Fully override the chunking strategy."}, {"location": "config/yaml/#storage", "title": "storage", "text": ""}, {"location": "config/yaml/#fields_6", "title": "Fields", "text": "
type
file|memory|none|blob - The cache type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write cache to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#update_index_storage", "title": "update_index_storage", "text": ""}, {"location": "config/yaml/#fields_7", "title": "Fields", "text": "
type
file|memory|blob - The storage type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write output artifacts to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#reporting", "title": "reporting", "text": ""}, {"location": "config/yaml/#fields_8", "title": "Fields", "text": "
type
file|memory|blob - The storage type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write output artifacts to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#entity_extraction", "title": "entity_extraction", "text": ""}, {"location": "config/yaml/#fields_9", "title": "Fields", "text": "
type
file|console|blob - The reporting type to use. Default=file
connection_string
str - (blob only) The Azure Storage connection string.container_name
str - (blob only) The Azure Storage container name.base_dir
str - The base directory to write reports to, relative to the root.storage_account_blob_url
str - The storage account blob URL to use."}, {"location": "config/yaml/#summarize_descriptions", "title": "summarize_descriptions", "text": ""}, {"location": "config/yaml/#fields_10", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.entity_types
list[str] - The entity types to identify.max_gleanings
int - The maximum number of gleaning cycles to use.encoding_model
str - The text encoding model to use. By default, this will use the top-level encoding model.strategy
dict - Fully override the entity extraction strategy."}, {"location": "config/yaml/#claim_extraction", "title": "claim_extraction", "text": ""}, {"location": "config/yaml/#fields_11", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.max_length
int - The maximum number of output tokens per summarization.strategy
dict - Fully override the summarize description strategy."}, {"location": "config/yaml/#community_reports", "title": "community_reports", "text": ""}, {"location": "config/yaml/#fields_12", "title": "Fields", "text": "
enabled
bool - Whether to enable claim extraction. Off by default, because claim prompts really need user tuning.llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.description
str - Describes the types of claims we want to extract.max_gleanings
int - The maximum number of gleaning cycles to use.encoding_model
str - The text encoding model to use. By default, this will use the top-level encoding model.strategy
dict - Fully override the claim extraction strategy."}, {"location": "config/yaml/#cluster_graph", "title": "cluster_graph", "text": ""}, {"location": "config/yaml/#fields_13", "title": "Fields", "text": "
llm
(see LLM top-level config)parallelization
(see Parallelization top-level config)async_mode
(see Async Mode top-level config)prompt
str - The prompt file to use.max_length
int - The maximum number of output tokens per report.max_input_length
int - The maximum number of input tokens to use when generating reports.strategy
dict - Fully override the community reports strategy."}, {"location": "config/yaml/#embed_graph", "title": "embed_graph", "text": ""}, {"location": "config/yaml/#fields_14", "title": "Fields", "text": "
max_cluster_size
int - The maximum cluster size to export.strategy
dict - Fully override the cluster_graph strategy."}, {"location": "config/yaml/#umap", "title": "umap", "text": ""}, {"location": "config/yaml/#fields_15", "title": "Fields", "text": "
enabled
bool - Whether to enable graph embeddings.num_walks
int - The node2vec number of walks.walk_length
int - The node2vec walk length.window_size
int - The node2vec window size.iterations
int - The node2vec number of iterations.random_seed
int - The node2vec random seed.strategy
dict - Fully override the embed graph strategy."}, {"location": "config/yaml/#snapshots", "title": "snapshots", "text": ""}, {"location": "config/yaml/#fields_16", "title": "Fields", "text": "
enabled
bool - Whether to enable UMAP layouts."}, {"location": "config/yaml/#encoding_model", "title": "encoding_model", "text": "
embeddings
bool - Export embeddings snapshots to parquet.graphml
bool - Export graph snapshots to GraphML.transient
bool - Export transient workflow tables snapshots to parquet.str - The text encoding model to use. Default=
"}, {"location": "config/yaml/#skip_workflows", "title": "skip_workflows", "text": "cl100k_base
.list[str] - Which workflow names to skip.
"}, {"location": "config/yaml/#query", "title": "Query", "text": ""}, {"location": "config/yaml/#local_search", "title": "local_search", "text": ""}, {"location": "config/yaml/#fields_17", "title": "Fields", "text": ""}, {"location": "config/yaml/#global_search", "title": "global_search", "text": ""}, {"location": "config/yaml/#fields_18", "title": "Fields", "text": "
prompt
str - The prompt file to use.text_unit_prop
float - The text unit proportion.community_prop
float - The community proportion.conversation_history_max_turns
int - The conversation history maximum turns.top_k_entities
int - The top k mapped entities.top_k_relationships
int - The top k mapped relations.temperature
float | None - The temperature to use for token generation.top_p
float | None - The top-p value to use for token generation.n
int | None - The number of completions to generate.max_tokens
int - The maximum tokens.llm_max_tokens
int - The LLM maximum tokens."}, {"location": "config/yaml/#drift_search", "title": "drift_search", "text": ""}, {"location": "config/yaml/#fields_19", "title": "Fields", "text": "
map_prompt
str - The mapper prompt file to use.reduce_prompt
str - The reducer prompt file to use.knowledge_prompt
str - The knowledge prompt file to use.map_prompt
str | None - The global search mapper prompt to use.reduce_prompt
str | None - The global search reducer to use.knowledge_prompt
str | None - The global search general prompt to use.temperature
float | None - The temperature to use for token generation.top_p
float | None - The top-p value to use for token generation.n
int | None - The number of completions to generate.max_tokens
int - The maximum context size in tokens.data_max_tokens
int - The data llm maximum tokens.map_max_tokens
int - The map llm maximum tokens.reduce_max_tokens
int - The reduce llm maximum tokens.concurrency
int - The number of concurrent requests.dynamic_search_llm
str - LLM model to use for dynamic community selection.dynamic_search_threshold
int - Rating threshold in include a community report.dynamic_search_keep_parent
bool - Keep parent community if any of the child communities are relevant.dynamic_search_num_repeats
int - Number of times to rate the same community report.dynamic_search_use_summary
bool - Use community summary instead of full_context.dynamic_search_concurrent_coroutines
int - Number of concurrent coroutines to rate community reports.dynamic_search_max_level
int - The maximum level of community hierarchy to consider if none of the processed communities are relevant."}, {"location": "data/operation_dulce/ABOUT/", "title": "About", "text": "
prompt
str - The prompt file to use.temperature
float - The temperature to use for token generation.\",top_p
float - The top-p value to use for token generation.n
int - The number of completions to generate.max_tokens
int - The maximum context size in tokens.data_max_tokens
int - The data llm maximum tokens.concurrency
int - The number of concurrent requests.drift_k_followups
int - The number of top global results to retrieve.primer_folds
int - The number of folds for search priming.primer_llm_max_tokens
int - The maximum number of tokens for the LLM in primer.n_depth
int - The number of drift search steps to take.local_search_text_unit_prop
float - The proportion of search dedicated to text units.local_search_community_prop
float - The proportion of search dedicated to community properties.local_search_top_k_mapped_entities
int - The number of top K entities to map during local search.local_search_top_k_relationships
int - The number of top K relationships to map during local search.local_search_max_data_tokens
int - The maximum context size in tokens for local search.local_search_temperature
float - The temperature to use for token generation in local search.local_search_top_p
float - The top-p value to use for token generation in local search.local_search_n
int - The number of completions to generate in local search.local_search_llm_max_gen_tokens
int - The maximum number of generated tokens for the LLM in local search.This document (Operation Dulce) is an AI-generated science fiction novella, included here for the purposes of integration testing.
"}, {"location": "index/architecture/", "title": "Indexing Architecture", "text": ""}, {"location": "index/architecture/#key-concepts", "title": "Key Concepts", "text": ""}, {"location": "index/architecture/#knowledge-model", "title": "Knowledge Model", "text": "In order to support the GraphRAG system, the outputs of the indexing engine (in the Default Configuration Mode) are aligned to a knowledge model we call the GraphRAG Knowledge Model. This model is designed to be an abstraction over the underlying data storage technology, and to provide a common interface for the GraphRAG system to interact with. In normal use-cases the outputs of the GraphRAG Indexer would be loaded into a database system, and the GraphRAG's Query Engine would interact with the database using the knowledge model data-store types.
"}, {"location": "index/architecture/#workflows", "title": "Workflows", "text": "Because of the complexity of our data indexing tasks, we needed to be able to express our data pipeline as series of multiple, interdependent workflows.
"}, {"location": "index/architecture/#dataframe-message-format", "title": "Dataframe Message Format", "text": "---\ntitle: Sample Workflow DAG\n---\nstateDiagram-v2\n [*] --> Prepare\n Prepare --> Chunk\n Chunk --> ExtractGraph\n Chunk --> EmbedDocuments\n ExtractGraph --> GenerateReports\n ExtractGraph --> EmbedEntities\n ExtractGraph --> EmbedGraph
The primary unit of communication between workflows, and between workflow steps is an instance of
"}, {"location": "index/architecture/#llm-caching", "title": "LLM Caching", "text": "pandas.DataFrame
. Although side-effects are possible, our goal is to be data-centric and table-centric in our approach to data processing. This allows us to easily reason about our data, and to leverage the power of dataframe-based ecosystems. Our underlying dataframe technology may change over time, but our primary goal is to support the workflow schema while retaining single-machine ease of use and developer ergonomics.The GraphRAG library was designed with LLM interactions in mind, and a common setback when working with LLM APIs is various errors due to network latency, throttling, etc.. Because of these potential error cases, we've added a cache layer around LLM interactions. When completion requests are made using the same input set (prompt and tuning parameters), we return a cached result if one exists. This allows our indexer to be more resilient to network issues, to act idempotently, and to provide a more efficient end-user experience.
"}, {"location": "index/default_dataflow/", "title": "Indexing Dataflow", "text": ""}, {"location": "index/default_dataflow/#the-graphrag-knowledge-model", "title": "The GraphRAG Knowledge Model", "text": "The knowledge model is a specification for data outputs that conform to our data-model definition. You can find these definitions in the python/graphrag/graphrag/model folder within the GraphRAG repository. The following entity types are provided. The fields here represent the fields that are text-embedded by default.
"}, {"location": "index/default_dataflow/#the-default-configuration-workflow", "title": "The Default Configuration Workflow", "text": "
Document
- An input document into the system. These either represent individual rows in a CSV or individual .txt file.TextUnit
- A chunk of text to analyze. The size of these chunks, their overlap, and whether they adhere to any data boundaries may be configured below. A common use case is to setCHUNK_BY_COLUMNS
toid
so that there is a 1-to-many relationship between documents and TextUnits instead of a many-to-many.Entity
- An entity extracted from a TextUnit. These represent people, places, events, or some other entity-model that you provide.Relationship
- A relationship between two entities. These are generated from the covariates.Covariate
- Extracted claim information, which contains statements about entities which may be time-bound.Community
- Once the graph of entities and relationships is built, we perform hierarchical community detection on them to create a clustering structure.Community Report
- The contents of each community are summarized into a generated report, useful for human reading and downstream search.Node
- This table contains layout information for rendered graph-views of the Entities and Documents which have been embedded and clustered.Let's take a look at how the default-configuration workflow transforms text documents into the GraphRAG Knowledge Model. This page gives a general overview of the major steps in this process. To fully configure this workflow, check out the configuration documentation.
"}, {"location": "index/default_dataflow/#phase-1-compose-textunits", "title": "Phase 1: Compose TextUnits", "text": "---\ntitle: Dataflow Overview\n---\nflowchart TB\n subgraph phase1[Phase 1: Compose TextUnits]\n documents[Documents] --> chunk[Chunk]\n chunk --> embed[Embed] --> textUnits[Text Units]\n end\n subgraph phase2[Phase 2: Graph Extraction]\n textUnits --> graph_extract[Entity & Relationship Extraction]\n graph_extract --> graph_summarize[Entity & Relationship Summarization]\n graph_summarize --> claim_extraction[Claim Extraction]\n claim_extraction --> graph_outputs[Graph Tables]\n end\n subgraph phase3[Phase 3: Graph Augmentation]\n graph_outputs --> community_detect[Community Detection]\n community_detect --> graph_embed[Graph Embedding]\n graph_embed --> augmented_graph[Augmented Graph Tables]\n end\n subgraph phase4[Phase 4: Community Summarization]\n augmented_graph --> summarized_communities[Community Summarization]\n summarized_communities --> embed_communities[Community Embedding]\n embed_communities --> community_outputs[Community Tables]\n end\n subgraph phase5[Phase 5: Document Processing]\n documents --> link_to_text_units[Link to TextUnits]\n textUnits --> link_to_text_units\n link_to_text_units --> embed_documents[Document Embedding]\n embed_documents --> document_graph[Document Graph Creation]\n document_graph --> document_outputs[Document Tables]\n end\n subgraph phase6[Phase 6: Network Visualization]\n document_outputs --> umap_docs[Umap Documents]\n augmented_graph --> umap_entities[Umap Entities]\n umap_docs --> combine_nodes[Nodes Table]\n umap_entities --> combine_nodes\n end
The first phase of the default-configuration workflow is to transform input documents into TextUnits. A TextUnit is a chunk of text that is used for our graph extraction techniques. They are also used as source-references by extracted knowledge items in order to empower breadcrumbs and provenance by concepts back to their original source tex.
The chunk size (counted in tokens), is user-configurable. By default this is set to 300 tokens, although we've had positive experience with 1200-token chunks using a single \"glean\" step. (A \"glean\" step is a follow-on extraction). Larger chunks result in lower-fidelity output and less meaningful reference texts; however, using larger chunks can result in much faster processing time.
The group-by configuration is also user-configurable. By default, we align our chunks to document boundaries, meaning that there is a strict 1-to-many relationship between Documents and TextUnits. In rare cases, this can be turned into a many-to-many relationship. This is useful when the documents are very short and we need several of them to compose a meaningful analysis unit (e.g. Tweets or a chat log)
Each of these text-units are text-embedded and passed into the next phase of the pipeline.
"}, {"location": "index/default_dataflow/#phase-2-graph-extraction", "title": "Phase 2: Graph Extraction", "text": "---\ntitle: Documents into Text Chunks\n---\nflowchart LR\n doc1[Document 1] --> tu1[TextUnit 1]\n doc1 --> tu2[TextUnit 2]\n doc2[Document 2] --> tu3[TextUnit 3]\n doc2 --> tu4[TextUnit 4]\n
In this phase, we analyze each text unit and extract our graph primitives: Entities, Relationships, and Claims. Entities and Relationships are extracted at once in our entity_extract verb, and claims are extracted in our claim_extract verb. Results are then combined and passed into following phases of the pipeline.
"}, {"location": "index/default_dataflow/#entity-relationship-extraction", "title": "Entity & Relationship Extraction", "text": "---\ntitle: Graph Extraction\n---\nflowchart LR\n tu[TextUnit] --> ge[Graph Extraction] --> gs[Graph Summarization]\n tu --> ce[Claim Extraction]
In this first step of graph extraction, we process each text-unit in order to extract entities and relationships out of the raw text using the LLM. The output of this step is a subgraph-per-TextUnit containing a list of entities with a name, type, and description, and a list of relationships with a source, target, and description.
These subgraphs are merged together - any entities with the same name and type are merged by creating an array of their descriptions. Similarly, any relationships with the same source and target are merged by creating an array of their descriptions.
"}, {"location": "index/default_dataflow/#entity-relationship-summarization", "title": "Entity & Relationship Summarization", "text": "Now that we have a graph of entities and relationships, each with a list of descriptions, we can summarize these lists into a single description per entity and relationship. This is done by asking the LLM for a short summary that captures all of the distinct information from each description. This allows all of our entities and relationships to have a single concise description.
"}, {"location": "index/default_dataflow/#claim-extraction-emission", "title": "Claim Extraction & Emission", "text": "Finally, as an independent workflow, we extract claims from the source TextUnits. These claims represent positive factual statements with an evaluated status and time-bounds. These get exported as a primary artifact called Covariates.
Note: claim extraction is optional and turned off by default. This is because claim extraction generally requires prompt tuning to be useful.
"}, {"location": "index/default_dataflow/#phase-3-graph-augmentation", "title": "Phase 3: Graph Augmentation", "text": "Now that we have a usable graph of entities and relationships, we want to understand their community structure and augment the graph with additional information. This is done in two steps: Community Detection and Graph Embedding. These give us explicit (communities) and implicit (embeddings) ways of understanding the topological structure of our graph.
"}, {"location": "index/default_dataflow/#community-detection", "title": "Community Detection", "text": "---\ntitle: Graph Augmentation\n---\nflowchart LR\n cd[Leiden Hierarchical Community Detection] --> ge[Node2Vec Graph Embedding] --> ag[Graph Table Emission]
In this step, we generate a hierarchy of entity communities using the Hierarchical Leiden Algorithm. This method will apply a recursive community-clustering to our graph until we reach a community-size threshold. This will allow us to understand the community structure of our graph and provide a way to navigate and summarize the graph at different levels of granularity.
"}, {"location": "index/default_dataflow/#graph-embedding", "title": "Graph Embedding", "text": "In this step, we generate a vector representation of our graph using the Node2Vec algorithm. This will allow us to understand the implicit structure of our graph and provide an additional vector-space in which to search for related concepts during our query phase.
"}, {"location": "index/default_dataflow/#graph-tables-emission", "title": "Graph Tables Emission", "text": "Once our graph augmentation steps are complete, the final Entities and Relationships tables are exported after their text fields are text-embedded.
"}, {"location": "index/default_dataflow/#phase-4-community-summarization", "title": "Phase 4: Community Summarization", "text": "---\ntitle: Community Summarization\n---\nflowchart LR\n sc[Generate Community Reports] --> ss[Summarize Community Reports] --> ce[Community Embedding] --> co[Community Tables Emission]
At this point, we have a functional graph of entities and relationships, a hierarchy of communities for the entities, as well as node2vec embeddings.
Now we want to build on the communities data and generate reports for each community. This gives us a high-level understanding of the graph at several points of graph granularity. For example, if community A is the top-level community, we'll get a report about the entire graph. If the community is lower-level, we'll get a report about a local cluster.
"}, {"location": "index/default_dataflow/#generate-community-reports", "title": "Generate Community Reports", "text": "In this step, we generate a summary of each community using the LLM. This will allow us to understand the distinct information contained within each community and provide a scoped understanding of the graph, from either a high-level or a low-level perspective. These reports contain an executive overview and reference the key entities, relationships, and claims within the community sub-structure.
"}, {"location": "index/default_dataflow/#summarize-community-reports", "title": "Summarize Community Reports", "text": "In this step, each community report is then summarized via the LLM for shorthand use.
"}, {"location": "index/default_dataflow/#community-embedding", "title": "Community Embedding", "text": "In this step, we generate a vector representation of our communities by generating text embeddings of the community report, the community report summary, and the title of the community report.
"}, {"location": "index/default_dataflow/#community-tables-emission", "title": "Community Tables Emission", "text": "At this point, some bookkeeping work is performed and we export the Communities and CommunityReports tables.
"}, {"location": "index/default_dataflow/#phase-5-document-processing", "title": "Phase 5: Document Processing", "text": "In this phase of the workflow, we create the Documents table for the knowledge model.
"}, {"location": "index/default_dataflow/#augment-with-columns-csv-only", "title": "Augment with Columns (CSV Only)", "text": "---\ntitle: Document Processing\n---\nflowchart LR\n aug[Augment] --> dp[Link to TextUnits] --> de[Avg. Embedding] --> dg[Document Table Emission]
If the workflow is operating on CSV data, you may configure your workflow to add additional fields to Documents output. These fields should exist on the incoming CSV tables. Details about configuring this can be found in the configuration documentation.
"}, {"location": "index/default_dataflow/#link-to-textunits", "title": "Link to TextUnits", "text": "In this step, we link each document to the text-units that were created in the first phase. This allows us to understand which documents are related to which text-units and vice-versa.
"}, {"location": "index/default_dataflow/#document-embedding", "title": "Document Embedding", "text": "In this step, we generate a vector representation of our documents using an average embedding of document slices. We re-chunk documents without overlapping chunks, and then generate an embedding for each chunk. We create an average of these chunks weighted by token-count and use this as the document embedding. This will allow us to understand the implicit relationship between documents, and will help us generate a network representation of our documents.
"}, {"location": "index/default_dataflow/#documents-table-emission", "title": "Documents Table Emission", "text": "At this point, we can export the Documents table into the knowledge Model.
"}, {"location": "index/default_dataflow/#phase-6-network-visualization", "title": "Phase 6: Network Visualization", "text": "In this phase of the workflow, we perform some steps to support network visualization of our high-dimensional vector spaces within our existing graphs. At this point there are two logical graphs at play: the Entity-Relationship graph and the Document graph.
---\ntitle: Network Visualization Workflows\n---\nflowchart LR\n nv[Umap Documents] --> ne[Umap Entities] --> ng[Nodes Table Emission]
For each of the logical graphs, we perform a UMAP dimensionality reduction to generate a 2D representation of the graph. This will allow us to visualize the graph in a 2D space and understand the relationships between the nodes in the graph. The UMAP embeddings are then exported as a table of Nodes. The rows of this table include a discriminator indicating whether the node is a document or an entity, and the UMAP coordinates.
"}, {"location": "index/outputs/", "title": "Outputs", "text": "The default pipeline produces a series of output tables that align with the conceptual knowledge model. This page describes the detailed output table schemas. By default we write these tables out as parquet files on disk.
"}, {"location": "index/outputs/#shared-fields", "title": "Shared fields", "text": "All tables have two identifier fields:
name type description id str Generated UUID, assuring global uniqueness human_readable_id int This is an incremented short ID created per-run. For example, we use this short ID with generated summaries that print citations so they are easy to cross-reference visually."}, {"location": "index/outputs/#create_final_communities", "title": "create_final_communities", "text": "This is a list of the final communities generated by Leiden. Communities are strictly hierarchical, subdividing into children as the cluster affinity is narrowed.
name type description community int Leiden-generated cluster ID for the community. Note that these increment with depth, so they are unique through all levels of the community hierarchy. For this table, human_readable_id is a copy of the community ID rather than a plain increment. parent int Parent community ID. level int Depth of the community in the hierarchy. title str Friendly name of the community. entity_ids str[] List of entities that are members of the community. relationship_ids str[] List of relationships that are wholly within the community (source and target are both in the community). text_unit_ids str[] List of text units represented within the community. period str Date of ingest, used for incremental update merges. ISO8601 size int Size of the community (entity count), used for incremental update merges."}, {"location": "index/outputs/#create_final_community_reports", "title": "create_final_community_reports", "text": "This is the list of summarized reports for each community.
name type description community int Short ID of the community this report applies to. parent int Parent community ID. level int Level of the community this report applies to. title str LM-generated title for the report. summary str LM-generated summary of the report. full_content str LM-generated full report. rank float LM-derived relevance ranking of the report based on member entity salience rank_explanation str LM-derived explanation of the rank. findings dict LM-derived list of the top 5-10 insights from the community. Containssummary
andexplanation
values. full_content_json json Full JSON output as returned by the LM. Most fields are extracted into columns, but this JSON is sent for query summarization so we leave it to allow for prompt tuning to add fields/content by end users. period str Date of ingest, used for incremental update merges. ISO8601 size int Size of the community (entity count), used for incremental update merges."}, {"location": "index/outputs/#create_final_covariates", "title": "create_final_covariates", "text": "(Optional) If claim extraction is turned on, this is a list of the extracted covariates. Note that claims are typically oriented around identifying malicious behavior such as fraud, so they are not useful for all datasets.
name type description covariate_type str This is always \"claim\" with our default covariates. type str Nature of the claim type. description str LM-generated description of the behavior. subject_id str Name of the source entity (that is performing the claimed behavior). object_id str Name of the target entity (that the claimed behavior is performed on). status str LM-derived assessment of the correctness of the claim. One of [TRUE, FALSE, SUSPECTED] start_date str LM-derived start of the claimed activity. ISO8601 end_date str LM-derived end of the claimed activity. ISO8601 source_text str Short string of text containing the claimed behavior. text_unit_id str ID of the text unit the claim text was extracted from."}, {"location": "index/outputs/#create_final_documents", "title": "create_final_documents", "text": "List of document content after import.
name type description title str Filename, unless otherwise configured during CSV import. text str Full text of the document. text_unit_ids str[] List of text units (chunks) that were parsed from the document. attributes dict (optional) If specified during CSV import, this is a dict of attributes for the document."}, {"location": "index/outputs/#create_final_entities", "title": "create_final_entities", "text": "List of all entities found in the data by the LM.
name type description title str Name of the entity. type str Type of the entity. By default this will be \"organization\", \"person\", \"geo\", or \"event\" unless configured differently or auto-tuning is used. description str Textual description of the entity. Entities may be found in many text units, so this is an LM-derived summary of all descriptions. text_unit_ids str[] List of the text units containing the entity."}, {"location": "index/outputs/#create_final_nodes", "title": "create_final_nodes", "text": "This is graph-related information for the entities. It contains only information relevant to the graph such as community. There is an entry for each entity at every community level it is found within, so you may see \"duplicate\" entities.
Note that the ID fields match those in create_final_entities and can be used for joining if additional information about a node is required.
name type description title str Name of the referenced entity. Duplicated from create_final_entities for convenient cross-referencing. community int Leiden community the node is found within. Entities are not always assigned a community (they may not be close enough to any), so they may have a ID of -1. level int Level of the community the entity is in. degree int Node degree (connectedness) in the graph. x float X position of the node for visual layouts. If graph embeddings and UMAP are not turned on, this will be 0. y float Y position of the node for visual layouts. If graph embeddings and UMAP are not turned on, this will be 0."}, {"location": "index/outputs/#create_final_relationships", "title": "create_final_relationships", "text": "List of all entity-to-entity relationships found in the data by the LM. This is also the edge list for the graph.
name type description source str Name of the source entity. target str Name of the target entity. description str LM-derived description of the relationship. Also see note for entity descriptions. weight float Weight of the edge in the graph. This is summed from an LM-derived \"strength\" measure for each relationship instance. combined_degree int Sum of source and target node degrees. text_unit_ids str[] List of text units the relationship was found within."}, {"location": "index/outputs/#create_final_text_units", "title": "create_final_text_units", "text": "List of all text chunks parsed from the input documents.
name type description text str Raw full text of the chunk. n_tokens int Number of tokens in the chunk. This should normally match thechunk_size
config parameter, except for the last chunk which is often shorter. document_ids str[] List of document IDs the chunk came from. This is normally only 1 due to our default groupby, but for very short text documents (e.g., microblogs) it can be configured so text units span multiple documents. entity_ids str[] List of entities found in the text unit. relationships_ids str[] List of relationships found in the text unit. covariate_ids str[] Optional list of covariates found in the text unit."}, {"location": "index/overview/", "title": "GraphRAG Indexing \ud83e\udd16", "text": "The GraphRAG indexing package is a data pipeline and transformation suite that is designed to extract meaningful, structured data from unstructured text using LLMs.
Indexing Pipelines are configurable. They are composed of workflows, standard and custom steps, prompt templates, and input/output adapters. Our standard pipeline is designed to:
- extract entities, relationships and claims from raw text
- perform community detection in entities
- generate community summaries and reports at multiple levels of granularity
- embed entities into a graph vector space
- embed text chunks into a textual vector space
The outputs of the pipeline can be stored in a variety of formats, including JSON and Parquet - or they can be handled manually via the Python API.
"}, {"location": "index/overview/#getting-started", "title": "Getting Started", "text": ""}, {"location": "index/overview/#requirements", "title": "Requirements", "text": "See the requirements section in Get Started for details on setting up a development environment.
The Indexing Engine can be used in either a default configuration mode or with a custom pipeline. To configure GraphRAG, see the configuration documentation. After you have a config file you can run the pipeline using the CLI or the Python API.
"}, {"location": "index/overview/#usage", "title": "Usage", "text": ""}, {"location": "index/overview/#cli", "title": "CLI", "text": ""}, {"location": "index/overview/#python-api", "title": "Python API", "text": "# Via Poetry\npoetry run poe cli --root <data_root> # default config mode\npoetry run poe cli --config your_pipeline.yml # custom config mode\n\n# Via Node\nyarn run:index --root <data_root> # default config mode\nyarn run:index --config your_pipeline.yml # custom config mode\n
Please see the examples folder for a handful of functional pipelines illustrating how to create and run via a custom settings.yml or through custom python scripts.
"}, {"location": "index/overview/#further-reading", "title": "Further Reading", "text": ""}, {"location": "prompt_tuning/auto_prompt_tuning/", "title": "Auto Prompt Tuning \u2699\ufe0f", "text": "
- To start developing within the GraphRAG project, see getting started
- To understand the underlying concepts and execution model of the indexing library, see the architecture documentation
- To get running with a series of examples, see the examples documentation
- To read more about configuring the indexing engine, see the configuration documentation
GraphRAG provides the ability to create domain adapted prompts for the generation of the knowledge graph. This step is optional, though it is highly encouraged to run it as it will yield better results when executing an Index Run.
These are generated by loading the inputs, splitting them into chunks (text units) and then running a series of LLM invocations and template substitutions to generate the final prompts. We suggest using the default values provided by the script, but in this page you'll find the detail of each in case you want to further explore and tweak the prompt tuning algorithm.
Figure 1: Auto Tuning Conceptual Diagram.
"}, {"location": "prompt_tuning/auto_prompt_tuning/#prerequisites", "title": "Prerequisites", "text": "Before running auto tuning, ensure you have already initialized your workspace with the
"}, {"location": "prompt_tuning/auto_prompt_tuning/#usage", "title": "Usage", "text": "graphrag init
command. This will create the necessary configuration files and the default prompts. Refer to the Init Documentation for more information about the initialization process.You can run the main script from the command line with various options:
"}, {"location": "prompt_tuning/auto_prompt_tuning/#command-line-options", "title": "Command-Line Options", "text": "graphrag prompt-tune [--root ROOT] [--config CONFIG] [--domain DOMAIN] [--selection-method METHOD] [--limit LIMIT] [--language LANGUAGE] \\\n[--max-tokens MAX_TOKENS] [--chunk-size CHUNK_SIZE] [--n-subset-max N_SUBSET_MAX] [--k K] \\\n[--min-examples-required MIN_EXAMPLES_REQUIRED] [--discover-entity-types] [--output OUTPUT]\n
"}, {"location": "prompt_tuning/auto_prompt_tuning/#example-usage", "title": "Example Usage", "text": "
--config
(required): The path to the configuration file. This is required to load the data and model settings.
--root
(optional): The data project root directory, including the config files (YML, JSON, or .env). Defaults to the current directory.
--domain
(optional): The domain related to your input data, such as 'space science', 'microbiology', or 'environmental news'. If left empty, the domain will be inferred from the input data.
--method
(optional): The method to select documents. Options are all, random, auto or top. Default is random.
--limit
(optional): The limit of text units to load when using random or top selection. Default is 15.
--language
(optional): The language to use for input processing. If it is different from the inputs' language, the LLM will translate. Default is \"\" meaning it will be automatically detected from the inputs.
--max-tokens
(optional): Maximum token count for prompt generation. Default is 2000.
--chunk-size
(optional): The size in tokens to use for generating text units from input documents. Default is 200.
--n-subset-max
(optional): The number of text chunks to embed when using auto selection method. Default is 300.
--k
(optional): The number of documents to select when using auto selection method. Default is 15.
--min-examples-required
(optional): The minimum number of examples required for entity extraction prompts. Default is 2.
--discover-entity-types
(optional): Allow the LLM to discover and extract entities automatically. We recommend using this when your data covers a lot of topics or it is highly randomized.
--output
(optional): The folder to save the generated prompts. Default is \"prompts\".python -m graphrag prompt-tune --root /path/to/project --config /path/to/settings.yaml --domain \"environmental news\" \\\n--method random --limit 10 --language English --max-tokens 2048 --chunk-size 256 --min-examples-required 3 \\\n--no-entity-types --output /path/to/output\n
or, with minimal configuration (suggested):
"}, {"location": "prompt_tuning/auto_prompt_tuning/#document-selection-methods", "title": "Document Selection Methods", "text": "python -m graphrag prompt-tune --root /path/to/project --config /path/to/settings.yaml --no-entity-types\n
The auto tuning feature ingests the input data and then divides it into text units the size of the chunk size parameter. After that, it uses one of the following selection methods to pick a sample to work with for prompt generation:
"}, {"location": "prompt_tuning/auto_prompt_tuning/#modify-env-vars", "title": "Modify Env Vars", "text": "
random
: Select text units randomly. This is the default and recommended option.top
: Select the head n text units.all
: Use all text units for the generation. Use only with small datasets; this option is not usually recommended.auto
: Embed text units in a lower-dimensional space and select the k nearest neighbors to the centroid. This is useful when you have a large dataset and want to select a representative sample.After running auto tuning, you should modify the following environment variables (or config variables) to pick up the new prompts on your index run. Note: Please make sure to update the correct path to the generated prompts, in this example we are using the default \"prompts\" path.
GRAPHRAG_ENTITY_EXTRACTION_PROMPT_FILE
= \"prompts/entity_extraction.txt\"
GRAPHRAG_COMMUNITY_REPORT_PROMPT_FILE
= \"prompts/community_report.txt\"
GRAPHRAG_SUMMARIZE_DESCRIPTIONS_PROMPT_FILE
= \"prompts/summarize_descriptions.txt\"or in your yaml config file:
"}, {"location": "prompt_tuning/manual_prompt_tuning/", "title": "Manual Prompt Tuning \u2699\ufe0f", "text": "entity_extraction:\n prompt: \"prompts/entity_extraction.txt\"\n\nsummarize_descriptions:\n prompt: \"prompts/summarize_descriptions.txt\"\n\ncommunity_reports:\n prompt: \"prompts/community_report.txt\"\n
The GraphRAG indexer, by default, will run with a handful of prompts that are designed to work well in the broad context of knowledge discovery. However, it is quite common to want to tune the prompts to better suit your specific use case. We provide a means for you to do this by allowing you to specify a custom prompt file, which will each use a series of token-replacements internally.
Each of these prompts may be overridden by writing a custom prompt file in plaintext. We use token-replacements in the form of
"}, {"location": "prompt_tuning/manual_prompt_tuning/#indexing-prompts", "title": "Indexing Prompts", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#entityrelationship-extraction", "title": "Entity/Relationship Extraction", "text": "{token_name}
, and the descriptions for the available tokens can be found below.Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#summarize-entityrelationship-descriptions", "title": "Summarize Entity/Relationship Descriptions", "text": "
- {input_text} - The input text to be processed.
- {entity_types} - A list of entity types
- {tuple_delimiter} - A delimiter for separating values within a tuple. A single tuple is used to represent an individual entity or relationship.
- {record_delimiter} - A delimiter for separating tuple instances.
- {completion_delimiter} - An indicator for when generation is complete.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_1", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#claim-extraction", "title": "Claim Extraction", "text": "
- {entity_name} - The name of the entity or the source/target pair of the relationship.
- {description_list} - A list of descriptions for the entity or relationship.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_2", "title": "Tokens", "text": "
- {input_text} - The input text to be processed.
- {tuple_delimiter} - A delimiter for separating values within a tuple. A single tuple is used to represent an individual entity or relationship.
- {record_delimiter} - A delimiter for separating tuple instances.
- {completion_delimiter} - An indicator for when generation is complete.
- {entity_specs} - A list of entity types.
- {claim_description} - Description of what claims should look like. Default is:
\"Any claims or facts that could be relevant to information discovery.\"
See the configuration documentation for details on how to change this.
"}, {"location": "prompt_tuning/manual_prompt_tuning/#generate-community-reports", "title": "Generate Community Reports", "text": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_3", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#query-prompts", "title": "Query Prompts", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#local-search", "title": "Local Search", "text": "
- {input_text} - The input text to generate the report with. This will contain tables of entities and relationships.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_4", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#global-search", "title": "Global Search", "text": "
- {response_type} - Describe how the response should look. We default to \"multiple paragraphs\".
- {context_data} - The data tables from GraphRAG's index.
Mapper Prompt Source
Reducer Prompt Source
Knowledge Prompt Source
Global search uses a map/reduce approach to summarization. You can tune these prompts independently. This search also includes the ability to adjust the use of general knowledge from the model's training.
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_5", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/manual_prompt_tuning/#drift-search", "title": "Drift Search", "text": "
- {response_type} - Describe how the response should look (reducer only). We default to \"multiple paragraphs\".
- {context_data} - The data tables from GraphRAG's index.
Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_6", "title": "Tokens", "text": ""}, {"location": "prompt_tuning/overview/", "title": "Prompt Tuning \u2699\ufe0f", "text": "
- {response_type} - Describe how the response should look. We default to \"multiple paragraphs\".
- {context_data} - The data tables from GraphRAG's index.
- {community_reports} - The most relevant community reports to include in the summarization.
- {query} - The query text as injected into the context.
This page provides an overview of the prompt tuning options available for the GraphRAG indexing engine.
"}, {"location": "prompt_tuning/overview/#default-prompts", "title": "Default Prompts", "text": "The default prompts are the simplest way to get started with the GraphRAG system. It is designed to work out-of-the-box with minimal configuration. More details about each of the default prompts for indexing and query can be found on the manual tuning page.
"}, {"location": "prompt_tuning/overview/#auto-tuning", "title": "Auto Tuning", "text": "Auto Tuning leverages your input data and LLM interactions to create domain adapted prompts for the generation of the knowledge graph. It is highly encouraged to run it as it will yield better results when executing an Index Run. For more details about how to use it, please refer to the Auto Tuning documentation.
"}, {"location": "prompt_tuning/overview/#manual-tuning", "title": "Manual Tuning", "text": "Manual tuning is an advanced use-case. Most users will want to use the Auto Tuning feature instead. Details about how to use manual configuration are available in the manual tuning documentation.
"}, {"location": "query/drift_search/", "title": "DRIFT Search \ud83d\udd0e", "text": ""}, {"location": "query/drift_search/#combining-local-and-global-search", "title": "Combining Local and Global Search", "text": "GraphRAG is a technique that uses large language models (LLMs) to create knowledge graphs and summaries from unstructured text documents and leverages them to improve retrieval-augmented generation (RAG) operations on private datasets. It offers comprehensive global overviews of large, private troves of unstructured text documents while also enabling exploration of detailed, localized information. By using LLMs to create comprehensive knowledge graphs that connect and describe entities and relationships contained in those documents, GraphRAG leverages semantic structuring of the data to generate responses to a wide variety of complex user queries.
DRIFT search (Dynamic Reasoning and Inference with Flexible Traversal) builds upon Microsoft\u2019s GraphRAG technique, combining characteristics of both global and local search to generate detailed responses in a method that balances computational costs with quality outcomes using our drift search method.
"}, {"location": "query/drift_search/#methodology", "title": "Methodology", "text": "Figure 1. An entire DRIFT search hierarchy highlighting the three core phases of the DRIFT search process. A (Primer): DRIFT compares the user\u2019s query with the top K most semantically relevant community reports, generating a broad initial answer and follow-up questions to steer further exploration. B (Follow-Up): DRIFT uses local search to refine queries, producing additional intermediate answers and follow-up questions that enhance specificity, guiding the engine towards context-rich information. A glyph on each node in the diagram shows the confidence the algorithm has to continue the query expansion step. C (Output Hierarchy): The final output is a hierarchical structure of questions and answers ranked by relevance, reflecting a balanced mix of global insights and local refinements, making the results adaptable and comprehensive.
DRIFT Search introduces a new approach to local search queries by including community information in the search process. This greatly expands the breadth of the query\u2019s starting point and leads to retrieval and usage of a far higher variety of facts in the final answer. This addition expands the GraphRAG query engine by providing a more comprehensive option for local search, which uses community insights to refine a query into detailed follow-up questions.
"}, {"location": "query/drift_search/#configuration", "title": "Configuration", "text": "Below are the key parameters of the DRIFTSearch class:
"}, {"location": "query/drift_search/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from community reports and query informationconfig
: model to define the DRIFT Search hyperparameters. DRIFT Config modeltoken_encoder
: token encoder for tracking the budget for the algorithm.query_state
: a state object as defined in Query State that allows to track execution of a DRIFT Search instance, alongside follow ups and DRIFT actions.An example of a drift search scenario can be found in the following notebook.
"}, {"location": "query/drift_search/#learn-more", "title": "Learn More", "text": "For a more in-depth look at the DRIFT search method, please refer to our DRIFT Search blog post
"}, {"location": "query/global_search/", "title": "Global Search \ud83d\udd0e", "text": ""}, {"location": "query/global_search/#whole-dataset-reasoning", "title": "Whole Dataset Reasoning", "text": "Baseline RAG struggles with queries that require aggregation of information across the dataset to compose an answer. Queries such as \u201cWhat are the top 5 themes in the data?\u201d perform terribly because baseline RAG relies on a vector search of semantically similar text content within the dataset. There is nothing in the query to direct it to the correct information.
However, with GraphRAG we can answer such questions, because the structure of the LLM-generated knowledge graph tells us about the structure (and thus themes) of the dataset as a whole. This allows the private dataset to be organized into meaningful semantic clusters that are pre-summarized. Using our global search method, the LLM uses these clusters to summarize these themes when responding to a user query.
"}, {"location": "query/global_search/#methodology", "title": "Methodology", "text": "---\ntitle: Global Search Dataflow\n---\n%%{ init: { 'flowchart': { 'curve': 'step' } } }%%\nflowchart LR\n\n uq[User Query] --- .1\n ch1[Conversation History] --- .1\n\n subgraph RIR\n direction TB\n ri1[Rated Intermediate<br/>Response 1]~~~ri2[Rated Intermediate<br/>Response 2] -.\"{1..N}\".-rin[Rated Intermediate<br/>Response N]\n end\n\n .1--Shuffled Community<br/>Report Batch 1-->RIR\n .1--Shuffled Community<br/>Report Batch 2-->RIR---.2\n .1--Shuffled Community<br/>Report Batch N-->RIR\n\n .2--Ranking +<br/>Filtering-->agr[Aggregated Intermediate<br/>Responses]-->res[Response]\n\n\n\n classDef green fill:#26B653,stroke:#333,stroke-width:2px,color:#fff;\n classDef turquoise fill:#19CCD3,stroke:#333,stroke-width:2px,color:#fff;\n classDef rose fill:#DD8694,stroke:#333,stroke-width:2px,color:#fff;\n classDef orange fill:#F19914,stroke:#333,stroke-width:2px,color:#fff;\n classDef purple fill:#B356CD,stroke:#333,stroke-width:2px,color:#fff;\n classDef invisible fill:#fff,stroke:#fff,stroke-width:0px,color:#fff, width:0px;\n class uq,ch1 turquoise;\n class ri1,ri2,rin rose;\n class agr orange;\n class res purple;\n class .1,.2 invisible;\n
Given a user query and, optionally, the conversation history, the global search method uses a collection of LLM-generated community reports from a specified level of the graph's community hierarchy as context data to generate response in a map-reduce manner. At the
map
step, community reports are segmented into text chunks of pre-defined size. Each text chunk is then used to produce an intermediate response containing a list of point, each of which is accompanied by a numerical rating indicating the importance of the point. At thereduce
step, a filtered set of the most important points from the intermediate responses are aggregated and used as the context to generate the final response.The quality of the global search\u2019s response can be heavily influenced by the level of the community hierarchy chosen for sourcing community reports. Lower hierarchy levels, with their detailed reports, tend to yield more thorough responses, but may also increase the time and LLM resources needed to generate the final response due to the volume of reports.
"}, {"location": "query/global_search/#configuration", "title": "Configuration", "text": "Below are the key parameters of the GlobalSearch class:
"}, {"location": "query/global_search/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from community reportsmap_system_prompt
: prompt template used in themap
stage. Default template can be found at map_system_promptreduce_system_prompt
: prompt template used in thereduce
stage, default template can be found at reduce_system_promptresponse_type
: free-form text describing the desired response type and format (e.g.,Multiple Paragraphs
,Multi-Page Report
)allow_general_knowledge
: setting this to True will include additional instructions to thereduce_system_prompt
to prompt the LLM to incorporate relevant real-world knowledge outside of the dataset. Note that this may increase hallucinations, but can be useful for certain scenarios. Default is False *general_knowledge_inclusion_prompt
: instruction to add to thereduce_system_prompt
ifallow_general_knowledge
is enabled. Default instruction can be found at general_knowledge_instructionmax_data_tokens
: token budget for the context datamap_llm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to be passed to the LLM call at themap
stagereduce_llm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to passed to the LLM call at thereduce
stagecontext_builder_params
: a dictionary of additional parameters to be passed to thecontext_builder
object when building context window for themap
stage.concurrent_coroutines
: controls the degree of parallelism in themap
stage.callbacks
: optional callback functions, can be used to provide custom event handlers for LLM's completion streaming eventsAn example of a global search scenario can be found in the following notebook.
"}, {"location": "query/local_search/", "title": "Local Search \ud83d\udd0e", "text": ""}, {"location": "query/local_search/#entity-based-reasoning", "title": "Entity-based Reasoning", "text": "The local search method combines structured data from the knowledge graph with unstructured data from the input documents to augment the LLM context with relevant entity information at query time. It is well-suited for answering questions that require an understanding of specific entities mentioned in the input documents (e.g., \u201cWhat are the healing properties of chamomile?\u201d).
"}, {"location": "query/local_search/#methodology", "title": "Methodology", "text": "---\ntitle: Local Search Dataflow\n---\n%%{ init: { 'flowchart': { 'curve': 'step' } } }%%\nflowchart LR\n\n uq[User Query] ---.1\n ch1[Conversation<br/>History]---.1\n\n .1--Entity<br/>Description<br/>Embedding--> ee[Extracted Entities]\n\n ee[Extracted Entities] ---.2--Entity-Text<br/>Unit Mapping--> ctu[Candidate<br/>Text Units]--Ranking + <br/>Filtering -->ptu[Prioritized<br/>Text Units]---.3\n .2--Entity-Report<br/>Mapping--> ccr[Candidate<br/>Community Reports]--Ranking + <br/>Filtering -->pcr[Prioritized<br/>Community Reports]---.3\n .2--Entity-Entity<br/>Relationships--> ce[Candidate<br/>Entities]--Ranking + <br/>Filtering -->pe[Prioritized<br/>Entities]---.3\n .2--Entity-Entity<br/>Relationships--> cr[Candidate<br/>Relationships]--Ranking + <br/>Filtering -->pr[Prioritized<br/>Relationships]---.3\n .2--Entity-Covariate<br/>Mappings--> cc[Candidate<br/>Covariates]--Ranking + <br/>Filtering -->pc[Prioritized<br/>Covariates]---.3\n ch1 -->ch2[Conversation History]---.3\n .3-->res[Response]\n\n classDef green fill:#26B653,stroke:#333,stroke-width:2px,color:#fff;\n classDef turquoise fill:#19CCD3,stroke:#333,stroke-width:2px,color:#fff;\n classDef rose fill:#DD8694,stroke:#333,stroke-width:2px,color:#fff;\n classDef orange fill:#F19914,stroke:#333,stroke-width:2px,color:#fff;\n classDef purple fill:#B356CD,stroke:#333,stroke-width:2px,color:#fff;\n classDef invisible fill:#fff,stroke:#fff,stroke-width:0px,color:#fff, width:0px;\n class uq,ch1 turquoise\n class ee green\n class ctu,ccr,ce,cr,cc rose\n class ptu,pcr,pe,pr,pc,ch2 orange\n class res purple\n class .1,.2,.3 invisible\n\n
Given a user query and, optionally, the conversation history, the local search method identifies a set of entities from the knowledge graph that are semantically-related to the user input. These entities serve as access points into the knowledge graph, enabling the extraction of further relevant details such as connected entities, relationships, entity covariates, and community reports. Additionally, it also extracts relevant text chunks from the raw input documents that are associated with the identified entities. These candidate data sources are then prioritized and filtered to fit within a single context window of pre-defined size, which is used to generate a response to the user query.
"}, {"location": "query/local_search/#configuration", "title": "Configuration", "text": "Below are the key parameters of the LocalSearch class:
"}, {"location": "query/local_search/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from collections of knowledge model objectssystem_prompt
: prompt template used to generate the search response. Default template can be found at system_promptresponse_type
: free-form text describing the desired response type and format (e.g.,Multiple Paragraphs
,Multi-Page Report
)llm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to be passed to the LLM callcontext_builder_params
: a dictionary of additional parameters to be passed to thecontext_builder
object when building context for the search promptcallbacks
: optional callback functions, can be used to provide custom event handlers for LLM's completion streaming eventsAn example of a local search scenario can be found in the following notebook.
"}, {"location": "query/overview/", "title": "Query Engine \ud83d\udd0e", "text": "The Query Engine is the retrieval module of the Graph RAG Library. It is one of the two main components of the Graph RAG library, the other being the Indexing Pipeline (see Indexing Pipeline). It is responsible for the following tasks:
"}, {"location": "query/overview/#local-search", "title": "Local Search", "text": "
- Local Search
- Global Search
- DRIFT Search
- Question Generation
Local search method generates answers by combining relevant data from the AI-extracted knowledge-graph with text chunks of the raw documents. This method is suitable for questions that require an understanding of specific entities mentioned in the documents (e.g. What are the healing properties of chamomile?).
For more details about how Local Search works please refer to the Local Search documentation.
"}, {"location": "query/overview/#global-search", "title": "Global Search", "text": "Global search method generates answers by searching over all AI-generated community reports in a map-reduce fashion. This is a resource-intensive method, but often gives good responses for questions that require an understanding of the dataset as a whole (e.g. What are the most significant values of the herbs mentioned in this notebook?).
More about this can be checked at the Global Search documentation.
"}, {"location": "query/overview/#drift-search", "title": "DRIFT Search", "text": "DRIFT Search introduces a new approach to local search queries by including community information in the search process. This greatly expands the breadth of the query\u2019s starting point and leads to retrieval and usage of a far higher variety of facts in the final answer. This addition expands the GraphRAG query engine by providing a more comprehensive option for local search, which uses community insights to refine a query into detailed follow-up questions.
To learn more about DRIFT Search, please refer to the DRIFT Search documentation.
"}, {"location": "query/overview/#question-generation", "title": "Question Generation", "text": "This functionality takes a list of user queries and generates the next candidate questions. This is useful for generating follow-up questions in a conversation or for generating a list of questions for the investigator to dive deeper into the dataset.
Information about how question generation works can be found at the Question Generation documentation page.
"}, {"location": "query/question_generation/", "title": "Question Generation \u2754", "text": ""}, {"location": "query/question_generation/#entity-based-question-generation", "title": "Entity-based Question Generation", "text": "The question generation method combines structured data from the knowledge graph with unstructured data from the input documents to generate candidate questions related to specific entities.
"}, {"location": "query/question_generation/#methodology", "title": "Methodology", "text": "Given a list of prior user questions, the question generation method uses the same context-building approach employed in local search to extract and prioritize relevant structured and unstructured data, including entities, relationships, covariates, community reports and raw text chunks. These data records are then fitted into a single LLM prompt to generate candidate follow-up questions that represent the most important or urgent information content or themes in the data.
"}, {"location": "query/question_generation/#configuration", "title": "Configuration", "text": "Below are the key parameters of the Question Generation class:
"}, {"location": "query/question_generation/#how-to-use", "title": "How to Use", "text": "
llm
: OpenAI model object to be used for response generationcontext_builder
: context builder object to be used for preparing context data from collections of knowledge model objects, using the same context builder class as in local searchsystem_prompt
: prompt template used to generate candidate questions. Default template can be found at system_promptllm_params
: a dictionary of additional parameters (e.g., temperature, max_tokens) to be passed to the LLM callcontext_builder_params
: a dictionary of additional parameters to be passed to thecontext_builder
object when building context for the question generation promptcallbacks
: optional callback functions, can be used to provide custom event handlers for LLM's completion streaming eventsAn example of the question generation function can be found in the following notebook.
"}, {"location": "query/notebooks/overview/", "title": "API Notebooks", "text": ""}, {"location": "query/notebooks/overview/#query-engine-notebooks", "title": "Query Engine Notebooks", "text": "
- API Overview Notebook
For examples about running Query please refer to the following notebooks:
- Global Search Notebook
- Local Search Notebook
- DRIFT Search Notebook
The test dataset for these notebooks can be found in dataset.zip.
"}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 969953a28c..274803bc55 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ