diff --git a/config/yaml/index.html b/config/yaml/index.html index 6cf7d7c2..8bac044f 100644 --- a/config/yaml/index.html +++ b/config/yaml/index.html @@ -1455,7 +1455,7 @@ api_key: ${GRAPHRAG_API_KEY}
This is a dict of model configurations. The dict key is used to reference this configuration elsewhere when a model instance is desired. In this way, you can specify as many different models as you need, and reference them differentially in the workflow steps.
For example: @@ -1473,137 +1473,155 @@
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.auth_type api_key|managed_identity - Indicate how you want to authenticate requests.type openai_chat|azure_openai_chat|openai_embedding|azure_openai_embedding|mock_chat|mock_embeddings - The type of LLM to use.model str - The model name.encoding_model str - The text encoding model to use. Default is to use the encoding model aligned with the language model (i.e., it is retrieved from tiktoken if unset).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 version.deployment_name str - The deployment name to use (Azure).organization str - The client organization.proxy str - The proxy URL to use.azure_auth_type api_key|managed_identity - if using Azure, please indicate how you want to authenticate requests.audience str - (Azure OpenAI only) The URI of the target Azure resource/service for which a managed identity token is requested. Used if api_key is not defined. Default=https://cognitiveservices.azure.com/.defaultdeployment_name str - The deployment name to use (Azure).model_supports_json bool - Whether the model supports JSON-mode output.request_timeout float - The per-request timeout.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.retry_strategy str - Retry strategy to use, "native" is the default and uses the strategy built into the OpenAI SDK. Other allowable values include "exponential_backoff", "random_wait", and "incremental_wait".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.async_mode asyncio|threaded The async mode to use. Either asyncio or threaded.responses list[str] - If this model type is mock, this is a list of response strings to return.max_tokens int - The maximum number of output tokens.temperature float - The temperature to use.top_p float - The top-p value to use.n int - The number of completions to generate.parallelization_stagger float - The threading stagger value.parallelization_num_threads int - The maximum number of work threads.async_mode asyncio|threaded The async mode to use. Either asyncio or `threaded.frequency_penalty float - Frequency penalty for token generation.presence_penalty float - Frequency penalty for token generation.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 customized by setting the target and names fields.
Supported embeddings names are:
-- text_unit.text
-- document.text
-- entity.title
-- entity.description
-- relationship.description
-- community.title
-- community.summary
-- community.full_content
Our pipeline can ingest .csv, .txt, or .json data from an input folder. See the inputs page for more details and examples.
type file|blob - The input type to use. Default=filefile_type text|csv|json - The type of input data to load. Default is textbase_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.encoding str - The encoding of the input file. Default is utf-8file_pattern str - A regex to match input files. Default is .*\.csv$, .*\.txt$, or .*\.json$ depending on the specified file_type, but you can customize it if needed.file_filter dict - Key/value pairs to filter. Default is None.text_column str - (CSV/JSON only) The text column name. If unset we expect a column named text.title_column str - (CSV/JSON only) The title column name, filename will be used if unset.metadata list[str] - (CSV/JSON only) The additional document attributes fields to keep.These settings configure how we parse documents into text chunks. This is necessary because very large documents may not fit into a single context window, and graph extraction accuracy can be modulated. Also note the metadata setting in the input document config, which will replicate document metadata into each chunk.
size int - The max chunk size in tokens.overlap int - The chunk overlap in tokens.group_by_columns list[str] - Group documents by these fields before chunking.strategy str[tokens|sentences] - How to chunk the text. encoding_model str - The text encoding model to use for splitting on token boundaries.prepend_metadata bool - Determines if metadata values should be added at the beginning of each chunk. Default=False.chunk_size_includes_metadata bool - Specifies whether the chunk size calculation should include metadata tokens. Default=False.This section controls the storage mechanism used by the pipeline used for exporting output tables.
+type file|memory|blob|cosmosdb - The storage type to use. Default=filebase_dir str - The base directory to write output artifacts to, relative to the root.connection_string str - (blob/cosmosdb only) The Azure Storage connection string.container_name str - (blob/cosmosdb only) The Azure Storage container name.storage_account_blob_url str - (blob only) The storage account blob URL to use.cosmosdb_account_blob_url str - (cosmosdb only) The CosmosDB account blob URL to use.The section defines a secondary storage location for running incremental indexing, to preserve your original outputs.
+type file|memory|blob|cosmosdb - The storage type to use. Default=filebase_dir str - The base directory to write output artifacts to, relative to the root.connection_string str - (blob/cosmosdb only) The Azure Storage connection string.container_name str - (blob/cosmosdb only) The Azure Storage container name.storage_account_blob_url str - (blob only) The storage account blob URL to use.cosmosdb_account_blob_url str - (cosmosdb only) The CosmosDB account blob URL to use.This section controls the cache mechanism used by the pipeline. This is used to cache LLM invocation results for faster performance when re-running the indexing process.
+type file|memory|blob|cosmosdb - The storage type to use. Default=filebase_dir str - The base directory to write output artifacts to, relative to the root.connection_string str - (blob/cosmosdb only) The Azure Storage connection string.container_name str - (blob/cosmosdb only) The Azure Storage container name.storage_account_blob_url str - (blob only) The storage account blob URL to use.cosmosdb_account_blob_url str - (cosmosdb only) The CosmosDB account blob URL to use.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.
+type file|console|blob - The reporting type to use. Default=filebase_dir str - The base directory to write reports to, relative to the root.connection_string str - (blob only) The Azure Storage connection string.container_name str - (blob only) The Azure Storage container name.storage_account_blob_url str - The storage account blob URL to use.Where to put all vectors for the system. Configured for lancedb by default. This is a dict, with the key used to identify individual store parameters (e.g., for text embedding).
+type lancedb|azure_ai_search|cosmosdb - Type of vector store. Default=lancedbdb_uri str (only for lancedb) - The database uri. Default=storage.base_dir/lancedburl 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.container_name str - The name of a vector container. This stores all indexes (tables) for a given dataset ingest. Default=defaultdatabase_name str - (cosmosdb only) Name of the database.overwrite bool (only used at index creation time) - Overwrite collection if it exist. Default=TrueThese settings control each individual workflow as they execute.
+list[str] - This is a list of workflow names to run, in order. GraphRAG has built-in pipelines to configure this, but you can run exactly and only what you want by specifying the list here. Useful if you have done part of the processing yourself.
+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 customized by setting the target and names fields.
Supported embeddings names are:
+text_unit.textdocument.textentity.titleentity.descriptionrelationship.descriptioncommunity.titlecommunity.summarycommunity.full_contentmodel_id str - Name of the model definition to use for text embedding.vector_store_id str - Name of vector store definition to write to.batch_size int - The maximum batch size to use.batch_max_tokens int - The maximum batch # of tokens.target required|all|selected|none - Determines which set of embeddings to export.names list[str] - If target=selected, this should be an explicit list of the embeddings names we support.Where to put all vectors for the system. Configured for lancedb by default.
-type str - lancedb or azure_ai_search. Default=lancedbdb_uri str (only for lancedb) - The database uri. Default=storage.base_dir/lancedburl 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=Truecontainer_name str - The name of a vector container. This stores all indexes (tables) for a given dataset ingest. Default=defaultOur pipeline can ingest .csv or .txt data from an input folder. These files can be nested within subfolders. In general, CSV-based data provides the most customizability. Each CSV should at least contain a text field. You can use the metadata list to specify additional columns from the CSV to include as headers in each text chunk, allowing you to repeat document content within each chunk for better LLM inclusion.
type file|blob - The input type to use. Default=filefile_type text|csv - The type of input data to load. Either text or csv. Default is textbase_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 is utf-8file_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.text_column str - (CSV Mode Only) The text column name.metadata list[str] - (CSV Mode Only) The additional document attributes to include.These settings configure how we parse documents into text chunks. This is necessary because very large documents may not fit into a single context window, and graph extraction accuracy can be modulated. Also note the metadata setting in the input document config, which will replicate document metadata into each chunk.
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 for splitting on token boundaries.prepend_metadata bool - Determines if metadata values should be added at the beginning of each chunk. Default=False.chunk_size_includes_metadata bool - Specifies whether the chunk size calculation should include metadata tokens. Default=False.This section controls the cache mechanism used by the pipeline. This is used to cache LLM invocation results.
-type file|memory|none|blob - The cache type to use. Default=fileconnection_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.This section controls the storage mechanism used by the pipeline used for exporting output tables.
-type file|memory|blob - The storage type to use. Default=fileconnection_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.The section defines a secondary storage location for running incremental indexing, to preserve your original outputs.
-type file|memory|blob - The storage type to use. Default=fileconnection_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.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.
-type file|console|blob - The reporting type to use. Default=fileconnection_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.Tune the language model-based graph extraction process.
model_id str - Name of the model definition to use for API calls.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. Default is to use the encoding model aligned with the language model (i.e., it is retrieved from tiktoken if unset). This is only used for gleanings during the logit_bias check.enabled bool - Whether to enable claim extraction. Off by default, because claim prompts really need user tuning.model_id str - Name of the model definition to use for API calls.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.model_id str - Name of the model definition to use for API calls.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.Parameters for manual graph pruning. This can be used to optimize the modularity of your graph clusters, by removing overly-connected or rare nodes.
-These are the settings used for Leiden hierarchical clustering of the graph to create communities.
-max_cluster_size int - The maximum cluster size to export.use_lcc bool - Whether to only use the largest connected component.seed int - A randomization seed to provide if consistent run-to-run results are desired. We do provide a default in order to guarantee clustering stability.enabled bool - Whether to enable claim extraction. Off by default, because claim prompts really need user tuning.model_id str - Name of the model definition to use for API calls.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. Default is to use the encoding model aligned with the language model (i.e., it is retrieved from tiktoken if unset). This is only used for gleanings during the logit_bias check.model_id str - Name of the model definition to use for API calls.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.We use node2vec to embed the graph. This is primarily used for visualization, so it is not turned on by default. However, if you do prefer to embed the graph for secondary analysis, you can turn this on and we will persist the embeddings to your configured vector store.
+We use node2vec to embed the graph. This is primarily used for visualization, so it is not turned on by default.
enabled bool - Whether to enable graph embeddings.dimensions int - Number of vector dimensions to produce.num_walks int - The node2vec number of walks.walk_length int - The node2vec walk length.window_size int - The node2vec window size.max_tokens int - The maximum tokens.llm_max_tokens int - The LLM maximum tokens.list[str] - This is a list of workflow names to run, in order. GraphRAG has built-in pipelines to configure this, but you can run exactly and only what you want by specifying the list here. Useful if you have done part of the processing yourself.
diff --git a/examples_notebooks/drift_search/index.html b/examples_notebooks/drift_search/index.html index 7034711e..7df5a1fd 100644 --- a/examples_notebooks/drift_search/index.html +++ b/examples_notebooks/drift_search/index.html @@ -2432,7 +2432,7 @@ search = DRIFTSearch(100%|██████████| 1/1 [00:12<00:00, 12.57s/it]+
100%|██████████| 1/1 [00:13<00:00, 13.62s/it]
33%|███▎ | 1/3 [00:14<00:29, 14.67s/it]+
33%|███▎ | 1/3 [00:14<00:29, 14.73s/it]
67%|██████▋ | 2/3 [00:18<00:08, 8.46s/it]+
67%|██████▋ | 2/3 [00:16<00:06, 6.85s/it]+
100%|██████████| 3/3 [00:21<00:00, 6.40s/it]
33%|███▎ | 1/3 [00:10<00:21, 10.91s/it]+
33%|███▎ | 1/3 [00:10<00:20, 10.17s/it]
67%|██████▋ | 2/3 [00:11<00:04, 4.96s/it]+
67%|██████▋ | 2/3 [00:10<00:04, 4.43s/it]
100%|██████████| 3/3 [00:14<00:00, 3.79s/it]+
100%|██████████| 3/3 [00:11<00:00, 2.81s/it]
33%|███▎ | 1/3 [00:08<00:16, 8.49s/it]+
33%|███▎ | 1/3 [00:09<00:18, 9.43s/it]
67%|██████▋ | 2/3 [00:09<00:03, 4.00s/it]+
67%|██████▋ | 2/3 [00:12<00:05, 5.40s/it]
100%|██████████| 3/3 [00:09<00:00, 2.23s/it]+
100%|██████████| 3/3 [00:13<00:00, 3.59s/it]
"Agent Alex Mercer is a pivotal figure within the Paranormal Military Squad, playing a crucial role in Operation: Dulce, which involves exploring and investigating the Dulce base rumored to house advanced alien technology. Mercer is recognized for his leadership qualities and serves as a mentor to fellow agent Sam Rivera, emphasizing intuition and trust in navigating the mission's uncertainties [Data: Reports (0, 1)].\n\nMercer's leadership style is collaborative and supportive, fostering open communication and valuing team members' insights and instincts. This approach helps build camaraderie and mutual respect within the team [Data: Reports (1)]. He works closely with other key team members, such as Dr. Jordan Hayes, who provides expertise in alien technology, and Taylor Cruz, whose authoritative leadership style contrasts with Mercer's more intuitive approach [Data: Reports (0, 1)].\n\nOverall, Mercer's ability to foster trust and intuition among his team members, coupled with his collaborative efforts, highlights his significance in the mission to explore and understand the Dulce base and its alien technology [Data: Reports (0)]."+
"Agent Alex Mercer is a pivotal member of the Paranormal Military Squad, playing a crucial role in Operation: Dulce. He is known for his leadership and mentorship abilities, which are essential to the success of the mission. Mercer's role involves guiding and supporting fellow team members, particularly Sam Rivera, and fostering trust and intuition within the team [Data: Reports (1); Sources (3, 0)].\n\nMercer is also noted for his determination and ability to maintain focus under pressure, as well as his reflective nature, which allows him to consider the broader implications of their mission beyond immediate objectives [Data: Sources (3)]. His interactions with other team members, such as Taylor Cruz and Jordan Hayes, highlight his ability to balance protocol with adaptability, encouraging open communication and collaboration [Data: Reports (1); Sources (0, 3)].\n\nOverall, Mercer's skills in leadership, mentorship, focus, and reflective thinking make him an invaluable asset to the Paranormal Military Squad, particularly in the complex and high-stakes environment of Operation: Dulce [Data: Reports (1); Sources (3)]."
{"How does Alex Mercer's leadership style differ from Taylor Cruz's?": {'reports': id title \
+{'What specific skills does Agent Mercer bring to the Paranormal Military Squad?': {'reports': id title \
0 1 Paranormal Military Squad and Operation: Dulce
content
0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
Columns: [in_context]
Index: [], 'sources': id text
-0 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-1 2 differently than praise from others. This was...
-2 3 contrast to the rigid silence enveloping the ...
+0 3 contrast to the rigid silence enveloping the ...
+1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
+2 1 , the hollow echo of the bay a stark reminder ...
+3 2 differently than praise from others. This was...
+4 4 a mask of duty.\n\nIn the midst of the descen...}, 'What are the potential implications of the discoveries at the Dulce base?': {'reports': id title \
+0 1 Paranormal Military Squad and Operation: Dulce
+
+ content
+0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
+Columns: [in_context]
+Index: [], 'sources': id text
+0 2 differently than praise from others. This was...
+1 3 contrast to the rigid silence enveloping the ...
+2 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
+3 4 a mask of duty.\n\nIn the midst of the descen...
+4 1 , the hollow echo of the bay a stark reminder ...}, "How do Agent Mercer's relationships with other team members influence the mission?": {'reports': id title \
+0 1 Paranormal Military Squad and Operation: Dulce
+
+ content
+0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
+Columns: [in_context]
+Index: [], 'sources': id text
+0 2 differently than praise from others. This was...
+1 3 contrast to the rigid silence enveloping the ...
+2 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
3 1 , the hollow echo of the bay a stark reminder ...
-4 4 a mask of duty.\n\nIn the midst of the descen...}, 'What is the significance of the Dulce base in Operation: Dulce?': {'reports': id title \
+4 4 a mask of duty.\n\nIn the midst of the descen...}, 'What specific technologies are being explored at the Dulce base?': {'reports': id title \
0 1 Paranormal Military Squad and Operation: Dulce
content
@@ -2646,18 +2674,7 @@ Index: [], 'sources': id text
1 3 contrast to the rigid silence enveloping the ...
2 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
3 4 a mask of duty.\n\nIn the midst of the descen...
-4 1 , the hollow echo of the bay a stark reminder ...}, "How does Sam Rivera benefit from Alex Mercer's mentorship?": {'reports': id title \
-0 1 Paranormal Military Squad and Operation: Dulce
-
- content
-0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
-Columns: [in_context]
-Index: [], 'sources': id text
-0 3 contrast to the rigid silence enveloping the ...
-1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-2 1 , the hollow echo of the bay a stark reminder ...
-3 2 differently than praise from others. This was...
-4 4 a mask of duty.\n\nIn the midst of the descen...}, 'What are the key challenges faced by the Paranormal Military Squad in Operation: Dulce?': {'reports': id title \
+4 1 , the hollow echo of the bay a stark reminder ...}, 'What role does agent Mercer play in the exploration of the Dulce base?': {'reports': id title \
0 1 Paranormal Military Squad and Operation: Dulce
content
@@ -2667,63 +2684,52 @@ Index: [], 'sources': id text
0 2 differently than praise from others. This was...
1 3 contrast to the rigid silence enveloping the ...
2 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-3 4 a mask of duty.\n\nIn the midst of the descen...
-4 1 , the hollow echo of the bay a stark reminder ...}, 'What challenges does Sam Rivera face during Operation: Dulce?': {'reports': id title \
-0 1 Paranormal Military Squad and Operation: Dulce
-
- content
-0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
-Columns: [in_context]
-Index: [], 'sources': id text
-0 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-1 2 differently than praise from others. This was...
-2 1 , the hollow echo of the bay a stark reminder ...
-3 3 contrast to the rigid silence enveloping the ...
-4 4 a mask of duty.\n\nIn the midst of the descen...}, 'What specific role does Alex Mercer play in overcoming these challenges?': {'reports': id title \
-0 1 Paranormal Military Squad and Operation: Dulce
-
- content
-0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
-Columns: [in_context]
-Index: [], 'sources': id text
-0 3 contrast to the rigid silence enveloping the ...
-1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-2 1 , the hollow echo of the bay a stark reminder ...
-3 2 differently than praise from others. This was...
-4 4 a mask of duty.\n\nIn the midst of the descen...}, "What specific instances demonstrate Alex Mercer's mentorship approach?": {'reports': id title \
-0 1 Paranormal Military Squad and Operation: Dulce
-
- content
-0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
-Columns: [in_context]
-Index: [], 'sources': id text
-0 3 contrast to the rigid silence enveloping the ...
-1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-2 1 , the hollow echo of the bay a stark reminder ...
-3 2 differently than praise from others. This was...
-4 4 a mask of duty.\n\nIn the midst of the descen...}, "In what ways do Alex Mercer's and Taylor Cruz's leadership styles complement each other?": {'reports': id title \
-0 1 Paranormal Military Squad and Operation: Dulce
-
- content
-0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
-Columns: [in_context]
-Index: [], 'sources': id text
-0 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-1 2 differently than praise from others. This was...
-2 3 contrast to the rigid silence enveloping the ...
3 1 , the hollow echo of the bay a stark reminder ...
-4 4 a mask of duty.\n\nIn the midst of the descen...}, 'What specific protocols does Taylor Cruz emphasize during Operation: Dulce?': {'reports': id title \
+4 4 a mask of duty.\n\nIn the midst of the descen...}, "How does Mercer's mentorship impact Sam Rivera's performance during the mission?": {'reports': id title \
0 1 Paranormal Military Squad and Operation: Dulce
content
0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
Columns: [in_context]
Index: [], 'sources': id text
-0 2 differently than praise from others. This was...
-1 3 contrast to the rigid silence enveloping the ...
-2 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
-3 4 a mask of duty.\n\nIn the midst of the descen...
-4 1 , the hollow echo of the bay a stark reminder ...}}
+0 3 contrast to the rigid silence enveloping the ...
+1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
+2 1 , the hollow echo of the bay a stark reminder ...
+3 2 differently than praise from others. This was...
+4 4 a mask of duty.\n\nIn the midst of the descen...}, "In what ways do Mercer's interactions with Taylor Cruz affect the team's decision-making process?": {'reports': id title \
+0 1 Paranormal Military Squad and Operation: Dulce
+
+ content
+0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
+Columns: [in_context]
+Index: [], 'sources': id text
+0 3 contrast to the rigid silence enveloping the ...
+1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
+2 1 , the hollow echo of the bay a stark reminder ...
+3 2 differently than praise from others. This was...
+4 4 a mask of duty.\n\nIn the midst of the descen...}, "What role does intuition play in Mercer's decision-making process?": {'reports': id title \
+0 1 Paranormal Military Squad and Operation: Dulce
+
+ content
+0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
+Columns: [in_context]
+Index: [], 'sources': id text
+0 3 contrast to the rigid silence enveloping the ...
+1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
+2 1 , the hollow echo of the bay a stark reminder ...
+3 2 differently than praise from others. This was...
+4 4 a mask of duty.\n\nIn the midst of the descen...}, "In what ways does Mercer's mentorship of Sam Rivera influence the team's operations?": {'reports': id title \
+0 1 Paranormal Military Squad and Operation: Dulce
+
+ content
+0 # Paranormal Military Squad and Operation: Dul... , 'entities': Empty DataFrame
+Columns: [in_context]
+Index: [], 'sources': id text
+0 3 contrast to the rigid silence enveloping the ...
+1 0 # Operation: Dulce\n\n## Chapter 1\n\nThe thru...
+2 1 , the hollow echo of the bay a stark reminder ...
+3 2 differently than praise from others. This was...
+4 4 a mask of duty.\n\nIn the midst of the descen...}}
### Overview of Operation: Dulce -Operation: Dulce is a significant mission undertaken by the Paranormal Military Squad, an elite group tasked with investigating alien technology and its implications for humanity. The operation focuses on the exploration and uncovering of secrets within the Dulce base, which is central to the mission's objectives [Data: Reports (0)]. +Operation: Dulce is a significant mission undertaken by the Paranormal Military Squad, focusing on the investigation of alien technology and its implications for humanity. This operation is centered around the exploration and uncovering of secrets within the Dulce base, which is known for its association with advanced alien technology. The mission's complexity and importance are underscored by the strategic objectives tied to understanding and potentially harnessing this technology [Data: Reports (0)]. -### Key Elements and Objectives +### Key Participants -The Dulce base is associated with advanced alien technology, making it a crucial element in the mission. The exploration of this base is vital for the success of Operation: Dulce, as it involves navigating its depths to uncover hidden technologies and secrets that may have profound implications for humanity [Data: Reports (1)]. +The operation is executed by the Paranormal Military Squad, which includes key agents such as Alex Mercer, Taylor Cruz, Jordan Hayes, and Sam Rivera. The involvement of these agents is critical to the mission's success, as their expertise and dedication are essential in navigating the challenges posed by the Dulce base [Data: Reports (1)]. -### Team and Motivation +### Mission Objectives -The mission is executed by key agents of the Paranormal Military Squad, including Alex Mercer, Taylor Cruz, Jordan Hayes, and Sam Rivera. Each of these agents plays a significant role in the operation, driven by a strong sense of duty to navigate the complexities of the Dulce base and achieve the mission's objectives [Data: Reports (1, 0)]. +The primary objective of Operation: Dulce is to explore the depths of the Dulce base and investigate the advanced alien technology housed within. This technology is crucial to the mission's goals and the overall success of the operation. The agents are tasked with uncovering the secrets of the base, which may have significant implications for humanity [Data: Reports (1)]. + +### Motivation and Challenges + +A strong sense of duty drives the individuals involved in Operation: Dulce. This motivation is a key factor in their willingness to undertake the mission and face the complexities associated with the Dulce base. The operation requires navigating a range of challenges, emphasizing the importance of the agents' commitment and resolve [Data: Reports (0)].
Build context (gpt-4o) -LLM calls: 2. Prompt tokens: 1761. Output tokens: 208. +LLM calls: 2. Prompt tokens: 1761. Output tokens: 209. Map-reduce (gpt-4o) -LLM calls: 2. Prompt tokens: 3378. Output tokens: 493. +LLM calls: 2. Prompt tokens: 3378. Output tokens: 591.
### Overview of Agent Alex Mercer -Agent Alex Mercer is a prominent member of the Paranormal Military Squad, an elite group tasked with executing Operation: Dulce. He plays a crucial role in the mission, providing guidance and emphasizing the importance of intuition and trust among his team members. Mercer's leadership and mentorship are particularly significant, as he serves as a mentor to Sam Rivera, offering valuable support and leadership [Data: Reports (1); Entities (0); Relationships (2, 15)]. - -### Role in Operation: Dulce - -In Operation: Dulce, Alex Mercer is one of the agents exploring the Dulce base, a mysterious and secretive location associated with advanced alien technology. His involvement in the mission is critical, as he is responsible for leading the team into the Dulce base and navigating its complexities. Mercer's leadership is characterized by a balance between compliance with protocols and a natural inclination to question and explore all details, which sometimes leads to internal conflict [Data: Reports (1); Entities (0, 8); Relationships (23, 4); Claims (3, 5)]. - -### Relationships and Interactions - -Agent Mercer maintains professional relationships with other key members of the Paranormal Military Squad, including Taylor Cruz, Jordan Hayes, and Sam Rivera. His relationship with Taylor Cruz is primarily professional, with Mercer acknowledging Cruz's authority while also experiencing a competitive undercurrent due to Cruz's authoritative nature. With Jordan Hayes, Mercer shares a mutual respect and understanding, particularly admiring each other's expertise and analytical abilities. His mentorship of Sam Rivera highlights his role as a guiding figure within the team [Data: Reports (1); Entities (0, 1, 2, 3); Relationships (0, 1, 2, 15)]. +Agent Alex Mercer is a pivotal member of the Paranormal Military Squad, an elite group tasked with executing Operation: Dulce. His role is crucial to the mission's success, as he is one of the agents exploring the Dulce base, a mysterious and secretive location associated with advanced alien technology [Data: Reports (1); Entities (0, 8); Relationships (23, 4)]. ### Leadership and Mentorship -Alex Mercer's leadership style is marked by his emphasis on intuition and trust, which he believes are essential for the success of their mission. His mentorship of Sam Rivera is a testament to his commitment to nurturing the skills and potential of his team members. This mentorship is not only about imparting knowledge but also about fostering a sense of confidence and readiness in facing the unknown challenges of Operation: Dulce [Data: Reports (1); Entities (0, 3); Relationships (2, 15)]. +Alex Mercer is recognized for his leadership qualities and serves as a mentor to Sam Rivera, another key member of the squad. He provides guidance and emphasizes the importance of intuition and trust, which are essential traits for navigating the complexities of Operation: Dulce. His mentorship relationship with Sam Rivera highlights his supportive nature and his ability to foster talent within the team [Data: Reports (1); Entities (0, 3); Relationships (2, 15)]. -In summary, Agent Alex Mercer is a key figure in the Paranormal Military Squad, whose leadership and mentorship are vital to the success of Operation: Dulce. His ability to balance protocol with intuition, along with his strong professional relationships, underscores his importance in the mission and his role as a mentor to his colleagues. +### Professional Relationships + +Mercer maintains professional relationships with other team members, including Taylor Cruz and Jordan Hayes. His interactions with Taylor Cruz are marked by a competitive undercurrent, as Cruz's authoritative nature often challenges Mercer's compliance. Despite this, Mercer acknowledges Cruz's authority and follows their lead during the mission [Data: Reports (1); Entities (0, 1, 2); Relationships (0, 1)]. + +### Internal Conflict and Role in Operation: Dulce + +Agent Mercer experiences internal conflict between adhering to protocols and his natural inclination to question and explore all details. This conflict is evident in his interactions with Taylor Cruz and his own reflections on the mission. Despite these challenges, Mercer is depicted as a determined individual who is leading a mission into the Dulce base, indicating his significant role in mission leadership and decision-making [Data: Claims (3, 5); Reports (1); Entities (0)]. + +In summary, Agent Alex Mercer is a key figure in the Paranormal Military Squad, known for his leadership, mentorship, and professional relationships. His role in Operation: Dulce is critical, as he navigates the complexities of the mission while managing internal conflicts and fostering teamwork among his colleagues.
### Overview of Dr. Jordan Hayes +## Overview of Dr. Jordan Hayes Dr. Jordan Hayes is a prominent scientist and a key member of the Paranormal Military Squad, known for their expertise in physics and composed demeanor. They play a significant role in Operation: Dulce, particularly in working with alien technology, which is a central element of the mission [Data: Entities (2); Reports (1)]. -### Role in Operation: Dulce +## Role in Operation: Dulce -Dr. Hayes is deeply involved in the exploration of the Dulce base, where they contribute their analytical skills to the mission. Their work primarily focuses on understanding and analyzing alien technology, which is crucial for the success of Operation: Dulce. This role highlights their importance in the mission, as they provide valuable insights and expertise in dealing with the complexities of alien technology [Data: Reports (1); Entities (2, 13); Relationships (26, 48, 51)]. +Dr. Hayes is deeply involved in the exploration of the Dulce base, where they contribute their analytical skills to the mission. Their work primarily focuses on understanding and manipulating alien technology, which is crucial for the success of Operation: Dulce. Hayes is recognized for their analytical mind and reflective nature, often contemplating the complexities of their missions [Data: Reports (1); Entities (2, 13)]. -### Professional Relationships +## Professional Relationships -Dr. Hayes maintains professional relationships with other key members of the Paranormal Military Squad, including Taylor Cruz, Sam Rivera, and Alex Mercer. Their interactions with these team members emphasize the importance of adaptability and analytical thinking in the mission. Dr. Hayes is known for their skepticism towards strict adherence to protocols, advocating for a more flexible approach to the unknown variables encountered during the mission [Data: Reports (1); Relationships (1, 5, 9, 25)]. +Dr. Hayes maintains professional relationships with other key members of the Paranormal Military Squad, including Taylor Cruz, Sam Rivera, and Alex Mercer. Their interactions with Taylor Cruz are marked by differing views on protocol and adaptability, highlighting a complex relationship characterized by moments of mutual respect. With Sam Rivera, Hayes shares a common belief in the importance of adaptability, which is essential for the mission's success [Data: Reports (1); Relationships (5, 9, 25)]. -### Analytical and Skeptical Nature +## Analytical and Skeptical Nature -Dr. Hayes is portrayed as a skeptical and analytical member of the team, often contemplating the layers of data and the complexities of their missions. This skepticism is particularly evident in their interactions with Taylor Cruz, where they emphasize the need for adaptability over rigid protocols. Their analytical insights are crucial in identifying hidden elements within the Dulce base, such as a suspicious panel that seemed out of place [Data: Claims (2, 6, 10); Sources (0, 2)]. +Dr. Hayes is portrayed as skeptical of strict adherence to protocols, emphasizing the need for adaptability and acknowledging the unknown variables that exceed the known. This skepticism is evident in their interactions and comments during mission briefings. They provide analytical insights and express concerns about the mission, indicating a role in analytical assessment [Data: Claims (2, 6); Sources (0)]. -### Contribution to the Team +## Contributions and Discoveries -Dr. Hayes' contribution to the Paranormal Military Squad is significant, as they bring a reflective and analytical perspective to the mission. Their ability to navigate the complexities of alien technology and their composed demeanor make them a valuable asset to the team. Their role in Operation: Dulce underscores the importance of scientific expertise and adaptability in dealing with the unknown challenges posed by the mission [Data: Reports (1); Entities (2); Relationships (10, 18, 21)]. +During the mission, Dr. Hayes identified a suspicious panel that seemed out of place, indicating a hidden element within the Dulce base. This discovery underscores their role in uncovering critical aspects of the mission and highlights their importance in the team's efforts to navigate the complexities of the Dulce base [Data: Claims (10); Sources (2)]. -In summary, Dr. Jordan Hayes is a critical member of the Paranormal Military Squad, whose expertise in physics and alien technology plays a vital role in the success of Operation: Dulce. Their analytical nature and professional relationships with other team members highlight the importance of adaptability and scientific insight in navigating the complexities of the mission. +In summary, Dr. Jordan Hayes is a vital member of the Paranormal Military Squad, contributing their scientific expertise and analytical skills to Operation: Dulce. Their role in working with alien technology and their professional relationships with other team members are crucial to the mission's success.
['- What is the role of Agent Alex Mercer in Operation: Dulce?', "- How does Agent Taylor Cruz's leadership style impact the team's mission at Dulce base?", '- What expertise does Dr. Jordan Hayes bring to the exploration of the Dulce base?', '- How does Sam Rivera contribute to the mission at Dulce base with their cybersecurity skills?', '- What are the dynamics and relationships among the Paranormal Military Squad members during Operation: Dulce?'] +['- What is the role of Agent Alex Mercer in Operation: Dulce?', "- How does Agent Taylor Cruz's leadership style impact the Paranormal Military Squad's mission?", '- What expertise does Dr. Jordan Hayes bring to the exploration of the Dulce base?', '- How does Sam Rivera contribute to the success of Operation: Dulce?', '- What are the dynamics and relationships among the members of the Paranormal Military Squad during their mission at the Dulce base?']
\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 language model's 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:
To address this, the tech community is working to develop methods that extend and enhance RAG. Microsoft Research\u2019s new approach, GraphRAG, creates 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": "At query time, these structures are used to provide materials for the LLM context window when answering a question. The primary query modes are:
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": "#versioning", "title": "Versioning", "text": "Please see the breaking changes document for notes on our approach to versioning the project.
Always run graphrag init --root [path] --force between minor version bumps to ensure you have the latest config format. Run the provided migration notebook between major version bumps if you want to avoid re-indexing prior datasets. Note that this will overwrite your configuration and prompts, so backup if necessary.
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:
--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"}, {"location": "cli/#index", "title": "index", "text": "Build a knowledge graph index.
Usage:
index [OPTIONS]\n Options:
--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --method [standard|fast] The indexing method to use. \\[default:\n standard]\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 --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 output.base_dir in the\n configuration file.\n"}, {"location": "cli/#init", "title": "init", "text": "Generate a default configuration file.
Usage:
init [OPTIONS]\n Options:
--root PATH The project root directory. \\[required]\n --force / --no-force Force initialization even if the project already\n exists. \\[default: no-force]\n"}, {"location": "cli/#prompt-tune", "title": "prompt-tune", "text": "Generate custom graphrag prompts with your own data (i.e. auto templating).
Usage:
prompt-tune [OPTIONS]\n Options:
--root PATH The project root directory. \\[default: .]\n --config PATH The configuration to use.\n --verbose / --no-verbose Run the prompt tuning pipeline with verbose\n logging \\[default: no-verbose]\n --logger [rich|print|none] The progress logger to use. \\[default:\n rich]\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 size of each example text chunk.\n Overrides chunks.size in the configuration\n file. \\[default: 1200]\n --overlap INTEGER The overlap size for chunking documents.\n Overrides chunks.overlap in the\n configuration file \\[default: 100]\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"}, {"location": "cli/#query", "title": "query", "text": "Query a knowledge graph index.
Usage:
query [OPTIONS]\n Options:
--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"}, {"location": "cli/#update", "title": "update", "text": "Update an existing knowledge graph index.
Applies a default output 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:
--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --method [standard|fast] The indexing method to use. \\[default:\n standard]\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 output.base_dir in the\n configuration file.\n"}, {"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": "# Install Python dependencies.\npoetry install\n"}, {"location": "developing/#execute-the-indexing-engine", "title": "Execute the Indexing Engine", "text": "poetry run poe index <...args>\n"}, {"location": "developing/#executing-queries", "title": "Executing Queries", "text": "poetry run poe query <...args>\n"}, {"location": "developing/#azurite", "title": "Azurite", "text": "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 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:
poetry run poe index - Run the Indexing CLIpoetry run poe query - Run the Query CLIpoetry build - This invokes poetry 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 test_verbs - This will execute tests of the basic workflows.poetry run poe check - This will perform a suite of static checks across the package, including: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
export LLVM_CONFIG=/usr/bin/llvm-config-9
Make sure you have python3.10-dev installed or more generally python<version>-dev
sudo apt-get install python3.10-dev
GRAPHRAG_LLM_THREAD_COUNT and GRAPHRAG_EMBEDDING_THREAD_COUNT are both set to 50 by default. You can modify these values to reduce concurrency. Please refer to the Configuration Documents
Python 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:
curl https://www.gutenberg.org/cache/epub/24022/pg24022.txt -o ./ragtest/input/book.txt\n"}, {"location": "get_started/#set-up-your-workspace-variables", "title": "Set Up Your Workspace Variables", "text": "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 and settings.yaml in the ./ragtest directory.
.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 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 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 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.
snapshots:\n graphml: true\n (Optional) To support other visualization tools and exploration, additional parameters can be enabled that provide access to vector embeddings. embed_graph:\n enabled: true # will generate node2vec embeddings for nodes\numap:\n enabled: true # will generate UMAP embeddings for nodes\n After running the indexing pipeline over your data, there will be an output folder (defined by the storage.base_dir setting). In the output folder, look for a file named merged_graph.graphml. graphml is a standard file format supported by many visualization tools. We recommend trying Gephi.
output folder containing the various parquet files.merged_graph.graphml file into Gephi. This will result in a fairly plain view of the undirected graph nodes and edges.Tools -> Plugins.Install and restart Gephi.Statistics tab on the right, click Run for Average Degree and Leiden Algorithm.Appearance pane in the upper left side of Gephi.Nodes, then Partition, and click the color palette icon in the upper right.Cluster from the dropdown.Palette... hyperlink, then Generate....Limit number of colors, click Generate, and then Ok.Apply to color the graph. This will color the graph based on the partitions discovered by Leiden.Appearance pane in the upper left, select Nodes -> RankingSizing icon in the upper right.Degree and set:Apply.Layout tab in the lower left, select OpenORD.Liquid and Expansion stages to 50, and everything else to 0.Run and monitor the progress.Force Atlas 2 in the layout options.Run and wait.Stop when it looks like the graph nodes have settled and no longer change position significantly.Your final graph should now be visually organized and ready for analysis!
"}, {"location": "config/env_vars/", "title": "Default Configuration Mode (using Env Vars)", "text": "As of version 1.3, GraphRAG no longer supports a full complement of pre-built environment variables. Instead, we support variable replacement within the settings.yml file so you can specify any environment variables you like.
The only standard environment variable we expect, and include in the default settings.yml, is GRAPHRAG_API_KEY. If you are already using a number of the previous GRAPHRAG_* environment variables, you can insert them with template syntax into settings.yml and they will be adopted.
The environment variables below are documented as an aid for migration, but they WILL NOT be read unless you use template syntax in your settings.yml.
"}, {"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 to all.
text_unit.textdocument.textentity.titleentity.descriptionrelationship.descriptioncommunity.titlecommunity.summarycommunity.full_contentOur 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 GRAPHRAG_INPUT_ below. In general, CSV-based data provides the most customizability. Each CSV should at least contain a text field (which can be mapped with environment variables), but it's helpful if they also have title, timestamp, and source fields. Additional fields can be included as well, which will land as extra fields on the Document 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 URL str 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. Either openai_chat or azure_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 URL str 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 50 GRAPHRAG_LLM_THREAD_STAGGER The time to wait (in seconds) between starting each thread. float 0.3 GRAPHRAG_LLM_CONCURRENT_REQUESTS The number of concurrent requests to allow for the embedding client. int 25 GRAPHRAG_LLM_TOKENS_PER_MINUTE The number of tokens per minute to allow for the LLM client. 0 = Bypass int 0 GRAPHRAG_LLM_REQUESTS_PER_MINUTE The number of requests per minute to allow for the LLM client. 0 = Bypass int 0 GRAPHRAG_LLM_MAX_RETRIES The maximum number of retries to attempt when a request fails. int 10 GRAPHRAG_LLM_MAX_RETRY_WAIT The maximum number of seconds to wait between retries. int 10 GRAPHRAG_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 0 GRAPHRAG_LLM_TOP_P The top_p to use for sampling. float 1 GRAPHRAG_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. Either openai_embedding or azure_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 16 GRAPHRAG_EMBEDDING_BATCH_MAX_TOKENS The maximum tokens per batch (Azure limit is 8191) int 8191 GRAPHRAG_EMBEDDING_TARGET The target fields to embed. Either required or all. str required 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 50 GRAPHRAG_EMBEDDING_CONCURRENT_REQUESTS The number of concurrent requests to allow for the embedding client. int 25 GRAPHRAG_EMBEDDING_TOKENS_PER_MINUTE The number of tokens per minute to allow for the embedding client. 0 = Bypass int 0 GRAPHRAG_EMBEDDING_REQUESTS_PER_MINUTE The number of requests per minute to allow for the embedding client. 0 = Bypass int 0 GRAPHRAG_EMBEDDING_MAX_RETRIES The maximum number of retries to attempt when a request fails. int 10 GRAPHRAG_EMBEDDING_MAX_RETRY_WAIT The maximum number of seconds to wait between retries. int 10 GRAPHRAG_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 Default GRAPHRAG_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 Default GRAPHRAG_INPUT_TYPE The input storage type to use when reading files. (file or blob) str optional file GRAPHRAG_INPUT_FILE_PATTERN The file pattern regexp to use when reading input files from the input directory. str optional .*\\.txt$ GRAPHRAG_INPUT_TEXT_COLUMN The 'text' column to use when reading CSV input files. str optional text GRAPHRAG_INPUT_METADATA A list of CSV columns, comma-separated, to incorporate as JSON in a metadata column. str optional None GRAPHRAG_INPUT_TITLE_COLUMN The 'title' column to use when reading CSV input files. str optional title GRAPHRAG_INPUT_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_INPUT_CONNECTION_STRING The connection string to use when reading CSV input files from Azure Blob Storage. str optional None GRAPHRAG_INPUT_CONTAINER_NAME The container name to use when reading CSV input files from Azure Blob Storage. str optional None GRAPHRAG_INPUT_BASE_DIR The base directory to read input files from. str optional None"}, {"location": "config/env_vars/#data-mapping-settings", "title": "Data Mapping Settings", "text": "Parameter Description Type Required or Optional Default GRAPHRAG_INPUT_FILE_TYPE The type of input data, csv or text str optional text GRAPHRAG_INPUT_ENCODING The encoding to apply when reading CSV/text input files. str optional utf-8"}, {"location": "config/env_vars/#data-chunking", "title": "Data Chunking", "text": "Parameter Description Type Required or Optional Default GRAPHRAG_CHUNK_SIZE The chunk size in tokens for text-chunk analysis windows. str optional 1200 GRAPHRAG_CHUNK_OVERLAP The chunk overlap in tokens for text-chunk analysis windows. str optional 100 GRAPHRAG_CHUNK_BY_COLUMNS A comma-separated list of document attributes to groupby when performing TextUnit chunking. str optional id 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 Default GRAPHRAG_ENTITY_EXTRACTION_PROMPT_FILE The path (relative to the root) of an entity extraction prompt template text file. str optional None GRAPHRAG_ENTITY_EXTRACTION_MAX_GLEANINGS The maximum number of redrives (gleanings) to invoke when extracting entities in a loop. int optional 1 GRAPHRAG_ENTITY_EXTRACTION_ENTITY_TYPES A comma-separated list of entity types to extract. str optional organization,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 optional None GRAPHRAG_SUMMARIZE_DESCRIPTIONS_MAX_LENGTH The maximum number of tokens to generate per description summarization. int optional 500 GRAPHRAG_CLAIM_EXTRACTION_ENABLED Whether claim extraction is enabled for this pipeline. bool optional False 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 optional None GRAPHRAG_CLAIM_EXTRACTION_MAX_GLEANINGS The maximum number of redrives (gleanings) to invoke when extracting claims in a loop. int optional 1 GRAPHRAG_CLAIM_EXTRACTION_ENCODING_MODEL The encoding model to use for claim extraction. str optional The top-level encoding model GRAPHRAG_COMMUNITY_REPORTS_PROMPT_FILE The community reports extraction prompt to utilize. string optional None 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 are file, memory, or blob str optional file GRAPHRAG_STORAGE_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_STORAGE_CONNECTION_STRING The Azure Storage connection string to use when in blob mode. str optional None GRAPHRAG_STORAGE_CONTAINER_NAME The Azure Storage container name to use when in blob mode. str optional None GRAPHRAG_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 are file, memory, none or blob str optional file GRAPHRAG_CACHE_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_CACHE_CONNECTION_STRING The Azure Storage connection string to use when in blob mode. str optional None GRAPHRAG_CACHE_CONTAINER_NAME The Azure Storage container name to use when in blob mode. str optional None GRAPHRAG_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 are file, console, or blob str optional file GRAPHRAG_REPORTING_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_REPORTING_CONNECTION_STRING The Azure Storage connection string to use when in blob mode. str optional None GRAPHRAG_REPORTING_CONTAINER_NAME The Azure Storage container name to use when in blob mode. str optional None GRAPHRAG_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 Default GRAPHRAG_NODE2VEC_ENABLED Whether to enable Node2Vec bool optional False GRAPHRAG_NODE2VEC_NUM_WALKS The Node2Vec number of walks to perform int optional 10 GRAPHRAG_NODE2VEC_WALK_LENGTH The Node2Vec walk length int optional 40 GRAPHRAG_NODE2VEC_WINDOW_SIZE The Node2Vec window size int optional 2 GRAPHRAG_NODE2VEC_ITERATIONS The number of iterations to run node2vec int optional 3 GRAPHRAG_NODE2VEC_RANDOM_SEED The random seed to use for node2vec int optional 597832"}, {"location": "config/env_vars/#data-snapshotting", "title": "Data Snapshotting", "text": "Parameter Description Type Required or Optional Default GRAPHRAG_SNAPSHOT_EMBEDDINGS Whether to enable embeddings snapshots. bool optional False GRAPHRAG_SNAPSHOT_GRAPHML Whether to enable GraphML snapshots. bool optional False GRAPHRAG_SNAPSHOT_RAW_ENTITIES Whether to enable raw entity snapshots. bool optional False GRAPHRAG_SNAPSHOT_TOP_LEVEL_NODES Whether to enable top-level node snapshots. bool optional False GRAPHRAG_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 Default GRAPHRAG_ASYNC_MODE Which async mode to use. Either asyncio or threaded. str optional asyncio GRAPHRAG_ENCODING_MODEL The text encoding model, used in tiktoken, to encode text. str optional cl100k_base GRAPHRAG_MAX_CLUSTER_SIZE The maximum number of entities to include in a single Leiden cluster. int optional 10 GRAPHRAG_UMAP_ENABLED Whether to enable UMAP layouts bool optional False"}, {"location": "config/init/", "title": "Configuring GraphRAG Indexing", "text": "To start using GraphRAG, you must generate a configuration file. The init command is the easiest way to get started. It will create a .env and settings.yaml files in the specified directory with the necessary configuration settings. It will also output the default LLM prompts used by GraphRAG.
graphrag init [--root PATH] [--force, --no-force]\n"}, {"location": "config/init/#options", "title": "Options", "text": "--root PATH - The project root directory to initialize graphrag at. Default is the current directory.--force, --no-force - Optional, default is --no-force. Overwrite existing configuration and prompt files if they exist.graphrag init --root ./ragtest\n"}, {"location": "config/init/#output", "title": "Output", "text": "The init command will create the following files in the specified directory:
settings.yaml - The configuration settings file. This file contains the configuration settings for GraphRAG..env - The environment variables file. These are referenced in the settings.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:
The default configuration mode may be configured by using a settings.yml or settings.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 in graphrag 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:
# .env\nGRAPHRAG_API_KEY=some_api_key\n\n# settings.yml\nllm: \n api_key: ${GRAPHRAG_API_KEY}\n"}, {"location": "config/yaml/#config-sections", "title": "Config Sections", "text": ""}, {"location": "config/yaml/#indexing", "title": "Indexing", "text": ""}, {"location": "config/yaml/#models", "title": "models", "text": "This is a dict of model configurations. The dict key is used to reference this configuration elsewhere when a model instance is desired. In this way, you can specify as many different models as you need, and reference them differentially in the workflow steps.
For example:
models:\n default_chat_model:\n api_key: ${GRAPHRAG_API_KEY}\n type: openai_chat\n model: gpt-4o\n model_supports_json: true\n default_embedding_model:\n api_key: ${GRAPHRAG_API_KEY}\n type: openai_embedding\n model: text-embedding-ada-002\n"}, {"location": "config/yaml/#fields", "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.encoding_model str - The text encoding model to use. Default is to use the encoding model aligned with the language model (i.e., it is retrieved from tiktoken if unset).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 version.organization str - The client organization.proxy str - The proxy URL to use.azure_auth_type api_key|managed_identity - if using Azure, please indicate how you want to authenticate requests.audience str - (Azure OpenAI only) The URI of the target Azure resource/service for which a managed identity token is requested. Used if api_key is not defined. Default=https://cognitiveservices.azure.com/.defaultdeployment_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.parallelization_stagger float - The threading stagger value.parallelization_num_threads int - The maximum number of work threads.async_mode asyncio|threaded The async mode to use. Either asyncio or `threaded.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 customized by setting the target and names fields.
Supported embeddings names are: - text_unit.text - document.text - entity.title - entity.description - relationship.description - community.title - community.summary - community.full_content
model_id str - Name of the model definition to use for text embedding.batch_size int - The maximum batch size to use.batch_max_tokens int - The maximum batch # of tokens.target required|all|selected|none - Determines which set of embeddings to export.names list[str] - If target=selected, this should be an explicit list of the embeddings names we support.Where to put all vectors for the system. Configured for lancedb by default.
"}, {"location": "config/yaml/#fields_2", "title": "Fields", "text": "type str - lancedb or azure_ai_search. Default=lancedbdb_uri str (only for lancedb) - The database uri. Default=storage.base_dir/lancedburl 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=Truecontainer_name str - The name of a vector container. This stores all indexes (tables) for a given dataset ingest. Default=defaultOur pipeline can ingest .csv or .txt data from an input folder. These files can be nested within subfolders. In general, CSV-based data provides the most customizability. Each CSV should at least contain a text field. You can use the metadata list to specify additional columns from the CSV to include as headers in each text chunk, allowing you to repeat document content within each chunk for better LLM inclusion.
type file|blob - The input type to use. Default=filefile_type text|csv - The type of input data to load. Either text or csv. Default is textbase_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 is utf-8file_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.text_column str - (CSV Mode Only) The text column name.metadata list[str] - (CSV Mode Only) The additional document attributes to include.These settings configure how we parse documents into text chunks. This is necessary because very large documents may not fit into a single context window, and graph extraction accuracy can be modulated. Also note the metadata setting in the input document config, which will replicate document metadata into each chunk.
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 for splitting on token boundaries.prepend_metadata bool - Determines if metadata values should be added at the beginning of each chunk. Default=False.chunk_size_includes_metadata bool - Specifies whether the chunk size calculation should include metadata tokens. Default=False.This section controls the cache mechanism used by the pipeline. This is used to cache LLM invocation results.
"}, {"location": "config/yaml/#fields_5", "title": "Fields", "text": "type file|memory|none|blob - The cache type to use. Default=fileconnection_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.This section controls the storage mechanism used by the pipeline used for exporting output tables.
"}, {"location": "config/yaml/#fields_6", "title": "Fields", "text": "type file|memory|blob - The storage type to use. Default=fileconnection_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.The section defines a secondary storage location for running incremental indexing, to preserve your original outputs.
"}, {"location": "config/yaml/#fields_7", "title": "Fields", "text": "type file|memory|blob - The storage type to use. Default=fileconnection_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.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.
"}, {"location": "config/yaml/#fields_8", "title": "Fields", "text": "type file|console|blob - The reporting type to use. Default=fileconnection_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.model_id str - Name of the model definition to use for API calls.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.model_id str - Name of the model definition to use for API calls.prompt str - The prompt file to use.max_length int - The maximum number of output tokens per summarization.Defines settings for NLP-based graph extraction methods.
"}, {"location": "config/yaml/#fields_11", "title": "Fields", "text": "normalize_edge_weights bool - Whether to normalize the edge weights during graph construction. Default=True.text_analyzer dict - Parameters for the NLP model.regex_english.15.True.None, we use an internal stopword list.enabled bool - Whether to enable claim extraction. Off by default, because claim prompts really need user tuning.model_id str - Name of the model definition to use for API calls.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.model_id str - Name of the model definition to use for API calls.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.Parameters for manual graph pruning. This can be used to optimize the modularity of your graph clusters, by removing overly-connected or rare nodes.
"}, {"location": "config/yaml/#fields_14", "title": "Fields", "text": "These are the settings used for Leiden hierarchical clustering of the graph to create communities.
"}, {"location": "config/yaml/#fields_15", "title": "Fields", "text": "max_cluster_size int - The maximum cluster size to export.use_lcc bool - Whether to only use the largest connected component.seed int - A randomization seed to provide if consistent run-to-run results are desired. We do provide a default in order to guarantee clustering stability.We use node2vec to embed the graph. This is primarily used for visualization, so it is not turned on by default. However, if you do prefer to embed the graph for secondary analysis, you can turn this on and we will persist the embeddings to your configured vector store.
"}, {"location": "config/yaml/#fields_16", "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.Indicates whether we should run UMAP dimensionality reduction. This is used to provide an x/y coordinate to each graph node, suitable for visualization. If this is not enabled, nodes will receive a 0/0 x/y coordinate. If this is enabled, you must enable graph embedding as well.
"}, {"location": "config/yaml/#fields_17", "title": "Fields", "text": "enabled bool - Whether to enable UMAP layouts.embeddings bool - Export embeddings snapshots to parquet.graphml bool - Export graph snapshots to GraphML.chat_model_id str - Name of the model definition to use for Chat Completion calls.embedding_model_id str - Name of the model definition to use for Embedding calls.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.chat_model_id str - Name of the model definition to use for Chat Completion calls.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.chat_model_id str - Name of the model definition to use for Chat Completion calls.embedding_model_id str - Name of the model definition to use for Embedding calls.prompt str - The prompt file to use.reduce_prompt str - The reducer 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.chat_model_id str - Name of the model definition to use for Chat Completion calls.embedding_model_id str - Name of the model definition to use for Embedding calls.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.list[str] - This is a list of workflow names to run, in order. GraphRAG has built-in pipelines to configure this, but you can run exactly and only what you want by specifying the list here. Useful if you have done part of the processing yourself.
"}, {"location": "data/operation_dulce/ABOUT/", "title": "About", "text": "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.
---\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"}, {"location": "index/architecture/#llm-caching", "title": "LLM Caching", "text": "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.
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 set CHUNK_BY_COLUMNS to id 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.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.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.
---\ntitle: Dataflow Overview\n---\nflowchart TB\n subgraph phase1[Phase 1: Compose TextUnits]\n documents[Documents] --> chunk[Chunk]\n chunk --> 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 --> community_outputs[Communities Table]\n end\n subgraph phase4[Phase 4: Community Summarization]\n community_outputs --> summarized_communities[Community Summarization]\n summarized_communities --> community_report_outputs[Community Reports Table]\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 --> document_outputs[Documents Table]\n end\n subgraph phase6[Phase 6: Network Visualization]\n graph_outputs --> graph_embed[Graph Embedding]\n graph_embed --> umap_entities[Umap Entities]\n umap_entities --> combine_nodes[Final Entities]\n end\n subgraph phase7[Phase 7: Text Embeddings]\n textUnits --> text_embed[Text Embedding]\n graph_outputs --> description_embed[Description Embedding]\n community_report_outputs --> content_embed[Content Embedding]\n end"}, {"location": "index/default_dataflow/#phase-1-compose-textunits", "title": "Phase 1: Compose TextUnits", "text": "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 text.
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)
---\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"}, {"location": "index/default_dataflow/#phase-2-graph-extraction", "title": "Phase 2: Graph Extraction", "text": "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.
---\ntitle: Graph Extraction\n---\nflowchart LR\n tu[TextUnit] --> ge[Graph Extraction] --> gs[Graph Summarization]\n tu --> ce[Claim Extraction]"}, {"location": "index/default_dataflow/#entity-relationship-extraction", "title": "Entity & Relationship Extraction", "text": "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 title, type, and description, and a list of relationships with a source, target, and description.
These subgraphs are merged together - any entities with the same title 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-optional", "title": "Claim Extraction (optional)", "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. These give us explicit ways of understanding the topological structure of our graph.
---\ntitle: Graph Augmentation\n---\nflowchart LR\n cd[Leiden Hierarchical Community Detection] --> ag[Graph Tables]"}, {"location": "index/default_dataflow/#community-detection", "title": "Community Detection", "text": "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-tables", "title": "Graph Tables", "text": "Once our graph augmentation steps are complete, the final Entities, Relationships, and Communities tables are exported.
"}, {"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] --> co[Community Reports Table] At this point, we have a functional graph of entities and relationships and a hierarchy of communities for the entities.
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-reports-table", "title": "Community Reports Table", "text": "At this point, some bookkeeping work is performed and we export the Community Reports 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.
---\ntitle: Document Processing\n---\nflowchart LR\n aug[Augment] --> dp[Link to TextUnits] --> dg[Documents Table]"}, {"location": "index/default_dataflow/#augment-with-columns-csv-only", "title": "Augment with Columns (CSV Only)", "text": "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/#documents-table", "title": "Documents Table", "text": "At this point, we can export the Documents table into the knowledge Model.
"}, {"location": "index/default_dataflow/#phase-6-network-visualization-optional", "title": "Phase 6: Network Visualization (optional)", "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 ag[Graph Table] --> ge[Node2Vec Graph Embedding] --> ne[Umap Entities] --> ng[Entities Table]"}, {"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/#dimensionality-reduction", "title": "Dimensionality Reduction", "text": "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 reduced to two dimensions as x/y coordinates.
"}, {"location": "index/default_dataflow/#phase-7-text-embedding", "title": "Phase 7: Text Embedding", "text": "For all artifacts that require downstream vector search, we generate text embeddings as a final step. These embeddings are written directly to a configured vector store. By default we embed entity descriptions, text unit text, and community report text.
---\ntitle: Text Embedding Workflows\n---\nflowchart LR\n textUnits[Text Units] --> text_embed[Text Embedding]\n graph_outputs[Graph Tables] --> description_embed[Description Embedding]\n community_report_outputs[Community Reports] --> content_embed[Content Embedding]"}, {"location": "index/inputs/", "title": "Inputs", "text": "GraphRAG supports several input formats to simplify ingesting your data. The mechanics and features available for input files and text chunking are discussed here.
"}, {"location": "index/inputs/#input-loading-and-schema", "title": "Input Loading and Schema", "text": "All input formats are loaded within GraphRAG and passed to the indexing pipeline as a documents DataFrame. This DataFrame has a row for each document using a shared column schema:
Also see the outputs documentation for the final documents table schema saved to parquet after pipeline completion.
"}, {"location": "index/inputs/#formats", "title": "Formats", "text": "We support three file formats out-of-the-box. This covers the overwhelming majority of use cases we have encountered. If you have a different format, we recommend writing a script to convert to one of these, which are widely used and supported by many tools and libraries.
"}, {"location": "index/inputs/#plain-text", "title": "Plain Text", "text": "Plain text files (typically ending in .txt file extension). With plain text files we import the entire file contents as the text field, and the title is always the filename.
CSV files (typically ending in a .csv extension). These are loaded using pandas' read_csv method with default options. Each row in a CSV file is treated as a single document. If you have multiple CSV files in your input folder, they will be concatenated into a single resulting documents DataFrame.
With the CSV format you can configure the text_column, and title_column if your data has structured content you would prefer to use. If you do not configure these within the input block of your settings.yaml, the title will be the filename as described in the schema above. The text_column is assumed to be \"text\" in your file if not configured specifically. We will also look for and use an \"id\" column if present, otherwise the ID will be generated as described above.
JSON files (typically ending in a .json extension) contain structured objects. These are loaded using python's json.loads method, so your files must be properly compliant. JSON files may contain a single object in the file or the file may contain an array of objects at the root. We will check for and handle either of these cases. As with CSV, multiple files will be concatenated into a final table, and the text_column and title_column config options will be applied to the properties of each loaded object. Note that the specialized jsonl format produced by some libraries (one full JSON object on each line, not in an array) is not currently supported.
With the structured file formats (CSV and JSON) you can configure any number of columns to be added to a persisted metadata field in the DataFrame. This is configured by supplying a list of columns name to collect. If this is configured, the output metadata column will have a dict containing a key for each column, and the value of the column for that document. This metadata can optionally be used later in the GraphRAG pipeline.
software.csv
text,title,tag\nMy first program,Hello World,tutorial\nAn early space shooter game,Space Invaders,arcade\n settings.yaml
input:\n metadata: [title,tag]\n Documents DataFrame
id title text creation_date metadata (generated from text) Hello World My first program (create date of software.csv) { \"title\": \"Hello World\", \"tag\": \"tutorial\" } (generated from text) Space Invaders An early space shooter game (create date of software.csv) { \"title\": \"Space Invaders\", \"tag\": \"arcade\" }"}, {"location": "index/inputs/#chunking-and-metadata", "title": "Chunking and Metadata", "text": "As described on the default dataflow page, documents are chunked into smaller \"text units\" for processing. This is done because document content size often exceeds the available context window for a given language model. There are a handful of settings you can adjust for this chunking, the most relevant being the chunk_size and overlap. We now also support a metadata processing scheme that can improve indexing results for some use cases. We will describe this feature in detail here.
Imagine the following scenario: you are indexing a collection of news articles. Each article text starts with a headline and author, and then proceeds with the content. When documents are chunked, they are split evenly according to your configured chunk size. In other words, the first n tokens are read into a text unit, and then the next n, until the end of the content. This means that front matter at the beginning of the document (such as the headline and author in this example) is not copied to each chunk. It only exists in the first chunk. When we later retrieve those chunks for summarization, they may therefore be missing shared information about the source document that should always be provided to the model. We have configuration options to copy repeated content into each text unit to address this issue.
"}, {"location": "index/inputs/#input-config", "title": "Input Config", "text": "As described above, when documents are imported you can specify a list of metadata columns to include with each row. This must be configured for the per-chunk copying to work.
Next, the chunks block needs to instruct the chunker how to handle this metadata when creating text units. By default, it is ignored. We have two settings to include it:
prepend_metadata. This instructs the importer to copy the contents of the metadata column for each row into the start of every single text chunk. This metadata is copied as key: value pairs on new lines.chunk_size_includes_metadata: This tells the chunker how to compute the chunk size when metadata is included. By default, we create the text units using your specified chunk_size and then prepend the metadata. This means that the final text unit lengths may be longer than your configured chunk_size, and it will vary based on the length of the metadata for each document. When this setting is True, we will compute the raw text using the remainder after measuring the metadata length so that the resulting text units always comply with your configured chunk_size.The following are several examples to help illustrate how chunking config and metadate prepending works for each file format. Note that we are using word count here as \"tokens\" for the illustration, but language model tokens are not equivalent to words.
"}, {"location": "index/inputs/#text-files", "title": "Text files", "text": "This example uses two individual news article text files.
--
File: US to lift most federal COVID-19 vaccine mandates.txt
Content:
WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday.
--
File: NY lawmakers begin debating budget 1 month after due date.txt
Content:
ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate.
--
settings.yaml
input:\n file_type: text\n metadata: [title]\n\nchunks:\n size: 100\n overlap: 0\n prepend_metadata: true\n chunk_size_includes_metadata: false\n Documents DataFrame
id title text creation_date metadata (generated from text) US to lift most federal COVID-19 vaccine mandates.txt (full content of text file) (create date of article txt file) { \"title\": \"US to lift most federal COVID-19 vaccine mandates.txt\" } (generated from text) NY lawmakers begin debating budget 1 month after due date.txt (full content of text file) (create date of article txt file) { \"title\": \"NY lawmakers begin debating budget 1 month after due date.txt\" }Raw Text Chunks
content length title: US to lift most federal COVID-19 vaccine mandates.txtWASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as 109 title: US to lift most federal COVID-19 vaccine mandates.txtthe deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday. 82 title: NY lawmakers begin debating budget 1 month after due date.txtALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to 111 title: NY lawmakers begin debating budget 1 month after due date.txtbe wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it 111 title: NY lawmakers begin debating budget 1 month after due date.txtwould undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate. 89In this example we can see that the two input documents were parsed into five output text chunks. The title (filename) of each document is prepended but not included in the computed chunk size. Also note that the final text chunk for each document is usually smaller than the chunk size because it contains the last tokens.
"}, {"location": "index/inputs/#csv-files", "title": "CSV files", "text": "This example uses a single CSV file with the same two articles as rows (note that the text content is not properly escaped for actual CSV use).
--
File: articles.csv
Content
headline,article
US to lift most federal COVID-19 vaccine mandates,WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday.
NY lawmakers begin debating budget 1 month after due date,ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate.
--
settings.yaml
input:\n file_type: csv\n title_column: headline\n text_column: article\n metadata: [headline]\n\nchunks:\n size: 50\n overlap: 5\n prepend_metadata: true\n chunk_size_includes_metadata: true\n Documents DataFrame
id title text creation_date metadata (generated from text) US to lift most federal COVID-19 vaccine mandates (article column content) (create date of articles.csv) { \"headline\": \"US to lift most federal COVID-19 vaccine mandates\" } (generated from text) NY lawmakers begin debating budget 1 month after due date (article column content) (create date of articles.csv) { \"headline\": \"NY lawmakers begin debating budget 1 month after due date\" }Raw Text Chunks
content length title: US to lift most federal COVID-19 vaccine mandatesWASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, 50 title: US to lift most federal COVID-19 vaccine mandatesfederal workers and federal contractors as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. 50 title: US to lift most federal COVID-19 vaccine mandatesnoncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how 50 title: US to lift most federal COVID-19 vaccine mandatesthe latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that 50 title: US to lift most federal COVID-19 vaccine mandatespoint where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday. 38 title: NY lawmakers begin debating budget 1 month after due dateALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new 50 title: NY lawmakers begin debating budget 1 month after due datestoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and 50 title: NY lawmakers begin debating budget 1 month after due dateto the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget 50 title: NY lawmakers begin debating budget 1 month after due dateup Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been 50 title: NY lawmakers begin debating budget 1 month after due datevoting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges 50 title: NY lawmakers begin debating budget 1 month after due datethe standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 50 title: NY lawmakers begin debating budget 1 month after due datebail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum 50 title: NY lawmakers begin debating budget 1 month after due dateto state officials. The minimum wage would be raised to $17 in be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 50 title: NY lawmakers begin debating budget 1 month after due date2026. That's up from $15 in the city and $14.20 upstate. 22In this example we can see that the two input documents were parsed into fourteen output text chunks. The title (headline) of each document is prepended and included in the computed chunk size, so each chunk matches the configured chunk size (except the last one for each document). We've also configured some overlap in these text chunks, so the last five tokens are shared. Why would you use overlap in your text chunks? Consider that when you are splitting documents based on tokens, it is highly likely that sentences or even related concepts will be split into separate chunks. Each text chunk is processed separately by the language model, so this may result in incomplete \"ideas\" at the boundaries of the chunk. Overlap ensures that these split concepts are fully contained in at least one of the chunks.
"}, {"location": "index/inputs/#json-files", "title": "JSON files", "text": "This final example uses a JSON file for each of the same two articles. In this example we'll set the object fields to read, but we will not add metadata to the text chunks.
--
File: article1.json
Content
{\n \"headline\": \"US to lift most federal COVID-19 vaccine mandates\",\n \"content\": \"WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday.\"\n}\n File: article2.json
Content
{\n \"headline\": \"NY lawmakers begin debating budget 1 month after due date\",\n \"content\": \"ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate.\"\n}\n --
settings.yaml
input:\n file_type: json\n title_column: headline\n text_column: content\n\nchunks:\n size: 100\n overlap: 10\n Documents DataFrame
id title text creation_date metadata (generated from text) US to lift most federal COVID-19 vaccine mandates (article column content) (create date of article1.json) { } (generated from text) NY lawmakers begin debating budget 1 month after due date (article column content) (create date of article2.json) { }Raw Text Chunks
content length WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as 100 measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday. 83 ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to 100 Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges 100 means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate. 98In this example the two input documents were parsed into five output text chunks. There is no metadata prepended, so each chunk matches the configured chunk size (except the last one for each document). We've also configured some overlap in these text chunks, so the last ten tokens are shared.
"}, {"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/#communities", "title": "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. children int[] List of child community IDs. 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/#community_reports", "title": "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. children int[] List of child community IDs. 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 rating_explanation str LM-derived explanation of the rank. findings dict LM-derived list of the top 5-10 insights from the community. Containssummary and explanation 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/#covariates", "title": "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/#documents", "title": "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. metadata dict If specified during CSV import, this is a dict of metadata for the document."}, {"location": "index/outputs/#entities", "title": "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. frequency int Count of text units the entity was found within. 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/#relationships", "title": "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/#text_units", "title": "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:
The outputs of the pipeline are stored as Parquet tables by default, and embeddings are written to your configured vector store.
"}, {"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.
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": "# Via Poetry\npoetry run poe index --root <data_root> # default config mode\n"}, {"location": "index/overview/#python-api", "title": "Python API", "text": "Please see the indexing API python file for the recommended method to call directly from Python code.
"}, {"location": "index/overview/#further-reading", "title": "Further Reading", "text": "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 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:
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/#command-line-options", "title": "Command-Line Options", "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.
--selection-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--selection-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):
python -m graphrag prompt-tune --root /path/to/project --config /path/to/settings.yaml --no-entity-types\n"}, {"location": "prompt_tuning/auto_prompt_tuning/#document-selection-methods", "title": "Document Selection Methods", "text": "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:
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:
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"}, {"location": "prompt_tuning/manual_prompt_tuning/", "title": "Manual Prompt Tuning \u2699\ufe0f", "text": "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 {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": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_1", "title": "Tokens", "text": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_2", "title": "Tokens", "text": "\"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": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_4", "title": "Tokens", "text": "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": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_6", "title": "Tokens", "text": "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:
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 the reduce 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:
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 the map stage. Default template can be found at map_system_promptreduce_system_prompt: prompt template used in the reduce 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 the reduce_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 the reduce_system_prompt if allow_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 the map stagereduce_llm_params: a dictionary of additional parameters (e.g., temperature, max_tokens) to passed to the LLM call at the reduce stagecontext_builder_params: a dictionary of additional parameters to be passed to the context_builder object when building context window for the map stage.concurrent_coroutines: controls the degree of parallelism in the map 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:
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 the context_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:
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:
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 the context_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": "For examples about running Query please refer to the following notebooks:
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 language model's 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:
To address this, the tech community is working to develop methods that extend and enhance RAG. Microsoft Research\u2019s new approach, GraphRAG, creates 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": "At query time, these structures are used to provide materials for the LLM context window when answering a question. The primary query modes are:
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": "#versioning", "title": "Versioning", "text": "Please see the breaking changes document for notes on our approach to versioning the project.
Always run graphrag init --root [path] --force between minor version bumps to ensure you have the latest config format. Run the provided migration notebook between major version bumps if you want to avoid re-indexing prior datasets. Note that this will overwrite your configuration and prompts, so backup if necessary.
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:
--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"}, {"location": "cli/#index", "title": "index", "text": "Build a knowledge graph index.
Usage:
index [OPTIONS]\n Options:
--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --method [standard|fast] The indexing method to use. \\[default:\n standard]\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 --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 output.base_dir in the\n configuration file.\n"}, {"location": "cli/#init", "title": "init", "text": "Generate a default configuration file.
Usage:
init [OPTIONS]\n Options:
--root PATH The project root directory. \\[required]\n --force / --no-force Force initialization even if the project already\n exists. \\[default: no-force]\n"}, {"location": "cli/#prompt-tune", "title": "prompt-tune", "text": "Generate custom graphrag prompts with your own data (i.e. auto templating).
Usage:
prompt-tune [OPTIONS]\n Options:
--root PATH The project root directory. \\[default: .]\n --config PATH The configuration to use.\n --verbose / --no-verbose Run the prompt tuning pipeline with verbose\n logging \\[default: no-verbose]\n --logger [rich|print|none] The progress logger to use. \\[default:\n rich]\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 size of each example text chunk.\n Overrides chunks.size in the configuration\n file. \\[default: 1200]\n --overlap INTEGER The overlap size for chunking documents.\n Overrides chunks.overlap in the\n configuration file \\[default: 100]\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"}, {"location": "cli/#query", "title": "query", "text": "Query a knowledge graph index.
Usage:
query [OPTIONS]\n Options:
--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"}, {"location": "cli/#update", "title": "update", "text": "Update an existing knowledge graph index.
Applies a default output 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:
--config PATH The configuration to use.\n --root PATH The project root directory. \\[default: .]\n --method [standard|fast] The indexing method to use. \\[default:\n standard]\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 output.base_dir in the\n configuration file.\n"}, {"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": "# Install Python dependencies.\npoetry install\n"}, {"location": "developing/#execute-the-indexing-engine", "title": "Execute the Indexing Engine", "text": "poetry run poe index <...args>\n"}, {"location": "developing/#executing-queries", "title": "Executing Queries", "text": "poetry run poe query <...args>\n"}, {"location": "developing/#azurite", "title": "Azurite", "text": "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 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:
poetry run poe index - Run the Indexing CLIpoetry run poe query - Run the Query CLIpoetry build - This invokes poetry 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 test_verbs - This will execute tests of the basic workflows.poetry run poe check - This will perform a suite of static checks across the package, including: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
export LLVM_CONFIG=/usr/bin/llvm-config-9
Make sure you have python3.10-dev installed or more generally python<version>-dev
sudo apt-get install python3.10-dev
GRAPHRAG_LLM_THREAD_COUNT and GRAPHRAG_EMBEDDING_THREAD_COUNT are both set to 50 by default. You can modify these values to reduce concurrency. Please refer to the Configuration Documents
Python 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:
curl https://www.gutenberg.org/cache/epub/24022/pg24022.txt -o ./ragtest/input/book.txt\n"}, {"location": "get_started/#set-up-your-workspace-variables", "title": "Set Up Your Workspace Variables", "text": "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 and settings.yaml in the ./ragtest directory.
.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 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 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 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.
snapshots:\n graphml: true\n (Optional) To support other visualization tools and exploration, additional parameters can be enabled that provide access to vector embeddings. embed_graph:\n enabled: true # will generate node2vec embeddings for nodes\numap:\n enabled: true # will generate UMAP embeddings for nodes\n After running the indexing pipeline over your data, there will be an output folder (defined by the storage.base_dir setting). In the output folder, look for a file named merged_graph.graphml. graphml is a standard file format supported by many visualization tools. We recommend trying Gephi.
output folder containing the various parquet files.merged_graph.graphml file into Gephi. This will result in a fairly plain view of the undirected graph nodes and edges.Tools -> Plugins.Install and restart Gephi.Statistics tab on the right, click Run for Average Degree and Leiden Algorithm.Appearance pane in the upper left side of Gephi.Nodes, then Partition, and click the color palette icon in the upper right.Cluster from the dropdown.Palette... hyperlink, then Generate....Limit number of colors, click Generate, and then Ok.Apply to color the graph. This will color the graph based on the partitions discovered by Leiden.Appearance pane in the upper left, select Nodes -> RankingSizing icon in the upper right.Degree and set:Apply.Layout tab in the lower left, select OpenORD.Liquid and Expansion stages to 50, and everything else to 0.Run and monitor the progress.Force Atlas 2 in the layout options.Run and wait.Stop when it looks like the graph nodes have settled and no longer change position significantly.Your final graph should now be visually organized and ready for analysis!
"}, {"location": "config/env_vars/", "title": "Default Configuration Mode (using Env Vars)", "text": "As of version 1.3, GraphRAG no longer supports a full complement of pre-built environment variables. Instead, we support variable replacement within the settings.yml file so you can specify any environment variables you like.
The only standard environment variable we expect, and include in the default settings.yml, is GRAPHRAG_API_KEY. If you are already using a number of the previous GRAPHRAG_* environment variables, you can insert them with template syntax into settings.yml and they will be adopted.
The environment variables below are documented as an aid for migration, but they WILL NOT be read unless you use template syntax in your settings.yml.
"}, {"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 to all.
text_unit.textdocument.textentity.titleentity.descriptionrelationship.descriptioncommunity.titlecommunity.summarycommunity.full_contentOur 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 GRAPHRAG_INPUT_ below. In general, CSV-based data provides the most customizability. Each CSV should at least contain a text field (which can be mapped with environment variables), but it's helpful if they also have title, timestamp, and source fields. Additional fields can be included as well, which will land as extra fields on the Document 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 URL str 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. Either openai_chat or azure_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 URL str 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 50 GRAPHRAG_LLM_THREAD_STAGGER The time to wait (in seconds) between starting each thread. float 0.3 GRAPHRAG_LLM_CONCURRENT_REQUESTS The number of concurrent requests to allow for the embedding client. int 25 GRAPHRAG_LLM_TOKENS_PER_MINUTE The number of tokens per minute to allow for the LLM client. 0 = Bypass int 0 GRAPHRAG_LLM_REQUESTS_PER_MINUTE The number of requests per minute to allow for the LLM client. 0 = Bypass int 0 GRAPHRAG_LLM_MAX_RETRIES The maximum number of retries to attempt when a request fails. int 10 GRAPHRAG_LLM_MAX_RETRY_WAIT The maximum number of seconds to wait between retries. int 10 GRAPHRAG_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 0 GRAPHRAG_LLM_TOP_P The top_p to use for sampling. float 1 GRAPHRAG_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. Either openai_embedding or azure_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 16 GRAPHRAG_EMBEDDING_BATCH_MAX_TOKENS The maximum tokens per batch (Azure limit is 8191) int 8191 GRAPHRAG_EMBEDDING_TARGET The target fields to embed. Either required or all. str required 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 50 GRAPHRAG_EMBEDDING_CONCURRENT_REQUESTS The number of concurrent requests to allow for the embedding client. int 25 GRAPHRAG_EMBEDDING_TOKENS_PER_MINUTE The number of tokens per minute to allow for the embedding client. 0 = Bypass int 0 GRAPHRAG_EMBEDDING_REQUESTS_PER_MINUTE The number of requests per minute to allow for the embedding client. 0 = Bypass int 0 GRAPHRAG_EMBEDDING_MAX_RETRIES The maximum number of retries to attempt when a request fails. int 10 GRAPHRAG_EMBEDDING_MAX_RETRY_WAIT The maximum number of seconds to wait between retries. int 10 GRAPHRAG_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 Default GRAPHRAG_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 Default GRAPHRAG_INPUT_TYPE The input storage type to use when reading files. (file or blob) str optional file GRAPHRAG_INPUT_FILE_PATTERN The file pattern regexp to use when reading input files from the input directory. str optional .*\\.txt$ GRAPHRAG_INPUT_TEXT_COLUMN The 'text' column to use when reading CSV input files. str optional text GRAPHRAG_INPUT_METADATA A list of CSV columns, comma-separated, to incorporate as JSON in a metadata column. str optional None GRAPHRAG_INPUT_TITLE_COLUMN The 'title' column to use when reading CSV input files. str optional title GRAPHRAG_INPUT_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_INPUT_CONNECTION_STRING The connection string to use when reading CSV input files from Azure Blob Storage. str optional None GRAPHRAG_INPUT_CONTAINER_NAME The container name to use when reading CSV input files from Azure Blob Storage. str optional None GRAPHRAG_INPUT_BASE_DIR The base directory to read input files from. str optional None"}, {"location": "config/env_vars/#data-mapping-settings", "title": "Data Mapping Settings", "text": "Parameter Description Type Required or Optional Default GRAPHRAG_INPUT_FILE_TYPE The type of input data, csv or text str optional text GRAPHRAG_INPUT_ENCODING The encoding to apply when reading CSV/text input files. str optional utf-8"}, {"location": "config/env_vars/#data-chunking", "title": "Data Chunking", "text": "Parameter Description Type Required or Optional Default GRAPHRAG_CHUNK_SIZE The chunk size in tokens for text-chunk analysis windows. str optional 1200 GRAPHRAG_CHUNK_OVERLAP The chunk overlap in tokens for text-chunk analysis windows. str optional 100 GRAPHRAG_CHUNK_BY_COLUMNS A comma-separated list of document attributes to groupby when performing TextUnit chunking. str optional id 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 Default GRAPHRAG_ENTITY_EXTRACTION_PROMPT_FILE The path (relative to the root) of an entity extraction prompt template text file. str optional None GRAPHRAG_ENTITY_EXTRACTION_MAX_GLEANINGS The maximum number of redrives (gleanings) to invoke when extracting entities in a loop. int optional 1 GRAPHRAG_ENTITY_EXTRACTION_ENTITY_TYPES A comma-separated list of entity types to extract. str optional organization,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 optional None GRAPHRAG_SUMMARIZE_DESCRIPTIONS_MAX_LENGTH The maximum number of tokens to generate per description summarization. int optional 500 GRAPHRAG_CLAIM_EXTRACTION_ENABLED Whether claim extraction is enabled for this pipeline. bool optional False 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 optional None GRAPHRAG_CLAIM_EXTRACTION_MAX_GLEANINGS The maximum number of redrives (gleanings) to invoke when extracting claims in a loop. int optional 1 GRAPHRAG_CLAIM_EXTRACTION_ENCODING_MODEL The encoding model to use for claim extraction. str optional The top-level encoding model GRAPHRAG_COMMUNITY_REPORTS_PROMPT_FILE The community reports extraction prompt to utilize. string optional None 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 are file, memory, or blob str optional file GRAPHRAG_STORAGE_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_STORAGE_CONNECTION_STRING The Azure Storage connection string to use when in blob mode. str optional None GRAPHRAG_STORAGE_CONTAINER_NAME The Azure Storage container name to use when in blob mode. str optional None GRAPHRAG_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 are file, memory, none or blob str optional file GRAPHRAG_CACHE_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_CACHE_CONNECTION_STRING The Azure Storage connection string to use when in blob mode. str optional None GRAPHRAG_CACHE_CONTAINER_NAME The Azure Storage container name to use when in blob mode. str optional None GRAPHRAG_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 are file, console, or blob str optional file GRAPHRAG_REPORTING_STORAGE_ACCOUNT_BLOB_URL The Azure Storage blob endpoint to use when in blob mode and using managed identity. Will have the format https://<storage_account_name>.blob.core.windows.net str optional None GRAPHRAG_REPORTING_CONNECTION_STRING The Azure Storage connection string to use when in blob mode. str optional None GRAPHRAG_REPORTING_CONTAINER_NAME The Azure Storage container name to use when in blob mode. str optional None GRAPHRAG_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 Default GRAPHRAG_NODE2VEC_ENABLED Whether to enable Node2Vec bool optional False GRAPHRAG_NODE2VEC_NUM_WALKS The Node2Vec number of walks to perform int optional 10 GRAPHRAG_NODE2VEC_WALK_LENGTH The Node2Vec walk length int optional 40 GRAPHRAG_NODE2VEC_WINDOW_SIZE The Node2Vec window size int optional 2 GRAPHRAG_NODE2VEC_ITERATIONS The number of iterations to run node2vec int optional 3 GRAPHRAG_NODE2VEC_RANDOM_SEED The random seed to use for node2vec int optional 597832"}, {"location": "config/env_vars/#data-snapshotting", "title": "Data Snapshotting", "text": "Parameter Description Type Required or Optional Default GRAPHRAG_SNAPSHOT_EMBEDDINGS Whether to enable embeddings snapshots. bool optional False GRAPHRAG_SNAPSHOT_GRAPHML Whether to enable GraphML snapshots. bool optional False GRAPHRAG_SNAPSHOT_RAW_ENTITIES Whether to enable raw entity snapshots. bool optional False GRAPHRAG_SNAPSHOT_TOP_LEVEL_NODES Whether to enable top-level node snapshots. bool optional False GRAPHRAG_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 Default GRAPHRAG_ASYNC_MODE Which async mode to use. Either asyncio or threaded. str optional asyncio GRAPHRAG_ENCODING_MODEL The text encoding model, used in tiktoken, to encode text. str optional cl100k_base GRAPHRAG_MAX_CLUSTER_SIZE The maximum number of entities to include in a single Leiden cluster. int optional 10 GRAPHRAG_UMAP_ENABLED Whether to enable UMAP layouts bool optional False"}, {"location": "config/init/", "title": "Configuring GraphRAG Indexing", "text": "To start using GraphRAG, you must generate a configuration file. The init command is the easiest way to get started. It will create a .env and settings.yaml files in the specified directory with the necessary configuration settings. It will also output the default LLM prompts used by GraphRAG.
graphrag init [--root PATH] [--force, --no-force]\n"}, {"location": "config/init/#options", "title": "Options", "text": "--root PATH - The project root directory to initialize graphrag at. Default is the current directory.--force, --no-force - Optional, default is --no-force. Overwrite existing configuration and prompt files if they exist.graphrag init --root ./ragtest\n"}, {"location": "config/init/#output", "title": "Output", "text": "The init command will create the following files in the specified directory:
settings.yaml - The configuration settings file. This file contains the configuration settings for GraphRAG..env - The environment variables file. These are referenced in the settings.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:
The default configuration mode may be configured by using a settings.yml or settings.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 in graphrag 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:
# .env\nGRAPHRAG_API_KEY=some_api_key\n\n# settings.yml\nllm: \n api_key: ${GRAPHRAG_API_KEY}\n"}, {"location": "config/yaml/#config-sections", "title": "Config Sections", "text": ""}, {"location": "config/yaml/#language-model-setup", "title": "Language Model Setup", "text": ""}, {"location": "config/yaml/#models", "title": "models", "text": "This is a dict of model configurations. The dict key is used to reference this configuration elsewhere when a model instance is desired. In this way, you can specify as many different models as you need, and reference them differentially in the workflow steps.
For example:
models:\n default_chat_model:\n api_key: ${GRAPHRAG_API_KEY}\n type: openai_chat\n model: gpt-4o\n model_supports_json: true\n default_embedding_model:\n api_key: ${GRAPHRAG_API_KEY}\n type: openai_embedding\n model: text-embedding-ada-002\n"}, {"location": "config/yaml/#fields", "title": "Fields", "text": "api_key str - The OpenAI API key to use.auth_type api_key|managed_identity - Indicate how you want to authenticate requests.type openai_chat|azure_openai_chat|openai_embedding|azure_openai_embedding|mock_chat|mock_embeddings - The type of LLM to use.model str - The model name.encoding_model str - The text encoding model to use. Default is to use the encoding model aligned with the language model (i.e., it is retrieved from tiktoken if unset).api_base str - The API base url to use.api_version str - The API version.deployment_name str - The deployment name to use (Azure).organization 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 if api_key is not defined. Default=https://cognitiveservices.azure.com/.defaultmodel_supports_json bool - Whether the model supports JSON-mode output.request_timeout float - The per-request timeout.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.retry_strategy str - Retry strategy to use, \"native\" is the default and uses the strategy built into the OpenAI SDK. Other allowable values include \"exponential_backoff\", \"random_wait\", and \"incremental_wait\".max_retries int - The maximum number of retries to use.max_retry_wait float - The maximum backoff time.concurrent_requests int The number of open requests to allow at once.async_mode asyncio|threaded The async mode to use. Either asyncio or threaded.responses list[str] - If this model type is mock, this is a list of response strings to return.max_tokens int - The maximum number of output tokens.temperature float - The temperature to use.top_p float - The top-p value to use.n int - The number of completions to generate.frequency_penalty float - Frequency penalty for token generation.presence_penalty float - Frequency penalty for token generation.Our pipeline can ingest .csv, .txt, or .json data from an input folder. See the inputs page for more details and examples.
"}, {"location": "config/yaml/#fields_1", "title": "Fields", "text": "type file|blob - The input type to use. Default=filefile_type text|csv|json - The type of input data to load. Default is textbase_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.encoding str - The encoding of the input file. Default is utf-8file_pattern str - A regex to match input files. Default is .*\\.csv$, .*\\.txt$, or .*\\.json$ depending on the specified file_type, but you can customize it if needed.file_filter dict - Key/value pairs to filter. Default is None.text_column str - (CSV/JSON only) The text column name. If unset we expect a column named text.title_column str - (CSV/JSON only) The title column name, filename will be used if unset.metadata list[str] - (CSV/JSON only) The additional document attributes fields to keep.These settings configure how we parse documents into text chunks. This is necessary because very large documents may not fit into a single context window, and graph extraction accuracy can be modulated. Also note the metadata setting in the input document config, which will replicate document metadata into each chunk.
size int - The max chunk size in tokens.overlap int - The chunk overlap in tokens.group_by_columns list[str] - Group documents by these fields before chunking.strategy str[tokens|sentences] - How to chunk the text. encoding_model str - The text encoding model to use for splitting on token boundaries.prepend_metadata bool - Determines if metadata values should be added at the beginning of each chunk. Default=False.chunk_size_includes_metadata bool - Specifies whether the chunk size calculation should include metadata tokens. Default=False.This section controls the storage mechanism used by the pipeline used for exporting output tables.
"}, {"location": "config/yaml/#fields_3", "title": "Fields", "text": "type file|memory|blob|cosmosdb - The storage type to use. Default=filebase_dir str - The base directory to write output artifacts to, relative to the root.connection_string str - (blob/cosmosdb only) The Azure Storage connection string.container_name str - (blob/cosmosdb only) The Azure Storage container name.storage_account_blob_url str - (blob only) The storage account blob URL to use.cosmosdb_account_blob_url str - (cosmosdb only) The CosmosDB account blob URL to use.The section defines a secondary storage location for running incremental indexing, to preserve your original outputs.
"}, {"location": "config/yaml/#fields_4", "title": "Fields", "text": "type file|memory|blob|cosmosdb - The storage type to use. Default=filebase_dir str - The base directory to write output artifacts to, relative to the root.connection_string str - (blob/cosmosdb only) The Azure Storage connection string.container_name str - (blob/cosmosdb only) The Azure Storage container name.storage_account_blob_url str - (blob only) The storage account blob URL to use.cosmosdb_account_blob_url str - (cosmosdb only) The CosmosDB account blob URL to use.This section controls the cache mechanism used by the pipeline. This is used to cache LLM invocation results for faster performance when re-running the indexing process.
"}, {"location": "config/yaml/#fields_5", "title": "Fields", "text": "type file|memory|blob|cosmosdb - The storage type to use. Default=filebase_dir str - The base directory to write output artifacts to, relative to the root.connection_string str - (blob/cosmosdb only) The Azure Storage connection string.container_name str - (blob/cosmosdb only) The Azure Storage container name.storage_account_blob_url str - (blob only) The storage account blob URL to use.cosmosdb_account_blob_url str - (cosmosdb only) The CosmosDB account blob URL to use.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.
"}, {"location": "config/yaml/#fields_6", "title": "Fields", "text": "type file|console|blob - The reporting type to use. Default=filebase_dir str - The base directory to write reports to, relative to the root.connection_string str - (blob only) The Azure Storage connection string.container_name str - (blob only) The Azure Storage container name.storage_account_blob_url str - The storage account blob URL to use.Where to put all vectors for the system. Configured for lancedb by default. This is a dict, with the key used to identify individual store parameters (e.g., for text embedding).
"}, {"location": "config/yaml/#fields_7", "title": "Fields", "text": "type lancedb|azure_ai_search|cosmosdb - Type of vector store. Default=lancedbdb_uri str (only for lancedb) - The database uri. Default=storage.base_dir/lancedburl 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.container_name str - The name of a vector container. This stores all indexes (tables) for a given dataset ingest. Default=defaultdatabase_name str - (cosmosdb only) Name of the database.overwrite bool (only used at index creation time) - Overwrite collection if it exist. Default=TrueThese settings control each individual workflow as they execute.
"}, {"location": "config/yaml/#workflows", "title": "workflows", "text": "list[str] - This is a list of workflow names to run, in order. GraphRAG has built-in pipelines to configure this, but you can run exactly and only what you want by specifying the list here. Useful if you have done part of the processing yourself.
"}, {"location": "config/yaml/#embed_text", "title": "embed_text", "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 customized by setting the target and names fields.
Supported embeddings names are:
text_unit.textdocument.textentity.titleentity.descriptionrelationship.descriptioncommunity.titlecommunity.summarycommunity.full_contentmodel_id str - Name of the model definition to use for text embedding.vector_store_id str - Name of vector store definition to write to.batch_size int - The maximum batch size to use.batch_max_tokens int - The maximum batch # of tokens.target required|all|selected|none - Determines which set of embeddings to export.names list[str] - If target=selected, this should be an explicit list of the embeddings names we support.Tune the language model-based graph extraction process.
"}, {"location": "config/yaml/#fields_9", "title": "Fields", "text": "model_id str - Name of the model definition to use for API calls.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. Default is to use the encoding model aligned with the language model (i.e., it is retrieved from tiktoken if unset). This is only used for gleanings during the logit_bias check.model_id str - Name of the model definition to use for API calls.prompt str - The prompt file to use.max_length int - The maximum number of output tokens per summarization.Defines settings for NLP-based graph extraction methods.
"}, {"location": "config/yaml/#fields_11", "title": "Fields", "text": "normalize_edge_weights bool - Whether to normalize the edge weights during graph construction. Default=True.text_analyzer dict - Parameters for the NLP model.regex_english.15.True.None, we use an internal stopword list.Parameters for manual graph pruning. This can be used to optimize the modularity of your graph clusters, by removing overly-connected or rare nodes.
"}, {"location": "config/yaml/#fields_12", "title": "Fields", "text": "These are the settings used for Leiden hierarchical clustering of the graph to create communities.
"}, {"location": "config/yaml/#fields_13", "title": "Fields", "text": "max_cluster_size int - The maximum cluster size to export.use_lcc bool - Whether to only use the largest connected component.seed int - A randomization seed to provide if consistent run-to-run results are desired. We do provide a default in order to guarantee clustering stability.enabled bool - Whether to enable claim extraction. Off by default, because claim prompts really need user tuning.model_id str - Name of the model definition to use for API calls.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. Default is to use the encoding model aligned with the language model (i.e., it is retrieved from tiktoken if unset). This is only used for gleanings during the logit_bias check.model_id str - Name of the model definition to use for API calls.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.We use node2vec to embed the graph. This is primarily used for visualization, so it is not turned on by default.
"}, {"location": "config/yaml/#fields_16", "title": "Fields", "text": "enabled bool - Whether to enable graph embeddings.dimensions int - Number of vector dimensions to produce.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.Indicates whether we should run UMAP dimensionality reduction. This is used to provide an x/y coordinate to each graph node, suitable for visualization. If this is not enabled, nodes will receive a 0/0 x/y coordinate. If this is enabled, you must enable graph embedding as well.
"}, {"location": "config/yaml/#fields_17", "title": "Fields", "text": "enabled bool - Whether to enable UMAP layouts.embeddings bool - Export embeddings snapshots to parquet.graphml bool - Export graph snapshots to GraphML.chat_model_id str - Name of the model definition to use for Chat Completion calls.embedding_model_id str - Name of the model definition to use for Embedding calls.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.chat_model_id str - Name of the model definition to use for Chat Completion calls.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.chat_model_id str - Name of the model definition to use for Chat Completion calls.embedding_model_id str - Name of the model definition to use for Embedding calls.prompt str - The prompt file to use.reduce_prompt str - The reducer 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.chat_model_id str - Name of the model definition to use for Chat Completion calls.embedding_model_id str - Name of the model definition to use for Embedding calls.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.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.
---\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"}, {"location": "index/architecture/#llm-caching", "title": "LLM Caching", "text": "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.
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 set CHUNK_BY_COLUMNS to id 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.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.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.
---\ntitle: Dataflow Overview\n---\nflowchart TB\n subgraph phase1[Phase 1: Compose TextUnits]\n documents[Documents] --> chunk[Chunk]\n chunk --> 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 --> community_outputs[Communities Table]\n end\n subgraph phase4[Phase 4: Community Summarization]\n community_outputs --> summarized_communities[Community Summarization]\n summarized_communities --> community_report_outputs[Community Reports Table]\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 --> document_outputs[Documents Table]\n end\n subgraph phase6[Phase 6: Network Visualization]\n graph_outputs --> graph_embed[Graph Embedding]\n graph_embed --> umap_entities[Umap Entities]\n umap_entities --> combine_nodes[Final Entities]\n end\n subgraph phase7[Phase 7: Text Embeddings]\n textUnits --> text_embed[Text Embedding]\n graph_outputs --> description_embed[Description Embedding]\n community_report_outputs --> content_embed[Content Embedding]\n end"}, {"location": "index/default_dataflow/#phase-1-compose-textunits", "title": "Phase 1: Compose TextUnits", "text": "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 text.
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)
---\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"}, {"location": "index/default_dataflow/#phase-2-graph-extraction", "title": "Phase 2: Graph Extraction", "text": "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.
---\ntitle: Graph Extraction\n---\nflowchart LR\n tu[TextUnit] --> ge[Graph Extraction] --> gs[Graph Summarization]\n tu --> ce[Claim Extraction]"}, {"location": "index/default_dataflow/#entity-relationship-extraction", "title": "Entity & Relationship Extraction", "text": "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 title, type, and description, and a list of relationships with a source, target, and description.
These subgraphs are merged together - any entities with the same title 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-optional", "title": "Claim Extraction (optional)", "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. These give us explicit ways of understanding the topological structure of our graph.
---\ntitle: Graph Augmentation\n---\nflowchart LR\n cd[Leiden Hierarchical Community Detection] --> ag[Graph Tables]"}, {"location": "index/default_dataflow/#community-detection", "title": "Community Detection", "text": "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-tables", "title": "Graph Tables", "text": "Once our graph augmentation steps are complete, the final Entities, Relationships, and Communities tables are exported.
"}, {"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] --> co[Community Reports Table] At this point, we have a functional graph of entities and relationships and a hierarchy of communities for the entities.
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-reports-table", "title": "Community Reports Table", "text": "At this point, some bookkeeping work is performed and we export the Community Reports 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.
---\ntitle: Document Processing\n---\nflowchart LR\n aug[Augment] --> dp[Link to TextUnits] --> dg[Documents Table]"}, {"location": "index/default_dataflow/#augment-with-columns-csv-only", "title": "Augment with Columns (CSV Only)", "text": "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/#documents-table", "title": "Documents Table", "text": "At this point, we can export the Documents table into the knowledge Model.
"}, {"location": "index/default_dataflow/#phase-6-network-visualization-optional", "title": "Phase 6: Network Visualization (optional)", "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 ag[Graph Table] --> ge[Node2Vec Graph Embedding] --> ne[Umap Entities] --> ng[Entities Table]"}, {"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/#dimensionality-reduction", "title": "Dimensionality Reduction", "text": "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 reduced to two dimensions as x/y coordinates.
"}, {"location": "index/default_dataflow/#phase-7-text-embedding", "title": "Phase 7: Text Embedding", "text": "For all artifacts that require downstream vector search, we generate text embeddings as a final step. These embeddings are written directly to a configured vector store. By default we embed entity descriptions, text unit text, and community report text.
---\ntitle: Text Embedding Workflows\n---\nflowchart LR\n textUnits[Text Units] --> text_embed[Text Embedding]\n graph_outputs[Graph Tables] --> description_embed[Description Embedding]\n community_report_outputs[Community Reports] --> content_embed[Content Embedding]"}, {"location": "index/inputs/", "title": "Inputs", "text": "GraphRAG supports several input formats to simplify ingesting your data. The mechanics and features available for input files and text chunking are discussed here.
"}, {"location": "index/inputs/#input-loading-and-schema", "title": "Input Loading and Schema", "text": "All input formats are loaded within GraphRAG and passed to the indexing pipeline as a documents DataFrame. This DataFrame has a row for each document using a shared column schema:
Also see the outputs documentation for the final documents table schema saved to parquet after pipeline completion.
"}, {"location": "index/inputs/#formats", "title": "Formats", "text": "We support three file formats out-of-the-box. This covers the overwhelming majority of use cases we have encountered. If you have a different format, we recommend writing a script to convert to one of these, which are widely used and supported by many tools and libraries.
"}, {"location": "index/inputs/#plain-text", "title": "Plain Text", "text": "Plain text files (typically ending in .txt file extension). With plain text files we import the entire file contents as the text field, and the title is always the filename.
CSV files (typically ending in a .csv extension). These are loaded using pandas' read_csv method with default options. Each row in a CSV file is treated as a single document. If you have multiple CSV files in your input folder, they will be concatenated into a single resulting documents DataFrame.
With the CSV format you can configure the text_column, and title_column if your data has structured content you would prefer to use. If you do not configure these within the input block of your settings.yaml, the title will be the filename as described in the schema above. The text_column is assumed to be \"text\" in your file if not configured specifically. We will also look for and use an \"id\" column if present, otherwise the ID will be generated as described above.
JSON files (typically ending in a .json extension) contain structured objects. These are loaded using python's json.loads method, so your files must be properly compliant. JSON files may contain a single object in the file or the file may contain an array of objects at the root. We will check for and handle either of these cases. As with CSV, multiple files will be concatenated into a final table, and the text_column and title_column config options will be applied to the properties of each loaded object. Note that the specialized jsonl format produced by some libraries (one full JSON object on each line, not in an array) is not currently supported.
With the structured file formats (CSV and JSON) you can configure any number of columns to be added to a persisted metadata field in the DataFrame. This is configured by supplying a list of columns name to collect. If this is configured, the output metadata column will have a dict containing a key for each column, and the value of the column for that document. This metadata can optionally be used later in the GraphRAG pipeline.
software.csv
text,title,tag\nMy first program,Hello World,tutorial\nAn early space shooter game,Space Invaders,arcade\n settings.yaml
input:\n metadata: [title,tag]\n Documents DataFrame
id title text creation_date metadata (generated from text) Hello World My first program (create date of software.csv) { \"title\": \"Hello World\", \"tag\": \"tutorial\" } (generated from text) Space Invaders An early space shooter game (create date of software.csv) { \"title\": \"Space Invaders\", \"tag\": \"arcade\" }"}, {"location": "index/inputs/#chunking-and-metadata", "title": "Chunking and Metadata", "text": "As described on the default dataflow page, documents are chunked into smaller \"text units\" for processing. This is done because document content size often exceeds the available context window for a given language model. There are a handful of settings you can adjust for this chunking, the most relevant being the chunk_size and overlap. We now also support a metadata processing scheme that can improve indexing results for some use cases. We will describe this feature in detail here.
Imagine the following scenario: you are indexing a collection of news articles. Each article text starts with a headline and author, and then proceeds with the content. When documents are chunked, they are split evenly according to your configured chunk size. In other words, the first n tokens are read into a text unit, and then the next n, until the end of the content. This means that front matter at the beginning of the document (such as the headline and author in this example) is not copied to each chunk. It only exists in the first chunk. When we later retrieve those chunks for summarization, they may therefore be missing shared information about the source document that should always be provided to the model. We have configuration options to copy repeated content into each text unit to address this issue.
"}, {"location": "index/inputs/#input-config", "title": "Input Config", "text": "As described above, when documents are imported you can specify a list of metadata columns to include with each row. This must be configured for the per-chunk copying to work.
Next, the chunks block needs to instruct the chunker how to handle this metadata when creating text units. By default, it is ignored. We have two settings to include it:
prepend_metadata. This instructs the importer to copy the contents of the metadata column for each row into the start of every single text chunk. This metadata is copied as key: value pairs on new lines.chunk_size_includes_metadata: This tells the chunker how to compute the chunk size when metadata is included. By default, we create the text units using your specified chunk_size and then prepend the metadata. This means that the final text unit lengths may be longer than your configured chunk_size, and it will vary based on the length of the metadata for each document. When this setting is True, we will compute the raw text using the remainder after measuring the metadata length so that the resulting text units always comply with your configured chunk_size.The following are several examples to help illustrate how chunking config and metadate prepending works for each file format. Note that we are using word count here as \"tokens\" for the illustration, but language model tokens are not equivalent to words.
"}, {"location": "index/inputs/#text-files", "title": "Text files", "text": "This example uses two individual news article text files.
--
File: US to lift most federal COVID-19 vaccine mandates.txt
Content:
WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday.
--
File: NY lawmakers begin debating budget 1 month after due date.txt
Content:
ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate.
--
settings.yaml
input:\n file_type: text\n metadata: [title]\n\nchunks:\n size: 100\n overlap: 0\n prepend_metadata: true\n chunk_size_includes_metadata: false\n Documents DataFrame
id title text creation_date metadata (generated from text) US to lift most federal COVID-19 vaccine mandates.txt (full content of text file) (create date of article txt file) { \"title\": \"US to lift most federal COVID-19 vaccine mandates.txt\" } (generated from text) NY lawmakers begin debating budget 1 month after due date.txt (full content of text file) (create date of article txt file) { \"title\": \"NY lawmakers begin debating budget 1 month after due date.txt\" }Raw Text Chunks
content length title: US to lift most federal COVID-19 vaccine mandates.txtWASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as 109 title: US to lift most federal COVID-19 vaccine mandates.txtthe deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday. 82 title: NY lawmakers begin debating budget 1 month after due date.txtALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to 111 title: NY lawmakers begin debating budget 1 month after due date.txtbe wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it 111 title: NY lawmakers begin debating budget 1 month after due date.txtwould undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate. 89In this example we can see that the two input documents were parsed into five output text chunks. The title (filename) of each document is prepended but not included in the computed chunk size. Also note that the final text chunk for each document is usually smaller than the chunk size because it contains the last tokens.
"}, {"location": "index/inputs/#csv-files", "title": "CSV files", "text": "This example uses a single CSV file with the same two articles as rows (note that the text content is not properly escaped for actual CSV use).
--
File: articles.csv
Content
headline,article
US to lift most federal COVID-19 vaccine mandates,WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday.
NY lawmakers begin debating budget 1 month after due date,ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate.
--
settings.yaml
input:\n file_type: csv\n title_column: headline\n text_column: article\n metadata: [headline]\n\nchunks:\n size: 50\n overlap: 5\n prepend_metadata: true\n chunk_size_includes_metadata: true\n Documents DataFrame
id title text creation_date metadata (generated from text) US to lift most federal COVID-19 vaccine mandates (article column content) (create date of articles.csv) { \"headline\": \"US to lift most federal COVID-19 vaccine mandates\" } (generated from text) NY lawmakers begin debating budget 1 month after due date (article column content) (create date of articles.csv) { \"headline\": \"NY lawmakers begin debating budget 1 month after due date\" }Raw Text Chunks
content length title: US to lift most federal COVID-19 vaccine mandatesWASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, 50 title: US to lift most federal COVID-19 vaccine mandatesfederal workers and federal contractors as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. 50 title: US to lift most federal COVID-19 vaccine mandatesnoncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how 50 title: US to lift most federal COVID-19 vaccine mandatesthe latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that 50 title: US to lift most federal COVID-19 vaccine mandatespoint where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday. 38 title: NY lawmakers begin debating budget 1 month after due dateALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new 50 title: NY lawmakers begin debating budget 1 month after due datestoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and 50 title: NY lawmakers begin debating budget 1 month after due dateto the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget 50 title: NY lawmakers begin debating budget 1 month after due dateup Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been 50 title: NY lawmakers begin debating budget 1 month after due datevoting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges 50 title: NY lawmakers begin debating budget 1 month after due datethe standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 50 title: NY lawmakers begin debating budget 1 month after due datebail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum 50 title: NY lawmakers begin debating budget 1 month after due dateto state officials. The minimum wage would be raised to $17 in be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 50 title: NY lawmakers begin debating budget 1 month after due date2026. That's up from $15 in the city and $14.20 upstate. 22In this example we can see that the two input documents were parsed into fourteen output text chunks. The title (headline) of each document is prepended and included in the computed chunk size, so each chunk matches the configured chunk size (except the last one for each document). We've also configured some overlap in these text chunks, so the last five tokens are shared. Why would you use overlap in your text chunks? Consider that when you are splitting documents based on tokens, it is highly likely that sentences or even related concepts will be split into separate chunks. Each text chunk is processed separately by the language model, so this may result in incomplete \"ideas\" at the boundaries of the chunk. Overlap ensures that these split concepts are fully contained in at least one of the chunks.
"}, {"location": "index/inputs/#json-files", "title": "JSON files", "text": "This final example uses a JSON file for each of the same two articles. In this example we'll set the object fields to read, but we will not add metadata to the text chunks.
--
File: article1.json
Content
{\n \"headline\": \"US to lift most federal COVID-19 vaccine mandates\",\n \"content\": \"WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday.\"\n}\n File: article2.json
Content
{\n \"headline\": \"NY lawmakers begin debating budget 1 month after due date\",\n \"content\": \"ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate.\"\n}\n --
settings.yaml
input:\n file_type: json\n title_column: headline\n text_column: content\n\nchunks:\n size: 100\n overlap: 10\n Documents DataFrame
id title text creation_date metadata (generated from text) US to lift most federal COVID-19 vaccine mandates (article column content) (create date of article1.json) { } (generated from text) NY lawmakers begin debating budget 1 month after due date (article column content) (create date of article2.json) { }Raw Text Chunks
content length WASHINGTON (AP) The Biden administration will end most of the last remaining federal COVID-19 vaccine requirements next week when the national public health emergency for the coronavirus ends, the White House said Monday. Vaccine requirements for federal workers and federal contractors, as well as foreign air travelers to the U.S., will end May 11. The government is also beginning the process of lifting shot requirements for Head Start educators, healthcare workers, and noncitizens at U.S. land borders. The requirements are among the last vestiges of some of the more coercive measures taken by the federal government to promote vaccination as 100 measures taken by the federal government to promote vaccination as the deadly virus raged, and their end marks the latest display of how President Joe Biden's administration is moving to treat COVID-19 as a routine, endemic illness. \"While I believe that these vaccine mandates had a tremendous beneficial impact, we are now at a point where we think that it makes a lot of sense to pull these requirements down,\" White House COVID-19 coordinator Dr. Ashish Jha told The Associated Press on Monday. 83 ALBANY, N.Y. (AP) New York lawmakers began voting Monday on a $229 billion state budget due a month ago that would raise the minimum wage, crack down on illicit pot shops and ban gas stoves and furnaces in new buildings. Negotiations among Gov. Kathy Hochul and her fellow Democrats in control of the Legislature dragged on past the April 1 budget deadline, largely because of disagreements over changes to the bail law and other policy proposals included in the spending plan. Floor debates on some budget bills began Monday. State Senate Majority Leader Andrea Stewart-Cousins said she expected voting to 100 Senate Majority Leader Andrea Stewart-Cousins said she expected voting to be wrapped up Tuesday for a budget she said contains \"significant wins\" for New Yorkers. \"I would have liked to have done this sooner. I think we would all agree to that,\" Cousins told reporters before voting began. \"This has been a very policy-laden budget and a lot of the policies had to parsed through.\" Hochul was able to push through a change to the bail law that will eliminate the standard that requires judges to prescribe the \"least restrictive\" means to ensure defendants return to court. Hochul said judges 100 means to ensure defendants return to court. Hochul said judges needed the extra discretion. Some liberal lawmakers argued that it would undercut the sweeping bail reforms approved in 2019 and result in more people with low incomes and people of color in pretrial detention. Here are some other policy provisions that will be included in the budget, according to state officials. The minimum wage would be raised to $17 in New York City and some of its suburbs and $16 in the rest of the state by 2026. That's up from $15 in the city and $14.20 upstate. 98In this example the two input documents were parsed into five output text chunks. There is no metadata prepended, so each chunk matches the configured chunk size (except the last one for each document). We've also configured some overlap in these text chunks, so the last ten tokens are shared.
"}, {"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/#communities", "title": "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. children int[] List of child community IDs. 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/#community_reports", "title": "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. children int[] List of child community IDs. 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 rating_explanation str LM-derived explanation of the rank. findings dict LM-derived list of the top 5-10 insights from the community. Containssummary and explanation 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/#covariates", "title": "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/#documents", "title": "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. metadata dict If specified during CSV import, this is a dict of metadata for the document."}, {"location": "index/outputs/#entities", "title": "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. frequency int Count of text units the entity was found within. 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/#relationships", "title": "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/#text_units", "title": "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:
The outputs of the pipeline are stored as Parquet tables by default, and embeddings are written to your configured vector store.
"}, {"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.
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": "# Via Poetry\npoetry run poe index --root <data_root> # default config mode\n"}, {"location": "index/overview/#python-api", "title": "Python API", "text": "Please see the indexing API python file for the recommended method to call directly from Python code.
"}, {"location": "index/overview/#further-reading", "title": "Further Reading", "text": "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 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:
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/#command-line-options", "title": "Command-Line Options", "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.
--selection-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--selection-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):
python -m graphrag prompt-tune --root /path/to/project --config /path/to/settings.yaml --no-entity-types\n"}, {"location": "prompt_tuning/auto_prompt_tuning/#document-selection-methods", "title": "Document Selection Methods", "text": "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:
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:
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"}, {"location": "prompt_tuning/manual_prompt_tuning/", "title": "Manual Prompt Tuning \u2699\ufe0f", "text": "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 {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": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_1", "title": "Tokens", "text": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_2", "title": "Tokens", "text": "\"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": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_4", "title": "Tokens", "text": "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": "Prompt Source
"}, {"location": "prompt_tuning/manual_prompt_tuning/#tokens_6", "title": "Tokens", "text": "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:
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 the reduce 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:
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 the map stage. Default template can be found at map_system_promptreduce_system_prompt: prompt template used in the reduce 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 the reduce_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 the reduce_system_prompt if allow_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 the map stagereduce_llm_params: a dictionary of additional parameters (e.g., temperature, max_tokens) to passed to the LLM call at the reduce stagecontext_builder_params: a dictionary of additional parameters to be passed to the context_builder object when building context window for the map stage.concurrent_coroutines: controls the degree of parallelism in the map 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:
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 the context_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:
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:
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 the context_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": "For examples about running Query please refer to the following notebooks:
The test dataset for these notebooks can be found in dataset.zip.
"}]} \ No newline at end of file