@cogitator-ai/rag 0.1.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/README.md +359 -0
- package/package.json +65 -0
package/README.md
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
# @cogitator-ai/rag
|
|
2
|
+
|
|
3
|
+
Retrieval-Augmented Generation pipeline for Cogitator AI agents. Load documents, chunk them, embed, retrieve, and rerank — all with a single builder API.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @cogitator-ai/rag
|
|
9
|
+
|
|
10
|
+
# Optional dependencies for specific loaders
|
|
11
|
+
pnpm add cheerio # HTML and web page loading
|
|
12
|
+
pnpm add papaparse # CSV loading
|
|
13
|
+
pnpm add pdf-parse # PDF loading
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Features
|
|
17
|
+
|
|
18
|
+
- **7 Document Loaders** — Text, Markdown, JSON, CSV, HTML, PDF, Web pages
|
|
19
|
+
- **3 Chunking Strategies** — Fixed-size, recursive, semantic (embedding-based)
|
|
20
|
+
- **4 Retrieval Strategies** — Similarity, MMR, hybrid (BM25 + vector), multi-query
|
|
21
|
+
- **2 Rerankers** — LLM-based scoring, Cohere Rerank API
|
|
22
|
+
- **Pipeline Builder** — Fluent API to wire everything together
|
|
23
|
+
- **Agent Tools** — Drop-in `rag_search` and `rag_ingest` tools for Cogitator agents
|
|
24
|
+
- **Zod Validation** — Type-safe configuration with runtime checks
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## Quick Start
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { RAGPipelineBuilder, TextLoader } from '@cogitator-ai/rag';
|
|
32
|
+
import { InMemoryEmbeddingAdapter, OpenAIEmbeddingService } from '@cogitator-ai/memory';
|
|
33
|
+
|
|
34
|
+
const pipeline = new RAGPipelineBuilder()
|
|
35
|
+
.withLoader(new TextLoader())
|
|
36
|
+
.withEmbeddingService(
|
|
37
|
+
new OpenAIEmbeddingService({
|
|
38
|
+
apiKey: process.env.OPENAI_API_KEY!,
|
|
39
|
+
})
|
|
40
|
+
)
|
|
41
|
+
.withEmbeddingAdapter(new InMemoryEmbeddingAdapter())
|
|
42
|
+
.withConfig({
|
|
43
|
+
chunking: { strategy: 'recursive', chunkSize: 500, chunkOverlap: 50 },
|
|
44
|
+
retrieval: { strategy: 'similarity', topK: 5, threshold: 0.3 },
|
|
45
|
+
})
|
|
46
|
+
.build();
|
|
47
|
+
|
|
48
|
+
// ingest documents from a file or directory
|
|
49
|
+
await pipeline.ingest('./docs');
|
|
50
|
+
|
|
51
|
+
// query the knowledge base
|
|
52
|
+
const results = await pipeline.query('How does authentication work?');
|
|
53
|
+
|
|
54
|
+
for (const r of results) {
|
|
55
|
+
console.log(`[${r.score.toFixed(3)}] ${r.content.slice(0, 100)}...`);
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Document Loaders
|
|
62
|
+
|
|
63
|
+
| Loader | Formats | Optional Dep | Notes |
|
|
64
|
+
| ---------------- | --------------------- | ------------ | ----------------------------- |
|
|
65
|
+
| `TextLoader` | `.txt` | — | Files and directories |
|
|
66
|
+
| `MarkdownLoader` | `.md` | — | Strips frontmatter by default |
|
|
67
|
+
| `JSONLoader` | `.json` | — | Configurable JSON path |
|
|
68
|
+
| `CSVLoader` | `.csv` | `papaparse` | Column selection, row mapping |
|
|
69
|
+
| `HTMLLoader` | `.html`, `.htm` | `cheerio` | CSS selector support |
|
|
70
|
+
| `PDFLoader` | `.pdf` | `pdf-parse` | Text extraction from PDFs |
|
|
71
|
+
| `WebLoader` | `http://`, `https://` | `cheerio` | Fetches and parses web pages |
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
import { MarkdownLoader, WebLoader, CSVLoader } from '@cogitator-ai/rag';
|
|
75
|
+
|
|
76
|
+
const md = new MarkdownLoader({ stripFrontmatter: true });
|
|
77
|
+
const web = new WebLoader({ selector: 'article' });
|
|
78
|
+
const csv = new CSVLoader({ columns: ['title', 'body'] });
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Chunking Strategies
|
|
84
|
+
|
|
85
|
+
| Strategy | Class | Best For |
|
|
86
|
+
| ----------- | ------------------ | -------------------------------------- |
|
|
87
|
+
| `fixed` | `FixedSizeChunker` | Simple, predictable chunk sizes |
|
|
88
|
+
| `recursive` | `RecursiveChunker` | Respects paragraph/sentence boundaries |
|
|
89
|
+
| `semantic` | `SemanticChunker` | Groups semantically similar sentences |
|
|
90
|
+
|
|
91
|
+
### Fixed-size
|
|
92
|
+
|
|
93
|
+
Splits text into chunks of exactly `chunkSize` characters with optional overlap.
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
import { FixedSizeChunker } from '@cogitator-ai/rag';
|
|
97
|
+
|
|
98
|
+
const chunker = new FixedSizeChunker({ chunkSize: 500, chunkOverlap: 50 });
|
|
99
|
+
const chunks = chunker.chunk(text, documentId);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Recursive
|
|
103
|
+
|
|
104
|
+
Splits on configurable separators (`\n\n`, `\n`, `. `, ` `) trying to keep paragraphs and sentences intact.
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
import { RecursiveChunker } from '@cogitator-ai/rag';
|
|
108
|
+
|
|
109
|
+
const chunker = new RecursiveChunker({
|
|
110
|
+
chunkSize: 500,
|
|
111
|
+
chunkOverlap: 50,
|
|
112
|
+
separators: ['\n\n', '\n', '. ', ' '],
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Semantic
|
|
117
|
+
|
|
118
|
+
Uses embedding similarity between sentences to find natural breakpoints. Async — requires an `EmbeddingService`.
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
import { SemanticChunker } from '@cogitator-ai/rag';
|
|
122
|
+
|
|
123
|
+
const chunker = new SemanticChunker({
|
|
124
|
+
embeddingService,
|
|
125
|
+
breakpointThreshold: 0.5,
|
|
126
|
+
minChunkSize: 100,
|
|
127
|
+
maxChunkSize: 2000,
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const chunks = await chunker.chunk(text, documentId);
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Factory
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import { createChunker } from '@cogitator-ai/rag';
|
|
137
|
+
|
|
138
|
+
const chunker = createChunker(
|
|
139
|
+
{ strategy: 'recursive', chunkSize: 500, chunkOverlap: 50 },
|
|
140
|
+
embeddingService
|
|
141
|
+
);
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## Retrieval Strategies
|
|
147
|
+
|
|
148
|
+
| Strategy | Class | Description |
|
|
149
|
+
| ------------- | --------------------- | ------------------------------------------------------------- |
|
|
150
|
+
| `similarity` | `SimilarityRetriever` | Pure cosine similarity search |
|
|
151
|
+
| `mmr` | `MMRRetriever` | Maximal Marginal Relevance — balances relevance and diversity |
|
|
152
|
+
| `hybrid` | `HybridRetriever` | Combines BM25 keyword search with vector search (RRF) |
|
|
153
|
+
| `multi-query` | `MultiQueryRetriever` | Expands query into variants, merges results |
|
|
154
|
+
|
|
155
|
+
### Similarity
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { SimilarityRetriever } from '@cogitator-ai/rag';
|
|
159
|
+
|
|
160
|
+
const retriever = new SimilarityRetriever({
|
|
161
|
+
embeddingAdapter,
|
|
162
|
+
embeddingService,
|
|
163
|
+
defaultTopK: 10,
|
|
164
|
+
defaultThreshold: 0.3,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const results = await retriever.retrieve('What is TypeScript?');
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### MMR
|
|
171
|
+
|
|
172
|
+
Reduces redundancy by penalizing results that are too similar to already-selected ones.
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { MMRRetriever } from '@cogitator-ai/rag';
|
|
176
|
+
|
|
177
|
+
const retriever = new MMRRetriever({
|
|
178
|
+
embeddingAdapter,
|
|
179
|
+
embeddingService,
|
|
180
|
+
defaultLambda: 0.7, // 1.0 = pure relevance, 0.0 = pure diversity
|
|
181
|
+
defaultTopK: 10,
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Hybrid
|
|
186
|
+
|
|
187
|
+
Requires `HybridSearch` from `@cogitator-ai/memory`.
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
import { HybridRetriever } from '@cogitator-ai/rag';
|
|
191
|
+
import { HybridSearch } from '@cogitator-ai/memory';
|
|
192
|
+
|
|
193
|
+
const retriever = new HybridRetriever({
|
|
194
|
+
hybridSearch,
|
|
195
|
+
defaultWeights: { bm25: 0.4, vector: 0.6 },
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Multi-Query
|
|
200
|
+
|
|
201
|
+
Generates query variations and merges results. You provide the expansion function (typically an LLM call).
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
import { MultiQueryRetriever } from '@cogitator-ai/rag';
|
|
205
|
+
|
|
206
|
+
const retriever = new MultiQueryRetriever({
|
|
207
|
+
baseRetriever: similarityRetriever,
|
|
208
|
+
expandQuery: async (query) => {
|
|
209
|
+
const response = await llm.generate(
|
|
210
|
+
`Generate 3 alternative phrasings for: "${query}". Return one per line.`
|
|
211
|
+
);
|
|
212
|
+
return response.split('\n').filter(Boolean);
|
|
213
|
+
},
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Factory
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
import { createRetriever } from '@cogitator-ai/rag';
|
|
221
|
+
|
|
222
|
+
const retriever = createRetriever({
|
|
223
|
+
strategy: 'mmr',
|
|
224
|
+
embeddingAdapter,
|
|
225
|
+
embeddingService,
|
|
226
|
+
lambda: 0.7,
|
|
227
|
+
topK: 10,
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
---
|
|
232
|
+
|
|
233
|
+
## Reranking
|
|
234
|
+
|
|
235
|
+
Rerankers rescore retrieval results for higher precision. Enable via pipeline config.
|
|
236
|
+
|
|
237
|
+
### LLM Reranker
|
|
238
|
+
|
|
239
|
+
Uses any LLM to score document relevance on a 0-10 scale.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
import { LLMReranker } from '@cogitator-ai/rag';
|
|
243
|
+
|
|
244
|
+
const reranker = new LLMReranker({
|
|
245
|
+
generateFn: (prompt) => llm.generate(prompt),
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
const pipeline = new RAGPipelineBuilder()
|
|
249
|
+
.withLoader(loader)
|
|
250
|
+
.withEmbeddingService(embeddingService)
|
|
251
|
+
.withEmbeddingAdapter(embeddingAdapter)
|
|
252
|
+
.withReranker(reranker)
|
|
253
|
+
.withConfig({
|
|
254
|
+
chunking: { strategy: 'recursive', chunkSize: 500, chunkOverlap: 50 },
|
|
255
|
+
retrieval: { strategy: 'similarity', topK: 20 },
|
|
256
|
+
reranking: { enabled: true, topN: 5 },
|
|
257
|
+
})
|
|
258
|
+
.build();
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
### Cohere Reranker
|
|
262
|
+
|
|
263
|
+
Uses the Cohere Rerank API (rerank-v3.5 by default).
|
|
264
|
+
|
|
265
|
+
```typescript
|
|
266
|
+
import { CohereReranker } from '@cogitator-ai/rag';
|
|
267
|
+
|
|
268
|
+
const reranker = new CohereReranker({
|
|
269
|
+
apiKey: process.env.COHERE_API_KEY!,
|
|
270
|
+
model: 'rerank-v3.5',
|
|
271
|
+
});
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
---
|
|
275
|
+
|
|
276
|
+
## Agent Integration
|
|
277
|
+
|
|
278
|
+
Use `ragTools()` to give a Cogitator agent access to your knowledge base.
|
|
279
|
+
|
|
280
|
+
```typescript
|
|
281
|
+
import { Agent, tool } from '@cogitator-ai/core';
|
|
282
|
+
import { RAGPipelineBuilder, TextLoader, createSearchTool } from '@cogitator-ai/rag';
|
|
283
|
+
import { InMemoryEmbeddingAdapter, OpenAIEmbeddingService } from '@cogitator-ai/memory';
|
|
284
|
+
import { z } from 'zod';
|
|
285
|
+
|
|
286
|
+
const pipeline = new RAGPipelineBuilder()
|
|
287
|
+
.withLoader(new TextLoader())
|
|
288
|
+
.withEmbeddingService(new OpenAIEmbeddingService({ apiKey: process.env.OPENAI_API_KEY! }))
|
|
289
|
+
.withEmbeddingAdapter(new InMemoryEmbeddingAdapter())
|
|
290
|
+
.withConfig({
|
|
291
|
+
chunking: { strategy: 'recursive', chunkSize: 400, chunkOverlap: 50 },
|
|
292
|
+
retrieval: { strategy: 'similarity', topK: 3, threshold: 0.3 },
|
|
293
|
+
})
|
|
294
|
+
.build();
|
|
295
|
+
|
|
296
|
+
await pipeline.ingest('./knowledge-base');
|
|
297
|
+
|
|
298
|
+
const ragSearch = createSearchTool(pipeline);
|
|
299
|
+
|
|
300
|
+
const searchKB = tool({
|
|
301
|
+
name: ragSearch.name,
|
|
302
|
+
description: ragSearch.description,
|
|
303
|
+
parameters: z.object({
|
|
304
|
+
query: z.string().describe('Search query'),
|
|
305
|
+
limit: z.number().int().positive().optional(),
|
|
306
|
+
threshold: z.number().min(0).max(1).optional(),
|
|
307
|
+
}),
|
|
308
|
+
execute: async (params) => ragSearch.execute(params),
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
const agent = new Agent({
|
|
312
|
+
name: 'docs-assistant',
|
|
313
|
+
model: 'gpt-4o',
|
|
314
|
+
instructions: 'Use rag_search to find information before answering.',
|
|
315
|
+
tools: [searchKB],
|
|
316
|
+
});
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
## Pipeline Stats
|
|
322
|
+
|
|
323
|
+
```typescript
|
|
324
|
+
const stats = pipeline.getStats();
|
|
325
|
+
console.log(stats.documentsIngested);
|
|
326
|
+
console.log(stats.chunksStored);
|
|
327
|
+
console.log(stats.queriesProcessed);
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## Examples
|
|
333
|
+
|
|
334
|
+
See [`examples/rag/`](../../examples/rag/) for runnable examples:
|
|
335
|
+
|
|
336
|
+
- **01-basic-retrieval.ts** — Ingest documents and run semantic queries
|
|
337
|
+
- **02-chunking-strategies.ts** — Compare fixed, recursive, and semantic chunking
|
|
338
|
+
- **03-agent-with-rag.ts** — Full agent with RAG search tools
|
|
339
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
## Zod Schemas
|
|
343
|
+
|
|
344
|
+
```typescript
|
|
345
|
+
import {
|
|
346
|
+
ChunkingStrategySchema,
|
|
347
|
+
ChunkingConfigSchema,
|
|
348
|
+
RetrievalStrategySchema,
|
|
349
|
+
RetrievalConfigSchema,
|
|
350
|
+
RerankingConfigSchema,
|
|
351
|
+
RAGPipelineConfigSchema,
|
|
352
|
+
} from '@cogitator-ai/rag';
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
## License
|
|
358
|
+
|
|
359
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cogitator-ai/rag",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Retrieval Augmented Generation for Cogitator AI agents",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc",
|
|
19
|
+
"dev": "tsc --watch",
|
|
20
|
+
"clean": "rm -rf dist",
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"test": "vitest run",
|
|
23
|
+
"test:watch": "vitest"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@cogitator-ai/types": "workspace:*",
|
|
27
|
+
"nanoid": "^5.0.4",
|
|
28
|
+
"zod": "^4.3.6"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@cogitator-ai/core": "workspace:*",
|
|
32
|
+
"@cogitator-ai/memory": "workspace:*"
|
|
33
|
+
},
|
|
34
|
+
"peerDependenciesMeta": {
|
|
35
|
+
"@cogitator-ai/core": {
|
|
36
|
+
"optional": true
|
|
37
|
+
},
|
|
38
|
+
"@cogitator-ai/memory": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"optionalDependencies": {
|
|
43
|
+
"cheerio": "^1.0.0",
|
|
44
|
+
"papaparse": "^5.5.0",
|
|
45
|
+
"pdf-parse": "^1.1.1"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@cogitator-ai/core": "workspace:*",
|
|
49
|
+
"@cogitator-ai/memory": "workspace:*",
|
|
50
|
+
"@types/papaparse": "^5.3.15",
|
|
51
|
+
"@types/pdf-parse": "^1.1.5",
|
|
52
|
+
"typescript": "^5.7.2",
|
|
53
|
+
"vitest": "^4.0.18"
|
|
54
|
+
},
|
|
55
|
+
"repository": {
|
|
56
|
+
"type": "git",
|
|
57
|
+
"url": "https://github.com/cogitator-ai/Cogitator-AI.git",
|
|
58
|
+
"directory": "packages/rag"
|
|
59
|
+
},
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public",
|
|
62
|
+
"registry": "https://npm.pkg.github.com"
|
|
63
|
+
},
|
|
64
|
+
"license": "MIT"
|
|
65
|
+
}
|