Files
memoryweave/cli-anything/cli_anything/zhiyi/zhiyi_cli.py
T
xiaowei 2a350cf781 fix(distill): max_tokens 800→1200 — Agnes推理token预算不足
Agnes 2.0-flash是推理模型,推理token占大量预算。
800仍不够→JSON截断(parse error: unexpected end of JSON input)。
1200确保推理+正文都够用。
2026-08-20 01:13:06 +08:00

460 lines
15 KiB
Python

#!/usr/bin/env python3
"""cli-anything-zhiyi — Agent-native CLI for ZhiYi MemoryWeave.
Usage:
# One-shot
cli-anything-zhiyi health
cli-anything-zhiyi search "小唯" --top-k 5 --mode hybrid
cli-anything-zhiyi stats
cli-anything-zhiyi graph navigate "织忆" --hops 2
# Interactive REPL (default)
cli-anything-zhiyi repl
cli-anything-zhiyi # same as repl
"""
import json
import sys
import os
import shlex
import shutil
import subprocess
from pathlib import Path
import click
from cli_anything.zhiyi.core.client import ZhiYiClient
# ---- Globals ----
_json_output = False
_client: ZhiYiClient | None = None
def get_client() -> ZhiYiClient:
global _client
if _client is None:
base = os.environ.get("ZHIYI_API_BASE")
key = os.environ.get("ZHIYI_API_KEY")
_client = ZhiYiClient(base=base, api_key=key)
return _client
def output(data, message: str = ""):
if _json_output:
click.echo(json.dumps(data, indent=2, ensure_ascii=False, default=str))
else:
if message:
click.echo(message)
if isinstance(data, dict):
for k, v in data.items():
if isinstance(v, (dict, list)):
click.echo(f" {k}: {json.dumps(v, ensure_ascii=False, default=str)}")
else:
click.echo(f" {k}: {v}")
elif isinstance(data, list):
for item in data:
click.echo(f" • {str(item)[:200]}")
else:
click.echo(str(data))
# ---- Shared options ----
_common = [
click.option("--json", "json_flag", is_flag=True, help="Machine-readable JSON output"),
]
def common_options(f):
for opt in reversed(_common):
f = opt(f)
return f
# ---- CLI group ----
@click.group(invoke_without_command=True)
@click.pass_context
@common_options
def cli(ctx, json_flag):
"""ZhiYi MemoryWeave — Agent-native memory system CLI."""
global _json_output
_json_output = json_flag
if ctx.invoked_subcommand is None:
ctx.invoke(repl)
# ---- health ----
@cli.command()
@common_options
def health(json_flag):
"""Check system health (zhiyid, bge-embed, IPC sidecar, graph DB)."""
global _json_output
_json_output = json_flag
result = get_client().diagnose()
if _json_output:
click.echo(json.dumps(result, indent=2, ensure_ascii=False))
return
click.echo("═══ 织忆系统诊断 ═══")
for component, info in result.items():
if component == "overall":
continue
status = info.get("status", "?")
icon = {"ok": "✅", "warn": "⚠️", "fail": "❌"}.get(status, "❓")
click.echo(f" {icon} {component}: {status}")
overall = result.get("overall", "?")
icon = {"ok": "✅", "degraded": "⚠️", "fail": "❌"}.get(overall, "❓")
click.echo(f"\n {icon} 整体状态: {overall}")
# ---- search ----
@cli.command()
@click.argument("query")
@click.option("--top-k", default=5, type=int, help="Number of results (default: 5)")
@click.option("--mode", default="hybrid",
type=click.Choice(["hybrid", "semantic", "keyword"]),
help="Search mode (default: hybrid)")
@click.option("--diversity", default=0.3, type=float, help="MMR diversity (0-1, default: 0.3)")
@common_options
def search(query, top_k, mode, diversity, json_flag):
"""Search memories by query."""
global _json_output
_json_output = json_flag
result = get_client().search(query, top_k=top_k, mode=mode, diversity=diversity)
if _json_output:
click.echo(json.dumps(result, indent=2, ensure_ascii=False, default=str))
return
results = result.get("results", result.get("memories", []))
click.echo(f"🔍 搜索 \"{query}\" [{mode}, top_{top_k}, diversity={diversity}]")
click.echo(f" 找到 {len(results)} 条结果\n")
for i, r in enumerate(results, 1):
content = r.get("content", "")
score = r.get("score", 0)
mid = r.get("id", r.get("memory_id", ""))
# Truncate content for display
display = str(content)[:200].replace("\n", " ")
click.echo(f" [{i}] (score={score:.3f}) {display}")
click.echo(f" id: {mid}")
click.echo()
# ---- stats ----
@cli.command()
@click.option("--type", "stat_type", default="all",
type=click.Choice(["all", "memories", "graph", "cache", "metrics"]),
help="Stat category (default: all)")
@common_options
def stats(stat_type, json_flag):
"""Show memory/graph/cache/metrics statistics."""
global _json_output
_json_output = json_flag
c = get_client()
data = {}
if stat_type in ("all", "memories"):
data["memories"] = c.stats()
if stat_type in ("all", "graph"):
data["graph"] = c.graph_stats()
if stat_type in ("all", "cache"):
data["cache"] = c.cache_stats()
if stat_type in ("all", "metrics"):
data["metrics"] = c.metrics()
if _json_output:
click.echo(json.dumps(data, indent=2, ensure_ascii=False, default=str))
return
click.echo("═══ 织忆统计 ═══")
if "memories" in data:
s = data["memories"]
click.echo(f"\n📦 记忆后端: {s.get('backend', '?')}")
click.echo(f" 记忆: {s.get('total_memories', '?')} 条")
click.echo(f" 片段: {s.get('total_episodes', '?')} 条")
click.echo(f" 数据目录: {s.get('data_dir', '?')}")
if "graph" in data:
g = data["graph"]
click.echo(f"\n🕸️ 图谱: {g.get('node_count', '?')} 节点 / {g.get('edge_count', '?')} 边")
click.echo(f" 密度: {g.get('density', '?'):.6f}")
if "cache" in data:
ca = data["cache"].get("graph_cache", {})
click.echo(f"\n⚡ 缓存: {ca.get('size', '?')}/{ca.get('max_size', '?')} | "
f"命中: {ca.get('total_hits', '?')} 次 | TTL: {ca.get('ttl', '?')}")
if "metrics" in data:
m = data["metrics"]
click.echo(f"\n📊 自优化指标:")
click.echo(f" 召回命中率: {m.get('recall_hit_rate', '?'):.1%}")
click.echo(f" 召回有用率: {m.get('recall_usefulness_rate', '?'):.1%}")
click.echo(f" 记忆总数: {m.get('total_memories', '?')}")
# ---- graph ----
@cli.group()
def graph():
"""Graph operations."""
pass
@graph.command("navigate")
@click.option("--entity", "-e", required=True, help="Entity to navigate from")
@click.option("--hops", "-n", default=2, type=int, help="Max hops (default: 2)")
@common_options
def graph_navigate(entity, hops, json_flag):
"""Navigate the knowledge graph from an entity."""
global _json_output
_json_output = json_flag
result = get_client().graph_navigate(entity, max_hops=hops)
if _json_output:
click.echo(json.dumps(result, indent=2, ensure_ascii=False, default=str))
return
click.echo(f"🕸️ 从 \"{entity}\" 出发,{hops} 跳")
paths = result.get("paths", [])
relation_count = result.get("relation_count", 0)
suggestions = result.get("suggestions", [])
click.echo(f" 找到 {len(paths)} 条路径, {relation_count} 种关系\n")
# Group by relation
grouped = result.get("grouped_by_relation", {})
if grouped:
for rel, edges in grouped.items():
click.echo(f" [{rel}]")
for e in edges[:10]:
click.echo(f" {e.get('from', '?')} → {e.get('to', '?')} (w={e.get('weight', 0):.3f})")
click.echo()
if suggestions:
click.echo(f"💡 建议继续探索:")
for s in suggestions[:10]:
click.echo(f" • {s}")
@graph.command("stats")
@common_options
def graph_stats_cmd(json_flag):
"""Show graph statistics."""
global _json_output
_json_output = json_flag
result = get_client().graph_stats()
output(result)
@graph.command("cleanup")
@common_options
def graph_cleanup(json_flag):
"""Clean up stale graph edges."""
global _json_output
_json_output = json_flag
result = get_client().graph_cleanup()
output(result)
# ---- feedback ----
@cli.command()
@click.option("--id", "memory_id", required=True, help="Memory ID to provide feedback on")
@click.option("--useful/--not-useful", default=True, help="Whether this memory was useful")
@click.option("--reason", default="", help="Optional reason (only for not-useful)")
@common_options
def feedback(memory_id, useful, reason, json_flag):
"""Provide feedback on a memory."""
global _json_output
_json_output = json_flag
result = get_client().feedback(memory_id, useful=useful, reason=reason)
output(result, f"反馈已发送: {'✅ 有用' if useful else '❌ 无用'} → {memory_id}")
# ---- repl ----
@cli.command()
@common_options
def repl(json_flag):
"""Interactive REPL mode."""
global _json_output
_json_output = json_flag
c = get_client()
# Try to use ReplSkin if available, fall back to simple REPL
try:
from cli_anything.zhiyi.utils.repl_skin import ReplSkin
skin = ReplSkin("zhiyi", version="0.1.0")
skin.print_banner()
_repl_with_skin(c, skin)
except ImportError:
_repl_simple(c)
def _repl_simple(c: ZhiYiClient):
"""Simple REPL fallback."""
click.echo("ZhiYi REPL — 输入 ? 查看帮助, quit 退出")
while True:
try:
line = click.prompt("zhiyi", prompt_suffix="> ").strip()
except (EOFError, KeyboardInterrupt):
click.echo("\n再见 👋")
break
if not line:
continue
if line in ("quit", "exit", "q"):
click.echo("再见 👋")
break
if line in ("?", "help"):
click.echo("""
可用命令:
health — 系统诊断
search <query> — 搜索记忆
stats — 查看统计
graph navigate <entity> — 图谱导航
feedback <id> <0|1> — 记忆反馈
? / help — 帮助
quit / exit — 退出
""")
continue
parts = shlex.split(line)
cmd = parts[0]
args = parts[1:]
try:
if cmd == "health":
r = c.diagnose()
click.echo(json.dumps(r, indent=2, ensure_ascii=False))
elif cmd == "search":
query = " ".join(args) if args else click.prompt("query")
r = c.search(query)
for res in r.get("results", r.get("memories", [])):
click.echo(f" [{res.get('score', 0):.3f}] {str(res.get('content',''))[:150]}")
elif cmd == "stats":
click.echo(json.dumps(c.stats(), indent=2, ensure_ascii=False))
click.echo(json.dumps(c.graph_stats(), indent=2, ensure_ascii=False))
elif cmd == "graph" and args and args[0] == "navigate":
entity = args[1] if len(args) > 1 else click.prompt("entity")
r = c.graph_navigate(entity)
click.echo(json.dumps(r, indent=2, ensure_ascii=False)[:1000])
elif cmd == "feedback" and len(args) >= 2:
mid = args[0]
useful = args[1].lower() in ("1", "true", "yes", "y")
r = c.feedback(mid, useful=useful)
click.echo(f"反馈结果: {r}")
else:
click.echo(f"未知命令: {cmd} (输入 ? 查看帮助)")
except Exception as e:
click.echo(f"错误: {e}")
def _repl_with_skin(c: ZhiYiClient, skin):
"""REPL with ReplSkin (prompt_toolkit)."""
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
import atexit
hist_path = os.path.expanduser("~/.zhiyi_history")
session = PromptSession(history=FileHistory(hist_path))
commands = {
"health": "系统诊断",
"search": "搜索记忆",
"stats": "查看统计",
"graph": "图谱操作 (navigate, stats, cleanup)",
"feedback": "记忆反馈",
}
skin.help(commands)
while True:
try:
line = skin.get_input(session)
except (EOFError, KeyboardInterrupt):
break
except Exception:
break
if not line:
continue
line = line.strip()
if line in ("quit", "exit", "q"):
break
if line in ("?", "help"):
skin.help(commands)
continue
parts = shlex.split(line)
cmd = parts[0]
args = parts[1:]
try:
if cmd == "health":
r = c.diagnose()
for comp, info in r.items():
if comp == "overall":
continue
icon = {"ok": "✅", "warn": "⚠️", "fail": "❌"}.get(info.get("status", ""), "❓")
skin.info(f"{icon} {comp}")
elif cmd == "search":
query = " ".join(args) if args else click.prompt("query")
r = c.search(query)
results = r.get("results", r.get("memories", []))
for res in results[:5]:
score = res.get("score", 0)
content = str(res.get("content", ""))[:200].replace("\n", " ")
skin.status(f"[{score:.3f}]", content)
elif cmd == "stats":
s = c.stats()
g = c.graph_stats()
m = c.metrics()
skin.table(
["指标", "值"],
[
["记忆数", str(s.get("total_memories", "?"))],
["图谱节点", str(g.get("node_count", "?"))],
["图谱边", str(g.get("edge_count", "?"))],
["召回命中率", f"{m.get('recall_hit_rate', '?'):.1%}"],
],
)
elif cmd == "graph" and args and args[0] == "navigate":
entity = args[1] if len(args) > 1 else click.prompt("entity")
r = c.graph_navigate(entity)
paths = r.get("paths", [])
skin.info(f"找到 {len(paths)} 条路径")
for p in paths[:5]:
skin.status("→", f"{p.get('from', '?')} → {p.get('to', '?')} ({p.get('relation', '?')})")
elif cmd == "feedback" and len(args) >= 2:
mid = args[0]
useful = args[1].lower() in ("1", "true", "yes", "y")
c.feedback(mid, useful=useful)
skin.success("反馈已发送")
else:
skin.warning(f"未知命令: {cmd}")
except Exception as e:
skin.error(str(e))
skin.print_goodbye()
# ---- Main ----
if __name__ == "__main__":
cli()