Query the A-Mem memory system and generate response. Steps: 1. Retrieve related memories using A-Mem's find_related_memories 2. Construct context with retrieved memories 3. Generate response using LLM
(
self,
question: str,
system_message: Optional[str] = None,
**kwargs,
)
| 300 | ) |
| 301 | |
| 302 | def query( |
| 303 | self, |
| 304 | question: str, |
| 305 | system_message: Optional[str] = None, |
| 306 | **kwargs, |
| 307 | ) -> AgentResponse: |
| 308 | """Query the A-Mem memory system and generate response. |
| 309 | |
| 310 | Steps: |
| 311 | 1. Retrieve related memories using A-Mem's find_related_memories |
| 312 | 2. Construct context with retrieved memories |
| 313 | 3. Generate response using LLM |
| 314 | """ |
| 315 | context_id = self._get_context_id() |
| 316 | memory_system = self._get_memory_system(context_id) |
| 317 | |
| 318 | # Retrieve related memories |
| 319 | memory_str, indices = memory_system.find_related_memories(question, k=self.retrieve_num) |
| 320 | |
| 321 | # Calculate available tokens for memory context |
| 322 | system_tokens = self._llm_client.count_tokens(system_message) if system_message else 0 |
| 323 | question_tokens = self._llm_client.count_tokens(question) |
| 324 | reserved_tokens = self.amem_max_tokens + RESERVED_OUTPUT_TOKENS |
| 325 | max_memory_tokens = max( |
| 326 | self.amem_max_context_tokens - system_tokens - question_tokens - reserved_tokens, |
| 327 | 0, |
| 328 | ) |
| 329 | |
| 330 | # Truncate memory if needed and construct full question |
| 331 | if memory_str.strip(): |
| 332 | memory_str = self._truncate_to_token_limit(memory_str, max_memory_tokens) |
| 333 | memory_context = f"[Retrieved A-Mem Notes]\n{memory_str}\n\n" |
| 334 | full_question = memory_context + question |
| 335 | else: |
| 336 | full_question = question |
| 337 | |
| 338 | # Generate response |
| 339 | messages = format_messages(full_question, system_message) |
| 340 | response = self._llm_client.chat(messages) |
| 341 | |
| 342 | # Build retrieved memories list for logging |
| 343 | indices_list = indices.tolist() if hasattr(indices, "tolist") else list(indices) |
| 344 | retrieved_memories: List[Dict[str, Any]] = [] |
| 345 | if memory_str.strip(): |
| 346 | retrieved_memories.append({ |
| 347 | "memory": memory_str[:2000], |
| 348 | "type": "amem_retrieval", |
| 349 | "indices": indices_list, |
| 350 | }) |
| 351 | |
| 352 | return AgentResponse( |
| 353 | output=response.content, |
| 354 | retrieved_count=len(indices_list), |
| 355 | retrieved_memories=retrieved_memories, |
| 356 | extra={ |
| 357 | "method": "amem", |
| 358 | "context_id": context_id, |
| 359 | }, |
nothing calls this directly
no test coverage detected