Skip to content

Commit 4dcbcac

Browse files
tangg555fridayLglin93
authored
Scheduler: improve add apis (#703)
* debug an error function name * feat: Add DynamicCache compatibility for different transformers versions - Fix build_kv_cache method in hf.py to handle both old and new DynamicCache structures - Support new 'layers' attribute with key_cache/value_cache or keys/values - Maintain backward compatibility with direct key_cache/value_cache attributes - Add comprehensive error handling and logging for unsupported structures - Update move_dynamic_cache_htod function in kv.py for cross-version compatibility - Handle layers-based structure in newer transformers versions - Support alternative attribute names (keys/values vs key_cache/value_cache) - Preserve original functionality for older transformers versions - Add comprehensive tests for DynamicCache compatibility - Test activation memory update with mock DynamicCache layers - Verify layers attribute access across different transformers versions - Fix scheduler logger mock to include memory_manager attribute This resolves AttributeError issues when using different versions of the transformers library and ensures robust handling of DynamicCache objects. debug * feat: implement APIAnalyzerForScheduler for memory operations - Add APIAnalyzerForScheduler class with search/add operations - Support requests and http.client with connection reuse - Include comprehensive error handling and dynamic configuration - Add English test suite with real-world conversation scenarios * feat: Add search_ws API endpoint and enhance API analyzer functionality - Add search_ws endpoint in server_router.py for scheduler-enabled search - Fix missing imports: time module, SearchRequest class, and get_mos_product_instance function - Implement search_ws method in api_analyzer.py with HTTP client support - Add _search_ws_with_requests and _search_ws_with_http_client private methods - Include search_ws usage example in demonstration code - Enhance scheduler and dispatcher capabilities for improved memory management - Expand test coverage to ensure functionality stability This update primarily strengthens the memory scheduling system's search capabilities, providing users with more flexible API interface options. * fix: resolve test failures and warnings in test suite - Fix Pydantic serialization warning in test_memos_chen_tang_hello_world * Add warnings filter to suppress UserWarning from Pydantic serialization - Fix KeyError: 'past_key_values' in test_build_kv_cache_and_generation * Update mock configuration to properly return forward_output with past_key_values * Add DynamicCache version compatibility handling in test mocks * Support both old and new transformers versions with layers/key_cache attributes * Improve assertion logic to check all model calls for required parameters - Update base_scheduler.py to use centralized DEFAULT_MAX_INTERNAL_MESSAGE_QUEUE_SIZE constant * Add import for DEFAULT_MAX_INTERNAL_MESSAGE_QUEUE_SIZE from general_schemas * Replace hardcoded value 100 with configurable constant (1000) All tests now pass successfully with proper version compatibility handling. * feat: add a test_robustness execution to test thread pool execution * feat: optimize scheduler configuration and API search functionality - Add DEFAULT_TOP_K and DEFAULT_CONTEXT_WINDOW_SIZE global constants in general_schemas.py - Update base_scheduler.py to use global default values instead of hardcoded numbers - Fix SchedulerConfigFactory initialization issue by using keyword argument expansion - Resolve UnboundLocalError variable conflict in search_memories_ws function - Fix indentation and parameter issues in OptimizedScheduler search_for_api method - Improve code standardization and maintainability * feat: Add Redis auto-initialization with fallback strategies - Add auto_initialize_redis() with config/env/local fallback - Move Redis logic from dispatcher_monitor to redis_service - Update base_scheduler to use auto initialization - Add proper resource cleanup and error handling * feat: add database connection management to ORM module - Add MySQL engine loading from environment variables in BaseDBManager - Add Redis connection loading from environment variables in BaseDBManager - Enhance database configuration validation and error handling - Complete database adapter infrastructure for ORM module - Provide unified database connection management interface This update provides comprehensive database connection management capabilities for the mem_scheduler module, supporting dynamic MySQL and Redis configuration loading from environment variables, establishing reliable data persistence foundation for scheduling services and API services. * remove part of test * feat: add Redis-based ORM with multiprocess synchronization - Add RedisDBManager and RedisLockableORM classes - Implement atomic locking mechanism for concurrent access - Add merge functionality for different object types - Include comprehensive test suite and examples - Fix Redis key type conflicts in lock operations * fix: resolve scheduler module import and Redis integration issues * revise naive memcube creation in server router * remove long-time tests in test_scheduler * remove redis test which needs .env * refactor all codes about mixture search with scheduler * fix: resolve Redis API synchronization issues and implement search API with reranker - Fix running_entries to running_task_ids migration across codebase - Update sync_search_data method to properly handle TaskRunningStatus - Correct variable naming and logic in API synchronization flow - Implement search API endpoint with reranker functionality - Update test files to reflect new running_task_ids convention - Ensure proper Redis state management for concurrent tasks * remove a test for api module * revise to pass the test suite * address some bugs to make mix_search normally running * modify codes according to evaluation logs * feat: Optimize mixture search and enhance API client * feat: Add conversation_turn tracking for session-based memory search - Add conversation_turn field to APIMemoryHistoryEntryItem schema with default value 0 - Implement session counter in OptimizedScheduler to track turn count per session_id - Update sync_search_data method to accept and store conversation_turn parameter - Maintain session history with LRU eviction (max 5 sessions) - Rename conversation_id to session_id for consistency with request object - Enable direct access to session_id from search requests This feature allows tracking conversation turns within the same session, providing better context for memory retrieval and search history management. * adress time bug in monitor * revise simple tree * add mode to evaluation client; rewrite print to logger.info in db files * feat: 1. add redis queue for scheduler 2. finish the code related to mix search and fine search * debug the working memory code * addressed a range of bugs to make scheduler running correctly * remove test_dispatch_parallel test * print change to logger.info * adjucted the core code related to fine and mixture apis * feat: create task queue to wrap local queue and redis queue. queue now split FIFO to multi queue from different users. addressed a range of bugs * fix bugs: debug bugs about internet trigger * debug get searcher mode * feat: add manual internet * Fix: fix code format * feat: add strategy for fine search * debug redis queue * debug redis queue * fix bugs: completely addressed bugs about redis queue * refactor: add searcher to handler_init; remove info log from task_queue * refactor: modify analyzer * refactor: revise locomo_eval to make it support llm other than gpt-4o-mini * feat: develop advanced searcher with deep search * feat: finish a complete version of deep search * refactor: refactor deep search feature, now only allowing one-round deep search * feat: implement the feature of get_tasks_status, but completed tasks are not recorded yet; waiting to be developed * debuging merged code; searching memories have bugs * change logging level * debug api evaluation * fix bugs: change top to top_k * change log * refactor: rewrite deep search to make it work better * change num_users * feat: developed and test task broker and orchestrator * Fix: Include task_id in ScheduleMessageItem serialization * Fix(Scheduler): Correct event log creation and task_id serialization * Feat(Scheduler): Add conditional detailed logging for KB updates Fix(Scheduler): Correct create_event_log indentation * Fix(Scheduler): Correct create_event_log call sites Reverts previous incorrect fix to scheduler_logger.py and correctly fixes the TypeError at the call sites in general_scheduler.py by removing the invalid 'log_content' kwarg and adding the missing memory_type kwargs. * Fix(Scheduler): Deserialize task_id in ScheduleMessageItem.from_dict This completes the fix for the task_id loss. The 'to_dict' method was previously fixed to serialize the task_id, but the corresponding 'from_dict' method was not updated to deserialize it, causing the value to be lost when messages were read from the queue. * Refactor(Config): Centralize RabbitMQ config override logic Moves all environment variable override logic into initialize_rabbitmq for a single source of truth. This ensures Nacos-provided environment variables for all RabbitMQ settings are respected over file configurations. Also removes now-redundant logging from the publish method. * Revert "Refactor(Config): Centralize RabbitMQ config override logic" This reverts commit b8cc42a. * Fix(Redis): Convert None task_id to empty string during serialization Resolves DataError in Redis Streams when task_id is None by ensuring it's serialized as an empty string instead of None, which Redis does not support. Applies to ScheduleMessageItem.to_dict method. * Feat(Log): Add diagnostic log to /product/add endpoint Adds an INFO level diagnostic log message at the beginning of the create_memory function to help verify code deployment. * Feat(Log): Add comprehensive diagnostic logs for /product/add flow Introduces detailed INFO level diagnostic logs across the entire call chain for the /product/add API endpoint. These logs include relevant context, such as full request bodies, message items before scheduler submission, and messages before RabbitMQ publication, to aid in debugging deployment discrepancies and tracing data flow, especially concerning task_id propagation. Logs added/enhanced in: - src/memos/api/routers/product_router.py - src/memos/api/handlers/add_handler.py - src/memos/multi_mem_cube/single_cube.py - src/memos/mem_os/core.py - src/memos/mem_scheduler/general_scheduler.py - src/memos/mem_scheduler/base_scheduler.py - src/memos/mem_scheduler/webservice_modules/rabbitmq_service.py * Feat(Log): Add comprehensive diagnostic logs for /product/add flow and apply ruff formatting Introduces detailed INFO level diagnostic logs across the entire call chain for the /product/add API endpoint. These logs include relevant context, such as full request bodies, message items before scheduler submission, and messages before RabbitMQ publication, to aid in debugging deployment discrepancies and tracing data flow, especially concerning task_id propagation. Also applies automatic code formatting using ruff format to all modified files. Logs added/enhanced in: - src/memos/api/routers/product_router.py - src/memos/api/handlers/add_handler.py - src/memos/multi_mem_cube/single_cube.py - src/memos/mem_os/core.py - src/memos/mem_scheduler/general_scheduler.py - src/memos/mem_scheduler/base_scheduler.py - src/memos/mem_scheduler/webservice_modules/rabbitmq_service.py * Fix(rabbitmq): Use env vars for KB updates and improve logging * Fix(rabbitmq): Explicitly use MEMSCHEDULER_RABBITMQ_EXCHANGE_NAME and empty routing key for KB updates * Fix(add_handler): Update diagnostic log timestamp * Fix(add_handler): Update diagnostic log timestamp again (auto-updated) * Update default scheduler redis stream prefix * Update diagnostic timestamp in add handler * Allow optional log_content in scheduler event log * feat: new examples to test scheduelr * feat: fair scheduler and refactor of search function * fix bugs: address bugs caused by outdated test code * feat: add task_schedule_monitor * fix: handle nil mem_cube in scheduler message consumers * fix bugs: response messaged changed in memos code * refactor: revise task queue to allow it dealing with pending tasks when no task remaining * refactor: revise mixture search and scheduler logger * Fix scheduler task tracking * fix bugs: address ai review issues * fix bugs: address rabbitmq initialization failed when doing pytest * fix(scheduler): Correct dispatcher task and future tracking * Remove dump.rdb * fix bugs: revised message ack logics; refactor add log function * fix bugs: change Chinese notation to English * fix indent error in logger * fix bugs: addressed the issues caused by multiprocessing codes obtain same pending tasks * addMemory/updateMemory log * fix bugs: modify redis queue logics to make it run as expected * feat: add a default mem cube initialization for scheduler * address scheduler init bug * feat(scheduler): Propagate trace_id across process boundaries for mem… (#592) feat(scheduler): Propagate trace_id across process boundaries for mem_scheduler logs This commit addresses the issue where 'trace_id' was missing from logs generated by the 'mem_scheduler' module, especially when tasks were executed in separate processes. The changes implement a manual propagation of 'trace_id' from the message producer to the consumer: 1. **Schema Update**: Added an optional 'trace_id' field to 'ScheduleMessageItem' in 'src/memos/mem_scheduler/schemas/message_schemas.py' to allow 'trace_id' to be carried within messages. 2. **Producer-side Capture**: Modified 'src/memos/mem_scheduler/task_schedule_modules/task_queue.py' to capture the current 'trace_id' and embed it into the 'ScheduleMessageItem' before messages are enqueued. 3. **Consumer-side Context Re-establishment**: Updated 'src/memos/mem_scheduler/task_schedule_modules/dispatcher.py' to extract the 'trace_id' from incoming messages and re-establish the logging context using 'RequestContext' for each task's execution. This ensures all logs within a task's scope correctly include its associated 'trace_id', even when crossing process boundaries. This approach ensures robust and accurate tracing of tasks within the scheduler, enhancing observability and debugging capabilities. Co-authored-by: [email protected] <> * fix bugs: redis queue allows to reget pending tasks which exceeding idle time * fix(scheduler): Correct lazy-loading logic for mem_cube property * Add MONITOR_EVENT logs for scheduler lifecycle * fix: Resolve Ruff linting and formatting issues * Handle dequeue timestamp without pydantic errors * feat: orchestrator add task priority; move task labels into task_schemas; add synchronous execuation option in dispatcher * feat: more logs for debug * fix bugs: addresss some bugs * refactor: remove logger info in pref add function * refactor: change redis queue to periodically refresh pending tasks * feat: a faster and better redis queue * refactor: remove cleanup in redis queue * feat: allow directly execute task if task priority is level 1 * refactor: refactor log_add_handler and redis queue to make the code running better * fix bugs: fix the bug in _process_chat_data * fix: use message item_id for task status updates instead of execution id * style: format dispatcher.py with ruff * chore: emit dequeue for immediate tasks * fix: resolve ruff UP038 in base_scheduler.py * feat: add scheduler queue status endpoint * fix: lazy-init redis in queue status handler * fix: unwrap queue wrapper for redis status * fix bugs: fix a bug causing no schedule memory * feat: add a new env variable to set stream_prefix in redis; make add func hallucination filter to improve qualities of added memories * fix bugs: update start_listening in redis_queue * refactor: revise polardb and scheduelr init * feat: time task_broker; add a hallucination filter for simple struct add * feat & fix bugs: redis scheduler support periodically refresh active streams and deleted inactive streams; fix bugs of xautoclaims * refactor: revise the code according to llm suggestions * address ruff * modify examples * feat: process chunks from redis streams * refactor: update add operation * feat: status_tracker support lazy init * refactor: improve scheduler * fix bugs: rewrite retriever.search and resolve the json wrong decoding issue * refactor: revise add * refactor: more logs and revision of simple struct * address ruff * address ruff * fix bugs and refactor: revise add api * fix bugs: logger error * feat & fix bugs: revise fine add functions and fix bugs of claiming pending tasks --------- Co-authored-by: fridayL <[email protected]> Co-authored-by: [email protected] <> Co-authored-by: Zehao Lin <[email protected]> Co-authored-by: chunyu li <[email protected]>
1 parent 8ee783e commit 4dcbcac

File tree

5 files changed

+113
-50
lines changed

5 files changed

+113
-50
lines changed

examples/mem_scheduler/try_schedule_modules.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -204,19 +204,16 @@ def add_msgs(
204204

205205
for item_idx, item in enumerate(tqdm(questions, desc="processing queries")):
206206
query = item["question"]
207-
messages_to_send = [
208-
ScheduleMessageItem(
209-
item_id=f"test_item_{item_idx}",
210-
user_id=trying_modules.current_user_id,
211-
mem_cube_id=trying_modules.current_mem_cube_id,
212-
label=MEM_UPDATE_TASK_LABEL,
213-
content=query,
214-
)
215-
]
216-
207+
message = ScheduleMessageItem(
208+
item_id=f"test_item_{item_idx}",
209+
user_id=trying_modules.current_user_id,
210+
mem_cube_id=trying_modules.current_mem_cube_id,
211+
label=MEM_UPDATE_TASK_LABEL,
212+
content=query,
213+
)
217214
# Run one session turn manually to get search candidates
218215
mem_scheduler._memory_update_consumer(
219-
messages=messages_to_send,
216+
messages=[message],
220217
)
221218

222219
# Show accumulated web logs

src/memos/mem_reader/simple_struct.py

Lines changed: 53 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ def get_memory(
459459
@staticmethod
460460
def _parse_hallucination_filter_response(text: str) -> tuple[bool, dict[int, dict]]:
461461
"""Parse index-keyed JSON from hallucination filter response.
462-
Expected shape: { "0": {"need_rewrite": bool, "rewritten_suffix": str, "reason": str}, ... }
462+
Expected shape: { "0": {"need_rewrite": bool, "rewritten": str, "reason": str}, ... }
463463
Returns (success, parsed_dict) with int keys.
464464
"""
465465
try:
@@ -483,16 +483,16 @@ def _parse_hallucination_filter_response(text: str) -> tuple[bool, dict[int, dic
483483
if not isinstance(v, dict):
484484
continue
485485
need_rewrite = v.get("need_rewrite")
486-
rewritten_suffix = v.get("rewritten_suffix", "")
486+
rewritten = v.get("rewritten", "")
487487
reason = v.get("reason", "")
488488
if (
489489
isinstance(need_rewrite, bool)
490-
and isinstance(rewritten_suffix, str)
490+
and isinstance(rewritten, str)
491491
and isinstance(reason, str)
492492
):
493493
result[idx] = {
494494
"need_rewrite": need_rewrite,
495-
"rewritten_suffix": rewritten_suffix,
495+
"rewritten": rewritten,
496496
"reason": reason,
497497
}
498498

@@ -503,6 +503,8 @@ def filter_hallucination_in_memories(
503503
) -> list[TextualMemoryItem]:
504504
# Build input objects with memory text and metadata (timestamps, sources, etc.)
505505
template = PROMPT_MAPPING["hallucination_filter"]
506+
if len(messages) < 2:
507+
return memory_list
506508
prompt_args = {
507509
"messages_inline": "\n".join(
508510
[f"- [{message['role']}]: {message['content']}" for message in messages]
@@ -523,32 +525,27 @@ def filter_hallucination_in_memories(
523525
f"[filter_hallucination_in_memories] Hallucination filter parsed successfully: {success}"
524526
)
525527
if success:
526-
new_mem_list = []
527528
logger.info(f"Hallucination filter result: {parsed}")
528529
assert len(parsed) == len(memory_list)
529530
for mem_idx, content in parsed.items():
530531
need_rewrite = content.get("need_rewrite", False)
531-
rewritten_suffix = content.get("rewritten_suffix", "")
532+
rewritten_text = content.get("rewritten", "")
532533
reason = content.get("reason", "")
533534

534-
# Append a new memory item instead of replacing the original
535+
# Replace memory text with rewritten content when rewrite is needed
535536
if (
536537
need_rewrite
537-
and isinstance(rewritten_suffix, str)
538-
and len(rewritten_suffix.strip()) > 0
538+
and isinstance(rewritten_text, str)
539+
and len(rewritten_text.strip()) > 0
539540
):
540541
original_text = memory_list[mem_idx].memory
541542

542543
logger.info(
543-
f"[filter_hallucination_in_memories] index={mem_idx}, need_rewrite={need_rewrite}, rewritten_suffix='{rewritten_suffix}', reason='{reason}', original memory='{original_text}', action='append_suffix'"
544+
f"[filter_hallucination_in_memories] index={mem_idx}, need_rewrite={need_rewrite}, rewritten='{rewritten_text}', reason='{reason}', original memory='{original_text}', action='replace_text'"
544545
)
545546

546-
# Append only the suffix to the original memory text
547-
memory_list[mem_idx].memory = original_text + rewritten_suffix
548-
new_mem_list.append(memory_list[mem_idx])
549-
else:
550-
new_mem_list.append(memory_list[mem_idx])
551-
return new_mem_list
547+
memory_list[mem_idx].memory = rewritten_text
548+
return memory_list
552549
else:
553550
logger.warning("Hallucination filter parsing failed or returned empty result.")
554551
except Exception as e:
@@ -603,13 +600,46 @@ def _read_memory(
603600

604601
if os.getenv("SIMPLE_STRUCT_ADD_FILTER", "false") == "true":
605602
# Build inputs
606-
new_memory_list = []
607-
for unit_messages, unit_memory_list in zip(messages, memory_list, strict=False):
608-
unit_memory_list = self.filter_hallucination_in_memories(
609-
messages=unit_messages, memory_list=unit_memory_list
610-
)
611-
new_memory_list.append(unit_memory_list)
612-
memory_list = new_memory_list
603+
combined_messages = []
604+
for group_messages in messages:
605+
combined_messages.extend(group_messages)
606+
607+
for group_id in range(len(memory_list)):
608+
try:
609+
revised_memory_list = self.filter_hallucination_in_memories(
610+
messages=combined_messages,
611+
memory_list=memory_list[group_id],
612+
)
613+
if len(revised_memory_list) != len(memory_list[group_id]):
614+
original_serialized = [
615+
one.memory if hasattr(one, "memory") else str(one)
616+
for one in memory_list[group_id]
617+
]
618+
filtered_serialized = [
619+
one.memory if hasattr(one, "memory") else str(one)
620+
for one in revised_memory_list
621+
]
622+
logger.error(
623+
f"Length mismatch after hallucination filtering for group_id={group_id}: "
624+
f"original={len(memory_list[group_id])}, filtered={len(revised_memory_list)}"
625+
f"\noriginal_memory_list(serialized): {original_serialized}"
626+
f"\nfiltered_memory_list(serialized): {filtered_serialized}"
627+
f"\nmessages: {combined_messages}"
628+
f"\nSkipping update and keeping original memory."
629+
)
630+
continue
631+
memory_list[group_id] = revised_memory_list
632+
except Exception as e:
633+
group_serialized = [
634+
one.memory if hasattr(one, "memory") else str(one)
635+
for one in memory_list[group_id]
636+
]
637+
logger.error(
638+
f"There is an exception while filtering group_id={group_id}: {e}\n"
639+
f"messages: {combined_messages}\n"
640+
f"memory_list(serialized): {group_serialized}",
641+
exc_info=True,
642+
)
613643
return memory_list
614644

615645
def fine_transfer_simple_mem(

src/memos/mem_scheduler/general_scheduler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,8 +156,8 @@ def long_memory_update_process(
156156
logger.info(
157157
f"[long_memory_update_process] For user_id='{user_id}', mem_cube_id='{mem_cube_id}': "
158158
f"Scheduler replaced working memory based on query history {queries}. "
159-
f"Old working memory ({len(old_memory_texts)} items): {old_memory_texts}. "
160-
f"New working memory ({len(new_memory_texts)} items): {new_memory_texts}."
159+
f"Old working memory ({len(cur_working_memory)} items): {old_memory_texts}. "
160+
f"New working memory ({len(new_order_working_memory)} items): {new_memory_texts}."
161161
)
162162

163163
# update activation memories

src/memos/mem_scheduler/task_schedule_modules/redis_queue.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -723,8 +723,32 @@ def _batch_claim_pending_messages(
723723
)
724724
results.append(res)
725725
except Exception as se:
726-
logger.warning(f"Sequential xautoclaim failed for '{stream_key}': {se}")
727-
results.append(None)
726+
err_msg = str(se).lower()
727+
if "nogroup" in err_msg or "no such key" in err_msg:
728+
logger.warning(
729+
f"Sequential xautoclaim failed for '{stream_key}': {se}. Retrying with _ensure_consumer_group."
730+
)
731+
with contextlib.suppress(Exception):
732+
self._ensure_consumer_group(stream_key=stream_key)
733+
try:
734+
res = self._redis_conn.xautoclaim(
735+
name=stream_key,
736+
groupname=self.consumer_group,
737+
consumername=self.consumer_name,
738+
min_idle_time=self.orchestrator.get_task_idle_min(task_label=label),
739+
start_id="0-0",
740+
count=need_count,
741+
justid=False,
742+
)
743+
results.append(res)
744+
except Exception as retry_err:
745+
logger.warning(
746+
f"Retry sequential xautoclaim failed for '{stream_key}': {retry_err}"
747+
)
748+
results.append(None)
749+
else:
750+
logger.warning(f"Sequential xautoclaim failed for '{stream_key}': {se}")
751+
results.append(None)
728752

729753
claimed_pairs: list[tuple[str, list[tuple[str, dict]]]] = []
730754
for (stream_key, _need_count, _label), claimed_result in zip(

src/memos/templates/mem_reader_prompts.py

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -623,15 +623,23 @@
623623

624624

625625
SIMPLE_STRUCT_HALLUCINATION_FILTER_PROMPT = """
626-
You are a strict memory validator.
626+
You are a strict, language-preserving memory validator and rewriter.
627627
628-
Task:
629-
Check each memory against the user messages (ground truth). Do not modify the original text. Generate ONLY a suffix to append.
628+
Your task is to compare each memory against the provided user messages (the ground truth) and produce a corrected version only when necessary. Always preserve the original language of the memory—do not translate.
630629
631630
Rules:
632-
- Append " [Source:] Inference by assistant." if the memory contains assistant inference (not directly stated by the user).
633-
- Otherwise output an empty suffix.
634-
- No other commentary or formatting.
631+
1. **Language Consistency**: The rewritten memory must be in the exact same language as the original input memory. Never switch languages.
632+
2. **Strict Grounding**: Only use information explicitly stated in the user messages. Do not introduce external facts, assumptions, or common sense.
633+
3. **Ambiguity Resolution**:
634+
- Replace vague pronouns (e.g., "he", "it", "they") or unclear references with specific, unambiguous entities based solely on the messages.
635+
- Convert relative time expressions (e.g., "yesterday", "last week", "in two days") into absolute dates or times **only if the messages provide enough context** (e.g., current date is known or implied).
636+
4. **Handling Assistant Inferences**:
637+
- If a memory contains any content **not directly stated by the user**—such as interpretations, summaries, emotional attributions, predictions, causal claims, or generalizations—this is considered an assistant inference.
638+
- In such cases, you **must** set `need_rewrite = true`.
639+
- The `rewritten` text **must explicitly indicate that the statement is an inference**, using a clear and natural prefix in the memory’s language. For English memories, use:
640+
> "The assistant inferred that [rest of the memory]."
641+
- Do **not** present inferred content as factual user statements.
642+
5. **No Rewrite Needed**: If the memory is factually accurate, fully grounded in the messages, unambiguous, and contains no unsupported content, set `need_rewrite = false` and copy the original memory exactly.
635643
636644
Inputs:
637645
messages:
@@ -640,12 +648,16 @@
640648
memories:
641649
{memories_inline}
642650
643-
Output JSON:
644-
- Keys: same indices as input ("0", "1", ...).
645-
- Values: {{ "need_rewrite": boolean, "rewritten_suffix": string, "reason": string }}
646-
- need_rewrite = true only when assistant inference is detected.
647-
- rewritten_suffix = " [Source:] Inference by assistant." or "".
648-
- reason: brief, e.g., "assistant inference detected" or "explicit user statement".
651+
Output Format:
652+
- Return a JSON object with string keys ("0", "1", "2", ...) corresponding to the input memory indices.
653+
- Each value must be: {{ "need_rewrite": boolean, "rewritten": string, "reason": string }}
654+
- The "reason" should be concise and specific, e.g.:
655+
- "contains assistant inference not stated by user"
656+
- "pronoun 'it' has no clear referent in messages"
657+
- "relative time 'yesterday' converted to 2025-12-16"
658+
- "accurate and directly supported by user message"
659+
660+
Important: Output **only** the JSON. No additional text, explanations, markdown, or fields.
649661
"""
650662

651663

0 commit comments

Comments
 (0)