-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
153 lines (133 loc) · 5.21 KB
/
Copy pathrunner.py
File metadata and controls
153 lines (133 loc) · 5.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import json
import os
import sys
import time
import getpass
from art import text2art as t2
sys.path.append(os.path.join(os.path.dirname(__file__), 'router'))
from commands import Commands
from router.gemini_provider import GeminiProvider
from router.ollama_provider import Ollama
from router.openai_provider import OpenAIProvider
from router.openrouter_provider import OpenRouterProvider
from database import Database
PICTURE_MAIN = t2("CORTEX")
CONFIG_DIR = os.path.expanduser("~/.cortex")
CONFIG_PATH = os.path.join(CONFIG_DIR, "config.json")
DEFAULT_CONFIG = {
"gemini": {
"api_key": "",
"model": "gemini-2.5-flash"
},
"openai": {
"api_key": "",
"model": "gpt-3.5-turbo"
},
"openrouter": {
"api_key": "",
"model": "meta-llama/llama-3-8b-instruct:free"
},
"ollama": {
"model": "glm-4.7-flash:latest",
"base_url": "http://localhost:11434"
},
"agents": {
"code": "ollama",
"ideas": "ollama",
"other": "ollama"
}
}
def load_config():
if not os.path.exists(CONFIG_PATH):
os.makedirs(CONFIG_DIR, exist_ok=True)
with open(CONFIG_PATH, "w") as f:
json.dump(DEFAULT_CONFIG, f, indent=4)
print(f"[SYSTEM] Config file created at: {CONFIG_PATH}")
print("[SYSTEM] Please open it, add your API keys, assign agents, and restart Cortex.")
sys.exit(0)
with open(CONFIG_PATH, "r") as f:
return json.load(f)
class Runner:
def __init__(self):
self.name = "CORTEX"
self.version = 'v0.1.0'
# 1. Запрашиваем пароль для расшифровки БД
print("--- DATABASE AUTHENTICATION ---")
pwd = getpass.getpass("Enter master password: ")
self.db = Database(pwd)
print("Database loaded successfully.\n")
# 2. Загружаем конфиг
self.config = load_config()
# 3. Инициализация провайдеров
self.providers = {
"ollama": Ollama(
model=self.config["ollama"]["model"],
url=self.config["ollama"]["base_url"]
),
"gemini": GeminiProvider(
api_key=self.config["gemini"]["api_key"],
model=self.config["gemini"]["model"]
) if self.config["gemini"]["api_key"] else None,
"openai": OpenAIProvider(
api_key=self.config["openai"]["api_key"],
model=self.config["openai"]["model"]
) if self.config["openai"]["api_key"] else None,
"openrouter": OpenRouterProvider(
api_key=self.config["openrouter"]["api_key"],
model=self.config["openrouter"]["model"]
) if self.config["openrouter"]["api_key"] else None
}
# 4. Передаем db в Commands!
self.commands_handler = Commands(
providers=self.providers,
agent_map=self.config["agents"],
config_path=CONFIG_PATH,
version=self.version,
db=self.db # ВОТ ТУТ МЫ ПЕРЕДАЕМ БАЗУ
)
def main(self):
print(PICTURE_MAIN)
print(f"Version: {self.version} | Type /help for commands\n")
while True:
try:
user_input = input("Cortex > ").strip()
if not user_input:
continue
if user_input.startswith("/message:"):
cmd_text = user_input.replace("/message:", "").strip()
self.commands_handler.message(cmd_text)
elif user_input.startswith("/new "):
chat_name = user_input.replace("/new ", "").strip()
self.commands_handler.new_chat(chat_name)
elif user_input == "/chats":
self.commands_handler.list_chats()
elif user_input.startswith("/switch "):
chat_id = user_input.replace("/switch ", "").strip()
self.commands_handler.switch_chat(chat_id)
elif user_input == "/stop":
print("Stopping Cortex...")
time.sleep(1)
sys.exit(0)
elif user_input == "/help":
self.commands_handler.help()
elif user_input == "/about":
self.commands_handler.about()
elif user_input == "/version":
self.commands_handler.version()
elif user_input == "/settings":
self.commands_handler.settings()
else:
print(f"[ERROR] Command '{user_input}' not found. Type /help")
except KeyboardInterrupt:
print("\n[SYSTEM] Cortex stopped by user.")
sys.exit(0)
except Exception as err:
print(f"[ERROR] An error occurred: {err}")
if __name__ == "__main__":
try:
app = Runner()
app.main()
except Exception as err:
print(f'[ERROR] An error has occurred: {err}')
except KeyboardInterrupt:
print("[SYSTEM] Cortex stopped by user.")