Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): an inferred image intent needs a multimodal embedding model; text-only installs keep the keyword arm and expansion
time-attackdb21b1332114
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 42a99ed115..47a868a5ee 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -2169,6 +2169,27 @@ async function embedMultimodalOpenAICompat(* model (typically OpenAI text-embedding-3-large at 1536d or 2560d, NOT* compatible with the 1024d multimodal column).*/+/**+ * The model `embedMultimodal` would embed with (`embedding_multimodal_model`,+ * else `embedding_model`) when it can embed multimodal input, otherwise null.+ * Hybrid search routes a query to the image column only when this is set: on+ * a text-only install (the default `voyage:voyage-4`) the image embed always+ * throws, and routing there only dropped the keyword arm and expansion.+ */+export function multimodalEmbeddingModel(): string | null {+ if (!_config) return null;+ const modelStr = _config.embedding_multimodal_model ?? getEmbeddingModel();+ try {+ const { parsed, recipe } = resolveRecipe(modelStr);+ const touchpoint = recipe.touchpoints.embedding;+ if (!touchpoint?.supports_multimodal) return null;+ if (touchpoint.multimodal_models && !touchpoint.multimodal_models.includes(parsed.modelId)) return null;+ return modelStr;+ } catch {+ return null;+ }+}+export async function embedQueryMultimodal(text: string): Promise<Float32Array> {const [vec] = await embedMultimodal([{ kind: 'text', text }], { inputType: 'query' });if (!vec) {diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 09a42bc615..f4764741b1 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -1091,7 +1091,7 @@ export async function hybridSearch(const postFusionOpts = buildPostFusionOpts(req);const relationalList = await buildRelationalList(req);- const { isAvailable } = await import('../ai/gateway.ts');+ const { isAvailable, multimodalEmbeddingModel } = await import('../ai/gateway.ts');const providerProbe = resolvedCol.embeddingModel || undefined;// Image/both/unified routing embeds via the MULTIMODAL provider, not the// text provider — so a multimodal-only install (text provider absent) must@@ -1100,8 +1100,7 @@ export async function hybridSearch(// multimodal-routed queries) the multimodal provider is reachable. Without// this guard a multimodal-only install would fall to keyword-only here and// never run the image/unified vector path.- const multimodalProviderProbe =- cfgForColumn?.embedding_multimodal_model ?? 'voyage:voyage-multimodal-3';+ const multimodalProviderProbe = multimodalEmbeddingModel();// The LLM intent tie-break (below) can escalate a regex-'text' query to// 'image'/'both'; account for that possibility so an ambiguous query on a// multimodal-only install still reaches the multimodal branch.@@ -1115,6 +1114,7 @@ export async function hybridSearch(earlyModality === 'both' ||mayEscalateToMultimodal) &&!opts?._embeddingOptedOut &&+ multimodalProviderProbe !== null &&isAvailable('embedding', multimodalProviderProbe);// Hermetic eval canaries/CI: a caller-supplied queryEmbedFn produces the// vector-arm query embedding without the gateway, so provider@@ -1125,7 +1125,8 @@ export async function hybridSearch(const { effectiveModality, unifiedRouting, queries } = await resolveModalityAndQueries(req);const { vectorArms, queryEmbedding, imageQueryEmbedding, unifiedDone } =- await runVectorArms(req, { effectiveModality, unifiedRouting, queries, multimodalProviderProbe });+ await runVectorArms(req, { effectiveModality, unifiedRouting, queries,+ multimodalProviderProbe: multimodalProviderProbe ?? cfgForColumn?.embedding_multimodal_model ?? 'voyage:voyage-multimodal-3' });if (vectorArms.length === 0) {return searchVectorFallback(req, lexical, relationalList, postFusionOpts);}diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex f7b465f9ab..4a69457951 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -197,7 +197,8 @@ export async function resolveModalityAndQueries(req: HybridRequest) {explicitModality === undefined &®exModality === 'text' &&resolvedMode.cross_modal_llm_intent &&- isAmbiguousModalityQuery(query)+ isAmbiguousModalityQuery(query) &&+ (await import('../../ai/gateway.ts')).multimodalEmbeddingModel() !== null) {try {const { classifyModalityWithLLM } = await import('../llm-intent.ts');diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex af5ca995d6..f21bea25b5 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -176,7 +176,12 @@ export async function resolveHybridRequest(// System One S2: an above-threshold intent replaces the regex one before// weights, detail and search options are derived (regex is the fallback).const decide = decidePending ? await decidePending : undefined;- const suggestions = decide ? await applySearchIntent(decide, query, regexSuggestions).catch(() => regexSuggestions) : regexSuggestions;+ const intended = decide ? await applySearchIntent(decide, query, regexSuggestions).catch(() => regexSuggestions) : regexSuggestions;+ // An inferred image intent needs a multimodal embedding model; without one+ // the image arm cannot run, so the query stays a text query (keyword arm and+ // expansion included). An explicit `crossModal` still routes as asked.+ const suggestions = intended.suggestedModality !== 'text' && (await import('../../ai/gateway.ts')).multimodalEmbeddingModel() === null+ ? { ...intended, suggestedModality: 'text' as const } : intended;const intentWeightingOn = resolvedMode.intentWeighting;const intentWeights = intentWeightingOn? weightsForIntent(suggestions.intent)diff --git a/test/cross-modal-hybrid-integration.serial.test.ts b/test/cross-modal-hybrid-integration.serial.test.tsindex 8f31d2e36d..89f292a7b1 100644--- a/test/cross-modal-hybrid-integration.serial.test.ts+++ b/test/cross-modal-hybrid-integration.serial.test.ts@@ -7,6 +7,7 @@import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';import {configureGateway,resetGateway,@@ -217,4 +218,28 @@ describe('hybridSearch cross-modal routing (Phase 1 integration)', () => {expect(Array.isArray(results)).toBe(true);// Did NOT throw; fell back successfully.});++ test('an inferred image intent on a text-only install stays a text query: keyword arm, expansion and no failed arm', async () => {+ // The shipped default: voyage-4 text embeddings, no multimodal model. Before the fix+ // the regex routed "a photo of ..." to the image arm, which skipped the keyword arm and+ // expansion, then failed the multimodal embed and reported vector_arm_failed.+ configureGateway({ embedding_model: 'voyage:voyage-4', embedding_dimensions: 1024, env: { VOYAGE_API_KEY: 'voyage-test-key' } });+ fetchHandler = async (url) => {+ if (url.includes('multimodalembeddings')) throw new Error('the multimodal endpoint must not be called on a text-only install');+ return new Response(JSON.stringify({ data: [{ embedding: Array.from({ length: 1024 }, () => 0.1), index: 0 }], model: 'voyage-4' }), { status: 200 });+ };+ await engine.putPage('trips/half-dome', { type: 'note', title: 'Yosemite trip', compiled_truth: 'A photo of Half Dome during sunset for the contest.' });+ await installFixtureChunks(engine, 'trips/half-dome', [{ chunk_index: 0, chunk_text: 'A photo of Half Dome during sunset for the contest.', chunk_source: 'compiled_truth' }]);+ let meta: any;+ const results = await hybridSearch(engine, 'A photo of Half Dome during sunset', { limit: 5, onMeta: m => { meta = m; } });+ expect(results.map(r => r.slug)).toContain('trips/half-dome');+ expect((meta?.degraded ?? []).map((d: any) => d.stage)).not.toContain('vector_arm_failed');+ expect(fetchUrlsSeen.some(u => u.includes('multimodalembeddings'))).toBe(false);+ });++ test('the same inferred image intent still routes to the image arm when a multimodal model is configured', async () => {+ configureBoth();+ await hybridSearch(engine, 'A photo of Half Dome during sunset', { limit: 5 });+ expect(fetchUrlsSeen.some(u => u.includes('multimodalembeddings'))).toBe(true);+ });});