Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: index and recall images with multimodal embedding models (#3683)
lyingbug0c5d28abb791
diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.tsindex c4ae43a69..48e0bef11 100644--- a/frontend/src/api/knowledge-base/index.ts+++ b/frontend/src/api/knowledge-base/index.ts@@ -213,13 +213,17 @@ export async function fetchImageAttrSchema(kbId: string): Promise<ImageAttrSchem}// Mirrors backend types.ImageProcessingConfig (snake_case JSON). The UI edits-// the attribute-observation switch and the on_unobserved toggle; saving sends-// the snapshot back with those fields updated so API-side settings survive a-// UI edit.+// the attribute-observation switch, the on_unobserved toggle and the+// image-vector switch; saving sends the snapshot back with those fields+// updated so API-side settings survive a UI edit.export interface ImageProcessingConfig {model_id?: string;image_actions?: ImageActionsConfig;image_attrs_enabled?: boolean;+ // Index and recall images by their own vectors. Off unless the knowledge+ // base opts in, and only takes effect with an embedding model that takes+ // images.+ image_vector_enabled?: boolean;}export type VectorStoreSource = 'env' | 'user' | 'shared' | 'unavailable';diff --git a/frontend/src/components/ModelEditorDialog.vue b/frontend/src/components/ModelEditorDialog.vueindex ed53f38a3..a5799b16d 100644--- a/frontend/src/components/ModelEditorDialog.vue+++ b/frontend/src/components/ModelEditorDialog.vue@@ -501,6 +501,15 @@</div></div>+ <!-- Embedding: image input. Catalogued models answer it themselves; a row declares it in spec.input. -->+ <div v-if="activeModelType === 'embedding'" class="form-item">+ <label class="form-label">{{ $t('model.editor.embeddingImageInputLabel') }}</label>+ <div class="vision-toggle">+ <t-switch v-model="embeddingAcceptsImages" />+ <span class="form-desc form-desc--inline">{{ $t('model.editor.embeddingImageInputDesc') }}</span>+ </div>+ </div>+<!-- Chat / VLM: context window. Agent compaction sizes itself from this. --><div v-if="activeModelType === 'chat' || activeModelType === 'vllm'" class="form-item"><label class="form-label">{{ $t('model.editor.contextWindowLabel') }}</label>@@ -955,6 +964,38 @@ const vendorDocLink = computed(() => {*/const catalogFilled = ref<Partial<ModelFormData>>({})+/** Whether the catalog says the selected embedding model takes images. */+const catalogEmbeddingAcceptsImages = computed(() =>+ !!findCatalogEntry((formData.value.modelName || '').trim())?.input?.includes('image'))++/**+ * Image input of an embedding model: spec.input when the row declares it,+ * the catalog otherwise. The row only stores a declaration that differs from+ * the catalog, so a later catalog correction still reaches it.+ */+const embeddingAcceptsImages = computed<boolean>({+ get: () => {+ const input = formData.value.spec?.input+ return Array.isArray(input) && input.length > 0+ ? input.includes('image')+ : catalogEmbeddingAcceptsImages.value+ },+ set: (value) => {+ const spec: ModelSpecOverride = { ...(formData.value.spec || {}) }+ if (value === catalogEmbeddingAcceptsImages.value) delete spec.input+ else spec.input = value ? ['text', 'image'] : ['text']+ formData.value.spec = Object.keys(spec).length > 0 ? spec : null+ },+})++/** A declared input belongs to the model it was declared for. */+const dropEmbeddingInputOverride = () => {+ if (!formData.value.spec?.input) return+ const spec: ModelSpecOverride = { ...formData.value.spec }+ delete spec.input+ formData.value.spec = Object.keys(spec).length > 0 ? spec : null+}+/** Fill blank capability fields from a catalog entry the user just picked. */const applyCatalogEntry = (entry: ModelCatalogEntry) => {if (activeModelType.value === 'chat' || activeModelType.value === 'vllm') {@@ -971,6 +1012,7 @@ const applyCatalogEntry = (entry: ModelCatalogEntry) => {formData.value.supportsVision = truecatalogFilled.value.supportsVision = true}+ if (activeModelType.value === 'embedding') dropEmbeddingInputOverride()if (activeModelType.value === 'embedding' && !formData.value.dimension && entry.dimension) {formData.value.dimension = entry.dimensioncatalogFilled.value.dimension = entry.dimension@@ -1623,6 +1665,7 @@ const resetModelSelectionForVendor = () => {if (filled.supportsVision && formData.value.supportsVision) {formData.value.supportsVision = false}+ if (activeModelType.value === 'embedding') dropEmbeddingInputOverride()catalogFilled.value = {}modelChecked.value = falsemodelAvailable.value = falsediff --git a/frontend/src/components/modelEditorFlow.test.ts b/frontend/src/components/modelEditorFlow.test.tsindex 08d0d449e..5be2bd092 100644--- a/frontend/src/components/modelEditorFlow.test.ts+++ b/frontend/src/components/modelEditorFlow.test.ts@@ -430,6 +430,49 @@ test('picking a catalog model fills blank capability fields only', async () => {} finally { f.close() }})+const embeddingProviders = [{+ value: 'volcengine', label: 'Volcengine', description: '', order: 1, icon: '',+ defaultUrls: { embedding: 'https://ark.cn-beijing.volces.com/api/v3' },+ modelTypes: ['embedding'],+ models: [+ { id: 'doubao-embedding-vision-251215', name: 'Doubao Embedding Vision', type: 'embedding', input: ['text', 'image', 'video'], dimension: 2048 },+ { id: 'doubao-embedding-text', name: 'Doubao Embedding Text', type: 'embedding', dimension: 2048 },+ ],+}]++test('embedding image input follows the catalog and stores only a differing declaration', async () => {+ const f = await fixture({ type: 'embedding', providers: embeddingProviders })+ try {+ f.vm.formData.provider = 'volcengine'+ f.vm.formData.modelName = 'doubao-embedding-vision-251215'+ f.vm.handleCatalogModelChange('doubao-embedding-vision-251215')+ await nextTick()+ assert.equal(f.vm.embeddingAcceptsImages, true, 'catalogued multimodal model')+ assert.equal(f.vm.formData.spec, null, 'the catalog answer is not copied into the row')++ f.vm.embeddingAcceptsImages = false+ assert.deepEqual(plain(f.vm.formData.spec), { input: ['text'] }, 'narrowing the catalog is a declaration')+ f.vm.embeddingAcceptsImages = true+ assert.equal(f.vm.formData.spec, null, 'back to the catalog answer drops it again')++ // A custom model has nothing in the catalog; declaring image input sticks+ // next to whatever else spec already carries.+ f.vm.formData.spec = { compat: { encoding_format: 'float' } }+ f.vm.handleCatalogModelCreate('my-clip')+ await nextTick()+ assert.equal(f.vm.embeddingAcceptsImages, false)+ f.vm.embeddingAcceptsImages = true+ assert.deepEqual(plain(f.vm.formData.spec), { compat: { encoding_format: 'float' }, input: ['text', 'image'] })++ // Picking a catalogued model discards a declaration made for another one.+ f.vm.formData.modelName = 'doubao-embedding-text'+ f.vm.handleCatalogModelChange('doubao-embedding-text')+ await nextTick()+ assert.equal(f.vm.embeddingAcceptsImages, false)+ assert.deepEqual(plain(f.vm.formData.spec), { compat: { encoding_format: 'float' } })+ } finally { f.close() }+})+test('resolve panel is refreshed once per 400ms burst of edits and ignored while hidden', async () => {const f = await fixture({ type: 'chat', providers: catalogProviders })try {diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 8324bb92d..e56d2f014 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -3960,6 +3960,9 @@ export default {customInstructionsPlaceholder: 'For example: prioritize nameplates, model numbers, alarm codes, and table units…',imageAttrsLabel: 'Image attribute observation',imageAttrsDescription: 'When on, each image is first observed for attributes and described, then the attributes decide whether an OCR round runs for the text in the image. When off, the basic mode applies: every image is described and OCR runs for all of them',+ imageVectorLabel: 'Image vector search',+ imageVectorDescription: 'When on, each image is also encoded by the embedding model itself after its description is generated, so searches can find images by what they show even where the description leaves it out. Needs an embedding model that takes images; costs one extra embedding call per image and widens the vector search pool. Applies to documents ingested or re-parsed afterwards; scanned PDF pages are skipped',+ imageVectorModelUnsupported: 'The current embedding model does not declare image input, so no image vectors will be indexed or recalled',imageAttrsSchemaLabel: 'Observable image attributes',imageAttrsSchemaDescription: 'The model observes the attributes below (defined by the backend registry) to drive the OCR policy',imageAttrsOcrConditions: 'Trigger OCR based on the observed attribute conditions',@@ -5076,6 +5079,8 @@ export default {dimensionOverrideDesc: 'Enable only if the provider documentation says this model accepts a dimensions parameter.',supportsVisionLabel: 'Supports Vision / Multimodal',supportsVisionDesc: 'Whether the model accepts image and multimodal input',+ embeddingImageInputLabel: 'Image Input',+ embeddingImageInputDesc: 'The model embeds images into the same vector space as text. Catalogued models are detected automatically; declare it for custom models',contextWindowLabel: 'Context Window',contextWindowPlaceholder: 'Default {value}',contextWindowDesc: 'How many tokens this model can take in one request. Agent history compaction uses this limit. Leave empty for the default 200000 (200K). Use the provider’s real window — a larger guess means compaction never fires and the provider rejects the request.',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex 2c377c9b5..d602dd0a0 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -3960,6 +3960,9 @@ export default {customInstructionsPlaceholder: '例: 銘板、型番、アラームコード、表の単位を優先する…',imageAttrsLabel: '画像属性の観察',imageAttrsDescription: 'オンにすると各画像を先に「属性観察+説明」し、その属性で画像内テキストへの OCR 実行可否を決定します。オフは基本モード:全画像を1枚ずつ説明し全て OCR します',+ imageVectorLabel: '画像ベクトル検索',+ imageVectorDescription: 'オンにすると、画像の説明を生成した後に埋め込みモデルで画像そのものもエンコードし、説明に書かれていない内容でも画像を検索できるようにします。画像入力に対応した埋め込みモデルが必要で、画像ごとに埋め込み呼び出しが1回増え、ベクトル検索の候補範囲も広がります。以降に取り込み・再解析した文書にのみ適用され、スキャン PDF のページは対象外です',+ imageVectorModelUnsupported: '現在の埋め込みモデルは画像入力を宣言していないため、画像ベクトルは生成も検索もされません',imageAttrsSchemaLabel: '観察可能な画像属性',imageAttrsSchemaDescription: 'モデルは以下の属性(バックエンドのレジストリで定義)を観察して OCR ポリシーを決めます',imageAttrsOcrConditions: '観察した属性条件に基づいて OCR を実行',@@ -5076,6 +5079,8 @@ export default {dimensionOverrideDesc: 'プロバイダのドキュメントでこのモデルがdimensionsパラメータに対応していると記載されている場合にのみ有効にしてください。デフォルトでは検出された実際の次元数のみを使用します。',supportsVisionLabel: '視覚・マルチモーダルに対応',supportsVisionDesc: 'モデルが画像やマルチモーダル入力を受け付けるかどうか',+ embeddingImageInputLabel: '画像入力',+ embeddingImageInputDesc: 'モデルが画像をテキストと同じベクトル空間に埋め込めるかどうか。カタログ内のモデルは自動判定され、カスタムモデルは手動で宣言します',contextWindowLabel: 'コンテキストウィンドウ',contextWindowPlaceholder: 'デフォルト値{value}',contextWindowDesc: '1回のリクエストでこのモデルが受け付けられるトークン数です。エージェントの履歴圧縮はこの上限を基準にします。空欄の場合はデフォルト値の200000(200K)が使われます。プロバイダの実際のウィンドウサイズを指定してください。大きすぎる値を指定すると圧縮が働かず、プロバイダにリクエストを拒否されます。',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex c0c3074bb..298bcde32 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -3066,6 +3066,8 @@ export default {dimensionOverrideDesc: '제공자 문서에서 이 모델이 dimensions 매개변수를 지원한다고 확인한 경우에만 켜세요.',supportsVisionLabel: '비전/멀티모달 지원',supportsVisionDesc: '모델의 이미지 등 멀티모달 입력 지원 여부',+ embeddingImageInputLabel: '이미지 입력',+ embeddingImageInputDesc: '모델이 이미지를 텍스트와 같은 벡터 공간에 임베딩할 수 있는지 여부. 카탈로그 모델은 자동으로 인식되며, 사용자 정의 모델은 직접 선언합니다',contextWindowLabel: '컨텍스트 창',contextWindowPlaceholder: '기본값 {value}',contextWindowDesc: '모델이 한 요청에 수용할 수 있는 토큰 수입니다. 에이전트 대화 압축이 이 한도를 사용합니다. 비워 두면 기본값 200000(200K)을 사용합니다. 공급자 문서의 실제 값을 입력하세요. 더 크게 설정하면 압축이 발생하지 않고 요청이 거부될 수 있습니다.',@@ -4118,6 +4120,9 @@ export default {customInstructionsPlaceholder: '예: 명판, 모델 번호, 경고 코드 및 표 단위를 중점적으로 인식…',imageAttrsLabel: '이미지 속성 관찰',imageAttrsDescription: '켜면 각 이미지를 먼저 속성 관찰+설명한 뒤, 속성에 따라 이미지 내 텍스트에 OCR을 실행할지 결정합니다. 끄면 기본 모드: 모든 이미지를 하나씩 설명하고 모두 OCR합니다',+ imageVectorLabel: '이미지 벡터 검색',+ imageVectorDescription: '켜면 이미지 설명을 생성한 뒤 임베딩 모델로 이미지 자체도 인코딩하여, 설명에 없는 내용으로도 이미지를 검색할 수 있습니다. 이미지 입력을 지원하는 임베딩 모델이 필요하며, 이미지마다 임베딩 호출이 한 번 늘고 벡터 검색 후보 범위도 넓어집니다. 이후 수집하거나 다시 파싱한 문서에만 적용되며, 스캔 PDF 페이지는 제외됩니다',+ imageVectorModelUnsupported: '현재 임베딩 모델은 이미지 입력을 선언하지 않아 이미지 벡터가 생성되거나 검색되지 않습니다',imageAttrsSchemaLabel: '관찰 가능한 이미지 속성',imageAttrsSchemaDescription: '모델은 아래 속성(백엔드 레지스트리 정의)을 관찰해 OCR 정책을 결정합니다',imageAttrsOcrConditions: '관찰된 속성 조건에 따라 OCR 실행',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 9675aac74..248cbd44f 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -3066,6 +3066,8 @@ export default {dimensionOverrideDesc: 'Включайте только если документация провайдера подтверждает поддержку параметра dimensions.',supportsVisionLabel: 'Поддержка визуального / мультимодального ввода',supportsVisionDesc: 'Поддерживает ли модель изображения и другой мультимодальный ввод',+ embeddingImageInputLabel: 'Ввод изображений',+ embeddingImageInputDesc: 'Модель встраивает изображения в то же векторное пространство, что и текст. Для моделей из каталога определяется автоматически, для своих моделей укажите вручную',contextWindowLabel: 'Контекстное окно',contextWindowPlaceholder: 'По умолчанию {value}',contextWindowDesc: 'Сколько токенов модель принимает за один запрос. Сжатие истории агента использует этот лимит. Пустое значение — по умолчанию 200000 (200K). Укажите реальное окно провайдера: завышенное значение не запускает сжатие, и провайдер отклоняет запрос.',@@ -4118,6 +4120,9 @@ export default {customInstructionsPlaceholder: 'Например: распознавать шильдики, модели, коды ошибок и единицы таблиц…',imageAttrsLabel: 'Наблюдение атрибутов изображений',imageAttrsDescription: 'Когда включено, каждое изображение сначала наблюдается на атрибуты и описывается, затем атрибуты решают, нужен ли OCR текста в изображении. Когда выключено — базовый режим: каждое изображение описывается и распознаётся',+ imageVectorLabel: 'Поиск по векторам изображений',+ imageVectorDescription: 'Когда включено, после генерации описания изображение также кодируется самой моделью эмбеддингов, и поиск находит изображения по их содержимому, даже если описание этого не упоминает. Нужна модель эмбеддингов с поддержкой изображений; на каждое изображение добавляется один вызов эмбеддинга, а пул кандидатов векторного поиска расширяется. Действует для документов, загруженных или повторно разобранных после включения; страницы сканированных PDF пропускаются',+ imageVectorModelUnsupported: 'Текущая модель эмбеддингов не заявляет поддержку изображений, поэтому векторы изображений не будут ни созданы, ни найдены',imageAttrsSchemaLabel: 'Наблюдаемые атрибуты изображений',imageAttrsSchemaDescription: 'Модель наблюдает перечисленные ниже атрибуты (определены реестром бэкенда), чтобы управлять политикой OCR',imageAttrsOcrConditions: 'Запуск OCR по наблюдаемым условиям атрибутов',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 9fcc1a81a..d26e0db46 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -3068,6 +3068,8 @@ export default {dimensionOverrideDesc: '仅在确认该模型支持 dimensions 参数时开启;默认只使用检测到的实际维度。',supportsVisionLabel: '支持视觉/多模态',supportsVisionDesc: '模型是否支持图片等多模态输入',+ embeddingImageInputLabel: '图片输入',+ embeddingImageInputDesc: '模型能把图片编码到与文本相同的向量空间。目录内的模型自动识别,自定义模型需手动声明',contextWindowLabel: '上下文窗口',contextWindowPlaceholder: '默认 {value}',contextWindowDesc: '该模型一次请求能容纳的 token 数。智能体压缩对话历史会按此上限工作。留空则使用默认 200000(200K)。请按厂商文档填写真实值,填大会导致压缩不触发、上游直接拒绝请求。',@@ -4120,6 +4122,9 @@ export default {customInstructionsPlaceholder: '例如:重点识别设备铭牌、型号、告警代码和表格中的单位…',imageAttrsLabel: '图片属性观察',imageAttrsDescription: '开启后,解析时对每张图片先「观察属性+描述」,再按属性决定是否对图内文字再跑一轮 OCR;关闭则沿用基础模式:所有图片逐张描述并全部 OCR',+ imageVectorLabel: '图片向量检索',+ imageVectorDescription: '开启后,生成图片描述之后再用向量模型直接对图片编码,检索时按图片内容召回描述没写到的信息。需要向量模型支持图片输入;每张图片多一次向量调用,向量检索的候选范围也会放大。只对此后入库或重新解析的文档生效,扫描件 PDF 页不生成',+ imageVectorModelUnsupported: '当前向量模型未声明图片输入,开启后不会生成或召回图片向量',imageAttrsSchemaLabel: '可观察的图片属性',imageAttrsSchemaDescription: '模型会观察以下属性(由后端注册表定义)以驱动 OCR 策略',imageAttrsOcrConditions: '根据观察到的属性条件触发 OCR',diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.tsindex 007321b09..3f7a54733 100644--- a/frontend/src/i18n/locales/zh-TW.ts+++ b/frontend/src/i18n/locales/zh-TW.ts@@ -3068,6 +3068,8 @@ export default {dimensionOverrideDesc: '僅在確認該模型支持 dimensions 參數時開啟;預設只使用檢測到的實際維度。',supportsVisionLabel: '支持視覺/多模態',supportsVisionDesc: '模型是否支持圖片等多模態輸入',+ embeddingImageInputLabel: '圖片輸入',+ embeddingImageInputDesc: '模型能把圖片編碼到與文字相同的向量空間。目錄內的模型會自動識別,自訂模型需手動宣告',contextWindowLabel: '脈絡視窗',contextWindowPlaceholder: '預設 {value}',contextWindowDesc: '該模型一次請求能容納的 token 數。智慧代理壓縮對話歷史會按此上限工作。留空則使用預設 200000(200K)。請按廠商文件填寫真實值,填大會導致壓縮不觸發、上遊直接拒絕請求。',@@ -4120,6 +4122,9 @@ export default {customInstructionsPlaceholder: '例如:重點識別裝置銘牌、型號、告警程式碼和表格中的單位…',imageAttrsLabel: '圖片屬性觀察',imageAttrsDescription: '開啟後,解析時對每張圖片先「觀察屬性+描述」,再按屬性決定是否對圖內文字再跑一輪 OCR;關閉則沿用基礎模式:所有圖片逐張描述並全部 OCR',+ imageVectorLabel: '圖片向量檢索',+ imageVectorDescription: '開啟後,產生圖片描述之後再用向量模型直接對圖片編碼,檢索時可依圖片內容找回描述中沒寫到的資訊。需要向量模型支援圖片輸入;每張圖片多一次向量呼叫,向量檢索的候選範圍也會擴大。僅對之後匯入或重新解析的文件生效,掃描版 PDF 頁面不會產生',+ imageVectorModelUnsupported: '目前的向量模型未宣告支援圖片輸入,開啟後不會產生或檢索圖片向量',imageAttrsSchemaLabel: '可觀察的圖片屬性',imageAttrsSchemaDescription: '模型會觀察以下屬性(由後端登錄檔定義)以驅動 OCR 策略',imageAttrsOcrConditions: '根據觀察到的屬性條件觸發 OCR',diff --git a/frontend/src/utils/imageProcessingConfig.test.ts b/frontend/src/utils/imageProcessingConfig.test.tsindex 56178c21b..340aadb83 100644--- a/frontend/src/utils/imageProcessingConfig.test.ts+++ b/frontend/src/utils/imageProcessingConfig.test.ts@@ -14,7 +14,7 @@ test('saving keeps OCR conditions customised through the API', () => {const custom = [{ prop: 'contain.text', is: 'sparse' }]const built = buildImageProcessingConfig({ model_id: 'vlm-1', image_attrs_enabled: true, image_actions: { ocr: { on: custom, on_unobserved: true } } },- { imageAttrsEnabled: true, onUnobserved: false, defaultOn: DEFAULT_ON },+ { imageAttrsEnabled: true, imageVectorEnabled: false, onUnobserved: false, defaultOn: DEFAULT_ON },)assert.deepEqual(built, {@@ -27,7 +27,7 @@ test('saving keeps OCR conditions customised through the API', () => {test('a KB without custom conditions gets the registry default alongside on_unobserved', () => {const built = buildImageProcessingConfig({ model_id: 'vlm-1' },- { imageAttrsEnabled: true, onUnobserved: false, defaultOn: DEFAULT_ON },+ { imageAttrsEnabled: true, imageVectorEnabled: false, onUnobserved: false, defaultOn: DEFAULT_ON },)assert.deepEqual(built, {@@ -42,7 +42,33 @@ test('an unchanged configuration is not sent', () => {const snapshot = { image_attrs_enabled: true, image_actions: { ocr: { on: custom, on_unobserved: true } } }assert.equal(- buildImageProcessingConfig(snapshot, { imageAttrsEnabled: true, onUnobserved: true, defaultOn: DEFAULT_ON }),+ buildImageProcessingConfig(snapshot, { imageAttrsEnabled: true, imageVectorEnabled: false, onUnobserved: true, defaultOn: DEFAULT_ON }),+ null,+ )+})++test('the image-vector switch is saved when turned on and when turned back off', () => {+ const on = buildImageProcessingConfig(+ { model_id: 'vlm-1' },+ { imageAttrsEnabled: false, imageVectorEnabled: true, onUnobserved: true, defaultOn: DEFAULT_ON },+ )+ assert.equal(on?.image_vector_enabled, true)++ const off = buildImageProcessingConfig(+ { model_id: 'vlm-1', image_vector_enabled: true },+ { imageAttrsEnabled: false, imageVectorEnabled: false, onUnobserved: true, defaultOn: DEFAULT_ON },+ )+ assert.equal(off?.image_vector_enabled, false)+})++test('a knowledge base that never touched the image-vector switch does not get one written', () => {+ // The backend reads a missing key as off, which is what every knowledge+ // base from before the switch has; an unrelated save must leave it so.+ const snapshot = { image_attrs_enabled: true, image_actions: { ocr: { on: DEFAULT_ON, on_unobserved: true } } }+ assert.equal(+ buildImageProcessingConfig(snapshot, {+ imageAttrsEnabled: true, imageVectorEnabled: false, onUnobserved: true, defaultOn: DEFAULT_ON,+ }),null,)})diff --git a/frontend/src/utils/imageProcessingConfig.ts b/frontend/src/utils/imageProcessingConfig.tsindex 400b06191..0002992e6 100644--- a/frontend/src/utils/imageProcessingConfig.ts+++ b/frontend/src/utils/imageProcessingConfig.ts@@ -7,6 +7,8 @@ export interface ImageAttrConditionLike {/** The fields of the KB editor that feed image_processing_config. */export interface ImageProcessingEdits {imageAttrsEnabled: boolean+ /** Index and recall images by their own vectors (off unless opted in). */+ imageVectorEnabled: booleanonUnobserved: boolean/** The registry's current default OCR conditions (GET /image-attrs/schema). */defaultOn: ImageAttrConditionLike[]@@ -22,6 +24,10 @@ export interface ImageProcessingEdits {* OCR clause only when `on` is set. A knowledge base whose `on` was customised* through the API keeps it; one without a custom list gets the registry's* current default, so it still follows the default as it evolves.+ *+ * image_vector_enabled is written only when it is on or was already stored:+ * a knowledge base that never touched the switch reads as off on the+ * backend, so writing `false` into it would be a change for nothing.*/export function buildImageProcessingConfig(snapshot: Record<string, unknown> | null | undefined,@@ -30,7 +36,7 @@ export function buildImageProcessingConfig(const snap = snapshot || {}const storedOn = (snap.image_actions as { ocr?: { on?: unknown } } | undefined)?.ocr?.onconst on = Array.isArray(storedOn) && storedOn.length > 0 ? storedOn : edits.defaultOn- const built = {+ const built: Record<string, unknown> = {...snap,image_attrs_enabled: edits.imageAttrsEnabled,image_actions: {@@ -40,5 +46,8 @@ export function buildImageProcessingConfig(},},}+ if (edits.imageVectorEnabled || 'image_vector_enabled' in snap) {+ built.image_vector_enabled = edits.imageVectorEnabled+ }return JSON.stringify(built) === JSON.stringify(snap) ? null : built}diff --git a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vueindex f7fdd0555..360a2cad6 100644--- a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue+++ b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue@@ -364,6 +364,20 @@</div></div>+ <!-- 图片向量:默认关闭,显式开启才为图片单独编码、检索时召回 -->+ <div v-if="formData.multimodalConfig.enabled" class="setting-row">+ <div class="setting-info">+ <label>{{ $t('knowledgeEditor.advanced.multimodal.imageVectorLabel') }}</label>+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.imageVectorDescription') }}</p>+ <p v-if="formData.imageVectorEnabled && !embeddingTakesImages" class="desc desc-warning">+ {{ $t('knowledgeEditor.advanced.multimodal.imageVectorModelUnsupported') }}+ </p>+ </div>+ <div class="setting-control">+ <t-switch v-model="formData.imageVectorEnabled" size="medium" />+ </div>+ </div>+<div v-if="formData.multimodalConfig.enabled" class="setting-row"><div class="setting-info"><label>{{ $t('knowledgeEditor.advanced.multimodal.imageAttrsLabel') }}</label>@@ -828,6 +842,13 @@ const advancedSettingsRef = ref<InstanceType<typeof KBAdvancedSettings>>()// 表单数据const formData = ref<any>(null)+// 图片向量只在向量模型能处理图片时生效;模型列表里查不到(未加载、跨租户共享)时+// 不报警,后端会按实际模型判断。+const embeddingTakesImages = computed(() => {+ const id = formData.value?.modelConfig.embeddingModelId+ const model = id ? allModels.value.find((m) => m.id === id) : undefined+ return !model || !!model.capabilities?.input?.includes('image')+})const isFAQ = computed(() => formData.value?.type === 'faq')const kbCreateNeedsEmbedding = computed(() => {@@ -909,6 +930,8 @@ const initFormData = (type: 'document' | 'faq' = 'document') => {// 新建模式也必须用完整默认动作初始化——imageActions.ocr.on_unobserved// 直接被开关绑定,缺省会让打开开关的瞬间渲染崩溃。imageAttrsEnabled: false,+ // 图片向量默认关闭:能处理图片的向量模型也常只用来编码文本。+ imageVectorEnabled: false,imageActions: mergeImageActions(),imageProcessingConfigSnapshot: null as Record<string, unknown> | null,asrConfig: {@@ -1062,6 +1085,8 @@ const loadKBData = async (},imageAttrsEnabled:!!(kb as Record<string, any>).image_processing_config?.image_attrs_enabled,+ imageVectorEnabled:+ !!(kb as Record<string, any>).image_processing_config?.image_vector_enabled,imageActions: mergeImageActions((kb as Record<string, any>).image_processing_config?.image_actions,),@@ -1456,6 +1481,7 @@ const buildSubmitData = () => {{const built = buildImageProcessingConfig(formData.value.imageProcessingConfigSnapshot, {imageAttrsEnabled: formData.value.imageAttrsEnabled,+ imageVectorEnabled: formData.value.imageVectorEnabled,onUnobserved: formData.value.imageActions.ocr.on_unobserved,defaultOn: displaySchema.value.default_actions.ocr.on,})@@ -2242,6 +2268,11 @@ watch(() => chatResources.allModels, (list) => {margin: 0;line-height: 1.5;}++ .desc-warning {+ margin-top: 4px;+ color: var(--td-warning-color);+ }}.setting-control {diff --git a/frontend/src/views/settings/ModelSettings.vue b/frontend/src/views/settings/ModelSettings.vueindex 9efa20824..f68fc4e75 100644--- a/frontend/src/views/settings/ModelSettings.vue+++ b/frontend/src/views/settings/ModelSettings.vue@@ -132,7 +132,8 @@:title="contextWindowTitle(model.contextWindow)">{{ formatContextWindow(model.contextWindow) }}</span></template>- <template v-if="model._modelType === 'chat' && model.supportsVision">+ <template v-if="(model._modelType === 'chat' && model.supportsVision)+ || (model._modelType === 'embedding' && model.capabilities?.input?.includes('image'))"><span class="model-card__sep">·</span><span class="model-card__vision" :title="$t('model.editor.supportsVisionLabel')":aria-label="$t('model.editor.supportsVisionLabel')">diff --git a/go.mod b/go.modindex 02256d68d..7ce2b564e 100644--- a/go.mod+++ b/go.mod@@ -77,6 +77,7 @@ require (go.opentelemetry.io/otel/trace v1.43.0go.uber.org/dig v1.19.0golang.org/x/crypto v0.53.0+ golang.org/x/image v0.38.0golang.org/x/mod v0.36.0golang.org/x/net v0.56.0golang.org/x/sync v0.21.0diff --git a/internal/agent/compaction/compactor.go b/internal/agent/compaction/compactor.goindex 474213eda..330a7cfc4 100644--- a/internal/agent/compaction/compactor.go+++ b/internal/agent/compaction/compactor.go@@ -259,6 +259,12 @@ func (c *Compactor) streamSummary(var sb strings.BuilderstreamErr := ""for {+ // select picks at random among ready cases, and a provider closes its+ // stream once the turn's context is cancelled, so a stopped turn could+ // otherwise read as a completed (partial) summary.+ if err := ctx.Err(); err != nil {+ return "", "", err+ }select {case <-ctx.Done():return "", "", ctx.Err()@@ -266,6 +272,9 @@ func (c *Compactor) streamSummary(return "", "", fmt.Errorf("summarization stalled: no output for %s", timeout)case chunk, ok := <-stream:if !ok {+ if err := ctx.Err(); err != nil {+ return "", "", err+ }if streamErr != "" {return "", finishReason, fmt.Errorf("summarization stream error: %s", streamErr)}diff --git a/internal/application/service/chat_pipeline/merge.go b/internal/application/service/chat_pipeline/merge.goindex 9d131908d..02cef5535 100644--- a/internal/application/service/chat_pipeline/merge.go+++ b/internal/application/service/chat_pipeline/merge.go@@ -282,7 +282,7 @@ func (p *PluginMerge) resolveParentChunks(// without using editable StartAt/EndAt coordinates.imageTextParentIDs := make(map[string]struct{})for _, r := range results {- if r.ChunkType == string(types.ChunkTypeImageOCR) || r.ChunkType == string(types.ChunkTypeImageCaption) {+ if types.IsImageChildChunkType(r.ChunkType) {imageTextParentIDs[r.ParentChunkID] = struct{}{}}}@@ -356,7 +356,7 @@ func (p *PluginMerge) resolveParentChunks(r.SubChunkID = append(r.SubChunkID, r.ID)}- case string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption):+ case string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption), string(types.ChunkTypeImageVector):textParent, ok := parentMap[r.ParentChunkID]if !ok || textParent.Content == "" || textParent.ChunkType != types.ChunkTypeText {continue@@ -436,7 +436,7 @@ func collectScopedTextChildIDs(}seen[r.ID] = struct{}{}ids = append(ids, r.ID)- case string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption):+ case string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption), string(types.ChunkTypeImageVector):if _, ok := seen[r.ParentChunkID]; ok {continue}diff --git a/internal/application/service/chat_pipeline/merge_parent_resolve_test.go b/internal/application/service/chat_pipeline/merge_parent_resolve_test.goindex a6d447a1e..b41e41c7d 100644--- a/internal/application/service/chat_pipeline/merge_parent_resolve_test.go+++ b/internal/application/service/chat_pipeline/merge_parent_resolve_test.go@@ -361,3 +361,43 @@ func TestResolveImageOCRHit_KeepsTextWhenPlaceholderIsPruned(t *testing.T) {t.Fatalf("OCR count after chat enrichment = %d: %q", strings.Count(passage, ocrText), passage)}}++// An image found by its own vector reads like a caption hit: the caption is+// its body, and the text around the image comes from the parent chunks.+func TestResolveImageVectorHit_ExpandsLikeACaptionHit(t *testing.T) {+ caption := "柱状图:2025 年各季度销售额,第三季度最高"+ imageInfo, err := json.Marshal([]types.ImageInfo{{URL: "images/sales.png", Caption: caption}})+ if err != nil {+ t.Fatal(err)+ }+ repo := &expandChunkRepo{+ chunks: map[string]*types.Chunk{+ "text": {+ ID: "text", ParentChunkID: "parent", ChunkType: types.ChunkTypeText, ChunkIndex: 2,+ Content: "季度回顾如下:\n",+ },+ "parent": {+ ID: "parent", ChunkType: types.ChunkTypeParentText,+ Content: "第二章 经营情况\n季度回顾如下:\n",+ },+ },+ }+ plugin := &PluginMerge{chunkRepo: repo}+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))+ result := &types.SearchResult{+ ID: "vec-1", KnowledgeID: "doc", ChunkType: string(types.ChunkTypeImageVector),+ ParentChunkID: "text", Content: caption, ImageInfo: string(imageInfo),+ }++ got := plugin.resolveParentChunks(ctx, &types.ChatManage{}, []*types.SearchResult{result})+ if len(got) != 1 {+ t.Fatalf("result count = %d, want 1", len(got))+ }+ if !strings.Contains(got[0].Content, "经营情况") || !strings.Contains(got[0].Content, "第三季度最高") {+ t.Fatalf("image hit lost its surrounding text or caption: %q", got[0].Content)+ }+ passage := getEnrichedPassageForChat(ctx, got[0])+ if strings.Count(passage, caption) != 1 {+ t.Fatalf("caption duplicated after chat enrichment: %q", passage)+ }+}diff --git a/internal/application/service/chunk.go b/internal/application/service/chunk.goindex 6cae3464b..22133d9ae 100644--- a/internal/application/service/chunk.go+++ b/internal/application/service/chunk.go@@ -650,7 +650,7 @@ func (s *chunkService) syncEditedChunkImages(ctx context.Context, chunk *types.C}contentURLs := searchutil.ImageURLsInContent(chunk.Content)for _, child := range children {- if child.ChunkType != types.ChunkTypeImageOCR && child.ChunkType != types.ChunkTypeImageCaption {+ if !types.IsImageChildChunkType(child.ChunkType) {continue}desiredEnabled := chunk.IsEnabled && imageChildMatchesContent(child, contentURLs)@@ -776,6 +776,11 @@ func (s *chunkService) syncChunkIndex(ctx context.Context, chunk *types.Chunk) eif err != nil {return err}+ if chunk.ChunkType == types.ChunkTypeImageVector {+ // Its index row holds the image's own vector; re-embedding Content+ // would replace it with the caption's. Only the enabled flag follows.+ return engine.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{chunk.ID: chunk.IsEnabled})+ }if err := engine.DeleteByChunkIDList(ctx, []string{chunk.ID}, embedder.GetDimensions(), kb.Type); err != nil {return err}diff --git a/internal/application/service/chunk_edit_parent_test.go b/internal/application/service/chunk_edit_parent_test.goindex ab0ea2d69..773cfa9bb 100644--- a/internal/application/service/chunk_edit_parent_test.go+++ b/internal/application/service/chunk_edit_parent_test.go@@ -125,6 +125,11 @@ func TestSyncEditedChunkImagesDisablesAndRestoresImageChildren(t *testing.T) {ID: "image", TenantID: 1, KnowledgeBaseID: "kb", ParentChunkID: "text",ChunkType: types.ChunkTypeImageOCR, ImageInfo: string(imageInfo),IsEnabled: true, IndexStatus: "ready",+ }, {+ // The image's own vector follows the image like its OCR text does.+ ID: "image-vector", TenantID: 1, KnowledgeBaseID: "kb", ParentChunkID: "text",+ ChunkType: types.ChunkTypeImageVector, ImageInfo: string(imageInfo),+ IsEnabled: true, IndexStatus: "ready",}}}service := &chunkService{chunkRepository: repo, kbRepository: editableChunkKBRepo{}}parent := &types.Chunk{ID: "text", TenantID: 1, IsEnabled: true, Content: "image removed"}@@ -132,16 +137,20 @@ func TestSyncEditedChunkImagesDisablesAndRestoresImageChildren(t *testing.T) {if err := service.syncEditedChunkImages(context.Background(), parent); err != nil {t.Fatalf("disable removed image child: %v", err)}- if repo.children[0].IsEnabled || repo.children[0].IndexStatus != "ready" {- t.Fatalf("removed image child was not disabled cleanly: %+v", repo.children[0])+ for _, child := range repo.children {+ if child.IsEnabled || child.IndexStatus != "ready" {+ t.Fatalf("removed image child was not disabled cleanly: %+v", child)+ }}parent.Content = "image restored\n"if err := service.syncEditedChunkImages(context.Background(), parent); err != nil {t.Fatalf("restore image child: %v", err)}- if !repo.children[0].IsEnabled || repo.children[0].IndexStatus != "ready" {- t.Fatalf("restored image child was not re-enabled: %+v", repo.children[0])+ for _, child := range repo.children {+ if !child.IsEnabled || child.IndexStatus != "ready" {+ t.Fatalf("restored image child was not re-enabled: %+v", child)+ }}}diff --git a/internal/application/service/image_multimodal.go b/internal/application/service/image_multimodal.goindex b0e5c7db8..ce3abb433 100644--- a/internal/application/service/image_multimodal.go+++ b/internal/application/service/image_multimodal.go@@ -14,6 +14,7 @@ import ("github.com/Tencent/WeKnora/internal/application/repository""github.com/Tencent/WeKnora/internal/application/service/retriever""github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/models/embedding""github.com/Tencent/WeKnora/internal/models/utils/ollama""github.com/Tencent/WeKnora/internal/models/vlm""github.com/Tencent/WeKnora/internal/tracing/langfuse"@@ -420,7 +421,7 @@ func (s *ImageMultimodalService) processImage(}// Index chunks so they can be retrieved- s.indexChunks(ctx, *payload, newChunks)+ s.indexChunks(ctx, *payload, newChunks, imgBytes, out)out["indexed"] = truereturn nil@@ -585,8 +586,12 @@ func isFinalAsynqAttempt(ctx context.Context) bool {}// indexChunks indexes the newly created multimodal chunks into the retrieval engine-// so they can participate in semantic search.-func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types.ImageMultimodalPayload, chunks []*types.Chunk) {+// so they can participate in semantic search, then embeds the image itself+// when the knowledge base opted in and its embedding model takes images.+func (s *ImageMultimodalService) indexChunks(+ ctx context.Context, payload types.ImageMultimodalPayload, chunks []*types.Chunk,+ img []byte, out types.JSONMap,+) {kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)if err != nil || kb == nil {logger.Warnf(ctx, "[ImageMultimodal] Failed to get KB for indexing: %v", err)@@ -676,6 +681,117 @@ func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types.logger.Infof(ctx, "[ImageMultimodal] Indexed %d multimodal chunks for knowledge %s",len(chunks), payload.KnowledgeID)++ if status := s.indexImageVector(ctx, kb, payload, img, chunks, embeddingModel, engine); status != "" {+ out["image_vector"] = status+ }+}++// indexImageVector embeds the image itself with a multimodal embedding model+// and stores the vector under an image_vector chunk, so a query can find the+// image by what it shows even where the caption left that out. It returns a+// short status for the trace, "" when the knowledge base has not opted in+// (ImageProcessingConfig.ImageVectorEnabled) or the model takes no images.+//+// The caption and OCR chunks are already indexed, so a failure here only+// loses the extra recall and never fails the task.+func (s *ImageMultimodalService) indexImageVector(+ ctx context.Context, kb *types.KnowledgeBase, payload types.ImageMultimodalPayload, img []byte,+ chunks []*types.Chunk, model embedding.Embedder, engine *retriever.CompositeRetrieveEngine,+) string {+ // Off unless the knowledge base asked for it: a model that takes images+ // is often chosen for text alone, and this costs a call per image.+ if !kb.IsImageVectorEnabled() {+ return ""+ }+ imageModel, ok := embedding.AsImageEmbedder(model)+ if !ok {+ return ""+ }+ // A scanned page is text, which its OCR chunk already carries better+ // than an image vector can: multimodal embeddings are weakest on dense+ // text, and a document of such pages would cost a call each.+ if payload.ImageSourceType == "scanned_pdf" {+ return "skipped: scanned page"+ }+ // The chunk needs text for reranking and the answer context; the caption+ // describes the image, the OCR text is the fallback.+ var source *types.Chunk+ for _, c := range chunks {+ if c.ChunkType == types.ChunkTypeImageCaption {+ source = c+ break+ }+ if c.ChunkType == types.ChunkTypeImageOCR {+ source = c+ }+ }+ if source == nil {+ return "skipped: no caption or OCR text"+ }++ prepared, err := embedding.PrepareImage(img, imageModel.ImageLimits())+ if err != nil {+ logger.Warnf(ctx, "[ImageMultimodal] Image %s not embeddable: %v", payload.ImageURL, err)+ return "failed: " + err.Error()+ }+ vectors, err := imageModel.BatchEmbedImages(ctx, []embedding.Image{prepared})+ if err != nil {+ logger.Warnf(ctx, "[ImageMultimodal] Image embedding failed for %s: %v", payload.ImageURL, err)+ return "failed: " + err.Error()+ }+ if dims := model.GetDimensions(); dims > 0 && len(vectors[0]) != dims {+ // The index is laid out for the text vectors' width; a vector of+ // another would land in a different collection or be refused.+ logger.Warnf(ctx, "[ImageMultimodal] Image vector for %s has %d dimensions, the index %d",+ payload.ImageURL, len(vectors[0]), dims)+ return fmt.Sprintf("failed: %d dimensions, index has %d", len(vectors[0]), dims)+ }++ now := time.Now()+ chunk := &types.Chunk{+ ID: uuid.New().String(),+ TenantID: payload.TenantID,+ KnowledgeID: payload.KnowledgeID,+ KnowledgeBaseID: payload.KnowledgeBaseID,+ Content: source.Content,+ ChunkType: types.ChunkTypeImageVector,+ ParentChunkID: payload.ChunkID,+ IsEnabled: true,+ Flags: types.ChunkFlagRecommended,+ ImageInfo: source.ImageInfo,+ CreatedAt: now,+ UpdatedAt: now,+ }+ if err := s.chunkService.GetRepository().CreateChunks(ctx, []*types.Chunk{chunk}); err != nil {+ logger.Warnf(ctx, "[ImageMultimodal] Failed to create image vector chunk for %s: %v", payload.ImageURL, err)+ return "failed: " + err.Error()+ }+ err = engine.BatchIndexVectors(ctx, model, []*types.IndexInfo{{+ Content: chunk.Content,+ SourceID: chunk.ID,+ SourceType: types.ImageSourceType,+ ChunkID: chunk.ID,+ KnowledgeID: chunk.KnowledgeID,+ KnowledgeBaseID: chunk.KnowledgeBaseID,+ IsEnabled: true,+ }}, vectors)+ if err != nil {+ // The chunk stays unindexed: nothing retrieves it, and a re-parse+ // replaces it with the rest of the knowledge's chunks.+ logger.Warnf(ctx, "[ImageMultimodal] Failed to index image vector for %s: %v", payload.ImageURL, err)+ return "failed: " + err.Error()+ }+ // Re-fetch for the same reason as indexChunks: GORM Save would zero+ // the generated fields the in-memory chunk lacks.+ if dbChunk, err := s.chunkService.GetChunkByIDOnly(ctx, chunk.ID); err == nil {+ dbChunk.Status = int(types.ChunkStatusIndexed)+ if err := s.chunkService.GetRepository().UpdateChunk(ctx, dbChunk); err != nil {+ logger.Warnf(ctx, "[ImageMultimodal] Failed to mark image vector chunk %s indexed: %v", chunk.ID, err)+ }+ }+ logger.Infof(ctx, "[ImageMultimodal] Indexed image vector chunk %s for image %s", chunk.ID, payload.ImageURL)+ return "indexed"}// resolveVLM creates a vlm.VLM instance for the given knowledge base,diff --git a/internal/application/service/image_multimodal_vector_test.go b/internal/application/service/image_multimodal_vector_test.gonew file mode 100644index 000000000..a4cc7c012--- /dev/null+++ b/internal/application/service/image_multimodal_vector_test.go@@ -0,0 +1,241 @@+package service++import (+ "bytes"+ "context"+ "image"+ "image/png"+ "testing"++ "github.com/Tencent/WeKnora/internal/application/service/retriever"+ "github.com/Tencent/WeKnora/internal/models/embedding"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// vectorChunkRepo keeps created chunks in memory.+type vectorChunkRepo struct {+ interfaces.ChunkRepository+ chunks map[string]*types.Chunk+}++func (r *vectorChunkRepo) CreateChunks(_ context.Context, chunks []*types.Chunk) error {+ for _, c := range chunks {+ r.chunks[c.ID] = c+ }+ return nil+}++func (r *vectorChunkRepo) UpdateChunk(_ context.Context, c *types.Chunk) error {+ r.chunks[c.ID] = c+ return nil+}++type vectorChunkService struct {+ interfaces.ChunkService+ repo *vectorChunkRepo+}++func (s *vectorChunkService) GetRepository() interfaces.ChunkRepository { return s.repo }++func (s *vectorChunkService) GetChunkByIDOnly(_ context.Context, id string) (*types.Chunk, error) {+ c := *s.repo.chunks[id]+ return &c, nil+}++// imageModel is an embedding model with an image side.+type imageModel struct {+ embedding.Embedder+ dims int+ images []embedding.Image+}++func (m *imageModel) GetDimensions() int { return m.dims }+func (m *imageModel) AcceptsImages() bool { return true }+func (m *imageModel) ImageLimits() embedding.ImageLimits { return embedding.ImageLimits{} }++func (m *imageModel) BatchEmbedImages(_ context.Context, images []embedding.Image) ([][]float32, error) {+ m.images = append(m.images, images...)+ return [][]float32{{0.5, 0.5, 0.5}}, nil+}++// textModel has no image side.+type textModel struct{ embedding.Embedder }++// indexRecorder records what reaches the vector store.+type indexRecorder struct {+ interfaces.RetrieveEngineService+ rows []*types.IndexInfo+ vectors [][]float32+}++func (r *indexRecorder) EngineType() types.RetrieverEngineType {+ return types.PostgresRetrieverEngineType+}++func (r *indexRecorder) Support() []types.RetrieverType {+ return []types.RetrieverType{types.VectorRetrieverType}+}++func (r *indexRecorder) BatchIndex(ctx context.Context, e embedding.Embedder,+ rows []*types.IndexInfo, _ []types.RetrieverType,+) error {+ vectors, err := e.BatchEmbedWithPool(ctx, e, make([]string, len(rows)))+ if err != nil {+ return err+ }+ r.rows, r.vectors = append(r.rows, rows...), append(r.vectors, vectors...)+ return nil+}++func testPNG(t *testing.T) []byte {+ t.Helper()+ var buf bytes.Buffer+ require.NoError(t, png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 4, 4))))+ return buf.Bytes()+}++func imageVectorFixture(t *testing.T) (+ *ImageMultimodalService, *vectorChunkRepo, *indexRecorder, *retriever.CompositeRetrieveEngine,+) {+ t.Helper()+ repo := &vectorChunkRepo{chunks: map[string]*types.Chunk{}}+ recorder := &indexRecorder{}+ engine, err := retriever.NewCompositeRetrieveEngine(parentChildRetrieveRegistry{engine: recorder},+ []types.RetrieverEngineParams{{+ RetrieverEngineType: types.PostgresRetrieverEngineType, RetrieverType: types.VectorRetrieverType,+ }})+ require.NoError(t, err)+ return &ImageMultimodalService{chunkService: &vectorChunkService{repo: repo}}, repo, recorder, engine+}++// imageVectorKB has opted in to image vectors.+func imageVectorKB() *types.KnowledgeBase {+ return &types.KnowledgeBase{+ ID: "kb",+ IndexingStrategy: types.IndexingStrategy{VectorEnabled: true},+ ImageProcessingConfig: types.ImageProcessingConfig{ImageVectorEnabled: true},+ }+}++func multimodalChunks() []*types.Chunk {+ const info = `[{"url":"u"}]`+ return []*types.Chunk{+ {ID: "ocr", ChunkType: types.ChunkTypeImageOCR, Content: "SALES 2025", ImageInfo: info},+ {ID: "cap", ChunkType: types.ChunkTypeImageCaption, Content: "a bar chart of sales", ImageInfo: info},+ }+}++func TestIndexImageVectorStoresTheImagesOwnVector(t *testing.T) {+ svc, repo, recorder, engine := imageVectorFixture(t)+ model := &imageModel{dims: 3}+ payload := types.ImageMultimodalPayload{+ ChunkID: "text-parent", KnowledgeID: "k", KnowledgeBaseID: "kb", TenantID: 1, ImageURL: "u",+ }+ status := svc.indexImageVector(context.Background(), imageVectorKB(), payload, testPNG(t),+ multimodalChunks(), model, engine)+ require.Equal(t, "indexed", status)++ require.Len(t, model.images, 1)+ assert.Equal(t, "image/png", model.images[0].MIMEType)++ require.Len(t, repo.chunks, 1)+ var chunk *types.Chunk+ for _, c := range repo.chunks {+ chunk = c+ }+ assert.Equal(t, types.ChunkTypeImageVector, chunk.ChunkType)+ assert.Equal(t, "a bar chart of sales", chunk.Content, "the caption is preferred over OCR")+ assert.Equal(t, "text-parent", chunk.ParentChunkID)+ assert.True(t, chunk.IsEnabled)+ assert.Equal(t, int(types.ChunkStatusIndexed), chunk.Status)++ require.Len(t, recorder.rows, 1)+ row := recorder.rows[0]+ assert.Equal(t, types.ImageSourceType, row.SourceType)+ assert.Equal(t, chunk.ID, row.ChunkID)+ assert.Equal(t, chunk.ID, row.SourceID)+ assert.True(t, row.IsEnabled)+ assert.Equal(t, [][]float32{{0.5, 0.5, 0.5}}, recorder.vectors, "the image's vector, not the caption's")+}++func TestIndexImageVectorFallsBackToOCRText(t *testing.T) {+ svc, repo, _, engine := imageVectorFixture(t)+ status := svc.indexImageVector(context.Background(), imageVectorKB(), types.ImageMultimodalPayload{},+ testPNG(t), multimodalChunks()[:1], &imageModel{dims: 3}, engine)+ require.Equal(t, "indexed", status)+ for _, c := range repo.chunks {+ assert.Equal(t, "SALES 2025", c.Content)+ }+}++func TestIndexImageVectorSkips(t *testing.T) {+ cases := []struct {+ name string+ model embedding.Embedder+ payload types.ImageMultimodalPayload+ img []byte+ want string+ }{+ {"text-only model", &textModel{}, types.ImageMultimodalPayload{}, nil, ""},+ {+ "scanned page", &imageModel{dims: 3},+ types.ImageMultimodalPayload{ImageSourceType: "scanned_pdf"},+ nil,+ "skipped: scanned page",+ },+ {+ "not an image", &imageModel{dims: 3},+ types.ImageMultimodalPayload{},+ []byte("%PDF-1.7"),+ "failed: not an image (application/pdf)",+ },+ {+ "vector width differs from the index", &imageModel{dims: 1024},+ types.ImageMultimodalPayload{},+ nil,+ "failed: 3 dimensions, index has 1024",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ svc, repo, recorder, engine := imageVectorFixture(t)+ img := tc.img+ if img == nil {+ img = testPNG(t)+ }+ assert.Equal(t, tc.want, svc.indexImageVector(context.Background(), imageVectorKB(), tc.payload, img,+ multimodalChunks(), tc.model, engine))+ assert.Empty(t, repo.chunks)+ assert.Empty(t, recorder.rows)+ })+ }+}++// An image-capable model alone does not index images: the knowledge base+// has to opt in, and every knowledge base from before the switch is off.+func TestIndexImageVectorNeedsTheKnowledgeBaseToOptIn(t *testing.T) {+ cases := map[string]*types.KnowledgeBase{+ "switch off (every KB after an upgrade)": {+ ID: "kb", IndexingStrategy: types.IndexingStrategy{VectorEnabled: true},+ },+ "switch on but vector indexing off": {+ ID: "kb", IndexingStrategy: types.IndexingStrategy{KeywordEnabled: true},+ ImageProcessingConfig: types.ImageProcessingConfig{ImageVectorEnabled: true},+ },+ }+ for name, kb := range cases {+ t.Run(name, func(t *testing.T) {+ svc, repo, recorder, engine := imageVectorFixture(t)+ model := &imageModel{dims: 3}+ status := svc.indexImageVector(context.Background(), kb, types.ImageMultimodalPayload{},+ testPNG(t), multimodalChunks(), model, engine)+ assert.Empty(t, status)+ assert.Empty(t, model.images, "the image is not sent to the model")+ assert.Empty(t, repo.chunks)+ assert.Empty(t, recorder.rows)+ })+ }+}diff --git a/internal/application/service/knowledge_clone_move.go b/internal/application/service/knowledge_clone_move.goindex 596589761..518e54f24 100644--- a/internal/application/service/knowledge_clone_move.go+++ b/internal/application/service/knowledge_clone_move.go@@ -258,6 +258,14 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowlif err != nil {return err}+ // Image vectors exist only in a knowledge base that opted in to them+ // (indexImageVector). A copy into one that did not leaves them behind, the+ // index rows with the chunks: CopyIndices copies only mapped chunks' rows.+ if !targetKB.IsImageVectorEnabled() {+ sourceChunks = slices.DeleteFunc(sourceChunks, func(c *types.Chunk) bool {+ return c.ChunkType == types.ChunkTypeImageVector+ })+ }chunkPageSize := 100srcTodst := map[string]string{}tagIDMapping := map[string]string{} // srcTagID -> dstTagIDdiff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.goindex ee9760467..86ec93cb8 100644--- a/internal/application/service/knowledge_process.go+++ b/internal/application/service/knowledge_process.go@@ -3258,6 +3258,11 @@ func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, clogger.Warnf(ctx, "Knowledge base ID mismatch: %s != %s", chunk.KnowledgeBaseID, kbID)continue}+ // Its index row holds the image's own vector, which re-embedding+ // Content here would replace with a text vector of the caption.+ if chunk.ChunkType == types.ChunkTypeImageVector {+ continue+ }ids = append(ids, chunk.ID)if !chunk.IsEnabled || chunk.ChunkType == types.ChunkTypeParentText {continue@@ -3411,6 +3416,15 @@ func (s *knowledgeService) UpdateImageInfo(child.ImageInfo = imageInfoupdateChunk = append(updateChunk, chunkChildren[i])}+ case types.ChunkTypeImageVector:+ // The image's vector does not change with its caption, only the+ // text shown and reranked for it; updateChunkVector leaves the+ // vector alone.+ if image.Caption != "" && image.Caption != child.Content {+ child.Content = image.Caption+ child.ImageInfo = imageInfo+ updateChunk = append(updateChunk, chunkChildren[i])+ }}}diff --git a/internal/application/service/knowledge_transfer_test.go b/internal/application/service/knowledge_transfer_test.goindex d7b53ac69..a43c9d96a 100644--- a/internal/application/service/knowledge_transfer_test.go+++ b/internal/application/service/knowledge_transfer_test.go@@ -472,3 +472,72 @@ func TestTableSummaryCleanupDoesNotFollowMovedDocument(t *testing.T) {require.Equal(t, "other", current.KnowledgeBaseID)require.Equal(t, row.ParseStatus, current.ParseStatus)}++// cloneCopyEngine records the chunk mapping CloneChunk hands to CopyIndices.+type cloneCopyEngine struct {+ parentChildRetrieveEngine+ copied map[string]string+}++func (e *cloneCopyEngine) Support() []types.RetrieverType {+ return []types.RetrieverType{types.VectorRetrieverType, types.KeywordsRetrieverType}+}++func (e *cloneCopyEngine) CopyIndices(+ _ context.Context, _ string, _, chunks map[string]string, _ string, _ int, _ string,+) error {+ e.copied = chunks+ return nil+}++func TestCloneCopiesImageVectorsOnlyIntoKBsThatTakeThem(t *testing.T) {+ for _, targetOn := range []bool{false, true} {+ t.Run(map[bool]string{false: "target off", true: "target on"}[targetOn], func(t *testing.T) {+ t.Setenv("RETRIEVE_DRIVER", "postgres")+ f := transferFixture(t, access.KBTransferClone)+ require.NoError(t, f.db.Create(&types.Chunk{+ ID: "image-vector", TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb",+ ChunkType: types.ChunkTypeImageVector, ParentChunkID: "chunk", Content: "caption",+ }).Error)+ engine := &cloneCopyEngine{}+ f.svc.retrieveEngine = parentChildRetrieveRegistry{engine: engine}+ f.svc.modelService = parentChildModelService{embedder: parentChildEmbedder{}}+ for _, kb := range []*types.KnowledgeBase{f.kbs.values["kb"], f.kbs.values["other"]} {+ kb.EmbeddingModelID = "model"+ kb.IndexingStrategy.VectorEnabled = true+ }+ f.kbs.values["kb"].ImageProcessingConfig.ImageVectorEnabled = true+ f.kbs.values["other"].ImageProcessingConfig.ImageVectorEnabled = targetOn++ src, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")+ require.NoError(t, err)+ require.NoError(t, f.svc.cloneKnowledge(f.ctx, src, f.kbs.values["other"]))++ rows, err := f.repo.ListKnowledgeByKnowledgeBaseID(f.ctx, 7, "other")+ require.NoError(t, err)+ var dst *types.Knowledge+ for _, row := range rows {+ if row.ID != "other-doc" {+ dst = row+ }+ }+ require.NotNil(t, dst)+ chunks, err := f.chunkRepo.ListAllChunksByKnowledgeID(f.ctx, 7, dst.ID)+ require.NoError(t, err)+ var kinds []types.ChunkType+ for _, c := range chunks {+ kinds = append(kinds, c.ChunkType)+ }+ require.Contains(t, engine.copied, "chunk")+ if targetOn {+ require.ElementsMatch(t, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeImageVector}, kinds)+ require.Contains(t, engine.copied, "image-vector")+ return+ }+ require.Equal(t, []types.ChunkType{types.ChunkTypeText}, kinds,+ "a knowledge base that did not opt in gets no image vector chunk")+ require.NotContains(t, engine.copied, "image-vector",+ "nor its index row: CopyIndices copies only the rows of mapped chunks")+ })+ }+}diff --git a/internal/application/service/knowledgebase_search.go b/internal/application/service/knowledgebase_search.goindex 18462f277..3fd0dfc48 100644--- a/internal/application/service/knowledgebase_search.go+++ b/internal/application/service/knowledgebase_search.go@@ -257,6 +257,9 @@ func (s *knowledgeBaseService) hybridSearchCandidates(ctx context.Context,return nil, nil}+ // Image vectors are recalled only for KBs that opted in to them.+ s.applyImageRecall(ctx, kbs, groups, params)+// Execute retrieval with fan-out + score normalization (multi-store// only) and a langfuse span around the entire retrieve step.logger.Infof(ctx, "Starting multi-store retrieval, group count: %d", len(groups))diff --git a/internal/application/service/knowledgebase_search_fanout.go b/internal/application/service/knowledgebase_search_fanout.goindex b2abc8687..c0c4a693c 100644--- a/internal/application/service/knowledgebase_search_fanout.go+++ b/internal/application/service/knowledgebase_search_fanout.go@@ -59,8 +59,7 @@ func (s *knowledgeBaseService) retrieveFromStores(return nil, nil}if len(groups) == 1 {- res, err := groups[0].Engine.Retrieve(ctx, paramsWithTopK(groups[0]))- return retainPartialResults(ctx, groups[0], res, err)+ return retrieveGroup(ctx, groups[0])}timeout := multiStoreRetrieveTimeout()@@ -77,8 +76,7 @@ func (s *knowledgeBaseService) retrieveFromStores(g.Go(func() error {gcCtx, cancel := context.WithTimeout(gctx, timeout)defer cancel()- res, err := grp.Engine.Retrieve(gcCtx, paramsWithTopK(grp))- res, err = retainPartialResults(gcCtx, grp, res, err)+ res, err := retrieveGroup(gcCtx, grp)if err != nil {logger.WarnWithFields(gctx, logger.Fields{"tenant_id": grp.OwnerTenantID,@@ -137,6 +135,22 @@ func (s *knowledgeBaseService) retrieveFromStores(return all, nil}+// retrieveGroup runs one group's retrieval and holds its hits to the group's+// image rules (filterImageHits), refilling the document vector and keyword+// pools first when image rows it drops took room in them+// (refillPastDroppedImages).+func retrieveGroup(ctx context.Context, g *storeGroup) ([]*types.RetrieveResult, error) {+ params := paramsWithTopK(g)+ res, err := g.Engine.Retrieve(ctx, params)+ res, err = retainPartialResults(ctx, g, res, err)+ if err != nil {+ return nil, err+ }+ refillPastDroppedImages(ctx, g, params, res)+ filterImageHits(res, g)+ return res, nil+}+// retainPartialResults keeps results that arrive together with an error.//// CompositeRetrieveEngine returns a non-nil error alongside results only when@@ -182,6 +196,9 @@ func paramsWithTopK(g *storeGroup) []types.RetrieveParams {out := make([]types.RetrieveParams, len(g.BaseParams))for i, p := range g.BaseParams {p.TopK = g.TopK+ if g.imageRecall() {+ p = withImageRecall(p)+ }out[i] = p}return outdiff --git a/internal/application/service/knowledgebase_search_image.go b/internal/application/service/knowledgebase_search_image.gonew file mode 100644index 000000000..1059ba735--- /dev/null+++ b/internal/application/service/knowledgebase_search_image.go@@ -0,0 +1,290 @@+package service++import (+ "context"+ "fmt"+ "slices"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/models/embedding"+ "github.com/Tencent/WeKnora/internal/types"+)++// Image vectors share one vector search with text, but they do not score+// like text: a text query lands measurably further from an image than from a+// passage saying the same thing (the modality gap). So they get their own+// threshold, and vector retrieval widens its pool to leave them room.+const (+ // imageVectorThreshold is the most an image hit is asked to score. It is+ // empirical, a ceiling below the text defaults (0.15–0.2); a lower text+ // threshold, or none, still wins.+ imageVectorThreshold = 0.1+ // imageRecallWidening is how much larger the vector pool is when image+ // hits compete in it: one half again, so text keeps close to the pool+ // it had before images arrived.+ imageRecallWidening = 2 // TopK + TopK/imageRecallWidening+)++// imageThreshold is the threshold an image hit must pass when text hits must+// pass textThreshold.+func imageThreshold(textThreshold float64) float64 {+ return min(textThreshold, imageVectorThreshold)+}++// applyImageRecall marks, on each store group, the KBs whose image vectors+// this search recalls. A KB takes part only when it opted in+// (KnowledgeBase.IsImageVectorEnabled) and the search's embedding model+// embeds images; a model that merely could is not enough, since one that+// takes images is often chosen for text alone. Groups left without such a+// KB search exactly as text-only ones and drop any image row they meet.+func (s *knowledgeBaseService) applyImageRecall(ctx context.Context,+ kbs []*types.KnowledgeBase, groups []*storeGroup, params types.SearchParams,+) {+ if params.DisableVectorMatch {+ return+ }+ optedIn := make(map[string]struct{})+ var modelKB *types.KnowledgeBase+ for _, kb := range kbs {+ if kb.IsImageVectorEnabled() && kb.EmbeddingModelID != "" {+ optedIn[kb.ID] = struct{}{}+ if modelKB == nil {+ modelKB = kb+ }+ }+ }+ // Ask about the model only when some KB wants images; the vector KBs of+ // a search share one model (validateSameEmbeddingModel).+ if modelKB == nil || !s.embeddingTakesImages(ctx, modelKB) {+ return+ }+ for _, g := range groups {+ for _, id := range g.KBIDs {+ if _, ok := optedIn[id]; !ok {+ continue+ }+ if g.ImageKBIDs == nil {+ g.ImageKBIDs = make(map[string]struct{})+ }+ g.ImageKBIDs[id] = struct{}{}+ }+ if g.imageRecall() {+ g.VectorThreshold = params.VectorThreshold+ }+ }+}++// embeddingTakesImages reports whether kb's embedding model embeds images,+// which is what puts image vectors in its index.+func (s *knowledgeBaseService) embeddingTakesImages(ctx context.Context, kb *types.KnowledgeBase) bool {+ var (+ model embedding.Embedder+ err error+ )+ if kb.TenantID != types.MustTenantIDFromContext(ctx) {+ model, err = s.modelService.GetEmbeddingModelForTenant(ctx, kb.EmbeddingModelID, kb.TenantID)+ } else {+ model, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)+ }+ if err != nil {+ // The query embedding already resolved this model, so a failure here+ // is transient; searching as text-only is the safe fallback.+ logger.Warnf(ctx, "image recall: resolve embedding model %s: %v", kb.EmbeddingModelID, err)+ return false+ }+ _, ok := embedding.AsImageEmbedder(model)+ return ok+}++// withImageRecall widens a document vector search to leave room for image+// hits and lowers its threshold to theirs; filterImageHits restores the text+// threshold on text hits afterwards. FAQ indexes hold no images.+func withImageRecall(p types.RetrieveParams) types.RetrieveParams {+ if p.RetrieverType != types.VectorRetrieverType || p.KnowledgeType != "" {+ return p+ }+ p.TopK = min(p.TopK+p.TopK/imageRecallWidening, maxRetrievalPoolSize)+ p.Threshold = imageThreshold(p.Threshold)+ return p+}++// filterImageHits holds each hit of one store group to the threshold of its+// kind. It runs before score normalization, while scores are still on the+// scale the thresholds were set in.+//+// Keyword hits on image rows are dropped whatever the group: the row's+// Content is the caption, whose own chunk is already keyword-indexed, so a+// match there would count the same text twice. Vector hits on image rows+// are kept only for KBs that recall images; a KB that indexed images while+// opted in and has since opted out gets none back.+func filterImageHits(results []*types.RetrieveResult, g *storeGroup) {+ for _, rr := range results {+ if rr == nil {+ continue+ }+ kept := rr.Results[:0]+ for _, hit := range rr.Results {+ if keepHit(hit, rr.RetrieverType, g) {+ kept = append(kept, hit)+ }+ }+ // Clear the tail so dropped hits are not kept alive by the array.+ clear(rr.Results[len(kept):])+ rr.Results = kept+ }+}++func keepHit(hit *types.IndexWithScore, retriever types.RetrieverType, g *storeGroup) bool {+ if hit == nil {+ return false+ }+ image := hit.SourceType == types.ImageSourceType+ switch retriever {+ case types.KeywordsRetrieverType:+ return !image+ case types.VectorRetrieverType:+ if image {+ return !staleImage(hit, g) && hit.Score >= imageThreshold(g.VectorThreshold)+ }+ if !g.imageRecall() {+ return true+ }+ return hit.Score >= g.VectorThreshold+ }+ return true+}++// staleImage reports whether a vector hit is an image row of a KB that does+// not recall images: indexed while it was opted in, kept after it opted out.+func staleImage(hit *types.IndexWithScore, g *storeGroup) bool {+ if hit == nil || hit.SourceType != types.ImageSourceType {+ return false+ }+ _, recalled := g.ImageKBIDs[hit.KnowledgeBaseID]+ return !recalled+}++// droppedImage reports whether filterImageHits drops a hit for being an+// image row, whatever it scored: any keyword hit on one, and a vector hit on+// a stale one.+func droppedImage(hit *types.IndexWithScore, retriever types.RetrieverType, g *storeGroup) bool {+ if retriever == types.KeywordsRetrieverType {+ return hit != nil && hit.SourceType == types.ImageSourceType+ }+ return staleImage(hit, g)+}++func countDroppedImages(hits []*types.IndexWithScore, retriever types.RetrieverType, g *storeGroup) int {+ n := 0+ for _, hit := range hits {+ if droppedImage(hit, retriever, g) {+ n+++ }+ }+ return n+}++// refillPastDroppedImages gives back, in res, the room dropped image rows took in a+// group's document pools: stale image rows in the vector pool, and every+// image row in the keyword pool. An image row's Content is its caption, so+// it matches a keyword query wherever the caption's own chunk does.+//+// No engine filters rows by source type, so filterImageHits drops these rows+// only after the engine has cut its ranking at TopK; enough of them ranked+// above the text would leave the search short of text hits, or with none.+// When a pool came back full and held some, its search runs again on a pool+// twice as large, until it holds TopK rows that are kept, the index runs+// out of rows, or the pool reaches maxRetrievalPoolSize: at most+// ceil(log2(maxRetrievalPoolSize/TopK)) extra calls per pool, four for the+// smallest pool of DefaultRetrievalTopK. The pool is then cut back to TopK+// such rows, which is what excluding the rows in the engine would return,+// unless more than maxRetrievalPoolSize-TopK of them rank above the text.+//+// A refill is best effort: a search that fails, or answers only in part+// (RetrieveResult.Error, as when some collections of the store did not+// answer), stops the refill and leaves the pool it would have replaced. A+// partial answer to the larger search can hold fewer kept rows than the+// complete smaller one, or none, so taking it would lose hits the search+// already had.+//+// The FAQ search never needs this, since its index holds no images.+func refillPastDroppedImages(ctx context.Context, g *storeGroup,+ params []types.RetrieveParams, res []*types.RetrieveResult,+) {+ for _, retriever := range []types.RetrieverType{types.VectorRetrieverType, types.KeywordsRetrieverType} {+ refillPool(ctx, g, retriever, params, res)+ }+}++// refillPool refills, in res, the document pool of one retriever type, as+// refillPastDroppedImages describes.+func refillPool(ctx context.Context, g *storeGroup, retriever types.RetrieverType,+ params []types.RetrieveParams, res []*types.RetrieveResult,+) {+ set := slices.IndexFunc(res, func(rr *types.RetrieveResult) bool {+ return rr != nil && rr.RetrieverType == retriever && countDroppedImages(rr.Results, retriever, g) > 0+ })+ param := slices.IndexFunc(params, func(p types.RetrieveParams) bool {+ return p.RetrieverType == retriever && p.KnowledgeType == ""+ })+ if set < 0 || param < 0 {+ return+ }+ p := params[param]+ want := p.TopK+ refilled := false+ for {+ hits := res[set].Results+ dropped := countDroppedImages(hits, retriever, g)+ if len(hits) < p.TopK || len(hits)-dropped >= want || p.TopK >= maxRetrievalPoolSize {+ break+ }+ p.TopK = min(2*p.TopK, maxRetrievalPoolSize)+ more, ok := refillSearch(ctx, g, p)+ if !ok {+ break+ }+ res[set] = more+ refilled = true+ }+ if refilled {+ res[set].Results = keepFirstKept(res[set].Results, want, retriever, g)+ }+}++// refillSearch runs one refill search and reports whether its answer is+// complete; refillPool keeps the pool it has otherwise.+func refillSearch(ctx context.Context, g *storeGroup, p types.RetrieveParams) (*types.RetrieveResult, bool) {+ more, err := g.Engine.Retrieve(ctx, []types.RetrieveParams{p})+ if err == nil && len(more) == 1 && more[0] != nil && more[0].Error != nil {+ err = more[0].Error+ }+ if err == nil && (len(more) != 1 || more[0] == nil) {+ err = fmt.Errorf("expected one result set, got %d", len(more))+ }+ if err != nil {+ logger.WarnWithFields(ctx, logger.Fields{+ "tenant_id": g.OwnerTenantID,+ "kb_count": len(g.KBIDs),+ "store_kind": storeKindLabel(g.StoreID),+ "retriever": p.RetrieverType,+ "top_k": p.TopK,+ }, fmt.Sprintf("image row refill incomplete, keeping the smaller pool: %v", err))+ return nil, false+ }+ return more[0], true+}++// keepFirstKept cuts hits after the n-th one that is not a dropped image row.+func keepFirstKept(+ hits []*types.IndexWithScore, n int, retriever types.RetrieverType, g *storeGroup,+) []*types.IndexWithScore {+ for i, hit := range hits {+ if !droppedImage(hit, retriever, g) {+ if n--; n == 0 {+ return hits[:i+1]+ }+ }+ }+ return hits+}diff --git a/internal/application/service/knowledgebase_search_image_test.go b/internal/application/service/knowledgebase_search_image_test.gonew file mode 100644index 000000000..f857fafc8--- /dev/null+++ b/internal/application/service/knowledgebase_search_image_test.go@@ -0,0 +1,498 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "slices"+ "sync"+ "testing"++ "github.com/Tencent/WeKnora/internal/models/embedding"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// hit is a hit in knowledge base "kb".+func hit(id string, score float64, source types.SourceType) *types.IndexWithScore {+ return kbHit("kb", id, score, source)+}++func kbHit(kbID, id string, score float64, source types.SourceType) *types.IndexWithScore {+ return &types.IndexWithScore{+ ChunkID: id, SourceID: id, Score: score, SourceType: source, KnowledgeBaseID: kbID,+ }+}++// recalls is the ImageKBIDs of a group whose KBs recall images.+func recalls(ids ...string) map[string]struct{} {+ out := make(map[string]struct{}, len(ids))+ for _, id := range ids {+ out[id] = struct{}{}+ }+ return out+}++func ids(hits []*types.IndexWithScore) []string {+ out := make([]string, len(hits))+ for i, h := range hits {+ out[i] = h.ChunkID+ }+ return out+}++func TestParamsWithTopKWidensOnlyTheDocumentVectorSearchForImages(t *testing.T) {+ g := &storeGroup{+ TopK: 100, ImageKBIDs: recalls("kb"), VectorThreshold: 0.3,+ BaseParams: []types.RetrieveParams{+ {RetrieverType: types.VectorRetrieverType, Threshold: 0.3},+ {RetrieverType: types.VectorRetrieverType, Threshold: 0.3, KnowledgeType: types.KnowledgeTypeFAQ},+ {RetrieverType: types.KeywordsRetrieverType, Threshold: 0.5},+ },+ }+ got := paramsWithTopK(g)+ assert.Equal(t, 150, got[0].TopK)+ assert.Equal(t, imageVectorThreshold, got[0].Threshold)+ assert.Equal(t, 100, got[1].TopK, "FAQ indexes hold no images")+ assert.Equal(t, 0.3, got[1].Threshold)+ assert.Equal(t, 100, got[2].TopK, "keyword search is left alone")+ assert.Equal(t, 0.5, got[2].Threshold)+ assert.Equal(t, 0.3, g.BaseParams[0].Threshold, "base params stay immutable")++ // A text threshold already under the image one is not raised, and the+ // pool never grows past the global cap.+ g = &storeGroup{TopK: maxRetrievalPoolSize, ImageKBIDs: recalls("kb"), BaseParams: []types.RetrieveParams{+ {RetrieverType: types.VectorRetrieverType, Threshold: 0.05},+ }}+ got = paramsWithTopK(g)+ assert.Equal(t, 0.05, got[0].Threshold)+ assert.Equal(t, maxRetrievalPoolSize, got[0].TopK)++ g.ImageKBIDs, g.TopK = nil, 100+ got = paramsWithTopK(g)+ assert.Equal(t, 0.05, got[0].Threshold)+ assert.Equal(t, 100, got[0].TopK, "without images the group TopK is used as is")+}++func TestFilterImageHitsHoldsEachKindToItsOwnThreshold(t *testing.T) {+ g := &storeGroup{ImageKBIDs: recalls("kb"), VectorThreshold: 0.3}+ vector := &types.RetrieveResult{RetrieverType: types.VectorRetrieverType, Results: []*types.IndexWithScore{+ hit("text-strong", 0.6, types.ChunkSourceType),+ hit("image-strong", 0.25, types.ImageSourceType),+ hit("text-weak", 0.2, types.ChunkSourceType), // only reached because the query threshold was lowered+ hit("image-weak", 0.05, types.ImageSourceType),+ }}+ keyword := &types.RetrieveResult{RetrieverType: types.KeywordsRetrieverType, Results: []*types.IndexWithScore{+ hit("text-kw", 0.9, types.ChunkSourceType),+ hit("image-kw", 0.9, types.ImageSourceType),+ }}+ filterImageHits([]*types.RetrieveResult{vector, keyword}, g)+ assert.Equal(t, []string{"text-strong", "image-strong"}, ids(vector.Results))+ assert.Equal(t, []string{"text-kw"}, ids(keyword.Results),+ "an image row's Content is the caption, already indexed as text")+}++func TestFilterImageHitsLeavesTextOnlySearchesAlone(t *testing.T) {+ // Without image recall the query ran at the text threshold, so every+ // text hit already passed it. Image rows a KB indexed while it was+ // opted in are dropped once it opts out, however well they score.+ g := &storeGroup{VectorThreshold: 0.3}+ vector := &types.RetrieveResult{RetrieverType: types.VectorRetrieverType, Results: []*types.IndexWithScore{+ hit("a", 0.31, types.ChunkSourceType), hit("b", 0.9, types.ImageSourceType),+ }}+ keyword := &types.RetrieveResult{RetrieverType: types.KeywordsRetrieverType, Results: []*types.IndexWithScore{+ hit("c", 0.9, types.ImageSourceType),+ }}+ filterImageHits([]*types.RetrieveResult{vector, nil, keyword}, g)+ assert.Equal(t, []string{"a"}, ids(vector.Results))+ assert.Empty(t, keyword.Results)+}++func TestFilterImageHitsRecallsImagesOnlyOfOptedInKBs(t *testing.T) {+ // One store group can hold KBs on both sides of the switch.+ g := &storeGroup{ImageKBIDs: recalls("kb-on"), VectorThreshold: 0.3}+ vector := &types.RetrieveResult{RetrieverType: types.VectorRetrieverType, Results: []*types.IndexWithScore{+ kbHit("kb-on", "image-on", 0.25, types.ImageSourceType),+ kbHit("kb-off", "image-off", 0.9, types.ImageSourceType),+ kbHit("kb-off", "text-off", 0.6, types.ChunkSourceType),+ }}+ filterImageHits([]*types.RetrieveResult{vector}, g)+ assert.Equal(t, []string{"image-on", "text-off"}, ids(vector.Results))+}++// imageRecallModels hands out one embedding model and records each lookup.+type imageRecallModels struct {+ interfaces.ModelService+ model embedding.Embedder+ requested []string+}++func (m *imageRecallModels) GetEmbeddingModel(_ context.Context, id string) (embedding.Embedder, error) {+ m.requested = append(m.requested, id)+ return m.model, nil+}++func TestApplyImageRecallNeedsTheKBSwitchAndAnImageModel(t *testing.T) {+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))+ vectorKB := func(id string, imageVectors bool) *types.KnowledgeBase {+ return &types.KnowledgeBase{+ ID: id, TenantID: 1, EmbeddingModelID: "embed-1",+ IndexingStrategy: types.IndexingStrategy{VectorEnabled: true},+ ImageProcessingConfig: types.ImageProcessingConfig{ImageVectorEnabled: imageVectors},+ }+ }+ params := types.SearchParams{VectorThreshold: 0.3}++ cases := []struct {+ name string+ kbs []*types.KnowledgeBase+ model embedding.Embedder+ params types.SearchParams+ want map[string]struct{}+ modelResolved bool+ }{+ {+ // Every KB from before the switch: the image-capable model is+ // not even looked up.+ name: "switch off, image model",+ kbs: []*types.KnowledgeBase{vectorKB("kb-a", false)},+ model: &imageModel{dims: 3}, params: params,+ },+ {+ name: "switch on, text-only model",+ kbs: []*types.KnowledgeBase{vectorKB("kb-a", true)},+ model: &textModel{}, params: params, modelResolved: true,+ },+ {+ name: "switch on, vector match disabled",+ kbs: []*types.KnowledgeBase{vectorKB("kb-a", true)},+ model: &imageModel{dims: 3}, params: types.SearchParams{DisableVectorMatch: true},+ },+ {+ name: "switch on, image model",+ kbs: []*types.KnowledgeBase{vectorKB("kb-a", true), vectorKB("kb-b", false)},+ model: &imageModel{dims: 3}, params: params,+ want: recalls("kb-a"), modelResolved: true,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ models := &imageRecallModels{model: tc.model}+ s := &knowledgeBaseService{modelService: models}+ g := &storeGroup{KBIDs: []string{"kb-a", "kb-b"}, TopK: 100, BaseParams: []types.RetrieveParams{+ {RetrieverType: types.VectorRetrieverType, Threshold: 0.3},+ }}+ s.applyImageRecall(ctx, tc.kbs, []*storeGroup{g}, tc.params)++ assert.Equal(t, tc.modelResolved, len(models.requested) > 0)+ if tc.want == nil {+ assert.False(t, g.imageRecall())+ got := paramsWithTopK(g)+ require.Len(t, got, 1)+ assert.Equal(t, 100, got[0].TopK, "the pool is not widened")+ assert.Equal(t, 0.3, got[0].Threshold, "the threshold is not lowered")+ return+ }+ assert.Equal(t, tc.want, g.ImageKBIDs)+ assert.Equal(t, 0.3, g.VectorThreshold)+ got := paramsWithTopK(g)+ assert.Equal(t, 150, got[0].TopK)+ assert.Equal(t, imageVectorThreshold, got[0].Threshold)+ })+ }+}++// rankedEngine answers each search with the first TopK rows of its ranking,+// cut as an engine cuts its own, and records the TopK each search asked for.+type rankedEngine struct {+ fakeRetrieveEngineService+ ranked map[types.RetrieverType][]*types.IndexWithScore+ mu sync.Mutex+ topKs map[types.RetrieverType][]int+}++func (e *rankedEngine) Retrieve(_ context.Context, p types.RetrieveParams) ([]*types.RetrieveResult, error) {+ e.mu.Lock()+ if e.topKs == nil {+ e.topKs = make(map[types.RetrieverType][]int)+ }+ e.topKs[p.RetrieverType] = append(e.topKs[p.RetrieverType], p.TopK)+ e.mu.Unlock()+ rows := e.ranked[p.RetrieverType]+ return []*types.RetrieveResult{{+ Results: slices.Clone(rows[:min(p.TopK, len(rows))]),+ RetrieverEngineType: types.PostgresRetrieverEngineType,+ RetrieverType: p.RetrieverType,+ }}, nil+}++// rankedHits is n hits of one kind in knowledge base kbID, best first.+func rankedHits(kbID, prefix string, n int, from float64, source types.SourceType) []*types.IndexWithScore {+ out := make([]*types.IndexWithScore, n)+ for i := range out {+ out[i] = kbHit(kbID, fmt.Sprintf("%s%d", prefix, i), from-float64(i)*1e-4, source)+ }+ return out+}++func TestRetrieveFromStoresRefillsPastStaleImageVectors(t *testing.T) {+ cases := []struct {+ name string+ imageKBs map[string]struct{}+ stale int // image rows of the KB, ranked above all its text+ text int+ wantText int+ wantImages int+ wantTopKs []int+ }{+ {+ // MatchCount 5 over-retrieves a pool of 50, all of it image rows+ // of a KB that has since turned image vectors off.+ name: "the whole pool is stale", stale: 50, text: 10,+ wantText: 10, wantTopKs: []int{50, 100},+ },+ {+ name: "stale rows push text out of the pool", stale: 120, text: 200,+ wantText: 50, wantTopKs: []int{50, 100, 200},+ },+ {+ // Past the cap the search stays short: the stated bound.+ name: "more stale rows than the largest pool", stale: 600, text: 10,+ wantTopKs: []int{50, 100, 200, 400, maxRetrievalPoolSize},+ },+ {+ name: "a pool that is not full is not searched again", stale: 5, text: 10,+ wantText: 10, wantTopKs: []int{50},+ },+ {+ name: "images of a KB that recalls them are not stale", imageKBs: recalls("kb"),+ stale: 50, text: 10, wantText: 10, wantImages: 50, wantTopKs: []int{75},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ engine := &rankedEngine{+ fakeRetrieveEngineService: fakeRetrieveEngineService{+ engineType: types.PostgresRetrieverEngineType,+ support: []types.RetrieverType{types.VectorRetrieverType, types.KeywordsRetrieverType},+ },+ ranked: map[types.RetrieverType][]*types.IndexWithScore{+ types.VectorRetrieverType: append(+ rankedHits("kb", "image", tc.stale, 0.9, types.ImageSourceType),+ rankedHits("kb", "text", tc.text, 0.5, types.ChunkSourceType)...),+ types.KeywordsRetrieverType: rankedHits("kb", "kw", 3, 0.9, types.ChunkSourceType),+ },+ }+ g := &storeGroup{+ KBIDs: []string{"kb"}, Engine: buildBoundComposite(t, engine), TopK: 50,+ ImageKBIDs: tc.imageKBs,+ BaseParams: []types.RetrieveParams{+ {RetrieverType: types.VectorRetrieverType},+ {RetrieverType: types.KeywordsRetrieverType},+ },+ }+ res, err := (&knowledgeBaseService{}).retrieveFromStores(+ context.Background(), []*storeGroup{g}, nil)+ require.NoError(t, err)++ var text, images, keyword int+ for _, rr := range res {+ for _, h := range rr.Results {+ switch {+ case rr.RetrieverType == types.KeywordsRetrieverType:+ keyword+++ case h.SourceType == types.ImageSourceType:+ images+++ default:+ text+++ }+ }+ }+ assert.Equal(t, tc.wantText, text)+ assert.Equal(t, tc.wantImages, images)+ assert.Equal(t, 3, keyword, "the keyword search is left as it was")+ assert.Equal(t, tc.wantTopKs, engine.topKs[types.VectorRetrieverType])+ assert.Equal(t, []int{50}, engine.topKs[types.KeywordsRetrieverType],+ "only the document vector search runs again")+ })+ }+}++// interleave alternates the hits of a and b, a first, then appends the rest.+func interleave(a, b []*types.IndexWithScore) []*types.IndexWithScore {+ out := make([]*types.IndexWithScore, 0, len(a)+len(b))+ for i := 0; i < max(len(a), len(b)); i++ {+ if i < len(a) {+ out = append(out, a[i])+ }+ if i < len(b) {+ out = append(out, b[i])+ }+ }+ return out+}++func TestRetrieveFromStoresRefillsPastKeywordImageRows(t *testing.T) {+ cases := []struct {+ name string+ imageKBs map[string]struct{}+ ranked []*types.IndexWithScore+ wantText int+ wantTopKs []int+ }{+ {+ // An engine that ranks every image row above the text, as a+ // constant keyword score can, fills the whole pool with them.+ name: "the whole pool is image rows",+ ranked: append(rankedHits("kb", "image", 50, 0.9, types.ImageSourceType),+ rankedHits("kb", "text", 10, 0.5, types.ChunkSourceType)...),+ wantText: 10, wantTopKs: []int{50, 100},+ },+ {+ // An image row's Content is its caption, so it ranks beside the+ // caption's own chunk and takes half the pool.+ name: "image rows beside their captions", imageKBs: recalls("kb"),+ ranked: interleave(rankedHits("kb", "image", 100, 0.9, types.ImageSourceType),+ rankedHits("kb", "text", 200, 0.9, types.ChunkSourceType)),+ wantText: 50, wantTopKs: []int{50, 100},+ },+ {+ name: "a pool that is not full is not searched again",+ ranked: append(rankedHits("kb", "image", 5, 0.9, types.ImageSourceType),+ rankedHits("kb", "text", 10, 0.5, types.ChunkSourceType)...),+ wantText: 10, wantTopKs: []int{50},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ engine := &rankedEngine{+ fakeRetrieveEngineService: fakeRetrieveEngineService{+ engineType: types.PostgresRetrieverEngineType,+ support: []types.RetrieverType{types.VectorRetrieverType, types.KeywordsRetrieverType},+ },+ ranked: map[types.RetrieverType][]*types.IndexWithScore{+ types.VectorRetrieverType: rankedHits("kb", "vec", 3, 0.9, types.ChunkSourceType),+ types.KeywordsRetrieverType: tc.ranked,+ },+ }+ g := &storeGroup{+ KBIDs: []string{"kb"}, Engine: buildBoundComposite(t, engine), TopK: 50,+ ImageKBIDs: tc.imageKBs,+ BaseParams: []types.RetrieveParams{+ {RetrieverType: types.VectorRetrieverType},+ {RetrieverType: types.KeywordsRetrieverType},+ },+ }+ res, err := (&knowledgeBaseService{}).retrieveFromStores(+ context.Background(), []*storeGroup{g}, nil)+ require.NoError(t, err)++ var keyword []*types.IndexWithScore+ for _, rr := range res {+ if rr.RetrieverType == types.KeywordsRetrieverType {+ keyword = append(keyword, rr.Results...)+ }+ }+ assert.Len(t, keyword, tc.wantText)+ for _, h := range keyword {+ assert.Equal(t, types.ChunkSourceType, h.SourceType)+ }+ assert.Equal(t, tc.wantTopKs, engine.topKs[types.KeywordsRetrieverType])+ assert.Len(t, engine.topKs[types.VectorRetrieverType], 1,+ "a vector pool without dropped rows is not searched again")+ })+ }+}++// flakyRefillEngine answers the first search of each retriever type in full+// and every later one, a refill, as refill says.+type flakyRefillEngine struct {+ rankedEngine+ refill func(rows []*types.IndexWithScore) ([]*types.RetrieveResult, error)+}++func (e *flakyRefillEngine) Retrieve(ctx context.Context, p types.RetrieveParams) ([]*types.RetrieveResult, error) {+ res, err := e.rankedEngine.Retrieve(ctx, p)+ e.mu.Lock()+ calls := len(e.topKs[p.RetrieverType])+ e.mu.Unlock()+ if calls == 1 || err != nil {+ return res, err+ }+ return e.refill(res[0].Results)+}++func TestRetrieveFromStoresKeepsThePoolWhenARefillIsIncomplete(t *testing.T) {+ cases := []struct {+ name string+ refill func(rows []*types.IndexWithScore) ([]*types.RetrieveResult, error)+ }{+ {+ // The collection holding the text did not answer the larger+ // search: what came back is the image rows alone.+ name: "the refill answers in part",+ refill: func(rows []*types.IndexWithScore) ([]*types.RetrieveResult, error) {+ var images []*types.IndexWithScore+ for _, h := range rows {+ if h.SourceType == types.ImageSourceType {+ images = append(images, h)+ }+ }+ return []*types.RetrieveResult{{+ Results: images,+ RetrieverEngineType: types.PostgresRetrieverEngineType,+ RetrieverType: types.VectorRetrieverType,+ Error: errors.New("collection text: unavailable"),+ }}, nil+ },+ },+ {+ name: "the refill fails",+ refill: func([]*types.IndexWithScore) ([]*types.RetrieveResult, error) {+ return nil, errors.New("store unavailable")+ },+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ engine := &flakyRefillEngine{+ rankedEngine: rankedEngine{+ fakeRetrieveEngineService: fakeRetrieveEngineService{+ engineType: types.PostgresRetrieverEngineType,+ support: []types.RetrieverType{types.VectorRetrieverType, types.KeywordsRetrieverType},+ },+ ranked: map[types.RetrieverType][]*types.IndexWithScore{+ // A full first pool: 40 stale image rows above 10 text.+ types.VectorRetrieverType: append(+ rankedHits("kb", "image", 40, 0.9, types.ImageSourceType),+ rankedHits("kb", "text", 10, 0.5, types.ChunkSourceType)...),+ types.KeywordsRetrieverType: rankedHits("kb", "kw", 3, 0.9, types.ChunkSourceType),+ },+ },+ refill: tc.refill,+ }+ g := &storeGroup{+ KBIDs: []string{"kb"}, Engine: buildBoundComposite(t, engine), TopK: 50,+ BaseParams: []types.RetrieveParams{+ {RetrieverType: types.VectorRetrieverType},+ {RetrieverType: types.KeywordsRetrieverType},+ },+ }+ res, err := (&knowledgeBaseService{}).retrieveFromStores(+ context.Background(), []*storeGroup{g}, nil)+ require.NoError(t, err)++ var vector []*types.IndexWithScore+ for _, rr := range res {+ if rr.RetrieverType == types.VectorRetrieverType {+ vector = append(vector, rr.Results...)+ }+ }+ assert.Equal(t, ids(rankedHits("kb", "text", 10, 0.5, types.ChunkSourceType)), ids(vector),+ "the text hits of the complete first pool survive an incomplete refill")+ assert.Equal(t, []int{50, 100}, engine.topKs[types.VectorRetrieverType])+ })+ }+}diff --git a/internal/application/service/knowledgebase_search_results.go b/internal/application/service/knowledgebase_search_results.goindex 096853eac..b4c03c452 100644--- a/internal/application/service/knowledgebase_search_results.go+++ b/internal/application/service/knowledgebase_search_results.go@@ -195,10 +195,10 @@ func (s *knowledgeBaseService) collectParentChunkIDs(return ids}-// hasImageChunks returns true if any chunk is an image_ocr or image_caption type.+// hasImageChunks returns true if any chunk is one of the image child types.func (s *knowledgeBaseService) hasImageChunks(chunks []*types.Chunk) bool {for _, c := range chunks {- if c.ChunkType == types.ChunkTypeImageOCR || c.ChunkType == types.ChunkTypeImageCaption {+ if types.IsImageChildChunkType(c.ChunkType) {return true}}@@ -378,6 +378,6 @@ func (s *knowledgeBaseService) isSearchableChunk(chunk *types.Chunk) bool {types.ChunkTypeText, types.ChunkTypeSummary,types.ChunkTypeTableColumn, types.ChunkTypeTableSummary,types.ChunkTypeFAQ,- types.ChunkTypeImageOCR, types.ChunkTypeImageCaption,+ types.ChunkTypeImageOCR, types.ChunkTypeImageCaption, types.ChunkTypeImageVector,}, chunk.ChunkType)}diff --git a/internal/application/service/knowledgebase_search_storegroup.go b/internal/application/service/knowledgebase_search_storegroup.goindex 00f5dc694..14f1923d5 100644--- a/internal/application/service/knowledgebase_search_storegroup.go+++ b/internal/application/service/knowledgebase_search_storegroup.go@@ -62,6 +62,20 @@ type storeGroup struct {// (knowledgebase_search_faq.go) updates this between calls to// retrieveFromStores. Single-shot HybridSearch sets it once.TopK int++ // ImageKBIDs are the KBs of this group whose image vectors the search+ // recalls: they opted in (KnowledgeBase.IsImageVectorEnabled) and the+ // embedding model embeds images. When it is non-empty the group's+ // document vector search is widened to find image rows, and+ // VectorThreshold is the text threshold, which filterImageHits restores+ // on text hits. Image hits of any other KB are dropped.+ ImageKBIDs map[string]struct{}+ VectorThreshold float64+}++// imageRecall reports whether any KB of the group recalls image vectors.+func (g *storeGroup) imageRecall() bool {+ return len(g.ImageKBIDs) > 0}// resolveStoreGroups partitions kbs by (VectorStoreID, KB.TenantID),diff --git a/internal/application/service/retriever/precomputed.go b/internal/application/service/retriever/precomputed.gonew file mode 100644index 000000000..18d441c4c--- /dev/null+++ b/internal/application/service/retriever/precomputed.go@@ -0,0 +1,85 @@+package retriever++import (+ "context"+ "fmt"+ "slices"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/models/embedding"+ "github.com/Tencent/WeKnora/internal/types"+)++// BatchIndexVectors saves index rows whose vectors were computed elsewhere:+// an image embedded by a multimodal model, which no text embedder could+// reproduce from the row's Content. vectors[i] belongs to indexInfoList[i].+//+// It goes through the same per-engine BatchIndex as text, so every backend+// stores these rows exactly as it stores any other, but only on engines that+// serve vector retrieval: the rows are for vector recall, and a keyword-only+// engine (Elasticsearch v7) would hold nothing but their caption, which the+// caption's own chunk already indexes. An engine serving both kinds keeps+// one row for both, so its keyword search still meets them; retrieval+// discards those hits and refills the pool past them.+func (c *CompositeRetrieveEngine) BatchIndexVectors(ctx context.Context,+ model embedding.Embedder, indexInfoList []*types.IndexInfo, vectors [][]float32,+) error {+ if len(indexInfoList) != len(vectors) {+ return fmt.Errorf("%d vectors for %d index rows", len(vectors), len(indexInfoList))+ }+ // Each engine pairs rows with vectors by position. The composite's own+ // BatchIndex de-duplicates by SourceID and does not keep the order, so+ // this refuses duplicates instead and hands the list over as it is.+ seen := make(map[string]struct{}, len(indexInfoList))+ for _, info := range indexInfoList {+ if _, dup := seen[info.SourceID]; dup {+ return fmt.Errorf("source id %s appears twice", info.SourceID)+ }+ seen[info.SourceID] = struct{}{}+ }+ embedder := &precomputedEmbedder{Embedder: model, vectors: vectors}+ return c.concurrentExecWithError(ctx, func(ctx context.Context, info *engineInfo) error {+ if !slices.Contains(info.retrieverType, types.VectorRetrieverType) {+ return nil+ }+ if err := info.retrieveEngine.BatchIndex(ctx, embedder, indexInfoList, info.retrieverType); err != nil {+ logger.Errorf(ctx, "Repository %s failed to save precomputed vectors: %v",+ info.retrieveEngine.EngineType(), err)+ return err+ }+ return nil+ })+}++// precomputedEmbedder answers with vectors computed beforehand, in the order+// they were given. Everything else — name, id, dimensions — is the model's+// that produced them.+type precomputedEmbedder struct {+ embedding.Embedder+ vectors [][]float32+}++func (p *precomputedEmbedder) take(n int) ([][]float32, error) {+ if n != len(p.vectors) {+ return nil, fmt.Errorf("asked for %d precomputed vectors, have %d", n, len(p.vectors))+ }+ return p.vectors, nil+}++func (p *precomputedEmbedder) Embed(_ context.Context, _ string) ([]float32, error) {+ vectors, err := p.take(1)+ if err != nil {+ return nil, err+ }+ return vectors[0], nil+}++func (p *precomputedEmbedder) BatchEmbed(_ context.Context, texts []string) ([][]float32, error) {+ return p.take(len(texts))+}++func (p *precomputedEmbedder) BatchEmbedWithPool(+ _ context.Context, _ embedding.Embedder, texts []string,+) ([][]float32, error) {+ return p.take(len(texts))+}diff --git a/internal/application/service/retriever/precomputed_test.go b/internal/application/service/retriever/precomputed_test.gonew file mode 100644index 000000000..cb1e17e3b--- /dev/null+++ b/internal/application/service/retriever/precomputed_test.go@@ -0,0 +1,86 @@+package retriever++import (+ "context"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type recordingRepository struct {+ saveOnlyRepository+ rows []*types.IndexInfo+ embeddings map[string][]float32+}++func (r *recordingRepository) BatchSave(+ _ context.Context, indexInfoList []*types.IndexInfo, params map[string]any,+) error {+ r.rows = append(r.rows, indexInfoList...)+ if m, ok := params["embedding"].(map[string][]float32); ok {+ if r.embeddings == nil {+ r.embeddings = map[string][]float32{}+ }+ for k, v := range m {+ r.embeddings[k] = v+ }+ }+ return nil+}++func compositeOver(repo *recordingRepository, retrievers ...types.RetrieverType) *CompositeRetrieveEngine {+ return &CompositeRetrieveEngine{engineInfos: []*engineInfo{{+ retrieveEngine: &KeywordsVectorHybridRetrieveEngineService{indexRepository: repo},+ retrieverType: retrievers,+ }}}+}++func TestBatchIndexVectorsStoresTheGivenVectorsNotTheTextOnes(t *testing.T) {+ repo := &recordingRepository{}+ c := compositeOver(repo, types.KeywordsRetrieverType, types.VectorRetrieverType)+ // The model would embed the caption as text; the stored vector must be+ // the image's.+ model := &capturingEmbedder{}+ rows := []*types.IndexInfo{+ {SourceID: "a", ChunkID: "a", Content: "a red bicycle", SourceType: types.ImageSourceType},+ {SourceID: "b", ChunkID: "b", Content: "a blue car", SourceType: types.ImageSourceType},+ }+ require.NoError(t, c.BatchIndexVectors(context.Background(), model, rows, [][]float32{{0.1, 0.2}, {0.3, 0.4}}))++ assert.Empty(t, model.batchTexts, "the text embedder is never asked")+ assert.Equal(t, map[string][]float32{"a": {0.1, 0.2}, "b": {0.3, 0.4}}, repo.embeddings)+ require.Len(t, repo.rows, 2)+ assert.Equal(t, types.ImageSourceType, repo.rows[0].SourceType)+}++func TestBatchIndexVectorsSkipsKeywordOnlyEngines(t *testing.T) {+ keywordOnly, vector := &recordingRepository{}, &recordingRepository{}+ c := &CompositeRetrieveEngine{engineInfos: []*engineInfo{+ {+ retrieveEngine: &KeywordsVectorHybridRetrieveEngineService{indexRepository: keywordOnly},+ retrieverType: []types.RetrieverType{types.KeywordsRetrieverType},+ },+ {+ retrieveEngine: &KeywordsVectorHybridRetrieveEngineService{indexRepository: vector},+ retrieverType: []types.RetrieverType{types.VectorRetrieverType},+ },+ }}+ rows := []*types.IndexInfo{{SourceID: "a", ChunkID: "a", Content: "caption", SourceType: types.ImageSourceType}}+ require.NoError(t, c.BatchIndexVectors(context.Background(), &capturingEmbedder{}, rows, [][]float32{{0.1}}))++ assert.Empty(t, keywordOnly.rows, "an image row would hold only its caption in a keyword-only index")+ assert.Len(t, vector.rows, 1)+}++func TestBatchIndexVectorsRefusesWhatWouldMisalignVectors(t *testing.T) {+ c := compositeOver(&recordingRepository{}, types.VectorRetrieverType)+ rows := []*types.IndexInfo{{SourceID: "a"}, {SourceID: "a"}}+ assert.ErrorContains(t,+ c.BatchIndexVectors(context.Background(), &capturingEmbedder{}, rows, [][]float32{{1}, {2}}),+ "appears twice")+ assert.ErrorContains(t,+ c.BatchIndexVectors(context.Background(), &capturingEmbedder{}, rows[:1], [][]float32{{1}, {2}}),+ "2 vectors for 1")+}diff --git a/internal/handler/dto/model.go b/internal/handler/dto/model.goindex d57051971..4cf37f91b 100644--- a/internal/handler/dto/model.go+++ b/internal/handler/dto/model.go@@ -193,8 +193,10 @@ type ModelResponse struct {// Per-field "configured?" map. Omitted for builtin models unless the// caller is a system administrator. See MCPServiceResponse.Credentials.Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`- // Capabilities is the catalog view of the model: protocol, whether it- // can think and at which levels, context window. Chat models only.+ // Capabilities is the catalog view of the model. Chat models get the+ // protocol, thinking levels and context window; embedding models get the+ // input modalities, which decide whether images can be embedded in the+ // same space as text.Capabilities *modelruntime.Capabilities `json:"capabilities,omitempty"`}@@ -308,7 +310,8 @@ func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {}}var caps *modelruntime.Capabilities- if m.Type == types.ModelTypeKnowledgeQA || m.Type == types.ModelTypeVLLM {+ switch m.Type {+ case types.ModelTypeKnowledgeQA, types.ModelTypeVLLM, types.ModelTypeEmbedding:if resolved, err := modelruntime.Resolve(modelruntime.Ref{Provider: m.Parameters.Provider, Model: m.Name, BaseURL: m.Parameters.BaseURL,ModelType: m.Type, Extra: m.Parameters.ExtraConfig, Override: m.Parameters.Spec,diff --git a/internal/handler/dto/model_test.go b/internal/handler/dto/model_test.goindex acda26383..a5114e2da 100644--- a/internal/handler/dto/model_test.go+++ b/internal/handler/dto/model_test.go@@ -3,6 +3,7 @@ package dtoimport ("context""encoding/json"+ "slices""strings""testing"@@ -339,3 +340,38 @@ func TestNewModelResponseStripsSpecFromNonAdmins(t *testing.T) {t.Errorf("NewModelResponse must not clear the stored spec")}}++func TestNewModelResponseReportsEmbeddingInputModalities(t *testing.T) {+ // Whether an embedding model maps images into the same space as text is+ // what decides if a knowledge base can store image vectors. The catalog+ // knows it for listed models; a row can declare it through spec.input.+ declare := func(input ...string) *types.ModelSpecOverride { return &types.ModelSpecOverride{Input: input} }+ embedding := func(provider, name string, spec *types.ModelSpecOverride) *types.Model {+ return &types.Model{+ ID: "e1", Name: name, Type: types.ModelTypeEmbedding, Source: types.ModelSourceRemote,+ Parameters: types.ModelParameters{Provider: provider, Spec: spec},+ }+ }+ viewer := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)+ cases := []struct {+ name string+ model *types.Model+ image bool+ }{+ {"catalog multimodal", embedding("volcengine", "doubao-embedding-vision-251215", nil), true},+ {"catalog pattern", embedding("aliyun", "qwen3-vl-embedding", nil), true},+ {"catalog text only", embedding("openai", "text-embedding-3-small", nil), false},+ {"row declares image", embedding("openai", "my-clip", declare("text", "image")), true},+ {"row narrows catalog", embedding("jina", "jina-embeddings-v4", declare("text")), false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ // A viewer never sees spec, but the capability it implies is+ // not configuration and stays visible.+ caps := NewModelResponse(viewer, tc.model).Capabilities+ require.NotNil(t, caps)+ assert.Equal(t, tc.image, slices.Contains(caps.Input, "image"), "input=%v", caps.Input)+ assert.Empty(t, caps.ThinkingLevels, "an embedding model does not think")+ })+ }+}diff --git a/internal/models/api/arkembeddings/client.go b/internal/models/api/arkembeddings/client.goindex a4eb00fa3..538fafa13 100644--- a/internal/models/api/arkembeddings/client.go+++ b/internal/models/api/arkembeddings/client.go@@ -57,6 +57,23 @@ func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[strifor _, text := range texts {input = append(input, map[string]any{"type": "text", "text": text})}+ return c.body(input)+}++// BuildImageRequestBody is the golden-test entry point for images. The+// reference takes an image as a URL or as+// "data:image/{图片格式};base64,{图片Base64编码}" under image_url.url.+func (c *Client) BuildImageRequestBody(images []api.EmbedImage, _ api.EmbedInputType) map[string]any {+ input := make([]any, 0, len(images))+ for _, img := range images {+ input = append(input, map[string]any{+ "type": "image_url", "image_url": map[string]any{"url": img.DataURI()},+ })+ }+ return c.body(input)+}++func (c *Client) body(input []any) map[string]any {body := map[string]any{"model": c.cfg.Endpoint.Model,"input": input,@@ -87,11 +104,29 @@ func (c *Client) Embed(len(texts),)}+ return c.post(ctx, c.BuildRequestBody(texts, kind))+}++// AcceptsImages is always true: the image part is part of the schema.+func (c *Client) AcceptsImages() bool { return true }++// EmbedImages vectorizes one image, for the same reason Embed takes one text.+func (c *Client) EmbedImages(+ ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,+) ([][]float32, error) {+ if len(images) != 1 {+ return nil, fmt.Errorf(+ "ark embedding fuses its input into one vector, so it takes one image per request, got %d",+ len(images),+ )+ }+ return c.post(ctx, c.BuildImageRequestBody(images, kind))+}++func (c *Client) post(ctx context.Context, body map[string]any) ([][]float32, error) {var decoded responseurl := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)- err := c.cfg.Endpoint.PostJSONWithRetry(- ctx, url, c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",- )+ err := c.cfg.Endpoint.PostJSONWithRetry(ctx, url, body, &decoded, c.cfg.Retry, "embedding")if err != nil {return nil, err}diff --git a/internal/models/api/dashscopeembeddings/client.go b/internal/models/api/dashscopeembeddings/client.goindex 3ca334633..eede07501 100644--- a/internal/models/api/dashscopeembeddings/client.go+++ b/internal/models/api/dashscopeembeddings/client.go@@ -54,6 +54,20 @@ func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[strifor _, text := range texts {contents = append(contents, map[string]any{"text": text})}+ return c.body(contents)+}++// BuildImageRequestBody is the golden-test entry point for images. Each+// content is {"image": URL or "data:image/{format};base64,{data}"}.+func (c *Client) BuildImageRequestBody(images []api.EmbedImage, _ api.EmbedInputType) map[string]any {+ contents := make([]any, 0, len(images))+ for _, img := range images {+ contents = append(contents, map[string]any{"image": img.DataURI()})+ }+ return c.body(contents)+}++func (c *Client) body(contents []any) map[string]any {body := map[string]any{"model": c.cfg.Endpoint.Model,"input": map[string]any{"contents": contents},@@ -75,11 +89,23 @@ func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[strifunc (c *Client) Embed(ctx context.Context, texts []string, kind api.EmbedInputType,) ([][]float32, error) {+ return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))+}++// AcceptsImages is always true: the image part is part of the schema.+func (c *Client) AcceptsImages() bool { return true }++// EmbedImages vectorizes one batch of images, each its own vector.+func (c *Client) EmbedImages(+ ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,+) ([][]float32, error) {+ return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))+}++func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {var decoded responseurl := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)- err := c.cfg.Endpoint.PostJSONWithRetry(- ctx, url, c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",- )+ err := c.cfg.Endpoint.PostJSONWithRetry(ctx, url, body, &decoded, c.cfg.Retry, "embedding")if err != nil {return nil, err}@@ -87,7 +113,7 @@ func (c *Client) Embed(if decoded.Code != "" {return nil, fmt.Errorf("DashScope embedding error %s: %s", decoded.Code, decoded.Message)}- return api.PlaceEmbeddings(len(texts), len(decoded.Output.Embeddings), func(i int) (int, []float32) {+ return api.PlaceEmbeddings(want, len(decoded.Output.Embeddings), func(i int) (int, []float32) {return decoded.Output.Embeddings[i].Index, decoded.Output.Embeddings[i].Embedding})}diff --git a/internal/models/api/embeddings.go b/internal/models/api/embeddings.goindex d0b6d972c..ef8437671 100644--- a/internal/models/api/embeddings.go+++ b/internal/models/api/embeddings.go@@ -2,6 +2,7 @@ package apiimport ("context"+ "encoding/base64""fmt")@@ -55,6 +56,31 @@ type Embedder interface {Embed(ctx context.Context, texts []string, kind EmbedInputType) ([][]float32, error)}+// EmbedImage is one image to embed. It travels inline rather than as a URL:+// the object store WeKnora reads images from is usually not reachable from+// the vendor, and every multimodal vendor in the catalog accepts base64.+type EmbedImage struct {+ Data []byte+ MIMEType string+}++// Base64 is the image in standard base64, Gemini's inlineData form.+func (i EmbedImage) Base64() string { return base64.StdEncoding.EncodeToString(i.Data) }++// DataURI is the data:{mime};base64,{data} form Ark, DashScope and Jina+// document.+func (i EmbedImage) DataURI() string { return "data:" + i.MIMEType + ";base64," + i.Base64() }++// ImageEmbedder is implemented by the protocols that can carry an image.+// Whether a given model maps images into the space of its text vectors is+// the catalog entry's input, not the protocol's, so the caller checks that+// first. Callers pass a batch within EmbeddingsSettings.ImageBatchLimit.+type ImageEmbedder interface {+ // AcceptsImages reports whether this endpoint can carry an image at all.+ AcceptsImages() bool+ EmbedImages(ctx context.Context, images []EmbedImage, kind EmbedInputType) ([][]float32, error)+}+// PlaceEmbeddings puts returned vectors back in the order the texts were// sent, using the index each vendor reports, and refuses a response that does// not cover every input.diff --git a/internal/models/api/embeddings_settings.go b/internal/models/api/embeddings_settings.goindex 85db5fdc9..55a342c1f 100644--- a/internal/models/api/embeddings_settings.go+++ b/internal/models/api/embeddings_settings.go@@ -1,5 +1,10 @@package api+import (+ "fmt"+ "slices"+)+// EmbeddingsCompat is the overlay form (every field optional) of the// embedding settings. JSON keys are the documented names used in models.json// and config/models.json.@@ -22,6 +27,10 @@ type EmbeddingsCompat struct {AcceptsTruncatePromptTokens *bool `json:"accepts_truncate_prompt_tokens,omitempty"`RequestTimeout *int `json:"request_timeout_seconds,omitempty"`ExtraBody map[string]any `json:"extra_body,omitempty"`+ ImageField *string `json:"image_field,omitempty"`+ MaxImageBatchSize *int `json:"max_image_batch_size,omitempty"`+ MaxImageBytes *int `json:"max_image_bytes,omitempty"`+ ImageMIMETypes []string `json:"image_mime_types,omitempty"`}// EmbeddingsSettings is the resolved (fully defaulted) form.@@ -67,6 +76,22 @@ type EmbeddingsSettings struct {// without its own deadline and lets the caller's context govern.RequestTimeout intExtraBody map[string]any+ // ImageField is the key of the input object that carries an image on+ // the OpenAI shape — "image" on Jina. That shape has no standard image+ // input, so an endpoint that does not name one takes no images. The+ // multimodal protocols have their image part fixed by their own schema.+ ImageField string `json:",omitempty"`+ // MaxImageBatchSize is the documented number of images per request.+ // 0 means one: a vendor that fuses its inputs, or does not say, must not+ // be sent several.+ MaxImageBatchSize int `json:",omitempty"`+ // MaxImageBytes is the documented size limit of one image, 0 when the+ // vendor states none. The caller shrinks an image to fit; the client+ // refuses one that does not rather than spend a request on it.+ MaxImageBytes int `json:",omitempty"`+ // ImageMIMETypes lists the formats the vendor documents, empty when it+ // takes any common one.+ ImageMIMETypes []string `json:",omitempty"`}// BatchLimits renders the documented ceilings for SplitBatches.@@ -74,6 +99,28 @@ func (s EmbeddingsSettings) BatchLimits() BatchLimits {return BatchLimits{MaxItems: s.MaxBatchSize, MaxItemRunes: s.MaxInputChars}}+// ImageBatchLimit is the number of images one request may carry.+func (s EmbeddingsSettings) ImageBatchLimit() int {+ if s.MaxImageBatchSize > 0 {+ return s.MaxImageBatchSize+ }+ return 1+}++// CheckImage reports an image the vendor documents it will not take.+func (s EmbeddingsSettings) CheckImage(img EmbedImage) error {+ if len(img.Data) == 0 {+ return fmt.Errorf("image is empty")+ }+ if s.MaxImageBytes > 0 && len(img.Data) > s.MaxImageBytes {+ return fmt.Errorf("image is %d bytes; the limit is %d", len(img.Data), s.MaxImageBytes)+ }+ if len(s.ImageMIMETypes) > 0 && !slices.Contains(s.ImageMIMETypes, img.MIMEType) {+ return fmt.Errorf("image type %q is not one of %v", img.MIMEType, s.ImageMIMETypes)+ }+ return nil+}+// InputTypeValue maps a neutral input kind onto the vendor's vocabulary,// returning "" when this vendor does not distinguish the two sides.func (s EmbeddingsSettings) InputTypeValue(kind EmbedInputType) string {diff --git a/internal/models/api/googleembeddings/client.go b/internal/models/api/googleembeddings/client.goindex e44c81852..6d9ab43d9 100644--- a/internal/models/api/googleembeddings/client.go+++ b/internal/models/api/googleembeddings/client.go@@ -76,12 +76,33 @@ type response struct {// BuildRequestBody is the golden-test entry point.func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[string]any {- s := c.cfg.Settings- requests := make([]any, 0, len(texts))+ parts := make([]any, 0, len(texts))for _, text := range texts {+ parts = append(parts, map[string]any{"text": text})+ }+ return c.body(parts, kind)+}++// BuildImageRequestBody is the golden-test entry point for images: an image+// is an inlineData part carrying its MIME type and base64 bytes.+func (c *Client) BuildImageRequestBody(images []api.EmbedImage, kind api.EmbedInputType) map[string]any {+ parts := make([]any, 0, len(images))+ for _, img := range images {+ parts = append(parts, map[string]any{+ "inlineData": map[string]any{"mimeType": img.MIMEType, "data": img.Base64()},+ })+ }+ return c.body(parts, kind)+}++// body wraps every part in its own request, so each gets its own vector.+func (c *Client) body(parts []any, kind api.EmbedInputType) map[string]any {+ s := c.cfg.Settings+ requests := make([]any, 0, len(parts))+ for _, part := range parts {req := map[string]any{"model": c.qualifiedModel(),- "content": map[string]any{"parts": []any{map[string]any{"text": text}}},+ "content": map[string]any{"parts": []any{part}},}config := map[string]any{}if field := s.InputTypeField; field != "" {@@ -110,21 +131,33 @@ func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[sfunc (c *Client) Embed(ctx context.Context, texts []string, kind api.EmbedInputType,) ([][]float32, error) {+ return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))+}++// AcceptsImages is always true: inlineData is part of the schema.+func (c *Client) AcceptsImages() bool { return true }++// EmbedImages vectorizes one batch of images, each its own vector.+func (c *Client) EmbedImages(+ ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,+) ([][]float32, error) {+ return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))+}++func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {var decoded response- err := c.cfg.Endpoint.PostJSONWithRetry(- ctx, c.url(), c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",- )+ err := c.cfg.Endpoint.PostJSONWithRetry(ctx, c.url(), body, &decoded, c.cfg.Retry, "embedding")if err != nil {return nil, err}if decoded.Error != nil && decoded.Error.Message != "" {return nil, fmt.Errorf("gemini embedding error: %s", decoded.Error.Message)}- if len(decoded.Embeddings) != len(texts) {+ if len(decoded.Embeddings) != want {return nil, fmt.Errorf(- "gemini returned %d embeddings for %d inputs", len(decoded.Embeddings), len(texts))+ "gemini returned %d embeddings for %d inputs", len(decoded.Embeddings), want)}- return api.PlaceEmbeddings(len(texts), len(decoded.Embeddings), func(i int) (int, []float32) {+ return api.PlaceEmbeddings(want, len(decoded.Embeddings), func(i int) (int, []float32) {return i, decoded.Embeddings[i].Values})}diff --git a/internal/models/api/openaiembeddings/client.go b/internal/models/api/openaiembeddings/client.goindex 49233359a..031ed8d66 100644--- a/internal/models/api/openaiembeddings/client.go+++ b/internal/models/api/openaiembeddings/client.go@@ -75,10 +75,26 @@ type response struct {// BuildRequestBody is the golden-test entry point: it returns the exact JSON// object that would be sent.func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[string]any {+ return c.body(texts, kind)+}++// BuildImageRequestBody is the golden-test entry point for images. The shape+// has no standard image input; a vendor that extends it names the key of the+// object that carries one, and Jina's reference gives+// {"image": URL or data URI}.+func (c *Client) BuildImageRequestBody(images []api.EmbedImage, kind api.EmbedInputType) map[string]any {+ input := make([]any, 0, len(images))+ for _, img := range images {+ input = append(input, map[string]any{c.cfg.Settings.ImageField: img.DataURI()})+ }+ return c.body(input, kind)+}++func (c *Client) body(input any, kind api.EmbedInputType) map[string]any {s := c.cfg.Settingsbody := map[string]any{"model": c.cfg.Endpoint.Model,- "input": texts,+ "input": input,}if s.SendEncodingFormat {body["encoding_format"] = "float"@@ -111,17 +127,34 @@ func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[sfunc (c *Client) Embed(ctx context.Context, texts []string, kind api.EmbedInputType,) ([][]float32, error) {+ return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))+}++// AcceptsImages reports whether the vendor names an image field. Without+// one a plain OpenAI-compatible server would read the objects as malformed+// text input.+func (c *Client) AcceptsImages() bool { return c.cfg.Settings.ImageField != "" }++// EmbedImages vectorizes one batch of images, in the order it was given.+func (c *Client) EmbedImages(+ ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,+) ([][]float32, error) {+ if !c.AcceptsImages() {+ return nil, fmt.Errorf("this embedding endpoint declares no image input")+ }+ return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))+}++func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {var decoded response- err := c.cfg.Endpoint.PostJSONWithRetry(- ctx, c.url(), c.BuildRequestBody(texts, kind), &decoded, c.cfg.Retry, "embedding",- )+ err := c.cfg.Endpoint.PostJSONWithRetry(ctx, c.url(), body, &decoded, c.cfg.Retry, "embedding")if err != nil {return nil, err}if decoded.Error != nil && decoded.Error.Message != "" {return nil, fmt.Errorf("embedding API error: %s", decoded.Error.Message)}- return api.PlaceEmbeddings(len(texts), len(decoded.Data), func(i int) (int, []float32) {+ return api.PlaceEmbeddings(want, len(decoded.Data), func(i int) (int, []float32) {if decoded.Data[i].Index == nil {return i, decoded.Data[i].Embedding}diff --git a/internal/models/catalog/data/models.generated.json b/internal/models/catalog/data/models.generated.jsonindex 39d5048f7..0219e3764 100644--- a/internal/models/catalog/data/models.generated.json+++ b/internal/models/catalog/data/models.generated.json@@ -802,65 +802,107 @@"id": "tongyi-embedding-vision-plus","name": "Tongyi Embedding Vision Plus","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"dimension": 1152,"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference","compat": {"api": "dashscope-embeddings",- "dimensions_field": ""+ "dimensions_field": "",+ "max_image_batch_size": 8,+ "max_image_bytes": 3000000}},{"name": "tongyi-embedding-vision-flash (fixed 768 dimensions)","match": "tongyi-embedding-vision-flash","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference","compat": {"api": "dashscope-embeddings",- "dimensions_field": ""+ "dimensions_field": "",+ "max_image_batch_size": 8,+ "max_image_bytes": 3000000}},{"name": "tongyi-embedding-vision snapshots","match": "tongyi-embedding-vision*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference","compat": {"api": "dashscope-embeddings","dimensions_field": "dimension",- "max_batch_size": 20+ "max_batch_size": 20,+ "max_image_batch_size": 8,+ "max_image_bytes": 3000000}},{"name": "qwen3-vl-embedding (independent vectors by default)","match": "qwen3-vl-embedding*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference","compat": {"api": "dashscope-embeddings","dimensions_field": "dimension",- "max_batch_size": 20+ "max_batch_size": 20,+ "max_image_batch_size": 10,+ "max_image_bytes": 10000000}},{"name": "qwen2.5-vl-embedding (fused vectors only)","match": "qwen2.5-vl-embedding*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference","compat": {"api": "dashscope-embeddings","dimensions_field": "dimension",- "max_batch_size": 1+ "max_batch_size": 1,+ "max_image_batch_size": 1,+ "max_image_bytes": 5000000}},{"name": "multimodal-embedding-v1","match": "multimodal-embedding*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference","compat": {"api": "dashscope-embeddings","dimensions_field": "",- "max_batch_size": 20+ "max_batch_size": 20,+ "max_image_batch_size": 1,+ "max_image_bytes": 3000000}},{@@ -1865,7 +1907,14 @@"input": 0.2,"output": 0},- "source": "https://ai.google.dev/gemini-api/docs/embeddings"+ "source": "https://ai.google.dev/gemini-api/docs/embeddings",+ "compat": {+ "max_image_batch_size": 6,+ "image_mime_types": [+ "image/png",+ "image/jpeg"+ ]+ }}],"generic": [@@ -2124,6 +2173,10 @@"id": "jina-embeddings-v4","name": "Jina Embeddings v4","type": "Embedding",+ "input": [+ "text",+ "image"+ ],"dimension": 2048,"context_window": 32768,"source": "https://jina.ai/models/jina-embeddings-v4/"@@ -5527,6 +5580,11 @@"id": "doubao-embedding-vision-251215","name": "Doubao Embedding Vision (251215)","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"dimension": 2048,"source": "https://docs.volcengine.com/docs/ark/multimodal-vectorization-api?lang=zh"},@@ -5534,6 +5592,11 @@"id": "doubao-embedding-vision-250615","name": "Doubao Embedding Vision","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"dimension": 2048,"source": "https://docs.volcengine.com/docs/ark/multimodal-vectorization-api?lang=zh"},diff --git a/internal/models/catalog/data/overrides.json b/internal/models/catalog/data/overrides.jsonindex f7f6a7990..38288cee6 100644--- a/internal/models/catalog/data/overrides.json+++ b/internal/models/catalog/data/overrides.json@@ -357,7 +357,9 @@"type": "Embedding","compat": {"api": "dashscope-embeddings",- "dimensions_field": ""+ "dimensions_field": "",+ "max_image_batch_size": 8,+ "max_image_bytes": 3000000}},{@@ -365,7 +367,9 @@"type": "Embedding","compat": {"api": "dashscope-embeddings",- "dimensions_field": ""+ "dimensions_field": "",+ "max_image_batch_size": 8,+ "max_image_bytes": 3000000}},{@@ -374,7 +378,9 @@"compat": {"api": "dashscope-embeddings","dimensions_field": "dimension",- "max_batch_size": 20+ "max_batch_size": 20,+ "max_image_batch_size": 8,+ "max_image_bytes": 3000000}},{@@ -383,7 +389,9 @@"compat": {"api": "dashscope-embeddings","dimensions_field": "dimension",- "max_batch_size": 20+ "max_batch_size": 20,+ "max_image_batch_size": 10,+ "max_image_bytes": 10000000}},{@@ -392,7 +400,9 @@"compat": {"api": "dashscope-embeddings","dimensions_field": "dimension",- "max_batch_size": 1+ "max_batch_size": 1,+ "max_image_batch_size": 1,+ "max_image_bytes": 5000000}},{@@ -401,7 +411,9 @@"compat": {"api": "dashscope-embeddings","dimensions_field": "",- "max_batch_size": 20+ "max_batch_size": 20,+ "max_image_batch_size": 1,+ "max_image_bytes": 3000000}},{@@ -848,6 +860,17 @@"compat": {"thinking_mode": "budget"}+ },+ {+ "id": "gemini-embedding-2",+ "type": "Embedding",+ "compat": {+ "max_image_batch_size": 6,+ "image_mime_types": [+ "image/png",+ "image/jpeg"+ ]+ }}],"generic": [diff --git a/internal/models/catalog/data/seed.json b/internal/models/catalog/data/seed.jsonindex 6edd4c2b2..c17870732 100644--- a/internal/models/catalog/data/seed.json+++ b/internal/models/catalog/data/seed.json@@ -584,6 +584,11 @@"id": "tongyi-embedding-vision-plus","name": "Tongyi Embedding Vision Plus","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"dimension": 1152,"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},@@ -591,30 +596,55 @@"name": "tongyi-embedding-vision-flash (fixed 768 dimensions)","match": "tongyi-embedding-vision-flash","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},{"name": "tongyi-embedding-vision snapshots","match": "tongyi-embedding-vision*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},{"name": "qwen3-vl-embedding (independent vectors by default)","match": "qwen3-vl-embedding*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},{"name": "qwen2.5-vl-embedding (fused vectors only)","match": "qwen2.5-vl-embedding*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},{"name": "multimodal-embedding-v1","match": "multimodal-embedding*","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"source": "https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference"},{@@ -1497,6 +1527,10 @@"id": "jina-embeddings-v4","name": "Jina Embeddings v4","type": "Embedding",+ "input": [+ "text",+ "image"+ ],"dimension": 2048,"context_window": 32768,"source": "https://jina.ai/models/jina-embeddings-v4/"@@ -4322,6 +4356,11 @@"id": "doubao-embedding-vision-251215","name": "Doubao Embedding Vision (251215)","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"dimension": 2048,"source": "https://docs.volcengine.com/docs/ark/multimodal-vectorization-api?lang=zh"},@@ -4329,6 +4368,11 @@"id": "doubao-embedding-vision-250615","name": "Doubao Embedding Vision","type": "Embedding",+ "input": [+ "text",+ "image",+ "video"+ ],"dimension": 2048,"source": "https://docs.volcengine.com/docs/ark/multimodal-vectorization-api?lang=zh"},diff --git a/internal/models/embedding/concurrency_wrapper.go b/internal/models/embedding/concurrency_wrapper.goindex ed20e6f16..acd5f1001 100644--- a/internal/models/embedding/concurrency_wrapper.go+++ b/internal/models/embedding/concurrency_wrapper.go@@ -51,6 +51,23 @@ func (w *concurrencyEmbedder) BatchEmbedWithPool(return w.inner.BatchEmbedWithPool(ctx, w, texts)}+func (w *concurrencyEmbedder) AcceptsImages() bool {+ _, ok := AsImageEmbedder(w.inner)+ return ok+}++func (w *concurrencyEmbedder) ImageLimits() ImageLimits { return imageLimitsOf(w.inner) }++func (w *concurrencyEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {+ inner, err := imageSide(w.inner)+ if err != nil {+ return nil, err+ }+ release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)+ defer release()+ return inner.BatchEmbedImages(ctx, images)+}+func (w *concurrencyEmbedder) GetModelName() string { return w.inner.GetModelName() }func (w *concurrencyEmbedder) GetDimensions() int { return w.inner.GetDimensions() }func (w *concurrencyEmbedder) GetModelID() string { return w.inner.GetModelID() }diff --git a/internal/models/embedding/embedder.go b/internal/models/embedding/embedder.goindex 4d008c4b3..c629333b5 100644--- a/internal/models/embedding/embedder.go+++ b/internal/models/embedding/embedder.go@@ -2,10 +2,12 @@ package embeddingimport ("context"+ "errors""fmt""strings""github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/models/api""github.com/Tencent/WeKnora/internal/models/utils/ollama""github.com/Tencent/WeKnora/internal/tracing/langfuse""github.com/Tencent/WeKnora/internal/types"@@ -31,6 +33,61 @@ type Embedder interface {EmbedderPooler}+// Image is one image to embed: its bytes and MIME type.+type Image = api.EmbedImage++// ErrImagesUnsupported is returned when an embedder is asked for an image+// vector its model or endpoint cannot produce.+var ErrImagesUnsupported = errors.New("embedding model does not accept images")++// ImageEmbedder is the image side of an Embedder whose model maps images into+// the same space as its text vectors, so that a text query can find an image.+// It is a separate interface because most embedders have no image side; use+// AsImageEmbedder rather than a type assertion, since every decorator+// implements it whether or not the model underneath does.+type ImageEmbedder interface {+ // AcceptsImages reports whether both the model and its endpoint take+ // images.+ AcceptsImages() bool+ // ImageLimits are the vendor's documented per-image limits. The caller+ // shrinks or converts an image to fit; an image outside them is refused.+ ImageLimits() ImageLimits+ // BatchEmbedImages converts images to vectors comparable with Embed's.+ BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error)+}++// ImageLimits describes what one image may be. Zero values mean the vendor+// documents no limit.+type ImageLimits struct {+ MaxBytes int+ MIMETypes []string+}++// AsImageEmbedder returns e's image side when its model accepts images.+func AsImageEmbedder(e Embedder) (ImageEmbedder, bool) {+ ie, ok := e.(ImageEmbedder)+ if !ok || !ie.AcceptsImages() {+ return nil, false+ }+ return ie, true+}++// imageSide is AsImageEmbedder for decorators, which must fail a call their+// inner embedder cannot serve.+func imageSide(e Embedder) (ImageEmbedder, error) {+ if ie, ok := AsImageEmbedder(e); ok {+ return ie, nil+ }+ return nil, fmt.Errorf("%s: %w", e.GetModelName(), ErrImagesUnsupported)+}++func imageLimitsOf(e Embedder) ImageLimits {+ if ie, ok := AsImageEmbedder(e); ok {+ return ie.ImageLimits()+ }+ return ImageLimits{}+}+type EmbedderPooler interface {BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error)}diff --git a/internal/models/embedding/image_prep.go b/internal/models/embedding/image_prep.gonew file mode 100644index 000000000..bc6a48307--- /dev/null+++ b/internal/models/embedding/image_prep.go@@ -0,0 +1,107 @@+package embedding++import (+ "bytes"+ "fmt"+ "image"+ "image/color"+ _ "image/gif" // decode GIF sources+ "image/jpeg"+ "image/png"+ "net/http"+ "slices"+ "strings"++ _ "golang.org/x/image/bmp" // decode BMP sources+ "golang.org/x/image/draw"+ _ "golang.org/x/image/webp" // decode WebP sources+)++const (+ // prepJPEGQuality is the quality images are re-encoded at when they have+ // to be. Embedding models see the content, not the artefacts, so there is+ // nothing to gain from more.+ prepJPEGQuality = 85+ // prepScaleStep shrinks each side per attempt when an image is still+ // over the byte limit after re-encoding.+ prepScaleStep = 0.75+ // prepMinSide is where shrinking stops: below it an image no longer+ // carries anything worth a vector.+ prepMinSide = 64+)++// PrepareImage turns stored image bytes into an Image the model will take.+// An image already in an accepted format and within the byte limit goes as+// it is; anything else is re-encoded — as JPEG where the vendor takes it,+// PNG otherwise — and scaled down until it fits.+func PrepareImage(data []byte, limits ImageLimits) (Image, error) {+ if len(data) == 0 {+ return Image{}, fmt.Errorf("image is empty")+ }+ mime := http.DetectContentType(data)+ if !strings.HasPrefix(mime, "image/") {+ return Image{}, fmt.Errorf("not an image (%s)", mime)+ }+ if acceptsMIME(limits, mime) && fitsBytes(limits, len(data)) {+ return Image{Data: data, MIMEType: mime}, nil+ }++ src, _, err := image.Decode(bytes.NewReader(data))+ if err != nil {+ return Image{}, fmt.Errorf("decode %s: %w", mime, err)+ }+ target := "image/jpeg"+ if !acceptsMIME(limits, target) {+ target = "image/png"+ if !acceptsMIME(limits, target) {+ return Image{}, fmt.Errorf("the model takes none of the formats this can produce: %v", limits.MIMETypes)+ }+ }++ img := src+ for {+ out, err := encodeImage(img, target)+ if err != nil {+ return Image{}, err+ }+ if fitsBytes(limits, len(out)) {+ return Image{Data: out, MIMEType: target}, nil+ }+ b := img.Bounds()+ w, h := int(float64(b.Dx())*prepScaleStep), int(float64(b.Dy())*prepScaleStep)+ if w < prepMinSide || h < prepMinSide {+ return Image{}, fmt.Errorf("image does not fit %d bytes even scaled down", limits.MaxBytes)+ }+ scaled := image.NewRGBA(image.Rect(0, 0, w, h))+ draw.ApproxBiLinear.Scale(scaled, scaled.Bounds(), img, b, draw.Src, nil)+ img = scaled+ }+}++func acceptsMIME(limits ImageLimits, mime string) bool {+ return len(limits.MIMETypes) == 0 || slices.Contains(limits.MIMETypes, mime)+}++func fitsBytes(limits ImageLimits, n int) bool {+ return limits.MaxBytes <= 0 || n <= limits.MaxBytes+}++func encodeImage(img image.Image, mime string) ([]byte, error) {+ var buf bytes.Buffer+ var err error+ if mime == "image/jpeg" {+ // JPEG has no alpha. Flatten onto white, which is what a transparent+ // diagram or logo looks like on the page it came from.+ b := img.Bounds()+ flat := image.NewRGBA(b)+ draw.Draw(flat, b, image.NewUniform(color.White), image.Point{}, draw.Src)+ draw.Draw(flat, b, img, b.Min, draw.Over)+ err = jpeg.Encode(&buf, flat, &jpeg.Options{Quality: prepJPEGQuality})+ } else {+ err = png.Encode(&buf, img)+ }+ if err != nil {+ return nil, fmt.Errorf("encode %s: %w", mime, err)+ }+ return buf.Bytes(), nil+}diff --git a/internal/models/embedding/image_prep_test.go b/internal/models/embedding/image_prep_test.gonew file mode 100644index 000000000..f96b86fea--- /dev/null+++ b/internal/models/embedding/image_prep_test.go@@ -0,0 +1,96 @@+package embedding++import (+ "bytes"+ "image"+ "image/color"+ "image/gif"+ "image/jpeg"+ "image/png"+ "math/rand"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func encoded(+ t *testing.T, w, h int, encode func(*bytes.Buffer, image.Image) error, fill func(x, y int) color.Color,+) []byte {+ t.Helper()+ img := image.NewRGBA(image.Rect(0, 0, w, h))+ for y := 0; y < h; y++ {+ for x := 0; x < w; x++ {+ img.Set(x, y, fill(x, y))+ }+ }+ var buf bytes.Buffer+ require.NoError(t, encode(&buf, img))+ return buf.Bytes()+}++func pngEncode(b *bytes.Buffer, img image.Image) error { return png.Encode(b, img) }+func gifEncode(b *bytes.Buffer, img image.Image) error { return gif.Encode(b, img, nil) }++// noise does not compress, so its size follows its pixel count.+func noise() func(x, y int) color.Color {+ r := rand.New(rand.NewSource(1))+ return func(int, int) color.Color {+ return color.RGBA{uint8(r.Intn(256)), uint8(r.Intn(256)), uint8(r.Intn(256)), 255}+ }+}++func TestPrepareImagePassesThroughWhatTheModelTakes(t *testing.T) {+ data := encoded(t, 8, 8, pngEncode, noise())+ img, err := PrepareImage(data, ImageLimits{MaxBytes: 1 << 20, MIMETypes: []string{"image/png"}})+ require.NoError(t, err)+ assert.Equal(t, "image/png", img.MIMEType)+ assert.Equal(t, data, img.Data, "an acceptable image is sent untouched")+}++func TestPrepareImageConvertsAFormatTheModelDoesNotTake(t *testing.T) {+ data := encoded(t, 8, 8, gifEncode, noise())+ img, err := PrepareImage(data, ImageLimits{MIMETypes: []string{"image/png", "image/jpeg"}})+ require.NoError(t, err)+ assert.Equal(t, "image/jpeg", img.MIMEType)+ _, err = jpeg.Decode(bytes.NewReader(img.Data))+ assert.NoError(t, err)++ img, err = PrepareImage(data, ImageLimits{MIMETypes: []string{"image/png"}})+ require.NoError(t, err)+ assert.Equal(t, "image/png", img.MIMEType, "PNG when the model takes no JPEG")+}++func TestPrepareImageShrinksUntilItFits(t *testing.T) {+ data := encoded(t, 600, 600, pngEncode, noise())+ limit := len(data) / 10+ img, err := PrepareImage(data, ImageLimits{MaxBytes: limit})+ require.NoError(t, err)+ assert.LessOrEqual(t, len(img.Data), limit)+ cfg, err := jpeg.DecodeConfig(bytes.NewReader(img.Data))+ require.NoError(t, err)+ assert.Less(t, cfg.Width, 600)+ assert.Equal(t, cfg.Width, cfg.Height, "the aspect ratio is kept")++ _, err = PrepareImage(data, ImageLimits{MaxBytes: 100})+ assert.ErrorContains(t, err, "does not fit")+}++func TestPrepareImageFlattensTransparencyOntoWhite(t *testing.T) {+ data := encoded(t, 8, 8, pngEncode, func(int, int) color.Color { return color.Transparent })+ img, err := PrepareImage(data, ImageLimits{MIMETypes: []string{"image/jpeg"}})+ require.NoError(t, err)+ decoded, err := jpeg.Decode(bytes.NewReader(img.Data))+ require.NoError(t, err)+ r, g, b, _ := decoded.At(4, 4).RGBA()+ assert.Greater(t, r>>8, uint32(240))+ assert.Greater(t, g>>8, uint32(240))+ assert.Greater(t, b>>8, uint32(240))+}++func TestPrepareImageRejectsWhatIsNotAnImage(t *testing.T) {+ _, err := PrepareImage([]byte("<svg xmlns='http://www.w3.org/2000/svg'/>"), ImageLimits{})+ assert.ErrorContains(t, err, "not an image")+ _, err = PrepareImage(nil, ImageLimits{})+ assert.ErrorContains(t, err, "empty")+}diff --git a/internal/models/embedding/image_wire_test.go b/internal/models/embedding/image_wire_test.gonew file mode 100644index 000000000..908e0c4fe--- /dev/null+++ b/internal/models/embedding/image_wire_test.go@@ -0,0 +1,209 @@+package embedding++import (+ "bytes"+ "context"+ "errors"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// pngs returns n images of 1..n bytes, so each answer's vector names its image.+func pngs(n int) []Image {+ out := make([]Image, n)+ for i := range out {+ out[i] = Image{Data: bytes.Repeat([]byte{0x89}, i+1), MIMEType: "image/png"}+ }+ return out+}++func imageEmbedder(t *testing.T, up *upstream, provider, model, base string, spec *types.ModelSpecOverride) Embedder {+ t.Helper()+ e, err := NewEmbedder(Config{+ Source: types.ModelSourceRemote, Provider: provider, ModelName: model,+ BaseURL: up.url + base, APIKey: "k", Dimensions: 256, Spec: spec,+ }, nil, nil)+ require.NoError(t, err)+ return e+}++// TestImageEmbeddingWireFormatPerVendor pins the image request each+// multimodal vendor is sent, and how a batch is split at the documented+// number of images per request. The image part of every body is the shape+// the vendor's reference gives, as cited on the protocol client.+func TestImageEmbeddingWireFormatPerVendor(t *testing.T) {+ uri := "data:image/png;base64,iQ==" // one 0x89 byte+ const dashPath = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"+ cases := []struct {+ name, provider, model, base string+ images int+ wantPath string+ wantRequests int+ wantBody map[string]any // the first request's body, exactly+ }{+ {+ name: "volcengine fuses, so one image per request", provider: "volcengine",+ model: "doubao-embedding-vision-251215", base: "/api/v3", images: 2, wantRequests: 2,+ wantPath: "/api/v3/embeddings/multimodal",+ wantBody: map[string]any{+ "model": "doubao-embedding-vision-251215", "encoding_format": "float",+ "input": []any{map[string]any{"type": "image_url", "image_url": map[string]any{"url": uri}}},+ },+ },+ {+ name: "aliyun tongyi vision plus takes eight images", provider: "aliyun",+ model: "tongyi-embedding-vision-plus", base: "/compatible-mode/v1", images: 9, wantRequests: 2,+ wantPath: dashPath,+ wantBody: map[string]any{+ "model": "tongyi-embedding-vision-plus",+ "input": map[string]any{"contents": func() []any {+ out := []any{}+ for _, img := range pngs(8) {+ out = append(out, map[string]any{"image": img.DataURI()})+ }+ return out+ }()},+ },+ },+ {+ name: "aliyun multimodal-embedding-v1 takes one image", provider: "aliyun",+ model: "multimodal-embedding-v1", base: "/compatible-mode/v1", images: 2, wantRequests: 2,+ wantPath: dashPath,+ wantBody: map[string]any{+ "model": "multimodal-embedding-v1",+ "input": map[string]any{"contents": []any{map[string]any{"image": uri}}},+ },+ },+ {+ name: "gemini embeds each image as its own inlineData request", provider: "gemini",+ model: "gemini-embedding-2", base: "/v1beta", images: 2, wantRequests: 1,+ wantPath: "/v1beta/models/gemini-embedding-2:batchEmbedContents",+ wantBody: map[string]any{"requests": []any{+ map[string]any{+ "model": "models/gemini-embedding-2",+ "content": map[string]any{"parts": []any{+ map[string]any{"inlineData": map[string]any{"mimeType": "image/png", "data": "iQ=="}},+ }},+ },+ map[string]any{+ "model": "models/gemini-embedding-2",+ "content": map[string]any{"parts": []any{+ map[string]any{"inlineData": map[string]any{"mimeType": "image/png", "data": "iYk="}},+ }},+ },+ }},+ },+ {+ name: "jina sends an image object in input", provider: "jina",+ model: "jina-embeddings-v5-omni-small", base: "/v1", images: 2, wantRequests: 2,+ wantPath: "/v1/embeddings",+ wantBody: map[string]any{+ "model": "jina-embeddings-v5-omni-small", "truncate": true,+ "input": []any{map[string]any{"image": uri}},+ },+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ up := newUpstream(t)+ ie, ok := AsImageEmbedder(imageEmbedder(t, up, tc.provider, tc.model, tc.base, nil))+ require.True(t, ok, "the catalog lists this model as taking images")++ images := pngs(tc.images)+ got, err := ie.BatchEmbedImages(context.Background(), images)+ require.NoError(t, err)+ want := make([][]float32, len(images))+ for i, img := range images {+ want[i] = []float32{float32(len(img.Data))}+ }+ assert.Equal(t, want, got, "every vector must come back in its own slot")++ require.Len(t, up.requests, tc.wantRequests)+ assert.Equal(t, tc.wantPath, up.requests[0].path)+ assert.Equal(t, tc.wantBody, up.requests[0].body)+ })+ }+}++func TestImageEmbeddingNeedsBothTheModelAndTheEndpoint(t *testing.T) {+ declare := &types.ModelSpecOverride{Input: []string{"text", "image"}}+ cases := []struct {+ name, provider, model string+ spec *types.ModelSpecOverride+ want bool+ }{+ {"text model on a vendor with an image field", "jina", "jina-embeddings-v3", nil, false},+ {"text model on the OpenAI shape", "openai", "text-embedding-3-small", nil, false},+ // A generic OpenAI-compatible server has no image input to send to,+ // whatever the row declares.+ {"declared, but the endpoint names no image field", "generic", "my-clip", declare, false},+ {"declared on a vendor that names one", "jina", "my-jina-omni", declare, true},+ {+ "the row narrows a multimodal catalog entry", "volcengine", "doubao-embedding-vision-251215",+ &types.ModelSpecOverride{Input: []string{"text"}}, false,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ up := newUpstream(t)+ e := imageEmbedder(t, up, tc.provider, tc.model, "/v1", tc.spec)+ _, ok := AsImageEmbedder(e)+ assert.Equal(t, tc.want, ok)+ if !tc.want {+ // Every decorator carries the method, so a caller that skips+ // AsImageEmbedder still gets a refusal rather than a request.+ _, err := e.(ImageEmbedder).BatchEmbedImages(context.Background(), pngs(1))+ assert.True(t, errors.Is(err, ErrImagesUnsupported), "got %v", err)+ assert.Empty(t, up.requests)+ }+ })+ }+}++func TestImageEmbeddingRefusesWhatTheVendorDocumentsItWillNotTake(t *testing.T) {+ up := newUpstream(t)+ gemini, ok := AsImageEmbedder(imageEmbedder(t, up, "gemini", "gemini-embedding-2", "/v1beta", nil))+ require.True(t, ok)+ assert.Equal(t, []string{"image/png", "image/jpeg"}, gemini.ImageLimits().MIMETypes)+ _, err := gemini.BatchEmbedImages(context.Background(),+ append(pngs(1), Image{Data: []byte{1}, MIMEType: "image/webp"}))+ assert.ErrorContains(t, err, "image 1")++ jina, ok := AsImageEmbedder(imageEmbedder(t, up, "jina", "jina-embeddings-v4", "/v1", nil))+ require.True(t, ok)+ limit := jina.ImageLimits().MaxBytes+ require.Equal(t, 5_000_000, limit)+ _, err = jina.BatchEmbedImages(context.Background(),+ []Image{{Data: make([]byte, limit+1), MIMEType: "image/png"}})+ assert.ErrorContains(t, err, "limit")++ _, err = jina.BatchEmbedImages(context.Background(), []Image{{MIMEType: "image/png"}})+ assert.ErrorContains(t, err, "empty")++ // Refused before sending anything: no half-embedded batch.+ assert.Empty(t, up.requests)+}++// The factory adds the debug and Langfuse decorators only when those are+// switched on, so the image side through them is exercised here directly.+func TestImageEmbeddingPassesThroughEveryDecorator(t *testing.T) {+ up := newUpstream(t)+ inner := imageEmbedder(t, up, "jina", "jina-embeddings-v4", "/v1", nil)+ wrapped := &debugEmbedder{inner: &langfuseEmbedder{inner: inner}}++ ie, ok := AsImageEmbedder(wrapped)+ require.True(t, ok)+ assert.Equal(t, 5_000_000, ie.ImageLimits().MaxBytes)+ got, err := ie.BatchEmbedImages(context.Background(), pngs(2))+ require.NoError(t, err)+ assert.Equal(t, [][]float32{{1}, {2}}, got)++ textOnly := imageEmbedder(t, up, "openai", "text-embedding-3-small", "/v1", nil)+ text := &debugEmbedder{inner: &langfuseEmbedder{inner: textOnly}}+ _, ok = AsImageEmbedder(text)+ assert.False(t, ok)+ assert.Equal(t, ImageLimits{}, text.ImageLimits())+}diff --git a/internal/models/embedding/langfuse_wrapper.go b/internal/models/embedding/langfuse_wrapper.goindex 41585b272..21009e3f9 100644--- a/internal/models/embedding/langfuse_wrapper.go+++ b/internal/models/embedding/langfuse_wrapper.go@@ -78,6 +78,49 @@ func (l *langfuseEmbedder) BatchEmbedWithPool(ctx context.Context, model Embeddereturn l.inner.BatchEmbedWithPool(ctx, l, texts)}+func (l *langfuseEmbedder) AcceptsImages() bool {+ _, ok := AsImageEmbedder(l.inner)+ return ok+}++func (l *langfuseEmbedder) ImageLimits() ImageLimits { return imageLimitsOf(l.inner) }++func (l *langfuseEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {+ inner, err := imageSide(l.inner)+ if err != nil {+ return nil, err+ }+ mgr := langfuse.GetManager()+ if !mgr.Enabled() {+ return inner.BatchEmbedImages(ctx, images)+ }+ genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{+ Name: "embedding.batch_embed_images",+ Model: l.inner.GetModelName(),+ Input: map[string]interface{}{+ "count": len(images),+ "preview": previewTexts(describeImages(images), 5),+ },+ Metadata: map[string]interface{}{+ "model_id": l.inner.GetModelID(),+ "dimensions": l.inner.GetDimensions(),+ "batch_size": len(images),+ },+ })+ result, err := inner.BatchEmbedImages(genCtx, images)+ var out interface{}+ if len(result) > 0 {+ out = map[string]interface{}{+ "count": len(result),+ "dimensions": len(result[0]),+ }+ }+ // No usage: the text approximation has nothing to count, and a made-up+ // token figure for an image would mislead the cost report.+ gen.Finish(out, nil, err)+ return result, err+}+func (l *langfuseEmbedder) GetModelName() string { return l.inner.GetModelName() }func (l *langfuseEmbedder) GetDimensions() int { return l.inner.GetDimensions() }func (l *langfuseEmbedder) GetModelID() string { return l.inner.GetModelID() }diff --git a/internal/models/embedding/llm_debug.go b/internal/models/embedding/llm_debug.goindex c891f02b2..d67f24260 100644--- a/internal/models/embedding/llm_debug.go+++ b/internal/models/embedding/llm_debug.go@@ -32,6 +32,34 @@ func (d *debugEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder,return d.inner.BatchEmbedWithPool(ctx, d, texts)}+func (d *debugEmbedder) AcceptsImages() bool {+ _, ok := AsImageEmbedder(d.inner)+ return ok+}++func (d *debugEmbedder) ImageLimits() ImageLimits { return imageLimitsOf(d.inner) }++func (d *debugEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {+ inner, err := imageSide(d.inner)+ if err != nil {+ return nil, err+ }+ start := time.Now()+ result, err := inner.BatchEmbedImages(ctx, images)+ logEmbeddingDebug(ctx, d.inner.GetModelName(), describeImages(images), result, err, time.Since(start))+ return result, err+}++// describeImages stands in for the images in logs and traces, which must not+// carry their bytes.+func describeImages(images []Image) []string {+ out := make([]string, len(images))+ for i, img := range images {+ out[i] = fmt.Sprintf("<%s, %d bytes>", img.MIMEType, len(img.Data))+ }+ return out+}+func (d *debugEmbedder) GetModelName() string { return d.inner.GetModelName() }func (d *debugEmbedder) GetDimensions() int { return d.inner.GetDimensions() }func (d *debugEmbedder) GetModelID() string { return d.inner.GetModelID() }diff --git a/internal/models/embedding/protocol.go b/internal/models/embedding/protocol.goindex 3398049bb..951dded3e 100644--- a/internal/models/embedding/protocol.go+++ b/internal/models/embedding/protocol.go@@ -3,6 +3,7 @@ package embeddingimport ("context""fmt"+ "slices""strings""time"@@ -91,8 +92,16 @@ func newRemoteEmbedder(config Config, pooler EmbedderPooler) (Embedder, error) {return nil, fmt.Errorf("unsupported embedding api %q for provider %s", resolved.EmbeddingAPI, vendor.ID)}+ // Images need both halves: the catalog saying the model maps them into+ // its text space, and a protocol that can carry one to this vendor.+ var images api.ImageEmbedder+ if ie, ok := client.(api.ImageEmbedder); ok && ie.AcceptsImages() && resolved.Spec.AcceptsImages() {+ images = ie+ }+return &protocolEmbedder{inner: client,+ images: images,settings: settings,modelName: config.ModelName,modelID: config.ModelID,@@ -106,7 +115,9 @@ func newRemoteEmbedder(config Config, pooler EmbedderPooler) (Embedder, error) {// itself: splitting a batch that exceeds the documented per-request ceiling,// and telling the vendor which side of a search a text is on.type protocolEmbedder struct {- inner api.Embedder+ inner api.Embedder+ // images is nil unless the model and the endpoint both take images.+ images api.ImageEmbeddersettings api.EmbeddingsSettingsmodelName stringmodelID string@@ -157,3 +168,48 @@ func (e *protocolEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]}return out, nil}++func (e *protocolEmbedder) AcceptsImages() bool { return e.images != nil }++func (e *protocolEmbedder) ImageLimits() ImageLimits {+ return ImageLimits{MaxBytes: e.settings.MaxImageBytes, MIMETypes: slices.Clone(e.settings.ImageMIMETypes)}+}++// BatchEmbedImages checks every image against the documented limits before+// sending any, so a batch never half-succeeds on an image the vendor was+// always going to refuse, then splits it at the documented images per+// request.+func (e *protocolEmbedder) BatchEmbedImages(ctx context.Context, images []Image) ([][]float32, error) {+ if e.images == nil {+ return nil, fmt.Errorf("%s: %w", e.modelName, ErrImagesUnsupported)+ }+ if len(images) == 0 {+ return nil, nil+ }+ for i, img := range images {+ if err := e.settings.CheckImage(img); err != nil {+ return nil, fmt.Errorf("%s embedding: image %d: %w", e.modelName, i, err)+ }+ }+ kind := api.EmbedDocument+ if types.IsEmbedQuery(ctx) {+ kind = api.EmbedQuery+ }+ limit := e.settings.ImageBatchLimit()+ out := make([][]float32, len(images))+ // Serial for the same reason as BatchEmbed.+ for start := 0; start < len(images); start += limit {+ batch := images[start:min(start+limit, len(images))]+ vectors, err := e.images.EmbedImages(ctx, batch, kind)+ if err != nil {+ return nil, err+ }+ if len(vectors) != len(batch) {+ return nil, fmt.Errorf(+ "%s embedding: %d vectors for %d images", e.modelName, len(vectors), len(batch),+ )+ }+ copy(out[start:], vectors)+ }+ return out, nil+}diff --git a/internal/models/embedding/wire_test.go b/internal/models/embedding/wire_test.goindex f9ab4982c..333c17f13 100644--- a/internal/models/embedding/wire_test.go+++ b/internal/models/embedding/wire_test.go@@ -2,6 +2,7 @@ package embeddingimport ("context"+ "encoding/base64""encoding/json""fmt""net/http"@@ -64,6 +65,37 @@ func newUpstream(t *testing.T) *upstream {func runeLen(v any) int { return utf8.RuneCountInString(v.(string)) }+// itemLen is the length of one input item whatever its shape: the runes of+// a text, or the decoded bytes of an inline image. Images in these tests+// differ in size, so the vector still tells which input it answers.+func itemLen(v any) int {+ item, ok := v.(map[string]any)+ if !ok {+ return runeLen(v)+ }+ switch {+ case item["text"] != nil:+ return runeLen(item["text"])+ case item["image"] != nil:+ return dataURILen(item["image"].(string))+ case item["image_url"] != nil:+ return dataURILen(item["image_url"].(map[string]any)["url"].(string))+ case item["inlineData"] != nil:+ data, _ := base64.StdEncoding.DecodeString(item["inlineData"].(map[string]any)["data"].(string))+ return len(data)+ }+ panic(fmt.Sprintf("unrecognised input item %v", item))+}++func dataURILen(uri string) int {+ _, encoded, ok := strings.Cut(uri, ";base64,")+ if !ok {+ panic("not a base64 data URI: " + uri)+ }+ data, _ := base64.StdEncoding.DecodeString(encoded)+ return len(data)+}+// answer replies in the protocol the path belongs to. The OpenAI and// DashScope shapes are answered in reverse order so that placement by index// is exercised on every request.@@ -72,24 +104,24 @@ func answer(path string, body map[string]any) string {switch {case strings.HasSuffix(path, ":batchEmbedContents"):for _, req := range body["requests"].([]any) {- text := req.(map[string]any)["content"].(map[string]any)["parts"].([]any)[0].(map[string]any)["text"]- parts = append(parts, fmt.Sprintf(`{"values":[%d]}`, runeLen(text)))+ part := req.(map[string]any)["content"].(map[string]any)["parts"].([]any)[0]+ parts = append(parts, fmt.Sprintf(`{"values":[%d]}`, itemLen(part)))}return `{"embeddings":[` + strings.Join(parts, ",") + `]}`case strings.HasSuffix(path, "/multimodal-embedding"):contents := body["input"].(map[string]any)["contents"].([]any)for i := len(contents) - 1; i >= 0; i-- {- n := runeLen(contents[i].(map[string]any)["text"])+ n := itemLen(contents[i])parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d],"type":"text"}`, i, n))}return `{"output":{"embeddings":[` + strings.Join(parts, ",") + `]}}`case strings.HasSuffix(path, "/embeddings/multimodal"):- n := runeLen(body["input"].([]any)[0].(map[string]any)["text"])+ n := itemLen(body["input"].([]any)[0])return fmt.Sprintf(`{"data":{"embedding":[%d],"object":"embedding"}}`, n)default:input := body["input"].([]any)for i := len(input) - 1; i >= 0; i-- {- parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d]}`, i, runeLen(input[i])))+ parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d]}`, i, itemLen(input[i])))}return `{"data":[` + strings.Join(parts, ",") + `]}`}diff --git a/internal/models/parity/testdata/catalog-baseline.json b/internal/models/parity/testdata/catalog-baseline.jsonindex a7224ee77..cd363ad96 100644--- a/internal/models/parity/testdata/catalog-baseline.json+++ b/internal/models/parity/testdata/catalog-baseline.json@@ -1,18 +1,18 @@{"aliyun/ASR/qwen3-asr-flash": "bb6104c02ce1013fd954de79c4998fd5b9e96e8b91cbbe083c9bc02a23660d7a","aliyun/ASR/snapshot": "error: catalog: aliyun does not serve \"\" through a protocol this build implements: Alibaba's other recognition models take a public file URL or run as asynchronous tasks; only qwen3-asr-flash accepts the audio in the request",- "aliyun/Embedding/multimodal-embeddingsnapshot": "841622b61917a7ec092feffad27e86d4a9125deecdc27d46117c439d44c85806",- "aliyun/Embedding/qwen2.5-vl-embeddingsnapshot": "b975e014ce58f39766a416bd75098b7d17124a63a71861b5e53316ef2eb22b1b",- "aliyun/Embedding/qwen3-vl-embeddingsnapshot": "6360c00080aace602f2f430b8fbdd61a03db3307fe8d760b4fd72c516361b57e",+ "aliyun/Embedding/multimodal-embeddingsnapshot": "abd8e6e33132030c401670448cbc649f51c200bd5b0042157d3ecbabb093fd4d",+ "aliyun/Embedding/qwen2.5-vl-embeddingsnapshot": "f957cb1c3bdba7cfe010c2c2f58a5148e422c629a4486321296a35ee4b7790f0",+ "aliyun/Embedding/qwen3-vl-embeddingsnapshot": "3d6dba847c93c3ea41c64a18dd31ec521c37426a05d94968bfea90c951544127","aliyun/Embedding/qwen3.7-text-embedding": "1747d31bcb369f32605000f3f2cc59406a4f7ddc5be6123c80e4e06f5d7fc2e7","aliyun/Embedding/qwen3.7-text-embedding-flash": "14ce61f8e4aea6394b43f6383bd2ec3d1398abd0a8d666374c4300fb86845cd5","aliyun/Embedding/text-embedding-v1": "1e7d78c2635542f53008f0aa30d69544fd4fae3a48d36745b027875005cfb2d6","aliyun/Embedding/text-embedding-v2": "b3eb2440097a26c93dea795bdf9b9d1ea4d4a11f1e20a034e2bb146d7226883f","aliyun/Embedding/text-embedding-v3": "ef7acfe7150c048a9c46d5e8e2bc14d890df0721f877d76c41e6a2ed275bb7cc","aliyun/Embedding/text-embedding-v4": "acd6a3536ee4f98330fb02e39c9f1952dbb1eb578d70a82c64278355ca44bc36",- "aliyun/Embedding/tongyi-embedding-vision-flash": "4e471e8267f1a58f999fea0c7c8d7280f96977d08f5381845195d98d141103c4",- "aliyun/Embedding/tongyi-embedding-vision-plus": "0962b5ddbc901c0428bcab0ab362059ecd1628b6e1c8b41907122d6e8a037068",- "aliyun/Embedding/tongyi-embedding-visionsnapshot": "f6dc43b2e5f638957bb1fedb361d4bd5f68a86d656ca1bd662be21695d18c9f9",+ "aliyun/Embedding/tongyi-embedding-vision-flash": "fbcbf6d25d1078a137fa0d35dac9da104985a8da9b797bf161ec3b72a7775f02",+ "aliyun/Embedding/tongyi-embedding-vision-plus": "fd37a8b75ef6f1c54dbbba9975e75f2668690d479f42beda61804f1be5b3c6bd",+ "aliyun/Embedding/tongyi-embedding-visionsnapshot": "37e1d6878a0ec196c49339fc5ba48615f12453b7f065c6ac0e50e272b76ac219","aliyun/KnowledgeQA/deepseek-r1": "735322a596dda4a914b7e53041643eab61bd90b51e18e0cffd36dcc807b6fd16","aliyun/KnowledgeQA/deepseek-v3snapshot": "b3e72a6d322e5d53b18cf1204434be5f75de77262e67bab838492376c7c287b3","aliyun/KnowledgeQA/deepseek-v4-flash": "ac9d4d9224054609f98ba4ab3fc32c47b99f6af8c4153793a2fd00f5495212e9",@@ -84,8 +84,8 @@"deepseek/KnowledgeQA/deepseek-v4-flash": "a1d11bc227bae61b53cd3642d32c59affa715b2cdb73fc53995c6a0ad9977438","deepseek/KnowledgeQA/deepseek-v4-pro": "5b245660012e5b1e4160861575244ecd1d0feb9b24a366d10cc58b4ae8257786","gemini/Embedding/gemini-embedding-001": "2126e8863f9ba5d4cef4e0154c5b8ce8579dddd7d8aeb674bb74632b6294a7dd",- "gemini/Embedding/gemini-embedding-2": "e99a5211364c62e875aa93c65911197d150f8e5581654705da6433ca129c34e7",- "gemini/Embedding/gemini-embedding-2-preview": "a9d78acffaeabbae5c554d346a2c5893b7b68882f239cc5fc1e108126d4c8260",+ "gemini/Embedding/gemini-embedding-2": "d79dee9bc056de3bc95e90877eebcb8846edf967e4555028d72a2e5694d8188a",+ "gemini/Embedding/gemini-embedding-2-preview": "f45ec78e4183dbc342640f9754a59a6a48144a67564cf17a3c68567c8e0dcfa2","gemini/KnowledgeQA/gemini-2.5-flash": "8fd1fd7205b512d2e7c506f171d4cf09f77e7c1f08d327942e42a63dd6a10560","gemini/KnowledgeQA/gemini-2.5-flash-lite": "04688ec4b28a2ffc5afd5fa501b6ea144c3ee519badcbb36d82b61d44a25dd17","gemini/KnowledgeQA/gemini-2.5-pro": "6929d8015b51e7326d9de5f333408b7abe91c23f87623af4f4434a78a6cbbaa2",@@ -114,14 +114,14 @@"hunyuan/KnowledgeQA/hunyuan-turbos-vision": "de1994d9055a856578b34082829c6de1728633d1e7e664b02b993131797f1291","hunyuan/KnowledgeQA/hunyuan-turbos-vision-video": "07d35ec30279d336e39257ff80f558dd69ffa1c3e865a34a1585f2a261aad640","hunyuan/KnowledgeQA/hunyuan-vision-1.5-instruct": "eb831ff45f66229ed468214ad2c40cd89e07d60021ee79685ff58d8cc68421e9",- "jina/Embedding/jina-code-embeddings-0.5b": "b0d7bb78d59e7ab07673bdff461f516c5b50a48903d0eaeeeb01bfd0f53fa730",- "jina/Embedding/jina-code-embeddings-1.5b": "06932f7c3e756ebfaedbcc60ff918cd7b544e3b4fdfaaca3bf49ef3746073e04",- "jina/Embedding/jina-embeddings-v3": "34fede5426a6aa78e1e2c575a7fef52afd3af53331155f15e82d6ae566beff69",- "jina/Embedding/jina-embeddings-v4": "f8b2c8a0328f5ba3b2e3eacb72dbbab13558d3961cf9c51eb76535b6a9d8db0b",- "jina/Embedding/jina-embeddings-v5-omni-nano": "90d9ca7bd2bccbe643d984d5eff478f09f5190436d5baefbc498e700bd7131c6",- "jina/Embedding/jina-embeddings-v5-omni-small": "fe239e4fc9e4ef3e61f6a43ea9eab9b23a249d85e8d2fbc38d2d5368fe0d6811",- "jina/Embedding/jina-embeddings-v5-text-nano": "c9efe64eee9dc11b2583155ce522af3332188b5bbedaaa8bc07caaab54910f74",- "jina/Embedding/jina-embeddings-v5-text-small": "16bdb3d6cba14b0fd16786cb6e9c16dfa411488661ff134629a330b0cbc9cba4",+ "jina/Embedding/jina-code-embeddings-0.5b": "9775240b72e8ba4a05e8847f9ebcbbb254c988c756783b883f6cba293fdc89f9",+ "jina/Embedding/jina-code-embeddings-1.5b": "d5c3d65b861352b2324a19224ee5712f84c9347b4e89d3a51ba0f2c88abf9f03",+ "jina/Embedding/jina-embeddings-v3": "3af8aeb042e5a2727fe9497c70c53399036fa16ebc349660ce69ea4e9a48953f",+ "jina/Embedding/jina-embeddings-v4": "b76a9b00b360adfbdfa1f98cd068f725f3f2beb0c48da71bcaaefcf0a2d9c59d",+ "jina/Embedding/jina-embeddings-v5-omni-nano": "93af28d6a431cd3fe9f937a121f2f8912491df57e218c43d21c1b387b9bd0587",+ "jina/Embedding/jina-embeddings-v5-omni-small": "e93d92bed96c1a3b810ea93502fb4fdd02f7299e1c43d97e9c197f7883c4dc38",+ "jina/Embedding/jina-embeddings-v5-text-nano": "efa8aa5e980a90db2f510dc005a1e573f059f97157209cd34880998007a72ad9",+ "jina/Embedding/jina-embeddings-v5-text-small": "4ef8c82f495ba94c28010ec54e8317e201ce3e9c1bf73a8911f49eb20889f138","jina/Rerank/jina-reranker-m0": "056816679d30640e0c9c0583d42cb1db42bce784206d85397dff780ff6762552","jina/Rerank/jina-reranker-v2-base-multilingual": "40e4c4971b8fca257fd877fe92d59f8f4042552c07f8c0d3d282eddee491686a","jina/Rerank/jina-reranker-v3": "686a1e72192f3d0d4ca422135c08612131a96017eea0dae371ec390c81497ea7",@@ -317,8 +317,8 @@"siliconflow/Rerank/Qwen/Qwen3-Reranker-8B": "712284e5eef89f522e30c96bba18d019d0c48703adb2dc0fc1239aa55d582d49","volcengine/Embedding/doubao-embedding-large-textsnapshot": "44d79d19f14506e75d7b9144907ffe70c3eb3110e07470362264022866ce104e","volcengine/Embedding/doubao-embedding-textsnapshot": "e522020c10b4d3962869cd0bdfa42f845ca60cf2d1862f06ecb725d67386f32a",- "volcengine/Embedding/doubao-embedding-vision-250615": "3d1035120259b61b2b7c6fc26d21948c6b2ef7420365f51f518573be2e4767d3",- "volcengine/Embedding/doubao-embedding-vision-251215": "4c353f33993f52212365357f33f4547a49e127391c5f5424f52136b6924027fd",+ "volcengine/Embedding/doubao-embedding-vision-250615": "6e447d353627e2f90da5ce3bf6458f73c7caf796210ebdee28af0497b77bc66f",+ "volcengine/Embedding/doubao-embedding-vision-251215": "d0bd4b44b168a1422272a923739dd396af5d220c53d1c8f831f34478e3dc1d1b","volcengine/KnowledgeQA/deepseek-v4-1-flash-260910": "da798ebd4b75f0cac486e0c13b7b944db5e72119d70cb95749ea9a7546c8694b","volcengine/KnowledgeQA/deepseek-v4-flash-ga-260731": "a5150f406c1a4889c3488cc113f14a55e55fbc67ad254e00f3e7919b3d6ea04d","volcengine/KnowledgeQA/deepseek-v4-pro-ga-260813": "0bfe115ffe3d5837228188d4c94c34d58f374b4dd9c9c70106f0717ad335b456",diff --git a/internal/models/providers/jina.go b/internal/models/providers/jina.goindex 5a21153e4..cd487acd8 100644--- a/internal/models/providers/jina.go+++ b/internal/models/providers/jina.go@@ -72,6 +72,11 @@ func newJinaProvider() *Definition {DimensionsField: api.Ptr("dimensions"),TruncateField: api.Ptr("truncate"),TruncateValue: api.Ptr("true"),+ // The multimodal models take {"image": URL or data URI} in+ // input; "Maximum file sizes are 5 MB for images". The page+ // gives no image count per request, so each image goes alone.+ ImageField: api.Ptr("image"),+ MaxImageBytes: api.Ptr(5_000_000),},Rerank: api.RerankCompat{// return_documents echoes the text back. Results are matcheddiff --git a/internal/models/runtime/resolve.go b/internal/models/runtime/resolve.goindex c2b950849..a7e61c84b 100644--- a/internal/models/runtime/resolve.go+++ b/internal/models/runtime/resolve.go@@ -300,6 +300,12 @@ func (r *Resolved) Capabilities() Capabilities {ContextWindow: r.Spec.ContextWindow,MaxOutputTokens: r.Spec.MaxOutputTokens,}+ // Embedding, rerank and ASR references resolve no chat protocol, and an+ // empty level map reads as "every level supported"; they do not think.+ if r.API == "" {+ caps.ThinkingLevels = []api.ReasoningEffort{}+ return caps+ }switch r.API {case api.APIOpenAICompletions:caps.ThinkingFormat = string(r.OpenAICompletions.ThinkingFormat)diff --git a/internal/searchutil/imageinfo.go b/internal/searchutil/imageinfo.goindex cc5468a40..2de46e4f3 100644--- a/internal/searchutil/imageinfo.go+++ b/internal/searchutil/imageinfo.go@@ -390,6 +390,15 @@ func ClearImageInfoTextMatchingBody(imageInfoJSON, recognized, chunkType string)infos[i].Caption = ""changed = true}+ case string(types.ChunkTypeImageVector):+ // Its body is the caption, or the OCR text when there was none.+ if infos[i].Caption == recognized {+ infos[i].Caption = ""+ changed = true+ } else if infos[i].OCRText == recognized {+ infos[i].OCRText = ""+ changed = true+ }}}if !changed {diff --git a/internal/types/chunk.go b/internal/types/chunk.goindex 719e7ff7d..ccb902e87 100644--- a/internal/types/chunk.go+++ b/internal/types/chunk.go@@ -21,6 +21,11 @@ const (ChunkTypeImageOCR ChunkType = "image_ocr"// ChunkTypeImageCaption 表示图片描述的 ChunkChunkTypeImageCaption ChunkType = "image_caption"+ // ChunkTypeImageVector 表示由多模态向量模型直接对图片编码的 Chunk。+ // 它的索引行存的是图片本身的向量(SourceType 为 ImageSourceType),+ // 不是 Content 的文本向量;Content 复用图片描述(没有描述时用 OCR 文本),+ // 供重排和回答上下文使用。任何按文本重建索引的路径都不能处理它。+ ChunkTypeImageVector ChunkType = "image_vector"// ChunkTypeSummary 表示摘要类型的 ChunkChunkTypeSummary = "summary"// ChunkTypeEntity 表示实体类型的 Chunk@@ -39,6 +44,12 @@ const (ChunkTypeWikiPage ChunkType = "wiki_page")+// IsImageChildChunkType reports whether a chunk is one the multimodal+// pipeline hangs under the text chunk that shows an image.+func IsImageChildChunkType(t ChunkType) bool {+ return t == ChunkTypeImageOCR || t == ChunkTypeImageCaption || t == ChunkTypeImageVector+}+// ChunkStatus 定义了不同状态的 Chunktype ChunkStatus intdiff --git a/internal/types/embedding.go b/internal/types/embedding.goindex 5ea5b506a..a488c4ca2 100644--- a/internal/types/embedding.go+++ b/internal/types/embedding.go@@ -7,6 +7,12 @@ const (ChunkSourceType SourceType = iota // Source is a text chunkPassageSourceType // Source is a passageSummarySourceType // Source is a summary+ // ImageSourceType is an image embedded by a multimodal embedding model.+ // Its vector lives in the text space but scores lower against a text+ // query than text does, and its Content is not what was embedded, so+ // retrieval gives it its own threshold and never counts it as a+ // keyword hit.+ ImageSourceType)// MatchType represents the type of matching algorithmdiff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.goindex f92b23ed6..bdd4482aa 100644--- a/internal/types/knowledgebase.go+++ b/internal/types/knowledgebase.go@@ -553,6 +553,13 @@ type ImageProcessingConfig struct {// override it per document through// KnowledgeProcessOverrides.ImageAttrsEnabled.ImageAttrsEnabled bool `yaml:"image_attrs_enabled,omitempty" json:"image_attrs_enabled,omitempty"` //nolint:lll // one-line struct tag+ // ImageVectorEnabled lets a knowledge base whose embedding model takes+ // images index each image by its own vector and recall it with one. It+ // is off by default on purpose: a model that takes images is also used+ // for plain text, and turning this on costs an embedding call per image+ // and widens vector recall. Existing knowledge bases stay off after an+ // upgrade because the stored JSON has no such key.+ ImageVectorEnabled bool `yaml:"image_vector_enabled,omitempty" json:"image_vector_enabled,omitempty"` //nolint:lll // one-line struct tag}// Value implements the driver.Valuer interface, used to convert ChunkingConfig to database value@@ -899,6 +906,14 @@ func (kb *KnowledgeBase) IsMultimodalEnabled() bool {return kb.VLMConfig.IsEnabled()}+// IsImageVectorEnabled reports whether the knowledge base opted in to+// indexing and recalling images by their own vectors. The embedding model+// must also take images; callers check that separately, since it needs the+// model resolved.+func (kb *KnowledgeBase) IsImageVectorEnabled() bool {+ return kb.IsVectorEnabled() && kb.ImageProcessingConfig.ImageVectorEnabled+}+// HasVectorStore reports whether the KB is bound to a DB-managed VectorStore// (as opposed to the tenant's env-store fallback).//diff --git a/internal/types/knowledgebase_test.go b/internal/types/knowledgebase_test.goindex 943fa9752..45c3fce83 100644--- a/internal/types/knowledgebase_test.go+++ b/internal/types/knowledgebase_test.go@@ -413,3 +413,54 @@ func TestKnowledgeBase_MarshalJSONWithholdsInlineCredentials(t *testing.T) {t.Fatalf("VLM column lost its key: %v %s", err, vlmColumn)}}++// A knowledge base saved before the image-vector switch has no such key in+// image_processing_config, and must read back as opted out even when every+// other image setting is on.+func TestKnowledgeBase_IsImageVectorEnabled(t *testing.T) {+ var stored ImageProcessingConfig+ if err := stored.Scan([]byte(`{"model_id":"vlm-1","image_attrs_enabled":true}`)); err != nil {+ t.Fatal(err)+ }+ vector := IndexingStrategy{VectorEnabled: true}+ upgraded := &KnowledgeBase{IndexingStrategy: vector, ImageProcessingConfig: stored}+ upgraded.EnsureDefaults()+ if upgraded.IsImageVectorEnabled() {+ t.Error("a knowledge base from before the switch must stay off")+ }++ var nilKB *KnowledgeBase+ cases := []struct {+ name string+ kb *KnowledgeBase+ want bool+ }{+ {"nil", nilKB, false},+ {"switch on", &KnowledgeBase{+ IndexingStrategy: vector,+ ImageProcessingConfig: ImageProcessingConfig{ImageVectorEnabled: true},+ }, true},+ {"switch on, vector indexing off", &KnowledgeBase{+ IndexingStrategy: IndexingStrategy{KeywordEnabled: true},+ ImageProcessingConfig: ImageProcessingConfig{ImageVectorEnabled: true},+ }, false},+ }+ for _, tc := range cases {+ if got := tc.kb.IsImageVectorEnabled(); got != tc.want {+ t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)+ }+ }++ // The switch survives a save.+ raw, err := ImageProcessingConfig{ImageVectorEnabled: true}.Value()+ if err != nil {+ t.Fatal(err)+ }+ var back ImageProcessingConfig+ if err := back.Scan(raw); err != nil {+ t.Fatal(err)+ }+ if !back.ImageVectorEnabled || !strings.Contains(string(raw.([]byte)), `"image_vector_enabled":true`) {+ t.Errorf("round trip lost the switch: %s", raw)+ }+}diff --git a/website-docs/02-architecture/03-document-pipeline.md b/website-docs/02-architecture/03-document-pipeline.mdindex 24f7225e6..338f867a1 100644--- a/website-docs/02-architecture/03-document-pipeline.md+++ b/website-docs/02-architecture/03-document-pipeline.md@@ -394,6 +394,8 @@ promoted, err := s.knowledgeRepo.SetFinalizing(ctx, payload.KnowledgeID, expecte1. `readImageBytes` 从存储/URL 取图;`resolveVLM` 取 KB 的 VLM 配置;2. 生成 Caption(VLM,prompt 由 `buildVLMCaptionPrompt` 按 `DescriptionLanguage/CustomInstructions` 组装)与 OCR 文本;3. 结果写回所属文本 Chunk 的 `ImageInfo`(JSON),并创建/更新两个**子 Chunk**:`ChunkTypeImageCaption` 与 `ChunkTypeImageOCR`,`ParentChunkID` 指向文本块,随后单独 `indexChunks` 入向量索引 —— 使"搜图片描述也能召回原文块";+ - **图片向量**:知识库开启了图片向量(`ImageProcessingConfig.ImageVectorEnabled`,默认关闭,见 `KnowledgeBase.IsImageVectorEnabled`)且向量模型能处理图片时(模型能力 `input` 含 `image`,且厂商协议能传图片,见 `embedding.AsImageEmbedder`),`indexImageVector` 再用该模型直接对图片编码,存为第三个子 Chunk `ChunkTypeImageVector`:索引行的 `SourceType` 为 `ImageSourceType`,向量是图片本身的(经 `CompositeRetrieveEngine.BatchIndexVectors` 写入预先算好的向量),`Content` 复用图片描述(没有描述时用 OCR 文本),供重排与回答上下文使用。图片先经 `embedding.PrepareImage` 按厂商限制转格式、压缩;扫描件 PDF 页不做(OCR 更准)。这一步失败只记日志,不影响任务;+ - `ChunkTypeImageVector` 的向量不能由文本重建:`syncChunkIndex` 对它只同步启用状态,`updateChunkVector` 跳过它;图片描述被修改时只更新它的 `Content`;4. `shouldDropOrphanedMultimodal` 检查父块是否已被删除/取代,孤儿任务直接丢弃;5. `checkAndFinalizeAllImages`:全部图片处理完毕后,`enqueueKnowledgePostProcessTask` 触发 [后处理编排(knowledge_post_process.go,Stage: postprocess)](#_6-6-后处理编排-knowledge-post-process-go-stage-postprocess) 的后处理编排。后处理任务入队会就地重试 3 次,仍失败时本次任务返回错误交给重试,不会确认任务后让文档停在 `processing`。最后一次尝试时即使读取知识行失败,这张图片也会计入完成数。Lite 模式没有 Redis,计数器保存在进程内存中,所有图片都完成后才进入后处理。diff --git a/website-docs/02-architecture/04-rag-pipeline.md b/website-docs/02-architecture/04-rag-pipeline.mdindex 448c55374..ce564e163 100644--- a/website-docs/02-architecture/04-rag-pipeline.md+++ b/website-docs/02-architecture/04-rag-pipeline.md@@ -241,7 +241,7 @@ pipeline = types.NewPipelineBuilder().1. **选择输入**:优先 `RerankResult`,为空则回退 `SearchResult`(按分排序并截到 `RerankTopK`,避免对全部召回结果做回表和扩展);2. **去重**:ID + 内容签名;3. **注入历史引用**(`merge_history.go`):从最近一轮带引用的历史取 `KnowledgeReferences`,按引用覆盖了多少查询词过滤(重合系数 `|q∩c|/min(|q|,|c|)` ≥ 0.3;Jaccard 除以并集,约 8 个词的查询对上几百词的分块永远到不了阈值),分数打 0.6 折,最多注入 3 条,标记 `MatchTypeHistory`;-4. **父子块解析** `resolveParentChunks`:text 子块与 image_ocr/image_caption 子块都用**当前** parent_text 内容补齐上下文;图片 Markdown 的收窄靠稳定的图片 URL(`PruneMarkdownImagesByImageInfo`)而不是解析器坐标;ImageInfo 严格限定在命中的 text 子块,避免图片密集的父块把兄弟页面的 OCR 全部灌进上下文。image → text → parent_text 这条链只在确实命中图片结果时才多查一次祖父块;+4. **父子块解析** `resolveParentChunks`:text 子块与 image_ocr/image_caption/image_vector 子块都用**当前** parent_text 内容补齐上下文;图片 Markdown 的收窄靠稳定的图片 URL(`PruneMarkdownImagesByImageInfo`)而不是解析器坐标;ImageInfo 严格限定在命中的 text 子块,避免图片密集的父块把兄弟页面的 OCR 全部灌进上下文。image → text → parent_text 这条链只在确实命中图片结果时才多查一次祖父块;5. **分组顺序合并** `groupAndMergeCurrentContent`:按 `KnowledgeID + ChunkType` 分组,组内按 `ChunkIndex` 排序后 `mergeSequentialChunks`——序号连续、或一方内容包含另一方时用 `searchutil.JoinChunkContent` 拼接,保留最高分,`SubChunkID` 记录被合并块,`mergeImageInfo` 按 URL 去重合并图片信息;6. **FAQ 答案填充**(`merge_faq.go`):FAQ 类型 chunk 批量回表读 `FAQMetadata`,重写 Content 为 `Q: 标准问题 + Answer: 答案列表`;7. **短上下文邻居扩展**(`merge_expand.go`):text 块内容不足 350 字符时,批量取 `PreChunkID`/`NextChunkID` 邻居拼接至最长约 850 字符。命中块本身完整保留,剩余长度分给紧挨着它的前文末尾与后文开头;邻居必须属于同一文档,组织共享知识库的分块同样可以扩展;@@ -484,15 +484,16 @@ sequenceDiagram2. **入参归一化 + 过召回**:`MatchCount <= 0`(调用方未传时 JSON 反序列化即为 0)先经 `normalizedMatchCount` 归一化为 `types.DefaultRetrievalTopK`(50),使过召回下限、FAQ 迭代触发条件、末尾截断三处读到同一个值——否则截断会把结果集切成 `[:0]`,负数还会越界 panic;随后 `matchCount = max(MatchCount*5, 50) * len(KBs)`,上限 `maxRetrievalPoolSize`(500)。3. **查询向量只算一次**,随 `params.QueryEmbedding` 传播到所有 store 组。4. **storeGroup 分组**(`knowledgebase_search_storegroup.go`):按 `(VectorStoreID, 属主租户)` 分组;每组经 `retriever.CreateRetrieveEngineForKB` 解析出 `CompositeRetrieveEngine`。`buildRetrievalParams` 按组内每个 KB 的类型路由:FAQ 库走 FAQ 向量索引(`KnowledgeType=faq`,无关键词索引),文档库走默认向量索引 + 关键词索引。-5. **fan-out**(`knowledgebase_search_fanout.go`):单组直查零开销;多组用 `errgroup` 并发(上限 4),每组超时 `MULTI_STORE_RETRIEVE_TIMEOUT_SEC`(默认 30s),all-or-nothing 失败策略;结果跨引擎类型时用 `EngineAwareNormalizer` 把向量分归一化到 [0,1](详见检索引擎文档)。-6. **融合**(`knowledgebase_search_fusion.go`):+5. **图片召回**(`knowledgebase_search_image.go`):`applyImageRecall` 只在有知识库开启了图片向量(`ImageProcessingConfig.ImageVectorEnabled`,默认关闭)时才解析向量模型、判断它能否处理图片;两者都满足时,把这些知识库记入所在组的 `ImageKBIDs`,该组文档向量检索的 TopK 放大 1.5 倍(仍封顶 500)、阈值降到 `min(VectorThreshold, 0.1)`。文本查询与图片的相似度天然低于与文本(模态鸿沟),共用文本阈值会把图片几乎全部挡掉。每组结果在归一化前经 `filterImageHits` 按来源分别过阈值:文本命中仍按 `VectorThreshold`,图片命中(`ImageSourceType`)按 `min(VectorThreshold, 0.1)`;关键词命中里的图片行一律丢弃(其 `Content` 就是图片描述,描述块已有自己的关键词索引);不在 `ImageKBIDs` 里的知识库(未开启,或开启后又关闭,或文档从开启的知识库移动过来)的图片向量命中也一律丢弃,组里没有开启的知识库时 TopK 与阈值不变。这些图片向量的分块与索引行并不删除:删除 / 重新解析文档、删除知识库时按 knowledge ID 随文档清除,知识库重新开启后恢复召回。引擎不按来源类型过滤,被丢弃的图片行在引擎截断 TopK 之后才剔除,排在文本前面时会挤占候选池;所以过滤前先由 `refillPastDroppedImages` 补检:文档向量池或关键词池打满且含被丢弃的图片行时,TopK 翻倍重检,直到池中保留行够 TopK、索引耗尽或触到 `maxRetrievalPoolSize`(500),再截回 TopK 条保留行(50 条池最多多 4 次查询)。代价是含图片行的组可能多出几次检索查询;排在文本前面的图片行超过约 500 条时文本命中仍会漏掉。补检是尽力而为:某次补检报错或只部分返回(`RetrieveResult.Error`)即停止,保留上一轮的完整池,不用不完整的结果替换它。+6. **fan-out**(`knowledgebase_search_fanout.go`):单组直查零开销;多组用 `errgroup` 并发(上限 4),每组超时 `MULTI_STORE_RETRIEVE_TIMEOUT_SEC`(默认 30s),all-or-nothing 失败策略;结果跨引擎类型时用 `EngineAwareNormalizer` 把向量分归一化到 [0,1](详见检索引擎文档)。+7. **融合**(`knowledgebase_search_fusion.go`):- 仅向量或仅关键词 → `deduplicateByScore`(按 chunk 保留最高分);- 混合 → **加权 RRF**:`score = vectorWeight/(k+vectorRank) + keywordWeight/(k+keywordRank)`,再除以理论最大值 `(vectorWeight+keywordWeight)/(k+1)` 归一化到 [0,1];`k` 与权重来自租户 `RetrievalConfig`(有缺省值),rank 在每个检索结果列表内按分数单独计算(1-indexed),chunk 取最好名次;- 三条路径输出都在 [0,1](向量为 cosine 相似度),不同检索调用的结果可以一起排序。-7. **FAQ 命中策略**(`knowledgebase_search_faq.go`,仅 FAQ 类型 KB):+8. **FAQ 命中策略**(`knowledgebase_search_faq.go`,仅 FAQ 类型 KB):- **迭代检索**(主 KB 为 FAQ 库时):去重后不足 `MatchCount` 且有某个向量结果列表已打满 → 从首轮深度的 2 倍起最多 5 轮翻倍扩大 TopK 重检索,跨 store 组统一生效,每轮按首轮相同的方式融合(分数尺度一致),chunk 数据缓存避免重复回表;种子与每轮增长均封顶 `maxRetrievalPoolSize`,首轮已到上限则不迭代,触顶即停;- **负例问题过滤**:查询与 FAQ 的 `NegativeQuestions` 精确匹配(小写去空格)即剔除该条——支持"这个问题不要用这条 FAQ 答"的运营配置。-8. 截断到 `MatchCount` 后 `processSearchResults` 补全 chunk 元数据(管线场景 `SkipContextEnrichment=true`,上下文组装留给 merge 阶段)。+9. 截断到 `MatchCount` 后 `processSearchResults` 补全 chunk 元数据(管线场景 `SkipContextEnrichment=true`,上下文组装留给 merge 阶段)。FAQ 在管线侧的配套策略(Agent 配置 `FAQPriorityEnabled` / `FAQScoreBoost` / `FAQDirectAnswerThreshold`)见 [CHUNK_RERANK — 重排、复合打分、MMR、Wiki 加权](#_3-4-chunk-rerank-—-重排、复合打分、mmr、wiki-加权) 与 [INTO_CHAT_MESSAGE — 上下文组装](#_3-9-into-chat-message-—-上下文组装)。diff --git a/website-docs/03-features/02-knowledge-base.md b/website-docs/03-features/02-knowledge-base.mdindex 85a1528ce..058e8168b 100644--- a/website-docs/03-features/02-knowledge-base.md+++ b/website-docs/03-features/02-knowledge-base.md@@ -184,13 +184,14 @@ graph TB**ASRConfig**:`enabled` / `model_id` / `language`(语言提示,可选)。-**ImageProcessingConfig(图片属性观察与条件 OCR)**:+**ImageProcessingConfig(图片属性观察、条件 OCR 与图片向量)**:| 字段 | 类型 | 默认 | 说明 || --- | --- | --- | --- || `model_id` | string | - | 图片理解使用的 VLM 模型 ID(参与模型用量追踪) || `image_attrs_enabled` | bool | false | 图片属性观察管线开关。关闭(默认)=历史行为:每张图片各发一次描述请求、各发一次 OCR 请求,不做属性观察;开启后第一轮「属性观察+描述」,再由代码纯函数按观察结果决定该图是否值得再跑一轮 OCR || `image_actions` | object | 见下 | OCR 触发条件:`{ ocr: { on: ImageAttrCondition[], on_unobserved: bool } }`。`on` 为「属性=值」触发条件列表;`on_unobserved` 为属性未被模型观察时的保守兜底(默认 true=仍 OCR) |+| `image_vector_enabled` | bool | false | 图片向量开关。开启且知识库的向量模型能处理图片(模型「图片输入」能力)时,生成图片描述之后再用向量模型直接对图片编码、存一条图片向量,检索时一并召回;见下文「图片向量」 |开启 `image_attrs_enabled` 后,模型**不再对图片分类**,只逐项「观察」属性并产出描述。本期激活两个观察项(完整注册表见 `GET /api/v1/image-attrs/schema`,只读、需 Viewer 权限;该注册表是全局的,不随知识库变化):@@ -211,6 +212,14 @@ OCR 决策是代码纯函数 `DecideOCR`(`internal/application/service/image_a单次上传 / 重新解析可在请求体的 `process_config`(`KnowledgeProcessOverrides`)里按文档覆盖 `image_attrs_enabled` 与 `image_actions`;未传的项沿用知识库设置。`image_actions` 按 action key 合并(`on` 整体替换)。接口字段见[知识库 API](../04-api/02-api-knowledge.md),管线细节见[文档解析](03-document-parsing.md)。+**图片向量(`image_vector_enabled`)**:默认关闭,升级后已有知识库也保持关闭(库里存的配置没有这个键,读出来就是 false),需要在知识库设置「图像处理配置 → 图片向量检索」里(开启多模态后出现)或通过 API 显式开启。只有**开关打开且向量模型能处理图片**时才生效,两者缺一则入库不生成图片向量、检索也不召回图片向量。之所以不随模型能力自动开启:能处理图片的向量模型常常只是被用来编码文本,自动开启会给这些知识库凭空增加每张图片一次的向量调用,并改变检索行为——开启后文档向量检索的候选池放大 1.5 倍,图片命中按 `min(VectorThreshold, 0.1)` 的单独阈值过滤。++- 图片向量在多模态任务里生成,所以还需要开启多模态(VLM):图片向量的 `Content` 复用图片描述(没有描述时用 OCR 文本);扫描件 PDF 页不生成;+- 开关只影响此后入库或重新解析的文档;已有文档要补图片向量需重新解析;+- 开关关闭时,已有的图片向量(关闭前生成的,或文档从开启了图片向量的知识库**移动**过来时随文档带来的)连同其分块会保留,但检索时一律丢弃,不再召回;删除或重新解析文档、删除知识库时随文档一起清除;重新开启开关后,这些保留的图片向量恢复召回。**复制**文档到未开启的知识库则不会复制图片向量;+- 多知识库联合检索时按知识库各自的开关判断,未开启的知识库不召回图片向量;+- 检索引擎无法按来源类型过滤,不召回的图片行(未开启知识库的图片向量命中,以及关键词检索命中的任何图片行)只能在结果返回后丢弃。为免它们占满候选池、把文本挤出去,文档向量池或关键词池打满且含这类图片行时,会把 TopK 翻倍重新检索,直到凑够不需丢弃的候选(文本命中,以及开启了图片向量的知识库的图片命中)、索引耗尽或到达 500 条候选上限(以默认的 50 条池计,每个池最多多 4 次查询)。因此含图片行的 store 组可能多出几次检索查询;排在文本前面的图片行超过约 500 条时,文本命中仍可能被漏掉。补检失败或只部分返回时保留上一轮的完整结果。+**QuestionGenerationConfig(问题生成)**:`enabled`;`question_count` 每分块生成问题数(默认 3,上限 10);`custom_instructions` 目标受众 / 风格说明。**ExtractConfig(知识图谱)**:`enabled`、`text`、`tags`、`nodes []*GraphNode{name, chunks, attributes}`、`relations []*GraphRelation{node1, node2, type}`、`custom_instructions`(领域提取指导)。diff --git a/website-docs/03-features/06-models.md b/website-docs/03-features/06-models.mdindex 159e0e7c1..ab62447bf 100644--- a/website-docs/03-features/06-models.md+++ b/website-docs/03-features/06-models.md@@ -46,6 +46,7 @@| 向量维度 / 自定义输出维度 | 向量 | 维度需与索引一致。只有确认模型支持指定维度时才开启「自定义输出维度」 || 上下文窗口 | 对话、视觉 | 留空使用默认 200000。按厂商文档填写真实值;填得过大会导致智能体历史压缩不触发,上游直接拒绝请求 || 支持视觉/多模态 | 对话 | 模型是否接受图片输入 |+| 图片输入 | 向量 | 模型能否把图片编码到与文本相同的向量空间。开启且厂商协议支持传图时,**开启了「图片向量检索」的知识库**在生成图片描述之后还会为每张图片存一条图片向量,按图片内容召回描述没写到的信息(扫描件 PDF 页除外);知识库的这个开关默认关闭,只声明模型能力不会改变已有知识库的行为。目录中的模型自动识别,只在与目录不一致时才保存到该模型;目录里没有的模型需手动声明 || 最大输出 tokens | 对话、视觉 | 单次回复的输出上限,留空沿用目录中该模型的默认值 || 后台并发上限 | 对话、视觉、向量 | 限制文档入库、富化等后台任务对该模型的并发数;0 或留空使用全局默认,不影响交互式对话 || 高级 → 协议覆盖 | 对话、视觉 | 强制使用某种请求协议,一般保持「自动」 |@@ -190,6 +191,10 @@| `accepts_truncate_prompt_tokens` | bool | false | 服务是否支持 vLLM 的 `truncate_prompt_tokens` || `request_timeout_seconds` | int | 60 | 单次请求超时(秒) || `extra_body` | object | 空 | 附加到每次请求的字段 |+| `image_field` | string | 空 | 仅 `openai-embeddings`:`input` 里承载图片的对象键名(Jina 为 `image`)。留空表示该端点不收图片 |+| `max_image_batch_size` | int | 1 | 单次请求的最大图片数,超出自动分批 |+| `max_image_bytes` | int | 0(不限) | 单张图片的字节上限,超出的图片直接拒绝、不发请求 |+| `image_mime_types` | array | 空(不限) | 厂商接受的图片格式,如 `["image/png", "image/jpeg"]` |**重排模型**diff --git a/website-docs/04-api/02-api-knowledge.md b/website-docs/04-api/02-api-knowledge.mdindex 0c401428f..bee5a7bc6 100644--- a/website-docs/04-api/02-api-knowledge.md+++ b/website-docs/04-api/02-api-knowledge.md@@ -21,7 +21,7 @@| `type` | string | 否 | `document`(默认)/`faq`/`wiki` || `embedding_model_id` | string | 否 | Embedding 模型 ID || `chunking_config` | object | 否 | 分块配置(chunk_size/overlap/separators/strategy…) |-| `image_processing_config` | object | 否 | 图片属性观察配置:`model_id` / `image_attrs_enabled` / `image_actions`(`{ ocr: { on: [...], on_unobserved: bool } }`) |+| `image_processing_config` | object | 否 | 图片处理配置:`model_id` / `image_attrs_enabled` / `image_actions`(`{ ocr: { on: [...], on_unobserved: bool } }`)/ `image_vector_enabled`(图片向量索引与召回,默认 false,见[知识库功能](../03-features/02-knowledge-base.md)) || `storage_provider_config` | object | 否 | 存储配置 || `vector_store_id` | string | 否 | 向量库绑定(非法返回 code 2200/2201) || `faq_config` / `wiki_config` / `extract_config` / `indexing_strategy` | object | 否 | 类型相关配置 |@@ -100,7 +100,7 @@ curl $BASE/api/v1/knowledge-bases/kb-1 -H "Authorization: Bearer $TOKEN"| --- | --- | --- | --- || `name` | string | 是(`binding:"required"`) | 名称 || `description` | string | 否 | 描述 |-| `config` | object | 否 | 局部配置更新:`chunking_config`、`image_processing_config`、`faq_config`、`wiki_config`、`auto_tag_config`、`profile_config`、`indexing_strategy` |+| `config` | object | 否 | 局部配置更新:`chunking_config`、`image_processing_config`、`faq_config`、`wiki_config`、`auto_tag_config`、`profile_config`、`indexing_strategy`。`image_processing_config` 不传则保持不变,传了则整体替换(未带的 `image_vector_enabled` 等字段回到 false) || `vlm_config` | object | 否 | 多模态配置,整体替换:只取 `enabled`、`model_id`(须为 VLLM 模型)、`description_language`、`custom_instructions`(≤4000 字),未传的字段按空值处理;不想改就不要传。共享库需所有者空间或共享 admin 权限(editor 返回 403)。旧版内联字段 `model_name`/`base_url`/`api_key`/`interface_type` 不会被写入:启用托管 `model_id` 或关闭时会清空已存的旧版配置,但纯旧版库(未存 `model_id`,只存了 `model_name`/`base_url`)原样回传 GET 结果(`enabled=false` 且 `model_name`/`base_url` 与存储一致)视为不改;其余库 `enabled=true` 却缺 `model_id` 返回 400 |响应:200 `{"success":true,"data":{KnowledgeBase}}`