mirror of
https://github.com/open-webui/open-webui.git
synced 2026-12-04 00:08:54 +00:00
refac
This commit is contained in:
1 parent
9ab9c59a5f
commit
57c955a033
10 files changed
+96
-33
No files matched your search
+4
-2
@@ -38,9 +38,11 @@ RAG_TOP_K=10
|
||||
RAG_TOP_K_RERANKER=10
|
||||
# Zero disables relevance score filtering.
|
||||
RAG_RELEVANCE_THRESHOLD=0.0
|
||||
# Always include full extracted text up to this character count per uploaded file.
|
||||
# Always include full extracted text up to this size per uploaded file.
|
||||
# Only larger attachments switch to retrieval; this never truncates text. Set to 0 to always use retrieval.
|
||||
RAG_FULL_TEXT_CHAR_THRESHOLD=50000
|
||||
RAG_FULL_TEXT_THRESHOLD=50000
|
||||
# Leave empty to measure in characters, or set to token to count tokens with TIKTOKEN_ENCODING_NAME.
|
||||
RAG_FULL_TEXT_THRESHOLD_TYPE=
|
||||
|
||||
# Default character chunk size approximates MiniLM's 256-token window at 4 chars/token.
|
||||
# This is an estimate, not a tokenizer-enforced limit.
|
||||
|
||||
@@ -964,15 +964,19 @@ ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS = (
|
||||
)
|
||||
|
||||
RAG_FULL_CONTEXT = os.getenv('RAG_FULL_CONTEXT', 'False').lower() == 'true'
|
||||
RAG_FULL_TEXT_CHAR_THRESHOLD = max(
|
||||
RAG_FULL_TEXT_THRESHOLD = max(
|
||||
0,
|
||||
int(
|
||||
os.getenv(
|
||||
'RAG_FULL_TEXT_CHAR_THRESHOLD',
|
||||
os.getenv('RAG_RETRIEVAL_CHAR_THRESHOLD', os.getenv('RAG_FULL_CONTEXT_CHAR_THRESHOLD', '50000')),
|
||||
'RAG_FULL_TEXT_THRESHOLD',
|
||||
os.getenv(
|
||||
'RAG_FULL_TEXT_CHAR_THRESHOLD',
|
||||
os.getenv('RAG_RETRIEVAL_CHAR_THRESHOLD', os.getenv('RAG_FULL_CONTEXT_CHAR_THRESHOLD', '50000')),
|
||||
),
|
||||
)
|
||||
),
|
||||
)
|
||||
RAG_FULL_TEXT_THRESHOLD_TYPE = os.getenv('RAG_FULL_TEXT_THRESHOLD_TYPE', '')
|
||||
|
||||
RAG_FILE_MAX_COUNT = int(os.getenv('RAG_FILE_MAX_COUNT')) if os.getenv('RAG_FILE_MAX_COUNT') else None
|
||||
KNOWLEDGE_MAX_UPLOAD_COUNT = (
|
||||
@@ -3045,7 +3049,8 @@ DEFAULT_CONFIG = {
|
||||
'rag.enable_hybrid_search_enriched_texts': ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS,
|
||||
'rag.full_context': RAG_FULL_CONTEXT,
|
||||
# Retain the stored key so renaming the setting preserves saved thresholds.
|
||||
'rag.full_context_char_threshold': RAG_FULL_TEXT_CHAR_THRESHOLD,
|
||||
'rag.full_context_char_threshold': RAG_FULL_TEXT_THRESHOLD,
|
||||
'rag.full_text_threshold_type': RAG_FULL_TEXT_THRESHOLD_TYPE,
|
||||
'rag.file.max_count': RAG_FILE_MAX_COUNT,
|
||||
'knowledge.max_upload_count': KNOWLEDGE_MAX_UPLOAD_COUNT,
|
||||
'knowledge.max_file_count': KNOWLEDGE_MAX_FILE_COUNT,
|
||||
|
||||
@@ -2482,6 +2482,7 @@ async def get_app_config(request: Request):
|
||||
'rag.full_context',
|
||||
'rag.bypass_embedding_and_retrieval',
|
||||
'rag.full_context_char_threshold',
|
||||
'rag.full_text_threshold_type',
|
||||
'file.image_compression_width',
|
||||
'file.image_compression_height',
|
||||
'user.permissions',
|
||||
@@ -2622,7 +2623,8 @@ async def get_app_config(request: Request):
|
||||
'full_context': bool(
|
||||
config.get('rag.full_context') or config.get('rag.bypass_embedding_and_retrieval')
|
||||
),
|
||||
'full_text_char_threshold': config.get('rag.full_context_char_threshold'),
|
||||
'full_text_threshold': config.get('rag.full_context_char_threshold'),
|
||||
'full_text_threshold_type': config.get('rag.full_text_threshold_type'),
|
||||
'image_compression': {
|
||||
'width': config.get('file.image_compression_width'),
|
||||
'height': config.get('file.image_compression_height'),
|
||||
|
||||
@@ -12,6 +12,7 @@ from urllib.parse import quote
|
||||
import aiohttp
|
||||
import numpy as np
|
||||
import requests
|
||||
import tiktoken
|
||||
from fastapi import HTTPException
|
||||
from langchain_classic.retrievers import (
|
||||
ContextualCompressionRetriever,
|
||||
@@ -1380,6 +1381,17 @@ def filter_source_metadata(metadata: dict) -> dict:
|
||||
return result
|
||||
|
||||
|
||||
TIKTOKEN_DISALLOWED_SPECIAL = ()
|
||||
|
||||
|
||||
def is_full_text(content: str, config: dict) -> bool:
|
||||
threshold = config.get('rag.full_context_char_threshold') or 0
|
||||
if threshold and config.get('rag.full_text_threshold_type') == 'token':
|
||||
encoding = tiktoken.get_encoding(config['rag.tiktoken_encoding_name'])
|
||||
return 0 < len(encoding.encode(content, disallowed_special=TIKTOKEN_DISALLOWED_SPECIAL)) <= threshold
|
||||
return 0 < len(content) <= threshold
|
||||
|
||||
|
||||
async def get_sources_from_items(
|
||||
request,
|
||||
items,
|
||||
@@ -1396,9 +1408,13 @@ async def get_sources_from_items(
|
||||
):
|
||||
log.debug('items: %s %s %s %s %s', items, queries, embedding_function, reranking_function, full_context)
|
||||
|
||||
context_config = await Config.get_many('rag.bypass_embedding_and_retrieval', 'rag.full_context_char_threshold')
|
||||
context_config = await Config.get_many(
|
||||
'rag.bypass_embedding_and_retrieval',
|
||||
'rag.full_context_char_threshold',
|
||||
'rag.full_text_threshold_type',
|
||||
'rag.tiktoken_encoding_name',
|
||||
)
|
||||
bypass_embedding_and_retrieval = context_config.get('rag.bypass_embedding_and_retrieval')
|
||||
char_threshold = context_config.get('rag.full_context_char_threshold') or 0
|
||||
extracted_collections = []
|
||||
query_results = []
|
||||
folder_items = set()
|
||||
@@ -1428,7 +1444,7 @@ async def get_sources_from_items(
|
||||
# Used during temporary chat file uploads or web page & youtube attachements
|
||||
|
||||
content = (item.get('file') or {}).get('data', {}).get('content') or ''
|
||||
if item.get('context') == 'full' or (char_threshold > 0 and 0 < len(content) <= char_threshold):
|
||||
if item.get('context') == 'full' or await asyncio.to_thread(is_full_text, content, context_config):
|
||||
if item.get('file'):
|
||||
# if item has file data, use it
|
||||
query_result = {
|
||||
@@ -1577,7 +1593,7 @@ async def get_sources_from_items(
|
||||
)
|
||||
):
|
||||
content = (file_object.data or {}).get('content') or '' if file_object else ''
|
||||
if char_threshold > 0 and 0 < len(content) <= char_threshold:
|
||||
if await asyncio.to_thread(is_full_text, content, context_config):
|
||||
query_result = {
|
||||
'documents': [[content]],
|
||||
'metadatas': [
|
||||
|
||||
@@ -39,13 +39,13 @@ from open_webui.models.config import Config
|
||||
from open_webui.models.files import (
|
||||
FileForm,
|
||||
FileListResponse,
|
||||
FileModel,
|
||||
FileModelResponse,
|
||||
Files,
|
||||
)
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.knowledge import Knowledges
|
||||
from open_webui.models.users import Users
|
||||
from open_webui.retrieval.utils import is_full_text
|
||||
from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT
|
||||
from open_webui.routers.audio import transcribe
|
||||
from open_webui.routers.knowledge import check_knowledge_upload_limits
|
||||
@@ -641,7 +641,7 @@ async def delete_all_files(
|
||||
# Get File By Id
|
||||
|
||||
|
||||
@router.get('/{id}', response_model=Optional[FileModel])
|
||||
@router.get('/{id}', response_model=Optional[dict])
|
||||
async def get_file_by_id(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
file = await Files.get_file_by_id(id, db=db)
|
||||
|
||||
@@ -652,7 +652,12 @@ async def get_file_by_id(id: str, user=Depends(get_verified_user), db: AsyncSess
|
||||
)
|
||||
|
||||
if file.user_id == user.id or user.role == 'admin' or await has_access_to_file(id, 'read', user, db=db):
|
||||
return file
|
||||
config = await Config.get_many(
|
||||
'rag.full_context_char_threshold', 'rag.full_text_threshold_type', 'rag.tiktoken_encoding_name', db=db
|
||||
)
|
||||
content = (file.data or {}).get('content') or ''
|
||||
full_text = await asyncio.to_thread(is_full_text, content, config)
|
||||
return {**file.model_dump(), 'full_text': full_text}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
|
||||
@@ -69,6 +69,7 @@ from open_webui.models.users import UserModel
|
||||
# Document loaders
|
||||
from open_webui.retrieval.loaders.youtube import YoutubeLoader, YoutubeTranscriptError
|
||||
from open_webui.retrieval.utils import (
|
||||
TIKTOKEN_DISALLOWED_SPECIAL,
|
||||
build_loader_from_config,
|
||||
filter_accessible_collections,
|
||||
get_content_from_url,
|
||||
@@ -134,8 +135,6 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
TIKTOKEN_DISALLOWED_SPECIAL = ()
|
||||
|
||||
# Utility functions
|
||||
# Let us find what is true among the many voices,
|
||||
# and let us not mistake the loudest answer for the wisest.
|
||||
@@ -352,7 +351,8 @@ RETRIEVAL_CONFIG_KEYS = {
|
||||
'RAG_EXTERNAL_RERANKER_TIMEOUT': 'rag.external_reranker_timeout',
|
||||
'RAG_EXTERNAL_RERANKER_URL': 'rag.external_reranker_url',
|
||||
'RAG_FULL_CONTEXT': 'rag.full_context',
|
||||
'RAG_FULL_TEXT_CHAR_THRESHOLD': 'rag.full_context_char_threshold',
|
||||
'RAG_FULL_TEXT_THRESHOLD': 'rag.full_context_char_threshold',
|
||||
'RAG_FULL_TEXT_THRESHOLD_TYPE': 'rag.full_text_threshold_type',
|
||||
'RAG_OLLAMA_API_KEY': 'rag.ollama.api_key',
|
||||
'RAG_OLLAMA_BASE_URL': 'rag.ollama.base_url',
|
||||
'RAG_OPENAI_API_BASE_URL': 'rag.openai.api_base_url',
|
||||
@@ -618,7 +618,8 @@ async def get_rag_config(request: Request, user=Depends(get_admin_user)):
|
||||
'TOP_K': config['rag.top_k'],
|
||||
'BYPASS_EMBEDDING_AND_RETRIEVAL': config['rag.bypass_embedding_and_retrieval'],
|
||||
'RAG_FULL_CONTEXT': config['rag.full_context'],
|
||||
'RAG_FULL_TEXT_CHAR_THRESHOLD': config['rag.full_context_char_threshold'],
|
||||
'RAG_FULL_TEXT_THRESHOLD': config['rag.full_context_char_threshold'],
|
||||
'RAG_FULL_TEXT_THRESHOLD_TYPE': config['rag.full_text_threshold_type'],
|
||||
# Hybrid search settings
|
||||
'ENABLE_RAG_HYBRID_SEARCH': config['rag.enable_hybrid_search'],
|
||||
'ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS': config['rag.enable_hybrid_search_enriched_texts'],
|
||||
@@ -864,7 +865,8 @@ class ConfigForm(BaseModel):
|
||||
TOP_K: int | None = None
|
||||
BYPASS_EMBEDDING_AND_RETRIEVAL: bool | None = None
|
||||
RAG_FULL_CONTEXT: bool | None = None
|
||||
RAG_FULL_TEXT_CHAR_THRESHOLD: int | None = Field(default=None, ge=0)
|
||||
RAG_FULL_TEXT_THRESHOLD: int | None = Field(default=None, ge=0)
|
||||
RAG_FULL_TEXT_THRESHOLD_TYPE: str | None = None
|
||||
|
||||
# Hybrid search settings
|
||||
ENABLE_RAG_HYBRID_SEARCH: bool | None = None
|
||||
@@ -1087,7 +1089,8 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend
|
||||
'TOP_K': config['rag.top_k'],
|
||||
'BYPASS_EMBEDDING_AND_RETRIEVAL': config['rag.bypass_embedding_and_retrieval'],
|
||||
'RAG_FULL_CONTEXT': config['rag.full_context'],
|
||||
'RAG_FULL_TEXT_CHAR_THRESHOLD': config['rag.full_context_char_threshold'],
|
||||
'RAG_FULL_TEXT_THRESHOLD': config['rag.full_context_char_threshold'],
|
||||
'RAG_FULL_TEXT_THRESHOLD_TYPE': config['rag.full_text_threshold_type'],
|
||||
# Hybrid search settings
|
||||
'ENABLE_RAG_HYBRID_SEARCH': config['rag.enable_hybrid_search'],
|
||||
'TOP_K_RERANKER': config['rag.top_k_reranker'],
|
||||
|
||||
@@ -171,7 +171,11 @@
|
||||
),
|
||||
RAG_EMBEDDING_QUERY_PREFIX: $i18n.t('settings.admin.documents.embeddingQueryPrefix.label'),
|
||||
RAG_EMBEDDING_CONTENT_PREFIX: $i18n.t('settings.admin.documents.embeddingContentPrefix.label'),
|
||||
RAG_FULL_TEXT_CHAR_THRESHOLD: $i18n.t('settings.admin.documents.fullTextCharThreshold.label'),
|
||||
RAG_FULL_TEXT_THRESHOLD_TYPE: $i18n.t('settings.admin.documents.fullTextThresholdType.label'),
|
||||
RAG_FULL_TEXT_THRESHOLD:
|
||||
RAGConfig?.RAG_FULL_TEXT_THRESHOLD_TYPE === 'token'
|
||||
? $i18n.t('settings.admin.documents.fullTextTokenThreshold.label')
|
||||
: $i18n.t('settings.admin.documents.fullTextCharThreshold.label'),
|
||||
RAG_FULL_CONTEXT: $i18n.t('settings.admin.documents.fullContextMode.label'),
|
||||
ENABLE_RAG_HYBRID_SEARCH: $i18n.t('settings.admin.documents.hybridSearch.label'),
|
||||
ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS: $i18n.t(
|
||||
@@ -1506,16 +1510,35 @@
|
||||
|
||||
<AdminSettingSection title={$i18n.t('settings.admin.documents.sections.retrieval.title')}>
|
||||
{#if !RAGConfig.BYPASS_EMBEDDING_AND_RETRIEVAL}
|
||||
<AdminSettingRow
|
||||
label={$i18n.t('settings.admin.documents.fullTextThresholdType.label')}
|
||||
description={$i18n.t('settings.admin.documents.fullTextThresholdType.description')}
|
||||
let:labelId
|
||||
>
|
||||
<SettingsSelect
|
||||
id={`${labelId}-control`}
|
||||
bind:value={RAGConfig.RAG_FULL_TEXT_THRESHOLD_TYPE}
|
||||
disabled={RAGConfig.RAG_FULL_CONTEXT}
|
||||
>
|
||||
<option value="">{$i18n.t('Default')} ({$i18n.t('Character')})</option>
|
||||
<option value="token">{$i18n.t('Token')} ({$i18n.t('Tiktoken')})</option>
|
||||
</SettingsSelect>
|
||||
</AdminSettingRow>
|
||||
|
||||
<AdminSettingField
|
||||
label={$i18n.t('settings.admin.documents.fullTextCharThreshold.label')}
|
||||
description={$i18n.t('settings.admin.documents.fullTextCharThreshold.description')}
|
||||
forId="full-text-char-threshold"
|
||||
label={RAGConfig.RAG_FULL_TEXT_THRESHOLD_TYPE === 'token'
|
||||
? $i18n.t('settings.admin.documents.fullTextTokenThreshold.label')
|
||||
: $i18n.t('settings.admin.documents.fullTextCharThreshold.label')}
|
||||
description={RAGConfig.RAG_FULL_TEXT_THRESHOLD_TYPE === 'token'
|
||||
? $i18n.t('settings.admin.documents.fullTextTokenThreshold.description')
|
||||
: $i18n.t('settings.admin.documents.fullTextCharThreshold.description')}
|
||||
forId="full-text-threshold"
|
||||
>
|
||||
<input
|
||||
id="full-text-char-threshold"
|
||||
id="full-text-threshold"
|
||||
class={inputClass}
|
||||
type="number"
|
||||
bind:value={RAGConfig.RAG_FULL_TEXT_CHAR_THRESHOLD}
|
||||
bind:value={RAGConfig.RAG_FULL_TEXT_THRESHOLD}
|
||||
disabled={RAGConfig.RAG_FULL_CONTEXT}
|
||||
min="0"
|
||||
step="1"
|
||||
|
||||
@@ -187,7 +187,7 @@
|
||||
expandedContent = false;
|
||||
docxData = null;
|
||||
externalKnowledge = false;
|
||||
if ($config?.file?.full_text_char_threshold === undefined) {
|
||||
if ($config?.file?.full_text_threshold === undefined) {
|
||||
await getBackendConfig()
|
||||
.then((value) => config.set(value))
|
||||
.catch((error) => console.error('Error fetching file context settings:', error));
|
||||
@@ -238,15 +238,17 @@
|
||||
loadContent();
|
||||
}
|
||||
|
||||
$: fullTextCharThreshold = $config?.file?.full_text_char_threshold ?? 0;
|
||||
$: fullTextThreshold = $config?.file?.full_text_threshold ?? 0;
|
||||
$: contentLength = getCharacterCount(item?.file?.data?.content ?? '');
|
||||
$: automaticFullContent =
|
||||
!externalKnowledge &&
|
||||
(Boolean($config?.file?.full_context) ||
|
||||
((item?.type === 'file' || item?.type === 'text') &&
|
||||
fullTextCharThreshold > 0 &&
|
||||
// Files are measured by the backend, which can count tokens.
|
||||
(item?.type === 'file' && Boolean(item?.file?.full_text)) ||
|
||||
(item?.type === 'text' &&
|
||||
$config?.file?.full_text_threshold_type !== 'token' &&
|
||||
contentLength > 0 &&
|
||||
contentLength <= fullTextCharThreshold));
|
||||
contentLength <= fullTextThreshold));
|
||||
$: enableFullContent = automaticFullContent || item?.context === 'full';
|
||||
|
||||
onMount(() => {
|
||||
@@ -342,7 +344,7 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if edit && !loading && $config?.file?.full_text_char_threshold !== undefined}
|
||||
{#if edit && !loading && $config?.file?.full_text_threshold !== undefined}
|
||||
<div class=" self-end">
|
||||
<Tooltip
|
||||
content={automaticFullContent
|
||||
|
||||
@@ -3537,6 +3537,10 @@
|
||||
"settings.admin.documents.fullContextMode.label": "Always Use Full Text",
|
||||
"settings.admin.documents.fullTextCharThreshold.description": "Include the complete extracted text of each uploaded file up to this character count. Only larger files switch to retrieval; text is never truncated at this threshold. Set to 0 to always use retrieval. Explicit full-context selections still take priority.",
|
||||
"settings.admin.documents.fullTextCharThreshold.label": "Full Text Threshold (Characters)",
|
||||
"settings.admin.documents.fullTextThresholdType.description": "Choose how file size is measured.",
|
||||
"settings.admin.documents.fullTextThresholdType.label": "Full Text Threshold Type",
|
||||
"settings.admin.documents.fullTextTokenThreshold.description": "Include the complete extracted text of each uploaded file up to this token count. Only larger files switch to retrieval; text is never truncated at this threshold. Set to 0 to always use retrieval. Explicit full-context selections still take priority. Counts are approximate for models that use another tokenizer.",
|
||||
"settings.admin.documents.fullTextTokenThreshold.label": "Full Text Threshold (Tokens)",
|
||||
"settings.admin.documents.googleDrive.description": "Allow Google Drive as a document source.",
|
||||
"settings.admin.documents.googleDrive.label": "Google Drive",
|
||||
"settings.admin.documents.headers.description": "Additional JSON headers sent to the external document loader.",
|
||||
|
||||
@@ -421,7 +421,8 @@ type Config = {
|
||||
max_size?: number | null;
|
||||
max_count?: number | null;
|
||||
full_context?: boolean;
|
||||
full_text_char_threshold?: number;
|
||||
full_text_threshold?: number;
|
||||
full_text_threshold_type?: string;
|
||||
image_compression?: { width?: number | null; height?: number | null };
|
||||
};
|
||||
metadata?: {
|
||||
|
||||
Reference in new issue
Block a user