diff --git a/backend/open_webui/routers/chats.py b/backend/open_webui/routers/chats.py index d2b7c66a5d..937ba79c0c 100644 --- a/backend/open_webui/routers/chats.py +++ b/backend/open_webui/routers/chats.py @@ -1672,6 +1672,43 @@ async def update_chat_params( return chat.chat['params'] +# Add Chat Messages By Id +class MessagesForm(BaseModel): + messages: dict[str, dict] + + +@router.post('/{id}/messages', response_model=bool) +async def add_chat_messages_by_id( + request: Request, + id: str, + form_data: MessagesForm, + user=Depends(get_verified_user), + db: AsyncSession = Depends(get_async_session), +): + """Append new messages without reading or returning the whole chat; stored ids are left untouched.""" + if not await Chats.is_chat_owner(id, user.id, db=db): + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) + stored = await ChatMessages.get_messages_map_by_message_ids(id, list(form_data.messages), db=db) + messages = {mid: message for mid, message in form_data.messages.items() if mid not in stored} + if not messages: + return True + + set_message_authors({'history': {'messages': messages}}, user) + for message_id, message in messages.items(): + chat = await Chats.upsert_message_to_chat_by_id_and_message_id(id, message_id, message) + if chat is None: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()) + + await publish_event( + request, + EVENTS.CHAT_UPDATED, + actor=user, + subject_id=id, + data={'title': chat.title}, + ) + return True + + # Update Chat Message By Id class MessageForm(BaseModel): content: str | None = None diff --git a/src/lib/apis/chats/index.ts b/src/lib/apis/chats/index.ts index af906a0791..0ece5383ef 100644 --- a/src/lib/apis/chats/index.ts +++ b/src/lib/apis/chats/index.ts @@ -1378,6 +1378,23 @@ export const updateChatParams = async ( return res.json(); }; +export const addChatMessagesById = async ( + token: string, + id: string, + messages: Record +) => { + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/messages`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + }, + body: JSON.stringify({ messages }) + }); + if (!res.ok) throw getErrorDetail(await res.json()); + return res.json(); +}; + export const compactChatById = async (token: string, id: string, model?: string | null) => { let error = null; diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 4aa9a025c1..89818fb4c2 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -121,6 +121,7 @@ } from './Messages/structuredOutput'; import { + addChatMessagesById, addTagById, archiveChatById, compactChatById, @@ -4105,15 +4106,15 @@ const _chatId = $chatId || (await getChatId(history)); if (_chatId === null) return; - if (_chatId) { - // The server merges a partial history, so send only the new pair and its parent. - const pair = [parentMessage, userMessage, ...responseMessages].filter(Boolean); - await saveChatHandler(_chatId, { - messages: Object.fromEntries(pair.map((message) => [message.id, message])), - currentId: history.currentId - }); - } else { + if (!_chatId) { await initChatHandler(history); + } else if (!$temporaryChat) { + const pair = [userMessage, ...responseMessages]; + await addChatMessagesById( + localStorage.token, + _chatId, + Object.fromEntries(pair.map((message) => [message.id, message])) + ).catch((error) => toast.error(`${error}`)); } } };