mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* feat: embedding_multimodal_model — separate model routing for multimodal embeddings v0.28.9 shipped multimodal image embeddings via Voyage, but embedMultimodal() hardcodes to the primary embedding_model. Brains using OpenAI text-embedding-3-large (1536-dim) for text cannot use Voyage voyage-multimodal-3 (1024-dim) for images without switching their entire embedding pipeline. This adds embedding_multimodal_model as a distinct config key that embedMultimodal() prefers over embedding_model when set. The dual- column schema (embedding vs embedding_image) already supports different dimensions — this patch completes the routing. Config surface: - gbrain config set embedding_multimodal_model voyage:voyage-multimodal-3 - env: GBRAIN_EMBEDDING_MULTIMODAL_MODEL=voyage:voyage-multimodal-3 Files changed: - core/ai/types.ts: AIGatewayConfig gains embedding_multimodal_model - core/ai/gateway.ts: configureGateway stores it; embedMultimodal reads it - core/config.ts: GBrainConfig type + env loader + DB merge path - cli.ts: threads config into gateway; reconfigures after DB merge Tested on a 96K-page brain with OpenAI text + Voyage multimodal running side by side. Voyage returns 1024-dim vectors into embedding_image column; text embeddings unchanged. * refactor(cli): extract buildGatewayConfig + always re-config after DB merge Two related changes co-located so the un-gate doesn't leave the duplicated configureGateway shapes drifting: 1. Extract file-local `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig` helper. Both configureGateway sites in connectEngine() now pass through it; future fields touch one place. 2. Drop the field-name-gated re-config trigger. The previous gate fired only when `merged.embedding_multimodal_model` was truthy, coupling the trigger to one field name. Future DB-mutable gateway fields would silently miss it. Re-config now always fires when loadConfigWithEngine returns non-null. One extra cache+shrinkState clear per startup is microseconds, no hot path. Schema-sizing fields stay stable because loadConfigWithEngine respects file/env first; merged.embedding_dimensions equals config.embedding_dimensions when no DB override exists. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(ai): model-level multimodal validation + getMultimodalModel accessor Codex review of PR #719 (F1) caught a real footgun: the Voyage recipe shares supports_multimodal: true across all 12 models in its embedding touchpoint, of which only voyage-multimodal-3 is valid at /multimodalembeddings. A user setting embedding_multimodal_model to a text-only Voyage model (e.g. voyage-3-large) passes local validation and fails at the endpoint with HTTP 400 — which gateway.ts:626 misclassifies as transient (TODO: reclassify, tracked in TODOS.md). Adds: - EmbeddingTouchpoint.multimodal_models?: string[] (optional, model-level allow-list inside a recipe that mixes text-only + multimodal models). - Voyage declares multimodal_models: ['voyage-multimodal-3']. - embedMultimodal() validates parsed.modelId against the allow-list AFTER the existing recipe-level supports_multimodal check. Throws AIConfigError with the full multimodal_models list in the fix hint. - getMultimodalModel() public accessor mirroring getEmbeddingModel / getChatModel — needed by the cli-multimodal-integration test and useful for future doctor checks. Recipe-level fast-fail stays so non-multimodal providers (Anthropic / OpenAI today) keep their AIConfigError path unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: cover embedding_multimodal_model precedence + gateway override + cli integration PR #719 originally shipped zero tests for the new code paths. Closes that gap with three layers: 1. test/loadConfig-merge.test.ts — extends the existing env > file > DB precedence pattern (which already covers embedding_image_ocr_model) with four cases for embedding_multimodal_model: DB-only fills in, file wins over DB, all-unset stays undefined, null/empty DB ignored. 2. test/voyage-multimodal.test.ts — four cases for embedMultimodal model resolution: prefers multimodal_model over embedding_model, falls back to embedding_model when unset (regression guard), AIConfigError on non-multimodal recipe, AIConfigError on Voyage text-only model (Codex F1 model-level validation). 3. test/cli-multimodal-integration.test.ts (NEW) — three PGLite-based integration tests for the cli.ts re-config glue itself (Codex F3: the actual bug site that "mechanical glue" claims hide). Drives the loadConfigWithEngine + buildGatewayConfig + configureGateway sequence connectEngine() runs and asserts the gateway observed the DB-set value. 11 new test cases total. All pass against the production code in this PR. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(todos): follow-ups from PR #719 codex review Three items surfaced during /codex outside-voice review of PR #719's plan that are out of scope for the current PR but worth tracking: - gbrain doctor: warn on misconfigured multimodal model (P2). Two checks: multimodal_model set without recipe API key; embedding_multimodal flag on without a multimodal-capable embedding_model. - Reclassify Voyage HTTP 4xx as AIConfigError (P2, Codex F2). Today gateway.ts:626 throws AITransientError for any non-401/403 4xx, so permanent config bugs (malformed body, model not in multimodal_models) trigger retry storms. Aligns with normalizeAIError's contract. - gbrain config unset <key> (P3, Codex F6). Once a user sets a key in DB there's no normal CLI path to clear it. Pre-existing UX gap; PR #719's new key surfaces it again. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v0.28.11) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: v0.28.11 annotations for ai/types, ai/gateway, voyage recipe Updates the Key Files section so the per-file annotations reflect the multimodal_model routing + model-level validation that landed in #719. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: garrytan-agents <garrytan-agents@users.noreply.github.com> Co-authored-by: Garry Tan <garrytan@gmail.com> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
358 lines
12 KiB
TypeScript
358 lines
12 KiB
TypeScript
// Phase 6 (D1-D3) + Eng-3A: voyage-multimodal-3 recipe + gateway.embedMultimodal.
|
|
//
|
|
// Verifies recipe registration, gateway happy-path with mocked fetch,
|
|
// 401 / 429 / dim-mismatch error paths, and the off-by-one batch math
|
|
// (n=0, n=1, n=32, n=33, n=64) flagged by Eng-3A.
|
|
|
|
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
import { configureGateway, embedMultimodal, resetGateway } from '../src/core/ai/gateway.ts';
|
|
import { getRecipe } from '../src/core/ai/recipes/index.ts';
|
|
import { AIConfigError, AITransientError } from '../src/core/ai/errors.ts';
|
|
|
|
// Capture all fetch calls. Each test installs a fresh handler and asserts
|
|
// the request shape AND returns a plausible Voyage payload.
|
|
type FetchHandler = (url: string, init: RequestInit) => Promise<Response>;
|
|
let fetchHandler: FetchHandler | null = null;
|
|
const origFetch = globalThis.fetch;
|
|
|
|
beforeEach(() => {
|
|
fetchHandler = null;
|
|
globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
|
|
if (!fetchHandler) {
|
|
throw new Error('fetch called but no handler installed');
|
|
}
|
|
return fetchHandler(typeof url === 'string' ? url : url.toString(), init ?? {});
|
|
}) as typeof fetch;
|
|
});
|
|
|
|
afterEach(() => {
|
|
globalThis.fetch = origFetch;
|
|
resetGateway();
|
|
});
|
|
|
|
function configureVoyageMultimodal(env: Record<string, string | undefined> = {}) {
|
|
configureGateway({
|
|
embedding_model: 'voyage:voyage-multimodal-3',
|
|
embedding_dimensions: 1024,
|
|
env: { VOYAGE_API_KEY: 'test-key', ...env },
|
|
});
|
|
}
|
|
|
|
function makeImage(mimeOverride?: string) {
|
|
return {
|
|
kind: 'image_base64' as const,
|
|
data: Buffer.from('fake-image-bytes').toString('base64'),
|
|
mime: mimeOverride ?? 'image/jpeg',
|
|
};
|
|
}
|
|
|
|
function fakeVoyageResponse(count: number, dims = 1024): Response {
|
|
const data = Array.from({ length: count }, (_, i) => ({
|
|
embedding: Array.from({ length: dims }, () => 0.1 * (i + 1)),
|
|
index: i,
|
|
}));
|
|
return new Response(JSON.stringify({ data, model: 'voyage-multimodal-3' }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
describe('voyage recipe — multimodal registration', () => {
|
|
test('voyage-multimodal-3 is in the recipe model list', () => {
|
|
const voyage = getRecipe('voyage');
|
|
expect(voyage).toBeDefined();
|
|
expect(voyage!.touchpoints.embedding!.models).toContain('voyage-multimodal-3');
|
|
});
|
|
|
|
test('voyage embedding touchpoint declares supports_multimodal: true', () => {
|
|
const voyage = getRecipe('voyage');
|
|
expect(voyage!.touchpoints.embedding!.supports_multimodal).toBe(true);
|
|
});
|
|
|
|
test('voyage default_dims is 1024 (parity with multimodal output dim)', () => {
|
|
const voyage = getRecipe('voyage');
|
|
expect(voyage!.touchpoints.embedding!.default_dims).toBe(1024);
|
|
});
|
|
});
|
|
|
|
describe('gateway.embedMultimodal — happy path', () => {
|
|
test('single image produces a 1024-dim Float32Array', async () => {
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async (url, init) => {
|
|
expect(url).toContain('/multimodalembeddings');
|
|
const body = JSON.parse(init.body as string);
|
|
expect(body.model).toBe('voyage-multimodal-3');
|
|
expect(body.inputs.length).toBe(1);
|
|
expect(body.inputs[0].content[0].type).toBe('image_base64');
|
|
expect(body.inputs[0].content[0].image_base64).toContain('data:image/jpeg;base64,');
|
|
return fakeVoyageResponse(1);
|
|
};
|
|
const out = await embedMultimodal([makeImage()]);
|
|
expect(out.length).toBe(1);
|
|
expect(out[0]).toBeInstanceOf(Float32Array);
|
|
expect(out[0].length).toBe(1024);
|
|
});
|
|
|
|
test('Authorization header is set with bearer token', async () => {
|
|
configureVoyageMultimodal();
|
|
let captured: Record<string, string> = {};
|
|
fetchHandler = async (_url, init) => {
|
|
captured = init.headers as Record<string, string>;
|
|
return fakeVoyageResponse(1);
|
|
};
|
|
await embedMultimodal([makeImage()]);
|
|
expect(captured.Authorization).toBe('Bearer test-key');
|
|
expect(captured['Content-Type']).toBe('application/json');
|
|
});
|
|
});
|
|
|
|
describe('gateway.embedMultimodal — Eng-3A batch boundary tests', () => {
|
|
test('n=0 short-circuits: returns [] without calling fetch', async () => {
|
|
configureVoyageMultimodal();
|
|
let called = false;
|
|
fetchHandler = async () => {
|
|
called = true;
|
|
return fakeVoyageResponse(0);
|
|
};
|
|
const out = await embedMultimodal([]);
|
|
expect(out).toEqual([]);
|
|
expect(called).toBe(false);
|
|
});
|
|
|
|
test('n=1: single batch, single embedding back', async () => {
|
|
configureVoyageMultimodal();
|
|
let calls = 0;
|
|
fetchHandler = async () => {
|
|
calls++;
|
|
return fakeVoyageResponse(1);
|
|
};
|
|
const out = await embedMultimodal([makeImage()]);
|
|
expect(out.length).toBe(1);
|
|
expect(calls).toBe(1);
|
|
});
|
|
|
|
test('n=32 (exact batch): one HTTP call', async () => {
|
|
configureVoyageMultimodal();
|
|
let calls = 0;
|
|
fetchHandler = async (_url, init) => {
|
|
calls++;
|
|
const body = JSON.parse(init.body as string);
|
|
expect(body.inputs.length).toBe(32);
|
|
return fakeVoyageResponse(body.inputs.length);
|
|
};
|
|
const out = await embedMultimodal(Array.from({ length: 32 }, () => makeImage()));
|
|
expect(out.length).toBe(32);
|
|
expect(calls).toBe(1);
|
|
});
|
|
|
|
test('n=33 (off-by-one): two HTTP calls, sizes 32 + 1', async () => {
|
|
configureVoyageMultimodal();
|
|
const seenSizes: number[] = [];
|
|
fetchHandler = async (_url, init) => {
|
|
const body = JSON.parse(init.body as string);
|
|
seenSizes.push(body.inputs.length);
|
|
return fakeVoyageResponse(body.inputs.length);
|
|
};
|
|
const out = await embedMultimodal(Array.from({ length: 33 }, () => makeImage()));
|
|
expect(out.length).toBe(33);
|
|
expect(seenSizes).toEqual([32, 1]);
|
|
});
|
|
|
|
test('n=64 (clean two batches): two calls of 32', async () => {
|
|
configureVoyageMultimodal();
|
|
const seenSizes: number[] = [];
|
|
fetchHandler = async (_url, init) => {
|
|
const body = JSON.parse(init.body as string);
|
|
seenSizes.push(body.inputs.length);
|
|
return fakeVoyageResponse(body.inputs.length);
|
|
};
|
|
const out = await embedMultimodal(Array.from({ length: 64 }, () => makeImage()));
|
|
expect(out.length).toBe(64);
|
|
expect(seenSizes).toEqual([32, 32]);
|
|
});
|
|
});
|
|
|
|
describe('gateway.embedMultimodal — error paths', () => {
|
|
test('401 → AIConfigError with auth fix hint', async () => {
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async () => new Response('{"error":"unauthorized"}', { status: 401 });
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AIConfigError);
|
|
expect((err as AIConfigError).message).toContain('401');
|
|
});
|
|
|
|
test('429 → AITransientError', async () => {
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async () => new Response('rate limited', { status: 429 });
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AITransientError);
|
|
});
|
|
|
|
test('5xx → AITransientError', async () => {
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async () => new Response('server error', { status: 503 });
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AITransientError);
|
|
});
|
|
|
|
test('dim mismatch → AIConfigError', async () => {
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async () => fakeVoyageResponse(1, 768); // wrong dim
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AIConfigError);
|
|
expect((err as AIConfigError).message).toContain('1024');
|
|
});
|
|
|
|
test('malformed JSON → AITransientError', async () => {
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async () =>
|
|
new Response('not json', { status: 200, headers: { 'Content-Type': 'application/json' } });
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AITransientError);
|
|
});
|
|
|
|
test('embedding count mismatch → AITransientError', async () => {
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async () => fakeVoyageResponse(1); // returns 1, sent 2
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage(), makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AITransientError);
|
|
});
|
|
|
|
test('missing API key → AIConfigError', async () => {
|
|
configureGateway({
|
|
embedding_model: 'voyage:voyage-multimodal-3',
|
|
embedding_dimensions: 1024,
|
|
env: {}, // no VOYAGE_API_KEY
|
|
});
|
|
fetchHandler = async () => fakeVoyageResponse(1); // never called
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AIConfigError);
|
|
expect((err as AIConfigError).message).toContain('VOYAGE_API_KEY');
|
|
});
|
|
|
|
test('non-multimodal recipe → AIConfigError', async () => {
|
|
configureGateway({
|
|
embedding_model: 'openai:text-embedding-3-large',
|
|
embedding_dimensions: 1536,
|
|
env: { OPENAI_API_KEY: 'sk-test' },
|
|
});
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AIConfigError);
|
|
expect((err as AIConfigError).message).toMatch(/does not support multimodal|not implemented/i);
|
|
});
|
|
});
|
|
|
|
// v0.28.11 (PR #719): embedding_multimodal_model override + model-level
|
|
// validation. Confirms the gateway's two-layer multimodal gate:
|
|
// 1. recipe.touchpoints.embedding.supports_multimodal (recipe scope)
|
|
// 2. recipe.touchpoints.embedding.multimodal_models[] (model scope)
|
|
describe('gateway.embedMultimodal — multimodal_model override + model-level validation', () => {
|
|
test('prefers embedding_multimodal_model over embedding_model when both set', async () => {
|
|
configureGateway({
|
|
embedding_model: 'openai:text-embedding-3-large',
|
|
embedding_dimensions: 1536,
|
|
embedding_multimodal_model: 'voyage:voyage-multimodal-3',
|
|
env: { VOYAGE_API_KEY: 'voyage-key', OPENAI_API_KEY: 'sk-test' },
|
|
});
|
|
let capturedUrl = '';
|
|
let capturedBody: { model?: string } = {};
|
|
fetchHandler = async (url, init) => {
|
|
capturedUrl = url;
|
|
capturedBody = JSON.parse(init.body as string);
|
|
return fakeVoyageResponse(1);
|
|
};
|
|
const out = await embedMultimodal([makeImage()]);
|
|
expect(out.length).toBe(1);
|
|
expect(capturedUrl).toContain('/multimodalembeddings');
|
|
expect(capturedBody.model).toBe('voyage-multimodal-3');
|
|
});
|
|
|
|
test('falls back to embedding_model when embedding_multimodal_model is unset', async () => {
|
|
// Regression guard for the existing single-model setup.
|
|
configureVoyageMultimodal();
|
|
fetchHandler = async () => fakeVoyageResponse(1);
|
|
const out = await embedMultimodal([makeImage()]);
|
|
expect(out.length).toBe(1);
|
|
});
|
|
|
|
test('embedding_multimodal_model pointing at non-multimodal recipe → AIConfigError', async () => {
|
|
configureGateway({
|
|
embedding_model: 'voyage:voyage-multimodal-3', // would normally work
|
|
embedding_multimodal_model: 'openai:text-embedding-3-large', // override breaks it
|
|
embedding_dimensions: 1536,
|
|
env: { VOYAGE_API_KEY: 'voyage-key', OPENAI_API_KEY: 'sk-test' },
|
|
});
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AIConfigError);
|
|
expect((err as AIConfigError).message).toMatch(/does not support multimodal/i);
|
|
});
|
|
|
|
test('embedding_multimodal_model pointing at Voyage text-only model → AIConfigError (D4 / Codex F1)', async () => {
|
|
// Voyage shares supports_multimodal: true across all 12 models in the
|
|
// recipe. Without the model-level multimodal_models gate, voyage-3-large
|
|
// would pass validation locally and fail at /multimodalembeddings with
|
|
// HTTP 400 — which gateway.ts:626 misclassifies as transient. Change 3
|
|
// closes this gap.
|
|
configureGateway({
|
|
embedding_model: 'openai:text-embedding-3-large',
|
|
embedding_dimensions: 1536,
|
|
embedding_multimodal_model: 'voyage:voyage-3-large', // text-only Voyage
|
|
env: { VOYAGE_API_KEY: 'voyage-key', OPENAI_API_KEY: 'sk-test' },
|
|
});
|
|
let err: unknown;
|
|
try {
|
|
await embedMultimodal([makeImage()]);
|
|
} catch (e) {
|
|
err = e;
|
|
}
|
|
expect(err).toBeInstanceOf(AIConfigError);
|
|
expect((err as AIConfigError).message).toMatch(/voyage-3-large.*not.*multimodal/i);
|
|
expect((err as AIConfigError).fix ?? '').toMatch(/voyage:voyage-multimodal-3/);
|
|
});
|
|
});
|