Skip to content

Commit 7460cf3

Browse files
committed
fix: self-healing fallback for incomplete message chains
1 parent e1252db commit 7460cf3

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
@@ -2167,14 +2168,38 @@ async def convert_url_images_to_base64(form_data, user=None):
21672168

21682169
async def load_messages_from_db(chat_id: str, message_id: str) -> Optional[list[dict]]:
21692170
"""
2170-
Load the message chain from DB up to message_id,
2171-
keeping only LLM-relevant fields (role, content, output).
2171+
Load the message chain, keeping only LLM-relevant fields.
2172+
Falls back to embedded history when the chain is incomplete.
21722173
"""
21732174
messages_map = await Chats.get_messages_map_by_chat_id(chat_id)
21742175
if not messages_map:
21752176
return None
21762177

21772178
db_messages = get_message_list(messages_map, message_id)
2179+
2180+
# Target unreachable or chain truncated before root.
2181+
if not db_messages or db_messages[0].get('parentId') is not None:
2182+
chat = await Chats.get_chat_by_id(chat_id)
2183+
if chat:
2184+
history = (chat.chat or {}).get('history', {}).get('messages', {}) or {}
2185+
history_messages = get_message_list(history, message_id)
2186+
if history_messages:
2187+
db_messages = history_messages
2188+
# Backfill missing rows so the next request uses the fast path.
2189+
# Mirrors the gap-healing in get_messages_map_by_chat_id (chats.py).
2190+
for msg in history_messages:
2191+
msg_id = msg.get('id')
2192+
if msg_id and msg_id not in messages_map:
2193+
try:
2194+
await ChatMessages.upsert_message(
2195+
message_id=msg_id,
2196+
chat_id=chat_id,
2197+
user_id=chat.user_id,
2198+
data=msg,
2199+
)
2200+
except Exception:
2201+
pass
2202+
21782203
if not db_messages:
21792204
return None
21802205

0 commit comments

Comments
 (0)