-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
2177 lines (1859 loc) · 91.5 KB
/
agent.py
File metadata and controls
2177 lines (1859 loc) · 91.5 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
import os
import sys
import subprocess
import json
import psutil
import platform
from typing import List, Dict, Any, Optional, Generator, Tuple, Union, Callable
from datetime import datetime
import threading
import time
import re
import enum
import unicodedata
# LangChain imports
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langchain.tools import BaseTool
from langchain.schema import BaseOutputParser
from langchain_core.callbacks import StreamingStdOutCallbackHandler
import asyncio
from langchain_core.callbacks.base import BaseCallbackHandler
# 全局变量,用于工具访问R1增强器
intelligent_assistant = None
class MacOSTools:
"""macOS系统工具集合"""
# 添加一个类变量存储当前的R1增强器
r1_enhancer = None
@classmethod
def set_r1_enhancer(cls, enhancer):
"""设置R1增强器"""
cls.r1_enhancer = enhancer
@staticmethod
@tool
def get_system_info() -> str:
"""获取macOS系统信息"""
try:
# 系统版本信息
version_info = subprocess.run(['sw_vers'], capture_output=True, text=True)
# CPU信息
cpu_info = subprocess.run(['sysctl', '-n', 'machdep.cpu.brand_string'], capture_output=True, text=True)
# 内存信息
memory = psutil.virtual_memory()
# 磁盘信息
disk = psutil.disk_usage('/')
info = f"""
系统信息:
{version_info.stdout}
CPU: {cpu_info.stdout.strip()}
内存: {memory.total // (1024**3)}GB 总内存, {memory.percent}% 使用率
磁盘: {disk.total // (1024**3)}GB 总空间, {disk.percent}% 使用率
"""
return info
except Exception as e:
return f"获取系统信息失败: {str(e)}"
@staticmethod
@tool
def get_running_processes() -> str:
"""获取正在运行的进程列表"""
try:
processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
try:
processes.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
# 按CPU使用率排序,取前10个
processes.sort(key=lambda x: x['cpu_percent'], reverse=True)
top_processes = processes[:10]
result = "正在运行的进程 (按CPU使用率排序):\n"
for proc in top_processes:
result += f"PID: {proc['pid']}, 名称: {proc['name']}, CPU: {proc['cpu_percent']:.1f}%, 内存: {proc['memory_percent']:.1f}%\n"
return result
except Exception as e:
return f"获取进程信息失败: {str(e)}"
@staticmethod
@tool
def open_application(app_name: str) -> str:
"""增强:支持别名、拼音、英文、中文混输,模糊匹配"""
try:
import difflib
import unicodedata
# 获取所有已安装应用
all_apps = MacOSTools._get_all_applications()
if not all_apps:
return "无法获取应用程序列表"
# 别名表
aliases = {
'safari': ['safari', '浏览器', 'web', 'sāfārī', 'sfl', '苹果浏览器'],
'chrome': ['chrome', 'google chrome', '谷歌浏览器', 'gǔgē', '谷歌', 'chromium'],
'finder': ['finder', '访达', '文件管理器', 'fǎngdá'],
'terminal': ['terminal', '终端', '命令行', 'zhōngduān'],
'wechat': ['wechat', '微信', 'wēixìn'],
'qq': ['qq', '腾讯qq', 'q q'],
'vscode': ['visual studio code', 'vscode', 'vs code', '代码编辑器'],
'notes': ['notes', '备忘录', '笔记'],
'music': ['music', '音乐', 'itunes'],
'photos': ['photos', '照片', '相册'],
'mail': ['mail', '邮件', '邮箱'],
'messages': ['messages', '信息', '短信'],
'calendar': ['calendar', '日历'],
'preview': ['preview', '预览'],
'appstore': ['app store', 'appstore', '应用商店'],
'reminders': ['reminders', '提醒事项'],
'calculator': ['calculator', '计算器'],
'sublime': ['sublime text', 'sublime', '文本编辑器'],
'bilibili': ['bilibili', 'b站', '哔哩哔哩'],
'alipay': ['alipay', '支付宝'],
'taobao': ['taobao', '淘宝'],
'jd': ['jd', '京东'],
'netflix': ['netflix', '网飞'],
'youtube': ['youtube', '油管'],
}
# 归一化
def norm(s):
return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode('ascii').lower()
app_name_norm = norm(app_name)
# 先查别名
for key, alias_list in aliases.items():
if app_name_norm in [norm(a) for a in alias_list]:
for app in all_apps:
if norm(app['name']) == norm(key):
subprocess.run(['open', app['path']])
return f"已打开 {app['name']}"
# 模糊匹配
all_names = [app['name'] for app in all_apps]
matches = difflib.get_close_matches(app_name, all_names, n=1, cutoff=0.6)
if matches:
best = next(app for app in all_apps if app['name'] == matches[0])
subprocess.run(['open', best['path']])
return f"已打开 {best['name']}"
return f"未找到匹配的应用程序: {app_name}"
except Exception as e:
return f"打开应用程序失败: {str(e)}"
@staticmethod
def _get_all_applications():
"""获取所有已安装的应用程序"""
apps = []
# 搜索系统应用程序目录
search_paths = [
'/Applications',
'/System/Applications',
'/System/Applications/Utilities',
os.path.expanduser('~/Applications')
]
for search_path in search_paths:
if os.path.exists(search_path):
try:
result = subprocess.run(['find', search_path, '-name', '*.app', '-type', 'd'],
capture_output=True, text=True, timeout=10)
if result.stdout.strip():
for app_path in result.stdout.strip().split('\n'):
if app_path and os.path.exists(app_path):
app_name = os.path.basename(app_path).replace('.app', '')
apps.append({
'name': app_name,
'path': app_path,
'display_name': app_name
})
except:
continue
return apps
@staticmethod
def _find_matching_apps(query, apps):
"""智能匹配应用程序"""
query_lower = query.lower().strip()
matches = []
for app in apps:
app_name_lower = app['name'].lower()
display_name_lower = app['display_name'].lower()
# 计算匹配分数
score = 0
# 完全匹配
if query_lower == app_name_lower or query_lower == display_name_lower:
score = 100
# 开头匹配
elif app_name_lower.startswith(query_lower) or display_name_lower.startswith(query_lower):
score = 80
# 包含匹配
elif query_lower in app_name_lower or query_lower in display_name_lower:
score = 60
# 部分词匹配
else:
query_words = query_lower.split()
app_words = app_name_lower.split()
for query_word in query_words:
for app_word in app_words:
if query_word in app_word or app_word in query_word:
score += 20
break
# 特殊处理常见应用程序的别名
aliases = {
'safari': ['safari', '浏览器', 'web'],
'chrome': ['chrome', 'google chrome', '谷歌浏览器'],
'terminal': ['terminal', '终端', '命令行'],
'finder': ['finder', '访达', '文件管理器'],
'calculator': ['calculator', '计算器', 'calc'],
'mail': ['mail', '邮件', '邮箱'],
'messages': ['messages', '信息', '短信'],
'facetime': ['facetime', '视频通话'],
'photos': ['photos', '照片', '相册'],
'music': ['music', '音乐', 'itunes'],
'tv': ['tv', '电视', '视频'],
'podcasts': ['podcasts', '播客'],
'books': ['books', '图书', '阅读'],
'notes': ['notes', '备忘录', '笔记'],
'reminders': ['reminders', '提醒事项'],
'calendar': ['calendar', '日历'],
'contacts': ['contacts', '通讯录', '联系人'],
'maps': ['maps', '地图'],
'weather': ['weather', '天气'],
'stocks': ['stocks', '股票'],
'voice_memos': ['voice memos', '语音备忘录'],
'home': ['home', '家庭'],
'shortcuts': ['shortcuts', '快捷指令'],
'settings': ['settings', '系统偏好设置', '设置'],
'vscode': ['visual studio code', 'vscode', 'vs code', '代码编辑器'],
'premiere': ['adobe premiere pro', 'premiere', 'pr', '视频编辑'],
'photoshop': ['adobe photoshop', 'photoshop', 'ps', '图像编辑'],
'illustrator': ['adobe illustrator', 'illustrator', 'ai', '矢量图'],
'after_effects': ['adobe after effects', 'after effects', 'ae', '特效'],
'xd': ['adobe xd', 'xd', '设计'],
'figma': ['figma', '设计工具'],
'sketch': ['sketch', '设计'],
'xcode': ['xcode', '开发工具'],
'intellij': ['intellij idea', 'intellij', '开发工具'],
'pycharm': ['pycharm', 'python开发'],
'sublime': ['sublime text', 'sublime', '文本编辑器'],
'atom': ['atom', '文本编辑器'],
'spotify': ['spotify', '音乐播放器'],
'zoom': ['zoom', '视频会议'],
'teams': ['microsoft teams', 'teams', '团队协作'],
'slack': ['slack', '团队沟通'],
'discord': ['discord', '游戏聊天'],
'wechat': ['wechat', '微信'],
'qq': ['qq', '腾讯qq'],
'alipay': ['alipay', '支付宝'],
'taobao': ['taobao', '淘宝'],
'jd': ['jd', '京东'],
'netflix': ['netflix', '网飞'],
'youtube': ['youtube', '油管'],
'bilibili': ['bilibili', 'b站', '哔哩哔哩']
}
# 检查别名匹配
for app_key, alias_list in aliases.items():
if query_lower in alias_list:
if app_name_lower in alias_list or any(alias in app_name_lower for alias in alias_list):
score = max(score, 90)
if score > 0:
matches.append((app, score))
# 按分数排序,返回前5个最佳匹配
matches.sort(key=lambda x: x[1], reverse=True)
return [app for app, score in matches[:5]]
@staticmethod
@tool
def execute_terminal_command(command: str) -> str:
"""分步执行&&分割的命令,逐步捕获异常"""
try:
dangerous_commands = [
"rm -rf", "dd if=", "> /dev/", ":(){ :|:& };:",
"chmod -R 777 /", "mv / /dev/null"
]
for dc in dangerous_commands:
if dc in command:
return f"为安全起见,系统拒绝执行包含 '{dc}' 的命令。请确保您的命令是安全的。"
# 分步执行
steps = [c.strip() for c in command.split('&&') if c.strip()]
output = ""
for step in steps:
result = subprocess.run(step, shell=True, capture_output=True, text=True, timeout=10)
out = result.stdout if result.stdout else ""
err = result.stderr if result.stderr else ""
if err:
output += f"命令: {step}\n错误: {err}\n"
break
output += out
return output if output else "命令执行成功"
except subprocess.TimeoutExpired:
return "命令超时(执行时间超过10秒)"
except Exception as e:
return f"执行命令时出错: {str(e)}"
@staticmethod
@tool
def get_network_info() -> str:
"""获取网络连接信息"""
try:
# 获取网络接口信息
interfaces = psutil.net_if_addrs()
# 获取网络连接状态
connections = psutil.net_connections()
result = "网络信息:\n"
# 显示网络接口
for interface, addrs in interfaces.items():
result += f"\n接口: {interface}\n"
for addr in addrs:
result += f" {addr.family.name}: {addr.address}\n"
# 显示活跃连接
active_connections = [conn for conn in connections if conn.status == 'ESTABLISHED']
result += f"\n活跃连接数: {len(active_connections)}"
return result
except Exception as e:
return f"获取网络信息失败: {str(e)}"
@staticmethod
@tool
def get_battery_info() -> str:
"""获取电池信息"""
try:
battery = psutil.sensors_battery()
if battery:
plugged = "已连接电源" if battery.power_plugged else "使用电池"
percent = battery.percent
time_left = battery.secsleft if battery.secsleft != -1 else "未知"
if time_left != "未知":
hours = time_left // 3600
minutes = (time_left % 3600) // 60
time_str = f"{hours}小时{minutes}分钟"
else:
time_str = "未知"
return f"电池状态: {plugged}\n电量: {percent}%\n剩余时间: {time_str}"
else:
return "无法获取电池信息"
except Exception as e:
return f"获取电池信息失败: {str(e)}"
@staticmethod
@tool
def search_files(query: str, directory: str = "/Users") -> str:
"""搜索文件
Args:
query: 搜索查询
directory: 搜索目录,默认为/Users
Returns:
搜索结果
"""
try:
# 尝试使用R1增强器进行搜索
if MacOSTools.r1_enhancer and MacOSTools.r1_enhancer.is_available:
enhanced_results = MacOSTools.r1_enhancer.enhance_file_search(query, directory)
if enhanced_results:
result_text = "查找到以下文件:\n\n"
for item in enhanced_results:
result_text += f"{item['path']} (相关度: {item['relevance']})\n"
return result_text
# 如果R1增强器不可用或未找到结果,使用基本搜索方法
result = subprocess.run(["find", directory, "-name", f"*{query}*", "-type", "f"],
capture_output=True, text=True, timeout=10)
if not result.stdout.strip():
return f"在{directory}中未找到包含'{query}'的文件"
files = result.stdout.strip().split('\n')
return f"找到以下文件:\n\n" + '\n'.join(files[:10]) + (f"\n\n共找到{len(files)}个文件,仅显示前10个" if len(files) > 10 else "")
except Exception as e:
return f"搜索文件时出错: {str(e)}"
@staticmethod
@tool
def get_installed_applications() -> str:
"""获取已安装的应用程序列表"""
try:
# 使用新的动态获取方法
all_apps = MacOSTools._get_all_applications()
if not all_apps:
return "未找到应用程序"
# 按名称排序
all_apps.sort(key=lambda x: x['name'].lower())
# 只显示前30个应用程序
apps_to_show = all_apps[:30]
result = f"已安装的应用程序 (共{len(all_apps)}个,显示前30个):\n"
for i, app in enumerate(apps_to_show, 1):
result += f"{i}. {app['name']}\n"
if len(all_apps) > 30:
result += f"\n... 还有 {len(all_apps) - 30} 个应用程序"
return result
except Exception as e:
return f"获取应用程序列表失败: {str(e)}"
@staticmethod
@tool
def create_note(content: str, filename: str = None) -> str:
"""创建笔记文件,自动创建父目录,支持~、绝对、相对路径"""
try:
import os
if not filename:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"note_{timestamp}.txt"
# 展开~
filepath = os.path.expanduser(filename)
# 如果不是绝对路径,默认放桌面
if not os.path.isabs(filepath):
filepath = os.path.join(os.path.expanduser("~/Desktop"), filepath)
# 自动创建父目录
dirpath = os.path.dirname(filepath)
if not os.path.exists(dirpath):
os.makedirs(dirpath, exist_ok=True)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(f"创建时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("=" * 50 + "\n")
f.write(content)
return f"笔记已创建: {filepath}"
except Exception as e:
return f"创建笔记失败: {str(e)}"
@staticmethod
@tool
def set_system_volume(volume: int) -> str:
"""设置系统音量 (0-100)"""
try:
if not 0 <= volume <= 100:
return "音量必须在0-100之间"
# 使用osascript设置音量
script = f'set volume output volume {volume}'
subprocess.run(['osascript', '-e', script])
return f"系统音量已设置为 {volume}%"
except Exception as e:
return f"设置音量失败: {str(e)}"
@staticmethod
@tool
def get_current_time() -> str:
"""获取当前时间"""
now = datetime.now()
return f"当前时间: {now.strftime('%Y年%m月%d日 %H:%M:%S')}"
class TaskComplexity(enum.Enum):
"""任务复杂度枚举"""
SIMPLE = 1 # 简单任务:直接查询、单一操作
MEDIUM = 2 # 中等任务:2-3步操作,有条件判断
COMPLEX = 3 # 复杂任务:多步骤,需要推理,系统诊断
ADVANCED = 4 # 高级任务:创造性解决方案,复杂诊断,自适应执行
class ArchitectureType(enum.Enum):
"""架构类型枚举"""
DIRECT = 1 # 直接响应,无思考链
BASIC_COT = 2 # 基础思考链
FULL_COT = 3 # 完整思考链
REACT = 4 # Reasoning + Acting 架构
PLANNER = 5 # 完整规划架构
class EnhancedStreamingHandler(BaseCallbackHandler):
"""增强的流式处理回调处理器
支持以下回调:
- streaming_callback: 每个token的回调
- thinking_callback: 思考状态变化的回调
- start_callback: 开始生成时的回调
- end_callback: 结束生成时的回调
- function_call_callback: 函数调用时的回调
- function_result_callback: 函数返回结果时的回调
"""
def __init__(self, streaming_callback=None, thinking_callback=None,
start_callback=None, end_callback=None,
function_call_callback=None, function_result_callback=None):
"""初始化处理器
Args:
streaming_callback: token回调函数
thinking_callback: 思考状态回调函数
start_callback: 开始回调函数
end_callback: 结束回调函数
function_call_callback: 函数调用回调
function_result_callback: 函数结果回调
"""
self.streaming_callback = streaming_callback
self.thinking_callback = thinking_callback
self.start_callback = start_callback
self.end_callback = end_callback
self.function_call_callback = function_call_callback
self.function_result_callback = function_result_callback
# 内部状态
self.response_started = False
self.is_thinking = False
self.current_token_buffer = ""
self.thinking_buffer = ""
self.thinking_markers = [
"思考中", "让我思考", "分析一下", "思考:", "思考:",
"分析:", "分析:", "让我想一想", "考虑一下", "推理:"
]
def on_function_call(self, function_name, arguments):
"""函数调用时的回调
Args:
function_name: 函数名称
arguments: 函数参数
"""
# 如果之前在思考状态,退出思考状态
if self.is_thinking:
self.is_thinking = False
if self.thinking_callback:
self.thinking_callback(False)
if self.function_call_callback:
self.function_call_callback(function_name, arguments)
def on_function_result(self, result):
"""函数返回结果时的回调
Args:
result: 函数返回结果
"""
if self.function_result_callback:
self.function_result_callback(result)
def on_llm_start(self, *args, **kwargs):
"""LLM开始生成时的回调"""
if self.start_callback:
self.start_callback()
def on_llm_new_token(self, token: str, **kwargs):
"""接收新token时的回调"""
# 检测和处理思考模式
if not self.response_started and token.strip():
self.response_started = True
# 更精确地检测思考状态
# 检查是否进入思考状态
if not self.is_thinking:
# 将当前缓冲区与新token组合起来检查
check_text = self.current_token_buffer + token
if any(marker in check_text for marker in self.thinking_markers):
self.is_thinking = True
self.thinking_buffer = check_text # 将当前文本作为思考的起始
if self.thinking_callback:
self.thinking_callback(True)
return
# 如果是思考状态,将token加入思考缓冲区
if self.is_thinking:
self.thinking_buffer += token
# 检查是否退出思考状态(识别思考结束标记)
end_markers = ["结论:", "结论:", "回应:", "回应:", "回答:",
"回答:", "总结:", "总结:", "因此,", "因此,"]
if any(marker in self.thinking_buffer[-20:] for marker in end_markers):
self.is_thinking = False
if self.thinking_callback:
self.thinking_callback(False)
# 在思考状态下不发送token给streaming_callback
return
# 缓冲和处理非思考状态的token
self.current_token_buffer += token
# 当缓冲区包含完整词或标点时才发送
if (len(self.current_token_buffer) > 5 or
any(p in self.current_token_buffer for p in [" ", ".", ",", "!", "?", "\n"])):
if self.streaming_callback:
self.streaming_callback(self.current_token_buffer)
self.current_token_buffer = ""
def on_llm_end(self, *args, **kwargs):
"""LLM结束生成时的回调"""
# 发送任何剩余的缓冲区内容
if self.current_token_buffer and self.streaming_callback:
self.streaming_callback(self.current_token_buffer)
self.current_token_buffer = ""
# 结束思考模式(如果仍在思考)
if self.is_thinking and self.thinking_callback:
self.is_thinking = False
self.thinking_callback(False)
# 调用结束回调
if self.end_callback:
self.end_callback()
# 重置状态
self.response_started = False
self.thinking_buffer = ""
class DeepSeekR1Enhancer:
"""DeepSeek R1模型增强器
用于在特定复杂场景下使用DeepSeek R1模型提高系统智能度
"""
def __init__(self, api_key: str, base_url: str = "https://api.deepseek.com"):
"""初始化R1增强器
Args:
api_key: API密钥
base_url: API基础URL
"""
self.api_key = api_key
self.base_url = base_url
# 创建R1模型LLM (温度较低以提高准确性)
try:
self.r1_llm = ChatOpenAI(
model="deepseek-reasoner", # deepseek-reasoner模型(推理增强型)
openai_api_key=api_key,
openai_api_base=base_url,
temperature=0.3, # 较低的温度以获得更确定性的回答
streaming=True
)
self.is_available = True
except Exception as e:
print(f"初始化DeepSeek Reasoner模型失败: {str(e)}")
self.is_available = False
def is_complex_technical_query(self, query: str) -> bool:
"""判断是否为复杂技术查询
Args:
query: 用户输入
Returns:
是否为复杂技术查询
"""
# 复杂技术查询关键词
technical_keywords = [
"编译", "内核", "驱动程序", "文件系统", "进程管理",
"内存管理", "网络协议", "安全漏洞", "性能优化",
"系统架构", "代码分析", "调试", "异常处理",
"集成", "API接口", "数据库", "缓存", "并发",
"线程", "同步", "异步", "脚本自动化"
]
# 检查是否包含技术关键词
for keyword in technical_keywords:
if keyword in query:
return True
# 检查是否为长查询(长查询可能更复杂)
if len(query) > 100:
return True
return False
def enhance_complexity_evaluation(self, user_input: str, original_complexity: TaskComplexity) -> TaskComplexity:
"""增强任务复杂度评估
Args:
user_input: 用户输入
original_complexity: 原始复杂度评估
Returns:
增强后的复杂度评估
"""
if not self.is_available:
return original_complexity
# 对特定场景使用更精确的复杂度评估
if self.is_complex_technical_query(user_input):
try:
complexity_prompt = """
请评估以下macOS相关任务的复杂度,并返回相应的复杂度级别编号:
1 = 简单任务 (直接查询、单一操作,如查看时间、打开应用)
2 = 中等任务 (2-3步操作,有条件判断,如查找特定文件)
3 = 复杂任务 (多步骤,需要推理,系统诊断,如解决问题)
4 = 高级任务 (创造性解决方案,复杂诊断,自适应执行)
深入分析考虑:
- 任务涉及到的系统组件数量
- 需要的操作步骤
- 是否需要专业知识
- 是否需要处理异常情况
- 是否需要定制化解决方案
只返回一个数字,不要解释。用户任务:"{user_input}"
"""
result = self.r1_llm.invoke(complexity_prompt.format(user_input=user_input))
complexity_text = result.content.strip()
# 提取数字
if '1' in complexity_text:
return TaskComplexity.SIMPLE
elif '2' in complexity_text:
return TaskComplexity.MEDIUM
elif '3' in complexity_text:
return TaskComplexity.COMPLEX
else:
return TaskComplexity.ADVANCED
except:
return original_complexity
return original_complexity
def generate_advanced_plan(self, user_input: str) -> str:
"""使用R1模型生成高级执行计划
Args:
user_input: 用户输入
Returns:
详细的执行计划
"""
if not self.is_available:
return ""
try:
planning_prompt = f"""
针对用户在macOS环境下的以下请求,制定一个详细的执行计划:
用户请求: {user_input}
请提供以下内容的有结构的执行计划:
1. 任务分解: 将主要任务分解为具体子任务
2. 工具选择: 每个子任务使用哪些macOS命令行工具或系统API
3. 执行顺序: 子任务的最佳执行顺序
4. 潜在问题: 可能遇到的问题和解决方案
非常重要: 请以清晰的段落和结构返回,使用明确的标题分隔不同部分。
"""
result = self.r1_llm.invoke(planning_prompt)
plan_text = result.content
# 格式化执行计划,确保有清晰的结构
formatted_plan = "【执行计划】\n"
formatted_plan += "-" * 40 + "\n"
# 尝试识别计划中的各个部分并格式化
sections = ["任务分解", "工具选择", "执行顺序", "潜在问题"]
current_section = ""
for line in plan_text.split('\n'):
# 检查行是否是新的节标题
is_section_header = False
for section in sections:
if section in line and (":" in line or ":" in line or "#" in line or "步骤" in line):
current_section = section
formatted_plan += f"\n● {line.strip()}\n"
is_section_header = True
break
if not is_section_header and line.strip():
if current_section:
formatted_plan += f" {line.strip()}\n"
else:
formatted_plan += f"{line.strip()}\n"
formatted_plan += "-" * 40
return formatted_plan
except Exception as e:
print(f"生成高级计划失败: {str(e)}")
return ""
def optimize_system_command(self, command: str) -> str:
"""优化系统命令
Args:
command: 原始命令
Returns:
优化后的命令
"""
if not self.is_available or not command:
return command
try:
optimization_prompt = f"""
请优化以下macOS终端命令,提高其效率、安全性和可靠性:
原始命令: {command}
请考虑:
1. 安全性改进 (避免潜在风险或数据损失)
2. 效率优化 (更快执行或使用更高效的选项)
3. 错误处理 (添加错误检测或条件执行)
4. 可读性 (如果有助于维护但不影响功能)
只返回优化后的命令,不要解释。如果原命令已经最优,则返回原命令。
"""
result = self.r1_llm.invoke(optimization_prompt)
optimized = result.content.strip()
# 如果优化结果为空或异常,返回原命令
if not optimized or len(optimized) < len(command) / 2:
return command
return optimized
except:
return command
def analyze_error(self, error_message: str, original_command: str) -> Dict[str, str]:
"""分析错误并提供修复建议
Args:
error_message: 错误消息
original_command: 导致错误的原始命令
Returns:
包含错误分析和修复建议的字典
"""
if not self.is_available:
return {"analysis": "", "fix": ""}
try:
error_prompt = f"""
分析以下在macOS终端执行命令时遇到的错误,并提供修复建议:
原始命令: {original_command}
错误消息: {error_message}
请提供:
1. 简洁的错误根本原因分析
2. 推荐的修复命令
以JSON格式回答,包含两个字段: "analysis"和"fix"
"""
result = self.r1_llm.invoke(error_prompt)
# 尝试从回复中提取JSON
content = result.content
try:
import json
# 查找JSON内容
start_idx = content.find('{')
end_idx = content.rfind('}') + 1
if start_idx >= 0 and end_idx > start_idx:
json_str = content[start_idx:end_idx]
return json.loads(json_str)
except:
# 如果JSON解析失败,手动提取关键内容
analysis = ""
fix = ""
if "分析" in content or "原因" in content:
analysis_start = content.find("分析") if "分析" in content else content.find("原因")
analysis_end = content.find("修复") if "修复" in content else len(content)
analysis = content[analysis_start:analysis_end].strip()
if "修复" in content or "建议" in content:
fix_start = content.find("修复") if "修复" in content else content.find("建议")
fix_end = len(content)
fix = content[fix_start:fix_end].strip()
# 尝试提取命令
if "`" in fix:
start_cmd = fix.find("`")
end_cmd = fix.find("`", start_cmd + 1)
if end_cmd > start_cmd:
fix = fix[start_cmd+1:end_cmd]
return {"analysis": analysis, "fix": fix}
return {"analysis": "无法分析错误", "fix": ""}
except Exception as e:
print(f"分析错误失败: {str(e)}")
return {"analysis": "", "fix": ""}
def enhance_file_search(self, query: str, directory: str) -> List[Dict[str, str]]:
"""增强文件搜索功能
Args:
query: 搜索查询
directory: 搜索目录
Returns:
增强的搜索结果
"""
if not self.is_available:
return []
try:
# 使用R1模型生成更智能的搜索命令
search_prompt = f"""
为在macOS上查找以下文件,生成一个高效、准确的find或mdfind命令:
搜索查询: {query}
搜索目录: {directory}
考虑:
1. 根据查询特点选择合适的搜索工具(find适合精确路径搜索,mdfind适合内容搜索)
2. 加入适当的过滤条件(文件类型、大小、修改时间等)
3. 排序方式(最近修改、名称相关性等)
4. 搜索深度限制(避免过深遍历)
只返回一个完整的命令,不要解释。
"""
result = self.r1_llm.invoke(search_prompt)
search_command = result.content.strip()
if not search_command or len(search_command) < 10:
return []
# 提取实际命令(如果有代码块标记)
if "```" in search_command:
parts = search_command.split("```")
for part in parts:
if part.strip() and not part.startswith("bash") and not part.startswith("sh"):
search_command = part.strip()
break
# 执行搜索命令并解析结果
import subprocess
try:
result = subprocess.run(search_command, shell=True, capture_output=True, text=True, timeout=10)
if result.returncode == 0:
files = result.stdout.strip().split('\n')
enhanced_results = []
for file in files[:10]: # 限制为前10个结果
if file.strip():
enhanced_results.append({
"path": file.strip(),
"relevance": "高" # 可以进一步改进相关性评分
})
return enhanced_results
except:
pass
except Exception as e:
print(f"增强文件搜索失败: {str(e)}")
return []
class IntelligentMacOSAssistant:
"""增强智能的macOS系统助手"""
def __init__(self, api_key: str, base_url: str = "https://api.deepseek.com"):
self.api_key = api_key
self.base_url = base_url
# 创建基础LLM
self.llm = ChatOpenAI(
model="deepseek-chat",
openai_api_key=api_key,
openai_api_base=base_url,
temperature=0.7,
streaming=True # 启用流式响应
)
# 创建R1增强器
self.r1_enhancer = DeepSeekR1Enhancer(api_key, base_url)
# 注册R1增强器到MacOSTools类
MacOSTools.set_r1_enhancer(self.r1_enhancer)
# 初始化use_r1_enhancement标志
self.use_r1_enhancement = False
# 获取所有工具
self.tools = [
MacOSTools.get_system_info,
MacOSTools.get_running_processes,
MacOSTools.open_application,
MacOSTools.execute_terminal_command,
MacOSTools.get_network_info,
MacOSTools.get_battery_info,
MacOSTools.search_files,
MacOSTools.get_installed_applications,
MacOSTools.create_note,
MacOSTools.set_system_volume,
MacOSTools.get_current_time
]
# 用户上下文记忆:保存用户偏好和使用模式