-
Notifications
You must be signed in to change notification settings - Fork 200
/
app.py
1786 lines (1501 loc) · 67.6 KB
/
app.py
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gradio as gr
from gradio.helpers import Progress
import asyncio
import subprocess
import yaml
import os
import networkx as nx
import plotly.graph_objects as go
import numpy as np
import plotly.io as pio
import lancedb
import random
import io
import shutil
import logging
import queue
import threading
import time
from collections import deque
import re
import glob
from datetime import datetime
import json
import requests
import aiohttp
from openai import OpenAI
from openai import AsyncOpenAI
import pyarrow.parquet as pq
import pandas as pd
import sys
import colorsys
from dotenv import load_dotenv, set_key
import argparse
import socket
import tiktoken
from graphrag.query.context_builder.entity_extraction import EntityVectorStoreKey
from graphrag.query.indexer_adapters import (
read_indexer_covariates,
read_indexer_entities,
read_indexer_relationships,
read_indexer_reports,
read_indexer_text_units,
)
from graphrag.llm.openai import create_openai_chat_llm
from graphrag.llm.openai.factories import create_openai_embedding_llm
from graphrag.query.input.loaders.dfs import store_entity_semantic_embeddings
from graphrag.query.llm.oai.chat_openai import ChatOpenAI
from graphrag.llm.openai.openai_configuration import OpenAIConfiguration
from graphrag.llm.openai.openai_embeddings_llm import OpenAIEmbeddingsLLM
from graphrag.query.llm.oai.typing import OpenaiApiType
from graphrag.query.structured_search.local_search.mixed_context import LocalSearchMixedContext
from graphrag.query.structured_search.local_search.search import LocalSearch
from graphrag.query.structured_search.global_search.community_context import GlobalCommunityContext
from graphrag.query.structured_search.global_search.search import GlobalSearch
from graphrag.vector_stores.lancedb import LanceDBVectorStore
import textwrap
# Suppress warnings
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="gradio_client.documentation")
load_dotenv('indexing/.env')
# Set default values for API-related environment variables
os.environ.setdefault("LLM_API_BASE", os.getenv("LLM_API_BASE"))
os.environ.setdefault("LLM_API_KEY", os.getenv("LLM_API_KEY"))
os.environ.setdefault("LLM_MODEL", os.getenv("LLM_MODEL"))
os.environ.setdefault("EMBEDDINGS_API_BASE", os.getenv("EMBEDDINGS_API_BASE"))
os.environ.setdefault("EMBEDDINGS_API_KEY", os.getenv("EMBEDDINGS_API_KEY"))
os.environ.setdefault("EMBEDDINGS_MODEL", os.getenv("EMBEDDINGS_MODEL"))
# Add the project root to the Python path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, project_root)
# Set up logging
log_queue = queue.Queue()
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
llm = None
text_embedder = None
class QueueHandler(logging.Handler):
def __init__(self, log_queue):
super().__init__()
self.log_queue = log_queue
def emit(self, record):
self.log_queue.put(self.format(record))
queue_handler = QueueHandler(log_queue)
logging.getLogger().addHandler(queue_handler)
def initialize_models():
global llm, text_embedder
llm_api_base = os.getenv("LLM_API_BASE")
llm_api_key = os.getenv("LLM_API_KEY")
embeddings_api_base = os.getenv("EMBEDDINGS_API_BASE")
embeddings_api_key = os.getenv("EMBEDDINGS_API_KEY")
llm_service_type = os.getenv("LLM_SERVICE_TYPE", "openai_chat").lower() # Provide a default and lower it
embeddings_service_type = os.getenv("EMBEDDINGS_SERVICE_TYPE", "openai").lower() # Provide a default and lower it
llm_model = os.getenv("LLM_MODEL")
embeddings_model = os.getenv("EMBEDDINGS_MODEL")
logging.info("Fetching models...")
models = fetch_models(llm_api_base, llm_api_key, llm_service_type)
# Use the same models list for both LLM and embeddings
llm_models = models
embeddings_models = models
# Initialize LLM
if llm_service_type == "openai_chat":
llm = ChatOpenAI(
api_key=llm_api_key,
api_base=f"{llm_api_base}/v1",
model=llm_model,
api_type=OpenaiApiType.OpenAI,
max_retries=20,
)
# Initialize OpenAI client for embeddings
openai_client = OpenAI(
api_key=embeddings_api_key or "dummy_key",
base_url=f"{embeddings_api_base}/v1"
)
# Initialize text embedder using OpenAIEmbeddingsLLM
text_embedder = OpenAIEmbeddingsLLM(
client=openai_client,
configuration={
"model": embeddings_model,
"api_type": "open_ai",
"api_base": embeddings_api_base,
"api_key": embeddings_api_key or None,
"provider": embeddings_service_type
}
)
return llm_models, embeddings_models, llm_service_type, embeddings_service_type, llm_api_base, embeddings_api_base, text_embedder
def find_latest_output_folder():
root_dir = "./indexing/output"
folders = [f for f in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, f))]
if not folders:
raise ValueError("No output folders found")
# Sort folders by creation time, most recent first
sorted_folders = sorted(folders, key=lambda x: os.path.getctime(os.path.join(root_dir, x)), reverse=True)
latest_folder = None
timestamp = None
for folder in sorted_folders:
try:
# Try to parse the folder name as a timestamp
timestamp = datetime.strptime(folder, "%Y%m%d-%H%M%S")
latest_folder = folder
break
except ValueError:
# If the folder name is not a valid timestamp, skip it
continue
if latest_folder is None:
raise ValueError("No valid timestamp folders found")
latest_path = os.path.join(root_dir, latest_folder)
artifacts_path = os.path.join(latest_path, "artifacts")
if not os.path.exists(artifacts_path):
raise ValueError(f"Artifacts folder not found in {latest_path}")
return latest_path, latest_folder
def initialize_data():
global entity_df, relationship_df, text_unit_df, report_df, covariate_df
tables = {
"entity_df": "create_final_nodes",
"relationship_df": "create_final_edges",
"text_unit_df": "create_final_text_units",
"report_df": "create_final_reports",
"covariate_df": "create_final_covariates"
}
timestamp = None # Initialize timestamp to None
try:
latest_output_folder, timestamp = find_latest_output_folder()
artifacts_folder = os.path.join(latest_output_folder, "artifacts")
for df_name, file_prefix in tables.items():
file_pattern = os.path.join(artifacts_folder, f"{file_prefix}*.parquet")
matching_files = glob.glob(file_pattern)
if matching_files:
latest_file = max(matching_files, key=os.path.getctime)
df = pd.read_parquet(latest_file)
globals()[df_name] = df
logging.info(f"Successfully loaded {df_name} from {latest_file}")
else:
logging.warning(f"No matching file found for {df_name} in {artifacts_folder}. Initializing as an empty DataFrame.")
globals()[df_name] = pd.DataFrame()
except Exception as e:
logging.error(f"Error initializing data: {str(e)}")
for df_name in tables.keys():
globals()[df_name] = pd.DataFrame()
return timestamp
# Call initialize_data and store the timestamp
current_timestamp = initialize_data()
def find_available_port(start_port, max_attempts=100):
for port in range(start_port, start_port + max_attempts):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(('', port))
return port
except OSError:
continue
raise IOError("No free ports found")
def start_api_server(port):
subprocess.Popen([sys.executable, "api_server.py", "--port", str(port)])
def wait_for_api_server(port):
max_retries = 30
for _ in range(max_retries):
try:
response = requests.get(f"http://localhost:{port}")
if response.status_code == 200:
print(f"API server is up and running on port {port}")
return
else:
print(f"Unexpected response from API server: {response.status_code}")
except requests.ConnectionError:
time.sleep(1)
print("Failed to connect to API server")
def load_settings():
try:
with open("indexing/settings.yaml", "r") as f:
return yaml.safe_load(f) or {}
except FileNotFoundError:
return {}
def update_setting(key, value):
settings = load_settings()
try:
settings[key] = json.loads(value)
except json.JSONDecodeError:
settings[key] = value
try:
with open("indexing/settings.yaml", "w") as f:
yaml.dump(settings, f, default_flow_style=False)
return f"Setting '{key}' updated successfully"
except Exception as e:
return f"Error updating setting '{key}': {str(e)}"
def create_setting_component(key, value):
with gr.Accordion(key, open=False):
if isinstance(value, (dict, list)):
value_str = json.dumps(value, indent=2)
lines = value_str.count('\n') + 1
else:
value_str = str(value)
lines = 1
text_area = gr.TextArea(value=value_str, label="Value", lines=lines, max_lines=20)
update_btn = gr.Button("Update", variant="primary")
status = gr.Textbox(label="Status", visible=False)
update_btn.click(
fn=update_setting,
inputs=[gr.Textbox(value=key, visible=False), text_area],
outputs=[status]
).then(
fn=lambda: gr.update(visible=True),
outputs=[status]
)
def get_openai_client():
return OpenAI(
base_url=os.getenv("LLM_API_BASE"),
api_key=os.getenv("LLM_API_KEY"),
llm_model = os.getenv("LLM_MODEL")
)
async def chat_with_openai(messages, model, temperature, max_tokens, api_base):
client = AsyncOpenAI(
base_url=api_base,
api_key=os.getenv("LLM_API_KEY")
)
try:
response = await client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens
)
return response.choices[0].message.content
except Exception as e:
logging.error(f"Error in chat_with_openai: {str(e)}")
return f"An error occurred: {str(e)}"
return f"Error: {str(e)}"
def chat_with_llm(query, history, system_message, temperature, max_tokens, model, api_base):
try:
messages = [{"role": "system", "content": system_message}]
for item in history:
if isinstance(item, tuple) and len(item) == 2:
human, ai = item
messages.append({"role": "user", "content": human})
messages.append({"role": "assistant", "content": ai})
messages.append({"role": "user", "content": query})
logging.info(f"Sending chat request to {api_base} with model {model}")
client = OpenAI(base_url=api_base, api_key=os.getenv("LLM_API_KEY", "dummy-key"))
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens
)
return response.choices[0].message.content
except Exception as e:
logging.error(f"Error in chat_with_llm: {str(e)}")
logging.error(f"Attempted with model: {model}, api_base: {api_base}")
raise RuntimeError(f"Chat request failed: {str(e)}")
def run_graphrag_query(cli_args):
try:
command = ' '.join(cli_args)
logging.info(f"Executing command: {command}")
result = subprocess.run(cli_args, capture_output=True, text=True, check=True)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
logging.error(f"Error running GraphRAG query: {e}")
logging.error(f"Command output (stdout): {e.stdout}")
logging.error(f"Command output (stderr): {e.stderr}")
raise RuntimeError(f"GraphRAG query failed: {e.stderr}")
def parse_query_response(response: str):
try:
# Split the response into metadata and content
parts = response.split("\n\n", 1)
if len(parts) < 2:
return response # Return original response if it doesn't contain metadata
metadata_str, content = parts
metadata = json.loads(metadata_str)
# Extract relevant information from metadata
query_type = metadata.get("query_type", "Unknown")
execution_time = metadata.get("execution_time", "N/A")
tokens_used = metadata.get("tokens_used", "N/A")
# Remove unwanted lines from the content
content_lines = content.split('\n')
filtered_content = '\n'.join([line for line in content_lines if not line.startswith("INFO:") and not line.startswith("creating llm client")])
# Format the parsed response
parsed_response = f"""
Query Type: {query_type}
Execution Time: {execution_time} seconds
Tokens Used: {tokens_used}
{filtered_content.strip()}
"""
return parsed_response
except Exception as e:
print(f"Error parsing query response: {str(e)}")
return response
def send_message(query_type, query, history, system_message, temperature, max_tokens, preset, community_level, response_type, custom_cli_args, selected_folder):
try:
if query_type in ["global", "local"]:
cli_args = construct_cli_args(query_type, preset, community_level, response_type, custom_cli_args, query, selected_folder)
logging.info(f"Executing {query_type} search with command: {' '.join(cli_args)}")
result = run_graphrag_query(cli_args)
parsed_result = parse_query_response(result)
logging.info(f"Parsed query result: {parsed_result}")
else: # Direct chat
llm_model = os.getenv("LLM_MODEL")
api_base = os.getenv("LLM_API_BASE")
logging.info(f"Executing direct chat with model: {llm_model}")
try:
result = chat_with_llm(query, history, system_message, temperature, max_tokens, llm_model, api_base)
parsed_result = result # No parsing needed for direct chat
logging.info(f"Direct chat result: {parsed_result[:100]}...") # Log first 100 chars of result
except Exception as chat_error:
logging.error(f"Error in chat_with_llm: {str(chat_error)}")
raise RuntimeError(f"Direct chat failed: {str(chat_error)}")
history.append((query, parsed_result))
except Exception as e:
error_message = f"An error occurred: {str(e)}"
logging.error(error_message)
logging.exception("Exception details:")
history.append((query, error_message))
return history, gr.update(value=""), update_logs()
def construct_cli_args(query_type, preset, community_level, response_type, custom_cli_args, query, selected_folder):
if not selected_folder:
raise ValueError("No folder selected. Please select an output folder before querying.")
artifacts_folder = os.path.join("./indexing/output", selected_folder, "artifacts")
if not os.path.exists(artifacts_folder):
raise ValueError(f"Artifacts folder not found in {artifacts_folder}")
base_args = [
"python", "-m", "graphrag.query",
"--data", artifacts_folder,
"--method", query_type,
]
# Apply preset configurations
if preset.startswith("Default"):
base_args.extend(["--community_level", "2", "--response_type", "Multiple Paragraphs"])
elif preset.startswith("Detailed"):
base_args.extend(["--community_level", "4", "--response_type", "Multi-Page Report"])
elif preset.startswith("Quick"):
base_args.extend(["--community_level", "1", "--response_type", "Single Paragraph"])
elif preset.startswith("Bullet"):
base_args.extend(["--community_level", "2", "--response_type", "List of 3-7 Points"])
elif preset.startswith("Comprehensive"):
base_args.extend(["--community_level", "5", "--response_type", "Multi-Page Report"])
elif preset.startswith("High-Level"):
base_args.extend(["--community_level", "1", "--response_type", "Single Page"])
elif preset.startswith("Focused"):
base_args.extend(["--community_level", "3", "--response_type", "Multiple Paragraphs"])
elif preset == "Custom Query":
base_args.extend([
"--community_level", str(community_level),
"--response_type", f'"{response_type}"',
])
if custom_cli_args:
base_args.extend(custom_cli_args.split())
# Add the query at the end
base_args.append(query)
return base_args
def upload_file(file):
if file is not None:
input_dir = os.path.join("indexing", "input")
os.makedirs(input_dir, exist_ok=True)
# Get the original filename from the uploaded file
original_filename = file.name
# Create the destination path
destination_path = os.path.join(input_dir, os.path.basename(original_filename))
# Move the uploaded file to the destination path
shutil.move(file.name, destination_path)
logging.info(f"File uploaded and moved to: {destination_path}")
status = f"File uploaded: {os.path.basename(original_filename)}"
else:
status = "No file uploaded"
# Get the updated file list
updated_file_list = [f["path"] for f in list_input_files()]
return status, gr.update(choices=updated_file_list), update_logs()
def list_input_files():
input_dir = os.path.join("indexing", "input")
files = []
if os.path.exists(input_dir):
files = os.listdir(input_dir)
return [{"name": f, "path": os.path.join(input_dir, f)} for f in files]
def delete_file(file_path):
try:
os.remove(file_path)
logging.info(f"File deleted: {file_path}")
status = f"File deleted: {os.path.basename(file_path)}"
except Exception as e:
logging.error(f"Error deleting file: {str(e)}")
status = f"Error deleting file: {str(e)}"
# Get the updated file list
updated_file_list = [f["path"] for f in list_input_files()]
return status, gr.update(choices=updated_file_list), update_logs()
def read_file_content(file_path):
try:
if file_path.endswith('.parquet'):
df = pd.read_parquet(file_path)
# Get basic information about the DataFrame
info = f"Parquet File: {os.path.basename(file_path)}\n"
info += f"Rows: {len(df)}, Columns: {len(df.columns)}\n\n"
info += "Column Names:\n" + "\n".join(df.columns) + "\n\n"
# Display first few rows
info += "First 5 rows:\n"
info += df.head().to_string() + "\n\n"
# Display basic statistics
info += "Basic Statistics:\n"
info += df.describe().to_string()
return info
else:
with open(file_path, 'r', encoding='utf-8', errors='replace') as file:
content = file.read()
return content
except Exception as e:
logging.error(f"Error reading file: {str(e)}")
return f"Error reading file: {str(e)}"
def save_file_content(file_path, content):
try:
with open(file_path, 'w') as file:
file.write(content)
logging.info(f"File saved: {file_path}")
status = f"File saved: {os.path.basename(file_path)}"
except Exception as e:
logging.error(f"Error saving file: {str(e)}")
status = f"Error saving file: {str(e)}"
return status, update_logs()
def manage_data():
db = lancedb.connect("./indexing/lancedb")
tables = db.table_names()
table_info = ""
if tables:
table = db[tables[0]]
table_info = f"Table: {tables[0]}\nSchema: {table.schema}"
input_files = list_input_files()
return {
"database_info": f"Tables: {', '.join(tables)}\n\n{table_info}",
"input_files": input_files
}
def find_latest_graph_file(root_dir):
pattern = os.path.join(root_dir, "output", "*", "artifacts", "*.graphml")
graph_files = glob.glob(pattern)
if not graph_files:
# If no files found, try excluding .DS_Store
output_dir = os.path.join(root_dir, "output")
run_dirs = [d for d in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, d)) and d != ".DS_Store"]
if run_dirs:
latest_run = max(run_dirs)
pattern = os.path.join(root_dir, "output", latest_run, "artifacts", "*.graphml")
graph_files = glob.glob(pattern)
if not graph_files:
return None
# Sort files by modification time, most recent first
latest_file = max(graph_files, key=os.path.getmtime)
return latest_file
def update_visualization(folder_name, file_name, layout_type, node_size, edge_width, node_color_attribute, color_scheme, show_labels, label_size):
root_dir = "./indexing"
if not folder_name or not file_name:
return None, "Please select a folder and a GraphML file."
file_name = file_name.split("] ")[1] if "]" in file_name else file_name # Remove file type prefix
graph_path = os.path.join(root_dir, "output", folder_name, "artifacts", file_name)
if not graph_path.endswith('.graphml'):
return None, "Please select a GraphML file for visualization."
try:
# Load the GraphML file
graph = nx.read_graphml(graph_path)
# Create layout based on user selection
if layout_type == "3D Spring":
pos = nx.spring_layout(graph, dim=3, seed=42, k=0.5)
elif layout_type == "2D Spring":
pos = nx.spring_layout(graph, dim=2, seed=42, k=0.5)
else: # Circular
pos = nx.circular_layout(graph)
# Extract node positions
if layout_type == "3D Spring":
x_nodes = [pos[node][0] for node in graph.nodes()]
y_nodes = [pos[node][1] for node in graph.nodes()]
z_nodes = [pos[node][2] for node in graph.nodes()]
else:
x_nodes = [pos[node][0] for node in graph.nodes()]
y_nodes = [pos[node][1] for node in graph.nodes()]
z_nodes = [0] * len(graph.nodes()) # Set all z-coordinates to 0 for 2D layouts
# Extract edge positions
x_edges, y_edges, z_edges = [], [], []
for edge in graph.edges():
x_edges.extend([pos[edge[0]][0], pos[edge[1]][0], None])
y_edges.extend([pos[edge[0]][1], pos[edge[1]][1], None])
if layout_type == "3D Spring":
z_edges.extend([pos[edge[0]][2], pos[edge[1]][2], None])
else:
z_edges.extend([0, 0, None])
# Generate node colors based on user selection
if node_color_attribute == "Degree":
node_colors = [graph.degree(node) for node in graph.nodes()]
else: # Random
node_colors = [random.random() for _ in graph.nodes()]
node_colors = np.array(node_colors)
node_colors = (node_colors - node_colors.min()) / (node_colors.max() - node_colors.min())
# Create the trace for edges
edge_trace = go.Scatter3d(
x=x_edges, y=y_edges, z=z_edges,
mode='lines',
line=dict(color='lightgray', width=edge_width),
hoverinfo='none'
)
# Create the trace for nodes
node_trace = go.Scatter3d(
x=x_nodes, y=y_nodes, z=z_nodes,
mode='markers+text' if show_labels else 'markers',
marker=dict(
size=node_size,
color=node_colors,
colorscale=color_scheme,
colorbar=dict(
title='Node Degree' if node_color_attribute == "Degree" else "Random Value",
thickness=10,
x=1.1,
tickvals=[0, 1],
ticktext=['Low', 'High']
),
line=dict(width=1)
),
text=[node for node in graph.nodes()],
textposition="top center",
textfont=dict(size=label_size, color='black'),
hoverinfo='text'
)
# Create the plot
fig = go.Figure(data=[edge_trace, node_trace])
# Update layout for better visualization
fig.update_layout(
title=f'{layout_type} Graph Visualization: {os.path.basename(graph_path)}',
showlegend=False,
scene=dict(
xaxis=dict(showbackground=False, showticklabels=False, title=''),
yaxis=dict(showbackground=False, showticklabels=False, title=''),
zaxis=dict(showbackground=False, showticklabels=False, title='')
),
margin=dict(l=0, r=0, b=0, t=40),
annotations=[
dict(
showarrow=False,
text=f"Interactive {layout_type} visualization of GraphML data",
xref="paper",
yref="paper",
x=0,
y=0
)
],
autosize=True
)
fig.update_layout(autosize=True)
fig.update_layout(height=600) # Set a fixed height
return fig, f"Graph visualization generated successfully. Using file: {graph_path}"
except Exception as e:
return go.Figure(), f"Error visualizing graph: {str(e)}"
def update_logs():
logs = []
while not log_queue.empty():
logs.append(log_queue.get())
return "\n".join(logs)
def fetch_models(base_url, api_key, service_type):
try:
if service_type.lower() == "ollama":
response = requests.get(f"{base_url}/tags", timeout=10)
else: # OpenAI Compatible
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
response = requests.get(f"{base_url}/models", headers=headers, timeout=10)
logging.info(f"Raw API response: {response.text}")
if response.status_code == 200:
data = response.json()
if service_type.lower() == "ollama":
models = [model.get('name', '') for model in data.get('models', data) if isinstance(model, dict)]
else: # OpenAI Compatible
models = [model.get('id', '') for model in data.get('data', []) if isinstance(model, dict)]
models = [model for model in models if model] # Remove empty strings
if not models:
logging.warning(f"No models found in {service_type} API response")
return ["No models available"]
logging.info(f"Successfully fetched {service_type} models: {models}")
return models
else:
logging.error(f"Error fetching {service_type} models. Status code: {response.status_code}, Response: {response.text}")
return ["Error fetching models"]
except requests.RequestException as e:
logging.error(f"Exception while fetching {service_type} models: {str(e)}")
return ["Error: Connection failed"]
except Exception as e:
logging.error(f"Unexpected error in fetch_models: {str(e)}")
return ["Error: Unexpected issue"]
def update_model_choices(base_url, api_key, service_type, settings_key):
models = fetch_models(base_url, api_key, service_type)
if not models:
logging.warning(f"No models fetched for {service_type}.")
# Get the current model from settings
current_model = settings.get(settings_key, {}).get('llm', {}).get('model')
# If the current model is not in the list, add it
if current_model and current_model not in models:
models.append(current_model)
return gr.update(choices=models, value=current_model if current_model in models else (models[0] if models else None))
def update_llm_model_choices(base_url, api_key, service_type):
return update_model_choices(base_url, api_key, service_type, 'llm')
def update_embeddings_model_choices(base_url, api_key, service_type):
return update_model_choices(base_url, api_key, service_type, 'embeddings')
def update_llm_settings(llm_model, embeddings_model, context_window, system_message, temperature, max_tokens,
llm_api_base, llm_api_key,
embeddings_api_base, embeddings_api_key, embeddings_service_type):
try:
# Update settings.yaml
settings = load_settings()
settings['llm'].update({
"type": "openai", # Always set to "openai" since we removed the radio button
"model": llm_model,
"api_base": llm_api_base,
"api_key": "${GRAPHRAG_API_KEY}",
"temperature": temperature,
"max_tokens": max_tokens,
"provider": "openai_chat" # Always set to "openai_chat"
})
settings['embeddings']['llm'].update({
"type": "openai_embedding", # Always use OpenAIEmbeddingsLLM
"model": embeddings_model,
"api_base": embeddings_api_base,
"api_key": "${GRAPHRAG_API_KEY}",
"provider": embeddings_service_type
})
with open("indexing/settings.yaml", 'w') as f:
yaml.dump(settings, f, default_flow_style=False)
# Update .env file
update_env_file("LLM_API_BASE", llm_api_base)
update_env_file("LLM_API_KEY", llm_api_key)
update_env_file("LLM_MODEL", llm_model)
update_env_file("EMBEDDINGS_API_BASE", embeddings_api_base)
update_env_file("EMBEDDINGS_API_KEY", embeddings_api_key)
update_env_file("EMBEDDINGS_MODEL", embeddings_model)
update_env_file("CONTEXT_WINDOW", str(context_window))
update_env_file("SYSTEM_MESSAGE", system_message)
update_env_file("TEMPERATURE", str(temperature))
update_env_file("MAX_TOKENS", str(max_tokens))
update_env_file("LLM_SERVICE_TYPE", "openai_chat")
update_env_file("EMBEDDINGS_SERVICE_TYPE", embeddings_service_type)
# Reload environment variables
load_dotenv(override=True)
return "LLM and embeddings settings updated successfully in both settings.yaml and .env files."
except Exception as e:
return f"Error updating LLM and embeddings settings: {str(e)}"
def update_env_file(key, value):
env_path = 'indexing/.env'
with open(env_path, 'r') as file:
lines = file.readlines()
updated = False
for i, line in enumerate(lines):
if line.startswith(f"{key}="):
lines[i] = f"{key}={value}\n"
updated = True
break
if not updated:
lines.append(f"{key}={value}\n")
with open(env_path, 'w') as file:
file.writelines(lines)
custom_css = """
html, body {
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
}
.gradio-container {
margin: 0 !important;
padding: 0 !important;
width: 100vw !important;
max-width: 100vw !important;
height: 100vh !important;
max-height: 100vh !important;
overflow: auto;
display: flex;
flex-direction: column;
}
#main-container {
flex: 1;
display: flex;
overflow: hidden;
}
#left-column, #right-column {
height: 100%;
overflow-y: auto;
padding: 10px;
}
#left-column {
flex: 1;
}
#right-column {
flex: 2;
display: flex;
flex-direction: column;
}
#chat-container {
flex: 0 0 auto; /* Don't allow this to grow */
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--color-accent);
border-radius: 8px;
padding: 10px;
overflow-y: auto;
}
#chatbot {
overflow-y: hidden;
height: 100%;
}
#chat-input-row {
margin-top: 10px;
}
#visualization-plot {
width: 100%;
aspect-ratio: 1 / 1;
max-height: 600px; /* Adjust this value as needed */
}
#vis-controls-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 10px;
}
#vis-controls-row > * {
flex: 1;
margin: 0 5px;
}
#vis-status {
margin-top: 10px;
}
/* Chat input styling */
#chat-input-row {
display: flex;
flex-direction: column;
}
#chat-input-row > div {
width: 100% !important;
}
#chat-input-row input[type="text"] {
width: 100% !important;
}
/* Adjust padding for all containers */
.gr-box, .gr-form, .gr-panel {
padding: 10px !important;
}
/* Ensure all textboxes and textareas have full height */
.gr-textbox, .gr-textarea {
height: auto !important;
min-height: 100px !important;
}
/* Ensure all dropdowns have full width */
.gr-dropdown {
width: 100% !important;
}
:root {
--color-background: #2C3639;
--color-foreground: #3F4E4F;
--color-accent: #A27B5C;
--color-text: #DCD7C9;
}
body, .gradio-container {
background-color: var(--color-background);
color: var(--color-text);
}
.gr-button {
background-color: var(--color-accent);
color: var(--color-text);
}
.gr-input, .gr-textarea, .gr-dropdown {
background-color: var(--color-foreground);
color: var(--color-text);
border: 1px solid var(--color-accent);
}
.gr-panel {
background-color: var(--color-foreground);
border: 1px solid var(--color-accent);
}
.gr-box {
border-radius: 8px;
margin-bottom: 10px;
background-color: var(--color-foreground);
}
.gr-padded {
padding: 10px;
}
.gr-form {
background-color: var(--color-foreground);
}
.gr-input-label, .gr-radio-label {
color: var(--color-text);
}
.gr-checkbox-label {
color: var(--color-text);
}