qw_agent: bash shell (not cmd), SSE streaming in serve mode, docs
This commit is contained in:
+67
-5
@@ -20,9 +20,11 @@ Safety: destructive shell commands ask for confirmation unless --yolo; --root co
|
||||
"""
|
||||
import argparse
|
||||
import fnmatch
|
||||
import glob as globmod
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -211,6 +213,33 @@ def t_fs_grep(st, path, pattern, glob=None, max_hits=40):
|
||||
return {"hits": hits, "truncated": False}
|
||||
|
||||
|
||||
def _find_bash():
|
||||
"""Prefer a real POSIX bash: subprocess(shell=True) on Windows is cmd.exe, where `date`, `wc`,
|
||||
`grep` and friends do not exist."""
|
||||
for env in ("QW_SHELL_BIN", "SHELL"):
|
||||
cand = os.environ.get(env)
|
||||
if cand and os.path.isfile(cand):
|
||||
return cand
|
||||
cand = shutil.which("bash")
|
||||
if cand:
|
||||
return cand
|
||||
patterns = [
|
||||
"C:/Users/User/AppData/Local/hermes/tools/git-*/usr/bin/bash.exe",
|
||||
"C:/Users/User/AppData/Local/hermes/tools/git-*/bin/bash.exe",
|
||||
"C:/Program Files/Git/bin/bash.exe",
|
||||
"C:/Program Files (x86)/Git/bin/bash.exe",
|
||||
"C:/ProgramData/mingw64/mingw64/usr/bin/bash.exe",
|
||||
]
|
||||
for pat in patterns:
|
||||
hits = sorted(globmod.glob(pat))
|
||||
if hits:
|
||||
return hits[0].replace("\\", "/")
|
||||
return None
|
||||
|
||||
|
||||
BASH = _find_bash()
|
||||
|
||||
|
||||
def t_shell(st, command, cwd=None, timeout=180):
|
||||
if DANGER.search(command) and not st.yolo:
|
||||
if not st.confirm("dangerous command, run? %s" % command):
|
||||
@@ -218,9 +247,14 @@ def t_shell(st, command, cwd=None, timeout=180):
|
||||
if cwd:
|
||||
cwd = st.guard(cwd)
|
||||
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:]}
|
||||
if BASH:
|
||||
p = subprocess.run([BASH, "-lc", command], cwd=cwd, capture_output=True, text=True,
|
||||
timeout=timeout, encoding="utf-8", errors="replace")
|
||||
else:
|
||||
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:],
|
||||
"shell": BASH or "cmd"}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"exit": -1, "stdout": "", "stderr": "timeout after %ss" % timeout}
|
||||
|
||||
@@ -387,9 +421,37 @@ class ServeHandler(BaseHTTPRequestHandler):
|
||||
if req.get("model"):
|
||||
be.model = req["model"]
|
||||
r = run_task(be, user, st, max_turns=int(req.get("max_turns") or 20), verbose=False, system=sys_msg)
|
||||
cid = "chatcmpl-" + uuid.uuid4().hex[:24]
|
||||
created = int(time.time())
|
||||
if req.get("stream"):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
def chunk(delta, finish=None):
|
||||
payload = {"id": cid, "object": "chat.completion.chunk", "created": created,
|
||||
"model": be.model, "choices": [{"index": 0, "delta": delta,
|
||||
"finish_reason": finish}]}
|
||||
self.wfile.write(("data: " + json.dumps(payload, ensure_ascii=False) + "\n\n").encode())
|
||||
self.wfile.flush()
|
||||
try:
|
||||
chunk({"role": "assistant", "content": ""})
|
||||
ans = r["answer"] or ""
|
||||
for i in range(0, len(ans), 400):
|
||||
chunk({"content": ans[i:i + 400]})
|
||||
chunk({}, "stop")
|
||||
self.wfile.write(("data: " + json.dumps({"id": cid, "x_qw_tools": [t["tool"] for t in r["trace"]]},
|
||||
ensure_ascii=False) + "\n\n").encode())
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
self.close_connection = True
|
||||
return
|
||||
return self._json(200, {
|
||||
"id": "chatcmpl-" + uuid.uuid4().hex[:24], "object": "chat.completion",
|
||||
"created": int(time.time()), "model": be.model,
|
||||
"id": cid, "object": "chat.completion",
|
||||
"created": created, "model": be.model,
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": r["answer"]},
|
||||
"finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": len(user) // 4, "completion_tokens": len(r["answer"]) // 4,
|
||||
|
||||
Reference in New Issue
Block a user