@@ -72,10 +72,6 @@ def _get_backend_cls(backend: str) -> type[BaseLongTermMemoryBackend]:
7272 raise ValueError (f"Unsupported long term memory backend: { backend } " )
7373
7474
75- def build_long_term_memory_index (app_name : str , user_id : str ):
76- return f"{ app_name } _{ user_id } "
77-
78-
7975class LongTermMemory (BaseMemoryService , BaseModel ):
8076 backend : Union [
8177 Literal ["local" , "opensearch" , "redis" , "viking" , "viking_mem" , "mem0" ],
@@ -89,19 +85,14 @@ class LongTermMemory(BaseMemoryService, BaseModel):
8985 top_k : int = 5
9086 """Number of top similar documents to retrieve during search."""
9187
88+ index : str = ""
89+
9290 app_name : str = ""
9391
9492 user_id : str = ""
93+ """Deprecated attribute"""
9594
9695 def model_post_init (self , __context : Any ) -> None :
97- if self .backend == "viking_mem" :
98- logger .warning (
99- "The `viking_mem` backend is deprecated, please use `viking` instead."
100- )
101- self .backend = "viking"
102-
103- self ._backend = None
104-
10596 # Once user define a backend instance, use it directly
10697 if isinstance (self .backend , BaseLongTermMemoryBackend ):
10798 self ._backend = self .backend
@@ -110,33 +101,23 @@ def model_post_init(self, __context: Any) -> None:
110101 )
111102 return
112103
113- if self .backend_config :
114- logger .warning (
115- f"Initialized long term memory backend { self .backend } with config. We will ignore `app_name` and `user_id` if provided."
104+ # Check index
105+ self .index = self .index or self .app_name
106+ if not self .index :
107+ raise ValueError (
108+ "Attribute `index` or `app_name` must be provided one of both."
116109 )
117- self ._backend = _get_backend_cls (self .backend )(** self .backend_config )
118- _index = self .backend_config .get ("index" , None )
119- if _index :
120- self ._index = _index
121- logger .info (f"Long term memory index set to { self ._index } ." )
122- else :
123- logger .warning (
124- "Cannot find index via backend_config, please set `index` parameter."
125- )
126- return
127110
128- if self .app_name and self .user_id :
129- self ._index = build_long_term_memory_index (
130- app_name = self .app_name , user_id = self .user_id
131- )
132- logger .info (f"Long term memory index set to { self ._index } ." )
133- self ._backend = _get_backend_cls (self .backend )(
134- index = self ._index , ** self .backend_config if self .backend_config else {}
135- )
136- else :
111+ # Forward compliance
112+ if self .backend == "viking_mem" :
137113 logger .warning (
138- "Neither `backend_instance`, `backend_config`, nor (`app_name`/`user_id`) is provided, the long term memory storage will initialize when adding a session ."
114+ "The `viking_mem` backend is deprecated, change to `viking` instead ."
139115 )
116+ self .backend = "viking"
117+
118+ self ._backend = _get_backend_cls (self .backend )(
119+ index = self .index , ** self .backend_config if self .backend_config else {}
120+ )
140121
141122 def _filter_and_convert_events (self , events : list [Event ]) -> list [str ]:
142123 final_events = []
@@ -164,75 +145,32 @@ async def add_session_to_memory(
164145 self ,
165146 session : Session ,
166147 ):
167- app_name = session .app_name
168148 user_id = session .user_id
169-
170- if not self ._backend and isinstance (self .backend , str ):
171- self ._index = build_long_term_memory_index (app_name , user_id )
172- self ._backend = _get_backend_cls (self .backend )(
173- index = self ._index , ** self .backend_config if self .backend_config else {}
174- )
175- logger .info (
176- f"Initialize long term memory backend now, index is { self ._index } "
177- )
178-
179- if not self ._index and self ._index != build_long_term_memory_index (
180- app_name , user_id
181- ):
182- logger .warning (
183- f"The `app_name` or `user_id` is different from the initialized one, skip add session to memory. Initialized index: { self ._index } , current built index: { build_long_term_memory_index (app_name , user_id )} "
184- )
185- return
186149 event_strings = self ._filter_and_convert_events (session .events )
187150
188151 logger .info (
189- f"Adding { len (event_strings )} events to long term memory: index={ self ._index } "
152+ f"Adding { len (event_strings )} events to long term memory: index={ self .index } "
153+ )
154+ self ._backend .save_memory (user_id = user_id , event_strings = event_strings )
155+ logger .info (
156+ f"Added { len (event_strings )} events to long term memory: index={ self .index } , user_id={ user_id } "
190157 )
191-
192- if self ._backend :
193- self ._backend .save_memory (event_strings = event_strings , user_id = user_id )
194-
195- logger .info (
196- f"Added { len (event_strings )} events to long term memory: index={ self ._index } "
197- )
198- else :
199- logger .error (
200- "Long term memory backend initialize failed, cannot add session to memory."
201- )
202158
203159 @override
204- async def search_memory (self , * , app_name : str , user_id : str , query : str ):
205- # prevent model invoke `load_memory` before add session to this memory
206- if not self ._backend and isinstance (self .backend , str ):
207- self ._index = build_long_term_memory_index (app_name , user_id )
208- self ._backend = _get_backend_cls (self .backend )(
209- index = self ._index , ** self .backend_config if self .backend_config else {}
210- )
211- logger .info (
212- f"Initialize long term memory backend now, index is { self ._index } "
213- )
160+ async def search_memory (
161+ self , * , app_name : str , user_id : str , query : str
162+ ) -> SearchMemoryResponse :
163+ logger .info (f"Search memory with query={ query } " )
214164
215- if not self ._index and self ._index != build_long_term_memory_index (
216- app_name , user_id
217- ):
218- logger .warning (
219- f"The `app_name` or `user_id` is different from the initialized one. Initialized index: { self ._index } , current built index: { build_long_term_memory_index (app_name , user_id )} . Search memory return empty list."
165+ memory_chunks = []
166+ try :
167+ memory_chunks = self ._backend .search_memory (
168+ query = query , top_k = self .top_k , user_id = user_id
220169 )
221- return SearchMemoryResponse (memories = [])
222-
223- if not self ._backend :
170+ except Exception as e :
224171 logger .error (
225- "Long term memory backend is not initialized, cannot search memory. "
172+ f"Exception orrcus during memory search: { e } . Return empty memory chunks "
226173 )
227- return SearchMemoryResponse (memories = [])
228-
229- logger .info (
230- f"Searching long term memory: query={ query } index={ self ._index } top_k={ self .top_k } "
231- )
232-
233- memory_chunks = self ._backend .search_memory (
234- query = query , top_k = self .top_k , user_id = user_id
235- )
236174
237175 memory_events = []
238176 for memory in memory_chunks :
@@ -260,6 +198,6 @@ async def search_memory(self, *, app_name: str, user_id: str, query: str):
260198 )
261199
262200 logger .info (
263- f"Return { len (memory_events )} memory events for query: { query } index={ self ._index } "
201+ f"Return { len (memory_events )} memory events for query: { query } index={ self .index } user_id= { user_id } "
264202 )
265203 return SearchMemoryResponse (memories = memory_events )
0 commit comments