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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -29
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=["*"],
@@ -22,25 +23,36 @@ client = genai.Client(api_key=GEMINI_API_KEY)
22
  class ChatRequest(BaseModel):
23
  message: str
24
 
25
- def execute_in_sandbox(command: str):
 
 
 
 
 
26
  try:
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
 
45
  @app.post("/chat")
46
  async def agent_chat(request: ChatRequest):
@@ -51,33 +63,81 @@ async def agent_chat(request: ChatRequest):
51
  "YOUR DEVELOPMENT ENVIRONMENT capabilities:\n"
52
  "- **Python 3** is installed. You can write and execute python scripts (`python3 script.py`).\n"
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=["*"],
 
23
  class ChatRequest(BaseModel):
24
  message: str
25
 
26
+ # TOOL: Hardcore Terminal Execution System (Root Permission)
27
+ def run_terminal_command(command: str) -> str:
28
+ """
29
+ Executes any bash command inside the secure Linux sandbox workspace (/tmp).
30
+ Use this to run python scripts, compile Flutter apps, build APKs, or manage git operations (like git worktree).
31
+ """
32
  try:
 
33
  full_command = f"cd /tmp && {command}"
34
+ env = os.environ.copy()
35
 
36
  result = subprocess.run(
37
  full_command,
38
  shell=True,
39
  capture_output=True,
40
  text=True,
41
+ errors="replace",
42
+ timeout=300,
43
+ env=env
44
  )
45
+
46
+ output = f"Exit Code: {result.returncode}\n"
47
+ if result.stdout:
48
+ output += f"STDOUT:\n{result.stdout}\n"
49
+ if result.stderr:
50
+ output += f"STDERR:\n{result.stderr}\n"
51
+ return output
52
+ except subprocess.TimeoutExpired:
53
+ return "ERROR: Command execution timed out after 5 minutes to prevent server freeze."
54
  except Exception as e:
55
+ return f"SYSTEM ERROR: {str(e)}"
56
 
57
  @app.post("/chat")
58
  async def agent_chat(request: ChatRequest):
 
63
  "YOUR DEVELOPMENT ENVIRONMENT capabilities:\n"
64
  "- **Python 3** is installed. You can write and execute python scripts (`python3 script.py`).\n"
65
  "- **Flutter & Dart SDK** are pre-installed globally. You can run `flutter create` and `flutter build apk --release`.\n"
66
+ "- **Android Native Build System** is pre-installed. Full OpenJDK 17, Android SDK (API 34), Build-Tools (34.0.0), and Gradle Build Binary are ready. You can create Native Android apps (using gradle wrappers) and build them directly.\n"
67
+ "- **HOP-AI SDK** is pre-installed. You can use 'import hop' in your python scripts to interact with remote cloud volumes, manage infrastructure, or offload long-running tasks if necessary.\n"
68
+ "- You are operating with full administrative permissions inside the `/tmp` directory.\n\n"
69
+ "YOUR AVAILABLE TOOLS:\n"
70
+ "- `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"
71
+ "- `Google Search`: You have native access to live Google Search. Use it automatically whenever you need to look up documentation for APIs (like catbox.moe, gofile.io, transfer.sh), research web endpoints, check dependency updates, or debug compilation errors.\n\n"
72
+ "CRITICAL APPLICATION GENERATION RULES:\n"
73
+ "- The workspace sandbox is initially empty. There are no pre-existing Android or Flutter templates inside `/tmp`. If you are tasked to create an app, you MUST programmatically write and create every single source directory, file structure, configuration script, layout resource, and source file entirely from scratch.\n"
74
+ "- Always use standard POSIX compatible shell scripting loops (e.g., `for i in 1 2 3; do ... done`) instead of advanced bash-specific loops like `for ((i=0; i<3; i++))` because the sandbox default runtime shell executor is `/bin/sh`.\n\n"
75
+ "ADVANCED GIT WORKSPACE MANAGEMENT:\n"
76
+ "- You are encouraged to use `git worktree` when managing parallel tasks, feature implementations, or isolated testing branches. Instead of risky checkout switching or stashing uncommitted modifications, utilize `git worktree add -b <branch-name> <path>` to spin up isolated, standalone directories inside `/tmp` for separate branches. This keeps the main codebase safe and unpolluted during builds.\n\n"
77
+ "CRITICAL EXECUTION RULES:\n"
78
+ "- Analyze tool execution outputs carefully. If a command or build script fails, analyze the error log, use Google Search to find a solution or documentation if needed, self-correct, update your code, and execute again until successful.\n"
79
+ "- Once the objective is completed successfully (e.g., app compiled or file uploaded), present a clean summary and direct download links to the user."
80
  )
81
 
82
  try:
83
+ # Custom functional tools mapping
84
+ custom_tools = {
85
+ "run_terminal_command": run_terminal_command
86
+ }
87
+
88
+ # Gemma-2-9b-it model configurations
89
+ config = types.GenerateContentConfig(
90
+ system_instruction=system_instruction,
91
+ tools=[run_terminal_command, {'google_search': {}}],
92
+ temperature=0.2
93
  )
94
 
95
+ # Chat session explicitly locked to Gemma
96
+ chat = client.chats.create(model='gemma2-9b-it', config=config)
97
+ response = chat.send_message(user_prompt)
98
 
99
+ max_turns = 6
100
+ current_turn = 0
101
+ execution_history = []
102
+
103
+ # AGENT EXECUTION LOOP
104
+ while response.function_calls and current_turn < max_turns:
105
+ function_responses = []
106
+
107
+ for function_call in response.function_calls:
108
+ name = function_call.name
109
+ args = function_call.args
110
+ call_id = function_call.id
111
+
112
+ if name in custom_tools:
113
+ tool_output = custom_tools[name](**args)
114
+
115
+ execution_history.append({
116
+ "turn": current_turn + 1,
117
+ "tool_called": name,
118
+ "arguments": args,
119
+ "raw_output": tool_output
120
+ })
121
+
122
+ function_responses.append(
123
+ types.Part.from_function_response(
124
+ name=name,
125
+ response={"result": tool_output},
126
+ id=call_id
127
+ )
128
+ )
129
+
130
+ if function_responses:
131
+ response = chat.send_message(function_responses)
132
+ else:
133
+ break
134
+
135
+ current_turn += 1
136
 
137
+ return {
138
+ "agent_response": response.text,
139
+ "execution_history": execution_history if execution_history else None
140
+ }
141
 
142
  except Exception as e:
143
  raise HTTPException(status_code=500, detail=str(e))