WeKnora/internal/models/embedding/protocol.go

216 lines
7.2 KiB
Go
Raw Normal View History

package embedding
import (
"context"
"fmt"
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
2026-10-08 10:19:53 +00:00
"slices"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/models/api/arkembeddings"
"github.com/Tencent/WeKnora/internal/models/api/dashscopeembeddings"
"github.com/Tencent/WeKnora/internal/models/api/googleembeddings"
"github.com/Tencent/WeKnora/internal/models/api/openaiembeddings"
modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"
"github.com/Tencent/WeKnora/internal/types"
)
// retryPolicy is the transport-error retry budget; tests shorten it.
var retryPolicy = api.DefaultRetryPolicy
// newRemoteEmbedder resolves the catalog and returns the protocol client for
// the configured model, wrapped in the shared batching layer. It mirrors
// rerank.newReranker: the vendor's facts decide the protocol, the URL and the
// credential, and this function knows no vendor names.
func newRemoteEmbedder(config Config, pooler EmbedderPooler) (Embedder, error) {
if strings.TrimSpace(config.ModelName) == "" {
return nil, fmt.Errorf("model name is required")
}
resolved, err := modelruntime.Resolve(modelruntime.Ref{
Provider: config.Provider,
Model: config.ModelName,
BaseURL: config.BaseURL,
ModelType: types.ModelTypeEmbedding,
Extra: config.ExtraConfig,
Override: config.Spec,
TruncatePromptTokens: config.TruncatePromptTokens,
})
if err != nil {
return nil, err
}
if err := validateEmbeddingBaseURL(resolved.BaseURL); err != nil {
return nil, err
}
vendor := resolved.Vendor
endpoint, err := resolved.Endpoint(types.ModelTypeEmbedding, modelruntime.Connection{
ModelID: config.ModelID,
Credentials: api.Credentials{APIKey: config.APIKey, AppID: config.AppID, AppSecret: config.AppSecret},
Headers: config.CustomHeaders,
Extra: config.ExtraConfig,
Client: newEmbeddingHTTPClient(time.Duration(resolved.Embeddings.RequestTimeout) * time.Second),
})
if err != nil {
return nil, err
}
if endpoint.URL != "" {
if err := validateEmbeddingBaseURL(endpoint.URL); err != nil {
return nil, err
}
}
settings := resolved.Embeddings
// The width is the vendor's field but the operator's decision: a row
// that did not opt in keeps the model's native width even where the
// vendor could narrow it.
dimensions := 0
if config.SupportsDimensionOverride {
dimensions = config.Dimensions
}
retry := retryPolicy()
var client api.Embedder
switch resolved.EmbeddingAPI {
case api.EmbeddingOpenAI:
client = openaiembeddings.New(openaiembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
case api.EmbeddingDashScope:
client = dashscopeembeddings.New(dashscopeembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
case api.EmbeddingArk:
client = arkembeddings.New(arkembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
case api.EmbeddingGoogle:
client = googleembeddings.New(googleembeddings.Config{
Endpoint: endpoint, Settings: settings, Dimensions: dimensions, Retry: retry,
})
default:
return nil, fmt.Errorf("unsupported embedding api %q for provider %s", resolved.EmbeddingAPI, vendor.ID)
}
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
2026-10-08 10:19:53 +00:00
// 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,
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
2026-10-08 10:19:53 +00:00
images: images,
settings: settings,
modelName: config.ModelName,
modelID: config.ModelID,
dimensions: config.Dimensions,
EmbedderPooler: pooler,
}, nil
}
// protocolEmbedder adapts a protocol client to the Embedder interface and
// owns the two things every vendor needs and none of them should implement
// 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 {
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
2026-10-08 10:19:53 +00:00
inner api.Embedder
// images is nil unless the model and the endpoint both take images.
images api.ImageEmbedder
settings api.EmbeddingsSettings
modelName string
modelID string
dimensions int
EmbedderPooler
}
func (e *protocolEmbedder) GetModelName() string { return e.modelName }
func (e *protocolEmbedder) GetModelID() string { return e.modelID }
func (e *protocolEmbedder) GetDimensions() int { return e.dimensions }
func (e *protocolEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
vectors, err := e.BatchEmbed(ctx, []string{text})
if err != nil {
return nil, err
}
return vectors[0], nil
}
func (e *protocolEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
if len(texts) == 0 {
return nil, nil
}
kind := api.EmbedDocument
if types.IsEmbedQuery(ctx) {
kind = api.EmbedQuery
}
batches, err := api.SplitBatches(texts, 0, e.settings.BatchLimits())
if err != nil {
return nil, fmt.Errorf("%s embedding: %w", e.modelName, err)
}
out := make([][]float32, len(texts))
// Serial on purpose. BatchEmbedWithPool and the per-model concurrency
// gate already bound how many requests are in flight; fanning out again
// here would multiply past both, and a one-text-per-request vendor would
// turn every pool chunk into a burst.
for _, batch := range batches {
vectors, err := e.inner.Embed(ctx, batch.Items, kind)
if err != nil {
return nil, err
}
if len(vectors) != len(batch.Items) {
return nil, fmt.Errorf(
"%s embedding: %d vectors for %d inputs", e.modelName, len(vectors), len(batch.Items),
)
}
copy(out[batch.Start:], vectors)
}
return out, nil
}
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
2026-10-08 10:19:53 +00:00
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
}