zjrwtx commited on
Commit
538cdc0
·
1 Parent(s): f8259c2

refactor direactory

Browse files
owl/app.py DELETED
@@ -1,891 +0,0 @@
1
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
- import os
15
- import sys
16
- import gradio as gr
17
- import subprocess
18
- import threading
19
- import time
20
- from datetime import datetime
21
- import queue
22
- from pathlib import Path
23
- import json
24
- import signal
25
- import dotenv
26
-
27
- # 设置日志队列
28
- log_queue: queue.Queue[str] = queue.Queue()
29
-
30
- # 当前运行的进程
31
- current_process = None
32
- process_lock = threading.Lock()
33
-
34
- # 脚本选项
35
- SCRIPTS = {
36
- "Qwen Mini (中文)": "run_qwen_mini_zh.py",
37
- "Qwen (中文)": "run_qwen_zh.py",
38
- "Mini": "run_mini.py",
39
- "DeepSeek (中文)": "run_deepseek_zh.py",
40
- "Default": "run.py",
41
- "GAIA Roleplaying": "run_gaia_roleplaying.py",
42
- "OpenAI Compatible": "run_openai_compatiable_model.py",
43
- "Ollama": "run_ollama.py",
44
- "Terminal": "run_terminal_zh.py",
45
- }
46
-
47
- # 脚本描述
48
- SCRIPT_DESCRIPTIONS = {
49
- "Qwen Mini (中文)": "使用阿里云Qwen模型的中文版本,适合中文问答和任务",
50
- "Qwen (中文)": "使用阿里云Qwen模型,支持多种工具和功能",
51
- "Mini": "轻量级版本,使用OpenAI GPT-4o模型",
52
- "DeepSeek (中文)": "使用DeepSeek模型,适合非多模态任务",
53
- "Default": "默认OWL实现,使用OpenAI GPT-4o模型和全套工具",
54
- "GAIA Roleplaying": "GAIA基准测试实现,用于评估模型能力",
55
- "OpenAI Compatible": "使用兼容OpenAI API的第三方模型,支持自定义API端点",
56
- "Ollama": "使用Ollama API",
57
- "Terminal": "使用本地终端执行python文件",
58
- }
59
-
60
- # 环境变量分组
61
- ENV_GROUPS = {
62
- "模型API": [
63
- {
64
- "name": "OPENAI_API_KEY",
65
- "label": "OpenAI API密钥",
66
- "type": "password",
67
- "required": False,
68
- "help": "OpenAI API密钥,用于访问GPT模型。获取方式:https://platform.openai.com/api-keys",
69
- },
70
- {
71
- "name": "OPENAI_API_BASE_URL",
72
- "label": "OpenAI API基础URL",
73
- "type": "text",
74
- "required": False,
75
- "help": "OpenAI API的基础URL,可选。如果使用代理或自定义端点,请设置此项。",
76
- },
77
- {
78
- "name": "QWEN_API_KEY",
79
- "label": "阿里云Qwen API密钥",
80
- "type": "password",
81
- "required": False,
82
- "help": "阿里云Qwen API密钥,用于访问Qwen模型。获取方式:https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key",
83
- },
84
- {
85
- "name": "DEEPSEEK_API_KEY",
86
- "label": "DeepSeek API密钥",
87
- "type": "password",
88
- "required": False,
89
- "help": "DeepSeek API密钥,用于访问DeepSeek模型。获取方式:https://platform.deepseek.com/api_keys",
90
- },
91
- ],
92
- "搜索工具": [
93
- {
94
- "name": "GOOGLE_API_KEY",
95
- "label": "Google API密钥",
96
- "type": "password",
97
- "required": False,
98
- "help": "Google搜索API密钥,用于网络搜索功能。获取方式:https://developers.google.com/custom-search/v1/overview",
99
- },
100
- {
101
- "name": "SEARCH_ENGINE_ID",
102
- "label": "搜索引擎ID",
103
- "type": "text",
104
- "required": False,
105
- "help": "Google自定义搜索引擎ID,与Google API密钥配合使用。获取方式:https://developers.google.com/custom-search/v1/overview",
106
- },
107
- ],
108
- "其他工具": [
109
- {
110
- "name": "HF_TOKEN",
111
- "label": "Hugging Face令牌",
112
- "type": "password",
113
- "required": False,
114
- "help": "Hugging Face API令牌,用于访问Hugging Face模型和数据集。获取方式:https://huggingface.co/join",
115
- },
116
- {
117
- "name": "CHUNKR_API_KEY",
118
- "label": "Chunkr API密钥",
119
- "type": "password",
120
- "required": False,
121
- "help": "Chunkr API密钥,用于文档处理功能。获取方式:https://chunkr.ai/",
122
- },
123
- {
124
- "name": "FIRECRAWL_API_KEY",
125
- "label": "Firecrawl API密钥",
126
- "type": "password",
127
- "required": False,
128
- "help": "Firecrawl API密钥,用于网页爬取功能。获取方式:https://www.firecrawl.dev/",
129
- },
130
- ],
131
- "自定义环境变量": [], # 用户自定义的环境变量将存储在这里
132
- }
133
-
134
-
135
- def get_script_info(script_name):
136
- """获取脚本的详细信息"""
137
- return SCRIPT_DESCRIPTIONS.get(script_name, "无描述信息")
138
-
139
-
140
- def load_env_vars():
141
- """加载环境变量"""
142
- env_vars = {}
143
- # 尝试从.env文件加载
144
- dotenv.load_dotenv()
145
-
146
- # 获取所有环境变量
147
- for group in ENV_GROUPS.values():
148
- for var in group:
149
- env_vars[var["name"]] = os.environ.get(var["name"], "")
150
-
151
- # 加载.env文件中可能存在的其他环境变量
152
- if Path(".env").exists():
153
- try:
154
- with open(".env", "r", encoding="utf-8") as f:
155
- for line in f:
156
- line = line.strip()
157
- if line and not line.startswith("#") and "=" in line:
158
- try:
159
- key, value = line.split("=", 1)
160
- key = key.strip()
161
- value = value.strip()
162
-
163
- # 处理引号包裹的值
164
- if (value.startswith('"') and value.endswith('"')) or (
165
- value.startswith("'") and value.endswith("'")
166
- ):
167
- value = value[1:-1] # 移除首尾的引号
168
-
169
- # 检查是否是已知的环境变量
170
- known_var = False
171
- for group in ENV_GROUPS.values():
172
- if any(var["name"] == key for var in group):
173
- known_var = True
174
- break
175
-
176
- # 如果不是已知的环境变量,添加到自定义环境变量组
177
- if not known_var and key not in env_vars:
178
- ENV_GROUPS["自定义环境变量"].append(
179
- {
180
- "name": key,
181
- "label": key,
182
- "type": "text",
183
- "required": False,
184
- "help": "用户自定义环境变量",
185
- }
186
- )
187
- env_vars[key] = value
188
- except Exception as e:
189
- print(f"解析环境变量行时出错: {line}, 错误: {str(e)}")
190
- except Exception as e:
191
- print(f"加载.env文件时出错: {str(e)}")
192
-
193
- return env_vars
194
-
195
-
196
- def save_env_vars(env_vars):
197
- """保存环境变量到.env文件"""
198
- # 读取现有的.env文件内容
199
- env_path = Path(".env")
200
- existing_content = {}
201
-
202
- if env_path.exists():
203
- try:
204
- with open(env_path, "r", encoding="utf-8") as f:
205
- for line in f:
206
- line = line.strip()
207
- if line and not line.startswith("#") and "=" in line:
208
- try:
209
- key, value = line.split("=", 1)
210
- existing_content[key.strip()] = value.strip()
211
- except Exception as e:
212
- print(f"解析环境变量行时出错: {line}, 错误: {str(e)}")
213
- except Exception as e:
214
- print(f"读取.env文件时出错: {str(e)}")
215
-
216
- # 更新环境变量
217
- for key, value in env_vars.items():
218
- if value is not None: # 允许空字符串值,但不允许None
219
- # 确保值是字符串形式
220
- value = str(value) # 确保值是字符串
221
-
222
- # 检查值是否已经被引号包裹
223
- if (value.startswith('"') and value.endswith('"')) or (
224
- value.startswith("'") and value.endswith("'")
225
- ):
226
- # 已经被引号包裹,保持原样
227
- existing_content[key] = value
228
- # 更新环境变量时移除引号
229
- os.environ[key] = value[1:-1]
230
- else:
231
- # 没有被引号包裹,添加双引号
232
- # 用双引号包裹值,确保特殊字符被正确处理
233
- quoted_value = f'"{value}"'
234
- existing_content[key] = quoted_value
235
- # 同时更新当前进程的环境变量(使用未引用的值)
236
- os.environ[key] = value
237
-
238
- # 写入.env文件
239
- try:
240
- with open(env_path, "w", encoding="utf-8") as f:
241
- for key, value in existing_content.items():
242
- f.write(f"{key}={value}\n")
243
- except Exception as e:
244
- print(f"写入.env文件时出错: {str(e)}")
245
- return f"❌ 保存环境变量失败: {str(e)}"
246
-
247
- return "✅ 环境变量已保存"
248
-
249
-
250
- def add_custom_env_var(name, value, var_type):
251
- """添加自定义环境变量"""
252
- if not name:
253
- return "❌ 环境变量名不能为空", None
254
-
255
- # 检查是否已存在同名环境变量
256
- for group in ENV_GROUPS.values():
257
- if any(var["name"] == name for var in group):
258
- return f"❌ 环境变量 {name} 已存在", None
259
-
260
- # 添加到自定义环境变量组
261
- ENV_GROUPS["自定义环境变量"].append(
262
- {
263
- "name": name,
264
- "label": name,
265
- "type": var_type,
266
- "required": False,
267
- "help": "用户自定义环境变量",
268
- }
269
- )
270
-
271
- # 保存环境变量
272
- env_vars = {name: value}
273
- save_env_vars(env_vars)
274
-
275
- # 返回成功消息和更新后的环境变量组
276
- return f"✅ 已添加环境变量 {name}", ENV_GROUPS["自定义环境变量"]
277
-
278
-
279
- def update_custom_env_var(name, value, var_type):
280
- """更改自定义环境变量"""
281
- if not name:
282
- return "❌ 环境变量名不能为空", None
283
-
284
- # 检查环境变量是否存在于自定义环境变量组中
285
- found = False
286
- for i, var in enumerate(ENV_GROUPS["自定义环境变量"]):
287
- if var["name"] == name:
288
- # 更新类型
289
- ENV_GROUPS["自定义环境变量"][i]["type"] = var_type
290
- found = True
291
- break
292
-
293
- if not found:
294
- return f"❌ 自定义环境变量 {name} 不存在", None
295
-
296
- # 保存环境变量值
297
- env_vars = {name: value}
298
- save_env_vars(env_vars)
299
-
300
- # 返回成功消息和更新后的环境变量组
301
- return f"✅ 已更新环境变量 {name}", ENV_GROUPS["自定义环境变量"]
302
-
303
-
304
- def delete_custom_env_var(name):
305
- """删除自定义环境变量"""
306
- if not name:
307
- return "❌ 环境变量名不能为空", None
308
-
309
- # 检查环境变量是否存在于自定义环境变量组中
310
- found = False
311
- for i, var in enumerate(ENV_GROUPS["自定义环境变量"]):
312
- if var["name"] == name:
313
- # 从自定义环境变量组中删除
314
- del ENV_GROUPS["自定义环境变量"][i]
315
- found = True
316
- break
317
-
318
- if not found:
319
- return f"❌ 自定义环境变量 {name} 不存在", None
320
-
321
- # 从.env文件中删除该环境变量
322
- env_path = Path(".env")
323
- if env_path.exists():
324
- try:
325
- with open(env_path, "r", encoding="utf-8") as f:
326
- lines = f.readlines()
327
-
328
- with open(env_path, "w", encoding="utf-8") as f:
329
- for line in lines:
330
- try:
331
- # 更精确地匹配环境变量行
332
- line_stripped = line.strip()
333
- # 检查是否为注释行或空行
334
- if not line_stripped or line_stripped.startswith("#"):
335
- f.write(line) # 保留注释行和空行
336
- continue
337
-
338
- # 检查是否包含等号
339
- if "=" not in line_stripped:
340
- f.write(line) # 保留不包含等号的行
341
- continue
342
-
343
- # 提取变量名并检查是否与要删除的变量匹配
344
- var_name = line_stripped.split("=", 1)[0].strip()
345
- if var_name != name:
346
- f.write(line) # 保留不匹配的变量
347
- except Exception as e:
348
- print(f"处理.env文件行时出错: {line}, 错误: {str(e)}")
349
- # 出错时保留原行
350
- f.write(line)
351
- except Exception as e:
352
- print(f"删除环境变量时出错: {str(e)}")
353
- return f"❌ 删除环境变量失败: {str(e)}", None
354
-
355
- # 从当前进程的环境变量中删除
356
- if name in os.environ:
357
- del os.environ[name]
358
-
359
- # 返回成功消息和更新后的环境变量组
360
- return f"✅ 已删除环境变量 {name}", ENV_GROUPS["自定义环境变量"]
361
-
362
-
363
- def terminate_process():
364
- """终止当前运行的进程"""
365
- global current_process
366
-
367
- with process_lock:
368
- if current_process is not None and current_process.poll() is None:
369
- try:
370
- # 在Windows上使用taskkill强制终止进程树
371
- if os.name == "nt":
372
- # 获取进程ID
373
- pid = current_process.pid
374
- # 使用taskkill命令终止进程及其子进程 - 避免使用shell=True以提高安全性
375
- try:
376
- subprocess.run(
377
- ["taskkill", "/F", "/T", "/PID", str(pid)], check=False
378
- )
379
- except subprocess.SubprocessError as e:
380
- log_queue.put(f"终止进程时出错: {str(e)}\n")
381
- return f"❌ 终止进程时出错: {str(e)}"
382
- else:
383
- # 在Unix上使用SIGTERM和SIGKILL
384
- current_process.terminate()
385
- try:
386
- current_process.wait(timeout=3)
387
- except subprocess.TimeoutExpired:
388
- current_process.kill()
389
-
390
- # 等待进程终止
391
- try:
392
- current_process.wait(timeout=2)
393
- except subprocess.TimeoutExpired:
394
- pass # 已经尝试强制终止,忽略超时
395
-
396
- log_queue.put("进程已终止\n")
397
- return "✅ 进程已终止"
398
- except Exception as e:
399
- log_queue.put(f"终止进程时出错: {str(e)}\n")
400
- return f"❌ 终止进程时出错: {str(e)}"
401
- else:
402
- return "❌ 没有正在运行的进程"
403
-
404
-
405
- def run_script(script_dropdown, question, progress=gr.Progress()):
406
- """运行选定的脚本并返回输出"""
407
- global current_process
408
-
409
- script_name = SCRIPTS.get(script_dropdown)
410
- if not script_name:
411
- return "❌ 无效的脚本选择", "", "", "", None
412
-
413
- if not question.strip():
414
- return "请输入问题!", "", "", "", None
415
-
416
- # 清空日志队列
417
- while not log_queue.empty():
418
- log_queue.get()
419
-
420
- # 创建日志目录
421
- log_dir = Path("logs")
422
- log_dir.mkdir(exist_ok=True)
423
-
424
- # 创建带时间戳的日志文件
425
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
426
- log_file = log_dir / f"{script_name.replace('.py', '')}_{timestamp}.log"
427
-
428
- # 构建命令
429
- # 获取当前脚本所在的基础路径
430
- base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
431
-
432
- cmd = [
433
- sys.executable,
434
- os.path.join(base_path, "owl", "script_adapter.py"),
435
- os.path.join(base_path, "owl", script_name),
436
- ]
437
-
438
- # 创建环境变量副本并添加问题
439
- env = os.environ.copy()
440
- # 确保问题是字符串类型
441
- if not isinstance(question, str):
442
- question = str(question)
443
- # 保留换行符,但确保是有效的字符串
444
- env["OWL_QUESTION"] = question
445
-
446
- # 启动进程
447
- with process_lock:
448
- current_process = subprocess.Popen(
449
- cmd,
450
- stdout=subprocess.PIPE,
451
- stderr=subprocess.STDOUT,
452
- text=True,
453
- bufsize=1,
454
- env=env,
455
- encoding="utf-8",
456
- )
457
-
458
- # 创建线程来读取输出
459
- def read_output():
460
- try:
461
- # 使用唯一的时间戳确保日志文件名不重复
462
- timestamp_unique = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
463
- unique_log_file = (
464
- log_dir / f"{script_name.replace('.py', '')}_{timestamp_unique}.log"
465
- )
466
-
467
- # 使用这个唯一的文件名写入日志
468
- with open(unique_log_file, "w", encoding="utf-8") as f:
469
- # 更新全局日志文件路径
470
- nonlocal log_file
471
- log_file = unique_log_file
472
-
473
- for line in iter(current_process.stdout.readline, ""):
474
- if line:
475
- # 写入日志文件
476
- f.write(line)
477
- f.flush()
478
- # 添加到队列
479
- log_queue.put(line)
480
- except Exception as e:
481
- log_queue.put(f"读取输出时出错: {str(e)}\n")
482
-
483
- # 启动读取线程
484
- threading.Thread(target=read_output, daemon=True).start()
485
-
486
- # 收集日志
487
- logs = []
488
- progress(0, desc="正在运行...")
489
-
490
- # 等待进程完成或超时
491
- start_time = time.time()
492
- timeout = 1800 # 30分钟超时
493
-
494
- while current_process.poll() is None:
495
- # 检查是否超时
496
- if time.time() - start_time > timeout:
497
- with process_lock:
498
- if current_process.poll() is None:
499
- if os.name == "nt":
500
- current_process.send_signal(signal.CTRL_BREAK_EVENT)
501
- else:
502
- current_process.terminate()
503
- log_queue.put("执行超时,已终止进程\n")
504
- break
505
-
506
- # 从队列获取日志
507
- while not log_queue.empty():
508
- log = log_queue.get()
509
- logs.append(log)
510
-
511
- # 更新进度
512
- elapsed = time.time() - start_time
513
- progress(min(elapsed / 300, 0.99), desc="正在运行...")
514
-
515
- # 短暂休眠以减少CPU使用
516
- time.sleep(0.1)
517
-
518
- # 每秒更新一次日志显示
519
- yield (
520
- status_message(current_process),
521
- extract_answer(logs),
522
- "".join(logs),
523
- str(log_file),
524
- None,
525
- )
526
-
527
- # 获取剩余日志
528
- while not log_queue.empty():
529
- logs.append(log_queue.get())
530
-
531
- # 提取聊天历史(如果有)
532
- chat_history = extract_chat_history(logs)
533
-
534
- # 返回最终状态和日志
535
- return (
536
- status_message(current_process),
537
- extract_answer(logs),
538
- "".join(logs),
539
- str(log_file),
540
- chat_history,
541
- )
542
-
543
-
544
- def status_message(process):
545
- """根据进程状态返回状态消息"""
546
- if process.poll() is None:
547
- return "⏳ 正在运行..."
548
- elif process.returncode == 0:
549
- return "✅ 执行成功"
550
- else:
551
- return f"❌ 执行失败 (返回码: {process.returncode})"
552
-
553
-
554
- def extract_answer(logs):
555
- """从日志中提取答案"""
556
- answer = ""
557
- for log in logs:
558
- if "Answer:" in log:
559
- answer = log.split("Answer:", 1)[1].strip()
560
- break
561
- return answer
562
-
563
-
564
- def extract_chat_history(logs):
565
- """尝试从日志中提取聊天历史"""
566
- try:
567
- chat_json_str = ""
568
- capture_json = False
569
-
570
- for log in logs:
571
- if "chat_history" in log:
572
- # 开始捕获JSON
573
- start_idx = log.find("[")
574
- if start_idx != -1:
575
- capture_json = True
576
- chat_json_str = log[start_idx:]
577
- elif capture_json:
578
- # 继续捕获JSON直到找到匹配的结束括号
579
- chat_json_str += log
580
- if "]" in log:
581
- # 找到结束括号,尝试解析JSON
582
- end_idx = chat_json_str.rfind("]") + 1
583
- if end_idx > 0:
584
- try:
585
- # 清理可能的额外文本
586
- json_str = chat_json_str[:end_idx].strip()
587
- chat_data = json.loads(json_str)
588
-
589
- # 格式化为Gradio聊天组件可用的格式
590
- formatted_chat = []
591
- for msg in chat_data:
592
- if "role" in msg and "content" in msg:
593
- role = "用户" if msg["role"] == "user" else "助手"
594
- formatted_chat.append([role, msg["content"]])
595
- return formatted_chat
596
- except json.JSONDecodeError:
597
- # 如果解析失败,继续捕获
598
- pass
599
- except Exception:
600
- # 其他错误,停止捕获
601
- capture_json = False
602
- except Exception:
603
- pass
604
- return None
605
-
606
-
607
- def create_ui():
608
- """创建Gradio界面"""
609
- # 加载环境变量
610
- env_vars = load_env_vars()
611
-
612
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as app:
613
- gr.Markdown(
614
- """
615
- # 🦉 OWL 智能助手运行平台
616
-
617
- 选择一个模型并输入您的问题,系统将运行相应的脚本并显示结果。
618
- """
619
- )
620
-
621
- with gr.Tabs():
622
- with gr.TabItem("运行模式"):
623
- with gr.Row():
624
- with gr.Column(scale=1):
625
- # 确保默认值是SCRIPTS中存在的键
626
- default_script = list(SCRIPTS.keys())[0] if SCRIPTS else None
627
- script_dropdown = gr.Dropdown(
628
- choices=list(SCRIPTS.keys()),
629
- value=default_script,
630
- label="选择模式",
631
- )
632
-
633
- script_info = gr.Textbox(
634
- value=get_script_info(default_script)
635
- if default_script
636
- else "",
637
- label="模型描述",
638
- interactive=False,
639
- )
640
-
641
- script_dropdown.change(
642
- fn=lambda x: get_script_info(x),
643
- inputs=script_dropdown,
644
- outputs=script_info,
645
- )
646
-
647
- question_input = gr.Textbox(
648
- lines=8,
649
- placeholder="请输入您的问题...",
650
- label="问题",
651
- elem_id="question_input",
652
- show_copy_button=True,
653
- )
654
-
655
- gr.Markdown(
656
- """
657
- > **注意**: 您输入的问题将替换脚本中的默认问题。系统会自动处理问题的替换,确保您的问题被正确使用。
658
- > 支持多行输入,换行将被保留。
659
- """
660
- )
661
-
662
- with gr.Row():
663
- run_button = gr.Button("运行", variant="primary")
664
- stop_button = gr.Button("终止", variant="stop")
665
-
666
- with gr.Column(scale=2):
667
- with gr.Tabs():
668
- with gr.TabItem("结果"):
669
- status_output = gr.Textbox(label="状态")
670
- answer_output = gr.Textbox(label="回答", lines=10)
671
- log_file_output = gr.Textbox(label="日志文件路径")
672
-
673
- with gr.TabItem("运行日志"):
674
- log_output = gr.Textbox(label="完整日志", lines=25)
675
-
676
- with gr.TabItem("聊天历史"):
677
- chat_output = gr.Chatbot(label="对话历史")
678
-
679
- # 示例问题
680
- examples = [
681
- [
682
- "Qwen Mini (中文)",
683
- "浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格",
684
- ],
685
- [
686
- "DeepSeek (中文)",
687
- "请分析GitHub上CAMEL-AI项目的最新统计数据。找出该项目的星标数量、贡献者数量和最近的活跃度。然后,创建一个简单的Excel表格来展示这些数据,并生成一个柱状图来可视化这些指标。最后,总结CAMEL项目的受欢迎程度和发展趋势。",
688
- ],
689
- [
690
- "Default",
691
- "Navigate to Amazon.com and identify one product that is attractive to coders. Please provide me with the product name and price. No need to verify your answer.",
692
- ],
693
- ]
694
-
695
- gr.Examples(examples=examples, inputs=[script_dropdown, question_input])
696
-
697
- with gr.TabItem("环境变量配置"):
698
- env_inputs = {}
699
- save_status = gr.Textbox(label="保存状态", interactive=False)
700
-
701
- # 添加自定义环境变量部分
702
- with gr.Accordion("添加自定义环境变量", open=True):
703
- with gr.Row():
704
- new_var_name = gr.Textbox(
705
- label="环境变量名", placeholder="例如:MY_CUSTOM_API_KEY"
706
- )
707
- new_var_value = gr.Textbox(
708
- label="环境变量值", placeholder="输入值"
709
- )
710
- new_var_type = gr.Dropdown(
711
- choices=["text", "password"], value="text", label="类型"
712
- )
713
-
714
- add_var_button = gr.Button("添加环境变量", variant="primary")
715
- add_var_status = gr.Textbox(label="添加状态", interactive=False)
716
-
717
- # 自定义环境变量列表
718
- custom_vars_list = gr.JSON(
719
- value=ENV_GROUPS["自定义环境变量"],
720
- label="已添加的自定义环境变量",
721
- visible=len(ENV_GROUPS["自定义环境变量"]) > 0,
722
- )
723
-
724
- # 更改和删除自定义环境变量部分
725
- with gr.Accordion(
726
- "更改或删除自定义环境变量",
727
- open=True,
728
- visible=len(ENV_GROUPS["自定义环境变量"]) > 0,
729
- ) as update_delete_accordion:
730
- with gr.Row():
731
- # 创建下拉菜单,显示所有自定义环境变量
732
- custom_var_dropdown = gr.Dropdown(
733
- choices=[
734
- var["name"] for var in ENV_GROUPS["自定义环境变量"]
735
- ],
736
- label="选择环境变量",
737
- interactive=True,
738
- )
739
- update_var_value = gr.Textbox(
740
- label="新的环境变量值", placeholder="输入新值"
741
- )
742
- update_var_type = gr.Dropdown(
743
- choices=["text", "password"], value="text", label="类型"
744
- )
745
-
746
- with gr.Row():
747
- update_var_button = gr.Button("更新环境变量", variant="primary")
748
- delete_var_button = gr.Button("删除环境变量", variant="stop")
749
-
750
- update_var_status = gr.Textbox(label="操作状态", interactive=False)
751
-
752
- # 添加环境变量按钮点击事件
753
- add_var_button.click(
754
- fn=add_custom_env_var,
755
- inputs=[new_var_name, new_var_value, new_var_type],
756
- outputs=[add_var_status, custom_vars_list],
757
- ).then(
758
- fn=lambda vars: {"visible": len(vars) > 0},
759
- inputs=[custom_vars_list],
760
- outputs=[update_delete_accordion],
761
- )
762
-
763
- # 更新环境变量按钮点击事件
764
- update_var_button.click(
765
- fn=update_custom_env_var,
766
- inputs=[custom_var_dropdown, update_var_value, update_var_type],
767
- outputs=[update_var_status, custom_vars_list],
768
- )
769
-
770
- # 删除环境变量按钮点击事件
771
- delete_var_button.click(
772
- fn=delete_custom_env_var,
773
- inputs=[custom_var_dropdown],
774
- outputs=[update_var_status, custom_vars_list],
775
- ).then(
776
- fn=lambda vars: {"visible": len(vars) > 0},
777
- inputs=[custom_vars_list],
778
- outputs=[update_delete_accordion],
779
- )
780
-
781
- # 当自定义环境变量列表更新时,更新下拉菜单选项
782
- custom_vars_list.change(
783
- fn=lambda vars: {
784
- "choices": [var["name"] for var in vars],
785
- "value": None,
786
- },
787
- inputs=[custom_vars_list],
788
- outputs=[custom_var_dropdown],
789
- )
790
-
791
- # 现有环境变量配置
792
- for group_name, vars in ENV_GROUPS.items():
793
- if (
794
- group_name != "自定义环境变量" or len(vars) > 0
795
- ): # 只显示非空的自定义环境变量组
796
- with gr.Accordion(
797
- group_name, open=(group_name != "自定义环境变量")
798
- ):
799
- for var in vars:
800
- # 添加帮助信息
801
- gr.Markdown(f"**{var['help']}**")
802
-
803
- if var["type"] == "password":
804
- env_inputs[var["name"]] = gr.Textbox(
805
- value=env_vars.get(var["name"], ""),
806
- label=var["label"],
807
- placeholder=f"请输入{var['label']}",
808
- type="password",
809
- )
810
- else:
811
- env_inputs[var["name"]] = gr.Textbox(
812
- value=env_vars.get(var["name"], ""),
813
- label=var["label"],
814
- placeholder=f"请输入{var['label']}",
815
- )
816
-
817
- save_button = gr.Button("保存环境变量", variant="primary")
818
-
819
- # 保存环境变量
820
- save_inputs = [
821
- env_inputs[var_name]
822
- for group in ENV_GROUPS.values()
823
- for var in group
824
- for var_name in [var["name"]]
825
- if var_name in env_inputs
826
- ]
827
- save_button.click(
828
- fn=lambda *values: save_env_vars(
829
- dict(
830
- zip(
831
- [
832
- var["name"]
833
- for group in ENV_GROUPS.values()
834
- for var in group
835
- if var["name"] in env_inputs
836
- ],
837
- values,
838
- )
839
- )
840
- ),
841
- inputs=save_inputs,
842
- outputs=save_status,
843
- )
844
-
845
- # 运行脚本
846
- run_button.click(
847
- fn=run_script,
848
- inputs=[script_dropdown, question_input],
849
- outputs=[
850
- status_output,
851
- answer_output,
852
- log_output,
853
- log_file_output,
854
- chat_output,
855
- ],
856
- show_progress=True,
857
- )
858
-
859
- # 终止运行
860
- stop_button.click(fn=terminate_process, inputs=[], outputs=[status_output])
861
-
862
- # 添加页脚
863
- gr.Markdown(
864
- """
865
- ### 📝 使用说明
866
-
867
- - 选择一个模型并输入您的问题
868
- - 点击"运行"按钮开始执行
869
- - 如需终止运行,点击"终止"按钮
870
- - 在"结果"标签页查看执行状态和回答
871
- - 在"运行日志"标签页查看完整日志
872
- - 在"聊天历史"标签页查看对话历史(如果有)
873
- - 在"环境变量配置"标签页配置API密钥和其他环境变量
874
- - 您可以添加自定义环境变量,满足特殊需求
875
-
876
- ### ⚠️ 注意事项
877
-
878
- - 运行某些模型可能需要API密钥,请确保在"环境变量配置"标签页中设置了相应的环境变量
879
- - 某些脚本可能需要较长时间运行,请耐心等待
880
- - 如果运行超过30分钟,进程将自动终止
881
- - 您输入的问题将替换脚本中的默认问题,确保问题与所选模型兼容
882
- """
883
- )
884
-
885
- return app
886
-
887
-
888
- if __name__ == "__main__":
889
- # 创建并启动应用
890
- app = create_ui()
891
- app.queue().launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
owl/app_en.py DELETED
@@ -1,918 +0,0 @@
1
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
- import os
15
- import sys
16
- import gradio as gr
17
- import subprocess
18
- import threading
19
- import time
20
- from datetime import datetime
21
- import queue
22
- from pathlib import Path
23
- import json
24
- import signal
25
- import dotenv
26
-
27
- # Set up log queue
28
- log_queue: queue.Queue[str] = queue.Queue()
29
-
30
- # Currently running process
31
- current_process = None
32
- process_lock = threading.Lock()
33
-
34
- # Script options
35
- SCRIPTS = {
36
- "Qwen Mini (Chinese)": "run_qwen_mini_zh.py",
37
- "Qwen (Chinese)": "run_qwen_zh.py",
38
- "Mini": "run_mini.py",
39
- "DeepSeek (Chinese)": "run_deepseek_zh.py",
40
- "Default": "run.py",
41
- "GAIA Roleplaying": "run_gaia_roleplaying.py",
42
- "OpenAI Compatible": "run_openai_compatiable_model.py",
43
- "Ollama": "run_ollama.py",
44
- "Terminal": "run_terminal.py",
45
- }
46
-
47
- # Script descriptions
48
- SCRIPT_DESCRIPTIONS = {
49
- "Qwen Mini (Chinese)": "Uses the Chinese version of Alibaba Cloud's Qwen model, suitable for Chinese Q&A and tasks",
50
- "Qwen (Chinese)": "Uses Alibaba Cloud's Qwen model, supports various tools and functions",
51
- "Mini": "Lightweight version, uses OpenAI GPT-4o model",
52
- "DeepSeek (Chinese)": "Uses DeepSeek model, suitable for non-multimodal tasks",
53
- "Default": "Default OWL implementation, uses OpenAI GPT-4o model and full set of tools",
54
- "GAIA Roleplaying": "GAIA benchmark implementation, used to evaluate model capabilities",
55
- "OpenAI Compatible": "Uses third-party models compatible with OpenAI API, supports custom API endpoints",
56
- "Ollama": "Uses Ollama API",
57
- "Terminal": "Uses local terminal to execute python files",
58
- }
59
-
60
- # Environment variable groups
61
- ENV_GROUPS = {
62
- "Model API": [
63
- {
64
- "name": "OPENAI_API_KEY",
65
- "label": "OpenAI API Key",
66
- "type": "password",
67
- "required": False,
68
- "help": "OpenAI API key for accessing GPT models. Get it from: https://platform.openai.com/api-keys",
69
- },
70
- {
71
- "name": "OPENAI_API_BASE_URL",
72
- "label": "OpenAI API Base URL",
73
- "type": "text",
74
- "required": False,
75
- "help": "Base URL for OpenAI API, optional. Set this if using a proxy or custom endpoint.",
76
- },
77
- {
78
- "name": "QWEN_API_KEY",
79
- "label": "Alibaba Cloud Qwen API Key",
80
- "type": "password",
81
- "required": False,
82
- "help": "Alibaba Cloud Qwen API key for accessing Qwen models. Get it from: https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key",
83
- },
84
- {
85
- "name": "DEEPSEEK_API_KEY",
86
- "label": "DeepSeek API Key",
87
- "type": "password",
88
- "required": False,
89
- "help": "DeepSeek API key for accessing DeepSeek models. Get it from: https://platform.deepseek.com/api_keys",
90
- },
91
- ],
92
- "Search Tools": [
93
- {
94
- "name": "GOOGLE_API_KEY",
95
- "label": "Google API Key",
96
- "type": "password",
97
- "required": False,
98
- "help": "Google Search API key for web search functionality. Get it from: https://developers.google.com/custom-search/v1/overview",
99
- },
100
- {
101
- "name": "SEARCH_ENGINE_ID",
102
- "label": "Search Engine ID",
103
- "type": "text",
104
- "required": False,
105
- "help": "Google Custom Search Engine ID, used with Google API key. Get it from: https://developers.google.com/custom-search/v1/overview",
106
- },
107
- ],
108
- "Other Tools": [
109
- {
110
- "name": "HF_TOKEN",
111
- "label": "Hugging Face Token",
112
- "type": "password",
113
- "required": False,
114
- "help": "Hugging Face API token for accessing Hugging Face models and datasets. Get it from: https://huggingface.co/join",
115
- },
116
- {
117
- "name": "CHUNKR_API_KEY",
118
- "label": "Chunkr API Key",
119
- "type": "password",
120
- "required": False,
121
- "help": "Chunkr API key for document processing functionality. Get it from: https://chunkr.ai/",
122
- },
123
- {
124
- "name": "FIRECRAWL_API_KEY",
125
- "label": "Firecrawl API Key",
126
- "type": "password",
127
- "required": False,
128
- "help": "Firecrawl API key for web crawling functionality. Get it from: https://www.firecrawl.dev/",
129
- },
130
- ],
131
- "Custom Environment Variables": [], # User-defined environment variables will be stored here
132
- }
133
-
134
-
135
- def get_script_info(script_name):
136
- """Get detailed information about the script"""
137
- return SCRIPT_DESCRIPTIONS.get(script_name, "No description available")
138
-
139
-
140
- def load_env_vars():
141
- """Load environment variables"""
142
- env_vars = {}
143
- # Try to load from .env file
144
- dotenv.load_dotenv()
145
-
146
- # Get all environment variables
147
- for group in ENV_GROUPS.values():
148
- for var in group:
149
- env_vars[var["name"]] = os.environ.get(var["name"], "")
150
-
151
- # Load other environment variables that may exist in the .env file
152
- if Path(".env").exists():
153
- try:
154
- with open(".env", "r", encoding="utf-8") as f:
155
- for line in f:
156
- line = line.strip()
157
- if line and not line.startswith("#") and "=" in line:
158
- try:
159
- key, value = line.split("=", 1)
160
- key = key.strip()
161
- value = value.strip()
162
-
163
- # Handle quoted values
164
- if (value.startswith('"') and value.endswith('"')) or (
165
- value.startswith("'") and value.endswith("'")
166
- ):
167
- value = value[
168
- 1:-1
169
- ] # Remove quotes at the beginning and end
170
-
171
- # Check if it's a known environment variable
172
- known_var = False
173
- for group in ENV_GROUPS.values():
174
- if any(var["name"] == key for var in group):
175
- known_var = True
176
- break
177
-
178
- # If it's not a known environment variable, add it to the custom environment variables group
179
- if not known_var and key not in env_vars:
180
- ENV_GROUPS["Custom Environment Variables"].append(
181
- {
182
- "name": key,
183
- "label": key,
184
- "type": "text",
185
- "required": False,
186
- "help": "User-defined environment variable",
187
- }
188
- )
189
- env_vars[key] = value
190
- except Exception as e:
191
- print(
192
- f"Error parsing environment variable line: {line}, error: {str(e)}"
193
- )
194
- except Exception as e:
195
- print(f"Error loading .env file: {str(e)}")
196
-
197
- return env_vars
198
-
199
-
200
- def save_env_vars(env_vars):
201
- """Save environment variables to .env file"""
202
- # Read existing .env file content
203
- env_path = Path(".env")
204
- existing_content = {}
205
-
206
- if env_path.exists():
207
- try:
208
- with open(env_path, "r", encoding="utf-8") as f:
209
- for line in f:
210
- line = line.strip()
211
- if line and not line.startswith("#") and "=" in line:
212
- try:
213
- key, value = line.split("=", 1)
214
- existing_content[key.strip()] = value.strip()
215
- except Exception as e:
216
- print(
217
- f"Error parsing environment variable line: {line}, error: {str(e)}"
218
- )
219
- except Exception as e:
220
- print(f"Error reading .env file: {str(e)}")
221
-
222
- # Update environment variables
223
- for key, value in env_vars.items():
224
- if value is not None: # Allow empty string values, but not None
225
- # Ensure the value is a string
226
- value = str(value) # Ensure the value is a string
227
-
228
- # Check if the value is already wrapped in quotes
229
- if (value.startswith('"') and value.endswith('"')) or (
230
- value.startswith("'") and value.endswith("'")
231
- ):
232
- # Already wrapped in quotes, keep as is
233
- existing_content[key] = value
234
- # Update environment variable by removing quotes
235
- os.environ[key] = value[1:-1]
236
- else:
237
- # Not wrapped in quotes, add double quotes
238
- # Wrap the value in double quotes to ensure special characters are handled correctly
239
- quoted_value = f'"{value}"'
240
- existing_content[key] = quoted_value
241
- # Also update the environment variable for the current process (using the unquoted value)
242
- os.environ[key] = value
243
-
244
- # Write to .env file
245
- try:
246
- with open(env_path, "w", encoding="utf-8") as f:
247
- for key, value in existing_content.items():
248
- f.write(f"{key}={value}\n")
249
- except Exception as e:
250
- print(f"Error writing to .env file: {str(e)}")
251
- return f"❌ Failed to save environment variables: {str(e)}"
252
-
253
- return "✅ Environment variables saved"
254
-
255
-
256
- def add_custom_env_var(name, value, var_type):
257
- """Add custom environment variable"""
258
- if not name:
259
- return "❌ Environment variable name cannot be empty", None
260
-
261
- # Check if an environment variable with the same name already exists
262
- for group in ENV_GROUPS.values():
263
- if any(var["name"] == name for var in group):
264
- return f"❌ Environment variable {name} already exists", None
265
-
266
- # Add to custom environment variables group
267
- ENV_GROUPS["Custom Environment Variables"].append(
268
- {
269
- "name": name,
270
- "label": name,
271
- "type": var_type,
272
- "required": False,
273
- "help": "User-defined environment variable",
274
- }
275
- )
276
-
277
- # Save environment variables
278
- env_vars = {name: value}
279
- save_env_vars(env_vars)
280
-
281
- # Return success message and updated environment variable group
282
- return f"✅ Added environment variable {name}", ENV_GROUPS[
283
- "Custom Environment Variables"
284
- ]
285
-
286
-
287
- def update_custom_env_var(name, value, var_type):
288
- """Update custom environment variable"""
289
- if not name:
290
- return "❌ Environment variable name cannot be empty", None
291
-
292
- # Check if the environment variable exists in the custom environment variables group
293
- found = False
294
- for i, var in enumerate(ENV_GROUPS["Custom Environment Variables"]):
295
- if var["name"] == name:
296
- # Update type
297
- ENV_GROUPS["Custom Environment Variables"][i]["type"] = var_type
298
- found = True
299
- break
300
-
301
- if not found:
302
- return f"❌ Custom environment variable {name} does not exist", None
303
-
304
- # Save environment variable value
305
- env_vars = {name: value}
306
- save_env_vars(env_vars)
307
-
308
- # Return success message and updated environment variable group
309
- return f"✅ Updated environment variable {name}", ENV_GROUPS[
310
- "Custom Environment Variables"
311
- ]
312
-
313
-
314
- def delete_custom_env_var(name):
315
- """Delete custom environment variable"""
316
- if not name:
317
- return "❌ Environment variable name cannot be empty", None
318
-
319
- # Check if the environment variable exists in the custom environment variables group
320
- found = False
321
- for i, var in enumerate(ENV_GROUPS["Custom Environment Variables"]):
322
- if var["name"] == name:
323
- # Delete from custom environment variables group
324
- del ENV_GROUPS["Custom Environment Variables"][i]
325
- found = True
326
- break
327
-
328
- if not found:
329
- return f"❌ Custom environment variable {name} does not exist", None
330
-
331
- # Delete the environment variable from .env file
332
- env_path = Path(".env")
333
- if env_path.exists():
334
- try:
335
- with open(env_path, "r", encoding="utf-8") as f:
336
- lines = f.readlines()
337
-
338
- with open(env_path, "w", encoding="utf-8") as f:
339
- for line in lines:
340
- try:
341
- # More precisely match environment variable lines
342
- line_stripped = line.strip()
343
- # Check if it's a comment line or empty line
344
- if not line_stripped or line_stripped.startswith("#"):
345
- f.write(line) # Keep comment lines and empty lines
346
- continue
347
-
348
- # Check if it contains an equals sign
349
- if "=" not in line_stripped:
350
- f.write(line) # Keep lines without equals sign
351
- continue
352
-
353
- # Extract variable name and check if it matches the variable to be deleted
354
- var_name = line_stripped.split("=", 1)[0].strip()
355
- if var_name != name:
356
- f.write(line) # Keep variables that don't match
357
- except Exception as e:
358
- print(
359
- f"Error processing .env file line: {line}, error: {str(e)}"
360
- )
361
- # Keep the original line when an error occurs
362
- f.write(line)
363
- except Exception as e:
364
- print(f"Error deleting environment variable: {str(e)}")
365
- return f"❌ Failed to delete environment variable: {str(e)}", None
366
-
367
- # Delete from current process environment variables
368
- if name in os.environ:
369
- del os.environ[name]
370
-
371
- # Return success message and updated environment variable group
372
- return f"✅ Deleted environment variable {name}", ENV_GROUPS[
373
- "Custom Environment Variables"
374
- ]
375
-
376
-
377
- def terminate_process():
378
- """Terminate the currently running process"""
379
- global current_process
380
-
381
- with process_lock:
382
- if current_process is not None and current_process.poll() is None:
383
- try:
384
- # On Windows, use taskkill to forcibly terminate the process tree
385
- if os.name == "nt":
386
- # Get process ID
387
- pid = current_process.pid
388
- # Use taskkill command to terminate the process and its children - avoid using shell=True for better security
389
- try:
390
- subprocess.run(
391
- ["taskkill", "/F", "/T", "/PID", str(pid)], check=False
392
- )
393
- except subprocess.SubprocessError as e:
394
- log_queue.put(f"Error terminating process: {str(e)}\n")
395
- return f"❌ Error terminating process: {str(e)}"
396
- else:
397
- # On Unix, use SIGTERM and SIGKILL
398
- current_process.terminate()
399
- try:
400
- current_process.wait(timeout=3)
401
- except subprocess.TimeoutExpired:
402
- current_process.kill()
403
-
404
- # Wait for process to terminate
405
- try:
406
- current_process.wait(timeout=2)
407
- except subprocess.TimeoutExpired:
408
- pass # Already tried to force terminate, ignore timeout
409
-
410
- log_queue.put("Process terminated\n")
411
- return "✅ Process terminated"
412
- except Exception as e:
413
- log_queue.put(f"Error terminating process: {str(e)}\n")
414
- return f"❌ Error terminating process: {str(e)}"
415
- else:
416
- return "❌ No process is currently running"
417
-
418
-
419
- def run_script(script_dropdown, question, progress=gr.Progress()):
420
- """Run the selected script and return the output"""
421
- global current_process
422
-
423
- script_name = SCRIPTS.get(script_dropdown)
424
- if not script_name:
425
- return "❌ Invalid script selection", "", "", "", None
426
-
427
- if not question.strip():
428
- return "Please enter a question!", "", "", "", None
429
-
430
- # Clear the log queue
431
- while not log_queue.empty():
432
- log_queue.get()
433
-
434
- # Create log directory
435
- log_dir = Path("logs")
436
- log_dir.mkdir(exist_ok=True)
437
-
438
- # Create log file with timestamp
439
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
440
- log_file = log_dir / f"{script_name.replace('.py', '')}_{timestamp}.log"
441
-
442
- # Build command
443
- base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
444
- cmd = [
445
- sys.executable,
446
- os.path.join(base_path, "owl", "script_adapter.py"),
447
- os.path.join(base_path, "owl", script_name),
448
- ]
449
-
450
- # Create a copy of environment variables and add the question
451
- env = os.environ.copy()
452
- # Ensure question is a string type
453
- if not isinstance(question, str):
454
- question = str(question)
455
- # Preserve newlines, but ensure it's a valid string
456
- env["OWL_QUESTION"] = question
457
-
458
- # Start the process
459
- with process_lock:
460
- current_process = subprocess.Popen(
461
- cmd,
462
- stdout=subprocess.PIPE,
463
- stderr=subprocess.STDOUT,
464
- text=True,
465
- bufsize=1,
466
- env=env,
467
- encoding="utf-8",
468
- )
469
-
470
- # Create thread to read output
471
- def read_output():
472
- try:
473
- # Use a unique timestamp to ensure log filename is not duplicated
474
- timestamp_unique = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
475
- unique_log_file = (
476
- log_dir / f"{script_name.replace('.py', '')}_{timestamp_unique}.log"
477
- )
478
-
479
- # Use this unique filename to write logs
480
- with open(unique_log_file, "w", encoding="utf-8") as f:
481
- # Update global log file path
482
- nonlocal log_file
483
- log_file = unique_log_file
484
-
485
- for line in iter(current_process.stdout.readline, ""):
486
- if line:
487
- # Write to log file
488
- f.write(line)
489
- f.flush()
490
- # Add to queue
491
- log_queue.put(line)
492
- except Exception as e:
493
- log_queue.put(f"Error reading output: {str(e)}\n")
494
-
495
- # Start the reading thread
496
- threading.Thread(target=read_output, daemon=True).start()
497
-
498
- # Collect logs
499
- logs = []
500
- progress(0, desc="Running...")
501
-
502
- # Wait for process to complete or timeout
503
- start_time = time.time()
504
- timeout = 1800 # 30 minutes timeout
505
-
506
- while current_process.poll() is None:
507
- # Check if timeout
508
- if time.time() - start_time > timeout:
509
- with process_lock:
510
- if current_process.poll() is None:
511
- if os.name == "nt":
512
- current_process.send_signal(signal.CTRL_BREAK_EVENT)
513
- else:
514
- current_process.terminate()
515
- log_queue.put("Execution timeout, process terminated\n")
516
- break
517
-
518
- # Get logs from queue
519
- while not log_queue.empty():
520
- log = log_queue.get()
521
- logs.append(log)
522
-
523
- # Update progress
524
- elapsed = time.time() - start_time
525
- progress(min(elapsed / 300, 0.99), desc="Running...")
526
-
527
- # Short sleep to reduce CPU usage
528
- time.sleep(0.1)
529
-
530
- # Update log display once per second
531
- yield (
532
- status_message(current_process),
533
- extract_answer(logs),
534
- "".join(logs),
535
- str(log_file),
536
- None,
537
- )
538
-
539
- # Get remaining logs
540
- while not log_queue.empty():
541
- logs.append(log_queue.get())
542
-
543
- # Extract chat history (if any)
544
- chat_history = extract_chat_history(logs)
545
-
546
- # Return final status and logs
547
- return (
548
- status_message(current_process),
549
- extract_answer(logs),
550
- "".join(logs),
551
- str(log_file),
552
- chat_history,
553
- )
554
-
555
-
556
- def status_message(process):
557
- """Return status message based on process status"""
558
- if process.poll() is None:
559
- return "⏳ Running..."
560
- elif process.returncode == 0:
561
- return "✅ Execution successful"
562
- else:
563
- return f"❌ Execution failed (return code: {process.returncode})"
564
-
565
-
566
- def extract_answer(logs):
567
- """Extract answer from logs"""
568
- answer = ""
569
- for log in logs:
570
- if "Answer:" in log:
571
- answer = log.split("Answer:", 1)[1].strip()
572
- break
573
- return answer
574
-
575
-
576
- def extract_chat_history(logs):
577
- """Try to extract chat history from logs"""
578
- try:
579
- chat_json_str = ""
580
- capture_json = False
581
-
582
- for log in logs:
583
- if "chat_history" in log:
584
- # Start capturing JSON
585
- start_idx = log.find("[")
586
- if start_idx != -1:
587
- capture_json = True
588
- chat_json_str = log[start_idx:]
589
- elif capture_json:
590
- # Continue capturing JSON until finding the matching closing bracket
591
- chat_json_str += log
592
- if "]" in log:
593
- # Found closing bracket, try to parse JSON
594
- end_idx = chat_json_str.rfind("]") + 1
595
- if end_idx > 0:
596
- try:
597
- # Clean up possible extra text
598
- json_str = chat_json_str[:end_idx].strip()
599
- chat_data = json.loads(json_str)
600
-
601
- # Format for use with Gradio chat component
602
- formatted_chat = []
603
- for msg in chat_data:
604
- if "role" in msg and "content" in msg:
605
- role = (
606
- "User" if msg["role"] == "user" else "Assistant"
607
- )
608
- formatted_chat.append([role, msg["content"]])
609
- return formatted_chat
610
- except json.JSONDecodeError:
611
- # If parsing fails, continue capturing
612
- pass
613
- except Exception:
614
- # Other errors, stop capturing
615
- capture_json = False
616
- except Exception:
617
- pass
618
- return None
619
-
620
-
621
- def create_ui():
622
- """Create Gradio interface"""
623
- # Load environment variables
624
- env_vars = load_env_vars()
625
-
626
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as app:
627
- gr.Markdown(
628
- """
629
- # 🦉 OWL Intelligent Assistant Platform
630
-
631
- Select a model and enter your question, the system will run the corresponding script and display the results.
632
- """
633
- )
634
-
635
- with gr.Tabs():
636
- with gr.TabItem("Run Mode"):
637
- with gr.Row():
638
- with gr.Column(scale=1):
639
- # Ensure default value is a key that exists in SCRIPTS
640
- default_script = list(SCRIPTS.keys())[0] if SCRIPTS else None
641
- script_dropdown = gr.Dropdown(
642
- choices=list(SCRIPTS.keys()),
643
- value=default_script,
644
- label="Select Mode",
645
- )
646
-
647
- script_info = gr.Textbox(
648
- value=get_script_info(default_script)
649
- if default_script
650
- else "",
651
- label="Model Description",
652
- interactive=False,
653
- )
654
-
655
- script_dropdown.change(
656
- fn=lambda x: get_script_info(x),
657
- inputs=script_dropdown,
658
- outputs=script_info,
659
- )
660
-
661
- question_input = gr.Textbox(
662
- lines=8,
663
- placeholder="Please enter your question...",
664
- label="Question",
665
- elem_id="question_input",
666
- show_copy_button=True,
667
- )
668
-
669
- gr.Markdown(
670
- """
671
- > **Note**: Your question will replace the default question in the script. The system will automatically handle the replacement, ensuring your question is used correctly.
672
- > Multi-line input is supported, line breaks will be preserved.
673
- """
674
- )
675
-
676
- with gr.Row():
677
- run_button = gr.Button("Run", variant="primary")
678
- stop_button = gr.Button("Stop", variant="stop")
679
-
680
- with gr.Column(scale=2):
681
- with gr.Tabs():
682
- with gr.TabItem("Results"):
683
- status_output = gr.Textbox(label="Status")
684
- answer_output = gr.Textbox(label="Answer", lines=10)
685
- log_file_output = gr.Textbox(label="Log File Path")
686
-
687
- with gr.TabItem("Run Logs"):
688
- log_output = gr.Textbox(label="Complete Logs", lines=25)
689
-
690
- with gr.TabItem("Chat History"):
691
- chat_output = gr.Chatbot(label="Conversation History")
692
-
693
- # Example questions
694
- examples = [
695
- [
696
- "Qwen Mini (Chinese)",
697
- "Browse Amazon and find a product that is attractive to programmers. Please provide the product name and price.",
698
- ],
699
- [
700
- "DeepSeek (Chinese)",
701
- "Please analyze the latest statistics of the CAMEL-AI project on GitHub. Find out the number of stars, number of contributors, and recent activity of the project. Then, create a simple Excel spreadsheet to display this data and generate a bar chart to visualize these metrics. Finally, summarize the popularity and development trends of the CAMEL project.",
702
- ],
703
- [
704
- "Default",
705
- "Navigate to Amazon.com and identify one product that is attractive to coders. Please provide me with the product name and price. No need to verify your answer.",
706
- ],
707
- ]
708
-
709
- gr.Examples(examples=examples, inputs=[script_dropdown, question_input])
710
-
711
- with gr.TabItem("Environment Variable Configuration"):
712
- env_inputs = {}
713
- save_status = gr.Textbox(label="Save Status", interactive=False)
714
-
715
- # Add custom environment variables section
716
- with gr.Accordion("Add Custom Environment Variables", open=True):
717
- with gr.Row():
718
- new_var_name = gr.Textbox(
719
- label="Environment Variable Name",
720
- placeholder="Example: MY_CUSTOM_API_KEY",
721
- )
722
- new_var_value = gr.Textbox(
723
- label="Environment Variable Value",
724
- placeholder="Enter value",
725
- )
726
- new_var_type = gr.Dropdown(
727
- choices=["text", "password"], value="text", label="Type"
728
- )
729
-
730
- add_var_button = gr.Button(
731
- "Add Environment Variable", variant="primary"
732
- )
733
- add_var_status = gr.Textbox(label="Add Status", interactive=False)
734
-
735
- # Custom environment variables list
736
- custom_vars_list = gr.JSON(
737
- value=ENV_GROUPS["Custom Environment Variables"],
738
- label="Added Custom Environment Variables",
739
- visible=len(ENV_GROUPS["Custom Environment Variables"]) > 0,
740
- )
741
-
742
- # Update and delete custom environment variables section
743
- with gr.Accordion(
744
- "Update or Delete Custom Environment Variables",
745
- open=True,
746
- visible=len(ENV_GROUPS["Custom Environment Variables"]) > 0,
747
- ) as update_delete_accordion:
748
- with gr.Row():
749
- # Create dropdown menu to display all custom environment variables
750
- custom_var_dropdown = gr.Dropdown(
751
- choices=[
752
- var["name"]
753
- for var in ENV_GROUPS["Custom Environment Variables"]
754
- ],
755
- label="Select Environment Variable",
756
- interactive=True,
757
- )
758
- update_var_value = gr.Textbox(
759
- label="New Environment Variable Value",
760
- placeholder="Enter new value",
761
- )
762
- update_var_type = gr.Dropdown(
763
- choices=["text", "password"], value="text", label="Type"
764
- )
765
-
766
- with gr.Row():
767
- update_var_button = gr.Button(
768
- "Update Environment Variable", variant="primary"
769
- )
770
- delete_var_button = gr.Button(
771
- "Delete Environment Variable", variant="stop"
772
- )
773
-
774
- update_var_status = gr.Textbox(
775
- label="Operation Status", interactive=False
776
- )
777
-
778
- # Add environment variable button click event
779
- add_var_button.click(
780
- fn=add_custom_env_var,
781
- inputs=[new_var_name, new_var_value, new_var_type],
782
- outputs=[add_var_status, custom_vars_list],
783
- ).then(
784
- fn=lambda vars: {"visible": len(vars) > 0},
785
- inputs=[custom_vars_list],
786
- outputs=[update_delete_accordion],
787
- )
788
-
789
- # Update environment variable button click event
790
- update_var_button.click(
791
- fn=update_custom_env_var,
792
- inputs=[custom_var_dropdown, update_var_value, update_var_type],
793
- outputs=[update_var_status, custom_vars_list],
794
- )
795
-
796
- # Delete environment variable button click event
797
- delete_var_button.click(
798
- fn=delete_custom_env_var,
799
- inputs=[custom_var_dropdown],
800
- outputs=[update_var_status, custom_vars_list],
801
- ).then(
802
- fn=lambda vars: {"visible": len(vars) > 0},
803
- inputs=[custom_vars_list],
804
- outputs=[update_delete_accordion],
805
- )
806
-
807
- # When custom environment variables list is updated, update dropdown menu options
808
- custom_vars_list.change(
809
- fn=lambda vars: {
810
- "choices": [var["name"] for var in vars],
811
- "value": None,
812
- },
813
- inputs=[custom_vars_list],
814
- outputs=[custom_var_dropdown],
815
- )
816
-
817
- # Existing environment variable configuration
818
- for group_name, vars in ENV_GROUPS.items():
819
- if (
820
- group_name != "Custom Environment Variables" or len(vars) > 0
821
- ): # Only show non-empty custom environment variable groups
822
- with gr.Accordion(
823
- group_name,
824
- open=(group_name != "Custom Environment Variables"),
825
- ):
826
- for var in vars:
827
- # Add help information
828
- gr.Markdown(f"**{var['help']}**")
829
-
830
- if var["type"] == "password":
831
- env_inputs[var["name"]] = gr.Textbox(
832
- value=env_vars.get(var["name"], ""),
833
- label=var["label"],
834
- placeholder=f"Please enter {var['label']}",
835
- type="password",
836
- )
837
- else:
838
- env_inputs[var["name"]] = gr.Textbox(
839
- value=env_vars.get(var["name"], ""),
840
- label=var["label"],
841
- placeholder=f"Please enter {var['label']}",
842
- )
843
-
844
- save_button = gr.Button("Save Environment Variables", variant="primary")
845
-
846
- # Save environment variables
847
- save_inputs = [
848
- env_inputs[var_name]
849
- for group in ENV_GROUPS.values()
850
- for var in group
851
- for var_name in [var["name"]]
852
- if var_name in env_inputs
853
- ]
854
- save_button.click(
855
- fn=lambda *values: save_env_vars(
856
- dict(
857
- zip(
858
- [
859
- var["name"]
860
- for group in ENV_GROUPS.values()
861
- for var in group
862
- if var["name"] in env_inputs
863
- ],
864
- values,
865
- )
866
- )
867
- ),
868
- inputs=save_inputs,
869
- outputs=save_status,
870
- )
871
-
872
- # Run script
873
- run_button.click(
874
- fn=run_script,
875
- inputs=[script_dropdown, question_input],
876
- outputs=[
877
- status_output,
878
- answer_output,
879
- log_output,
880
- log_file_output,
881
- chat_output,
882
- ],
883
- show_progress=True,
884
- )
885
-
886
- # Terminate execution
887
- stop_button.click(fn=terminate_process, inputs=[], outputs=[status_output])
888
-
889
- # Add footer
890
- gr.Markdown(
891
- """
892
- ### 📝 Instructions
893
-
894
- - Select a model and enter your question
895
- - Click the "Run" button to start execution
896
- - To stop execution, click the "Stop" button
897
- - View execution status and answers in the "Results" tab
898
- - View complete logs in the "Run Logs" tab
899
- - View conversation history in the "Chat History" tab (if available)
900
- - Configure API keys and other environment variables in the "Environment Variable Configuration" tab
901
- - You can add custom environment variables to meet special requirements
902
-
903
- ### ⚠️ Notes
904
-
905
- - Running some models may require API keys, please make sure you have set the corresponding environment variables in the "Environment Variable Configuration" tab
906
- - Some scripts may take a long time to run, please be patient
907
- - If execution exceeds 30 minutes, the process will automatically terminate
908
- - Your question will replace the default question in the script, ensure the question is compatible with the selected model
909
- """
910
- )
911
-
912
- return app
913
-
914
-
915
- if __name__ == "__main__":
916
- # Create and launch the application
917
- app = create_ui()
918
- app.queue().launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
owl/{run.py → examples/run.py} RENAMED
File without changes
owl/{run_deepseek_zh.py → examples/run_deepseek_zh.py} RENAMED
File without changes
owl/{run_gaia_roleplaying.py → examples/run_gaia_roleplaying.py} RENAMED
File without changes
owl/{run_mini.py → examples/run_mini.py} RENAMED
File without changes
owl/{run_ollama.py → examples/run_ollama.py} RENAMED
File without changes
owl/{run_openai_compatiable_model.py → examples/run_openai_compatiable_model.py} RENAMED
File without changes
owl/{run_qwen_mini_zh.py → examples/run_qwen_mini_zh.py} RENAMED
File without changes
owl/{run_qwen_zh.py → examples/run_qwen_zh.py} RENAMED
File without changes
owl/{run_terminal.py → examples/run_terminal.py} RENAMED
File without changes
owl/{run_terminal_zh.py → examples/run_terminal_zh.py} RENAMED
File without changes
owl/script_adapter.py DELETED
@@ -1,267 +0,0 @@
1
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
- import os
15
- import sys
16
- import importlib.util
17
- import re
18
- from pathlib import Path
19
- import traceback
20
-
21
-
22
- def load_module_from_path(module_name, file_path):
23
- """从文件路径加载Python模块"""
24
- try:
25
- spec = importlib.util.spec_from_file_location(module_name, file_path)
26
- if spec is None:
27
- print(f"错误: 无法从 {file_path} 创建模块规范")
28
- return None
29
-
30
- module = importlib.util.module_from_spec(spec)
31
- sys.modules[module_name] = module
32
- spec.loader.exec_module(module)
33
- return module
34
- except Exception as e:
35
- print(f"加载模块时出错: {e}")
36
- traceback.print_exc()
37
- return None
38
-
39
-
40
- def run_script_with_env_question(script_name):
41
- """使用环境变量中的问题运行脚本"""
42
- # 获取环境变量中的问题
43
- question = os.environ.get("OWL_QUESTION")
44
- if not question:
45
- print("错误: 未设置OWL_QUESTION环境变量")
46
- sys.exit(1)
47
-
48
- # 脚本路径
49
- script_path = Path(script_name).resolve()
50
- if not script_path.exists():
51
- print(f"错误: 脚本 {script_path} 不存在")
52
- sys.exit(1)
53
-
54
- # 创建临时文件路径
55
- temp_script_path = script_path.with_name(f"temp_{script_path.name}")
56
-
57
- try:
58
- # 读取脚本内容
59
- try:
60
- with open(script_path, "r", encoding="utf-8") as f:
61
- content = f.read()
62
- except Exception as e:
63
- print(f"读取脚本文件时出错: {e}")
64
- sys.exit(1)
65
-
66
- # 检查脚本是否有main函数
67
- has_main = re.search(r"def\s+main\s*\(\s*\)\s*:", content) is not None
68
-
69
- # 转义问题中的特殊字符
70
- escaped_question = (
71
- question.replace("\\", "\\\\")
72
- .replace('"', '\\"')
73
- .replace("'", "\\'")
74
- .replace("\n", "\\n") # 转义换行符
75
- .replace("\r", "\\r") # 转义回车符
76
- )
77
-
78
- # 查找脚本中所有的question赋值 - 改进的正则表达式
79
- # 匹配单行和多行字符串赋值
80
- question_assignments = re.findall(
81
- r'question\s*=\s*(?:["\'].*?["\']|""".*?"""|\'\'\'.*?\'\'\'|\(.*?\))',
82
- content,
83
- re.DOTALL,
84
- )
85
- print(f"在脚本中找到 {len(question_assignments)} 个question赋值")
86
-
87
- # 修改脚本内容,替换所有的question赋值
88
- modified_content = content
89
-
90
- # 如果脚本中有question赋值,替换所有的赋值
91
- if question_assignments:
92
- for assignment in question_assignments:
93
- modified_content = modified_content.replace(
94
- assignment, f'question = "{escaped_question}"'
95
- )
96
- print(f"已替换脚本中的所有question赋值为: {question}")
97
- else:
98
- # 如果没有找到question赋值,尝试在main函数前插入
99
- if has_main:
100
- main_match = re.search(r"def\s+main\s*\(\s*\)\s*:", content)
101
- if main_match:
102
- insert_pos = main_match.start()
103
- modified_content = (
104
- content[:insert_pos]
105
- + f'\n# 用户输入的问题\nquestion = "{escaped_question}"\n\n'
106
- + content[insert_pos:]
107
- )
108
- print(f"已在main函数前插入问题: {question}")
109
- else:
110
- # 如果没有main函数,在文件开头插入
111
- modified_content = (
112
- f'# 用户输入的问题\nquestion = "{escaped_question}"\n\n' + content
113
- )
114
- print(f"已在文件开头插入问题: {question}")
115
-
116
- # 添加monkey patch代码,确保construct_society函数使用用户的问题
117
- monkey_patch_code = f"""
118
- # 确保construct_society函数使用用户的问题
119
- original_construct_society = globals().get('construct_society')
120
- if original_construct_society:
121
- def patched_construct_society(*args, **kwargs):
122
- # 忽略传入的参数,始终使用用户的问题
123
- return original_construct_society("{escaped_question}")
124
-
125
- # 替换原始函数
126
- globals()['construct_society'] = patched_construct_society
127
- print("已修补construct_society函数��确保使用用户问题")
128
- """
129
-
130
- # 在文件末尾添加monkey patch代码
131
- modified_content += monkey_patch_code
132
-
133
- # 如果脚本没有调用main函数,添加调用代码
134
- if has_main and "__main__" not in content:
135
- modified_content += """
136
-
137
- # 确保调用main函数
138
- if __name__ == "__main__":
139
- main()
140
- """
141
- print("已添加main函数调用代码")
142
-
143
- # 如果脚本没有construct_society调用,添加调用代码
144
- if (
145
- "construct_society" in content
146
- and "run_society" in content
147
- and "Answer:" not in content
148
- ):
149
- modified_content += f"""
150
-
151
- # 确保执行construct_society和run_society
152
- if "construct_society" in globals() and "run_society" in globals():
153
- try:
154
- society = construct_society("{escaped_question}")
155
- from utils import run_society
156
- answer, chat_history, token_count = run_society(society)
157
- print(f"Answer: {{answer}}")
158
- except Exception as e:
159
- print(f"运行时出错: {{e}}")
160
- import traceback
161
- traceback.print_exc()
162
- """
163
- print("已添加construct_society和run_society调用代码")
164
-
165
- # 执行修改后的脚本
166
- try:
167
- # 将脚本目录添加到sys.path
168
- script_dir = script_path.parent
169
- if str(script_dir) not in sys.path:
170
- sys.path.insert(0, str(script_dir))
171
-
172
- # 创建临时文件
173
- try:
174
- with open(temp_script_path, "w", encoding="utf-8") as f:
175
- f.write(modified_content)
176
- print(f"已创建临时脚本文件: {temp_script_path}")
177
- except Exception as e:
178
- print(f"创建临时脚本文件时出错: {e}")
179
- sys.exit(1)
180
-
181
- try:
182
- # 直接执行临时脚本
183
- print("开始执行脚本...")
184
-
185
- # 如果有main函数,加载模块并调用main
186
- if has_main:
187
- # 加载临时模块
188
- module_name = f"temp_{script_path.stem}"
189
- module = load_module_from_path(module_name, temp_script_path)
190
-
191
- if module is None:
192
- print(f"错误: 无法加载模块 {module_name}")
193
- sys.exit(1)
194
-
195
- # 确保模块中有question变量,并且值是用户输入的问题
196
- setattr(module, "question", question)
197
-
198
- # 如果模块中有construct_society函数,修补它
199
- if hasattr(module, "construct_society"):
200
- original_func = module.construct_society
201
-
202
- def patched_func(*args, **kwargs):
203
- return original_func(question)
204
-
205
- module.construct_society = patched_func
206
- print("已在模块级别修补construct_society函数")
207
-
208
- # 调用main函数
209
- if hasattr(module, "main"):
210
- print("调用main函数...")
211
- module.main()
212
- else:
213
- print(f"错误: 脚本 {script_path} 中没有main函数")
214
- sys.exit(1)
215
- else:
216
- # 如果没有main函数,直接执行修改后的脚本
217
- print("直接执行脚本内容...")
218
- # 使用更安全的方式执行脚本
219
- with open(temp_script_path, "r", encoding="utf-8") as f:
220
- script_code = f.read()
221
-
222
- # 创建一个安全的全局命名空间
223
- safe_globals = {
224
- "__file__": str(temp_script_path),
225
- "__name__": "__main__",
226
- }
227
- # 添加内置函数
228
- safe_globals.update(
229
- {k: v for k, v in globals().items() if k in ["__builtins__"]}
230
- )
231
-
232
- # 执行脚本
233
- exec(script_code, safe_globals)
234
-
235
- except Exception as e:
236
- print(f"执行脚本时出错: {e}")
237
- traceback.print_exc()
238
- sys.exit(1)
239
-
240
- except Exception as e:
241
- print(f"处理脚本时出错: {e}")
242
- traceback.print_exc()
243
- sys.exit(1)
244
-
245
- except Exception as e:
246
- print(f"处理脚本时出错: {e}")
247
- traceback.print_exc()
248
- sys.exit(1)
249
-
250
- finally:
251
- # 删除临时文件
252
- if temp_script_path.exists():
253
- try:
254
- temp_script_path.unlink()
255
- print(f"已删除临时脚本文件: {temp_script_path}")
256
- except Exception as e:
257
- print(f"删除临时脚本文件时出错: {e}")
258
-
259
-
260
- if __name__ == "__main__":
261
- # 检查命令行参数
262
- if len(sys.argv) < 2:
263
- print("用法: python script_adapter.py <script_path>")
264
- sys.exit(1)
265
-
266
- # 运行指定的脚本
267
- run_script_with_env_question(sys.argv[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
owl/webapp.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import from the correct module path
2
+ from owl.utils import run_society
3
+ import os
4
+ import gradio as gr
5
+ import time
6
+ import json
7
+ from typing import Tuple, List, Dict, Any
8
+ import importlib
9
+
10
+ # Enhanced CSS with navigation bar and additional styling
11
+ custom_css = """
12
+ :root {
13
+ --primary-color: #1e3c72;
14
+ --secondary-color: #2a5298;
15
+ --accent-color: #4776E6;
16
+ --light-bg: #f8f9fa;
17
+ --border-color: #dee2e6;
18
+ --text-muted: #6c757d;
19
+ }
20
+
21
+ .container {
22
+ max-width: 1200px;
23
+ margin: 0 auto;
24
+ }
25
+
26
+ .navbar {
27
+ display: flex;
28
+ justify-content: space-between;
29
+ align-items: center;
30
+ padding: 15px 30px;
31
+ background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
32
+ color: white;
33
+ border-radius: 10px 10px 0 0;
34
+ margin-bottom: 0;
35
+ }
36
+
37
+ .navbar-logo {
38
+ display: flex;
39
+ align-items: center;
40
+ gap: 10px;
41
+ font-size: 1.5em;
42
+ font-weight: bold;
43
+ }
44
+
45
+ .navbar-menu {
46
+ display: flex;
47
+ gap: 20px;
48
+ }
49
+
50
+ .navbar-menu a {
51
+ color: white;
52
+ text-decoration: none;
53
+ padding: 5px 10px;
54
+ border-radius: 5px;
55
+ transition: background-color 0.3s;
56
+ }
57
+
58
+ .navbar-menu a:hover {
59
+ background-color: rgba(255, 255, 255, 0.1);
60
+ }
61
+
62
+ .header {
63
+ text-align: center;
64
+ margin-bottom: 20px;
65
+ background: linear-gradient(180deg, var(--secondary-color), var(--accent-color));
66
+ color: white;
67
+ padding: 40px 20px;
68
+ border-radius: 0 0 10px 10px;
69
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
70
+ }
71
+
72
+ .module-info {
73
+ background-color: var(--light-bg);
74
+ border-left: 5px solid var(--primary-color);
75
+ padding: 10px 15px;
76
+ margin-top: 10px;
77
+ border-radius: 5px;
78
+ font-size: 0.9em;
79
+ }
80
+
81
+ .answer-box {
82
+ background-color: var(--light-bg);
83
+ border-left: 5px solid var(--secondary-color);
84
+ padding: 15px;
85
+ margin-bottom: 20px;
86
+ border-radius: 5px;
87
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
88
+ }
89
+
90
+ .token-count {
91
+ background-color: #e9ecef;
92
+ padding: 10px;
93
+ border-radius: 5px;
94
+ text-align: center;
95
+ font-weight: bold;
96
+ margin-bottom: 20px;
97
+ }
98
+
99
+ .chat-container {
100
+ border: 1px solid var(--border-color);
101
+ border-radius: 5px;
102
+ max-height: 500px;
103
+ overflow-y: auto;
104
+ margin-bottom: 20px;
105
+ }
106
+
107
+ .footer {
108
+ text-align: center;
109
+ margin-top: 20px;
110
+ color: var(--text-muted);
111
+ font-size: 0.9em;
112
+ padding: 20px;
113
+ border-top: 1px solid var(--border-color);
114
+ }
115
+
116
+ .features-section {
117
+ display: grid;
118
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
119
+ gap: 20px;
120
+ margin: 20px 0;
121
+ }
122
+
123
+ .feature-card {
124
+ background-color: white;
125
+ border-radius: 8px;
126
+ padding: 20px;
127
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
128
+ transition: transform 0.3s, box-shadow 0.3s;
129
+ }
130
+
131
+ .feature-card:hover {
132
+ transform: translateY(-5px);
133
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
134
+ }
135
+
136
+ .feature-icon {
137
+ font-size: 2em;
138
+ color: var(--primary-color);
139
+ margin-bottom: 10px;
140
+ }
141
+
142
+ /* Improved button and input styles */
143
+ button.primary {
144
+ background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
145
+ transition: all 0.3s;
146
+ }
147
+
148
+ button.primary:hover {
149
+ background: linear-gradient(90deg, var(--secondary-color), var(--primary-color));
150
+ transform: translateY(-2px);
151
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
152
+ }
153
+ """
154
+
155
+ # Dictionary containing module descriptions
156
+ MODULE_DESCRIPTIONS = {
157
+ "run": "默认模式:使用默认的智能体协作模式,适合大多数任务。",
158
+ "run_mini":"使用最小化配置处理任务",
159
+ "run_deepseek_zh":"使用deepseek模型处理中文任务",
160
+ "run_terminal_zh": "终端模式:可执行命令行操作,支持网络搜索、文件处理等功能。适合需要系统交互的任务。",
161
+ "run_mini": "精简模式:轻量级智能体协作,适合快速回答和简单任务处理,响应速度更快。",
162
+ "run_gaia_roleplaying":"GAIA基准测试实现,用于评估模型能力",
163
+ "run_openai_compatiable_model":"使用openai兼容模型处理任务",
164
+ "run_ollama":"使用本地ollama模型处理任务",
165
+ "run_qwen_mini_zh":"使用qwen模型处理中文任务",
166
+ "run_qwen_zh":"使用qwen模型处理任务",
167
+
168
+
169
+
170
+ }
171
+
172
+ def format_chat_history(chat_history: List[Dict[str, str]]) -> List[List[str]]:
173
+ """将聊天历史格式化为Gradio聊天组件可接受的格式
174
+
175
+ Args:
176
+ chat_history: 原始聊天历史
177
+
178
+ Returns:
179
+ List[List[str]]: 格式化后的聊天历史
180
+ """
181
+ formatted_history = []
182
+ for message in chat_history:
183
+ user_msg = message.get("user", "")
184
+ assistant_msg = message.get("assistant", "")
185
+
186
+ if user_msg:
187
+ formatted_history.append([user_msg, None])
188
+ if assistant_msg and formatted_history:
189
+ formatted_history[-1][1] = assistant_msg
190
+ elif assistant_msg:
191
+ formatted_history.append([None, assistant_msg])
192
+
193
+ return formatted_history
194
+
195
+ def run_owl(question: str, example_module: str) -> Tuple[str, List[List[str]], str, str]:
196
+ """运行OWL系统并返回结果
197
+
198
+ Args:
199
+ question: 用户问题
200
+ example_module: 要导入的示例模块名(如 "run_terminal_zh" 或 "run_deep")
201
+
202
+ Returns:
203
+ Tuple[...]: 回答、聊天历史、令牌计数、状态
204
+ """
205
+ try:
206
+ # 动态导入目标模块
207
+ module_path = f"owl.examples.{example_module}"
208
+ module = importlib.import_module(module_path)
209
+
210
+ # 检查是否包含construct_society函数
211
+ if not hasattr(module, "construct_society"):
212
+ raise AttributeError(f"模块 {module_path} 中未找到 construct_society 函数")
213
+
214
+ # 构建社会模拟
215
+ society = module.construct_society(question)
216
+
217
+ # 运行社会模拟(假设run_society兼容不同模块)
218
+ answer, chat_history, token_info = run_society(society)
219
+
220
+ # 格式化和令牌计数(与原逻辑一致)
221
+ formatted_chat_history = format_chat_history(chat_history)
222
+ total_tokens = token_info["completion_token_count"] + token_info["prompt_token_count"]
223
+
224
+ return (
225
+ answer,
226
+ formatted_chat_history,
227
+ f"完成令牌: {token_info['completion_token_count']:,} | 提示令牌: {token_info['prompt_token_count']:,} | 总计: {total_tokens:,}",
228
+ "✅ 成功完成"
229
+ )
230
+
231
+ except Exception as e:
232
+ return (
233
+ f"发生错误: {str(e)}",
234
+ [],
235
+ "0",
236
+ f"❌ 错误: {str(e)}"
237
+ )
238
+
239
+ def update_module_description(module_name: str) -> str:
240
+ """返回所选模块的描述"""
241
+ return MODULE_DESCRIPTIONS.get(module_name, "无可用描述")
242
+
243
+ def create_ui():
244
+ """创建增强版Gradio界面"""
245
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="blue")) as app:
246
+ with gr.Column(elem_classes="container"):
247
+ gr.HTML("""
248
+ <div class="navbar">
249
+ <div class="navbar-logo">
250
+ 🦉 OWL 智能助手
251
+ </div>
252
+ <div class="navbar-menu">
253
+ <a href="#home">首页</a>
254
+ <a href="#features">功能</a>
255
+ <a href="#about">关于</a>
256
+ <a href="#docs">文档</a>
257
+ <a href="#contact">联系我们</a>
258
+ </div>
259
+ </div>
260
+ <div class="header" id="home">
261
+ <h1>多智能体协作系统</h1>
262
+ <p>基于CAMEL框架的先进多智能体协作平台,解决复杂问题的智能解决方案</p>
263
+ </div>
264
+ """)
265
+
266
+ with gr.Row(elem_id="features"):
267
+ gr.HTML("""
268
+ <div class="features-section">
269
+ <div class="feature-card">
270
+ <div class="feature-icon">🔍</div>
271
+ <h3>智能信息获取</h3>
272
+ <p>自动化网络搜索和数据收集,提供精准信息</p>
273
+ </div>
274
+ <div class="feature-card">
275
+ <div class="feature-icon">🤖</div>
276
+ <h3>多智能体协作</h3>
277
+ <p>多个专家智能体协同工作,解决复杂问题</p>
278
+ </div>
279
+ <div class="feature-card">
280
+ <div class="feature-icon">📊</div>
281
+ <h3>数据分析与可视化</h3>
282
+ <p>强大的数据分析能力,生成直观的可视化结果</p>
283
+ </div>
284
+ </div>
285
+ """)
286
+
287
+ with gr.Row():
288
+ with gr.Column(scale=2):
289
+ question_input = gr.Textbox(
290
+ lines=5,
291
+ placeholder="请输入您的问题...",
292
+ label="问题",
293
+ elem_id="question_input",
294
+ show_copy_button=True,
295
+ )
296
+
297
+ # 增强版模块选择下拉菜单
298
+ module_dropdown = gr.Dropdown(
299
+ choices=["run", "run_mini","run_terminal_zh","run_gaia_roleplaying",
300
+ "run_openai_compatiable_model","run_ollama","run_qwen_zh","run_qwen_mini_zh","run_deepseek_zh","run_terminal"],
301
+ value="run_terminal_zh",
302
+ label="选择功能模块",
303
+ interactive=True
304
+ )
305
+
306
+ # 模块描述文本框
307
+ module_description = gr.Textbox(
308
+ value=MODULE_DESCRIPTIONS["run_terminal_zh"],
309
+ label="模块描述",
310
+ interactive=False,
311
+ elem_classes="module-info"
312
+ )
313
+
314
+ run_button = gr.Button("运行", variant="primary", elem_classes="primary")
315
+
316
+ with gr.Column(scale=1):
317
+ gr.Markdown("""
318
+ ### 使用指南
319
+
320
+ 1. **选择适合的模块**:根据您的任务需求选择合适的功能模块
321
+ 2. **详细描述您的需求**:在输入框中清晰描述您的问题或任务
322
+ 3. **启动智能处理**:点击"运行"按钮开始多智能体协作处理
323
+ 4. **查看结果**:在下方标签页查看回答和完整对话历史
324
+
325
+ > **高级提示**: 对于复杂任务,可以尝试指定具体步骤和预期结果
326
+ """)
327
+
328
+ status_output = gr.Textbox(label="状态", interactive=False)
329
+
330
+ with gr.Tabs():
331
+ with gr.TabItem("回答"):
332
+ answer_output = gr.Textbox(
333
+ label="回答",
334
+ lines=10,
335
+ elem_classes="answer-box"
336
+ )
337
+
338
+ with gr.TabItem("对话历史"):
339
+ chat_output = gr.Chatbot(
340
+ label="完整对话记录",
341
+ elem_classes="chat-container",
342
+ height=500
343
+ )
344
+
345
+
346
+
347
+ token_count_output = gr.Textbox(
348
+ label="令牌计数",
349
+ interactive=False,
350
+ elem_classes="token-count"
351
+ )
352
+
353
+ # 示例问题
354
+ examples = [
355
+ "打开百度搜索,总结一下camel-ai的camel框架的github star、fork数目等,并把数字用plot包写成python文件保存到本地,用本地终端执行python文件显示图出来给我",
356
+ "请分析GitHub上CAMEL-AI项目的最新统计数据。找出该项目的星标数量、贡献者数量和最近的活跃度。",
357
+ "浏览亚马逊并找出一款对程序员有吸引力的产品。请提供产品名称和价格",
358
+ "写一个hello world的python文件,保存到本地",
359
+
360
+ ]
361
+
362
+ gr.Examples(
363
+ examples=examples,
364
+ inputs=question_input
365
+ )
366
+
367
+ gr.HTML("""
368
+ <div class="footer" id="about">
369
+ <h3>关于 OWL 智能助手</h3>
370
+ <p>OWL 是一个基于CAMEL框架开发的先进多智能体协作系统,旨在通过智能体协作解决复杂问题。</p>
371
+ <p>© 2024 CAMEL-AI.org. 基于Apache License 2.0开源协议</p>
372
+ <p><a href="https://github.com/camel-ai/camel" target="_blank">GitHub</a> |
373
+ <a href="#docs">文档</a> |
374
+ <a href="#contact" id="contact">联系我们</a></p>
375
+ </div>
376
+ """)
377
+
378
+ # 设置事件处理
379
+ run_button.click(
380
+ fn=run_owl,
381
+ inputs=[question_input, module_dropdown],
382
+ outputs=[answer_output, chat_output, token_count_output, status_output]
383
+ )
384
+
385
+ # 模块选择更新描述
386
+ module_dropdown.change(
387
+ fn=update_module_description,
388
+ inputs=module_dropdown,
389
+ outputs=module_description
390
+ )
391
+
392
+ return app
393
+
394
+ # 主函数
395
+ def main():
396
+ app = create_ui()
397
+ app.launch(share=False)
398
+
399
+ if __name__ == "__main__":
400
+ main()
run_app.py DELETED
@@ -1,62 +0,0 @@
1
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
- #!/usr/bin/env python
15
- # -*- coding: utf-8 -*-
16
-
17
- """
18
- OWL Intelligent Assistant Platform Launch Script
19
- """
20
-
21
- import os
22
- import sys
23
- from pathlib import Path
24
-
25
- os.environ['PYTHONIOENCODING'] = 'utf-8'
26
-
27
- def main():
28
- """Main function to launch the OWL Intelligent Assistant Platform"""
29
- # Ensure the current directory is the project root
30
- project_root = Path(__file__).resolve().parent
31
- os.chdir(project_root)
32
-
33
- # Create log directory
34
- log_dir = project_root / "logs"
35
- log_dir.mkdir(exist_ok=True)
36
-
37
- # Add project root to Python path
38
- sys.path.insert(0, str(project_root))
39
-
40
- try:
41
- from owl.app_en import create_ui
42
-
43
- # Create and launch the application
44
- app = create_ui()
45
- app.queue().launch(share=False)
46
-
47
- except ImportError as e:
48
- print(
49
- f"Error: Unable to import necessary modules. Please ensure all dependencies are installed: {e}"
50
- )
51
- print("Tip: Run 'pip install -r requirements.txt' to install all dependencies")
52
- sys.exit(1)
53
- except Exception as e:
54
- print(f"Error occurred while starting the application: {e}")
55
- import traceback
56
-
57
- traceback.print_exc()
58
- sys.exit(1)
59
-
60
-
61
- if __name__ == "__main__":
62
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
run_app_zh.py DELETED
@@ -1,60 +0,0 @@
1
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
- #!/usr/bin/env python
15
- # -*- coding: utf-8 -*-
16
-
17
- """
18
- OWL 智能助手运行平台启动脚本
19
- """
20
-
21
- import os
22
- import sys
23
- from pathlib import Path
24
-
25
- os.environ['PYTHONIOENCODING'] = 'utf-8'
26
-
27
- def main():
28
- """主函数,启动OWL智能助手运行平台"""
29
- # 确保当前目录是项目根目录
30
- project_root = Path(__file__).resolve().parent
31
- os.chdir(project_root)
32
-
33
- # 创建日志目录
34
- log_dir = project_root / "logs"
35
- log_dir.mkdir(exist_ok=True)
36
-
37
- # 导入并运行应用
38
- sys.path.insert(0, str(project_root))
39
-
40
- try:
41
- from owl.app import create_ui
42
-
43
- # 创建并启动应用
44
- app = create_ui()
45
- app.queue().launch(share=False)
46
-
47
- except ImportError as e:
48
- print(f"错误: 无法导入必要的模块。请确保已安装所有依赖项: {e}")
49
- print("提示: 运行 'pip install -r requirements.txt' 安装所有依赖项")
50
- sys.exit(1)
51
- except Exception as e:
52
- print(f"启动应用程序时出错: {e}")
53
- import traceback
54
-
55
- traceback.print_exc()
56
- sys.exit(1)
57
-
58
-
59
- if __name__ == "__main__":
60
- main()