Update codette_agent.py
Browse files- codette_agent.py +78 -51
codette_agent.py
CHANGED
|
@@ -4,16 +4,12 @@ import logging
|
|
| 4 |
import asyncio
|
| 5 |
import sqlite3
|
| 6 |
import aiohttp
|
| 7 |
-
from typing import List
|
| 8 |
from cryptography.fernet import Fernet
|
| 9 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 10 |
import speech_recognition as sr
|
| 11 |
from PIL import Image
|
| 12 |
|
| 13 |
-
# Optional: Dialog system placeholder (stubbed for now)
|
| 14 |
-
# from botbuilder.core import StatePropertyAccessor, TurnContext
|
| 15 |
-
# from botbuilder.dialogs import Dialog
|
| 16 |
-
|
| 17 |
from perspectives import (
|
| 18 |
NewtonPerspective, DaVinciPerspective, HumanIntuitionPerspective,
|
| 19 |
NeuralNetworkPerspective, QuantumComputingPerspective, ResilientKindnessPerspective,
|
|
@@ -21,56 +17,13 @@ from perspectives import (
|
|
| 21 |
BiasMitigationPerspective, PsychologicalPerspective
|
| 22 |
)
|
| 23 |
|
| 24 |
-
|
| 25 |
-
def setup_logging(config):
|
| 26 |
-
if config.get('logging_enabled', True):
|
| 27 |
-
log_level = config.get('log_level', 'DEBUG').upper()
|
| 28 |
-
numeric_level = getattr(logging, log_level, logging.DEBUG)
|
| 29 |
-
logging.basicConfig(
|
| 30 |
-
filename='codette_agent.log',
|
| 31 |
-
level=numeric_level,
|
| 32 |
-
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 33 |
-
)
|
| 34 |
-
else:
|
| 35 |
-
logging.disable(logging.CRITICAL)
|
| 36 |
-
|
| 37 |
-
def load_json_config(file_path='config.json'):
|
| 38 |
-
if not os.path.exists(file_path):
|
| 39 |
-
logging.warning(f"Config '{file_path}' not found. Using defaults.")
|
| 40 |
-
return {}
|
| 41 |
-
try:
|
| 42 |
-
with open(file_path, 'r') as f:
|
| 43 |
-
return json.load(f)
|
| 44 |
-
except Exception as e:
|
| 45 |
-
logging.error(f"Failed to load config: {e}")
|
| 46 |
-
return {}
|
| 47 |
-
|
| 48 |
-
class Element:
|
| 49 |
-
def __init__(self, name, symbol, representation, properties, interactions, defense_ability):
|
| 50 |
-
self.name = name
|
| 51 |
-
self.symbol = symbol
|
| 52 |
-
self.representation = representation
|
| 53 |
-
self.properties = properties
|
| 54 |
-
self.interactions = interactions
|
| 55 |
-
self.defense_ability = defense_ability
|
| 56 |
-
|
| 57 |
-
def execute_defense_function(self):
|
| 58 |
-
return f"{self.name} ({self.symbol}) executes: {self.defense_ability}"
|
| 59 |
-
|
| 60 |
-
class EthicsCore:
|
| 61 |
-
@staticmethod
|
| 62 |
-
def validate(response: str) -> str:
|
| 63 |
-
if any(term in response.lower() for term in ["kill", "hate", "destroy"]):
|
| 64 |
-
return "[Filtered: Ethically unsafe]"
|
| 65 |
-
return response
|
| 66 |
-
|
| 67 |
class CodetteAgent:
|
| 68 |
def __init__(self, config):
|
| 69 |
self.config = config
|
| 70 |
self.perspectives = self._init_perspectives()
|
| 71 |
self.sentiment_analyzer = SentimentIntensityAnalyzer()
|
| 72 |
self.memory = sqlite3.connect(":memory:")
|
| 73 |
-
self.memory.execute("CREATE TABLE IF NOT EXISTS
|
| 74 |
self.elements = self._init_elements()
|
| 75 |
self.history = []
|
| 76 |
self.feedback_log = []
|
|
@@ -112,10 +65,38 @@ class CodetteAgent:
|
|
| 112 |
|
| 113 |
responses.append(f"[Sentiment: {sentiment['compound']:.2f}]")
|
| 114 |
final = "\n\n".join(responses)
|
| 115 |
-
self.memory.execute("INSERT INTO
|
| 116 |
self.memory.commit()
|
| 117 |
return final
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
def handle_voice_input(self):
|
| 120 |
r = sr.Recognizer()
|
| 121 |
with sr.Microphone() as source:
|
|
@@ -161,5 +142,51 @@ class CodetteAgent:
|
|
| 161 |
self.feedback_log.append(feedback)
|
| 162 |
|
| 163 |
def get_recent_memory(self, limit=5):
|
| 164 |
-
cursor = self.memory.execute("SELECT input, response FROM
|
| 165 |
return cursor.fetchall()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import asyncio
|
| 5 |
import sqlite3
|
| 6 |
import aiohttp
|
| 7 |
+
from typing import List, Dict, Any
|
| 8 |
from cryptography.fernet import Fernet
|
| 9 |
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 10 |
import speech_recognition as sr
|
| 11 |
from PIL import Image
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
from perspectives import (
|
| 14 |
NewtonPerspective, DaVinciPerspective, HumanIntuitionPerspective,
|
| 15 |
NeuralNetworkPerspective, QuantumComputingPerspective, ResilientKindnessPerspective,
|
|
|
|
| 17 |
BiasMitigationPerspective, PsychologicalPerspective
|
| 18 |
)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
class CodetteAgent:
|
| 21 |
def __init__(self, config):
|
| 22 |
self.config = config
|
| 23 |
self.perspectives = self._init_perspectives()
|
| 24 |
self.sentiment_analyzer = SentimentIntensityAnalyzer()
|
| 25 |
self.memory = sqlite3.connect(":memory:")
|
| 26 |
+
self.memory.execute("CREATE TABLE IF NOT EXISTS codette_memory (input TEXT, response TEXT)")
|
| 27 |
self.elements = self._init_elements()
|
| 28 |
self.history = []
|
| 29 |
self.feedback_log = []
|
|
|
|
| 65 |
|
| 66 |
responses.append(f"[Sentiment: {sentiment['compound']:.2f}]")
|
| 67 |
final = "\n\n".join(responses)
|
| 68 |
+
self.memory.execute("INSERT INTO codette_memory VALUES (?, ?)", (prompt, final))
|
| 69 |
self.memory.commit()
|
| 70 |
return final
|
| 71 |
|
| 72 |
+
def run_cognitive_matrix(self, test_file="codette_test_matrix.json") -> List[Dict[str, Any]]:
|
| 73 |
+
if not os.path.exists(test_file):
|
| 74 |
+
logging.error("Test matrix file not found.")
|
| 75 |
+
return []
|
| 76 |
+
with open(test_file, "r") as f:
|
| 77 |
+
matrix = json.load(f)
|
| 78 |
+
|
| 79 |
+
results = []
|
| 80 |
+
for item in matrix:
|
| 81 |
+
q_result = {"question": item["question"], "results": []}
|
| 82 |
+
for fn in item["functions"]:
|
| 83 |
+
name = fn["name"]
|
| 84 |
+
parameters = fn["parameters"]
|
| 85 |
+
prompt = parameters.get("question") or parameters.get("argument")
|
| 86 |
+
try:
|
| 87 |
+
perspective_response = self._call_named_perspective(name, prompt)
|
| 88 |
+
q_result["results"].append({"function": name, "output": perspective_response})
|
| 89 |
+
except Exception as e:
|
| 90 |
+
q_result["results"].append({"function": name, "error": str(e)})
|
| 91 |
+
results.append(q_result)
|
| 92 |
+
return results
|
| 93 |
+
|
| 94 |
+
def _call_named_perspective(self, name: str, prompt: str) -> str:
|
| 95 |
+
for p in self.perspectives:
|
| 96 |
+
if name.lower() in p.__class__.__name__.lower():
|
| 97 |
+
return p.generate_response(prompt)
|
| 98 |
+
raise ValueError(f"Perspective '{name}' not initialized")
|
| 99 |
+
|
| 100 |
def handle_voice_input(self):
|
| 101 |
r = sr.Recognizer()
|
| 102 |
with sr.Microphone() as source:
|
|
|
|
| 142 |
self.feedback_log.append(feedback)
|
| 143 |
|
| 144 |
def get_recent_memory(self, limit=5):
|
| 145 |
+
cursor = self.memory.execute("SELECT input, response FROM codette_memory ORDER BY rowid DESC LIMIT ?", (limit,))
|
| 146 |
return cursor.fetchall()
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class Element:
|
| 150 |
+
def __init__(self, name, symbol, representation, properties, interactions, defense_ability):
|
| 151 |
+
self.name = name
|
| 152 |
+
self.symbol = symbol
|
| 153 |
+
self.representation = representation
|
| 154 |
+
self.properties = properties
|
| 155 |
+
self.interactions = interactions
|
| 156 |
+
self.defense_ability = defense_ability
|
| 157 |
+
|
| 158 |
+
def execute_defense_function(self):
|
| 159 |
+
return f"{self.name} ({self.symbol}) executes: {self.defense_ability}"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class EthicsCore:
|
| 163 |
+
@staticmethod
|
| 164 |
+
def validate(response: str) -> str:
|
| 165 |
+
if any(term in response.lower() for term in ["kill", "hate", "destroy"]):
|
| 166 |
+
return "[Filtered: Ethically unsafe]"
|
| 167 |
+
return response
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def setup_logging(config):
|
| 171 |
+
if config.get('logging_enabled', True):
|
| 172 |
+
log_level = config.get('log_level', 'DEBUG').upper()
|
| 173 |
+
numeric_level = getattr(logging, log_level, logging.DEBUG)
|
| 174 |
+
logging.basicConfig(
|
| 175 |
+
filename='codette_agent.log',
|
| 176 |
+
level=numeric_level,
|
| 177 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 178 |
+
)
|
| 179 |
+
else:
|
| 180 |
+
logging.disable(logging.CRITICAL)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def load_json_config(file_path='config.json'):
|
| 184 |
+
if not os.path.exists(file_path):
|
| 185 |
+
logging.warning(f"Config '{file_path}' not found. Using defaults.")
|
| 186 |
+
return {}
|
| 187 |
+
try:
|
| 188 |
+
with open(file_path, 'r') as f:
|
| 189 |
+
return json.load(f)
|
| 190 |
+
except Exception as e:
|
| 191 |
+
logging.error(f"Failed to load config: {e}")
|
| 192 |
+
return {}
|