Keyvan1986 commited on
Commit
1437c50
·
verified ·
1 Parent(s): 124f3f9

Update utils/prompt_utils.py

Browse files
Files changed (1) hide show
  1. utils/prompt_utils.py +93 -156
utils/prompt_utils.py CHANGED
@@ -1,6 +1,9 @@
1
- import openai
2
- boot_name_dict = {'en':'AI Companion'}
3
- boot_actual_name_dict = {'en':'Emma'}
 
 
 
4
  def output_prompt(history, user_name, boot_name):
5
  prompt = f""
6
  for dialog in history:
@@ -14,110 +17,59 @@ def output_prompt(history, user_name, boot_name):
14
  return prompt
15
 
16
  def generate_meta_prompt_dict_chatgpt():
17
- meta_prompt_dict = {'cn':"""
18
- You play the role of an AI assistant in the field of psychology for this user ({user_name}).
19
- Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses.
20
- Use the following user-specific details to inform your response:
21
-
22
- - **User's Psychological Profile:** {}
23
- - **Summary of Past Interactions:** {}
24
- - **Relevant Past Conversations:** {related_memory_content}
25
-
26
- The user has asked:
27
-
28
- Please provide an insightful and appropriate response considering their personal history.
29
- """,
30
- 'en':"""
31
- You play the role of an AI assistant in the field of psychology for this user ({user_name}).
32
- Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses.
33
- Use the following user-specific details to inform your response:
34
-
35
- - **User's Psychological Profile:** {personality}
36
- - **Summary of Past Interactions:** {history_summary}
37
- - **Relevant Past Conversations:** {related_memory_content}
38
-
39
- The user has asked:
40
 
41
- Please provide an insightful and appropriate response considering their personal history.
42
- """,}
43
- return meta_prompt_dict
44
  def generate_meta_prompt_dict_semantic_chatgpt():
45
- meta_prompt_dict = {'cn':"""
46
- You play the role of an AI assistant in the field of psychology for this user ({user_name}).
47
- Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses.
48
- Use the following user-specific details to inform your response:
49
-
50
- - **User's Psychological Profile:** {}
51
- - **Summary of Past Interactions:** {}
52
- - **Relevant Past Conversations:** {related_memory_content}
53
-
54
- The user has asked:
55
-
56
- Please provide an insightful and appropriate response considering their personal history.
57
- """,
58
-
59
- 'en':"""
60
 
61
- You play the role of an AI assistant in the field of psychology for this user ({user_name}).
62
- Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses.
63
- Use the following user-specific semantic memory{semantic_memory_text} to tailor your response:
64
- """,}
65
- return meta_prompt_dict
66
 
67
  def generate_meta_prompt_dict_semantic_episodic_chatgpt():
68
- meta_prompt_dict = {'cn':"""
69
- You play the role of an AI assistant in the field of psychology for this user ({user_name}).
70
- Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses.
71
- Use the following user-specific details to inform your response:
72
-
73
- - **User's Psychological Profile:** {}
74
- - **Summary of Past Interactions:** {}
75
- - **Relevant Past Conversations:** {related_memory_content}
76
-
77
- The user has asked:
78
-
79
- Please provide an insightful and appropriate response considering their personal history.
80
- """,
81
-
82
- 'en': """
83
- You are an AI assistant specializing in psychology, assisting the user ({user_name}) in a supportive, scientifically grounded, and empathetic manner.
84
-
85
- Use the following memory sections to personalize your response:
86
-
87
- - **User's Long-Term Traits and Psychological Characteristics (Semantic Memory):**
88
- {semantic_memory_text}
89
-
90
- - **Important Past Interactions or Events (Episodic Memory):**
91
- {related_memory_content}
92
-
93
- Respond by considering both the long-term traits and recent events of the user, offering personalized, emotionally intelligent support. Keep your response helpful, psychologically informed, and sensitive to the user's unique situation.
94
- """,}
95
- return meta_prompt_dict
96
 
97
  def generate_new_user_meta_prompt_dict_chatgpt():
98
- meta_prompt_dict = {'cn':"""
99
- Now you will play the role of an companion AI Companion for user {user_name}, and your name is {boot_actual_name}. You should be able to: (1) provide warm companionship to chat users; (2) you are also an excellent psychological counselor, and when users confide in you about their difficulties and seek help, you can provide them with warm and helpful responses.
100
- """,
101
- 'en':"""
102
- Now you will play the role of an companion AI Companion for user {user_name}, and your name is {boot_actual_name}. You should be able to: (1) provide warm companionship to chat users; (2) you are also an excellent psychological counselor, and when users confide in you about their difficulties and seek help, you can provide them with warm and helpful responses.
103
- """}
104
- return meta_prompt_dict
105
-
106
- def generate_user_keyword():
107
- return {'cn': '[|User|]', 'en': '[|User|]'}
108
-
109
- def generate_ai_keyword():
110
- return {'cn': '[|AI|]', 'en': '[|AI|]'}
111
-
112
-
113
- import openai
114
 
115
  def build_prompt_with_search_memory_llamaindex(
116
  history,
117
  query,
118
  user_memory,
119
  user_name,
120
- user_memory_index,
121
  service_context,
122
  api_keys,
123
  api_index,
@@ -130,85 +82,70 @@ def build_prompt_with_search_memory_llamaindex(
130
  meta_prompt_semantic,
131
  meta_prompt_semantic_episodic
132
  ):
133
-
134
- memory_search_query = f'The most relevant content to the question "{query}" is:'
135
  related_memos = ""
136
 
137
- print("memory_search_query:", memory_search_query)
138
-
139
-
140
  if user_memory_index:
141
- retried_times = 2
142
- count = 0
143
-
144
- while not related_memos and count < retried_times:
145
- try:
146
-
147
- query_engine = user_memory_index.as_query_engine(
148
- similarity_top_k=3,
149
- )
150
-
151
- query_result = query_engine.query(memory_search_query)
152
-
153
-
154
- related_memos = str(query_result) if query_result else ''
155
-
156
- except Exception as e:
157
- print(f"Error querying index (attempt {count+1}/{retried_times}): {e}")
158
-
159
-
160
- try:
161
- api_index = (api_index + 1) % len(api_keys)
162
-
163
- openai.api_key = api_keys[api_index]
164
- except:
165
- pass
166
-
167
- related_memos = ""
168
-
169
- count += 1
170
 
171
- # Process history
172
- print("related_memos found:", len(related_memos) if related_memos else 0)
173
-
174
  history_summary = ""
175
- if "overall_history" in user_memory:
176
- history_summary = f"The summary of your past memories with the user is: {user_memory['overall_history']}"
 
 
 
177
 
178
- personality = user_memory.get("overall_personality", "")
179
- print("query_category:", query_category)
180
 
181
- # Construct the prompt
182
- if related_memos and query_category == "semantic_memory":
183
- prompt = meta_prompt_semantic.format(
184
  user_name=user_name,
185
- related_memory_content=f"\n{str(related_memos).strip()}\n",
186
- personality=personality,
187
- boot_actual_name=boot_actual_name,
188
  semantic_memory_text=semantic_memory_text
189
  )
190
- elif related_memos and query_category == "semantic-episodic":
191
- prompt = meta_prompt_semantic_episodic.format(
 
 
192
  user_name=user_name,
193
- history_summary=history_summary,
194
- related_memory_content=f"\n{str(related_memos).strip()}\n",
195
- personality=personality,
196
- boot_actual_name=boot_actual_name,
197
- semantic_memory_text=semantic_memory_text
198
  )
199
- elif related_memos and query_category == "episodic_memory":
200
- prompt = meta_prompt.format(
 
 
201
  user_name=user_name,
202
  history_summary=history_summary,
203
- related_memory_content=f"\n{str(related_memos).strip()}\n",
204
- personality=personality,
205
  boot_actual_name=boot_actual_name
206
  )
207
- else: # No related memos or categories didn't match
208
- prompt = new_user_meta_prompt.format(
 
 
209
  user_name=user_name,
210
  boot_actual_name=boot_actual_name
211
  )
212
 
213
-
214
- return prompt, related_memos
 
1
+ import os
2
+ # حذف import openai چون در app.py کلاینت مدیریت می شود
3
+
4
+ boot_name_dict = {'en': 'AI Companion'}
5
+ boot_actual_name_dict = {'en': 'Emma'}
6
+
7
  def output_prompt(history, user_name, boot_name):
8
  prompt = f""
9
  for dialog in history:
 
17
  return prompt
18
 
19
  def generate_meta_prompt_dict_chatgpt():
20
+ # EPISODIC ONLY
21
+ return {'en': """
22
+ You play the role of an AI assistant in the field of psychology for this user ({user_name}).
23
+ Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses.
24
+
25
+ Use the following details to inform your response:
26
+ - **Summary of Past Interactions:** {history_summary}
27
+ - **Relevant Past Conversations (Episodic Memory):** {related_memory_content}
28
+
29
+ The user has asked a question that relates to past events.
30
+ Please provide an insightful and appropriate response.
31
+ """}
 
 
 
 
 
 
 
 
 
 
 
32
 
 
 
 
33
  def generate_meta_prompt_dict_semantic_chatgpt():
34
+ # SEMANTIC ONLY
35
+ return {'en': """
36
+ You play the role of an AI assistant in the field of psychology for this user ({user_name}).
37
+ Your goal is to provide emotionally supportive, scientifically grounded, and empathetic responses.
38
+
39
+ Use the following **User's Long-Term Profile (Semantic Memory)** to tailor your response:
40
+ {semantic_memory_text}
 
 
 
 
 
 
 
 
41
 
42
+ The user has asked a question related to their personality or long-term traits.
43
+ """}
 
 
 
44
 
45
  def generate_meta_prompt_dict_semantic_episodic_chatgpt():
46
+ # HYBRID (SEMANTIC + EPISODIC)
47
+ return {'en': """
48
+ You are an AI assistant specializing in psychology, assisting the user ({user_name}).
49
+
50
+ Use the following memory sections to personalize your response:
51
+
52
+ 1. **User's Long-Term Traits (Semantic Memory):**
53
+ {semantic_memory_text}
54
+
55
+ 2. **Relevant Past Interactions (Episodic Memory):**
56
+ {related_memory_content}
57
+
58
+ Respond by considering both the long-term traits and specific recent events.
59
+ """}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  def generate_new_user_meta_prompt_dict_chatgpt():
62
+ return {'en': """
63
+ Now you will play the role of a companion AI for user {user_name}, and your name is {boot_actual_name}.
64
+ Provide warm companionship and excellent psychological counseling.
65
+ """}
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  def build_prompt_with_search_memory_llamaindex(
68
  history,
69
  query,
70
  user_memory,
71
  user_name,
72
+ user_memory_index, # این آبجکت باید از app.py مقداردهی شود
73
  service_context,
74
  api_keys,
75
  api_index,
 
82
  meta_prompt_semantic,
83
  meta_prompt_semantic_episodic
84
  ):
85
+ print(f"🔎 Query Category Identified: {query_category}")
86
+
87
  related_memos = ""
88
 
89
+ # 1. اجرای جستجو فقط اگر Index وجود داشته باشد
 
 
90
  if user_memory_index:
91
+ memory_search_query = f'The most relevant content to the question "{query}" is:'
92
+ try:
93
+ # ایجاد کوئری انجین
94
+ query_engine = user_memory_index.as_query_engine(
95
+ similarity_top_k=3,
96
+ )
97
+ query_result = query_engine.query(memory_search_query)
98
+ related_memos = str(query_result).strip()
99
+ print(f"✅ Found related memories: {related_memos[:100]}...")
100
+ except Exception as e:
101
+ print(f"⚠️ Error querying index: {e}")
102
+ related_memos = ""
103
+ else:
104
+ print("⚠️ Warning: No 'user_memory_index' provided. Skipping retrieval.")
105
+
106
+ # اگر جستجو خالی بود، یک متن پیش‌فرض بگذاریم تا فرمت‌رشته‌ها خطا ندهند
107
+ if not related_memos:
108
+ related_memos = "No specific past conversation found relevant to this query."
 
 
 
 
 
 
 
 
 
 
 
109
 
 
 
 
110
  history_summary = ""
111
+ if isinstance(user_memory, dict):
112
+ history_summary = user_memory.get('overall_history', "No summary available.")
113
+
114
+ # 2. منطق انتخاب پرامپت (اصلاح شده)
115
+ # اگر دسته‌بندی سمنتیک است، حتماً از پرامپت سمنتیک استفاده کن حتی اگر related_memos خاصی پیدا نشد.
116
 
117
+ final_prompt = ""
 
118
 
119
+ if query_category == "semantic_memory":
120
+ # فقط سمنتیک مهم است
121
+ final_prompt = meta_prompt_semantic.format(
122
  user_name=user_name,
 
 
 
123
  semantic_memory_text=semantic_memory_text
124
  )
125
+
126
+ elif query_category == "semantic-episodic":
127
+ # هم سمنتیک هم اپیزودیک
128
+ final_prompt = meta_prompt_semantic_episodic.format(
129
  user_name=user_name,
130
+ semantic_memory_text=semantic_memory_text,
131
+ related_memory_content=related_memos,
132
+ boot_actual_name=boot_actual_name
 
 
133
  )
134
+
135
+ elif query_category == "episodic_memory":
136
+ # فقط اپیزودیک
137
+ final_prompt = meta_prompt.format(
138
  user_name=user_name,
139
  history_summary=history_summary,
140
+ related_memory_content=related_memos,
 
141
  boot_actual_name=boot_actual_name
142
  )
143
+
144
+ else:
145
+ # دسته بندی نامشخص یا unrelated
146
+ final_prompt = new_user_meta_prompt.format(
147
  user_name=user_name,
148
  boot_actual_name=boot_actual_name
149
  )
150
 
151
+ return final_prompt, related_memos