Api overview
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License.
API Overview¶
This notebook provides a demonstration of how to interact with graphrag as a library using the API as opposed to the CLI. Note that graphrag's CLI actually connects to the library through this API for all operations.
from pathlib import Path
from pprint import pprint
import graphrag.api as api
import pandas as pd
from graphrag.config.load_config import load_config
from graphrag.index.typing.pipeline_run_result import PipelineRunResult
PROJECT_DIRECTORY = "<your project directory>"
Prerequisite¶
As a prerequisite to all API operations, a GraphRagConfig object is required. It is the primary means to control the behavior of graphrag and can be instantiated from a settings.yaml configuration file.
Please refer to the CLI docs for more detailed information on how to generate the settings.yaml file.
Generate a GraphRagConfig object¶
# note that we expect this to fail on the deployed docs because the PROJECT_DIRECTORY is not set to a real location.
# if you run this notebook locally, make sure to point at a location containing your settings.yaml
graphrag_config = load_config(Path(PROJECT_DIRECTORY))
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[4], line 3 1 # note that we expect this to fail on the deployed docs because the PROJECT_DIRECTORY is not set to a real location. 2 # if you run this notebook locally, make sure to point at a location containing your settings.yaml ----> 3 graphrag_config = load_config(Path(PROJECT_DIRECTORY)) File ~/work/graphrag/graphrag/packages/graphrag/graphrag/config/load_config.py:43, in load_config(root_dir, cli_overrides) 14 def load_config( 15 root_dir: str | Path, 16 cli_overrides: dict[str, Any] | None = None, 17 ) -> GraphRagConfig: 18 """Load configuration from a file. 19 20 Parameters (...) 41 If there are pydantic validation errors when instantiating the config. 42 """ ---> 43 return lc( 44 config_initializer=GraphRagConfig, 45 config_path=root_dir, 46 overrides=cli_overrides, 47 ) File ~/work/graphrag/graphrag/packages/graphrag-common/graphrag_common/config/load_config.py:172, in load_config(config_initializer, config_path, overrides, set_cwd, parse_env_vars, load_dot_env_file, dot_env_path, config_parser, file_encoding) 117 """Load configuration from a file. 118 119 Parameters (...) 169 - If the parser fails to parse the configuration text. 170 """ 171 config_path = Path(config_path).resolve() if config_path else Path.cwd() --> 172 config_path = _get_config_file_path(config_path) 174 file_contents = config_path.read_text(encoding=file_encoding) 176 if parse_env_vars: File ~/work/graphrag/graphrag/packages/graphrag-common/graphrag_common/config/load_config.py:38, in _get_config_file_path(config_dir_or_file) 36 if not config_dir_or_file.is_dir(): 37 msg = f"Invalid config path: {config_dir_or_file} is not a directory" ---> 38 raise FileNotFoundError(msg) 40 for file in _default_config_files: 41 if (config_dir_or_file / file).is_file(): FileNotFoundError: Invalid config path: /home/runner/work/graphrag/graphrag/docs/examples_notebooks/<your project directory> is not a directory
Indexing API¶
Indexing is the process of ingesting raw text data and constructing a knowledge graph. GraphRAG currently supports plaintext (.txt) and .csv file formats.
Build an index¶
index_result: list[PipelineRunResult] = await api.build_index(config=graphrag_config)
# index_result is a list of workflows that make up the indexing pipeline that was run
for workflow_result in index_result:
status = f"error\n{workflow_result.errors}" if workflow_result.errors else "success"
print(f"Workflow Name: {workflow_result.workflow}\tStatus: {status}")
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[5], line 1 ----> 1 index_result: list[PipelineRunResult] = await api.build_index(config=graphrag_config) 2 3 # index_result is a list of workflows that make up the indexing pipeline that was run 4 for workflow_result in index_result: NameError: name 'graphrag_config' is not defined
Query an index¶
To query an index, several index files must first be read into memory and passed to the query API.
entities = pd.read_parquet(f"{PROJECT_DIRECTORY}/output/entities.parquet")
communities = pd.read_parquet(f"{PROJECT_DIRECTORY}/output/communities.parquet")
community_reports = pd.read_parquet(
f"{PROJECT_DIRECTORY}/output/community_reports.parquet"
)
response, context = await api.global_search(
config=graphrag_config,
entities=entities,
communities=communities,
community_reports=community_reports,
community_level=2,
dynamic_community_selection=False,
response_type="Multiple Paragraphs",
query="Who is Scrooge and what are his main relationships?",
)
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[6], line 1 ----> 1 entities = pd.read_parquet(f"{PROJECT_DIRECTORY}/output/entities.parquet") 2 communities = pd.read_parquet(f"{PROJECT_DIRECTORY}/output/communities.parquet") 3 community_reports = pd.read_parquet( 4 f"{PROJECT_DIRECTORY}/output/community_reports.parquet" File ~/work/graphrag/graphrag/.venv/lib/python3.13/site-packages/pandas/io/parquet.py:760, in read_parquet(path, engine, columns, storage_options, dtype_backend, filesystem, filters, to_pandas_kwargs, **kwargs) 757 impl = get_engine(engine) 758 check_dtype_backend(dtype_backend) --> 760 return impl.read( 761 path, 762 columns=columns, 763 filters=filters, 764 storage_options=storage_options, 765 dtype_backend=dtype_backend, 766 filesystem=filesystem, 767 to_pandas_kwargs=to_pandas_kwargs, 768 **kwargs, 769 ) File ~/work/graphrag/graphrag/.venv/lib/python3.13/site-packages/pandas/io/parquet.py:296, in PyArrowImpl.read(self, path, columns, filters, dtype_backend, storage_options, filesystem, to_pandas_kwargs, **kwargs) 289 path_or_handle, handles, filesystem = _get_path_or_handle( 290 path, 291 filesystem, 292 storage_options=storage_options, 293 mode="rb", 294 ) 295 try: --> 296 pa_table = self.api.parquet.read_table( 297 path_or_handle, 298 columns=columns, 299 filesystem=filesystem, 300 filters=filters, 301 **kwargs, 302 ) 304 df_metadata = None 305 if pa_table.schema.metadata: File ~/work/graphrag/graphrag/.venv/lib/python3.13/site-packages/pyarrow/parquet/core.py:1915, in read_table(source, columns, use_threads, schema, use_pandas_metadata, read_dictionary, binary_type, list_type, memory_map, buffer_size, partitioning, filesystem, filters, ignore_prefixes, pre_buffer, coerce_int96_timestamp_unit, decryption_properties, thrift_string_size_limit, thrift_container_size_limit, schema_depth_limit, page_checksum_verification, arrow_extensions_enabled) 1903 def read_table(source, *, columns=None, use_threads=True, 1904 schema=None, use_pandas_metadata=False, read_dictionary=None, 1905 binary_type=None, list_type=None, memory_map=False, buffer_size=0, (...) 1911 page_checksum_verification=False, 1912 arrow_extensions_enabled=True): 1914 try: -> 1915 dataset = ParquetDataset( 1916 source, 1917 schema=schema, 1918 filesystem=filesystem, 1919 partitioning=partitioning, 1920 memory_map=memory_map, 1921 read_dictionary=read_dictionary, 1922 binary_type=binary_type, 1923 list_type=list_type, 1924 buffer_size=buffer_size, 1925 filters=filters, 1926 ignore_prefixes=ignore_prefixes, 1927 pre_buffer=pre_buffer, 1928 coerce_int96_timestamp_unit=coerce_int96_timestamp_unit, 1929 decryption_properties=decryption_properties, 1930 thrift_string_size_limit=thrift_string_size_limit, 1931 thrift_container_size_limit=thrift_container_size_limit, 1932 schema_depth_limit=schema_depth_limit, 1933 page_checksum_verification=page_checksum_verification, 1934 arrow_extensions_enabled=arrow_extensions_enabled, 1935 ) 1936 except ImportError: 1937 # fall back on ParquetFile for simple cases when pyarrow.dataset 1938 # module is not available 1939 if filters is not None: File ~/work/graphrag/graphrag/.venv/lib/python3.13/site-packages/pyarrow/parquet/core.py:1491, in ParquetDataset.__init__(self, path_or_paths, filesystem, schema, filters, read_dictionary, binary_type, list_type, memory_map, buffer_size, partitioning, ignore_prefixes, pre_buffer, coerce_int96_timestamp_unit, decryption_properties, thrift_string_size_limit, thrift_container_size_limit, schema_depth_limit, page_checksum_verification, arrow_extensions_enabled) 1487 if partitioning == "hive": 1488 partitioning = ds.HivePartitioning.discover( 1489 infer_dictionary=True) -> 1491 self._dataset = ds.dataset(path_or_paths, filesystem=filesystem, 1492 schema=schema, format=parquet_format, 1493 partitioning=partitioning, 1494 ignore_prefixes=ignore_prefixes) File ~/work/graphrag/graphrag/.venv/lib/python3.13/site-packages/pyarrow/dataset.py:790, in dataset(source, schema, format, filesystem, partitioning, partition_base_dir, exclude_invalid_files, ignore_prefixes) 779 kwargs = dict( 780 schema=schema, 781 filesystem=filesystem, (...) 786 selector_ignore_prefixes=ignore_prefixes 787 ) 789 if _is_path_like(source): --> 790 return _filesystem_dataset(source, **kwargs) 791 elif isinstance(source, (tuple, list)): 792 if all(_is_path_like(elem) or isinstance(elem, FileInfo) for elem in source): File ~/work/graphrag/graphrag/.venv/lib/python3.13/site-packages/pyarrow/dataset.py:472, in _filesystem_dataset(source, schema, filesystem, partitioning, format, partition_base_dir, exclude_invalid_files, selector_ignore_prefixes) 470 fs, paths_or_selector = _ensure_multiple_sources(source, filesystem) 471 else: --> 472 fs, paths_or_selector = _ensure_single_source(source, filesystem) 474 options = FileSystemFactoryOptions( 475 partitioning=partitioning, 476 partition_base_dir=partition_base_dir, 477 exclude_invalid_files=exclude_invalid_files, 478 selector_ignore_prefixes=selector_ignore_prefixes 479 ) 480 factory = FileSystemDatasetFactory(fs, paths_or_selector, format, options) File ~/work/graphrag/graphrag/.venv/lib/python3.13/site-packages/pyarrow/dataset.py:437, in _ensure_single_source(path, filesystem) 435 paths_or_selector = [path] 436 else: --> 437 raise FileNotFoundError(path) 439 return filesystem, paths_or_selector FileNotFoundError: <your project directory>/output/entities.parquet
The response object contains GraphRAG's response, while the context object holds metadata about the querying process used to obtain the final response.
print(response)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[7], line 1 ----> 1 print(response) NameError: name 'response' is not defined
Digging into the context a bit more provides users with extremely granular information such as what sources of data (down to the level of text chunks) were ultimately retrieved and used as part of the context sent to the LLM model).
pprint(context) # noqa: T203
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[8], line 1 ----> 1 pprint(context) # noqa: T203 NameError: name 'context' is not defined