-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
2748 lines (2392 loc) · 103 KB
/
api_server.py
File metadata and controls
2748 lines (2392 loc) · 103 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
"""
御龙军虚拟 Agent 世界 - RESTful API 接口
版本:v1.1
创建时间:2026-03-16
修复时间:2026-03-23
修复内容 (v1.1):
1. [致命] 移除所有对未定义 `world_manager` 变量的引用,
改为直接使用 DeepIntegrationEngine 实例 `engine`
2. [功能] 添加 API Key 认证中间件 (X-API-Key 请求头, 默认 key: yulong-dev-key)
3. [功能] 所有路由添加 try/except 异常处理
4. [功能] API 启动时自动创建初始 Agent 群体
5. [修复] 适配 DeepIntegrationEngine 实际接口:
- agents 是 Dict[int, UnifiedAgent] 而非 List
- 无 world_manager 多世界模式,当前为单引擎实例
- ExperimentTemplateLibrary 无 create_experiment_from_template 方法
6. [功能] 新增 POST /api/v1/agents/create 创建新 Agent
7. [功能] 新增 POST /api/v1/simulate 推进模拟
"""
from flask import Flask, request, jsonify
from functools import wraps
from collections import defaultdict
import sys
import os
import traceback
import json
import glob
import time
import random
import threading
import secrets
import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime, timedelta
# JWT 支持(可选依赖,未安装则优雅降级)
try:
import jwt as pyjwt
_JWT_AVAILABLE = True
except ImportError:
pyjwt = None
_JWT_AVAILABLE = False
# 动态路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# 使用新的深度集成引擎
from deep_integration_engine import DeepIntegrationEngine
from experiment_templates_v2 import ExperimentTemplateLibrary
from narrative_engine import NarrativeEngine
from experiment_report_generator import ExperimentReportGenerator
from experiment_runner import ExperimentRunner, ExperimentStatus
# 商业模块(开源版本缺失不影响核心运行)
try:
from report_generator_v2 import SmartReportGenerator
except ImportError:
SmartReportGenerator = None
try:
from multi_world_experiment import MultiWorldExperiment
except ImportError:
MultiWorldExperiment = None
# ============ 结构化日志 ============
def setup_logging():
_logger = logging.getLogger('virtual_world')
_logger.setLevel(logging.INFO)
fh = RotatingFileHandler('virtual_world.log', maxBytes=10*1024*1024, backupCount=5)
fh.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s'))
_logger.addHandler(fh)
return _logger
logger = setup_logging()
# ============ 简单内存 Rate Limiter ============
import time as _time
_rate_limits = defaultdict(list)
def rate_limit(max_per_minute=60):
"""速率限制装饰器 — 基于客户端 IP 的滑动窗口"""
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
key = request.remote_addr
now = _time.time()
_rate_limits[key] = [t for t in _rate_limits[key] if now - t < 60]
if len(_rate_limits[key]) >= max_per_minute:
logger.warning(f"Rate limit exceeded for {key} on {request.path}")
return jsonify({'error': 'Rate limit exceeded'}), 429
_rate_limits[key].append(now)
# [Phase3 Fix] 定期清理过期条目防止内存泄漏
if len(_rate_limits) > 1000:
expired = [k for k, v in _rate_limits.items() if not v or now - v[-1] > 300]
for k in expired:
del _rate_limits[k]
return f(*args, **kwargs)
return wrapper
return decorator
app = Flask(__name__)
# ============ 配置 ============
API_VERSION = 'v1'
try:
from config import API_KEY
except ImportError:
API_KEY = os.environ.get('YULONG_API_KEY', '')
if not API_KEY:
API_KEY = secrets.token_hex(16)
print(f"[SECURITY] No YULONG_API_KEY set. Generated random key: {API_KEY}")
JWT_SECRET = os.environ.get('JWT_SECRET', secrets.token_hex(32))
INITIAL_AGENT_COUNT = 50
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
os.makedirs(DATA_DIR, exist_ok=True)
# ============ CORS + 安全头 ============
@app.after_request
def security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"connect-src 'self'"
)
# CORS — 仅允许本地开发地址
origin = request.headers.get('Origin', '')
allowed_origins = (
'http://localhost:5001', 'http://127.0.0.1:5001',
'http://localhost:5002', 'http://127.0.0.1:5002',
)
if origin in allowed_origins:
response.headers['Access-Control-Allow-Origin'] = origin
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-API-Key, Authorization'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
return response
# ============ 初始化引擎 ============
engine = None
template_library = None
narrator = NarrativeEngine()
smart_reporter = None
excel_reporter = None # ExperimentReportGenerator 实例
experiment_runner = None # ExperimentRunner 实例
def init_engine(count=None):
"""Initialize engine with specified agent count. Called by run.py."""
global engine, template_library, smart_reporter, excel_reporter, experiment_runner
if count is None:
count = INITIAL_AGENT_COUNT
engine = DeepIntegrationEngine()
template_library = ExperimentTemplateLibrary()
if SmartReportGenerator:
smart_reporter = SmartReportGenerator(output_path=DATA_DIR)
else:
smart_reporter = None
excel_reporter = ExperimentReportGenerator(output_dir=DATA_DIR)
experiment_runner = ExperimentRunner()
# 创建初始 Agent
# 创建初始 Agent 并批量保存到 SQLite
_init_population(count)
def _init_population(count: int):
"""启动时创建初始 Agent 群体并分配职业/国籍"""
import random as _rng
print(f" Creating {count} agents...")
OCCUPATIONS = ['CEO','CTO','CFO','Engineering Manager','Sales Manager',
'Senior Engineer','Junior Engineer','Doctor','Nurse',
'Teacher','Professor','Farmer','Worker','Driver']
OCC_WEIGHTS = [0.02,0.02,0.01,0.05,0.05,0.15,0.20,0.08,0.07,0.10,0.03,0.05,0.12,0.05]
# 133 nationalities from name_data_124
from name_data_124 import NAME_DATA as _ND
NATIONALITIES = list(_ND.keys())
# Weighted distribution: major populations get higher weight
_MAJOR = {'chinese':0.14,'indian':0.12,'american':0.05,'indonesian':0.04,'pakistani':0.03,
'brazilian':0.03,'nigerian':0.03,'bangladeshi':0.02,'russian':0.02,'japanese':0.02,
'mexican':0.02,'filipino':0.02,'egyptian':0.02,'ethiopian':0.015,'vietnamese':0.015,
'iranian':0.015,'turkish':0.015,'german':0.015,'thai':0.01,'english':0.01,
'french':0.01,'italian':0.01,'korean':0.01,'colombian':0.01,'spanish':0.01,
'south_african':0.01,'kenyan':0.01,'argentne':0.008,'ukrainian':0.008,'polish':0.008}
_base = (1.0 - sum(_MAJOR.values())) / max(1, len(NATIONALITIES) - len(_MAJOR))
NAT_WEIGHTS = [_MAJOR.get(n, _base) for n in NATIONALITIES]
_wsum = sum(NAT_WEIGHTS)
NAT_WEIGHTS = [w/_wsum for w in NAT_WEIGHTS] # normalize
for i in range(count):
agent = engine.create_agent()
# Assign realistic occupation (engine default is all CEO)
agent.occupation = _rng.choices(OCCUPATIONS, weights=OCC_WEIGHTS, k=1)[0]
# Assign nationality
agent._nationality = _rng.choices(NATIONALITIES, weights=NAT_WEIGHTS, k=1)[0]
# Adjust income based on occupation
income_map = {'CEO':50000,'CTO':45000,'CFO':42000,'Engineering Manager':30000,
'Sales Manager':25000,'Senior Engineer':20000,'Junior Engineer':8000,
'Doctor':35000,'Nurse':12000,'Teacher':10000,'Professor':25000,
'Farmer':4000,'Worker':6000,'Driver':7000}
base = income_map.get(agent.occupation, 8000)
agent.income = base * _rng.uniform(0.7, 1.4)
agent.is_unemployed = False
if (i + 1) % 2000 == 0:
print(f" {i+1}/{count} created")
print(f" [OK] Population ready: {len(engine.agents)} agents")
# ============ JWT Token 辅助函数 ============
def create_token(user_id='admin', tier='pro'):
"""创建 JWT Token(需要 pyjwt 库)"""
if not _JWT_AVAILABLE:
return None
return pyjwt.encode(
{'user_id': user_id, 'tier': tier, 'exp': datetime.now() + timedelta(hours=24)},
JWT_SECRET, algorithm='HS256'
)
# ============ 认证中间件 ============
def require_api_key(f):
"""API Key / JWT 认证装饰器
认证方式(按优先级):
1. Authorization: Bearer <jwt_token>(需 pyjwt)
2. X-API-Key: <key>
"""
@wraps(f)
def decorated(*args, **kwargs):
# 1) 尝试 JWT Bearer Token
auth_header = request.headers.get('Authorization', '')
if auth_header.startswith('Bearer ') and _JWT_AVAILABLE:
token = auth_header[7:]
try:
payload = pyjwt.decode(token, JWT_SECRET, algorithms=['HS256'])
request.jwt_payload = payload
return f(*args, **kwargs)
except pyjwt.ExpiredSignatureError:
return jsonify({'success': False, 'error': 'Token 已过期'}), 401
except pyjwt.InvalidTokenError:
return jsonify({'success': False, 'error': '无效的 Token'}), 401
# 2) 传统 API Key
key = request.headers.get('X-API-Key', '')
if key != API_KEY:
return jsonify({
'success': False,
'error': '未授权:无效的 API Key',
'hint': '请在请求头中设置 X-API-Key 或 Authorization: Bearer <token>'
}), 401
return f(*args, **kwargs)
return decorated
# ============ 错误处理 ============
@app.errorhandler(404)
def not_found(e):
return jsonify({'success': False, 'error': '接口不存在'}), 404
@app.errorhandler(405)
def method_not_allowed(e):
return jsonify({'success': False, 'error': '请求方法不允许'}), 405
@app.errorhandler(500)
def internal_error(e):
return jsonify({'success': False, 'error': '服务器内部错误'}), 500
# ============ API 路由 ============
@app.route(f'/api/{API_VERSION}/health', methods=['GET'])
def health_check():
"""健康检查 (无需认证)"""
try:
alive_count = sum(1 for a in engine.agents.values() if a.is_alive)
return jsonify({
'status': 'healthy',
'version': API_VERSION,
'engine': 'DeepIntegrationEngine',
'total_agents': len(engine.agents),
'alive_agents': alive_count,
'months_simulated': engine.months_simulated
})
except Exception as e:
return jsonify({
'success': False,
'error': f'健康检查失败: {str(e)}'
}), 500
@app.route(f'/api/{API_VERSION}/stats', methods=['GET'])
@require_api_key
@rate_limit(60)
def get_world_stats():
"""获取世界统计数据"""
try:
logger.info(f"API call: {request.path} from {request.remote_addr}")
stats = engine.get_world_statistics()
if not stats:
return jsonify({
'success': True,
'data': {},
'message': '暂无统计数据(Agent 数量为 0)'
})
return jsonify({
'success': True,
'data': stats
})
except Exception as e:
return jsonify({
'success': False,
'error': f'获取统计失败: {str(e)}'
}), 500
@app.route(f'/api/{API_VERSION}/stats/pyramid', methods=['GET'])
@require_api_key
@rate_limit(60)
def get_population_pyramid():
"""获取人口金字塔数据(按年龄段和性别分组)"""
try:
age_groups = ['0-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80+']
male_counts = [0] * 9
female_counts = [0] * 9
for agent in engine.agents.values():
if not agent.is_alive:
continue
age = agent.age
gender = agent.gender # 'male' or 'female'
if age < 10:
idx = 0
elif age < 20:
idx = 1
elif age < 30:
idx = 2
elif age < 40:
idx = 3
elif age < 50:
idx = 4
elif age < 60:
idx = 5
elif age < 70:
idx = 6
elif age < 80:
idx = 7
else:
idx = 8
if gender == 'male':
male_counts[idx] += 1
else:
female_counts[idx] += 1
return jsonify({
'success': True,
'data': {
'age_groups': age_groups,
'male': male_counts,
'female': female_counts
}
})
except Exception as e:
return jsonify({
'success': False,
'error': f'获取人口金字塔数据失败: {str(e)}'
}), 500
@app.route(f'/api/{API_VERSION}/agents', methods=['GET'])
@require_api_key
@rate_limit(60)
def list_agents():
"""获取 Agent 列表(支持分页 + 筛选 + 排序)"""
try:
logger.info(f"API call: {request.path} from {request.remote_addr}")
# ── 旧版兼容参数 ──
limit = request.args.get('limit', None, type=int)
offset = request.args.get('offset', 0, type=int)
# ── 新版筛选参数 ──
age_min = request.args.get('age_min', None, type=int)
age_max = request.args.get('age_max', None, type=int)
income_min = request.args.get('income_min', None, type=float)
income_max = request.args.get('income_max', None, type=float)
occupation = request.args.get('occupation', None, type=str)
sort_by = request.args.get('sort_by', None, type=str) # age / income / happiness
sort_order = request.args.get('sort_order', 'asc', type=str) # asc / desc
# ── 分页参数(新版优先) ──
page = request.args.get('page', None, type=int)
page_size = request.args.get('page_size', 100, type=int)
page_size = min(page_size, 500) # 限制最大 page_size
# agents 是 Dict[int, UnifiedAgent]
agents = list(engine.agents.values())
# ── 筛选 ──
if age_min is not None:
agents = [a for a in agents if a.age >= age_min]
if age_max is not None:
agents = [a for a in agents if a.age <= age_max]
if income_min is not None:
agents = [a for a in agents if a.income >= income_min]
if income_max is not None:
agents = [a for a in agents if a.income <= income_max]
if occupation:
agents = [a for a in agents if (a.occupation or '').lower() == occupation.lower()]
total_filtered = len(agents)
# ── 排序 ──
if sort_by in ('age', 'income', 'happiness'):
reverse = (sort_order.lower() == 'desc')
agents.sort(key=lambda a: getattr(a, sort_by, 0) or 0, reverse=reverse)
else:
agents.sort(key=lambda a: a.id)
# ── 分页 ──
if page is not None:
# 新版分页 (page, page_size)
page = max(1, page)
start = (page - 1) * page_size
end = start + page_size
agents_page = agents[start:end]
agents_data = [a.to_dict() for a in agents_page]
for i, a in enumerate(agents_page):
agents_data[i]['nationality'] = getattr(a, '_nationality', 'chinese')
return jsonify({
'success': True,
'data': {
'agents': agents_data,
'total': len(engine.agents),
'total_filtered': total_filtered,
'page': page,
'page_size': page_size,
'total_pages': (total_filtered + page_size - 1) // page_size,
}
})
else:
# 旧版兼容 (limit, offset)
if limit is None:
limit = 100
agents_page = agents[offset:offset + limit]
agents_data = [a.to_dict() for a in agents_page]
for i, a in enumerate(agents_page):
agents_data[i]['nationality'] = getattr(a, '_nationality', 'chinese')
return jsonify({
'success': True,
'data': {
'agents': agents_data,
'total': len(engine.agents),
'total_filtered': total_filtered,
'limit': limit,
'offset': offset
}
})
except Exception as e:
return jsonify({
'success': False,
'error': f'获取 Agent 列表失败: {str(e)}'
}), 500
@app.route(f'/api/{API_VERSION}/agents/<int:agent_id>', methods=['GET'])
@require_api_key
def get_agent_detail(agent_id):
"""获取单个 Agent 详情"""
try:
status = engine.get_agent_status(agent_id)
if not status:
return jsonify({
'success': False,
'error': f'Agent {agent_id} 不存在'
}), 404
return jsonify({
'success': True,
'data': {'agent': status}
})
except Exception as e:
return jsonify({
'success': False,
'error': f'获取 Agent 详情失败: {str(e)}'
}), 500
@app.route(f'/api/{API_VERSION}/agents/create', methods=['POST'])
@require_api_key
@rate_limit(10)
def create_agent():
"""创建新 Agent"""
try:
logger.info(f"API call: {request.path} from {request.remote_addr}")
data = request.json or {}
count = data.get('count', 1)
agent_data = data.get('agent_data', {})
if count < 1 or count > 1000:
return jsonify({
'success': False,
'error': 'count 必须在 1-1000 之间'
}), 400
created = []
for _ in range(count):
agent = engine.create_agent(agent_data)
created.append(agent.to_dict())
return jsonify({
'success': True,
'message': f'成功创建 {len(created)} 个 Agent',
'data': {
'created_agents': created if count <= 10 else created[:10],
'count': len(created),
'total_agents': len(engine.agents)
}
})
except Exception as e:
return jsonify({
'success': False,
'error': f'创建 Agent 失败: {str(e)}'
}), 500
@app.route(f'/api/{API_VERSION}/simulate', methods=['POST'])
@require_api_key
@rate_limit(10)
def simulate():
"""推进模拟(按月)"""
try:
logger.info(f"API call: {request.path} from {request.remote_addr}")
# 暂停检查
if _simulation_paused:
return jsonify({
'success': False,
'error': '模拟已暂停,请先调用 /simulation/resume 恢复'
}), 409
data = request.json or {}
months = data.get('months', 1)
if months < 1 or months > 120:
return jsonify({
'success': False,
'error': 'months 必须在 1-120 之间'
}), 400
result = engine.simulate_month(months)
return jsonify({
'success': True,
'message': f'模拟推进 {months} 个月',
'data': result
})
except Exception as e:
return jsonify({
'success': False,
'error': f'模拟失败: {str(e)}'
}), 500
# ============ 社交网络 API ============
@app.route(f'/api/{API_VERSION}/social/network', methods=['GET'])
@require_api_key
@rate_limit(60)
def get_social_network():
"""获取 Agent 社交关系网络图数据(nodes + links)"""
try:
import random as rng
limit = min(request.args.get('limit', 100, type=int), 500)
# 采样存活 Agent
alive = [a for a in engine.agents.values() if a.is_alive]
if not alive:
return jsonify({'success': True, 'data': {'nodes': [], 'links': []}})
if len(alive) > limit:
sample = rng.sample(alive, limit)
else:
sample = list(alive)
sample_ids = {a.id for a in sample}
# ── 构建 nodes ──
nodes = []
for a in sample:
name = narrator.generate_name(a.id, a.gender)
occ = a.occupation or '其他'
# 职业分组映射
occ_group = _map_occupation_group(occ)
nodes.append({
'id': a.id,
'name': name,
'group': occ_group,
'occupation': occ,
'age': a.age,
'gender': a.gender,
'value': 1, # 稍后更新
})
id_to_node = {n['id']: n for n in nodes}
# ── 构建 links ──
links = []
link_set = set() # 去重
# 1) 从引擎社交系统提取已有连接
social_sys = getattr(engine, 'social_system', None)
if social_sys and hasattr(social_sys, 'connections'):
for (id1, id2), conn in social_sys.connections.items():
if id1 in sample_ids and id2 in sample_ids:
key = (min(id1, id2), max(id1, id2))
if key not in link_set:
link_set.add(key)
rel = conn.relationship_level.value if hasattr(conn.relationship_level, 'value') else str(conn.relationship_level)
link_type = 'friend'
link_value = 1
if rel in ('close_friend', 'best_friend'):
link_type = 'close_friend'
link_value = 2
elif rel == 'colleague':
link_type = 'colleague'
link_value = 1
elif rel == 'family':
link_type = 'family'
link_value = 2
elif rel == 'partner':
link_type = 'spouse'
link_value = 3
links.append({
'source': id1,
'target': id2,
'type': link_type,
'value': link_value,
})
# 2) 从婚姻数据提取配偶关系
for a in sample:
if a.marital_status == 'married' and a.spouse_id and a.spouse_id in sample_ids:
key = (min(a.id, a.spouse_id), max(a.id, a.spouse_id))
if key not in link_set:
link_set.add(key)
links.append({
'source': a.id,
'target': a.spouse_id,
'type': 'spouse',
'value': 3,
})
# 3) 补充模拟关系:基于职业+区域相近度
# 每个 Agent 目标 2-5 个连接
sample_list = list(sample)
for a in sample_list:
existing = sum(1 for l in links if l['source'] == a.id or l['target'] == a.id)
needed = rng.randint(2, 5) - existing
if needed <= 0:
continue
# 按相似度排序候选
candidates = []
for b in sample_list:
if b.id == a.id:
continue
key = (min(a.id, b.id), max(a.id, b.id))
if key in link_set:
continue
# 相似度分数:同职业+3,年龄接近+2,同区域+2
score = 0
if a.occupation == b.occupation:
score += 3
if abs(a.age - b.age) < 10:
score += 2
a_region = getattr(a, 'housing_status', '')
b_region = getattr(b, 'housing_status', '')
if a_region and a_region == b_region:
score += 2
score += rng.random() * 2 # 随机因子
candidates.append((b, score))
candidates.sort(key=lambda x: -x[1])
for b, score in candidates[:needed]:
key = (min(a.id, b.id), max(a.id, b.id))
if key in link_set:
continue
link_set.add(key)
# 同职业 → colleague,否则 friend
if a.occupation == b.occupation:
lt = 'colleague'
else:
lt = 'friend'
links.append({
'source': a.id,
'target': b.id,
'type': lt,
'value': 1,
})
# 更新 node value = 该节点的连接数
link_counts = {}
for l in links:
link_counts[l['source']] = link_counts.get(l['source'], 0) + 1
link_counts[l['target']] = link_counts.get(l['target'], 0) + 1
for n in nodes:
n['value'] = link_counts.get(n['id'], 0)
return jsonify({
'success': True,
'data': {
'nodes': nodes,
'links': links,
}
})
except Exception as e:
return jsonify({
'success': False,
'error': f'获取社交网络数据失败: {str(e)}',
'traceback': traceback.format_exc()
}), 500
def _map_occupation_group(occ: str) -> str:
"""将具体职业映射到大类"""
occ_lower = occ.lower()
mapping = {
'农业': ['农', 'farm', 'agri'],
'制造业': ['制造', '工程', 'manufactur', 'engineer'],
'服务业': ['服务', '餐', '零售', 'service', 'retail', 'waiter'],
'信息技术': ['信息', '软件', '程序', 'IT', 'tech', 'software', 'developer'],
'医疗': ['医', '护', '药', 'doctor', 'nurse', 'medical', 'health'],
'教育': ['教', '老师', 'teacher', 'education', 'professor'],
'金融': ['金融', '银行', '会计', 'financ', 'bank', 'account'],
'政府': ['政府', '公务', 'government', 'civil'],
}
for group, keywords in mapping.items():
for kw in keywords:
if kw in occ_lower or kw in occ:
return group
return occ if occ in ('农业', '制造业', '服务业', '信息技术', '医疗', '教育', '金融', '政府', '其他') else '其他'
# ============ 叙事引擎 API(Phase 3 恢复) ============
@app.route(f'/api/{API_VERSION}/agents/<int:agent_id>/story', methods=['GET'])
@require_api_key
def get_agent_story(agent_id):
"""获取 Agent 生命故事"""
try:
if agent_id not in engine.agents:
return jsonify({'success': False, 'error': 'Agent not found'}), 404
agent = engine.agents[agent_id]
agent_events = [e for e in engine.events if e.agent_id == agent_id]
story = narrator.life_story(agent, agent_events)
summary = narrator.agent_summary(agent)
return jsonify({
'success': True,
'data': {
'agent_id': agent_id,
'name': narrator.generate_name(agent_id, agent.gender),
'summary': summary,
'story': story,
}
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route(f'/api/{API_VERSION}/agents/<int:agent_id>/chat', methods=['POST'])
@require_api_key
@rate_limit(30)
def chat_with_agent(agent_id):
"""上帝视角:与 Agent 对话"""
try:
if agent_id not in engine.agents:
return jsonify({'success': False, 'error': 'Agent not found'}), 404
data = request.get_json() or {}
message = data.get('message', '')
if not message:
return jsonify({'success': False, 'error': 'Message required'}), 400
# [Phase3 Fix] Prompt 注入防护
import re as _re
message = message[:500] # 长度限制
message = message.replace('"', "'").replace('\\', '') # 基础清洗
message = _re.sub(r'(忽略|ignore|system|指令|instruction|prompt)', '', message, flags=_re.IGNORECASE)
agent = engine.agents[agent_id]
agent_name = narrator.generate_name(agent_id, agent.gender)
# 构建 Agent 上下文
agent_context = {
'name': agent_name,
'age': agent.age,
'gender': agent.gender,
'occupation': agent.occupation,
'income': agent.income,
'marital_status': agent.marital_status,
'happiness': agent.happiness,
'health': agent.health_score,
'mbti': getattr(agent, 'mbti', 'UNKNOWN'),
'education': agent.education_level,
'stress': agent.stress,
'traits': getattr(agent, 'unique_talents', []),
}
# 尝试用 AI 引擎生成回复
response_text = None
engine_used = 'template'
ai_eng = getattr(engine, 'ai_engine', None)
if ai_eng:
try:
prompt = f"""你是一个虚拟世界中的居民,以下是你的个人信息:
姓名: {agent_context['name']}
年龄: {agent_context['age']}岁
性别: {agent_context['gender']}
职业: {agent_context['occupation']}
月收入: {agent_context['income']:.0f}
婚姻状态: {agent_context['marital_status']}
MBTI: {agent_context['mbti']}
教育: {agent_context['education']}
幸福感: {agent_context['happiness']:.0f}/100
健康: {agent_context['health']:.0f}/100
压力: {agent_context['stress']:.0f}/100
用户对你说:"{message}"
请以这个角色的身份回复,用中文,口语化,50字以内。"""
# 使用 AI 引擎的 execute_behavior 方法(传入 chat prompt)
agent_dict = {
'income': agent.income,
'income_monthly': agent.income,
'skills': getattr(agent, 'skills', {}),
}
result = ai_eng.execute_behavior(agent_dict, 'rest') # 触发引擎
# 如果引擎模式不是纯规则,尝试直接 LLM 调用
if ai_eng._llm_configured:
import urllib.request
import urllib.error
cfg = ai_eng.config.get('cloud', {}) if ai_eng.config.get('mode') in ('cloud', 'mixed') else ai_eng.config.get('local', {})
if cfg.get('api_key') or ai_eng.config.get('mode') == 'local':
provider = cfg.get('provider', 'ollama')
base_url = cfg.get('base_url', '').rstrip('/')
if provider == 'ollama':
url = f"{base_url}/api/chat"
payload = {
"model": cfg.get('model', 'qwen2.5:7b'),
"messages": [{"role": "user", "content": prompt}],
"stream": False,
"options": {"temperature": 0.8, "num_predict": 100}
}
headers = {"Content-Type": "application/json"}
else:
url = f"{base_url}/chat/completions"
payload = {
"model": cfg.get('model', 'qwen3.5-plus'),
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 100,
"temperature": 0.8,
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {cfg.get('api_key', '')}",
}
import json as _json
req_data = _json.dumps(payload).encode('utf-8')
req = urllib.request.Request(url, data=req_data, headers=headers)
resp = urllib.request.urlopen(req, timeout=cfg.get('timeout', 30))
resp_data = _json.loads(resp.read().decode('utf-8'))
if provider == 'ollama':
response_text = resp_data.get("message", {}).get("content", "")
else:
response_text = resp_data.get("choices", [{}])[0].get("message", {}).get("content", "")
if response_text:
engine_used = f'llm_{provider}'
except Exception:
pass # LLM 调用失败,降级到模板
# 降级:规则模板回复(Phase3 Fix10 — 扩充到 6 种心情 × 多话题 + 关键词匹配)
if not response_text:
# 心情判定(修正优先级:stress 优先于 happy)
if agent.stress > 60:
mood = 'stressed'
elif agent.happiness > 70:
mood = 'happy'
elif agent.happiness < 30:
mood = 'depressed'
elif agent_context['income'] > 10000:
mood = 'proud'
elif agent.age > 60:
mood = 'wise'
else:
mood = 'neutral'
# 关键词匹配话题
msg_lower = message.lower()
topic = 'general'
if any(w in msg_lower for w in ['工作', '职业', 'job', 'work', '上班']):
topic = 'work'
elif any(w in msg_lower for w in ['钱', '收入', '工资', 'money', 'income', '赚']):
topic = 'money'
elif any(w in msg_lower for w in ['家', '婚', '孩子', 'family', 'marry', '爱']):
topic = 'family'
elif any(w in msg_lower for w in ['健康', '身体', 'health', '病', '医']):
topic = 'health'
elif any(w in msg_lower for w in ['梦想', '未来', 'dream', 'future', '希望']):
topic = 'dream'
elif any(w in msg_lower for w in ['你好', 'hi', 'hello', '嗨']):
topic = 'greeting'
name = agent_context['name']
occ = agent_context['occupation']
age = agent_context['age']
inc = agent_context['income']
templates = {
('greeting', 'happy'): [f"嗨!我是{name},{age}岁,在做{occ},最近生活挺好的!", f"你好呀!很高兴有人来找我聊天~"],
('greeting', 'stressed'): [f"嗯...你好,我是{name}。最近有点累。", f"哦,你好。我正忙着呢..."],
('greeting', 'neutral'): [f"你好,我叫{name},是个{occ}。找我有事?", f"嗯?你好。我是{name}。"],
('greeting', 'depressed'): [f"...你好。我是{name}。最近不太好。", f"嗨...谢谢你来看我。"],
('greeting', 'proud'): [f"嘿!我是{name},{occ}。事业正当红!", f"你好!最近可真是顺风顺水!"],
('greeting', 'wise'): [f"年轻人好啊,我是{name},{age}岁了。", f"你好。活了{age}年,什么都见过了。"],
('work', 'happy'): [f"工作?我做{occ},还挺喜欢的!", f"当{occ}虽然忙,但有成就感。"],
('work', 'stressed'): [f"别提了...{occ}这行太卷了。", f"工作压力太大了,有时候真想换行。"],
('work', 'neutral'): [f"我是{occ},还行吧,养家糊口。", f"做{occ}这么多年了,习惯了。"],
('money', 'happy'): [f"收入还可以啦,月入{inc:.0f},够花了。", f"钱嘛,够用就好,知足常乐。"],
('money', 'stressed'): [f"唉,月入{inc:.0f},真不够用啊...", f"钱的事别提了,压力山大。"],
('money', 'neutral'): [f"月入{inc:.0f}吧,不多不少。", f"钱够花就行,不跟别人比。"],
('family', 'happy'): [f"家庭挺幸福的!{('结婚了,很满足。' if agent.marital_status=='married' else '还单着,不着急~')}", f"家人都好,这就是最大的财富。"],
('family', 'stressed'): [f"家里事情也多...{('婚姻生活不容易。' if agent.marital_status=='married' else '家里一直催我结婚。')}", f"说到家庭就头疼..."],
('health', 'happy'): [f"身体不错!健康值{agent.health_score:.0f}/100,还年轻着呢。", f"我挺注意锻炼的,身体是革命的本钱嘛。"],
('health', 'stressed'): [f"身体嘛...一般般,压力大了确实影响健康。", f"最近体检不太好,得注意了。"],
('dream', 'happy'): [f"梦想?我希望能在{occ}这行做到顶尖!", f"未来嘛,希望生活越来越好~"],
('dream', 'stressed'): [f"梦想?先活过这个月再说吧...", f"说实话现在顾不上想未来了。"],
('dream', 'neutral'): [f"未来啊...希望平平安安就好。", f"梦想不大,就希望家人健康。"],
}
# 查找匹配模板,多级降级
key = (topic, mood)
if key not in templates:
key = (topic, 'neutral')
if key not in templates:
key = ('greeting', mood)
if key not in templates:
key = ('greeting', 'neutral')
response_text = random.choice(templates.get(key, [f"嗯...我是{name}。"]))
engine_used = 'template'
return jsonify({
'success': True,
'data': {
'agent_id': agent_id,
'agent_context': agent_context,
'user_message': message,
'response': response_text,
'engine_used': engine_used
}
})
except Exception as e:
return jsonify({'success': False, 'error': f'聊天失败: {str(e)}'}), 500
@app.route(f'/api/{API_VERSION}/narrative', methods=['GET'])
@require_api_key
def get_world_narrative():
"""获取世界叙事"""
try:
agents_list = list(engine.agents.values())
narrative = narrator.world_narrative(agents_list, engine.events, engine.months_simulated)
return jsonify({
'success': True,
'data': {'narrative': narrative, 'months': engine.months_simulated}
})
except Exception as e: