@@ -71,19 +71,15 @@ def chat(
7171 m .metadata .embedding = []
7272 new_memories_list .append (m )
7373 memories_list = new_memories_list
74- system_prompt = self ._build_base_system_prompt (base_prompt , mode = "base" )
75-
76- memory_context = self ._build_memory_context (memories_list , mode = "base" )
77-
78- user_content = memory_context + query if memory_context else query
74+ system_prompt = self ._build_system_prompt (memories_list , base_prompt )
7975
8076 history_info = []
8177 if history :
8278 history_info = history [- 20 :]
8379 current_messages = [
8480 {"role" : "system" , "content" : system_prompt },
8581 * history_info ,
86- {"role" : "user" , "content" : user_content },
82+ {"role" : "user" , "content" : query },
8783 ]
8884 response = self .chat_llm .generate (current_messages )
8985 time_end = time .time ()
@@ -187,6 +183,42 @@ def _build_base_system_prompt(
187183 prefix = (base_prompt .strip () + "\n \n " ) if base_prompt else ""
188184 return prefix + sys_body
189185
186+ def _build_system_prompt (
187+ self ,
188+ memories : list [TextualMemoryItem ] | list [str ] | None = None ,
189+ base_prompt : str | None = None ,
190+ ** kwargs ,
191+ ) -> str :
192+ """Build system prompt with optional memories context."""
193+ if base_prompt is None :
194+ base_prompt = (
195+ "You are a knowledgeable and helpful AI assistant. "
196+ "You have access to conversation memories that help you provide more personalized responses. "
197+ "Use the memories to understand the user's context, preferences, and past interactions. "
198+ "If memories are provided, reference them naturally when relevant, but don't explicitly mention having memories."
199+ )
200+
201+ memory_context = ""
202+ if memories :
203+ memory_list = []
204+ for i , memory in enumerate (memories , 1 ):
205+ if isinstance (memory , TextualMemoryItem ):
206+ text_memory = memory .memory
207+ else :
208+ if not isinstance (memory , str ):
209+ logger .error ("Unexpected memory type." )
210+ text_memory = memory
211+ memory_list .append (f"{ i } . { text_memory } " )
212+ memory_context = "\n " .join (memory_list )
213+
214+ if "{memories}" in base_prompt :
215+ return base_prompt .format (memories = memory_context )
216+ elif base_prompt and memories :
217+ # For backward compatibility, append memories if no placeholder is found
218+ memory_context_with_header = "\n \n ## Memories:\n " + memory_context
219+ return base_prompt + memory_context_with_header
220+ return base_prompt
221+
190222 def _build_memory_context (
191223 self ,
192224 memories_all : list [TextualMemoryItem ],
0 commit comments