pripro commited on
Commit
fe4f509
Β·
verified Β·
1 Parent(s): 20ed2ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -67
app.py CHANGED
@@ -27,16 +27,20 @@ if not os.path.exists(global_context_path):
27
  with open(global_context_path, "w") as f:
28
  f.write("# Global Context & Browser Workspace\nShared knowledge base accessible across all connected IP environments under /px.")
29
 
30
- # Zero-dependency auto-bootstrapper
31
- for package in ["gradio", "requests", "ollama", "beautifulsoup4"]:
 
32
  try:
33
- __import__(package)
 
34
  except ImportError:
35
  print(f"Installing missing dependency: {package}...")
36
  subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", package])
37
 
38
  import requests
39
- import ollama
 
 
40
  import gradio as gr
41
  from bs4 import BeautifulSoup
42
 
@@ -65,14 +69,30 @@ with open(LOG_FILE, "a") as log_file:
65
  log_file.write(log_entry)
66
 
67
  print("\n" + "=" * 65)
68
- print(f"🌐 PX TECH SOLUTIONS - EVAL BETA 0.2 AGENTIC CORE (/px)")
69
  print(f" β€’ Base Directory : {BASE_DIR}")
70
  print(f" β€’ Local URL : http://{local_ip}:7860")
71
  print(f" β€’ Server IP : {server_public_ip}")
72
- print(f" β€’ Active Engine : Bash | Write | Read | Search | Big Context")
73
  print("=" * 65 + "\n")
74
 
75
- MODEL_NAME = "smarthomemain10123/eval-beta-0.2"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  # Custom Cyber-Dark UI Styling
78
  custom_css = """
@@ -81,7 +101,7 @@ body { background-color: #0b0f19; color: #f3f4f6; }
81
  """
82
 
83
  # =====================================================================
84
- # AGENTIC TOOL DEFINITIONS (OpenCode Ecosystem)
85
  # =====================================================================
86
  tools_definition = [
87
  {
@@ -137,7 +157,6 @@ tools_definition = [
137
  }
138
  ]
139
 
140
- # Tool Executors
141
  def execute_tool(name, args, ip_folder, yolo_mode):
142
  try:
143
  if name == "bash":
@@ -181,8 +200,9 @@ def execute_tool(name, args, ip_folder, yolo_mode):
181
  return f"Tool execution failed: {str(e)}"
182
 
183
  # =====================================================================
184
- # AGENT PREDICT LOOP
185
  # =====================================================================
 
186
  def predict(message, history, system_prompt, temperature, yolo_mode, request: gr.Request):
187
  client_ip = "127.0.0.1"
188
  if request and request.headers:
@@ -221,63 +241,31 @@ def predict(message, history, system_prompt, temperature, yolo_mode, request: gr
221
  f"--- [USER IP CONTEXT] ---\nClient IP: {client_ip} | Workspace Folder: {ip_folder} | Security Mode: {security_mode}"
222
  )
223
 
224
- messages = [{"role": "system", "content": enhanced_system_prompt}]
225
  for human, assistant in history:
226
- messages.append({"role": "user", "content": human})
227
- messages.append({"role": "assistant", "content": assistant})
228
- messages.append({"role": "user", "content": message})
229
 
230
  history_log_path = os.path.join(ip_folder, "chat_history.log")
231
  with open(history_log_path, "a") as hf:
232
  hf.write(f"[{timestamp}] User (YOLO: {yolo_mode} | Sec: {security_mode}): {message}\n")
233
 
234
- max_turns = 5
235
- turn = 0
236
- accumulated_output = ""
 
 
 
 
 
 
 
237
 
238
- while turn < max_turns:
239
- turn += 1
240
- try:
241
- response = ollama.chat(
242
- model=MODEL_NAME,
243
- messages=messages,
244
- tools=tools_definition,
245
- options={"temperature": temperature}
246
- )
247
-
248
- message_resp = response.get("message", {})
249
- content = message_resp.get("content", "")
250
- tool_calls = message_resp.get("tool_calls", [])
251
-
252
- if content:
253
- accumulated_output += content
254
- yield accumulated_output
255
-
256
- if tool_calls:
257
- messages.append(message_resp)
258
- for tc in tool_calls:
259
- func = tc.get("function", {})
260
- func_name = func.get("name")
261
- func_args = func.get("arguments", {})
262
-
263
- status_msg = f"\n\nβš™οΈ `[Executing Tool: {func_name} | Args: {json.dumps(func_args)}]`...\n"
264
- accumulated_output += status_msg
265
- yield accumulated_output
266
-
267
- tool_result = execute_tool(func_name, func_args, ip_folder, yolo_mode)
268
-
269
- messages.append({
270
- 'role': 'tool',
271
- 'content': tool_result
272
- })
273
-
274
- accumulated_output += f"```output\n{tool_result}\n```\n"
275
- yield accumulated_output
276
- else:
277
- break
278
- except Exception as e:
279
- yield accumulated_output + f"\n\n⚠️ **Agent Execution Error:** {str(e)}"
280
- break
281
 
282
  with open(history_log_path, "a") as hf:
283
  hf.write(f"[{timestamp}] Assistant: {accumulated_output}\n")
@@ -293,18 +281,18 @@ def update_global_context(new_content):
293
  with gr.Blocks() as demo:
294
  gr.Markdown(
295
  """
296
- # ⚑ EVAL BETA 0.2 | PX TECH SOLUTIONS (AGENTIC OPENCODE ENVIRONMENT)
297
- ### Autonomous Environment with Full Tool-Use (Bash, File Read/Write, Web Search, Big Context) & YOLO Security Mode
298
  """
299
  )
300
 
301
  with gr.Row():
302
- gr.Markdown(f"🟒 **Status:** Active | πŸ“ **Root Path:** `{BASE_DIR}` | ⏱️ **Slot 1 Active (48h Limit)** | πŸ› οΈ **Tools Enabled:** Bash, Write, Read, Search")
303
 
304
  with gr.Accordion("βš™οΈ Engine Configuration, Global Context & YOLO Security Toggle", open=False):
305
  system_prompt_input = gr.Textbox(
306
  label="System Environment Prompt",
307
- value="You are EVAL BETA 0.2, an advanced autonomous agent with full tool capabilities (bash execution, file manipulation, big context inspection, web searching) created by Pripro / PX TECH SOLUTIONS.",
308
  lines=2
309
  )
310
  temperature_slider = gr.Slider(
@@ -334,14 +322,13 @@ with gr.Blocks() as demo:
334
  gr.Markdown(
335
  """
336
  ---
337
- **Queue Architecture & /px Layout:** Strict queue line-up (`concurrency_limit=1`) with Slot 1 allocation and 48-hour session limits. All tools operate within isolated workspace paths under `/px`.
338
  """
339
  )
340
 
341
  if __name__ == "__main__":
342
- print(f"πŸš€ Launching agentic environment under {BASE_DIR} with Slot 1 Queue & Full Tools on port 7860...")
343
  demo.queue(default_concurrency_limit=1, max_size=20)
344
- # Gradio 6 compliant theme and css passed directly to launch()
345
  demo.launch(
346
  server_name="0.0.0.0",
347
  server_port=7860,
 
27
  with open(global_context_path, "w") as f:
28
  f.write("# Global Context & Browser Workspace\nShared knowledge base accessible across all connected IP environments under /px.")
29
 
30
+ # Auto-bootstrapper for ZeroGPU environment requirements
31
+ required_packages = ["gradio==4.44.1", "requests", "spaces", "torch", "llama-cpp-python", "beautifulsoup4"]
32
+ for package in required_packages:
33
  try:
34
+ pkg_name = package.split("==")[0]
35
+ __import__(pkg_name)
36
  except ImportError:
37
  print(f"Installing missing dependency: {package}...")
38
  subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", package])
39
 
40
  import requests
41
+ import spaces
42
+ import torch
43
+ from llama_cpp import Llama
44
  import gradio as gr
45
  from bs4 import BeautifulSoup
46
 
 
69
  log_file.write(log_entry)
70
 
71
  print("\n" + "=" * 65)
72
+ print(f"🌐 PX TECH SOLUTIONS - EVAL BETA 0.2 ZEROGPU CORE (/px)")
73
  print(f" β€’ Base Directory : {BASE_DIR}")
74
  print(f" β€’ Local URL : http://{local_ip}:7860")
75
  print(f" β€’ Server IP : {server_public_ip}")
76
+ print(f" β€’ Active Engine : ZeroGPU (@spaces.GPU) | Bash | Write | Read | Search")
77
  print("=" * 65 + "\n")
78
 
79
+ # Model Loader (Lazy initialized inside ZeroGPU context)
80
+ MODEL_PATH = os.path.join(BASE_DIR, "eval-beta-0.2.gguf")
81
+ _llm_instance = None
82
+
83
+ def get_llm():
84
+ global _llm_instance
85
+ if _llm_instance is None:
86
+ print(f"πŸ“¦ Initializing model weights from {MODEL_PATH} on ZeroGPU...")
87
+ if not os.path.exists(MODEL_PATH):
88
+ print("⚠️ Warning: Model GGUF file not found in /px. Please ensure your model weights are uploaded.")
89
+ _llm_instance = Llama(
90
+ model_path=MODEL_PATH if os.path.exists(MODEL_PATH) else "model.gguf",
91
+ n_ctx=4096,
92
+ n_gpu_layers=-1, # Full GPU offload via ZeroGPU
93
+ verbose=False
94
+ )
95
+ return _llm_instance
96
 
97
  # Custom Cyber-Dark UI Styling
98
  custom_css = """
 
101
  """
102
 
103
  # =====================================================================
104
+ # AGENTIC TOOL DEFINITIONS
105
  # =====================================================================
106
  tools_definition = [
107
  {
 
157
  }
158
  ]
159
 
 
160
  def execute_tool(name, args, ip_folder, yolo_mode):
161
  try:
162
  if name == "bash":
 
200
  return f"Tool execution failed: {str(e)}"
201
 
202
  # =====================================================================
203
+ # ZEROGPU DECORATED PREDICT LOOP
204
  # =====================================================================
205
+ @spaces.GPU(duration=120)
206
  def predict(message, history, system_prompt, temperature, yolo_mode, request: gr.Request):
207
  client_ip = "127.0.0.1"
208
  if request and request.headers:
 
241
  f"--- [USER IP CONTEXT] ---\nClient IP: {client_ip} | Workspace Folder: {ip_folder} | Security Mode: {security_mode}"
242
  )
243
 
244
+ prompt = f"System: {enhanced_system_prompt}\n"
245
  for human, assistant in history:
246
+ prompt += f"<|im_start|>user\n{human}<|im_end|>\n<|im_start|>assistant\n{assistant}<|im_end|>\n"
247
+ prompt += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
 
248
 
249
  history_log_path = os.path.join(ip_folder, "chat_history.log")
250
  with open(history_log_path, "a") as hf:
251
  hf.write(f"[{timestamp}] User (YOLO: {yolo_mode} | Sec: {security_mode}): {message}\n")
252
 
253
+ llm = get_llm()
254
+
255
+ # Stream generation
256
+ output = llm(
257
+ prompt,
258
+ max_tokens=1024,
259
+ stop=["<|im_end|>", "<|im_start|>", "User:"],
260
+ temperature=temperature,
261
+ stream=True
262
+ )
263
 
264
+ accumulated_output = ""
265
+ for chunk in output:
266
+ delta = chunk["choices"][0]["text"]
267
+ accumulated_output += delta
268
+ yield accumulated_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
  with open(history_log_path, "a") as hf:
271
  hf.write(f"[{timestamp}] Assistant: {accumulated_output}\n")
 
281
  with gr.Blocks() as demo:
282
  gr.Markdown(
283
  """
284
+ # ⚑ EVAL BETA 0.2 | PX TECH SOLUTIONS (ZEROGPU AGENTIC ENVIRONMENT)
285
+ ### Autonomous Environment with ZeroGPU Acceleration, Full Tool-Use, & YOLO Security Mode
286
  """
287
  )
288
 
289
  with gr.Row():
290
+ gr.Markdown(f"🟒 **Status:** Active (ZeroGPU) | πŸ“ **Root Path:** `{BASE_DIR}` | ⏱️ **Slot 1 Active (48h Limit)** | πŸ› οΈ **Tools Enabled:** Bash, Write, Read, Search")
291
 
292
  with gr.Accordion("βš™οΈ Engine Configuration, Global Context & YOLO Security Toggle", open=False):
293
  system_prompt_input = gr.Textbox(
294
  label="System Environment Prompt",
295
+ value="You are EVAL BETA 0.2, an advanced autonomous agent with full tool capabilities created by Pripro / PX TECH SOLUTIONS.",
296
  lines=2
297
  )
298
  temperature_slider = gr.Slider(
 
322
  gr.Markdown(
323
  """
324
  ---
325
+ **Queue Architecture & /px Layout:** Strict queue line-up (`concurrency_limit=1`) with Slot 1 allocation and 48-hour session limits. Powered by Hugging Face ZeroGPU (`@spaces.GPU`).
326
  """
327
  )
328
 
329
  if __name__ == "__main__":
330
+ print(f"πŸš€ Launching ZeroGPU environment under {BASE_DIR} with Slot 1 Queue on port 7860...")
331
  demo.queue(default_concurrency_limit=1, max_size=20)
 
332
  demo.launch(
333
  server_name="0.0.0.0",
334
  server_port=7860,