File size: 12,782 Bytes
fdd71c3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | """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()
|