memgate 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +12 -0
- package/README.md +52 -2
- package/VERSIONS.json +17 -0
- package/dist/index.js +726 -0
- package/index.ts +25 -0
- package/openclaw.plugin.json +53 -0
- package/package.json +37 -3
- package/src/admission.py +208 -0
- package/src/bridge.ts +205 -0
- package/src/bridge_cli.py +600 -0
- package/src/context-engine.ts +373 -0
- package/src/hebbian_link.py +34 -0
- package/src/kernel/activity_telemetry.py +51 -0
- package/src/kernel/admission.py +208 -0
- package/src/kernel/calldecay/__init__.py +24 -0
- package/src/kernel/calldecay/__main__.py +7 -0
- package/src/kernel/calldecay/_kernel.py +32 -0
- package/src/kernel/calldecay/adapter.py +126 -0
- package/src/kernel/calldecay/cli.py +80 -0
- package/src/kernel/calldecay/gate.py +93 -0
- package/src/kernel/calldecay/landing.py +1298 -0
- package/src/kernel/calldecay/metrics.py +37 -0
- package/src/kernel/calldecay/mock.py +68 -0
- package/src/kernel/calldecay/pipeline.py +85 -0
- package/src/kernel/calldecay/proxy.py +220 -0
- package/src/kernel/calldecay/summarize.py +401 -0
- package/src/kernel/core/LICENSE +228 -0
- package/src/kernel/core/__init__.py +0 -0
- package/src/kernel/core/accept_contract.py +67 -0
- package/src/kernel/core/chain_probe_world.py +133 -0
- package/src/kernel/core/concept_ontology.py +2401 -0
- package/src/kernel/core/concept_opposition.py +291 -0
- package/src/kernel/core/concept_phase.py +1342 -0
- package/src/kernel/core/concept_principle.py +2481 -0
- package/src/kernel/core/concept_pyramid.py +287 -0
- package/src/kernel/core/concept_space.py +45 -0
- package/src/kernel/core/concept_space_mixin.py +941 -0
- package/src/kernel/core/concept_state.py +2748 -0
- package/src/kernel/core/decision_symbolic.py +245 -0
- package/src/kernel/core/eco_math_world.py +489 -0
- package/src/kernel/core/emergence.py +362 -0
- package/src/kernel/core/events.py +93 -0
- package/src/kernel/core/hebbian.py +117 -0
- package/src/kernel/core/llm_arm.py +551 -0
- package/src/kernel/core/memory_shadow.py +158 -0
- package/src/kernel/core/mes_layer_base.py +309 -0
- package/src/kernel/core/mes_vnext.py +540 -0
- package/src/kernel/core/ontology_core.py +168 -0
- package/src/kernel/core/phase_field.py +187 -0
- package/src/kernel/core/reasoning.py +185 -0
- package/src/kernel/core/rhythm_vnext.py +777 -0
- package/src/kernel/dashboard_render.py +196 -0
- package/src/kernel/depscan_probe.py +96 -0
- package/src/kernel/health_probe.py +186 -0
- package/src/kernel/hebbian_link.py +34 -0
- package/src/kernel/knowledge_distiller/README.md +9 -0
- package/src/kernel/knowledge_distiller/__init__.py +1 -0
- package/src/kernel/knowledge_distiller/knowledge_distiller.py +196 -0
- package/src/kernel/m3_judge.py +215 -0
- package/src/kernel/mechanism_advisor.py +203 -0
- package/src/kernel/mechanism_learner.py +193 -0
- package/src/kernel/memory_core.py +81 -0
- package/src/kernel/quality_gate/README.md +9 -0
- package/src/kernel/quality_gate/__init__.py +1 -0
- package/src/kernel/quality_gate/quality_gate.py +7 -0
- package/src/kernel/registry_gate.py +57 -0
- package/src/kernel/semantic_recall.py +635 -0
- package/src/kernel/tiered_decay/README.md +9 -0
- package/src/kernel/tiered_decay/__init__.py +1 -0
- package/src/kernel/tiered_decay/tiered_decay.py +17 -0
- package/src/kernel/tokenizer/README.md +9 -0
- package/src/kernel/tokenizer/__init__.py +2 -0
- package/src/kernel/tokenizer/tokenizer.py +14 -0
- package/src/kernel/version_binding.py +131 -0
- package/src/knowledge_distiller.py +196 -0
- package/src/m3_collector.py +247 -0
- package/src/m3_judge.py +215 -0
- package/src/memory-capability.ts +44 -0
- package/src/semantic_recall.py +635 -0
- package/src/thinking_stub.ts +141 -0
- package/src/toolface_hook.ts +69 -0
- package/src/tools.ts +98 -0
- package/src/vendor/calldecay-sdk/calldecay/__init__.py +24 -0
- package/src/vendor/calldecay-sdk/calldecay/__main__.py +7 -0
- package/src/vendor/calldecay-sdk/calldecay/_kernel.py +32 -0
- package/src/vendor/calldecay-sdk/calldecay/adapter.py +126 -0
- package/src/vendor/calldecay-sdk/calldecay/cli.py +80 -0
- package/src/vendor/calldecay-sdk/calldecay/gate.py +93 -0
- package/src/vendor/calldecay-sdk/calldecay/landing.py +1298 -0
- package/src/vendor/calldecay-sdk/calldecay/metrics.py +37 -0
- package/src/vendor/calldecay-sdk/calldecay/mock.py +68 -0
- package/src/vendor/calldecay-sdk/calldecay/pipeline.py +85 -0
- package/src/vendor/calldecay-sdk/calldecay/proxy.py +220 -0
- package/src/vendor/calldecay-sdk/calldecay/summarize.py +401 -0
- package/src/vendor/core/LICENSE +228 -0
- package/src/vendor/core/__init__.py +0 -0
- package/src/vendor/core/accept_contract.py +67 -0
- package/src/vendor/core/chain_probe_world.py +133 -0
- package/src/vendor/core/concept_ontology.py +2401 -0
- package/src/vendor/core/concept_opposition.py +291 -0
- package/src/vendor/core/concept_phase.py +1342 -0
- package/src/vendor/core/concept_principle.py +2481 -0
- package/src/vendor/core/concept_pyramid.py +287 -0
- package/src/vendor/core/concept_space.py +45 -0
- package/src/vendor/core/concept_space_mixin.py +941 -0
- package/src/vendor/core/concept_state.py +2748 -0
- package/src/vendor/core/decision_symbolic.py +245 -0
- package/src/vendor/core/eco_math_world.py +489 -0
- package/src/vendor/core/emergence.py +362 -0
- package/src/vendor/core/events.py +93 -0
- package/src/vendor/core/hebbian.py +117 -0
- package/src/vendor/core/llm_arm.py +551 -0
- package/src/vendor/core/memory_shadow.py +158 -0
- package/src/vendor/core/mes_layer_base.py +309 -0
- package/src/vendor/core/mes_vnext.py +540 -0
- package/src/vendor/core/ontology_core.py +168 -0
- package/src/vendor/core/phase_field.py +187 -0
- package/src/vendor/core/reasoning.py +185 -0
- package/src/vendor/core/rhythm_vnext.py +777 -0
- package/src/vendor/pvs-sdk/pvs/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/adapters/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/adapters/llm_backends.py +69 -0
- package/src/vendor/pvs-sdk/pvs/core/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/core/budget.py +84 -0
- package/src/vendor/pvs-sdk/pvs/core/llm_gate.py +149 -0
- package/src/vendor/pvs-sdk/pvs/core/memory.py +143 -0
- package/src/vendor/pvs-sdk/pvs/core/pvs.py +175 -0
- package/src/vendor/pvs-sdk/pvs/core/verifier.py +77 -0
- package/src/vendor/pvs-sdk/pvs/eval/__init__.py +3 -0
- package/src/vendor/pvs-sdk/pvs/eval/coverage.py +82 -0
- package/src/vendor/pvs-sdk/pvs/gate/__init__.py +5 -0
- package/src/vendor/pvs-sdk/pvs/gate/__main__.py +3 -0
- package/src/vendor/pvs-sdk/pvs/gate/boot.py +68 -0
- package/src/vendor/pvs-sdk/pvs/gate/ledger.py +157 -0
- package/src/vendor/pvs-sdk/pvs/gate/preflight.py +342 -0
- package/src/vendor/pvs-sdk/pvs/harness/__init__.py +0 -0
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""LLM 决策臂: 概念空间精疲力尽时的外部候选 (路线 3, 2026-09-24)
|
|
2
|
+
|
|
3
|
+
黄金准则:
|
|
4
|
+
- LLM 臂 = 第一候选, 不是最终决策者 — 候选最终由元仲裁/轮换决定
|
|
5
|
+
- LLM 候选不设预期 (与记忆候选同级, 结果由 RPE 自然修正)
|
|
6
|
+
- gated 默认关 (LLM_ARM=1 启用) — 零影响既有行为
|
|
7
|
+
- 所有 LLM 调用审计日志 → experiments/llm_arm/audit/ (可复现)
|
|
8
|
+
- 超时 fallback → None (不阻塞行为环)
|
|
9
|
+
- 调用方: decision_symbolic.decide_symbolic 在 unplanned 回退路径中
|
|
10
|
+
- 后端: llama.cpp server (OpenAI 兼容 API), 本机 8082 端口
|
|
11
|
+
|
|
12
|
+
三铁律:
|
|
13
|
+
1. LLM 臂不写 concept_space, 不调边权重, 不提建议 — 只建议动作
|
|
14
|
+
2. 所有建议标注 is_explore=True (不设预期)
|
|
15
|
+
3. 默认关已验证 (全量回归时 LLM_ARM=0 逐位不变)
|
|
16
|
+
"""
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
import subprocess
|
|
21
|
+
import time
|
|
22
|
+
import traceback
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
from typing import Optional, Dict, Any, List
|
|
25
|
+
|
|
26
|
+
log = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
# ── gated ────────────────────────────────────────────────
|
|
29
|
+
ENABLED = os.environ.get('LLM_ARM', '0') == '1'
|
|
30
|
+
_AUDIT_DIR = os.environ.get('LLM_ARM_AUDIT_DIR',
|
|
31
|
+
'experiments/llm_arm/audit/')
|
|
32
|
+
|
|
33
|
+
# 后端: llama.cpp server (OpenAI 兼容);LLM_ARM_HOSTS=逗号分隔回落链(首项优先,
|
|
34
|
+
# 2026-11-06 包裹本地模型模式:本地模型 + 云 API 组合),未设则等价单主机旧行为。
|
|
35
|
+
_LLAMA_HOST = os.environ.get('LLM_ARM_HOST', 'http://localhost:8082')
|
|
36
|
+
_HOSTS_RAW = os.environ.get('LLM_ARM_HOSTS', '') or _LLAMA_HOST
|
|
37
|
+
_LLAMA_HOSTS = [h.strip() for h in _HOSTS_RAW.split(',') if h.strip()]
|
|
38
|
+
_TIMEOUT = int(os.environ.get('LLM_ARM_TIMEOUT', '15'))
|
|
39
|
+
|
|
40
|
+
# ── 门控降级逻辑 ────────────────────────────────────────
|
|
41
|
+
# 门控等级 0-4 (BAN/OFF/RELUCTANT/NORMAL/EAGER)
|
|
42
|
+
_GATE_LEVEL = int(os.environ.get('LLM_ARM_GATE', '0')) # 默认 OFF
|
|
43
|
+
_GATE_LEVEL_DEFAULT = _GATE_LEVEL
|
|
44
|
+
|
|
45
|
+
# 调用概率映射 (level -> probability)
|
|
46
|
+
_GATE_PROB_MAP = {0: 0.0, 1: 0.0, 2: 0.1, 3: 0.5, 4: 0.9}
|
|
47
|
+
|
|
48
|
+
# 评估窗口
|
|
49
|
+
_GATE_EVAL_L = int(os.environ.get('LLM_ARM_EVAL_L', '10'))
|
|
50
|
+
_GATE_FAIL_N = int(os.environ.get('LLM_ARM_FAIL_N', '5'))
|
|
51
|
+
|
|
52
|
+
# 调用历史 (列表, 每条 {'action_ok': bool, 'novelty_resolved': bool})
|
|
53
|
+
_gate_history: list = []
|
|
54
|
+
|
|
55
|
+
# ======== 门控 API ========
|
|
56
|
+
def gate_level() -> int:
|
|
57
|
+
return _GATE_LEVEL
|
|
58
|
+
|
|
59
|
+
def gate_level_str(level: int = _GATE_LEVEL) -> str:
|
|
60
|
+
return ['BAN', 'OFF', 'RELUCTANT', 'NORMAL', 'EAGER'][min(level, 4)]
|
|
61
|
+
|
|
62
|
+
def gate_should_call() -> bool:
|
|
63
|
+
"""根据当前门控等级和调用概率决定是否调 LLM"""
|
|
64
|
+
if _QUARANTINE['active']:
|
|
65
|
+
return gate_quarantine_probe_due() # 隔离期: 仅探测调用可出
|
|
66
|
+
if _GATE_LEVEL == 0 or _GATE_LEVEL == 1:
|
|
67
|
+
return False
|
|
68
|
+
p = _GATE_PROB_MAP.get(_GATE_LEVEL, 0.0)
|
|
69
|
+
import random
|
|
70
|
+
return random.random() < p
|
|
71
|
+
|
|
72
|
+
def gate_raise(novelty_strength: float = 0.0):
|
|
73
|
+
"""提升门控等级.
|
|
74
|
+
Args:
|
|
75
|
+
novelty_strength: 新颖性增益(>2.0 直接跃升到 3)
|
|
76
|
+
"""
|
|
77
|
+
global _GATE_LEVEL
|
|
78
|
+
if novelty_strength > 2.0:
|
|
79
|
+
_GATE_LEVEL = max(_GATE_LEVEL, 3) # 直接跃升到 NORMAL
|
|
80
|
+
else:
|
|
81
|
+
_GATE_LEVEL = min(_GATE_LEVEL + 1, 4)
|
|
82
|
+
|
|
83
|
+
def gate_record_call(action_ok: bool, novelty_resolved: bool):
|
|
84
|
+
"""记录一次 LLM 调用结果, 用于降级评估"""
|
|
85
|
+
_gate_history.append({'action_ok': action_ok, 'novelty_resolved': novelty_resolved})
|
|
86
|
+
# 截断历史到评估窗口大小
|
|
87
|
+
while len(_gate_history) > _GATE_EVAL_L + 5:
|
|
88
|
+
_gate_history.pop(0)
|
|
89
|
+
|
|
90
|
+
def gate_eval_downgrade() -> bool:
|
|
91
|
+
"""评估最近 L 条调用, 若条件满足则降级. 返回 True = 已降级"""
|
|
92
|
+
global _GATE_LEVEL
|
|
93
|
+
if _GATE_LEVEL <= 1:
|
|
94
|
+
return False
|
|
95
|
+
recent = _gate_history[-_GATE_EVAL_L:] if len(_gate_history) >= _GATE_EVAL_L else _gate_history
|
|
96
|
+
if len(recent) < _GATE_EVAL_L // 2:
|
|
97
|
+
return False # 样本不足, 不评估
|
|
98
|
+
# 有效动作率
|
|
99
|
+
n_ok = sum(1 for r in recent if r['action_ok'])
|
|
100
|
+
n_resolved = sum(1 for r in recent if r['novelty_resolved'])
|
|
101
|
+
# 降级条件: 有效动作率 > 0.8 且新颖性已消退
|
|
102
|
+
if n_ok >= len(recent) * 0.8 and n_resolved >= len(recent) * 0.8:
|
|
103
|
+
_GATE_LEVEL = max(_GATE_LEVEL - 1, 1)
|
|
104
|
+
return True
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
# ── 门控隔离 (对称信任规则: 有效动作率下限隔离 + 探测恢复) ──
|
|
108
|
+
# 2026-09-27: 补"顾问失效不切断"缺口. 默认关 (LLM_ARM_QUARANTINE=0) ⇒ 零行为变化.
|
|
109
|
+
# 触发: 滑窗 _QUAR_W 条调用的有效动作率 < _QUAR_LOW ⇒ 隔离 (仅探测可出)
|
|
110
|
+
# 解除: 探测连续 _QUAR_PROBE_N 次有效率 ≥ _QUAR_HIGH ⇒ 恢复 (对称峰值保持)
|
|
111
|
+
_QUAR_ENABLED = os.environ.get('LLM_ARM_QUARANTINE', '0') == '1'
|
|
112
|
+
_QUAR_LOW = float(os.environ.get('LLM_ARM_QUAR_LOW', '0.2'))
|
|
113
|
+
_QUAR_HIGH = float(os.environ.get('LLM_ARM_QUAR_HIGH', '0.5'))
|
|
114
|
+
_QUAR_W = int(os.environ.get('LLM_ARM_QUAR_W', '10'))
|
|
115
|
+
_QUAR_K = int(os.environ.get('LLM_ARM_QUAR_K', '5'))
|
|
116
|
+
_QUAR_PROBE_N = int(os.environ.get('LLM_ARM_QUAR_PROBE_N', '3'))
|
|
117
|
+
_QUARANTINE = {'active': False, 'enter_step': None, 'steps_since_probe': 0,
|
|
118
|
+
'probe_results': [], 'events': []}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def gate_quarantine_active() -> bool:
|
|
122
|
+
return _QUARANTINE['active']
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def gate_eval_quarantine(step: int = 0) -> str:
|
|
126
|
+
"""每步调用. 返回 'none' | 'enter'. 新颖性不解除隔离 (仅探测可解除)"""
|
|
127
|
+
if not _QUAR_ENABLED:
|
|
128
|
+
return 'none'
|
|
129
|
+
q = _QUARANTINE
|
|
130
|
+
if q['active']:
|
|
131
|
+
q['steps_since_probe'] += 1
|
|
132
|
+
return 'none'
|
|
133
|
+
recent = _gate_history[-_QUAR_W:] if len(_gate_history) >= _QUAR_W else _gate_history
|
|
134
|
+
if len(recent) >= max(_QUAR_W // 2, 2):
|
|
135
|
+
rate = sum(1 for r in recent if r['action_ok']) / len(recent)
|
|
136
|
+
if rate < _QUAR_LOW:
|
|
137
|
+
q.update(active=True, enter_step=step, steps_since_probe=0, probe_results=[])
|
|
138
|
+
q['events'].append({'type': 'enter', 'step': step, 'rate': round(rate, 3)})
|
|
139
|
+
return 'enter'
|
|
140
|
+
return 'none'
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def gate_quarantine_probe_due() -> bool:
|
|
144
|
+
q = _QUARANTINE
|
|
145
|
+
return q['active'] and q['steps_since_probe'] >= _QUAR_K
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def gate_quarantine_record_probe(action_ok: bool, step: int = 0) -> str:
|
|
149
|
+
"""探测结果记录; 连续 _QUAR_PROBE_N 次有效率 ≥ _QUAR_HIGH ⇒ 解除隔离"""
|
|
150
|
+
q = _QUARANTINE
|
|
151
|
+
q['steps_since_probe'] = 0
|
|
152
|
+
q['probe_results'].append(bool(action_ok))
|
|
153
|
+
if len(q['probe_results']) >= _QUAR_PROBE_N:
|
|
154
|
+
rate = sum(q['probe_results']) / len(q['probe_results'])
|
|
155
|
+
if rate >= _QUAR_HIGH:
|
|
156
|
+
q.update(active=False, probe_results=[])
|
|
157
|
+
q['events'].append({'type': 'exit', 'step': step, 'rate': round(rate, 3)})
|
|
158
|
+
return 'exit'
|
|
159
|
+
return 'stay'
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def gate_quarantine_state() -> dict:
|
|
163
|
+
q = _QUARANTINE
|
|
164
|
+
return {'active': q['active'], 'enter_step': q['enter_step'],
|
|
165
|
+
'steps_since_probe': q['steps_since_probe'],
|
|
166
|
+
'probe_results': list(q['probe_results']), 'events': list(q['events']),
|
|
167
|
+
'enabled': _QUAR_ENABLED, 'low': _QUAR_LOW, 'high': _QUAR_HIGH,
|
|
168
|
+
'window': _QUAR_W, 'probe_interval': _QUAR_K,
|
|
169
|
+
'probe_n': _QUAR_PROBE_N}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def gate_reset():
|
|
173
|
+
"""重置门控到默认 (LLM_ARM=1 启动时的初始等级)"""
|
|
174
|
+
global _GATE_LEVEL
|
|
175
|
+
global _gate_history
|
|
176
|
+
_GATE_LEVEL = int(os.environ.get('LLM_ARM_GATE', '0'))
|
|
177
|
+
_gate_history = []
|
|
178
|
+
_QUARANTINE.update(active=False, enter_step=None, steps_since_probe=0,
|
|
179
|
+
probe_results=[], events=[])
|
|
180
|
+
|
|
181
|
+
def gate_full_state() -> dict:
|
|
182
|
+
return {
|
|
183
|
+
'level': _GATE_LEVEL,
|
|
184
|
+
'label': gate_level_str(),
|
|
185
|
+
'call_prob': _GATE_PROB_MAP.get(_GATE_LEVEL, 0.0),
|
|
186
|
+
'history_len': len(_gate_history),
|
|
187
|
+
'eval_window': _GATE_EVAL_L,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# ── 审计 ──────────────────────────────────────────────────
|
|
192
|
+
def _audit_log(entry: dict):
|
|
193
|
+
"""每一条 LLM 调用记录审计文件 (JSONL)"""
|
|
194
|
+
if not ENABLED:
|
|
195
|
+
return
|
|
196
|
+
try:
|
|
197
|
+
os.makedirs(_AUDIT_DIR, exist_ok=True)
|
|
198
|
+
ts = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
|
|
199
|
+
path = os.path.join(_AUDIT_DIR, f'llm_arm_{ts}.json')
|
|
200
|
+
with open(path, 'w') as f:
|
|
201
|
+
json.dump(entry, f, ensure_ascii=False, indent=2)
|
|
202
|
+
except Exception as e:
|
|
203
|
+
log.warning(f"[LLM] audit write failed: {e}")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _health(host: str = _LLAMA_HOST) -> dict:
|
|
207
|
+
"""llama.cpp server 健康检查"""
|
|
208
|
+
try:
|
|
209
|
+
r = subprocess.run(
|
|
210
|
+
['curl', '-s', f'{host}/health'],
|
|
211
|
+
capture_output=True, text=True, timeout=5)
|
|
212
|
+
if r.returncode != 0:
|
|
213
|
+
return {'ok': False, 'error': f'curl failed: {r.stderr[:200]}'}
|
|
214
|
+
data = json.loads(r.stdout)
|
|
215
|
+
return {'ok': data.get('status') == 'ok',
|
|
216
|
+
'detail': r.stdout[:200]}
|
|
217
|
+
except Exception as e:
|
|
218
|
+
return {'ok': False, 'error': str(e)}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ── accept 契约 + 候选准入 (F1/F3): 公共契约模块, 单一来源 (B4) ──
|
|
222
|
+
# 见 core/accept_contract.py — 治理层/记忆层两层共享同一 accept 契约,
|
|
223
|
+
try:
|
|
224
|
+
from core.accept_contract import accept, admit # noqa: E402
|
|
225
|
+
except ImportError:
|
|
226
|
+
from accept_contract import accept, admit # noqa: E402
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
# ── 核心建议函数 ───────────────────────────────────────────
|
|
230
|
+
def suggest(obj: str, goal: str, current: Optional[str] = None,
|
|
231
|
+
world_name: str = '',
|
|
232
|
+
actions: Optional[List[str]] = None,
|
|
233
|
+
context: Optional[List] = None,
|
|
234
|
+
timeline: Optional[List[str]] = None) -> Optional[Dict[str, Any]]:
|
|
235
|
+
"""当离散符号层无解时, 问外部 LLM 获得候选动作.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
obj: 当前操作对象
|
|
239
|
+
goal: 目标状态
|
|
240
|
+
current: 当前状态
|
|
241
|
+
world_name: 世界名 (用于 prompt 上下文)
|
|
242
|
+
actions: 可用动作列表
|
|
243
|
+
context: 关联对象状态 (context of SymbolicDecision)
|
|
244
|
+
timeline: 近期事件流 (最后 5-10 条)
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
{'act': str, 'confidence': float, 'reasoning': str}
|
|
248
|
+
None = 无候选 (超时/失败/关闭)
|
|
249
|
+
"""
|
|
250
|
+
if not ENABLED:
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
# 门控检查: 根据等级和概率决定是否调 LLM
|
|
254
|
+
if not gate_should_call():
|
|
255
|
+
return None
|
|
256
|
+
|
|
257
|
+
# 健康检查
|
|
258
|
+
health = _health()
|
|
259
|
+
if not health['ok']:
|
|
260
|
+
log.warning(f"[LLM] llama.cpp unreachable: {health.get('error')}")
|
|
261
|
+
return None
|
|
262
|
+
|
|
263
|
+
# --- 构建 prompt ---
|
|
264
|
+
prompt_lines: List[str] = [
|
|
265
|
+
"You are a decision assistant for an autonomous agent.",
|
|
266
|
+
"",
|
|
267
|
+
f"You are in world '{world_name}'.",
|
|
268
|
+
f"Current object: {obj}",
|
|
269
|
+
]
|
|
270
|
+
if current:
|
|
271
|
+
prompt_lines.append(f"Current state: {current}")
|
|
272
|
+
if goal:
|
|
273
|
+
prompt_lines.append(f"Goal: {goal}")
|
|
274
|
+
else:
|
|
275
|
+
prompt_lines.append("Goal: maximize reward (no specific target state)")
|
|
276
|
+
|
|
277
|
+
if actions:
|
|
278
|
+
prompt_lines.append(f"Available actions: {', '.join(actions)}")
|
|
279
|
+
|
|
280
|
+
if context:
|
|
281
|
+
ctx_str = '; '.join([f"{k}={v}" for k, v in context[:6]])
|
|
282
|
+
prompt_lines.append(f"Context: {ctx_str}")
|
|
283
|
+
|
|
284
|
+
if timeline:
|
|
285
|
+
last_events = timeline[-8:]
|
|
286
|
+
prompt_lines.append("Recent events:")
|
|
287
|
+
for ev in last_events:
|
|
288
|
+
prompt_lines.append(f" - {ev}")
|
|
289
|
+
|
|
290
|
+
# 状态感知提示: 当前状态过度时引导保守动作
|
|
291
|
+
# LLM_ARM_HINTS=0 = 消融开关 (提示行编码 2/3 评分分支, 归因实验需关提示)
|
|
292
|
+
if current and os.environ.get('LLM_ARM_HINTS', '1') != '0':
|
|
293
|
+
if current in ('暴增', '爆炸', '多', '过多'):
|
|
294
|
+
prompt_lines.append("")
|
|
295
|
+
prompt_lines.append("提示: 当前状态已接近/超过目标,优先选择观望或放牧")
|
|
296
|
+
elif current in ('濒危', '危险', '即将灭绝'):
|
|
297
|
+
prompt_lines.append("")
|
|
298
|
+
prompt_lines.append("提示: 当前状态极端低落,优先选择保护")
|
|
299
|
+
|
|
300
|
+
prompt_lines.append("")
|
|
301
|
+
prompt_lines.append("最佳:")
|
|
302
|
+
|
|
303
|
+
prompt = '\n'.join(prompt_lines)
|
|
304
|
+
|
|
305
|
+
# --- 调用 llama.cpp API (OpenAI 兼容) ---
|
|
306
|
+
_use_chat = os.environ.get('LLM_ARM_CHAT', '0') == '1'
|
|
307
|
+
if _use_chat:
|
|
308
|
+
# gemma 系 raw 续写不兼容 (回显提示行/裸数字/控制符泄漏, 2026-09-27 审计实锤),
|
|
309
|
+
# 走模型原生 chat 端点; 默认路径零变化
|
|
310
|
+
payload = json.dumps({
|
|
311
|
+
'model': os.environ.get('LLM_ARM_MODEL', ''),
|
|
312
|
+
'messages': [{'role': 'user', 'content': prompt}],
|
|
313
|
+
'temperature': 0.0,
|
|
314
|
+
'max_tokens': 512,
|
|
315
|
+
})
|
|
316
|
+
else:
|
|
317
|
+
payload = json.dumps({
|
|
318
|
+
'prompt': prompt,
|
|
319
|
+
'n_predict': 4,
|
|
320
|
+
'temperature': 0.0,
|
|
321
|
+
'stop': ['```', '###', '\n', '。', '.'],
|
|
322
|
+
'cache_prompt': True, # KV cache 复用: 相同前缀只算一次 (2026-11-18)
|
|
323
|
+
})
|
|
324
|
+
|
|
325
|
+
entry: Dict[str, Any] = {
|
|
326
|
+
'timestamp': datetime.now().isoformat(),
|
|
327
|
+
'prompt_snippet': prompt[:300],
|
|
328
|
+
'world': world_name,
|
|
329
|
+
'obj': obj,
|
|
330
|
+
'goal': goal,
|
|
331
|
+
'current': current,
|
|
332
|
+
'actions': actions,
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
start = time.time()
|
|
336
|
+
try:
|
|
337
|
+
# 主机链回落(2026-11-06):传输失败(拒连/curl 非 0/超时)换下家;
|
|
338
|
+
# 单主机时行为与旧版一致。
|
|
339
|
+
r = None
|
|
340
|
+
_tried = []
|
|
341
|
+
for _host in _LLAMA_HOSTS:
|
|
342
|
+
_api_url = (f'{_host}/v1/chat/completions' if _use_chat
|
|
343
|
+
else f'{_host}/completion')
|
|
344
|
+
try:
|
|
345
|
+
r = subprocess.run(
|
|
346
|
+
['curl', '-s', '-X', 'POST',
|
|
347
|
+
_api_url,
|
|
348
|
+
'-d', payload],
|
|
349
|
+
capture_output=True, text=True, timeout=_TIMEOUT)
|
|
350
|
+
except subprocess.TimeoutExpired:
|
|
351
|
+
_tried.append(f'{_host}(timeout)')
|
|
352
|
+
r = None
|
|
353
|
+
continue
|
|
354
|
+
if r.returncode != 0:
|
|
355
|
+
_tried.append(f'{_host}(curl {r.returncode})')
|
|
356
|
+
r = None
|
|
357
|
+
continue
|
|
358
|
+
entry['host'] = _host
|
|
359
|
+
break
|
|
360
|
+
elapsed = time.time() - start
|
|
361
|
+
entry['elapsed_s'] = round(elapsed, 2)
|
|
362
|
+
|
|
363
|
+
if r is None:
|
|
364
|
+
entry['error'] = ('timeout' if _tried and all('timeout' in t for t in _tried)
|
|
365
|
+
else f'all hosts failed: {_tried}')
|
|
366
|
+
_audit_log(entry)
|
|
367
|
+
return None
|
|
368
|
+
|
|
369
|
+
result = json.loads(r.stdout)
|
|
370
|
+
|
|
371
|
+
if _use_chat:
|
|
372
|
+
_msg = ((result.get('choices') or [{}])[0].get('message') or {})
|
|
373
|
+
_usage = result.get('usage') or {}
|
|
374
|
+
# gemma-4 输出走 deepseek reasoning 格式: 正文常在 reasoning_content
|
|
375
|
+
_txt = (_msg.get('content') or '').strip()
|
|
376
|
+
if not _txt:
|
|
377
|
+
import re as _re2
|
|
378
|
+
_rc = (_msg.get('reasoning_content') or '').strip()
|
|
379
|
+
_m = _re2.findall(r'Action\s*[::]\s*([^\n]+)', _rc)
|
|
380
|
+
if _m:
|
|
381
|
+
_txt = _m[-1]
|
|
382
|
+
else:
|
|
383
|
+
_best, _bi = _rc[-40:], -1
|
|
384
|
+
for _a in (actions or []):
|
|
385
|
+
_i = _rc.rfind(_a)
|
|
386
|
+
if _i > _bi:
|
|
387
|
+
_best, _bi = _a, _i
|
|
388
|
+
_txt = _best
|
|
389
|
+
result = {'content': _txt,
|
|
390
|
+
'timings': {'prompt_n': _usage.get('prompt_tokens'),
|
|
391
|
+
'predicted_n': _usage.get('completion_tokens')}}
|
|
392
|
+
|
|
393
|
+
# token 计量 (2026-09-27): llama.cpp timings → prompt_n/predicted_n
|
|
394
|
+
_tim = result.get('timings') if isinstance(result, dict) else None
|
|
395
|
+
if isinstance(_tim, dict):
|
|
396
|
+
if _tim.get('prompt_n') is not None:
|
|
397
|
+
entry['prompt_tokens'] = _tim['prompt_n']
|
|
398
|
+
if _tim.get('predicted_n') is not None:
|
|
399
|
+
entry['response_tokens'] = _tim['predicted_n']
|
|
400
|
+
|
|
401
|
+
if 'content' not in result:
|
|
402
|
+
entry['error'] = f'no content in response: {r.stdout[:300]}'
|
|
403
|
+
_audit_log(entry)
|
|
404
|
+
return None
|
|
405
|
+
|
|
406
|
+
raw_text = result['content'].strip()
|
|
407
|
+
entry['raw_response'] = raw_text[:200]
|
|
408
|
+
|
|
409
|
+
# 解析: 从 LLM 输出中提取动作名
|
|
410
|
+
# LLM 可能会输出完整句子, 需要切词匹配
|
|
411
|
+
if not actions:
|
|
412
|
+
# 无动作列表: 返回原始文本, 由调用方做二次匹配
|
|
413
|
+
# 取第一个看起来像动作的词
|
|
414
|
+
import re as _re
|
|
415
|
+
words = raw_text.strip().split()
|
|
416
|
+
act = words[0].strip('"\'`.,!?:;()[] ') if words else ''
|
|
417
|
+
if not act or len(act) < 2:
|
|
418
|
+
entry['error'] = f'no usable action in: {raw_text[:80]}'
|
|
419
|
+
_audit_log(entry)
|
|
420
|
+
return None
|
|
421
|
+
suggestion = {
|
|
422
|
+
'act': act,
|
|
423
|
+
'confidence': 0.5,
|
|
424
|
+
'reasoning': raw_text[:200],
|
|
425
|
+
}
|
|
426
|
+
entry['suggestion'] = suggestion
|
|
427
|
+
_audit_log(entry)
|
|
428
|
+
return suggestion
|
|
429
|
+
|
|
430
|
+
# 有动作列表: 逐词匹配 (大小写不敏感)
|
|
431
|
+
words = raw_text.strip().split()
|
|
432
|
+
matched_act = None
|
|
433
|
+
for w in words:
|
|
434
|
+
w_clean = w.strip('"\'`.,!?:;()[] ')
|
|
435
|
+
if not w_clean:
|
|
436
|
+
continue
|
|
437
|
+
if w_clean in actions:
|
|
438
|
+
matched_act = w_clean
|
|
439
|
+
break
|
|
440
|
+
for a in actions:
|
|
441
|
+
if w_clean.lower() == a.lower():
|
|
442
|
+
matched_act = a
|
|
443
|
+
break
|
|
444
|
+
if w_clean.lower() in a.lower() or a.lower() in w_clean.lower():
|
|
445
|
+
matched_act = a
|
|
446
|
+
break
|
|
447
|
+
if matched_act:
|
|
448
|
+
break
|
|
449
|
+
|
|
450
|
+
# fallback: 子串匹配 — 在全文搜索动作名
|
|
451
|
+
if not matched_act:
|
|
452
|
+
for a in actions:
|
|
453
|
+
if a in raw_text:
|
|
454
|
+
matched_act = a
|
|
455
|
+
break
|
|
456
|
+
|
|
457
|
+
# F1 accept 契约 (2026-10-22): 候选必须严格 ∈ actions.
|
|
458
|
+
# 已删旧版"取第一个看起来像动作的词"fallback (越界候选缺口 — 会把
|
|
459
|
+
# 不在 actions 内的词当候选, 违反 vt ∈ A). 无匹配 ⇒ 拒收 None.
|
|
460
|
+
if not matched_act:
|
|
461
|
+
entry['out_of_vocab'] = raw_text[:100]
|
|
462
|
+
entry['error'] = f'no matching action in {actions}'
|
|
463
|
+
_audit_log(entry)
|
|
464
|
+
return None
|
|
465
|
+
act = matched_act
|
|
466
|
+
|
|
467
|
+
# 置信度: 简单映射 — 用 token 数/n_predict 做粗略估计
|
|
468
|
+
n_tokens = result.get('tokens_evaluated', 0) or 0
|
|
469
|
+
confidence = 1.0 - min(1.0, max(0.0, n_tokens / 64.0))
|
|
470
|
+
|
|
471
|
+
suggestion = {
|
|
472
|
+
'act': act,
|
|
473
|
+
'confidence': round(confidence, 3),
|
|
474
|
+
'reasoning': raw_text[:200],
|
|
475
|
+
}
|
|
476
|
+
# F3 候选准入: 经确定性内核准入 (accept + confidence + 来源绑定)
|
|
477
|
+
admitted = admit(suggestion, actions)
|
|
478
|
+
entry['suggestion'] = admitted
|
|
479
|
+
if admitted is None:
|
|
480
|
+
entry['error'] = f'candidate rejected by accept contract: {act}'
|
|
481
|
+
_audit_log(entry)
|
|
482
|
+
return None
|
|
483
|
+
_audit_log(entry)
|
|
484
|
+
return admitted
|
|
485
|
+
|
|
486
|
+
except subprocess.TimeoutExpired:
|
|
487
|
+
entry['error'] = 'timeout'
|
|
488
|
+
_audit_log(entry)
|
|
489
|
+
return None
|
|
490
|
+
except json.JSONDecodeError as e:
|
|
491
|
+
entry['error'] = f'json parse: {e}'
|
|
492
|
+
_audit_log(entry)
|
|
493
|
+
return None
|
|
494
|
+
except Exception as e:
|
|
495
|
+
entry['error'] = f'unexpected: {e}'
|
|
496
|
+
entry['traceback'] = traceback.format_exc()
|
|
497
|
+
_audit_log(entry)
|
|
498
|
+
return None
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
# ── self-test ─────────────────────────────────────────────
|
|
502
|
+
def _self_test():
|
|
503
|
+
"""健康检查 + 一次简单提示测试"""
|
|
504
|
+
health = _health()
|
|
505
|
+
if not health['ok']:
|
|
506
|
+
return {'ok': False,
|
|
507
|
+
'detail': f'llama.cpp unavailable: {health.get("error")}'}
|
|
508
|
+
|
|
509
|
+
# 测试: 3 选 1
|
|
510
|
+
r = suggest('box', 'open', current='closed',
|
|
511
|
+
world_name='test_world',
|
|
512
|
+
actions=['push', 'pull', 'lift'])
|
|
513
|
+
if r and r.get('act') in ('push', 'pull', 'lift'):
|
|
514
|
+
return {'ok': True,
|
|
515
|
+
'detail': f'llm arm ready, suggestion: {r}'}
|
|
516
|
+
return {'ok': False,
|
|
517
|
+
'detail': f'test failed, result={r}'}
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
if __name__ == '__main__':
|
|
521
|
+
import sys
|
|
522
|
+
|
|
523
|
+
if '--health' in sys.argv:
|
|
524
|
+
print(json.dumps(_health(), ensure_ascii=False))
|
|
525
|
+
sys.exit(0)
|
|
526
|
+
|
|
527
|
+
if '--test' in sys.argv:
|
|
528
|
+
result = _self_test()
|
|
529
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
530
|
+
sys.exit(0 if result['ok'] else 1)
|
|
531
|
+
|
|
532
|
+
# 手动: python core/llm_arm.py <obj> <goal> [current] [world] [action1 action2 ...]
|
|
533
|
+
if len(sys.argv) >= 3:
|
|
534
|
+
r = suggest(
|
|
535
|
+
obj=sys.argv[1],
|
|
536
|
+
goal=sys.argv[2],
|
|
537
|
+
current=sys.argv[3] if len(sys.argv) > 3 else None,
|
|
538
|
+
world_name=sys.argv[4] if len(sys.argv) > 4 else '',
|
|
539
|
+
actions=sys.argv[5:] if len(sys.argv) > 5 else None,
|
|
540
|
+
)
|
|
541
|
+
print(json.dumps(r, ensure_ascii=False, indent=2))
|
|
542
|
+
else:
|
|
543
|
+
print("Usage:")
|
|
544
|
+
print(" python core/llm_arm.py --health # 检查 llama.cpp 服务")
|
|
545
|
+
print(" python core/llm_arm.py --test # 全自测")
|
|
546
|
+
print(" python core/llm_arm.py <obj> <goal> [current] [world] [action ...]")
|
|
547
|
+
print("Env:")
|
|
548
|
+
print(" LLM_ARM=1 启用 (默认关)")
|
|
549
|
+
print(" LLM_ARM_HOST 默认 http://localhost:8082")
|
|
550
|
+
print(" LLM_ARM_TIMEOUT 请求超时秒数 (默认 15)")
|
|
551
|
+
print(" LLM_ARM_AUDIT_DIR 审计日志目录")
|