WeKnora/internal/models/runtime/resolve.go

566 lines
19 KiB
Go
Raw Normal View History

package runtime
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/models"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/models/catalog"
"github.com/Tencent/WeKnora/internal/models/internal/configcopy"
"github.com/Tencent/WeKnora/internal/models/providers"
"github.com/Tencent/WeKnora/internal/types"
)
// Ref identifies one configured model.
type Ref struct {
Provider string
Model string
BaseURL string
ModelType types.ModelType
Extra map[string]string
Override *types.ModelSpecOverride
// TruncatePromptTokens is an embedding row's
// embedding_parameters.truncate_prompt_tokens. It is a first-class column
// rather than an extra_config key, which is why it arrives here instead
// of in Extra.
TruncatePromptTokens int
}
// Resolved is the fully merged view of one model: which vendor, which
// protocol, which settings.
type Resolved struct {
Vendor *providers.Definition
// Spec is the effective catalog entry (synthesized when unknown).
Spec models.ModelSpec
// Cataloged reports whether the model name matched a catalog entry.
Cataloged bool
API api.API
BaseURL string
// RemoteModel is the id sent on the wire.
RemoteModel string
ThinkingLevels api.ThinkingLevelMap
OpenAICompletions api.OpenAICompletionsSettings
OpenAIResponses api.OpenAIResponsesSettings
AnthropicMessages api.AnthropicMessagesSettings
GoogleGenerativeAI api.GoogleGenerativeAISettings
// RerankAPI and Rerank are filled only when the reference asked for a
// rerank model. Chat resolution is on every request's hot path, so the
// rerank overlay is not merged for it.
RerankAPI api.RerankAPI
Rerank api.RerankSettings
// EmbeddingAPI and Embeddings are filled only for an embedding reference,
// for the same reason.
EmbeddingAPI api.EmbeddingAPI
Embeddings api.EmbeddingsSettings
// TranscriptionAPI and Transcriptions are filled only for an ASR
// reference.
TranscriptionAPI api.TranscriptionAPI
Transcriptions api.TranscriptionsSettings
}
// Resolve merges the vendor, catalog entry, extra-config and per-row
// overrides for a model reference. It never fails for unknown vendors or
// models: they degrade to the generic OpenAI-compatible baseline.
func Resolve(ref Ref) (*Resolved, error) { return Default().Resolve(ref) }
// Resolve merges one model against a single generation of this runtime.
func (rt *Runtime) Resolve(ref Ref) (*Resolved, error) {
return resolveWithVendor(ref, rt.selectProvider(ref.Provider, ref.BaseURL))
}
func resolveWithVendor(ref Ref, vendor *Provider) (*Resolved, error) {
if vendor == nil {
return nil, fmt.Errorf("catalog: no vendors registered")
}
modelType := ref.ModelType
if modelType == "" {
modelType = types.ModelTypeKnowledgeQA
}
baseURL := strings.TrimRight(strings.TrimSpace(ref.BaseURL), "/")
if baseURL == "" {
baseURL = strings.TrimRight(vendor.GetDefaultURL(modelType), "/")
}
spec, cataloged := vendor.FindModel(ref.Model, modelType)
if !cataloged {
spec = models.ModelSpec{ID: ref.Model, Type: catalog.EntryType(modelType)}
}
if spec.API == "" {
spec.API = vendor.API
}
catalogAPI := spec.API
if ref.Override != nil {
applySpecOverride(&spec, ref.Override)
}
if modelType == types.ModelTypeRerank {
return resolveRerank(ref, vendor, spec, cataloged, baseURL)
}
if modelType == types.ModelTypeEmbedding {
return resolveEmbeddings(ref, vendor, spec, cataloged, baseURL)
}
if modelType == types.ModelTypeASR {
return resolveTranscriptions(ref, vendor, spec, cataloged, baseURL)
}
resolvedAPI := spec.API
if forced := strings.TrimSpace(ref.Extra[models.ExtraAPI]); forced != "" {
resolvedAPI = api.API(forced)
} else if ref.Override == nil || ref.Override.API == "" {
resolvedAPI = inferAPIFromURL(baseURL, resolvedAPI)
if vendor.PreferAPI != nil {
if preferred := vendor.PreferAPI(baseURL, spec); preferred != "" {
resolvedAPI = preferred
}
}
}
if !resolvedAPI.Known() {
return nil, fmt.Errorf("catalog: unknown api %q for provider %s", resolvedAPI, vendor.ID)
}
levels := api.ThinkingLevelMap{}
for k, v := range vendor.ThinkingLevels {
levels[k] = v
}
for k, v := range spec.ThinkingLevels {
levels[k] = v
}
if ref.Override != nil {
for k, v := range ref.Override.ThinkingLevels {
levels[api.ReasoningEffort(k)] = v
}
}
out := &Resolved{
Vendor: configcopy.Clone(vendor.Definition),
Spec: spec,
Cataloged: cataloged,
API: resolvedAPI,
BaseURL: baseURL,
RemoteModel: ref.Model,
ThinkingLevels: levels,
}
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
out.RemoteModel = override
}
overrideCompat := ref.Override.CompatJSON()
// Every protocol's settings are resolved so callers can inspect any of
// them, but only the layers whose API matches contribute model/override
// compat (a flat compat object is meaningless for another protocol).
completions := api.DefaultOpenAICompletions()
ApplyCompat(&completions, &vendor.Compat.OpenAICompletions)
if err := applyRawCompat(
&completions, &api.OpenAICompletionsCompat{}, spec.Compat, catalogAPI, api.APIOpenAICompletions,
); err != nil {
return nil, err
}
if err := applyRawCompat(
&completions, &api.OpenAICompletionsCompat{}, overrideCompat, resolvedAPI, api.APIOpenAICompletions,
); err != nil {
return nil, err
}
legacyThinkingControlApplied := applyLegacyThinkingControl(
&completions, ref.Extra[models.ExtraThinkingControl],
)
out.OpenAICompletions = completions
responses := api.DefaultOpenAIResponses()
ApplyCompat(&responses, &vendor.Compat.OpenAIResponses)
if err := applyRawCompat(
&responses, &api.OpenAIResponsesCompat{}, spec.Compat, catalogAPI, api.APIOpenAIResponses,
); err != nil {
return nil, err
}
if err := applyRawCompat(
&responses, &api.OpenAIResponsesCompat{}, overrideCompat, resolvedAPI, api.APIOpenAIResponses,
); err != nil {
return nil, err
}
out.OpenAIResponses = responses
anthropic := api.DefaultAnthropicMessages()
ApplyCompat(&anthropic, &vendor.Compat.AnthropicMessages)
if err := applyRawCompat(
&anthropic, &api.AnthropicMessagesCompat{}, spec.Compat, catalogAPI, api.APIAnthropicMessages,
); err != nil {
return nil, err
}
if err := applyRawCompat(
&anthropic, &api.AnthropicMessagesCompat{}, overrideCompat, resolvedAPI, api.APIAnthropicMessages,
); err != nil {
return nil, err
}
out.AnthropicMessages = anthropic
google := api.DefaultGoogleGenerativeAI()
ApplyCompat(&google, &vendor.Compat.GoogleGenerativeAI)
if err := applyRawCompat(
&google, &api.GoogleGenerativeAICompat{}, spec.Compat, catalogAPI, api.APIGoogleGenerativeAI,
); err != nil {
return nil, err
}
if err := applyRawCompat(
&google, &api.GoogleGenerativeAICompat{}, overrideCompat, resolvedAPI, api.APIGoogleGenerativeAI,
); err != nil {
return nil, err
}
out.GoogleGenerativeAI = google
// A non-default legacy thinking_control is an explicit per-row override.
// An ignored provider default lets the catalog's reasoning metadata apply.
if !legacyThinkingControlApplied {
out.silenceThinkingForNonReasoningModel()
}
return out, nil
}
// silenceThinkingForNonReasoningModel drops every thinking field for a
// catalogued model the vendor documents as non-reasoning (DeepSeek's
// non-thinking alias, LKEAP's V3-0324 generation, plain instruct models).
// Without this, a caller that asks for thinking — an agent whose config says
// so, or the model debug drawer — would send a switch the model does not
// understand, and some vendors answer 400.
//
// The gate deliberately applies only to catalogued entries: an unknown model
// on a self-hosted runtime carries Reasoning=false simply because nobody
// described it, and those deployments do rely on the thinking switch.
func (r *Resolved) silenceThinkingForNonReasoningModel() {
if !r.Cataloged || r.Spec.Reasoning {
return
}
r.OpenAICompletions.ThinkingFormat = api.ThinkingFormatNone
r.OpenAICompletions.ThinkingBudgetField = ""
r.OpenAICompletions.SupportsReasoningEffort = false
r.GoogleGenerativeAI.ThinkingMode = api.GoogleThinkingNone
r.ThinkingLevels = api.ThinkingLevelMap{}
for _, level := range api.ReasoningLadder {
r.ThinkingLevels[level] = nil
}
r.ThinkingLevels[api.ReasoningAuto] = nil
}
// applyRawCompat decodes raw into the overlay type and applies it when the
// layer's API matches the target protocol.
func applyRawCompat(settings any, overlayPtr any, raw json.RawMessage, layerAPI, target api.API) error {
if len(raw) == 0 || layerAPI != target {
return nil
}
if err := DecodeCompat(raw, overlayPtr); err != nil {
return fmt.Errorf("%s compat: %w", target, err)
}
ApplyCompat(settings, overlayPtr)
return nil
}
func applySpecOverride(spec *models.ModelSpec, o *types.ModelSpecOverride) {
if o == nil {
return
}
if o.API != "" {
spec.API = api.API(o.API)
}
if o.Reasoning != nil {
spec.Reasoning = *o.Reasoning
}
if len(o.Input) > 0 {
spec.Input = o.Input
}
if o.ContextWindow > 0 {
spec.ContextWindow = o.ContextWindow
}
if o.MaxOutputTokens > 0 {
spec.MaxOutputTokens = o.MaxOutputTokens
}
}
// Capabilities is the frontend contract, independent of runtime assembly.
type Capabilities = models.Capabilities
// Capabilities summarizes the resolved model for API responses.
func (r *Resolved) Capabilities() Capabilities {
if r == nil {
return Capabilities{}
}
caps := Capabilities{
Provider: r.Vendor.ID,
API: r.API,
Cataloged: r.Cataloged,
Reasoning: r.Spec.Reasoning,
Input: r.Spec.Input,
ContextWindow: r.Spec.ContextWindow,
MaxOutputTokens: r.Spec.MaxOutputTokens,
}
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
// Embedding, rerank and ASR references resolve no chat protocol, and an
// empty level map reads as "every level supported"; they do not think.
if r.API == "" {
caps.ThinkingLevels = []api.ReasoningEffort{}
return caps
}
switch r.API {
case api.APIOpenAICompletions:
caps.ThinkingFormat = string(r.OpenAICompletions.ThinkingFormat)
caps.MaxTokensField = r.OpenAICompletions.MaxTokensField
if caps.ThinkingFormat == string(api.ThinkingFormatNone) {
caps.ThinkingLevels = []api.ReasoningEffort{}
return caps
}
case api.APIOpenAIResponses:
caps.ThinkingFormat = "reasoning.effort"
caps.MaxTokensField = "max_output_tokens"
case api.APIAnthropicMessages:
caps.ThinkingFormat = "thinking." + string(r.AnthropicMessages.ThinkingMode)
caps.MaxTokensField = "max_tokens"
case api.APIGoogleGenerativeAI:
caps.ThinkingFormat = "thinkingConfig." + string(r.GoogleGenerativeAI.ThinkingMode)
caps.MaxTokensField = "maxOutputTokens"
if r.GoogleGenerativeAI.ThinkingMode == api.GoogleThinkingNone {
caps.ThinkingLevels = []api.ReasoningEffort{}
return caps
}
case api.APIOllama:
caps.ThinkingFormat = "think"
caps.MaxTokensField = "num_predict"
}
caps.ThinkingLevels = r.ThinkingLevels.SupportedLevels()
fix(models): stop advertising graded thinking levels the wire format drops (#3552) * fix(models): stop advertising graded thinking levels the wire format drops A generic-provider row (relays, self-hosted runtimes — the default for uncatalogued models) resolves an empty ThinkingLevelMap, whose missing-key semantics report every graded rung as supported. Capabilities() then hands minimal/low/medium/high to the frontend, which renders a selector whose choice applyThinking silently discards: the chat-template-kwargs branch sends only the enable_thinking boolean and no reasoning_effort is computed. Same defect class as the two NVIDIA NIM entries fixed in #3489, but there is no catalog entry to repair here. Collapse Capabilities() to the levels the wire can actually express for a boolean-only switch (off/auto) unless the settings opt into supports_reasoning_effort. The vendor map itself is untouched, so vendors that do carry effort keep their ladders. * fix(models): carry reasoning_effort through the chat-template switch when opted in The Capabilities() guard kept a vendor's ladder when it opts into supports_reasoning_effort, but applyThinking's chat-template-kwargs branch wrote only the enable_thinking boolean and dropped the already-computed effort — so the opt-in combination still sent byte-identical bodies for every graded rung (#3551's defect, alive in exactly the shape the review flagged). Mirror the enable_thinking dialect: write reasoning_effort on top of the switch when one was computed. A golden case pins the opt-in combination; the no-opt-in guard case keeps asserting the level is dropped. * style(models): wrap long Resolve call in thinking-levels test --------- Co-authored-by: wizardchen <wizardchen@tencent.com> Co-authored-by: lyingbug <xiayula2014@gmail.com>
2026-09-25 14:23:08 +00:00
// A chat-template switch carries only the enable_thinking boolean: every
// graded rung is silently dropped on the wire (and a relay backend that
// does not know enable_thinking drops the boolean too), so the selector
// must not offer rungs the request cannot express. Vendors that opt into
// a top-level effort field keep their ladders (#3489 moved its NIM
// entries to that shape).
if r.API == api.APIOpenAICompletions &&
r.OpenAICompletions.ThinkingFormat == api.ThinkingFormatChatTemplateKwargs &&
!r.OpenAICompletions.SupportsReasoningEffort {
keep := make([]api.ReasoningEffort, 0, 2)
for _, level := range caps.ThinkingLevels {
if !level.Graded() {
keep = append(keep, level)
}
}
caps.ThinkingLevels = keep
}
return caps
}
// resolveRerank merges the rerank layers. Rerank has one settings struct
// rather than one per protocol, so the model entry's compat object is decoded
// unconditionally instead of being matched against a protocol.
func resolveRerank(
ref Ref, vendor *Provider, spec models.ModelSpec, cataloged bool, baseURL string,
) (*Resolved, error) {
protocol := vendor.RerankAPI
if protocol == "" {
protocol = api.RerankCohere
}
if !protocol.Known() {
return nil, fmt.Errorf("catalog: unknown rerank api %q for provider %s", protocol, vendor.ID)
}
// Lowest precedence first: protocol default, vendor, model entry, row spec
// override. extra_config is the operator speaking about this one row, so it
// comes last.
settings := api.DefaultRerank()
ApplyCompat(&settings, &vendor.Compat.Rerank)
if len(spec.Compat) > 0 {
overlay := &api.RerankCompat{}
if err := DecodeCompat(spec.Compat, overlay); err != nil {
return nil, fmt.Errorf("rerank compat: %w", err)
}
ApplyCompat(&settings, overlay)
}
if raw := ref.Override.CompatJSON(); len(raw) > 0 {
overlay := &api.RerankCompat{}
if err := DecodeCompat(raw, overlay); err != nil {
return nil, fmt.Errorf("rerank compat: %w", err)
}
ApplyCompat(&settings, overlay)
}
if raw := strings.TrimSpace(ref.Extra[models.ExtraScoreScale]); raw != "" {
scale := api.ScoreScale(strings.ToLower(raw))
if scale != api.ScoreProbability && scale != api.ScoreLogit {
return nil, fmt.Errorf(
"catalog: invalid %s in extra_config: %q (expected %q or %q)",
models.ExtraScoreScale, raw, api.ScoreProbability, api.ScoreLogit,
)
}
settings.ScoreScale = scale
}
if raw := strings.TrimSpace(ref.Extra[models.ExtraTruncatePromptTokens]); raw != "" {
if !settings.AcceptsTruncatePromptTokens {
return nil, fmt.Errorf(
"catalog: %s is a vLLM extension and %s does not implement it; "+
"remove it from extra_config (it is accepted by self-hosted runtimes only)",
models.ExtraTruncatePromptTokens, vendor.ID,
)
}
budget, err := strconv.Atoi(raw)
if err != nil || budget <= 0 {
return nil, fmt.Errorf("catalog: invalid %s in extra_config: %q", models.ExtraTruncatePromptTokens, raw)
}
settings.TruncatePromptTokens = budget
}
// Checked after every layer: a model entry is what declares a dialect
// this build cannot speak.
if settings.UnsupportedReason != "" {
return nil, &UnsupportedModelError{Provider: vendor.ID, Model: spec.ID, Reason: settings.UnsupportedReason}
}
out := &Resolved{
Vendor: configcopy.Clone(vendor.Definition),
Spec: spec,
Cataloged: cataloged,
BaseURL: baseURL,
RemoteModel: ref.Model,
RerankAPI: protocol,
Rerank: settings,
}
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
out.RemoteModel = override
}
return out, nil
}
// resolveEmbeddings merges the embedding layers, in the same order as
// resolveRerank: protocol default, vendor, model entry, row spec override,
// then extra_config, which is the operator speaking about this one row.
func resolveEmbeddings(
ref Ref, vendor *Provider, spec models.ModelSpec, cataloged bool, baseURL string,
) (*Resolved, error) {
protocol := vendor.EmbeddingAPI
if protocol == "" {
protocol = api.EmbeddingOpenAI
}
if !protocol.Known() {
return nil, fmt.Errorf("catalog: unknown embedding api %q for provider %s", protocol, vendor.ID)
}
settings := api.DefaultEmbeddings()
ApplyCompat(&settings, &vendor.Compat.Embeddings)
if len(spec.Compat) > 0 {
overlay := &api.EmbeddingsCompat{}
if err := DecodeCompat(spec.Compat, overlay); err != nil {
return nil, fmt.Errorf("embeddings compat: %w", err)
}
ApplyCompat(&settings, overlay)
}
if raw := ref.Override.CompatJSON(); len(raw) > 0 {
overlay := &api.EmbeddingsCompat{}
if err := DecodeCompat(raw, overlay); err != nil {
return nil, fmt.Errorf("embeddings compat: %w", err)
}
ApplyCompat(&settings, overlay)
}
// The row may carry a truncation budget, but the extension is vLLM's and
// appears in no managed vendor's schema. Dropping it where the vendor
// does not implement it is the quiet direction on purpose: unlike the
// rerank opt-in, this field has a UI control that every embedding row
// has always carried, so refusing to resolve would break rows whose only
// mistake is a non-zero default.
//
// Where it is accepted, an unset row keeps the budget the pre-catalog
// client always sent. A self-hosted index was built with long chunks cut
// at that length; embedding new chunks uncut would put them in a
// different place from the old ones without anything failing.
if settings.AcceptsTruncatePromptTokens {
settings.TruncatePromptTokens = ref.TruncatePromptTokens
if settings.TruncatePromptTokens <= 0 {
settings.TruncatePromptTokens = models.LegacyTruncatePromptTokens
}
}
// A model entry may name a different dialect than the vendor default.
if settings.API != "" {
if !settings.API.Known() {
return nil, fmt.Errorf(
"catalog: unknown embedding api %q on %s/%s", settings.API, vendor.ID, spec.ID)
}
protocol = settings.API
}
settings.API = protocol
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
if !settings.ImageFormat.Known() {
return nil, fmt.Errorf(
"catalog: unknown embedding image_format %q on %s/%s (expected %q or %q)",
settings.ImageFormat, vendor.ID, spec.ID, api.EmbeddingImageObject, api.EmbeddingImageMessages)
}
out := &Resolved{
Vendor: configcopy.Clone(vendor.Definition),
Spec: spec,
Cataloged: cataloged,
BaseURL: baseURL,
RemoteModel: ref.Model,
EmbeddingAPI: protocol,
Embeddings: settings,
}
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
out.RemoteModel = override
}
return out, nil
}
// resolveTranscriptions merges the speech-to-text layers, in the same order
// as resolveEmbeddings: protocol default, vendor compat, the catalog entry,
// the row's own compat, then remote_model_name.
func resolveTranscriptions(
ref Ref, vendor *Provider, spec models.ModelSpec, cataloged bool, baseURL string,
) (*Resolved, error) {
protocol := vendor.TranscriptionAPI
if protocol == "" {
protocol = api.TranscriptionOpenAI
}
settings := api.DefaultTranscriptions()
ApplyCompat(&settings, &vendor.Compat.Transcriptions)
for _, raw := range []json.RawMessage{spec.Compat, ref.Override.CompatJSON()} {
if len(raw) == 0 {
continue
}
overlay := &api.TranscriptionsCompat{}
if err := DecodeCompat(raw, overlay); err != nil {
return nil, fmt.Errorf("transcriptions compat: %w", err)
}
ApplyCompat(&settings, overlay)
}
if settings.API != "" {
protocol = settings.API
}
if !protocol.Known() {
return nil, fmt.Errorf("catalog: unknown transcription api %q for %s/%s", protocol, vendor.ID, spec.ID)
}
settings.API = protocol
switch settings.LanguageParam {
case "", api.LanguageForm, api.LanguageHeader, api.LanguageASROptions:
default:
return nil, fmt.Errorf("catalog: unknown language_param %q for %s/%s",
settings.LanguageParam, vendor.ID, spec.ID)
}
// Checked after every layer: an entry may lift a vendor-wide refusal for
// the one model that takes the audio in the request.
if settings.UnsupportedReason != "" {
return nil, &UnsupportedModelError{Provider: vendor.ID, Model: spec.ID, Reason: settings.UnsupportedReason}
}
out := &Resolved{
Vendor: configcopy.Clone(vendor.Definition),
Spec: spec,
Cataloged: cataloged,
BaseURL: baseURL,
RemoteModel: ref.Model,
TranscriptionAPI: protocol,
Transcriptions: settings,
}
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
out.RemoteModel = override
}
return out, nil
}