From 0c5d28abb7917b49d36f79bafb78fb59796a068b Mon Sep 17 00:00:00 2001 From: lyingbug Date: Thu, 8 Oct 2026 18:19:53 +0800 Subject: [PATCH] feat: index and recall images with multimodal embedding models (#3683) * feat(models): expose embedding input modalities Whether an embedding model maps images into the same space as text is what will decide if a knowledge base can store image vectors. The catalog already had the field, but most multimodal embedding models were missing it and embedding rows never reported it. - Catalog: declare input modalities for the Doubao and Tongyi vision embeddings, the Aliyun multimodal / qwen-vl embedding families and jina-embeddings-v4, as listed in each vendor's documentation. The migration baseline changes for exactly these nine entries. - Model responses resolve capabilities for embedding rows too, so capabilities.input reflects the catalog merged with spec.input. - Model editor: an "Image input" switch for embedding models. It follows the catalog and writes spec.input only when the row differs from it; picking another catalog model or switching vendor drops the declaration. Model cards show the image badge for such models. * feat(embedding): embed images with multimodal embedding models Adds the image side of an embedder, for models that map images into the same space as their text vectors so a text query can find an image. - api: EmbedImage (bytes + MIME type, sent inline as base64 because the object store is usually unreachable from the vendor) and an ImageEmbedder implemented by all four protocols, each in the image shape its reference documents: Ark image_url, DashScope contents[].image, Gemini inlineData parts, and on the OpenAI shape an object keyed by the vendor's image_field (Jina: "image"). A plain OpenAI-compatible endpoint names no image field and takes no images. - Settings: image_field, max_image_batch_size (default one per request), max_image_bytes and image_mime_types, filled from vendor docs for the DashScope multimodal models, gemini-embedding-2 and Jina. - embedding: an optional ImageEmbedder interface reached through AsImageEmbedder, so existing Embedder implementations and fakes are untouched. An embedder takes images only when the catalog (or the row's spec.input) lists image AND the endpoint can carry one. Images are checked against the documented limits before any request, then split at the documented images per request. The concurrency, debug and Langfuse decorators forward it; logs and traces carry the MIME type and size, never the bytes. The migration baseline changes only for the entries whose resolved embedding settings now carry image limits. * feat(knowledge): index images by their own vector and recall them When the knowledge base's embedding model embeds images, each image now gets a vector of its own next to its caption and OCR chunks, so a query can find an image by what it shows even where the caption left it out. Ingestion - After the caption/OCR chunks are indexed, the multimodal task embeds the image (embedding.PrepareImage converts and shrinks it to the vendor's documented limits) and stores it as a new image_vector chunk: Content is the caption (OCR text when there is none) for reranking and the answer context; its index row carries the image's vector with SourceType ImageSourceType. Scanned PDF pages are skipped, their OCR text serves better. A failure here is logged and never fails the task. - The image vector gets its own chunk rather than a second index row on the caption chunk: OpenSearch and Weaviate key documents by ChunkID, so a second row would overwrite the caption's text vector, and copy, move and enable/disable all follow chunk IDs. - CompositeRetrieveEngine.BatchIndexVectors writes precomputed vectors through each engine's normal BatchIndex, keeping row order (the composite's de-duplication does not). - Paths that rebuild vectors from text leave image_vector alone: syncChunkIndex only syncs its enabled flag, updateChunkVector skips it, and a caption edit updates its Content only. - The multimodal task's caption/OCR index rows now set IsEnabled; only backends with a column default were storing them as enabled. Retrieval - A text query scores lower against an image than against text, so when the model embeds images the document vector search is widened by half (capped at 500) and run at min(VectorThreshold, 0.1); each store group's hits are then held to their own threshold before score normalization: text at VectorThreshold, images at min(VectorThreshold, 0.1). Keyword hits on image rows are dropped, their Content being the already-indexed caption. - image_vector hits are searchable and merge like caption hits: parent context is attached, and the caption is not repeated from ImageInfo. Adds golang.org/x/image for scaling and WebP/BMP decoding. * fix(models): report no thinking levels for embedding, rerank and ASR models Embedding rows now carry capabilities, and the end-to-end run showed them listing off/auto/minimal/low/medium/high: these references resolve no chat protocol, and an empty level map reads as "every level supported". A model without a chat protocol does not think, so its capabilities say so. * fix(compaction): never read a cancelled turn's stream as a summary streamSummary selects on the turn's context and the provider stream at once. When the turn is already cancelled both are ready (providers close the stream once their context ends), and select picks at random, so a stopped turn could come back as a completed, partial summary with a nil error. TestSummarizationIsNotRetriedOnceTheTurnIsCancelled caught it intermittently in CI and reproduces under -race with several -cpu values. Check the context before each receive and again when the stream closes. * feat(knowledge): put image vectors behind a knowledge-base switch, off by default Image vector indexing and recall used to turn on whenever the knowledge base's embedding model declared image input. A model that takes images is often chosen for text alone, so an upgrade would have added an embedding call per image, widened vector recall 1.5x and lowered the image threshold to 0.1 for those knowledge bases without anyone asking. ImageProcessingConfig gains image_vector_enabled (default false; stored JSON without the key reads as off, so existing knowledge bases stay off with no migration). Both sides now need the switch and the model: - indexImageVector returns before touching the model unless the KB opted in (KnowledgeBase.IsImageVectorEnabled, which also needs vector indexing). - applyImageRecall resolves the embedding model only when some KB in the search opted in, and records the opted-in KBs per store group (storeGroup.ImageKBIDs). Only those groups widen the pool and lower the threshold; image hits of any other KB, including ones indexed before the switch was turned off, are dropped. The KB editor shows the switch in the image processing section, with a warning when the selected embedding model does not declare image input; docs describe the switch, its cost and what turning it off does. * fix(knowledge): leave image vectors behind when cloning into a KB that is off CloneChunk copied every chunk of the source document and then CopyIndices for all of them, so copying a document from a knowledge base with image vectors on into one with the switch off (same model and store) still created image_vector chunks and their index rows, bypassing the switch that indexImageVector honours. Image vector chunks are now dropped from the copy when the target has not opted in. Every engine's CopyIndices copies only the rows of chunks in the mapping, so their index rows stay behind too. * fix(search): refill the vector pool past stale image vectors Image hits of a knowledge base whose switch is off were dropped only after the engine had ranked and cut its results at TopK. Image vectors indexed before the switch was turned off could fill that pool and push out valid text hits: with MatchCount 5 the pool is 50, and 50 stale image rows ranked above the text left the search empty. No engine can filter rows by source type (Postgres and SQLite do not even take ExcludeChunkIDs), so the exclusion cannot move into the query. When the document vector pool comes back full and holds stale image rows, that search alone runs again on a pool twice as large, until it holds TopK rows that are not stale, the index runs out, or the pool reaches maxRetrievalPoolSize (at most four extra calls from a pool of 50). The pool is then cut back to TopK such rows, matching an engine-side exclusion unless more than maxRetrievalPoolSize-TopK stale rows rank above the text. * feat(i18n): translate the image vector switch and image input keys into zh-TW The zh-TW locale arrived from main after this branch added five keys: the knowledge base's image vector switch (label, description, unsupported-model warning) and the embedding model's image input flag (label, description). * fix(knowledge): leave image vectors behind when moving into a KB that is off A reuse_vectors move relocates a document's chunks and index rows in place: MoveKnowledgeIndices rebinds the rows by document ID and MoveChunksByKnowledgeID rebinds the chunks. Moving a document from a knowledge base with image vectors on into one with the switch off therefore carried its image_vector chunks and their vectors along, the same bypass the clone path had. When the target has not opted in, the image_vector chunks are now deleted during the move, their index rows first and then the chunks, so a retry finds the chunks again rather than leaving orphaned rows. A target that opted in still receives them unchanged. * fix(retriever): keep image vectors out of keyword-only engines BatchIndexVectors handed image rows to every engine of the composite, including one that serves keyword retrieval alone (Elasticsearch v7 next to a vector store). There the row holds nothing but the image's caption, which the caption's own chunk already indexes, and retrieval discards every keyword hit on it. Image rows now go only to engines that serve vector retrieval. An engine that serves both keeps one row for both kinds, so its keyword search still meets them; the search side handles that. * fix(search): refill the keyword pool past image rows Every engine that serves both kinds of retrieval stores one row per index entry and runs its keyword search over that row's content, so an image vector row, whose content is its caption, is a keyword hit wherever the caption's own chunk is. filterImageHits drops all of them, but only after the engine has cut its ranking at TopK, so they crowded out text and caption hits; a keyword ranking that put the image rows first came back empty. The keyword pool is now refilled the way the vector pool is refilled past stale image vectors: when it came back full and held image rows, the keyword search runs again on a pool twice as large, up to maxRetrievalPoolSize, and is cut back to TopK hits that are kept. Leaving the rows out of the keyword index instead would mean writing them without searchable content (Milvus and Tencent VectorDB derive a BM25 sparse vector from it, and how they take an empty one is unverified) or a source-type filter in every engine's keyword query (ten engines, and filterable fields that existing collections lack). * revert: let image vectors move with the document into a KB that is off This reverts commit e259977fe915f7d0bc30c4b02bc7af04da1c8dd4. Deleting the image vector index rows by chunk ID before the move is not reliable: the Weaviate and Elasticsearch v8 delete wrappers ignore partial failures, and OpenSearch rejects more than 1000 IDs with ErrBatchTooLarge. A partial delete followed by the chunk delete leaves index rows whose chunks are gone, which nothing ever cleans up. Without it, the image_vector chunks and their index rows move together with the document. While the target's switch is off they are filtered at query time (the pool refill keeps them from crowding out text), they are removed with the document on delete, reparse or knowledge base delete, both chunks and index rows by knowledge ID, and they become active again if the target turns the switch on. The clone path keeps dropping them, since there the rows are copied rather than moved. * fix(search): keep the image row refill from losing hits it already had refillPool replaced a pool with the answer to each larger search. A refill that answered only in part (RetrieveResult.Error, swallowed into a warning by retainPartialResults, as when some collections of the store did not answer) could hold fewer text rows than the complete smaller pool, or none: 40 stale image rows above 10 text came back from a partial refill as the 40 image rows alone, and the search lost all 10 text hits. A refill that failed outright failed the whole store group, discarding a first round that had succeeded. A refill is now best effort. A failed or incomplete refill search stops the refill and leaves the last complete pool in place, cut back to TopK kept rows as before, so a refill can no longer leave a search worse off than it was without it. Merging the partial answer into the pool was not done: its rows would need deduplicating and its ranking is cut at a different TopK over a different set of collections, while keeping the previous pool is exact. * docs(knowledge): say what happens to image vectors in a KB that is off and what the refill costs The image vector section now says that with the switch off, image vectors that were indexed before it was turned off, or that came along when the document was moved in from a KB that has it on, are kept but filtered at query time, are removed when the document is deleted or reparsed or the KB is deleted, and are recalled again once the switch is turned on; a copy into such a KB leaves them behind. It also states the cost of keeping dropped image rows from crowding text out of the pools: the vector and keyword pools are searched again with TopK doubled up to the 500 candidate cap, which adds queries for store groups that hold such rows, and text can still be missed when more than about 500 candidates are image rows. A failed or partial refill keeps the previous complete pool. * fix(search): log unexpected refill result sets, and describe the refill stop condition precisely --- frontend/src/api/knowledge-base/index.ts | 10 +- frontend/src/components/ModelEditorDialog.vue | 43 ++ .../src/components/modelEditorFlow.test.ts | 43 ++ frontend/src/i18n/locales/en-US.ts | 5 + frontend/src/i18n/locales/ja-JP.ts | 5 + frontend/src/i18n/locales/ko-KR.ts | 5 + frontend/src/i18n/locales/ru-RU.ts | 5 + frontend/src/i18n/locales/zh-CN.ts | 5 + frontend/src/i18n/locales/zh-TW.ts | 5 + .../src/utils/imageProcessingConfig.test.ts | 32 +- frontend/src/utils/imageProcessingConfig.ts | 11 +- .../knowledge/KnowledgeBaseEditorModal.vue | 31 ++ frontend/src/views/settings/ModelSettings.vue | 3 +- go.mod | 1 + internal/agent/compaction/compactor.go | 9 + .../service/chat_pipeline/merge.go | 6 +- .../merge_parent_resolve_test.go | 40 ++ internal/application/service/chunk.go | 7 +- .../service/chunk_edit_parent_test.go | 17 +- .../application/service/image_multimodal.go | 122 ++++- .../service/image_multimodal_vector_test.go | 241 +++++++++ .../service/knowledge_clone_move.go | 8 + .../application/service/knowledge_process.go | 14 + .../service/knowledge_transfer_test.go | 69 +++ .../service/knowledgebase_search.go | 3 + .../service/knowledgebase_search_fanout.go | 25 +- .../service/knowledgebase_search_image.go | 290 ++++++++++ .../knowledgebase_search_image_test.go | 498 ++++++++++++++++++ .../service/knowledgebase_search_results.go | 6 +- .../knowledgebase_search_storegroup.go | 14 + .../service/retriever/precomputed.go | 85 +++ .../service/retriever/precomputed_test.go | 86 +++ internal/handler/dto/model.go | 9 +- internal/handler/dto/model_test.go | 36 ++ internal/models/api/arkembeddings/client.go | 41 +- .../models/api/dashscopeembeddings/client.go | 34 +- internal/models/api/embeddings.go | 26 + internal/models/api/embeddings_settings.go | 47 ++ .../models/api/googleembeddings/client.go | 51 +- .../models/api/openaiembeddings/client.go | 43 +- .../models/catalog/data/models.generated.json | 77 ++- internal/models/catalog/data/overrides.json | 35 +- internal/models/catalog/data/seed.json | 44 ++ .../models/embedding/concurrency_wrapper.go | 17 + internal/models/embedding/embedder.go | 57 ++ internal/models/embedding/image_prep.go | 107 ++++ internal/models/embedding/image_prep_test.go | 96 ++++ internal/models/embedding/image_wire_test.go | 209 ++++++++ internal/models/embedding/langfuse_wrapper.go | 43 ++ internal/models/embedding/llm_debug.go | 28 + internal/models/embedding/protocol.go | 58 +- internal/models/embedding/wire_test.go | 42 +- .../parity/testdata/catalog-baseline.json | 36 +- internal/models/providers/jina.go | 5 + internal/models/runtime/resolve.go | 6 + internal/searchutil/imageinfo.go | 9 + internal/types/chunk.go | 11 + internal/types/embedding.go | 6 + internal/types/knowledgebase.go | 15 + internal/types/knowledgebase_test.go | 51 ++ .../02-architecture/03-document-pipeline.md | 2 + .../02-architecture/04-rag-pipeline.md | 11 +- website-docs/03-features/02-knowledge-base.md | 11 +- website-docs/03-features/06-models.md | 5 + website-docs/04-api/02-api-knowledge.md | 4 +- 65 files changed, 2921 insertions(+), 95 deletions(-) create mode 100644 internal/application/service/image_multimodal_vector_test.go create mode 100644 internal/application/service/knowledgebase_search_image.go create mode 100644 internal/application/service/knowledgebase_search_image_test.go create mode 100644 internal/application/service/retriever/precomputed.go create mode 100644 internal/application/service/retriever/precomputed_test.go create mode 100644 internal/models/embedding/image_prep.go create mode 100644 internal/models/embedding/image_prep_test.go create mode 100644 internal/models/embedding/image_wire_test.go diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index c4ae43a6..48e0bef1 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 + +
+ +
+ + {{ $t('model.editor.embeddingImageInputDesc') }} +
+
+
@@ -955,6 +964,38 @@ const vendorDocLink = computed(() => { */ const catalogFilled = ref>({}) +/** 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({ + 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 = true catalogFilled.value.supportsVision = true } + if (activeModelType.value === 'embedding') dropEmbeddingInputOverride() if (activeModelType.value === 'embedding' && !formData.value.dimension && entry.dimension) { formData.value.dimension = entry.dimension catalogFilled.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 = false modelAvailable.value = false diff --git a/frontend/src/components/modelEditorFlow.test.ts b/frontend/src/components/modelEditorFlow.test.ts index 08d0d449..5be2bd09 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.ts index 8324bb92..e56d2f01 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.ts index 2c377c9b..d602dd0a 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.ts index c0c3074b..298bcde3 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.ts index 9675aac7..248cbd44 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.ts index 9fcc1a81..d26e0db4 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.ts index 007321b0..3f7a5473 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.ts index 56178c21..340aadb8 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.ts index 400b0619..0002992e 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: boolean onUnobserved: 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 | null | undefined, @@ -30,7 +36,7 @@ export function buildImageProcessingConfig( const snap = snapshot || {} const storedOn = (snap.image_actions as { ocr?: { on?: unknown } } | undefined)?.ocr?.on const on = Array.isArray(storedOn) && storedOn.length > 0 ? storedOn : edits.defaultOn - const built = { + const built: Record = { ...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.vue index f7fdd055..360a2cad 100644 --- a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue +++ b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue @@ -364,6 +364,20 @@
+ +
+
+ +

{{ $t('knowledgeEditor.advanced.multimodal.imageVectorDescription') }}

+

+ {{ $t('knowledgeEditor.advanced.multimodal.imageVectorModelUnsupported') }} +

+
+
+ +
+
+
@@ -828,6 +842,13 @@ const advancedSettingsRef = ref>() // 表单数据 const formData = ref(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 | null, asrConfig: { @@ -1062,6 +1085,8 @@ const loadKBData = async ( }, imageAttrsEnabled: !!(kb as Record).image_processing_config?.image_attrs_enabled, + imageVectorEnabled: + !!(kb as Record).image_processing_config?.image_vector_enabled, imageActions: mergeImageActions( (kb as Record).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.vue index 9efa2082..f68fc4e7 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) }} -