forked from noworneverev/graphrag-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
235 lines (206 loc) · 8.57 KB
/
api.py
File metadata and controls
235 lines (206 loc) · 8.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
import tiktoken
from graphrag.query.structured_search.global_search.search import GlobalSearch
from graphrag.query.structured_search.local_search.search import LocalSearch
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.local_search.mixed_context import LocalSearchMixedContext
from graphrag.query.context_builder.entity_extraction import EntityVectorStoreKey
from graphrag.vector_stores.lancedb import LanceDBVectorStore
from graphrag.query.indexer_adapters import (
read_indexer_covariates,
read_indexer_entities,
read_indexer_relationships,
read_indexer_reports,
read_indexer_text_units,
)
from graphrag.query.input.loaders.dfs import (
store_entity_semantic_embeddings,
)
from graphrag.query.llm.oai.embedding import OpenAIEmbedding
from dotenv import load_dotenv
from utils import convert_response_to_string, process_context_data, serialize_search_result
from settings import load_settings_from_yaml
from constants import (
COMMUNITY_REPORT_TABLE,
ENTITY_TABLE,
ENTITY_EMBEDDING_TABLE,
RELATIONSHIP_TABLE,
COVARIATE_TABLE,
TEXT_UNIT_TABLE,
)
_ = load_dotenv()
settings = load_settings_from_yaml("settings.yml")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "https://noworneverev.github.io"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load environment variables
api_key = settings.GRAPHRAG_API_KEY
llm_api_base = settings.GRAPHRAG_LLM_API_BASE
embedding_api_base = settings.GRAPHRAG_EMBEDDING_API_BASE
llm_model = settings.GRAPHRAG_LLM_MODEL
embedding_model = settings.GRAPHRAG_EMBEDDING_MODEL
claim_extraction_enabled = settings.GRAPHRAG_CLAIM_EXTRACTION_ENABLED
llm = ChatOpenAI(
model = llm_model,
api_key = api_key,
api_type = OpenaiApiType.OpenAI,
api_base = llm_api_base,
max_retries=20,
)
token_encoder = tiktoken.get_encoding("cl100k_base")
INPUT_DIR = settings.INPUT_DIR
COMMUNITY_LEVEL = settings.COMMUNITY_LEVEL
def load_parquet_files():
entity_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_TABLE}.parquet")
entity_embedding_df = pd.read_parquet(f"{INPUT_DIR}/{ENTITY_EMBEDDING_TABLE}.parquet")
report_df = pd.read_parquet(f"{INPUT_DIR}/{COMMUNITY_REPORT_TABLE}.parquet")
relationship_df = pd.read_parquet(f"{INPUT_DIR}/{RELATIONSHIP_TABLE}.parquet")
covariate_df = pd.read_parquet(f"{INPUT_DIR}/{COVARIATE_TABLE}.parquet") if claim_extraction_enabled else pd.DataFrame()
text_unit_df = pd.read_parquet(f"{INPUT_DIR}/{TEXT_UNIT_TABLE}.parquet")
return entity_df, entity_embedding_df, report_df, relationship_df, covariate_df, text_unit_df
entity_df, entity_embedding_df, report_df, relationship_df, covariate_df, text_unit_df = load_parquet_files()
def setup_global_search():
entities = read_indexer_entities(entity_df, entity_embedding_df, COMMUNITY_LEVEL)
reports = read_indexer_reports(report_df, entity_df, COMMUNITY_LEVEL)
context_builder = GlobalCommunityContext(
community_reports=reports,
entities=entities,
token_encoder=token_encoder,
)
search_engine = GlobalSearch(
llm=llm,
context_builder=context_builder,
token_encoder=token_encoder,
max_data_tokens=12_000,
map_llm_params={
"max_tokens": 1000,
"temperature": 0.0,
"response_format": {"type": "json_object"},
},
reduce_llm_params={
"max_tokens": 2000,
"temperature": 0.0,
},
allow_general_knowledge=False,
json_mode=True,
context_builder_params={
"use_community_summary": False,
"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,
"context_name": "Reports",
},
concurrent_coroutines=32,
response_type="single paragraph",
)
return search_engine
def setup_local_search():
entities = read_indexer_entities(entity_df, entity_embedding_df, COMMUNITY_LEVEL)
relationships = read_indexer_relationships(relationship_df)
claims = read_indexer_covariates(covariate_df) if claim_extraction_enabled else []
reports = read_indexer_reports(report_df, entity_df, COMMUNITY_LEVEL)
text_units = read_indexer_text_units(text_unit_df)
description_embedding_store = LanceDBVectorStore(
collection_name="entity_description_embeddings",
)
description_embedding_store.connect(db_uri=f"{INPUT_DIR}/lancedb")
store_entity_semantic_embeddings(entities=entities, vectorstore=description_embedding_store)
context_builder = LocalSearchMixedContext(
community_reports=reports,
text_units=text_units,
entities=entities,
relationships=relationships,
covariates={"claims": claims} if claim_extraction_enabled else None,
entity_text_embeddings=description_embedding_store,
embedding_vectorstore_key=EntityVectorStoreKey.ID,
text_embedder=OpenAIEmbedding(
api_key=api_key,
api_base=embedding_api_base,
api_type=OpenaiApiType.OpenAI,
model=embedding_model,
deployment_name=embedding_model,
max_retries=20,
),
token_encoder=token_encoder,
)
search_engine = LocalSearch(
llm=llm,
context_builder=context_builder,
token_encoder=token_encoder,
llm_params={
"max_tokens": 2_000,
"temperature": 0.0,
},
context_builder_params={
"text_unit_prop": 0.5,
"community_prop": 0.1,
"conversation_history_max_turns": 5,
"conversation_history_user_turns_only": True,
"top_k_mapped_entities": 10,
"top_k_relationships": 10,
"include_entity_rank": True,
"include_relationship_weight": True,
"include_community_rank": False,
"return_candidate_context": False,
"embedding_vectorstore_key": EntityVectorStoreKey.ID,
"max_tokens": 12_000,
},
response_type="single paragraph",
)
return search_engine
global_search_engine = setup_global_search()
local_search_engine = setup_local_search()
@app.get("/search/global")
async def global_search(query: str = Query(..., description="Search query for global context")):
try:
result = await global_search_engine.asearch(query)
response_dict = {
"response": convert_response_to_string(result.response),
"context_data": process_context_data(result.context_data),
"context_text": result.context_text,
"completion_time": result.completion_time,
"llm_calls": result.llm_calls,
"prompt_tokens": result.prompt_tokens,
"reduce_context_data": process_context_data(result.reduce_context_data),
"reduce_context_text": result.reduce_context_text,
"map_responses": [serialize_search_result(result) for result in result.map_responses],
}
return JSONResponse(content=response_dict)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/search/local")
async def local_search(query: str = Query(..., description="Search query for local context")):
try:
result = await local_search_engine.asearch(query)
response_dict = {
"response": convert_response_to_string(result.response),
"context_data": process_context_data(result.context_data),
"context_text": result.context_text,
"completion_time": result.completion_time,
"llm_calls": result.llm_calls,
"prompt_tokens": result.prompt_tokens,
}
return JSONResponse(content=response_dict)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/status")
async def status():
return JSONResponse(content={"status": "Server is up and running"})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)