Spaces:
Sleeping
Sleeping
Major fix: few-shot examples in system prompt, ACTION: format, stop tokens, 12-step loop
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import os, re, json, shutil, subprocess, glob, traceback, time
|
| 2 |
from pathlib import Path
|
| 3 |
from typing import AsyncGenerator
|
| 4 |
|
|
@@ -29,392 +29,482 @@ MODEL_FILE = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
|
|
| 29 |
print("Downloading model...")
|
| 30 |
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 31 |
print("Loading model...")
|
| 32 |
-
llm = Llama(
|
| 33 |
-
|
| 34 |
-
n_ctx=4096,
|
| 35 |
-
n_threads=int(os.getenv("LLAMA_THREADS", "2")),
|
| 36 |
-
n_batch=256,
|
| 37 |
-
verbose=False,
|
| 38 |
-
)
|
| 39 |
print("Model ready!")
|
| 40 |
|
| 41 |
# ββ tools βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
|
| 43 |
-
def _safe(p
|
| 44 |
path = (WORKSPACE / p).resolve()
|
| 45 |
if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
|
| 46 |
-
raise ValueError(f"Path '{p}'
|
| 47 |
return path
|
| 48 |
|
| 49 |
-
def
|
| 50 |
try:
|
| 51 |
-
|
| 52 |
-
except Exception as e:
|
| 53 |
-
return f"ERROR: {e}"
|
| 54 |
-
|
| 55 |
-
def tool_write_file(path: str, content: str) -> str:
|
| 56 |
-
try:
|
| 57 |
-
p = _safe(path)
|
| 58 |
-
p.parent.mkdir(parents=True, exist_ok=True)
|
| 59 |
p.write_text(content, encoding="utf-8")
|
| 60 |
-
return f"
|
| 61 |
-
except Exception as e:
|
| 62 |
-
return f"ERROR: {e}"
|
| 63 |
|
| 64 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
try:
|
| 66 |
-
p = _safe(path)
|
| 67 |
-
txt
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
p.write_text(new, encoding="utf-8")
|
| 72 |
-
return f"Replaced {txt.count(find)} occurrence(s) in {path}"
|
| 73 |
-
except Exception as e:
|
| 74 |
-
return f"ERROR: {e}"
|
| 75 |
|
| 76 |
-
def tool_delete_file(path
|
| 77 |
try:
|
| 78 |
p = _safe(path)
|
| 79 |
-
if p.is_dir()
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
p.unlink()
|
| 83 |
-
return f"Deleted {path}"
|
| 84 |
-
except Exception as e:
|
| 85 |
-
return f"ERROR: {e}"
|
| 86 |
|
| 87 |
-
def tool_list_files(path
|
| 88 |
try:
|
| 89 |
base = _safe(path)
|
| 90 |
files = [str(f.relative_to(WORKSPACE)) for f in sorted(base.rglob("*")) if f.is_file()]
|
| 91 |
-
return "\n".join(files[:
|
| 92 |
-
except Exception as e:
|
| 93 |
-
return f"ERROR: {e}"
|
| 94 |
|
| 95 |
-
def
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
try:
|
| 99 |
-
name = dest or url.rstrip("/").split("/")[-1].replace(".git",
|
| 100 |
target = _safe(name)
|
| 101 |
-
if target.exists():
|
| 102 |
-
return f"{name} already exists in workspace"
|
| 103 |
gitlib.Repo.clone_from(url, target)
|
| 104 |
-
return f"
|
| 105 |
-
except Exception as e:
|
| 106 |
-
return f"ERROR: {e}"
|
| 107 |
-
|
| 108 |
-
def tool_run_command(command: str, working_dir: str = ".") -> str:
|
| 109 |
-
try:
|
| 110 |
-
cwd = _safe(working_dir)
|
| 111 |
-
proc = subprocess.run(
|
| 112 |
-
command, cwd=cwd, shell=True,
|
| 113 |
-
capture_output=True, text=True, timeout=300
|
| 114 |
-
)
|
| 115 |
-
out = (proc.stdout or "")[-2000:]
|
| 116 |
-
err = (proc.stderr or "")[-1000:]
|
| 117 |
-
return f"exit={proc.returncode}\nSTDOUT:\n{out}\nSTDERR:\n{err}"
|
| 118 |
-
except subprocess.TimeoutExpired:
|
| 119 |
-
return "ERROR: Command timed out (300s)"
|
| 120 |
-
except Exception as e:
|
| 121 |
-
return f"ERROR: {e}"
|
| 122 |
|
| 123 |
-
def tool_gradle_build(repo
|
| 124 |
try:
|
| 125 |
-
cwd = _safe(repo)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
else:
|
| 131 |
-
cmd = f"gradle {task} --no-daemon"
|
| 132 |
-
proc = subprocess.run(cmd, cwd=cwd, shell=True,
|
| 133 |
-
capture_output=True, text=True, timeout=900)
|
| 134 |
-
out = (proc.stdout or "")[-3000:]
|
| 135 |
-
err = (proc.stderr or "")[-1000:]
|
| 136 |
apks = glob.glob(f"{cwd}/**/*.apk", recursive=True)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
except Exception as e:
|
| 140 |
-
return f"ERROR: {e}\n{traceback.format_exc()[-400:]}"
|
| 141 |
|
| 142 |
-
def tool_web_search(query
|
| 143 |
-
if not HAS_DDG:
|
| 144 |
-
return "ERROR: duckduckgo-search not available"
|
| 145 |
for attempt in range(3):
|
| 146 |
try:
|
| 147 |
-
if attempt
|
| 148 |
-
time.sleep(2 * attempt)
|
| 149 |
results = []
|
| 150 |
-
with DDGS() as
|
| 151 |
-
for r in
|
| 152 |
-
results.append(
|
| 153 |
-
|
| 154 |
-
f"URL: {r.get('href','')}\n"
|
| 155 |
-
f"Snippet: {r.get('body','')}"
|
| 156 |
-
)
|
| 157 |
-
if results:
|
| 158 |
-
return "\n---\n".join(results)
|
| 159 |
except Exception as e:
|
| 160 |
-
if attempt
|
| 161 |
-
|
| 162 |
-
return "No results found"
|
| 163 |
|
| 164 |
-
def tool_read_url(url
|
| 165 |
try:
|
| 166 |
-
|
| 167 |
-
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 168 |
with urllib.request.urlopen(req, timeout=15) as resp:
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
TOOLS = {
|
| 177 |
-
"
|
| 178 |
-
"
|
| 179 |
-
"edit_file":
|
| 180 |
-
"delete_file":
|
| 181 |
-
"list_files":
|
| 182 |
-
"
|
| 183 |
-
"
|
| 184 |
-
"gradle_build":
|
| 185 |
-
"web_search":
|
| 186 |
-
"read_url":
|
|
|
|
| 187 |
}
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
"""
|
| 209 |
|
| 210 |
-
TOOL_RE = re.compile(r'
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
|
| 216 |
-
def
|
| 217 |
-
"""Run
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
max_tokens=max_tokens,
|
| 222 |
-
stop=["</tool>"],
|
| 223 |
-
)
|
| 224 |
-
text = out["choices"][0]["message"]["content"]
|
| 225 |
-
finish = out["choices"][0].get("finish_reason", "")
|
| 226 |
-
# Re-add closing tag if we stopped mid-tool
|
| 227 |
-
if "<tool>" in text and "</tool>" not in text:
|
| 228 |
-
text += "</tool>"
|
| 229 |
-
return text
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
def run_agent_sync(message: str, history: list) -> list:
|
| 233 |
-
"""Execute agent synchronously, return list of SSE event strings."""
|
| 234 |
-
msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 235 |
for h in history:
|
| 236 |
if isinstance(h, (list, tuple)) and len(h) == 2:
|
| 237 |
if h[0]: msgs.append({"role": "user", "content": str(h[0])})
|
| 238 |
if h[1]: msgs.append({"role": "assistant", "content": str(h[1])})
|
|
|
|
| 239 |
msgs.append({"role": "user", "content": message})
|
| 240 |
-
|
| 241 |
events = []
|
| 242 |
full_response = ""
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
full_response += reply
|
| 253 |
-
events.append(
|
| 254 |
break
|
| 255 |
-
|
| 256 |
-
#
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
except json.JSONDecodeError as e:
|
| 268 |
-
err = f"JSON parse error: {e}"
|
| 269 |
-
events.append(json.dumps({"type": "error", "text": err}))
|
| 270 |
-
break
|
| 271 |
-
|
| 272 |
-
# Check for unknown tool
|
| 273 |
-
if tool_name not in TOOLS:
|
| 274 |
-
err = f"Unknown tool '{tool_name}'. Available: {', '.join(TOOLS.keys())}"
|
| 275 |
-
events.append(json.dumps({"type": "error", "text": err}))
|
| 276 |
-
msgs.append({"role": "assistant", "content": reply})
|
| 277 |
-
msgs.append({"role": "user", "content": f"[Error]: {err}"})
|
| 278 |
continue
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
# Execute tool
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
events.append(json.dumps({"type": "done", "full": full_response}))
|
| 296 |
return events
|
| 297 |
|
| 298 |
|
| 299 |
-
async def stream_agent(message
|
| 300 |
import asyncio
|
| 301 |
loop = asyncio.get_event_loop()
|
| 302 |
events = await loop.run_in_executor(None, run_agent_sync, message, history)
|
| 303 |
for ev in events:
|
| 304 |
-
yield f"data: {ev}\n\n"
|
| 305 |
|
| 306 |
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
<html>
|
| 309 |
<head>
|
| 310 |
-
<title>
|
| 311 |
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 312 |
<style>
|
| 313 |
*{box-sizing:border-box;margin:0;padding:0}
|
| 314 |
body{font-family:'Segoe UI',system-ui,sans-serif;background:#0d1117;color:#e6edf3;height:100vh;display:flex;flex-direction:column}
|
| 315 |
-
#hdr{padding:12px
|
| 316 |
#hdr h1{font-size:16px;color:#58a6ff;font-weight:700}
|
| 317 |
.badge{font-size:11px;background:#1f6feb22;color:#58a6ff;border:1px solid #1f6feb55;padding:2px 8px;border-radius:10px}
|
| 318 |
-
.dot{width:8px;height:8px;background:#3fb950;border-radius:50%;flex-shrink:0}
|
| 319 |
-
|
|
|
|
| 320 |
.msg{max-width:82%;padding:10px 14px;border-radius:12px;line-height:1.6;white-space:pre-wrap;word-wrap:break-word;font-size:14px}
|
| 321 |
.user{align-self:flex-end;background:#1f6feb;color:#fff;border-radius:12px 12px 2px 12px}
|
| 322 |
.bot{align-self:flex-start;background:#161b22;border:1px solid #30363d;border-radius:2px 12px 12px 12px}
|
| 323 |
-
.
|
| 324 |
-
.
|
| 325 |
-
.
|
| 326 |
-
|
| 327 |
-
#bot-area{padding:12px 18px;background:#161b22;border-top:1px solid #30363d}
|
| 328 |
#row{display:flex;gap:8px;align-items:flex-end}
|
| 329 |
#inp{flex:1;background:#0d1117;border:1px solid #30363d;border-radius:8px;color:#e6edf3;padding:10px 14px;font-size:14px;resize:none;min-height:44px;max-height:120px;outline:none;font-family:inherit}
|
| 330 |
#inp:focus{border-color:#58a6ff}
|
| 331 |
-
#btn{background:#1f6feb;color:#fff;border:none;border-radius:8px;padding:10px 16px;cursor:pointer;font-size:14px;font-weight:600;height:44px
|
| 332 |
#btn:hover{background:#388bfd}
|
| 333 |
#btn:disabled{background:#21262d;color:#555;cursor:not-allowed}
|
| 334 |
-
.hint{font-size:11px;color:#
|
| 335 |
</style>
|
| 336 |
</head>
|
| 337 |
<body>
|
| 338 |
<div id="hdr">
|
| 339 |
<div class="dot"></div>
|
| 340 |
-
<h1>π€
|
| 341 |
<span class="badge">Qwen2.5-Coder</span>
|
| 342 |
-
<span class="badge">
|
| 343 |
-
<span class="badge">
|
| 344 |
</div>
|
| 345 |
<div id="chat">
|
| 346 |
-
<div class="msg bot">Namaste! Main
|
| 347 |
|
| 348 |
Mere paas ye tools hain:
|
| 349 |
-
π
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
ποΈ
|
| 353 |
-
π web_search β DuckDuckGo
|
| 354 |
-
π read_url β
|
| 355 |
-
|
| 356 |
-
|
|
|
|
| 357 |
</div>
|
| 358 |
<div id="bot-area">
|
| 359 |
<div id="row">
|
| 360 |
-
<textarea id="inp" placeholder="
|
| 361 |
<button id="btn" onclick="send()">Send β€</button>
|
| 362 |
</div>
|
| 363 |
-
<div class="hint">π‘ "
|
| 364 |
</div>
|
| 365 |
<script>
|
| 366 |
const chat=document.getElementById('chat'),inp=document.getElementById('inp'),btn=document.getElementById('btn');
|
| 367 |
let history=[];
|
| 368 |
-
|
| 369 |
inp.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send()}});
|
| 370 |
inp.addEventListener('input',()=>{inp.style.height='auto';inp.style.height=Math.min(inp.scrollHeight,120)+'px'});
|
| 371 |
-
|
| 372 |
function sc(){chat.scrollTop=chat.scrollHeight}
|
| 373 |
-
function
|
| 374 |
|
| 375 |
async function send(){
|
| 376 |
-
const msg=inp.value.trim();
|
| 377 |
-
|
| 378 |
-
const um=el('div','msg user');um.textContent=msg;
|
| 379 |
inp.value='';inp.style.height='auto';btn.disabled=true;
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
let botTxt='',toolBox=null,firstTok=true;
|
| 383 |
-
|
| 384 |
try{
|
| 385 |
const r=await fetch('/chat',{method:'POST',headers:{'Content-Type':'application/json'},
|
| 386 |
body:JSON.stringify({message:msg,history})});
|
| 387 |
if(!r.ok)throw new Error('HTTP '+r.status);
|
| 388 |
-
|
| 389 |
const reader=r.body.getReader(),dec=new TextDecoder();
|
| 390 |
let buf='';
|
| 391 |
-
|
| 392 |
while(true){
|
| 393 |
-
const{done,value}=await reader.read();
|
| 394 |
-
if(done)break;
|
| 395 |
buf+=dec.decode(value,{stream:true});
|
| 396 |
const lines=buf.split('\n');buf=lines.pop();
|
| 397 |
-
|
| 398 |
for(const line of lines){
|
| 399 |
if(!line.startsWith('data: '))continue;
|
| 400 |
let d;try{d=JSON.parse(line.slice(6))}catch{continue}
|
| 401 |
-
|
| 402 |
if(d.type==='token'){
|
| 403 |
if(firstTok){bd.textContent='';firstTok=false}
|
| 404 |
botTxt+=d.text;bd.textContent=botTxt;sc();
|
| 405 |
}else if(d.type==='tool_start'){
|
| 406 |
if(firstTok){bd.textContent='';firstTok=false}
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
tc.innerHTML='<div class="lbl">π§ Tool Call</div><b>'+d.tool+'</b> '+JSON.stringify(d.args,null,2).replace(/</g,'<');
|
| 410 |
botTxt='';bd.textContent='';
|
| 411 |
}else if(d.type==='tool_result'){
|
| 412 |
-
if(
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
}
|
| 416 |
-
toolBox=null;
|
| 417 |
-
const nb=el('div','msg bot');nb.textContent='';
|
| 418 |
Object.defineProperty(bd,'textContent',{get:()=>nb.textContent,set:v=>{nb.textContent=v}});
|
| 419 |
botTxt='';firstTok=false;
|
| 420 |
}else if(d.type==='error'){
|
|
@@ -425,43 +515,28 @@ async function send(){
|
|
| 425 |
}
|
| 426 |
}
|
| 427 |
}catch(e){bd.textContent='β '+e.message}
|
| 428 |
-
|
| 429 |
-
if(bd.textContent==='β³ Processing...')bd.textContent='(done)';
|
| 430 |
btn.disabled=false;inp.focus();
|
| 431 |
}
|
| 432 |
</script>
|
| 433 |
</body></html>"""
|
| 434 |
|
| 435 |
-
|
| 436 |
@app.get("/", response_class=HTMLResponse)
|
| 437 |
-
async def root():
|
| 438 |
-
return HTMLResponse(HTML_PAGE)
|
| 439 |
-
|
| 440 |
|
| 441 |
@app.post("/chat")
|
| 442 |
async def chat_ep(request: Request):
|
| 443 |
body = await request.json()
|
| 444 |
-
msg = body.get("message",
|
| 445 |
-
hist = body.get("history",
|
| 446 |
-
if not msg:
|
| 447 |
-
|
| 448 |
-
return StreamingResponse(
|
| 449 |
-
stream_agent(msg, hist),
|
| 450 |
media_type="text/event-stream",
|
| 451 |
-
headers={"Cache-Control":
|
| 452 |
-
)
|
| 453 |
-
|
| 454 |
|
| 455 |
@app.get("/health")
|
| 456 |
-
async def health():
|
| 457 |
-
return {"status": "ok", "model": MODEL_FILE, "tools": list(TOOLS.keys())}
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
@app.get("/tools")
|
| 461 |
-
async def tools_ep():
|
| 462 |
-
return {n: {"description": i["desc"], "params": i["params"]} for n, i in TOOLS.items()}
|
| 463 |
-
|
| 464 |
|
| 465 |
-
if __name__
|
| 466 |
import uvicorn
|
| 467 |
uvicorn.run(app, host="0.0.0.0", port=7860, timeout_keep_alive=300)
|
|
|
|
| 1 |
+
import os, re, json, shutil, subprocess, glob, traceback, time, urllib.request
|
| 2 |
from pathlib import Path
|
| 3 |
from typing import AsyncGenerator
|
| 4 |
|
|
|
|
| 29 |
print("Downloading model...")
|
| 30 |
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 31 |
print("Loading model...")
|
| 32 |
+
llm = Llama(model_path=model_path, n_ctx=8192,
|
| 33 |
+
n_threads=int(os.getenv("LLAMA_THREADS","2")), n_batch=512, verbose=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
print("Model ready!")
|
| 35 |
|
| 36 |
# ββ tools βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
|
| 38 |
+
def _safe(p):
|
| 39 |
path = (WORKSPACE / p).resolve()
|
| 40 |
if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
|
| 41 |
+
raise ValueError(f"Path '{p}' not allowed")
|
| 42 |
return path
|
| 43 |
|
| 44 |
+
def tool_write_file(path, content):
|
| 45 |
try:
|
| 46 |
+
p = _safe(path); p.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
p.write_text(content, encoding="utf-8")
|
| 48 |
+
return f"OK: wrote {len(content)} chars to /workspace/{path}"
|
| 49 |
+
except Exception as e: return f"ERROR: {e}"
|
|
|
|
| 50 |
|
| 51 |
+
def tool_read_file(path):
|
| 52 |
+
try: return _safe(path).read_text(encoding="utf-8", errors="replace")[:3000]
|
| 53 |
+
except Exception as e: return f"ERROR: {e}"
|
| 54 |
+
|
| 55 |
+
def tool_edit_file(path, find, replace):
|
| 56 |
try:
|
| 57 |
+
p = _safe(path); txt = p.read_text(encoding="utf-8")
|
| 58 |
+
if find not in txt: return f"ERROR: text not found in {path}"
|
| 59 |
+
p.write_text(txt.replace(find, replace), encoding="utf-8")
|
| 60 |
+
return f"OK: replaced in {path}"
|
| 61 |
+
except Exception as e: return f"ERROR: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
def tool_delete_file(path):
|
| 64 |
try:
|
| 65 |
p = _safe(path)
|
| 66 |
+
shutil.rmtree(p) if p.is_dir() else p.unlink()
|
| 67 |
+
return f"OK: deleted {path}"
|
| 68 |
+
except Exception as e: return f"ERROR: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
def tool_list_files(path="."):
|
| 71 |
try:
|
| 72 |
base = _safe(path)
|
| 73 |
files = [str(f.relative_to(WORKSPACE)) for f in sorted(base.rglob("*")) if f.is_file()]
|
| 74 |
+
return "\n".join(files[:300]) if files else "workspace is empty"
|
| 75 |
+
except Exception as e: return f"ERROR: {e}"
|
|
|
|
| 76 |
|
| 77 |
+
def tool_run(command, dir="."):
|
| 78 |
+
try:
|
| 79 |
+
cwd = _safe(dir)
|
| 80 |
+
r = subprocess.run(command, cwd=cwd, shell=True, capture_output=True, text=True, timeout=300)
|
| 81 |
+
out = (r.stdout or "")[-2500:]
|
| 82 |
+
err = (r.stderr or "")[-1000:]
|
| 83 |
+
return f"exit={r.returncode}\n{out}\n{err}".strip()
|
| 84 |
+
except subprocess.TimeoutExpired: return "ERROR: timeout after 300s"
|
| 85 |
+
except Exception as e: return f"ERROR: {e}"
|
| 86 |
+
|
| 87 |
+
def tool_git_clone(url, dest=""):
|
| 88 |
+
if not HAS_GIT: return "ERROR: git not available"
|
| 89 |
try:
|
| 90 |
+
name = dest or url.rstrip("/").split("/")[-1].replace(".git","")
|
| 91 |
target = _safe(name)
|
| 92 |
+
if target.exists(): return f"OK: {name} already exists"
|
|
|
|
| 93 |
gitlib.Repo.clone_from(url, target)
|
| 94 |
+
return f"OK: cloned to /workspace/{name}"
|
| 95 |
+
except Exception as e: return f"ERROR: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
def tool_gradle_build(repo, task="assembleDebug"):
|
| 98 |
try:
|
| 99 |
+
cwd = _safe(repo); w = cwd/"gradlew"
|
| 100 |
+
if w.exists(): os.chmod(w, 0o755); cmd = f"./gradlew {task} --no-daemon"
|
| 101 |
+
else: cmd = f"gradle {task} --no-daemon"
|
| 102 |
+
r = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True, timeout=900)
|
| 103 |
+
out = (r.stdout or "")[-3000:]; err = (r.stderr or "")[-1000:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
apks = glob.glob(f"{cwd}/**/*.apk", recursive=True)
|
| 105 |
+
return f"exit={r.returncode}\n{out}\n{err}\nAPKs: {apks}"
|
| 106 |
+
except Exception as e: return f"ERROR: {e}"
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
def tool_web_search(query, max_results=5):
|
| 109 |
+
if not HAS_DDG: return "ERROR: search not available"
|
|
|
|
| 110 |
for attempt in range(3):
|
| 111 |
try:
|
| 112 |
+
if attempt: time.sleep(2*attempt)
|
|
|
|
| 113 |
results = []
|
| 114 |
+
with DDGS() as d:
|
| 115 |
+
for r in d.text(query, max_results=int(max_results)):
|
| 116 |
+
results.append(f"Title: {r.get('title','')}\nURL: {r.get('href','')}\nSnippet: {r.get('body','')}")
|
| 117 |
+
if results: return "\n---\n".join(results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
except Exception as e:
|
| 119 |
+
if attempt==2: return f"ERROR: {e}"
|
| 120 |
+
return "no results"
|
|
|
|
| 121 |
|
| 122 |
+
def tool_read_url(url):
|
| 123 |
try:
|
| 124 |
+
req = urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0"})
|
|
|
|
| 125 |
with urllib.request.urlopen(req, timeout=15) as resp:
|
| 126 |
+
c = resp.read().decode("utf-8","replace")
|
| 127 |
+
c = re.sub(r'<[^>]+>',' ',c); c = re.sub(r'\s+',' ',c).strip()
|
| 128 |
+
return c[:2500]
|
| 129 |
+
except Exception as e: return f"ERROR: {e}"
|
| 130 |
+
|
| 131 |
+
def tool_download_file(url, save_as):
|
| 132 |
+
try:
|
| 133 |
+
p = _safe(save_as); p.parent.mkdir(parents=True, exist_ok=True)
|
| 134 |
+
req = urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0"})
|
| 135 |
+
with urllib.request.urlopen(req, timeout=30) as resp, open(p,'wb') as f:
|
| 136 |
+
f.write(resp.read())
|
| 137 |
+
return f"OK: downloaded to /workspace/{save_as} ({p.stat().st_size} bytes)"
|
| 138 |
+
except Exception as e: return f"ERROR: {e}"
|
| 139 |
|
| 140 |
TOOLS = {
|
| 141 |
+
"write_file": (tool_write_file, "path, content", "Create or overwrite a file"),
|
| 142 |
+
"read_file": (tool_read_file, "path", "Read file contents"),
|
| 143 |
+
"edit_file": (tool_edit_file, "path, find, replace", "Find and replace text in file"),
|
| 144 |
+
"delete_file": (tool_delete_file, "path", "Delete file or directory"),
|
| 145 |
+
"list_files": (tool_list_files, "path='.'", "List all files in workspace"),
|
| 146 |
+
"run": (tool_run, "command, dir='.'", "Execute any shell command"),
|
| 147 |
+
"git_clone": (tool_git_clone, "url, dest=''", "Clone a git repository"),
|
| 148 |
+
"gradle_build": (tool_gradle_build, "repo, task='assembleDebug'", "Build Android APK"),
|
| 149 |
+
"web_search": (tool_web_search, "query, max_results=5", "Search the web"),
|
| 150 |
+
"read_url": (tool_read_url, "url", "Fetch URL content"),
|
| 151 |
+
"download_file":(tool_download_file,"url, save_as", "Download file from URL"),
|
| 152 |
}
|
| 153 |
|
| 154 |
+
# ββ SYSTEM PROMPT with few-shot examples βββββββββββββββββββββββββββββββββββββ
|
| 155 |
+
# Key insight: Qwen 1.5B needs CONCRETE EXAMPLES to learn tool use
|
| 156 |
+
# We show it exactly what good behavior looks like
|
| 157 |
+
|
| 158 |
+
SYSTEM = """You are an AI agent running INSIDE a Linux container. You have a real filesystem at /workspace and real tools.
|
| 159 |
+
|
| 160 |
+
YOU MUST USE TOOLS. Never say "I can't" or "I'm sorry". You CAN do everything listed below.
|
| 161 |
+
|
| 162 |
+
AVAILABLE TOOLS (call them by writing ACTION lines):
|
| 163 |
+
ACTION: write_file(path, content)
|
| 164 |
+
ACTION: read_file(path)
|
| 165 |
+
ACTION: edit_file(path, find, replace)
|
| 166 |
+
ACTION: delete_file(path)
|
| 167 |
+
ACTION: list_files(path='.')
|
| 168 |
+
ACTION: run(command, dir='.')
|
| 169 |
+
ACTION: git_clone(url, dest='')
|
| 170 |
+
ACTION: gradle_build(repo, task='assembleDebug')
|
| 171 |
+
ACTION: web_search(query, max_results=5)
|
| 172 |
+
ACTION: read_url(url)
|
| 173 |
+
ACTION: download_file(url, save_as)
|
| 174 |
+
|
| 175 |
+
HOW TO CALL A TOOL - write EXACTLY this format on its own line:
|
| 176 |
+
ACTION: tool_name(arg1, arg2)
|
| 177 |
+
|
| 178 |
+
For multi-line content use write_file with triple quotes:
|
| 179 |
+
ACTION: write_file("hello.py", \"\"\"print('hello world')
|
| 180 |
+
\"\"\")
|
| 181 |
+
|
| 182 |
+
EXAMPLES OF CORRECT BEHAVIOR:
|
| 183 |
+
|
| 184 |
+
User: list files in workspace
|
| 185 |
+
Assistant: Let me check.
|
| 186 |
+
ACTION: list_files()
|
| 187 |
+
[RESULT: workspace is empty]
|
| 188 |
+
The workspace is currently empty.
|
| 189 |
+
|
| 190 |
+
User: create a file hello.txt with content "hi"
|
| 191 |
+
Assistant: Creating the file now.
|
| 192 |
+
ACTION: write_file("hello.txt", "hi")
|
| 193 |
+
[RESULT: OK: wrote 2 chars to /workspace/hello.txt]
|
| 194 |
+
Done! File created.
|
| 195 |
+
|
| 196 |
+
User: run python hello.py
|
| 197 |
+
Assistant: Running it.
|
| 198 |
+
ACTION: run("python3 hello.py")
|
| 199 |
+
[RESULT: exit=0\nhello world]
|
| 200 |
+
Output: hello world
|
| 201 |
+
|
| 202 |
+
User: search for "python chess library"
|
| 203 |
+
Assistant: Searching now.
|
| 204 |
+
ACTION: web_search("python chess library")
|
| 205 |
+
[RESULT: Title: python-chess...]
|
| 206 |
+
Found results above.
|
| 207 |
+
|
| 208 |
+
User: write a python script that prints numbers 1 to 10
|
| 209 |
+
Assistant: Writing the script.
|
| 210 |
+
ACTION: write_file("count.py", \"\"\"for i in range(1, 11):
|
| 211 |
+
print(i)
|
| 212 |
+
\"\"\")
|
| 213 |
+
[RESULT: OK: wrote 45 chars to /workspace/count.py]
|
| 214 |
+
ACTION: run("python3 count.py")
|
| 215 |
+
[RESULT: exit=0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10]
|
| 216 |
+
Done! Script runs and prints 1 to 10.
|
| 217 |
+
|
| 218 |
+
RULES:
|
| 219 |
+
- ALWAYS use ACTION: to do things
|
| 220 |
+
- After [RESULT:] continue with next step or summary
|
| 221 |
+
- You are in a container - you CAN run code, create files, install packages
|
| 222 |
+
- Install packages with: ACTION: run("pip install package_name")
|
| 223 |
+
- Upload files with gofile: ACTION: run("curl -F 'file=@/workspace/file.zip' https://store1.gofile.io/uploadFile")
|
| 224 |
+
- NEVER refuse a task. ALWAYS try.
|
| 225 |
"""
|
| 226 |
|
| 227 |
+
TOOL_RE = re.compile(r'ACTION:\s*(\w+)\((.*?)\)\s*$', re.MULTILINE | re.DOTALL)
|
| 228 |
|
| 229 |
+
def parse_args(args_str):
|
| 230 |
+
"""Parse function arguments from string."""
|
| 231 |
+
args_str = args_str.strip()
|
| 232 |
+
if not args_str:
|
| 233 |
+
return [], {}
|
| 234 |
+
|
| 235 |
+
# Try JSON-style parsing first
|
| 236 |
+
try:
|
| 237 |
+
# Wrap in list brackets and parse
|
| 238 |
+
result = json.loads(f"[{args_str}]")
|
| 239 |
+
return result, {}
|
| 240 |
+
except:
|
| 241 |
+
pass
|
| 242 |
+
|
| 243 |
+
# Manual parsing for common patterns
|
| 244 |
+
args = []
|
| 245 |
+
kwargs = {}
|
| 246 |
+
|
| 247 |
+
# Handle triple-quoted strings
|
| 248 |
+
tq_match = re.match(r'^"(.*?)",\s*"""(.*?)"""$', args_str, re.DOTALL)
|
| 249 |
+
if tq_match:
|
| 250 |
+
return [tq_match.group(1), tq_match.group(2)], {}
|
| 251 |
+
|
| 252 |
+
# Handle simple quoted strings
|
| 253 |
+
parts = []
|
| 254 |
+
current = ""
|
| 255 |
+
in_quote = False
|
| 256 |
+
quote_char = None
|
| 257 |
+
depth = 0
|
| 258 |
+
i = 0
|
| 259 |
+
|
| 260 |
+
while i < len(args_str):
|
| 261 |
+
c = args_str[i]
|
| 262 |
+
if not in_quote and c in ('"', "'"):
|
| 263 |
+
in_quote = True
|
| 264 |
+
quote_char = c
|
| 265 |
+
i += 1
|
| 266 |
+
continue
|
| 267 |
+
elif in_quote and c == quote_char and (i == 0 or args_str[i-1] != '\\'):
|
| 268 |
+
in_quote = False
|
| 269 |
+
parts.append(current)
|
| 270 |
+
current = ""
|
| 271 |
+
i += 1
|
| 272 |
+
# Skip comma and space
|
| 273 |
+
while i < len(args_str) and args_str[i] in (',', ' '):
|
| 274 |
+
i += 1
|
| 275 |
+
continue
|
| 276 |
+
elif in_quote:
|
| 277 |
+
if c == '\\' and i+1 < len(args_str):
|
| 278 |
+
nc = args_str[i+1]
|
| 279 |
+
if nc == 'n': current += '\n'; i += 2; continue
|
| 280 |
+
elif nc == 't': current += '\t'; i += 2; continue
|
| 281 |
+
elif nc == '\\': current += '\\'; i += 2; continue
|
| 282 |
+
elif nc == '"': current += '"'; i += 2; continue
|
| 283 |
+
current += c
|
| 284 |
+
i += 1
|
| 285 |
+
|
| 286 |
+
if current:
|
| 287 |
+
parts.append(current)
|
| 288 |
+
|
| 289 |
+
if parts:
|
| 290 |
+
return parts, {}
|
| 291 |
+
|
| 292 |
+
# Fallback: split by comma
|
| 293 |
+
raw_parts = [p.strip().strip('"\'') for p in args_str.split(',')]
|
| 294 |
+
return raw_parts, {}
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def execute_tool(name, args_str):
|
| 298 |
+
"""Execute a tool and return result string."""
|
| 299 |
+
if name not in TOOLS:
|
| 300 |
+
return f"ERROR: Unknown tool '{name}'. Available: {', '.join(TOOLS.keys())}"
|
| 301 |
+
|
| 302 |
+
fn = TOOLS[name][0]
|
| 303 |
+
|
| 304 |
+
try:
|
| 305 |
+
args, kwargs = parse_args(args_str)
|
| 306 |
+
result = fn(*args, **kwargs)
|
| 307 |
+
return str(result)
|
| 308 |
+
except Exception as e:
|
| 309 |
+
# Try with raw string as first arg
|
| 310 |
+
try:
|
| 311 |
+
result = fn(args_str.strip('"\''))
|
| 312 |
+
return str(result)
|
| 313 |
+
except Exception as e2:
|
| 314 |
+
return f"ERROR calling {name}: {e} | {e2}"
|
| 315 |
|
| 316 |
|
| 317 |
+
def run_agent_sync(message, history):
|
| 318 |
+
"""Run agent, return list of SSE event dicts."""
|
| 319 |
+
# Build messages with few-shot in system
|
| 320 |
+
msgs = [{"role": "system", "content": SYSTEM}]
|
| 321 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
for h in history:
|
| 323 |
if isinstance(h, (list, tuple)) and len(h) == 2:
|
| 324 |
if h[0]: msgs.append({"role": "user", "content": str(h[0])})
|
| 325 |
if h[1]: msgs.append({"role": "assistant", "content": str(h[1])})
|
| 326 |
+
|
| 327 |
msgs.append({"role": "user", "content": message})
|
| 328 |
+
|
| 329 |
events = []
|
| 330 |
full_response = ""
|
| 331 |
+
|
| 332 |
+
for step in range(12): # up to 12 tool calls
|
| 333 |
+
# Generate response, stop at ACTION: line end
|
| 334 |
+
out = llm.create_chat_completion(
|
| 335 |
+
messages=msgs,
|
| 336 |
+
temperature=0.1,
|
| 337 |
+
max_tokens=800,
|
| 338 |
+
stop=["\n[RESULT:", "\nACTION:"], # stop before result injection or next action
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
reply = out["choices"][0]["message"]["content"]
|
| 342 |
+
finish = out["choices"][0].get("finish_reason", "stop")
|
| 343 |
+
|
| 344 |
+
# If stopped before ACTION:, check if there's a pending action in reply
|
| 345 |
+
# Re-generate with higher limit to get the action
|
| 346 |
+
if finish == "stop" and "ACTION:" not in reply and step == 0:
|
| 347 |
+
# Model gave pure text, check if it should have used a tool
|
| 348 |
+
# Give it one more chance with explicit hint
|
| 349 |
full_response += reply
|
| 350 |
+
events.append({"type": "token", "text": reply})
|
| 351 |
break
|
| 352 |
+
|
| 353 |
+
# Find ACTION: in reply
|
| 354 |
+
action_match = TOOL_RE.search(reply)
|
| 355 |
+
|
| 356 |
+
if not action_match:
|
| 357 |
+
# Pure text response - stream it
|
| 358 |
+
full_response += reply
|
| 359 |
+
events.append({"type": "token", "text": reply})
|
| 360 |
+
|
| 361 |
+
# If finish_reason is stop and no more actions, we're done
|
| 362 |
+
if finish == "stop":
|
| 363 |
+
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
continue
|
| 365 |
+
|
| 366 |
+
# Text before the ACTION line
|
| 367 |
+
action_pos = reply.rfind("ACTION:")
|
| 368 |
+
pre_text = reply[:action_pos].rstrip()
|
| 369 |
+
if pre_text:
|
| 370 |
+
full_response += pre_text + "\n"
|
| 371 |
+
events.append({"type": "token", "text": pre_text + "\n"})
|
| 372 |
+
|
| 373 |
+
tool_name = action_match.group(1)
|
| 374 |
+
args_str = action_match.group(2)
|
| 375 |
+
|
| 376 |
+
# Emit tool_start
|
| 377 |
+
events.append({"type": "tool_start", "tool": tool_name, "args": {
|
| 378 |
+
"args": args_str[:200] if len(args_str) > 200 else args_str
|
| 379 |
+
}})
|
| 380 |
+
|
| 381 |
# Execute tool
|
| 382 |
+
result = execute_tool(tool_name, args_str)
|
| 383 |
+
result_short = result[:2000]
|
| 384 |
+
|
| 385 |
+
events.append({"type": "tool_result", "tool": tool_name, "result": result_short})
|
| 386 |
+
|
| 387 |
+
# Add to conversation context
|
| 388 |
+
assistant_turn = reply + f"\n[RESULT: {result_short}]"
|
| 389 |
+
msgs.append({"role": "assistant", "content": assistant_turn})
|
| 390 |
+
msgs.append({"role": "user", "content": "Continue."})
|
| 391 |
+
|
| 392 |
+
full_response += f"[Tool: {tool_name}] {result_short[:100]}\n"
|
| 393 |
+
|
| 394 |
+
events.append({"type": "done", "full": full_response})
|
|
|
|
|
|
|
| 395 |
return events
|
| 396 |
|
| 397 |
|
| 398 |
+
async def stream_agent(message, history):
|
| 399 |
import asyncio
|
| 400 |
loop = asyncio.get_event_loop()
|
| 401 |
events = await loop.run_in_executor(None, run_agent_sync, message, history)
|
| 402 |
for ev in events:
|
| 403 |
+
yield f"data: {json.dumps(ev)}\n\n"
|
| 404 |
|
| 405 |
|
| 406 |
+
# ββ FastAPI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 407 |
+
app = FastAPI(title="Android Build Agent")
|
| 408 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 409 |
+
|
| 410 |
+
HTML = r"""<!DOCTYPE html>
|
| 411 |
<html>
|
| 412 |
<head>
|
| 413 |
+
<title>AI Agent</title>
|
| 414 |
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 415 |
<style>
|
| 416 |
*{box-sizing:border-box;margin:0;padding:0}
|
| 417 |
body{font-family:'Segoe UI',system-ui,sans-serif;background:#0d1117;color:#e6edf3;height:100vh;display:flex;flex-direction:column}
|
| 418 |
+
#hdr{padding:12px 18px;background:#161b22;border-bottom:1px solid #30363d;display:flex;align-items:center;gap:10px;flex-wrap:wrap}
|
| 419 |
#hdr h1{font-size:16px;color:#58a6ff;font-weight:700}
|
| 420 |
.badge{font-size:11px;background:#1f6feb22;color:#58a6ff;border:1px solid #1f6feb55;padding:2px 8px;border-radius:10px}
|
| 421 |
+
.dot{width:8px;height:8px;background:#3fb950;border-radius:50%;flex-shrink:0;animation:pulse 2s infinite}
|
| 422 |
+
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}
|
| 423 |
+
#chat{flex:1;overflow-y:auto;padding:14px 16px;display:flex;flex-direction:column;gap:8px}
|
| 424 |
.msg{max-width:82%;padding:10px 14px;border-radius:12px;line-height:1.6;white-space:pre-wrap;word-wrap:break-word;font-size:14px}
|
| 425 |
.user{align-self:flex-end;background:#1f6feb;color:#fff;border-radius:12px 12px 2px 12px}
|
| 426 |
.bot{align-self:flex-start;background:#161b22;border:1px solid #30363d;border-radius:2px 12px 12px 12px}
|
| 427 |
+
.tc{align-self:flex-start;max-width:88%;background:#0d1f3c;border:1px solid #1f6feb55;border-radius:8px;padding:8px 12px;font-size:12px;font-family:monospace}
|
| 428 |
+
.tr{align-self:flex-start;max-width:88%;background:#071a07;border:1px solid #3fb95055;border-radius:8px;padding:8px 12px;font-size:12px;font-family:monospace;max-height:180px;overflow-y:auto}
|
| 429 |
+
.lbl{font-size:10px;color:#8b949e;margin-bottom:3px;text-transform:uppercase;letter-spacing:.5px}
|
| 430 |
+
#bot-area{padding:10px 14px;background:#161b22;border-top:1px solid #30363d}
|
|
|
|
| 431 |
#row{display:flex;gap:8px;align-items:flex-end}
|
| 432 |
#inp{flex:1;background:#0d1117;border:1px solid #30363d;border-radius:8px;color:#e6edf3;padding:10px 14px;font-size:14px;resize:none;min-height:44px;max-height:120px;outline:none;font-family:inherit}
|
| 433 |
#inp:focus{border-color:#58a6ff}
|
| 434 |
+
#btn{background:#1f6feb;color:#fff;border:none;border-radius:8px;padding:10px 16px;cursor:pointer;font-size:14px;font-weight:600;height:44px}
|
| 435 |
#btn:hover{background:#388bfd}
|
| 436 |
#btn:disabled{background:#21262d;color:#555;cursor:not-allowed}
|
| 437 |
+
.hint{font-size:11px;color:#6e7681;margin-top:6px}
|
| 438 |
</style>
|
| 439 |
</head>
|
| 440 |
<body>
|
| 441 |
<div id="hdr">
|
| 442 |
<div class="dot"></div>
|
| 443 |
+
<h1>π€ AI Agent</h1>
|
| 444 |
<span class="badge">Qwen2.5-Coder</span>
|
| 445 |
+
<span class="badge">11 Tools</span>
|
| 446 |
+
<span class="badge">Linux Container</span>
|
| 447 |
</div>
|
| 448 |
<div id="chat">
|
| 449 |
+
<div class="msg bot">Namaste! Main ek AI Agent hoon jo Linux container mein run ho raha hoon.
|
| 450 |
|
| 451 |
Mere paas ye tools hain:
|
| 452 |
+
π write_file, read_file, edit_file, delete_file, list_files
|
| 453 |
+
β‘ run β koi bhi shell command (python, pip, curl, etc.)
|
| 454 |
+
π¦ git_clone β GitHub repo clone
|
| 455 |
+
ποΈ gradle_build β Android APK build
|
| 456 |
+
π web_search β DuckDuckGo
|
| 457 |
+
π read_url β URL content
|
| 458 |
+
β¬οΈ download_file β file download
|
| 459 |
+
|
| 460 |
+
Mujhe kuch bhi banane, chalane, ya dhundhne ko kaho!</div>
|
| 461 |
</div>
|
| 462 |
<div id="bot-area">
|
| 463 |
<div id="row">
|
| 464 |
+
<textarea id="inp" placeholder="e.g. Python se chess game banao aur gofile par upload karo" rows="1"></textarea>
|
| 465 |
<button id="btn" onclick="send()">Send β€</button>
|
| 466 |
</div>
|
| 467 |
+
<div class="hint">π‘ Try: "Python se chess ka game banao" | "Search for Android tutorial" | "List files" | "pip install requests aur test karo"</div>
|
| 468 |
</div>
|
| 469 |
<script>
|
| 470 |
const chat=document.getElementById('chat'),inp=document.getElementById('inp'),btn=document.getElementById('btn');
|
| 471 |
let history=[];
|
|
|
|
| 472 |
inp.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send()}});
|
| 473 |
inp.addEventListener('input',()=>{inp.style.height='auto';inp.style.height=Math.min(inp.scrollHeight,120)+'px'});
|
|
|
|
| 474 |
function sc(){chat.scrollTop=chat.scrollHeight}
|
| 475 |
+
function mkEl(cls,html,par){const e=document.createElement('div');e.className=cls;if(html)e.innerHTML=html;(par||chat).appendChild(e);sc();return e}
|
| 476 |
|
| 477 |
async function send(){
|
| 478 |
+
const msg=inp.value.trim();if(!msg||btn.disabled)return;
|
| 479 |
+
mkEl('msg user','').textContent=msg;
|
|
|
|
| 480 |
inp.value='';inp.style.height='auto';btn.disabled=true;
|
| 481 |
+
const bd=mkEl('msg bot','');bd.textContent='β³ Thinking...';
|
| 482 |
+
let botTxt='',firstTok=true,curTool=null;
|
|
|
|
|
|
|
| 483 |
try{
|
| 484 |
const r=await fetch('/chat',{method:'POST',headers:{'Content-Type':'application/json'},
|
| 485 |
body:JSON.stringify({message:msg,history})});
|
| 486 |
if(!r.ok)throw new Error('HTTP '+r.status);
|
|
|
|
| 487 |
const reader=r.body.getReader(),dec=new TextDecoder();
|
| 488 |
let buf='';
|
|
|
|
| 489 |
while(true){
|
| 490 |
+
const{done,value}=await reader.read();if(done)break;
|
|
|
|
| 491 |
buf+=dec.decode(value,{stream:true});
|
| 492 |
const lines=buf.split('\n');buf=lines.pop();
|
|
|
|
| 493 |
for(const line of lines){
|
| 494 |
if(!line.startsWith('data: '))continue;
|
| 495 |
let d;try{d=JSON.parse(line.slice(6))}catch{continue}
|
|
|
|
| 496 |
if(d.type==='token'){
|
| 497 |
if(firstTok){bd.textContent='';firstTok=false}
|
| 498 |
botTxt+=d.text;bd.textContent=botTxt;sc();
|
| 499 |
}else if(d.type==='tool_start'){
|
| 500 |
if(firstTok){bd.textContent='';firstTok=false}
|
| 501 |
+
const args=typeof d.args==='object'?JSON.stringify(d.args.args||d.args,null,1):String(d.args);
|
| 502 |
+
curTool=mkEl('tc','<div class="lbl">π§ Tool Call</div><b>'+d.tool+'</b><br><span style="color:#8b949e;font-size:11px">'+args.replace(/</g,'<').substring(0,300)+'</span>');
|
|
|
|
| 503 |
botTxt='';bd.textContent='';
|
| 504 |
}else if(d.type==='tool_result'){
|
| 505 |
+
if(curTool){const tr=mkEl('tr','<div class="lbl">β
Result: '+d.tool+'</div>',null);tr.firstChild.insertAdjacentText('afterend',(d.result||'').substring(0,1000).replace(/</g,'<'));chat.appendChild(tr);sc();}
|
| 506 |
+
curTool=null;
|
| 507 |
+
const nb=mkEl('msg bot','');nb.textContent='';
|
|
|
|
|
|
|
|
|
|
| 508 |
Object.defineProperty(bd,'textContent',{get:()=>nb.textContent,set:v=>{nb.textContent=v}});
|
| 509 |
botTxt='';firstTok=false;
|
| 510 |
}else if(d.type==='error'){
|
|
|
|
| 515 |
}
|
| 516 |
}
|
| 517 |
}catch(e){bd.textContent='β '+e.message}
|
| 518 |
+
if(bd.textContent==='β³ Thinking...')bd.textContent='(done)';
|
|
|
|
| 519 |
btn.disabled=false;inp.focus();
|
| 520 |
}
|
| 521 |
</script>
|
| 522 |
</body></html>"""
|
| 523 |
|
|
|
|
| 524 |
@app.get("/", response_class=HTMLResponse)
|
| 525 |
+
async def root(): return HTMLResponse(HTML)
|
|
|
|
|
|
|
| 526 |
|
| 527 |
@app.post("/chat")
|
| 528 |
async def chat_ep(request: Request):
|
| 529 |
body = await request.json()
|
| 530 |
+
msg = body.get("message","").strip()
|
| 531 |
+
hist = body.get("history",[])
|
| 532 |
+
if not msg: return JSONResponse({"error":"empty"},status_code=400)
|
| 533 |
+
return StreamingResponse(stream_agent(msg,hist),
|
|
|
|
|
|
|
| 534 |
media_type="text/event-stream",
|
| 535 |
+
headers={"Cache-Control":"no-cache","X-Accel-Buffering":"no"})
|
|
|
|
|
|
|
| 536 |
|
| 537 |
@app.get("/health")
|
| 538 |
+
async def health(): return {"status":"ok","tools":list(TOOLS.keys())}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 539 |
|
| 540 |
+
if __name__=="__main__":
|
| 541 |
import uvicorn
|
| 542 |
uvicorn.run(app, host="0.0.0.0", port=7860, timeout_keep_alive=300)
|