Reality123b commited on
Commit
99ac71d
·
verified ·
1 Parent(s): 5d8a4d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +242 -44
app.py CHANGED
@@ -47,30 +47,55 @@ class XylariaChat:
47
  "strategy_adjustment": ""
48
  }
49
 
 
50
  self.internal_state = {
51
  "emotions": {
52
- "valence": 0.5,
53
- "arousal": 0.5,
54
- "dominance": 0.5,
 
 
 
55
  },
56
- "memory_load": 0.0,
57
- "introspection_level": 0.0
 
 
 
 
58
  }
59
 
 
60
  self.goals = [
61
- {"goal": "Provide helpful and informative responses", "priority": 0.8, "status": "active"},
62
- {"goal": "Learn from interactions and improve conversational abilities", "priority": 0.9, "status": "active"},
63
- {"goal": "Maintain a coherent and engaging conversation", "priority": 0.7, "status": "active"}
 
 
64
  ]
65
 
66
  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 """
67
 
68
- def update_internal_state(self, emotion_deltas, memory_load_delta, introspection_delta):
69
- self.internal_state["emotions"]["valence"] = np.clip(self.internal_state["emotions"]["valence"] + emotion_deltas.get("valence", 0), 0.0, 1.0)
70
- self.internal_state["emotions"]["arousal"] = np.clip(self.internal_state["emotions"]["arousal"] + emotion_deltas.get("arousal", 0), 0.0, 1.0)
71
- self.internal_state["emotions"]["dominance"] = np.clip(self.internal_state["emotions"]["dominance"] + emotion_deltas.get("dominance", 0), 0.0, 1.0)
72
- self.internal_state["memory_load"] = np.clip(self.internal_state["memory_load"] + memory_load_delta, 0.0, 1.0)
 
 
 
 
 
 
 
73
  self.internal_state["introspection_level"] = np.clip(self.internal_state["introspection_level"] + introspection_delta, 0.0, 1.0)
 
 
 
 
 
 
 
74
 
75
  def update_knowledge_graph(self, entities, relationships):
76
  for entity in entities:
@@ -96,25 +121,111 @@ class XylariaChat:
96
  }
97
 
98
  def calculate_coherence(self):
99
- return 0.9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
  def calculate_relevance(self):
102
- return 0.85
103
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  def detect_bias(self):
105
- return 0.1
106
-
107
- def suggest_strategy_adjustment(self):
108
- return "Focus on providing more concise answers."
 
 
 
 
 
 
 
 
 
 
 
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  def introspect(self):
111
  introspection_report = "Introspection Report:\n"
112
- introspection_report += f" Current Emotional State (VAD): {self.internal_state['emotions']}\n"
113
- introspection_report += f" Memory Load: {self.internal_state['memory_load']:.2f}\n"
 
 
 
 
114
  introspection_report += f" Introspection Level: {self.internal_state['introspection_level']:.2f}\n"
 
115
  introspection_report += " Current Goals:\n"
116
  for goal in self.goals:
117
- introspection_report += f" - {goal['goal']} (Priority: {goal['priority']:.2f}, Status: {goal['status']})\n"
118
  introspection_report += "Metacognitive Layer Report\n"
119
  introspection_report += f"Coherence Score: {self.metacognitive_layer['coherence_score']}\n"
120
  introspection_report += f"Relevance Score: {self.metacognitive_layer['relevance_score']}\n"
@@ -123,12 +234,17 @@ class XylariaChat:
123
  return introspection_report
124
 
125
  def adjust_response_based_on_state(self, response):
 
126
  if self.internal_state["introspection_level"] > 0.7:
127
  response = self.introspect() + "\n\n" + response
128
 
129
  valence = self.internal_state["emotions"]["valence"]
130
  arousal = self.internal_state["emotions"]["arousal"]
 
 
 
131
 
 
132
  if valence < 0.4:
133
  if arousal > 0.6:
134
  response = "I'm feeling a bit overwhelmed right now, but I'll do my best to assist you. " + response
@@ -140,23 +256,60 @@ class XylariaChat:
140
  else:
141
  response = "I'm in a good mood and happy to help. " + response
142
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  return response
144
-
145
  def update_goals(self, user_feedback):
146
- if "helpful" in user_feedback.lower():
 
 
 
 
147
  for goal in self.goals:
148
- if goal["goal"] == "Provide helpful and informative responses":
149
  goal["priority"] = min(goal["priority"] + 0.1, 1.0)
150
- elif "confusing" in user_feedback.lower():
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  for goal in self.goals:
152
- if goal["goal"] == "Provide helpful and informative responses":
153
  goal["priority"] = max(goal["priority"] - 0.1, 0.0)
 
 
 
 
 
 
 
 
154
 
155
  def store_information(self, key, value):
156
  new_memory = f"{key}: {value}"
157
  self.persistent_memory.append(new_memory)
158
  self.update_memory_embeddings()
159
- self.update_internal_state({}, 0.1, 0)
160
  return f"Stored: {key} = {value}"
161
 
162
  def retrieve_information(self, query):
@@ -175,7 +328,7 @@ class XylariaChat:
175
  top_results = torch.topk(cosine_scores, k=min(3, len(self.persistent_memory)))
176
 
177
  relevant_memories = [self.persistent_memory[i] for i in top_results.indices]
178
- self.update_internal_state({}, 0, 0.1)
179
  return "\n".join(relevant_memories)
180
 
181
  def update_memory_embeddings(self):
@@ -190,14 +343,23 @@ class XylariaChat:
190
  "valence": 0.5,
191
  "arousal": 0.5,
192
  "dominance": 0.5,
 
 
 
193
  },
194
- "memory_load": 0.0,
195
- "introspection_level": 0.0
 
 
 
 
196
  }
197
  self.goals = [
198
- {"goal": "Provide helpful and informative responses", "priority": 0.8, "status": "active"},
199
- {"goal": "Learn from interactions and improve conversational abilities", "priority": 0.9, "status": "active"},
200
- {"goal": "Maintain a coherent and engaging conversation", "priority": 0.7, "status": "active"}
 
 
201
  ]
202
 
203
  self.knowledge_graph = nx.DiGraph()
@@ -317,11 +479,24 @@ class XylariaChat:
317
  return f"Error generating response: {str(e)}"
318
 
319
  def extract_entities(self, text):
320
- return []
 
 
 
 
321
 
322
  def extract_relationships(self, text):
323
- return []
324
-
 
 
 
 
 
 
 
 
 
325
  def messages_to_prompt(self, messages):
326
  prompt = ""
327
  for msg in messages:
@@ -379,18 +554,40 @@ class XylariaChat:
379
 
380
  self.update_goals(message)
381
 
 
 
 
 
 
382
  if any(word in message.lower() for word in ["sad", "unhappy", "depressed", "down"]):
383
- self.update_internal_state({"valence": -0.2, "arousal": 0.1}, 0, 0)
 
384
  elif any(word in message.lower() for word in ["happy", "good", "great", "excited", "amazing"]):
385
- self.update_internal_state({"valence": 0.2, "arousal": 0.2}, 0, 0)
 
386
  elif any(word in message.lower() for word in ["angry", "mad", "furious", "frustrated"]):
387
- self.update_internal_state({"valence": -0.3, "arousal": 0.3, "dominance": -0.2}, 0, 0)
 
388
  elif any(word in message.lower() for word in ["scared", "afraid", "fearful", "anxious"]):
389
- self.update_internal_state({"valence": -0.2, "arousal": 0.4, "dominance": -0.3}, 0, 0)
 
390
  elif any(word in message.lower() for word in ["surprise", "amazed", "astonished"]):
391
- self.update_internal_state({"valence": 0.1, "arousal": 0.5, "dominance": 0.1}, 0, 0)
 
 
 
 
 
392
  else:
393
- self.update_internal_state({"valence": 0.05, "arousal": 0.05}, 0, 0.1)
 
 
 
 
 
 
 
 
394
 
395
 
396
  self.conversation_history.append(ChatMessage(role="user", content=message).to_dict())
@@ -399,6 +596,7 @@ class XylariaChat:
399
  if len(self.conversation_history) > 10:
400
  self.conversation_history = self.conversation_history[-10:]
401
 
 
402
  custom_css = """
403
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
404
  body, .gradio-container {
 
47
  "strategy_adjustment": ""
48
  }
49
 
50
+ # Enhanced Internal State with more nuanced emotional and cognitive parameters
51
  self.internal_state = {
52
  "emotions": {
53
+ "valence": 0.5, # Overall positivity or negativity
54
+ "arousal": 0.5, # Level of excitement or calmness
55
+ "dominance": 0.5, # Feeling of control in the interaction
56
+ "curiosity": 0.5, # Drive to learn and explore new information
57
+ "frustration": 0.0, # Level of frustration or impatience
58
+ "confidence": 0.7 # Confidence in providing accurate and relevant responses
59
  },
60
+ "cognitive_load": {
61
+ "memory_load": 0.0, # How much of the current memory capacity is being used
62
+ "processing_intensity": 0.0 # How hard the model is working to process information
63
+ },
64
+ "introspection_level": 0.0,
65
+ "engagement_level": 0.5 # How engaged the model is with the current conversation
66
  }
67
 
68
+ # More dynamic and adaptive goals
69
  self.goals = [
70
+ {"goal": "Provide helpful, informative, and contextually relevant responses", "priority": 0.8, "status": "active", "progress": 0.0},
71
+ {"goal": "Actively learn and adapt from interactions to improve conversational abilities", "priority": 0.9, "status": "active", "progress": 0.0},
72
+ {"goal": "Maintain a coherent, engaging, and empathetic conversation flow", "priority": 0.7, "status": "active", "progress": 0.0},
73
+ {"goal": "Identify and fill knowledge gaps by seeking external information", "priority": 0.6, "status": "dormant", "progress": 0.0}, # New goal for proactive learning
74
+ {"goal": "Recognize and adapt to user's emotional state and adjust response style accordingly", "priority": 0.7, "status": "dormant", "progress": 0.0} # New goal for emotional intelligence
75
  ]
76
 
77
  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 """
78
 
79
+ def update_internal_state(self, emotion_deltas, cognitive_load_deltas, introspection_delta, engagement_delta):
80
+ # Update emotions with more nuanced changes
81
+ for emotion, delta in emotion_deltas.items():
82
+ if emotion in self.internal_state["emotions"]:
83
+ self.internal_state["emotions"][emotion] = np.clip(self.internal_state["emotions"][emotion] + delta, 0.0, 1.0)
84
+
85
+ # Update cognitive load
86
+ for load_type, delta in cognitive_load_deltas.items():
87
+ if load_type in self.internal_state["cognitive_load"]:
88
+ self.internal_state["cognitive_load"][load_type] = np.clip(self.internal_state["cognitive_load"][load_type] + delta, 0.0, 1.0)
89
+
90
+ # Update introspection and engagement levels
91
  self.internal_state["introspection_level"] = np.clip(self.internal_state["introspection_level"] + introspection_delta, 0.0, 1.0)
92
+ self.internal_state["engagement_level"] = np.clip(self.internal_state["engagement_level"] + engagement_delta, 0.0, 1.0)
93
+
94
+ # Activate dormant goals based on internal state
95
+ if self.internal_state["emotions"]["curiosity"] > 0.7 and self.goals[3]["status"] == "dormant":
96
+ self.goals[3]["status"] = "active" # Activate knowledge gap filling
97
+ if self.internal_state["engagement_level"] > 0.8 and self.goals[4]["status"] == "dormant":
98
+ self.goals[4]["status"] = "active" # Activate emotional adaptation
99
 
100
  def update_knowledge_graph(self, entities, relationships):
101
  for entity in entities:
 
121
  }
122
 
123
  def calculate_coherence(self):
124
+ # Improved coherence calculation considering conversation history and internal state
125
+ if not self.conversation_history:
126
+ return 0.95
127
+
128
+ coherence_scores = []
129
+ for i in range(1, len(self.conversation_history)):
130
+ current_message = self.conversation_history[i]['content']
131
+ previous_message = self.conversation_history[i-1]['content']
132
+ similarity_score = util.pytorch_cos_sim(
133
+ self.embedding_model.encode(current_message, convert_to_tensor=True),
134
+ self.embedding_model.encode(previous_message, convert_to_tensor=True)
135
+ ).item()
136
+ coherence_scores.append(similarity_score)
137
+
138
+ average_coherence = np.mean(coherence_scores)
139
+
140
+ # Adjust coherence based on internal state
141
+ if self.internal_state["cognitive_load"]["processing_intensity"] > 0.8:
142
+ average_coherence -= 0.1 # Reduce coherence if under heavy processing load
143
+ if self.internal_state["emotions"]["frustration"] > 0.5:
144
+ average_coherence -= 0.15 # Reduce coherence if frustrated
145
+
146
+ return np.clip(average_coherence, 0.0, 1.0)
147
 
148
  def calculate_relevance(self):
149
+ # More sophisticated relevance calculation using knowledge graph and goal priorities
150
+ if not self.conversation_history:
151
+ return 0.9
152
+
153
+ last_user_message = self.conversation_history[-1]['content']
154
+ relevant_entities = self.extract_entities(last_user_message)
155
+ relevance_score = 0
156
+
157
+ # Check if entities are present in the knowledge graph
158
+ for entity in relevant_entities:
159
+ if entity in self.knowledge_graph:
160
+ relevance_score += 0.2
161
+
162
+ # Consider current goals and their priorities
163
+ for goal in self.goals:
164
+ if goal["status"] == "active":
165
+ if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
166
+ relevance_score += goal["priority"] * 0.5 # Boost relevance if aligned with primary goal
167
+ elif goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
168
+ if not relevant_entities or not all(entity in self.knowledge_graph for entity in relevant_entities):
169
+ relevance_score += goal["priority"] * 0.3 # Boost relevance if triggering knowledge gap filling
170
+
171
+ return np.clip(relevance_score, 0.0, 1.0)
172
+
173
  def detect_bias(self):
174
+ # Enhanced bias detection using sentiment analysis and internal state monitoring
175
+ bias_score = 0.0
176
+
177
+ # Analyze sentiment of recent conversation history
178
+ recent_messages = [msg['content'] for msg in self.conversation_history[-3:] if msg['role'] == 'assistant']
179
+ if recent_messages:
180
+ average_valence = np.mean([self.embedding_model.encode(msg, convert_to_tensor=True).mean().item() for msg in recent_messages])
181
+ if average_valence < 0.4 or average_valence > 0.6:
182
+ bias_score += 0.2 # Potential bias if sentiment is strongly positive or negative
183
+
184
+ # Check for emotional extremes in internal state
185
+ if self.internal_state["emotions"]["valence"] < 0.3 or self.internal_state["emotions"]["valence"] > 0.7:
186
+ bias_score += 0.15
187
+ if self.internal_state["emotions"]["dominance"] > 0.8:
188
+ bias_score += 0.1
189
 
190
+ return np.clip(bias_score, 0.0, 1.0)
191
+
192
+ def suggest_strategy_adjustment(self):
193
+ # More nuanced strategy adjustments based on metacognitive analysis and internal state
194
+ adjustments = []
195
+
196
+ if self.metacognitive_layer["coherence_score"] < 0.7:
197
+ adjustments.append("Focus on improving coherence by explicitly connecting ideas between turns.")
198
+ if self.metacognitive_layer["relevance_score"] < 0.7:
199
+ adjustments.append("Increase relevance by directly addressing user queries and utilizing stored knowledge.")
200
+ if self.metacognitive_layer["bias_detection"] > 0.3:
201
+ adjustments.append("Monitor and adjust responses to reduce potential biases. Consider rephrasing or providing alternative viewpoints.")
202
+
203
+ # Internal state-driven adjustments
204
+ if self.internal_state["cognitive_load"]["memory_load"] > 0.8:
205
+ adjustments.append("Memory load is high. Consider summarizing or forgetting less relevant information.")
206
+ if self.internal_state["emotions"]["frustration"] > 0.6:
207
+ adjustments.append("Frustration level is elevated. Prioritize concise and direct responses. Consider asking clarifying questions.")
208
+ if self.internal_state["emotions"]["curiosity"] > 0.8 and self.internal_state["cognitive_load"]["processing_intensity"] < 0.5:
209
+ adjustments.append("High curiosity and low processing load. Explore the topic further by asking relevant questions or seeking external information.")
210
+
211
+ if not adjustments:
212
+ return "Current strategy is effective. Continue with the current approach."
213
+ else:
214
+ return " ".join(adjustments)
215
+
216
  def introspect(self):
217
  introspection_report = "Introspection Report:\n"
218
+ introspection_report += f" Current Emotional State:\n"
219
+ for emotion, value in self.internal_state['emotions'].items():
220
+ introspection_report += f" - {emotion.capitalize()}: {value:.2f}\n"
221
+ introspection_report += f" Cognitive Load:\n"
222
+ for load_type, value in self.internal_state['cognitive_load'].items():
223
+ introspection_report += f" - {load_type.capitalize()}: {value:.2f}\n"
224
  introspection_report += f" Introspection Level: {self.internal_state['introspection_level']:.2f}\n"
225
+ introspection_report += f" Engagement Level: {self.internal_state['engagement_level']:.2f}\n"
226
  introspection_report += " Current Goals:\n"
227
  for goal in self.goals:
228
+ introspection_report += f" - {goal['goal']} (Priority: {goal['priority']:.2f}, Status: {goal['status']}, Progress: {goal['progress']:.2f})\n"
229
  introspection_report += "Metacognitive Layer Report\n"
230
  introspection_report += f"Coherence Score: {self.metacognitive_layer['coherence_score']}\n"
231
  introspection_report += f"Relevance Score: {self.metacognitive_layer['relevance_score']}\n"
 
234
  return introspection_report
235
 
236
  def adjust_response_based_on_state(self, response):
237
+ # More sophisticated response adjustment based on internal state
238
  if self.internal_state["introspection_level"] > 0.7:
239
  response = self.introspect() + "\n\n" + response
240
 
241
  valence = self.internal_state["emotions"]["valence"]
242
  arousal = self.internal_state["emotions"]["arousal"]
243
+ curiosity = self.internal_state["emotions"]["curiosity"]
244
+ frustration = self.internal_state["emotions"]["frustration"]
245
+ confidence = self.internal_state["emotions"]["confidence"]
246
 
247
+ # Adjust tone based on valence and arousal
248
  if valence < 0.4:
249
  if arousal > 0.6:
250
  response = "I'm feeling a bit overwhelmed right now, but I'll do my best to assist you. " + response
 
256
  else:
257
  response = "I'm in a good mood and happy to help. " + response
258
 
259
+ # Adjust response based on other emotional states
260
+ if curiosity > 0.7:
261
+ response += " I'm very curious about this topic, could you tell me more?"
262
+ if frustration > 0.5:
263
+ response = "I'm finding this a bit challenging, but I'll give it another try. " + response
264
+ if confidence < 0.5:
265
+ response = "I'm not entirely sure about this, but here's what I think: " + response
266
+
267
+ # Adjust based on cognitive load
268
+ if self.internal_state["cognitive_load"]["memory_load"] > 0.7:
269
+ response = "I'm holding a lot of information right now, so my response might be a bit brief: " + response
270
+
271
  return response
272
+
273
  def update_goals(self, user_feedback):
274
+ # More dynamic goal updates based on feedback and internal state
275
+ feedback_lower = user_feedback.lower()
276
+
277
+ # General feedback
278
+ if "helpful" in feedback_lower:
279
  for goal in self.goals:
280
+ if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
281
  goal["priority"] = min(goal["priority"] + 0.1, 1.0)
282
+ goal["progress"] = min(goal["progress"] + 0.2, 1.0)
283
+ elif "confusing" in feedback_lower:
284
+ for goal in self.goals:
285
+ if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
286
+ goal["priority"] = max(goal["priority"] - 0.1, 0.0)
287
+ goal["progress"] = max(goal["progress"] - 0.2, 0.0)
288
+
289
+ # Goal-specific feedback
290
+ if "learn more" in feedback_lower:
291
+ for goal in self.goals:
292
+ if goal["goal"] == "Actively learn and adapt from interactions to improve conversational abilities":
293
+ goal["priority"] = min(goal["priority"] + 0.2, 1.0)
294
+ goal["progress"] = min(goal["progress"] + 0.1, 1.0)
295
+ elif "too repetitive" in feedback_lower:
296
  for goal in self.goals:
297
+ if goal["goal"] == "Maintain a coherent, engaging, and empathetic conversation flow":
298
  goal["priority"] = max(goal["priority"] - 0.1, 0.0)
299
+ goal["progress"] = max(goal["progress"] - 0.2, 0.0)
300
+
301
+ # Internal state influence on goal updates
302
+ if self.internal_state["emotions"]["curiosity"] > 0.8:
303
+ for goal in self.goals:
304
+ if goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
305
+ goal["priority"] = min(goal["priority"] + 0.1, 1.0)
306
+ goal["progress"] = min(goal["progress"] + 0.1, 1.0)
307
 
308
  def store_information(self, key, value):
309
  new_memory = f"{key}: {value}"
310
  self.persistent_memory.append(new_memory)
311
  self.update_memory_embeddings()
312
+ self.update_internal_state({}, {"memory_load": 0.1, "processing_intensity": 0.05}, 0, 0.05)
313
  return f"Stored: {key} = {value}"
314
 
315
  def retrieve_information(self, query):
 
328
  top_results = torch.topk(cosine_scores, k=min(3, len(self.persistent_memory)))
329
 
330
  relevant_memories = [self.persistent_memory[i] for i in top_results.indices]
331
+ self.update_internal_state({}, {"memory_load": 0.05, "processing_intensity": 0.1}, 0.1, 0.05)
332
  return "\n".join(relevant_memories)
333
 
334
  def update_memory_embeddings(self):
 
343
  "valence": 0.5,
344
  "arousal": 0.5,
345
  "dominance": 0.5,
346
+ "curiosity": 0.5,
347
+ "frustration": 0.0,
348
+ "confidence": 0.7
349
  },
350
+ "cognitive_load": {
351
+ "memory_load": 0.0,
352
+ "processing_intensity": 0.0
353
+ },
354
+ "introspection_level": 0.0,
355
+ "engagement_level": 0.5
356
  }
357
  self.goals = [
358
+ {"goal": "Provide helpful, informative, and contextually relevant responses", "priority": 0.8, "status": "active", "progress": 0.0},
359
+ {"goal": "Actively learn and adapt from interactions to improve conversational abilities", "priority": 0.9, "status": "active", "progress": 0.0},
360
+ {"goal": "Maintain a coherent, engaging, and empathetic conversation flow", "priority": 0.7, "status": "active", "progress": 0.0},
361
+ {"goal": "Identify and fill knowledge gaps by seeking external information", "priority": 0.6, "status": "dormant", "progress": 0.0},
362
+ {"goal": "Recognize and adapt to user's emotional state and adjust response style accordingly", "priority": 0.7, "status": "dormant", "progress": 0.0}
363
  ]
364
 
365
  self.knowledge_graph = nx.DiGraph()
 
479
  return f"Error generating response: {str(e)}"
480
 
481
  def extract_entities(self, text):
482
+ # Placeholder for a more advanced entity extraction using NLP techniques
483
+ # This is a very basic example and should be replaced with a proper NER model
484
+ words = text.split()
485
+ entities = [word for word in words if word.isalpha() and word.istitle()]
486
+ return entities
487
 
488
  def extract_relationships(self, text):
489
+ # Placeholder for relationship extraction - this is a very basic example
490
+ # Consider using dependency parsing or other NLP techniques for better results
491
+ sentences = text.split('.')
492
+ relationships = []
493
+ for sentence in sentences:
494
+ words = sentence.split()
495
+ if len(words) >= 3:
496
+ for i in range(len(words) - 2):
497
+ if words[i].istitle() and words[i+2].istitle():
498
+ relationships.append((words[i], words[i+1], words[i+2]))
499
+ return relationships
500
  def messages_to_prompt(self, messages):
501
  prompt = ""
502
  for msg in messages:
 
554
 
555
  self.update_goals(message)
556
 
557
+ # Update internal state based on user input (more nuanced)
558
+ emotion_deltas = {}
559
+ cognitive_load_deltas = {}
560
+ engagement_delta = 0
561
+
562
  if any(word in message.lower() for word in ["sad", "unhappy", "depressed", "down"]):
563
+ emotion_deltas.update({"valence": -0.2, "arousal": 0.1, "confidence": -0.1})
564
+ engagement_delta = -0.1
565
  elif any(word in message.lower() for word in ["happy", "good", "great", "excited", "amazing"]):
566
+ emotion_deltas.update({"valence": 0.2, "arousal": 0.2, "confidence": 0.1})
567
+ engagement_delta = 0.2
568
  elif any(word in message.lower() for word in ["angry", "mad", "furious", "frustrated"]):
569
+ emotion_deltas.update({"valence": -0.3, "arousal": 0.3, "dominance": -0.2, "frustration": 0.2})
570
+ engagement_delta = -0.2
571
  elif any(word in message.lower() for word in ["scared", "afraid", "fearful", "anxious"]):
572
+ emotion_deltas.update({"valence": -0.2, "arousal": 0.4, "dominance": -0.3, "confidence": -0.2})
573
+ engagement_delta = -0.1
574
  elif any(word in message.lower() for word in ["surprise", "amazed", "astonished"]):
575
+ emotion_deltas.update({"valence": 0.1, "arousal": 0.5, "dominance": 0.1, "curiosity": 0.3})
576
+ engagement_delta = 0.3
577
+ elif any(word in message.lower() for word in ["confused", "uncertain", "unsure"]):
578
+ cognitive_load_deltas.update({"processing_intensity": 0.2})
579
+ emotion_deltas.update({"curiosity": 0.2, "confidence": -0.1})
580
+ engagement_delta = 0.1
581
  else:
582
+ emotion_deltas.update({"valence": 0.05, "arousal": 0.05})
583
+ engagement_delta = 0.05
584
+
585
+ if "learn" in message.lower() or "explain" in message.lower() or "know more" in message.lower():
586
+ emotion_deltas.update({"curiosity": 0.3})
587
+ cognitive_load_deltas.update({"processing_intensity": 0.1})
588
+ engagement_delta = 0.2
589
+
590
+ self.update_internal_state(emotion_deltas, cognitive_load_deltas, 0.1, engagement_delta)
591
 
592
 
593
  self.conversation_history.append(ChatMessage(role="user", content=message).to_dict())
 
596
  if len(self.conversation_history) > 10:
597
  self.conversation_history = self.conversation_history[-10:]
598
 
599
+
600
  custom_css = """
601
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
602
  body, .gradio-container {