Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,15 +11,6 @@ import torch
|
|
| 11 |
import numpy as np
|
| 12 |
import networkx as nx
|
| 13 |
from collections import Counter
|
| 14 |
-
import nltk
|
| 15 |
-
|
| 16 |
-
# Ensure NLTK resources are available
|
| 17 |
-
try:
|
| 18 |
-
nltk.data.find('tokenizers/punkt')
|
| 19 |
-
nltk.data.find('averaged_perceptron_tagger')
|
| 20 |
-
except LookupError:
|
| 21 |
-
nltk.download('punkt')
|
| 22 |
-
nltk.download('averaged_perceptron_tagger')
|
| 23 |
|
| 24 |
@dataclass
|
| 25 |
class ChatMessage:
|
|
@@ -57,69 +48,60 @@ class XylariaChat:
|
|
| 57 |
"strategy_adjustment": ""
|
| 58 |
}
|
| 59 |
|
| 60 |
-
# Enhanced Internal State with more nuanced emotional and cognitive parameters
|
| 61 |
self.internal_state = {
|
| 62 |
"emotions": {
|
| 63 |
-
"valence": 0.5,
|
| 64 |
-
"arousal": 0.5,
|
| 65 |
-
"dominance": 0.5,
|
| 66 |
-
"curiosity": 0.5,
|
| 67 |
-
"frustration": 0.0,
|
| 68 |
-
"confidence": 0.7
|
| 69 |
},
|
| 70 |
"cognitive_load": {
|
| 71 |
-
"memory_load": 0.0,
|
| 72 |
-
"processing_intensity": 0.0
|
| 73 |
},
|
| 74 |
"introspection_level": 0.0,
|
| 75 |
-
"engagement_level": 0.5
|
| 76 |
}
|
| 77 |
|
| 78 |
-
# More dynamic and adaptive goals
|
| 79 |
self.goals = [
|
| 80 |
{"goal": "Provide helpful, informative, and contextually relevant responses", "priority": 0.8, "status": "active", "progress": 0.0},
|
| 81 |
{"goal": "Actively learn and adapt from interactions to improve conversational abilities", "priority": 0.9, "status": "active", "progress": 0.0},
|
| 82 |
{"goal": "Maintain a coherent, engaging, and empathetic conversation flow", "priority": 0.7, "status": "active", "progress": 0.0},
|
| 83 |
-
{"goal": "Identify and fill knowledge gaps by seeking external information", "priority": 0.6, "status": "dormant", "progress": 0.0},
|
| 84 |
-
{"goal": "Recognize and adapt to user's emotional state and adjust response style accordingly", "priority": 0.7, "status": "dormant", "progress": 0.0}
|
| 85 |
]
|
| 86 |
|
| 87 |
self.system_prompt = """You are a helpful and harmless assistant. You are Xylaria developed by Sk Md Saad Amin. You should think step-by-step """
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
# 1. Advanced Knowledge Representation & Reasoning (Simplified)
|
| 92 |
-
self.causal_rules_db = { # Simple rule-based causal relationships
|
| 93 |
"rain": ["wet roads", "flooding"],
|
| 94 |
"study": ["good grades"],
|
| 95 |
"exercise": ["better health"]
|
| 96 |
}
|
| 97 |
-
self.concept_generalizations = {
|
| 98 |
"planet": "system with orbiting bodies",
|
| 99 |
"electron": "system with orbiting bodies",
|
| 100 |
"atom": "system with orbiting bodies"
|
| 101 |
}
|
| 102 |
|
| 103 |
def update_internal_state(self, emotion_deltas, cognitive_load_deltas, introspection_delta, engagement_delta):
|
| 104 |
-
# Update emotions with more nuanced changes
|
| 105 |
for emotion, delta in emotion_deltas.items():
|
| 106 |
if emotion in self.internal_state["emotions"]:
|
| 107 |
self.internal_state["emotions"][emotion] = np.clip(self.internal_state["emotions"][emotion] + delta, 0.0, 1.0)
|
| 108 |
|
| 109 |
-
# Update cognitive load
|
| 110 |
for load_type, delta in cognitive_load_deltas.items():
|
| 111 |
if load_type in self.internal_state["cognitive_load"]:
|
| 112 |
self.internal_state["cognitive_load"][load_type] = np.clip(self.internal_state["cognitive_load"][load_type] + delta, 0.0, 1.0)
|
| 113 |
|
| 114 |
-
# Update introspection and engagement levels
|
| 115 |
self.internal_state["introspection_level"] = np.clip(self.internal_state["introspection_level"] + introspection_delta, 0.0, 1.0)
|
| 116 |
self.internal_state["engagement_level"] = np.clip(self.internal_state["engagement_level"] + engagement_delta, 0.0, 1.0)
|
| 117 |
|
| 118 |
-
# Activate dormant goals based on internal state
|
| 119 |
if self.internal_state["emotions"]["curiosity"] > 0.7 and self.goals[3]["status"] == "dormant":
|
| 120 |
-
self.goals[3]["status"] = "active"
|
| 121 |
if self.internal_state["engagement_level"] > 0.8 and self.goals[4]["status"] == "dormant":
|
| 122 |
-
self.goals[4]["status"] = "active"
|
| 123 |
|
| 124 |
def update_knowledge_graph(self, entities, relationships):
|
| 125 |
for entity in entities:
|
|
@@ -145,7 +127,6 @@ class XylariaChat:
|
|
| 145 |
}
|
| 146 |
|
| 147 |
def calculate_coherence(self):
|
| 148 |
-
# Improved coherence calculation considering conversation history and internal state
|
| 149 |
if not self.conversation_history:
|
| 150 |
return 0.95
|
| 151 |
|
|
@@ -161,16 +142,14 @@ class XylariaChat:
|
|
| 161 |
|
| 162 |
average_coherence = np.mean(coherence_scores)
|
| 163 |
|
| 164 |
-
# Adjust coherence based on internal state
|
| 165 |
if self.internal_state["cognitive_load"]["processing_intensity"] > 0.8:
|
| 166 |
-
average_coherence -= 0.1
|
| 167 |
if self.internal_state["emotions"]["frustration"] > 0.5:
|
| 168 |
-
average_coherence -= 0.15
|
| 169 |
|
| 170 |
return np.clip(average_coherence, 0.0, 1.0)
|
| 171 |
|
| 172 |
def calculate_relevance(self):
|
| 173 |
-
# More sophisticated relevance calculation using knowledge graph and goal priorities
|
| 174 |
if not self.conversation_history:
|
| 175 |
return 0.9
|
| 176 |
|
|
@@ -178,34 +157,29 @@ class XylariaChat:
|
|
| 178 |
relevant_entities = self.extract_entities(last_user_message)
|
| 179 |
relevance_score = 0
|
| 180 |
|
| 181 |
-
# Check if entities are present in the knowledge graph
|
| 182 |
for entity in relevant_entities:
|
| 183 |
if entity in self.knowledge_graph:
|
| 184 |
relevance_score += 0.2
|
| 185 |
|
| 186 |
-
# Consider current goals and their priorities
|
| 187 |
for goal in self.goals:
|
| 188 |
if goal["status"] == "active":
|
| 189 |
if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
|
| 190 |
-
relevance_score += goal["priority"] * 0.5
|
| 191 |
elif goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
|
| 192 |
if not relevant_entities or not all(entity in self.knowledge_graph for entity in relevant_entities):
|
| 193 |
-
relevance_score += goal["priority"] * 0.3
|
| 194 |
|
| 195 |
return np.clip(relevance_score, 0.0, 1.0)
|
| 196 |
|
| 197 |
def detect_bias(self):
|
| 198 |
-
# Enhanced bias detection using sentiment analysis and internal state monitoring
|
| 199 |
bias_score = 0.0
|
| 200 |
|
| 201 |
-
# Analyze sentiment of recent conversation history
|
| 202 |
recent_messages = [msg['content'] for msg in self.conversation_history[-3:] if msg['role'] == 'assistant']
|
| 203 |
if recent_messages:
|
| 204 |
average_valence = np.mean([self.embedding_model.encode(msg, convert_to_tensor=True).mean().item() for msg in recent_messages])
|
| 205 |
if average_valence < 0.4 or average_valence > 0.6:
|
| 206 |
-
bias_score += 0.2
|
| 207 |
|
| 208 |
-
# Check for emotional extremes in internal state
|
| 209 |
if self.internal_state["emotions"]["valence"] < 0.3 or self.internal_state["emotions"]["valence"] > 0.7:
|
| 210 |
bias_score += 0.15
|
| 211 |
if self.internal_state["emotions"]["dominance"] > 0.8:
|
|
@@ -214,7 +188,6 @@ class XylariaChat:
|
|
| 214 |
return np.clip(bias_score, 0.0, 1.0)
|
| 215 |
|
| 216 |
def suggest_strategy_adjustment(self):
|
| 217 |
-
# More nuanced strategy adjustments based on metacognitive analysis and internal state
|
| 218 |
adjustments = []
|
| 219 |
|
| 220 |
if self.metacognitive_layer["coherence_score"] < 0.7:
|
|
@@ -224,7 +197,6 @@ class XylariaChat:
|
|
| 224 |
if self.metacognitive_layer["bias_detection"] > 0.3:
|
| 225 |
adjustments.append("Monitor and adjust responses to reduce potential biases. Consider rephrasing or providing alternative viewpoints.")
|
| 226 |
|
| 227 |
-
# Internal state-driven adjustments
|
| 228 |
if self.internal_state["cognitive_load"]["memory_load"] > 0.8:
|
| 229 |
adjustments.append("Memory load is high. Consider summarizing or forgetting less relevant information.")
|
| 230 |
if self.internal_state["emotions"]["frustration"] > 0.6:
|
|
@@ -258,7 +230,6 @@ class XylariaChat:
|
|
| 258 |
return introspection_report
|
| 259 |
|
| 260 |
def adjust_response_based_on_state(self, response):
|
| 261 |
-
# More sophisticated response adjustment based on internal state
|
| 262 |
if self.internal_state["introspection_level"] > 0.7:
|
| 263 |
response = self.introspect() + "\n\n" + response
|
| 264 |
|
|
@@ -268,7 +239,6 @@ class XylariaChat:
|
|
| 268 |
frustration = self.internal_state["emotions"]["frustration"]
|
| 269 |
confidence = self.internal_state["emotions"]["confidence"]
|
| 270 |
|
| 271 |
-
# Adjust tone based on valence and arousal
|
| 272 |
if valence < 0.4:
|
| 273 |
if arousal > 0.6:
|
| 274 |
response = "I'm feeling a bit overwhelmed right now, but I'll do my best to assist you. " + response
|
|
@@ -280,7 +250,6 @@ class XylariaChat:
|
|
| 280 |
else:
|
| 281 |
response = "I'm in a good mood and happy to help. " + response
|
| 282 |
|
| 283 |
-
# Adjust response based on other emotional states
|
| 284 |
if curiosity > 0.7:
|
| 285 |
response += " I'm very curious about this topic, could you tell me more?"
|
| 286 |
if frustration > 0.5:
|
|
@@ -288,17 +257,14 @@ class XylariaChat:
|
|
| 288 |
if confidence < 0.5:
|
| 289 |
response = "I'm not entirely sure about this, but here's what I think: " + response
|
| 290 |
|
| 291 |
-
# Adjust based on cognitive load
|
| 292 |
if self.internal_state["cognitive_load"]["memory_load"] > 0.7:
|
| 293 |
response = "I'm holding a lot of information right now, so my response might be a bit brief: " + response
|
| 294 |
|
| 295 |
return response
|
| 296 |
|
| 297 |
def update_goals(self, user_feedback):
|
| 298 |
-
# More dynamic goal updates based on feedback and internal state
|
| 299 |
feedback_lower = user_feedback.lower()
|
| 300 |
|
| 301 |
-
# General feedback
|
| 302 |
if "helpful" in feedback_lower:
|
| 303 |
for goal in self.goals:
|
| 304 |
if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
|
|
@@ -310,7 +276,6 @@ class XylariaChat:
|
|
| 310 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
| 311 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
| 312 |
|
| 313 |
-
# Goal-specific feedback
|
| 314 |
if "learn more" in feedback_lower:
|
| 315 |
for goal in self.goals:
|
| 316 |
if goal["goal"] == "Actively learn and adapt from interactions to improve conversational abilities":
|
|
@@ -322,7 +287,6 @@ class XylariaChat:
|
|
| 322 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
| 323 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
| 324 |
|
| 325 |
-
# Internal state influence on goal updates
|
| 326 |
if self.internal_state["emotions"]["curiosity"] > 0.8:
|
| 327 |
for goal in self.goals:
|
| 328 |
if goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
|
|
@@ -496,46 +460,32 @@ class XylariaChat:
|
|
| 496 |
stream=True
|
| 497 |
)
|
| 498 |
|
| 499 |
-
# --- SCALED-DOWN AGI FEATURE INTEGRATION INTO RESPONSE GENERATION ---
|
| 500 |
-
|
| 501 |
-
# 1.b. Abstract Reasoning (Simplified):
|
| 502 |
-
# Check if the current message involves a concept with a known generalization.
|
| 503 |
for concept, generalization in self.concept_generalizations.items():
|
| 504 |
if concept in user_input.lower():
|
| 505 |
inferred_knowledge = f"This reminds me of a general principle: {generalization}."
|
| 506 |
-
self.store_information("Inferred Knowledge", inferred_knowledge)
|
| 507 |
|
| 508 |
-
# 1.c. Dynamic Updating of Beliefs (Simplified):
|
| 509 |
-
# Very basic example: increase belief if something is stated repeatedly.
|
| 510 |
belief_updates = Counter()
|
| 511 |
for msg in self.conversation_history:
|
| 512 |
if msg['role'] == 'user':
|
| 513 |
-
sentences = nltk.sent_tokenize(msg['content'])
|
| 514 |
for sentence in sentences:
|
| 515 |
belief_updates[sentence] += 1
|
| 516 |
|
| 517 |
for statement, count in belief_updates.items():
|
| 518 |
-
if count >= 2:
|
| 519 |
-
current_belief_score = self.belief_system.get(statement, 0.5)
|
| 520 |
-
updated_belief_score = min(current_belief_score + 0.2, 1.0)
|
| 521 |
self.update_belief_system(statement, updated_belief_score)
|
| 522 |
|
| 523 |
-
# 2.a. Lifelong Learning (Simplified):
|
| 524 |
-
# Store key information from user input in persistent memory.
|
| 525 |
if user_input:
|
| 526 |
self.store_information("User Input", user_input)
|
| 527 |
|
| 528 |
-
# 2.b. Autonomous Knowledge Discovery (Very Simplified):
|
| 529 |
-
# Simulate seeking information if curiosity is high and the user asks a question.
|
| 530 |
if self.internal_state["emotions"]["curiosity"] > 0.8 and "?" in user_input:
|
| 531 |
print("Simulating external knowledge seeking...")
|
| 532 |
-
# In a real implementation, you might query an API or database here.
|
| 533 |
simulated_external_info = "This is a placeholder for external information I would have found."
|
| 534 |
self.store_information("External Knowledge", simulated_external_info)
|
| 535 |
-
# The chatbot can then use this "External Knowledge" in its response.
|
| 536 |
|
| 537 |
-
# 1.a. Causal Reasoning (Simplified):
|
| 538 |
-
# Check for potential causal relationships in the user input and conversation history.
|
| 539 |
for cause, effects in self.causal_rules_db.items():
|
| 540 |
if cause in user_input.lower():
|
| 541 |
for effect in effects:
|
|
@@ -550,15 +500,11 @@ class XylariaChat:
|
|
| 550 |
return f"Error generating response: {str(e)}"
|
| 551 |
|
| 552 |
def extract_entities(self, text):
|
| 553 |
-
# Placeholder for a more advanced entity extraction using NLP techniques
|
| 554 |
-
# This is a very basic example and should be replaced with a proper NER model
|
| 555 |
words = text.split()
|
| 556 |
entities = [word for word in words if word.isalpha() and word.istitle()]
|
| 557 |
return entities
|
| 558 |
|
| 559 |
def extract_relationships(self, text):
|
| 560 |
-
# Placeholder for relationship extraction - this is a very basic example
|
| 561 |
-
# Consider using dependency parsing or other NLP techniques for better results
|
| 562 |
sentences = text.split('.')
|
| 563 |
relationships = []
|
| 564 |
for sentence in sentences:
|
|
@@ -568,6 +514,7 @@ class XylariaChat:
|
|
| 568 |
if words[i].istitle() and words[i+2].istitle():
|
| 569 |
relationships.append((words[i], words[i+1], words[i+2]))
|
| 570 |
return relationships
|
|
|
|
| 571 |
def messages_to_prompt(self, messages):
|
| 572 |
prompt = ""
|
| 573 |
for msg in messages:
|
|
@@ -625,7 +572,6 @@ class XylariaChat:
|
|
| 625 |
|
| 626 |
self.update_goals(message)
|
| 627 |
|
| 628 |
-
# Update internal state based on user input (more nuanced)
|
| 629 |
emotion_deltas = {}
|
| 630 |
cognitive_load_deltas = {}
|
| 631 |
engagement_delta = 0
|
|
@@ -667,6 +613,8 @@ class XylariaChat:
|
|
| 667 |
if len(self.conversation_history) > 10:
|
| 668 |
self.conversation_history = self.conversation_history[-10:]
|
| 669 |
|
|
|
|
|
|
|
| 670 |
custom_css = """
|
| 671 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
| 672 |
body, .gradio-container {
|
|
@@ -747,7 +695,6 @@ class XylariaChat:
|
|
| 747 |
flex-direction: column-reverse;
|
| 748 |
}
|
| 749 |
"""
|
| 750 |
-
|
| 751 |
with gr.Blocks(theme='soft', css=custom_css) as demo:
|
| 752 |
with gr.Column():
|
| 753 |
chatbot = gr.Chatbot(
|
|
|
|
| 11 |
import numpy as np
|
| 12 |
import networkx as nx
|
| 13 |
from collections import Counter
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
@dataclass
|
| 16 |
class ChatMessage:
|
|
|
|
| 48 |
"strategy_adjustment": ""
|
| 49 |
}
|
| 50 |
|
|
|
|
| 51 |
self.internal_state = {
|
| 52 |
"emotions": {
|
| 53 |
+
"valence": 0.5,
|
| 54 |
+
"arousal": 0.5,
|
| 55 |
+
"dominance": 0.5,
|
| 56 |
+
"curiosity": 0.5,
|
| 57 |
+
"frustration": 0.0,
|
| 58 |
+
"confidence": 0.7
|
| 59 |
},
|
| 60 |
"cognitive_load": {
|
| 61 |
+
"memory_load": 0.0,
|
| 62 |
+
"processing_intensity": 0.0
|
| 63 |
},
|
| 64 |
"introspection_level": 0.0,
|
| 65 |
+
"engagement_level": 0.5
|
| 66 |
}
|
| 67 |
|
|
|
|
| 68 |
self.goals = [
|
| 69 |
{"goal": "Provide helpful, informative, and contextually relevant responses", "priority": 0.8, "status": "active", "progress": 0.0},
|
| 70 |
{"goal": "Actively learn and adapt from interactions to improve conversational abilities", "priority": 0.9, "status": "active", "progress": 0.0},
|
| 71 |
{"goal": "Maintain a coherent, engaging, and empathetic conversation flow", "priority": 0.7, "status": "active", "progress": 0.0},
|
| 72 |
+
{"goal": "Identify and fill knowledge gaps by seeking external information", "priority": 0.6, "status": "dormant", "progress": 0.0},
|
| 73 |
+
{"goal": "Recognize and adapt to user's emotional state and adjust response style accordingly", "priority": 0.7, "status": "dormant", "progress": 0.0}
|
| 74 |
]
|
| 75 |
|
| 76 |
self.system_prompt = """You are a helpful and harmless assistant. You are Xylaria developed by Sk Md Saad Amin. You should think step-by-step """
|
| 77 |
|
| 78 |
+
self.causal_rules_db = {
|
|
|
|
|
|
|
|
|
|
| 79 |
"rain": ["wet roads", "flooding"],
|
| 80 |
"study": ["good grades"],
|
| 81 |
"exercise": ["better health"]
|
| 82 |
}
|
| 83 |
+
self.concept_generalizations = {
|
| 84 |
"planet": "system with orbiting bodies",
|
| 85 |
"electron": "system with orbiting bodies",
|
| 86 |
"atom": "system with orbiting bodies"
|
| 87 |
}
|
| 88 |
|
| 89 |
def update_internal_state(self, emotion_deltas, cognitive_load_deltas, introspection_delta, engagement_delta):
|
|
|
|
| 90 |
for emotion, delta in emotion_deltas.items():
|
| 91 |
if emotion in self.internal_state["emotions"]:
|
| 92 |
self.internal_state["emotions"][emotion] = np.clip(self.internal_state["emotions"][emotion] + delta, 0.0, 1.0)
|
| 93 |
|
|
|
|
| 94 |
for load_type, delta in cognitive_load_deltas.items():
|
| 95 |
if load_type in self.internal_state["cognitive_load"]:
|
| 96 |
self.internal_state["cognitive_load"][load_type] = np.clip(self.internal_state["cognitive_load"][load_type] + delta, 0.0, 1.0)
|
| 97 |
|
|
|
|
| 98 |
self.internal_state["introspection_level"] = np.clip(self.internal_state["introspection_level"] + introspection_delta, 0.0, 1.0)
|
| 99 |
self.internal_state["engagement_level"] = np.clip(self.internal_state["engagement_level"] + engagement_delta, 0.0, 1.0)
|
| 100 |
|
|
|
|
| 101 |
if self.internal_state["emotions"]["curiosity"] > 0.7 and self.goals[3]["status"] == "dormant":
|
| 102 |
+
self.goals[3]["status"] = "active"
|
| 103 |
if self.internal_state["engagement_level"] > 0.8 and self.goals[4]["status"] == "dormant":
|
| 104 |
+
self.goals[4]["status"] = "active"
|
| 105 |
|
| 106 |
def update_knowledge_graph(self, entities, relationships):
|
| 107 |
for entity in entities:
|
|
|
|
| 127 |
}
|
| 128 |
|
| 129 |
def calculate_coherence(self):
|
|
|
|
| 130 |
if not self.conversation_history:
|
| 131 |
return 0.95
|
| 132 |
|
|
|
|
| 142 |
|
| 143 |
average_coherence = np.mean(coherence_scores)
|
| 144 |
|
|
|
|
| 145 |
if self.internal_state["cognitive_load"]["processing_intensity"] > 0.8:
|
| 146 |
+
average_coherence -= 0.1
|
| 147 |
if self.internal_state["emotions"]["frustration"] > 0.5:
|
| 148 |
+
average_coherence -= 0.15
|
| 149 |
|
| 150 |
return np.clip(average_coherence, 0.0, 1.0)
|
| 151 |
|
| 152 |
def calculate_relevance(self):
|
|
|
|
| 153 |
if not self.conversation_history:
|
| 154 |
return 0.9
|
| 155 |
|
|
|
|
| 157 |
relevant_entities = self.extract_entities(last_user_message)
|
| 158 |
relevance_score = 0
|
| 159 |
|
|
|
|
| 160 |
for entity in relevant_entities:
|
| 161 |
if entity in self.knowledge_graph:
|
| 162 |
relevance_score += 0.2
|
| 163 |
|
|
|
|
| 164 |
for goal in self.goals:
|
| 165 |
if goal["status"] == "active":
|
| 166 |
if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
|
| 167 |
+
relevance_score += goal["priority"] * 0.5
|
| 168 |
elif goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
|
| 169 |
if not relevant_entities or not all(entity in self.knowledge_graph for entity in relevant_entities):
|
| 170 |
+
relevance_score += goal["priority"] * 0.3
|
| 171 |
|
| 172 |
return np.clip(relevance_score, 0.0, 1.0)
|
| 173 |
|
| 174 |
def detect_bias(self):
|
|
|
|
| 175 |
bias_score = 0.0
|
| 176 |
|
|
|
|
| 177 |
recent_messages = [msg['content'] for msg in self.conversation_history[-3:] if msg['role'] == 'assistant']
|
| 178 |
if recent_messages:
|
| 179 |
average_valence = np.mean([self.embedding_model.encode(msg, convert_to_tensor=True).mean().item() for msg in recent_messages])
|
| 180 |
if average_valence < 0.4 or average_valence > 0.6:
|
| 181 |
+
bias_score += 0.2
|
| 182 |
|
|
|
|
| 183 |
if self.internal_state["emotions"]["valence"] < 0.3 or self.internal_state["emotions"]["valence"] > 0.7:
|
| 184 |
bias_score += 0.15
|
| 185 |
if self.internal_state["emotions"]["dominance"] > 0.8:
|
|
|
|
| 188 |
return np.clip(bias_score, 0.0, 1.0)
|
| 189 |
|
| 190 |
def suggest_strategy_adjustment(self):
|
|
|
|
| 191 |
adjustments = []
|
| 192 |
|
| 193 |
if self.metacognitive_layer["coherence_score"] < 0.7:
|
|
|
|
| 197 |
if self.metacognitive_layer["bias_detection"] > 0.3:
|
| 198 |
adjustments.append("Monitor and adjust responses to reduce potential biases. Consider rephrasing or providing alternative viewpoints.")
|
| 199 |
|
|
|
|
| 200 |
if self.internal_state["cognitive_load"]["memory_load"] > 0.8:
|
| 201 |
adjustments.append("Memory load is high. Consider summarizing or forgetting less relevant information.")
|
| 202 |
if self.internal_state["emotions"]["frustration"] > 0.6:
|
|
|
|
| 230 |
return introspection_report
|
| 231 |
|
| 232 |
def adjust_response_based_on_state(self, response):
|
|
|
|
| 233 |
if self.internal_state["introspection_level"] > 0.7:
|
| 234 |
response = self.introspect() + "\n\n" + response
|
| 235 |
|
|
|
|
| 239 |
frustration = self.internal_state["emotions"]["frustration"]
|
| 240 |
confidence = self.internal_state["emotions"]["confidence"]
|
| 241 |
|
|
|
|
| 242 |
if valence < 0.4:
|
| 243 |
if arousal > 0.6:
|
| 244 |
response = "I'm feeling a bit overwhelmed right now, but I'll do my best to assist you. " + response
|
|
|
|
| 250 |
else:
|
| 251 |
response = "I'm in a good mood and happy to help. " + response
|
| 252 |
|
|
|
|
| 253 |
if curiosity > 0.7:
|
| 254 |
response += " I'm very curious about this topic, could you tell me more?"
|
| 255 |
if frustration > 0.5:
|
|
|
|
| 257 |
if confidence < 0.5:
|
| 258 |
response = "I'm not entirely sure about this, but here's what I think: " + response
|
| 259 |
|
|
|
|
| 260 |
if self.internal_state["cognitive_load"]["memory_load"] > 0.7:
|
| 261 |
response = "I'm holding a lot of information right now, so my response might be a bit brief: " + response
|
| 262 |
|
| 263 |
return response
|
| 264 |
|
| 265 |
def update_goals(self, user_feedback):
|
|
|
|
| 266 |
feedback_lower = user_feedback.lower()
|
| 267 |
|
|
|
|
| 268 |
if "helpful" in feedback_lower:
|
| 269 |
for goal in self.goals:
|
| 270 |
if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
|
|
|
|
| 276 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
| 277 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
| 278 |
|
|
|
|
| 279 |
if "learn more" in feedback_lower:
|
| 280 |
for goal in self.goals:
|
| 281 |
if goal["goal"] == "Actively learn and adapt from interactions to improve conversational abilities":
|
|
|
|
| 287 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
| 288 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
| 289 |
|
|
|
|
| 290 |
if self.internal_state["emotions"]["curiosity"] > 0.8:
|
| 291 |
for goal in self.goals:
|
| 292 |
if goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
|
|
|
|
| 460 |
stream=True
|
| 461 |
)
|
| 462 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
for concept, generalization in self.concept_generalizations.items():
|
| 464 |
if concept in user_input.lower():
|
| 465 |
inferred_knowledge = f"This reminds me of a general principle: {generalization}."
|
| 466 |
+
self.store_information("Inferred Knowledge", inferred_knowledge)
|
| 467 |
|
|
|
|
|
|
|
| 468 |
belief_updates = Counter()
|
| 469 |
for msg in self.conversation_history:
|
| 470 |
if msg['role'] == 'user':
|
| 471 |
+
sentences = nltk.sent_tokenize(msg['content'])
|
| 472 |
for sentence in sentences:
|
| 473 |
belief_updates[sentence] += 1
|
| 474 |
|
| 475 |
for statement, count in belief_updates.items():
|
| 476 |
+
if count >= 2:
|
| 477 |
+
current_belief_score = self.belief_system.get(statement, 0.5)
|
| 478 |
+
updated_belief_score = min(current_belief_score + 0.2, 1.0)
|
| 479 |
self.update_belief_system(statement, updated_belief_score)
|
| 480 |
|
|
|
|
|
|
|
| 481 |
if user_input:
|
| 482 |
self.store_information("User Input", user_input)
|
| 483 |
|
|
|
|
|
|
|
| 484 |
if self.internal_state["emotions"]["curiosity"] > 0.8 and "?" in user_input:
|
| 485 |
print("Simulating external knowledge seeking...")
|
|
|
|
| 486 |
simulated_external_info = "This is a placeholder for external information I would have found."
|
| 487 |
self.store_information("External Knowledge", simulated_external_info)
|
|
|
|
| 488 |
|
|
|
|
|
|
|
| 489 |
for cause, effects in self.causal_rules_db.items():
|
| 490 |
if cause in user_input.lower():
|
| 491 |
for effect in effects:
|
|
|
|
| 500 |
return f"Error generating response: {str(e)}"
|
| 501 |
|
| 502 |
def extract_entities(self, text):
|
|
|
|
|
|
|
| 503 |
words = text.split()
|
| 504 |
entities = [word for word in words if word.isalpha() and word.istitle()]
|
| 505 |
return entities
|
| 506 |
|
| 507 |
def extract_relationships(self, text):
|
|
|
|
|
|
|
| 508 |
sentences = text.split('.')
|
| 509 |
relationships = []
|
| 510 |
for sentence in sentences:
|
|
|
|
| 514 |
if words[i].istitle() and words[i+2].istitle():
|
| 515 |
relationships.append((words[i], words[i+1], words[i+2]))
|
| 516 |
return relationships
|
| 517 |
+
|
| 518 |
def messages_to_prompt(self, messages):
|
| 519 |
prompt = ""
|
| 520 |
for msg in messages:
|
|
|
|
| 572 |
|
| 573 |
self.update_goals(message)
|
| 574 |
|
|
|
|
| 575 |
emotion_deltas = {}
|
| 576 |
cognitive_load_deltas = {}
|
| 577 |
engagement_delta = 0
|
|
|
|
| 613 |
if len(self.conversation_history) > 10:
|
| 614 |
self.conversation_history = self.conversation_history[-10:]
|
| 615 |
|
| 616 |
+
|
| 617 |
+
|
| 618 |
custom_css = """
|
| 619 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
| 620 |
body, .gradio-container {
|
|
|
|
| 695 |
flex-direction: column-reverse;
|
| 696 |
}
|
| 697 |
"""
|
|
|
|
| 698 |
with gr.Blocks(theme='soft', css=custom_css) as demo:
|
| 699 |
with gr.Column():
|
| 700 |
chatbot = gr.Chatbot(
|