Add files via upload
This commit is contained in:
19 files changed
+1527
No files matched your search
@@ -0,0 +1 @@
|
||||
#memory package
|
||||
@@ -0,0 +1,80 @@
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
def get_base_dir():
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
BASE_DIR = get_base_dir()
|
||||
CONFIG_DIR = BASE_DIR / "config"
|
||||
CONFIG_FILE = CONFIG_DIR / "api_keys.json"
|
||||
|
||||
def ensure_config_dir() -> None:
|
||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def config_exists() -> bool:
|
||||
return CONFIG_FILE.exists()
|
||||
|
||||
def save_api_keys(
|
||||
openrouter_api_key: str | None = None,
|
||||
serpapi_api_key: str | None = None
|
||||
) -> None:
|
||||
"""
|
||||
Saves API keys into config/api_keys.json
|
||||
Only overwrites keys that are provided.
|
||||
"""
|
||||
|
||||
ensure_config_dir()
|
||||
|
||||
data: dict = {}
|
||||
|
||||
if CONFIG_FILE.exists():
|
||||
try:
|
||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
data = {}
|
||||
|
||||
if openrouter_api_key is not None:
|
||||
data["openrouter_api_key"] = openrouter_api_key.strip()
|
||||
|
||||
if serpapi_api_key is not None:
|
||||
data["serpapi_api_key"] = serpapi_api_key.strip()
|
||||
|
||||
CONFIG_FILE.write_text(
|
||||
json.dumps(data, indent=2),
|
||||
encoding="utf-8"
|
||||
)
|
||||
|
||||
def load_api_keys() -> dict:
|
||||
if not CONFIG_FILE.exists():
|
||||
return {}
|
||||
|
||||
try:
|
||||
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
except Exception as e:
|
||||
print(f"❌ Failed to load api_keys.json: {e}")
|
||||
return {}
|
||||
|
||||
def get_openrouter_key() -> str | None:
|
||||
return load_api_keys().get("openrouter_api_key")
|
||||
|
||||
|
||||
def get_serpapi_key() -> str | None:
|
||||
return load_api_keys().get("serpapi_api_key")
|
||||
|
||||
def is_openrouter_configured() -> bool:
|
||||
key = get_openrouter_key()
|
||||
return bool(key and len(key) > 15)
|
||||
|
||||
|
||||
def is_serpapi_configured() -> bool:
|
||||
key = get_serpapi_key()
|
||||
return bool(key and len(key) > 10)
|
||||
|
||||
|
||||
def is_fully_configured() -> bool:
|
||||
return is_openrouter_configured() and is_serpapi_configured()
|
||||
@@ -0,0 +1,83 @@
|
||||
# memory/memory_manager.py
|
||||
import json
|
||||
import os
|
||||
from threading import Lock
|
||||
from datetime import datetime
|
||||
|
||||
MEMORY_PATH = "memory/memory.json"
|
||||
_lock = Lock()
|
||||
|
||||
|
||||
def _empty_memory() -> dict:
|
||||
"""Return an empty memory structure."""
|
||||
return {
|
||||
"identity": {},
|
||||
"preferences": {},
|
||||
"relationships": {},
|
||||
"emotional_state": {}
|
||||
}
|
||||
|
||||
|
||||
def load_memory() -> dict:
|
||||
"""Load memory from disk, return empty if not exists or invalid."""
|
||||
if not os.path.exists(MEMORY_PATH):
|
||||
return _empty_memory()
|
||||
|
||||
with _lock:
|
||||
try:
|
||||
with open(MEMORY_PATH, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
return _empty_memory()
|
||||
except Exception:
|
||||
return _empty_memory()
|
||||
|
||||
|
||||
def save_memory(memory: dict) -> None:
|
||||
"""Save memory to disk safely."""
|
||||
if not isinstance(memory, dict):
|
||||
return
|
||||
|
||||
os.makedirs(os.path.dirname(MEMORY_PATH), exist_ok=True)
|
||||
|
||||
with _lock:
|
||||
with open(MEMORY_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(memory, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
def _recursive_update(target: dict, updates: dict) -> bool:
|
||||
"""Recursively merge updates into target memory. Returns True if changed."""
|
||||
changed = False
|
||||
now = datetime.utcnow().isoformat() + "Z"
|
||||
|
||||
for key, value in updates.items():
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
continue
|
||||
|
||||
if isinstance(value, dict) and "value" not in value:
|
||||
if key not in target or not isinstance(target[key], dict):
|
||||
target[key] = {}
|
||||
changed = True
|
||||
if _recursive_update(target[key], value):
|
||||
changed = True
|
||||
else:
|
||||
|
||||
entry = value if isinstance(value, dict) and "value" in value else {"value": value}
|
||||
if key not in target or target[key] != entry:
|
||||
target[key] = entry
|
||||
changed = True
|
||||
|
||||
return changed
|
||||
|
||||
|
||||
def update_memory(memory_update: dict) -> dict:
|
||||
"""Merge LLM memory update into global memory and save."""
|
||||
if not isinstance(memory_update, dict):
|
||||
return load_memory()
|
||||
|
||||
memory = load_memory()
|
||||
if _recursive_update(memory, memory_update):
|
||||
save_memory(memory)
|
||||
|
||||
return memory
|
||||
@@ -0,0 +1,136 @@
|
||||
# memory/temporary_memory.py
|
||||
from typing import Any
|
||||
|
||||
|
||||
class TemporaryMemory:
|
||||
"""
|
||||
Temporary runtime memory (session-only).
|
||||
Resets when program restarts.
|
||||
|
||||
Purpose:
|
||||
- Track multi-step intents
|
||||
- Keep short conversation context
|
||||
- Store last actions (search / open_app)
|
||||
- Support follow-up questions like:
|
||||
"why did he executed?"
|
||||
"""
|
||||
|
||||
def __init__(self, max_history: int = 5):
|
||||
self.max_history = max_history
|
||||
self.reset()
|
||||
|
||||
|
||||
def reset(self):
|
||||
self.pending_intent: str | None = None
|
||||
self.parameters: dict[str, Any] = {}
|
||||
self.current_question: str | None = None
|
||||
|
||||
self.last_user_text: str | None = None
|
||||
self.last_ai_response: str | None = None
|
||||
|
||||
# --- Action memory ---
|
||||
self.last_search: dict | None = None
|
||||
self.last_opened_app: str | None = None
|
||||
|
||||
# --- Conversation ---
|
||||
self.conversation_history: list[dict[str, str]] = []
|
||||
|
||||
|
||||
def set_pending_intent(self, intent: str):
|
||||
self.pending_intent = intent
|
||||
|
||||
def clear_pending_intent(self):
|
||||
self.pending_intent = None
|
||||
self.parameters = {}
|
||||
self.current_question = None
|
||||
|
||||
def has_pending_intent(self) -> bool:
|
||||
return self.pending_intent is not None
|
||||
|
||||
|
||||
def update_parameters(self, new_params: dict):
|
||||
if not isinstance(new_params, dict):
|
||||
return
|
||||
for k, v in new_params.items():
|
||||
if v not in (None, ""):
|
||||
self.parameters[k] = v
|
||||
|
||||
def get_parameters(self) -> dict:
|
||||
return self.parameters.copy()
|
||||
|
||||
def get_parameter(self, key: str):
|
||||
return self.parameters.get(key)
|
||||
|
||||
def set_current_question(self, param_name: str):
|
||||
self.current_question = param_name
|
||||
|
||||
def get_current_question(self) -> str | None:
|
||||
return self.current_question
|
||||
|
||||
def clear_current_question(self):
|
||||
self.current_question = None
|
||||
|
||||
def set_last_user_text(self, text: str):
|
||||
self.last_user_text = text
|
||||
self._add_to_history("user", text)
|
||||
|
||||
def set_last_ai_response(self, text: str):
|
||||
self.last_ai_response = text
|
||||
self._add_to_history("ai", text)
|
||||
|
||||
def get_last_user_text(self):
|
||||
return self.last_user_text
|
||||
|
||||
def get_last_ai_response(self):
|
||||
return self.last_ai_response
|
||||
|
||||
|
||||
def set_last_search(self, query: str, answer: str):
|
||||
self.last_search = {
|
||||
"query": query,
|
||||
"answer": answer
|
||||
}
|
||||
|
||||
def get_last_search(self):
|
||||
return self.last_search
|
||||
|
||||
def set_open_app(self, app_name: str):
|
||||
self.last_opened_app = app_name
|
||||
|
||||
def get_last_opened_app(self):
|
||||
return self.last_opened_app
|
||||
|
||||
def _add_to_history(self, role: str, text: str):
|
||||
if role not in ("user", "ai"):
|
||||
return
|
||||
|
||||
self.conversation_history.append({
|
||||
"role": role,
|
||||
"text": text
|
||||
})
|
||||
|
||||
if len(self.conversation_history) > self.max_history:
|
||||
self.conversation_history.pop(0)
|
||||
|
||||
def get_history_for_prompt(self) -> str:
|
||||
"""
|
||||
Returns compact history for LLM prompt.
|
||||
"""
|
||||
return "\n".join(
|
||||
f"{m['role'].capitalize()}: {m['text']}"
|
||||
for m in self.conversation_history
|
||||
)
|
||||
|
||||
|
||||
def get_context_summary(self) -> dict:
|
||||
"""
|
||||
Useful for debugging or smarter LLM prompts.
|
||||
"""
|
||||
return {
|
||||
"pending_intent": self.pending_intent,
|
||||
"parameters": self.parameters,
|
||||
"last_search": self.last_search,
|
||||
"last_opened_app": self.last_opened_app,
|
||||
"last_user_text": self.last_user_text,
|
||||
"last_ai_response": self.last_ai_response,
|
||||
}
|
||||
Reference in new issue
Block a user