From 1f22120e37e83b9183e23bc2e607e5a9efe8e95b Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sat, 21 Nov 2026 23:56:55 +0000 Subject: [PATCH 1/4] feat(graphile-search): vector search in the request language on tables with translations --- graphile/graphile-search/README.md | 8 ++ .../src/__tests__/vector-i18n.sql | 41 +++++++ .../src/__tests__/vector-i18n.test.ts | 115 ++++++++++++++++++ graphile/graphile-search/src/adapters/i18n.ts | 60 +++++++++ .../graphile-search/src/adapters/pgvector.ts | 74 +++++++++-- graphile/graphile-search/src/plugin.ts | 16 ++- graphile/graphile-search/src/ts-config.ts | 31 +++++ 7 files changed, 329 insertions(+), 16 deletions(-) create mode 100644 graphile/graphile-search/src/__tests__/vector-i18n.sql create mode 100644 graphile/graphile-search/src/__tests__/vector-i18n.test.ts create mode 100644 graphile/graphile-search/src/adapters/i18n.ts diff --git a/graphile/graphile-search/README.md b/graphile/graphile-search/README.md index 0f4b21eede..541c4e8734 100644 --- a/graphile/graphile-search/README.md +++ b/graphile/graphile-search/README.md @@ -62,6 +62,14 @@ then preset `tsConfig`, then request preferences. Configuration names and query text are SQL parameters; request preferences can select only built-in names from the language mapping. +Vector search follows the same request languages on a table tagged +`@i18n ` whose translations table has a vector column of +the same name (with `_id` and `lang_code` columns). A row is compared +with the query through its translation in the first requested language it has +an embedded translation for, and through its own vector otherwise. Without +request languages, or for a language the row has no translation in, only the +row's own vector is compared, so another language's translation never matches. + ## Features - **4 search algorithms** via adapters: tsvector (ts_rank), BM25 (pg_textsearch), pg_trgm (similarity), pgvector (distance) diff --git a/graphile/graphile-search/src/__tests__/vector-i18n.sql b/graphile/graphile-search/src/__tests__/vector-i18n.sql new file mode 100644 index 0000000000..d19cc453d2 --- /dev/null +++ b/graphile/graphile-search/src/__tests__/vector-i18n.sql @@ -0,0 +1,41 @@ +-- Seed for vector search in the request's language. +-- articles carries @i18n articles_translations; each translation has its own vector. +-- +-- Requires postgres-plus:18 image with: vector + +CREATE EXTENSION IF NOT EXISTS vector; + +CREATE SCHEMA IF NOT EXISTS vector_i18n_test; + +CREATE TABLE vector_i18n_test.articles ( + id serial PRIMARY KEY, + title text NOT NULL, + embedding vector(3) +); + +COMMENT ON TABLE vector_i18n_test.articles IS E'@i18n articles_translations'; + +CREATE TABLE vector_i18n_test.articles_translations ( + id serial PRIMARY KEY, + articles_id integer NOT NULL REFERENCES vector_i18n_test.articles(id), + lang_code text NOT NULL, + title text, + embedding vector(3), + UNIQUE (articles_id, lang_code) +); + +-- Every article's own text points away from the query except article 1; +-- articles 2 and 3 only match the query through a translation. +INSERT INTO vector_i18n_test.articles (id, title, embedding) VALUES + (1, 'matches in the default language', '[1, 0, 0]'), + (2, 'matches only in French', '[0, 1, 0]'), + (3, 'matches only in Spanish', '[0, 0, 1]'), + (4, 'no match in any language', '[0, 1, 0]'); + +INSERT INTO vector_i18n_test.articles_translations (articles_id, lang_code, title, embedding) VALUES + (2, 'fr', 'correspond en français', '[1, 0, 0]'), + (3, 'es', 'coincide en español', '[1, 0, 0]'), + (4, 'fr', 'ne correspond pas', '[0, 0, 1]'), + -- Article 1's French translation points away: a French request compares + -- through it, so article 1 is not a French match. + (1, 'fr', 'ne correspond pas en français', '[0, 1, 0]'); diff --git a/graphile/graphile-search/src/__tests__/vector-i18n.test.ts b/graphile/graphile-search/src/__tests__/vector-i18n.test.ts new file mode 100644 index 0000000000..9d103cb2d5 --- /dev/null +++ b/graphile/graphile-search/src/__tests__/vector-i18n.test.ts @@ -0,0 +1,115 @@ +/** + * Vector search in the request's language. + * + * A table with translations (@i18n) is compared with the query through the + * translation in the first requested language the row has one for, and + * through the row's own vector otherwise. A default-language request never + * matches a row through another language's translation. + */ + +import { ConnectionFilterPreset } from 'graphile-connection-filter'; +import type { GraphQLResponse } from 'graphile-test'; +import { getConnections, seed } from 'graphile-test'; +import { join } from 'path'; + +import { createPgvectorAdapter } from '../adapters/pgvector'; +import { VectorCodecPlugin } from '../codecs/vector-codec'; +import { createUnifiedSearchPlugin } from '../plugin'; + +type QueryFn = ( + query: string, + variables?: Record, + commit?: boolean, + reqOptions?: Record +) => Promise>; + +interface Result { + allArticles: { nodes: { rowId: number; embeddingVectorDistance: number | null }[] }; +} + +describe('vector search follows the request language', () => { + let teardown: () => Promise; + let query: QueryFn; + + beforeAll(async () => { + const connections = await getConnections( + { + schemas: ['vector_i18n_test'], + preset: { + extends: [ConnectionFilterPreset()], + plugins: [ + VectorCodecPlugin, + createUnifiedSearchPlugin({ adapters: [createPgvectorAdapter()], enableSearchScore: true }), + ], + }, + useRoot: true, + authRole: 'postgres', + }, + [seed.sqlfile([join(__dirname, './vector-i18n.sql')])] + ); + teardown = connections.teardown; + query = connections.query as QueryFn; + }); + + afterAll(async () => { + if (teardown) await teardown(); + }); + + async function matches(langCodes?: string[]): Promise { + const result = await query( + `query { + allArticles( + where: { vectorEmbedding: { vector: [1, 0, 0], metric: COSINE, distance: 0.1 } } + orderBy: PRIMARY_KEY_ASC + ) { nodes { rowId embeddingVectorDistance } } + }`, + undefined, + false, + langCodes ? { langCodes } : undefined + ); + expect(result.errors).toBeUndefined(); + return result.data!.allArticles.nodes.map((n) => n.rowId); + } + + it('compares only the base rows without a request language', async () => { + expect(await matches()).toEqual([1]); + }); + + it('never matches through a translation in a default-language request', async () => { + expect(await matches(['en'])).toEqual([1]); + }); + + it('compares through the requested translation, falling back to the base row', async () => { + // 2 matches through French; 1 has a French translation that does not + // match; 3 has no French translation and its own text does not match. + expect(await matches(['fr'])).toEqual([2]); + // 3 matches through Spanish; 1 has no Spanish translation and falls back + // to its own (matching) text. + expect(await matches(['es'])).toEqual([1, 3]); + }); + + it('uses the first requested language a row has a translation in', async () => { + expect(await matches(['es', 'fr'])).toEqual([2, 3]); + }); + + it('scores a row by the vector it was compared through', async () => { + const result = await query( + `query { + allArticles( + where: { vectorEmbedding: { vector: [1, 0, 0], metric: COSINE } } + orderBy: PRIMARY_KEY_ASC + ) { nodes { rowId embeddingVectorDistance } } + }`, + undefined, + false, + { langCodes: ['fr'] } + ); + expect(result.errors).toBeUndefined(); + const distance = Object.fromEntries( + result.data!.allArticles.nodes.map((n) => [n.rowId, n.embeddingVectorDistance]) + ); + expect(distance[2]).toBeCloseTo(0); + expect(distance[1]).toBeCloseTo(1); + expect(distance[3]).toBeCloseTo(1); + }); +}); diff --git a/graphile/graphile-search/src/adapters/i18n.ts b/graphile/graphile-search/src/adapters/i18n.ts new file mode 100644 index 0000000000..bc916931e8 --- /dev/null +++ b/graphile/graphile-search/src/adapters/i18n.ts @@ -0,0 +1,60 @@ +/** + * Translation vectors for a table with translations. + * + * A table the DataI18n module translated carries `@i18n `. + * When that translations table has a vector column of the same name (the + * metaschema gives it one whenever the base table has one), vector search can + * compare a query with the translation in the request's language. + */ + +export interface I18nVectorInfo { + schema: string; + tableName: string; + /** Translations column referencing the base row (`_id`). */ + parentFkField: string; + parentPkField: string; + langField: string; + embeddingField: string; + /** Translations column recording the model each translation vector came from. */ + modelColumn: string | null; +} + +export function getI18nVectorInfo( + codec: any, + attributeName: string, + dimensions: number | undefined, + build: any +): I18nVectorInfo | undefined { + const tableName = codec?.extensions?.tags?.i18n; + const pg = codec?.extensions?.pg; + if (typeof tableName !== 'string' || !tableName || !pg?.schemaName || !pg?.name) return undefined; + + const codecs = Object.values(build?.input?.pgRegistry?.pgCodecs ?? {}) as any[]; + const translations = codecs.find( + (c) => c?.attributes && c.extensions?.pg?.schemaName === pg.schemaName && c.extensions?.pg?.name === tableName + ); + const attributes = translations?.attributes as Record | undefined; + const vector = attributes?.[attributeName]; + if (vector?.codec?.name !== 'vector') return undefined; + // A translation vector of another width cannot be compared with the query. + const translationDimensions = vector.extensions?.vectorDimensions; + if (dimensions && translationDimensions && dimensions !== translationDimensions) return undefined; + + const parentFkField = `${pg.name}_id`; + const langField = 'lang_code'; + if (!attributes[parentFkField] || !attributes[langField] || !codec.attributes?.id) return undefined; + + const modelColumn = + Object.entries(attributes).find(([, other]) => other.extensions?.tags?.embeddingModelOf === attributeName)?.[0] ?? + null; + + return { + schema: pg.schemaName, + tableName, + parentFkField, + parentPkField: 'id', + langField, + embeddingField: attributeName, + modelColumn, + }; +} diff --git a/graphile/graphile-search/src/adapters/pgvector.ts b/graphile/graphile-search/src/adapters/pgvector.ts index 44e0b4696e..f1187fb1d7 100644 --- a/graphile/graphile-search/src/adapters/pgvector.ts +++ b/graphile/graphile-search/src/adapters/pgvector.ts @@ -10,6 +10,7 @@ import type { SQL } from 'pg-sql2'; import type { FilterApplyResult,SearchableColumn, SearchAdapter } from '../types'; import { type ChunksInfo,getChunksInfo } from './chunks'; +import { getI18nVectorInfo, type I18nVectorInfo } from './i18n'; /** * Build a distance expression for the given metric. @@ -101,12 +102,14 @@ export function createPgvectorAdapter( const modelColumn = Object.entries(codec.attributes as Record).find( ([, other]) => other.extensions?.tags?.embeddingModelOf === attributeName )?.[0]; + const i18nInfo = getI18nVectorInfo(codec, attributeName, dimensions, _build); columns.push({ attributeName, adapterData: - chunksInfo || dimensions || model || modelColumn + chunksInfo || dimensions || model || modelColumn || i18nInfo ? { ...(chunksInfo && { chunksInfo }), + ...(i18nInfo && { i18nInfo }), ...(dimensions && { dimensions }), ...(model && { model }), ...(modelColumn && { modelColumn }), @@ -224,7 +227,12 @@ export function createPgvectorAdapter( const vectorExpr = sql`${sql.value(vectorString)}::vector`; // Check if this column has chunks info and chunk querying is requested - const adapterData = column.adapterData as { chunksInfo?: ChunksInfo; modelColumn?: string } | undefined; + const adapterData = column.adapterData as { + chunksInfo?: ChunksInfo; + modelColumn?: string; + i18nInfo?: I18nVectorInfo; + langCodes?: string[]; + } | undefined; const chunksInfo = adapterData?.chunksInfo; // A row whose vector another model produced is not a worse match, it is @@ -240,6 +248,50 @@ export function createPgvectorAdapter( const scored = (distance: SQL): SQL => sameModel ? sql`CASE WHEN ${sameModel} THEN ${distance} END` : distance; + // A table with translations (@i18n) is searched in the request's + // language: a row is compared through its translation in the first + // requested language it has one embedded for, and through its own + // vector otherwise. A default-language request finds no translation and + // compares the base rows only, so another language's text never matches. + const i18nInfo = adapterData?.i18nInfo; + const langCodes = adapterData?.langCodes; + let translationDistance: SQL | null = null; + if (i18nInfo && langCodes && langCodes.length > 0) { + const t = sql.identifier('__translation'); + const langs = sql`${sql.value(langCodes)}::text[]`; + const position = sql`array_position(${langs}, ${t}.${sql.identifier(i18nInfo.langField)}::text)`; + const translationVector = sql`${t}.${sql.identifier(i18nInfo.embeddingField)}`; + const translationModel = + i18nInfo.modelColumn && typeof model === 'string' && model + ? sql` AND ${t}.${sql.identifier(i18nInfo.modelColumn)} = ${sql.value(model)}` + : sql``; + translationDistance = sql`( + SELECT ${buildDistanceExpr(sql, translationVector, vectorExpr, resolvedMetric)} + FROM ${sql.identifier(i18nInfo.schema, i18nInfo.tableName)} AS ${t} + WHERE ${t}.${sql.identifier(i18nInfo.parentFkField)} = ${alias}.${sql.identifier(i18nInfo.parentPkField)} + AND ${position} IS NOT NULL + AND ${translationVector} IS NOT NULL${translationModel} + ORDER BY ${position} + LIMIT 1 + )`; + } + const inRequestLanguage = (baseDistance: SQL, baseScorable: SQL | null): FilterApplyResult => { + const scoreExpression = translationDistance + ? sql`COALESCE(${translationDistance}, ${baseDistance})` + : baseDistance; + const scorableClause = translationDistance + ? sql`(${translationDistance} IS NOT NULL OR ${baseScorable ?? sql`true`})` + : baseScorable; + return { + whereClause: + distance !== undefined && distance !== null + ? sql`${scoreExpression} <= ${sql.value(distance)}` + : null, + scoreExpression, + scorableClause, + }; + }; + if (chunksInfo && (includeChunks !== false)) { // Chunk-aware query: find the closest chunk for each parent row // Uses a lateral subquery to get the minimum distance across all chunks @@ -277,22 +329,20 @@ export function createPgvectorAdapter( // MIN(distance) is NULL exactly when no chunk has an embedding. const scorableClause = sql`(${parentScorable} OR ${chunkDistanceSubquery} IS NOT NULL)`; - let whereClause: SQL | null = null; - if (distance !== undefined && distance !== null) { - whereClause = sql`${combinedDistanceExpr} <= ${sql.value(distance)}`; - } - - return { - whereClause, - scoreExpression: combinedDistanceExpr, - scorableClause, - }; + return inRequestLanguage(combinedDistanceExpr, scorableClause); } // Standard (non-chunk) query const columnExpr = sql`${alias}.${sql.identifier(column.attributeName)}`; const distanceExpr = buildDistanceExpr(sql, columnExpr, vectorExpr, resolvedMetric); + if (translationDistance) { + return inRequestLanguage( + scored(distanceExpr), + both(sameModel, sql`${columnExpr} IS NOT NULL`) + ); + } + let whereClause: SQL | null = null; if (distance !== undefined && distance !== null) { whereClause = sql`${distanceExpr} <= ${sql.value(distance)}`; diff --git a/graphile/graphile-search/src/plugin.ts b/graphile/graphile-search/src/plugin.ts index f45a9e92e2..cc1a978273 100644 --- a/graphile/graphile-search/src/plugin.ts +++ b/graphile/graphile-search/src/plugin.ts @@ -27,7 +27,14 @@ import type { GraphileConfig } from 'graphile-config'; import { getQueryBuilder } from 'graphile-plugin-utils'; import type { SQL } from 'pg-sql2'; -import { columnWithRequestTsConfig, REQUEST_TS_CONFIG, requestTsConfig } from './ts-config'; +import { + columnWithRequestContext, + columnWithRequestLangCodes, + REQUEST_LANG_CODES, + REQUEST_TS_CONFIG, + requestLangCodes, + requestTsConfig +} from './ts-config'; import type { SearchableColumn, SearchAdapter, UnifiedSearchOptions } from './types'; /** @@ -718,6 +725,7 @@ export function createUnifiedSearchPlugin( const { context, lambda } = build.grafast; $select.apply(lambda(context(), (ctx: any) => (qb: any) => { qb.setMeta(REQUEST_TS_CONFIG, requestTsConfig(ctx.langCodes)); + qb.setMeta(REQUEST_LANG_CODES, requestLangCodes(ctx.langCodes)); }, true)); return applyPlan($parent, $result, input, info); }, @@ -1305,7 +1313,7 @@ export function createUnifiedSearchPlugin( if (val == null) return; const applyFor = (alias: SQL) => - adapter.buildFilterApply(sql, alias, adapter.name === 'tsv' ? columnWithRequestTsConfig(column, $condition) : column, val, build); + adapter.buildFilterApply(sql, alias, columnWithRequestContext(adapter.name, column, $condition), val, build); const result = applyFor($condition.alias); if (!result) return; @@ -1401,7 +1409,7 @@ export function createUnifiedSearchPlugin( const filterInput = adapter.buildTextSearchInput!(text); const applyFor = (alias: SQL) => - adapter.buildFilterApply(sql, alias, adapter.name === 'tsv' ? columnWithRequestTsConfig(column, $condition) : column, filterInput, build); + adapter.buildFilterApply(sql, alias, columnWithRequestContext(adapter.name, column, $condition), filterInput, build); const result = applyFor($condition.alias); if (!result) continue; @@ -1427,7 +1435,7 @@ export function createUnifiedSearchPlugin( if (declared && declared !== query.vector.length) continue; const applyFor = (alias: SQL) => adapter.buildFilterApply( - sql, alias, column, + sql, alias, columnWithRequestLangCodes(column, $condition), { vector: query.vector, model: query.model, metric: 'COSINE' }, build ); diff --git a/graphile/graphile-search/src/ts-config.ts b/graphile/graphile-search/src/ts-config.ts index 2b755ddc3e..76142826a1 100644 --- a/graphile/graphile-search/src/ts-config.ts +++ b/graphile/graphile-search/src/ts-config.ts @@ -1,6 +1,7 @@ import type { SearchableColumn } from './types'; export const REQUEST_TS_CONFIG = '__graphile_search_ts_config'; +export const REQUEST_LANG_CODES = '__graphile_search_lang_codes'; const languageConfigs = new Map(Object.entries({ ar: 'arabic', hy: 'armenian', eu: 'basque', ca: 'catalan', da: 'danish', @@ -42,3 +43,33 @@ export function columnWithRequestTsConfig(column: SearchableColumn, condition: a }, }; } + +export function requestLangCodes(langCodes: unknown): string[] { + return Array.isArray(langCodes) ? langCodes.filter((code): code is string => typeof code === 'string' && code !== '') : []; +} + +export function conditionLangCodes(condition: any): string[] | undefined { + for (let current = condition; current; current = current.parent) { + const codes = current.getMetaRaw?.(REQUEST_LANG_CODES); + if (codes !== undefined) return codes; + } + return undefined; +} + +/** The request's languages, for a vector column whose table has translations (@i18n). */ +export function columnWithRequestLangCodes(column: SearchableColumn, condition: any): SearchableColumn { + if (!(column.adapterData as { i18nInfo?: unknown } | undefined)?.i18nInfo) return column; + return { + ...column, + adapterData: { + ...(column.adapterData as object), + langCodes: conditionLangCodes(condition) ?? [], + }, + }; +} + +export function columnWithRequestContext(adapterName: string, column: SearchableColumn, condition: any): SearchableColumn { + if (adapterName === 'tsv') return columnWithRequestTsConfig(column, condition); + if (adapterName === 'vector') return columnWithRequestLangCodes(column, condition); + return column; +} From ce447fe926e8b71d8e308c0977cdbd9a9d756df7 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sat, 21 Nov 2026 23:59:28 +0000 Subject: [PATCH 2/4] fix(graphile-search): join translations on the base table's primary key; savepoint per test --- .../graphile-search/src/__tests__/vector-i18n.test.ts | 6 ++++++ graphile/graphile-search/src/adapters/i18n.ts | 11 +++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/graphile/graphile-search/src/__tests__/vector-i18n.test.ts b/graphile/graphile-search/src/__tests__/vector-i18n.test.ts index 9d103cb2d5..cca604ed23 100644 --- a/graphile/graphile-search/src/__tests__/vector-i18n.test.ts +++ b/graphile/graphile-search/src/__tests__/vector-i18n.test.ts @@ -11,6 +11,7 @@ import { ConnectionFilterPreset } from 'graphile-connection-filter'; import type { GraphQLResponse } from 'graphile-test'; import { getConnections, seed } from 'graphile-test'; import { join } from 'path'; +import type { PgTestClient } from 'pgsql-test'; import { createPgvectorAdapter } from '../adapters/pgvector'; import { VectorCodecPlugin } from '../codecs/vector-codec'; @@ -28,6 +29,7 @@ interface Result { } describe('vector search follows the request language', () => { + let db: PgTestClient; let teardown: () => Promise; let query: QueryFn; @@ -47,6 +49,7 @@ describe('vector search follows the request language', () => { }, [seed.sqlfile([join(__dirname, './vector-i18n.sql')])] ); + db = connections.db; teardown = connections.teardown; query = connections.query as QueryFn; }); @@ -55,6 +58,9 @@ describe('vector search follows the request language', () => { if (teardown) await teardown(); }); + beforeEach(() => db.beforeEach()); + afterEach(() => db.afterEach()); + async function matches(langCodes?: string[]): Promise { const result = await query( `query { diff --git a/graphile/graphile-search/src/adapters/i18n.ts b/graphile/graphile-search/src/adapters/i18n.ts index bc916931e8..121cbc2716 100644 --- a/graphile/graphile-search/src/adapters/i18n.ts +++ b/graphile/graphile-search/src/adapters/i18n.ts @@ -40,9 +40,16 @@ export function getI18nVectorInfo( const translationDimensions = vector.extensions?.vectorDimensions; if (dimensions && translationDimensions && dimensions !== translationDimensions) return undefined; + const resources = Object.values(build?.input?.pgRegistry?.pgResources ?? {}) as any[]; + const primaryKey = resources + .find((r) => r?.codec === codec && !r.parameters) + ?.uniques?.find((u: any) => u.isPrimary)?.attributes; + if (!Array.isArray(primaryKey) || primaryKey.length !== 1) return undefined; + const parentPkField: string = primaryKey[0]; + const parentFkField = `${pg.name}_id`; const langField = 'lang_code'; - if (!attributes[parentFkField] || !attributes[langField] || !codec.attributes?.id) return undefined; + if (!attributes[parentFkField] || !attributes[langField]) return undefined; const modelColumn = Object.entries(attributes).find(([, other]) => other.extensions?.tags?.embeddingModelOf === attributeName)?.[0] ?? @@ -52,7 +59,7 @@ export function getI18nVectorInfo( schema: pg.schemaName, tableName, parentFkField, - parentPkField: 'id', + parentPkField, langField, embeddingField: attributeName, modelColumn, From bd1433d79e820a6d9116b14c8dc390116528b21d Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sun, 22 Nov 2026 00:22:38 +0000 Subject: [PATCH 3/4] fix(graphile-search): regional request languages fall back to their primary language for vector search --- graphile/graphile-search/src/__tests__/vector-i18n.test.ts | 4 ++++ graphile/graphile-search/src/ts-config.ts | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/graphile/graphile-search/src/__tests__/vector-i18n.test.ts b/graphile/graphile-search/src/__tests__/vector-i18n.test.ts index cca604ed23..582e203f06 100644 --- a/graphile/graphile-search/src/__tests__/vector-i18n.test.ts +++ b/graphile/graphile-search/src/__tests__/vector-i18n.test.ts @@ -94,6 +94,10 @@ describe('vector search follows the request language', () => { expect(await matches(['es'])).toEqual([1, 3]); }); + it('falls back from a regional request to its primary language', async () => { + expect(await matches(['fr-CA'])).toEqual([2]); + }); + it('uses the first requested language a row has a translation in', async () => { expect(await matches(['es', 'fr'])).toEqual([2, 3]); }); diff --git a/graphile/graphile-search/src/ts-config.ts b/graphile/graphile-search/src/ts-config.ts index 76142826a1..79301efb1c 100644 --- a/graphile/graphile-search/src/ts-config.ts +++ b/graphile/graphile-search/src/ts-config.ts @@ -44,8 +44,12 @@ export function columnWithRequestTsConfig(column: SearchableColumn, condition: a }; } +// Each requested tag is followed by its primary language (fr-CA, fr), so a +// regional request still finds a translation stored under the bare language. export function requestLangCodes(langCodes: unknown): string[] { - return Array.isArray(langCodes) ? langCodes.filter((code): code is string => typeof code === 'string' && code !== '') : []; + if (!Array.isArray(langCodes)) return []; + const codes = langCodes.filter((code): code is string => typeof code === 'string' && code !== ''); + return [...new Set(codes.flatMap((code) => [code, code.split('-')[0]]))]; } export function conditionLangCodes(condition: any): string[] | undefined { From d20e2d4eef920204bfac6392ec5b514dad644ccc Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sun, 22 Nov 2026 00:23:33 +0000 Subject: [PATCH 4/4] feat(llm-env): default query embedding model to embeddinggemma-2:440m --- graphile/graphile-llm/src/embedder.ts | 2 +- packages/llm-env/README.md | 4 ++-- packages/llm-env/__tests__/llm-env.test.ts | 4 ++-- packages/llm-env/src/index.ts | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/graphile/graphile-llm/src/embedder.ts b/graphile/graphile-llm/src/embedder.ts index 403dba9f21..c92fab01eb 100644 --- a/graphile/graphile-llm/src/embedder.ts +++ b/graphile/graphile-llm/src/embedder.ts @@ -179,7 +179,7 @@ export function buildEmbedder(config: EmbedderConfig): EmbedderFunction { * AGENTIC_SERVER_URL - The gateway root; with it set, an embedder is always * available (the gateway resolves the upstream). * EMBEDDER_PROVIDER - Upstream dialect the gateway should use (default: 'ollama') - * EMBEDDER_MODEL - Model identifier (default: 'nomic-embed-text') + * EMBEDDER_MODEL - Model identifier (default: 'embeddinggemma-2:440m') * * Naming a provider or model without a gateway throws; naming nothing at all * leaves text fields disabled. diff --git a/packages/llm-env/README.md b/packages/llm-env/README.md index 53b1c4bb39..aeddddc8ed 100644 --- a/packages/llm-env/README.md +++ b/packages/llm-env/README.md @@ -19,7 +19,7 @@ const envVars = getEnvVars(process.env); // Merged: defaults → env → overrides const opts = getEnvOptions(); // opts.embedding.provider → EMBEDDER_PROVIDER || 'ollama' -// opts.embedding.model → EMBEDDER_MODEL || 'nomic-embed-text' +// opts.embedding.model → EMBEDDER_MODEL || 'embeddinggemma-2:440m' // opts.embedding.baseUrl → EMBEDDER_BASE_URL || 'http://localhost:11434' // opts.chat.provider → CHAT_PROVIDER || 'ollama' // opts.chat.model → CHAT_MODEL || 'llama3' @@ -34,7 +34,7 @@ const custom = getEnvOptions({ embedding: { model: 'mxbai-embed-large' } }); | Variable | Default | Description | |----------|---------|-------------| | `EMBEDDER_PROVIDER` | `ollama` | Embedding provider name | -| `EMBEDDER_MODEL` | `nomic-embed-text` | Embedding model identifier | +| `EMBEDDER_MODEL` | `embeddinggemma-2:440m` | Embedding model identifier | | `EMBEDDER_BASE_URL` | `http://localhost:11434` | Embedding provider URL | | `CHAT_PROVIDER` | `ollama` | Chat provider name | | `CHAT_MODEL` | `llama3` | Chat model identifier | diff --git a/packages/llm-env/__tests__/llm-env.test.ts b/packages/llm-env/__tests__/llm-env.test.ts index 901d124b14..673b49954e 100644 --- a/packages/llm-env/__tests__/llm-env.test.ts +++ b/packages/llm-env/__tests__/llm-env.test.ts @@ -113,14 +113,14 @@ describe('getLlmEnvOptions (backward compat)', () => { EMBEDDER_PROVIDER: 'openai', }); expect(result.embedding.provider).toBe('openai'); - expect(result.embedding.model).toBe('nomic-embed-text'); + expect(result.embedding.model).toBe('embeddinggemma-2:440m'); }); }); describe('llmDefaults', () => { it('exports default values', () => { expect(llmDefaults.embedding.provider).toBe('ollama'); - expect(llmDefaults.embedding.model).toBe('nomic-embed-text'); + expect(llmDefaults.embedding.model).toBe('embeddinggemma-2:440m'); expect(llmDefaults.embedding.baseUrl).toBe('http://localhost:11434'); expect(llmDefaults.chat.provider).toBe('ollama'); expect(llmDefaults.chat.model).toBe('llama3'); diff --git a/packages/llm-env/src/index.ts b/packages/llm-env/src/index.ts index bd43f8a636..b84ab5f3b4 100644 --- a/packages/llm-env/src/index.ts +++ b/packages/llm-env/src/index.ts @@ -12,7 +12,7 @@ * * Environment variables: * EMBEDDER_PROVIDER - Embedding provider name (default: 'ollama') - * EMBEDDER_MODEL - Embedding model (default: 'nomic-embed-text') + * EMBEDDER_MODEL - Embedding model (default: 'embeddinggemma-2:440m') * EMBEDDER_BASE_URL - Embedding provider URL (default: 'http://localhost:11434') * CHAT_PROVIDER - Chat provider name (default: 'ollama') * CHAT_MODEL - Chat model (default: 'llama3') @@ -54,7 +54,7 @@ export interface ResolvedLlmEnvOptions { export const llmDefaults: ResolvedLlmEnvOptions = { embedding: { provider: 'ollama', - model: 'nomic-embed-text', + model: 'embeddinggemma-2:440m', baseUrl: 'http://localhost:11434' }, chat: {