WeKnora/internal/models/api/embeddings_settings.go

159 lines
7.7 KiB
Go
Raw Normal View History

package api
// EmbeddingsCompat is the overlay form (every field optional) of the
// embedding settings. JSON keys are the documented names used in models.json
// and config/models.json.
type EmbeddingsCompat struct {
// API overrides the vendor's embedding protocol for one model. Aliyun and
// Volcengine each serve two: a text endpoint in the OpenAI shape and a
// multimodal one of their own, chosen by which model the row names.
API *EmbeddingAPI `json:"api,omitempty"`
Path *string `json:"path,omitempty"`
SendEncodingFormat *bool `json:"send_encoding_format,omitempty"`
DimensionsField *string `json:"dimensions_field,omitempty"`
TruncateField *string `json:"truncate_field,omitempty"`
TruncateValue *string `json:"truncate_value,omitempty"`
InputTypeField *string `json:"input_type_field,omitempty"`
InputTypeValues map[string]string `json:"input_type_values,omitempty"`
MaxBatchSize *int `json:"max_batch_size,omitempty"`
MaxInputChars *int `json:"max_input_chars,omitempty"`
// AcceptsTruncatePromptTokens marks a vLLM-class runtime, the only kind
// that implements the `truncate_prompt_tokens` extension.
fix(models): align configuration and multimodal embedding workflows (#4080) * fix(models): align configuration defaults and multimodal workflows * feat(image): enhance image retrieval diagnostics and filtering - Implemented `retrieveObservedImagePool` to observe engine calls and record image recall decisions without altering results. - Added detailed diagnostics in `summarizeImagePool` and `summarizeImageCandidateCut` to track image filtering decisions and scores. - Introduced tests for image pool diagnostics to ensure accurate filtering and decision recording. - Updated existing functions to utilize new retrieval and summarization methods for improved observability and accuracy in image handling. * feat(embeddings): enhance image handling with new formats and message support - Introduced `EmbeddingImageFormat` to manage image input formats, allowing for both object and messages formats. - Updated `EmbeddingsSettings` to include new fields for `ImageFormat`, `ImagePrompt`, and `TextAsMessages` to support multimodal embedding workflows. - Enhanced `Client` methods to build request bodies for images in both formats, ensuring compatibility with vLLM's requirements. - Added tests to validate the new image message handling and ensure correct request formatting for different scenarios. - Updated documentation to reflect changes in image input handling and configuration options. * feat(similarity): add embedding similarity mode for enhanced document scoring - Introduced a new `similarity` option in `ModelDebugOptions` to score documents and an optional image against a query. - Updated `ModelDebugDrawer.vue` to support a new input mode for similarity, allowing users to select similarity as an input type. - Enhanced the UI to display similarity results, including ranked candidates based on cosine similarity. - Added tests to validate the functionality of the new similarity mode in embedding models. - Updated localization files to include new strings related to similarity mode in multiple languages. * feat(embeddings): add Qwen3-VL-Embedding support for multimodal input - Introduced Qwen3-VL-Embedding model with support for both text and image inputs. - Updated model configuration files to include compatibility settings for the new embedding type. - Enhanced tests to validate the functionality of Qwen3-VL-Embedding, ensuring correct handling of inputs and outputs. - Updated documentation to reflect the new model's capabilities and usage instructions. * test(models): wrap embedding assertions to satisfy lint * test(opensearch): isolate HTTP transports between parallel tests
2026-10-10 03:06:00 +00:00
AcceptsTruncatePromptTokens *bool `json:"accepts_truncate_prompt_tokens,omitempty"`
RequestTimeout *int `json:"request_timeout_seconds,omitempty"`
ExtraBody map[string]any `json:"extra_body,omitempty"`
ImageField *string `json:"image_field,omitempty"`
MaxImageBatchSize *int `json:"max_image_batch_size,omitempty"`
MaxImageBytes *int `json:"max_image_bytes,omitempty"`
ImageMIMETypes []string `json:"image_mime_types,omitempty"`
ImageFormat *EmbeddingImageFormat `json:"image_format,omitempty"`
ImagePrompt *string `json:"image_prompt,omitempty"`
TextAsMessages *bool `json:"text_as_messages,omitempty"`
}
// EmbeddingImageFormat is how an image travels on the OpenAI embedding
// shape, which has no standard image input of its own.
type EmbeddingImageFormat string
const (
// EmbeddingImageObject puts {ImageField: data URI} in `input`, as Jina
// and SGLang document.
EmbeddingImageObject EmbeddingImageFormat = "object"
// EmbeddingImageMessages sends a chat conversation in `messages` instead
// of `input`, which is how vLLM serves multimodal embedding models
// (https://docs.vllm.ai/en/latest/models/pooling_models.html). One
// conversation yields one vector, so every image is its own request.
EmbeddingImageMessages EmbeddingImageFormat = "messages"
)
// Known reports whether f is a format this build can send; empty is known.
func (f EmbeddingImageFormat) Known() bool {
return f == "" || f == EmbeddingImageObject || f == EmbeddingImageMessages
}
// EmbeddingsSettings is the resolved (fully defaulted) form.
type EmbeddingsSettings struct {
// API is the protocol this model speaks, which may differ from the
// vendor's default.
API EmbeddingAPI
// Path is appended to the base URL; vendors whose default base URL names
// the full endpoint leave it empty.
Path string
// SendEncodingFormat sends encoding_format: "float". OpenAI documents it;
// several compatible gateways do not list it at all.
SendEncodingFormat bool
// DimensionsField carries the requested vector width: "dimensions" on the
// OpenAI shape, "dimension" on DashScope (nested under parameters),
// "outputDimensionality" on Gemini, and empty where the vendor does not
// let a request choose. It is sent only when the row opted in with
// supports_dimension_override; the field name is the vendor's fact, the
// decision to narrow the vector is the operator's.
DimensionsField string
// TruncateField and TruncateValue are the vendor's server-side truncation
// switch for over-long input: a boolean on Jina, an enum on NIM. Empty
// sends nothing.
TruncateField string
TruncateValue string
// InputTypeField names the parameter that distinguishes an indexed
// document from a search query, and InputTypeValues maps the neutral
// EmbedInputType values onto the vendor's vocabulary. Asymmetric
// models score the two sides differently and are measurably worse when
// both are embedded the same way.
InputTypeField string
InputTypeValues map[string]string
// MaxBatchSize and MaxInputChars are the documented per-request ceilings.
MaxBatchSize int
MaxInputChars int
// AcceptsTruncatePromptTokens reports a vLLM-class runtime. The extension
// appears in no managed vendor's schema, so it must never be sent to one.
AcceptsTruncatePromptTokens bool
// TruncatePromptTokens is the budget the operator opted into on this row,
// honoured only where the vendor accepts the extension.
TruncatePromptTokens int
// RequestTimeout caps one request, in seconds. 0 leaves the client
// without its own deadline and lets the caller's context govern.
RequestTimeout int
ExtraBody map[string]any
feat: judge image hits by their image in rerank and show them to vision models (#4013) * 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(rerank): score images with multimodal rerank models Rerank models that read images can now be sent an image document and score it against a text query on the same scale as text, which is what a recall made by an image's own vector needs: a text reranker only sees the caption, and rejects an image for what the caption left out. - api: ImageReranker, implemented by the Cohere and NIM shapes. Image documents go in requests of their own, so text requests keep their exact shape. NIM sends image-only passages without text, as base64 data URLs (its VLM reranking reference requires both). The Cohere shape sends {"<image_field>": data URI} documents and asks for no echo of them. - The image settings embeddings already had (image_field, max_image_batch_size, max_image_bytes, image_mime_types) move into a shared ImageInput embedded in both settings; resolved embedding settings serialize exactly as before. - Catalog: jina-reranker-m0 and nvidia/llama-nemotron-rerank-vl-1b-v2 take text and image. Jina names "image" documents; its base64 form is not shown in any reranker example, so the data URI its embeddings reference documents is used and marked unverified. NVIDIA lists its six formats and 512 passages per request. - rerank: an optional ImageReranker reached through AsImageReranker, gated on the model's catalog input and the endpoint; images are checked against the documented limits before any request, scores are normalized like text, and the debug and Langfuse decorators forward it without logging image bytes. - Image preparation (format conversion, shrink to fit) moves from the embedding package to internal/models/imageprep, since rerank needs it too. * feat(retrieval): keep a vector hit's own similarity through fusion Hybrid fusion replaces a hit's Score with a rank-based RRF score. That is right for ordering, but it erases the evidence reranking needs to judge an image found by its own vector: how close the vector actually was. Record the engine's similarity on each vector hit (IndexWithScore.VectorScore) before normalization and fusion rewrite Score, and carry it onto the search result (SearchResult.VectorScore, not serialized). * feat(reranking): judge image hits by their image, not only their caption An image found by its own vector was reranked on its caption and OCR text, so a text reranker rejected it for exactly what the caption left out. - With a reranker that reads images and a LoadImage callback, image_vector hits are scored by their image (prepared to the model's limits) on the same scale as text, and pass or fail the same threshold. A hit whose image cannot be read, prepared or scored falls back to its text. - With a text reranker, its verdict stands for images that are mostly text (OCR of 200 characters or more). A pictorial hit it rejects is kept when its vector similarity (VectorScore) reaches Options.ImageKeepScore: at most two, strongest vector first, appended after the ranked results and marked kept_by=image_vector. This also returns an image when no text passes at all. - Diagnostics report images_scored and images_kept. * feat(rerank): read image hits' images in every rerank path The chat pipeline, the agent search_knowledge tool and the hybrid-search API now pass the rerank stage a way to read an image hit's image and an image keep score, so a multimodal reranker scores images by what they show and a text reranker can no longer drop a pictorial image its caption undersells. - KnowledgeBaseService.ReadChunkImage reads the first image of a result's image_info from the storage of its knowledge base (the knowledge base's tenant, so shared knowledge bases read from their owner's storage), capped at 32 MB. Plain http(s) images go through the SSRF-safe downloader. - The backend resolution the image multimodal task used moves into a shared knowledgeImageReader, so ingestion and reranking find an image in the same place. - reranking.ImageKeepScoreFor: an image is kept over a text reranker only when its vector was at least as close as a text hit had to be, and never below 0.25 (empirical). * feat(chat): show a vision model the images its answer rests on An image recalled by its own vector reached the answer as its caption only, so a vision model could not answer from what the caption left out. - Knowledge QA: INTO_CHAT_MESSAGE reads, for a model that supports vision, the images of the contexts that rest on an image vector match (at most three distinct ones, prepared to what every vision API takes: PNG, JPEG, WebP or GIF within 5 MB), attaches them after the user's own images, and names the contexts they belong to. - Agent: search_knowledge attaches the same images when the agent's model supports vision (the agent describes tool images to models that cannot see them, and these already carry captions). Stored history drops them; they are read again from storage. - An image hit and its caption hit read the same once merged, and de-duplication keeps either. The kept copy now inherits the image (image_vector_match), in the pipeline's exact and partial-overlap de-duplication and in the agent tool's. - Results the rerank stage kept outside its top-k (kept_by) no longer fall to the later top-k cuts: the pipeline's FilterTopK and the agent tool's MMR and limit let them ride along after the ranked results. * docs(website): describe how image hits are reranked and shown to vision models * Fix image evidence preservation and model source mapping
2026-10-09 05:01:48 +00:00
// ImageInput is how this endpoint takes images: on the OpenAI shape, the
// key of the input object that carries one ("image" on Jina; that shape
// has no standard image input, so an endpoint that names none takes no
// images), plus the documented per-request and per-image limits.
ImageInput
fix(models): align configuration and multimodal embedding workflows (#4080) * fix(models): align configuration defaults and multimodal workflows * feat(image): enhance image retrieval diagnostics and filtering - Implemented `retrieveObservedImagePool` to observe engine calls and record image recall decisions without altering results. - Added detailed diagnostics in `summarizeImagePool` and `summarizeImageCandidateCut` to track image filtering decisions and scores. - Introduced tests for image pool diagnostics to ensure accurate filtering and decision recording. - Updated existing functions to utilize new retrieval and summarization methods for improved observability and accuracy in image handling. * feat(embeddings): enhance image handling with new formats and message support - Introduced `EmbeddingImageFormat` to manage image input formats, allowing for both object and messages formats. - Updated `EmbeddingsSettings` to include new fields for `ImageFormat`, `ImagePrompt`, and `TextAsMessages` to support multimodal embedding workflows. - Enhanced `Client` methods to build request bodies for images in both formats, ensuring compatibility with vLLM's requirements. - Added tests to validate the new image message handling and ensure correct request formatting for different scenarios. - Updated documentation to reflect changes in image input handling and configuration options. * feat(similarity): add embedding similarity mode for enhanced document scoring - Introduced a new `similarity` option in `ModelDebugOptions` to score documents and an optional image against a query. - Updated `ModelDebugDrawer.vue` to support a new input mode for similarity, allowing users to select similarity as an input type. - Enhanced the UI to display similarity results, including ranked candidates based on cosine similarity. - Added tests to validate the functionality of the new similarity mode in embedding models. - Updated localization files to include new strings related to similarity mode in multiple languages. * feat(embeddings): add Qwen3-VL-Embedding support for multimodal input - Introduced Qwen3-VL-Embedding model with support for both text and image inputs. - Updated model configuration files to include compatibility settings for the new embedding type. - Enhanced tests to validate the functionality of Qwen3-VL-Embedding, ensuring correct handling of inputs and outputs. - Updated documentation to reflect the new model's capabilities and usage instructions. * test(models): wrap embedding assertions to satisfy lint * test(opensearch): isolate HTTP transports between parallel tests
2026-10-10 03:06:00 +00:00
// ImageFormat chooses between ImageField's object in `input` and a chat
// conversation in `messages`. Empty means object when ImageField is set.
ImageFormat EmbeddingImageFormat `json:",omitempty"`
// ImagePrompt is the text sent beside each image in the messages format;
// some chat templates (VLM2Vec's) expect an instruction there. Empty
// sends the image alone.
ImagePrompt string `json:",omitempty"`
// TextAsMessages sends texts in the messages format too, one per
// request. A model whose chat template frames its inputs only places a
// text and an image in the same space when both pass through it; a
// plain `input` string skips the template.
TextAsMessages bool `json:",omitempty"`
}
// OpenAIImageFormat is the effective image format on the OpenAI shape, empty
// when the endpoint takes no images there.
func (s EmbeddingsSettings) OpenAIImageFormat() EmbeddingImageFormat {
switch {
case s.ImageFormat == EmbeddingImageMessages:
return EmbeddingImageMessages
case s.ImageField != "":
return EmbeddingImageObject
}
return ""
}
// BatchLimits renders the documented ceilings for SplitBatches.
func (s EmbeddingsSettings) BatchLimits() BatchLimits {
return BatchLimits{MaxItems: s.MaxBatchSize, MaxItemRunes: s.MaxInputChars}
}
// InputTypeValue maps a neutral input kind onto the vendor's vocabulary,
// returning "" when this vendor does not distinguish the two sides.
func (s EmbeddingsSettings) InputTypeValue(kind EmbedInputType) string {
if s.InputTypeField == "" {
return ""
}
if v, ok := s.InputTypeValues[string(kind)]; ok {
return v
}
return string(kind)
}
// DefaultEmbeddings is the protocol baseline, and it is deliberately bare:
// `model` and `input` are the only two fields every vendor in this catalog
// documents. The rest disagree — NVIDIA NIM and Volcengine's text endpoint
// have no `dimensions` at all, Zhipu has no `encoding_format`, and the
// parameter that separates a query from a document is spelled three
// different ways. A vendor that documents one declares it; nothing is sent
// on the assumption that an OpenAI-shaped endpoint accepts every OpenAI
// field.
//
// The one non-wire default is the request deadline: every pre-catalog
// embedding client carried 60 seconds.
func DefaultEmbeddings() EmbeddingsSettings {
return EmbeddingsSettings{RequestTimeout: 60}
}