THED2 commited on
Commit
b222573
·
verified ·
1 Parent(s): 3395619

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -12
app.py CHANGED
@@ -8,6 +8,7 @@ from google.genai import types
8
 
9
  app = FastAPI()
10
 
 
11
  app.add_middleware(
12
  CORSMiddleware,
13
  allow_origins=["*"],
@@ -27,18 +28,29 @@ def execute_in_sandbox(command: str):
27
  # Saari commands hamesha /tmp folder me execute hongi jahan explicit write permissions hain
28
  full_command = f"cd /tmp && {command}"
29
 
 
 
 
30
  result = subprocess.run(
31
  full_command,
32
  shell=True,
33
  capture_output=True,
34
  text=True,
35
- timeout=600 # 10 minutes max timeout per execution
 
 
36
  )
37
  return {
38
  "stdout": result.stdout,
39
  "stderr": result.stderr,
40
  "exit_code": result.returncode
41
  }
 
 
 
 
 
 
42
  except Exception as e:
43
  return {"error": str(e)}
44
 
@@ -46,6 +58,7 @@ def execute_in_sandbox(command: str):
46
  async def agent_chat(request: ChatRequest):
47
  user_prompt = request.message
48
 
 
49
  system_instruction = (
50
  "You are an expert AI Agent Builder operating inside a fully equipped Linux sandbox.\n\n"
51
  "YOUR DEVELOPMENT ENVIRONMENT capabilities:\n"
@@ -53,31 +66,68 @@ async def agent_chat(request: ChatRequest):
53
  "- **Flutter & Dart SDK** are pre-installed globally. You can run `flutter create` and `flutter build apk --release`.\n"
54
  "- **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"
55
  "- You CANNOT use 'sudo'. Perform all workspace creation inside the `/tmp` directory.\n\n"
56
- "GOFILE.IO UPLOAD RULES:\n"
57
- "To upload a compiled file or APK, you MUST follow these exact steps in your bash script:\n"
58
- "1. Fetch an active server name: SERVER_NAME=$(curl -s https://api.gofile.io/getServer | grep -oP '\"server\":\"\\K[^\"]+')\n"
59
- "2. Upload using that server: UPLOAD_RESPONSE=$(curl -F \"file=@path_to_your_file\" https://${SERVER_NAME}.gofile.io/uploadFile)\n"
60
- "3. Extract download link: DOWNLOAD_LINK=$(echo \"${UPLOAD_RESPONSE}\" | grep -oP '\"downloadPage\":\"\\K[^\"]+')\n\n"
61
- "If you want to create a project, write python scripts, or build an APK, output the exact script inside a triple backtick block starting with 'bash'."
62
  )
63
 
64
  try:
65
- response = client.models.generate_content(
 
66
  model='gemini-2.5-flash',
67
- contents=user_prompt,
68
  config=types.GenerateContentConfig(system_instruction=system_instruction)
69
  )
70
 
 
 
71
  ai_response = response.text
72
 
73
- if "```bash" in ai_response:
 
 
 
 
 
74
  parts = ai_response.split("```bash")
75
  if len(parts) > 1:
76
  command = parts[1].split("```")[0].strip()
 
 
77
  exec_result = execute_in_sandbox(command)
78
- return {"agent_response": ai_response, "execution_result": exec_result}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- return {"agent_response": ai_response}
 
 
 
 
81
 
82
  except Exception as e:
83
  raise HTTPException(status_code=500, detail=str(e))
 
8
 
9
  app = FastAPI()
10
 
11
+ # CORS Configurations - Saari settings pehle jaisi safe hain
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
 
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(
35
  full_command,
36
  shell=True,
37
  capture_output=True,
38
  text=True,
39
+ errors="replace", # Large logs ya binary text par crash hone se bachata hai
40
+ timeout=300, # 5 minutes optimized timeout taaki HF gateway connection drop na kare
41
+ env=env
42
  )
43
  return {
44
  "stdout": result.stdout,
45
  "stderr": result.stderr,
46
  "exit_code": result.returncode
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 {"error": str(e)}
56
 
 
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
  "- **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
+ "GENERAL EXECUTION & UPLOAD RULES:\n"
70
+ "- You have full internet access inside the sandbox. You can download dependencies, interact with external APIs, or upload compilation artifacts (APKs, files, logs) to any hosting provider using tools like 'curl' or custom Python scripts.\n"
71
+ "- If the user asks you to upload a file to a specific platform (e.g., gofile.io, catbox, etc.) or perform an external operation, use your general knowledge to draft the correct API calls or bash routines using available environment variables.\n\n"
72
+ "OUTPUT FORMATTING:\n"
73
+ "If you want to create a project, write python scripts, compile an application, or run diagnostics, output the exact script inside a single triple backtick block starting with 'bash'.\n"
74
+ "Analyze the tool execution results carefully in each turn. If a command fails or throws an error, analyze the output, debug it, fix your script, and re-run it until the task is successfully completed. Once done, present a clean summary or download links to the user."
75
  )
76
 
77
  try:
78
+ # Multi-turn Chat session taaki AI background me tools chala sake
79
+ chat = client.chats.create(
80
  model='gemini-2.5-flash',
 
81
  config=types.GenerateContentConfig(system_instruction=system_instruction)
82
  )
83
 
84
+ # Turn 1: User ka input bhejte hain
85
+ response = chat.send_message(user_prompt)
86
  ai_response = response.text
87
 
88
+ max_loops = 4 # Infinite loops aur HF memory crash se bachne ke liye safe limit
89
+ current_loop = 0
90
+ execution_history = []
91
+
92
+ # SOLID AGENT LOOP: Jab tak AI bash block dega, tab tak loop chalega
93
+ while "```bash" in ai_response and current_loop < max_loops:
94
  parts = ai_response.split("```bash")
95
  if len(parts) > 1:
96
  command = parts[1].split("```")[0].strip()
97
+
98
+ # Command ko sandbox me run karein
99
  exec_result = execute_in_sandbox(command)
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
+ # AI ko feedback bhej kar agla turn check karte hain
121
+ response = chat.send_message(feedback)
122
+ ai_response = response.text
123
+
124
+ current_loop += 1
125
 
126
+ # UI par clean output dikhane ke liye execution history aur final text ko alag kar diya
127
+ return {
128
+ "agent_response": ai_response,
129
+ "execution_history": execution_history if execution_history else None
130
+ }
131
 
132
  except Exception as e:
133
  raise HTTPException(status_code=500, detail=str(e))