Reality123b commited on
Commit
ba26ed2
·
verified ·
1 Parent(s): bb1f80a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -65
app.py CHANGED
@@ -10,7 +10,6 @@ from sentence_transformers import SentenceTransformer, util
10
  import torch
11
  import numpy as np
12
  import networkx as nx
13
- from collections import Counter
14
 
15
  @dataclass
16
  class ChatMessage:
@@ -48,60 +47,55 @@ class XylariaChat:
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,6 +121,7 @@ class XylariaChat:
127
  }
128
 
129
  def calculate_coherence(self):
 
130
  if not self.conversation_history:
131
  return 0.95
132
 
@@ -142,14 +137,16 @@ class XylariaChat:
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,29 +154,34 @@ class XylariaChat:
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,6 +190,7 @@ class XylariaChat:
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,6 +200,7 @@ class XylariaChat:
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,6 +234,7 @@ class XylariaChat:
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,6 +244,7 @@ class XylariaChat:
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,6 +256,7 @@ class XylariaChat:
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,14 +264,17 @@ class XylariaChat:
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,6 +286,7 @@ class XylariaChat:
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,6 +298,7 @@ class XylariaChat:
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,39 +472,6 @@ class XylariaChat:
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:
492
- if effect in " ".join([msg['content'].lower() for msg in self.conversation_history]).lower():
493
- causal_inference = f"It seems {cause} might be related to {effect}."
494
- self.store_information("Causal Inference", causal_inference)
495
-
496
  return stream
497
 
498
  except Exception as e:
@@ -500,11 +479,15 @@ class XylariaChat:
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,7 +497,6 @@ class XylariaChat:
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,6 +554,7 @@ class XylariaChat:
572
 
573
  self.update_goals(message)
574
 
 
575
  emotion_deltas = {}
576
  cognitive_load_deltas = {}
577
  engagement_delta = 0
@@ -614,7 +597,6 @@ class XylariaChat:
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,6 +677,7 @@ class XylariaChat:
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(
 
10
  import torch
11
  import numpy as np
12
  import networkx as nx
 
13
 
14
  @dataclass
15
  class ChatMessage:
 
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
 
 
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
 
 
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:
 
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:
 
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:
 
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
 
 
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:
 
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":
 
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":
 
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":
 
472
  stream=True
473
  )
474
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  return stream
476
 
477
  except Exception as e:
 
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:
 
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
 
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 {
 
677
  flex-direction: column-reverse;
678
  }
679
  """
680
+
681
  with gr.Blocks(theme='soft', css=custom_css) as demo:
682
  with gr.Column():
683
  chatbot = gr.Chatbot(