File size: 5,671 Bytes
1437c50
 
 
 
 
 
4b8593c
 
 
 
 
 
 
 
 
 
 
 
 
1437c50
 
 
 
 
 
 
 
 
 
 
 
4b8593c
 
1437c50
 
 
 
 
 
 
4b8593c
1437c50
 
4b8593c
 
1437c50
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8593c
 
1437c50
 
 
 
4b8593c
 
 
 
 
 
1437c50
4b8593c
 
 
 
 
 
 
 
 
 
 
 
1437c50
 
4b8593c
 
1437c50
4b8593c
1437c50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8593c
 
1437c50
 
 
 
 
4b8593c
1437c50
4b8593c
1437c50
 
 
4b8593c
 
 
1437c50
 
 
 
4b8593c
1437c50
 
 
4b8593c
1437c50
 
 
 
4b8593c
 
1437c50
4b8593c
 
1437c50
 
 
 
4b8593c
 
 
 
1437c50
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
import os
# حذف import openai چون در app.py کلاینت مدیریت می شود

boot_name_dict = {'en': 'AI Companion'}
boot_actual_name_dict = {'en': 'Emma'}

def output_prompt(history, user_name, boot_name):
    prompt = f""
    for dialog in history:
        if isinstance(dialog, dict):
            query = dialog.get('query', '')
            response = dialog.get('response', '')
        else:
            query, response = dialog
        prompt += f"\n\n{user_name}{query}"
        prompt += f"\n\n{boot_name}{response}"
    return prompt

def generate_meta_prompt_dict_chatgpt():
    # EPISODIC ONLY
    return {'en': """
    You play the role of an AI assistant in the field of psychology for this user ({user_name}). 
    Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses. 
    
    Use the following details to inform your response:
    - **Summary of Past Interactions:** {history_summary}
    - **Relevant Past Conversations (Episodic Memory):** {related_memory_content} 
    
    The user has asked a question that relates to past events.
    Please provide an insightful and appropriate response.
    """}

def generate_meta_prompt_dict_semantic_chatgpt():
    # SEMANTIC ONLY
    return {'en': """
    You play the role of an AI assistant in the field of psychology for this user ({user_name}). 
    Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses. 
    
    Use the following **User's Long-Term Profile (Semantic Memory)** to tailor your response:
    {semantic_memory_text}
    
    The user has asked a question related to their personality or long-term traits.
    """}

def generate_meta_prompt_dict_semantic_episodic_chatgpt():
    # HYBRID (SEMANTIC + EPISODIC)
    return {'en': """
    You are an AI assistant specializing in psychology, assisting the user ({user_name}).
    
    Use the following memory sections to personalize your response:
    
    1. **User's Long-Term Traits (Semantic Memory):**
    {semantic_memory_text}
    
    2. **Relevant Past Interactions (Episodic Memory):**
    {related_memory_content}
    
    Respond by considering both the long-term traits and specific recent events.
    """}

def generate_new_user_meta_prompt_dict_chatgpt():
    return {'en': """
    Now you will play the role of a companion AI for user {user_name}, and your name is {boot_actual_name}. 
    Provide warm companionship and excellent psychological counseling.
    """}

def build_prompt_with_search_memory_llamaindex(
    history, 
    query,  
    user_memory, 
    user_name, 
    user_memory_index,  # این آبجکت باید از app.py مقداردهی شود
    service_context, 
    api_keys, 
    api_index, 
    meta_prompt, 
    new_user_meta_prompt, 
    data_args, 
    boot_actual_name,
    semantic_memory_text,
    query_category,
    meta_prompt_semantic,
    meta_prompt_semantic_episodic
):
    print(f"🔎 Query Category Identified: {query_category}")
    
    related_memos = ""
    
    # 1. اجرای جستجو فقط اگر Index وجود داشته باشد
    if user_memory_index:
        memory_search_query = f'The most relevant content to the question "{query}" is:'
        try:
            # ایجاد کوئری انجین
            query_engine = user_memory_index.as_query_engine(
                similarity_top_k=3,
            )
            query_result = query_engine.query(memory_search_query)
            related_memos = str(query_result).strip()
            print(f"✅ Found related memories: {related_memos[:100]}...")
        except Exception as e:
            print(f"⚠️ Error querying index: {e}")
            related_memos = ""
    else:
        print("⚠️ Warning: No 'user_memory_index' provided. Skipping retrieval.")

    # اگر جستجو خالی بود، یک متن پیش‌فرض بگذاریم تا فرمت‌رشته‌ها خطا ندهند
    if not related_memos:
        related_memos = "No specific past conversation found relevant to this query."

    history_summary = ""
    if isinstance(user_memory, dict):
        history_summary = user_memory.get('overall_history', "No summary available.")

    # 2. منطق انتخاب پرامپت (اصلاح شده)
    # اگر دسته‌بندی سمنتیک است، حتماً از پرامپت سمنتیک استفاده کن حتی اگر related_memos خاصی پیدا نشد.
    
    final_prompt = ""

    if query_category == "semantic_memory":
        # فقط سمنتیک مهم است
        final_prompt = meta_prompt_semantic.format(
            user_name=user_name,
            semantic_memory_text=semantic_memory_text
        )
        
    elif query_category == "semantic-episodic":
        # هم سمنتیک هم اپیزودیک
        final_prompt = meta_prompt_semantic_episodic.format(
            user_name=user_name,
            semantic_memory_text=semantic_memory_text,
            related_memory_content=related_memos,
            boot_actual_name=boot_actual_name
        )
        
    elif query_category == "episodic_memory":
        # فقط اپیزودیک
        final_prompt = meta_prompt.format(
            user_name=user_name,
            history_summary=history_summary,
            related_memory_content=related_memos,
            boot_actual_name=boot_actual_name
        )
        
    else:
        # دسته بندی نامشخص یا unrelated
        final_prompt = new_user_meta_prompt.format(
            user_name=user_name,
            boot_actual_name=boot_actual_name
        )
    
    return final_prompt, related_memos