Spaces:
Paused
Paused
fix pygmay
Browse files- pygmyclaw.py +77 -62
pygmyclaw.py
CHANGED
|
@@ -15,11 +15,8 @@ from huggingface_hub import hf_hub_download, upload_file
|
|
| 15 |
|
| 16 |
# -------------------- Globals --------------------
|
| 17 |
SCRIPT_DIR = Path(__file__).parent.resolve()
|
| 18 |
-
import os
|
| 19 |
-
|
| 20 |
DEFAULT_MODEL = os.environ.get("MODEL_NAME", "qwen3.5:0.8b")
|
| 21 |
-
print("pymyclass loaded and default model is ")
|
| 22 |
-
print(DEFAULT_MODEL)
|
| 23 |
DEFAULT_ENDPOINT = "http://localhost:11434/api/generate"
|
| 24 |
|
| 25 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
@@ -49,7 +46,6 @@ def download_hf_files():
|
|
| 49 |
local_path.write_text("{}")
|
| 50 |
print(f"Created empty {file_name}")
|
| 51 |
|
| 52 |
-
|
| 53 |
# -------------------- PygmyClaw Agent --------------------
|
| 54 |
class PygmyClaw:
|
| 55 |
def __init__(self):
|
|
@@ -176,7 +172,7 @@ class PygmyClaw:
|
|
| 176 |
exec(prompt, {}, local_vars)
|
| 177 |
result = str(local_vars)
|
| 178 |
else:
|
| 179 |
-
result = self.
|
| 180 |
print("Raw output to upload:")
|
| 181 |
print(result)
|
| 182 |
|
|
@@ -202,68 +198,87 @@ class PygmyClaw:
|
|
| 202 |
time.sleep(0.1)
|
| 203 |
return self.memory_data[task_id]["response"]
|
| 204 |
|
| 205 |
-
# -------------------- Model / Ollama call --------------------
|
| 206 |
-
def generate_with_ssd_cli(self, prompt: str, model: str = DEFAULT_MODEL):
|
| 207 |
-
"""
|
| 208 |
-
Run the model via Ollama CLI instead of HTTP request.
|
| 209 |
-
"""
|
| 210 |
-
import subprocess
|
| 211 |
-
|
| 212 |
-
try:
|
| 213 |
-
result = subprocess.run(
|
| 214 |
-
["ollama", "run", model, prompt],
|
| 215 |
-
capture_output=True,
|
| 216 |
-
text=True,
|
| 217 |
-
timeout=120
|
| 218 |
-
)
|
| 219 |
-
output = result.stdout.strip() if result.stdout else result.stderr.strip()
|
| 220 |
-
print('Run subprocess command:')
|
| 221 |
-
print(output)
|
| 222 |
-
return output
|
| 223 |
-
except subprocess.TimeoutExpired:
|
| 224 |
-
return "⏱️ Ollama CLI timed out."
|
| 225 |
-
except Exception as e:
|
| 226 |
-
return f"❌ Ollama CLI Error: {str(e)}"
|
| 227 |
-
|
| 228 |
def generate_with_ssd(self, prompt, num_predict=600, timeout=120):
|
| 229 |
"""
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
"""
|
| 233 |
-
|
| 234 |
-
"model": self.model,
|
| 235 |
-
"prompt": prompt,
|
| 236 |
-
"stream": False,
|
| 237 |
-
"enable_thinking": False,
|
| 238 |
-
"options": {"num_predict": num_predict, "temperature": 0.2},
|
| 239 |
-
}
|
| 240 |
-
|
| 241 |
-
req = urllib.request.Request(
|
| 242 |
-
self.endpoint,
|
| 243 |
-
data=json.dumps(payload).encode("utf-8"),
|
| 244 |
-
headers={"Content-Type": "application/json"},
|
| 245 |
-
method="POST"
|
| 246 |
-
)
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
| 252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
try:
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
-
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
self.memory_data["last_code"] = code
|
| 266 |
|
| 267 |
-
|
| 268 |
-
except Exception as e:
|
| 269 |
-
return f"❌ Model request failed: {e}"
|
|
|
|
| 15 |
|
| 16 |
# -------------------- Globals --------------------
|
| 17 |
SCRIPT_DIR = Path(__file__).parent.resolve()
|
|
|
|
|
|
|
| 18 |
DEFAULT_MODEL = os.environ.get("MODEL_NAME", "qwen3.5:0.8b")
|
| 19 |
+
print("pymyclass loaded and default model is ", DEFAULT_MODEL)
|
|
|
|
| 20 |
DEFAULT_ENDPOINT = "http://localhost:11434/api/generate"
|
| 21 |
|
| 22 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
|
|
| 46 |
local_path.write_text("{}")
|
| 47 |
print(f"Created empty {file_name}")
|
| 48 |
|
|
|
|
| 49 |
# -------------------- PygmyClaw Agent --------------------
|
| 50 |
class PygmyClaw:
|
| 51 |
def __init__(self):
|
|
|
|
| 172 |
exec(prompt, {}, local_vars)
|
| 173 |
result = str(local_vars)
|
| 174 |
else:
|
| 175 |
+
result = self.generate_with_ssd(prompt)
|
| 176 |
print("Raw output to upload:")
|
| 177 |
print(result)
|
| 178 |
|
|
|
|
| 198 |
time.sleep(0.1)
|
| 199 |
return self.memory_data[task_id]["response"]
|
| 200 |
|
| 201 |
+
# -------------------- Unified Model / Ollama call with automatic failover --------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
def generate_with_ssd(self, prompt, num_predict=600, timeout=120):
|
| 203 |
"""
|
| 204 |
+
Automatically sends a prompt to the model endpoint or Ollama CLI.
|
| 205 |
+
- Tries HTTP first; if it fails, falls back to CLI.
|
| 206 |
+
- Caches which backend worked for future calls.
|
| 207 |
+
- Stores raw response and extracted Python code in self.memory_data.
|
| 208 |
+
|
| 209 |
+
Parameters:
|
| 210 |
+
prompt (str): Prompt for the model.
|
| 211 |
+
num_predict (int): Max tokens/predictions (for HTTP).
|
| 212 |
+
timeout (int): Request timeout in seconds.
|
| 213 |
+
|
| 214 |
+
Returns:
|
| 215 |
+
str: Full model response.
|
| 216 |
"""
|
| 217 |
+
import json, re, textwrap, subprocess, urllib.request
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
+
# Track which backend worked
|
| 220 |
+
if not hasattr(self, "_ssd_backend"):
|
| 221 |
+
self._ssd_backend = "http" # default try HTTP first
|
| 222 |
+
|
| 223 |
+
output = ""
|
| 224 |
+
backends_to_try = ["http", "cli"] if self._ssd_backend == "http" else ["cli", "http"]
|
| 225 |
|
| 226 |
+
for backend in backends_to_try:
|
| 227 |
+
if backend == "http":
|
| 228 |
+
payload = {
|
| 229 |
+
"model": self.model,
|
| 230 |
+
"prompt": prompt,
|
| 231 |
+
"stream": False,
|
| 232 |
+
"enable_thinking": False,
|
| 233 |
+
"options": {"num_predict": num_predict, "temperature": 0.2},
|
| 234 |
+
}
|
| 235 |
+
req = urllib.request.Request(
|
| 236 |
+
self.endpoint,
|
| 237 |
+
data=json.dumps(payload).encode("utf-8"),
|
| 238 |
+
headers={"Content-Type": "application/json"},
|
| 239 |
+
method="POST"
|
| 240 |
+
)
|
| 241 |
+
try:
|
| 242 |
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 243 |
+
output = resp.read().decode("utf-8")
|
| 244 |
+
self._ssd_backend = "http" # mark as working backend
|
| 245 |
+
break
|
| 246 |
+
except Exception as e:
|
| 247 |
+
output = f"❌ HTTP request failed: {e}"
|
| 248 |
+
continue
|
| 249 |
+
|
| 250 |
+
elif backend == "cli":
|
| 251 |
try:
|
| 252 |
+
result = subprocess.run(
|
| 253 |
+
["ollama", "run", self.model, prompt],
|
| 254 |
+
capture_output=True,
|
| 255 |
+
text=True,
|
| 256 |
+
timeout=timeout
|
| 257 |
+
)
|
| 258 |
+
output = result.stdout.strip() if result.stdout else result.stderr.strip()
|
| 259 |
+
self._ssd_backend = "cli" # mark as working backend
|
| 260 |
+
break
|
| 261 |
+
except subprocess.TimeoutExpired:
|
| 262 |
+
output = "⏱️ Ollama CLI timed out."
|
| 263 |
+
except Exception as e:
|
| 264 |
+
output = f"❌ CLI failed: {e}"
|
| 265 |
+
continue
|
| 266 |
+
|
| 267 |
+
# Store raw response
|
| 268 |
+
self.memory_data["last_raw_response"] = output
|
| 269 |
+
|
| 270 |
+
# Parse JSON if possible
|
| 271 |
+
try:
|
| 272 |
+
data = json.loads(output)
|
| 273 |
+
except json.JSONDecodeError:
|
| 274 |
+
data = {"response": output}
|
| 275 |
|
| 276 |
+
full_text = data.get("response", output)
|
| 277 |
|
| 278 |
+
# Extract Python code
|
| 279 |
+
code_blocks = re.findall(r"```(?:python)?\s*(.*?)```", full_text, re.S | re.I)
|
| 280 |
+
code = "\n\n".join(code_blocks)
|
| 281 |
+
code = textwrap.dedent(code).replace("\t", " ").strip()
|
| 282 |
+
self.memory_data["last_code"] = code
|
|
|
|
| 283 |
|
| 284 |
+
return full_text
|
|
|
|
|
|