WeKnora/internal/models/api/dashscopeembeddings/client.go

120 lines
4.0 KiB
Go
Raw Normal View History

// Package dashscopeembeddings implements Alibaba Model Studio's native
// multimodal embedding shape: input.contents, parameters.dimension, and
// results under output.embeddings.
//
// Only the multimodal models use it. DashScope's text embeddings are served
// on the OpenAI-compatible endpoint, which is why the vendor's default
// protocol is the OpenAI one and the multimodal entries override it.
//
// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
package dashscopeembeddings
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.EmbeddingsSettings
Dimensions int
Retry api.RetryPolicy
}
// Client talks DashScope's native multimodal embedding to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
type response struct {
Output struct {
Embeddings []struct {
// The position field is `index`. DashScope's *text* embedding API
// one page over calls it `text_index`, and decoding that name
// here yields 0 for every element, collapsing a whole batch onto
// slot 0 (Tencent/WeKnora#3484).
Index int `json:"index"`
Embedding []float32 `json:"embedding"`
Type string `json:"type"`
} `json:"embeddings"`
} `json:"output"`
Code string `json:"code"`
Message string `json:"message"`
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[string]any {
contents := make([]any, 0, len(texts))
for _, text := range texts {
contents = append(contents, map[string]any{"text": text})
}
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
return c.body(contents)
}
// BuildImageRequestBody is the golden-test entry point for images. Each
// content is {"image": URL or "data:image/{format};base64,{data}"}.
func (c *Client) BuildImageRequestBody(images []api.EmbedImage, _ api.EmbedInputType) map[string]any {
contents := make([]any, 0, len(images))
for _, img := range images {
contents = append(contents, map[string]any{"image": img.DataURI()})
}
return c.body(contents)
}
func (c *Client) body(contents []any) map[string]any {
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"input": map[string]any{"contents": contents},
}
// The width lives under parameters, not at the top level, and the field
// is singular: `dimension`.
if c.cfg.Settings.DimensionsField != "" && c.cfg.Dimensions > 0 {
body["parameters"] = map[string]any{c.cfg.Settings.DimensionsField: c.cfg.Dimensions}
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
return body
}
// Embed vectorizes one batch.
func (c *Client) Embed(
ctx context.Context, texts []string, kind api.EmbedInputType,
) ([][]float32, error) {
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
return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))
}
// AcceptsImages is always true: the image part is part of the schema.
func (c *Client) AcceptsImages() bool { return true }
// EmbedImages vectorizes one batch of images, each its own vector.
func (c *Client) EmbedImages(
ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,
) ([][]float32, error) {
return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))
}
func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {
var decoded response
url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)
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
err := c.cfg.Endpoint.PostJSONWithRetry(ctx, url, body, &decoded, c.cfg.Retry, "embedding")
if err != nil {
return nil, err
}
// DashScope reports some failures in the body with a 200.
if decoded.Code != "" {
return nil, fmt.Errorf("DashScope embedding error %s: %s", decoded.Code, decoded.Message)
}
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
return api.PlaceEmbeddings(want, len(decoded.Output.Embeddings), func(i int) (int, []float32) {
return decoded.Output.Embeddings[i].Index, decoded.Output.Embeddings[i].Embedding
})
}