Theright07 commited on
Commit
e646bc3
Β·
verified Β·
1 Parent(s): 8829453

Fix: retry logic in web_search, tool loop prevention, cleaner system prompt

Browse files
Files changed (1) hide show
  1. app.py +198 -242
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:] if proc.stdout else ""
118
- err = proc.stderr[-1000:] if proc.stderr else ""
119
- return f"exit={proc.returncode}\nSTDOUT: {out}\nSTDERR: {err}"
120
  except subprocess.TimeoutExpired:
121
- return "ERROR: Timed out (300s)"
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
- try:
148
- results = []
149
- with DDGS() as ddgs:
150
- for r in ddgs.text(query, max_results=int(max_results)):
151
- results.append(f"Title: {r.get('title','')}\nURL: {r.get('href','')}\nSnippet: {r.get('body','')}")
152
- return "\n---\n".join(results) if results else "No results found"
153
- except Exception as e:
154
- return f"ERROR: {e}"
 
 
 
 
 
 
 
 
 
 
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", "params": {"path": "file path"}},
170
- "write_file": {"fn": tool_write_file, "desc": "Write/create file in workspace", "params": {"path": "file path", "content": "text content"}},
171
- "edit_file": {"fn": tool_edit_file, "desc": "Find & replace text in file", "params": {"path": "file path", "find": "text to find", "replace": "replacement"}},
172
- "delete_file": {"fn": tool_delete_file, "desc": "Delete file or directory", "params": {"path": "path"}},
173
- "list_files": {"fn": tool_list_files, "desc": "List files in workspace", "params": {"path": "directory (default '.')"}},
174
- "git_clone": {"fn": tool_git_clone, "desc": "Clone a git repo into workspace", "params": {"url": "git URL", "dest": "folder name (optional)"}},
175
- "run_command": {"fn": tool_run_command, "desc": "Run shell command in workspace", "params": {"command": "shell command", "working_dir": "directory (default '.')"}},
176
- "gradle_build": {"fn": tool_gradle_build, "desc": "Build Android APK with gradle", "params": {"repo": "repo folder name", "task": "gradle task (default assembleDebug)"}},
177
- "web_search": {"fn": tool_web_search, "desc": "Search web with DuckDuckGo", "params": {"query": "search query", "max_results": "count (default 5)"}},
178
- "read_url": {"fn": tool_read_url, "desc": "Fetch and read content from a URL", "params": {"url": "full URL"}},
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 any practical task.
187
 
188
- YOUR TOOLS:
189
  {TOOLS_LIST}
190
 
191
- TOOL CALL FORMAT - output EXACTLY this when calling a tool:
192
- <tool>{{"name": "tool_name", "args": {{"key": "value"}}}}</tool>
193
 
194
- RULES:
195
- - ALWAYS use tools when asked to build, search, clone, read files, etc.
196
- - Do NOT pretend. Actually call the tool.
197
- - Keep responses SHORT and ACTION-FOCUSED.
198
- - After tool result, continue with next step or summarize.
199
- - For APK build: 1) git_clone 2) list_files 3) gradle_build
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=512):
209
- """Synchronous LLM call, returns full text."""
210
  out = llm.create_chat_completion(
211
  messages=msgs,
212
  temperature=0.2,
213
  max_tokens=max_tokens,
214
- stop=["</tool>"], # stop after tool call so we can execute it
215
  )
216
  text = out["choices"][0]["message"]["content"]
217
- # If stopped due to </tool>, re-add the closing tag
218
- stop_reason = out["choices"][0].get("finish_reason", "")
219
- if stop_reason == "stop" and "<tool>" in text and "</tool>" not in text:
220
  text += "</tool>"
221
  return text
222
 
223
 
224
- def run_agent_sync(message: str, history: list):
225
- """Run agent, yield SSE events as strings."""
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=512)
238
 
239
- # Check for tool call
240
  tool_match = TOOL_RE.search(reply)
241
 
242
  if not tool_match:
243
- # Pure text response
244
  full_response += reply
245
  events.append(json.dumps({"type": "token", "text": reply}))
246
  break
247
 
248
  # Text before tool call
249
- pre_text = reply[:reply.index("<tool>")].strip()
250
- if pre_text:
251
- full_response += pre_text + "\n"
252
- events.append(json.dumps({"type": "token", "text": pre_text + "\n"}))
253
 
254
- # Execute tool
255
  try:
256
  call = json.loads(tool_match.group(1))
257
  tool_name = call.get("name", "")
258
  tool_args = call.get("args", {})
 
 
 
 
259
 
260
- if tool_name not in TOOLS:
261
- tool_result = f"Unknown tool '{tool_name}'. Use: {', '.join(TOOLS.keys())}"
262
- else:
263
- events.append(json.dumps({"type": "tool_start", "tool": tool_name, "args": tool_args}))
264
- try:
265
- tool_result = TOOLS[tool_name]["fn"](**tool_args)
266
- except Exception as e:
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
- except json.JSONDecodeError as e:
271
- tool_result = f"JSON parse error: {e} in: {tool_match.group(1)[:200]}"
272
- events.append(json.dumps({"type": "error", "text": tool_result}))
 
 
 
273
 
274
- # Add to context and continue
 
 
 
275
  msgs.append({"role": "assistant", "content": reply})
276
- msgs.append({"role": "user", "content": f"[Tool result: {tool_name}]\n{str(tool_result)[:2000]}"})
277
- full_response += f"[Used tool: {tool_name}]\n"
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, initial-scale=1">
302
  <style>
303
- * { box-sizing: border-box; margin: 0; padding: 0; }
304
- body { font-family: 'Segoe UI', system-ui, sans-serif; background: #0d1117; color: #e6edf3; height: 100vh; display: flex; flex-direction: column; }
305
- #header { padding: 14px 20px; background: #161b22; border-bottom: 1px solid #30363d; display: flex; align-items: center; gap: 10px; }
306
- #header h1 { font-size: 17px; color: #58a6ff; font-weight: 600; }
307
- .badge { font-size: 11px; background: #1f6feb22; color: #58a6ff; border: 1px solid #1f6feb44; padding: 2px 8px; border-radius: 12px; }
308
- .status-dot { width: 8px; height: 8px; background: #3fb950; border-radius: 50%; }
309
- #chat { flex: 1; overflow-y: auto; padding: 16px 20px; display: flex; flex-direction: column; gap: 10px; }
310
- .msg { max-width: 85%; padding: 10px 14px; border-radius: 12px; line-height: 1.6; white-space: pre-wrap; word-wrap: break-word; font-size: 14px; }
311
- .user { align-self: flex-end; background: #1f6feb; color: #fff; border-radius: 12px 12px 2px 12px; }
312
- .bot { align-self: flex-start; background: #161b22; border: 1px solid #30363d; border-radius: 2px 12px 12px 12px; min-width: 60px; }
313
- .tool-box { align-self: flex-start; max-width: 90%; width: 100%; }
314
- .tool-call { background: #0d1f3c; border: 1px solid #1f6feb55; border-radius: 8px; padding: 8px 12px; font-size: 12px; font-family: 'Courier New', monospace; }
315
- .tool-result { background: #0a1f0a; border: 1px solid #3fb95055; border-radius: 8px; padding: 8px 12px; font-size: 12px; font-family: 'Courier New', monospace; max-height: 180px; overflow-y: auto; margin-top: 4px; }
316
- .label { font-size: 10px; color: #8b949e; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.5px; }
317
- .thinking { color: #8b949e; font-style: italic; }
318
- #bottom { padding: 12px 20px; background: #161b22; border-top: 1px solid #30363d; }
319
- #row { display: flex; gap: 8px; align-items: flex-end; }
320
- #input { 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; }
321
- #input:focus { border-color: #58a6ff; }
322
- #send { background: #1f6feb; color: #fff; border: none; border-radius: 8px; padding: 10px 18px; cursor: pointer; font-size: 14px; font-weight: 600; white-space: nowrap; height: 44px; }
323
- #send:hover { background: #388bfd; }
324
- #send:disabled { background: #21262d; color: #8b949e; cursor: not-allowed; }
325
- .tools-hint { font-size: 11px; color: #8b949e; margin-top: 6px; }
326
  </style>
327
  </head>
328
  <body>
329
- <div id="header">
330
- <div class="status-dot"></div>
331
  <h1>πŸ€– Android Build Agent</h1>
332
- <span class="badge">Qwen2.5-Coder-1.5B</span>
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
- βš™οΈ run_command β€” koi bhi shell command
342
- πŸ—οΈ gradle_build β€” Android APK build karo
343
- πŸ” web_search β€” DuckDuckGo search
344
- 🌐 read_url β€” URL ka content padho
345
 
346
- Kya karna hai? Batao!</div>
347
  </div>
348
- <div id="bottom">
349
  <div id="row">
350
- <textarea id="input" placeholder="Message likhein... (Enter = send)" rows="1"></textarea>
351
- <button id="send" onclick="sendMsg()">Send ➀</button>
352
  </div>
353
- <div class="tools-hint">πŸ’‘ Try: "Search for Android Compose best practices" | "Clone https://github.com/... and build APK"</div>
354
  </div>
355
  <script>
356
- const chatEl = document.getElementById('chat');
357
- const inputEl = document.getElementById('input');
358
- const sendBtn = document.getElementById('send');
359
- let history = [];
360
-
361
- inputEl.addEventListener('keydown', e => {
362
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMsg(); }
363
- });
364
- inputEl.addEventListener('input', () => {
365
- inputEl.style.height = 'auto';
366
- inputEl.style.height = Math.min(inputEl.scrollHeight, 120) + 'px';
367
- });
368
-
369
- function scrollBot() { chatEl.scrollTop = chatEl.scrollHeight; }
370
-
371
- function addEl(tag, className, parent) {
372
- const el = document.createElement(tag);
373
- el.className = className;
374
- (parent || chatEl).appendChild(el);
375
- scrollBot();
376
- return el;
377
- }
378
-
379
- function addMsg(role, text) {
380
- const el = addEl('div', 'msg ' + role);
381
- el.textContent = text;
382
- return el;
383
- }
384
-
385
- function addToolCall(tool, args) {
386
- const box = addEl('div', 'tool-box');
387
- const tc = addEl('div', 'tool-call', box);
388
- tc.innerHTML = '<div class="label">πŸ”§ Tool Call</div><b>' + tool + '</b>(' +
389
- JSON.stringify(args, null, 2).replace(/</g,'&lt;') + ')';
390
- return box;
391
- }
392
-
393
- function addToolResult(box, tool, result) {
394
- const tr = addEl('div', 'tool-result', box);
395
- tr.innerHTML = '<div class="label">βœ… Result: ' + tool + '</div>' +
396
- result.substring(0, 1200).replace(/</g,'&lt;') + (result.length > 1200 ? '\n...(truncated)' : '');
397
- scrollBot();
398
- }
399
-
400
- async function sendMsg() {
401
- const msg = inputEl.value.trim();
402
- if (!msg || sendBtn.disabled) return;
403
-
404
- addMsg('user', msg);
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
- botText += data.text;
447
- botDiv.textContent = botText;
448
- scrollBot();
449
- } else if (data.type === 'tool_start') {
450
- if (firstContent) { botDiv.classList.remove('thinking'); botDiv.textContent = ''; firstContent = false; }
451
- currentToolBox = addToolCall(data.tool, data.args);
452
- botText = '';
453
- botDiv.textContent = '';
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
- } catch(e) {
470
- botDiv.classList.remove('thinking');
471
- botDiv.textContent = '❌ Error: ' + e.message;
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
- </html>"""
482
- return HTMLResponse(html)
 
 
 
483
 
484
 
485
  @app.post("/chat")
486
- async def chat_endpoint(request: Request):
487
  body = await request.json()
488
- message = body.get("message", "").strip()
489
- history = body.get("history", [])
490
- if not message:
491
  return JSONResponse({"error": "Empty message"}, status_code=400)
492
  return StreamingResponse(
493
- stream_agent(message, history),
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 list_tools_endpoint():
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,'&lt;');
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,'&lt;');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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