見出し画像

GraphRAGシステムの使い方:初心者向け完全ガイド


はじめに

GraphRAGは、テキストデータのインデックス作成と質問応答を行うための強力なシステムです。この記事では、GraphRAGシステムの基本的な使い方を、初心者の方にも分かりやすく説明していきます。

こちらの記事もおすすめ

https://hamaruki.com/graphrag-search-methods-local-vs-global/

https://hamaruki.com/building-global-search-graphrag-ai-data-analysis/

GraphRAGのインストール

まずは、GraphRAGをインストールしましょう。Pythonの環境(バージョン3.10から3.12)が必要です。

!pip install graphrag
    ├── create_final_community_reports
    ├── create_final_text_units
    ├── create_base_documents
    └── create_final_documents
    [?25h🚀 [32mAll workflows completed successfully.[0m


MS公式のGraphRAGに挑戦中。。。
indexに時間がかかってます。。。
🔗https://t.co/CG3M6tMiO4 pic.twitter.com/cDgxxTnbtl

— Maki@Sunwood AI Labs. (@hAru_mAki_ch) July 9, 2024


このコマンドを実行すると、入力データの解析とインデックス作成が行われます。処理時間は入力データのサイズや使用するモデルによって変わります。

処理が完了すると、./ragtest/output/<timestamp>/artifactsディレクトリにParquetファイルが生成されます。

クエリエンジンの使用

インデックス作成が完了したら、クエリエンジンを使って質問に答えることができます。

グローバル検索の例

全体的な内容に関する質問をする場合は、グローバル検索を使用します。

!python -m graphrag.query \
--root ./ragtest \
--method global \
"What are the top themes in this story?"
    2024-07-09 12:26:31.954045: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
    2024-07-09 12:26:31.954129: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
    2024-07-09 12:26:31.957466: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
    2024-07-09 12:26:33.947596: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
    
    
    INFO: Reading settings from ragtest/settings.yaml
    creating llm client with {'api_key': 'REDACTED,len=51', 'type': "openai_chat", 'model': 'gpt-4-turbo-preview', 'max_tokens': 4000, 'request_timeout': 180.0, 'api_base': None, 'api_version': None, 'organization': None, 'proxy': None, 'cognitive_services_endpoint': None, 'deployment_name': None, 'model_supports_json': True, 'tokens_per_minute': 0, 'requests_per_minute': 0, 'max_retries': 10, 'max_retry_wait': 10.0, 'sleep_on_rate_limit_recommendation': True, 'concurrent_requests': 25}
    
    SUCCESS: Global Search Response: ### Top Themes in the Story
    
    The story we're examining is rich with themes that delve into human nature, societal responsibilities, and the power of transformation. Below, we explore the most significant themes that stand out in the narrative.
    
    #### Transformation and Redemption
    
    At the heart of the story is the profound transformation of Scrooge, evolving from a miserly individual to a beacon of generosity. This journey is not just a personal awakening but a testament to the human capacity for change. Scrooge's interactions with various characters and spirits serve as catalysts for this dramatic shift, illustrating that redemption is accessible to all, regardless of past actions [Data: Reports (17, 1, 2, 18)].
    
    #### Impact of Individual Actions on Community
    
    The narrative places a strong emphasis on how individual actions can ripple through a community, affecting the well-being of others. Scrooge's transformation from a selfish to a generous individual underscores the positive impact one person can have on society. This theme highlights the interconnectedness of individuals within a community and the importance of contributing positively to the collective [Data: Reports (17, 2)].
    
    #### Empathy and Social Responsibility
    
    A key message woven throughout the story is the importance of empathy and social responsibility. Scrooge's evolving relationships, especially with the Cratchit family, showcase how understanding and caring for others can lead to a more fulfilling life. The narrative encourages readers to consider the consequences of their actions on others, promoting a message of compassion and responsibility towards one's community [Data: Reports (17, 2, 5)].
    
    #### Christmas Spirit and Transformation
    
    The Christmas spirit, with its emphasis on joy, generosity, and goodwill, acts as a powerful motif in the story. It is this spirit that ultimately catalyzes Scrooge's transformation, symbolizing the potential for change and renewal inherent in the holiday season. The story suggests that the essence of Christmas can inspire individuals to reflect on their lives and embrace the opportunity for positive change [Data: Reports (1, 13)].
    
    #### Generosity and the Spirit of Giving
    
    Finally, the theme of generosity and the spirit of giving is highlighted as Scrooge begins to act with kindness towards others. His transformation illustrates the positive effects that acts of generosity can have, not just on the recipients but also on the giver. The narrative suggests that true happiness and fulfillment come from giving to others and helping those in need [Data: Reports (2, 14)].
    
    In summary, the story weaves together these themes to present a narrative that is as much about personal transformation as it is about the impact of our actions on the world around us. Through the character of Scrooge, the story conveys powerful messages about redemption, community, empathy, and the true spirit of giving.
    
!python -m graphrag.query \
--root ./ragtest \
--method global \
"この物語の主要なテーマは何ですか?"
    2024-07-09 12:29:41.683866: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
    2024-07-09 12:29:41.683937: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
    2024-07-09 12:29:41.686353: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
    2024-07-09 12:29:43.377550: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
    
    
    INFO: Reading settings from ragtest/settings.yaml
    creating llm client with {'api_key': 'REDACTED,len=51', 'type': "openai_chat", 'model': 'gpt-4-turbo-preview', 'max_tokens': 4000, 'request_timeout': 180.0, 'api_base': None, 'api_version': None, 'organization': None, 'proxy': None, 'cognitive_services_endpoint': None, 'deployment_name': None, 'model_supports_json': True, 'tokens_per_minute': 0, 'requests_per_minute': 0, 'max_retries': 10, 'max_retry_wait': 10.0, 'sleep_on_rate_limit_recommendation': True, 'concurrent_requests': 25}
    
    SUCCESS: Global Search Response: この物語の核心をなすテーマは、Ebenezer Scroogeの個人的な変容、クリスマスの精神、家族との関係、贖罪と救済、そして社会的不平等と慈善の重要性に関連しています。これらのテーマは、物語全体を通じて織り交ぜられ、読者に深いメッセージを伝えます。
    
    ### Ebenezer Scroogeの変容
    物語の中心的なテーマは、Ebenezer Scroogeの個人的な変容です。彼の過去、現在、未来を巡る旅を通じて、人間性、共感、そして社会的責任の重要性が探求されます。この変容は、彼が経験する一連の霊的な訪問によって促され、読者に対して、人生を見つめ直し、改善する機会が常に存在することを示唆しています [Data: Reports (17, 1)]。
    
    ### クリスマスの精神
    クリスマスの精神とその変革力は、Scroogeの変化を促す重要な要素であり、人々がお互いに対してより思いやりを持ち、より良いコミュニティを築くことの価値を強調しています。このテーマは、物語を通じて、人間関係の改善と社会全体の福祉向上への希望を象徴しています [Data: Reports (1, 13)]。
    
    ### 家族との関係
    家族との関係、特にCratchit家族との関わりは、Scroogeの変化に大きな影響を与えます。このテーマは、家族の絆と愛の力を強調し、個人の幸福と社会的な調和の基盤としての家族の価値を探求しています [Data: Reports (2, 14)]。
    
    ### 贖罪と救済
    贖罪と救済のテーマは、Marleyの幽霊とその他の幽霊たちを通じて探求されます。これは、人生の選択が個人の魂に及ぼす影響と、改心による救済の可能性を示しており、読者に対して、過去の過ちを乗り越え、新たな始まりを迎える希望を与えます [Data: Reports (6, 18)]。
    
    ### 社会的不平等と慈善の重要性
    社会的不平等と慈善の重要性は、Scroogeの変化を通じて、より良い社会を築くための個人の役割と行動の影響をテーマにしています。このテーマは、社会的責任と個人の行動が社会全体に与える影響の重要性を強調し、読者に対して、慈善と思いやりの精神を持つことの価値を訴えかけます [Data: Reports (5, 7)]。
    
    これらのテーマは、物語を通じて複雑に絡み合い、読者に対して、人間性、共感、社会的責任について深く考えさせるメッセージを伝えています。
    

ローカル検索の例

特定のキャラクターや場面に関する質問をする場合は、ローカル検索を使用します。

!python -m graphrag.query \
--root ./ragtest \
--method local \
"スクルージとは誰で、彼の主な人間関係は何ですか?"
    2024-07-09 12:27:34.804127: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
    2024-07-09 12:27:34.804191: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
    2024-07-09 12:27:34.805719: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
    2024-07-09 12:27:36.969940: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
    
    
    INFO: Reading settings from ragtest/settings.yaml
    [0m[38;5;8m[[0m2024-07-09T12:27:47Z [0m[33mWARN [0m lance::dataset[0m[38;5;8m][0m No existing dataset at /content/lancedb/description_embedding.lance, it will be created
    creating llm client with {'api_key': 'REDACTED,len=51', 'type': "openai_chat", 'model': 'gpt-4-turbo-preview', 'max_tokens': 4000, 'request_timeout': 180.0, 'api_base': None, 'api_version': None, 'organization': None, 'proxy': None, 'cognitive_services_endpoint': None, 'deployment_name': None, 'model_supports_json': True, 'tokens_per_minute': 0, 'requests_per_minute': 0, 'max_retries': 10, 'max_retry_wait': 10.0, 'sleep_on_rate_limit_recommendation': True, 'concurrent_requests': 25}
    creating embedding llm client with {'api_key': 'REDACTED,len=51', 'type': "openai_embedding", 'model': 'text-embedding-3-small', 'max_tokens': 4000, 'request_timeout': 180.0, 'api_base': None, 'api_version': None, 'organization': None, 'proxy': None, 'cognitive_services_endpoint': None, 'deployment_name': None, 'model_supports_json': None, 'tokens_per_minute': 0, 'requests_per_minute': 0, 'max_retries': 10, 'max_retry_wait': 10.0, 'sleep_on_rate_limit_recommendation': True, 'concurrent_requests': 25}
    
    SUCCESS: Local Search Response: # スクルージとは
    
    エベネーザー・スクルージは、チャールズ・ディケンズの『クリスマス・キャロル』に登場する架空の人物です。彼は、物語の中心人物であり、最初は貪欲で心の狭い老人として描かれています。スクルージは、自身の事業パートナーであったジェイコブ・マーリーの幽霊と、過去、現在、未来のクリスマスの精霊たちによる訪問を通じて、人生と周囲の人々に対する彼の態度を深く反省することになります。この体験を通じて、彼は慈悲深く、周囲の人々に対して思いやりのある人物へと大きく変貌します [Data: Entities (32)]。
    
    # スクルージの主な人間関係
    
    ## ジェイコブ・マーリー
    ジェイコブ・マーリーは、スクルージの亡くなった事業パートナーであり、物語の始まりでスクルージを訪れる最初の幽霊です。マーリーの訪問は、スクルージの変化のきっかけとなります。彼はスクルージに対して、自分の人生を振り返り、改心する機会を与えるために、過去、現在、未来のクリスマスの精霊たちの訪問を告げます [Data: Entities (54); Relationships (21, 56)]。
    
    ## ボブ・クラチット
    ボブ・クラチットは、スクルージの事務所で働く書記であり、スクルージの厳しい扱いを受けながらも家族を支える優しい心を持った人物です。スクルージの変貌は、クラチット家、特にボブの息子であるタイニー・ティムの生活に直接的な良い影響を与えます [Data: Entities (45)]。
    
    ## フレッド
    フレッドはスクルージの甥であり、スクルージに対して友好的な態度を示す数少ない人物の一人です。彼はスクルージをクリスマスのディナーに招待することで、叔父との関係改善を試みます。フレッドの存在は、スクルージに家族の重要性とクリスマスの精神を思い出させる役割を果たします [Data: Entities (105, 10)]。
    
    ## タイニー・ティム
    タイニー・ティムは、ボブ・クラチットの息子であり、彼の健康と幸福は物語の中で重要なテーマとなっています。スクルージの変化は、タイニー・ティムの将来に希望をもたらします。
    
    これらの人間関係は、スクルージの人生と彼の周囲のコミュニティにおける彼の役割の変化を示しています。彼の物語は、個人の変化が周囲の人々に与える影響の力を強調しています。
    


MS公式のGraphRAGやってみた!!
結構いい感じに気がする。。。(公式チュートリアルをそのまま回すと5ドル近くかかりますので注意) https://t.co/aHfTC7frll pic.twitter.com/mpov2g6ci0

— Maki@Sunwood AI Labs. (@hAru_mAki_ch) July 9, 2024


まとめ

以上で、GraphRAGシステムの基本的な使い方の説明が完了しました。このガイドを通じて、以下のことを学びました:

  1. GraphRAGのインストール方法

  2. 環境設定の手順

  3. インデックス作成の実行方法

  4. クエリエンジンの使用方法

GraphRAGを使いこなすことで、大量のテキストデータから効率的に情報を抽出し、質問に答えることができます。さらに詳しい情報や高度な使用方法については、公式ドキュメントを参照してください。

📒ノートブック付

https://colab.research.google.com/drive/1z2d6Y14Dea_Us0CqRp4wGkglPF03rys9?usp=sharing

参考サイト

https://microsoft.github.io/graphrag/posts/get_started/


この記事が気に入ったらサポートをしてみませんか?