Skip to content

Commit cd2aeb8

Browse files
committed
fix: self-healing fallback for incomplete message chains
1 parent 0e7d3a0 commit cd2aeb8

1 file changed

Lines changed: 27 additions & 2 deletions

File tree

backend/open_webui/utils/middleware.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
GLOBAL_LOG_LEVEL,
4040
RAG_SYSTEM_CONTEXT,
4141
)
42+
from open_webui.models.chat_messages import ChatMessages
4243
from open_webui.models.chats import Chats
4344
from open_webui.models.folders import Folders
4445
from open_webui.models.functions import Functions
@@ -2169,14 +2170,38 @@ async def convert_url_images_to_base64(form_data, user=None):
21692170

21702171
async def load_messages_from_db(chat_id: str, message_id: str) -> Optional[list[dict]]:
21712172
"""
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.
21742175
"""
21752176
messages_map = await Chats.get_messages_map_by_chat_id(chat_id)
21762177
if not messages_map:
21772178
return None
21782179

21792180
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+
21802205
if not db_messages:
21812206
return None
21822207

0 commit comments

Comments
 (0)