Spaces:
Runtime error
Runtime error
Fix: retry logic in web_search, tool loop prevention, cleaner system prompt
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import os, re, json, shutil, subprocess, glob, traceback
|
| 2 |
from pathlib import Path
|
| 3 |
from typing import AsyncGenerator
|
| 4 |
|
|
@@ -38,7 +38,8 @@ llm = Llama(
|
|
| 38 |
)
|
| 39 |
print("Model ready!")
|
| 40 |
|
| 41 |
-
# ββ tools ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 42 |
def _safe(p: str) -> Path:
|
| 43 |
path = (WORKSPACE / p).resolve()
|
| 44 |
if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
|
|
@@ -86,10 +87,7 @@ def tool_delete_file(path: str) -> str:
|
|
| 86 |
def tool_list_files(path: str = ".") -> str:
|
| 87 |
try:
|
| 88 |
base = _safe(path)
|
| 89 |
-
files = []
|
| 90 |
-
for f in sorted(base.rglob("*")):
|
| 91 |
-
if f.is_file():
|
| 92 |
-
files.append(str(f.relative_to(WORKSPACE)))
|
| 93 |
return "\n".join(files[:200]) if files else "No files found"
|
| 94 |
except Exception as e:
|
| 95 |
return f"ERROR: {e}"
|
|
@@ -114,11 +112,11 @@ def tool_run_command(command: str, working_dir: str = ".") -> str:
|
|
| 114 |
command, cwd=cwd, shell=True,
|
| 115 |
capture_output=True, text=True, timeout=300
|
| 116 |
)
|
| 117 |
-
out = proc.stdout[-2000:]
|
| 118 |
-
err = proc.stderr[-1000:]
|
| 119 |
-
return f"exit={proc.returncode}\nSTDOUT:
|
| 120 |
except subprocess.TimeoutExpired:
|
| 121 |
-
return "ERROR:
|
| 122 |
except Exception as e:
|
| 123 |
return f"ERROR: {e}"
|
| 124 |
|
|
@@ -144,14 +142,24 @@ def tool_gradle_build(repo: str, task: str = "assembleDebug") -> str:
|
|
| 144 |
def tool_web_search(query: str, max_results: int = 5) -> str:
|
| 145 |
if not HAS_DDG:
|
| 146 |
return "ERROR: duckduckgo-search not available"
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
def tool_read_url(url: str) -> str:
|
| 157 |
try:
|
|
@@ -166,16 +174,16 @@ def tool_read_url(url: str) -> str:
|
|
| 166 |
return f"ERROR: {e}"
|
| 167 |
|
| 168 |
TOOLS = {
|
| 169 |
-
"read_file": {"fn": tool_read_file, "desc": "Read file from workspace",
|
| 170 |
-
"write_file": {"fn": tool_write_file, "desc": "Write/create file in workspace",
|
| 171 |
-
"edit_file": {"fn": tool_edit_file, "desc": "Find & replace text in file",
|
| 172 |
-
"delete_file": {"fn": tool_delete_file, "desc": "Delete file or directory",
|
| 173 |
-
"list_files": {"fn": tool_list_files, "desc": "List files in workspace",
|
| 174 |
-
"git_clone": {"fn": tool_git_clone, "desc": "Clone a git repo into workspace",
|
| 175 |
-
"run_command": {"fn": tool_run_command, "desc": "Run shell command in workspace",
|
| 176 |
-
"gradle_build": {"fn": tool_gradle_build, "desc": "Build Android APK with gradle",
|
| 177 |
-
"web_search": {"fn": tool_web_search, "desc": "Search web with DuckDuckGo",
|
| 178 |
-
"read_url": {"fn": tool_read_url, "desc": "Fetch and read content from
|
| 179 |
}
|
| 180 |
|
| 181 |
TOOLS_LIST = "\n".join([
|
|
@@ -183,20 +191,20 @@ TOOLS_LIST = "\n".join([
|
|
| 183 |
for name, info in TOOLS.items()
|
| 184 |
])
|
| 185 |
|
| 186 |
-
SYSTEM_PROMPT = f"""You are an Android build agent. You MUST use tools for
|
| 187 |
|
| 188 |
-
|
| 189 |
{TOOLS_LIST}
|
| 190 |
|
| 191 |
-
TOOL CALL FORMAT
|
| 192 |
-
<tool>{{"name": "tool_name", "args": {{"
|
| 193 |
|
| 194 |
-
RULES:
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
"""
|
| 201 |
|
| 202 |
TOOL_RE = re.compile(r'<tool>(.*?)</tool>', re.DOTALL)
|
|
@@ -205,24 +213,24 @@ app = FastAPI(title="Android Build Agent")
|
|
| 205 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 206 |
|
| 207 |
|
| 208 |
-
def llm_generate(msgs, max_tokens=
|
| 209 |
-
"""
|
| 210 |
out = llm.create_chat_completion(
|
| 211 |
messages=msgs,
|
| 212 |
temperature=0.2,
|
| 213 |
max_tokens=max_tokens,
|
| 214 |
-
stop=["</tool>"],
|
| 215 |
)
|
| 216 |
text = out["choices"][0]["message"]["content"]
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
if
|
| 220 |
text += "</tool>"
|
| 221 |
return text
|
| 222 |
|
| 223 |
|
| 224 |
-
def run_agent_sync(message: str, history: list):
|
| 225 |
-
"""
|
| 226 |
msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 227 |
for h in history:
|
| 228 |
if isinstance(h, (list, tuple)) and len(h) == 2:
|
|
@@ -230,107 +238,109 @@ def run_agent_sync(message: str, history: list):
|
|
| 230 |
if h[1]: msgs.append({"role": "assistant", "content": str(h[1])})
|
| 231 |
msgs.append({"role": "user", "content": message})
|
| 232 |
|
| 233 |
-
full_response = ""
|
| 234 |
events = []
|
|
|
|
|
|
|
| 235 |
|
| 236 |
for step in range(8):
|
| 237 |
-
reply = llm_generate(msgs, max_tokens=
|
| 238 |
|
| 239 |
-
# Check for tool call
|
| 240 |
tool_match = TOOL_RE.search(reply)
|
| 241 |
|
| 242 |
if not tool_match:
|
| 243 |
-
# Pure text
|
| 244 |
full_response += reply
|
| 245 |
events.append(json.dumps({"type": "token", "text": reply}))
|
| 246 |
break
|
| 247 |
|
| 248 |
# Text before tool call
|
| 249 |
-
|
| 250 |
-
if
|
| 251 |
-
full_response +=
|
| 252 |
-
events.append(json.dumps({"type": "token", "text":
|
| 253 |
|
| 254 |
-
#
|
| 255 |
try:
|
| 256 |
call = json.loads(tool_match.group(1))
|
| 257 |
tool_name = call.get("name", "")
|
| 258 |
tool_args = call.get("args", {})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
tool_result = f"Tool error: {e}\n{traceback.format_exc()[-300:]}"
|
| 268 |
-
events.append(json.dumps({"type": "tool_result", "tool": tool_name, "result": str(tool_result)[:2000]}))
|
| 269 |
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
| 275 |
msgs.append({"role": "assistant", "content": reply})
|
| 276 |
-
msgs.append({"role": "user", "content": f"[Tool
|
| 277 |
-
full_response += f"[
|
| 278 |
|
| 279 |
events.append(json.dumps({"type": "done", "full": full_response}))
|
| 280 |
return events
|
| 281 |
|
| 282 |
|
| 283 |
async def stream_agent(message: str, history: list) -> AsyncGenerator[str, None]:
|
| 284 |
-
"""Run agent in thread, stream events."""
|
| 285 |
import asyncio
|
| 286 |
loop = asyncio.get_event_loop()
|
| 287 |
-
|
| 288 |
-
# Run sync agent in executor
|
| 289 |
events = await loop.run_in_executor(None, run_agent_sync, message, history)
|
|
|
|
|
|
|
| 290 |
|
| 291 |
-
for event in events:
|
| 292 |
-
yield f"data: {event}\n\n"
|
| 293 |
|
| 294 |
-
|
| 295 |
-
@app.get("/", response_class=HTMLResponse)
|
| 296 |
-
async def root():
|
| 297 |
-
html = r"""<!DOCTYPE html>
|
| 298 |
<html>
|
| 299 |
<head>
|
| 300 |
<title>Android Build Agent</title>
|
| 301 |
-
<meta name="viewport" content="width=device-width,
|
| 302 |
<style>
|
| 303 |
-
*
|
| 304 |
-
body
|
| 305 |
-
#
|
| 306 |
-
#
|
| 307 |
-
.badge
|
| 308 |
-
.
|
| 309 |
-
#chat
|
| 310 |
-
.msg
|
| 311 |
-
.user
|
| 312 |
-
.bot
|
| 313 |
-
.tool-
|
| 314 |
-
.
|
| 315 |
-
.
|
| 316 |
-
.
|
| 317 |
-
|
| 318 |
-
#
|
| 319 |
-
#
|
| 320 |
-
#
|
| 321 |
-
#
|
| 322 |
-
#
|
| 323 |
-
#
|
| 324 |
-
|
| 325 |
-
.tools-hint { font-size: 11px; color: #8b949e; margin-top: 6px; }
|
| 326 |
</style>
|
| 327 |
</head>
|
| 328 |
<body>
|
| 329 |
-
<div id="
|
| 330 |
-
<div class="
|
| 331 |
<h1>π€ Android Build Agent</h1>
|
| 332 |
-
<span class="badge">Qwen2.5-Coder
|
| 333 |
<span class="badge">10 Tools</span>
|
|
|
|
| 334 |
</div>
|
| 335 |
<div id="chat">
|
| 336 |
<div class="msg bot">Namaste! Main Android Build Agent hoon π€
|
|
@@ -338,159 +348,105 @@ body { font-family: 'Segoe UI', system-ui, sans-serif; background: #0d1117; colo
|
|
| 338 |
Mere paas ye tools hain:
|
| 339 |
π read_file, write_file, edit_file, delete_file, list_files
|
| 340 |
π¦ git_clone β GitHub repo clone karo
|
| 341 |
-
βοΈ
|
| 342 |
-
ποΈ
|
| 343 |
-
π web_search β DuckDuckGo search
|
| 344 |
-
π read_url β URL ka content padho
|
| 345 |
|
| 346 |
-
|
| 347 |
</div>
|
| 348 |
-
<div id="
|
| 349 |
<div id="row">
|
| 350 |
-
<textarea id="
|
| 351 |
-
<button id="
|
| 352 |
</div>
|
| 353 |
-
<div class="
|
| 354 |
</div>
|
| 355 |
<script>
|
| 356 |
-
const
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
}
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
inputEl.value = '';
|
| 406 |
-
inputEl.style.height = 'auto';
|
| 407 |
-
sendBtn.disabled = true;
|
| 408 |
-
|
| 409 |
-
const botDiv = addMsg('bot', 'β³ Processing...');
|
| 410 |
-
botDiv.classList.add('thinking');
|
| 411 |
-
let botText = '';
|
| 412 |
-
let currentToolBox = null;
|
| 413 |
-
let firstContent = true;
|
| 414 |
-
|
| 415 |
-
try {
|
| 416 |
-
const resp = await fetch('/chat', {
|
| 417 |
-
method: 'POST',
|
| 418 |
-
headers: {'Content-Type': 'application/json'},
|
| 419 |
-
body: JSON.stringify({message: msg, history: history})
|
| 420 |
-
});
|
| 421 |
-
|
| 422 |
-
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
| 423 |
-
|
| 424 |
-
const reader = resp.body.getReader();
|
| 425 |
-
const dec = new TextDecoder();
|
| 426 |
-
let buf = '';
|
| 427 |
-
|
| 428 |
-
while (true) {
|
| 429 |
-
const {done, value} = await reader.read();
|
| 430 |
-
if (done) break;
|
| 431 |
-
buf += dec.decode(value, {stream: true});
|
| 432 |
-
const lines = buf.split('\n');
|
| 433 |
-
buf = lines.pop();
|
| 434 |
-
|
| 435 |
-
for (const line of lines) {
|
| 436 |
-
if (!line.startsWith('data: ')) continue;
|
| 437 |
-
let data;
|
| 438 |
-
try { data = JSON.parse(line.slice(6)); } catch { continue; }
|
| 439 |
-
|
| 440 |
-
if (data.type === 'token') {
|
| 441 |
-
if (firstContent) {
|
| 442 |
-
botDiv.classList.remove('thinking');
|
| 443 |
-
botDiv.textContent = '';
|
| 444 |
-
firstContent = false;
|
| 445 |
}
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
} else if (data.type === 'tool_result') {
|
| 455 |
-
if (currentToolBox) addToolResult(currentToolBox, data.tool, data.result);
|
| 456 |
-
currentToolBox = null;
|
| 457 |
-
// New bot div for next text
|
| 458 |
-
const newBotDiv = addEl('div', 'msg bot');
|
| 459 |
-
newBotDiv.textContent = '';
|
| 460 |
-
Object.assign(botDiv, {remove: () => {}});
|
| 461 |
-
} else if (data.type === 'error') {
|
| 462 |
-
botDiv.classList.remove('thinking');
|
| 463 |
-
botDiv.textContent = 'β ' + data.text;
|
| 464 |
-
} else if (data.type === 'done') {
|
| 465 |
-
history.push([msg, data.full]);
|
| 466 |
}
|
| 467 |
}
|
| 468 |
}
|
| 469 |
-
}
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
if (botDiv.textContent === 'β³ Processing...') botDiv.textContent = '(done)';
|
| 475 |
-
botDiv.classList.remove('thinking');
|
| 476 |
-
sendBtn.disabled = false;
|
| 477 |
-
inputEl.focus();
|
| 478 |
}
|
| 479 |
</script>
|
| 480 |
-
</body>
|
| 481 |
-
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
| 483 |
|
| 484 |
|
| 485 |
@app.post("/chat")
|
| 486 |
-
async def
|
| 487 |
body = await request.json()
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
if not
|
| 491 |
return JSONResponse({"error": "Empty message"}, status_code=400)
|
| 492 |
return StreamingResponse(
|
| 493 |
-
stream_agent(
|
| 494 |
media_type="text/event-stream",
|
| 495 |
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
| 496 |
)
|
|
@@ -502,7 +458,7 @@ async def health():
|
|
| 502 |
|
| 503 |
|
| 504 |
@app.get("/tools")
|
| 505 |
-
async def
|
| 506 |
return {n: {"description": i["desc"], "params": i["params"]} for n, i in TOOLS.items()}
|
| 507 |
|
| 508 |
|
|
|
|
| 1 |
+
import os, re, json, shutil, subprocess, glob, traceback, time
|
| 2 |
from pathlib import Path
|
| 3 |
from typing import AsyncGenerator
|
| 4 |
|
|
|
|
| 38 |
)
|
| 39 |
print("Model ready!")
|
| 40 |
|
| 41 |
+
# ββ tools βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
+
|
| 43 |
def _safe(p: str) -> Path:
|
| 44 |
path = (WORKSPACE / p).resolve()
|
| 45 |
if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
|
|
|
|
| 87 |
def tool_list_files(path: str = ".") -> str:
|
| 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[:200]) if files else "No files found"
|
| 92 |
except Exception as e:
|
| 93 |
return f"ERROR: {e}"
|
|
|
|
| 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 |
|
|
|
|
| 142 |
def tool_web_search(query: str, max_results: int = 5) -> str:
|
| 143 |
if not HAS_DDG:
|
| 144 |
return "ERROR: duckduckgo-search not available"
|
| 145 |
+
for attempt in range(3):
|
| 146 |
+
try:
|
| 147 |
+
if attempt > 0:
|
| 148 |
+
time.sleep(2 * attempt)
|
| 149 |
+
results = []
|
| 150 |
+
with DDGS() as ddgs:
|
| 151 |
+
for r in ddgs.text(query, max_results=int(max_results)):
|
| 152 |
+
results.append(
|
| 153 |
+
f"Title: {r.get('title','')}\n"
|
| 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 == 2:
|
| 161 |
+
return f"Search failed after 3 attempts: {e}"
|
| 162 |
+
return "No results found"
|
| 163 |
|
| 164 |
def tool_read_url(url: str) -> str:
|
| 165 |
try:
|
|
|
|
| 174 |
return f"ERROR: {e}"
|
| 175 |
|
| 176 |
TOOLS = {
|
| 177 |
+
"read_file": {"fn": tool_read_file, "desc": "Read file from workspace", "params": {"path": "file path"}},
|
| 178 |
+
"write_file": {"fn": tool_write_file, "desc": "Write/create file in workspace", "params": {"path": "file path", "content": "text content"}},
|
| 179 |
+
"edit_file": {"fn": tool_edit_file, "desc": "Find & replace text in file", "params": {"path": "file path", "find": "text to find", "replace": "replacement"}},
|
| 180 |
+
"delete_file": {"fn": tool_delete_file, "desc": "Delete file or directory", "params": {"path": "path"}},
|
| 181 |
+
"list_files": {"fn": tool_list_files, "desc": "List files in workspace", "params": {"path": "directory (default '.')"}},
|
| 182 |
+
"git_clone": {"fn": tool_git_clone, "desc": "Clone a git repo into workspace", "params": {"url": "git URL", "dest": "folder name (optional)"}},
|
| 183 |
+
"run_command": {"fn": tool_run_command, "desc": "Run shell command in workspace", "params": {"command": "shell command", "working_dir": "directory (default '.')"}},
|
| 184 |
+
"gradle_build": {"fn": tool_gradle_build, "desc": "Build Android APK with gradle", "params": {"repo": "repo folder name", "task": "gradle task (default assembleDebug)"}},
|
| 185 |
+
"web_search": {"fn": tool_web_search, "desc": "Search web with DuckDuckGo", "params": {"query": "search query", "max_results": "count (default 5)"}},
|
| 186 |
+
"read_url": {"fn": tool_read_url, "desc": "Fetch and read content from URL", "params": {"url": "full URL"}},
|
| 187 |
}
|
| 188 |
|
| 189 |
TOOLS_LIST = "\n".join([
|
|
|
|
| 191 |
for name, info in TOOLS.items()
|
| 192 |
])
|
| 193 |
|
| 194 |
+
SYSTEM_PROMPT = f"""You are an Android build agent with tools. You MUST use tools for practical tasks.
|
| 195 |
|
| 196 |
+
TOOLS AVAILABLE:
|
| 197 |
{TOOLS_LIST}
|
| 198 |
|
| 199 |
+
TOOL CALL FORMAT (use EXACTLY this syntax):
|
| 200 |
+
<tool>{{"name": "tool_name", "args": {{"param": "value"}}}}</tool>
|
| 201 |
|
| 202 |
+
IMPORTANT RULES:
|
| 203 |
+
1. Use tools for EVERY practical request (build, search, clone, files, etc.)
|
| 204 |
+
2. If a tool fails, try a DIFFERENT approach - do NOT retry the same call
|
| 205 |
+
3. Keep text responses SHORT - action first, explanation after
|
| 206 |
+
4. For APK builds: git_clone β list_files β gradle_build
|
| 207 |
+
5. You have FULL PERMISSION to use all tools listed above
|
| 208 |
"""
|
| 209 |
|
| 210 |
TOOL_RE = re.compile(r'<tool>(.*?)</tool>', re.DOTALL)
|
|
|
|
| 213 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 214 |
|
| 215 |
|
| 216 |
+
def llm_generate(msgs: list, max_tokens: int = 600) -> str:
|
| 217 |
+
"""Run LLM, stop after </tool> so we can execute tools immediately."""
|
| 218 |
out = llm.create_chat_completion(
|
| 219 |
messages=msgs,
|
| 220 |
temperature=0.2,
|
| 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:
|
|
|
|
| 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 |
+
used_tools = set() # prevent infinite loops
|
| 244 |
|
| 245 |
for step in range(8):
|
| 246 |
+
reply = llm_generate(msgs, max_tokens=600)
|
| 247 |
|
|
|
|
| 248 |
tool_match = TOOL_RE.search(reply)
|
| 249 |
|
| 250 |
if not tool_match:
|
| 251 |
+
# Pure text
|
| 252 |
full_response += reply
|
| 253 |
events.append(json.dumps({"type": "token", "text": reply}))
|
| 254 |
break
|
| 255 |
|
| 256 |
# Text before tool call
|
| 257 |
+
pre = reply[:reply.index("<tool>")].strip()
|
| 258 |
+
if pre:
|
| 259 |
+
full_response += pre + "\n"
|
| 260 |
+
events.append(json.dumps({"type": "token", "text": pre + "\n"}))
|
| 261 |
|
| 262 |
+
# Parse tool call
|
| 263 |
try:
|
| 264 |
call = json.loads(tool_match.group(1))
|
| 265 |
tool_name = call.get("name", "")
|
| 266 |
tool_args = call.get("args", {})
|
| 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 |
+
events.append(json.dumps({"type": "tool_start", "tool": tool_name, "args": tool_args}))
|
| 282 |
+
try:
|
| 283 |
+
tool_result = TOOLS[tool_name]["fn"](**tool_args)
|
| 284 |
+
except Exception as e:
|
| 285 |
+
tool_result = f"Tool execution error: {e}\n{traceback.format_exc()[-300:]}"
|
| 286 |
|
| 287 |
+
result_str = str(tool_result)[:2000]
|
| 288 |
+
events.append(json.dumps({"type": "tool_result", "tool": tool_name, "result": result_str}))
|
| 289 |
+
|
| 290 |
+
# Add to conversation
|
| 291 |
msgs.append({"role": "assistant", "content": reply})
|
| 292 |
+
msgs.append({"role": "user", "content": f"[Tool '{tool_name}' result]:\n{result_str}\n\nContinue. If successful, summarize. If failed, try different approach."})
|
| 293 |
+
full_response += f"[Tool: {tool_name}]\n"
|
| 294 |
|
| 295 |
events.append(json.dumps({"type": "done", "full": full_response}))
|
| 296 |
return events
|
| 297 |
|
| 298 |
|
| 299 |
async def stream_agent(message: str, history: list) -> AsyncGenerator[str, None]:
|
|
|
|
| 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 |
+
HTML_PAGE = r"""<!DOCTYPE html>
|
|
|
|
|
|
|
|
|
|
| 308 |
<html>
|
| 309 |
<head>
|
| 310 |
<title>Android Build Agent</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 20px;background:#161b22;border-bottom:1px solid #30363d;display:flex;align-items:center;gap:10px}
|
| 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 |
+
#chat{flex:1;overflow-y:auto;padding:14px 18px;display:flex;flex-direction:column;gap:8px}
|
| 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 |
+
.tool-wrap{align-self:flex-start;width:90%;max-width:700px}
|
| 324 |
+
.tc{background:#0d1f3c;border:1px solid #1f6feb44;border-radius:8px;padding:8px 12px;font-size:12px;font-family:monospace;margin-bottom:3px}
|
| 325 |
+
.tr{background:#071a07;border:1px solid #3fb95044;border-radius:8px;padding:8px 12px;font-size:12px;font-family:monospace;max-height:160px;overflow-y:auto}
|
| 326 |
+
.lbl{font-size:10px;color:#8b949e;margin-bottom:3px;letter-spacing:.5px;text-transform:uppercase}
|
| 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;white-space:nowrap}
|
| 332 |
+
#btn:hover{background:#388bfd}
|
| 333 |
+
#btn:disabled{background:#21262d;color:#555;cursor:not-allowed}
|
| 334 |
+
.hint{font-size:11px;color:#8b949e;margin-top:6px}
|
|
|
|
| 335 |
</style>
|
| 336 |
</head>
|
| 337 |
<body>
|
| 338 |
+
<div id="hdr">
|
| 339 |
+
<div class="dot"></div>
|
| 340 |
<h1>π€ Android Build Agent</h1>
|
| 341 |
+
<span class="badge">Qwen2.5-Coder</span>
|
| 342 |
<span class="badge">10 Tools</span>
|
| 343 |
+
<span class="badge">Streaming</span>
|
| 344 |
</div>
|
| 345 |
<div id="chat">
|
| 346 |
<div class="msg bot">Namaste! Main Android Build Agent hoon π€
|
|
|
|
| 348 |
Mere paas ye tools hain:
|
| 349 |
π read_file, write_file, edit_file, delete_file, list_files
|
| 350 |
π¦ git_clone β GitHub repo clone karo
|
| 351 |
+
βοΈ run_command β koi bhi shell command chalao
|
| 352 |
+
ποΈ gradle_build β Android APK build karo
|
| 353 |
+
π web_search β DuckDuckGo search karo
|
| 354 |
+
π read_url β kisi URL ka content padho
|
| 355 |
|
| 356 |
+
Sabhi tools use karne ki FULL PERMISSION hai. Batao kya karna hai!</div>
|
| 357 |
</div>
|
| 358 |
+
<div id="bot-area">
|
| 359 |
<div id="row">
|
| 360 |
+
<textarea id="inp" placeholder="Message likhein... (Enter=send, Shift+Enter=newline)" rows="1"></textarea>
|
| 361 |
+
<button id="btn" onclick="send()">Send β€</button>
|
| 362 |
</div>
|
| 363 |
+
<div class="hint">π‘ "Search Android Compose docs" | "Clone https://github.com/β¦ and build APK" | "List files in workspace"</div>
|
| 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 el(tag,cls,par){const e=document.createElement(tag);e.className=cls;(par||chat).appendChild(e);sc();return e}
|
| 374 |
+
|
| 375 |
+
async function send(){
|
| 376 |
+
const msg=inp.value.trim();
|
| 377 |
+
if(!msg||btn.disabled)return;
|
| 378 |
+
const um=el('div','msg user');um.textContent=msg;
|
| 379 |
+
inp.value='';inp.style.height='auto';btn.disabled=true;
|
| 380 |
+
|
| 381 |
+
const bd=el('div','msg bot');bd.textContent='β³ Processing...';
|
| 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 |
+
toolBox=el('div','tool-wrap');
|
| 408 |
+
const tc=el('div','tc',toolBox);
|
| 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(toolBox){
|
| 413 |
+
const tr=el('div','tr',toolBox);
|
| 414 |
+
tr.innerHTML='<div class="lbl">β
Result: '+d.tool+'</div>'+(d.result||'').substring(0,1000).replace(/</g,'<');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'){
|
| 421 |
+
bd.textContent='β '+d.text;
|
| 422 |
+
}else if(d.type==='done'){
|
| 423 |
+
history.push([msg,d.full]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
}
|
| 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", "").strip()
|
| 445 |
+
hist = body.get("history", [])
|
| 446 |
+
if not msg:
|
| 447 |
return JSONResponse({"error": "Empty message"}, status_code=400)
|
| 448 |
return StreamingResponse(
|
| 449 |
+
stream_agent(msg, hist),
|
| 450 |
media_type="text/event-stream",
|
| 451 |
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
| 452 |
)
|
|
|
|
| 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 |
|