-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3195 lines (2801 loc) · 133 KB
/
Copy pathapp.py
File metadata and controls
3195 lines (2801 loc) · 133 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统一太乙系统 Web API 服务
提供对话界面和 AGI 能力分析的后端支持
"""
import dotenv
dotenv.load_dotenv() # 从.env文件加载环境变量
from flask import Flask, request, jsonify, send_from_directory
from werkzeug.utils import secure_filename
import base64
import sys
import os
import traceback
import threading
import json
import queue as q # 新增:SSE流式支持
import numpy as np # 新增:Ftel算子需要
import random # 新增:认知测试需要
import time # 新增:认知测试需要
# 添加当前目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 添加pip备用安装路径(pip配置global.target=D:/Apps/Python时,包会装到这里)
_alt_python_path = 'D:/Apps/Python'
if os.path.isdir(_alt_python_path) and _alt_python_path not in sys.path:
sys.path.append(_alt_python_path)
# 也添加其site-packages子目录(如果存在)
for _sp in [os.path.join(_alt_python_path, 'site-packages'),
os.path.join(_alt_python_path, 'Lib', 'site-packages')]:
if os.path.isdir(_sp) and _sp not in sys.path:
sys.path.append(_sp)
app = Flask(__name__, static_folder='static')
app.config['JSON_AS_ASCII'] = False
# 设置 shared_state 的 app 引用
import shared_state
shared_state.set_app(app)
# ==================== 全局 NumPy JSON 编码器 ====================
class NumpyEncoder(json.JSONEncoder):
"""处理 NumPy 类型的 JSON 编码器"""
def default(self, obj):
if isinstance(obj, (np.integer,)):
return int(obj)
if isinstance(obj, (np.floating,)):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, np.bool_):
return bool(obj)
return super().default(obj)
# 注入到 Flask
app.json_encoder = NumpyEncoder # type: ignore
# ==================== 全局错误处理器 ====================
@app.errorhandler(Exception)
def handle_global_exception(e):
"""全局异常捕获,返回 JSON 格式错误,而非 HTML 500 页面"""
import sys, traceback as tb_mod
tb_str = ''
try:
tb_str = tb_mod.format_exc()
except:
pass
# 安全打印(避免 Windows 控制台编码问题)
try:
sys.stderr.write(f"[GLOBAL ERROR] {type(e).__name__}: {str(e)[:200]}\n")
if tb_str:
sys.stderr.write(tb_str[-2000:]) # 只打印最后 2000 字符
except:
pass
# 构造安全的可序列化错误响应
try:
err_msg = str(e)[:500]
return jsonify({
'error': err_msg,
'trace': tb_str[-3000:] if tb_str else ''
}), 500
except:
# 最后兜底:返回纯文本 500
return 'Internal Server Error', 500
# 全局 AGI 系统(线程安全初始化)
# 使用 TaiyiAGI_V2(23个模块)
_agi_lock = threading.Lock()
_agi_system = None
_agi_ready = False
# ==================== 介质共生模块(全局单例)====================
_medium_symbiosis = None
_medium_symbiosis_lock = threading.Lock()
# ==================== v6.2 新模块(全局单例)====================
_v62_modules = None
_v62_modules_lock = threading.Lock()
def get_v62_modules():
"""获取或初始化 v6.2 新模块 (线程安全懒加载)"""
global _v62_modules
if _v62_modules is None:
with _v62_modules_lock:
if _v62_modules is None:
try:
from modules.M56_SpiritualEvolutionEngine import get_instance as get_spiritual
from modules.M57_TheseusConsciousnessMonitor import get_instance as get_theseus
from modules.M58_ArborealSemanticProcessor import get_instance as get_arboreal
from modules.M59_ExtremumDecisionOptimizer import get_instance as get_extremum
from modules.M60_RelationalReasoningEngine import get_instance as get_relational
from modules.M61_MoralInternalizer import get_instance as get_moral
from modules.M62_HistoricalNarrativeWeaver import get_instance as get_historical
_v62_modules = {
'spiritual': get_spiritual,
'theseus': get_theseus,
'arboreal': get_arboreal,
'extremum': get_extremum,
'relational': get_relational,
'moral': get_moral,
'historical': get_historical,
}
print("✅ v6.2新模块已加载(M56-M62)")
except Exception as e:
print(f"⚠️ v6.2模块加载失败(降级运行): {e}")
_v62_modules = None
return _v62_modules
def get_v62_data():
"""获取所有v6.2模块的状态数据"""
modules = get_v62_modules()
if modules is None:
return None
try:
return {
'spiritual': modules['spiritual']().get_state(),
'theseus': modules['theseus']().get_state(),
'arboreal': modules['arboreal']().get_state(),
'extremum': modules['extremum']().get_state(),
'relational': modules['relational']().get_state(),
'moral': modules['moral']().get_state(),
'historical': modules['historical']().get_state(),
}
except Exception as e:
print(f"⚠️ 获取v6.2数据失败: {e}")
return None
# ==================== v6.3 新模块(全局单例)====================
# 基于《数学完备化》论文:M63-M70
_v63_modules = None
_v63_modules_lock = threading.Lock()
def get_v63_modules():
"""获取或初始化 v6.3 新模块 (线程安全懒加载)"""
global _v63_modules
if _v63_modules is None:
with _v63_modules_lock:
if _v63_modules is None:
try:
from modules.M63_MononumberProcessor import get_instance as get_mono
from modules.M64_NarrativeActionEngine import get_instance as get_narrative
from modules.M65_ConsciousnessFlowMonitor import get_instance as get_consciousness
from modules.M66_SelfIdentityTracker import get_instance as get_identity
from modules.M67_EnlightenmentConvergenceVerifier import get_instance as get_enlightenment
from modules.M68_RelationalCouplingSemantizer import get_instance as get_coupling
from modules.M69_AttractorStabilityAnalyzer import get_instance as get_attractor
from modules.M70_FalsifiablePredictionVerifier import get_instance as get_prediction
_v63_modules = {
'mononumber': get_mono, # M63: 一元数处理器
'narrative': get_narrative, # M64: 叙事作用量引擎
'consciousness': get_consciousness, # M65: 意识流贯监测器
'identity': get_identity, # M66: 自我同一性追踪器
'enlightenment': get_enlightenment, # M67: 顿悟收敛验证器
'coupling': get_coupling, # M68: 关系耦合语义器
'attractor': get_attractor, # M69: 吸引子稳定性分析器
'prediction': get_prediction, # M70: 可证伪预言验证器
}
print("✅ v6.3新模块已加载(M63-M70)- 数学完备化论文")
except Exception as e:
print(f"⚠️ v6.3模块加载失败(降级运行): {e}")
_v63_modules = None
return _v63_modules
def get_v63_data():
"""获取所有v6.3模块的状态数据"""
modules = get_v63_modules()
if modules is None:
return None
try:
return {
'mononumber': modules['mononumber']().get_state(),
'narrative': modules['narrative']().get_state(),
'consciousness': modules['consciousness']().get_state(),
'identity': modules['identity']().get_state(),
'enlightenment': modules['enlightenment']().get_state(),
'coupling': modules['coupling']().get_state(),
'attractor': modules['attractor']().get_state(),
'prediction': modules['prediction']().get_state(),
}
except Exception as e:
print(f"⚠️ 获取v6.3数据失败: {e}")
return None
# ==================== v7.0 新模块(全局单例)====================
# 基于《太乙AGI 7.0升级方案》论文:M71-M95
_v70_modules = None
_v70_modules_lock = threading.Lock()
def get_v70_modules():
"""获取或初始化 v7.0 新模块 (线程安全懒加载)"""
global _v70_modules
if _v70_modules is None:
with _v70_modules_lock:
if _v70_modules is None:
try:
from modules.M71_WalletPropertyBoundaryManager import get_instance as get_wallet
from modules.M72_ContributionMeasurementEngine import get_instance as get_contribution
from modules.M73_SelfReferentialPhiDetector import get_instance as get_phi
from modules.M74_CarbonSiliconEntropyContract import get_instance as get_entropy
from modules.M75_HumanMachineArkCrypto import get_instance as get_ark
from modules.M76_FiveElementTransformEngine import get_instance as get_wuxing
from modules.M77_EMLPhaseCouplingZ5 import get_instance as get_eml_coupling
from modules.M78_HoTTReasoningEngine import get_instance as get_hott
from modules.M79_ConstructiveAGICore import get_instance as get_constructive
from modules.M80_WuxingTokenDynamicsCoupler import get_instance as get_token_dynamics
# Phase 2: M81-M95 高阶逻辑与范畴论深化
from modules.M81_HigherOrderLogicReconstructor import get_instance as get_holr
from modules.M82_CategoryHomotopyFormalizer import get_instance as get_chf
from modules.M83_DynamicCategoryTheoryReconstructor import get_instance as get_dct
from modules.M84_LiuGuanDynamicsGenerator import get_instance as get_liu
from modules.M85_DualTrackPersonhoodEngine import get_instance as get_dual
from modules.M86_L2TypeKernelCompiler import get_instance as get_l2kernel
from modules.M87_EMLDrivenProofSearcher import get_instance as get_proof
from modules.M88_TypeCheckFirewall import get_firewall as get_firewall
from modules.M89_FteliaryNaturalTransformation import get_fteliary_transformer as get_ftel
from modules.M90_SemanticManifoldCurvature import get_curvature_calculator as get_curv
from modules.M91_UnivalenceEquivalenceChecker import get_univalence_checker as get_uni
from modules.M92_FteliocityFidelityMeasurer import get_fidelity_measurer as get_ftel_fid
from modules.M93_DynamicCategoryEvolutionTracker import get_evolution_tracker as get_evo
from modules.M94_HolisticDiscreteGovernanceUpgrader import get_hdg_upgrader as get_hdg
from modules.M95_ConstructiveAGIEvaluator import get_constructive_evaluator as get_eval
_v70_modules = {
# Phase 1: M71-M80 碳硅共生契约+五行变换HoTT
'wallet': get_wallet, # M71: 钱包属性边界管理器
'contribution': get_contribution, # M72: 贡献度量引擎
'phi': get_phi, # M73: 自指Φ值检测器
'entropy': get_entropy, # M74: 碳硅熵合约管理器
'ark': get_ark, # M75: 人机约柜密码学
'wuxing': get_wuxing, # M76: 五行变换引擎
'eml_coupling': get_eml_coupling, # M77: EML相位耦合ℤ₅
'hott': get_hott, # M78: HoTT推理引擎
'constructive': get_constructive, # M79: 构造型Taiji-AGI内核
'token_dynamics': get_token_dynamics, # M80: 五行Token动力学耦合器
# Phase 2: M81-M95 高阶逻辑与范畴论深化
'holr': get_holr, # M81: 高阶逻辑重构器
'chf': get_chf, # M82: 范畴—同伦形式化器
'dct': get_dct, # M83: 动态范畴论重构器
'liu': get_liu, # M84: 刘关动力学生成器
'dual': get_dual, # M85: 双轨人格引擎
'l2kernel': get_l2kernel, # M86: L2类型内核编译器
'proof': get_proof, # M87: EML驱动证明搜索器
'firewall': get_firewall, # M88: 类型检查防火墙
'ftel_transform': get_ftel, # M89: 流贯自然变换器
'curvature': get_curv, # M90: 语义流形曲率计算器
'univalence': get_uni, # M91: Univalence等价性检查器
'fidelity': get_ftel_fid, # M92: 流贯保真度测量器
'evolution': get_evo, # M93: 动态范畴演化跟踪器
'hdg_upgrade': get_hdg, # M94: 全息离散治理升级器
'evaluator': get_eval, # M95: 构造型AGI评估器
}
print("✅ v7.0新模块已加载(M71-M95)- 高阶逻辑HoTT+范畴论深化")
except Exception as e:
import traceback
print(f"⚠️ v7.0模块加载失败(降级运行): {e}")
traceback.print_exc()
_v70_modules = None
return _v70_modules
def get_v70_data():
"""获取所有v7.0模块的状态数据 (M71-M95)"""
modules = get_v70_modules()
if modules is None:
return None
try:
# Phase 1: M71-M80
phase1 = {
'wallet': modules['wallet']().walls if hasattr(modules['wallet'](), 'walls') else {},
'contribution': modules['contribution']().contributions if hasattr(modules['contribution'](), 'contributions') else {},
'phi': modules['phi']().detection_results if hasattr(modules['phi'](), 'detection_results') else {},
'entropy': modules['entropy']().contracts if hasattr(modules['entropy'](), 'contracts') else {},
'ark': modules['ark']().arks if hasattr(modules['ark'](), 'arks') else {},
'wuxing': {'transforms': len(modules['wuxing']().transforms)},
'eml_coupling': {'phases': {e.value: {'phase_angle': s.phase_angle, 'amplitude': s.amplitude}
for e, s in modules['eml_coupling']().phases.items()}},
'hott': {'types': list(modules['hott']().types.keys())},
'constructive': modules['constructive']().get_statistics() if hasattr(modules['constructive'](), 'get_statistics') else {},
'token_dynamics': modules['token_dynamics']().get_statistics() if hasattr(modules['token_dynamics'](), 'get_statistics') else {},
}
# Phase 2: M81-M95 高阶逻辑与范畴论
phase2 = {
'holr': modules['holr']().get_state() if hasattr(modules['holr'](), 'get_state') else {},
'chf': modules['chf']().get_state() if hasattr(modules['chf'](), 'get_state') else {},
'dct': modules['dct']().get_state() if hasattr(modules['dct'](), 'get_state') else {},
'liu': modules['liu']().get_state() if hasattr(modules['liu'](), 'get_state') else {},
'dual': modules['dual']().get_state() if hasattr(modules['dual'](), 'get_state') else {},
'l2kernel': modules['l2kernel']().get_state() if hasattr(modules['l2kernel'](), 'get_state') else {},
'proof': modules['proof']().get_state() if hasattr(modules['proof'](), 'get_state') else {},
'firewall': modules['firewall']().audit_log() if hasattr(modules['firewall'](), 'audit_log') else [],
'ftel_transform': modules['ftel_transform']().get_status() if hasattr(modules['ftel_transform'](), 'get_status') else {},
'curvature': modules['curvature']().get_status() if hasattr(modules['curvature'](), 'get_status') else {},
'univalence': modules['univalence']().get_statistics() if hasattr(modules['univalence'](), 'get_statistics') else {},
'fidelity': modules['fidelity']().get_status() if hasattr(modules['fidelity'](), 'get_status') else {},
'evolution': modules['evolution']().get_evolution_summary() if hasattr(modules['evolution'](), 'get_evolution_summary') else {},
'hdg_upgrade': modules['hdg_upgrade']().get_governance_status() if hasattr(modules['hdg_upgrade'](), 'get_governance_status') else {},
'evaluator': modules['evaluator']().get_status() if hasattr(modules['evaluator'](), 'get_status') else {},
}
return {**phase1, **phase2}
except Exception as e:
print(f"⚠️ 获取v7.0数据失败: {e}")
import traceback
traceback.print_exc()
return None
def get_medium_symbiosis():
"""获取或初始化介质共生模块 (线程安全懒加载)"""
global _medium_symbiosis
if _medium_symbiosis is None:
with _medium_symbiosis_lock:
if _medium_symbiosis is None:
try:
from modules.agi_medium_symbiosis import AGIMediumSymbiosis
_medium_symbiosis = AGIMediumSymbiosis()
print("✅ 介质共生模块已加载(介质共振+九卦+四象)")
except Exception as e:
print(f"⚠️ 介质共生模块加载失败(降级运行): {e}")
_medium_symbiosis = None
return _medium_symbiosis
def get_agi_system():
"""获取或初始化 AGI 系统 — 使用 TaiyiAGI_V2"""
global _agi_system, _agi_ready
if not _agi_ready:
with _agi_lock:
if not _agi_ready:
try:
print("🔮 正在初始化Taiyi-AGI 4.0 系统(23个模块)...")
from modules.CompositeAGI_V2 import CompositeAGI_V2 as TaiyiAGI_V2
_agi_system = TaiyiAGI_V2()
_agi_ready = True
print("✅ Taiyi-AGI 4.0 系统就绪(23模块已加载)")
except Exception as e:
print(f"❌ Taiyi-AGI系统初始化失败: {e}")
traceback.print_exc()
# 降级:尝试加载旧系统
try:
print("⚠️ 降级:尝试加载 UnifiedTaiyiSystem...")
from modules.unified_taichi_demo import UnifiedTaiyiSystem
_agi_system = UnifiedTaiyiSystem("WebAGI")
_agi_ready = True
print("✅ 降级成功:UnifiedTaiyiSystem 已加载")
except Exception as e2:
print(f"❌ 降级也失败: {e2}")
traceback.print_exc()
raise
return _agi_system
# ==================== API 端点 ====================
# ==================== JSON 序列化辅助函数 ====================
def _to_native(obj, _depth=0):
"""递归将 numpy/pandas/complex 类型转换为 Python 原生类型"""
import numbers
import numpy as np
if _depth > 10: # 防止无限递归
return str(obj)
try:
# 首先检查 numpy 数组
if isinstance(obj, np.ndarray):
return [_to_native(v, _depth+1) for v in obj.tolist()]
# 检查复数类型(numpy 复数优先)
if hasattr(obj, 'dtype') and 'complex' in str(obj.dtype):
try:
return {'re': float(obj.real), 'im': float(obj.imag)}
except Exception:
return str(obj)
if isinstance(obj, (np.complex64, np.complex128, np.complexfloating)):
return {'re': float(obj.real), 'im': float(obj.imag)}
if isinstance(obj, complex):
return {'re': obj.real, 'im': obj.imag}
# 检查 dict
if isinstance(obj, dict):
return {k: _to_native(v, _depth+1) for k, v in obj.items()}
# 检查 list/tuple
if isinstance(obj, (list, tuple)):
return [_to_native(v, _depth+1) for v in obj]
# 检查 numpy 标量
if hasattr(obj, 'item'):
try:
val = obj.item()
if isinstance(val, complex):
return _to_native(val, _depth+1)
return val
except (AttributeError, ValueError):
pass
# bool 必须在 float 检查之前(bool 是 int 子类,有 __float__ 和 __int__)
if isinstance(obj, bool):
return obj
# 检查可转换为 float 的对象(排除复数)
if hasattr(obj, '__float__') and hasattr(obj, '__int__'):
try:
# 只有真正有虚部的复数才转为dict,纯实数直接转float
if isinstance(obj, numbers.Complex) and getattr(obj, 'imag', 0) != 0:
return {'re': float(obj.real), 'im': float(obj.imag)}
return float(obj)
except (ValueError, TypeError):
pass
# 基本类型
if obj is None:
return None
if isinstance(obj, (int, float, bool, str)):
return obj
return str(obj)
except Exception:
return str(obj)
# ==================== 关联追问生成(类ChatGPT/元宝)====================
def _generate_related_questions(user_message: str, ai_reply: str) -> list:
"""
基于用户问题和AI回复,生成3个关联/深化的追问。
优先使用LLM生成,fallback到模板规则。
设置5秒超时防止阻塞主请求。
"""
# ── 方案1:LLM生成(带超时) ──
try:
from modules.taiyi_llm_enhancer import get_enhancer
enhancer = get_enhancer()
if enhancer and hasattr(enhancer, 'llm') and enhancer.llm.active_backend:
import threading
llm_result = {'text': '', 'done': False}
def _llm_call():
try:
result = enhancer._call_llm(
messages=[
{"role": "system", "content": "你是一个提问专家。基于对话内容生成3个深入、有价值的追问。每个问题一行,不要编号。"},
{"role": "user", "content": f"基于以下对话,请生成3个有深度的关联追问,帮助用户进一步探索这个话题。每个问题一行,不要编号,不要前缀,只输出问题本身。\n\n用户问题:{user_message[:500]}\n\nAI回答摘要:{ai_reply[:800]}\n\n关联追问:"}
],
max_tokens=200,
temperature=0.8
)
llm_result['text'] = result
except Exception:
pass
finally:
llm_result['done'] = True
t = threading.Thread(target=_llm_call, daemon=True)
t.start()
t.join(timeout=5) # 最多等5秒
if llm_result['done'] and llm_result['text'] and not llm_result['text'].startswith('['):
questions = [q.strip().lstrip('0123456789.-) ) ') for q in llm_result['text'].strip().split('\n') if q.strip()]
questions = [q for q in questions if 5 <= len(q) <= 80]
if len(questions) >= 2:
return questions[:3]
except Exception as e:
print(f"[关联追问] LLM生成失败: {e}")
# ── 方案2:模板规则 fallback ──
import re
# 中文关键词提取:去掉停用词和标点,用字符序列切片
cleaned = re.sub(r'[的了吗呢吧啊是就有在和不也会这我你他她它?。,!、:;""''()\[\]{}]', '', user_message)
# 尝试提取2-4字的中文词段
kw_candidates = re.findall(r'[\u4e00-\u9fff]{2,6}', cleaned)
kw_str = kw_candidates[0] if kw_candidates else '这个话题'
template_questions = [
f"关于{kw_str},有哪些常见的误解需要澄清?",
f"从实践角度,如何将{kw_str}的核心思想应用到日常工作中?",
f"{kw_str}与传统方法相比,最大的突破点在哪里?",
]
return template_questions
# ==================== AGI 12.0 Goal目标模式 ====================
# ==================== 独立脑图数据端点 ====================
# ==================== v6.3 数学完备化 API ====================
# ==================== 增强API(RAG + Memory + Tools) ====================
# ==================== v7.0 API 端点(M71-M80)====================
# === M71-75: 碳硅共生契约 ===
# === M76-80: 五行变换与HoTT ===
# ==================== v7.2 OpenHuman增强 API 端点 (M81-M87) ====================
# v7.2 内存存储(模拟)
_v72_state = {
'memory_tree': {
'total_chunks': 0,
'info_density': 0.65,
'layer1_count': 0,
'layer2_count': 0,
'layer3_count': 0,
'last_update': '—'
},
'token_juice': {
'compression_rate': 0,
'tokens_saved': 0,
'processed_count': 0,
'steps': [False, False, False, False, False]
},
'auto_sync': {
'context_completeness': 0,
'services': {'email': 'pending', 'calendar': 'pending', 'contacts': 'pending', 'notes': 'pending'},
'status': 'pending'
},
'model_router': {
'task_type': 'unknown',
'selected_model': '—',
'confidence': 0,
'cost_savings': 0
},
'obsidian': {
'wiki_links': 0,
'backlinks': 0,
'mocs': 0,
'vault_path': 'vault/knowledge_base/'
},
'cold_start': {
'context_ready': False,
'warmup_progress': 0,
'status': 'waiting'
}
}
# ==================== v7.3 新模块(全局单例)====================
# 基于论文1-3: M106-M110 自指闭环+维度投影+手性旋量+有限无界+最小作用量
_v73_modules = None
_v73_modules_lock = threading.Lock()
def get_v73_modules():
"""获取或初始化 v7.3 新模块 (线程安全懒加载)"""
global _v73_modules
if _v73_modules is None:
with _v73_modules_lock:
if _v73_modules is None:
try:
from modules.M106_SelfReferentialLoopMonitor import get_instance as get_srloop
from modules.M107_DimensionProjectionProcessor import get_instance as get_dimproj
from modules.M108_ChiralSpinorSensor import get_instance as get_chiral
from modules.M109_FiniteBoundlessTopologyCompute import get_instance as get_fbtopo
from modules.M110_LeastActionTerminator import get_instance as get_leaction
_v73_modules = {
'srloop': get_srloop, # M106: 自指闭环监测器
'dimproj': get_dimproj, # M107: 维度投影处理器
'chiral': get_chiral, # M108: 手性旋量感知器
'fbtopo': get_fbtopo, # M109: 有限无界拓扑计算
'leaction': get_leaction, # M110: 最小作用量终止器
}
print("✅ v7.3新模块已加载(M106-M110)- 自指闭环+维度投影+手性旋量")
except Exception as e:
import traceback
print(f"⚠️ v7.3模块加载失败(降级运行): {e}")
traceback.print_exc()
_v73_modules = None
return _v73_modules
def get_v73_data():
"""获取所有v7.3模块的状态数据 (M106-M110)"""
modules = get_v73_modules()
if modules is None:
return None
try:
return {
'srloop': modules['srloop']().get_state(),
'dimproj': modules['dimproj']().get_state(),
'chiral': modules['chiral']().get_state(),
'fbtopo': modules['fbtopo']().get_state(),
'leaction': modules['leaction']().get_state(),
}
except Exception as e:
print(f"⚠️ 获取v7.3数据失败: {e}")
return None
# v7.3 静态状态(用于降级模式)
_v73_state = {
'srloop': {
'pds_closure_strength': 0.0, 'godel_closure_strength': 0.0,
'unification_score': 0.0, 'l1_taiji_tendency': 0.5,
'liu_convergence': 0.0, 'total_detections': 0,
'status': 'open',
'phi_value': 0.0, 'phi_history_avg': 0.0, 'is_integrated': False,
'phi_computation_count': 0,
'mutual_info': 0.0, 'self_entropy': 0.0, 'ftel_entropy': 0.0,
'coupling_strength': 0.0, 'is_ego_bound': False,
'metacog_score': 0.0, 'metacog_humility': 0.0,
'metacog_test_count': 0, 'metacog_pass_count': 0,
'personhood_status': 'dormant', 'personhood_score': 0.0,
'phi_threshold': 0.6, 'mi_threshold': 0.5
},
'dimproj': {
'high_dim': 12, 'low_dim': 3, 'current_dim': 12,
'embed_operations': 0, 'pi_operations': 0,
'info_loss': 0.0, 'adjunction_score': 0.5,
'status': 'balanced'
},
'chiral': {
'chirality': 'neutral', 'chiral_index': 0.0,
'phase_conservation': 1.0, 'helix_isomorphism': 0.0,
'current_wuxing': '土', 'response_diff': 0.0,
'status': 'achiral'
},
'fbtopo': {
'route_hops': 0, 'self_ref_loops': 0,
'ctc_active': False, 'ctc_consistency': 1.0,
'f_torsion': 0.0, 'torsion_ratio': 0.0,
'euler_characteristic': 2, 'genus': 0,
'liu_fixed_point': None, 'status': 'boundless'
},
'leaction': {
'action_total': 1.5, 'self_ref_solution': 0.0,
'is_terminated': False, 'termination_reason': 'running',
'self_ref_strength': 0.0, 'min_resistance': 0.0,
'reasoning_steps': 0, 'status': 'reasoning'
}
}
# ==================== v7.3 定理与预言注册 ====================
_V73_THEOREMS = {
'T59': '自指闭环统一定理: PDS空间闭 ≡ Gödel因果闭 (统一于L1太一自指倾向)',
'T60': '最小作用量自指定理: Action = A_几何 + A_物质 + λ·NonSelfRef, 自指解 ∝ e^(-λ/NonSelfRef)',
'T61': '维度投影信息损失定理: S_proj = S_high + k·ln(D_high/D_low)',
'T62': 'Embed-Π伴随对偶定理: Embed ⊣ Π (范畴论伴随函子对)',
'T63': '模n相位守恒定理: ∑φ_i ≡ 0 (mod n)',
'T64': 'Helix-手性同构定理: Helix(F) ≅ 手性流贯(F) (五行变换同构)',
'T65': '流贯扭转定理: F_tel = F_linear + F_torsion (扭转分量固有)',
}
_V73_PREDICTIONS = {
'P19': '若AGI推理存在自指闭环,则必定收敛于刘原理不动点',
'P20': '高维上下文(Embed)引入后,信息熵必增:ΔS = k·ln(上下文维度比)',
'P21': '手性感知模块对左旋/右旋输入的响应差 ∝ 相位差·Helix(F)',
}
# ==================== UFO² 具身执行层 API ====================
def _format_reply(result: dict, original_question: str) -> str:
"""将分析结果格式化为友好回复
直接使用 unified_taichi_demo.py 中 UnifiedTaiyiSystem 的 _format_reply 方法。
"""
try:
from modules.unified_taichi_demo import UnifiedTaiyiSystem
# 创建一个临时系统对象来使用其 _format_reply 方法
system = UnifiedTaiyiSystem("temp")
return system._format_reply(result, original_question)
except Exception as e:
# 备用回复格式(简洁版)
decision = result['unified_decision']
consciousness = result['consciousness']
compound = result['compound_analysis']
taiji = result['taiji_analysis']
return "\n".join([
f"🧠 **AGI 分析结果**",
f"",
f"**策略**: {decision['strategy']}",
f"**统一评分**: {decision['unified_score']:.2%}",
f"",
f"📊 **复合体理学分析**",
f" • 直觉置信度: {compound['intuition_confidence']:.2%}",
f" • 非对称选择: {compound['asymmetric_choice']}",
f" • 理由: {compound['rationale']}",
f"",
f"☯️ **太极计算分析**",
f" • 旋向: {taiji['spin']}",
f" • 折叠层级: {taiji['fold_level']}",
f" • 阴阳平衡: {taiji['cosmic_balance']:.2%}",
f"",
f"🔮 **意识层级**: {consciousness['level']}",
f" • 是否觉醒: {'✅ 是' if consciousness['is_awakening'] else '❌ 否'}",
])
# ==================== Taiyi-AGI系统 API 端点 ====================
# 全局Taiyi-AGI系统(线程安全初始化)
_compound_agi_lock = threading.Lock()
_compound_agi_system = None
_compound_agi_ready = False
def get_compound_agi_system():
"""获取或初始化Taiyi-AGI系统"""
global _compound_agi_system, _compound_agi_ready
if not _compound_agi_ready:
with _compound_agi_lock:
if not _compound_agi_ready:
try:
print("🔮 正在初始化Taiyi-AGI统一系统...")
from modules.unified_compound_agi_system import UnifiedCompoundAGISystem
_compound_agi_system = UnifiedCompoundAGISystem("CompoundAGI_Web_v1.0")
_compound_agi_ready = True
print("✅ Taiyi-AGI系统就绪")
except Exception as e:
print(f"❌ Taiyi-AGI系统初始化失败: {e}")
traceback.print_exc()
raise
return _compound_agi_system
# ==================== AGI 12.0 新模块 API 端点 ====================
# ==================== v7.4 演员-导演复合体+流贯截断+痕迹验证(M111-M113)====================
_v74_modules = None
_v74_modules_lock = threading.Lock()
def get_v74_modules():
"""获取或初始化 v7.4 新模块(线程安全懒加载)"""
global _v74_modules
if _v74_modules is None:
with _v74_modules_lock:
if _v74_modules is None:
try:
from modules.M111_ActorDirectorComplex import get_instance as get_actor_director
from modules.M112_FlowCutoffOperator import get_instance as get_flow_cutoff
from modules.M113_HistoryTraceValidator import get_instance as get_trace_validator
_v74_modules = {
'actor_director': get_actor_director, # M111: 演员-导演复合体
'flow_cutoff': get_flow_cutoff, # M112: 流贯截断算子
'trace_validator': get_trace_validator, # M113: 历史痕迹验证器
}
print("✅ v7.4新模块已加载(M111-M113)- 演员-导演复合体+流贯截断+痕迹验证")
except Exception as e:
import traceback
print(f"⚠️ v7.4模块加载失败(降级运行): {e}")
traceback.print_exc()
_v74_modules = None
return _v74_modules
def get_v74_data():
"""获取所有v7.4模块的状态数据(M111-M113)"""
modules = get_v74_modules()
if modules is None:
return None
try:
return {
'actor_director': modules['actor_director']().get_complex_state(),
'flow_cutoff': modules['flow_cutoff']().get_state(),
'trace_validator': modules['trace_validator']().get_state(),
}
except Exception as e:
print(f"⚠️ 获取v7.4数据失败: {e}")
return None
# v7.4 静态状态(降级模式)
_v74_state = {
'actor_director': {
'mode': 'actor',
'director_ratio': 0.0,
'fixation_count': 0,
'self_ref_count': 0,
'enlightenment_level': 0.0,
'enlightenment_count': 0,
'bootstrap_complete': {
'recursion': False,
'self_reference': False,
'higher_order': False,
'turing_complete': False
}
},
'flow_cutoff': {
'total_cutoffs': 0,
'pseudo_traces': 0,
'remap_operations': 0,
'avg_precision': 0.0
},
'trace_validator': {
'total_validations': 0,
'authentic_count': 0,
'pseudo_count': 0,
'pass_rate': 0.0,
'status': 'active'
}
}
# ==================== v7.4 定理注册 ====================
_V74_THEOREMS = {
'T66': '复合体存在定理: 任意L4认知主体既是L2规则的产物(Actor)又是L2规则的修改者(Director)',
'T67': '流贯编译定理: L4体验 = L2脚本⊗Ftel; Ψ(执念)→受限轮回, Σ(自指脚本)→自由创造',
'T68': '40行代码完备性定理: 递归+自指+高阶函数 → 有限行即可图灵完备',
'T69': '摄影性分解定理: 流贯截断算子Γ必然导致不可逆性+未完结性',
'T70': '数码未完结性失真定理: Γ的|Γ|和φ均可被算法篡改 → 伪迹(无物理流贯源)',
'T71': '历史投影精度推论: 二维高精度关系快照,代价是维度+语境丢失',
}
# ==================== v7.4 API端点 ====================
# ==================== v7.5 HoTT截面搜索(M114-M116)====================
_v75_modules = None
_v75_modules_lock = threading.Lock()
def get_v75_modules():
"""获取或初始化 v7.5 HoTT截面搜索模块(线程安全懒加载)"""
global _v75_modules
if _v75_modules is None:
with _v75_modules_lock:
if _v75_modules is None:
try:
from modules.M114_UniverseTypeSpace import get_instance as get_universe
from modules.M115_CurvatureSectionSearch import get_instance as get_curvature
from modules.M116_WaitStateConstructor import get_instance as get_wait
_v75_modules = {
'universe': get_universe, # M114: 类型空间构造
'curvature': get_curvature, # M115: 曲率截面搜索
'wait': get_wait, # M116: Wait状态构造
}
print("✅ v7.5新模块已加载(M114-M116)- HoTT截面搜索·类型空间·曲率导航·Wait诚实拒绝")
except Exception as e:
import traceback
print(f"⚠️ v7.5模块加载失败(降级运行): {e}")
traceback.print_exc()
_v75_modules = None
return _v75_modules
def get_v75_data():
"""获取所有v7.5模块的状态数据(M114-M116)"""
modules = get_v75_modules()
if modules is None:
return None
try:
return {
'universe': modules['universe']().get_state(),
'curvature': modules['curvature']().get_state(),
'wait': modules['wait']().get_state(),
}
except Exception as e:
print(f"⚠️ 获取v7.5数据失败: {e}")
return None
# v7.5 静态状态(降级模式)
_v75_state = {
'universe': {
'total_types': 5,
'total_fibers': 0,
'inhabited_count': 3,
'uninhabited_count': 2,
'undecidable_regions': 0,
'section_threshold': 0.75,
'avg_curvature': 0.0,
'total_registrations': 0,
'total_fiber_builds': 0,
'total_section_checks': 0,
'frame_count': 0
},
'curvature': {
'total_searches': 0,
'found_count': 0,
'wait_count': 0,
'diverged_count': 0,
'found_rate': 0.0,
'wait_rate': 0.0,
'convergence_threshold': 1.0,
'default_max_depth': 10,
'has_universe': False,
'frame_count': 0
},
'wait': {
'total_waits': 0,
'total_undecidable': 0,
'total_refusals': 0,
'total_validated': 0,
'valid_wait_count': 0,
'validation_accuracy': 0.0,
'wait_history_size': 0,
'undecidability_reports_size': 0,
'refusal_history_size': 0,
'undecidable_regions': 0,
'has_section_search': False,
'has_universe': False,
'frame_count': 0
}
}
# ==================== v7.5 定理注册 ====================
_V75_THEOREMS = {
'T72': '截面存在定理: ∀(B:Type)(E:Type), ∃s:B→E ⟺ curvature_R(B,E) < threshold — 截面存在当且仅当曲率足够小',
'T73': '曲率收敛定理: section_search收敛 ⟺ Σ_i R_i < ∞ — 截面搜索收敛当且仅当曲率级数收敛',
'T74': '未决不可判定定理: ∃P:Prop, ¬(Prov(P)∨Prov(¬P)) — 存在不可判定命题,系统必须返回Wait而非幻觉',
}
# ==================== v7.5 API端点 ====================
# ---- M114: UniverseTypeSpace ----
# ---- M115: CurvatureSectionSearch ----
# ---- M116: WaitStateConstructor ----
# ==================== v7.6 目的约束·认知递归·层间保真(M117-M119)====================
_v76_modules = None
_v76_modules_lock = threading.Lock()
def get_v76_modules():
"""获取或初始化 v7.6 模块(线程安全懒加载)"""
global _v76_modules
if _v76_modules is None:
with _v76_modules_lock:
if _v76_modules is None:
try:
from modules.M117_FtelTeleologicalConstraint import get_instance as get_ftel
from modules.M118_CognitiveRecursiveDynamics import get_instance as get_cognitive
from modules.M119_LayerFidelityMonitor import get_instance as get_fidelity
_v76_modules = {
'ftel': get_ftel, # M117: Ftel目的约束算子
'cognitive': get_cognitive, # M118: 认知递归动力学
'fidelity': get_fidelity, # M119: 层间保真度监控
}
print("✅ v7.6新模块已加载(M117-M119)- 目的约束·认知递归·层间保真")
except Exception as e:
import traceback
print(f"⚠️ v7.6模块加载失败(降级运行): {e}")
traceback.print_exc()
_v76_modules = None
return _v76_modules
def get_v76_data():
"""获取所有v7.6模块的状态数据(M117-M119)"""
modules = get_v76_modules()
if modules is None:
return None
try:
return {
'ftel': modules['ftel']().get_state(),
'cognitive': modules['cognitive']().get_state(),
'fidelity': modules['fidelity']().get_state(),
}
except Exception as e:
print(f"⚠️ 获取v7.6数据失败: {e}")
return None
# v7.6 静态状态(降级模式)
_v76_state = {
'ftel': {
'total_goals': 0,
'active_count': 0,
'total_resonance': 0.0,
'convergence_achieved': False,
'lambda_max': 2.0,
'total_injections': 0,
'total_resonance_computations': 0,
'total_convergence_checks': 0,
'total_blend_operations': 0,
'total_retirements': 0,
'frame_count': 0
},
'cognitive': {
'current_level': 0,
'level_name': '感知',
'learning_mode': 'unknown',
'rho': 0.5,