feat: implement parent-child chunking strategy for enhanced context management

- Added support for parent-child chunking in the knowledge base, allowing for a two-level chunking strategy that improves context retrieval.
- Introduced new configuration options for enabling parent-child chunking, including parent and child chunk sizes.
- Updated relevant components and services to handle parent chunk data, ensuring proper linking and retrieval of child chunks.
- Enhanced user interface elements to reflect the new chunking options and provide better user guidance.

These changes significantly improve the knowledge extraction process by providing richer context through hierarchical chunking.
This commit is contained in:
wizardchen
2026-03-04 20:35:10 +08:00
committed by lyingbug
parent 8399527022
commit b333499078
22 changed files with 1100 additions and 403 deletions
+3
View File
@@ -83,6 +83,9 @@ export interface KBModelConfigRequest {
chunkOverlap: number
separators: string[]
parserEngineRules?: { file_types: string[]; engine: string }[]
enableParentChild?: boolean
parentChunkSize?: number
childChunkSize?: number
}
multimodal: {
enabled: boolean
+132 -17
View File
@@ -4,8 +4,8 @@ import { marked } from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import mermaid from "mermaid";
import { onMounted, ref, nextTick, onUnmounted, onUpdated, watch } from "vue";
import { downKnowledgeDetails, deleteGeneratedQuestion } from "@/api/knowledge-base/index";
import { onMounted, ref, nextTick, onUnmounted, watch } from "vue";
import { downKnowledgeDetails, deleteGeneratedQuestion, getChunkByIdOnly } from "@/api/knowledge-base/index";
import { MessagePlugin, DialogPlugin } from "tdesign-vue-next";
import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security';
import { openMermaidFullscreen } from '@/utils/mermaidViewer';
@@ -267,24 +267,39 @@ const isMarkdownFile = (fileType?: string): boolean => {
const markdownTypes = ['md', 'markdown'];
return markdownTypes.includes(fileType.toLowerCase());
};
const runMarkdownPostRenderPipeline = async () => {
await nextTick();
const renderRoot = mdContentWrap.value as ParentNode;
await hydrateProtectedFileImages(renderRoot);
const images = renderRoot?.querySelectorAll?.('img.markdown-image') as NodeListOf<HTMLImageElement> | undefined;
if (images) {
images.forEach(async item => {
const isValid = await checkImage(item.src);
if (!isValid) {
item.remove();
}
})
}
// 渲染 Mermaid 图表
await renderMermaidDiagrams();
};
watch(() => props.details.md, (newVal) => {
nextTick(async () => {
const renderRoot = (doc as ParentNode) || mdContentWrap.value;
await hydrateProtectedFileImages(renderRoot);
const images = renderRoot?.querySelectorAll?.('img.markdown-image') as NodeListOf<HTMLImageElement> | undefined;
if (images) {
images.forEach(async item => {
const isValid = await checkImage(item.src);
if (!isValid) {
item.remove();
}
})
}
// 渲染 Mermaid 图表
await renderMermaidDiagrams();
})
runMarkdownPostRenderPipeline();
}, { immediate: true, deep: true })
watch(() => viewMode.value, (mode) => {
if ((mode === 'chunks' || mode === 'merged') && props.visible) {
runMarkdownPostRenderPipeline();
}
});
watch(() => props.visible, (visible) => {
if (visible && (viewMode.value === 'chunks' || viewMode.value === 'merged')) {
runMarkdownPostRenderPipeline();
}
});
// 渲染 Mermaid 图表的函数
const renderMermaidDiagrams = async () => {
try {
@@ -557,6 +572,50 @@ const isDeleting = (chunkIndex: number, questionId: string) => {
return deletingQuestion.value?.chunkIndex === chunkIndex && deletingQuestion.value?.questionId === questionId;
};
// 父 Chunk 上下文展开状态
const parentContextExpanded = ref<Set<number>>(new Set());
const parentContextCache = ref<Map<string, string>>(new Map());
const parentContextLoading = ref<Set<number>>(new Set());
const hasParentChunk = (item: any) => !!item?.parent_chunk_id;
const isParentExpanded = (index: number) => parentContextExpanded.value.has(index);
const toggleParentContext = async (item: any, index: number) => {
if (parentContextExpanded.value.has(index)) {
parentContextExpanded.value.delete(index);
parentContextExpanded.value = new Set(parentContextExpanded.value);
return;
}
const parentId = item.parent_chunk_id;
if (!parentContextCache.value.has(parentId)) {
parentContextLoading.value.add(index);
parentContextLoading.value = new Set(parentContextLoading.value);
try {
const result: any = await getChunkByIdOnly(parentId);
if (result.success && result.data) {
parentContextCache.value.set(parentId, result.data.content || '');
parentContextCache.value = new Map(parentContextCache.value);
}
} catch (err) {
MessagePlugin.error(t('knowledgeBase.parentContextLoadFailed') || '加载父上下文失败');
return;
} finally {
parentContextLoading.value.delete(index);
parentContextLoading.value = new Set(parentContextLoading.value);
}
}
parentContextExpanded.value.add(index);
parentContextExpanded.value = new Set(parentContextExpanded.value);
await runMarkdownPostRenderPipeline();
};
const getParentContent = (item: any) => {
return parentContextCache.value.get(item.parent_chunk_id) || '';
};
const downloadFile = () => {
downKnowledgeDetails(props.details.id)
.then((result) => {
@@ -703,6 +762,14 @@ const handleDetailsScroll = () => {
<div class="chunk-header">
<span class="chunk-index">{{ $t('knowledgeBase.segment') || '片段' }} {{ index + 1 }}</span>
<div class="chunk-header-right">
<t-tag
v-if="hasParentChunk(item)"
size="small"
theme="primary"
variant="light"
>
{{ $t('knowledgeBase.childChunk') || '子块' }}
</t-tag>
<t-tag
v-if="getGeneratedQuestions(item).length > 0"
size="small"
@@ -716,6 +783,18 @@ const handleDetailsScroll = () => {
</div>
<div class="md-content" v-html="processMarkdown(item.content)"></div>
<!-- 父 Chunk 上下文展开 -->
<div v-if="hasParentChunk(item)" class="parent-context-section">
<div class="parent-context-toggle" @click="toggleParentContext(item, index)">
<t-icon v-if="!parentContextLoading.has(index)" :name="isParentExpanded(index) ? 'chevron-down' : 'chevron-right'" size="14px" />
<t-loading v-else size="small" style="width: 14px; height: 14px;" />
<span>{{ $t('knowledgeBase.viewParentContext') || '查看父块上下文' }}</span>
</div>
<div v-show="isParentExpanded(index)" class="parent-context-content">
<div class="md-content" v-html="processMarkdown(getParentContent(item))"></div>
</div>
</div>
<!-- 生成的问题展示 -->
<div v-if="getGeneratedQuestions(item).length > 0" class="questions-section">
<div class="questions-toggle" @click="toggleQuestions(index)">
@@ -1058,6 +1137,42 @@ const handleDetailsScroll = () => {
}
}
// 父 Chunk 上下文样式
.parent-context-section {
margin-top: 10px;
padding-top: 8px;
border-top: 1px dashed #d0d5dd;
}
.parent-context-toggle {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
color: #07c05f;
font-size: 12px;
font-weight: 500;
padding: 4px 0;
transition: color 0.2s ease;
&:hover {
color: #07c05f;
}
}
.parent-context-content {
margin-top: 8px;
padding: 10px 12px;
background: #f0f5ff;
border-radius: 4px;
border-left: 3px solid #07c05f;
.md-content {
color: #4e5969;
font-size: 13px;
}
}
// 生成的问题样式
.questions-section {
margin-top: 12px;
+10 -1
View File
@@ -142,6 +142,9 @@ export default {
loadOriginalFailed: 'Failed to load original file content',
questions: 'Questions',
generatedQuestions: 'Generated Questions',
childChunk: 'Child Chunk',
viewParentContext: 'View Parent Context',
parentContextLoadFailed: 'Failed to load parent context',
confirmDeleteQuestion: 'Are you sure you want to delete this question? The corresponding vector index will also be removed.',
legacyQuestionCannotDelete: 'Legacy format questions cannot be deleted. Please regenerate questions.',
notInitialized: 'Knowledge base is not initialized. Please configure models in settings before uploading files',
@@ -1415,7 +1418,13 @@ export default {
semicolonCn: 'Chinese semicolon (;)',
semicolonEn: 'Semicolon (;)',
space: 'Space ( )'
}
},
parentChildLabel: 'Parent-Child Chunking',
parentChildDescription: 'Enable two-level parent-child chunking strategy. Large parent chunks provide context while small child chunks are used for vector matching.',
parentChunkSizeLabel: 'Parent Chunk Size',
parentChunkSizeDescription: 'Size of parent chunks that provide context (256-4096)',
childChunkSizeLabel: 'Child Chunk Size',
childChunkSizeDescription: 'Size of child chunks used for embedding matching (64-1024)'
},
advanced: {
title: 'Advanced Settings',
+9
View File
@@ -143,6 +143,9 @@ export default {
loadOriginalFailed: "원본 파일 내용 로드 실패",
questions: "질문",
generatedQuestions: "생성된 질문",
childChunk: "자식 청크",
viewParentContext: "부모 컨텍스트 보기",
parentContextLoadFailed: "부모 컨텍스트 로드 실패",
confirmDeleteQuestion:
"이 질문을 삭제하시겠습니까? 삭제 시 해당 벡터 인덱스도 함께 제거됩니다.",
legacyQuestionCannotDelete: "이전 형식의 질문은 삭제할 수 없습니다. 질문을 다시 생성하세요",
@@ -1860,6 +1863,12 @@ export default {
semicolonEn: "영어 세미콜론 (;)",
space: "공백 ( )",
},
parentChildLabel: "부모-자식 청킹",
parentChildDescription: "2단계 부모-자식 청킹 전략을 활성화합니다. 큰 부모 청크는 컨텍스트를 제공하고, 작은 자식 청크는 벡터 매칭에 사용됩니다.",
parentChunkSizeLabel: "부모 청크 크기",
parentChunkSizeDescription: "컨텍스트를 제공하는 부모 청크의 문자 수 (256-4096)",
childChunkSizeLabel: "자식 청크 크기",
childChunkSizeDescription: "임베딩 매칭에 사용되는 자식 청크의 문자 수 (64-1024)",
},
advanced: {
title: "고급 설정",
+10 -1
View File
@@ -118,6 +118,9 @@ export default {
loadOriginalFailed: 'Не удалось загрузить содержимое исходного файла',
questions: 'Вопросы',
generatedQuestions: 'Сгенерированные вопросы',
childChunk: 'Дочерний блок',
viewParentContext: 'Просмотр родительского контекста',
parentContextLoadFailed: 'Не удалось загрузить родительский контекст',
confirmDeleteQuestion: 'Вы уверены, что хотите удалить этот вопрос? Соответствующий векторный индекс также будет удален.',
legacyQuestionCannotDelete: 'Вопросы в устаревшем формате нельзя удалить. Пожалуйста, сгенерируйте вопросы заново.',
notInitialized: 'База знаний не инициализирована. Пожалуйста, настройте модели в разделе настроек перед загрузкой файлов',
@@ -1253,7 +1256,13 @@ export default {
semicolonCn: 'Китайская точка с запятой (;)',
semicolonEn: 'Точка с запятой (;)',
space: 'Пробел ( )'
}
},
parentChildLabel: 'Родительско-дочернее разбиение',
parentChildDescription: 'Включить двухуровневую стратегию разбиения. Большие родительские блоки обеспечивают контекст, а маленькие дочерние блоки используются для векторного поиска.',
parentChunkSizeLabel: 'Размер родительского блока',
parentChunkSizeDescription: 'Размер родительских блоков для контекста (256-4096)',
childChunkSizeLabel: 'Размер дочернего блока',
childChunkSizeDescription: 'Размер дочерних блоков для поиска по эмбеддингам (64-1024)'
},
advanced: {
title: 'Расширенные настройки',
+9
View File
@@ -141,6 +141,9 @@ export default {
loadOriginalFailed: "加载原文件内容失败",
questions: "问题",
generatedQuestions: "生成的问题",
childChunk: "子块",
viewParentContext: "查看父块上下文",
parentContextLoadFailed: "加载父上下文失败",
confirmDeleteQuestion: "确定要删除这个问题吗?删除后将同时移除对应的向量索引。",
legacyQuestionCannotDelete: "旧格式问题无法删除,请重新生成问题",
docActionUnsupported: "当前知识库类型不支持该操作",
@@ -1820,6 +1823,12 @@ export default {
semicolonEn: "英文分号 (;)",
space: "空格 ( )",
},
parentChildLabel: "父子分块",
parentChildDescription: "启用两级父子分块策略。大的父块提供上下文,小的子块用于向量匹配检索。",
parentChunkSizeLabel: "父块大小",
parentChunkSizeDescription: "提供上下文的父块字符数(256-4096)",
childChunkSizeLabel: "子块大小",
childChunkSizeDescription: "用于向量匹配的子块字符数(64-1024)",
},
advanced: {
title: "高级设置",
@@ -296,7 +296,10 @@ const initFormData = (type: 'document' | 'faq' = 'document') => {
chunkSize: 512,
chunkOverlap: 100,
separators: ['\n\n', '\n', '。', '!', '?', ';', ';'],
parserEngineRules: undefined as any
parserEngineRules: undefined as any,
enableParentChild: false,
parentChunkSize: 1024,
childChunkSize: 256
},
storageProvider: 'local' as string,
multimodalConfig: {
@@ -373,7 +376,10 @@ const loadKBData = async () => {
chunkSize: kb.chunking_config?.chunk_size || 512,
chunkOverlap: kb.chunking_config?.chunk_overlap || 100,
separators: kb.chunking_config?.separators || ['\n\n', '\n', '。', '!', '?', ';', ';'],
parserEngineRules: kb.chunking_config?.parser_engine_rules || undefined
parserEngineRules: kb.chunking_config?.parser_engine_rules || undefined,
enableParentChild: kb.chunking_config?.enable_parent_child || false,
parentChunkSize: kb.chunking_config?.parent_chunk_size || 1024,
childChunkSize: kb.chunking_config?.child_chunk_size || 256
},
storageProvider: (kb.storage_config?.provider || 'local') as string,
multimodalConfig: {
@@ -503,6 +509,9 @@ const buildSubmitData = () => {
chunk_overlap: formData.value.chunkingConfig.chunkOverlap,
separators: formData.value.chunkingConfig.separators,
enable_multimodal: formData.value.multimodalConfig.enabled,
enable_parent_child: formData.value.chunkingConfig.enableParentChild,
parent_chunk_size: formData.value.chunkingConfig.parentChunkSize,
child_chunk_size: formData.value.chunkingConfig.childChunkSize,
...(formData.value.chunkingConfig.parserEngineRules?.length
? { parser_engine_rules: formData.value.chunkingConfig.parserEngineRules }
: {})
@@ -603,7 +612,10 @@ const handleSubmit = async () => {
chunkSize: data.chunking_config.chunk_size,
chunkOverlap: data.chunking_config.chunk_overlap,
separators: data.chunking_config.separators,
parserEngineRules: data.chunking_config.parser_engine_rules || undefined
parserEngineRules: data.chunking_config.parser_engine_rules || undefined,
enableParentChild: data.chunking_config.enable_parent_child || false,
parentChunkSize: data.chunking_config.parent_chunk_size || 1024,
childChunkSize: data.chunking_config.child_chunk_size || 256
},
multimodal: {
enabled: !!data.vlm_config?.enabled
@@ -69,6 +69,64 @@
/>
</div>
</div>
<!-- Parent-Child Chunking -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('knowledgeEditor.chunking.parentChildLabel') }}</label>
<p class="desc">{{ $t('knowledgeEditor.chunking.parentChildDescription') }}</p>
</div>
<div class="setting-control">
<t-switch
v-model="localEnableParentChild"
@change="handleParentChildChange"
/>
</div>
</div>
<!-- Parent Chunk Size -->
<div v-if="localEnableParentChild" class="setting-row">
<div class="setting-info">
<label>{{ $t('knowledgeEditor.chunking.parentChunkSizeLabel') }}</label>
<p class="desc">{{ $t('knowledgeEditor.chunking.parentChunkSizeDescription') }}</p>
</div>
<div class="setting-control">
<div class="slider-container">
<t-slider
v-model="localParentChunkSize"
:min="256"
:max="4096"
:step="64"
:marks="{ 256: '256', 1024: '1024', 2048: '2048', 4096: '4096' }"
@change="handleParentChunkSizeChange"
style="width: 200px;"
/>
<span class="value-display">{{ localParentChunkSize }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
</div>
</div>
</div>
<!-- Child Chunk Size -->
<div v-if="localEnableParentChild" class="setting-row">
<div class="setting-info">
<label>{{ $t('knowledgeEditor.chunking.childChunkSizeLabel') }}</label>
<p class="desc">{{ $t('knowledgeEditor.chunking.childChunkSizeDescription') }}</p>
</div>
<div class="setting-control">
<div class="slider-container">
<t-slider
v-model="localChildChunkSize"
:min="64"
:max="1024"
:step="32"
:marks="{ 64: '64', 256: '256', 512: '512', 1024: '1024' }"
@change="handleChildChunkSizeChange"
style="width: 200px;"
/>
<span class="value-display">{{ localChildChunkSize }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
</div>
</div>
</div>
</div>
</div>
</template>
@@ -87,6 +145,9 @@ interface ChunkingConfig {
chunkOverlap: number
separators: string[]
parserEngineRules?: ParserEngineRule[]
enableParentChild: boolean
parentChunkSize: number
childChunkSize: number
}
interface Props {
@@ -102,6 +163,9 @@ const emit = defineEmits<{
const localChunkSize = ref(props.config.chunkSize)
const localChunkOverlap = ref(props.config.chunkOverlap)
const localSeparators = ref([...props.config.separators])
const localEnableParentChild = ref(props.config.enableParentChild ?? false)
const localParentChunkSize = ref(props.config.parentChunkSize || 1024)
const localChildChunkSize = ref(props.config.childChunkSize || 256)
const { t } = useI18n()
const separatorOptions = computed(() => [
@@ -119,18 +183,27 @@ watch(() => props.config, (newConfig) => {
localChunkSize.value = newConfig.chunkSize
localChunkOverlap.value = newConfig.chunkOverlap
localSeparators.value = [...newConfig.separators]
localEnableParentChild.value = newConfig.enableParentChild ?? false
localParentChunkSize.value = newConfig.parentChunkSize || 1024
localChildChunkSize.value = newConfig.childChunkSize || 256
}, { deep: true })
const handleChunkSizeChange = () => { emitUpdate() }
const handleChunkOverlapChange = () => { emitUpdate() }
const handleSeparatorsChange = () => { emitUpdate() }
const handleParentChildChange = () => { emitUpdate() }
const handleParentChunkSizeChange = () => { emitUpdate() }
const handleChildChunkSizeChange = () => { emitUpdate() }
const emitUpdate = () => {
emit('update:config', {
chunkSize: localChunkSize.value,
chunkOverlap: localChunkOverlap.value,
separators: localSeparators.value,
parserEngineRules: props.config.parserEngineRules
parserEngineRules: props.config.parserEngineRules,
enableParentChild: localEnableParentChild.value,
parentChunkSize: localParentChunkSize.value,
childChunkSize: localChildChunkSize.value
})
}
</script>