@zukhruf/retrieval 0.8.82 → 0.8.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +16 -1
  2. package/dist/postgres/bind.d.ts +6 -0
  3. package/dist/postgres/bind.d.ts.map +1 -0
  4. package/dist/postgres/bind.js +9 -0
  5. package/dist/postgres/bind.js.map +1 -0
  6. package/dist/postgres/identifier.d.ts +3 -0
  7. package/dist/postgres/identifier.d.ts.map +1 -0
  8. package/dist/postgres/identifier.js +3 -0
  9. package/dist/postgres/identifier.js.map +1 -0
  10. package/dist/postgres/passage-row.d.ts +12 -0
  11. package/dist/postgres/passage-row.d.ts.map +1 -0
  12. package/dist/postgres/passage-row.js +27 -0
  13. package/dist/postgres/passage-row.js.map +1 -0
  14. package/dist/postgres/pgvector-embedding-retriever.d.ts +21 -0
  15. package/dist/postgres/pgvector-embedding-retriever.d.ts.map +1 -0
  16. package/dist/postgres/pgvector-embedding-retriever.js +120 -0
  17. package/dist/postgres/pgvector-embedding-retriever.js.map +1 -0
  18. package/dist/postgres/pgvector-keyword-retriever.d.ts +25 -0
  19. package/dist/postgres/pgvector-keyword-retriever.d.ts.map +1 -0
  20. package/dist/postgres/pgvector-keyword-retriever.js +52 -0
  21. package/dist/postgres/pgvector-keyword-retriever.js.map +1 -0
  22. package/dist/postgres/postgres-passage-store.d.ts +23 -0
  23. package/dist/postgres/postgres-passage-store.d.ts.map +1 -0
  24. package/dist/postgres/postgres-passage-store.js +37 -0
  25. package/dist/postgres/postgres-passage-store.js.map +1 -0
  26. package/dist/postgres/postgres-session.d.ts +9 -0
  27. package/dist/postgres/postgres-session.d.ts.map +1 -0
  28. package/dist/postgres/postgres-session.js +2 -0
  29. package/dist/postgres/postgres-session.js.map +1 -0
  30. package/dist/postgres/where.d.ts +9 -0
  31. package/dist/postgres/where.d.ts.map +1 -0
  32. package/dist/postgres/where.js +61 -0
  33. package/dist/postgres/where.js.map +1 -0
  34. package/dist/postgres.d.ts +5 -0
  35. package/dist/postgres.d.ts.map +1 -0
  36. package/dist/postgres.js +4 -0
  37. package/dist/postgres.js.map +1 -0
  38. package/package.json +15 -5
package/README.md CHANGED
@@ -80,6 +80,20 @@ const keywords = new SqliteBM25Retriever({
80
80
  const results = await keywords.retrieve('rotate signing key');
81
81
  ```
82
82
 
83
+ On Postgres the query has to use the text search configuration of the index. `PgvectorKeywordRetriever` takes it as `configuration`, `'english'` when absent, as Haystack's `language`, LlamaIndex's `text_search_config` and LangChain's `tsv_lang` do. The configuration is a parameter of the statement, never SQL.
84
+
85
+ ```ts
86
+ // Planned API.
87
+ import { PgvectorKeywordRetriever } from '@zukhruf/retrieval/postgres';
88
+
89
+ const keywords = new PgvectorKeywordRetriever({
90
+ session,
91
+ passages: 'docs_passages',
92
+ index: 'keywords', // GENERATED ALWAYS AS (to_tsvector('simple', text)) STORED
93
+ configuration: 'simple', // keeps stop words and does not stem
94
+ });
95
+ ```
96
+
83
97
  ## Combine searches
84
98
 
85
99
  `FusionRetriever` asks each retriever for `rankWindowSize` passages, fuses the lists on `Passage.id` and gives the best `topK`. The default fusion is reciprocal rank fusion with k 60 and ranks from 1; each retriever has a weight of 1 ([ADR 0007](./docs/adr/0007-reciprocal-rank-fusion-is-the-default-fusion-with-k-60-and-ranks-from-1.md)).
@@ -428,7 +442,8 @@ class PgvectorKeywordRetriever implements Retriever {
428
442
  passages: string;
429
443
  index: string;
430
444
  operator?: 'AND' | 'OR';
431
- });
445
+ configuration?: string;
446
+ }); // 'AND', 'english'
432
447
  }
433
448
  class PostgresPassageStore implements PassageStore {
434
449
  constructor(options: { session: PostgresSession; passages: string });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Adds a value to the positional parameters of a statement and gives its
3
+ * placeholder, `$1` for the first, as the Postgres wire protocol numbers them.
4
+ */
5
+ export declare function bind(parameters: unknown[], value: unknown): string;
6
+ //# sourceMappingURL=bind.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bind.d.ts","sourceRoot":"","sources":["../../src/postgres/bind.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,CAGlE"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Adds a value to the positional parameters of a statement and gives its
3
+ * placeholder, `$1` for the first, as the Postgres wire protocol numbers them.
4
+ */
5
+ export function bind(parameters, value) {
6
+ parameters.push(value);
7
+ return `$${parameters.length}`;
8
+ }
9
+ //# sourceMappingURL=bind.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bind.js","sourceRoot":"","sources":["../../src/postgres/bind.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,UAAU,IAAI,CAAC,UAAqB,EAAE,KAAc;IACxD,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACvB,OAAO,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC;AACjC,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** A table or column name as one Postgres identifier: a `"` inside it is doubled, so the name never ends the identifier. */
2
+ export declare const identifier: (name: string) => string;
3
+ //# sourceMappingURL=identifier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifier.d.ts","sourceRoot":"","sources":["../../src/postgres/identifier.ts"],"names":[],"mappings":"AAAA,4HAA4H;AAC5H,eAAO,MAAM,UAAU,SAAU,MAAM,KAAG,MACP,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** A table or column name as one Postgres identifier: a `"` inside it is doubled, so the name never ends the identifier. */
2
+ export const identifier = (name) => `"${name.replaceAll('"', '""')}"`;
3
+ //# sourceMappingURL=identifier.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifier.js","sourceRoot":"","sources":["../../src/postgres/identifier.ts"],"names":[],"mappings":"AAAA,4HAA4H;AAC5H,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAY,EAAU,EAAE,CACjD,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { Passage } from '../passage.ts';
2
+ /**
3
+ * The SQL of one cell that holds the row of the passages `p` as JSON text,
4
+ * without its `tsvector` columns: a `tsvector` column is a keyword index of
5
+ * the passages, not metadata (ADR 0004). One cell keeps every column of the
6
+ * passages under its own name, whatever cells the search adds beside it, and
7
+ * gives the same values through every driver.
8
+ */
9
+ export declare function passageJson(parameters: unknown[], passages: string): string;
10
+ /** The passage of a cell that `passageJson` gave. A metadata column is any other column of the passages, under its own name. */
11
+ export declare function passage(cell: unknown): Passage;
12
+ //# sourceMappingURL=passage-row.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passage-row.d.ts","sourceRoot":"","sources":["../../src/postgres/passage-row.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAK7C;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,UAAU,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAG3E;AAED,gIAAgI;AAChI,wBAAgB,OAAO,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAa9C"}
@@ -0,0 +1,27 @@
1
+ import { bind } from './bind.js';
2
+ const passageColumns = new Set(['id', 'source', 'seq', 'start', 'end', 'text']);
3
+ /**
4
+ * The SQL of one cell that holds the row of the passages `p` as JSON text,
5
+ * without its `tsvector` columns: a `tsvector` column is a keyword index of
6
+ * the passages, not metadata (ADR 0004). One cell keeps every column of the
7
+ * passages under its own name, whatever cells the search adds beside it, and
8
+ * gives the same values through every driver.
9
+ */
10
+ export function passageJson(parameters, passages) {
11
+ const relation = bind(parameters, passages);
12
+ return `(to_jsonb(p) - ARRAY(SELECT a."attname"::text FROM pg_attribute a WHERE a."attrelid" = ${relation}::regclass AND a."atttypid" = 'tsvector'::regtype AND a."attnum" > 0 AND NOT a."attisdropped"))::text`;
13
+ }
14
+ /** The passage of a cell that `passageJson` gave. A metadata column is any other column of the passages, under its own name. */
15
+ export function passage(cell) {
16
+ const row = JSON.parse(String(cell));
17
+ return {
18
+ id: String(row['id']),
19
+ text: String(row['text']),
20
+ source: String(row['source']),
21
+ seq: Number(row['seq']),
22
+ start: Number(row['start']),
23
+ end: Number(row['end']),
24
+ metadata: Object.fromEntries(Object.entries(row).filter(([name]) => !passageColumns.has(name))),
25
+ };
26
+ }
27
+ //# sourceMappingURL=passage-row.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passage-row.js","sourceRoot":"","sources":["../../src/postgres/passage-row.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AAEhF;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,UAAqB,EAAE,QAAgB;IACjE,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAC5C,OAAO,0FAA0F,QAAQ,uGAAuG,CAAC;AACnN,CAAC;AAED,gIAAgI;AAChI,MAAM,UAAU,OAAO,CAAC,IAAa;IACnC,MAAM,GAAG,GAA4B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9D,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACrB,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACzB,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC7B,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACvB,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC3B,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACvB,QAAQ,EAAE,MAAM,CAAC,WAAW,CAC1B,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAClE;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,21 @@
1
+ import { type EmbeddingModel } from 'ai';
2
+ import type { BatchRetriever } from '../batch-retriever.ts';
3
+ import type { RetrieveOptions } from '../retrieve-options.ts';
4
+ import type { ScoredPassage } from '../scored-passage.ts';
5
+ import type { PostgresSession } from './postgres-session.ts';
6
+ /**
7
+ * Ranks the passages by the cosine similarity of their vectors to the query,
8
+ * with pgvector's `<=>` in the SQL of Postgres (ADR 0003).
9
+ */
10
+ export declare class PgvectorEmbeddingRetriever implements BatchRetriever {
11
+ #private;
12
+ constructor(options: {
13
+ readonly session: PostgresSession;
14
+ readonly passages: string;
15
+ readonly vectors: string;
16
+ readonly model: EmbeddingModel;
17
+ });
18
+ retrieve(query: string, options?: RetrieveOptions): Promise<ScoredPassage[]>;
19
+ retrieveMany(queries: readonly string[], options?: RetrieveOptions): Promise<ScoredPassage[][]>;
20
+ }
21
+ //# sourceMappingURL=pgvector-embedding-retriever.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgvector-embedding-retriever.d.ts","sourceRoot":"","sources":["../../src/postgres/pgvector-embedding-retriever.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAoB,MAAM,IAAI,CAAC;AAK3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAQ5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAI1D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAG7D;;;GAGG;AACH,qBAAa,0BAA2B,YAAW,cAAc;;IAM/D,YAAY,OAAO,EAAE;QACnB,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;QAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QACzB,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;KAChC,EAKA;IAEK,QAAQ,CACZ,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,aAAa,EAAE,CAAC,CAU1B;IAEK,YAAY,CAChB,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAU5B;CA8FF"}
@@ -0,0 +1,120 @@
1
+ import { embed, embedMany } from 'ai';
2
+ import { fromSql, toSql } from 'pgvector';
3
+ import { DimensionMismatchError } from '@zukhruf/vectors';
4
+ import { describe, modelName, parseModelIdentity, } from '../model-identity.js';
5
+ import { ModelMismatchError } from '../model-mismatch-error.js';
6
+ import { bind } from './bind.js';
7
+ import { identifier } from './identifier.js';
8
+ import { passage, passageJson } from './passage-row.js';
9
+ import { where } from './where.js';
10
+ /**
11
+ * Ranks the passages by the cosine similarity of their vectors to the query,
12
+ * with pgvector's `<=>` in the SQL of Postgres (ADR 0003).
13
+ */
14
+ export class PgvectorEmbeddingRetriever {
15
+ #session;
16
+ #passages;
17
+ #vectors;
18
+ #model;
19
+ constructor(options) {
20
+ this.#session = options.session;
21
+ this.#passages = identifier(options.passages);
22
+ this.#vectors = identifier(options.vectors);
23
+ this.#model = options.model;
24
+ }
25
+ async retrieve(query, options = {}) {
26
+ const [passages] = await this.#retrieve(1, options, async (abortSignal) => {
27
+ const { embedding } = await embed({
28
+ model: this.#model,
29
+ value: query,
30
+ ...(abortSignal === undefined ? {} : { abortSignal }),
31
+ });
32
+ return [embedding];
33
+ });
34
+ return passages ?? [];
35
+ }
36
+ async retrieveMany(queries, options = {}) {
37
+ if (queries.length === 0)
38
+ return [];
39
+ return this.#retrieve(queries.length, options, async (abortSignal) => {
40
+ const { embeddings } = await embedMany({
41
+ model: this.#model,
42
+ values: [...queries],
43
+ ...(abortSignal === undefined ? {} : { abortSignal }),
44
+ });
45
+ return embeddings;
46
+ });
47
+ }
48
+ async #retrieve(count, options, embedQueries) {
49
+ options.abortSignal?.throwIfAborted();
50
+ const query = modelName(this.#model);
51
+ const stored = await this.#storedIdentities();
52
+ const [first] = stored;
53
+ if (first === undefined)
54
+ return Array.from({ length: count }, () => []);
55
+ const sameModel = stored.filter(({ provider, modelId }) => provider === query.provider && modelId === query.modelId);
56
+ const [nearest] = sameModel;
57
+ if (nearest === undefined) {
58
+ throw new ModelMismatchError({ provider: first.provider, modelId: first.modelId }, query);
59
+ }
60
+ const vectors = await embedQueries(options.abortSignal);
61
+ options.abortSignal?.throwIfAborted();
62
+ const dimensions = vectors[0]?.length ?? 0;
63
+ const identity = sameModel.find((candidate) => candidate.dimensions === dimensions);
64
+ if (identity === undefined) {
65
+ throw new DimensionMismatchError(nearest.dimensions, dimensions);
66
+ }
67
+ return this.#search(vectors, identity, options);
68
+ }
69
+ /** The identities of the stored vectors, in the byte order of their text, as SQLite orders text. */
70
+ async #storedIdentities() {
71
+ const rows = await this.#session.query(`SELECT DISTINCT "model" COLLATE "C" AS "model" FROM ${this.#vectors} ORDER BY 1`, []);
72
+ return rows.map(({ model }) => parseModelIdentity(String(model)));
73
+ }
74
+ /**
75
+ * One SQL query for every query vector: each query runs its own ordered,
76
+ * limited scan through `CROSS JOIN LATERAL`, the form that pgvector's index
77
+ * serves for each row of the queries. It compares a query only with the
78
+ * vectors of its own model identity, and breaks a tie of distance by the
79
+ * passage id, as `VectorSearch` of `@zukhruf/embeddings` does.
80
+ */
81
+ async #search(vectors, identity, options) {
82
+ const parameters = [];
83
+ const queries = vectors
84
+ .map((vector, index) => `(${index}, ${bind(parameters, toSql([...vector]))}::vector)`)
85
+ .join(', ');
86
+ const model = bind(parameters, describe(identity));
87
+ const row = passageJson(parameters, this.#passages);
88
+ const filter = where(options.filter, parameters);
89
+ const topK = bind(parameters, options.topK ?? 10);
90
+ const rows = await this.#session.query(`
91
+ WITH "queries" ("query", "vector") AS (VALUES ${queries})
92
+ SELECT q."query", r."distance", r."vector", r."passage"
93
+ FROM "queries" q CROSS JOIN LATERAL (
94
+ SELECT v."vector" <=> q."vector" AS "distance", v."vector"::text AS "vector", ${row} AS "passage", p."id"::text COLLATE "C" AS "id"
95
+ FROM ${this.#vectors} v JOIN ${this.#passages} p ON p."id" = v."id"
96
+ WHERE v."model" = ${model} AND ${filter}
97
+ ORDER BY v."vector" <=> q."vector", p."id"::text COLLATE "C"
98
+ LIMIT ${topK}
99
+ ) r
100
+ ORDER BY q."query", r."distance", r."id"`, parameters);
101
+ const lists = vectors.map(() => []);
102
+ for (const cells of rows) {
103
+ lists[Number(cells['query'])]?.push({
104
+ passage: passage(cells['passage']),
105
+ score: 1 - Number(cells['distance']),
106
+ ...(options.includeVectors === true
107
+ ? { vector: storedVector(cells['vector']) }
108
+ : {}),
109
+ });
110
+ }
111
+ return lists;
112
+ }
113
+ }
114
+ function storedVector(cell) {
115
+ const vector = fromSql(String(cell));
116
+ if (Array.isArray(vector))
117
+ return vector;
118
+ throw new TypeError(`A stored vector is a pgvector vector, not ${String(cell)}`);
119
+ }
120
+ //# sourceMappingURL=pgvector-embedding-retriever.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgvector-embedding-retriever.js","sourceRoot":"","sources":["../../src/postgres/pgvector-embedding-retriever.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAE1C,OAAO,EAAE,sB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AAC,CAAC,EAAE;oBAC3C,CAAC,CAAC,EAAE,CAAC;aACR,CAAC,CAAC;QACL,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAED,SAAS,YAAY,CAAC,IAAa;IACjC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IACrC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC;IACzC,MAAM,IAAI,SAAS,CACjB,6CAA6C,MAAM,CAAC,IAAI,CAAC,EAAE,CAC5D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { RetrieveOptions } from '../retrieve-options.ts';
2
+ import type { Retriever } from '../retriever.ts';
3
+ import type { ScoredPassage } from '../scored-passage.ts';
4
+ import type { PostgresSession } from './postgres-session.ts';
5
+ /**
6
+ * Ranks the passages by Postgres full-text search over the keyword index
7
+ * that elt writes: a `tsvector` column of the passages, `to_tsvector(configuration,
8
+ * text)`, with a GIN index (ADR 0004). The score is `ts_rank_cd`, which is
9
+ * higher for a better match (ADR 0005).
10
+ */
11
+ export declare class PgvectorKeywordRetriever implements Retriever {
12
+ #private;
13
+ constructor(options: {
14
+ readonly session: PostgresSession;
15
+ readonly passages: string;
16
+ /** The `tsvector` column of the passages. */
17
+ readonly index: string;
18
+ /** How the words of the query join: 'AND', as `plainto_tsquery` joins them, when absent. */
19
+ readonly operator?: 'AND' | 'OR';
20
+ /** The text search configuration of the index, 'english' when absent. */
21
+ readonly configuration?: string;
22
+ });
23
+ retrieve(query: string, options?: RetrieveOptions): Promise<ScoredPassage[]>;
24
+ }
25
+ //# sourceMappingURL=pgvector-keyword-retriever.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgvector-keyword-retriever.d.ts","sourceRoot":"","sources":["../../src/postgres/pgvector-keyword-retriever.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAI1D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAG7D;;;;;GAKG;AACH,qBAAa,wBAAyB,YAAW,SAAS;;IAOxD,YAAY,OAAO,EAAE;QACnB,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;QAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,6CAA6C;QAC7C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QACvB,4FAA4F;QAC5F,QAAQ,CAAC,QAAQ,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;QACjC,yEAAyE;QACzE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;KACjC,EAMA;IAEK,QAAQ,CACZ,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,aAAa,EAAE,CAAC,CA+B1B;CACF"}
@@ -0,0 +1,52 @@
1
+ import { bind } from './bind.js';
2
+ import { identifier } from './identifier.js';
3
+ import { passage, passageJson } from './passage-row.js';
4
+ import { where } from './where.js';
5
+ /**
6
+ * Ranks the passages by Postgres full-text search over the keyword index
7
+ * that elt writes: a `tsvector` column of the passages, `to_tsvector(configuration,
8
+ * text)`, with a GIN index (ADR 0004). The score is `ts_rank_cd`, which is
9
+ * higher for a better match (ADR 0005).
10
+ */
11
+ export class PgvectorKeywordRetriever {
12
+ #session;
13
+ #passages;
14
+ #index;
15
+ #operator;
16
+ #configuration;
17
+ constructor(options) {
18
+ this.#session = options.session;
19
+ this.#passages = identifier(options.passages);
20
+ this.#index = identifier(options.index);
21
+ this.#operator = options.operator ?? 'AND';
22
+ this.#configuration = options.configuration ?? 'english';
23
+ }
24
+ async retrieve(query, options = {}) {
25
+ options.abortSignal?.throwIfAborted();
26
+ const words = query.split(/\s+/).filter((word) => word !== '');
27
+ if (words.length === 0)
28
+ return [];
29
+ const parameters = [];
30
+ // The configuration is a parameter too, so its text is never SQL.
31
+ const configuration = `${bind(parameters, this.#configuration)}::regconfig`;
32
+ // Each word is its own plainto_tsquery, which reads it as plain text:
33
+ // `&`, `|`, `!`, `<->`, `:*` and quotes stay text, never operators.
34
+ const tsquery = words
35
+ .map((word) => `plainto_tsquery(${configuration}, ${bind(parameters, word)})`)
36
+ .join(this.#operator === 'AND' ? ' && ' : ' || ');
37
+ const row = passageJson(parameters, this.#passages);
38
+ const filter = where(options.filter, parameters);
39
+ const topK = bind(parameters, options.topK ?? 10);
40
+ const rows = await this.#session.query(`
41
+ SELECT ts_rank_cd(p.${this.#index}, q."query") AS "score", ${row} AS "passage"
42
+ FROM ${this.#passages} p CROSS JOIN (SELECT ${tsquery} AS "query") q
43
+ WHERE p.${this.#index} @@ q."query" AND ${filter}
44
+ ORDER BY 1 DESC, p."id"::text COLLATE "C"
45
+ LIMIT ${topK}`, parameters);
46
+ return rows.map((cells) => ({
47
+ passage: passage(cells['passage']),
48
+ score: Number(cells['score']),
49
+ }));
50
+ }
51
+ }
52
+ //# sourceMappingURL=pgvector-keyword-retriever.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pgvector-keyword-retriever.js","sourceRoot":"","sources":["../../src/postgres/pgvector-keyword-retriever.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAExD,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,OAAO,wBAAwB;IAC1B,QAAQ,CAAkB;IAC1B,SAAS,CAAS;IAClB,MAAM,CAAS;IACf,SAAS,CAAe;IACxB,cAAc,CAAS;IAEhC,YAAY,OASX;QACC,I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AAC;QACjD,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;QAClD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,CACpC;4BACsB,IAAI,CAAC,MAAM,4BAA4B,GAAG;aACzD,IAAI,CAAC,SAAS,yBAAyB,OAAO;gBAC3C,IAAI,CAAC,MAAM,qBAAqB,MAAM;;cAExC,IAAI,EAAE,EACd,UAAU,CACX,CAAC;QACF,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAC1B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;YAClC,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;SAC9B,CAAC,CAAC,CAAC;IACN,CAAC;CACF"}
@@ -0,0 +1,23 @@
1
+ import type { PassageStore } from '../passage-store.ts';
2
+ import type { Passage } from '../passage.ts';
3
+ import type { PostgresSession } from './postgres-session.ts';
4
+ /** Reads the passages of the passage contract in Postgres by id, and the neighbours of a passage in its source. */
5
+ export declare class PostgresPassageStore implements PassageStore {
6
+ #private;
7
+ constructor(options: {
8
+ readonly session: PostgresSession;
9
+ readonly passages: string;
10
+ });
11
+ get(ids: readonly string[]): Promise<ReadonlyMap<string, Passage>>;
12
+ /**
13
+ * The passages of the source from `seq - windowSize` to `seq + windowSize`,
14
+ * the passage itself among them, in the order of `seq`, as Haystack's
15
+ * `SentenceWindowRetriever` reads its window.
16
+ */
17
+ neighbours(options: {
18
+ readonly source: string;
19
+ readonly seq: number;
20
+ readonly windowSize: number;
21
+ }): Promise<Passage[]>;
22
+ }
23
+ //# sourceMappingURL=postgres-passage-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-passage-store.d.ts","sourceRoot":"","sources":["../../src/postgres/postgres-passage-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAI7C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,mHAAmH;AACnH,qBAAa,oBAAqB,YAAW,YAAY;;IAIvD,YAAY,OAAO,EAAE;QACnB,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;QAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;KAC3B,EAGA;IAEK,GAAG,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAcvE;IAED;;;;OAIG;IACG,UAAU,CAAC,OAAO,EAAE;QACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;KAC7B,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAWrB;CACF"}
@@ -0,0 +1,37 @@
1
+ import { bind } from './bind.js';
2
+ import { identifier } from './identifier.js';
3
+ import { passage, passageJson } from './passage-row.js';
4
+ /** Reads the passages of the passage contract in Postgres by id, and the neighbours of a passage in its source. */
5
+ export class PostgresPassageStore {
6
+ #session;
7
+ #passages;
8
+ constructor(options) {
9
+ this.#session = options.session;
10
+ this.#passages = identifier(options.passages);
11
+ }
12
+ async get(ids) {
13
+ const parameters = [];
14
+ const row = passageJson(parameters, this.#passages);
15
+ const list = bind(parameters, JSON.stringify(ids));
16
+ const rows = await this.#session.query(`SELECT ${row} AS "passage" FROM ${this.#passages} p WHERE p."id"::text IN (SELECT jsonb_array_elements_text(${list}::jsonb))`, parameters);
17
+ return new Map(rows.map((cells) => {
18
+ const found = passage(cells['passage']);
19
+ return [found.id, found];
20
+ }));
21
+ }
22
+ /**
23
+ * The passages of the source from `seq - windowSize` to `seq + windowSize`,
24
+ * the passage itself among them, in the order of `seq`, as Haystack's
25
+ * `SentenceWindowRetriever` reads its window.
26
+ */
27
+ async neighbours(options) {
28
+ const parameters = [];
29
+ const row = passageJson(parameters, this.#passages);
30
+ const source = bind(parameters, options.source);
31
+ const from = bind(parameters, options.seq - options.windowSize);
32
+ const to = bind(parameters, options.seq + options.windowSize);
33
+ const rows = await this.#session.query(`SELECT ${row} AS "passage" FROM ${this.#passages} p WHERE p."source" = ${source} AND p."seq" BETWEEN ${from} AND ${to} ORDER BY p."seq", p."id"::text COLLATE "C"`, parameters);
34
+ return rows.map((cells) => passage(cells['passage']));
35
+ }
36
+ }
37
+ //# sourceMappingURL=postgres-passage-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-passage-store.js","sourceRoot":"","sources":["../../src/postgres/postgres-passage-store.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGxD,mHAAmH;AACnH,MAAM,OAAO,oBAAoB;IACtB,QAAQ,CAAkB;IAC1B,SAAS,CAAS;IAE3B,YAAY,OAGX;QACC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC;QAChC,IAAI,CAAC,SAAS,GAAG,UAAU,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAChD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAsB;QAC9B,MAAM,UAAU,GAAc,EAAE,CAAC;QACjC,MAAM,GAAG,GAAG,WAAW,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QACpD,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;QACnD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,CACpC,UAAU,GAAG,sBAAsB,IAAI,CAAC,SAAS,8DAA8D,IAAI,WAAW,EAC9H,UAAU,CACX,CAAC;QACF,OAAO,IAAI,GAAG,CACZ,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;YACjB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;YACxC,OAAO,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QAC3B,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,UAAU,CAAC,OAIhB;QACC,MAAM,UAAU,GAAc,EAAE,CAAC;QACjC,MAAM,GAAG,GAAG,WAAW,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QACpD,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QAChD,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;QAChE,MAAM,EAAE,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;QAC9D,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,CACpC,UAAU,GAAG,sBAAsB,IAAI,CAAC,SAAS,yBAAyB,MAAM,wBAAwB,IAAI,QAAQ,EAAE,6CAA6C,EACnK,UAAU,CACX,CAAC;QACF,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IACxD,CAAC;CACF"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The port through which the Postgres retrievers send their SQL: the host
3
+ * writes it over its own driver. The parameters are positional, `$1` for the
4
+ * first, and the promise gives the rows of the result.
5
+ */
6
+ export type PostgresSession = {
7
+ query(sql: string, parameters: readonly unknown[]): Promise<readonly Record<string, unknown>[]>;
8
+ };
9
+ //# sourceMappingURL=postgres-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-session.d.ts","sourceRoot":"","sources":["../../src/postgres/postgres-session.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,CACH,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,SAAS,OAAO,EAAE,GAC7B,OAAO,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;CAChD,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=postgres-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-session.js","sourceRoot":"","sources":["../../src/postgres/postgres-session.ts"],"names":[],"mappings":""}
@@ -0,0 +1,9 @@
1
+ import type { Filter } from '../filter.ts';
2
+ /**
3
+ * The filter as a SQL condition on the passages, aliased `p`, with each value
4
+ * a positional parameter (ADR 0009). `==` and `!=` compare NULL as a value
5
+ * and `not in` keeps a NULL, as Haystack's pgvector store writes them
6
+ * (`IS NOT DISTINCT FROM`, `IS DISTINCT FROM`, `IS NULL OR NOT IN`).
7
+ */
8
+ export declare function where(filter: Filter | undefined, parameters: unknown[]): string;
9
+ //# sourceMappingURL=where.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"where.d.ts","sourceRoot":"","sources":["../../src/postgres/where.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAO3C;;;;;GAKG;AACH,wBAAgB,KAAK,CACnB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,UAAU,EAAE,OAAO,EAAE,GACpB,MAAM,CAER"}
@@ -0,0 +1,61 @@
1
+ import { bind } from './bind.js';
2
+ import { identifier } from './identifier.js';
3
+ const passageFields = new Set(['source', 'seq', 'start', 'end']);
4
+ const metadata = 'metadata.';
5
+ /**
6
+ * The filter as a SQL condition on the passages, aliased `p`, with each value
7
+ * a positional parameter (ADR 0009). `==` and `!=` compare NULL as a value
8
+ * and `not in` keeps a NULL, as Haystack's pgvector store writes them
9
+ * (`IS NOT DISTINCT FROM`, `IS DISTINCT FROM`, `IS NULL OR NOT IN`).
10
+ */
11
+ export function where(filter, parameters) {
12
+ return filter === undefined ? 'TRUE' : condition(filter, parameters);
13
+ }
14
+ function condition(filter, parameters) {
15
+ if ('conditions' in filter) {
16
+ const parts = filter.conditions.map((part) => condition(part, parameters));
17
+ if (filter.operator === 'OR')
18
+ return parts.length === 0 ? 'FALSE' : `(${parts.join(' OR ')})`;
19
+ const all = parts.length === 0 ? 'TRUE' : `(${parts.join(' AND ')})`;
20
+ return filter.operator === 'NOT' ? `(NOT ${all})` : all;
21
+ }
22
+ const field = column(filter.field);
23
+ const { operator, value } = filter;
24
+ if (operator === 'in' || operator === 'not in') {
25
+ if (!Array.isArray(value)) {
26
+ throw new TypeError(`The value of an ${JSON.stringify(operator)} filter on ${filter.field} is an array, not ${JSON.stringify(value)}`);
27
+ }
28
+ // Postgres refuses an empty list, `IN ()`; no value is in it.
29
+ if (value.length === 0)
30
+ return operator === 'in' ? 'FALSE' : 'TRUE';
31
+ const list = `(${value.map((item) => bind(parameters, parameter(item))).join(', ')})`;
32
+ return operator === 'in'
33
+ ? `${field} IN ${list}`
34
+ : `(${field} IS NULL OR ${field} NOT IN ${list})`;
35
+ }
36
+ const placeholder = bind(parameters, parameter(value));
37
+ if (operator === '==')
38
+ return `${field} IS NOT DISTINCT FROM ${placeholder}`;
39
+ if (operator === '!=')
40
+ return `${field} IS DISTINCT FROM ${placeholder}`;
41
+ return `${field} ${operator} ${placeholder}`;
42
+ }
43
+ function column(field) {
44
+ if (passageFields.has(field))
45
+ return `p.${identifier(field)}`;
46
+ if (field.startsWith(metadata))
47
+ return `p.${identifier(field.slice(metadata.length))}`;
48
+ throw new TypeError(`The filter field ${JSON.stringify(field)} is not source, seq, start, end or metadata.<column>`);
49
+ }
50
+ // Postgres has a boolean, so a boolean value compares with a boolean column.
51
+ function parameter(value) {
52
+ if (value === null ||
53
+ typeof value === 'string' ||
54
+ typeof value === 'number' ||
55
+ typeof value === 'bigint' ||
56
+ typeof value === 'boolean') {
57
+ return value;
58
+ }
59
+ throw new TypeError(`A filter value is a string, a number, a bigint, a boolean or null, not ${String(value)}`);
60
+ }
61
+ //# sourceMappingURL=where.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"where.js","sourceRoot":"","sources":["../../src/postgres/where.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,MAAM,QAAQ,GAAG,WAAW,CAAC;AAE7B;;;;;GAKG;AACH,MAAM,UAAU,KAAK,CACnB,MAA0B,EAC1B,UAAqB;IAErB,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AACvE,CAAC;AAED,SAAS,SAAS,CAAC,MAAc,EAAE,UAAqB;IACtD,IAAI,YAAY,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC;QAC3E,IAAI,MAAM,CAAC,QAAQ,KAAK,IAAI;YAC1B,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CA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,CAAC;IACD,MAAM,WAAW,GAAG,IAAI,CAAC,UAAU,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;IACvD,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,GAAG,KAAK,yBAAyB,WAAW,EAAE,CAAC;IAC7E,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,GAAG,KAAK,qBAAqB,WAAW,EAAE,CAAC;IACzE,OAAO,GAAG,KAAK,IAAI,QAAQ,IAAI,WAAW,EAAE,CAAC;AAC/C,CAAC;AAED,SAAS,MAAM,CAAC,KAAa;IAC3B,IAAI,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;IAC9D,IAAI,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC;QAC5B,OAAO,KAAK,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;IACzD,MAAM,IAAI,SAAS,CACjB,oBAAoB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,sDAAsD,CAChG,CAAC;AACJ,CAAC;AAED,6EAA6E;AAC7E,SAAS,SAAS,CAAC,KAAc;IAC/B,IACE,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAO,KAAK,KAAK,SAAS,EAC1B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,IAAI,SAAS,CACjB,0EAA0E,MAAM,CAAC,KAAK,CAAC,EAAE,CAC1F,CAAC;AACJ,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { PgvectorEmbeddingRetriever } from './postgres/pgvector-embedding-retriever.ts';
2
+ export { PgvectorKeywordRetriever } from './postgres/pgvector-keyword-retriever.ts';
3
+ export { PostgresPassageStore } from './postgres/postgres-passage-store.ts';
4
+ export type { PostgresSession } from './postgres/postgres-session.ts';
5
+ //# sourceMappingURL=postgres.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,4CAA4C,CAAC;AACxF,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,YAAY,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { PgvectorEmbeddingRetriever } from './postgres/pgvector-embedding-retriever.js';
2
+ export { PgvectorKeywordRetriever } from './postgres/pgvector-keyword-retriever.js';
3
+ export { PostgresPassageStore } from './postgres/postgres-passage-store.js';
4
+ //# sourceMappingURL=postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,4CAA4C,CAAC;AACxF,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zukhruf/retrieval",
3
- "version": "0.8.82",
3
+ "version": "0.8.84",
4
4
  "description": "The query side of RAG: retrievers that search a passage table by meaning or keywords in SQLite, Postgres or SQL Server, fuse lists, rerank and post-process, and give the best passages first with a score that is higher for a better passage.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -39,6 +39,12 @@
39
39
  "types": "./dist/sqlite.d.ts",
40
40
  "import": "./dist/sqlite.js",
41
41
  "default": "./dist/sqlite.js"
42
+ },
43
+ "./postgres": {
44
+ "@zukhruf/source": "./src/postgres.ts",
45
+ "types": "./dist/postgres.d.ts",
46
+ "import": "./dist/postgres.js",
47
+ "default": "./dist/postgres.js"
42
48
  }
43
49
  },
44
50
  "files": [
@@ -51,11 +57,15 @@
51
57
  "access": "public"
52
58
  },
53
59
  "dependencies": {
54
- "@zukhruf/statistics": "^0.8.82",
55
- "@zukhruf/vectors": "^0.8.82",
56
- "ai": "^7.0.179"
60
+ "@zukhruf/statistics": "^0.8.84",
61
+ "@zukhruf/vectors": "^0.8.84",
62
+ "ai": "^7.0.179",
63
+ "pgvector": "^0.3.1"
57
64
  },
58
65
  "devDependencies": {
59
- "@zukhruf/sqlite-open": "^0.8.82"
66
+ "@types/pg": "^8.23.1",
67
+ "@zukhruf/sqlite-open": "^0.8.84",
68
+ "@zukhruf/testing": "^0.8.84",
69
+ "pg": "^8.23.1"
60
70
  }
61
71
  }