Files
memoryweave/scripts/tools/zhiyi-standing-answers.py
T

127 lines
4.8 KiB
Python
Raw 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
# 织忆常设答案生成器(Hindsight mental models / knowledge pages)。
# 2026-10-13 t_e9a4d18f P2:读注册表 → 为每个问题召回相关记忆 → 用本地 2B
# (llama 队列代理 8081,免费)综合出答案 → 写入 /api/v1/standing-answers(version+1)。
#
# 用法:
# zhiyi-standing-answers.py 按注册表生成全部(改写)
# zhiyi-standing-answers.py --dry 干跑(只打印将写入的答案,不 POST)
# zhiyi-standing-answers.py --one <id> 只处理某一个问题
#
# 环境变量:
# ZHIYI_URL 织忆地址(默认 http://127.0.0.1:7821)
# ZHIYI_API_KEY 织忆 API key(默认 zhiyi-dev-key-2026,与插件默认一致)
# LLM_ENDPOINT 本地 2B 地址(默认 http://127.0.0.1:8081/v1/chat/completions)
# LLM_MODEL (默认 local/minicpm5-2b)
import argparse
import json
import os
import sys
import urllib.request
ZHIYI_URL = os.getenv("ZHIYI_URL", "http://127.0.0.1:7821")
ZHIYI_API_KEY = os.getenv("ZHIYI_API_KEY", "zhiyi-dev-key-2026")
LLM_ENDPOINT = os.getenv("LLM_ENDPOINT", "http://127.0.0.1:8081/v1/chat/completions")
LLM_MODEL = os.getenv("LLM_MODEL", "local/minicpm5-2b")
REGISTRY = os.path.expanduser("~/.hermes/config/zhiyi-standing-questions.yaml")
def _headers():
return {"Content-Type": "application/json", "X-API-Key": ZHIYI_API_KEY}
def load_registry():
try:
import yaml
except ImportError:
sys.exit("需要 pyyaml: pip install pyyaml")
with open(REGISTRY) as f:
data = yaml.safe_load(f)
return data.get("questions", [])
def recall(q, namespace, top_k):
"""从织忆召回相关记忆,返回 (content 列表, memory_id 列表)。"""
body = json.dumps({"query": q, "top_k": top_k, "namespace": namespace}).encode()
req = urllib.request.Request(
ZHIYI_URL + "/api/v1/recall", data=body, headers=_headers())
try:
with urllib.request.urlopen(req, timeout=20) as r:
data = json.loads(r.read())
except Exception as e:
return [], ["recall_err:" + str(e)]
results = data.get("results", []) or []
contents = [x.get("content", "") for x in results]
ids = [x.get("id", "") for x in results]
return contents, ids
def llm_summarize(question, contents):
"""用本地 2B 把召回的候选记忆综合成一条常设答案。"""
excerpt = "\n".join("- " + c[:300] for c in contents if c)
prompt = (
"你是记忆整理助手。下面是根据问题召回的候选记忆。请把它们综合成一条"
"精炼、确定的常设答案(可直接长期保存的知识页),不要重复记忆原文、"
"不要带分析过程、不要出现\"候选记忆\"这类字样。\n\n"
f"问题:{question}\n\n候选记忆:\n{excerpt}\n\n"
"常设答案:")
body = json.dumps({
"model": LLM_MODEL,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 400,
"temperature": 0.2,
}).encode()
req = urllib.request.Request(LLM_ENDPOINT, data=body, headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=120) as r:
data = json.loads(r.read())
return data["choices"][0]["message"]["content"].strip()
except Exception as e:
return "[生成失败: %s]" % e
def write_answer(q, dry):
c, ids = recall(q["question"], q["namespace"], q.get("top_k", 8))
if not c:
print(" ⚠ 无召回,跳过 %s" % q["id"])
return
ans = llm_summarize(q["question"], c)
print(" ✎ %s → %d 条证据 (%s)" % (q["id"], len(ids), "recall" if ids else "err"))
if dry:
print(" [dry] 答案(前80): %s" % ans[:80].replace("\n", " "))
return
body = json.dumps({
"question_id": q["id"],
"question": q["question"],
"answer": ans,
"source_memories": ids,
}).encode()
req = urllib.request.Request(
ZHIYI_URL + "/api/v1/standing-answers", data=body,
headers=_headers(), method="POST")
try:
with urllib.request.urlopen(req, timeout=20) as r:
out = json.loads(r.read())
print(" ✓ version=%d" % out.get("version", "?"))
except Exception as e:
print(" ✗ POST 失败: %s" % e)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dry", action="store_true", help="干跑,不 POST")
ap.add_argument("--one", help="只处理某个 question id")
args = ap.parse_args()
qs = load_registry()
if args.one:
qs = [q for q in qs if q["id"] == args.one]
if not qs:
sys.exit("注册表为空或无匹配 id: %s" % REGISTRY)
print("常设答案生成器,共 %d 个问题" % len(qs))
for q in qs:
write_answer(q, args.dry)
if __name__ == "__main__":
main()