Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,9 @@
|
|
| 1 |
import os
|
| 2 |
import subprocess
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from fastapi import FastAPI, HTTPException
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
from pydantic import BaseModel
|
|
@@ -23,12 +27,14 @@ client = genai.Client(api_key=GEMINI_API_KEY)
|
|
| 23 |
class ChatRequest(BaseModel):
|
| 24 |
message: str
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
try:
|
| 28 |
-
# Saari commands hamesha /tmp folder me execute hongi jahan explicit write permissions hain
|
| 29 |
full_command = f"cd /tmp && {command}"
|
| 30 |
-
|
| 31 |
-
# Hugging Face ke saare Environment Variables (tokens, paths) ko sub-process me pass karne ke liye
|
| 32 |
env = os.environ.copy()
|
| 33 |
|
| 34 |
result = subprocess.run(
|
|
@@ -36,29 +42,64 @@ def execute_in_sandbox(command: str):
|
|
| 36 |
shell=True,
|
| 37 |
capture_output=True,
|
| 38 |
text=True,
|
| 39 |
-
errors="replace",
|
| 40 |
-
timeout=300,
|
| 41 |
env=env
|
| 42 |
)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
"
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
except subprocess.TimeoutExpired:
|
| 49 |
-
return
|
| 50 |
-
"stdout": "",
|
| 51 |
-
"stderr": "Execution timed out! Command took longer than 5 minutes to prevent server freeze.",
|
| 52 |
-
"exit_code": -1
|
| 53 |
-
}
|
| 54 |
except Exception as e:
|
| 55 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
@app.post("/chat")
|
| 58 |
async def agent_chat(request: ChatRequest):
|
| 59 |
user_prompt = request.message
|
| 60 |
|
| 61 |
-
# SYSTEM INSTRUCTION: Gofile rules ko nikaal kar ise ekdum dynamic aur general bana diya hai
|
| 62 |
system_instruction = (
|
| 63 |
"You are an expert AI Agent Builder operating inside a fully equipped Linux sandbox.\n\n"
|
| 64 |
"YOUR DEVELOPMENT ENVIRONMENT capabilities:\n"
|
|
@@ -66,66 +107,75 @@ async def agent_chat(request: ChatRequest):
|
|
| 66 |
"- **Flutter & Dart SDK** are pre-installed globally. You can run `flutter create` and `flutter build apk --release`.\n"
|
| 67 |
"- **Android Native Build System** is pre-installed. Full OpenJDK 17, Android SDK (API 34), and Build-Tools (34.0.0) are ready. You can create Native Android apps (using gradle wrappers) and build them directly.\n"
|
| 68 |
"- You CANNOT use 'sudo'. Perform all workspace creation inside the `/tmp` directory.\n\n"
|
| 69 |
-
"
|
| 70 |
-
"-
|
| 71 |
-
"-
|
| 72 |
-
"
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
)
|
| 76 |
|
| 77 |
try:
|
| 78 |
-
#
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
)
|
| 83 |
|
| 84 |
-
#
|
|
|
|
| 85 |
response = chat.send_message(user_prompt)
|
| 86 |
-
ai_response = response.text
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
execution_history = []
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
while
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
# History maintain karne ke liye (Aapke UI/logs ke liye)
|
| 102 |
-
execution_history.append({
|
| 103 |
-
"step": current_loop + 1,
|
| 104 |
-
"command_executed": command,
|
| 105 |
-
"result": exec_result
|
| 106 |
-
})
|
| 107 |
-
|
| 108 |
-
# Safe feedback string bana rahe hain bina kisi memory leakage ke
|
| 109 |
-
feedback = (
|
| 110 |
-
f"Execution Result for Step {current_loop + 1}:\n"
|
| 111 |
-
f"Exit Code: {exec_result.get('exit_code')}\n"
|
| 112 |
-
f"Stdout: {exec_result.get('stdout')}\n"
|
| 113 |
-
f"Stderr: {exec_result.get('stderr')}\n"
|
| 114 |
-
)
|
| 115 |
-
if "error" in exec_result:
|
| 116 |
-
feedback += f"System Error: {exec_result['error']}\n"
|
| 117 |
-
|
| 118 |
-
feedback += "\nAnalyze this output. If the task succeeded, provide the final response or download links. If it failed, fix the code and output a new bash block to retry."
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
-
|
| 125 |
|
| 126 |
-
# UI par clean output dikhane ke liye execution history aur final text ko alag kar diya
|
| 127 |
return {
|
| 128 |
-
"agent_response":
|
| 129 |
"execution_history": execution_history if execution_history else None
|
| 130 |
}
|
| 131 |
|
|
|
|
| 1 |
import os
|
| 2 |
import subprocess
|
| 3 |
+
import urllib.request
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
from fastapi import FastAPI, HTTPException
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from pydantic import BaseModel
|
|
|
|
| 27 |
class ChatRequest(BaseModel):
|
| 28 |
message: str
|
| 29 |
|
| 30 |
+
# TOOL 1: Hardcore Terminal Execution System
|
| 31 |
+
def run_terminal_command(command: str) -> str:
|
| 32 |
+
"""
|
| 33 |
+
Executes any bash command inside the secure Linux sandbox workspace (/tmp).
|
| 34 |
+
Use this to run python scripts, compile Flutter apps, build APKs, or manage git operations.
|
| 35 |
+
"""
|
| 36 |
try:
|
|
|
|
| 37 |
full_command = f"cd /tmp && {command}"
|
|
|
|
|
|
|
| 38 |
env = os.environ.copy()
|
| 39 |
|
| 40 |
result = subprocess.run(
|
|
|
|
| 42 |
shell=True,
|
| 43 |
capture_output=True,
|
| 44 |
text=True,
|
| 45 |
+
errors="replace",
|
| 46 |
+
timeout=300,
|
| 47 |
env=env
|
| 48 |
)
|
| 49 |
+
|
| 50 |
+
output = f"Exit Code: {result.returncode}\n"
|
| 51 |
+
if result.stdout:
|
| 52 |
+
output += f"STDOUT:\n{result.stdout}\n"
|
| 53 |
+
if result.stderr:
|
| 54 |
+
output += f"STDERR:\n{result.stderr}\n"
|
| 55 |
+
return output
|
| 56 |
except subprocess.TimeoutExpired:
|
| 57 |
+
return "ERROR: Command execution timed out after 5 minutes to prevent server freeze."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
except Exception as e:
|
| 59 |
+
return f"SYSTEM ERROR: {str(e)}"
|
| 60 |
+
|
| 61 |
+
# TOOL 2: Crash-Free Pure Python Internet Search (No external package dependency)
|
| 62 |
+
def internet_search(query: str) -> str:
|
| 63 |
+
"""
|
| 64 |
+
Searches the live internet for API documentations, github repositories, code fixes, or upload guidelines.
|
| 65 |
+
Returns real-time web summaries using a clean, raw API request.
|
| 66 |
+
"""
|
| 67 |
+
try:
|
| 68 |
+
# Text-based query optimization bina kisi bloated third-party library ke
|
| 69 |
+
encoded_query = urllib.parse.quote(query)
|
| 70 |
+
url = f"https://html.duckduckgo.com/html/?q={encoded_query}"
|
| 71 |
+
|
| 72 |
+
req = urllib.request.Request(
|
| 73 |
+
url,
|
| 74 |
+
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
with urllib.request.urlopen(req, timeout=15) as response:
|
| 78 |
+
html = response.read().decode('utf-8', errors='replace')
|
| 79 |
+
|
| 80 |
+
# Simple text parsing se clean title aur snippets nikalna (100% crashproof)
|
| 81 |
+
links = re.findall(r'<a class="result__url" href="([^"]+)"', html)
|
| 82 |
+
snippets = re.findall(r'<a class="result__snippet"[^>]*>(.*?)</a>', html, re.DOTALL)
|
| 83 |
+
|
| 84 |
+
if not links:
|
| 85 |
+
return f"No direct text results found for '{query}'. Try executing a curl command in terminal tool instead."
|
| 86 |
+
|
| 87 |
+
search_summary = ""
|
| 88 |
+
for i in range(min(4, len(links))):
|
| 89 |
+
clean_link = urllib.parse.unquote(links[i].split('?uddg=')[-1].split('&')[0])
|
| 90 |
+
snippet_text = re.sub(r'<[^>]+>', '', snippets[i]).strip() if i < len(snippets) else "No summary available."
|
| 91 |
+
search_summary += f"[{i+1}] Link: {clean_link}\nSnippet: {snippet_text}\n\n"
|
| 92 |
+
|
| 93 |
+
return search_summary
|
| 94 |
+
|
| 95 |
+
except Exception as e:
|
| 96 |
+
# Agar block bhi hua toh backend crash nahi hoga, AI ko alternate option dikha dega
|
| 97 |
+
return f"INTERNET SEARCH NOTICE: Web endpoint restricted. Use 'run_terminal_command' tool to curl target docs directly."
|
| 98 |
|
| 99 |
@app.post("/chat")
|
| 100 |
async def agent_chat(request: ChatRequest):
|
| 101 |
user_prompt = request.message
|
| 102 |
|
|
|
|
| 103 |
system_instruction = (
|
| 104 |
"You are an expert AI Agent Builder operating inside a fully equipped Linux sandbox.\n\n"
|
| 105 |
"YOUR DEVELOPMENT ENVIRONMENT capabilities:\n"
|
|
|
|
| 107 |
"- **Flutter & Dart SDK** are pre-installed globally. You can run `flutter create` and `flutter build apk --release`.\n"
|
| 108 |
"- **Android Native Build System** is pre-installed. Full OpenJDK 17, Android SDK (API 34), and Build-Tools (34.0.0) are ready. You can create Native Android apps (using gradle wrappers) and build them directly.\n"
|
| 109 |
"- You CANNOT use 'sudo'. Perform all workspace creation inside the `/tmp` directory.\n\n"
|
| 110 |
+
"YOUR NATIVE PYTHON TOOLS:\n"
|
| 111 |
+
"- `run_terminal_command`: Call this tool to run any shell/bash script or build commands. Do NOT wrap shell code in text-based markdown blocks if you intend to run it; execute it directly via this tool.\n"
|
| 112 |
+
"- `internet_search`: Call this tool if you need to look up documentation for APIs (like catbox.moe, gofile.io, transfer.sh), debug code errors, or research integration steps. Never mock data.\n\n"
|
| 113 |
+
"CRITICAL EXECUTION RULES:\n"
|
| 114 |
+
"- You have full internet access inside the sandbox tool. Analyze execution outputs carefully. If a command or build script fails, analyze the error log, self-correct, update your code, and execute again until successful.\n"
|
| 115 |
+
"- Once the objective is completed successfully (e.g., app compiled or file uploaded), present a clean summary and direct download links to the user."
|
| 116 |
)
|
| 117 |
|
| 118 |
try:
|
| 119 |
+
# Gemini native tool definitions mapping
|
| 120 |
+
available_tools = {
|
| 121 |
+
"run_terminal_command": run_terminal_command,
|
| 122 |
+
"internet_search": internet_search
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
# Native client-side automation implementation
|
| 126 |
+
config = types.GenerateContentConfig(
|
| 127 |
+
system_instruction=system_instruction,
|
| 128 |
+
tools=[run_terminal_command, internet_search], # Gemini recognizes these python functions natively
|
| 129 |
+
temperature=0.2 # Lower temperature means highly accurate code and tool usage
|
| 130 |
)
|
| 131 |
|
| 132 |
+
# Chat session start
|
| 133 |
+
chat = client.chats.create(model='gemini-2.5-flash', config=config)
|
| 134 |
response = chat.send_message(user_prompt)
|
|
|
|
| 135 |
|
| 136 |
+
max_turns = 6 # Safe limit for autonomous iterations on Hugging Face
|
| 137 |
+
current_turn = 0
|
| 138 |
execution_history = []
|
| 139 |
|
| 140 |
+
# NATIVE TOOL CALLING LOOP: Handles recursive execution automatically
|
| 141 |
+
while response.function_calls and current_turn < max_turns:
|
| 142 |
+
function_responses = []
|
| 143 |
+
|
| 144 |
+
for function_call in response.function_calls:
|
| 145 |
+
name = function_call.name
|
| 146 |
+
args = function_call.args
|
| 147 |
+
call_id = function_call.id # Unique tracking ID for multiple/parallel calls
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
if name in available_tools:
|
| 150 |
+
# Tool execute karo aur function kwargs pass karo dynamically
|
| 151 |
+
tool_output = available_tools[name](**args)
|
| 152 |
+
|
| 153 |
+
execution_history.append({
|
| 154 |
+
"turn": current_turn + 1,
|
| 155 |
+
"tool_called": name,
|
| 156 |
+
"arguments": args,
|
| 157 |
+
"raw_output": tool_output
|
| 158 |
+
})
|
| 159 |
+
|
| 160 |
+
# Gemini format ke mutabik tool response register karna
|
| 161 |
+
function_responses.append(
|
| 162 |
+
types.Part.from_function_response(
|
| 163 |
+
name=name,
|
| 164 |
+
response={"result": tool_output},
|
| 165 |
+
id=call_id
|
| 166 |
+
)
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
if function_responses:
|
| 170 |
+
# Execution data ko wapas model ko feed karna loop continue rakhne ke liye
|
| 171 |
+
response = chat.send_message(function_responses)
|
| 172 |
+
else:
|
| 173 |
+
break
|
| 174 |
|
| 175 |
+
current_turn += 1
|
| 176 |
|
|
|
|
| 177 |
return {
|
| 178 |
+
"agent_response": response.text,
|
| 179 |
"execution_history": execution_history if execution_history else None
|
| 180 |
}
|
| 181 |
|