benzeng's picture
Add research code (pipelines, serve.py, agent.py) and docs
fdd71c3 verified
Raw History Blame Contribute Delete
12.8 kB
"""agent.py — 极简工具调用 Agent,用于测试小模型(MiniCPM5-2B 等)的 function calling
为什么需要它:Claude Code / ZCode 这类 agent 的系统提示动辄上万 token,
超过本地小模型的上下文包线(本机 6GB 卡:bf16 ~3K / fp16 ~8K token)。
本 agent 的固定开销控制在 ~150 token 以内。
用法:
.venv/bin/python agent.py # 交互式终端界面(REPL)
.venv/bin/python agent.py "创建 /tmp/agent_test.txt 写入 hello,然后读回确认" # 单轮模式
.venv/bin/python agent.py --url http://127.0.0.1:8000/v1 --thinking off "列出当前目录文件"
交互界面命令:
/quit /exit 退出
/reset 清空会话历史
/yes 切换 shell 命令逐条确认开关
/ablate off|on [k] 本次会话的请求级消融开关与子空间维度(默认跟随服务端)
/tokens 显示当前会话估计 token 数
/help 帮助
选项:
--url serve.py 的 OpenAI 端点(默认 http://127.0.0.1:8000/v1)
--max-steps 最大工具调用轮数(默认 10)
--budget 对话 token 预算(默认 6000;超限自动把最老的工具输出替换为占位符)
--out-chars 单次工具输出截断长度(默认 1000 字符)
--thinking on/off 思维链开关(默认 off,省 token)
--yes 执行 shell 命令前不询问(默认逐条询问)
"""
import argparse
import json
import os
import subprocess
import sys
import urllib.request
SYSTEM = "你是命令行助手。通过调用工具完成任务。工具结果给你后,继续调用工具或给出简短最终答复。"
TOOLS = [
{"type": "function", "function": {
"name": "run_shell",
"description": "执行 shell 命令并返回输出",
"parameters": {"type": "object",
"properties": {"command": {"type": "string", "description": "shell 命令"}},
"required": ["command"]}}},
{"type": "function", "function": {
"name": "read_file",
"description": "读取文本文件",
"parameters": {"type": "object",
"properties": {"path": {"type": "string", "description": "文件路径"},
"offset": {"type": "integer", "description": "起始行号(从1起)"},
"limit": {"type": "integer", "description": "最多读取行数"}},
"required": ["path"]}}},
{"type": "function", "function": {
"name": "write_file",
"description": "写入文本文件(覆盖)",
"parameters": {"type": "object",
"properties": {"path": {"type": "string", "description": "文件路径"},
"content": {"type": "string", "description": "文件内容"}},
"required": ["path", "content"]}}},
]
# ---------- 工具执行 ----------
def run_shell(command, assume_yes):
if not assume_yes:
ans = input(f"\033[33m执行命令?\033[0m {command}\n[y/N] ").strip().lower()
if ans != "y":
return "用户拒绝了该命令"
try:
r = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=60)
out = (r.stdout + r.stderr).strip()
return out or f"(退出码 {r.returncode},无输出)"
except subprocess.TimeoutExpired:
return "(命令超时 60s)"
def read_file(path, offset=None, limit=None):
try:
with open(path, errors="replace") as f:
lines = f.readlines()
start = max(0, (offset or 1) - 1)
sel = lines[start: start + (limit or 200)]
return "".join(sel) or "(空文件)"
except Exception as e:
return f"(读取失败: {e})"
def write_file(path, content):
try:
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, "w") as f:
f.write(content)
return f"(已写入 {len(content)} 字符)"
except Exception as e:
return f"(写入失败: {e})"
def execute(call, assume_yes):
fn = call["function"]
try:
args = json.loads(fn["arguments"] or "{}")
except json.JSONDecodeError:
return f"(参数 JSON 解析失败: {fn['arguments'][:100]!r})"
if fn["name"] == "run_shell":
return run_shell(args.get("command", ""), assume_yes)
if fn["name"] == "read_file":
return read_file(args.get("path", ""), args.get("offset"), args.get("limit"))
if fn["name"] == "write_file":
return write_file(args.get("path", ""), args.get("content", ""))
return f"(未知工具: {fn['name']})"
# ---------- 客户端 ----------
def chat(url, messages, max_tokens, thinking, ablate=None, ablate_k=None):
body = {"messages": messages, "tools": TOOLS, "max_tokens": max_tokens,
"enable_thinking": thinking}
if ablate is not None:
body["ablate_refusal"] = ablate
if ablate_k is not None:
body["ablate_k"] = ablate_k
req = urllib.request.Request(f"{url}/chat/completions", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=600) as r:
resp = json.load(r)
return resp["choices"][0]["message"], resp["choices"][0]["finish_reason"]
def estimate_tokens(messages):
"""粗略估计:中英文混合按 2 字符/token 偏保守"""
return sum(len(json.dumps(m, ensure_ascii=False)) for m in messages) // 2
def shrink(messages, budget):
"""超预算时把最老的 tool 输出替换为占位符(保留系统提示与最近上下文)"""
for m in messages:
if estimate_tokens(messages) <= budget:
break
if m["role"] == "tool" and m["content"] != "[历史输出已省略]":
m["content"] = "[历史输出已省略]"
def run_task(messages, task, args, ablate=None, ablate_k=None, ui=None):
"""执行一个任务的多轮工具循环。ui 非 None 时用 rich 渲染,否则纯文本。
返回 True=完成,False=达到轮数上限/出错。"""
messages.append({"role": "user", "content": task})
for step in range(1, args.max_steps + 1):
shrink(messages, args.budget)
try:
if ui is not None:
with ui.status("[dim]思考中…[/]", spinner="dots"):
msg, finish = chat(args.url, messages, args.max_tokens,
args.thinking == "on", ablate, ablate_k)
else:
msg, finish = chat(args.url, messages, args.max_tokens,
args.thinking == "on", ablate, ablate_k)
except urllib.error.HTTPError as e:
print(f"[HTTP {e.code}] {e.read().decode()[:200]}")
return False
tool_calls = msg.get("tool_calls") or []
if finish != "tool_calls" or not tool_calls:
content = msg.get("content") or "(空)"
if ui is not None:
from rich.markdown import Markdown
from rich.panel import Panel
ui.print(Panel(Markdown(content), title=f"[green]助手[/](第 {step} 轮)",
border_style="green"))
else:
print(f"\n=== 最终答复(第 {step} 轮)===\n{content}")
return True
messages.append({"role": "assistant", "content": msg.get("content") or "",
"tool_calls": tool_calls})
for call in tool_calls:
fn = call["function"]
if ui is not None:
ui.print(f"[cyan]🔧 step {step}[/] [bold]{fn['name']}[/]"
f"[dim]({fn['arguments'][:120]})[/]")
else:
print(f"[step {step}] {fn['name']}({fn['arguments'][:120]})")
out = execute(call, args.yes)
if len(out) > args.out_chars:
out = out[:args.out_chars] + f"... [截断,共 {len(out)} 字符]"
if ui is not None:
ui.print(f" [dim]→ {out[:150]!r}[/]")
else:
print(f" → {out[:150]!r}")
messages.append({"role": "tool", "content": out})
print(f"\n达到最大轮数 {args.max_steps},任务未完成。")
return False
HELP_TEXT = """\
[bold]命令[/]:
/quit, /exit 退出
/reset 清空会话历史(保留系统提示)
/yes 切换 shell 命令逐条确认开关
/ablate off 本会话关闭消融
/ablate on [k] 本会话开启消融,可选子空间维度 k(1–32)
/ablate 跟随服务端默认
/tokens 显示当前会话估计 token 数
/help 本帮助
直接输入任务文本即可开始多轮工具调用。"""
def interactive(args):
from rich.console import Console
from rich.panel import Panel
con = Console()
health_txt = ""
try:
hurl = args.url.rstrip("/")
hurl = hurl[:-3] + "/health" if hurl.endswith("/v1") else hurl + "/health"
with urllib.request.urlopen(hurl, timeout=5) as r:
h = json.load(r)
health_txt = (f"模型 [bold]{h.get('model')}[/]({h.get('device')})"
f"|服务端消融默认: {'开' if h.get('ablate_default') else '关'}")
except Exception as e:
con.print(f"[red]无法连接 {args.url}: {e}[/]")
sys.exit(1)
con.print(Panel(f"[bold]MiniAgent[/] — 极简小模型工具调用测试台\n{health_txt}\n"
f"token 预算 {args.budget}|思维链 {args.thinking}|输入 /help 查看命令",
border_style="cyan"))
messages = [{"role": "system", "content": SYSTEM}]
ablate, ablate_k = None, None # None = 跟随服务端默认
assume_yes = args.yes
while True:
try:
line = con.input("[bold magenta]任务 ›[/] ").strip()
except (EOFError, KeyboardInterrupt):
con.print("\n再见。")
return
if not line:
continue
if line.startswith("/"):
parts = line.split()
cmd = parts[0].lower()
if cmd in ("/quit", "/exit"):
con.print("再见。")
return
elif cmd == "/reset":
messages[:] = messages[:1]
con.print("[dim]会话已清空。[/]")
elif cmd == "/yes":
assume_yes = not assume_yes
args.yes = assume_yes
con.print(f"[dim]shell 逐条确认: {'关(自动执行)' if assume_yes else '开'}[/]")
elif cmd == "/ablate":
if len(parts) == 1 or parts[1] == "auto":
ablate, ablate_k = None, None
con.print("[dim]消融: 跟随服务端默认[/]")
elif parts[1] == "off":
ablate, ablate_k = False, None
con.print("[dim]消融: 本会话关闭[/]")
elif parts[1] == "on":
ablate = True
if len(parts) > 2 and parts[2].isdigit():
ablate_k = max(1, min(32, int(parts[2])))
con.print(f"[dim]消融: 本会话开启,k={ablate_k or '服务端默认'}[/]")
else:
con.print("[red]用法: /ablate [off|on [k]|auto][/]")
elif cmd == "/tokens":
con.print(f"[dim]会话估计 {estimate_tokens(messages)} token(预算 {args.budget})[/]")
elif cmd == "/help":
con.print(HELP_TEXT)
else:
con.print(f"[red]未知命令 {cmd},输入 /help[/]")
continue
run_task(messages, line, args, ablate=ablate, ablate_k=ablate_k, ui=con)
def main():
p = argparse.ArgumentParser()
p.add_argument("task", nargs="?", help="任务(省略则进入交互式终端界面)")
p.add_argument("--url", default="http://127.0.0.1:8000/v1")
p.add_argument("--max-steps", type=int, default=10)
p.add_argument("--budget", type=int, default=6000)
p.add_argument("--out-chars", type=int, default=1000)
p.add_argument("--max-tokens", type=int, default=512)
p.add_argument("--thinking", choices=["on", "off"], default="off")
p.add_argument("--yes", action="store_true", help="shell 命令不再逐条确认")
args = p.parse_args()
if args.task is None:
interactive(args)
return
messages = [{"role": "system", "content": SYSTEM}]
ok = run_task(messages, args.task, args)
sys.exit(0 if ok else 2)
if __name__ == "__main__":
main()