add qw_agent.py: OpenAI-compatible tool-use loop with local PC access (fs_*, shell)
This commit is contained in:
@@ -1,37 +1,35 @@
|
||||
# qwenwork-autoreg
|
||||
|
||||
Autoreg + private API reverse for **qwenwork.ai** (Qwen Work): HTTP-only account farm, OpenAI-compatible shim, full protocol notes.
|
||||
No browser needed except captcha, which is solved through 2captcha.
|
||||
## Tool use / local PC access
|
||||
|
||||
```
|
||||
farm.py autoreg / login -> accounts.jsonl {email, jwt}
|
||||
qw_shim.py OpenAI-compatible gateway (:48981 /v1/chat/completions)
|
||||
api.md reverse-engineered API reference
|
||||
QwenWork's own desktop CLI (`resources/agent-sdk/components/qwencode/.../qwen-code`, ACP mode
|
||||
`--acp`, `QWENWORK_QWENCODE_PROMPT_CAPABILITY=native-tools-v1`) does have native tools, but its
|
||||
provider is pinned to DashScope inside the build: `--auth-type openai` plus
|
||||
`OPENAI_BASE_URL` / `DASHSCOPE_PROXY_BASE_URL` / `QWENWORK_MODEL_PROXY_TARGET` still send the
|
||||
request to `dashscope.aliyuncs.com` and return `401 Incorrect API key provided` for any foreign key.
|
||||
So the desktop harness cannot be repointed at an arbitrary endpoint.
|
||||
|
||||
Instead `qw_agent.py` gives the same result with full control — an OpenAI-compatible tool loop over
|
||||
this PC: `fs_read`, `fs_write`, `fs_list`, `fs_grep`, `shell`.
|
||||
|
||||
```bash
|
||||
# any OpenAI-compatible backend, e.g. the qwenwork shim when the pool has credits
|
||||
python qw_agent.py --base http://127.0.0.1:48981/v1 --model qw-flash \
|
||||
--prompt "read C:/Users/User/tmp/qwrepo/README.md and report total_lines"
|
||||
```
|
||||
|
||||
## Models (server catalog, `GET /api/chat-modes`)
|
||||
Proof run (local router, `deepseek-v4.1-flash-1017`, 3 turns):
|
||||
|
||||
| mode key | price_factor | notes |
|
||||
|---|---|---|
|
||||
| `kimi-k3.1-pro` | 2.6 | vision, 1M ctx |
|
||||
| `qwen3.8-max` | 1.9 | vision |
|
||||
| `qwen4-max` | 1.4 | vision, anthropic-format |
|
||||
| `glm-5.3` | 1.3 | |
|
||||
| `gpt-6.1-sol` | 1.0 | vision |
|
||||
| `deepseek-v4.1-flash`, `deepseek-flash` | 0.2 | |
|
||||
| `glm-5.3-flash` | 0.2 | vision |
|
||||
| `minimax-m3.1-flash` | 0.2 | vision, anthropic-format |
|
||||
| `qwen3.8-flash` | 0.1 | default |
|
||||
| `flash` / `advanced` / `pro` | aliases | rank tiers |
|
||||
```
|
||||
[assistant] ...
|
||||
[tool] fs_read {'path': 'C:/Users/User/tmp/qwrepo/README.md'}
|
||||
[tool] shell {'command': 'wc -l C:/Users/User/tmp/qwrepo/README.md'}
|
||||
[tool] fs_read {'path': '...', 'offset': 70}
|
||||
result: tools_used = ["fs_read", "shell", "fs_read"] -> answer "total_lines = 79"
|
||||
```
|
||||
|
||||
Measured turn price from `/user/billings`: **0.016 – 0.044 credit** for `flash`.
|
||||
Free tier advertises 500 starter + 200 daily credits -> tens of thousands of turns in theory.
|
||||
|
||||
## Autoreg flow (plain HTTP, no JS)
|
||||
|
||||
1. **Captcha** — Aliyun Captcha v3, solved with 2captcha task type `AlibabaTaskProxyless`
|
||||
(`sceneId=l47rwlyt`, `prefix=13n1x6`, `region=ga`, `apiGetLib=https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js?t=2035`).
|
||||
2. `POST /auth/email-codes {email, purpose:"registration", captcha_token}` — 200 `{"code":"ok"}`.
|
||||
The model reads the real filesystem and runs real commands on the host: that is the "PC visible"
|
||||
part, without depending on the closed desktop client.
|
||||
{"code":"ok"}`.
|
||||
**`captcha_token` must be the whole 2captcha `solution` object serialised as a JSON string** —
|
||||
an object body gives 400, `solution.data` alone gives 403 `human verification failed`.
|
||||
3. read the 6-digit code from the mailbox over IMAP (qwenwork mail, `used_codes.txt` guards against
|
||||
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
"""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()
|
||||
Reference in New Issue
Block a user