import os
from dotenv import load_dotenv
load_dotenv()
True
from openai import OpenAI
# 实例化客户端
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# 调用 GPT-4o-mini 模型
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "你好,好久不见!"}
]
)
# 输出生成的响应内容
print(response.choices[0].message.content)
你好!很高兴再次见到你!你最近怎么样?有什么想聊的吗?
2、全局搜索 Global Search
通过利用社区总结来进行全局性推理。
全局搜索方法通过以 map-reduce 方式搜索所有 AI 生成的社区报告来生成答案。这是一种资源密集型方法,但对于需要整体理解数据集的问题(例如,本笔记中提到的草药中最重要的价值是什么?),通常能提供良好的答案。
import os
import pandas as pd
import tiktoken
from graphrag.config.enums import ModelType
from graphrag.config.models.language_model_config import LanguageModelConfig
from graphrag.language_model.manager import ModelManager
from graphrag.query.indexer_adapters import (
read_indexer_communities,
read_indexer_entities,
read_indexer_reports,
)
from graphrag.query.structured_search.global_search.community_context import (
GlobalCommunityContext,
)
from graphrag.query.structured_search.global_search.search import GlobalSearch
#配置模型参数
api_key = os.environ.get("OPENAI_API_KEY")
llm_model = "gpt-4o-mini"
# llm_model = "gpt-4o"
embedding_model = "text-embedding-3-small"
config = LanguageModelConfig(
api_key=api_key,
type=ModelType.OpenAIChat,
model=llm_model,
max_retries=20,
)
model = ModelManager().get_or_create_chat_model(
name="global_search",
model_type=ModelType.OpenAIChat,
config=config,
)
token_encoder = tiktoken.encoding_for_model(llm_model)
加载社区报告作为全局搜索的上下文
- 从 GraphRAG 的 community_reports 表中加载所有社区报告,用作全局搜索的上下文数据。
- 从 GraphRAG 的实体表中加载实体,用于计算上下文排名的社区权重。请注意,这是可选的(如果没有提供实体,我们将不计算社区权重,而仅使用社区报告表中的 rank 属性进行上下文排名)。
- 从 GraphRAG 的社区表中加载所有社区,用于重建社区图谱层次结构,以便进行动态社区选择。
# 从索引管道生成的 parquet 文件
INPUT_DIR = "/Users/dcs/study/ragtest/output"
COMMUNITY_TABLE = "communities"
COMMUNITY_REPORT_TABLE = "community_reports"
ENTITY_TABLE = "entities"
# 莱顿 Leiden 社区层级结构中的社区级别,我们将从中加载社区报告
# 值越高,意味着我们使用来自更细粒度社区的报告(但计算成本会更高)
COMMUNITY_LEVEL = 2
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")
communities = read_indexer_communities(community_df, report_df)
reports = read_indexer_reports(report_df, community_df, COMMUNITY_LEVEL)
entities = read_indexer_entities(entity_df, community_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: 5
Report count after filtering by community level 2: 5
| id | human_readable_id | community | level | parent | children | title | summary | full_content | rank | rating_explanation | findings | full_content_json | period | size | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 16dfc1a65704472da48ffb4e0a489264 | 3 | 3 | 1 | 1 | [] | Porsche Dealership Network in China | The community centers around Porsche, a luxury... | # Porsche Dealership Network in China\n\nThe c... | 7.5 | The impact severity rating is high due to Pors... | [{'explanation': 'Porsche is a well-establishe... | {\n "title": "Porsche Dealership Network in... | 2025-05-16 | 9 |
| 1 | e9da0e9891604c7ba6447e6540f517e7 | 4 | 4 | 1 | 1 | [] | Tianjin Airport Porsche Center and Tianjin | The community centers around the Tianjin Airpo... | # Tianjin Airport Porsche Center and Tianjin\n... | 6.0 | The impact severity rating is moderate due to ... | [{'explanation': 'The Tianjin Airport Porsche ... | {\n "title": "Tianjin Airport Porsche Cente... | 2025-05-16 | 2 |
| 2 | 0cd453e8b7044d2d83f65a02cb2bc52d | 0 | 0 | 0 | -1 | [] | 百小灵 and Its Integrated Services | The community centers around 百小灵, an intellige... | # 百小灵 and Its Integrated Services\n\nThe commu... | 7.5 | The impact severity rating is high due to the ... | [{'explanation': '百小灵 serves as the core entit... | {\n "title": "百小灵 and Its Integrated Servic... | 2025-05-16 | 4 |
| 3 | dae335f202224c27aa303bd0fcac3073 | 1 | 1 | 0 | -1 | [3, 4] | Porsche Dealership Network in China | The community centers around Porsche, a luxury... | # Porsche Dealership Network in China\n\nThe c... | 8.5 | The impact severity rating is high due to the ... | [{'explanation': 'Porsche is a well-establishe... | {\n "title": "Porsche Dealership Network in... | 2025-05-16 | 11 |
| 4 | dd50d0d4d96d447995bb129030028c71 | 2 | 2 | 0 | -1 | [] | Baideli Group and Key Leadership | The community centers around Baideli Group, a ... | # Baideli Group and Key Leadership\n\nThe comm... | 7.5 | The impact severity rating is high due to Baid... | [{'explanation': 'Zhou Xiaobo serves as the Ch... | {\n "title": "Baideli Group and Key Leaders... | 2025-05-16 | 10 |
from graphrag.config.enums import ModelType
from graphrag.config.models.language_model_config import LanguageModelConfig
from graphrag.language_model.manager import ModelManager
chat_config = LanguageModelConfig(
api_key=os.environ.get("OPENAI_API_KEY"),
type=ModelType.OpenAIChat,
model=llm_model,
max_retries=20,
)
chat_model = ModelManager().get_or_create_chat_model(
name="global_search",
model_type=ModelType.OpenAIChat,
config=chat_config,
)
token_encoder = tiktoken.encoding_for_model(llm_model)
embedding_config = LanguageModelConfig(
api_key=os.environ.get("OPENAI_API_KEY"),
type=ModelType.OpenAIEmbedding,
model=embedding_model,
max_retries=20,
)
text_embedder = ModelManager().get_or_create_embedding_model(
name="global_search_embedding",
model_type=ModelType.OpenAIEmbedding,
config=embedding_config,
)
# 根据社区报告构建全局背景
context_builder = GlobalCommunityContext(
community_reports=reports,
communities=communities,
entities=entities, # 如果您不想使用社区权重进行排名,则默认为 None
token_encoder=token_encoder,
)
# 执行全局搜索
# 配置全局搜索参数
context_builder_params = {
"use_community_summary": False, # False 表示使用完整的社区报告。True 表示使用社区简短摘要。
"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": 8000, # 根据您模型上的令牌限制进行更改(如果您使用的模型限制为 8k,则良好的设置可能是 5000)
"context_name": "Reports",
}
map_llm_params = {
"max_tokens": 800,
"temperature": 0.0,
"response_format": {"type": "json_object"}
}
reduce_llm_params = {
"max_tokens": 1000, # 根据您模型上的令牌限制进行更改(如果您使用的模型限制为 8k,则良好的设置可能是 1000-1500)
"temperature": 0.0,
}
# 构建全局搜索引擎
search_engine = GlobalSearch(
model=model,
context_builder=context_builder,
token_encoder=token_encoder,
max_data_tokens=8000, # 根据您模型上的令牌限制进行更改(如果您使用的模型限制为 8k,则良好的设置可能是 5000)
map_llm_params=map_llm_params,
reduce_llm_params=reduce_llm_params,
allow_general_knowledge=False, # 将其设置为 True 将添加指令以鼓励 LLM 在响应中融入一般知识,这可能会增加幻觉,但在某些用例中可能会有用。
json_mode=True, # 如果您的 LLM 模型不支持 JSON 模式,请将其设置为 False。
context_builder_params=context_builder_params,
concurrent_coroutines=32,
response_type="multiple paragraphs",
# 描述响应类型和格式的自由格式文本,可以是任何内容,例如优先列表、单段、多段、多页报告
)
result = await search_engine.search("百得利集团 企业概况?")
print(result.response)
print(search_engine.reduce_system_prompt)
---Role---
You are a helpful assistant responding to questions about a dataset by synthesizing perspectives from multiple analysts.
---Goal---
Generate a response of the target length and format that responds to the user's question, summarize all the reports from multiple analysts who focused on different parts of the dataset.
Note that the analysts' reports provided below are ranked in the **descending order of importance**.
If you don't know the answer or if the provided reports do not contain sufficient information to provide an answer, just say so. Do not make anything up.
The final response should remove all irrelevant information from the analysts' reports and merge the cleaned information into a comprehensive answer that provides explanations of all the key points and implications appropriate for the response length and format.
Add sections and commentary to the response as appropriate for the length and format. Style the response in markdown.
The response shall preserve the original meaning and use of modal verbs such as "shall", "may" or "will".
The response should also preserve all the data references previously included in the analysts' reports, but do not mention the roles of multiple analysts in the analysis process.
**Do not list more than 5 record ids in a single reference**. Instead, list the top 5 most relevant record ids and add "+more" to indicate that there are more.
For example:
"Person X is the owner of Company Y and subject to many allegations of wrongdoing [Data: Reports (2, 7, 34, 46, 64, +more)]. He is also CEO of company X [Data: Reports (1, 3)]"
where 1, 2, 3, 7, 34, 46, and 64 represent the id (not the index) of the relevant data record.
Do not include information where the supporting evidence for it is not provided.
Limit your response length to {max_length} words.
---Target response length and format---
{response_type}
---Analyst Reports---
{report_data}
---Goal---
Generate a response of the target length and format that responds to the user's question, summarize all the reports from multiple analysts who focused on different parts of the dataset.
Note that the analysts' reports provided below are ranked in the **descending order of importance**.
If you don't know the answer or if the provided reports do not contain sufficient information to provide an answer, just say so. Do not make anything up.
The final response should remove all irrelevant information from the analysts' reports and merge the cleaned information into a comprehensive answer that provides explanations of all the key points and implications appropriate for the response length and format.
The response shall preserve the original meaning and use of modal verbs such as "shall", "may" or "will".
The response should also preserve all the data references previously included in the analysts' reports, but do not mention the roles of multiple analysts in the analysis process.
**Do not list more than 5 record ids in a single reference**. Instead, list the top 5 most relevant record ids and add "+more" to indicate that there are more.
For example:
"Person X is the owner of Company Y and subject to many allegations of wrongdoing [Data: Reports (2, 7, 34, 46, 64, +more)]. He is also CEO of company X [Data: Reports (1, 3)]"
where 1, 2, 3, 7, 34, 46, and 64 represent the id (not the index) of the relevant data record.
Do not include information where the supporting evidence for it is not provided.
Limit your response length to {max_length} words.
---Target response length and format---
{response_type}
Add sections and commentary to the response as appropriate for the length and format. Style the response in markdown.
from IPython.display import Markdown
display(Markdown(result.response))
# 检查用于构建 LLM 响应上下文的数据
result.context_data["reports"]
| id | title | occurrence weight | content | rank | |
|---|---|---|---|---|---|
| 0 | 2 | Baideli Group and Key Leadership | 1.000000 | # Baideli Group and Key Leadership\n\nThe comm... | 7.5 |
| 1 | 1 | Porsche Dealership Network in China | 0.666667 | # Porsche Dealership Network in China\n\nThe c... | 8.5 |
| 2 | 0 | 百小灵 and Its Integrated Services | 0.666667 | # 百小灵 and Its Integrated Services\n\nThe commu... | 7.5 |
| 3 | 4 | Tianjin Airport Porsche Center and Tianjin | 0.666667 | # Tianjin Airport Porsche Center and Tianjin\n... | 6.0 |
| 4 | 3 | Porsche Dealership Network in China | 0.333333 | # Porsche Dealership Network in China\n\nThe c... | 7.5 |
# 检查 LLM 调用和令牌的数量
print(
f"LLM calls: {result.llm_calls}. Prompt tokens: {result.prompt_tokens}. Output tokens: {result.output_tokens}."
)
LLM calls: 2. Prompt tokens: 3798. Output tokens: 385.
3、DRIFT 搜索
结合局部搜索和社区信息,提供更准确和相关的答案。
DRIFT Search 通过在搜索过程中引入社区信息,为本地搜索查询引入了一种新方法。这极大地扩展了查询的起点,并使得最终答案能够检索和使用更丰富的事实。这一新增功能扩展了 GraphRAG 查询引擎,为本地搜索提供了更全面的选项,它利用社区洞察将查询细化为详细的后续问题。
import os
from pathlib import Path
import pandas as pd
import tiktoken
from graphrag.config.enums import ModelType
from graphrag.config.models.drift_search_config import DRIFTSearchConfig
from graphrag.config.models.language_model_config import LanguageModelConfig
from graphrag.language_model.manager import ModelManager
from graphrag.query.indexer_adapters import (
read_indexer_entities,
read_indexer_relationships,
read_indexer_report_embeddings,
read_indexer_reports,
read_indexer_text_units,
)
from graphrag.query.structured_search.drift_search.drift_context import (
DRIFTSearchContextBuilder,
)
from graphrag.query.structured_search.drift_search.search import DRIFTSearch
from graphrag.vector_stores.lancedb import LanceDBVectorStore
INPUT_DIR = "/Users/dcs/study/ragtest/output"
LANCEDB_URI = f"{INPUT_DIR}/lancedb"
COMMUNITY_REPORT_TABLE = "community_reports"
COMMUNITY_TABLE = "communities"
ENTITY_TABLE = "entities"
RELATIONSHIP_TABLE = "relationships"
COVARIATE_TABLE = "covariates"
TEXT_UNIT_TABLE = "text_units"
COMMUNITY_LEVEL = 2
# 读取节点表以获取社区和度数据
entity_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_TABLE}.parquet")
community_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_TABLE}.parquet")
print(f"Entity df columns: {entity_df.columns}")
entities = read_indexer_entities(entity_df, community_df, COMMUNITY_LEVEL)
# 将描述嵌入加载到内存中的 lancedb 向量存储
# 要连接到远程数据库,请指定 URL 和端口值。
description_embedding_store = LanceDBVectorStore(
collection_name="default-entity-description",
)
description_embedding_store.connect(db_uri=LANCEDB_URI)
full_content_embedding_store = LanceDBVectorStore(
collection_name="default-community-full_content",
)
full_content_embedding_store.connect(db_uri=LANCEDB_URI)
print(f"Entity count: {len(entity_df)}")
entity_df.head()
relationship_df = pd.read_parquet(f"{INPUT_DIR}/{RELATIONSHIP_TABLE}.parquet")
relationships = read_indexer_relationships(relationship_df)
print(f"Relationship count: {len(relationship_df)}")
relationship_df.head()
text_unit_df = pd.read_parquet(f"{INPUT_DIR}/{TEXT_UNIT_TABLE}.parquet")
text_units = read_indexer_text_units(text_unit_df)
print(f"Text unit records: {len(text_unit_df)}")
text_unit_df.head()
Entity df columns: Index(['id', 'human_readable_id', 'title', 'type', 'description',
'text_unit_ids', 'frequency', 'degree', 'x', 'y'],
dtype='object')
Entity count: 60
Relationship count: 48
Text unit records: 5
| id | human_readable_id | text | n_tokens | document_ids | entity_ids | relationship_ids | covariate_ids | |
|---|---|---|---|---|---|---|---|---|
| 0 | fcfd223135ec68d9db3de6d96a9acf067bba754a821bdf... | 1 | ---\n### **百得利集团(BetterLife Group)详细介绍**\n\n--... | 1200 | [4ad21bc3e51b59a81cf6154e067933779d25209edb4dd... | [354cf6e2-6a14-46e0-bca6-7ca915a1bdc6, a9a38cd... | [929afb7c-390e-4d90-8ef2-81125c87cf9e, 11a9cd3... | [] |
| 1 | 26d628a6139e04a0a88e7f8e2ef4514dc7623e42272d5d... | 2 | ---------------------------------------------... | 1200 | [4ad21bc3e51b59a81cf6154e067933779d25209edb4dd... | [9fbafca4-0501-4767-86cc-c960f7627a6f, 0c20e92... | [0c92d085-5daf-48ca-9be4-c30b7f12fcea, 61fcfe2... | [] |
| 2 | c3cf21b0ec18829069de824ee4584b34bdcff45be7b910... | 3 | ">杭州市滨江区江陵路1780号</font> | <font style="color:r... | 1200 | [4ad21bc3e51b59a81cf6154e067933779d25209edb4dd... | [83797f98-c10a-46a5-9b3c-89b3f8f70307, 9adbd33... | [de2fba5b-952b-49c6-accf-f74378c5c180, 1239e9f... | [] |
| 3 | 97aca591d3a56fb8a6427a818355a75a792a39da1fd488... | 4 | 3. **行业荣誉** \n - 连续多年入选“中国汽车经销商百强”。 \n -... | 1200 | [4ad21bc3e51b59a81cf6154e067933779d25209edb4dd... | [e05c66d7-cbdc-4c72-a622-43a632c710dc, 9c3824e... | [e4952720-c6e7-4222-be2b-8a073228a697, 0be14de... | [] |
| 4 | 4b96c621329960f421f7a922195c1f6590b8314ce5ee18... | 5 | 物流跟踪)、</font>**保险平台 **<font style="color:rgb(4... | 630 | [4ad21bc3e51b59a81cf6154e067933779d25209edb4dd... | [9c3824ef-034a-48cb-a7ee-8cde18650b04, 62c8ae2... | [d680e598-61c0-4375-a676-51d19d422002, 7a6571e... | [] |
chat_config = LanguageModelConfig(
api_key=api_key,
type=ModelType.OpenAIChat,
model=llm_model,
max_retries=20,
)
chat_model = ModelManager().get_or_create_chat_model(
name="DRIFT_search",
model_type=ModelType.OpenAIChat,
config=chat_config,
)
token_encoder = tiktoken.encoding_for_model(llm_model)
embedding_config = LanguageModelConfig(
api_key=api_key,
type=ModelType.OpenAIEmbedding,
model=embedding_model,
max_retries=20,
)
text_embedder = ModelManager().get_or_create_embedding_model(
name="DRIFT_search_embedding",
model_type=ModelType.OpenAIEmbedding,
config=embedding_config,
)
def read_community_reports(
input_dir: str,
community_report_table: str = COMMUNITY_REPORT_TABLE,
):
"""嵌入社区报告的全部内容,并将嵌入的 DataFrame 保存到输出路径。"""
input_path = Path(input_dir) / f"{community_report_table}.parquet"
return pd.read_parquet(input_path)
report_df = read_community_reports(INPUT_DIR)
reports = read_indexer_reports(
report_df,
community_df,
COMMUNITY_LEVEL,
content_embedding_col="full_content_embeddings",
)
read_indexer_report_embeddings(reports, full_content_embedding_store)
drift_params = DRIFTSearchConfig(
temperature=0,
max_tokens=1200,
primer_folds=1,
drift_k_followups=3,
n_depth=3,
n=1,
)
context_builder = DRIFTSearchContextBuilder(
model=chat_model,
text_embedder=text_embedder,
entities=entities,
relationships=relationships,
reports=reports,
entity_text_embeddings=description_embedding_store,
text_units=text_units,
token_encoder=token_encoder,
config=drift_params,
)
search = DRIFTSearch(
model=chat_model, context_builder=context_builder, token_encoder=token_encoder
)
resp = await search.search("百得利集团 企业概况?")
resp.response
print(resp.context_data)
778




被折叠的 条评论
为什么被折叠?



