Theright07 commited on
Commit
dc9be71
Β·
verified Β·
1 Parent(s): 1fdbbad

Complete rewrite: FastAPI+SSE streaming, proper tool calling, web_search, token streaming

Browse files
Files changed (1) hide show
  1. app.py +497 -97
app.py CHANGED
@@ -1,115 +1,515 @@
1
- import os, re, json, shutil, subprocess, glob, traceback
2
  from pathlib import Path
3
- import gradio as gr
4
- from huggingface_hub import hf_hub_download, HfApi
 
 
 
 
5
  from llama_cpp import Llama
6
- import git as gitlib
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  WORKSPACE = Path("/workspace")
9
  WORKSPACE.mkdir(exist_ok=True)
10
 
 
11
  MODEL_REPO = "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
12
  MODEL_FILE = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
13
 
14
- print("Downloading model ...")
15
  model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
16
- print("Loading llama.cpp ...")
17
- llm = Llama(model_path=model_path, n_ctx=4096,
18
- n_threads=int(os.getenv("LLAMA_THREADS","2")), n_batch=256, verbose=False)
 
 
 
 
 
 
19
 
20
- def _safe(p):
 
21
  path = (WORKSPACE / p).resolve()
22
  if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
23
- raise ValueError("Path escapes workspace")
24
  return path
25
 
26
- def read_file(path): return _safe(path).read_text(encoding="utf-8", errors="replace")
27
- def write_file(path, content):
28
- p = _safe(path); p.parent.mkdir(parents=True, exist_ok=True)
29
- p.write_text(content, encoding="utf-8"); return f"wrote {len(content)} bytes -> {path}"
30
- def edit_file(path, find, replace):
31
- p = _safe(path); txt = p.read_text(encoding="utf-8")
32
- if find not in txt: return "pattern not found"
33
- new = txt.replace(find, replace); p.write_text(new, encoding="utf-8")
34
- return f"replaced {txt.count(find)} occurrence(s)"
35
- def delete_file(path):
36
- p = _safe(path)
37
- if p.is_dir(): shutil.rmtree(p)
38
- else: p.unlink()
39
- return f"deleted {path}"
40
- def search_files(pattern, root="."):
41
- base = _safe(root)
42
- hits = [str(Path(x).relative_to(WORKSPACE)) for x in glob.glob(f"{base}/**/{pattern}", recursive=True)]
43
- return json.dumps(hits[:200])
44
- def git_clone(url, dest=""):
45
- name = dest or url.rstrip("/").split("/")[-1].replace(".git","")
46
- target = _safe(name)
47
- if target.exists(): return f"{name} already exists"
48
- gitlib.Repo.clone_from(url, target); return f"cloned -> {name}"
49
- def git_pull(repo):
50
- r = gitlib.Repo(_safe(repo)); r.remotes.origin.pull(); return "pulled"
51
- def git_push(repo, message="update", token=""):
52
- r = gitlib.Repo(_safe(repo)); r.git.add(A=True); r.index.commit(message)
53
- if token:
54
- url = r.remotes.origin.url.replace("https://", f"https://x-access-token:{token}@")
55
- r.remotes.origin.set_url(url)
56
- r.remotes.origin.push(); return "pushed"
57
- def _run(cmd, cwd):
58
- proc = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True, timeout=1800)
59
- return f"[exit {proc.returncode}]\n{proc.stdout[-4000:]}\n{proc.stderr[-2000:]}"
60
- def gradle_build(repo, task="assembleDebug"):
61
- cwd = _safe(repo); wrapper = cwd / "gradlew"
62
- if wrapper.exists():
63
- os.chmod(wrapper, 0o755); return _run(f"./gradlew {task} --no-daemon", cwd)
64
- return _run(f"gradle {task} --no-daemon", cwd)
65
- def build_apk(repo, variant="debug"):
66
- log = gradle_build(repo, f"assemble{variant.capitalize()}")
67
- apks = glob.glob(f"{_safe(repo)}/**/*.apk", recursive=True)
68
- return log + "\nAPKs:\n" + "\n".join(apks)
69
- def upload_artifact(path, repo_id, token, path_in_repo=""):
70
- a = HfApi(token=token); p = _safe(path)
71
- a.upload_file(path_or_fileobj=str(p), path_in_repo=path_in_repo or p.name,
72
- repo_id=repo_id, repo_type="model")
73
- return f"uploaded {p.name} -> {repo_id}"
74
-
75
- TOOLS = {"read_file":read_file,"write_file":write_file,"edit_file":edit_file,
76
- "delete_file":delete_file,"search_files":search_files,"git_clone":git_clone,
77
- "git_pull":git_pull,"git_push":git_push,"gradle_build":gradle_build,
78
- "build_apk":build_apk,"upload_artifact":upload_artifact}
79
-
80
- SYSTEM = ("You are an Android build agent. Use tools to clone, edit, build APKs, upload artifacts.\n"
81
- "Call tools with: ```tool\n{\"name\":\"...\",\"args\":{...}}\n```\n"
82
- "Tools: read_file, write_file, edit_file, delete_file, search_files, "
83
- "git_clone, git_pull, git_push, gradle_build, build_apk, upload_artifact")
84
- TOOL_RE = re.compile(r"```tool\s*(\{.*?\})\s*```", re.S)
85
-
86
- def chat_fn(message, history):
87
- msgs = [{"role":"system","content":SYSTEM}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  for h in history:
89
- msgs.append({"role":"user","content":h[0]})
90
- msgs.append({"role":"assistant","content":h[1]})
91
- msgs.append({"role":"user","content":message})
92
- transcript = ""
93
- for _ in range(6):
94
- out = llm.create_chat_completion(messages=msgs, temperature=0.2, max_tokens=800)
95
- reply = out["choices"][0]["message"]["content"]
96
- transcript += reply + "\n"
97
- m = TOOL_RE.search(reply)
98
- if not m:
99
- return transcript.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  try:
101
- call = json.loads(m.group(1))
102
- result = TOOLS[call["name"]](**call.get("args",{}))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  except Exception as e:
104
- result = f"ERROR: {e}\n{traceback.format_exc()[-300:]}"
105
- msgs.append({"role":"assistant","content":reply})
106
- msgs.append({"role":"user","content":f"tool_result:\n{result}"})
107
- transcript += f"\n[tool result]\n{result}\n"
108
- return transcript.strip()
109
-
110
- demo = gr.ChatInterface(
111
- fn=chat_fn,
112
- title="Android Build Agent",
113
- description="Powered by Qwen2.5-Coder-1.5B + llama.cpp",
114
- )
115
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, re, json, shutil, subprocess, glob, traceback, asyncio
2
  from pathlib import Path
3
+ from typing import AsyncGenerator
4
+
5
+ from fastapi import FastAPI, Request
6
+ from fastapi.responses import StreamingResponse, HTMLResponse, JSONResponse
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from huggingface_hub import hf_hub_download
9
  from llama_cpp import Llama
 
10
 
11
+ # ── optional tools ──────────────────────────────────────────────────────────
12
+ try:
13
+ import git as gitlib
14
+ HAS_GIT = True
15
+ except ImportError:
16
+ HAS_GIT = False
17
+
18
+ try:
19
+ from duckduckgo_search import DDGS
20
+ HAS_DDG = True
21
+ except ImportError:
22
+ HAS_DDG = False
23
+
24
+ # ── workspace ────────────────────────────────────────────────────────────────
25
  WORKSPACE = Path("/workspace")
26
  WORKSPACE.mkdir(exist_ok=True)
27
 
28
+ # ── model load ───────────────────────────────────────────────────────────────
29
  MODEL_REPO = "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
30
  MODEL_FILE = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
31
 
32
+ print("⏬ Downloading model...")
33
  model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
34
+ print("βœ… Loading model...")
35
+ llm = Llama(
36
+ model_path=model_path,
37
+ n_ctx=4096,
38
+ n_threads=int(os.getenv("LLAMA_THREADS", "2")),
39
+ n_batch=256,
40
+ verbose=False,
41
+ )
42
+ print("βœ… Model ready!")
43
 
44
+ # ── tools ────────────────────────────────────────────────────────────────────
45
+ def _safe(p: str) -> Path:
46
  path = (WORKSPACE / p).resolve()
47
  if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
48
+ raise ValueError(f"Path '{p}' escapes workspace")
49
  return path
50
 
51
+ def tool_read_file(path: str) -> str:
52
+ try:
53
+ return _safe(path).read_text(encoding="utf-8", errors="replace")
54
+ except Exception as e:
55
+ return f"ERROR: {e}"
56
+
57
+ def tool_write_file(path: str, content: str) -> str:
58
+ try:
59
+ p = _safe(path)
60
+ p.parent.mkdir(parents=True, exist_ok=True)
61
+ p.write_text(content, encoding="utf-8")
62
+ return f"βœ… Written {len(content)} bytes to {path}"
63
+ except Exception as e:
64
+ return f"ERROR: {e}"
65
+
66
+ def tool_edit_file(path: str, find: str, replace: str) -> str:
67
+ try:
68
+ p = _safe(path)
69
+ txt = p.read_text(encoding="utf-8")
70
+ if find not in txt:
71
+ return f"ERROR: Pattern not found in {path}"
72
+ new = txt.replace(find, replace)
73
+ p.write_text(new, encoding="utf-8")
74
+ return f"βœ… Replaced {txt.count(find)} occurrence(s) in {path}"
75
+ except Exception as e:
76
+ return f"ERROR: {e}"
77
+
78
+ def tool_delete_file(path: str) -> str:
79
+ try:
80
+ p = _safe(path)
81
+ if p.is_dir():
82
+ shutil.rmtree(p)
83
+ else:
84
+ p.unlink()
85
+ return f"βœ… Deleted {path}"
86
+ except Exception as e:
87
+ return f"ERROR: {e}"
88
+
89
+ def tool_list_files(path: str = ".") -> str:
90
+ try:
91
+ base = _safe(path)
92
+ files = []
93
+ for f in sorted(base.rglob("*")):
94
+ if f.is_file():
95
+ rel = str(f.relative_to(WORKSPACE))
96
+ files.append(rel)
97
+ return "\n".join(files[:300]) if files else "No files found"
98
+ except Exception as e:
99
+ return f"ERROR: {e}"
100
+
101
+ def tool_git_clone(url: str, dest: str = "") -> str:
102
+ if not HAS_GIT:
103
+ return "ERROR: gitpython not installed"
104
+ try:
105
+ name = dest or url.rstrip("/").split("/")[-1].replace(".git", "")
106
+ target = _safe(name)
107
+ if target.exists():
108
+ return f"βœ… {name} already exists"
109
+ gitlib.Repo.clone_from(url, target)
110
+ return f"βœ… Cloned {url} -> /workspace/{name}"
111
+ except Exception as e:
112
+ return f"ERROR: {e}"
113
+
114
+ def tool_run_command(command: str, working_dir: str = ".") -> str:
115
+ try:
116
+ cwd = _safe(working_dir)
117
+ proc = subprocess.run(
118
+ command, cwd=cwd, shell=True,
119
+ capture_output=True, text=True, timeout=600
120
+ )
121
+ out = proc.stdout[-3000:] if proc.stdout else ""
122
+ err = proc.stderr[-1500:] if proc.stderr else ""
123
+ return f"[exit {proc.returncode}]\nSTDOUT:\n{out}\nSTDERR:\n{err}"
124
+ except subprocess.TimeoutExpired:
125
+ return "ERROR: Command timed out (600s)"
126
+ except Exception as e:
127
+ return f"ERROR: {e}"
128
+
129
+ def tool_gradle_build(repo: str, task: str = "assembleDebug") -> str:
130
+ try:
131
+ cwd = _safe(repo)
132
+ wrapper = cwd / "gradlew"
133
+ if wrapper.exists():
134
+ os.chmod(wrapper, 0o755)
135
+ cmd = f"./gradlew {task} --no-daemon --stacktrace"
136
+ else:
137
+ cmd = f"gradle {task} --no-daemon"
138
+ proc = subprocess.run(cmd, cwd=cwd, shell=True,
139
+ capture_output=True, text=True, timeout=1200)
140
+ out = proc.stdout[-4000:] if proc.stdout else ""
141
+ err = proc.stderr[-2000:] if proc.stderr else ""
142
+ apks = glob.glob(f"{cwd}/**/*.apk", recursive=True)
143
+ apk_info = "\n\nπŸ“¦ APKs found:\n" + "\n".join(apks) if apks else "\n\n⚠️ No APK found"
144
+ return f"[exit {proc.returncode}]\n{out}\n{err}{apk_info}"
145
+ except Exception as e:
146
+ return f"ERROR: {e}\n{traceback.format_exc()[-500:]}"
147
+
148
+ def tool_web_search(query: str, max_results: int = 5) -> str:
149
+ if not HAS_DDG:
150
+ return "ERROR: duckduckgo-search not installed"
151
+ try:
152
+ results = []
153
+ with DDGS() as ddgs:
154
+ for r in ddgs.text(query, max_results=max_results):
155
+ results.append(f"Title: {r.get('title','')}\nURL: {r.get('href','')}\nSnippet: {r.get('body','')}\n")
156
+ return "\n---\n".join(results) if results else "No results found"
157
+ except Exception as e:
158
+ return f"ERROR: {e}"
159
+
160
+ def tool_read_url(url: str) -> str:
161
+ try:
162
+ import urllib.request
163
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
164
+ with urllib.request.urlopen(req, timeout=15) as resp:
165
+ content = resp.read().decode("utf-8", errors="replace")
166
+ # Strip HTML tags roughly
167
+ content = re.sub(r'<[^>]+>', ' ', content)
168
+ content = re.sub(r'\s+', ' ', content).strip()
169
+ return content[:3000]
170
+ except Exception as e:
171
+ return f"ERROR: {e}"
172
+
173
+ # ── tool registry ─────────────────────────────────────────────────────────────
174
+ TOOLS = {
175
+ "read_file": {"fn": tool_read_file, "desc": "Read a file from workspace", "params": {"path": "file path relative to /workspace"}},
176
+ "write_file": {"fn": tool_write_file, "desc": "Write/create a file in workspace", "params": {"path": "file path", "content": "file content"}},
177
+ "edit_file": {"fn": tool_edit_file, "desc": "Find and replace text in a file", "params": {"path": "file path", "find": "text to find", "replace": "replacement text"}},
178
+ "delete_file": {"fn": tool_delete_file, "desc": "Delete a file or directory", "params": {"path": "file or dir path"}},
179
+ "list_files": {"fn": tool_list_files, "desc": "List all files in workspace or subdirectory", "params": {"path": "directory path (default '.')"}},
180
+ "git_clone": {"fn": tool_git_clone, "desc": "Clone a git repository into workspace", "params": {"url": "git URL", "dest": "optional destination folder name"}},
181
+ "run_command": {"fn": tool_run_command, "desc": "Run any shell command in workspace", "params": {"command": "shell command", "working_dir": "working directory (default '.')"}},
182
+ "gradle_build": {"fn": tool_gradle_build, "desc": "Run gradle build task (e.g. assembleDebug) in a repo", "params": {"repo": "repo folder in workspace", "task": "gradle task (default assembleDebug)"}},
183
+ "web_search": {"fn": tool_web_search, "desc": "Search the web using DuckDuckGo", "params": {"query": "search query", "max_results": "number of results (default 5)"}},
184
+ "read_url": {"fn": tool_read_url, "desc": "Fetch and read content from a URL", "params": {"url": "full URL to fetch"}},
185
+ }
186
+
187
+ TOOLS_DESCRIPTION = "\n".join([
188
+ f'- **{name}**({", ".join(f"{k}" for k in info["params"])}): {info["desc"]}'
189
+ for name, info in TOOLS.items()
190
+ ])
191
+
192
+ SYSTEM_PROMPT = f"""You are an expert Android build agent with access to the following tools:
193
+
194
+ {TOOLS_DESCRIPTION}
195
+
196
+ ## HOW TO USE TOOLS
197
+ To call a tool, output a JSON block EXACTLY like this (nothing else on that line):
198
+ <tool>
199
+ {{"name": "tool_name", "args": {{"param1": "value1", "param2": "value2"}}}}
200
+ </tool>
201
+
202
+ After the tool result is shown, continue your response.
203
+
204
+ ## YOUR CAPABILITIES
205
+ - You can clone GitHub repos, read/write/edit files, run shell commands
206
+ - You can build Android APKs using gradle
207
+ - You can search the web for information
208
+ - You can read URLs for documentation
209
+
210
+ ## RULES
211
+ 1. ALWAYS use tools when asked to do something practical (build, clone, search, etc.)
212
+ 2. NEVER pretend to do something - actually use the tool
213
+ 3. After each tool result, explain what happened and what you'll do next
214
+ 4. For APK builds: clone repo β†’ check structure β†’ run gradle_build
215
+ 5. Be concise but thorough
216
+ """
217
+
218
+ TOOL_RE = re.compile(r'<tool>\s*(\{.*?\})\s*</tool>', re.DOTALL)
219
+
220
+ # ── FastAPI app ───────────────────────────────────────────────────────────────
221
+ app = FastAPI(title="Android Build Agent API")
222
+
223
+ app.add_middleware(
224
+ CORSMiddleware,
225
+ allow_origins=["*"],
226
+ allow_methods=["*"],
227
+ allow_headers=["*"],
228
+ )
229
+
230
+ async def run_agent_stream(message: str, history: list) -> AsyncGenerator[str, None]:
231
+ """Stream agent response token by token, executing tools inline."""
232
+ msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
233
  for h in history:
234
+ if isinstance(h, (list, tuple)) and len(h) == 2:
235
+ if h[0]:
236
+ msgs.append({"role": "user", "content": str(h[0])})
237
+ if h[1]:
238
+ msgs.append({"role": "assistant", "content": str(h[1])})
239
+ msgs.append({"role": "user", "content": message})
240
+
241
+ full_response = ""
242
+
243
+ for step in range(8): # max 8 tool calls per turn
244
+ # Stream tokens from LLM
245
+ buffer = ""
246
+ tool_triggered = False
247
+
248
+ stream = llm.create_chat_completion(
249
+ messages=msgs,
250
+ temperature=0.3,
251
+ max_tokens=1024,
252
+ stream=True,
253
+ )
254
+
255
+ for chunk in stream:
256
+ delta = chunk["choices"][0].get("delta", {})
257
+ token = delta.get("content", "")
258
+ if not token:
259
+ continue
260
+
261
+ buffer += token
262
+ full_response += token
263
+
264
+ # Check if we have a complete <tool> block
265
+ if "<tool>" in buffer and "</tool>" in buffer:
266
+ tool_triggered = True
267
+ # Stream everything up to <tool>
268
+ pre = buffer[:buffer.index("<tool>")]
269
+ if pre.strip():
270
+ yield f"data: {json.dumps({'type': 'token', 'text': pre})}\n\n"
271
+ break
272
+ else:
273
+ # Stream token if no partial tool tag forming
274
+ if "<tool>" not in buffer:
275
+ yield f"data: {json.dumps({'type': 'token', 'text': token})}\n\n"
276
+ await asyncio.sleep(0)
277
+
278
+ if not tool_triggered:
279
+ # No tool call, we're done
280
+ break
281
+
282
+ # Extract and execute tool
283
+ tool_match = TOOL_RE.search(buffer)
284
+ if not tool_match:
285
+ yield f"data: {json.dumps({'type': 'token', 'text': buffer})}\n\n"
286
+ break
287
+
288
  try:
289
+ call = json.loads(tool_match.group(1))
290
+ tool_name = call.get("name", "")
291
+ tool_args = call.get("args", {})
292
+
293
+ if tool_name not in TOOLS:
294
+ tool_result = f"ERROR: Unknown tool '{tool_name}'. Available: {', '.join(TOOLS.keys())}"
295
+ else:
296
+ yield f"data: {json.dumps({'type': 'tool_start', 'tool': tool_name, 'args': tool_args})}\n\n"
297
+ await asyncio.sleep(0)
298
+
299
+ # Run tool in thread pool to not block event loop
300
+ loop = asyncio.get_event_loop()
301
+ tool_fn = TOOLS[tool_name]["fn"]
302
+ tool_result = await loop.run_in_executor(None, lambda: tool_fn(**tool_args))
303
+
304
+ yield f"data: {json.dumps({'type': 'tool_result', 'tool': tool_name, 'result': str(tool_result)[:2000]})}\n\n"
305
+ await asyncio.sleep(0)
306
+
307
+ except json.JSONDecodeError as e:
308
+ tool_result = f"ERROR parsing tool call: {e}"
309
+ yield f"data: {json.dumps({'type': 'error', 'text': tool_result})}\n\n"
310
  except Exception as e:
311
+ tool_result = f"ERROR executing tool: {e}"
312
+ yield f"data: {json.dumps({'type': 'error', 'text': tool_result})}\n\n"
313
+
314
+ # Add assistant message + tool result to context and continue
315
+ msgs.append({"role": "assistant", "content": buffer})
316
+ msgs.append({"role": "user", "content": f"[Tool result for {tool_name}]:\n{tool_result}"})
317
+ full_response += f"\n[Tool: {tool_name}]\n{str(tool_result)[:500]}\n"
318
+
319
+ yield f"data: {json.dumps({'type': 'done', 'full': full_response})}\n\n"
320
+
321
+
322
+ @app.get("/", response_class=HTMLResponse)
323
+ async def root():
324
+ return HTMLResponse("""<!DOCTYPE html>
325
+ <html><head><title>Android Build Agent</title>
326
+ <style>
327
+ * { box-sizing: border-box; margin: 0; padding: 0; }
328
+ body { font-family: 'Segoe UI', sans-serif; background: #0d1117; color: #e6edf3; height: 100vh; display: flex; flex-direction: column; }
329
+ #header { padding: 16px 24px; background: #161b22; border-bottom: 1px solid #30363d; display: flex; align-items: center; gap: 12px; }
330
+ #header h1 { font-size: 18px; color: #58a6ff; }
331
+ #header .status { font-size: 12px; color: #3fb950; }
332
+ #chat { flex: 1; overflow-y: auto; padding: 16px 24px; display: flex; flex-direction: column; gap: 12px; }
333
+ .msg { max-width: 80%; padding: 12px 16px; border-radius: 12px; line-height: 1.6; white-space: pre-wrap; word-wrap: break-word; }
334
+ .user { align-self: flex-end; background: #1f6feb; color: #fff; border-radius: 12px 12px 2px 12px; }
335
+ .bot { align-self: flex-start; background: #161b22; border: 1px solid #30363d; border-radius: 12px 12px 12px 2px; }
336
+ .tool-call { background: #0d2137; border: 1px solid #1f6feb44; border-radius: 8px; padding: 8px 12px; margin: 6px 0; font-size: 13px; font-family: monospace; }
337
+ .tool-result { background: #0d2a0d; border: 1px solid #3fb95044; border-radius: 8px; padding: 8px 12px; margin: 6px 0; font-size: 12px; font-family: monospace; max-height: 200px; overflow-y: auto; }
338
+ .tool-label { font-size: 11px; color: #8b949e; margin-bottom: 4px; }
339
+ #input-area { padding: 16px 24px; background: #161b22; border-top: 1px solid #30363d; display: flex; gap: 10px; }
340
+ #input { flex: 1; background: #0d1117; border: 1px solid #30363d; border-radius: 8px; color: #e6edf3; padding: 12px 16px; font-size: 14px; resize: none; height: 56px; outline: none; }
341
+ #input:focus { border-color: #58a6ff; }
342
+ #send { background: #1f6feb; color: #fff; border: none; border-radius: 8px; padding: 0 20px; cursor: pointer; font-size: 14px; font-weight: 600; }
343
+ #send:hover { background: #388bfd; }
344
+ #send:disabled { background: #30363d; cursor: not-allowed; }
345
+ .thinking { color: #8b949e; font-style: italic; }
346
+ </style></head>
347
+ <body>
348
+ <div id="header">
349
+ <span>πŸ€–</span>
350
+ <h1>Android Build Agent</h1>
351
+ <span class="status">● Qwen2.5-Coder-1.5B + Tools</span>
352
+ </div>
353
+ <div id="chat">
354
+ <div class="msg bot">πŸ‘‹ Namaste! Main Android Build Agent hoon.<br><br>
355
+ Mere paas ye tools hain:<br>
356
+ πŸ”§ <b>read_file, write_file, edit_file, delete_file, list_files</b> β€” workspace file operations<br>
357
+ πŸ“¦ <b>git_clone</b> β€” GitHub repos clone karo<br>
358
+ βš™οΈ <b>run_command</b> β€” koi bhi shell command chalao<br>
359
+ πŸ—οΈ <b>gradle_build</b> β€” Android APK build karo<br>
360
+ πŸ” <b>web_search</b> β€” DuckDuckGo se search karo<br>
361
+ 🌐 <b>read_url</b> β€” kisi bhi URL ka content padho<br><br>
362
+ Kya karna hai? (e.g. "Clone https://github.com/... and build APK")</div>
363
+ </div>
364
+ <div id="input-area">
365
+ <textarea id="input" placeholder="Message likhein... (Enter = send, Shift+Enter = newline)"></textarea>
366
+ <button id="send" onclick="sendMsg()">Send</button>
367
+ </div>
368
+ <script>
369
+ const chat = document.getElementById('chat');
370
+ const input = document.getElementById('input');
371
+ const sendBtn = document.getElementById('send');
372
+ let history = [];
373
+
374
+ input.addEventListener('keydown', e => {
375
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMsg(); }
376
+ });
377
+
378
+ function addMsg(role, content) {
379
+ const div = document.createElement('div');
380
+ div.className = 'msg ' + role;
381
+ div.textContent = content;
382
+ chat.appendChild(div);
383
+ chat.scrollTop = chat.scrollHeight;
384
+ return div;
385
+ }
386
+
387
+ function addToolCall(tool, args) {
388
+ const div = document.createElement('div');
389
+ div.className = 'tool-call';
390
+ div.innerHTML = '<div class="tool-label">πŸ”§ TOOL CALL</div>' +
391
+ '<b>' + tool + '</b>(' + JSON.stringify(args, null, 2) + ')';
392
+ chat.appendChild(div);
393
+ chat.scrollTop = chat.scrollHeight;
394
+ }
395
+
396
+ function addToolResult(tool, result) {
397
+ const div = document.createElement('div');
398
+ div.className = 'tool-result';
399
+ div.innerHTML = '<div class="tool-label">βœ… RESULT: ' + tool + '</div>' +
400
+ result.substring(0, 1000) + (result.length > 1000 ? '...' : '');
401
+ chat.appendChild(div);
402
+ chat.scrollTop = chat.scrollHeight;
403
+ }
404
+
405
+ async function sendMsg() {
406
+ const msg = input.value.trim();
407
+ if (!msg) return;
408
+
409
+ addMsg('user', msg);
410
+ input.value = '';
411
+ sendBtn.disabled = true;
412
+
413
+ const botDiv = addMsg('bot', '');
414
+ botDiv.classList.add('thinking');
415
+ botDiv.textContent = '⏳ Thinking...';
416
+
417
+ let botText = '';
418
+ let firstToken = true;
419
+
420
+ try {
421
+ const resp = await fetch('/chat', {
422
+ method: 'POST',
423
+ headers: {'Content-Type': 'application/json'},
424
+ body: JSON.stringify({message: msg, history: history})
425
+ });
426
+
427
+ const reader = resp.body.getReader();
428
+ const decoder = new TextDecoder();
429
+ let buffer = '';
430
+
431
+ while (true) {
432
+ const {done, value} = await reader.read();
433
+ if (done) break;
434
+
435
+ buffer += decoder.decode(value, {stream: true});
436
+ const lines = buffer.split('\n');
437
+ buffer = lines.pop();
438
+
439
+ for (const line of lines) {
440
+ if (!line.startsWith('data: ')) continue;
441
+ try {
442
+ const data = JSON.parse(line.slice(6));
443
+
444
+ if (data.type === 'token') {
445
+ if (firstToken) {
446
+ botDiv.classList.remove('thinking');
447
+ botDiv.textContent = '';
448
+ firstToken = false;
449
+ }
450
+ botText += data.text;
451
+ botDiv.textContent = botText;
452
+ chat.scrollTop = chat.scrollHeight;
453
+ } else if (data.type === 'tool_start') {
454
+ addToolCall(data.tool, data.args);
455
+ } else if (data.type === 'tool_result') {
456
+ addToolResult(data.tool, data.result);
457
+ botText = '';
458
+ firstToken = true;
459
+ botDiv.textContent = '';
460
+ } else if (data.type === 'done') {
461
+ history.push([msg, data.full]);
462
+ }
463
+ } catch(e) {}
464
+ }
465
+ }
466
+ } catch(e) {
467
+ botDiv.textContent = '❌ Error: ' + e.message;
468
+ }
469
+
470
+ if (botDiv.textContent === '' || botDiv.textContent === '⏳ Thinking...') {
471
+ botDiv.textContent = '(No response)';
472
+ }
473
+ botDiv.classList.remove('thinking');
474
+ sendBtn.disabled = false;
475
+ input.focus();
476
+ }
477
+ </script>
478
+ </body></html>""")
479
+
480
+
481
+ @app.post("/chat")
482
+ async def chat_endpoint(request: Request):
483
+ body = await request.json()
484
+ message = body.get("message", "")
485
+ history = body.get("history", [])
486
+
487
+ if not message.strip():
488
+ return JSONResponse({"error": "Empty message"}, status_code=400)
489
+
490
+ return StreamingResponse(
491
+ run_agent_stream(message, history),
492
+ media_type="text/event-stream",
493
+ headers={
494
+ "Cache-Control": "no-cache",
495
+ "X-Accel-Buffering": "no",
496
+ }
497
+ )
498
+
499
+
500
+ @app.get("/health")
501
+ async def health():
502
+ return {"status": "ok", "model": MODEL_FILE, "tools": list(TOOLS.keys())}
503
+
504
+
505
+ @app.get("/tools")
506
+ async def list_tools():
507
+ return {
508
+ name: {"description": info["desc"], "params": info["params"]}
509
+ for name, info in TOOLS.items()
510
+ }
511
+
512
+
513
+ if __name__ == "__main__":
514
+ import uvicorn
515
+ uvicorn.run(app, host="0.0.0.0", port=7860)