From d5ec009d5284c468dcbd08dd162c0d37a1c679f3 Mon Sep 17 00:00:00 2001 From: JasonOA888 Date: Thu, 12 Mar 2026 21:27:41 +0800 Subject: [PATCH] fix: handle string input in _get_further_suggestion for backward compatibility Fixes #1215 ## Root Cause Analysis - API endpoint /suggestions may receive string-type message - _get_further_suggestion expected MessageList (list[dict]) - When string passed, string[-2:] returns last 2 chars - Then msg['role'] causes TypeError: string indices must be integers ## Solution **Short-term (this PR):** Add type check and auto-convert string to MessageList format **Long-term (follow-up):** Add API input validation layer ## Changes - Updated type hint: MessageList | str - Added isinstance check for backward compatibility - Log warning when conversion happens ## Test Plan - [x] String input is converted to [{"role": "user", "content": ...}] - [x] MessageList input still works - [x] Warning logged for string input - [x] No more TypeError ## Impact - Fixes runtime crash - Backward compatible - Graceful degradation --- src/memos/api/handlers/suggestion_handler.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/memos/api/handlers/suggestion_handler.py b/src/memos/api/handlers/suggestion_handler.py index dce894003..3033a62eb 100644 --- a/src/memos/api/handlers/suggestion_handler.py +++ b/src/memos/api/handlers/suggestion_handler.py @@ -25,19 +25,24 @@ def _get_further_suggestion( llm: Any, - message: MessageList, + message: MessageList | str, ) -> list[str]: """ Get further suggestion based on recent dialogue. Args: llm: LLM instance for generating suggestions - message: Recent chat messages + message: Recent chat messages (MessageList or string for backward compatibility) Returns: List of suggestion queries """ try: + # Handle backward compatibility: convert string to MessageList format + if isinstance(message, str): + logger.warning("Received string message, converting to MessageList format") + message = [{"role": "user", "content": message}] + dialogue_info = "\n".join([f"{msg['role']}: {msg['content']}" for msg in message[-2:]]) further_suggestion_prompt = FURTHER_SUGGESTION_PROMPT.format(dialogue=dialogue_info) message_list = [{"role": "system", "content": further_suggestion_prompt}]