openclaw-home-pc/workspace/scripts/context_memory_guard.py

77 lines
2.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""
上下文使用量检测脚本
当任一 session 上下文使用量 >= 90% 时自动保存记忆
"""
import subprocess
import re
import os
from datetime import datetime
# 加载环境变量
os.environ["SILICONFLOW_API_KEY"] = "sk-fpjdtxbxrhtekshircjhegstloxaodriekotjdyzzktyegcl"
def log(msg):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] {msg}")
def main():
log("========== 上下文使用量检测 ==========")
# 获取 OpenClaw 状态
result = subprocess.run(["openclaw", "status"], capture_output=True, text=True)
status_output = result.stdout
# 提取所有上下文使用量百分比
# 格式: "109k/200k (54%)" - 括号内是使用量
max_usage = 0
for line in status_output.split('\n'):
# 跳过表头和无关行
if '│ Tokens' in line or '' in line or '│ Key' in line:
continue
if 'FAQ:' in line or 'Troubleshooting:' in line:
continue
if 'Sessions' in line and '200k ctx' in line:
continue
# 查找类似 "109k/200k (54%)" 的模式
match = re.search(r'(\d+)k/200k \((\d+)%\)', line)
if match:
usage = int(match.group(2))
if usage > max_usage:
max_usage = usage
log(f"📊 当前最高上下文使用量: {max_usage}%")
if max_usage >= 90:
log(f"⚠️ 上下文使用量达到 {max_usage}%,开始保存记忆...")
# 1. 保存文件记忆
memory_file = f"{os.path.expanduser('~')}/.openclaw/workspace/memory/{datetime.now().strftime('%Y-%m-%d')}.md"
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(memory_file, "a") as f:
f.write(f"\n## 🔄 上下文自动保存 ({timestamp})\n\n")
f.write(f"**触发原因**: 上下文使用量达到 {max_usage}%\n\n")
log("✅ 文件记忆已更新")
# 2. 保存向量记忆
os.chdir(os.path.expanduser("~/openclaw-memory-vector"))
subprocess.run([
"python3", "memory_cli.py", "add",
f"【自动保存】上下文使用量达到 {max_usage}%,系统自动保存记忆。时间: {timestamp}",
"--tag", "auto-save,context-90"
], capture_output=True, text=True)
log("✅ 向量记忆已保存")
log("✅ 记忆保存完成")
else:
log(f"✅ 上下文使用量正常 ({max_usage}%),无需保存")
log("========== 检测完成 ==========\n")
if __name__ == "__main__":
main()