Repository navigation
Expand file tree
/
Copy pathweb_ai_researcher.py
More file actions
1562 lines (1281 loc) · 69.7 KB
/
Copy pathweb_ai_researcher.py
File metadata and controls
1562 lines (1281 loc) · 69.7 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
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
from main_ai_researcher import main_ai_researcher
import os
import gradio as gr
import time
import logging
import datetime
from typing import Tuple
from dotenv import load_dotenv, set_key, find_dotenv, unset_key
import threading
import queue
import global_state
import base64
os.environ["PYTHONIOENCODING"] = "utf-8"
# If you want to use proxy, please uncomment the following lines
os.environ['https_proxy'] = 'http://100.68.161.73:3128'
os.environ['http_proxy'] = 'http://100.68.161.73:3128'
os.environ['no_proxy'] = 'localhost,127.0.0.1,0.0.0.0'
def setup_path():
# logs_dir = os.path.join("casestudy_results", f'agent_{container_name}', 'logs')
logs_dir = os.path.join("casestudy_results", 'agent', 'logs')
os.makedirs(logs_dir, exist_ok=True)
# 生成日志文件名(使用当前日期)
current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# current_date = datetime.datetime.now().strftime("%Y-%m-%d")
log_file = os.path.join(logs_dir, f"gradio_log_{current_date}.log")
return log_file
# 配置日志系统
def setup_logging():
logs_dir = os.path.join(os.path.dirname(__file__), "logs")
os.makedirs(logs_dir, exist_ok=True)
current_date = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
log_file = os.path.join(logs_dir, f"log_{current_date}.log")
global_state.LOG_PATH = log_file
root_logger = logging.getLogger()
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
root_logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(log_file, encoding="utf-8", mode="a")
file_handler.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
logging.info("Logging system initialized, log file: %s", log_file)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("LiteLLM").setLevel(logging.WARNING)
return log_file
def return_log_file():
return LOG_FILE
def return_paper_file():
category = os.getenv("CATEGORY")
instance_id = os.getenv("INSTANCE_ID")
global PAPER_FILE
PAPER_FILE = f'{category}/target_sections/{instance_id}/iclr2025_conference.pdf'
return PAPER_FILE
def get_base64_image(image_path):
with open(image_path, "rb") as image_file:
encoded = base64.b64encode(image_file.read()).decode("utf-8")
return f"data:image/png;base64,{encoded}"
# 全局变量
LOG_FILE = None
LOG_READ_FILE = None
category = os.getenv("CATEGORY")
instance_id = os.getenv("INSTANCE_ID")
PAPER_FILE = f'{category}/target_sections/{instance_id}/iclr2025_conference.pdf'
# PAPER_FILE = './vq/target_sections/rotated_vq/iclr2025_conference.pdf'
# PAPER_LOG = './paper_agent/paper_logs/rotated_vq.log'
LOG_QUEUE: queue.Queue = queue.Queue()
STOP_LOG_THREAD = threading.Event()
CURRENT_PROCESS = None
STOP_REQUESTED = threading.Event()
# 日志读取和更新函数
def log_reader_thread(log_file):
try:
with open(log_file, "r", encoding="utf-8") as f:
# 移动到文件末尾
f.seek(0, 2)
while not STOP_LOG_THREAD.is_set():
line = f.readline()
if line:
LOG_QUEUE.put(line)
else:
time.sleep(0.1)
except Exception as e:
logging.error(f"Exception occurred in background log reader thread: {str(e)}")
def parse_logs_incrementally(logs, state_list, last_index):
existing_inputs = set()
existing_pairs = set()
for input_text, output_text in state_list:
existing_pairs.add((input_text.strip(), output_text.strip()))
existing_inputs.add(input_text.strip())
conversations = []
current_convo = None
state = "idle"
new_logs = logs[last_index:] # 只处理新日志
new_last_index = last_index + len(new_logs) # 更新后的索引
# 定义需要显示的工具列表
allowed_tools = {
"execute_command", "run_python", "create_file",
"write_file", "list_files", "gen_code_tree_structure"
}
def adjust_markdown_headers(content):
"""调整markdown标题级别,确保不与主标题冲突"""
lines = content.split('\n')
adjusted_lines = []
for line in lines:
# 检查是否是markdown标题
if line.strip().startswith('#'):
# 计算当前标题级别
header_level = 0
for char in line:
if char == '#':
header_level += 1
else:
break
# 如果是1-3级标题,调整为4-6级
if header_level <= 3:
# 添加额外的#使其成为更低级别的标题
adjusted_line = '#' * (header_level + 3) + line[header_level:]
adjusted_lines.append(adjusted_line)
else:
# 保持原样(4级及以上标题不变)
adjusted_lines.append(line)
else:
adjusted_lines.append(line)
return '\n'.join(adjusted_lines)
for line in new_logs:
line = line.strip()
if "Receive Task" in line or "Assistant Message" in line:
if current_convo:
conversations.append(current_convo)
current_convo = {
"user_time": None,
"user_content": "",
"assistant_time": None,
"assistant_role": None,
"assistant_content": "",
"tool_calls_time": None,
"tool_calls_content": "",
"tool_execution_time": None,
"tool_execution_content": "",
"current_tool_name": None # 添加当前工具名称跟踪
}
if "Receive Task" in line:
state = "await_user_time"
else:
state = "await_assistant_time"
elif current_convo is not None:
if state == "await_user_time" and line.startswith("["):
current_convo["user_time"] = line.strip("[]")
state = "await_user_input"
elif state == "await_user_input" and line.lower().startswith("receiveing the task:"):
state = "user_content"
elif state == "user_content" and not line.startswith("*"):
current_convo["user_content"] += line + "\n"
elif state == "await_assistant_time" and line.startswith("["):
current_convo["assistant_time"] = line.strip("[]")
state = "await_assistant_role"
elif state == "await_assistant_role":
if ":" in line:
parts = line.split(":", 1)
role = parts[0].strip()
content_line = parts[1].strip() + "\n"
else:
role = "assistant"
content_line = line + "\n"
current_convo["assistant_role"] = role
current_convo["assistant_content"] += content_line
state = "assistant_content"
elif state == "assistant_content":
if "Tool Calls" in line:
state = "await_tool_calls_time"
elif "Tool Execution" in line:
state = "await_tool_execution_time"
elif "End Turn" in line:
conversations.append(current_convo)
current_convo = None
state = "idle"
else:
current_convo["assistant_content"] += line + "\n"
elif state == "await_tool_calls_time" and line.startswith("["):
current_convo["tool_calls_time"] = line.strip("[]")
state = "tool_calls_content"
elif state == "tool_calls_content":
if "Tool Execution" in line:
state = "await_tool_execution_time"
elif "End Turn" in line:
conversations.append(current_convo)
current_convo = None
state = "idle"
else:
current_convo["tool_calls_content"] += line + "\n"
# 提取工具名称
if "tool execution:" in line.lower():
tool_name = line.split(":")[-1].strip()
current_convo["current_tool_name"] = tool_name
elif state == "await_tool_execution_time" and line.startswith("["):
current_convo["tool_execution_time"] = line.strip("[]")
state = "tool_execution_content"
elif state == "tool_execution_content":
if "End Turn" in line:
conversations.append(current_convo)
current_convo = None
state = "idle"
else:
current_convo["tool_execution_content"] += line + "\n"
# 🧹 收尾:捕获未被 End Turn 收尾的对话
if current_convo:
conversations.append(current_convo)
for convo in conversations:
section_input = ""
section_output = ""
# ✅ 每轮独立处理 user_content
if convo["user_content"].strip():
section_input = f"### 🙋 User ({convo['user_time']})\n```markdown\n{convo['user_content'].strip()}\n```"
else:
section_input = ""
input_clean = section_input.strip()
if (input_clean, "") not in existing_pairs:
state_list.append((input_clean, ""))
existing_inputs.add(input_clean)
existing_pairs.add((input_clean, ""))
output_parts = []
if convo["assistant_content"].strip():
# 检查Assistant内容是否为"None",如果是则设置为空字符串
assistant_content = convo["assistant_content"].strip()
if assistant_content.lower() == "none":
assistant_content = ""
# 始终显示Assistant块,即使内容为空
output_parts.append(
f"### 🤖 {convo['assistant_role']} ({convo['assistant_time']})\n{adjust_markdown_headers(assistant_content)}"
)
if convo["tool_calls_content"].strip():
output_parts.append(
f"### 🛠️ Tool Calls\n```python\n{convo['tool_calls_content'].strip()}\n```"
)
# 处理 Tool Execution 内容(只显示允许的工具,并放在markdown代码块中)
if convo["tool_execution_content"].strip():
# 检查是否是允许显示的工具
tool_name = convo.get("current_tool_name", "")
# 如果没有从tool_calls_content中提取到工具名,尝试从tool_execution_content中提取
if not tool_name:
for line in convo["tool_execution_content"].split('\n'):
if "tool execution:" in line.lower():
tool_name = line.split(":")[-1].strip()
break
# 只显示允许的工具执行结果
if tool_name in allowed_tools:
tool_execution_content = convo["tool_execution_content"].strip()
output_parts.append(
f"### ⚙️ Tool Execution\n```markdown\n{tool_execution_content}\n```"
)
if output_parts:
section_output = "\n\n".join(output_parts)
for i in reversed(range(len(state_list))):
user, bot = state_list[i]
if user.strip() == input_clean and not bot.strip():
new_pair = (user, section_output.strip())
if new_pair not in existing_pairs:
state_list[i] = new_pair
existing_pairs.add(new_pair)
break
return state_list, new_last_index
def get_latest_logs(max_lines=500, state=None, queue_source=None, last_index=0):
logs = []
log_queue = queue_source if queue_source else LOG_QUEUE
temp_queue = queue.Queue()
temp_logs = []
try:
while not log_queue.empty():
log = log_queue.get_nowait()
temp_logs.append(log)
temp_queue.put(log) # 将日志放回临时队列
except queue.Empty:
pass
logs = temp_logs
if LOG_FILE and os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, "r", encoding="utf-8") as f:
all_lines = f.readlines()
logs = all_lines
except Exception as e:
error_msg = f"Error reading log file: {str(e)}"
logging.error(error_msg)
if not logs:
logs = [error_msg]
if not logs:
return state, 0
filtered_logs = []
for log in logs:
if "- INFO -" not in log:
filtered_logs.append(log)
if not filtered_logs:
return state, 0
final_contents, updated_index = parse_logs_incrementally(filtered_logs, state, last_index)
return final_contents, updated_index
# Dictionary containing module descriptions
MODULE_DESCRIPTIONS = {
"Detailed Idea Description": "At this level, users provide comprehensive descriptions of their specific research ideas. The system processes these detailed inputs to develop implementation strategies based on the user's explicit requirements. Examples 1-2 are the templates of this mode.",
"Reference-Based Ideation": "This simpler level involves users submitting reference papers without a specific idea in mind. The user query typically follows the format: "'"I have some reference papers, please come up with an innovative idea and implement it with these papers."'" The system then analyzes the provided references to generate and develop novel research concepts. Examples 3-4 are the templates of this mode.",
"Paper Generation Agent": "Once all research and experimental work is finished, employ this agent for paper generation",
# "exit": "exit mode"
}
# 默认环境变量模板
DEFAULT_ENV_TEMPLATE = """#===========================================
# MODEL & API
# (See https://docs.camel-ai.org/key_modules/models.html#)
#===========================================
# OPENAI API (https://platform.openai.com/api-keys)
OPENAI_API_KEY='Your_Key'
# OPENAI_API_BASE_URL=""
# Azure OpenAI API
# AZURE_OPENAI_BASE_URL=""
# AZURE_API_VERSION=""
# AZURE_OPENAI_API_KEY=""
# AZURE_DEPLOYMENT_NAME=""
# Qwen API (https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key)
QWEN_API_KEY='Your_Key'
# DeepSeek API (https://platform.deepseek.com/api_keys)
DEEPSEEK_API_KEY='Your_Key'
#===========================================
# Tools & Services API
#===========================================
# Google Search API (https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3)
GOOGLE_API_KEY='Your_Key'
SEARCH_ENGINE_ID='Your_ID'
# Chunkr API (https://chunkr.ai/)
CHUNKR_API_KEY='Your_Key'
# Firecrawl API (https://www.firecrawl.dev/)
FIRECRAWL_API_KEY='Your_Key'
#FIRECRAWL_API_URL="https://api.firecrawl.dev"
"""
def validate_input(question: str) -> bool:
"""验证用户输入是否有效
Args:
question: 用户问题
Returns:
bool: 输入是否有效
"""
# 检查输入是否为空或只包含空格
if not question or question.strip() == "":
return False
return True
def run_ai_researcher(question: str, reference: str, example_module: str) -> Tuple[str, str, str]:
global CURRENT_PROCESS
# 验证输入
if not validate_input(question):
logging.warning("User submitted invalid input")
return ("Please enter a valid question", "0", "❌ Error: Invalid input question")
try:
# 确保环境变量已加载
load_dotenv(find_dotenv(), override=True)
logging.info(f"Processing question: '{question}', using module: {example_module}")
# 检查模块是否在MODULE_DESCRIPTIONS中
if example_module not in MODULE_DESCRIPTIONS:
logging.error(f"User selected an unsupported module: {example_module}")
return (
f"Selected module '{example_module}' is not supported",
"0",
"❌ Error: Unsupported module",
)
# 运行
try:
# logging.info("Runing AI Researcher...")
# answer, chat_history, token_info = run_society(society)
answer = main_ai_researcher(question, reference, example_module)
logging.info("Sucessully Runing AI Researcher")
except Exception as e:
logging.error(f"Error occurred while running Researcher: {str(e)}")
return (
f"Error occurred while running Researcher: {str(e)}",
"0",
f"❌ Error: Run failed - {str(e)}",
)
token_info = None
if not isinstance(token_info, dict):
token_info = {}
completion_tokens = token_info.get("completion_token_count", 0)
prompt_tokens = token_info.get("prompt_token_count", 0)
total_tokens = completion_tokens + prompt_tokens
logging.info(
f"Processing completed, token usage: completion={completion_tokens}, prompt={prompt_tokens}, total={total_tokens}"
)
return (
answer,
f"Completion tokens: {completion_tokens:,} | Prompt tokens: {prompt_tokens:,} | Total: {total_tokens:,}",
"✅ Successfully completed",
)
except Exception as e:
logging.error(
f"Uncaught error occurred while processing the question: {str(e)}"
)
return (f"Error occurred: {str(e)}", "0", f"❌ Error: {str(e)}")
def update_module_description(module_name: str) -> str:
return MODULE_DESCRIPTIONS.get(module_name, "No description available")
# 存储前端配置的环境变量
WEB_FRONTEND_ENV_VARS: dict[str, str] = {}
def init_env_file():
"""初始化.env文件如果不存在"""
dotenv_path = find_dotenv()
if not dotenv_path:
with open(".env", "w") as f:
f.write(DEFAULT_ENV_TEMPLATE)
dotenv_path = find_dotenv()
return dotenv_path
def load_env_vars():
"""加载环境变量并返回字典格式
Returns:
dict: 环境变量字典,每个值为一个包含值和来源的元组 (value, source)
"""
dotenv_path = init_env_file()
load_dotenv(dotenv_path, override=True)
# 从.env文件读取环境变量
env_file_vars = {}
with open(dotenv_path, "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
if "=" in line:
key, value = line.split("=", 1)
env_file_vars[key.strip()] = value.strip().strip("\"'")
# 从系统环境变量中获取
system_env_vars = {
k: v
for k, v in os.environ.items()
if k not in env_file_vars and k not in WEB_FRONTEND_ENV_VARS
}
# 合并环境变量,并标记来源
env_vars = {}
# 添加系统环境变量(最低优先级)
for key, value in system_env_vars.items():
env_vars[key] = (value, "System")
# 添加.env文件环境变量(中等优先级)
for key, value in env_file_vars.items():
env_vars[key] = (value, ".env file")
# 添加前端配置的环境变量(最高优先级)
for key, value in WEB_FRONTEND_ENV_VARS.items():
env_vars[key] = (value, "Frontend configuration")
# 确保操作系统环境变量也被更新
os.environ[key] = value
return env_vars
def add_env_var(key, value, from_frontend=True):
"""添加或更新单个环境变量
Args:
key: 环境变量名
value: 环境变量值
from_frontend: 是否来自前端配置,默认为True
"""
try:
if not key or not key.strip():
return False, "Variable name cannot be empty"
key = key.strip()
value = value.strip()
# 如果来自前端,则添加到前端环境变量字典
if from_frontend:
WEB_FRONTEND_ENV_VARS[key] = value
# 直接更新系统环境变量
os.environ[key] = value
# 同时更新.env文件
dotenv_path = init_env_file()
set_key(dotenv_path, key, value)
load_dotenv(dotenv_path, override=True)
return True, f"Environment variable {key} has been successfully added/updated!"
except Exception as e:
return False, f"Error adding environment variable: {str(e)}"
def delete_env_var(key):
"""删除环境变量"""
try:
if not key or not key.strip():
return False, "Variable name cannot be empty"
key = key.strip()
# 从.env文件中删除
dotenv_path = init_env_file()
unset_key(dotenv_path, key)
# 从前端环境变量字典中删除
if key in WEB_FRONTEND_ENV_VARS:
del WEB_FRONTEND_ENV_VARS[key]
# 从当前进程环境中也删除
if key in os.environ:
del os.environ[key]
return True, f"Environment variable {key} has been successfully deleted!"
except Exception as e:
return False, f"Error deleting environment variable: {str(e)}"
def is_api_related(key: str) -> bool:
"""判断环境变量是否与API相关
Args:
key: 环境变量名
Returns:
bool: 是否与API相关
"""
# API相关的关键词
api_keywords = [
"api",
"key",
"token",
"secret",
"password",
"openai",
"qwen",
"deepseek",
"google",
"search",
"hf",
"hugging",
"chunkr",
"firecrawl",
"category",
"instance_id",
"task_level",
"container_name",
"workplace_name",
"cache_path",
"port",
"max_iter_times"
]
# 检查是否包含API相关关键词(不区分大小写)
return any(keyword in key.lower() for keyword in api_keywords)
def get_api_guide(key: str) -> str:
"""根据环境变量名返回对应的API获取指南
Args:
key: 环境变量名
Returns:
str: API获取指南链接或说明
"""
key_lower = key.lower()
if "openai" in key_lower:
return "https://platform.openai.com/api-keys"
elif "qwen" in key_lower or "dashscope" in key_lower:
return "https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key"
elif "deepseek" in key_lower:
return "https://platform.deepseek.com/api_keys"
elif "google" in key_lower:
return "https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3"
elif "search_engine_id" in key_lower:
return "https://coda.io/@jon-dallas/google-image-search-pack-example/search-engine-id-and-google-api-key-3"
elif "chunkr" in key_lower:
return "https://chunkr.ai/"
elif "firecrawl" in key_lower:
return "https://www.firecrawl.dev/"
else:
return ""
def update_env_table():
"""更新环境变量表格显示,只显示API相关的环境变量"""
env_vars = load_env_vars()
# 过滤出API相关的环境变量
api_env_vars = {k: v for k, v in env_vars.items() if is_api_related(k)}
# 转换为列表格式,以符合Gradio Dataframe的要求
# 格式: [变量名, 变量值, 获取指南链接]
result = []
for k, v in api_env_vars.items():
guide = get_api_guide(k)
# 如果有指南链接,创建一个可点击的链接
guide_link = (
f"<a href='{guide}' target='_blank' class='guide-link'>🔗 获取</a>"
if guide
else ""
)
result.append([k, v[0], guide_link])
return result
def save_env_table_changes(data):
"""保存环境变量表格的更改
Args:
data: Dataframe数据,可能是pandas DataFrame对象
Returns:
str: 操作状态信息,包含HTML格式的状态消息
"""
try:
logging.info(
f"Starting to process environment variable table data, type: {type(data)}"
)
# 获取当前所有环境变量
current_env_vars = load_env_vars()
processed_keys = set() # 记录已处理的键,用于检测删除的变量
# 处理pandas DataFrame对象
import pandas as pd
if isinstance(data, pd.DataFrame):
# 获取列名信息
columns = data.columns.tolist()
logging.info(f"DataFrame column names: {columns}")
# 遍历DataFrame的每一行
for index, row in data.iterrows():
# 使用列名访问数据
if len(columns) >= 3:
# 获取变量名和值 (第0列是变量名,第1列是值)
key = row[0] if isinstance(row, pd.Series) else row.iloc[0]
value = row[1] if isinstance(row, pd.Series) else row.iloc[1]
# 检查是否为空行或已删除的变量
if key and str(key).strip(): # 如果键名不为空,则添加或更新
logging.info(f"Processing environment variable: {key} = {value}")
add_env_var(key, str(value))
processed_keys.add(key)
# 处理其他格式
elif isinstance(data, dict):
logging.info(f"Dictionary format data keys: {list(data.keys())}")
# 如果是字典格式,尝试不同的键
if "data" in data:
rows = data["data"]
elif "values" in data:
rows = data["values"]
elif "value" in data:
rows = data["value"]
else:
# 尝试直接使用字典作为行数据
rows = []
for key, value in data.items():
if key not in ["headers", "types", "columns"]:
rows.append([key, value])
if isinstance(rows, list):
for row in rows:
if isinstance(row, list) and len(row) >= 2:
key, value = row[0], row[1]
if key and str(key).strip():
add_env_var(key, str(value))
processed_keys.add(key)
elif isinstance(data, list):
# 列表格式
for row in data:
if isinstance(row, list) and len(row) >= 2:
key, value = row[0], row[1]
if key and str(key).strip():
add_env_var(key, str(value))
processed_keys.add(key)
else:
logging.error(f"Unknown data format: {type(data)}")
return f"❌ Save failed: Unknown data format {type(data)}"
# 处理删除的变量 - 检查当前环境变量中是否有未在表格中出现的变量
api_related_keys = {k for k in current_env_vars.keys() if is_api_related(k)}
keys_to_delete = api_related_keys - processed_keys
# 删除不在表格中的变量
for key in keys_to_delete:
logging.info(f"Deleting environment variable: {key}")
delete_env_var(key)
return "✅ Environment variables have been successfully saved"
except Exception as e:
import traceback
error_details = traceback.format_exc()
logging.error(f"Error saving environment variables: {str(e)}\n{error_details}")
return f"❌ Save failed: {str(e)}"
def create_ui():
def clear_log_file():
"""清空日志文件内容"""
try:
if LOG_FILE and os.path.exists(LOG_FILE):
# 清空日志文件内容而不是删除文件
open(LOG_FILE, "w").close()
logging.info("Log file has been cleared")
# 清空日志队列
while not LOG_QUEUE.empty():
try:
LOG_QUEUE.get_nowait()
except queue.Empty:
break
return ""
else:
return ""
except Exception as e:
logging.error(f"Error clearing log file: {str(e)}")
return ""
# 创建一个实时日志更新函数
def process_with_live_logs(question, reference, module_name, state, last_index):
"""处理问题并实时更新日志"""
global CURRENT_PROCESS
result_queue = queue.Queue()
def process_in_background():
try:
result = run_ai_researcher(question, reference, module_name)
result_queue.put(result)
except Exception as e:
result_queue.put(
(f"Error occurred: {str(e)}", "0", f"❌ Error: {str(e)}")
)
# 过滤空内容的对话记录
def filter_empty_conversations(conversations):
"""过滤掉完全空的对话记录,并处理部分空内容"""
filtered = []
for user_msg, bot_msg in conversations:
# 检查是否两者都为空
user_empty = not user_msg.strip()
bot_empty = not bot_msg.strip()
# 如果两者都为空,则跳过这个对话记录
if user_empty and bot_empty:
continue
# 如果只有一个为空,保留非空的那个,空的用None替代
processed_user = user_msg if not user_empty else None
processed_bot = bot_msg if not bot_empty else None
filtered.append((processed_user, processed_bot))
return filtered
# 启动后台处理线程
bg_thread = threading.Thread(target=process_in_background)
CURRENT_PROCESS = bg_thread # 记录当前进程
bg_thread.start()
# scroll_script = "<script>scrollToBottom();</script>"
# scroll_script = "<script>document.getElementById('top')?.scrollIntoView();</script>"
# scroll_script = "<script>document.getElementById('down').scrollTop = document.getElementById('chat-log').scrollHeight;</script>"
scroll_script = None
# 在等待处理完成的同时,每秒更新一次日志
while bg_thread.is_alive():
# 更新对话记录显示
logs2, updated_index = get_latest_logs(500, state, LOG_QUEUE, last_index)
# 过滤空内容的对话记录
filtered_logs = filter_empty_conversations(logs2)
# scroll_script = "<script>scrollToBottom();</script>"
# 始终更新状态
yield (
state,
"<span class='status-indicator status-running'></span> Processing...",
filtered_logs,
scroll_script,
updated_index
)
time.sleep(1)
# 处理完成,获取结果
if not result_queue.empty():
result = result_queue.get()
answer, token_count, status = result
# 最后一次更新对话记录
logs2, updated_index = get_latest_logs(500, state, LOG_QUEUE, last_index)
# 过滤空内容的对话记录
filtered_logs = filter_empty_conversations(logs2)
# 根据状态设置不同的指示器
if "错误" in status:
status_with_indicator = (
f"<span class='status-indicator status-error'></span> {status}"
)
else:
status_with_indicator = (
f"<span class='status-indicator status-success'></span> {status}"
)
yield token_count, status_with_indicator, filtered_logs, scroll_script, updated_index
# yield token_count, status_with_indicator, logs2
else:
logs2, updated_index = get_latest_logs(500, state, LOG_QUEUE, last_index)
# 过滤空内容的对话记录
filtered_logs = filter_empty_conversations(logs2)
yield (
state,
"<span class='status-indicator status-error'></span> Terminated",
filtered_logs,
None,
updated_index
)
with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber")) as app:
# gr.HTML("""
# <script>
# function scrollToBottom() {
# const chatLog = document.getElementById('chat-log');
# if (chatLog) {
# chatLog.scrollTop = chatLog.scrollHeight;
# }
# }
# </script>
# """)
image_base64 = get_base64_image("assets/logo.png")
gr.HTML(
f"""
<div style="display: flex; align-items: center; gap: 16px;">
<img src="{image_base64}" alt="模型图片" style="width: 100px; height: auto;">
<div style="display: flex; flex-direction: column;">
<h2 style="margin: 0;">AI-Researcher: Autonomous Scientific Innovation</h2>
<br>
<p style="margin: 0;">Welcome to AI-Researcher🤗 AI-Researcher introduces a revolutionary breakthrough in Automated</p>
<p style="margin: 0;">Scientific Discovery🔬, presenting a new system that fundamentally Reshapes the Traditional Research Paradigm.</p>
</div>
</div>
"""
)
# 添加自定义CSS
gr.HTML("""
<style>
/* 聊天容器样式 */
body, html, * {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.chat-container .chatbot {
height: 500px;
overflow-y: auto;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
/* 减少聊天消息间距 */
.chatbot .message {
margin-bottom: 8px !important;
padding: 8px 12px !important;
}
.chatbot .message-row {
margin-bottom: 8px !important;
gap: 8px !important;
}
.chatbot .message-bubble-border {
margin-bottom: 6px !important;
}
.chatbot .message-bubble {
margin-bottom: 6px !important;
padding: 10px 14px !important;
}
/* 减少markdown标题间距 */
.chatbot h3 {
margin-top: 8px !important;
margin-bottom: 6px !important;
line-height: 1.3 !important;
}
.chatbot h4, .chatbot h5, .chatbot h6 {
margin-top: 6px !important;