@molecule/api-ai-rag-qa 1.0.0
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.
- package/LICENSE +115 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/chunker.d.ts +10 -0
- package/dist/chunker.d.ts.map +1 -0
- package/dist/chunker.js +33 -0
- package/dist/index.d.ts +57 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +56 -0
- package/dist/pipeline.d.ts +43 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/pipeline.js +112 -0
- package/dist/types.d.ts +30 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-ai-rag-qa` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-ai-rag-qa is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ChunkOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Split a long text into overlapping chunks suitable for embedding.
|
|
4
|
+
*
|
|
5
|
+
* Tries paragraph boundaries first, then sentence boundaries, then
|
|
6
|
+
* character boundaries. Each chunk includes `overlap` characters from
|
|
7
|
+
* the prior chunk to preserve context across boundaries.
|
|
8
|
+
*/
|
|
9
|
+
export declare function chunkText(text: string, opts?: ChunkOptions): string[];
|
|
10
|
+
//# sourceMappingURL=chunker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunker.d.ts","sourceRoot":"","sources":["../src/chunker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE9C;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,YAAiB,GAAG,MAAM,EAAE,CA0BzE"}
|
package/dist/chunker.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Split a long text into overlapping chunks suitable for embedding.
|
|
3
|
+
*
|
|
4
|
+
* Tries paragraph boundaries first, then sentence boundaries, then
|
|
5
|
+
* character boundaries. Each chunk includes `overlap` characters from
|
|
6
|
+
* the prior chunk to preserve context across boundaries.
|
|
7
|
+
*/
|
|
8
|
+
export function chunkText(text, opts = {}) {
|
|
9
|
+
const maxChars = opts.maxChars ?? 1000;
|
|
10
|
+
const overlap = opts.overlap ?? 200;
|
|
11
|
+
const preferParagraphs = opts.preferParagraphs !== false;
|
|
12
|
+
if (text.length <= maxChars)
|
|
13
|
+
return [text];
|
|
14
|
+
const out = [];
|
|
15
|
+
let cursor = 0;
|
|
16
|
+
while (cursor < text.length) {
|
|
17
|
+
let end = Math.min(cursor + maxChars, text.length);
|
|
18
|
+
if (end < text.length) {
|
|
19
|
+
// Try to break at paragraph
|
|
20
|
+
const paraEnd = preferParagraphs ? text.lastIndexOf('\n\n', end) : -1;
|
|
21
|
+
const sentenceEnd = Math.max(text.lastIndexOf('. ', end), text.lastIndexOf('! ', end), text.lastIndexOf('? ', end));
|
|
22
|
+
if (paraEnd > cursor + maxChars / 2)
|
|
23
|
+
end = paraEnd;
|
|
24
|
+
else if (sentenceEnd > cursor + maxChars / 2)
|
|
25
|
+
end = sentenceEnd + 1;
|
|
26
|
+
}
|
|
27
|
+
out.push(text.slice(cursor, end).trim());
|
|
28
|
+
if (end >= text.length)
|
|
29
|
+
break;
|
|
30
|
+
cursor = Math.max(end - overlap, cursor + 1);
|
|
31
|
+
}
|
|
32
|
+
return out.filter((c) => c.length > 0);
|
|
33
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-ai-rag-qa` — RAG (retrieval-augmented generation) Q&A
|
|
3
|
+
* pipeline. Chunk source documents, embed them, store in the vector
|
|
4
|
+
* bond, then answer questions grounded in retrieved sources.
|
|
5
|
+
*
|
|
6
|
+
* Composes the existing `@molecule/api-ai`, `@molecule/api-ai-embeddings`,
|
|
7
|
+
* and `@molecule/api-ai-vector-store` bonds — works with any provider
|
|
8
|
+
* mix (Anthropic + OpenAI embeddings + pgvector, etc.).
|
|
9
|
+
*
|
|
10
|
+
* Extracted from the rag-knowledge-base flagship.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { indexDocument, answerQuestion } from '@molecule/api-ai-rag-qa'
|
|
15
|
+
*
|
|
16
|
+
* await indexDocument({
|
|
17
|
+
* collection: 'docs',
|
|
18
|
+
* documentId: 'getting-started',
|
|
19
|
+
* text: longMarkdown,
|
|
20
|
+
* metadata: { source: 'README.md' },
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* const { answer, sources } = await answerQuestion({
|
|
24
|
+
* collection: 'docs',
|
|
25
|
+
* question: 'How do I configure auth?',
|
|
26
|
+
* })
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* Wiring — the three composed cores use TWO different mechanisms:
|
|
31
|
+
* - `@molecule/api-ai-embeddings` and `@molecule/api-ai-vector-store` each
|
|
32
|
+
* keep their OWN singleton: wire each with THAT core's `setProvider(...)`
|
|
33
|
+
* (e.g. `setProvider(provider)` from `@molecule/api-ai-embeddings-local`).
|
|
34
|
+
* A generic `bond('ai-embeddings', …)` / `bond('ai-vector-store', …)` call
|
|
35
|
+
* is never seen by those cores — `indexDocument()` / `retrieve()` then throw
|
|
36
|
+
* "provider not configured" even though the bond call appeared to succeed.
|
|
37
|
+
* - `@molecule/api-ai` (used by `answerQuestion`) IS registry-based:
|
|
38
|
+
* `bond('ai', provider)` or named providers work.
|
|
39
|
+
*
|
|
40
|
+
* Vectors are only comparable within ONE embeddings model + dimension:
|
|
41
|
+
* after switching embeddings providers/models, re-index the collection —
|
|
42
|
+
* `retrieve()` against vectors from a different model returns meaningless
|
|
43
|
+
* similarity scores, not an error.
|
|
44
|
+
*
|
|
45
|
+
* `deleteDocument()` deletes constructed chunk ids (`<documentId>::0..N-1`,
|
|
46
|
+
* default `maxChunks: 1000`) — pass a larger `maxChunks` if a document
|
|
47
|
+
* chunked into more. `answerQuestion()` with zero retrieval hits resolves
|
|
48
|
+
* with the literal "I don't know based on the provided sources." and
|
|
49
|
+
* `sources: []` — no model call is made.
|
|
50
|
+
*
|
|
51
|
+
* @module
|
|
52
|
+
*/
|
|
53
|
+
export * from './browser-guard.js';
|
|
54
|
+
export * from './chunker.js';
|
|
55
|
+
export * from './pipeline.js';
|
|
56
|
+
export * from './types.js';
|
|
57
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,cAAc,CAAA;AAC5B,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-ai-rag-qa` — RAG (retrieval-augmented generation) Q&A
|
|
3
|
+
* pipeline. Chunk source documents, embed them, store in the vector
|
|
4
|
+
* bond, then answer questions grounded in retrieved sources.
|
|
5
|
+
*
|
|
6
|
+
* Composes the existing `@molecule/api-ai`, `@molecule/api-ai-embeddings`,
|
|
7
|
+
* and `@molecule/api-ai-vector-store` bonds — works with any provider
|
|
8
|
+
* mix (Anthropic + OpenAI embeddings + pgvector, etc.).
|
|
9
|
+
*
|
|
10
|
+
* Extracted from the rag-knowledge-base flagship.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { indexDocument, answerQuestion } from '@molecule/api-ai-rag-qa'
|
|
15
|
+
*
|
|
16
|
+
* await indexDocument({
|
|
17
|
+
* collection: 'docs',
|
|
18
|
+
* documentId: 'getting-started',
|
|
19
|
+
* text: longMarkdown,
|
|
20
|
+
* metadata: { source: 'README.md' },
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* const { answer, sources } = await answerQuestion({
|
|
24
|
+
* collection: 'docs',
|
|
25
|
+
* question: 'How do I configure auth?',
|
|
26
|
+
* })
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* Wiring — the three composed cores use TWO different mechanisms:
|
|
31
|
+
* - `@molecule/api-ai-embeddings` and `@molecule/api-ai-vector-store` each
|
|
32
|
+
* keep their OWN singleton: wire each with THAT core's `setProvider(...)`
|
|
33
|
+
* (e.g. `setProvider(provider)` from `@molecule/api-ai-embeddings-local`).
|
|
34
|
+
* A generic `bond('ai-embeddings', …)` / `bond('ai-vector-store', …)` call
|
|
35
|
+
* is never seen by those cores — `indexDocument()` / `retrieve()` then throw
|
|
36
|
+
* "provider not configured" even though the bond call appeared to succeed.
|
|
37
|
+
* - `@molecule/api-ai` (used by `answerQuestion`) IS registry-based:
|
|
38
|
+
* `bond('ai', provider)` or named providers work.
|
|
39
|
+
*
|
|
40
|
+
* Vectors are only comparable within ONE embeddings model + dimension:
|
|
41
|
+
* after switching embeddings providers/models, re-index the collection —
|
|
42
|
+
* `retrieve()` against vectors from a different model returns meaningless
|
|
43
|
+
* similarity scores, not an error.
|
|
44
|
+
*
|
|
45
|
+
* `deleteDocument()` deletes constructed chunk ids (`<documentId>::0..N-1`,
|
|
46
|
+
* default `maxChunks: 1000`) — pass a larger `maxChunks` if a document
|
|
47
|
+
* chunked into more. `answerQuestion()` with zero retrieval hits resolves
|
|
48
|
+
* with the literal "I don't know based on the provided sources." and
|
|
49
|
+
* `sources: []` — no model call is made.
|
|
50
|
+
*
|
|
51
|
+
* @module
|
|
52
|
+
*/
|
|
53
|
+
export * from './browser-guard.js';
|
|
54
|
+
export * from './chunker.js';
|
|
55
|
+
export * from './pipeline.js';
|
|
56
|
+
export * from './types.js';
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RAG pipeline — index chunks via vector bond + answer questions
|
|
3
|
+
* grounded in retrieved sources.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { type MetadataFilter } from '@molecule/api-ai-vector-store';
|
|
8
|
+
import type { ChunkOptions, GroundedAnswer, RetrievalHit } from './types.js';
|
|
9
|
+
/** Index a long document by chunking, embedding, and upserting to the vector store. */
|
|
10
|
+
export declare function indexDocument(opts: {
|
|
11
|
+
collection: string;
|
|
12
|
+
documentId: string;
|
|
13
|
+
text: string;
|
|
14
|
+
metadata?: Record<string, unknown>;
|
|
15
|
+
chunking?: ChunkOptions;
|
|
16
|
+
}): Promise<string[]>;
|
|
17
|
+
/** Delete all chunks for a previously-indexed document. */
|
|
18
|
+
export declare function deleteDocument(opts: {
|
|
19
|
+
collection: string;
|
|
20
|
+
documentId: string;
|
|
21
|
+
maxChunks?: number;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
/** Retrieve top-K most similar chunks for a query. */
|
|
24
|
+
export declare function retrieve(opts: {
|
|
25
|
+
collection: string;
|
|
26
|
+
query: string;
|
|
27
|
+
topK?: number;
|
|
28
|
+
filter?: MetadataFilter[];
|
|
29
|
+
}): Promise<RetrievalHit[]>;
|
|
30
|
+
/**
|
|
31
|
+
* Full RAG round-trip: retrieve top-K chunks, format them as numbered
|
|
32
|
+
* sources, and ground a generated answer in them.
|
|
33
|
+
*/
|
|
34
|
+
export declare function answerQuestion(opts: {
|
|
35
|
+
collection: string;
|
|
36
|
+
question: string;
|
|
37
|
+
topK?: number;
|
|
38
|
+
filter?: MetadataFilter[];
|
|
39
|
+
promptTemplate?: string;
|
|
40
|
+
model?: string;
|
|
41
|
+
temperature?: number;
|
|
42
|
+
}): Promise<GroundedAnswer>;
|
|
43
|
+
//# sourceMappingURL=pipeline.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.d.ts","sourceRoot":"","sources":["../src/pipeline.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EACL,KAAK,cAAc,EAEpB,MAAM,+BAA+B,CAAA;AAGtC,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE5E,uFAAuF;AACvF,wBAAsB,aAAa,CAAC,IAAI,EAAE;IACxC,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAClC,QAAQ,CAAC,EAAE,YAAY,CAAA;CACxB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAuBpB;AAED,2DAA2D;AAC3D,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,GAAG,OAAO,CAAC,IAAI,CAAC,CAKhB;AAED,sDAAsD;AACtD,wBAAsB,QAAQ,CAAC,IAAI,EAAE;IACnC,UAAU,EAAE,MAAM,CAAA;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,cAAc,EAAE,CAAA;CAC1B,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAgB1B;AAeD;;;GAGG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,cAAc,EAAE,CAAA;IACzB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB,GAAG,OAAO,CAAC,cAAc,CAAC,CAuC1B"}
|
package/dist/pipeline.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RAG pipeline — index chunks via vector bond + answer questions
|
|
3
|
+
* grounded in retrieved sources.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { requireProvider as requireAI } from '@molecule/api-ai';
|
|
8
|
+
import { requireProvider as requireEmbeddings } from '@molecule/api-ai-embeddings';
|
|
9
|
+
import { requireProvider as requireVectorStore, } from '@molecule/api-ai-vector-store';
|
|
10
|
+
import { chunkText } from './chunker.js';
|
|
11
|
+
/** Index a long document by chunking, embedding, and upserting to the vector store. */
|
|
12
|
+
export async function indexDocument(opts) {
|
|
13
|
+
const embeddings = requireEmbeddings();
|
|
14
|
+
const vectors = requireVectorStore();
|
|
15
|
+
const chunks = chunkText(opts.text, opts.chunking).map((text, i) => ({
|
|
16
|
+
id: `${opts.documentId}::${i}`,
|
|
17
|
+
text,
|
|
18
|
+
metadata: { ...(opts.metadata ?? {}), document_id: opts.documentId, chunk_index: i },
|
|
19
|
+
}));
|
|
20
|
+
if (chunks.length === 0)
|
|
21
|
+
return [];
|
|
22
|
+
const vectorList = await embeddings.embedDocuments(chunks.map((c) => c.text));
|
|
23
|
+
await vectors.upsert({
|
|
24
|
+
collection: opts.collection,
|
|
25
|
+
records: chunks.map((c, i) => ({
|
|
26
|
+
id: c.id,
|
|
27
|
+
embedding: vectorList[i],
|
|
28
|
+
content: c.text,
|
|
29
|
+
metadata: c.metadata,
|
|
30
|
+
})),
|
|
31
|
+
});
|
|
32
|
+
return chunks.map((c) => c.id);
|
|
33
|
+
}
|
|
34
|
+
/** Delete all chunks for a previously-indexed document. */
|
|
35
|
+
export async function deleteDocument(opts) {
|
|
36
|
+
const vectors = requireVectorStore();
|
|
37
|
+
const ids = [];
|
|
38
|
+
for (let i = 0; i < (opts.maxChunks ?? 1000); i++)
|
|
39
|
+
ids.push(`${opts.documentId}::${i}`);
|
|
40
|
+
await vectors.delete({ collection: opts.collection, ids });
|
|
41
|
+
}
|
|
42
|
+
/** Retrieve top-K most similar chunks for a query. */
|
|
43
|
+
export async function retrieve(opts) {
|
|
44
|
+
const embeddings = requireEmbeddings();
|
|
45
|
+
const vectors = requireVectorStore();
|
|
46
|
+
const queryVector = await embeddings.embedQuery(opts.query);
|
|
47
|
+
const hits = await vectors.query({
|
|
48
|
+
collection: opts.collection,
|
|
49
|
+
embedding: queryVector,
|
|
50
|
+
topK: opts.topK ?? 5,
|
|
51
|
+
filter: opts.filter,
|
|
52
|
+
});
|
|
53
|
+
return hits.map((h) => ({
|
|
54
|
+
id: h.record.id,
|
|
55
|
+
text: h.record.content ?? '',
|
|
56
|
+
score: h.score,
|
|
57
|
+
metadata: h.record.metadata,
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
const DEFAULT_GROUND_PROMPT = `You are a helpful assistant answering questions using ONLY the provided context.
|
|
61
|
+
|
|
62
|
+
If the answer is not in the context, say "I don't know based on the provided sources."
|
|
63
|
+
|
|
64
|
+
Cite source excerpts by their [number] in the answer when relevant.
|
|
65
|
+
|
|
66
|
+
Context:
|
|
67
|
+
{{CONTEXT}}
|
|
68
|
+
|
|
69
|
+
Question: {{QUESTION}}
|
|
70
|
+
|
|
71
|
+
Answer:`;
|
|
72
|
+
/**
|
|
73
|
+
* Full RAG round-trip: retrieve top-K chunks, format them as numbered
|
|
74
|
+
* sources, and ground a generated answer in them.
|
|
75
|
+
*/
|
|
76
|
+
export async function answerQuestion(opts) {
|
|
77
|
+
const sources = await retrieve({
|
|
78
|
+
collection: opts.collection,
|
|
79
|
+
query: opts.question,
|
|
80
|
+
topK: opts.topK ?? 5,
|
|
81
|
+
filter: opts.filter,
|
|
82
|
+
});
|
|
83
|
+
if (sources.length === 0) {
|
|
84
|
+
return {
|
|
85
|
+
answer: "I don't know based on the provided sources.",
|
|
86
|
+
sources: [],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const context = sources.map((s, i) => `[${i + 1}] ${s.text}`).join('\n\n');
|
|
90
|
+
const prompt = (opts.promptTemplate ?? DEFAULT_GROUND_PROMPT)
|
|
91
|
+
.replace('{{CONTEXT}}', context)
|
|
92
|
+
.replace('{{QUESTION}}', opts.question);
|
|
93
|
+
const ai = requireAI();
|
|
94
|
+
let answer = '';
|
|
95
|
+
for await (const event of ai.chat({
|
|
96
|
+
messages: [{ role: 'user', content: prompt }],
|
|
97
|
+
model: opts.model,
|
|
98
|
+
temperature: opts.temperature ?? 0.2,
|
|
99
|
+
})) {
|
|
100
|
+
// A ChatEvent's text payload is `content` (NOT `text` — that is the
|
|
101
|
+
// ContentBlock shape). Reading `event.text` here silently accumulated
|
|
102
|
+
// nothing, so every grounded answer came back empty in production while
|
|
103
|
+
// the unit test's wrong-shaped mock kept it green.
|
|
104
|
+
if (event.type === 'text')
|
|
105
|
+
answer += event.content;
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
answer,
|
|
109
|
+
sources,
|
|
110
|
+
contextTokens: Math.round(context.length / 4),
|
|
111
|
+
};
|
|
112
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** A chunk of source material to be embedded + indexed. */
|
|
2
|
+
export interface Chunk {
|
|
3
|
+
id: string;
|
|
4
|
+
text: string;
|
|
5
|
+
metadata?: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
/** A retrieval hit from the vector store. */
|
|
8
|
+
export interface RetrievalHit {
|
|
9
|
+
id: string;
|
|
10
|
+
text: string;
|
|
11
|
+
score: number;
|
|
12
|
+
metadata?: Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
/** Final grounded answer + the sources it cited. */
|
|
15
|
+
export interface GroundedAnswer {
|
|
16
|
+
answer: string;
|
|
17
|
+
sources: RetrievalHit[];
|
|
18
|
+
/** Token / chunk count used for the prompt (for cost telemetry). */
|
|
19
|
+
contextTokens?: number;
|
|
20
|
+
}
|
|
21
|
+
/** Chunking options for `chunkText`. */
|
|
22
|
+
export interface ChunkOptions {
|
|
23
|
+
/** Max characters per chunk. Default 1000. */
|
|
24
|
+
maxChars?: number;
|
|
25
|
+
/** Overlap characters between adjacent chunks. Default 200. */
|
|
26
|
+
overlap?: number;
|
|
27
|
+
/** Prefer chunking at paragraph boundaries when possible. Default true. */
|
|
28
|
+
preferParagraphs?: boolean;
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,MAAM,WAAW,KAAK;IACpB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACnC;AAED,6CAA6C;AAC7C,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACnC;AAED,oDAAoD;AACpD,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,YAAY,EAAE,CAAA;IACvB,oEAAoE;IACpE,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED,wCAAwC;AACxC,MAAM,WAAW,YAAY;IAC3B,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,2EAA2E;IAC3E,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-ai-rag-qa",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "RAG Q&A pipeline — chunk + embed + retrieve + ground answer with sources",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"test": "vitest run",
|
|
11
|
+
"test:watch": "vitest"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"molecule",
|
|
24
|
+
"ai",
|
|
25
|
+
"rag",
|
|
26
|
+
"qa",
|
|
27
|
+
"embeddings",
|
|
28
|
+
"vector",
|
|
29
|
+
"resource"
|
|
30
|
+
],
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@types/node": "26.1.2",
|
|
34
|
+
"typescript": "6.0.3",
|
|
35
|
+
"vitest": "4.1.10"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@molecule/api-bonds-default-express": "^1.0.0",
|
|
39
|
+
"@molecule/api-database": "^1.0.0",
|
|
40
|
+
"@molecule/api-i18n": "^1.0.0",
|
|
41
|
+
"@molecule/api-middleware-validation": "^1.0.0",
|
|
42
|
+
"@molecule/api-ai": "^1.0.0",
|
|
43
|
+
"@molecule/api-ai-embeddings": "^1.0.0",
|
|
44
|
+
"@molecule/api-ai-vector-store": "^1.0.0"
|
|
45
|
+
}
|
|
46
|
+
}
|