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