diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index 7cf0b5c74f..07a3e8befe 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -601,6 +601,29 @@ def get_response_completion_event_data(event: dict) -> dict: } +def get_citation_ids(source: dict, source_ids: dict) -> list[int]: + """ + Number a source's documents for citation and save the numbers with it. + + source_ids holds the numbers the chat has used so far, so a document keeps its + number across turns and a new one takes the next. A number saved earlier wins: + it is the one the model was shown. + """ + saved_ids = source.get('citation_ids') + saved_ids = saved_ids if isinstance(saved_ids, list) else [] + citation_ids = [] + for index, (_, meta) in enumerate(zip(source.get('document', []), source.get('metadata', []))): + source_id = meta.get('source') or source.get('source', {}).get('id') or 'N/A' + saved_id = saved_ids[index] if index < len(saved_ids) else None + if type(saved_id) is int and saved_id > 0: + source_ids[source_id] = saved_id + elif source_id not in source_ids: + source_ids[source_id] = max(source_ids.values(), default=0) + 1 + citation_ids.append(source_ids[source_id]) + source['citation_ids'] = citation_ids + return citation_ids + + def get_source_context(sources: list, source_ids: dict = None, include_content: bool = True) -> str: """ Build tag context string from citation sources. @@ -609,10 +632,8 @@ def get_source_context(sources: list, source_ids: dict = None, include_content: if source_ids is None: source_ids = {} for source in sources: - for doc, meta in zip(source.get('document', []), source.get('metadata', [])): - source_id = meta.get('source') or source.get('source', {}).get('id') or 'N/A' - if source_id not in source_ids: - source_ids[source_id] = len(source_ids) + 1 + citation_ids = get_citation_ids(source, source_ids) + for doc, meta, citation_id in zip(source.get('document', []), source.get('metadata', []), citation_ids): src_name = source.get('source', {}).get('name') src_type = source.get('source', {}).get('type') src_rid = source.get('source', {}).get('id') if src_type != 'text' else None @@ -623,7 +644,7 @@ def get_source_context(sources: list, source_ids: dict = None, include_content: continue extra_attrs += f' {key}="{html.escape(str(value))}"' context_string += ( - f' list: @@ -651,7 +673,7 @@ async def apply_source_context_to_messages( if not sources or not user_message: return messages - context = get_source_context(sources, include_content=include_content) + context = get_source_context(sources, source_ids, include_content=include_content) context = context.strip() if not context: @@ -681,11 +703,12 @@ async def tool_result_with_citations(name, params, result, tool, model, source_i except Exception as e: log.exception(f'Error extracting citation source: {e}') return content - if event_emitter: - for source in sources: - await event_emitter({'type': 'source', 'data': source}) if sources: + # Number the sources before they are emitted, so the saved message keeps the numbers. context = get_source_context(sources, source_ids, include_content=False).strip() + if event_emitter: + for source in sources: + await event_emitter({'type': 'source', 'data': source}) if context: citation_context = await rag_template(await Config.get('rag.template'), context, user_message or '') # Save markers with this result so later requests replay the same prefix. @@ -1884,10 +1907,15 @@ async def convert_url_images_to_base64(form_data, user=None): MESSAGE_REPLAY_KEYS = ('id', 'role', 'content', 'output', 'files', 'contextSummary', 'usage', 'model', 'meta') -async def load_messages_from_db(chat_id: str, message_id: str) -> Optional[list[dict]]: +async def load_messages_from_db( + chat_id: str, message_id: str, citation_source_ids: Optional[dict] = None +) -> Optional[list[dict]]: """ Load the message chain from DB up to message_id, keeping only fields needed to rebuild the LLM payload. + + When citation_source_ids is given, it is filled with the citation numbers + the chain's sources already use. """ messages_map = await Chats.get_messages_map_by_chat_id(chat_id) if not messages_map: @@ -1897,6 +1925,12 @@ async def load_messages_from_db(chat_id: str, message_id: str) -> Optional[list[ if not db_messages: return None + if citation_source_ids is not None: + for msg in db_messages: + for source in msg.get('sources') or []: + if isinstance(source, dict): + get_citation_ids(source, citation_source_ids) + for msg in db_messages: skills_create = (msg.get('meta') or {}).get('skills_create') # Replay the saved expansion unless the user edited the message. @@ -2100,7 +2134,9 @@ async def process_chat_payload(request, form_data, user, metadata, model): ) if is_saved_chat_id(chat_id) and user_message_id: - db_messages = await load_messages_from_db(chat_id, user_message_id) + # Earlier turns replay their ids, so this turn's sources continue that numbering. + metadata['citation_source_ids'] = {} + db_messages = await load_messages_from_db(chat_id, user_message_id, metadata['citation_source_ids']) if db_messages: # Continue: frontend sends assistant_message_id when continuing # an existing response. Load its content so the LLM sees prior output. @@ -2921,7 +2957,13 @@ async def process_chat_payload(request, form_data, user, metadata, model): # If context is not empty, insert it into the messages if sources and prompt: - form_data['messages'] = await apply_source_context_to_messages(request, form_data['messages'], sources, prompt) + form_data['messages'] = await apply_source_context_to_messages( + request, + form_data['messages'], + sources, + metadata.setdefault('citation_source_ids', {}), + prompt, + ) # If there are citations, add them to the data_items sources = [ @@ -3241,7 +3283,7 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message) return False event_emitter, event_caller = await get_event_emitter_and_caller(metadata) - citation_source_ids = {} + citation_source_ids = metadata.setdefault('citation_source_ids', {}) get_source_context( message.get('sources') or metadata.get('sources', []), citation_source_ids, include_content=False ) @@ -5798,7 +5840,7 @@ async def streaming_chat_response_handler(response, ctx): ) final_answer_requested = form_data.get('tool_choice') == 'none' stop_reason = None - citation_source_ids = {} + citation_source_ids = metadata.setdefault('citation_source_ids', {}) get_source_context( (message or {}).get('sources') or metadata.get('sources', []), citation_source_ids, diff --git a/src/lib/components/chat/Messages/Citations.svelte b/src/lib/components/chat/Messages/Citations.svelte index 59ce3e917d..8184117b07 100644 --- a/src/lib/components/chat/Messages/Citations.svelte +++ b/src/lib/components/chat/Messages/Citations.svelte @@ -2,6 +2,7 @@ import { getContext } from 'svelte'; import { embed, showTabs, showEmbeds } from '$lib/stores'; import { isValidHttpUrl } from '$lib/utils'; + import { getCitations } from '$lib/utils/citations'; import CitationModal from './Citations/CitationModal.svelte'; @@ -25,19 +26,9 @@ let selectedCitation: any = null; export const showSourceModal = (sourceId) => { - let index; - let suffix = null; - - if (typeof sourceId === 'string') { - const output = sourceId.split('#'); - index = parseInt(output[0]) - 1; - - if (output.length > 1) { - suffix = output[1]; - } - } else { - index = sourceId - 1; - } + // "2#page" and 2 both name citation number 2 + const number = typeof sourceId === 'string' ? parseInt(sourceId.split('#')[0]) : sourceId; + const index = citations.findIndex((citation) => citation.number === number); if (citations[index]) { console.log('Showing citation modal for:', citations[index]); @@ -132,46 +123,7 @@ } $: { - citations = sources.reduce((acc, source) => { - if (Object.keys(source).length === 0) { - return acc; - } - - source?.document?.forEach((document, index) => { - const metadata = source?.metadata?.[index]; - const distance = source?.distances?.[index]; - - // Within the same citation there could be multiple documents - const id = metadata?.source ?? source?.source?.id ?? 'N/A'; - let _source = source?.source; - - if (metadata?.name) { - _source = { ..._source, name: metadata.name }; - } - - if (id.startsWith('http://') || id.startsWith('https://')) { - _source = { ..._source, name: metadata?.external ? _source.name : id, url: id }; - } - - const existingSource = acc.find((item) => item.id === id); - - if (existingSource) { - existingSource.document.push(document); - existingSource.metadata.push(metadata); - if (distance !== undefined) existingSource.distances.push(distance); - } else { - acc.push({ - id: id, - source: _source, - document: [document], - metadata: metadata ? [metadata] : [], - distances: distance !== undefined ? [distance] : [] - }); - } - }); - - return acc; - }, []); + citations = getCitations(sources); console.log('citations', citations); showRelevance = calculateShowRelevance(citations); diff --git a/src/lib/components/chat/Messages/ContentRenderer.svelte b/src/lib/components/chat/Messages/ContentRenderer.svelte index 25eb934538..5359e82790 100644 --- a/src/lib/components/chat/Messages/ContentRenderer.svelte +++ b/src/lib/components/chat/Messages/ContentRenderer.svelte @@ -14,6 +14,7 @@ import { getOutputText } from './structuredOutput'; import FloatingButtons from '../ContentRenderer/FloatingButtons.svelte'; import { createMessagesList, replaceOutsideCode } from '$lib/utils'; + import { getCitations } from '$lib/utils/citations'; /** * Extracts all top-level
...
blocks from content, @@ -113,28 +114,11 @@ $: getSourceIds(sources); const getSourceIds = (sources) => { + // Titles by citation number; numbers are shared across the chat, so there can be gaps. const result = []; - const seenIds = new Set(); - for (const source of sources ?? []) { - for (let index = 0; index < (source.document ?? []).length; index++) { - if (model?.info?.meta?.capabilities?.citations == false) { - result.push('N/A'); - continue; - } - const metadata = source.metadata?.[index]; - const id = metadata?.source ?? source?.source?.id ?? 'N/A'; - if (seenIds.has(id)) { - continue; - } - seenIds.add(id); - if (metadata?.name) { - result.push(metadata.name); - } else if (id.startsWith('http://') || id.startsWith('https://')) { - result.push(id); - } else { - result.push(source?.source?.name ?? id); - } - } + for (const citation of getCitations(sources)) { + result[citation.number - 1] = + model?.info?.meta?.capabilities?.citations == false ? 'N/A' : citation.title; } sourceIds = result; }; diff --git a/src/lib/components/chat/Messages/ResponseMessage.svelte b/src/lib/components/chat/Messages/ResponseMessage.svelte index 08fccec758..1b3ea24b01 100644 --- a/src/lib/components/chat/Messages/ResponseMessage.svelte +++ b/src/lib/components/chat/Messages/ResponseMessage.svelte @@ -37,6 +37,7 @@ import { WEBUI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants'; import { resolveLocalizedModelName } from '$lib/utils/localizedContent'; import { isTemporaryChatId } from '$lib/utils/chatId'; + import { getCarriedSources } from '$lib/utils/citations'; import equal from 'fast-deep-equal'; import Name from './Name.svelte'; @@ -161,6 +162,14 @@ } } + // The message's own sources, plus any from earlier turns that it cites. + const getCitationSources = (message: any) => { + const sources = message?.sources ?? message?.citations; + const carriedSources = getCarriedSources(history.messages, message); + return carriedSources.length > 0 ? [...(sources ?? []), ...carriedSources] : sources; + }; + $: citationSources = getCitationSources(message); + export let siblings; export let setInputText: Function = () => {}; @@ -944,7 +953,7 @@ messageId={message.id} content={message.content ?? ''} output={message.output} - sources={message.sources} + sources={citationSources} floatingButtons={message?.done && !readOnly && ($settings?.showFloatingActionButtons ?? true)} @@ -1011,12 +1020,12 @@ {/if} - {#if (message?.sources || message?.citations) && (model?.info?.meta?.capabilities?.citations ?? true)} + {#if citationSources && (model?.info?.meta?.capabilities?.citations ?? true)} {/if} diff --git a/src/lib/utils/citations.ts b/src/lib/utils/citations.ts new file mode 100644 index 0000000000..bef1d9ca33 --- /dev/null +++ b/src/lib/utils/citations.ts @@ -0,0 +1,150 @@ +// A cited document is identified by its metadata source, falling back to the source id. +const getDocumentId = (source: any, index: number): string => + source?.metadata?.[index]?.source ?? source?.source?.id ?? 'N/A'; + +const getSavedNumber = (source: any, index: number): number | null => { + const number = source?.citation_ids?.[index]; + return Number.isInteger(number) && number > 0 ? number : null; +}; + +/** + * Groups a message's sources into one citation per document, each with the number the + * model cites it by: the number saved with the source, or its position for sources saved + * before numbers were shared across the chat. + */ +export const getCitations = (sources: any[] | null | undefined) => { + const citations: any[] = []; + + for (const source of sources ?? []) { + if (!source || Object.keys(source).length === 0) { + continue; + } + + (source.document ?? []).forEach((document: string, index: number) => { + const metadata = source.metadata?.[index]; + const distance = source.distances?.[index]; + const id = getDocumentId(source, index); + + const existing = citations.find((citation) => citation.id === id); + if (existing) { + existing.document.push(document); + existing.metadata.push(metadata); + if (distance !== undefined) existing.distances.push(distance); + return; + } + + const isUrl = id.startsWith('http://') || id.startsWith('https://'); + let _source = source.source; + if (metadata?.name) { + _source = { ..._source, name: metadata.name }; + } + if (isUrl) { + _source = { ..._source, name: metadata?.external ? _source?.name : id, url: id }; + } + + citations.push({ + id, + number: getSavedNumber(source, index) ?? citations.length + 1, + title: metadata?.name || (isUrl ? id : (source.source?.name ?? id)), + source: _source, + document: [document], + metadata: metadata ? [metadata] : [], + distances: distance !== undefined ? [distance] : [] + }); + }); + } + + return citations; +}; + +// [1], [1, 2] or [1#page]; not a link label like [1](url) +const CITATION_PATTERN = /\[(\d+(?:#[^,\]\s]+)?(?:,\s*\d+(?:#[^,\]\s]+)?)*)\](?!\()/g; + +const getCitedNumbers = (content: string) => { + const numbers = new Set(); + for (const segment of content.split(/(```[\s\S]*?```|`[\s\S]*?`)/)) { + if (segment.startsWith('`')) { + continue; + } + for (const match of segment.matchAll(CITATION_PATTERN)) { + for (const part of match[1].split(',')) { + numbers.add(parseInt(part, 10)); + } + } + } + return numbers; +}; + +/** + * Sources from earlier turns that a message cites without having them itself. The model is + * shown earlier tool results again, so it can cite their sources without fetching them anew. + */ +export const getCarriedSources = ( + messages: Record | null | undefined, + message: any +) => { + const content = message?.content; + if (typeof content !== 'string' || !content.includes('[')) { + return []; + } + + const cited = getCitedNumbers(content); + for (const citation of getCitations(message.sources ?? message.citations)) { + cited.delete(citation.number); + } + if (cited.size === 0) { + return []; + } + + const ancestors: any[] = []; + const visited = new Set(); + let parentId = message.parentId; + while (parentId && messages?.[parentId] && !visited.has(parentId)) { + visited.add(parentId); + ancestors.push(messages[parentId]); + parentId = messages[parentId].parentId; + } + ancestors.reverse(); + + // Number the chain the way the backend does: a saved number wins, anything else takes the next. + const numbers = new Map(); + const carried = new Map(); + for (const ancestor of ancestors) { + const found = new Map(); + for (const source of ancestor.sources ?? []) { + (source?.document ?? []).forEach((document: string, index: number) => { + const id = getDocumentId(source, index); + const saved = getSavedNumber(source, index); + if (saved) { + numbers.set(id, saved); + } else if (!numbers.has(id)) { + numbers.set(id, Math.max(0, ...numbers.values()) + 1); + } + + const number = numbers.get(id) as number; + if (!cited.has(number)) { + return; + } + + const metadata = source.metadata?.[index]; + const distance = source.distances?.[index]; + found.set(number, [ + ...(found.get(number) ?? []), + { + source: source.source, + document: [document], + metadata: metadata ? [metadata] : [], + distances: distance !== undefined ? [distance] : [], + citation_ids: [number] + } + ]); + }); + } + // When several turns hold a source, the latest is the copy the model saw last. + for (const [number, sources] of found) { + carried.set(number, sources); + } + } + + return [...carried.values()].flat(); +};