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

68 lines
2.2 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
上下文使用量检测脚本
当任一 session 上下文使用量 >= 90% 时自动保存记忆
"""
import subprocess
import re
import os
from datetime import datetime
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. 文件记忆已保存(向量记忆统一走 main.sqlite
log("✅ 文件记忆已更新")
log("✅ 记忆保存完成")
else:
log(f"✅ 上下文使用量正常 ({max_usage}%),无需保存")
log("========== 检测完成 ==========\n")
if __name__ == "__main__":
main()