Skip to content

Commit ad22342

Browse files
committed
fix: embedded history fallback for incomplete chains
1 parent bc848c2 commit ad22342

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
@@ -42,6 +42,7 @@
4242
GLOBAL_LOG_LEVEL,
4343
RAG_SYSTEM_CONTEXT,
4444
)
45+
from open_webui.models.chat_messages import ChatMessages
4546
from open_webui.models.chats import Chats
4647
from open_webui.models.folders import Folders
4748
from open_webui.models.functions import Functions
@@ -2171,14 +2172,38 @@ async def convert_url_images_to_base64(form_data):
21712172

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

21812182
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+
21822207
if not db_messages:
21832208
return None
21842209

0 commit comments

Comments
 (0)