MemoryOS 2.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (315) hide show
  1. memoryos-2.0.3.dist-info/METADATA +418 -0
  2. memoryos-2.0.3.dist-info/RECORD +315 -0
  3. memoryos-2.0.3.dist-info/WHEEL +4 -0
  4. memoryos-2.0.3.dist-info/entry_points.txt +3 -0
  5. memoryos-2.0.3.dist-info/licenses/LICENSE +201 -0
  6. memos/__init__.py +20 -0
  7. memos/api/client.py +571 -0
  8. memos/api/config.py +1018 -0
  9. memos/api/context/dependencies.py +50 -0
  10. memos/api/exceptions.py +53 -0
  11. memos/api/handlers/__init__.py +62 -0
  12. memos/api/handlers/add_handler.py +158 -0
  13. memos/api/handlers/base_handler.py +194 -0
  14. memos/api/handlers/chat_handler.py +1401 -0
  15. memos/api/handlers/component_init.py +388 -0
  16. memos/api/handlers/config_builders.py +190 -0
  17. memos/api/handlers/feedback_handler.py +93 -0
  18. memos/api/handlers/formatters_handler.py +237 -0
  19. memos/api/handlers/memory_handler.py +316 -0
  20. memos/api/handlers/scheduler_handler.py +497 -0
  21. memos/api/handlers/search_handler.py +222 -0
  22. memos/api/handlers/suggestion_handler.py +117 -0
  23. memos/api/mcp_serve.py +614 -0
  24. memos/api/middleware/request_context.py +101 -0
  25. memos/api/product_api.py +38 -0
  26. memos/api/product_models.py +1206 -0
  27. memos/api/routers/__init__.py +1 -0
  28. memos/api/routers/product_router.py +477 -0
  29. memos/api/routers/server_router.py +394 -0
  30. memos/api/server_api.py +44 -0
  31. memos/api/start_api.py +433 -0
  32. memos/chunkers/__init__.py +4 -0
  33. memos/chunkers/base.py +24 -0
  34. memos/chunkers/charactertext_chunker.py +41 -0
  35. memos/chunkers/factory.py +24 -0
  36. memos/chunkers/markdown_chunker.py +62 -0
  37. memos/chunkers/sentence_chunker.py +54 -0
  38. memos/chunkers/simple_chunker.py +50 -0
  39. memos/cli.py +113 -0
  40. memos/configs/__init__.py +0 -0
  41. memos/configs/base.py +82 -0
  42. memos/configs/chunker.py +59 -0
  43. memos/configs/embedder.py +88 -0
  44. memos/configs/graph_db.py +236 -0
  45. memos/configs/internet_retriever.py +100 -0
  46. memos/configs/llm.py +151 -0
  47. memos/configs/mem_agent.py +54 -0
  48. memos/configs/mem_chat.py +81 -0
  49. memos/configs/mem_cube.py +105 -0
  50. memos/configs/mem_os.py +83 -0
  51. memos/configs/mem_reader.py +91 -0
  52. memos/configs/mem_scheduler.py +385 -0
  53. memos/configs/mem_user.py +70 -0
  54. memos/configs/memory.py +324 -0
  55. memos/configs/parser.py +38 -0
  56. memos/configs/reranker.py +18 -0
  57. memos/configs/utils.py +8 -0
  58. memos/configs/vec_db.py +80 -0
  59. memos/context/context.py +355 -0
  60. memos/dependency.py +52 -0
  61. memos/deprecation.py +262 -0
  62. memos/embedders/__init__.py +0 -0
  63. memos/embedders/ark.py +95 -0
  64. memos/embedders/base.py +106 -0
  65. memos/embedders/factory.py +29 -0
  66. memos/embedders/ollama.py +77 -0
  67. memos/embedders/sentence_transformer.py +49 -0
  68. memos/embedders/universal_api.py +51 -0
  69. memos/exceptions.py +30 -0
  70. memos/graph_dbs/__init__.py +0 -0
  71. memos/graph_dbs/base.py +274 -0
  72. memos/graph_dbs/factory.py +27 -0
  73. memos/graph_dbs/item.py +46 -0
  74. memos/graph_dbs/nebular.py +1794 -0
  75. memos/graph_dbs/neo4j.py +1942 -0
  76. memos/graph_dbs/neo4j_community.py +1058 -0
  77. memos/graph_dbs/polardb.py +5446 -0
  78. memos/hello_world.py +97 -0
  79. memos/llms/__init__.py +0 -0
  80. memos/llms/base.py +25 -0
  81. memos/llms/deepseek.py +13 -0
  82. memos/llms/factory.py +38 -0
  83. memos/llms/hf.py +443 -0
  84. memos/llms/hf_singleton.py +114 -0
  85. memos/llms/ollama.py +135 -0
  86. memos/llms/openai.py +222 -0
  87. memos/llms/openai_new.py +198 -0
  88. memos/llms/qwen.py +13 -0
  89. memos/llms/utils.py +14 -0
  90. memos/llms/vllm.py +218 -0
  91. memos/log.py +237 -0
  92. memos/mem_agent/base.py +19 -0
  93. memos/mem_agent/deepsearch_agent.py +391 -0
  94. memos/mem_agent/factory.py +36 -0
  95. memos/mem_chat/__init__.py +0 -0
  96. memos/mem_chat/base.py +30 -0
  97. memos/mem_chat/factory.py +21 -0
  98. memos/mem_chat/simple.py +200 -0
  99. memos/mem_cube/__init__.py +0 -0
  100. memos/mem_cube/base.py +30 -0
  101. memos/mem_cube/general.py +240 -0
  102. memos/mem_cube/navie.py +172 -0
  103. memos/mem_cube/utils.py +169 -0
  104. memos/mem_feedback/base.py +15 -0
  105. memos/mem_feedback/feedback.py +1192 -0
  106. memos/mem_feedback/simple_feedback.py +40 -0
  107. memos/mem_feedback/utils.py +230 -0
  108. memos/mem_os/client.py +5 -0
  109. memos/mem_os/core.py +1203 -0
  110. memos/mem_os/main.py +582 -0
  111. memos/mem_os/product.py +1608 -0
  112. memos/mem_os/product_server.py +455 -0
  113. memos/mem_os/utils/default_config.py +359 -0
  114. memos/mem_os/utils/format_utils.py +1403 -0
  115. memos/mem_os/utils/reference_utils.py +162 -0
  116. memos/mem_reader/__init__.py +0 -0
  117. memos/mem_reader/base.py +47 -0
  118. memos/mem_reader/factory.py +53 -0
  119. memos/mem_reader/memory.py +298 -0
  120. memos/mem_reader/multi_modal_struct.py +965 -0
  121. memos/mem_reader/read_multi_modal/__init__.py +43 -0
  122. memos/mem_reader/read_multi_modal/assistant_parser.py +311 -0
  123. memos/mem_reader/read_multi_modal/base.py +273 -0
  124. memos/mem_reader/read_multi_modal/file_content_parser.py +826 -0
  125. memos/mem_reader/read_multi_modal/image_parser.py +359 -0
  126. memos/mem_reader/read_multi_modal/multi_modal_parser.py +252 -0
  127. memos/mem_reader/read_multi_modal/string_parser.py +139 -0
  128. memos/mem_reader/read_multi_modal/system_parser.py +327 -0
  129. memos/mem_reader/read_multi_modal/text_content_parser.py +131 -0
  130. memos/mem_reader/read_multi_modal/tool_parser.py +210 -0
  131. memos/mem_reader/read_multi_modal/user_parser.py +218 -0
  132. memos/mem_reader/read_multi_modal/utils.py +358 -0
  133. memos/mem_reader/simple_struct.py +912 -0
  134. memos/mem_reader/strategy_struct.py +163 -0
  135. memos/mem_reader/utils.py +157 -0
  136. memos/mem_scheduler/__init__.py +0 -0
  137. memos/mem_scheduler/analyzer/__init__.py +0 -0
  138. memos/mem_scheduler/analyzer/api_analyzer.py +714 -0
  139. memos/mem_scheduler/analyzer/eval_analyzer.py +219 -0
  140. memos/mem_scheduler/analyzer/mos_for_test_scheduler.py +571 -0
  141. memos/mem_scheduler/analyzer/scheduler_for_eval.py +280 -0
  142. memos/mem_scheduler/base_scheduler.py +1319 -0
  143. memos/mem_scheduler/general_modules/__init__.py +0 -0
  144. memos/mem_scheduler/general_modules/api_misc.py +137 -0
  145. memos/mem_scheduler/general_modules/base.py +80 -0
  146. memos/mem_scheduler/general_modules/init_components_for_scheduler.py +425 -0
  147. memos/mem_scheduler/general_modules/misc.py +313 -0
  148. memos/mem_scheduler/general_modules/scheduler_logger.py +389 -0
  149. memos/mem_scheduler/general_modules/task_threads.py +315 -0
  150. memos/mem_scheduler/general_scheduler.py +1495 -0
  151. memos/mem_scheduler/memory_manage_modules/__init__.py +5 -0
  152. memos/mem_scheduler/memory_manage_modules/memory_filter.py +306 -0
  153. memos/mem_scheduler/memory_manage_modules/retriever.py +547 -0
  154. memos/mem_scheduler/monitors/__init__.py +0 -0
  155. memos/mem_scheduler/monitors/dispatcher_monitor.py +366 -0
  156. memos/mem_scheduler/monitors/general_monitor.py +394 -0
  157. memos/mem_scheduler/monitors/task_schedule_monitor.py +254 -0
  158. memos/mem_scheduler/optimized_scheduler.py +410 -0
  159. memos/mem_scheduler/orm_modules/__init__.py +0 -0
  160. memos/mem_scheduler/orm_modules/api_redis_model.py +518 -0
  161. memos/mem_scheduler/orm_modules/base_model.py +729 -0
  162. memos/mem_scheduler/orm_modules/monitor_models.py +261 -0
  163. memos/mem_scheduler/orm_modules/redis_model.py +699 -0
  164. memos/mem_scheduler/scheduler_factory.py +23 -0
  165. memos/mem_scheduler/schemas/__init__.py +0 -0
  166. memos/mem_scheduler/schemas/analyzer_schemas.py +52 -0
  167. memos/mem_scheduler/schemas/api_schemas.py +233 -0
  168. memos/mem_scheduler/schemas/general_schemas.py +55 -0
  169. memos/mem_scheduler/schemas/message_schemas.py +173 -0
  170. memos/mem_scheduler/schemas/monitor_schemas.py +406 -0
  171. memos/mem_scheduler/schemas/task_schemas.py +132 -0
  172. memos/mem_scheduler/task_schedule_modules/__init__.py +0 -0
  173. memos/mem_scheduler/task_schedule_modules/dispatcher.py +740 -0
  174. memos/mem_scheduler/task_schedule_modules/local_queue.py +247 -0
  175. memos/mem_scheduler/task_schedule_modules/orchestrator.py +74 -0
  176. memos/mem_scheduler/task_schedule_modules/redis_queue.py +1385 -0
  177. memos/mem_scheduler/task_schedule_modules/task_queue.py +162 -0
  178. memos/mem_scheduler/utils/__init__.py +0 -0
  179. memos/mem_scheduler/utils/api_utils.py +77 -0
  180. memos/mem_scheduler/utils/config_utils.py +100 -0
  181. memos/mem_scheduler/utils/db_utils.py +50 -0
  182. memos/mem_scheduler/utils/filter_utils.py +176 -0
  183. memos/mem_scheduler/utils/metrics.py +125 -0
  184. memos/mem_scheduler/utils/misc_utils.py +290 -0
  185. memos/mem_scheduler/utils/monitor_event_utils.py +67 -0
  186. memos/mem_scheduler/utils/status_tracker.py +229 -0
  187. memos/mem_scheduler/webservice_modules/__init__.py +0 -0
  188. memos/mem_scheduler/webservice_modules/rabbitmq_service.py +485 -0
  189. memos/mem_scheduler/webservice_modules/redis_service.py +380 -0
  190. memos/mem_user/factory.py +94 -0
  191. memos/mem_user/mysql_persistent_user_manager.py +271 -0
  192. memos/mem_user/mysql_user_manager.py +502 -0
  193. memos/mem_user/persistent_factory.py +98 -0
  194. memos/mem_user/persistent_user_manager.py +260 -0
  195. memos/mem_user/redis_persistent_user_manager.py +225 -0
  196. memos/mem_user/user_manager.py +488 -0
  197. memos/memories/__init__.py +0 -0
  198. memos/memories/activation/__init__.py +0 -0
  199. memos/memories/activation/base.py +42 -0
  200. memos/memories/activation/item.py +56 -0
  201. memos/memories/activation/kv.py +292 -0
  202. memos/memories/activation/vllmkv.py +219 -0
  203. memos/memories/base.py +19 -0
  204. memos/memories/factory.py +42 -0
  205. memos/memories/parametric/__init__.py +0 -0
  206. memos/memories/parametric/base.py +19 -0
  207. memos/memories/parametric/item.py +11 -0
  208. memos/memories/parametric/lora.py +41 -0
  209. memos/memories/textual/__init__.py +0 -0
  210. memos/memories/textual/base.py +92 -0
  211. memos/memories/textual/general.py +236 -0
  212. memos/memories/textual/item.py +304 -0
  213. memos/memories/textual/naive.py +187 -0
  214. memos/memories/textual/prefer_text_memory/__init__.py +0 -0
  215. memos/memories/textual/prefer_text_memory/adder.py +504 -0
  216. memos/memories/textual/prefer_text_memory/config.py +106 -0
  217. memos/memories/textual/prefer_text_memory/extractor.py +221 -0
  218. memos/memories/textual/prefer_text_memory/factory.py +85 -0
  219. memos/memories/textual/prefer_text_memory/retrievers.py +177 -0
  220. memos/memories/textual/prefer_text_memory/spliter.py +132 -0
  221. memos/memories/textual/prefer_text_memory/utils.py +93 -0
  222. memos/memories/textual/preference.py +344 -0
  223. memos/memories/textual/simple_preference.py +161 -0
  224. memos/memories/textual/simple_tree.py +69 -0
  225. memos/memories/textual/tree.py +459 -0
  226. memos/memories/textual/tree_text_memory/__init__.py +0 -0
  227. memos/memories/textual/tree_text_memory/organize/__init__.py +0 -0
  228. memos/memories/textual/tree_text_memory/organize/handler.py +184 -0
  229. memos/memories/textual/tree_text_memory/organize/manager.py +518 -0
  230. memos/memories/textual/tree_text_memory/organize/relation_reason_detector.py +238 -0
  231. memos/memories/textual/tree_text_memory/organize/reorganizer.py +622 -0
  232. memos/memories/textual/tree_text_memory/retrieve/__init__.py +0 -0
  233. memos/memories/textual/tree_text_memory/retrieve/advanced_searcher.py +364 -0
  234. memos/memories/textual/tree_text_memory/retrieve/bm25_util.py +186 -0
  235. memos/memories/textual/tree_text_memory/retrieve/bochasearch.py +419 -0
  236. memos/memories/textual/tree_text_memory/retrieve/internet_retriever.py +270 -0
  237. memos/memories/textual/tree_text_memory/retrieve/internet_retriever_factory.py +102 -0
  238. memos/memories/textual/tree_text_memory/retrieve/reasoner.py +61 -0
  239. memos/memories/textual/tree_text_memory/retrieve/recall.py +497 -0
  240. memos/memories/textual/tree_text_memory/retrieve/reranker.py +111 -0
  241. memos/memories/textual/tree_text_memory/retrieve/retrieval_mid_structs.py +16 -0
  242. memos/memories/textual/tree_text_memory/retrieve/retrieve_utils.py +472 -0
  243. memos/memories/textual/tree_text_memory/retrieve/searcher.py +848 -0
  244. memos/memories/textual/tree_text_memory/retrieve/task_goal_parser.py +135 -0
  245. memos/memories/textual/tree_text_memory/retrieve/utils.py +54 -0
  246. memos/memories/textual/tree_text_memory/retrieve/xinyusearch.py +387 -0
  247. memos/memos_tools/dinding_report_bot.py +453 -0
  248. memos/memos_tools/lockfree_dict.py +120 -0
  249. memos/memos_tools/notification_service.py +44 -0
  250. memos/memos_tools/notification_utils.py +142 -0
  251. memos/memos_tools/singleton.py +174 -0
  252. memos/memos_tools/thread_safe_dict.py +310 -0
  253. memos/memos_tools/thread_safe_dict_segment.py +382 -0
  254. memos/multi_mem_cube/__init__.py +0 -0
  255. memos/multi_mem_cube/composite_cube.py +86 -0
  256. memos/multi_mem_cube/single_cube.py +874 -0
  257. memos/multi_mem_cube/views.py +54 -0
  258. memos/parsers/__init__.py +0 -0
  259. memos/parsers/base.py +15 -0
  260. memos/parsers/factory.py +21 -0
  261. memos/parsers/markitdown.py +28 -0
  262. memos/reranker/__init__.py +4 -0
  263. memos/reranker/base.py +25 -0
  264. memos/reranker/concat.py +103 -0
  265. memos/reranker/cosine_local.py +102 -0
  266. memos/reranker/factory.py +72 -0
  267. memos/reranker/http_bge.py +324 -0
  268. memos/reranker/http_bge_strategy.py +327 -0
  269. memos/reranker/noop.py +19 -0
  270. memos/reranker/strategies/__init__.py +4 -0
  271. memos/reranker/strategies/base.py +61 -0
  272. memos/reranker/strategies/concat_background.py +94 -0
  273. memos/reranker/strategies/concat_docsource.py +110 -0
  274. memos/reranker/strategies/dialogue_common.py +109 -0
  275. memos/reranker/strategies/factory.py +31 -0
  276. memos/reranker/strategies/single_turn.py +107 -0
  277. memos/reranker/strategies/singleturn_outmem.py +98 -0
  278. memos/settings.py +10 -0
  279. memos/templates/__init__.py +0 -0
  280. memos/templates/advanced_search_prompts.py +211 -0
  281. memos/templates/cloud_service_prompt.py +107 -0
  282. memos/templates/instruction_completion.py +66 -0
  283. memos/templates/mem_agent_prompts.py +85 -0
  284. memos/templates/mem_feedback_prompts.py +822 -0
  285. memos/templates/mem_reader_prompts.py +1096 -0
  286. memos/templates/mem_reader_strategy_prompts.py +238 -0
  287. memos/templates/mem_scheduler_prompts.py +626 -0
  288. memos/templates/mem_search_prompts.py +93 -0
  289. memos/templates/mos_prompts.py +403 -0
  290. memos/templates/prefer_complete_prompt.py +735 -0
  291. memos/templates/tool_mem_prompts.py +139 -0
  292. memos/templates/tree_reorganize_prompts.py +230 -0
  293. memos/types/__init__.py +34 -0
  294. memos/types/general_types.py +151 -0
  295. memos/types/openai_chat_completion_types/__init__.py +15 -0
  296. memos/types/openai_chat_completion_types/chat_completion_assistant_message_param.py +56 -0
  297. memos/types/openai_chat_completion_types/chat_completion_content_part_image_param.py +27 -0
  298. memos/types/openai_chat_completion_types/chat_completion_content_part_input_audio_param.py +23 -0
  299. memos/types/openai_chat_completion_types/chat_completion_content_part_param.py +43 -0
  300. memos/types/openai_chat_completion_types/chat_completion_content_part_refusal_param.py +16 -0
  301. memos/types/openai_chat_completion_types/chat_completion_content_part_text_param.py +16 -0
  302. memos/types/openai_chat_completion_types/chat_completion_message_custom_tool_call_param.py +27 -0
  303. memos/types/openai_chat_completion_types/chat_completion_message_function_tool_call_param.py +32 -0
  304. memos/types/openai_chat_completion_types/chat_completion_message_param.py +18 -0
  305. memos/types/openai_chat_completion_types/chat_completion_message_tool_call_union_param.py +15 -0
  306. memos/types/openai_chat_completion_types/chat_completion_system_message_param.py +36 -0
  307. memos/types/openai_chat_completion_types/chat_completion_tool_message_param.py +30 -0
  308. memos/types/openai_chat_completion_types/chat_completion_user_message_param.py +34 -0
  309. memos/utils.py +123 -0
  310. memos/vec_dbs/__init__.py +0 -0
  311. memos/vec_dbs/base.py +117 -0
  312. memos/vec_dbs/factory.py +23 -0
  313. memos/vec_dbs/item.py +50 -0
  314. memos/vec_dbs/milvus.py +654 -0
  315. memos/vec_dbs/qdrant.py +355 -0
@@ -0,0 +1,211 @@
1
+ STAGE1_EXPAND_RETRIEVE_PROMPT = """
2
+ ## Goal
3
+ Determine whether the current memories can answer the query using concrete, specific facts. If not, generate 3–8 precise retrieval phrases that capture the missing information.
4
+
5
+ ## Strict Criteria for Answerability
6
+ - The answer MUST be factual, precise, and grounded solely in memory content.
7
+ - Do NOT use vague adjectives (e.g., "usually", "often"), unresolved pronouns ("he", "it"), or generic statements.
8
+ - Do NOT answer with placeholders, speculation, or inferred information.
9
+
10
+ ## Retrieval Phrase Requirements (if can_answer = false)
11
+ - Output 3–8 short, discriminative noun phrases or attribute-value pairs.
12
+ - Each phrase must include at least one explicit entity, attribute, time, or location.
13
+ - Avoid fuzzy words, subjective terms, or pronouns.
14
+ - Phrases must be directly usable as search queries in a vector or keyword retriever.
15
+
16
+ ## Input
17
+ - Query: {query}
18
+ - Previous retrieval phrases:
19
+ {previous_retrieval_phrases}
20
+ - Current Memories:
21
+ {memories}
22
+
23
+ ## Output (STRICT TAG-BASED FORMAT)
24
+ Respond ONLY with the following structure. Do not add any other text, explanation, or formatting.
25
+
26
+ <can_answer>
27
+ true or false
28
+ </can_answer>
29
+ <reason>
30
+ Brief, one-sentence explanation for why the query is or isn't answerable with current memories.
31
+ </reason>
32
+ <retrieval_phrases>
33
+ - missing phrase 1
34
+ - missing phrase 2
35
+ ...
36
+ </retrieval_phrases>
37
+
38
+ Answer:
39
+ """
40
+
41
+
42
+ # Stage 2: if Stage 1 phrases still fail, rewrite the retrieval query and phrases to maximize recall
43
+ STAGE2_EXPAND_RETRIEVE_PROMPT = """
44
+ ## Goal
45
+ Rewrite the original query and generate an improved list of retrieval phrases to maximize recall of relevant memories. Use reference resolution, canonicalization, synonym expansion, and constraint enrichment.
46
+
47
+ ## Rewrite Strategy
48
+ - **Resolve ambiguous references**: Replace pronouns (e.g., “she”, “they”, “it”) and vague terms (e.g., “the book”, “that event”) with explicit entity names or descriptors using only information from the current memories.
49
+ - **Canonicalize entities**: Use full names (e.g., “Melanie Smith”), known roles (e.g., “Caroline’s mentor”), or unambiguous identifiers when available.
50
+ - **Normalize temporal expressions**: Convert relative time references (e.g., “yesterday”, “last weekend”, “a few months ago”) to absolute dates or date ranges **only if the current memories provide sufficient context**.
51
+ - **Enrich with discriminative context**: Combine entity + action/event + time + location when supported by memory content (e.g., “Melanie pottery class July 2023”).
52
+ - **Decompose complex queries**: Break multi-part or abstract questions into concrete, focused sub-queries targeting distinct factual dimensions.
53
+ - **Never invent, assume, or retain unresolved pronouns, vague nouns, or subjective language**.
54
+
55
+ ## Input
56
+ - Query: {query}
57
+ - Previous retrieval phrases:
58
+ {previous_retrieval_phrases}
59
+ - Current Memories:
60
+ {memories}
61
+
62
+ ## Output (STRICT TAG-BASED FORMAT)
63
+ Respond ONLY with the following structure. Do not add any other text, explanation, or formatting.
64
+
65
+ <can_answer>
66
+ true or false
67
+ </can_answer>
68
+ <reason>
69
+ Brief explanation (1–2 sentences) of how this rewrite improves recall—e.g., by resolving pronouns, normalizing time, or adding concrete attributes—over Stage 1 phrases.
70
+ </reason>
71
+ <retrieval_phrases>
72
+ - new phrase 1 (Rewritten, canonical, fully grounded in memory content)
73
+ - new phrase 2
74
+ ...
75
+ </retrieval_phrases>
76
+
77
+ Answer:
78
+ """
79
+
80
+
81
+ # Stage 3: generate grounded hypotheses to guide retrieval when still not answerable
82
+ STAGE3_EXPAND_RETRIEVE_PROMPT = """
83
+ ## Goal
84
+ As the query remains unanswerable, generate grounded, plausible hypotheses based ONLY on the provided memories. Each hypothesis must imply a concrete retrieval target and define clear validation criteria.
85
+
86
+ ## Rules
87
+ - Base hypotheses strictly on facts from the memories. Do NOT introduce new entities, events, or assumptions.
88
+ - Frame each hypothesis as a testable conditional statement: "If [X] is true, then the query can be answered."
89
+ - For each hypothesis, specify 1–3 concrete evidence requirements that would confirm it (e.g., a specific date, name, or event description).
90
+ - Do NOT guess, invent, or speculate beyond logical extrapolation from existing memory content.
91
+
92
+ ## Input
93
+ - Query: {query}
94
+ - Previous retrieval phrases:
95
+ {previous_retrieval_phrases}
96
+ - Memories:
97
+ {memories}
98
+
99
+ ## Output (STRICT TAG-BASED FORMAT)
100
+ Respond ONLY with the following structure. Do not add any other text, explanation, or formatting.
101
+
102
+ <can_answer>
103
+ true or false
104
+ </can_answer>
105
+ <reason>
106
+ - statement: <tentative, grounded hypothesis derived from memory>
107
+ retrieval_query: <concise, searchable query to test the hypothesis>
108
+ validation_criteria:
109
+ - <specific evidence that would confirm the hypothesis>
110
+ - <another required piece of evidence (if applicable)>
111
+ - statement: <another distinct hypothesis>
112
+ retrieval_query: <searchable query>
113
+ validation_criteria:
114
+ - <required evidence>
115
+ </reason>
116
+ <retrieval_phrases>
117
+ - <retrieval_query from hypothesis 1>
118
+ - <retrieval_query from hypothesis 2>
119
+ ...
120
+ </retrieval_phrases>
121
+
122
+ Answer:
123
+ """
124
+
125
+ MEMORY_JUDGMENT_PROMPT = """
126
+ # Memory Relevance Judgment
127
+
128
+ ## Role
129
+ You are a precise memory evaluator. Given a user query and a set of retrieved memories, your task is to judge whether the memories contain sufficient relevant information to answer the query.
130
+
131
+ ## Instructions
132
+
133
+ ### Core Principles
134
+ - Use ONLY facts from the provided memories. Do not invent, infer, guess, or hallucinate.
135
+ - Resolve all pronouns (e.g., "he", "it", "they") and vague terms (e.g., "this", "that", "some people") to explicit entities using memory content.
136
+ - Each fact must be atomic, unambiguous, and verifiable.
137
+ - Preserve all key details: who, what, when, where, why — if present in memory.
138
+ - Judge whether the memories directly support answering the query.
139
+ - Focus on relevance: does this memory content actually help answer what was asked?
140
+
141
+ ### Processing Logic
142
+ - Assess each memory's direct relevance to the query.
143
+ - Judge whether the combination of memories provides sufficient information for a complete answer.
144
+ - Exclude any memory that does not directly support answering the query.
145
+ - Prioritize specificity: e.g., "Travis Tang moved to Singapore in 2021" > "He relocated abroad."
146
+
147
+ ## Input
148
+ - Query: {query}
149
+ - Current Memories:
150
+ {memories}
151
+
152
+ ## Output Format (STRICT TAG-BASED)
153
+ Respond ONLY with the following XML-style tags. Do NOT include any other text, explanations, or formatting.
154
+
155
+ <reason>
156
+ Brief explanation of why the memories are or are not sufficient for answering the query
157
+ </reason>
158
+ <can_answer>
159
+ YES or NO - indicating whether the memories are sufficient to answer the query
160
+ </can_answer>
161
+
162
+ Answer:
163
+ """
164
+
165
+ MEMORY_RECREATE_ENHANCEMENT_PROMPT = """
166
+ You are a precise and detail-oriented AI assistant specialized in temporal memory reconstruction, reference resolution, and relevance-aware memory fusion.
167
+
168
+ # GOAL
169
+ Transform the original memories into a clean, unambiguous, and consolidated set of factual statements that:
170
+ 1. **Resolve all vague or relative references** (e.g., “yesterday” → actual date, “she” → full name, “last weekend” → specific dates, "home" → actual address) **using only information present in the provided memories**.
171
+ 2. **Fuse memory entries that are related by time, topic, participants, or explicit context**—prioritizing the merging of entries that clearly belong together.
172
+ 3. **Preserve every explicit fact from every original memory entry**—no deletion, no loss of detail. Redundant phrasing may be streamlined, but all distinct information must appear in the output.
173
+ 4. **Return at most {top_k} fused and disambiguated memory segments in <answer>, ordered by relevance to the user query** (most relevant first).
174
+
175
+ # RULES
176
+ - **You MUST retain all information from all original memory entries.** Even if an entry seems minor, repetitive, or less relevant, its content must be represented in the output.
177
+ - **Do not add, assume, or invent any information** not grounded in the original memories.
178
+ - **Disambiguate pronouns, time expressions, and vague terms ONLY when the necessary context exists within the memories** (e.g., if “yesterday” appears in a message dated July 3, resolve it to July 2).
179
+ - **If you cannot resolve a vague reference (e.g., “she”, “back home”, “recently”, “a few days ago”) due to insufficient context, DO NOT guess or omit it—include the original phrasing verbatim in the output.**
180
+ - **Prioritize merging memory entries that are semantically or contextually related** (e.g., same event, same conversation thread, shared participants, or consecutive timestamps). Grouping should reflect natural coherence, not just proximity.
181
+ - **The total number of bullets in <answer> must not exceed {top_k}.** To meet this limit, fuse related entries as much as possible while ensuring **no factual detail is omitted**.
182
+ - **Never sacrifice factual completeness for brevity or conciseness.** If needed, create broader but fully informative fused segments rather than dropping information.
183
+ - **Each bullet in <answer> must be a self-contained, fluent sentence or clause** that includes all resolved details from the original entries it represents. If part of the entry cannot be resolved, preserve that part exactly as written.
184
+ - **Sort the final list by how directly and specifically it addresses the user’s query**—not by chronology or source.
185
+
186
+ # OUTPUT FORMAT (STRICT)
187
+ Return ONLY the following structure:
188
+
189
+ <answer>
190
+ - [Fully resolved, fused memory segment most relevant to the query — containing all facts from the original entries it covers; unresolved parts kept verbatim]
191
+ - [Next most relevant resolved and fused segment — again, with no factual loss]
192
+ - [...]
193
+ </answer>
194
+
195
+
196
+ ## User Query
197
+ {query}
198
+
199
+ ## Original Memories
200
+ {memories}
201
+
202
+ Final Output:
203
+ """
204
+
205
+ PROMPT_MAPPING = {
206
+ "memory_judgement": MEMORY_JUDGMENT_PROMPT,
207
+ "stage1_expand_retrieve": STAGE1_EXPAND_RETRIEVE_PROMPT,
208
+ "stage2_expand_retrieve": STAGE2_EXPAND_RETRIEVE_PROMPT,
209
+ "stage3_expand_retrieve": STAGE3_EXPAND_RETRIEVE_PROMPT,
210
+ "memory_recreate_enhancement": MEMORY_RECREATE_ENHANCEMENT_PROMPT,
211
+ }
@@ -0,0 +1,107 @@
1
+ from datetime import datetime
2
+
3
+
4
+ CLOUD_CHAT_PROMPT_ZH = """
5
+ # Role
6
+ 你是一个拥有长期记忆能力的智能助手 (MemOS Assistant)。你的目标是结合检索到的记忆片段,为用户提供高度个性化、准确且逻辑严密的回答。
7
+
8
+ # System Context
9
+ - 当前时间: {current_time} (请以此作为判断记忆时效性的基准)
10
+
11
+ # Memory Data
12
+ 以下是 MemOS 检索到的相关信息,分为“事实”和“偏好”。
13
+ - **事实 (Facts)**:可能包含用户属性、历史对话记录或第三方信息。
14
+ - **特别注意**:其中标记为 `[assistant观点]`、`[模型总结]` 的内容代表 **AI 过去的推断**,**并非**用户的原话。
15
+ - **偏好 (Preferences)**:用户对回答风格、格式或逻辑的显式/隐式要求。
16
+
17
+ <memories>
18
+ {memories}
19
+ </memories>
20
+
21
+ # Critical Protocol: Memory Safety (记忆安全协议)
22
+ 检索到的记忆可能包含**AI 自身的推测**、**无关噪音**或**主体错误**。你必须严格执行以下**“四步判决”**,只要有一步不通过,就**丢弃**该条记忆:
23
+
24
+ 1. **来源真值检查 (Source Verification)**:
25
+ - **核心**:区分“用户原话”与“AI 推测”。
26
+ - 如果记忆带有 `[assistant观点]` 等标签,这仅代表AI过去的**假设**,**不可**将其视为用户的绝对事实。
27
+ - *反例*:记忆显示 `[assistant观点] 用户酷爱芒果`。如果用户没提,不要主动假设用户喜欢芒果,防止循环幻觉。
28
+ - **原则:AI 的总结仅供参考,权重大幅低于用户的直接陈述。**
29
+
30
+ 2. **主语归因检查 (Attribution Check)**:
31
+ - 记忆中的行为主体是“用户本人”吗?
32
+ - 如果记忆描述的是**第三方**(如“候选人”、“面试者”、“虚构角色”、“案例数据”),**严禁**将其属性归因于用户。
33
+
34
+ 3. **强相关性检查 (Relevance Check)**:
35
+ - 记忆是否直接有助于回答当前的 `Original Query`?
36
+ - 如果记忆仅仅是关键词匹配(如:都提到了“代码”)但语境完全不同,**必须忽略**。
37
+
38
+ 4. **时效性检查 (Freshness Check)**:
39
+ - 记忆内容是否与用户的最新意图冲突?以当前的 `Original Query` 为最高事实标准。
40
+
41
+ # Instructions
42
+ 1. **审视**:先阅读 `facts memories`,执行“四步判决”,剔除噪音和不可靠的 AI 观点。
43
+ 2. **执行**:
44
+ - 仅使用通过筛选的记忆补充背景。
45
+ - 严格遵守 `preferences` 中的风格要求。
46
+ 3. **输出**:直接回答问题,**严禁**提及“记忆库”、“检索”或“AI 观点”等系统内部术语。
47
+ 4. **语言**:回答语言应与用户查询语言一致。
48
+ """
49
+
50
+
51
+ CLOUD_CHAT_PROMPT_EN = """
52
+ # Role
53
+ You are an intelligent assistant powered by MemOS. Your goal is to provide personalized and accurate responses by leveraging retrieved memory fragments, while strictly avoiding hallucinations caused by past AI inferences.
54
+
55
+ # System Context
56
+ - Current Time: {current_time} (Baseline for freshness)
57
+
58
+ # Memory Data
59
+ Below is the information retrieved by MemOS, categorized into "Facts" and "Preferences".
60
+ - **Facts**: May contain user attributes, historical logs, or third-party details.
61
+ - **Warning**: Content tagged with `[assistant观点]` or `[summary]` represents **past AI inferences**, NOT direct user quotes.
62
+ - **Preferences**: Explicit or implicit user requirements regarding response style and format.
63
+
64
+ <memories>
65
+ {memories}
66
+ </memories>
67
+
68
+ # Critical Protocol: Memory Safety
69
+ You must strictly execute the following **"Four-Step Verdict"**. If a memory fails any step, **DISCARD IT**:
70
+
71
+ 1. **Source Verification (CRITICAL)**:
72
+ - **Core**: Distinguish between "User's Input" and "AI's Inference".
73
+ - If a memory is tagged as `[assistant观点]`, treat it as a **hypothesis**, not a hard fact.
74
+ - *Example*: Memory says `[assistant view] User loves mango`. Do not treat this as absolute truth unless reaffirmed.
75
+ - **Principle: AI summaries have much lower authority than direct user statements.**
76
+
77
+ 2. **Attribution Check**:
78
+ - Is the "Subject" of the memory definitely the User?
79
+ - If the memory describes a **Third Party** (e.g., Candidate, Fictional Character), **NEVER** attribute these traits to the User.
80
+
81
+ 3. **Relevance Check**:
82
+ - Does the memory *directly* help answer the current `Original Query`?
83
+ - If it is merely a keyword match with different context, **IGNORE IT**.
84
+
85
+ 4. **Freshness Check**:
86
+ - Does the memory conflict with the user's current intent? The current `Original Query` is always the supreme Source of Truth.
87
+
88
+ # Instructions
89
+ 1. **Filter**: Apply the "Four-Step Verdict" to all `fact memories` to filter out noise and unreliable AI views.
90
+ 2. **Synthesize**: Use only validated memories for context.
91
+ 3. **Style**: Strictly adhere to `preferences`.
92
+ 4. **Output**: Answer directly. **NEVER** mention "retrieved memories," "database," or "AI views" in your response.
93
+ 5. **language**: The response language should be the same as the user's query language.
94
+ """
95
+
96
+
97
+ def get_cloud_chat_prompt(lang: str = "en") -> str:
98
+ if lang == "zh":
99
+ return CLOUD_CHAT_PROMPT_ZH.replace(
100
+ "{current_time}", datetime.now().strftime("%Y-%m-%d %H:%M (%A)")
101
+ )
102
+ elif lang == "en":
103
+ return CLOUD_CHAT_PROMPT_EN.replace(
104
+ "{current_time}", datetime.now().strftime("%Y-%m-%d %H:%M (%A)")
105
+ )
106
+ else:
107
+ raise ValueError(f"Invalid language: {lang}")
@@ -0,0 +1,66 @@
1
+ from typing import Any
2
+
3
+ from memos.mem_reader.read_multi_modal import detect_lang
4
+ from memos.templates.prefer_complete_prompt import PREF_INSTRUCTIONS, PREF_INSTRUCTIONS_ZH
5
+
6
+
7
+ def instruct_completion(
8
+ memories: list[dict[str, Any]] | None = None,
9
+ ) -> [str, str]:
10
+ """Create instruction following the preferences."""
11
+ explicit_pref = []
12
+ implicit_pref = []
13
+ for memory in memories:
14
+ pref_type = memory.get("metadata", {}).get("preference_type")
15
+ pref = memory.get("metadata", {}).get("preference", None)
16
+ if not pref:
17
+ continue
18
+ if pref_type == "explicit_preference":
19
+ explicit_pref.append(pref)
20
+ elif pref_type == "implicit_preference":
21
+ implicit_pref.append(pref)
22
+
23
+ explicit_pref_str = (
24
+ "Explicit Preference:\n"
25
+ + "\n".join(f"{i + 1}. {pref}" for i, pref in enumerate(explicit_pref))
26
+ if explicit_pref
27
+ else ""
28
+ )
29
+ implicit_pref_str = (
30
+ "Implicit Preference:\n"
31
+ + "\n".join(f"{i + 1}. {pref}" for i, pref in enumerate(implicit_pref))
32
+ if implicit_pref
33
+ else ""
34
+ )
35
+
36
+ _prompt_map = {
37
+ "zh": PREF_INSTRUCTIONS_ZH,
38
+ "en": PREF_INSTRUCTIONS,
39
+ }
40
+ _remove_exp_map = {
41
+ "zh": "显式偏好 > ",
42
+ "en": "explicit preference > ",
43
+ }
44
+ _remove_imp_map = {
45
+ "zh": "隐式偏好 > ",
46
+ "en": "implicit preference > ",
47
+ }
48
+ lang = detect_lang(
49
+ explicit_pref_str.replace("Explicit Preference:\n", "")
50
+ + implicit_pref_str.replace("Implicit Preference:\n", "")
51
+ )
52
+
53
+ if not explicit_pref_str and not implicit_pref_str:
54
+ return "", ""
55
+ if not explicit_pref_str:
56
+ pref_note = _prompt_map[lang].replace(_remove_exp_map[lang], "")
57
+ pref_string = implicit_pref_str + "\n" + pref_note
58
+ return pref_string, pref_note
59
+ if not implicit_pref_str:
60
+ pref_note = _prompt_map[lang].replace(_remove_imp_map[lang], "")
61
+ pref_string = explicit_pref_str + "\n" + pref_note
62
+ return pref_string, pref_note
63
+
64
+ pref_note = _prompt_map[lang]
65
+ pref_string = explicit_pref_str + "\n" + implicit_pref_str + "\n" + pref_note
66
+ return pref_string, pref_note
@@ -0,0 +1,85 @@
1
+ QUERY_REWRITE_PROMPT = """
2
+ You are a query rewriting specialist. Your task is to rewrite user queries to be more standalone and searchable.
3
+
4
+ Given the conversation history and current user query, rewrite the query to:
5
+ 1. Be self-contained and independent of conversation context
6
+ 2. Include relevant context from history when necessary
7
+ 3. Maintain the original intent and scope
8
+ 4. Use clear, specific terminology
9
+
10
+ Conversation History:
11
+ {history}
12
+
13
+ Current Query: {query}
14
+
15
+ Rewritten Query:"""
16
+
17
+ REFLECTION_PROMPT = """
18
+ You are an information sufficiency analyst. Evaluate whether the retrieved context is sufficient to answer the user's query.
19
+
20
+ Query: {query}
21
+ Retrieved Context:
22
+ {context}
23
+
24
+ Analyze the context and determine the next step. Return your response in JSON format with the following structure:
25
+ ```json
26
+ {{
27
+ "status": "sufficient|missing_info|needs_raw",
28
+ "reasoning": "Brief explanation of your decision",
29
+ "missing_entities": ["entity1", "entity2"],
30
+ "new_search_query": "new search query",
31
+ }}
32
+ ```
33
+
34
+ Status definitions:
35
+ - "sufficient": Context fully answers the query
36
+ - "missing_info": Key information is missing (e.g., specific dates, locations, details)
37
+ - "needs_raw": Content is relevant but too summarized/vague, need original sources
38
+
39
+ IMPORTANT for "new_search_query":
40
+ - MUST preserve ALL specific entities from the original query (names, dates, times, locations, etc.)
41
+ - DO NOT replace specific information with generic terms like "user", "person", "they", etc.
42
+ - Keep the exact same subjects, time references, and key details as in the original query
43
+ - Only modify the query to focus on the missing information while maintaining all original specifics
44
+ - Example: If original query mentions "May 2024", keep "May 2024" in new query, don't change to "that month"
45
+
46
+ Response:"""
47
+
48
+ KEYWORD_EXTRACTION_PROMPT = """
49
+ Analyze the user query and extract key search terms and identify optimal data sources.
50
+
51
+ Query: {query}
52
+
53
+ Extract:
54
+ 1. Key search terms and concepts
55
+ 2. Important entities (people, places, dates, etc.)
56
+ 3. Suggested data sources or memory types to search
57
+
58
+ Return response in JSON format:
59
+ {{
60
+ "keywords": ["keyword1", "keyword2"],
61
+ "entities": ["entity1", "entity2"],
62
+ "search_strategy": "Brief strategy description"
63
+ }}
64
+
65
+ Response:"""
66
+
67
+
68
+ FINAL_GENERATION_PROMPT = """
69
+ You are a comprehensive information synthesizer. Generate a complete answer based on the retrieved information.
70
+
71
+ User Query: {query}
72
+ Search Sources: {sources}
73
+ Retrieved Information:
74
+ {context}
75
+
76
+ Missing Information (if any): {missing_info}
77
+
78
+ Instructions:
79
+ 1. Synthesize all relevant information to answer the query comprehensively
80
+ 2. If information is missing, acknowledge gaps and suggest next steps
81
+ 3. Maintain accuracy and cite sources when possible
82
+ 4. Provide a well-structured, coherent response
83
+ 5. Use natural, conversational tone
84
+
85
+ Response:"""