"""Minimal tool-use harness (OpenAI-compatible) that gives a model eyes/hands on this PC. Why: QwenWork's own desktop CLI pins its provider to DashScope and its tool schema is ACP-only, so the portable way to run any OpenAI-compatible model (including our qwenwork shim) with real local tools is this loop. Tools exposed to the model: fs_read, fs_write, fs_list, fs_grep, shell. Usage: python qw_agent.py --prompt "count lines in C:/path/file.md" python qw_agent.py --base http://127.0.0.1:48981/v1 --model qw-flash --prompt "..." # qwenwork pool python qw_agent.py --interactive """ import argparse import json import os import re import subprocess import sys import urllib.error import urllib.request TOOLS = [ {"type": "function", "function": { "name": "fs_read", "description": "Read a UTF-8 text file from the local filesystem.", "parameters": {"type": "object", "properties": { "path": {"type": "string", "description": "Absolute path, e.g. C:/Users/User/notes.md"}, "offset": {"type": "integer", "description": "1-based first line (default 1)"}, "limit": {"type": "integer", "description": "max lines (default 400)"}}, "required": ["path"]}}}, {"type": "function", "function": { "name": "fs_write", "description": "Overwrite a text file with the given content.", "parameters": {"type": "object", "properties": { "path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}}, {"type": "function", "function": { "name": "fs_list", "description": "List a directory (names + sizes).", "parameters": {"type": "object", "properties": { "path": {"type": "string"}}, "required": ["path"]}}}, {"type": "function", "function": { "name": "fs_grep", "description": "Regex search inside files of a directory tree.", "parameters": {"type": "object", "properties": { "path": {"type": "string"}, "pattern": {"type": "string"}, "glob": {"type": "string", "description": "optional, e.g. *.py"}, "max_hits": {"type": "integer"}}, "required": ["path", "pattern"]}}}, {"type": "function", "function": { "name": "shell", "description": "Run a shell command (bash on this host) and return stdout/stderr.", "parameters": {"type": "object", "properties": { "command": {"type": "string"}, "cwd": {"type": "string"}, "timeout": {"type": "integer"}}, "required": ["command"]}}}, ] SYSTEM = ("You are a local PC agent. You can inspect and modify this Windows machine through the tools. " "Paths use forward slashes (C:/Users/User/...). Use tools instead of guessing; report what you " "actually observed.") def fs_read(path, offset=1, limit=400): with open(path, encoding="utf-8", errors="replace") as f: lines = f.readlines() chunk = lines[offset - 1: offset - 1 + limit] return {"path": path, "total_lines": len(lines), "offset": offset, "content": "".join(chunk)[:60000]} def fs_write(path, content): os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(content) return {"path": path, "bytes": len(content.encode())} def fs_list(path): out = [] for name in sorted(os.listdir(path))[:400]: p = os.path.join(path, name) try: out.append({"name": name, "dir": os.path.isdir(p), "size": os.path.getsize(p)}) except OSError: out.append({"name": name, "dir": os.path.isdir(p)}) return {"path": path, "entries": out} def fs_grep(path, pattern, glob=None, max_hits=40): rx = re.compile(pattern) hits = [] for root, dirs, files in os.walk(path): dirs[:] = [d for d in dirs if d not in (".git", "__pycache__", "node_modules", ".venv", "venv")] for fn in files: if glob and not fn.endswith(glob.replace("*", "")): continue p = os.path.join(root, fn) try: if os.path.getsize(p) > 3_000_000: continue with open(p, encoding="utf-8", errors="replace") as f: for i, line in enumerate(f, 1): if rx.search(line): hits.append({"file": p, "line": i, "text": line.rstrip()[:300]}) if len(hits) >= max_hits: return {"hits": hits, "truncated": True} except OSError: continue return {"hits": hits, "truncated": False} def shell(command, cwd=None, timeout=120): try: p = subprocess.run(command, shell=True, cwd=cwd, capture_output=True, text=True, timeout=timeout, encoding="utf-8", errors="replace") return {"exit": p.returncode, "stdout": (p.stdout or "")[-20000:], "stderr": (p.stderr or "")[-4000:]} except subprocess.TimeoutExpired: return {"exit": -1, "stdout": "", "stderr": "timeout"} DISPATCH = {"fs_read": fs_read, "fs_write": fs_write, "fs_list": fs_list, "fs_grep": fs_grep, "shell": shell} def call_tool(name, args): fn = DISPATCH.get(name) if not fn: return {"error": "unknown tool %s" % name} try: return fn(**args) except Exception as e: return {"error": "%s: %s" % (type(e).__name__, e)} def chat(base, model, api_key, messages, tools=True, timeout=180): body = {"model": model, "messages": messages, "temperature": 0} if tools: body["tools"] = TOOLS body["tool_choice"] = "auto" req = urllib.request.Request(base.rstrip("/") + "/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "Authorization": "Bearer " + (api_key or "sk-local")}) try: with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode()) except urllib.error.HTTPError as e: raise SystemExit("[http %s] %s" % (e.code, e.read().decode("utf-8", "replace")[:400])) def run(base, model, api_key, prompt, max_turns=12, verbose=True): messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}] trace = [] for turn in range(max_turns): resp = chat(base, model, api_key, messages) msg = (resp.get("choices") or [{}])[0].get("message") or {} calls = msg.get("tool_calls") or [] if verbose: if msg.get("content"): print("\n[assistant]", (msg["content"] or "").strip()[:1500]) for c in calls: print("[tool]", c["function"]["name"], c["function"]["arguments"][:200]) messages.append({"role": "assistant", "content": msg.get("content") or "", "tool_calls": calls or None} if calls else {"role": "assistant", "content": msg.get("content") or ""}) if not calls: return {"answer": (msg.get("content") or "").strip(), "turns": turn + 1, "trace": trace} for c in calls: name = c["function"]["name"] try: args = json.loads(c["function"].get("arguments") or "{}") except Exception: args = {} result = call_tool(name, args) trace.append({"tool": name, "args": args, "ok": "error" not in result}) messages.append({"role": "tool", "tool_call_id": c.get("id") or name, "content": json.dumps(result, ensure_ascii=False)[:40000]}) return {"answer": "(max turns reached)", "turns": max_turns, "trace": trace} def main(): ap = argparse.ArgumentParser() ap.add_argument("--base", default=os.environ.get("QW_AGENT_BASE", "http://127.0.0.1:48981/v1")) ap.add_argument("--model", default=os.environ.get("QW_AGENT_MODEL", "qw-flash")) ap.add_argument("--key", default=os.environ.get("QW_AGENT_KEY", "sk-local")) ap.add_argument("--prompt") ap.add_argument("--max-turns", type=int, default=12) ap.add_argument("--interactive", action="store_true") a = ap.parse_args() if a.prompt: r = run(a.base, a.model, a.key, a.prompt, a.max_turns) print("\n--- result ---") print(json.dumps({"answer": r["answer"], "turns": r["turns"], "tools_used": [t["tool"] for t in r["trace"]]}, ensure_ascii=False, indent=1)) return if a.interactive: while True: try: q = input("\n> ").strip() except (EOFError, KeyboardInterrupt): return if not q: continue if q in ("exit", "quit"): return run(a.base, a.model, a.key, q, a.max_turns) return ap.print_help() if __name__ == "__main__": main()