forked from CAI-testbooks/LLM-Course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
1387 lines (1147 loc) · 51.4 KB
/
Copy pathagent.py
File metadata and controls
1387 lines (1147 loc) · 51.4 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
"""
四智能体气象RAG系统
多智能体协作框架
"""
import numpy as np
import torch
from typing import Dict, List, Tuple, Optional, Any
import json
import pickle
from pathlib import Path
import warnings
import logging
import re
from datetime import datetime, timedelta
import asyncio
from collections import defaultdict
warnings.filterwarnings('ignore')
from sentence_transformers import SentenceTransformer, util
from config import config
class BaseAgent:
"""智能体基类"""
def __init__(self, name: str, description: str):
self.name = name
self.description = description
self.logger = logging.getLogger(f"Agent.{name}")
def log(self, message: str, level: str = "info"):
"""日志记录"""
getattr(self.logger, level)(f"[{self.name}] {message}")
def validate_input(self, input_data: Any) -> bool:
"""验证输入"""
return True
def process(self, **kwargs) -> Dict:
"""处理函数(子类必须实现)"""
raise NotImplementedError
class RetrievalAgent(BaseAgent):
"""检索智能体 - 负责知识检索"""
def __init__(self, knowledge_path: str = None):
super().__init__(
name="RetrievalAgent",
description="负责从知识库中检索相关信息,提供科学依据和预警指标"
)
self.knowledge_path = knowledge_path or config.paths.get(
"knowledge_json",
"/home/Liyang/agent/knowledge_base.json"
)
# 加载知识库
self.knowledge_base = self._load_knowledge_base()
# 初始化检索模型
model_name = config.knowledge_config.get(
'base_model',
'paraphrase-multilingual-MiniLM-L12-v2'
)
self.model = SentenceTransformer(model_name)
# 准备文档
self.documents, self.doc_embeddings = self._prepare_documents()
self.log(f"初始化完成,加载 {len(self.documents)} 个文档")
def _load_knowledge_base(self) -> Dict:
"""加载知识库"""
knowledge_path = Path(self.knowledge_path)
if not knowledge_path.exists():
self.log(f"警告: 知识库文件不存在: {knowledge_path}", "warning")
return {"items": []}
try:
with open(knowledge_path, 'r', encoding='utf-8') as f:
knowledge_base = json.load(f)
return knowledge_base
except Exception as e:
self.log(f"加载知识库失败: {e}", "error")
return {"items": []}
def _prepare_documents(self) -> Tuple[List[str], np.ndarray]:
"""准备文档和嵌入向量"""
documents = []
# 格式化知识库条目
for item in self.knowledge_base.get('items', []):
doc_text = self._format_document(item)
documents.append(doc_text)
if not documents:
# 创建示例文档
documents = [
"高温热浪: 气温≥35℃时容易导致中暑,建议减少户外活动,多喝水。",
"暴雨洪水: 短时强降雨可能导致内涝,注意交通安全,避免涉水。",
"台风防御: 台风天气风力强劲,请固定好门窗,避免外出。",
"干旱应对: 干旱天气需要节约用水,注意防火,减少户外活动。",
"寒潮防护: 寒潮天气气温骤降,请注意保暖,预防感冒。"
]
self.log("使用示例文档", "warning")
# 计算嵌入向量
embeddings = self.model.encode(
documents,
convert_to_numpy=True,
normalize_embeddings=True
)
return documents, embeddings
def _format_document(self, item: Dict) -> str:
"""格式化文档"""
parts = []
if 'title' in item:
parts.append(f"标题: {item['title']}")
if 'category' in item:
parts.append(f"类别: {item['category']}")
if 'scientific_basis' in item:
parts.append(f"科学依据: {item['scientific_basis']}")
if 'warning_indicators' in item:
parts.append(f"预警指标: {item['warning_indicators']}")
return "\n".join(parts)
def process(self, query: str, top_k: int = 5, **kwargs) -> Dict:
"""检索相关文档"""
self.log(f"检索查询: {query}")
if len(self.documents) == 0:
return {
'success': False,
'error': '知识库为空',
'results': []
}
try:
# 编码查询
query_embedding = self.model.encode(
query,
convert_to_numpy=True,
normalize_embeddings=True
)
# 计算相似度
similarities = util.cos_sim(query_embedding, self.doc_embeddings)[0]
# 获取top_k结果
top_indices = torch.topk(
similarities,
k=min(top_k, len(self.documents))
).indices.tolist()
# 构建结果
results = []
for idx in top_indices:
similarity = similarities[idx].item()
doc_text = self.documents[idx]
# 提取关键信息
category = "未知"
title = "无标题"
# 从文档文本中解析信息
for line in doc_text.split('\n'):
if line.startswith('类别:'):
category = line.replace('类别:', '').strip()
elif line.startswith('标题:'):
title = line.replace('标题:', '').strip()
results.append({
'document': doc_text,
'category': category,
'title': title,
'similarity': similarity,
'confidence': min(0.99, similarity * 1.2) # 置信度增强
})
# 按类别分组
category_groups = defaultdict(list)
for result in results:
category_groups[result['category']].append(result)
# 计算类别权重
category_scores = {}
for category, items in category_groups.items():
category_scores[category] = sum(item['similarity'] for item in items) / len(items)
self.log(f"检索完成,找到 {len(results)} 个相关文档")
return {
'success': True,
'query': query,
'results': results,
'category_scores': dict(category_scores),
'total_docs': len(self.documents),
'top_categories': sorted(category_scores.items(), key=lambda x: x[1], reverse=True)[:3]
}
except Exception as e:
self.log(f"检索失败: {e}", "error")
return {
'success': False,
'error': str(e),
'results': []
}
class AnalysisAgent(BaseAgent):
"""分析智能体 - 负责气象特征提取和风险评估"""
def __init__(self):
super().__init__(
name="AnalysisAgent",
description="负责分析气象特征,进行风险评估和趋势预测"
)
# 初始化特征提取规则
self.feature_rules = self._init_feature_rules()
# 风险评估模型
self.risk_levels = {
'low': {'min': 0, 'max': 3, 'color': '🟢', 'description': '低风险'},
'medium': {'min': 4, 'max': 6, 'color': '🟡', 'description': '中风险'},
'high': {'min': 7, 'max': 9, 'color': '🟠', 'description': '高风险'},
'extreme': {'min': 10, 'max': 12, 'color': '🔴', 'description': '极高风险'}
}
self.log("初始化完成")
def _init_feature_rules(self) -> Dict:
"""初始化特征提取规则"""
return {
'temperature': {
'patterns': [
r'温度\s*([0-9]+\.?[0-9]*)\s*℃',
r'([0-9]+\.?[0-9]*)\s*℃',
r'气温\s*([0-9]+\.?[0-9]*)度'
],
'unit': '℃',
'risk_weight': 1.5
},
'humidity': {
'patterns': [
r'湿度\s*([0-9]+\.?[0-9]*)\s*%',
r'([0-9]+\.?[0-9]*)\s*%湿度'
],
'unit': '%',
'risk_weight': 1.0
},
'precipitation': {
'patterns': [
r'降雨\s*([0-9]+\.?[0-9]*)\s*mm',
r'降水\s*([0-9]+\.?[0-9]*)\s*毫米',
r'雨量\s*([0-9]+\.?[0-9]*)'
],
'unit': 'mm',
'risk_weight': 1.8
},
'wind': {
'patterns': [
r'风速\s*([0-9]+\.?[0-9]*)\s*m/s',
r'风力\s*([0-9]+\.?[0-9]*)\s*级'
],
'unit': 'm/s',
'risk_weight': 1.3
}
}
def extract_features(self, query: str) -> Dict:
"""提取气象特征"""
features = {'raw_features': {}, 'keywords': []}
# 提取数值特征
for feature_name, rule in self.feature_rules.items():
for pattern in rule['patterns']:
matches = re.findall(pattern, query)
if matches:
values = [float(match) for match in matches if self._is_number(match)]
if values:
avg_value = sum(values) / len(values)
features['raw_features'][feature_name] = {
'value': avg_value,
'unit': rule['unit'],
'risk_weight': rule['risk_weight']
}
break
# 提取关键词
weather_keywords = {
'高温': 'heat',
'热浪': 'heatwave',
'暴雨': 'heavy_rain',
'台风': 'typhoon',
'干旱': 'drought',
'寒潮': 'cold_wave',
'大风': 'strong_wind',
'冰雹': 'hail',
'雷电': 'lightning',
'雾霾': 'haze',
'沙尘': 'sandstorm'
}
for keyword, key in weather_keywords.items():
if keyword in query:
features['keywords'].append({
'keyword': keyword,
'key': key,
'risk_level': self._get_keyword_risk(keyword)
})
# 提取时间信息
time_keywords = {
'今天': 'today',
'明天': 'tomorrow',
'后天': 'day_after_tomorrow',
'本周': 'this_week',
'周末': 'weekend',
'未来三天': 'next_3_days',
'下周': 'next_week',
'近期': 'recent'
}
for keyword, key in time_keywords.items():
if keyword in query:
features['time_period'] = key
break
self.log(f"提取到特征: {features}")
return features
def _is_number(self, s: str) -> bool:
"""判断是否为数字"""
try:
float(s)
return True
except ValueError:
return False
def _get_keyword_risk(self, keyword: str) -> str:
"""获取关键词风险等级"""
risk_map = {
'高温': 'high', '热浪': 'extreme', '暴雨': 'high',
'台风': 'extreme', '干旱': 'medium', '寒潮': 'medium',
'大风': 'medium', '冰雹': 'high', '雷电': 'high',
'雾霾': 'low', '沙尘': 'medium'
}
return risk_map.get(keyword, 'low')
def assess_risk(self, features: Dict, retrieval_results: Dict = None) -> Dict:
"""风险评估"""
risk_score = 0
risk_factors = []
# 1. 数值特征风险评估
for feature_name, feature_data in features.get('raw_features', {}).items():
value = feature_data['value']
weight = feature_data['risk_weight']
# 根据特征值计算风险
if feature_name == 'temperature':
if value >= 35:
risk_score += 3 * weight
risk_factors.append(f"高温({value}℃)")
elif value >= 30:
risk_score += 2 * weight
risk_factors.append(f"炎热({value}℃)")
elif feature_name == 'precipitation':
if value >= 50:
risk_score += 3 * weight
risk_factors.append(f"暴雨({value}mm)")
elif value >= 25:
risk_score += 2 * weight
risk_factors.append(f"大雨({value}mm)")
elif feature_name == 'wind':
if value >= 10.8: # 6级风以上
risk_score += 2 * weight
risk_factors.append(f"大风({value}m/s)")
# 2. 关键词风险评估
for keyword_data in features.get('keywords', []):
risk_level = keyword_data['risk_level']
keyword = keyword_data['keyword']
if risk_level == 'extreme':
risk_score += 4
risk_factors.append(f"{keyword}(极高风险)")
elif risk_level == 'high':
risk_score += 3
risk_factors.append(f"{keyword}(高风险)")
elif risk_level == 'medium':
risk_score += 2
risk_factors.append(f"{keyword}(中风险)")
else:
risk_score += 1
risk_factors.append(f"{keyword}(低风险)")
# 3. 结合检索结果的类别风险
if retrieval_results and retrieval_results.get('success'):
top_categories = retrieval_results.get('top_categories', [])
for category, score in top_categories:
if any(high_risk in category for high_risk in ['高温', '台风', '暴雨', '干旱']):
risk_score += score * 2
risk_factors.append(f"相关类别: {category}")
# 确定风险等级
risk_level = 'low'
level_info = None
for level_name, level_range in self.risk_levels.items():
if level_range['min'] <= risk_score <= level_range['max']:
risk_level = level_name
level_info = level_range
break
else:
# 如果超过最大值,设为最高风险
risk_level = 'extreme'
level_info = self.risk_levels['extreme']
risk_assessment = {
'risk_score': round(risk_score, 2),
'risk_level': risk_level,
'level_info': level_info,
'risk_factors': risk_factors,
'risk_components': {
'feature_risk': round(risk_score * 0.6, 2),
'keyword_risk': round(risk_score * 0.3, 2),
'category_risk': round(risk_score * 0.1, 2)
}
}
self.log(f"风险评估完成: {risk_assessment}")
return risk_assessment
def generate_analysis_report(self, query: str, features: Dict,
risk_assessment: Dict) -> Dict:
"""生成分析报告"""
report = {
'query': query,
'timestamp': datetime.now().isoformat(),
'feature_analysis': {},
'risk_assessment': risk_assessment,
'trend_analysis': {},
'confidence': 0.85
}
# 特征分析
if features.get('raw_features'):
report['feature_analysis']['numerical_features'] = features['raw_features']
if features.get('keywords'):
report['feature_analysis']['detected_keywords'] = features['keywords']
if features.get('time_period'):
report['feature_analysis']['time_period'] = features['time_period']
# 趋势分析(模拟)
trend_indicators = []
if 'temperature' in features.get('raw_features', {}):
temp = features['raw_features']['temperature']['value']
if temp > 30:
trend_indicators.append("温度呈上升趋势,可能发展为热浪天气")
if any(k['key'] == 'heavy_rain' for k in features.get('keywords', [])):
trend_indicators.append("降水条件具备,可能发展为持续性降雨")
report['trend_analysis']['indicators'] = trend_indicators
report['trend_analysis']['prediction_horizon'] = "未来24-48小时"
return report
def process(self, query: str, retrieval_results: Dict = None, **kwargs) -> Dict:
"""处理分析任务"""
self.log(f"分析查询: {query}")
try:
# 1. 提取特征
features = self.extract_features(query)
# 2. 风险评估
risk_assessment = self.assess_risk(features, retrieval_results)
# 3. 生成分析报告
analysis_report = self.generate_analysis_report(
query, features, risk_assessment
)
analysis_report['success'] = True
return analysis_report
except Exception as e:
self.log(f"分析失败: {e}", "error")
return {
'success': False,
'error': str(e),
'query': query
}
class DecisionAgent(BaseAgent):
"""决策智能体 - 负责生成应对建议和措施"""
def __init__(self):
super().__init__(
name="DecisionAgent",
description="根据分析和检索结果,生成具体应对建议和决策方案"
)
# 决策规则库
self.decision_rules = self._init_decision_rules()
# 建议模板
self.recommendation_templates = {
'high_temperature': [
"避免在高温时段(10:00-16:00)进行户外活动",
"穿着宽松、透气的浅色衣物",
"及时补充水分,每天至少饮水2-3升",
"使用防晒霜(SPF30+),佩戴太阳镜和遮阳帽",
"关注老人、儿童和慢性病患者的健康状况",
"如出现头晕、恶心等中暑症状,立即到阴凉处休息并就医"
],
'heavy_rain': [
"关注气象预警,避免前往低洼地带",
"驾车时注意减速慢行,保持安全车距",
"避免在树下、广告牌下停留,防止雷击",
"检查房屋排水系统,防止雨水倒灌",
"准备应急照明和通讯设备",
"如遇积水路段,不要强行通过"
],
'typhoon': [
"加固门窗,移除阳台上的易坠落物品",
"储备3天以上的食物、水和药品",
"避免外出,如需外出请远离海岸和山区",
"关注官方发布的台风路径和预警信息",
"准备应急电源,保持通讯畅通",
"台风过后注意检查房屋安全,防范次生灾害"
],
'drought': [
"节约用水,优先保证生活用水",
"调整农业灌溉时间,避免中午高温时段",
"注意防火,不要在林区和野外用火",
"做好个人防护,防止皮肤干燥开裂",
"关注水库蓄水情况和供水通知",
"考虑雨水收集和中水回用"
],
'cold_wave': [
"注意保暖,特别是头部、手部和脚部",
"使用取暖设备时注意通风,防止一氧化碳中毒",
"老人、儿童和体弱者减少外出",
"注意水管防冻,防止爆裂",
"适当增加高热量食物摄入",
"关注天气预报,及时添加衣物"
],
'general': [
"关注当地气象部门的最新预报和预警",
"根据天气变化及时调整出行计划",
"保持通讯畅通,随时了解天气信息",
"准备必要的应急物资",
"学习基本的防灾减灾知识"
]
}
self.log("初始化完成")
def _init_decision_rules(self) -> Dict:
"""初始化决策规则"""
return {
'heatwave': {
'conditions': ['temperature>=35', 'has_heatwave'],
'priority': 1,
'action_type': 'immediate'
},
'heavy_rain_alert': {
'conditions': ['precipitation>=50', 'has_heavy_rain'],
'priority': 1,
'action_type': 'immediate'
},
'typhoon_warning': {
'conditions': ['has_typhoon', 'wind>=10.8'],
'priority': 1,
'action_type': 'emergency'
},
'drought_alert': {
'conditions': ['has_drought', 'humidity<=30'],
'priority': 2,
'action_type': 'monitor'
},
'cold_protection': {
'conditions': ['temperature<=10', 'has_cold_wave'],
'priority': 2,
'action_type': 'preventive'
}
}
def generate_decisions(self, analysis_report: Dict,
retrieval_results: Dict) -> List[Dict]:
"""生成决策建议"""
decisions = []
# 获取分析结果
features = analysis_report.get('feature_analysis', {})
risk_assessment = analysis_report.get('risk_assessment', {})
risk_level = risk_assessment.get('risk_level', 'low')
# 确定需要应对的天气类型
weather_types = set()
# 从关键词中提取
for keyword_data in features.get('detected_keywords', []):
key = keyword_data['key']
if key in ['heat', 'heatwave']:
weather_types.add('high_temperature')
elif key in ['heavy_rain', 'typhoon']:
weather_types.add(key)
elif key in ['drought', 'cold_wave']:
weather_types.add(key)
# 从数值特征中判断
numerical_features = features.get('numerical_features', {})
if 'temperature' in numerical_features:
temp = numerical_features['temperature']['value']
if temp >= 35:
weather_types.add('high_temperature')
elif temp <= 10:
weather_types.add('cold_wave')
if 'precipitation' in numerical_features:
precip = numerical_features['precipitation']['value']
if precip >= 50:
weather_types.add('heavy_rain')
# 如果没有特定天气类型,使用通用建议
if not weather_types:
weather_types.add('general')
# 根据风险等级调整建议强度
priority_map = {
'extreme': '紧急应对',
'high': '高度重视',
'medium': '加强防范',
'low': '正常关注'
}
priority = priority_map.get(risk_level, '正常关注')
# 生成具体决策
for weather_type in weather_types:
if weather_type in self.recommendation_templates:
recommendations = self.recommendation_templates[weather_type]
# 根据风险等级调整建议数量
if risk_level in ['low', 'medium']:
recommendations = recommendations[:3]
elif risk_level == 'high':
recommendations = recommendations[:5]
# extreme风险等级使用所有建议
decisions.append({
'weather_type': weather_type,
'priority': priority,
'recommendations': recommendations,
'applicable_conditions': self._get_applicable_conditions(weather_type)
})
# 从检索结果中提取额外建议
if retrieval_results.get('success'):
top_results = retrieval_results.get('results', [])[:2]
for result in top_results:
doc_text = result.get('document', '')
# 从文档中提取关键建议
if '应对:' in doc_text:
response_part = doc_text.split('应对:')[1]
key_points = [p.strip() for p in response_part.split('。') if p.strip()]
if key_points:
decisions.append({
'weather_type': result.get('category', '通用'),
'priority': '知识库建议',
'recommendations': key_points[:3],
'source': '知识库',
'confidence': result.get('confidence', 0.7)
})
self.log(f"生成 {len(decisions)} 个决策建议")
return decisions
def _get_applicable_conditions(self, weather_type: str) -> List[str]:
"""获取适用条件"""
conditions_map = {
'high_temperature': ['气温≥35℃', '相对湿度≥60%', '连续高温≥3天'],
'heavy_rain': ['小时降雨量≥50mm', '持续降雨≥3小时', '伴有雷电'],
'typhoon': ['风力≥10级', '伴有暴雨', '风暴潮预警'],
'drought': ['连续无降水≥15天', '土壤湿度≤30%', '水库蓄水不足'],
'cold_wave': ['24小时降温≥8℃', '最低气温≤0℃', '伴有大风']
}
return conditions_map.get(weather_type, ['通用天气条件'])
def generate_action_plan(self, decisions: List[Dict]) -> Dict:
"""生成行动方案"""
action_plan = {
'immediate_actions': [],
'short_term_actions': [],
'monitoring_actions': [],
'preparedness_actions': []
}
for decision in decisions:
weather_type = decision['weather_type']
priority = decision['priority']
recommendations = decision['recommendations']
if priority in ['紧急应对', '高度重视']:
action_plan['immediate_actions'].extend(recommendations[:2])
action_plan['short_term_actions'].extend(recommendations[2:4])
elif priority == '加强防范':
action_plan['short_term_actions'].extend(recommendations[:3])
action_plan['monitoring_actions'].extend(recommendations[3:])
else:
action_plan['preparedness_actions'].extend(recommendations[:3])
# 去重
for key in action_plan:
action_plan[key] = list(set(action_plan[key]))
return action_plan
def process(self, analysis_report: Dict, retrieval_results: Dict, **kwargs) -> Dict:
"""处理决策任务"""
self.log(f"生成决策建议")
try:
# 1. 生成决策建议
decisions = self.generate_decisions(analysis_report, retrieval_results)
# 2. 生成行动方案
action_plan = self.generate_action_plan(decisions)
# 3. 生成决策报告
decision_report = {
'success': True,
'decisions': decisions,
'action_plan': action_plan,
'summary': self._generate_decision_summary(decisions),
'timestamp': datetime.now().isoformat()
}
return decision_report
except Exception as e:
self.log(f"决策生成失败: {e}", "error")
return {
'success': False,
'error': str(e)
}
def _generate_decision_summary(self, decisions: List[Dict]) -> str:
"""生成决策摘要"""
if not decisions:
return "当前天气条件正常,建议关注常规天气预报"
summary_parts = []
for decision in decisions:
weather_type = decision['weather_type']
priority = decision['priority']
if weather_type == 'high_temperature':
summary_parts.append(f"高温天气,{priority}")
elif weather_type == 'heavy_rain':
summary_parts.append(f"暴雨天气,{priority}")
elif weather_type == 'typhoon':
summary_parts.append(f"台风天气,{priority}")
elif weather_type == 'drought':
summary_parts.append(f"干旱天气,{priority}")
elif weather_type == 'cold_wave':
summary_parts.append(f"寒潮天气,{priority}")
return ";".join(summary_parts) if summary_parts else "天气条件复杂,请关注详细建议"
class CoordinatorAgent(BaseAgent):
"""协调智能体 - 负责协调其他智能体工作"""
def __init__(self, agents: Dict[str, BaseAgent]):
super().__init__(
name="CoordinatorAgent",
description="协调和管理各智能体的工作流程,整合最终结果"
)
self.agents = agents
self.workflow_status = {}
self.results_cache = {}
self.log(f"初始化完成,管理 {len(agents)} 个智能体")
async def execute_workflow(self, query: str) -> Dict:
"""执行工作流程"""
self.log(f"开始执行工作流程,查询: {query}")
workflow_id = f"wf_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
self.workflow_status[workflow_id] = {
'query': query,
'start_time': datetime.now().isoformat(),
'status': 'running',
'agents_status': {}
}
try:
# 1. 检索阶段
self.log("阶段1: 知识检索")
retrieval_agent = self.agents.get('retrieval')
if retrieval_agent:
retrieval_result = await self._execute_agent_task(
retrieval_agent, 'retrieval', workflow_id, query=query
)
self.results_cache['retrieval'] = retrieval_result
else:
retrieval_result = {'success': False, 'error': '检索智能体未配置'}
# 2. 分析阶段
self.log("阶段2: 特征分析与风险评估")
analysis_agent = self.agents.get('analysis')
if analysis_agent:
analysis_result = await self._execute_agent_task(
analysis_agent, 'analysis', workflow_id,
query=query, retrieval_results=retrieval_result
)
self.results_cache['analysis'] = analysis_result
else:
analysis_result = {'success': False, 'error': '分析智能体未配置'}
# 3. 决策阶段
self.log("阶段3: 决策建议生成")
decision_agent = self.agents.get('decision')
if decision_agent:
decision_result = await self._execute_agent_task(
decision_agent, 'decision', workflow_id,
analysis_report=analysis_result,
retrieval_results=retrieval_result
)
self.results_cache['decision'] = decision_result
else:
decision_result = {'success': False, 'error': '决策智能体未配置'}
# 4. 整合结果
self.log("阶段4: 结果整合")
final_result = self._integrate_results(
query, retrieval_result, analysis_result, decision_result
)
# 更新工作流状态
self.workflow_status[workflow_id].update({
'end_time': datetime.now().isoformat(),
'status': 'completed',
'final_result': final_result.get('success', False)
})
self.log(f"工作流程完成: {workflow_id}")
return final_result
except Exception as e:
self.log(f"工作流程执行失败: {e}", "error")
self.workflow_status[workflow_id].update({
'end_time': datetime.now().isoformat(),
'status': 'failed',
'error': str(e)
})
return {
'success': False,
'error': f"工作流程执行失败: {str(e)}",
'query': query,
'workflow_id': workflow_id
}
async def _execute_agent_task(self, agent: BaseAgent, agent_name: str,
workflow_id: str, **kwargs) -> Dict:
"""执行智能体任务"""
try:
start_time = datetime.now()
# 记录开始状态
self.workflow_status[workflow_id]['agents_status'][agent_name] = {
'status': 'running',
'start_time': start_time.isoformat()
}
# 执行任务
result = agent.process(**kwargs)
# 记录结束状态
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
self.workflow_status[workflow_id]['agents_status'][agent_name].update({
'status': 'completed' if result.get('success') else 'failed',
'end_time': end_time.isoformat(),
'duration': duration,
'success': result.get('success', False)
})
agent.log(f"任务完成,耗时: {duration:.2f}秒")
return result
except Exception as e:
agent.log(f"任务执行失败: {e}", "error")
self.workflow_status[workflow_id]['agents_status'][agent_name] = {
'status': 'failed',
'error': str(e),
'end_time': datetime.now().isoformat()
}
return {
'success': False,
'error': f"{agent_name}执行失败: {str(e)}"
}
def _integrate_results(self, query: str, retrieval_result: Dict,
analysis_result: Dict, decision_result: Dict) -> Dict:
"""整合所有结果"""
final_result = {
'success': all([
retrieval_result.get('success', False),
analysis_result.get('success', False),
decision_result.get('success', False)
]),
'query': query,
'timestamp': datetime.now().isoformat(),
'components': {
'retrieval': retrieval_result.get('success', False),
'analysis': analysis_result.get('success', False),
'decision': decision_result.get('success', False)
}
}
if final_result['success']:
# 整合成功结果
final_result.update({
'knowledge_retrieval': {
'total_docs': retrieval_result.get('total_docs', 0),
'relevant_docs': len(retrieval_result.get('results', [])),
'top_categories': retrieval_result.get('top_categories', [])
},
'risk_assessment': analysis_result.get('risk_assessment', {}),
'decisions': decision_result.get('decisions', []),
'action_plan': decision_result.get('action_plan', {}),
'summary': decision_result.get('summary', '')
})
# 生成最终响应
final_result['response'] = self._generate_final_response(
query, analysis_result, decision_result
)
# 计算综合置信度
confidence_sources = []
if retrieval_result.get('results'):
conf = retrieval_result['results'][0].get('confidence', 0) if retrieval_result['results'] else 0
confidence_sources.append(conf)
if 'confidence' in analysis_result:
confidence_sources.append(analysis_result['confidence'])
final_result['confidence'] = sum(confidence_sources) / len(
confidence_sources) if confidence_sources else 0.7
else:
# 处理失败情况
errors = []
if not retrieval_result.get('success'):
errors.append(f"检索失败: {retrieval_result.get('error')}")
if not analysis_result.get('success'):
errors.append(f"分析失败: {analysis_result.get('error')}")
if not decision_result.get('success'):
errors.append(f"决策失败: {decision_result.get('error')}")
final_result['errors'] = errors
final_result['response'] = f"抱歉,处理您的查询时出现错误: {'; '.join(errors)}"
return final_result
def _generate_final_response(self, query: str, analysis_result: Dict,
decision_result: Dict) -> str:
"""生成最终响应文本"""
risk_assessment = analysis_result.get('risk_assessment', {})
decisions = decision_result.get('decisions', [])
action_plan = decision_result.get('action_plan', {})
lines = []