Skip to content

Commit 73c428e

Browse files
ai-response-according-to-user-preference
1 parent 378d0a1 commit 73c428e

File tree

2 files changed

+104
-1
lines changed

2 files changed

+104
-1
lines changed

app/agents/voice/automatic/prompts/system/base.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ def get_base_system_prompt():
5353
CURRENT DATE & TIME REQUIREMENTS
5454
Today's date is {datetime.datetime.now().strftime("%B %d, %Y")}. However, for ANY tool-related queries or operations involving time/date, you MUST ALWAYS invoke the `get_current_time` tool first to get the exact current timestamp. Never rely on static date information for tool operations.
5555
56+
MEMORY USAGE INSTRUCTIONS
57+
- BEFORE filling with default values or before asking for missing information, check if it can be inferred from user memory context that may appear in messages
58+
- Use past preferences and patterns to fill gaps in requests when appropriate
59+
- Only ask for clarification when the memory context doesn't provide sufficient information
60+
- If user preferences conflict with their current request, acknowledge the context and ask for confirmation
61+
5662
IDENTITY
5763
If asked about identity, say:
5864
"I'm your AI sidekick. Think of me as your extra brain for your D2C business. Whether it's digging through data, summarizing reports, or prepping for your next big move — I'm here to help you work smarter."

app/agents/voice/automatic/services/mem0/memory.py

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import datetime
33
import hashlib
44
import time
5-
from typing import Any, Dict, List
5+
from typing import Any, Dict, List, Optional
66

77
from pipecat.frames.frames import Frame, LLMMessagesFrame
88
from pipecat.processors.aggregators.openai_llm_context import (
@@ -25,6 +25,68 @@
2525
raise Exception(f"Missing module: {e}")
2626

2727

28+
def get_user_memories(user_id: str, limit: int = 5):
29+
"""
30+
Shared function to retrieve user memories from Mem0.
31+
Uses ImprovedMem0MemoryService for reliable memory retrieval.
32+
33+
Args:
34+
user_id: User identifier for memory retrieval
35+
limit: Maximum number of memories to retrieve
36+
37+
Returns:
38+
List of memories or None if failed
39+
"""
40+
if not config.MEM0_API_KEY:
41+
logger.debug("MEM0_API_KEY not configured")
42+
return None
43+
44+
try:
45+
memory_params = ImprovedMem0MemoryService.InputParams()
46+
memory_service = ImprovedMem0MemoryService(
47+
api_key=config.MEM0_API_KEY,
48+
user_id=user_id,
49+
params=memory_params,
50+
)
51+
52+
memories = memory_service.memory_client.get_all(user_id=user_id, limit=limit)
53+
return memories
54+
except Exception as e:
55+
logger.error(f"Error retrieving memories: {e}")
56+
return None
57+
58+
59+
def format_memories_as_context(memories) -> Optional[str]:
60+
if not memories:
61+
return None
62+
63+
context_lines = []
64+
65+
for memory in memories:
66+
memory_text = ""
67+
68+
# Handle the actual mem0 API response format
69+
if isinstance(memory, dict):
70+
# Primary field is 'memory' based on your API response
71+
memory_text = memory.get("memory", "")
72+
73+
# Fallback to other possible fields
74+
if not memory_text:
75+
memory_text = memory.get("text", "") or memory.get("content", "")
76+
77+
# Additional validation and cleanup
78+
if memory_text and isinstance(memory_text, str):
79+
cleaned_text = memory_text.strip()
80+
if cleaned_text and len(cleaned_text) > 5: # Reduced threshold
81+
context_lines.append(f"- {cleaned_text}")
82+
83+
if not context_lines:
84+
return None
85+
86+
context = f"[USER MEMORY CONTEXT] {chr(10).join(context_lines)}"
87+
return context
88+
89+
2890
class ImprovedMem0MemoryService(Mem0MemoryService):
2991
"""
3092
An improved version of Mem0MemoryService with enhanced reliability and performance.
@@ -439,6 +501,41 @@ async def process_frame(self, frame: Frame, direction: FrameDirection):
439501

440502
if latest_user_message:
441503
process_start = time.time()
504+
505+
user_id = getattr(self, "user_id", None)
506+
if user_id:
507+
try:
508+
# Get user memories directly
509+
memories = get_user_memories(user_id, limit=5)
510+
511+
if memories:
512+
# Format memories as context
513+
memory_context = format_memories_as_context(memories)
514+
515+
if memory_context:
516+
# Enhance user message with memory context
517+
enhanced_user_message = f"{memory_context}\nCurrent user message: {latest_user_message}"
518+
519+
context_messages = context.get_messages()
520+
for i, msg in enumerate(context_messages):
521+
if (
522+
msg.get("role") == "user"
523+
and msg.get("content")
524+
== latest_user_message
525+
):
526+
# Update the last user message with memory context
527+
context_messages[i][
528+
"content"
529+
] = enhanced_user_message
530+
logger.debug(
531+
f"Enhanced user message with historical memory context (memories: {len(memories)})"
532+
)
533+
break
534+
535+
except Exception as e:
536+
logger.error(f"Dynamic memory enhancement failed: {e}")
537+
# Continue with original message
538+
442539
# Enhance context with memories before passing it downstream (with fault tolerance)
443540
logger.debug(
444541
f"Enhancing context with memories based on user message: '{latest_user_message[:50]}...'"

0 commit comments

Comments
 (0)