|
42 | 42 | GLOBAL_LOG_LEVEL, |
43 | 43 | RAG_SYSTEM_CONTEXT, |
44 | 44 | ) |
| 45 | +from open_webui.models.chat_messages import ChatMessages |
45 | 46 | from open_webui.models.chats import Chats |
46 | 47 | from open_webui.models.folders import Folders |
47 | 48 | from open_webui.models.functions import Functions |
@@ -2171,14 +2172,38 @@ async def convert_url_images_to_base64(form_data): |
2171 | 2172 |
|
2172 | 2173 | async def load_messages_from_db(chat_id: str, message_id: str) -> Optional[list[dict]]: |
2173 | 2174 | """ |
2174 | | - Load the message chain from DB up to message_id, |
2175 | | - keeping only LLM-relevant fields (role, content, output). |
| 2175 | + Load the message chain, keeping only LLM-relevant fields. |
| 2176 | + Falls back to embedded history when the chain is incomplete. |
2176 | 2177 | """ |
2177 | 2178 | messages_map = await Chats.get_messages_map_by_chat_id(chat_id) |
2178 | 2179 | if not messages_map: |
2179 | 2180 | return None |
2180 | 2181 |
|
2181 | 2182 | db_messages = get_message_list(messages_map, message_id) |
| 2183 | + |
| 2184 | + # Target unreachable or chain truncated before root. |
| 2185 | + if not db_messages or db_messages[0].get('parentId') is not None: |
| 2186 | + chat = await Chats.get_chat_by_id(chat_id) |
| 2187 | + if chat: |
| 2188 | + history = (chat.chat or {}).get('history', {}).get('messages', {}) or {} |
| 2189 | + history_messages = get_message_list(history, message_id) |
| 2190 | + if history_messages: |
| 2191 | + db_messages = history_messages |
| 2192 | + # Backfill missing rows so the next request uses the fast path. |
| 2193 | + # Mirrors the gap-healing in get_messages_map_by_chat_id (chats.py). |
| 2194 | + for msg in history_messages: |
| 2195 | + msg_id = msg.get('id') |
| 2196 | + if msg_id and msg_id not in messages_map: |
| 2197 | + try: |
| 2198 | + await ChatMessages.upsert_message( |
| 2199 | + message_id=msg_id, |
| 2200 | + chat_id=chat_id, |
| 2201 | + user_id=chat.user_id, |
| 2202 | + data=msg, |
| 2203 | + ) |
| 2204 | + except Exception: |
| 2205 | + pass |
| 2206 | + |
2182 | 2207 | if not db_messages: |
2183 | 2208 | return None |
2184 | 2209 |
|
|
0 commit comments