Skip to content

Commit aa5a863

Browse files
authored
Update app.py
1 parent ea2707c commit aa5a863

File tree

1 file changed

+38
-33
lines changed

1 file changed

+38
-33
lines changed

app.py

+38-33
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@
6262
warnings.filterwarnings("ignore", category=UserWarning, module="gradio_client.documentation")
6363

6464

65-
load_dotenv('ragtest/.env')
65+
load_dotenv('indexing/.env')
6666

6767
# Set default values for API-related environment variables
6868
os.environ.setdefault("LLM_API_BASE", os.getenv("LLM_API_BASE"))
@@ -105,8 +105,8 @@ def initialize_models():
105105
embeddings_api_base = os.getenv("EMBEDDINGS_API_BASE")
106106
embeddings_api_key = os.getenv("EMBEDDINGS_API_KEY")
107107

108-
llm_service_type = os.getenv("LLM_SERVICE_TYPE")
109-
embeddings_service_type = os.getenv("EMBEDDINGS_SERVICE_TYPE")
108+
llm_service_type = os.getenv("LLM_SERVICE_TYPE", "openai_chat").lower() # Provide a default and lower it
109+
embeddings_service_type = os.getenv("EMBEDDINGS_SERVICE_TYPE", "openai").lower() # Provide a default and lower it
110110

111111
llm_model = os.getenv("LLM_MODEL")
112112
embeddings_model = os.getenv("EMBEDDINGS_MODEL")
@@ -119,7 +119,7 @@ def initialize_models():
119119
embeddings_models = models
120120

121121
# Initialize LLM
122-
if llm_service_type.lower() == "openai_chat":
122+
if llm_service_type == "openai_chat":
123123
llm = ChatOpenAI(
124124
api_key=llm_api_key,
125125
api_base=f"{llm_api_base}/v1",
@@ -140,15 +140,15 @@ def initialize_models():
140140
"model": embeddings_model,
141141
"api_type": "open_ai",
142142
"api_base": embeddings_api_base,
143-
"api_key": embeddings_api_key or None, # Change this line
144-
"provider": embeddings_service_type.lower()
143+
"api_key": embeddings_api_key or None,
144+
"provider": embeddings_service_type
145145
}
146146
)
147147

148148
return llm_models, embeddings_models, llm_service_type, embeddings_service_type, llm_api_base, embeddings_api_base, text_embedder
149149

150150
def find_latest_output_folder():
151-
root_dir = "./ragtest/output"
151+
root_dir = "./indexing/output"
152152
folders = [f for f in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, f))]
153153

154154
if not folders:
@@ -251,7 +251,7 @@ def wait_for_api_server(port):
251251

252252
def load_settings():
253253
try:
254-
with open("ragtest/settings.yaml", "r") as f:
254+
with open("indexing/settings.yaml", "r") as f:
255255
return yaml.safe_load(f) or {}
256256
except FileNotFoundError:
257257
return {}
@@ -264,7 +264,7 @@ def update_setting(key, value):
264264
settings[key] = value
265265

266266
try:
267-
with open("ragtest/settings.yaml", "w") as f:
267+
with open("indexing/settings.yaml", "w") as f:
268268
yaml.dump(settings, f, default_flow_style=False)
269269
return f"Setting '{key}' updated successfully"
270270
except Exception as e:
@@ -301,11 +301,14 @@ def get_openai_client():
301301
llm_model = os.getenv("LLM_MODEL")
302302
)
303303

304-
def chat_with_openai(messages, model, temperature, max_tokens, api_base):
304+
async def chat_with_openai(messages, model, temperature, max_tokens, api_base):
305+
client = AsyncOpenAI(
306+
base_url=api_base,
307+
api_key=os.getenv("LLM_API_KEY")
308+
)
309+
305310
try:
306-
logging.info(f"Attempting to use model: {model}")
307-
client = OpenAI(base_url=api_base, api_key=os.getenv("LLM_API_KEY"))
308-
response = client.chat.completions.create(
311+
response = await client.chat.completions.create(
309312
model=model,
310313
messages=messages,
311314
temperature=temperature,
@@ -314,7 +317,7 @@ def chat_with_openai(messages, model, temperature, max_tokens, api_base):
314317
return response.choices[0].message.content
315318
except Exception as e:
316319
logging.error(f"Error in chat_with_openai: {str(e)}")
317-
logging.error(f"Attempted with model: {model}, api_base: {api_base}")
320+
return f"An error occurred: {str(e)}"
318321
return f"Error: {str(e)}"
319322

320323
def chat_with_llm(query, history, system_message, temperature, max_tokens, model, api_base):
@@ -419,7 +422,7 @@ def construct_cli_args(query_type, preset, community_level, response_type, custo
419422
if not selected_folder:
420423
raise ValueError("No folder selected. Please select an output folder before querying.")
421424

422-
artifacts_folder = os.path.join("./ragtest/output", selected_folder, "artifacts")
425+
artifacts_folder = os.path.join("./indexing/output", selected_folder, "artifacts")
423426
if not os.path.exists(artifacts_folder):
424427
raise ValueError(f"Artifacts folder not found in {artifacts_folder}")
425428

@@ -464,7 +467,7 @@ def construct_cli_args(query_type, preset, community_level, response_type, custo
464467

465468
def upload_file(file):
466469
if file is not None:
467-
input_dir = os.path.join("ragtest", "input")
470+
input_dir = os.path.join("indexing", "input")
468471
os.makedirs(input_dir, exist_ok=True)
469472

470473
# Get the original filename from the uploaded file
@@ -487,7 +490,7 @@ def upload_file(file):
487490
return status, gr.update(choices=updated_file_list), update_logs()
488491

489492
def list_input_files():
490-
input_dir = os.path.join("ragtest", "input")
493+
input_dir = os.path.join("indexing", "input")
491494
files = []
492495
if os.path.exists(input_dir):
493496
files = os.listdir(input_dir)
@@ -546,7 +549,7 @@ def save_file_content(file_path, content):
546549
return status, update_logs()
547550

548551
def manage_data():
549-
db = lancedb.connect("./ragtest/lancedb")
552+
db = lancedb.connect("./indexing/lancedb")
550553
tables = db.table_names()
551554
table_info = ""
552555
if tables:
@@ -581,7 +584,7 @@ def find_latest_graph_file(root_dir):
581584
return latest_file
582585

583586
def update_visualization(folder_name, file_name, layout_type, node_size, edge_width, node_color_attribute, color_scheme, show_labels, label_size):
584-
root_dir = "./ragtest"
587+
root_dir = "./indexing"
585588
if not folder_name or not file_name:
586589
return None, "Please select a folder and a GraphML file."
587590
file_name = file_name.split("] ")[1] if "]" in file_name else file_name # Remove file type prefix
@@ -788,7 +791,7 @@ def update_llm_settings(llm_model, embeddings_model, context_window, system_mess
788791
"provider": embeddings_service_type
789792
})
790793

791-
with open("ragtest/settings.yaml", 'w') as f:
794+
with open("indexing/settings.yaml", 'w') as f:
792795
yaml.dump(settings, f, default_flow_style=False)
793796

794797
# Update .env file
@@ -813,7 +816,7 @@ def update_llm_settings(llm_model, embeddings_model, context_window, system_mess
813816
return f"Error updating LLM and embeddings settings: {str(e)}"
814817

815818
def update_env_file(key, value):
816-
env_path = 'ragtest/.env'
819+
env_path = 'indexing/.env'
817820
with open(env_path, 'r') as file:
818821
lines = file.readlines()
819822

@@ -1115,19 +1118,19 @@ def list_folder_contents(folder_path):
11151118
return contents
11161119

11171120
def update_output_folder_list():
1118-
root_dir = "./ragtest"
1121+
root_dir = "./"
11191122
folders = list_output_folders(root_dir)
11201123
return gr.update(choices=folders, value=folders[0] if folders else None)
11211124

11221125
def update_folder_content_list(folder_name):
1123-
root_dir = "./ragtest"
1126+
root_dir = "./"
11241127
if not folder_name:
11251128
return gr.update(choices=[])
11261129
contents = list_folder_contents(os.path.join(root_dir, "output", folder_name, "artifacts"))
11271130
return gr.update(choices=contents)
11281131

11291132
def handle_content_selection(folder_name, selected_item):
1130-
root_dir = "./ragtest"
1133+
root_dir = "./"
11311134
if isinstance(selected_item, list) and selected_item:
11321135
selected_item = selected_item[0] # Take the first item if it's a list
11331136

@@ -1147,7 +1150,7 @@ def handle_content_selection(folder_name, selected_item):
11471150
return gr.update(), "", ""
11481151

11491152
def initialize_selected_folder(folder_name):
1150-
root_dir = "./ragtest"
1153+
root_dir = "./"
11511154
if not folder_name:
11521155
return "Please select a folder first.", gr.update(choices=[])
11531156
folder_path = os.path.join(root_dir, "output", folder_name, "artifacts")
@@ -1194,7 +1197,7 @@ def refresh_indexing():
11941197

11951198

11961199
def run_indexing(root_dir, config_file, verbose, nocache, resume, reporter, emit_formats, custom_args):
1197-
cmd = ["python", "-m", "graphrag.index", "--root", "./ragtest"]
1200+
cmd = ["python", "-m", "graphrag.index", "--root", "./indexing"]
11981201

11991202
# Add custom CLI arguments
12001203
if custom_args:
@@ -1271,6 +1274,7 @@ def run_indexing(root_dir, config_file, verbose, nocache, resume, reporter, emit
12711274
gr.update(interactive=False),
12721275
gr.update(interactive=True),
12731276
str(iterations_completed))
1277+
12741278
global_vector_store_wrapper = None
12751279

12761280
def create_gradio_interface():
@@ -1308,7 +1312,7 @@ def create_gradio_interface():
13081312

13091313

13101314
with gr.TabItem("Indexing"):
1311-
root_dir = gr.Textbox(label="Root Directory", value="./ragtest")
1315+
root_dir = gr.Textbox(label="Root Directory", value="./")
13121316
config_file = gr.File(label="Config File (optional)")
13131317
with gr.Row():
13141318
verbose = gr.Checkbox(label="Verbose", value=True)
@@ -1370,7 +1374,7 @@ def create_gradio_interface():
13701374
)
13711375

13721376
with gr.TabItem("Indexing Outputs/Visuals"):
1373-
output_folder_list = gr.Dropdown(label="Select Output Folder (Select GraphML File to Visualize)", choices=list_output_folders("./ragtest"), interactive=True)
1377+
output_folder_list = gr.Dropdown(label="Select Output Folder (Select GraphML File to Visualize)", choices=list_output_folders("./indexing"), interactive=True)
13741378
refresh_folder_btn = gr.Button("Refresh Folder List", variant="secondary")
13751379
initialize_folder_btn = gr.Button("Initialize Selected Folder", variant="primary")
13761380
folder_content_list = gr.Dropdown(label="Select File or Directory", choices=[], interactive=True)
@@ -1401,14 +1405,14 @@ def create_gradio_interface():
14011405
embeddings_service_type = gr.Radio(
14021406
label="Embeddings Service Type",
14031407
choices=["openai", "ollama"],
1404-
value=settings['embeddings']['llm'].get('type', 'openai'),
1408+
value=settings.get('embeddings', {}).get('llm', {}).get('type', 'openai'),
14051409
visible=False,
14061410
)
14071411

14081412
embeddings_model_dropdown = gr.Dropdown(
14091413
label="Embeddings Model",
14101414
choices=[],
1411-
value=settings['embeddings']['llm'].get('model'),
1415+
value=settings.get('embeddings', {}).get('llm', {}).get('model'),
14121416
allow_custom_value=True
14131417
)
14141418
refresh_embeddings_models_btn = gr.Button("Refresh Embedding Models", variant="secondary")
@@ -1550,7 +1554,7 @@ def create_gradio_interface():
15501554
)
15511555
selected_folder = gr.Dropdown(
15521556
label="Select Index Folder to Chat With",
1553-
choices=list_output_folders("./ragtest"),
1557+
choices=list_output_folders("./indexing"),
15541558
value=None,
15551559
interactive=True
15561560
)
@@ -1626,7 +1630,7 @@ def update_custom_options(preset):
16261630
save_btn.click(fn=save_file_content, inputs=[file_list, file_content], outputs=[operation_status, log_output])
16271631

16281632
refresh_folder_btn.click(
1629-
fn=lambda: gr.update(choices=list_output_folders("./ragtest")),
1633+
fn=lambda: gr.update(choices=list_output_folders("./indexing")),
16301634
outputs=[selected_folder]
16311635
)
16321636

@@ -1755,10 +1759,11 @@ def update_custom_options(preset):
17551759

17561760
return demo.queue()
17571761

1758-
def main():
1762+
async def main():
17591763
api_port = 8088
17601764
gradio_port = 7860
17611765

1766+
17621767
print(f"Starting API server on port {api_port}")
17631768
start_api_server(api_port)
17641769

0 commit comments

Comments
 (0)