2026-09-21 03:55:38 +00:00
|
|
|
package embedding
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
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
|
|
|
"encoding/base64"
|
2026-09-21 03:55:38 +00:00
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"net/http"
|
|
|
|
|
"net/http/httptest"
|
|
|
|
|
"strings"
|
|
|
|
|
"sync"
|
|
|
|
|
"testing"
|
|
|
|
|
"unicode/utf8"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// recorded is one request as the upstream saw it.
|
|
|
|
|
type recorded struct {
|
|
|
|
|
path string
|
|
|
|
|
query string
|
|
|
|
|
header http.Header
|
|
|
|
|
body map[string]any
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// upstream is a stand-in vendor. It answers in whichever shape the request's
|
|
|
|
|
// path asks for, one vector per input whose single value is the input's
|
|
|
|
|
// length in runes, so that a test can tell which vector went where.
|
|
|
|
|
type upstream struct {
|
|
|
|
|
mu sync.Mutex
|
|
|
|
|
requests []recorded
|
|
|
|
|
url string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func allowLoopback(t *testing.T) {
|
|
|
|
|
t.Helper()
|
|
|
|
|
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
|
|
|
|
secutils.ResetSSRFWhitelistForTest()
|
|
|
|
|
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func newUpstream(t *testing.T) *upstream {
|
|
|
|
|
t.Helper()
|
|
|
|
|
allowLoopback(t)
|
|
|
|
|
u := &upstream{}
|
|
|
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
var body map[string]any
|
|
|
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
u.mu.Lock()
|
|
|
|
|
u.requests = append(u.requests, recorded{r.URL.Path, r.URL.RawQuery, r.Header.Clone(), body})
|
|
|
|
|
u.mu.Unlock()
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
_, _ = w.Write([]byte(answer(r.URL.Path, body)))
|
|
|
|
|
}))
|
|
|
|
|
t.Cleanup(server.Close)
|
|
|
|
|
u.url = server.URL
|
|
|
|
|
return u
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func runeLen(v any) int { return utf8.RuneCountInString(v.(string)) }
|
|
|
|
|
|
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
|
|
|
// itemLen is the length of one input item whatever its shape: the runes of
|
|
|
|
|
// a text, or the decoded bytes of an inline image. Images in these tests
|
|
|
|
|
// differ in size, so the vector still tells which input it answers.
|
|
|
|
|
func itemLen(v any) int {
|
|
|
|
|
item, ok := v.(map[string]any)
|
|
|
|
|
if !ok {
|
|
|
|
|
return runeLen(v)
|
|
|
|
|
}
|
|
|
|
|
switch {
|
|
|
|
|
case item["text"] != nil:
|
|
|
|
|
return runeLen(item["text"])
|
|
|
|
|
case item["image"] != nil:
|
|
|
|
|
return dataURILen(item["image"].(string))
|
|
|
|
|
case item["image_url"] != nil:
|
|
|
|
|
return dataURILen(item["image_url"].(map[string]any)["url"].(string))
|
|
|
|
|
case item["inlineData"] != nil:
|
|
|
|
|
data, _ := base64.StdEncoding.DecodeString(item["inlineData"].(map[string]any)["data"].(string))
|
|
|
|
|
return len(data)
|
|
|
|
|
}
|
|
|
|
|
panic(fmt.Sprintf("unrecognised input item %v", item))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func dataURILen(uri string) int {
|
|
|
|
|
_, encoded, ok := strings.Cut(uri, ";base64,")
|
|
|
|
|
if !ok {
|
|
|
|
|
panic("not a base64 data URI: " + uri)
|
|
|
|
|
}
|
|
|
|
|
data, _ := base64.StdEncoding.DecodeString(encoded)
|
|
|
|
|
return len(data)
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-21 03:55:38 +00:00
|
|
|
// answer replies in the protocol the path belongs to. The OpenAI and
|
|
|
|
|
// DashScope shapes are answered in reverse order so that placement by index
|
|
|
|
|
// is exercised on every request.
|
|
|
|
|
func answer(path string, body map[string]any) string {
|
|
|
|
|
var parts []string
|
|
|
|
|
switch {
|
|
|
|
|
case strings.HasSuffix(path, ":batchEmbedContents"):
|
|
|
|
|
for _, req := range body["requests"].([]any) {
|
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
|
|
|
part := req.(map[string]any)["content"].(map[string]any)["parts"].([]any)[0]
|
|
|
|
|
parts = append(parts, fmt.Sprintf(`{"values":[%d]}`, itemLen(part)))
|
2026-09-21 03:55:38 +00:00
|
|
|
}
|
|
|
|
|
return `{"embeddings":[` + strings.Join(parts, ",") + `]}`
|
|
|
|
|
case strings.HasSuffix(path, "/multimodal-embedding"):
|
|
|
|
|
contents := body["input"].(map[string]any)["contents"].([]any)
|
|
|
|
|
for i := len(contents) - 1; i >= 0; i-- {
|
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
|
|
|
n := itemLen(contents[i])
|
2026-09-21 03:55:38 +00:00
|
|
|
parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d],"type":"text"}`, i, n))
|
|
|
|
|
}
|
|
|
|
|
return `{"output":{"embeddings":[` + strings.Join(parts, ",") + `]}}`
|
|
|
|
|
case strings.HasSuffix(path, "/embeddings/multimodal"):
|
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
|
|
|
n := itemLen(body["input"].([]any)[0])
|
2026-09-21 03:55:38 +00:00
|
|
|
return fmt.Sprintf(`{"data":{"embedding":[%d],"object":"embedding"}}`, n)
|
2026-10-10 03:06:00 +00:00
|
|
|
case body["messages"] != nil:
|
|
|
|
|
turn := body["messages"].([]any)[0].(map[string]any)
|
|
|
|
|
n := itemLen(turn["content"].([]any)[0])
|
|
|
|
|
return fmt.Sprintf(`{"data":[{"index":0,"embedding":[%d]}]}`, n)
|
2026-09-21 03:55:38 +00:00
|
|
|
default:
|
|
|
|
|
input := body["input"].([]any)
|
|
|
|
|
for i := len(input) - 1; i >= 0; i-- {
|
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
|
|
|
parts = append(parts, fmt.Sprintf(`{"index":%d,"embedding":[%d]}`, i, itemLen(input[i])))
|
2026-09-21 03:55:38 +00:00
|
|
|
}
|
|
|
|
|
return `{"data":[` + strings.Join(parts, ",") + `]}`
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func texts(n int) []string {
|
|
|
|
|
out := make([]string, n)
|
|
|
|
|
for i := range out {
|
|
|
|
|
out[i] = strings.Repeat("x", i+1)
|
|
|
|
|
}
|
|
|
|
|
return out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func strs(in []string) []any {
|
|
|
|
|
out := make([]any, len(in))
|
|
|
|
|
for i, s := range in {
|
|
|
|
|
out[i] = s
|
|
|
|
|
}
|
|
|
|
|
return out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestEmbeddingWireFormatPerVendor pins, for every embedding vendor in the
|
|
|
|
|
// catalog, the request the factory actually sends: URL, credential and the
|
|
|
|
|
// complete body. Each expectation traces to the vendor's reference as cited
|
|
|
|
|
// in its vendor.go; a field appears here only if that page documents it.
|
|
|
|
|
func TestEmbeddingWireFormatPerVendor(t *testing.T) {
|
|
|
|
|
three := []string{"a", "bb", "ccc"}
|
|
|
|
|
openAIBody := func(model string, input []string, extra map[string]any) map[string]any {
|
|
|
|
|
body := map[string]any{"model": model, "input": strs(input)}
|
|
|
|
|
for k, v := range extra {
|
|
|
|
|
body[k] = v
|
|
|
|
|
}
|
|
|
|
|
return body
|
|
|
|
|
}
|
|
|
|
|
arkBody := func(model, text string, extra map[string]any) map[string]any {
|
|
|
|
|
body := map[string]any{
|
|
|
|
|
"model": model,
|
|
|
|
|
"input": []any{map[string]any{"type": "text", "text": text}},
|
|
|
|
|
}
|
|
|
|
|
for k, v := range extra {
|
|
|
|
|
body[k] = v
|
|
|
|
|
}
|
|
|
|
|
return body
|
|
|
|
|
}
|
|
|
|
|
dashBody := func(model string, input []string, extra map[string]any) map[string]any {
|
|
|
|
|
contents := make([]any, len(input))
|
|
|
|
|
for i, s := range input {
|
|
|
|
|
contents[i] = map[string]any{"text": s}
|
|
|
|
|
}
|
|
|
|
|
body := map[string]any{"model": model, "input": map[string]any{"contents": contents}}
|
|
|
|
|
for k, v := range extra {
|
|
|
|
|
body[k] = v
|
|
|
|
|
}
|
|
|
|
|
return body
|
|
|
|
|
}
|
|
|
|
|
const dashPath = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"
|
|
|
|
|
|
|
|
|
|
cases := []struct {
|
|
|
|
|
name string
|
|
|
|
|
provider string
|
|
|
|
|
model string
|
|
|
|
|
base string // appended to the upstream URL
|
|
|
|
|
extra map[string]string
|
|
|
|
|
override bool // supports_dimension_override with dimension 256
|
|
|
|
|
truncate int // embedding_parameters.truncate_prompt_tokens
|
|
|
|
|
query bool
|
|
|
|
|
texts []string
|
|
|
|
|
appID string
|
|
|
|
|
|
|
|
|
|
wantPath string
|
|
|
|
|
wantQuery string
|
|
|
|
|
wantAuth [2]string
|
|
|
|
|
wantRequests int
|
|
|
|
|
wantBody map[string]any // the first request's body, exactly
|
|
|
|
|
}{
|
|
|
|
|
{
|
|
|
|
|
name: "openai sends dimensions where the row opted in", provider: "openai",
|
|
|
|
|
model: "text-embedding-3-small", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("text-embedding-3-small", three,
|
|
|
|
|
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "openai keeps the native width without the opt-in", provider: "openai",
|
|
|
|
|
model: "text-embedding-3-small", base: "/v1",
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("text-embedding-3-small", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "ada-002 has a fixed width", provider: "openai",
|
|
|
|
|
model: "text-embedding-ada-002", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("text-embedding-ada-002", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "generic keeps the historical truncation budget", provider: "generic",
|
|
|
|
|
model: "bge-m3", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("bge-m3", three, map[string]any{
|
|
|
|
|
"encoding_format": "float", "dimensions": float64(256), "truncate_prompt_tokens": float64(511),
|
|
|
|
|
}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "generic honours the row's truncation budget", provider: "generic",
|
|
|
|
|
model: "bge-m3", base: "/v1", truncate: 256,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("bge-m3", three, map[string]any{
|
|
|
|
|
"encoding_format": "float", "truncate_prompt_tokens": float64(256),
|
|
|
|
|
}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "gpustack is a vLLM runtime", provider: "gpustack",
|
|
|
|
|
model: "bge-m3", base: "/v1",
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("bge-m3", three, map[string]any{
|
|
|
|
|
"encoding_format": "float", "truncate_prompt_tokens": float64(511),
|
|
|
|
|
}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "zhipu documents no encoding_format", provider: "zhipu",
|
|
|
|
|
model: "embedding-3", base: "/api/paas/v4", override: true, truncate: 300,
|
|
|
|
|
wantPath: "/api/paas/v4/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("embedding-3", three, map[string]any{"dimensions": float64(256)}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "zhipu embedding-2 is fixed at 1024", provider: "zhipu",
|
|
|
|
|
model: "embedding-2", base: "/api/paas/v4", override: true,
|
|
|
|
|
wantPath: "/api/paas/v4/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("embedding-2", three, nil),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "jina truncates as it always has and sends no task", provider: "jina",
|
|
|
|
|
model: "jina-embeddings-v3", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("jina-embeddings-v3", three,
|
|
|
|
|
map[string]any{"dimensions": float64(256), "truncate": true}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "nvidia embeds documents as passages", provider: "nvidia",
|
|
|
|
|
model: "nvidia/nemotron-3-embed-1b", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("nvidia/nemotron-3-embed-1b", three, map[string]any{
|
|
|
|
|
"encoding_format": "float", "input_type": "passage", "truncate": "END",
|
|
|
|
|
}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "nvidia embeds a search query as a query", provider: "nvidia",
|
|
|
|
|
model: "nvidia/nemotron-3-embed-1b", base: "/v1", query: true, texts: []string{"q"},
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("nvidia/nemotron-3-embed-1b", []string{"q"}, map[string]any{
|
|
|
|
|
"encoding_format": "float", "input_type": "query", "truncate": "END",
|
|
|
|
|
}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "hunyuan takes model and input only", provider: "hunyuan",
|
|
|
|
|
model: "hunyuan-embedding", base: "/v1", override: true, truncate: 300,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("hunyuan-embedding", three, nil),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "modelscope documents nothing beyond the baseline", provider: "modelscope",
|
|
|
|
|
model: "Qwen/Qwen3-Embedding-8B", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("Qwen/Qwen3-Embedding-8B", three, nil),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "novita documents encoding_format only", provider: "novita",
|
|
|
|
|
model: "baai/bge-m3", base: "/openai/v1", override: true,
|
|
|
|
|
wantPath: "/openai/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("baai/bge-m3", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "siliconflow narrows only the Qwen3 series", provider: "siliconflow",
|
|
|
|
|
model: "Qwen/Qwen3-Embedding-8B", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("Qwen/Qwen3-Embedding-8B", three,
|
|
|
|
|
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "siliconflow bge-m3 has a fixed width", provider: "siliconflow",
|
|
|
|
|
model: "BAAI/bge-m3", base: "/v1", override: true,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("BAAI/bge-m3", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "siliconflow takes up to thirty-two texts", provider: "siliconflow",
|
|
|
|
|
model: "BAAI/bge-m3", base: "/v1", texts: texts(33), wantRequests: 2,
|
|
|
|
|
wantPath: "/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("BAAI/bge-m3", texts(32), map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "aliyun text-embedding-v2 has a fixed width and takes 25", provider: "aliyun",
|
|
|
|
|
model: "text-embedding-v2", base: "/compatible-mode/v1", override: true,
|
|
|
|
|
texts: texts(26), wantRequests: 2,
|
|
|
|
|
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("text-embedding-v2", texts(25), map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "openrouter", provider: "openrouter",
|
|
|
|
|
model: "openai/text-embedding-3-small", base: "/api/v1", override: true,
|
|
|
|
|
wantPath: "/api/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("openai/text-embedding-3-small", three,
|
|
|
|
|
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "qianfan takes up to sixteen texts", provider: "qianfan",
|
|
|
|
|
model: "embedding-v1", base: "/v2", texts: texts(17), wantRequests: 2,
|
|
|
|
|
wantPath: "/v2/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("embedding-v1", texts(16), map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "qianfan tao-8k takes one text", provider: "qianfan",
|
|
|
|
|
model: "tao-8k", base: "/v2", wantRequests: 3,
|
|
|
|
|
wantPath: "/v2/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("tao-8k", []string{"a"}, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "aliyun text models use the compatible endpoint", provider: "aliyun",
|
|
|
|
|
model: "text-embedding-v4", base: "/compatible-mode/v1", override: true,
|
|
|
|
|
texts: texts(12), wantRequests: 2,
|
|
|
|
|
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("text-embedding-v4", texts(10),
|
|
|
|
|
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "aliyun text models from a bare host", provider: "aliyun",
|
|
|
|
|
model: "text-embedding-v4",
|
|
|
|
|
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("text-embedding-v4", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "aliyun text model not yet in the catalog", provider: "aliyun",
|
|
|
|
|
model: "qwen3.8-text-embedding", base: "/compatible-mode/v1",
|
|
|
|
|
wantPath: "/compatible-mode/v1/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: openAIBody("qwen3.8-text-embedding", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "aliyun vision plus uses the native API at a fixed width", provider: "aliyun",
|
|
|
|
|
model: "tongyi-embedding-vision-plus", base: "/compatible-mode/v1", override: true,
|
|
|
|
|
wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: dashBody("tongyi-embedding-vision-plus", three, nil),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "aliyun qwen3-vl-embedding narrows under parameters", provider: "aliyun",
|
|
|
|
|
model: "qwen3-vl-embedding", base: "/compatible-mode/v1", override: true,
|
|
|
|
|
wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: dashBody("qwen3-vl-embedding", three,
|
|
|
|
|
map[string]any{"parameters": map[string]any{"dimension": float64(256)}}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "aliyun qwen2.5-vl-embedding fuses, so one text per request", provider: "aliyun",
|
|
|
|
|
model: "qwen2.5-vl-embedding", base: "/compatible-mode/v1", wantRequests: 3,
|
|
|
|
|
wantPath: dashPath, wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: dashBody("qwen2.5-vl-embedding", []string{"a"}, nil),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "volcengine fuses, so one text per request", provider: "volcengine",
|
|
|
|
|
model: "doubao-embedding-vision-251215", base: "/api/v3/embeddings/multimodal",
|
|
|
|
|
override: true, wantRequests: 3,
|
|
|
|
|
wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: arkBody("doubao-embedding-vision-251215", "a",
|
|
|
|
|
map[string]any{"encoding_format": "float", "dimensions": float64(256)}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "volcengine from the chat base URL", provider: "volcengine",
|
|
|
|
|
model: "doubao-embedding-vision-251215", base: "/api/v3", wantRequests: 3,
|
|
|
|
|
wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: arkBody("doubao-embedding-vision-251215", "a", map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "volcengine from a bare host", provider: "volcengine",
|
|
|
|
|
model: "doubao-embedding-vision-251215", wantRequests: 3,
|
|
|
|
|
wantPath: "/api/v3/embeddings/multimodal", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
wantBody: arkBody("doubao-embedding-vision-251215", "a", map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "volcengine retired text models keep their own endpoint", provider: "volcengine",
|
|
|
|
|
model: "doubao-embedding-text-240715", base: "/api/v3/embeddings/multimodal", override: true,
|
|
|
|
|
wantPath: "/api/v3/embeddings", wantAuth: [2]string{"Authorization", "Bearer k"},
|
|
|
|
|
// The archived reference lists encoding_format too, and no dimensions.
|
|
|
|
|
wantBody: openAIBody("doubao-embedding-text-240715", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "gemini posts to the native method", provider: "gemini",
|
|
|
|
|
model: "gemini-embedding-001", base: "/v1beta", override: true, texts: []string{"a"},
|
|
|
|
|
wantPath: "/v1beta/models/gemini-embedding-001:batchEmbedContents",
|
|
|
|
|
wantAuth: [2]string{"X-Goog-Api-Key", "k"},
|
|
|
|
|
wantBody: map[string]any{"requests": []any{map[string]any{
|
|
|
|
|
"model": "models/gemini-embedding-001",
|
|
|
|
|
"content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},
|
|
|
|
|
"embedContentConfig": map[string]any{"outputDimensionality": float64(256)},
|
|
|
|
|
}}},
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "gemini rows on the OpenAI facade still embed natively", provider: "gemini",
|
|
|
|
|
model: "gemini-embedding-2", base: "/v1beta/openai", texts: []string{"a"},
|
|
|
|
|
wantPath: "/v1beta/models/gemini-embedding-2:batchEmbedContents",
|
|
|
|
|
wantAuth: [2]string{"X-Goog-Api-Key", "k"},
|
|
|
|
|
wantBody: map[string]any{"requests": []any{map[string]any{
|
|
|
|
|
"model": "models/gemini-embedding-2",
|
|
|
|
|
"content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},
|
|
|
|
|
}}},
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "azure without api_version uses the v1 data plane", provider: "azure_openai",
|
|
|
|
|
model: "my-deployment",
|
|
|
|
|
wantPath: "/openai/v1/embeddings", wantAuth: [2]string{"Api-Key", "k"},
|
|
|
|
|
wantBody: openAIBody("my-deployment", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "azure with api_version uses the deployments path", provider: "azure_openai",
|
|
|
|
|
model: "my-deployment", extra: map[string]string{"api_version": "2024-10-21"},
|
|
|
|
|
wantPath: "/openai/deployments/my-deployment/embeddings", wantQuery: "api-version=2024-10-21",
|
|
|
|
|
wantAuth: [2]string{"Api-Key", "k"},
|
|
|
|
|
wantBody: openAIBody("my-deployment", three, map[string]any{"encoding_format": "float"}),
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: "weknoracloud signs its own path", provider: "weknoracloud",
|
|
|
|
|
model: "cloud-embedding", appID: "app",
|
|
|
|
|
wantPath: "/api/v1/embeddings", wantAuth: [2]string{"X-Appid", "app"},
|
|
|
|
|
wantBody: openAIBody("cloud-embedding", three, nil),
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for _, tc := range cases {
|
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
|
up := newUpstream(t)
|
|
|
|
|
input := tc.texts
|
|
|
|
|
if input == nil {
|
|
|
|
|
input = three
|
|
|
|
|
}
|
|
|
|
|
config := Config{
|
|
|
|
|
Source: types.ModelSourceRemote,
|
|
|
|
|
Provider: tc.provider,
|
|
|
|
|
BaseURL: up.url + tc.base,
|
|
|
|
|
ModelName: tc.model,
|
|
|
|
|
APIKey: "k",
|
|
|
|
|
Dimensions: 256,
|
|
|
|
|
SupportsDimensionOverride: tc.override,
|
|
|
|
|
TruncatePromptTokens: tc.truncate,
|
|
|
|
|
ExtraConfig: tc.extra,
|
|
|
|
|
AppID: tc.appID,
|
|
|
|
|
AppSecret: "secret",
|
|
|
|
|
}
|
|
|
|
|
embedder, err := newEmbedder(config, nil, nil)
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
if tc.query {
|
|
|
|
|
ctx = types.WithEmbedQuery(ctx)
|
|
|
|
|
}
|
|
|
|
|
got, err := embedder.BatchEmbed(ctx, input)
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
|
|
want := make([][]float32, len(input))
|
|
|
|
|
for i, s := range input {
|
|
|
|
|
want[i] = []float32{float32(utf8.RuneCountInString(s))}
|
|
|
|
|
}
|
|
|
|
|
assert.Equal(t, want, got, "every vector must come back in its own slot")
|
|
|
|
|
|
|
|
|
|
wantRequests := tc.wantRequests
|
|
|
|
|
if wantRequests == 0 {
|
|
|
|
|
wantRequests = 1
|
|
|
|
|
}
|
|
|
|
|
require.Len(t, up.requests, wantRequests)
|
|
|
|
|
first := up.requests[0]
|
|
|
|
|
assert.Equal(t, tc.wantPath, first.path)
|
|
|
|
|
assert.Equal(t, tc.wantQuery, first.query)
|
|
|
|
|
assert.Equal(t, tc.wantAuth[1], first.header.Get(tc.wantAuth[0]))
|
|
|
|
|
assert.Equal(t, tc.wantBody, first.body)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|