Skip to content

Commit 938ce29

Browse files
committed
v0.1.1: Added flexfible agent settings and smart db
1 parent f7bd903 commit 938ce29

7 files changed

Lines changed: 49 additions & 25 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# **Cortex**
44
Secure Multi-Agent AI Framework
55

6-
[![Cortex: 0.1.0](https://img.shields.io/badge/Version-v0.1.0-blue?style=flat-square)](https://github.com/Alexx-coder/Cortex.git)
6+
[![Cortex: 0.1.1](https://img.shields.io/badge/Version-v0.1.1-blue?style=flat-square)](https://github.com/Alexx-coder/Cortex.git)
77
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)](https://opensource.org/licenses/MIT)
88
[![Python 3.8+](https://img.shields.io/badge/Python-3.8+-green?style=flat-square&logo=python)](https://www.python.org/downloads/)
99
[![Encryption: Fernet AES](https://img.shields.io/badge/Encryption-Fernet_AES-red?style=flat-square&logo=datadog)](https://cryptography.io/en/latest/fernet/)
264 Bytes
Binary file not shown.

commands.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,11 @@ def message(self, full_input):
9292
print(f"[ERROR] Agent '{agent_name}' does not exist. Available: {', '.join(self.agent_map.keys())}")
9393
return
9494

95-
provider_name = self.agent_map[agent_name]
95+
agent_settings = self.agent_map[agent_name]
96+
provider_name = agent_settings.get("provider")
97+
temperature = agent_settings.get("temperature", 0.7)
98+
max_tokens = agent_settings.get("max_tokens", 4096)
99+
96100
agent_provider = self.providers.get(provider_name)
97101

98102
if not agent_provider:
@@ -104,15 +108,18 @@ def message(self, full_input):
104108

105109
print(f"\n[{agent_name.upper()}] Thinking...")
106110

107-
# Сохраняем запрос пользователя в историю ПЕРЕД отправкой
108111
self.db.add_message("user", prompt_text)
109112

110113
try:
111-
# Отправляем историю в ИИ
112-
response = agent_provider.chat(prompt_text, system=system_prompt, history=history)
114+
response = agent_provider.chat(
115+
prompt_text,
116+
system=system_prompt,
117+
history=history,
118+
temperature=temperature,
119+
max_tokens=max_tokens
120+
)
113121
print(f"\n[{agent_name.upper()}]:\n{response}\n")
114122

115-
# Сохраняем ответ ИИ в историю
116123
self.db.add_message("assistant", response)
117124

118125
except Exception as e:

database.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ def __init__(self, password: str, db_path: str = None):
1919
self.data = self._load()
2020

2121
def _load(self):
22-
# Используем self.db_path вместо старого DB_PATH
2322
if not os.path.exists(self.db_path) or os.path.getsize(self.db_path) == 0:
2423
return {"active_chat": None, "chats": {}}
2524

@@ -30,24 +29,29 @@ def _load(self):
3029
return {"active_chat": None, "chats": {}}
3130

3231
try:
33-
# Дешифруем сырые байты из файла
3432
decrypted_bytes = self.cipher.decrypt(encrypted_data)
3533
json_string = decrypted_bytes.decode('utf-8')
3634
return json.loads(json_string)
3735
except Exception as e:
38-
print(f"[ERROR] Failed to decrypt database. Wrong password? Details: {e}")
39-
exit(1)
36+
print(f"\n[CRITICAL ERROR] Failed to decrypt database.")
37+
print(f"Reason: {str(e) or 'Database file is corrupted or wrong password.'}")
38+
39+
choice = input("Do you want to DELETE the corrupted database and start fresh? (y/n): ").strip().lower()
40+
if choice == 'y':
41+
os.remove(self.db_path)
42+
print("[SYSTEM] Corrupted database deleted. Starting with a clean slate.")
43+
return {"active_chat": None, "chats": {}}
44+
else:
45+
print("[SYSTEM] Exiting. Please check your password or database file manually.")
46+
exit(1)
4047

4148
def _save(self):
4249
json_string = json.dumps(self.data, indent=4, ensure_ascii=False)
4350

4451
try:
45-
# Шифруем строку JSON, получаем байты
4652
encrypted_data = self.cipher.encrypt(json_string.encode('utf-8'))
4753

48-
# Используем self.db_path!
4954
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
50-
# Записываем зашифрованные байты
5155
with open(self.db_path, "wb") as f:
5256
f.write(encrypted_data)
5357
except Exception as e:
@@ -77,7 +81,7 @@ def add_message(self, role: str, content: str):
7781
self._save()
7882

7983
def list_chats(self):
80-
return [f"{cid}: {info['name']} ({len(info['history'])} messages)" for cid, info in self.data['chats'].items()]
84+
return [f"{cid}: { info['name']} ({len(info['history'])} messages)" for cid, info in self.data['chats'].items()]
8185

8286
def switch_chat(self, chat_id: str):
8387
if chat_id in self.data['chats']:
153 Bytes
Binary file not shown.

router/ollama_provider.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,30 @@ def list_models(self):
2121
except requests.RequestException:
2222
return []
2323

24-
def chat(self, prompt: str, system: Optional[str] = None, history: list = None) -> str:
24+
def chat(self, prompt: str, system: Optional[str] = None, history: list = None, temperature: float = 0.7, max_tokens: int = 4096) -> str:
2525
if not self.model:
2626
return "[ERROR] No Ollama model selected in config.json."
2727

28-
# Берем старую историю, если она есть
2928
messages = history.copy() if history else []
3029

31-
# Вставляем системный промпт в начало, если его там нет
3230
if system:
3331
if not messages or messages[0].get("role") != "system":
3432
messages.insert(0, {"role": "system", "content": system})
3533

36-
# Добавляем новое сообщение пользователя
3734
messages.append({"role": "user", "content": prompt})
3835

3936
try:
4037
r = requests.post(
4138
f"{self.url}/api/chat",
42-
json={"model": self.model, "messages": messages, "stream": False},
39+
json={
40+
"model": self.model,
41+
"messages": messages,
42+
"stream": False,
43+
"options": {
44+
"temperature": temperature,
45+
"num_predict": max_tokens
46+
}
47+
},
4348
timeout=300,
4449
)
4550
r.raise_for_status()

runner.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,18 +59,27 @@ def load_config():
5959
class Runner:
6060
def __init__(self):
6161
self.name = "CORTEX"
62-
self.version = 'v0.1.0'
62+
self.version = 'v0.1.1'
6363

64-
# 1. Запрашиваем пароль для расшифровки БД
6564
print("--- DATABASE AUTHENTICATION ---")
6665
pwd = getpass.getpass("Enter master password: ")
6766
self.db = Database(pwd)
6867
print("Database loaded successfully.\n")
6968

70-
# 2. Загружаем конфиг
7169
self.config = load_config()
70+
71+
self.config = load_config()
72+
73+
74+
for agent_name, agent_value in self.config["agents"].items():
75+
if isinstance(agent_value, str):
76+
self.config["agents"][agent_name] = {
77+
"provider": agent_value,
78+
"temperature": 0.7,
79+
"max_tokens": 4096
80+
}
81+
7282

73-
# 3. Инициализация провайдеров
7483
self.providers = {
7584
"ollama": Ollama(
7685
model=self.config["ollama"]["model"],
@@ -92,13 +101,12 @@ def __init__(self):
92101
) if self.config["openrouter"]["api_key"] else None
93102
}
94103

95-
# 4. Передаем db в Commands!
96104
self.commands_handler = Commands(
97105
providers=self.providers,
98106
agent_map=self.config["agents"],
99107
config_path=CONFIG_PATH,
100108
version=self.version,
101-
db=self.db # ВОТ ТУТ МЫ ПЕРЕДАЕМ БАЗУ
109+
db=self.db
102110
)
103111

104112
def main(self):

0 commit comments

Comments
 (0)