Emma / utils /prompt_utils.py
Keyvan1986's picture
Update utils/prompt_utils.py
1437c50 verified
Raw
History Blame Contribute Delete
5.67 kB
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