Spaces:
Runtime error
Runtime error
Delete server/universal_agent.py
Browse files- server/universal_agent.py +0 -145
server/universal_agent.py
DELETED
|
@@ -1,145 +0,0 @@
|
|
| 1 |
-
"""Универсальный агент с поддержкой Open Interpreter"""
|
| 2 |
-
|
| 3 |
-
import json
|
| 4 |
-
import urllib.request
|
| 5 |
-
import re
|
| 6 |
-
from typing import Dict, List, Optional, Any
|
| 7 |
-
from .models import Role, ModelConfig
|
| 8 |
-
from .config import API_KEY, API_BASE, HF_TOKEN
|
| 9 |
-
from .file_manager import FILE_MANAGER
|
| 10 |
-
from .internet_agent import INTERNET_AGENT
|
| 11 |
-
from .notification_system import NOTIFICATIONS
|
| 12 |
-
from .process_manager import PROCESS_MANAGER
|
| 13 |
-
from .state import STATE
|
| 14 |
-
|
| 15 |
-
class UniversalAgent:
|
| 16 |
-
def __init__(self, role: Role, model: ModelConfig, use_interpreter: bool = False):
|
| 17 |
-
self.role = role
|
| 18 |
-
self.model = model
|
| 19 |
-
self.use_interpreter = use_interpreter
|
| 20 |
-
self.conversation_history: List[Dict[str, str]] = []
|
| 21 |
-
self.file_manager = FILE_MANAGER
|
| 22 |
-
self.internet = INTERNET_AGENT
|
| 23 |
-
self.notifications = NOTIFICATIONS
|
| 24 |
-
self.tools = {
|
| 25 |
-
"search_web": self.internet.search_web,
|
| 26 |
-
"fetch_page": self.internet.fetch_page,
|
| 27 |
-
"analyze_website": self.internet.analyze_website,
|
| 28 |
-
"read_file": self.file_manager.read_file,
|
| 29 |
-
"save_file": self.file_manager.save_file,
|
| 30 |
-
"list_files": self.file_manager.list_files,
|
| 31 |
-
"analyze_file": self.file_manager.analyze_file,
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
def _add_tools_to_task(self, task: str) -> str:
|
| 35 |
-
tools_desc = "\n\nAVAILABLE TOOLS:\n"
|
| 36 |
-
for name, func in self.tools.items():
|
| 37 |
-
tools_desc += f"- {name}: {func.__doc__ or 'No description'}\n"
|
| 38 |
-
tools_desc += "\nUse tools when needed. Return results in natural language."
|
| 39 |
-
return task + tools_desc
|
| 40 |
-
|
| 41 |
-
def execute(self, task: str, sys_prompt_override: str = None, chat_id: str = None,
|
| 42 |
-
history: List[Dict[str, str]] = None, mode: str = "chat") -> str:
|
| 43 |
-
if self.use_interpreter and mode in ("skill", "build"):
|
| 44 |
-
return self._execute_with_interpreter(task, chat_id, mode)
|
| 45 |
-
return self._execute_with_api(task, sys_prompt_override, chat_id, history, mode)
|
| 46 |
-
|
| 47 |
-
def _execute_with_interpreter(self, task: str, chat_id: str = None, mode: str = "chat") -> str:
|
| 48 |
-
try:
|
| 49 |
-
from interpreter import interpreter
|
| 50 |
-
configure_interpreter_for_model(self.model.name)
|
| 51 |
-
base_instructions = interpreter.custom_instructions or ""
|
| 52 |
-
interpreter.custom_instructions = base_instructions + f"\n\nCURRENT ROLE: {self.role.name}\n{self.role.prompt}"
|
| 53 |
-
messages = interpreter.chat(task, display=False)
|
| 54 |
-
interpreter.custom_instructions = base_instructions
|
| 55 |
-
if messages and len(messages) > 0:
|
| 56 |
-
return messages[-1].get("content", "Done")
|
| 57 |
-
return "No response from interpreter"
|
| 58 |
-
except Exception as e:
|
| 59 |
-
return f"Interpreter error: {e}. Falling back to API..."
|
| 60 |
-
|
| 61 |
-
def _execute_with_api(self, task: str, sys_prompt_override: str = None, chat_id: str = None,
|
| 62 |
-
history: List[Dict[str, str]] = None, mode: str = "chat") -> str:
|
| 63 |
-
system_prompt = sys_prompt_override or self.role.prompt
|
| 64 |
-
messages = [{"role": "system", "content": system_prompt}]
|
| 65 |
-
if history:
|
| 66 |
-
for h in history[-10:]:
|
| 67 |
-
messages.append({"role": h.get("role", "user"), "content": h.get("content", "")})
|
| 68 |
-
messages.append({"role": "user", "content": task})
|
| 69 |
-
|
| 70 |
-
if self.model.provider == "hf":
|
| 71 |
-
return self._call_hf(messages, chat_id)
|
| 72 |
-
return self._call_openai_compatible(messages, chat_id)
|
| 73 |
-
|
| 74 |
-
def _call_openai_compatible(self, messages: List[Dict], chat_id: str = None) -> str:
|
| 75 |
-
url = f"{API_BASE}/chat/completions"
|
| 76 |
-
data = json.dumps({
|
| 77 |
-
"model": self.model.endpoint,
|
| 78 |
-
"messages": messages,
|
| 79 |
-
"temperature": 0.7,
|
| 80 |
-
"max_tokens": self.model.max_tokens
|
| 81 |
-
}).encode('utf-8')
|
| 82 |
-
req = urllib.request.Request(url, data=data, headers={
|
| 83 |
-
"Authorization": f"Bearer {API_KEY}",
|
| 84 |
-
"Content-Type": "application/json"
|
| 85 |
-
})
|
| 86 |
-
try:
|
| 87 |
-
with urllib.request.urlopen(req, timeout=45) as response:
|
| 88 |
-
res = json.loads(response.read().decode('utf-8'))
|
| 89 |
-
return res['choices'][0]['message']['content']
|
| 90 |
-
except Exception as primary_error:
|
| 91 |
-
return self._tiered_fallback(messages, primary_error, chat_id)
|
| 92 |
-
|
| 93 |
-
def _call_hf(self, messages: List[Dict], chat_id: str = None) -> str:
|
| 94 |
-
url = "https://api-inference.huggingface.co/v1/chat/completions"
|
| 95 |
-
data = json.dumps({
|
| 96 |
-
"model": self.model.endpoint,
|
| 97 |
-
"messages": messages,
|
| 98 |
-
"temperature": 0.7,
|
| 99 |
-
"max_tokens": self.model.max_tokens
|
| 100 |
-
}).encode('utf-8')
|
| 101 |
-
req = urllib.request.Request(url, data=data, headers={
|
| 102 |
-
"Authorization": f"Bearer {HF_TOKEN}",
|
| 103 |
-
"Content-Type": "application/json"
|
| 104 |
-
})
|
| 105 |
-
try:
|
| 106 |
-
with urllib.request.urlopen(req, timeout=60) as response:
|
| 107 |
-
res = json.loads(response.read().decode('utf-8'))
|
| 108 |
-
return res['choices'][0]['message']['content']
|
| 109 |
-
except Exception as e:
|
| 110 |
-
return f"HF API Error: {e}"
|
| 111 |
-
|
| 112 |
-
def _tiered_fallback(self, messages: List[Dict], primary_error, chat_id: str = None) -> str:
|
| 113 |
-
if chat_id:
|
| 114 |
-
from .telegram_utils import send_tg
|
| 115 |
-
send_tg(chat_id, f"⚠️ {self.model.name} failed: {primary_error}. Trying fallback...")
|
| 116 |
-
tried = [self.model.name]
|
| 117 |
-
current = self.model.name
|
| 118 |
-
while True:
|
| 119 |
-
next_model = STATE.get_next_tier_model(current)
|
| 120 |
-
if not next_model or next_model in tried:
|
| 121 |
-
break
|
| 122 |
-
tried.append(next_model)
|
| 123 |
-
model_cfg = STATE.models.get(next_model)
|
| 124 |
-
if not model_cfg:
|
| 125 |
-
break
|
| 126 |
-
try:
|
| 127 |
-
agent = UniversalAgent(self.role, model_cfg)
|
| 128 |
-
result = agent._call_hf(messages, chat_id) if model_cfg.provider == "hf" else agent._call_openai_compatible(messages, chat_id)
|
| 129 |
-
return result + f"\n\n_(Fallback via {next_model})_"
|
| 130 |
-
except Exception as e:
|
| 131 |
-
current = next_model
|
| 132 |
-
continue
|
| 133 |
-
return self._fallback_hf(messages, primary_error, chat_id, tried)
|
| 134 |
-
|
| 135 |
-
def _fallback_hf(self, messages: List[Dict], primary_error, chat_id: str = None, tried_models: List[str] = None) -> str:
|
| 136 |
-
if not HF_TOKEN:
|
| 137 |
-
return f"API Error: {primary_error}. No HF_TOKEN for backup."
|
| 138 |
-
fallback = STATE.models.get("hf_fallback")
|
| 139 |
-
if not fallback:
|
| 140 |
-
return f"API Error: {primary_error}. HF fallback not configured."
|
| 141 |
-
try:
|
| 142 |
-
result = self._call_hf(messages, chat_id)
|
| 143 |
-
return result + "\n\n_(Context saved via HF Serverless)_"
|
| 144 |
-
except Exception as hf_error:
|
| 145 |
-
return f"Both systems failed.\n1. API: {primary_error}\n2. HF Fallback: {hf_error}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|