File size: 49,877 Bytes
db37698 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 |
# smart_context.py
import os
import json
import logging
import asyncio
import hashlib
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional, Tuple, Set
from collections import defaultdict, deque
import pickle
from dataclasses import dataclass, field
from enum import Enum
import re
import heapq
# برای embeddings (در صورت نبود کتابخانه، از روش جایگزین استفاده میشود)
try:
from sentence_transformers import SentenceTransformer
HAS_SBERT = True
except ImportError:
HAS_SBERT = False
from sklearn.feature_extraction.text import TfidfVectorizer
import warnings
warnings.filterwarnings("ignore")
# وارد کردن مدیر دادهها
import data_manager
logger = logging.getLogger(__name__)
# ==================== ENUMS و DataClasses ====================
class MemoryPriority(Enum):
"""اولویت حافظه"""
LOW = 1
MEDIUM = 2
HIGH = 3
CRITICAL = 4
class MessageType(Enum):
"""نوع پیام"""
FACT = "fact"
PREFERENCE = "preference"
EMOTION = "emotion"
QUESTION = "question"
ANSWER = "answer"
DECISION = "decision"
ACTION = "action"
CHITCHAT = "chitchat"
class EmotionType(Enum):
"""نوع احساس"""
POSITIVE = "positive"
NEUTRAL = "neutral"
NEGATIVE = "negative"
EXCITED = "excited"
ANGRY = "angry"
CONFUSED = "confused"
@dataclass
class MessageNode:
"""گره پیام در گراف حافظه"""
id: str
content: str
role: str
timestamp: datetime
message_type: MessageType
importance_score: float = 0.5
emotion_score: Dict[EmotionType, float] = field(default_factory=dict)
tokens: int = 0
embeddings: Optional[np.ndarray] = None
metadata: Dict[str, Any] = field(default_factory=dict)
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
return self.id == other.id
@dataclass
class MemoryConnection:
"""اتصال بین پیامها در گراف حافظه"""
source_id: str
target_id: str
connection_type: str # 'semantic', 'temporal', 'causal', 'contextual'
strength: float = 1.0
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class UserProfile:
"""پروفایل کاربر"""
user_id: int
personality_traits: Dict[str, float] = field(default_factory=dict)
interests: Set[str] = field(default_factory=set)
preferences: Dict[str, Any] = field(default_factory=dict)
conversation_style: str = "balanced"
knowledge_level: Dict[str, float] = field(default_factory=dict)
emotional_patterns: Dict[str, List[float]] = field(default_factory=dict)
learning_style: Optional[str] = None
def update_from_message(self, message: str, analysis: Dict[str, Any]):
"""بهروزرسانی پروفایل بر اساس پیام جدید"""
if 'personality_clues' in analysis:
for trait, score in analysis['personality_clues'].items():
current = self.personality_traits.get(trait, 0.5)
self.personality_traits[trait] = 0.7 * current + 0.3 * score
if 'interests' in analysis:
self.interests.update(analysis['interests'])
if 'preferences' in analysis:
self.preferences.update(analysis['preferences'])
# ==================== کلاس Embedding Manager ====================
class EmbeddingManager:
"""مدیریت embeddings برای جستجوی معنایی"""
def __init__(self, model_name: str = None):
self.model = None
self.vectorizer = None
self.use_sbert = HAS_SBERT
if self.use_sbert:
try:
self.model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
logger.info("Loaded multilingual sentence transformer")
except Exception as e:
logger.warning(f"Failed to load sentence transformer: {e}")
self.use_sbert = False
if not self.use_sbert:
try:
from sklearn.feature_extraction.text import TfidfVectorizer
self.vectorizer = TfidfVectorizer(max_features=1000)
logger.info("Using TF-IDF for embeddings")
except ImportError:
logger.warning("scikit-learn not available, using simple word vectors")
self.vectorizer = None
def get_embedding(self, text: str) -> np.ndarray:
"""دریافت embedding برای متن"""
if self.use_sbert and self.model:
return self.model.encode([text])[0]
elif self.vectorizer:
# برای TF-IDF نیاز به fit داریم، فقط بردار ساده برمیگردانیم
words = text.lower().split()
unique_words = list(set(words))
embedding = np.zeros(100)
for i, word in enumerate(unique_words[:100]):
embedding[i] = hash(word) % 100 / 100.0
return embedding
else:
# روش سادهتر
text_lower = text.lower()
embedding = np.zeros(50)
# وزن بر اساس طول و محتوا
embedding[0] = len(text) / 1000.0
embedding[1] = text.count('؟') / 5.0
embedding[2] = text.count('!') / 5.0
# ویژگیهای ساده
embedding[3] = 1.0 if 'چه' in text_lower else 0.0
embedding[4] = 1.0 if 'چرا' in text_lower else 0.0
embedding[5] = 1.0 if 'چگونه' in text_lower else 0.0
return embedding
def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
"""محاسبه cosine similarity"""
norm1 = np.linalg.norm(vec1)
norm2 = np.linalg.norm(vec2)
if norm1 == 0 or norm2 == 0:
return 0.0
return np.dot(vec1, vec2) / (norm1 * norm2)
# ==================== کلاس Memory Graph ====================
class MemoryGraph:
"""گراف حافظه برای ذخیره و بازیابی ارتباطات"""
def __init__(self):
self.nodes: Dict[str, MessageNode] = {}
self.connections: List[MemoryConnection] = []
self.adjacency: Dict[str, List[MemoryConnection]] = defaultdict(list)
self.topic_clusters: Dict[str, Set[str]] = defaultdict(set)
self.time_index: List[Tuple[datetime, str]] = []
def add_node(self, node: MessageNode):
"""افزودن گره جدید"""
self.nodes[node.id] = node
self.time_index.append((node.timestamp, node.id))
self.time_index.sort(key=lambda x: x[0])
def add_connection(self, connection: MemoryConnection):
"""افزودن اتصال جدید"""
self.connections.append(connection)
self.adjacency[connection.source_id].append(connection)
def find_similar_nodes(self, query_embedding: np.ndarray,
threshold: float = 0.7,
max_results: int = 5) -> List[Tuple[str, float]]:
"""یافتن گرههای مشابه"""
similarities = []
for node_id, node in self.nodes.items():
if node.embeddings is not None:
similarity = self._cosine_similarity(query_embedding, node.embeddings)
if similarity > threshold:
similarities.append((node_id, similarity))
similarities.sort(key=lambda x: x[1], reverse=True)
return similarities[:max_results]
def get_temporal_neighbors(self, node_id: str,
time_window: timedelta = timedelta(hours=24)) -> List[str]:
"""یافتن همسایههای زمانی"""
if node_id not in self.nodes:
return []
node_time = self.nodes[node_id].timestamp
neighbors = []
for timestamp, nid in self.time_index:
if nid != node_id and abs(timestamp - node_time) <= time_window:
neighbors.append(nid)
return neighbors
def get_semantic_cluster(self, node_id: str, min_similarity: float = 0.6) -> Set[str]:
"""دریافت خوشه معنایی یک گره"""
cluster = {node_id}
if node_id not in self.nodes or self.nodes[node_id].embeddings is None:
return cluster
query_embedding = self.nodes[node_id].embeddings
for other_id, other_node in self.nodes.items():
if other_id != node_id and other_node.embeddings is not None:
similarity = self._cosine_similarity(query_embedding, other_node.embeddings)
if similarity > min_similarity:
cluster.add(other_id)
return cluster
def _cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
"""محاسبه cosine similarity"""
norm1 = np.linalg.norm(vec1)
norm2 = np.linalg.norm(vec2)
if norm1 == 0 or norm2 == 0:
return 0.0
return np.dot(vec1, vec2) / (norm1 * norm2)
# ==================== کلاس Context Analyzer ====================
class ContextAnalyzer:
"""آنالیزور هوشمند context"""
def __init__(self):
self.keyword_patterns = {
'name': [r'نام\s+من\s+(.*?)(?:است|میباشد)', r'اسم\s+من\s+(.*?)'],
'age': [r'سن\s+من\s+(\d+)', r'(\d+)\s+سالمه'],
'location': [r'اهل\s+(.*?)\s+هستم', r'در\s+(.*?)\s+زندگی میکنم'],
'preference': [r'دوست\s+دارم\s+(.*?)', r'علاقه\s+دارم\s+(.*?)', r'ترجیح\s+میدهم\s+(.*?)'],
'dislike': [r'دوست\s+ندارم\s+(.*?)', r'مخالف\s+(.*?)\s+هستم'],
'goal': [r'میخواهم\s+(.*?)', r'هدف\s+من\s+(.*?)\s+است'],
'question': [r'(چرا|چگونه|چه|کجا|کی|آیا)\s+.*?\?'],
'decision': [r'تصمیم\s+گرفتم\s+(.*?)', r'قصد\s+دارم\s+(.*?)'],
'emotion': [r'احساس\s+(.*?)\s+دارم', r'(خوشحالم|ناراحتم|عصبانیام|خستهام)']
}
self.emotion_keywords = {
EmotionType.POSITIVE: ['خوب', 'عالی', 'خوشحال', 'عالی', 'ممنون', 'مرسی', 'دوست دارم', 'عالیه'],
EmotionType.NEGATIVE: ['بد', 'بدی', 'ناراحت', 'غمگین', 'عصبانی', 'مشکل', 'خطا', 'اشتباه'],
EmotionType.EXCITED: ['هیجانزده', 'هیجان', 'جالب', 'شگفتانگیز', 'عالی', 'وای'],
EmotionType.ANGRY: ['عصبانی', 'خشمگین', 'ناراحت', 'اعصاب', 'دیوانه'],
EmotionType.CONFUSED: ['سردرگم', 'گیج', 'نمیفهمم', 'مشکل دارم', 'کمک']
}
def analyze_message(self, text: str, role: str) -> Dict[str, Any]:
"""آنالیز پیام و استخراج اطلاعات"""
analysis = {
'type': self._detect_message_type(text, role),
'entities': self._extract_entities(text),
'keywords': self._extract_keywords(text),
'emotion': self._analyze_emotion(text),
'importance': self._calculate_importance(text, role),
'topics': self._extract_topics(text),
'intent': self._detect_intent(text),
'complexity': self._calculate_complexity(text),
'has_personal_info': False,
'personal_info': {}
}
# استخراج اطلاعات شخصی
personal_info = self._extract_personal_info(text)
if personal_info:
analysis['has_personal_info'] = True
analysis['personal_info'] = personal_info
# استخراج ترجیحات
preferences = self._extract_preferences(text)
if preferences:
analysis['preferences'] = preferences
return analysis
def _detect_message_type(self, text: str, role: str) -> MessageType:
"""تشخیص نوع پیام"""
text_lower = text.lower()
if role == 'user':
if any(q in text_lower for q in ['؟', '?', 'چرا', 'چگونه', 'چه', 'کجا']):
return MessageType.QUESTION
elif any(e in text_lower for e in ['احساس', 'حالم', 'خوشحالم', 'ناراحتم']):
return MessageType.EMOTION
elif any(d in text_lower for d in ['تصمیم', 'قصد', 'میخواهم']):
return MessageType.DECISION
elif any(p in text_lower for p in ['دوست دارم', 'علاقه', 'ترجیح']):
return MessageType.PREFERENCE
else:
return MessageType.FACT
else:
if '؟' in text_lower:
return MessageType.QUESTION
elif any(a in text_lower for a in ['پاسخ', 'جواب', 'راه حل']):
return MessageType.ANSWER
else:
return MessageType.FACT
def _extract_entities(self, text: str) -> List[str]:
"""استخراج موجودیتها"""
entities = []
# الگوهای ساده برای اسامی
name_patterns = [
r'نام\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
r'اسم\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)',
]
for pattern in name_patterns:
matches = re.findall(pattern, text)
entities.extend(matches)
return entities
def _extract_keywords(self, text: str) -> List[str]:
"""استخراج کلمات کلیدی"""
# حذف کلمات توقف فارسی
stopwords = {'و', 'در', 'با', 'به', 'از', 'که', 'این', 'آن', 'را', 'برای', 'اما', 'یا'}
words = re.findall(r'\b[\wآ-ی]+\b', text.lower())
keywords = [w for w in words if w not in stopwords and len(w) > 2]
return list(set(keywords))[:10]
def _analyze_emotion(self, text: str) -> Dict[EmotionType, float]:
"""تحلیل احساسات متن"""
emotion_scores = {e: 0.0 for e in EmotionType}
text_lower = text.lower()
for emotion_type, keywords in self.emotion_keywords.items():
score = 0.0
for keyword in keywords:
if keyword in text_lower:
score += 1.0
emotion_scores[emotion_type] = min(score / 3.0, 1.0)
# تشخیص احساس کلی
if sum(emotion_scores.values()) == 0:
emotion_scores[EmotionType.NEUTRAL] = 1.0
return emotion_scores
def _calculate_importance(self, text: str, role: str) -> float:
"""محاسبه اهمیت پیام"""
score = 0.0
# امتیاز بر اساس نقش
if role == 'user':
score += 0.3
# امتیاز بر اساس طول
length = len(text)
if length > 200:
score += 0.3
elif length > 100:
score += 0.2
elif length > 50:
score += 0.1
# امتیاز بر اساس سوال بودن
if '؟' in text or '?' in text:
score += 0.2
# امتیاز بر اساس کلمات کلیدی مهم
important_words = ['مهم', 'لطفا', 'فوری', 'ضروری', 'لازم', 'حتما']
for word in important_words:
if word in text.lower():
score += 0.2
break
# امتیاز بر اساس اطلاعات شخصی
if any(pattern in text for pattern in ['نام من', 'سن من', 'اهل']):
score += 0.3
return min(score, 1.0)
def _extract_topics(self, text: str) -> List[str]:
"""استخراج موضوعات"""
topics = []
# دستهبندی موضوعات بر اساس کلمات کلیدی
topic_categories = {
'ورزش': ['فوتبال', 'ورزش', 'تمرین', 'مسابقه', 'تیم'],
'تکنولوژی': ['کامپیوتر', 'برنامه', 'کد', 'پایتون', 'هوش مصنوعی'],
'هنر': ['فیلم', 'موسیقی', 'نقاشی', 'کتاب', 'خواننده'],
'علم': ['تحقیق', 'دانش', 'کشف', 'آزمایش', 'نظریه'],
'غذا': ['غذا', 'رستوران', 'پخت', 'خوراک', 'ناهار'],
'سفر': ['سفر', 'مسافرت', 'کشور', 'شهر', 'هتل'],
'سلامتی': ['سلامت', 'بیماری', 'درمان', 'دکتر', 'بیمارستان'],
'کاری': ['کار', 'شغل', 'شرکت', 'مصاحبه', 'پروژه'],
'تحصیل': ['درس', 'دانشگاه', 'مدرسه', 'آموزش', 'یادگیری'],
}
text_lower = text.lower()
for topic, keywords in topic_categories.items():
if any(keyword in text_lower for keyword in keywords):
topics.append(topic)
return topics[:3]
def _detect_intent(self, text: str) -> str:
"""تشخیص قصد کاربر"""
text_lower = text.lower()
if any(q in text_lower for q in ['چطور', 'چگونه', 'راهنمایی']):
return 'guidance'
elif any(q in text_lower for q in ['چه', 'اطلاعات', 'معرفی']):
return 'information'
elif any(q in text_lower for q in ['چرا', 'دلیل', 'علت']):
return 'explanation'
elif any(q in text_lower for q in ['کمک', 'راه حل', 'مشکل']):
return 'help'
elif any(q in text_lower for q in ['توصیه', 'پیشنهاد', 'نظر']):
return 'advice'
elif any(q in text_lower for q in ['بحث', 'بحث کنیم', 'نظرت']):
return 'discussion'
else:
return 'general'
def _calculate_complexity(self, text: str) -> float:
"""محاسبه پیچیدگی متن"""
# میانگین طول کلمات
words = text.split()
if not words:
return 0.0
avg_word_length = sum(len(w) for w in words) / len(words)
# تعداد جملات
sentences = re.split(r'[.!?]', text)
num_sentences = max(len(sentences), 1)
# نسبت کلمات منحصر به فرد
unique_words = len(set(words))
diversity = unique_words / len(words) if words else 0
complexity = (avg_word_length / 10.0 + diversity + min(len(words) / 50.0, 1.0)) / 3.0
return min(complexity, 1.0)
def _extract_personal_info(self, text: str) -> Dict[str, Any]:
"""استخراج اطلاعات شخصی"""
info = {}
for info_type, patterns in self.keyword_patterns.items():
for pattern in patterns:
matches = re.findall(pattern, text)
if matches:
info[info_type] = matches[0]
break
return info
def _extract_preferences(self, text: str) -> Dict[str, Any]:
"""استخراج ترجیحات"""
preferences = {}
text_lower = text.lower()
# ترجیحات ساده
if 'دوست دارم' in text_lower:
parts = text_lower.split('دوست دارم')
if len(parts) > 1:
preference = parts[1].split('.')[0].strip()
if preference:
preferences['likes'] = preferences.get('likes', []) + [preference]
if 'دوست ندارم' in text_lower:
parts = text_lower.split('دوست ندارم')
if len(parts) > 1:
preference = parts[1].split('.')[0].strip()
if preference:
preferences['dislikes'] = preferences.get('dislikes', []) + [preference]
return preferences
# ==================== کلاس Intelligent Context Manager ====================
class IntelligentContextManager:
"""مدیر هوشمند context"""
def __init__(self, user_id: int):
self.user_id = user_id
self.embedding_manager = EmbeddingManager()
self.analyzer = ContextAnalyzer()
self.memory_graph = MemoryGraph()
self.user_profile = UserProfile(user_id=user_id)
# لایههای حافظه
self.memory_layers = {
'ephemeral': deque(maxlen=20), # حافظه زودگذر (چند دقیقه)
'working': deque(maxlen=50), # حافظه فعال (مکالمه جاری)
'recent': deque(maxlen=100), # حافظه اخیر (چند روز)
'long_term': [], # حافظه بلندمدت (اهمیت بالا)
'core': [] # حافظه هسته (اطلاعات حیاتی)
}
# تنظیمات
self.max_working_tokens = 512
self.max_context_tokens = 2048
self.min_importance_threshold = 0.3
self.semantic_similarity_threshold = 0.7
# آمار
self.stats = {
'total_messages': 0,
'compressed_messages': 0,
'retrieved_memories': 0,
'profile_updates': 0,
'average_importance': 0.0
}
# بارگذاری دادههای ذخیره شده
self._load_saved_data()
def _load_saved_data(self):
"""بارگذاری دادههای ذخیره شده"""
try:
# بارگذاری از data_manager
user_data = data_manager.DATA['users'].get(str(self.user_id), {})
if 'smart_context' in user_data:
saved_data = user_data['smart_context']
# بارگذاری پروفایل کاربر
if 'profile' in saved_data:
self.user_profile = UserProfile(**saved_data['profile'])
# بارگذاری آمار
if 'stats' in saved_data:
self.stats.update(saved_data['stats'])
logger.info(f"Loaded smart context for user {self.user_id}")
except Exception as e:
logger.error(f"Error loading saved context data: {e}")
def _save_data(self):
"""ذخیره دادهها"""
try:
user_id_str = str(self.user_id)
if user_id_str not in data_manager.DATA['users']:
data_manager.DATA['users'][user_id_str] = {}
# ذخیره دادههای هوشمند
data_manager.DATA['users'][user_id_str]['smart_context'] = {
'profile': {
'user_id': self.user_profile.user_id,
'personality_traits': dict(self.user_profile.personality_traits),
'interests': list(self.user_profile.interests),
'preferences': dict(self.user_profile.preferences),
'conversation_style': self.user_profile.conversation_style,
'knowledge_level': dict(self.user_profile.knowledge_level),
'emotional_patterns': dict(self.user_profile.emotional_patterns),
'learning_style': self.user_profile.learning_style
},
'stats': self.stats,
'last_updated': datetime.now().isoformat()
}
data_manager.save_data()
except Exception as e:
logger.error(f"Error saving smart context data: {e}")
async def process_message(self, role: str, content: str) -> Dict[str, Any]:
"""پرداش کامل یک پیام جدید"""
start_time = datetime.now()
# 1. تحلیل پیام
analysis = self.analyzer.analyze_message(content, role)
# 2. ایجاد گره حافظه
message_id = self._generate_message_id(content)
# ایجاد embedding به صورت غیرهمزمان
embedding_task = asyncio.create_task(
self._get_embedding_async(content)
)
node = MessageNode(
id=message_id,
content=content,
role=role,
timestamp=datetime.now(),
message_type=analysis['type'],
importance_score=analysis['importance'],
emotion_score=analysis['emotion'],
tokens=data_manager.count_tokens(content),
embeddings=None, # موقتاً None
metadata={
'analysis': analysis,
'topics': analysis['topics'],
'intent': analysis['intent'],
'complexity': analysis['complexity']
}
)
# دریافت embedding (اگر موجود باشد)
try:
node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0)
except asyncio.TimeoutError:
logger.warning(f"Embedding generation timeout for message {message_id}")
node.embeddings = self.embedding_manager.get_embedding(content)
# 3. افزودن به حافظه و گراف
await asyncio.to_thread(self._add_to_memory_layers, node, analysis)
await asyncio.to_thread(self.memory_graph.add_node, node)
# 4. ایجاد ارتباطات
await asyncio.to_thread(self._create_memory_connections, node)
# 5. بهروزرسانی پروفایل کاربر
if role == 'user':
await asyncio.to_thread(self._update_user_profile, content, analysis)
# 6. بهینهسازی حافظه
await asyncio.to_thread(self._optimize_memory)
# 7. بهروزرسانی آمار
self.stats['total_messages'] += 1
self.stats['average_importance'] = (
self.stats['average_importance'] * (self.stats['total_messages'] - 1) +
analysis['importance']
) / self.stats['total_messages']
# 8. ذخیره دادهها
await asyncio.to_thread(self._save_data)
processing_time = (datetime.now() - start_time).total_seconds()
logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}")
return {
'node_id': message_id,
'analysis': analysis,
'processing_time': processing_time
}
async def _get_embedding_async(self, text: str) -> np.ndarray:
"""دریافت embedding به صورت async"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None,
self.embedding_manager.get_embedding,
text
)
def _generate_message_id(self, content: str) -> str:
"""تولید شناسه منحصر به فرد برای پیام"""
timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
content_hash = hashlib.md5(content.encode()).hexdigest()[:8]
return f"{self.user_id}_{timestamp}_{content_hash}"
def _add_to_memory_layers(self, node: MessageNode, analysis: Dict[str, Any]):
"""افزودن پیام به لایههای حافظه مناسب"""
# همیشه به حافظه زودگذر و فعال اضافه میشود
self.memory_layers['ephemeral'].append(node)
self.memory_layers['working'].append(node)
# بررسی برای حافظه اخیر
if analysis['importance'] > 0.2:
self.memory_layers['recent'].append(node)
# بررسی برای حافظه بلندمدت
if analysis['importance'] > self.min_importance_threshold:
self.memory_layers['long_term'].append(node)
# بررسی برای حافظه هسته (اطلاعات حیاتی)
if analysis.get('has_personal_info', False) or analysis['importance'] > 0.8:
core_entry = {
'node': node,
'info': analysis.get('personal_info', {}),
'timestamp': datetime.now()
}
self.memory_layers['core'].append(core_entry)
def _create_memory_connections(self, node: MessageNode):
"""ایجاد ارتباطات حافظه برای گره جدید"""
# اگر گرههای قبلی وجود دارند، ارتباط ایجاد کن
if len(self.memory_graph.nodes) > 1:
# ارتباط زمانی با آخرین گره
last_nodes = list(self.memory_graph.nodes.values())[-5:]
for last_node in last_nodes:
if last_node.id != node.id:
temporal_conn = MemoryConnection(
source_id=last_node.id,
target_id=node.id,
connection_type='temporal',
strength=0.8
)
self.memory_graph.add_connection(temporal_conn)
# ارتباط معنایی با گرههای مشابه
if node.embeddings is not None:
similar_nodes = self.memory_graph.find_similar_nodes(
node.embeddings,
threshold=self.semantic_similarity_threshold
)
for similar_id, similarity in similar_nodes:
semantic_conn = MemoryConnection(
source_id=node.id,
target_id=similar_id,
connection_type='semantic',
strength=similarity
)
self.memory_graph.add_connection(semantic_conn)
def _update_user_profile(self, content: str, analysis: Dict[str, Any]):
"""بهروزرسانی پروفایل کاربر"""
# بهروزرسانی علاقهمندیها
if 'topics' in analysis:
for topic in analysis['topics']:
self.user_profile.interests.add(topic)
# بهروزرسانی ترجیحات
if 'preferences' in analysis:
self.user_profile.preferences.update(analysis['preferences'])
# تشخیص سبک مکالمه
complexity = analysis.get('complexity', 0.5)
if complexity > 0.7:
self.user_profile.conversation_style = "detailed"
elif complexity < 0.3:
self.user_profile.conversation_style = "concise"
# بهروزرسانی الگوهای احساسی
emotion = analysis.get('emotion', {})
for emotion_type, score in emotion.items():
if score > 0.3:
emotion_name = emotion_type.value if hasattr(emotion_type, 'value') else str(emotion_type)
if emotion_name not in self.user_profile.emotional_patterns:
self.user_profile.emotional_patterns[emotion_name] = []
self.user_profile.emotional_patterns[emotion_name].append(score)
self.stats['profile_updates'] += 1
def _optimize_memory(self):
"""بهینهسازی و فشردهسازی حافظه"""
# فشردهسازی حافظه فعال اگر توکنها زیاد شد
working_tokens = sum(node.tokens for node in self.memory_layers['working'])
if working_tokens > self.max_working_tokens:
self._compress_working_memory()
self.stats['compressed_messages'] += 1
# پاکسازی حافظه زودگذر قدیمی
if len(self.memory_layers['ephemeral']) > 50:
self.memory_layers['ephemeral'].clear()
# مرتبسازی حافظه بلندمدت بر اساس اهمیت
self.memory_layers['long_term'].sort(key=lambda x: x.importance_score, reverse=True)
if len(self.memory_layers['long_term']) > 100:
self.memory_layers['long_term'] = self.memory_layers['long_term'][:100]
def _compress_working_memory(self):
"""فشردهسازی هوشمند حافظه فعال"""
if len(self.memory_layers['working']) <= 10:
return
working_memory = list(self.memory_layers['working'])
# 1. محاسبه امتیاز برای هر پیام
scored_messages = []
for i, node in enumerate(working_memory):
score = self._calculate_compression_score(node, i, len(working_memory))
scored_messages.append((score, node))
# 2. مرتبسازی بر اساس امتیاز
scored_messages.sort(key=lambda x: x[0], reverse=True)
# 3. انتخاب پیامهای برتر تا سقف توکن
compressed = []
total_tokens = 0
for score, node in scored_messages:
if total_tokens + node.tokens <= self.max_working_tokens:
compressed.append(node)
total_tokens += node.tokens
else:
break
# 4. مرتبسازی دوباره بر اساس زمان
compressed.sort(key=lambda x: x.timestamp)
# 5. جایگزینی حافظه فعال
self.memory_layers['working'] = deque(compressed, maxlen=50)
logger.info(f"Compressed working memory: {len(working_memory)} -> {len(compressed)} messages")
def _calculate_compression_score(self, node: MessageNode, index: int, total: int) -> float:
"""محاسبه امتیاز فشردهسازی برای یک پیام"""
score = 0.0
# 1. اهمیت پیام
score += node.importance_score * 0.4
# 2. تازگی (پیامهای جدیدتر مهمتر)
recency = (index / total) * 0.3
score += recency
# 3. تنوع اطلاعات (بر اساس topics)
topics = node.metadata.get('topics', [])
topic_diversity = min(len(topics) / 3.0, 0.2)
score += topic_diversity
# 4. نوع پیام
type_weights = {
MessageType.QUESTION: 0.2,
MessageType.PREFERENCE: 0.2,
MessageType.DECISION: 0.2,
MessageType.EMOTION: 0.1,
MessageType.FACT: 0.1,
MessageType.ANSWER: 0.1,
MessageType.ACTION: 0.2,
MessageType.CHITCHAT: 0.05
}
score += type_weights.get(node.message_type, 0.1)
# 5. اطلاعات شخصی
if 'has_personal_info' in node.metadata.get('analysis', {}):
if node.metadata['analysis']['has_personal_info']:
score += 0.2
return score
async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]:
"""بازیابی هوشمند context مرتبط با query"""
try:
if max_tokens is None:
max_tokens = self.max_context_tokens
start_time = datetime.now()
# دریافت embedding با timeout
try:
embedding_task = asyncio.create_task(
self._get_embedding_async(query)
)
query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0)
except asyncio.TimeoutError:
logger.warning(f"Embedding timeout for query: {query[:50]}")
query_embedding = self.embedding_manager.get_embedding(query)
# بازیابی از حافظههای مختلف به صورت موازی
tasks = []
# حافظه فعال
tasks.append(asyncio.create_task(
asyncio.to_thread(self._retrieve_from_working_memory)
))
# حافظه معنایی
tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent'))
tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term'))
# حافظه هسته
tasks.append(asyncio.create_task(
asyncio.to_thread(self._retrieve_core_memories, query)
))
# اجرای موازی همه tasks
results = await asyncio.gather(*tasks, return_exceptions=True)
# جمعآوری نتایج
retrieved_memories = []
for result in results:
if isinstance(result, Exception):
logger.error(f"Error retrieving memory: {result}")
continue
retrieved_memories.extend(result)
except Exception as e:
logger.error(f"Error in retrieve_context: {e}")
# Fallback: برگرداندن حافظه فعال
return self._retrieve_from_working_memory()
# 1. دریافت embedding برای query
query_embedding = self.embedding_manager.get_embedding(query)
# 2. بازیابی از لایههای مختلف حافظه
retrieved_memories = []
# از حافظه فعال (همیشه)
retrieved_memories.extend(self._retrieve_from_working_memory())
# از حافظه اخیر (بر اساس شباهت)
recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent')
retrieved_memories.extend(recent_memories)
# از حافظه بلندمدت (اطلاعات مهم)
long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term')
retrieved_memories.extend(long_term_memories)
# از حافظه هسته (اطلاعات حیاتی کاربر)
core_memories = self._retrieve_core_memories(query)
retrieved_memories.extend(core_memories)
# 3. حذف تکراریها و مرتبسازی
unique_memories = self._deduplicate_memories(retrieved_memories)
prioritized_memories = self._prioritize_memories(unique_memories, query_embedding)
# 4. انتخاب تا سقف توکن
final_context = []
total_tokens = 0
for memory in prioritized_memories:
memory_tokens = memory['node'].tokens if 'node' in memory else 50
if total_tokens + memory_tokens <= max_tokens:
final_context.append(memory)
total_tokens += memory_tokens
else:
break
# 5. بهروزرسانی آمار
self.stats['retrieved_memories'] += len(final_context)
retrieval_time = (datetime.now() - start_time).total_seconds()
logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s")
return final_context
def _retrieve_from_working_memory(self) -> List[Dict[str, Any]]:
"""بازیابی از حافظه فعال"""
memories = []
for node in list(self.memory_layers['working'])[-10:]: # 10 پیام آخر
memories.append({
'node': node,
'source': 'working',
'relevance': 1.0,
'recency': 1.0
})
return memories
async def _retrieve_semantic_memories(self, query_embedding: np.ndarray,
layer: str) -> List[Dict[str, Any]]:
"""بازیابی حافظههای معنایی"""
memories = []
if layer not in self.memory_layers:
return memories
layer_memories = self.memory_layers[layer]
for item in layer_memories:
node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None
if node and node.embeddings is not None:
similarity = self.embedding_manager.cosine_similarity(
query_embedding, node.embeddings
)
if similarity > self.semantic_similarity_threshold:
recency_weight = 1.0 if layer == 'working' else 0.7
memories.append({
'node': node,
'source': layer,
'relevance': similarity,
'recency': recency_weight,
'importance': node.importance_score
})
return memories
def _retrieve_core_memories(self, query: str) -> List[Dict[str, Any]]:
"""بازیابی حافظههای هسته"""
memories = []
query_lower = query.lower()
for core_entry in self.memory_layers['core']:
node = core_entry['node']
info = core_entry.get('info', {})
# بررسی تطابق با query
relevance = 0.0
# تطابق با اطلاعات شخصی
for key, value in info.items():
if isinstance(value, str) and value.lower() in query_lower:
relevance = 0.9
break
# تطابق با محتوای پیام
if relevance == 0.0 and node.content.lower() in query_lower:
relevance = 0.7
if relevance > 0.5:
memories.append({
'node': node,
'source': 'core',
'relevance': relevance,
'recency': 0.8,
'importance': 1.0,
'personal_info': info
})
return memories
def _deduplicate_memories(self, memories: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""حذف حافظههای تکراری"""
seen_ids = set()
unique_memories = []
for memory in memories:
node = memory.get('node')
if node and node.id not in seen_ids:
seen_ids.add(node.id)
unique_memories.append(memory)
return unique_memories
def _prioritize_memories(self, memories: List[Dict[str, Any]],
query_embedding: np.ndarray) -> List[Dict[str, Any]]:
"""اولویتبندی حافظههای بازیابی شده"""
def calculate_priority(memory: Dict[str, Any]) -> float:
"""محاسبه اولویت برای یک حافظه"""
priority = 0.0
# 1. ارتباط معنایی
priority += memory.get('relevance', 0.0) * 0.4
# 2. تازگی
priority += memory.get('recency', 0.0) * 0.3
# 3. اهمیت
priority += memory.get('importance', 0.5) * 0.2
# 4. منبع (حافظه هسته اولویت بالاتری دارد)
source = memory.get('source', '')
if source == 'core':
priority += 0.2
elif source == 'long_term':
priority += 0.1
return priority
# محاسبه اولویت و مرتبسازی
prioritized = []
for memory in memories:
priority = calculate_priority(memory)
prioritized.append((priority, memory))
prioritized.sort(key=lambda x: x[0], reverse=True)
return [memory for _, memory in prioritized]
async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]:
"""تهیه context برای ارسال به API"""
# اگر query داریم، context هوشمند بازیابی کن
if query:
retrieved = await self.retrieve_context(query)
# تبدیل به فرمت API
api_messages = []
# ابتدا اطلاعات پروفایل کاربر
api_messages.append({
'role': 'system',
'content': f"User profile: {self._format_user_profile()}"
})
# سپس حافظههای بازیابی شده
for memory in retrieved:
node = memory['node']
api_messages.append({
'role': node.role,
'content': node.content
})
return api_messages
else:
# حالت ساده: فقط حافظه فعال
api_messages = []
for node in list(self.memory_layers['working'])[-6:]:
api_messages.append({
'role': node.role,
'content': node.content
})
return api_messages
def _format_user_profile(self) -> str:
"""قالببندی پروفایل کاربر برای سیستم"""
profile_parts = []
if self.user_profile.interests:
interests_str = ', '.join(list(self.user_profile.interests)[:5])
profile_parts.append(f"Interests: {interests_str}")
if self.user_profile.preferences:
prefs = list(self.user_profile.preferences.items())[:3]
prefs_str = ', '.join(f"{k}: {v}" for k, v in prefs)
profile_parts.append(f"Preferences: {prefs_str}")
if self.user_profile.conversation_style:
profile_parts.append(f"Conversation style: {self.user_profile.conversation_style}")
if self.user_profile.learning_style:
profile_parts.append(f"Learning style: {self.user_profile.learning_style}")
if profile_parts:
return ' | '.join(profile_parts)
else:
return "New user, minimal profile information available."
def get_summary(self) -> Dict[str, Any]:
"""دریافت خلاصه وضعیت"""
return {
'user_id': self.user_id,
'total_messages': self.stats['total_messages'],
'working_memory': len(self.memory_layers['working']),
'recent_memory': len(self.memory_layers['recent']),
'long_term_memory': len(self.memory_layers['long_term']),
'core_memory': len(self.memory_layers['core']),
'profile_interests': list(self.user_profile.interests)[:10],
'average_importance': self.stats['average_importance'],
'compression_ratio': self.stats.get('compressed_messages', 0) / max(self.stats['total_messages'], 1),
'retrieval_efficiency': self.stats.get('retrieved_memories', 0) / max(self.stats['total_messages'], 1)
}
def clear_context(self):
"""پاک کردن context کاربر"""
self.memory_layers['working'].clear()
self.memory_layers['ephemeral'].clear()
# حافظه هسته و بلندمدت پاک نمیشوند
logger.info(f"Cleared context for user {self.user_id}")
def export_debug_info(self) -> Dict[str, Any]:
"""دریافت اطلاعات دیباگ"""
return {
'memory_graph_size': len(self.memory_graph.nodes),
'memory_graph_connections': len(self.memory_graph.connections),
'user_profile': {
'interests_count': len(self.user_profile.interests),
'preferences_count': len(self.user_profile.preferences),
'personality_traits': dict(self.user_profile.personality_traits)
},
'layer_sizes': {k: len(v) for k, v in self.memory_layers.items()},
'stats': dict(self.stats)
} |