7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(embeddings): accept optional dimensions parameter for MRL truncation (#393)
Jasnoor Gilla8cdc3d9238d
diff --git a/server/src/__tests__/services/embeddings.test.ts b/server/src/__tests__/services/embeddings.test.tsindex 190b24bb..4e8bd626 100644--- a/server/src/__tests__/services/embeddings.test.ts+++ b/server/src/__tests__/services/embeddings.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import type { MockedFunction } from 'vitest';import { initDb, getDb } from '../../db/index.js';import { encrypt } from '../../lib/crypto.js';import { resolveFamily, getDefaultFamily, runEmbeddings, EmbeddingsError } from '../../services/embeddings.js';@@ -192,5 +193,124 @@ describe('embeddings service', () => {`).get() as { used: number };expect(chatUsed.used).toBe(0);});++ describe('dimensions parameter (MRL truncation)', () => {+ // Typed fetch mock so .mock.calls is properly indexed without `as any`.+ // The cast on assignment to globalThis.fetch is unavoidable because+ // globalThis.fetch in lib.dom is typed loosely; this is the same+ // pattern the existing tests in this file use.+ function mockFetch(impl: typeof fetch): MockedFunction<typeof fetch> {+ const m = vi.fn(impl) as MockedFunction<typeof fetch>;+ globalThis.fetch = m as unknown as typeof fetch;+ return m;+ }++ it('forwards dimensions to NVIDIA NeMo NIM in the request body', async () => {+ addKey('nvidia');+ const fetchMock = mockFetch(async () => okEmbeddingResponse(1536));++ await runEmbeddings('llama-nemotron-embed-vl-1b-v2', ['hello'], 1536);++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const body = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));+ expect(body.dimensions).toBe(1536);+ // The provider-prefixed model id (nvidia/<id>) is what reaches the upstream;+ // the bare id is used internally for family resolution only.+ expect(body.model).toBe('nvidia/llama-nemotron-embed-vl-1b-v2');+ // input_type is still set on nvidia (existing behavior preserved)+ expect(body.input_type).toBe('query');+ });++ it('omits dimensions from the upstream body when not requested', async () => {+ addKey('nvidia');+ const fetchMock = mockFetch(async () => okEmbeddingResponse(2048));++ await runEmbeddings('llama-nemotron-embed-vl-1b-v2', ['hello']);++ const body = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));+ expect(body).not.toHaveProperty('dimensions');+ });++ it('returns the truncated dimension reported by the upstream response', async () => {+ addKey('nvidia');+ // Mock responds with 1536-dim vector even though model is native 2048.+ mockFetch(async () => okEmbeddingResponse(1536));++ const result = await runEmbeddings('llama-nemotron-embed-vl-1b-v2', ['hello'], 1536);+ expect(result.dimensions).toBe(1536);+ expect(result.vectors[0]).toHaveLength(1536);+ });++ it('forwards dimensions to the google provider', async () => {+ // Use a family served by google. gemini-embedding-001 has google in its chain.+ addKey('google');+ const fetchMock = mockFetch(async () => okEmbeddingResponse(768));++ await runEmbeddings('gemini-embedding-001', ['hello'], 768);++ const body = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));+ expect(body.dimensions).toBe(768);+ expect(String(fetchMock.mock.calls[0][0])).toContain('generativelanguage.googleapis.com');+ });++ it('forwards dimensions to the github provider', async () => {+ addKey('github');+ const fetchMock = mockFetch(async () => okEmbeddingResponse(512));++ await runEmbeddings('text-embedding-3-small', ['hello'], 512);++ const body = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));+ expect(body.dimensions).toBe(512);+ expect(String(fetchMock.mock.calls[0][0])).toContain('models.github.ai');+ });++ it('forwards dimensions to the openrouter provider', async () => {+ addKey('openrouter');+ const fetchMock = mockFetch(async () => okEmbeddingResponse(1024));++ await runEmbeddings('llama-nemotron-embed-vl-1b-v2', ['hello'], 1024);++ const body = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));+ expect(body.dimensions).toBe(1024);+ expect(String(fetchMock.mock.calls[0][0])).toContain('openrouter.ai');+ });++ it('preserves byte-identical upstream bodies when dimensions is undefined', async () => {+ // Snapshot the request body that runEmbeddings sends today, then verify+ // that adding the dimensions parameter does not change ANY other field.+ addKey('nvidia');+ const beforeMock = mockFetch(async () => okEmbeddingResponse(2048));+ await runEmbeddings('llama-nemotron-embed-vl-1b-v2', ['hello']);+ const beforeBody = JSON.parse(String((beforeMock.mock.calls[0][1] as RequestInit).body));++ addKey('nvidia'); // re-seed; previous run consumed nothing+ const afterMock = mockFetch(async () => okEmbeddingResponse(2048));+ await runEmbeddings('llama-nemotron-embed-vl-1b-v2', ['hello'], undefined);+ const afterBody = JSON.parse(String((afterMock.mock.calls[0][1] as RequestInit).body));++ expect(afterBody).toEqual(beforeBody);+ });++ it('passes dimensions through the family failover chain', async () => {+ // nvidia is the primary for llama-nemotron-embed-vl-1b-v2; if it 429s,+ // openrouter takes over. Both should see the dimensions parameter.+ addKey('nvidia');+ addKey('openrouter');+ const fetchMock = mockFetch(async () => new Response('rate limited', { status: 429 }));+ fetchMock.mockResolvedValueOnce(new Response('rate limited', { status: 429 }));+ fetchMock.mockResolvedValueOnce(okEmbeddingResponse(1024));++ const result = await runEmbeddings('llama-nemotron-embed-vl-1b-v2', ['hello'], 1024);+ expect(result.platform).toBe('openrouter');+ expect(result.dimensions).toBe(1024);+ expect(fetchMock).toHaveBeenCalledTimes(2);++ // Both attempts forwarded dimensions+ const body1 = JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body));+ const body2 = JSON.parse(String((fetchMock.mock.calls[1][1] as RequestInit).body));+ expect(body1.dimensions).toBe(1024);+ expect(body2.dimensions).toBe(1024);+ });+ });});});diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 3776ca65..aed806e2 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -414,6 +414,11 @@ export function streamChunkText(chunk: any): string {const EmbeddingsBody = z.object({model: z.string().optional(),input: z.union([z.string(), z.array(z.string())]),+ // Optional output-dimension override forwarded to providers that support MRL+ // truncation (NVIDIA NeMo NIM, Google Gemini Embedding, OpenAI v3). Validation+ // only — bounds checking happens upstream (the provider rejects out-of-range+ // values with a clear 400).+ dimensions: z.number().int().positive().optional(),});proxyRouter.post('/embeddings', async (req: Request, res: Response) => {@@ -430,7 +435,7 @@ proxyRouter.post('/embeddings', async (req: Request, res: Response) => {}const inputs = Array.isArray(parsed.data.input) ? parsed.data.input : [parsed.data.input];try {- const result = await runEmbeddings(parsed.data.model, inputs);+ const result = await runEmbeddings(parsed.data.model, inputs, parsed.data.dimensions);res.json({object: 'list',data: result.vectors.map((values, i) => ({ object: 'embedding', index: i, embedding: values })),diff --git a/server/src/services/embeddings.ts b/server/src/services/embeddings.tsindex b1255c78..6cc8ea92 100644--- a/server/src/services/embeddings.ts+++ b/server/src/services/embeddings.ts@@ -91,11 +91,20 @@ async function openAiStyleEmbed(modelId: string,inputs: string[],extra: Record<string, unknown> = {},+ dimensions?: number,): Promise<ProviderCallResult> {+ const body: Record<string, unknown> = { model: modelId, input: inputs, ...extra };+ // Some providers (NVIDIA NeMo NIM, Google Gemini Embedding, OpenAI v3) support+ // Matryoshka Representation Learning (MRL) — a smaller output_dim is valid and+ // truncates the vector rather than failing. Others (HuggingFace feature-extraction,+ // Cloudflare BGE) ignore unknown fields silently. We only forward the param when+ // the caller asked for an explicit override, so providers that don't accept it+ // see a request body identical to today.+ if (dimensions !== undefined) body.dimensions = dimensions;const r = await proxyFetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },- body: JSON.stringify({ model: modelId, input: inputs, ...extra }),+ body: JSON.stringify(body),signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),});if (!r.ok) {@@ -112,18 +121,19 @@ async function openAiStyleEmbed(};}-async function callProvider(row: EmbeddingModelRow, key: string, inputs: string[]): Promise<ProviderCallResult> {+async function callProvider(row: EmbeddingModelRow, key: string, inputs: string[], dimensions?: number): Promise<ProviderCallResult> {switch (row.platform) {case 'google':- return openAiStyleEmbed('https://generativelanguage.googleapis.com/v1beta/openai/embeddings', key, row.model_id, inputs, {});+ return openAiStyleEmbed('https://generativelanguage.googleapis.com/v1beta/openai/embeddings', key, row.model_id, inputs, {}, dimensions);case 'nvidia':// NeMo Retriever NIMs require input_type; 'query' is the symmetric-safe// choice for a gateway that can't know whether this is index or query time.- return openAiStyleEmbed('https://integrate.api.nvidia.com/v1/embeddings', key, row.model_id, inputs, { input_type: 'query' });+ // MRL models (e.g. llama-nemotron-embed-1b-v2) accept dimensions and truncate.+ return openAiStyleEmbed('https://integrate.api.nvidia.com/v1/embeddings', key, row.model_id, inputs, { input_type: 'query' }, dimensions);case 'openrouter':- return openAiStyleEmbed('https://openrouter.ai/api/v1/embeddings', key, row.model_id, inputs, {});+ return openAiStyleEmbed('https://openrouter.ai/api/v1/embeddings', key, row.model_id, inputs, {}, dimensions);case 'github':- return openAiStyleEmbed('https://models.github.ai/inference/embeddings', key, row.model_id, inputs, {});+ return openAiStyleEmbed('https://models.github.ai/inference/embeddings', key, row.model_id, inputs, {}, dimensions);case 'cloudflare': {// Key is stored as "account_id:token".const sep = key.indexOf(':');@@ -190,8 +200,15 @@ function logEmbeddingRequest(}/** Embed `inputs` via the family's provider chain, failing over within the- * family on any provider error. Throws EmbeddingsError when the chain is dry. */-export async function runEmbeddings(model: string | undefined, inputs: string[]): Promise<EmbeddingsResult> {+ * family on any provider error. Throws EmbeddingsError when the chain is dry.+ *+ * `dimensions` (optional): client-supplied output-dimension override forwarded to+ * providers that support MRL truncation (NVIDIA NeMo NIM, Google Gemini Embedding,+ * OpenAI text-embedding-3-*). Providers that ignore the field see an identical+ * request body. The override is independent of the model's native dimension — the+ * family registry still pins the canonical dimension, this just lets callers ask+ * for a smaller vector at the cost of some accuracy. */+export async function runEmbeddings(model: string | undefined, inputs: string[], dimensions?: number): Promise<EmbeddingsResult> {const family = resolveFamily(model);if (!family) {throw new EmbeddingsError(@@ -212,7 +229,7 @@ export async function runEmbeddings(model: string | undefined, inputs: string[])if (!key) continue; // no usable key for this provider — try the next oneconst started = Date.now();try {- const out = await callProvider(row, key, inputs);+ const out = await callProvider(row, key, inputs, dimensions);if (out.vectors.length !== inputs.length || out.vectors.some(v => !Array.isArray(v) || v.length === 0)) {throw new EmbeddingsError('upstream returned malformed embeddings', 502);}