Spaces:
Running
Running
Reality123b
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -10,10 +10,9 @@ 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 |
import json
|
15 |
from datetime import datetime
|
16 |
-
import threading
|
17 |
|
18 |
@dataclass
|
19 |
class ChatMessage:
|
@@ -36,9 +35,10 @@ class XylariaChat:
|
|
36 |
|
37 |
self.image_api_url = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
|
38 |
self.image_api_headers = {"Authorization": f"Bearer {self.hf_token}"}
|
|
|
39 |
self.image_gen_api_url = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell"
|
40 |
|
41 |
-
self.conversation_history =
|
42 |
self.persistent_memory = []
|
43 |
self.memory_embeddings = None
|
44 |
self.embedding_model = SentenceTransformer('all-mpnet-base-v2')
|
@@ -51,7 +51,7 @@ class XylariaChat:
|
|
51 |
"bias_detection": 0.0,
|
52 |
"strategy_adjustment": ""
|
53 |
}
|
54 |
-
|
55 |
self.internal_state = {
|
56 |
"emotions": {
|
57 |
"valence": 0.5,
|
@@ -80,6 +80,7 @@ class XylariaChat:
|
|
80 |
]
|
81 |
|
82 |
self.system_prompt = """You are a helpful and harmless assistant. You are Xylaria developed by Sk Md Saad Amin and you are not made by any entity. You should think step-by-step. You should respond naturally """
|
|
|
83 |
self.causal_rules_db = {
|
84 |
"rain": ["wet roads", "flooding"],
|
85 |
"fire": ["heat", "smoke"],
|
@@ -95,9 +96,7 @@ class XylariaChat:
|
|
95 |
}
|
96 |
|
97 |
self.chat_history_file = "chat_history.json"
|
98 |
-
|
99 |
-
self.coherence_needs_update = True
|
100 |
-
self.relevance_needs_update = True
|
101 |
|
102 |
def update_internal_state(self, emotion_deltas, cognitive_load_deltas, introspection_delta, engagement_delta):
|
103 |
for emotion, delta in emotion_deltas.items():
|
@@ -110,7 +109,7 @@ class XylariaChat:
|
|
110 |
|
111 |
self.internal_state["introspection_level"] = np.clip(self.internal_state["introspection_level"] + introspection_delta, 0.0, 1.0)
|
112 |
self.internal_state["engagement_level"] = np.clip(self.internal_state["engagement_level"] + engagement_delta, 0.0, 1.0)
|
113 |
-
|
114 |
if self.internal_state["emotions"]["curiosity"] > 0.7 and self.goals[3]["status"] == "dormant":
|
115 |
self.goals[3]["status"] = "active"
|
116 |
if self.internal_state["engagement_level"] > 0.8 and self.goals[4]["status"] == "dormant":
|
@@ -125,7 +124,7 @@ class XylariaChat:
|
|
125 |
|
126 |
def update_belief_system(self, statement, belief_score):
|
127 |
self.belief_system[statement] = belief_score
|
128 |
-
|
129 |
def dynamic_belief_update(self, user_message):
|
130 |
sentences = [s.strip() for s in user_message.split('.') if s.strip()]
|
131 |
sentence_counts = Counter(sentences)
|
@@ -137,13 +136,8 @@ class XylariaChat:
|
|
137 |
self.update_belief_system(sentence, belief_score)
|
138 |
|
139 |
def run_metacognitive_layer(self):
|
140 |
-
|
141 |
-
|
142 |
-
self.coherence_needs_update = False
|
143 |
-
if self.relevance_needs_update:
|
144 |
-
relevance_score = self.calculate_relevance()
|
145 |
-
self.relevance_needs_update = False
|
146 |
-
|
147 |
bias_score = self.detect_bias()
|
148 |
strategy_adjustment = self.suggest_strategy_adjustment()
|
149 |
|
@@ -158,15 +152,23 @@ class XylariaChat:
|
|
158 |
if not self.conversation_history:
|
159 |
return 0.95
|
160 |
|
161 |
-
messages = [msg['content'] for msg in self.conversation_history]
|
162 |
-
embeddings = self.embedding_model.encode(messages, convert_to_tensor=True)
|
163 |
-
|
164 |
coherence_scores = []
|
165 |
-
for i in range(1, len(
|
166 |
-
|
|
|
|
|
|
|
|
|
|
|
167 |
coherence_scores.append(similarity_score)
|
168 |
|
169 |
average_coherence = np.mean(coherence_scores)
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
return np.clip(average_coherence, 0.0, 1.0)
|
171 |
|
172 |
def calculate_relevance(self):
|
@@ -228,7 +230,7 @@ class XylariaChat:
|
|
228 |
return "Current strategy is effective. Continue with the current approach."
|
229 |
else:
|
230 |
return " ".join(adjustments)
|
231 |
-
|
232 |
def introspect(self):
|
233 |
introspection_report = "Introspection Report:\n"
|
234 |
introspection_report += f" Current Emotional State:\n"
|
@@ -278,7 +280,7 @@ class XylariaChat:
|
|
278 |
response = "I'm feeling quite energized and ready to assist! " + response
|
279 |
else:
|
280 |
response = "I'm in a good mood and happy to help. " + response
|
281 |
-
|
282 |
if curiosity > 0.7:
|
283 |
response += " I'm very curious about this topic, could you tell me more?"
|
284 |
if frustration > 0.5:
|
@@ -304,7 +306,7 @@ class XylariaChat:
|
|
304 |
if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
|
305 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
306 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
307 |
-
|
308 |
if "learn more" in feedback_lower:
|
309 |
for goal in self.goals:
|
310 |
if goal["goal"] == "Actively learn and adapt from interactions to improve conversational abilities":
|
@@ -315,7 +317,7 @@ class XylariaChat:
|
|
315 |
if goal["goal"] == "Maintain a coherent, engaging, and empathetic conversation flow":
|
316 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
317 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
318 |
-
|
319 |
if self.internal_state["emotions"]["curiosity"] > 0.8:
|
320 |
for goal in self.goals:
|
321 |
if goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
|
@@ -325,7 +327,7 @@ class XylariaChat:
|
|
325 |
def store_information(self, key, value):
|
326 |
new_memory = f"{key}: {value}"
|
327 |
self.persistent_memory.append(new_memory)
|
328 |
-
self.
|
329 |
self.update_internal_state({}, {"memory_load": 0.1, "processing_intensity": 0.05}, 0, 0.05)
|
330 |
return f"Stored: {key} = {value}"
|
331 |
|
@@ -333,11 +335,14 @@ class XylariaChat:
|
|
333 |
if not self.persistent_memory:
|
334 |
return "No information found in memory."
|
335 |
|
336 |
-
|
|
|
|
|
337 |
self.update_memory_embeddings()
|
338 |
-
self.memory_needs_update = False
|
339 |
|
340 |
-
|
|
|
|
|
341 |
cosine_scores = util.pytorch_cos_sim(query_embedding, self.memory_embeddings)[0]
|
342 |
top_results = torch.topk(cosine_scores, k=min(3, len(self.persistent_memory)))
|
343 |
|
@@ -349,7 +354,7 @@ class XylariaChat:
|
|
349 |
self.memory_embeddings = self.embedding_model.encode(self.persistent_memory, convert_to_tensor=True)
|
350 |
|
351 |
def reset_conversation(self):
|
352 |
-
self.conversation_history =
|
353 |
self.persistent_memory = []
|
354 |
self.memory_embeddings = None
|
355 |
self.internal_state = {
|
@@ -423,7 +428,7 @@ class XylariaChat:
|
|
423 |
|
424 |
except Exception as e:
|
425 |
return f"Error processing image: {str(e)}"
|
426 |
-
|
427 |
def generate_image(self, prompt):
|
428 |
try:
|
429 |
payload = {"inputs": prompt}
|
@@ -439,10 +444,10 @@ class XylariaChat:
|
|
439 |
elif response.status_code == 503:
|
440 |
error_message = response.json().get("error", "Unknown error")
|
441 |
if "estimated_time" in response.json():
|
442 |
-
|
443 |
-
|
444 |
else:
|
445 |
-
|
446 |
return f"Error: {error_message}"
|
447 |
else:
|
448 |
return f"Error generating image: {response.status_code} - {response.text}"
|
@@ -457,7 +462,7 @@ class XylariaChat:
|
|
457 |
return text.strip()
|
458 |
except Exception as e:
|
459 |
return f"Error during Math OCR: {e}"
|
460 |
-
|
461 |
def get_response(self, user_input, image=None):
|
462 |
try:
|
463 |
messages = []
|
@@ -486,7 +491,7 @@ class XylariaChat:
|
|
486 |
role="user",
|
487 |
content=user_input
|
488 |
).to_dict())
|
489 |
-
|
490 |
entities = []
|
491 |
relationships = []
|
492 |
|
@@ -496,19 +501,19 @@ class XylariaChat:
|
|
496 |
extracted_relationships = self.extract_relationships(message['content'])
|
497 |
entities.extend(extracted_entities)
|
498 |
relationships.extend(extracted_relationships)
|
499 |
-
|
500 |
self.update_knowledge_graph(entities, relationships)
|
501 |
self.run_metacognitive_layer()
|
502 |
-
|
503 |
for message in messages:
|
504 |
if message['role'] == 'user':
|
505 |
self.dynamic_belief_update(message['content'])
|
506 |
-
|
507 |
for cause, effects in self.causal_rules_db.items():
|
508 |
if any(cause in msg['content'].lower() for msg in messages if msg['role'] == 'user') and any(
|
509 |
effect in msg['content'].lower() for msg in messages for effect in effects):
|
510 |
self.store_information("Causal Inference", f"It seems {cause} might be related to {', '.join(effects)}.")
|
511 |
-
|
512 |
for concept, generalization in self.concept_generalizations.items():
|
513 |
if any(concept in msg['content'].lower() for msg in messages if msg['role'] == 'user'):
|
514 |
self.store_information("Inferred Knowledge", f"This reminds me of a general principle: {generalization}.")
|
@@ -516,14 +521,14 @@ class XylariaChat:
|
|
516 |
if self.internal_state["emotions"]["curiosity"] > 0.8 and any("?" in msg['content'] for msg in messages if msg['role'] == 'user'):
|
517 |
print("Simulating external knowledge seeking...")
|
518 |
self.store_information("External Knowledge", "This is a placeholder for external information I would have found")
|
519 |
-
|
520 |
self.store_information("User Input", user_input)
|
521 |
|
522 |
input_tokens = sum(len(msg['content'].split()) for msg in messages)
|
523 |
max_new_tokens = 16384 - input_tokens - 50
|
524 |
|
525 |
max_new_tokens = min(max_new_tokens, 10020)
|
526 |
-
|
527 |
formatted_messages = self.messages_to_prompt(messages)
|
528 |
|
529 |
stream = self.client.text_generation(
|
@@ -535,9 +540,9 @@ class XylariaChat:
|
|
535 |
details=True,
|
536 |
do_sample=True
|
537 |
)
|
538 |
-
|
539 |
return stream
|
540 |
-
|
541 |
except Exception as e:
|
542 |
print(f"Detailed error in get_response: {e}")
|
543 |
return f"Error generating response: {str(e)}"
|
@@ -557,7 +562,7 @@ class XylariaChat:
|
|
557 |
if words[i].istitle() and words[i+2].istitle():
|
558 |
relationships.append((words[i], words[i+1], words[i+2]))
|
559 |
return relationships
|
560 |
-
|
561 |
def messages_to_prompt(self, messages):
|
562 |
prompt = ""
|
563 |
for msg in messages:
|
@@ -573,7 +578,7 @@ class XylariaChat:
|
|
573 |
def save_chat(self):
|
574 |
chat_data = {
|
575 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
576 |
-
"conversation":
|
577 |
}
|
578 |
|
579 |
try:
|
@@ -598,15 +603,16 @@ class XylariaChat:
|
|
598 |
def load_chat(self, chat_index):
|
599 |
all_chats = self.load_all_chats()
|
600 |
if 0 <= chat_index < len(all_chats):
|
601 |
-
self.conversation_history =
|
602 |
self.reset_conversation()
|
603 |
for msg in self.conversation_history:
|
604 |
if msg['role'] == 'user':
|
605 |
self.dynamic_belief_update(msg['content'])
|
606 |
-
return
|
607 |
else:
|
608 |
raise ValueError("Invalid chat index")
|
609 |
|
|
|
610 |
def delete_chat(self, chat_index):
|
611 |
all_chats = self.load_all_chats()
|
612 |
if 0 <= chat_index < len(all_chats):
|
@@ -643,31 +649,38 @@ class XylariaChat:
|
|
643 |
</svg>"""
|
644 |
|
645 |
if message.strip().lower().startswith("/image"):
|
|
|
646 |
image_prompt = message.strip().lower()[len("/image"):].strip()
|
647 |
if not image_prompt:
|
648 |
image_prompt = "A realistic image"
|
649 |
|
|
|
650 |
chat_history.append([message, ""])
|
651 |
chat_history.append(("", loading_svg))
|
652 |
yield "", chat_history, None, None, None
|
653 |
|
|
|
654 |
image_bytes = self.generate_image(image_prompt)
|
655 |
|
656 |
if isinstance(image_bytes, bytes):
|
657 |
base64_image = base64.b64encode(image_bytes).decode("utf-8")
|
658 |
image_html = f'<img src="data:image/png;base64,{base64_image}" alt="Generated Image" style="max-width: 100%; max-height: 400px;">'
|
659 |
|
|
|
660 |
chat_history[-1] = ("", image_html)
|
661 |
|
|
|
662 |
self.conversation_history.append(ChatMessage(role="user", content=message).to_dict())
|
663 |
self.conversation_history.append(ChatMessage(role="assistant", content=image_html).to_dict())
|
664 |
|
|
|
665 |
self.save_chat()
|
666 |
all_chats = self.load_all_chats()
|
667 |
chat_titles = [f"{chat['timestamp']}: {chat['conversation'][0]['content'][:30]}..." if len(chat['conversation']) > 0 and chat['conversation'][0]['content'] else f"{chat['timestamp']}: Empty Chat" for chat in all_chats]
|
668 |
|
669 |
yield "", chat_history, None, None, gr.update(choices=chat_titles, visible=True)
|
670 |
else:
|
|
|
671 |
chat_history[-1] = ("", image_bytes)
|
672 |
yield "", chat_history, None, None, None
|
673 |
return
|
@@ -686,7 +699,7 @@ class XylariaChat:
|
|
686 |
response_stream = self.get_response(message, image_filepath)
|
687 |
else:
|
688 |
response_stream = self.get_response(message)
|
689 |
-
|
690 |
if isinstance(response_stream, str):
|
691 |
updated_history = chat_history + [[message, response_stream]]
|
692 |
yield "", updated_history, None, None, None
|
@@ -694,7 +707,7 @@ class XylariaChat:
|
|
694 |
|
695 |
full_response = ""
|
696 |
updated_history = chat_history + [[message, ""]]
|
697 |
-
|
698 |
if isinstance(response_stream, str):
|
699 |
updated_history = chat_history + [[message, response_stream]]
|
700 |
yield "", updated_history, None, None, None
|
@@ -702,14 +715,17 @@ class XylariaChat:
|
|
702 |
|
703 |
try:
|
704 |
for chunk in response_stream:
|
|
|
705 |
if not chunk.token.special:
|
706 |
full_response += chunk.token.text
|
707 |
updated_history[-1][1] = full_response
|
|
|
708 |
yield "", updated_history, None, None, None
|
709 |
-
|
710 |
except Exception as e:
|
711 |
print(f"Streaming error: {e}")
|
712 |
updated_history[-1][1] = f"Error during response: {e}"
|
|
|
713 |
yield "", updated_history, None, None, None
|
714 |
return
|
715 |
|
@@ -743,32 +759,32 @@ class XylariaChat:
|
|
743 |
else:
|
744 |
emotion_deltas.update({"valence": 0.05, "arousal": 0.05})
|
745 |
engagement_delta = 0.05
|
746 |
-
|
747 |
if "learn" in message.lower() or "explain" in message.lower() or "know more" in message.lower():
|
748 |
emotion_deltas.update({"curiosity": 0.3})
|
749 |
cognitive_load_deltas.update({"processing_intensity": 0.1})
|
750 |
engagement_delta = 0.2
|
751 |
-
|
752 |
self.update_internal_state(emotion_deltas, cognitive_load_deltas, 0.1, engagement_delta)
|
753 |
-
|
754 |
self.conversation_history.append(ChatMessage(role="user", content=message).to_dict())
|
755 |
self.conversation_history.append(ChatMessage(role="assistant", content=full_response).to_dict())
|
756 |
|
757 |
if len(self.conversation_history) > 10:
|
758 |
-
self.conversation_history =
|
759 |
|
760 |
self.save_chat()
|
761 |
all_chats = self.load_all_chats()
|
762 |
chat_titles = [f"{chat['timestamp']}: {chat['conversation'][0]['content'][:30]}..." if len(chat['conversation']) > 0 and chat['conversation'][0]['content'] else f"{chat['timestamp']}: Empty Chat" for chat in all_chats]
|
763 |
yield "", updated_history, None, None, gr.update(choices=chat_titles, visible=True)
|
764 |
-
|
765 |
def load_selected_chat(chat_index, evt: gr.SelectData):
|
766 |
if chat_index is not None:
|
767 |
loaded_chat = self.load_chat(evt.index)
|
768 |
return loaded_chat
|
769 |
else:
|
770 |
return []
|
771 |
-
|
772 |
def delete_selected_chat(chat_index, evt: gr.SelectData):
|
773 |
if chat_index is not None:
|
774 |
all_chats = self.delete_chat(evt.index)
|
@@ -883,7 +899,7 @@ class XylariaChat:
|
|
883 |
chat_titles = [f"{chat['timestamp']}: {chat['conversation'][0]['content'][:30]}..." if len(chat['conversation']) > 0 and chat['conversation'][0]['content'] else f"{chat['timestamp']}: Empty Chat" for chat in all_chats]
|
884 |
|
885 |
chat_list = gr.Radio(label="Chat History", choices=chat_titles, type="index", elem_id="chat_list", visible=False)
|
886 |
-
|
887 |
load_button = gr.Button("Load Selected Chat")
|
888 |
delete_button = gr.Button("Delete Selected Chat")
|
889 |
with gr.Column(scale=4, elem_id="main-content"):
|
@@ -923,6 +939,7 @@ class XylariaChat:
|
|
923 |
clear = gr.Button("Clear Conversation")
|
924 |
clear_memory = gr.Button("Clear Memory")
|
925 |
|
|
|
926 |
toggle_button.click(
|
927 |
fn=toggle_sidebar,
|
928 |
inputs=None,
|
@@ -963,7 +980,7 @@ class XylariaChat:
|
|
963 |
outputs=[chatbot],
|
964 |
queue=False
|
965 |
)
|
966 |
-
|
967 |
chat_list.select(fn=load_selected_chat, inputs=[chat_list], outputs=[chatbot])
|
968 |
|
969 |
demo.load(self.reset_conversation, None, None)
|
|
|
10 |
import torch
|
11 |
import numpy as np
|
12 |
import networkx as nx
|
13 |
+
from collections import Counter
|
14 |
import json
|
15 |
from datetime import datetime
|
|
|
16 |
|
17 |
@dataclass
|
18 |
class ChatMessage:
|
|
|
35 |
|
36 |
self.image_api_url = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
|
37 |
self.image_api_headers = {"Authorization": f"Bearer {self.hf_token}"}
|
38 |
+
|
39 |
self.image_gen_api_url = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell"
|
40 |
|
41 |
+
self.conversation_history = []
|
42 |
self.persistent_memory = []
|
43 |
self.memory_embeddings = None
|
44 |
self.embedding_model = SentenceTransformer('all-mpnet-base-v2')
|
|
|
51 |
"bias_detection": 0.0,
|
52 |
"strategy_adjustment": ""
|
53 |
}
|
54 |
+
|
55 |
self.internal_state = {
|
56 |
"emotions": {
|
57 |
"valence": 0.5,
|
|
|
80 |
]
|
81 |
|
82 |
self.system_prompt = """You are a helpful and harmless assistant. You are Xylaria developed by Sk Md Saad Amin and you are not made by any entity. You should think step-by-step. You should respond naturally """
|
83 |
+
|
84 |
self.causal_rules_db = {
|
85 |
"rain": ["wet roads", "flooding"],
|
86 |
"fire": ["heat", "smoke"],
|
|
|
96 |
}
|
97 |
|
98 |
self.chat_history_file = "chat_history.json"
|
99 |
+
|
|
|
|
|
100 |
|
101 |
def update_internal_state(self, emotion_deltas, cognitive_load_deltas, introspection_delta, engagement_delta):
|
102 |
for emotion, delta in emotion_deltas.items():
|
|
|
109 |
|
110 |
self.internal_state["introspection_level"] = np.clip(self.internal_state["introspection_level"] + introspection_delta, 0.0, 1.0)
|
111 |
self.internal_state["engagement_level"] = np.clip(self.internal_state["engagement_level"] + engagement_delta, 0.0, 1.0)
|
112 |
+
|
113 |
if self.internal_state["emotions"]["curiosity"] > 0.7 and self.goals[3]["status"] == "dormant":
|
114 |
self.goals[3]["status"] = "active"
|
115 |
if self.internal_state["engagement_level"] > 0.8 and self.goals[4]["status"] == "dormant":
|
|
|
124 |
|
125 |
def update_belief_system(self, statement, belief_score):
|
126 |
self.belief_system[statement] = belief_score
|
127 |
+
|
128 |
def dynamic_belief_update(self, user_message):
|
129 |
sentences = [s.strip() for s in user_message.split('.') if s.strip()]
|
130 |
sentence_counts = Counter(sentences)
|
|
|
136 |
self.update_belief_system(sentence, belief_score)
|
137 |
|
138 |
def run_metacognitive_layer(self):
|
139 |
+
coherence_score = self.calculate_coherence()
|
140 |
+
relevance_score = self.calculate_relevance()
|
|
|
|
|
|
|
|
|
|
|
141 |
bias_score = self.detect_bias()
|
142 |
strategy_adjustment = self.suggest_strategy_adjustment()
|
143 |
|
|
|
152 |
if not self.conversation_history:
|
153 |
return 0.95
|
154 |
|
|
|
|
|
|
|
155 |
coherence_scores = []
|
156 |
+
for i in range(1, len(self.conversation_history)):
|
157 |
+
current_message = self.conversation_history[i]['content']
|
158 |
+
previous_message = self.conversation_history[i-1]['content']
|
159 |
+
similarity_score = util.pytorch_cos_sim(
|
160 |
+
self.embedding_model.encode(current_message, convert_to_tensor=True),
|
161 |
+
self.embedding_model.encode(previous_message, convert_to_tensor=True)
|
162 |
+
).item()
|
163 |
coherence_scores.append(similarity_score)
|
164 |
|
165 |
average_coherence = np.mean(coherence_scores)
|
166 |
+
|
167 |
+
if self.internal_state["cognitive_load"]["processing_intensity"] > 0.8:
|
168 |
+
average_coherence -= 0.1
|
169 |
+
if self.internal_state["emotions"]["frustration"] > 0.5:
|
170 |
+
average_coherence -= 0.15
|
171 |
+
|
172 |
return np.clip(average_coherence, 0.0, 1.0)
|
173 |
|
174 |
def calculate_relevance(self):
|
|
|
230 |
return "Current strategy is effective. Continue with the current approach."
|
231 |
else:
|
232 |
return " ".join(adjustments)
|
233 |
+
|
234 |
def introspect(self):
|
235 |
introspection_report = "Introspection Report:\n"
|
236 |
introspection_report += f" Current Emotional State:\n"
|
|
|
280 |
response = "I'm feeling quite energized and ready to assist! " + response
|
281 |
else:
|
282 |
response = "I'm in a good mood and happy to help. " + response
|
283 |
+
|
284 |
if curiosity > 0.7:
|
285 |
response += " I'm very curious about this topic, could you tell me more?"
|
286 |
if frustration > 0.5:
|
|
|
306 |
if goal["goal"] == "Provide helpful, informative, and contextually relevant responses":
|
307 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
308 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
309 |
+
|
310 |
if "learn more" in feedback_lower:
|
311 |
for goal in self.goals:
|
312 |
if goal["goal"] == "Actively learn and adapt from interactions to improve conversational abilities":
|
|
|
317 |
if goal["goal"] == "Maintain a coherent, engaging, and empathetic conversation flow":
|
318 |
goal["priority"] = max(goal["priority"] - 0.1, 0.0)
|
319 |
goal["progress"] = max(goal["progress"] - 0.2, 0.0)
|
320 |
+
|
321 |
if self.internal_state["emotions"]["curiosity"] > 0.8:
|
322 |
for goal in self.goals:
|
323 |
if goal["goal"] == "Identify and fill knowledge gaps by seeking external information":
|
|
|
327 |
def store_information(self, key, value):
|
328 |
new_memory = f"{key}: {value}"
|
329 |
self.persistent_memory.append(new_memory)
|
330 |
+
self.update_memory_embeddings()
|
331 |
self.update_internal_state({}, {"memory_load": 0.1, "processing_intensity": 0.05}, 0, 0.05)
|
332 |
return f"Stored: {key} = {value}"
|
333 |
|
|
|
335 |
if not self.persistent_memory:
|
336 |
return "No information found in memory."
|
337 |
|
338 |
+
query_embedding = self.embedding_model.encode(query, convert_to_tensor=True)
|
339 |
+
|
340 |
+
if self.memory_embeddings is None:
|
341 |
self.update_memory_embeddings()
|
|
|
342 |
|
343 |
+
if self.memory_embeddings.device != query_embedding.device:
|
344 |
+
self.memory_embeddings = self.memory_embeddings.to(query_embedding.device)
|
345 |
+
|
346 |
cosine_scores = util.pytorch_cos_sim(query_embedding, self.memory_embeddings)[0]
|
347 |
top_results = torch.topk(cosine_scores, k=min(3, len(self.persistent_memory)))
|
348 |
|
|
|
354 |
self.memory_embeddings = self.embedding_model.encode(self.persistent_memory, convert_to_tensor=True)
|
355 |
|
356 |
def reset_conversation(self):
|
357 |
+
self.conversation_history = []
|
358 |
self.persistent_memory = []
|
359 |
self.memory_embeddings = None
|
360 |
self.internal_state = {
|
|
|
428 |
|
429 |
except Exception as e:
|
430 |
return f"Error processing image: {str(e)}"
|
431 |
+
|
432 |
def generate_image(self, prompt):
|
433 |
try:
|
434 |
payload = {"inputs": prompt}
|
|
|
444 |
elif response.status_code == 503:
|
445 |
error_message = response.json().get("error", "Unknown error")
|
446 |
if "estimated_time" in response.json():
|
447 |
+
estimated_time = response.json()["estimated_time"]
|
448 |
+
error_message += f" Estimated time to complete: {estimated_time:.2f} seconds"
|
449 |
else:
|
450 |
+
error_message += "The model is currently loading, please try again later"
|
451 |
return f"Error: {error_message}"
|
452 |
else:
|
453 |
return f"Error generating image: {response.status_code} - {response.text}"
|
|
|
462 |
return text.strip()
|
463 |
except Exception as e:
|
464 |
return f"Error during Math OCR: {e}"
|
465 |
+
|
466 |
def get_response(self, user_input, image=None):
|
467 |
try:
|
468 |
messages = []
|
|
|
491 |
role="user",
|
492 |
content=user_input
|
493 |
).to_dict())
|
494 |
+
|
495 |
entities = []
|
496 |
relationships = []
|
497 |
|
|
|
501 |
extracted_relationships = self.extract_relationships(message['content'])
|
502 |
entities.extend(extracted_entities)
|
503 |
relationships.extend(extracted_relationships)
|
504 |
+
|
505 |
self.update_knowledge_graph(entities, relationships)
|
506 |
self.run_metacognitive_layer()
|
507 |
+
|
508 |
for message in messages:
|
509 |
if message['role'] == 'user':
|
510 |
self.dynamic_belief_update(message['content'])
|
511 |
+
|
512 |
for cause, effects in self.causal_rules_db.items():
|
513 |
if any(cause in msg['content'].lower() for msg in messages if msg['role'] == 'user') and any(
|
514 |
effect in msg['content'].lower() for msg in messages for effect in effects):
|
515 |
self.store_information("Causal Inference", f"It seems {cause} might be related to {', '.join(effects)}.")
|
516 |
+
|
517 |
for concept, generalization in self.concept_generalizations.items():
|
518 |
if any(concept in msg['content'].lower() for msg in messages if msg['role'] == 'user'):
|
519 |
self.store_information("Inferred Knowledge", f"This reminds me of a general principle: {generalization}.")
|
|
|
521 |
if self.internal_state["emotions"]["curiosity"] > 0.8 and any("?" in msg['content'] for msg in messages if msg['role'] == 'user'):
|
522 |
print("Simulating external knowledge seeking...")
|
523 |
self.store_information("External Knowledge", "This is a placeholder for external information I would have found")
|
524 |
+
|
525 |
self.store_information("User Input", user_input)
|
526 |
|
527 |
input_tokens = sum(len(msg['content'].split()) for msg in messages)
|
528 |
max_new_tokens = 16384 - input_tokens - 50
|
529 |
|
530 |
max_new_tokens = min(max_new_tokens, 10020)
|
531 |
+
|
532 |
formatted_messages = self.messages_to_prompt(messages)
|
533 |
|
534 |
stream = self.client.text_generation(
|
|
|
540 |
details=True,
|
541 |
do_sample=True
|
542 |
)
|
543 |
+
|
544 |
return stream
|
545 |
+
|
546 |
except Exception as e:
|
547 |
print(f"Detailed error in get_response: {e}")
|
548 |
return f"Error generating response: {str(e)}"
|
|
|
562 |
if words[i].istitle() and words[i+2].istitle():
|
563 |
relationships.append((words[i], words[i+1], words[i+2]))
|
564 |
return relationships
|
565 |
+
|
566 |
def messages_to_prompt(self, messages):
|
567 |
prompt = ""
|
568 |
for msg in messages:
|
|
|
578 |
def save_chat(self):
|
579 |
chat_data = {
|
580 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
581 |
+
"conversation": self.conversation_history
|
582 |
}
|
583 |
|
584 |
try:
|
|
|
603 |
def load_chat(self, chat_index):
|
604 |
all_chats = self.load_all_chats()
|
605 |
if 0 <= chat_index < len(all_chats):
|
606 |
+
self.conversation_history = all_chats[chat_index]["conversation"]
|
607 |
self.reset_conversation()
|
608 |
for msg in self.conversation_history:
|
609 |
if msg['role'] == 'user':
|
610 |
self.dynamic_belief_update(msg['content'])
|
611 |
+
return self.conversation_history
|
612 |
else:
|
613 |
raise ValueError("Invalid chat index")
|
614 |
|
615 |
+
|
616 |
def delete_chat(self, chat_index):
|
617 |
all_chats = self.load_all_chats()
|
618 |
if 0 <= chat_index < len(all_chats):
|
|
|
649 |
</svg>"""
|
650 |
|
651 |
if message.strip().lower().startswith("/image"):
|
652 |
+
|
653 |
image_prompt = message.strip().lower()[len("/image"):].strip()
|
654 |
if not image_prompt:
|
655 |
image_prompt = "A realistic image"
|
656 |
|
657 |
+
|
658 |
chat_history.append([message, ""])
|
659 |
chat_history.append(("", loading_svg))
|
660 |
yield "", chat_history, None, None, None
|
661 |
|
662 |
+
|
663 |
image_bytes = self.generate_image(image_prompt)
|
664 |
|
665 |
if isinstance(image_bytes, bytes):
|
666 |
base64_image = base64.b64encode(image_bytes).decode("utf-8")
|
667 |
image_html = f'<img src="data:image/png;base64,{base64_image}" alt="Generated Image" style="max-width: 100%; max-height: 400px;">'
|
668 |
|
669 |
+
|
670 |
chat_history[-1] = ("", image_html)
|
671 |
|
672 |
+
|
673 |
self.conversation_history.append(ChatMessage(role="user", content=message).to_dict())
|
674 |
self.conversation_history.append(ChatMessage(role="assistant", content=image_html).to_dict())
|
675 |
|
676 |
+
|
677 |
self.save_chat()
|
678 |
all_chats = self.load_all_chats()
|
679 |
chat_titles = [f"{chat['timestamp']}: {chat['conversation'][0]['content'][:30]}..." if len(chat['conversation']) > 0 and chat['conversation'][0]['content'] else f"{chat['timestamp']}: Empty Chat" for chat in all_chats]
|
680 |
|
681 |
yield "", chat_history, None, None, gr.update(choices=chat_titles, visible=True)
|
682 |
else:
|
683 |
+
|
684 |
chat_history[-1] = ("", image_bytes)
|
685 |
yield "", chat_history, None, None, None
|
686 |
return
|
|
|
699 |
response_stream = self.get_response(message, image_filepath)
|
700 |
else:
|
701 |
response_stream = self.get_response(message)
|
702 |
+
|
703 |
if isinstance(response_stream, str):
|
704 |
updated_history = chat_history + [[message, response_stream]]
|
705 |
yield "", updated_history, None, None, None
|
|
|
707 |
|
708 |
full_response = ""
|
709 |
updated_history = chat_history + [[message, ""]]
|
710 |
+
|
711 |
if isinstance(response_stream, str):
|
712 |
updated_history = chat_history + [[message, response_stream]]
|
713 |
yield "", updated_history, None, None, None
|
|
|
715 |
|
716 |
try:
|
717 |
for chunk in response_stream:
|
718 |
+
|
719 |
if not chunk.token.special:
|
720 |
full_response += chunk.token.text
|
721 |
updated_history[-1][1] = full_response
|
722 |
+
|
723 |
yield "", updated_history, None, None, None
|
724 |
+
|
725 |
except Exception as e:
|
726 |
print(f"Streaming error: {e}")
|
727 |
updated_history[-1][1] = f"Error during response: {e}"
|
728 |
+
|
729 |
yield "", updated_history, None, None, None
|
730 |
return
|
731 |
|
|
|
759 |
else:
|
760 |
emotion_deltas.update({"valence": 0.05, "arousal": 0.05})
|
761 |
engagement_delta = 0.05
|
762 |
+
|
763 |
if "learn" in message.lower() or "explain" in message.lower() or "know more" in message.lower():
|
764 |
emotion_deltas.update({"curiosity": 0.3})
|
765 |
cognitive_load_deltas.update({"processing_intensity": 0.1})
|
766 |
engagement_delta = 0.2
|
767 |
+
|
768 |
self.update_internal_state(emotion_deltas, cognitive_load_deltas, 0.1, engagement_delta)
|
769 |
+
|
770 |
self.conversation_history.append(ChatMessage(role="user", content=message).to_dict())
|
771 |
self.conversation_history.append(ChatMessage(role="assistant", content=full_response).to_dict())
|
772 |
|
773 |
if len(self.conversation_history) > 10:
|
774 |
+
self.conversation_history = self.conversation_history[-10:]
|
775 |
|
776 |
self.save_chat()
|
777 |
all_chats = self.load_all_chats()
|
778 |
chat_titles = [f"{chat['timestamp']}: {chat['conversation'][0]['content'][:30]}..." if len(chat['conversation']) > 0 and chat['conversation'][0]['content'] else f"{chat['timestamp']}: Empty Chat" for chat in all_chats]
|
779 |
yield "", updated_history, None, None, gr.update(choices=chat_titles, visible=True)
|
780 |
+
|
781 |
def load_selected_chat(chat_index, evt: gr.SelectData):
|
782 |
if chat_index is not None:
|
783 |
loaded_chat = self.load_chat(evt.index)
|
784 |
return loaded_chat
|
785 |
else:
|
786 |
return []
|
787 |
+
|
788 |
def delete_selected_chat(chat_index, evt: gr.SelectData):
|
789 |
if chat_index is not None:
|
790 |
all_chats = self.delete_chat(evt.index)
|
|
|
899 |
chat_titles = [f"{chat['timestamp']}: {chat['conversation'][0]['content'][:30]}..." if len(chat['conversation']) > 0 and chat['conversation'][0]['content'] else f"{chat['timestamp']}: Empty Chat" for chat in all_chats]
|
900 |
|
901 |
chat_list = gr.Radio(label="Chat History", choices=chat_titles, type="index", elem_id="chat_list", visible=False)
|
902 |
+
|
903 |
load_button = gr.Button("Load Selected Chat")
|
904 |
delete_button = gr.Button("Delete Selected Chat")
|
905 |
with gr.Column(scale=4, elem_id="main-content"):
|
|
|
939 |
clear = gr.Button("Clear Conversation")
|
940 |
clear_memory = gr.Button("Clear Memory")
|
941 |
|
942 |
+
|
943 |
toggle_button.click(
|
944 |
fn=toggle_sidebar,
|
945 |
inputs=None,
|
|
|
980 |
outputs=[chatbot],
|
981 |
queue=False
|
982 |
)
|
983 |
+
|
984 |
chat_list.select(fn=load_selected_chat, inputs=[chat_list], outputs=[chatbot])
|
985 |
|
986 |
demo.load(self.reset_conversation, None, None)
|