From 4d49c6d950a25cbe935fc2128171117c1d04aeef Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 26 Nov 2026 21:25:16 +0400 Subject: [PATCH] refac --- backend/open_webui/retrieval/external.py | 52 +++++++++++++++-- backend/open_webui/routers/knowledge.py | 2 + .../admin/Settings/ExternalKnowledge.svelte | 57 ++++++++++++++++++- src/lib/i18n/locales/ar-BH/translation.json | 2 + src/lib/i18n/locales/ar/translation.json | 2 + src/lib/i18n/locales/az-AZ/translation.json | 2 + src/lib/i18n/locales/bg-BG/translation.json | 2 + src/lib/i18n/locales/bn-BD/translation.json | 2 + src/lib/i18n/locales/bo-TB/translation.json | 2 + src/lib/i18n/locales/bs-BA/translation.json | 2 + src/lib/i18n/locales/ca-ES/translation.json | 2 + src/lib/i18n/locales/ceb-PH/translation.json | 2 + src/lib/i18n/locales/cs-CZ/translation.json | 2 + src/lib/i18n/locales/da-DK/translation.json | 2 + src/lib/i18n/locales/de-DE/translation.json | 2 + src/lib/i18n/locales/dg-DG/translation.json | 2 + src/lib/i18n/locales/el-GR/translation.json | 2 + src/lib/i18n/locales/en-GB/translation.json | 2 + src/lib/i18n/locales/en-US/translation.json | 2 + src/lib/i18n/locales/es-ES/translation.json | 2 + src/lib/i18n/locales/et-EE/translation.json | 2 + src/lib/i18n/locales/eu-ES/translation.json | 2 + src/lib/i18n/locales/fa-IR/translation.json | 2 + src/lib/i18n/locales/fi-FI/translation.json | 2 + src/lib/i18n/locales/fil-PH/translation.json | 2 + src/lib/i18n/locales/fo-FO/translation.json | 2 + src/lib/i18n/locales/fr-CA/translation.json | 2 + src/lib/i18n/locales/fr-FR/translation.json | 2 + src/lib/i18n/locales/gl-ES/translation.json | 2 + src/lib/i18n/locales/he-IL/translation.json | 2 + src/lib/i18n/locales/hi-IN/translation.json | 2 + src/lib/i18n/locales/hr-HR/translation.json | 2 + src/lib/i18n/locales/hu-HU/translation.json | 2 + src/lib/i18n/locales/id-ID/translation.json | 2 + src/lib/i18n/locales/ie-GA/translation.json | 2 + src/lib/i18n/locales/it-IT/translation.json | 2 + src/lib/i18n/locales/ja-JP/translation.json | 2 + src/lib/i18n/locales/ka-GE/translation.json | 2 + src/lib/i18n/locales/kab-DZ/translation.json | 2 + src/lib/i18n/locales/ko-KR/translation.json | 2 + src/lib/i18n/locales/lt-LT/translation.json | 2 + src/lib/i18n/locales/lv-LV/translation.json | 2 + src/lib/i18n/locales/ms-MY/translation.json | 2 + src/lib/i18n/locales/nb-NO/translation.json | 2 + src/lib/i18n/locales/nl-NL/translation.json | 2 + src/lib/i18n/locales/pa-IN/translation.json | 2 + src/lib/i18n/locales/pl-PL/translation.json | 2 + src/lib/i18n/locales/pt-BR/translation.json | 2 + src/lib/i18n/locales/pt-PT/translation.json | 2 + src/lib/i18n/locales/ro-RO/translation.json | 2 + src/lib/i18n/locales/ru-RU/translation.json | 2 + src/lib/i18n/locales/sk-SK/translation.json | 2 + src/lib/i18n/locales/sl-SI/translation.json | 2 + src/lib/i18n/locales/sr-RS/translation.json | 2 + src/lib/i18n/locales/sv-SE/translation.json | 2 + src/lib/i18n/locales/ta-IN/translation.json | 2 + src/lib/i18n/locales/th-TH/translation.json | 2 + src/lib/i18n/locales/tk-TM/translation.json | 2 + src/lib/i18n/locales/tr-TR/translation.json | 2 + src/lib/i18n/locales/ug-CN/translation.json | 2 + src/lib/i18n/locales/uk-UA/translation.json | 2 + src/lib/i18n/locales/ur-PK/translation.json | 2 + .../i18n/locales/uz-Cyrl-UZ/translation.json | 2 + .../i18n/locales/uz-Latn-UZ/translation.json | 2 + src/lib/i18n/locales/vi-VN/translation.json | 2 + src/lib/i18n/locales/zh-CN/translation.json | 2 + src/lib/i18n/locales/zh-TW/translation.json | 2 + 67 files changed, 232 insertions(+), 7 deletions(-) diff --git a/backend/open_webui/retrieval/external.py b/backend/open_webui/retrieval/external.py index c93770d841..76910d0987 100644 --- a/backend/open_webui/retrieval/external.py +++ b/backend/open_webui/retrieval/external.py @@ -583,6 +583,33 @@ async def list_virtual_knowledge(user_id: Optional[str] = None, query: Optional[ return knowledge +async def _rerank(request, query: str, chunks: list[dict], embedding_function, user=None) -> list[dict]: + """Rescore chunks with the configured reranker, keeping the top TOP_K_RERANKER above RELEVANCE_THRESHOLD.""" + from langchain_core.documents import Document + from open_webui.retrieval.utils import RerankCompressor + + if not chunks: + return [] + + config = await Config.get_many('rag.top_k_reranker', 'rag.relevance_threshold') + reranking_function = getattr(request.app.state, 'RERANKING_FUNCTION', None) + compressor = RerankCompressor( + embedding_function=embedding_function, + top_n=config.get('rag.top_k_reranker'), + reranking_function=( + (lambda query, documents: reranking_function(query, documents, user=user)) if reranking_function else None + ), + r_score=config.get('rag.relevance_threshold'), + ) + documents = await compressor.acompress_documents( + [Document(page_content=chunk['content'], metadata=chunk['metadata']) for chunk in chunks], query + ) + return [ + {'content': doc.page_content, 'metadata': doc.metadata, 'distance': doc.metadata.get('score')} + for doc in documents + ] + + async def retrieve_external_knowledge( request, knowledge: KnowledgeModel, @@ -632,13 +659,26 @@ async def retrieve_external_knowledge_for_connection( *(retrieve(connection, auth_config, knowledge, query, count, embedding_function) for query in queries) ) - # Score direction differs per provider and metric, so merge by rank + if (connection.get('config') or {}).get('rerank'): + query_chunks = await asyncio.gather( + *( + _rerank(request, query, query_result, embedding_function, user) + for query, query_result in zip(queries, query_chunks) + ) + ) + # Reranker scores share one scale, so merge by score like internal knowledge. + merged = sorted( + (chunk for result in query_chunks for chunk in result), key=lambda c: c['distance'], reverse=True + ) + else: + # Score direction differs per provider and metric, so merge by rank + merged = (chunk for chunks_at_rank in zip_longest(*query_chunks) for chunk in chunks_at_rank if chunk) + seen_contents = set() - for chunks_at_rank in zip_longest(*query_chunks): - for chunk in chunks_at_rank: - if chunk and chunk['content'] not in seen_contents: - seen_contents.add(chunk['content']) - chunks.append(chunk) + for chunk in merged: + if chunk['content'] not in seen_contents: + seen_contents.add(chunk['content']) + chunks.append(chunk) chunks = chunks[:count] log.info( diff --git a/backend/open_webui/routers/knowledge.py b/backend/open_webui/routers/knowledge.py index 651785b518..6fbc24b30b 100644 --- a/backend/open_webui/routers/knowledge.py +++ b/backend/open_webui/routers/knowledge.py @@ -598,6 +598,8 @@ def _get_external_connection_provider_and_config(form_data: ExternalKnowledgeCon if provider == 'milvus': allowed_config_keys.add('db_name') normalized = {key: value for key, value in config.items() if key in allowed_config_keys} + # Reranks results with the configured reranker and applies RELEVANCE_THRESHOLD. + normalized['rerank'] = config.get('rerank') is True # Like model_ids on provider connections: a store_ids list (empty means all) lists the stores as # knowledge bases, readable by whoever access_grants allows. diff --git a/src/lib/components/admin/Settings/ExternalKnowledge.svelte b/src/lib/components/admin/Settings/ExternalKnowledge.svelte index 7885bc2339..394b7ba955 100644 --- a/src/lib/components/admin/Settings/ExternalKnowledge.svelte +++ b/src/lib/components/admin/Settings/ExternalKnowledge.svelte @@ -74,6 +74,7 @@ let storeIdInput = ''; // Save a connection whose stores are listed as knowledge bases, live, instead of one knowledge base. let listStores = false; + let showAdvanced = false; let creating = false; let showSourceModal = false; let connections: ExternalKnowledgeConnection[] = []; @@ -102,6 +103,7 @@ documentIdField: 'id', tableName: 'document_chunk', collectionField: 'collection_name', + rerank: false, testQuery: '' }; @@ -153,6 +155,7 @@ timeout: 30, dbName: '', sourceName: '', + rerank: false, testQuery: '', ...schemaDefaults(DEFAULT_PROVIDER) }; @@ -162,6 +165,7 @@ storeIds = []; storeIdInput = ''; listStores = false; + showAdvanced = false; editingItem = null; editingConnection = null; }; @@ -175,10 +179,12 @@ name: connection.name ?? '', provider: connection.provider, endpoint: connection.endpoint ?? '', - timeout: connection.config?.timeout ?? 30 + timeout: connection.config?.timeout ?? 30, + rerank: connection.config?.rerank === true }; storeIds = connection.config?.store_ids ?? []; accessGrants = structuredClone(connection.config?.access_grants ?? []); + showAdvanced = sourceForm.rerank; showSourceModal = true; }; @@ -210,6 +216,7 @@ timeout: connection.config?.timeout ?? 30, dbName: connection.config?.db_name ?? '', sourceName: source?.name ?? '', + rerank: connection.config?.rerank === true, testQuery: '', contentField: sourceConfig.content_field ?? defaults.contentField, vectorField: sourceConfig.vector_field ?? defaults.vectorField, @@ -225,6 +232,7 @@ .map((id: string) => id.trim()) .filter(Boolean); accessGrants = structuredClone(item.access_grants ?? []); + showAdvanced = sourceForm.rerank; showSourceModal = true; }; @@ -289,6 +297,7 @@ : {}, config: { timeout: Number(sourceForm.timeout) || 30, + rerank: sourceForm.rerank, ...(sourceForm.provider === 'milvus' && sourceForm.dbName ? { db_name: sourceForm.dbName } : {}) @@ -1059,6 +1068,52 @@ {/if} +
+ +
+ + {#if showAdvanced} +
+ + + + +
+ {/if} +