Global Search
In [1]:
Copied!
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License.
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License.
In [2]:
Copied!
import os
import pandas as pd
import tiktoken
from graphrag.query.indexer_adapters import (
read_indexer_communities,
read_indexer_entities,
read_indexer_reports,
)
from graphrag.query.llm.oai.chat_openai import ChatOpenAI
from graphrag.query.llm.oai.typing import OpenaiApiType
from graphrag.query.structured_search.global_search.community_context import (
GlobalCommunityContext,
)
from graphrag.query.structured_search.global_search.search import GlobalSearch
import os
import pandas as pd
import tiktoken
from graphrag.query.indexer_adapters import (
read_indexer_communities,
read_indexer_entities,
read_indexer_reports,
)
from graphrag.query.llm.oai.chat_openai import ChatOpenAI
from graphrag.query.llm.oai.typing import OpenaiApiType
from graphrag.query.structured_search.global_search.community_context import (
GlobalCommunityContext,
)
from graphrag.query.structured_search.global_search.search import GlobalSearch
Global Search example¶
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?).
LLM setup¶
In [3]:
Copied!
api_key = os.environ["GRAPHRAG_API_KEY"]
llm_model = os.environ["GRAPHRAG_LLM_MODEL"]
llm = ChatOpenAI(
api_key=api_key,
model=llm_model,
api_type=OpenaiApiType.OpenAI, # OpenaiApiType.OpenAI or OpenaiApiType.AzureOpenAI
max_retries=20,
)
token_encoder = tiktoken.encoding_for_model(llm_model)
api_key = os.environ["GRAPHRAG_API_KEY"]
llm_model = os.environ["GRAPHRAG_LLM_MODEL"]
llm = ChatOpenAI(
api_key=api_key,
model=llm_model,
api_type=OpenaiApiType.OpenAI, # OpenaiApiType.OpenAI or OpenaiApiType.AzureOpenAI
max_retries=20,
)
token_encoder = tiktoken.encoding_for_model(llm_model)
Load community reports as context for global search¶
- Load all community reports in the
create_final_community_reports
table from the ire-indexing engine, to be used as context data for global search. - Load entities from the
create_final_nodes
andcreate_final_entities
tables from the ire-indexing engine, to be used for calculating community weights for context ranking. Note that this is optional (if no entities are provided, we will not calculate community weights and only use the rank attribute in the community reports table for context ranking) - Load all communities in the
create_final_communites
table from the ire-indexing engine, to be used to reconstruct the community graph hierarchy for dynamic community selection.
In [4]:
Copied!
# parquet files generated from indexing pipeline
INPUT_DIR = "./inputs/operation dulce"
COMMUNITY_TABLE = "create_final_communities"
COMMUNITY_REPORT_TABLE = "create_final_community_reports"
ENTITY_TABLE = "create_final_nodes"
ENTITY_EMBEDDING_TABLE = "create_final_entities"
# community level in the Leiden community hierarchy from which we will load the community reports
# higher value means we use reports from more fine-grained communities (at the cost of higher computation cost)
COMMUNITY_LEVEL = 2
# parquet files generated from indexing pipeline
INPUT_DIR = "./inputs/operation dulce"
COMMUNITY_TABLE = "create_final_communities"
COMMUNITY_REPORT_TABLE = "create_final_community_reports"
ENTITY_TABLE = "create_final_nodes"
ENTITY_EMBEDDING_TABLE = "create_final_entities"
# community level in the Leiden community hierarchy from which we will load the community reports
# higher value means we use reports from more fine-grained communities (at the cost of higher computation cost)
COMMUNITY_LEVEL = 2
In [5]:
Copied!
community_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_TABLE}.parquet")
entity_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_TABLE}.parquet")
report_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_REPORT_TABLE}.parquet")
entity_embedding_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_EMBEDDING_TABLE}.parquet")
communities = read_indexer_communities(community_df, entity_df, report_df)
reports = read_indexer_reports(report_df, entity_df, COMMUNITY_LEVEL)
entities = read_indexer_entities(entity_df, entity_embedding_df, COMMUNITY_LEVEL)
print(f"Total report count: {len(report_df)}")
print(
f"Report count after filtering by community level {COMMUNITY_LEVEL}: {len(reports)}"
)
report_df.head()
community_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_TABLE}.parquet")
entity_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_TABLE}.parquet")
report_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_REPORT_TABLE}.parquet")
entity_embedding_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_EMBEDDING_TABLE}.parquet")
communities = read_indexer_communities(community_df, entity_df, report_df)
reports = read_indexer_reports(report_df, entity_df, COMMUNITY_LEVEL)
entities = read_indexer_entities(entity_df, entity_embedding_df, COMMUNITY_LEVEL)
print(f"Total report count: {len(report_df)}")
print(
f"Report count after filtering by community level {COMMUNITY_LEVEL}: {len(reports)}"
)
report_df.head()
Total report count: 20 Report count after filtering by community level 2: 17
Out[5]:
community | full_content | level | rank | title | rank_explanation | summary | findings | full_content_json | id | |
---|---|---|---|---|---|---|---|---|---|---|
0 | 10 | # Paranormal Military Squad at Dulce Base: Dec... | 1 | 8.5 | Paranormal Military Squad at Dulce Base: Decod... | The impact severity rating is high due to the ... | The Paranormal Military Squad, stationed at Du... | [{'explanation': 'Jordan is a central figure i... | {\n "title": "Paranormal Military Squad at ... | 1ba2d200-dd26-4693-affe-a5539d0a0e0d |
1 | 11 | # Dulce and Paranormal Military Squad Operatio... | 1 | 8.5 | Dulce and Paranormal Military Squad Operations | The impact severity rating is high due to the ... | The community centers around Dulce, a secretiv... | [{'explanation': 'Dulce is described as a top-... | {\n "title": "Dulce and Paranormal Military... | a8a530b0-ae6b-44ea-b11c-9f70d138298d |
2 | 12 | # Paranormal Military Squad and Dulce Base Ope... | 1 | 7.5 | Paranormal Military Squad and Dulce Base Opera... | The impact severity rating is relatively high ... | The community centers around the Paranormal Mi... | [{'explanation': 'Taylor is a central figure w... | {\n "title": "Paranormal Military Squad and... | 0478975b-c805-4cc1-b746-82f3e689e2f3 |
3 | 13 | # Mission Dynamics and Leadership: Cruz and Wa... | 1 | 7.5 | Mission Dynamics and Leadership: Cruz and Wash... | The impact severity rating is relatively high ... | This report explores the intricate dynamics of... | [{'explanation': 'Cruz is a central figure in ... | {\n "title": "Mission Dynamics and Leadersh... | b56f6e68-3951-4f07-8760-63700944a375 |
4 | 14 | # Dulce Base and Paranormal Military Squad: Br... | 1 | 8.5 | Dulce Base and Paranormal Military Squad: Brid... | The impact severity rating is high due to the ... | The community centers around the Dulce Base, a... | [{'explanation': 'Sam Rivera, a member of the ... | {\n "title": "Dulce Base and Paranormal Mil... | 736e7006-d050-4abb-a122-00febf3f540f |
Build global context based on community reports¶
In [6]:
Copied!
context_builder = GlobalCommunityContext(
community_reports=reports,
communities=communities,
entities=entities, # default to None if you don't want to use community weights for ranking
token_encoder=token_encoder,
)
context_builder = GlobalCommunityContext(
community_reports=reports,
communities=communities,
entities=entities, # default to None if you don't want to use community weights for ranking
token_encoder=token_encoder,
)
Perform global search¶
In [7]:
Copied!
context_builder_params = {
"use_community_summary": False, # False means using full community reports. True means using community short summaries.
"shuffle_data": True,
"include_community_rank": True,
"min_community_rank": 0,
"community_rank_name": "rank",
"include_community_weight": True,
"community_weight_name": "occurrence weight",
"normalize_community_weight": True,
"max_tokens": 12_000, # change this based on the token limit you have on your model (if you are using a model with 8k limit, a good setting could be 5000)
"context_name": "Reports",
}
map_llm_params = {
"max_tokens": 1000,
"temperature": 0.0,
"response_format": {"type": "json_object"},
}
reduce_llm_params = {
"max_tokens": 2000, # change this based on the token limit you have on your model (if you are using a model with 8k limit, a good setting could be 1000-1500)
"temperature": 0.0,
}
context_builder_params = {
"use_community_summary": False, # False means using full community reports. True means using community short summaries.
"shuffle_data": True,
"include_community_rank": True,
"min_community_rank": 0,
"community_rank_name": "rank",
"include_community_weight": True,
"community_weight_name": "occurrence weight",
"normalize_community_weight": True,
"max_tokens": 12_000, # change this based on the token limit you have on your model (if you are using a model with 8k limit, a good setting could be 5000)
"context_name": "Reports",
}
map_llm_params = {
"max_tokens": 1000,
"temperature": 0.0,
"response_format": {"type": "json_object"},
}
reduce_llm_params = {
"max_tokens": 2000, # change this based on the token limit you have on your model (if you are using a model with 8k limit, a good setting could be 1000-1500)
"temperature": 0.0,
}
In [8]:
Copied!
search_engine = GlobalSearch(
llm=llm,
context_builder=context_builder,
token_encoder=token_encoder,
max_data_tokens=12_000, # change this based on the token limit you have on your model (if you are using a model with 8k limit, a good setting could be 5000)
map_llm_params=map_llm_params,
reduce_llm_params=reduce_llm_params,
allow_general_knowledge=False, # set this to True will add instruction to encourage the LLM to incorporate general knowledge in the response, which may increase hallucinations, but could be useful in some use cases.
json_mode=True, # set this to False if your LLM model does not support JSON mode.
context_builder_params=context_builder_params,
concurrent_coroutines=32,
response_type="multiple paragraphs", # free form text describing the response type and format, can be anything, e.g. prioritized list, single paragraph, multiple paragraphs, multiple-page report
)
search_engine = GlobalSearch(
llm=llm,
context_builder=context_builder,
token_encoder=token_encoder,
max_data_tokens=12_000, # change this based on the token limit you have on your model (if you are using a model with 8k limit, a good setting could be 5000)
map_llm_params=map_llm_params,
reduce_llm_params=reduce_llm_params,
allow_general_knowledge=False, # set this to True will add instruction to encourage the LLM to incorporate general knowledge in the response, which may increase hallucinations, but could be useful in some use cases.
json_mode=True, # set this to False if your LLM model does not support JSON mode.
context_builder_params=context_builder_params,
concurrent_coroutines=32,
response_type="multiple paragraphs", # free form text describing the response type and format, can be anything, e.g. prioritized list, single paragraph, multiple paragraphs, multiple-page report
)
In [9]:
Copied!
result = await search_engine.asearch(
"What is Cosmic Vocalization and who are involved in it?"
)
print(result.response)
result = await search_engine.asearch(
"What is Cosmic Vocalization and who are involved in it?"
)
print(result.response)
### Overview of Cosmic Vocalization Cosmic Vocalization is a phenomenon that has garnered significant attention within the community, involving various individuals and groups. It is perceived as a complex and potentially responsive cosmic event, which has led to diverse interpretations and reactions from those involved. ### Key Perspectives and Concerns Alex Mercer views Cosmic Vocalization as part of an interstellar duet, suggesting that it may be a responsive or interactive event in the cosmic realm [Data: Reports (6)]. This perspective highlights the potential for Cosmic Vocalization to be part of a larger cosmic communication or interaction. On the other hand, Taylor Cruz expresses concerns that Cosmic Vocalization might be a homing tune, which introduces a sense of urgency and potential threat [Data: Reports (6)]. This interpretation suggests that the phenomenon could have implications for security or safety, warranting careful monitoring and analysis. ### Strategic Engagement The Paranormal Military Squad's involvement with Cosmic Vocalization underscores its significance in terms of security measures. Their engagement indicates a strategic response to these cosmic phenomena, reflecting the importance of understanding and potentially mitigating any associated risks [Data: Reports (6)]. In summary, Cosmic Vocalization is a multifaceted phenomenon that has attracted attention from various stakeholders, each with their own interpretations and concerns. The involvement of individuals like Alex Mercer and Taylor Cruz, as well as organizations like the Paranormal Military Squad, highlights the complexity and potential implications of this cosmic event.
In [10]:
Copied!
# inspect the data used to build the context for the LLM responses
result.context_data["reports"]
# inspect the data used to build the context for the LLM responses
result.context_data["reports"]
Out[10]:
id | title | occurrence weight | content | rank | |
---|---|---|---|---|---|
0 | 15 | Dulce Base and the Paranormal Military Squad: ... | 1.00 | # Dulce Base and the Paranormal Military Squad... | 9.5 |
1 | 11 | Dulce and Paranormal Military Squad Operations | 0.30 | # Dulce and Paranormal Military Squad Operatio... | 8.5 |
2 | 10 | Paranormal Military Squad at Dulce Base: Decod... | 0.30 | # Paranormal Military Squad at Dulce Base: Dec... | 8.5 |
3 | 7 | Operation: Dulce and the Paranormal Military S... | 0.20 | # Operation: Dulce and the Paranormal Military... | 8.5 |
4 | 8 | Dr. Jordan Hayes and the Paranormal Military S... | 0.18 | # Dr. Jordan Hayes and the Paranormal Military... | 8.5 |
5 | 1 | Earth's Interstellar Communication Initiative | 0.16 | # Earth's Interstellar Communication Initiativ... | 8.5 |
6 | 12 | Paranormal Military Squad and Dulce Base Opera... | 0.16 | # Paranormal Military Squad and Dulce Base Ope... | 7.5 |
7 | 13 | Mission Dynamics and Leadership: Cruz and Wash... | 0.16 | # Mission Dynamics and Leadership: Cruz and Wa... | 7.5 |
8 | 14 | Dulce Base and Paranormal Military Squad: Brid... | 0.12 | # Dulce Base and Paranormal Military Squad: Br... | 8.5 |
9 | 16 | Dulce Military Base and Alien Intelligence Com... | 0.08 | # Dulce Military Base and Alien Intelligence C... | 8.5 |
10 | 18 | Paranormal Military Squad Team and Dulce Base'... | 0.04 | # Paranormal Military Squad Team and Dulce Bas... | 8.5 |
11 | 5 | Alien Script and First Contact Operations | 0.02 | # Alien Script and First Contact Operations\n\... | 8.5 |
12 | 4 | Dulce Facility and Control Room of Dulce: Extr... | 0.02 | # Dulce Facility and Control Room of Dulce: Ex... | 8.5 |
13 | 17 | Dulce Team and Underground Command Center: Int... | 0.02 | # Dulce Team and Underground Command Center: I... | 8.5 |
14 | 19 | Central Terminal and Viewing Monitors at Dulce... | 0.02 | # Central Terminal and Viewing Monitors at Dul... | 8.5 |
15 | 6 | Cosmic Vocalization and Universe Interactions | 0.02 | # Cosmic Vocalization and Universe Interaction... | 7.5 |
16 | 9 | Dulce Base Exploration by TEAM and MAINFRAME ROOM | 0.02 | # Dulce Base Exploration by TEAM and MAINFRAME... | 7.5 |
In [11]:
Copied!
# inspect number of LLM calls and tokens
print(
f"LLM calls: {result.llm_calls}. Prompt tokens: {result.prompt_tokens}. Output tokens: {result.output_tokens}."
)
# inspect number of LLM calls and tokens
print(
f"LLM calls: {result.llm_calls}. Prompt tokens: {result.prompt_tokens}. Output tokens: {result.output_tokens}."
)
LLM calls: 2. Prompt tokens: 11237. Output tokens: 468.