@mastra/rag 2.5.0-alpha.0 → 2.6.0-alpha.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.
@@ -0,0 +1,347 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # OracleDB vector store
4
+
5
+ `OracleVector` stores embeddings in Oracle Database `VECTOR` columns and exposes them through Mastra's vector interface. Each logical Mastra vector index is mapped to an Oracle vector table through a registry table, while metadata is stored as Oracle JSON for structured filtering.
6
+
7
+ ## Installation
8
+
9
+ **npm**:
10
+
11
+ ```bash
12
+ npm install @mastra/oracledb@latest
13
+ ```
14
+
15
+ **pnpm**:
16
+
17
+ ```bash
18
+ pnpm add @mastra/oracledb@latest
19
+ ```
20
+
21
+ **Yarn**:
22
+
23
+ ```bash
24
+ yarn add @mastra/oracledb@latest
25
+ ```
26
+
27
+ **Bun**:
28
+
29
+ ```bash
30
+ bun add @mastra/oracledb@latest
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ```ts
36
+ import { OracleVector } from '@mastra/oracledb'
37
+
38
+ const vector = new OracleVector({
39
+ id: 'oracle-vector',
40
+ user: process.env.ORACLE_DATABASE_USER,
41
+ password: process.env.ORACLE_DATABASE_PASSWORD,
42
+ connectString: process.env.ORACLE_DATABASE_CONNECT_STRING,
43
+ })
44
+
45
+ await vector.createIndex({
46
+ indexName: 'memory_messages',
47
+ dimension: 1536,
48
+ metric: 'cosine',
49
+ })
50
+
51
+ await vector.upsert({
52
+ indexName: 'memory_messages',
53
+ vectors: [embedding],
54
+ metadata: [{ resource_id: 'user-1', thread_id: 'thread-1' }],
55
+ })
56
+
57
+ const results = await vector.query({
58
+ indexName: 'memory_messages',
59
+ queryVector,
60
+ topK: 5,
61
+ filter: { resource_id: 'user-1' },
62
+ })
63
+ ```
64
+
65
+ By default, `OracleVector` uses exact search with no approximate vector index. Configure IVF or HNSW when your dataset and latency requirements need approximate search.
66
+
67
+ ## Constructor options
68
+
69
+ Pass Oracle connection options (`user`, `password`, `connectString`, `pool`, wallet options, or `externalAuth`) directly, or pass `poolManager` to share the pool used by `OracleStore`. The vector-specific options are:
70
+
71
+ **id** (`string`): Unique identifier for this vector store instance.
72
+
73
+ **poolManager** (`OraclePoolManager`): Shared Oracle pool manager. Use this to share one Oracle pool with OracleStore.
74
+
75
+ **schemaName** (`string`): Oracle schema name used to qualify the vector registry and vector tables.
76
+
77
+ **tablePrefix** (`string`): Prefix used for physical Oracle vector tables. (Default: `'MASTRA_VEC'`)
78
+
79
+ **registryTableName** (`string`): Oracle table used to map Mastra logical index names to physical vector tables. (Default: `'MASTRA_VECTOR_INDEXES'`)
80
+
81
+ **defaultIndexConfig** (`OracleVectorIndexConfig`): Default Oracle vector index configuration. (Default: `{ type: 'none', accuracy: 95 }`)
82
+
83
+ **defaultMetadataIndexes** (`string[]`): Metadata fields to index automatically when vector tables are created. (Default: `['thread_id', 'resource_id', 'message_id', 'source_id']`)
84
+
85
+ **defaultVectorFormat** (`'vector' | 'bit' | 'int8'`): Default Oracle vector format for dense, binary, and int8 embeddings. (Default: `'vector'`)
86
+
87
+ **upsertBatchSize** (`number`): Number of vectors sent per Oracle executeMany call. The full upsert commits once after all batches succeed. (Default: `200`)
88
+
89
+ ## Constructor examples
90
+
91
+ ### Shared pool with OracleStore
92
+
93
+ ```ts
94
+ import { OracleStore, OracleVector } from '@mastra/oracledb'
95
+
96
+ const storage = new OracleStore({ id: 'oracle-storage', user, password, connectString })
97
+
98
+ const vector = new OracleVector({
99
+ id: 'oracle-vector',
100
+ poolManager: storage.getPoolManager(),
101
+ })
102
+ ```
103
+
104
+ For Autonomous Database and mTLS connections, pass `walletLocation`, `walletPassword`, and `configDir` in the same constructor.
105
+
106
+ ## Methods
107
+
108
+ ### `createIndex()`
109
+
110
+ Creates the registry row, physical Oracle vector table, metadata indexes, and optionally an Oracle vector index.
111
+
112
+ **indexName** (`string`): Logical Mastra index name. The provider maps this to a valid Oracle table name internally.
113
+
114
+ **dimension** (`number`): Vector dimension. This must match the embedding model output size.
115
+
116
+ **metric** (`'cosine' | 'euclidean' | 'dotproduct' | 'hamming' | 'jaccard'`): Distance metric for similarity search. Binary vectors support hamming and jaccard. (Default: `cosine`)
117
+
118
+ **vectorFormat** (`'vector' | 'bit' | 'int8'`): Oracle vector storage format. (Default: `vector`)
119
+
120
+ **indexConfig** (`OracleVectorIndexConfig`): Oracle vector index configuration. none means exact search with no approximate vector index. (Default: `{ type: 'none', accuracy: 95 }`)
121
+
122
+ **buildIndex** (`boolean`): Whether to build the Oracle vector index when indexConfig.type is ivf or hnsw. (Default: `true`)
123
+
124
+ **metadataIndexes** (`string[]`): Metadata field names to index for faster JSON metadata filtering.
125
+
126
+ #### `OracleVectorIndexConfig`
127
+
128
+ **type** (`'none' | 'ivf' | 'hnsw'`): Oracle vector index type. (Default: `'none'`)
129
+
130
+ **accuracy** (`number`): Target accuracy for approximate vector search. (Default: `95`)
131
+
132
+ **ivf.neighborPartitions** (`number`): Oracle IVF neighbor partitions setting.
133
+
134
+ **hnsw\.neighbors** (`number`): Oracle HNSW neighbor setting.
135
+
136
+ **hnsw\.efConstruction** (`number`): Oracle HNSW build-time construction setting.
137
+
138
+ #### Index configuration
139
+
140
+ ```ts
141
+ await vector.createIndex({
142
+ indexName: 'support_articles',
143
+ dimension: 1536,
144
+ metric: 'cosine',
145
+ indexConfig: {
146
+ type: 'ivf',
147
+ accuracy: 95,
148
+ ivf: {
149
+ neighborPartitions: 32,
150
+ },
151
+ },
152
+ })
153
+ ```
154
+
155
+ The default is `indexConfig: { type: 'none' }`, which uses exact search and requires no approximate index tuning. Use IVF or HNSW only when your data volume and latency requirements justify approximate search. HNSW is configured with `indexConfig: { type: 'hnsw', hnsw: { neighbors, efConstruction } }` and requires Oracle Vector Pool memory, which `configureVectorMemory()` can allocate for local or self-managed databases.
156
+
157
+ ### `upsert()`
158
+
159
+ **indexName** (`string`): Name of the index to upsert vectors into.
160
+
161
+ **vectors** (`number[][]`): Array of embedding vectors.
162
+
163
+ **metadata** (`Record<string, any>[]`): Metadata stored as Oracle JSON. Must align by position with vectors.
164
+
165
+ **ids** (`string[]`): Optional vector IDs. IDs are generated when omitted.
166
+
167
+ ### `query()`
168
+
169
+ **indexName** (`string`): Name of the index to query.
170
+
171
+ **queryVector** (`number[]`): Query vector.
172
+
173
+ **topK** (`number`): Number of results to return. (Default: `10`)
174
+
175
+ **filter** (`Record<string, any>`): Mastra metadata filter translated to Oracle JSON predicates.
176
+
177
+ **includeVector** (`boolean`): Whether to include the vector in each result. (Default: `false`)
178
+
179
+ **minScore** (`number`): Minimum similarity score threshold. (Default: `-1`)
180
+
181
+ **queryMode** (`'exact' | 'approx'`): Oracle query mode. Exact search is used by default when no approximate vector index is configured.
182
+
183
+ **targetAccuracy** (`number`): Target accuracy for approximate Oracle vector queries.
184
+
185
+ ### `listIndexes()`
186
+
187
+ Returns the logical Mastra index names recorded in the Oracle vector registry table.
188
+
189
+ ### `describeIndex()`
190
+
191
+ Returns Oracle index metadata, including the physical table name, dimension, vector count, metric, index type, vector format, and configured accuracy.
192
+
193
+ ### `deleteIndex()`
194
+
195
+ Deletes the Oracle vector table and removes the registry entry for the logical index.
196
+
197
+ ### `updateVector()`
198
+
199
+ Update vectors by ID or metadata filter. Either `id` or `filter` must be provided, but not both. The `update` object may include `vector`, `metadata`, or both.
200
+
201
+ ```ts
202
+ await vector.updateVector({
203
+ indexName: 'support_articles',
204
+ id: 'doc-1',
205
+ update: { metadata: { status: 'reviewed' } },
206
+ })
207
+ ```
208
+
209
+ ### `deleteVector()`
210
+
211
+ Deletes a single vector by ID.
212
+
213
+ ### `deleteVectors()`
214
+
215
+ Deletes multiple vectors by IDs or by metadata filter. Either `ids` or `filter` must be provided, but not both.
216
+
217
+ ### `buildIndex()`
218
+
219
+ Builds an Oracle vector index for an existing logical index. If the resolved index type is `none`, this method is a no-op.
220
+
221
+ ### `rebuildIndex()`
222
+
223
+ Drops and recreates the Oracle vector index for an existing logical index, typically after changing approximate-index tuning.
224
+
225
+ ### Index diagnostics
226
+
227
+ Use `getIndexStatus({ indexName })` to inspect Oracle catalog status, and `indexAccuracyQuery({ indexName, queryVector, topK, targetAccuracy })` to run `DBMS_VECTOR.INDEX_ACCURACY_QUERY` for approximate indexes.
228
+
229
+ ### `configureVectorMemory()`
230
+
231
+ Allocates Oracle Vector Pool memory, which HNSW indexes require. This calls `ALTER SYSTEM SET VECTOR_MEMORY_SIZE`, so it requires a privileged connection such as `SYSDBA` or `SYSTEM`.
232
+
233
+ **size** (`string`): Vector pool size, as an integer optionally followed by K, M, or G (for example "512M").
234
+
235
+ **scope** (`'MEMORY' | 'SPFILE' | 'BOTH'`): Oracle ALTER SYSTEM scope. Use 'SPFILE' or 'BOTH' so the setting survives a database restart. (Default: `'MEMORY'`)
236
+
237
+ ### `disconnect()`
238
+
239
+ Closes the Oracle pool when `OracleVector` created the pool manager. If you provide `pool` or `poolManager`, you own that lifecycle.
240
+
241
+ ## Metadata filters
242
+
243
+ `OracleVector` accepts Mastra's standard metadata filter syntax. Filters are translated into Oracle JSON predicates with bound values:
244
+
245
+ - scalar comparisons use `JSON_VALUE`
246
+ - array, existence, and element-match checks use `JSON_EXISTS`
247
+ - regex filters use `REGEXP_LIKE`
248
+ - string contains filters use case-insensitive `LIKE`
249
+
250
+ ```ts
251
+ const results = await vector.query({
252
+ indexName: 'memory_messages',
253
+ queryVector,
254
+ topK: 5,
255
+ filter: {
256
+ resource_id: 'user-1',
257
+ tags: { $contains: 'support' },
258
+ score: { $gte: 0.8 },
259
+ $or: [{ source: 'docs' }, { source: 'tickets' }],
260
+ },
261
+ })
262
+ ```
263
+
264
+ Metadata is stored as native Oracle JSON, so the rows are also readable directly with standard Oracle JDBC tools such as DBeaver and SQL Developer.
265
+
266
+ Use `ORACLEDB_PROMPT` when an agent should generate Oracle-compatible metadata filters for `createVectorQueryTool()`:
267
+
268
+ ```ts
269
+ import { Agent } from '@mastra/core/agent'
270
+ import { createVectorQueryTool } from '@mastra/rag'
271
+ import { fastembed } from '@mastra/fastembed'
272
+ import { ORACLEDB_PROMPT } from '@mastra/oracledb'
273
+
274
+ const vectorQueryTool = createVectorQueryTool({
275
+ vectorStoreName: 'oracle',
276
+ indexName: 'support_articles',
277
+ model: fastembed,
278
+ enableFilter: true,
279
+ })
280
+
281
+ export const ragAgent = new Agent({
282
+ id: 'oracle-rag-agent',
283
+ name: 'Oracle RAG Agent',
284
+ model: 'openai/gpt-5.6-sol',
285
+ instructions: `
286
+ Use the retrieval tool when you need source context.
287
+ Available metadata fields: resource_id, thread_id, source, category, tags.
288
+ ${ORACLEDB_PROMPT}
289
+ `,
290
+ tools: { vectorQueryTool },
291
+ })
292
+ ```
293
+
294
+ ## Response types
295
+
296
+ Query results are returned in this format:
297
+
298
+ ```ts
299
+ interface QueryResult {
300
+ id: string
301
+ score: number
302
+ metadata: Record<string, any>
303
+ vector?: number[]
304
+ }
305
+ ```
306
+
307
+ ## Usage example
308
+
309
+ ```ts
310
+ import { Agent } from '@mastra/core/agent'
311
+ import { Memory } from '@mastra/memory'
312
+ import { fastembed } from '@mastra/fastembed'
313
+ import { OracleStore, OracleVector } from '@mastra/oracledb'
314
+
315
+ const storage = new OracleStore({
316
+ id: 'oracle-storage',
317
+ user: process.env.ORACLE_DATABASE_USER,
318
+ password: process.env.ORACLE_DATABASE_PASSWORD,
319
+ connectString: process.env.ORACLE_DATABASE_CONNECT_STRING,
320
+ })
321
+
322
+ const vector = new OracleVector({
323
+ id: 'oracle-vector',
324
+ poolManager: storage.getPoolManager(),
325
+ })
326
+
327
+ export const oracleAgent = new Agent({
328
+ id: 'oracle-agent',
329
+ name: 'Oracle Agent',
330
+ instructions: 'You are an assistant with OracleDB-backed memory and semantic recall.',
331
+ model: 'openai/gpt-5.6-sol',
332
+ memory: new Memory({
333
+ storage,
334
+ vector,
335
+ embedder: fastembed,
336
+ options: {
337
+ semanticRecall: { topK: 3, messageRange: 2 },
338
+ },
339
+ }),
340
+ })
341
+ ```
342
+
343
+ ## Related
344
+
345
+ - [OracleDB storage](https://mastra.ai/integrations/databases/oracledb)
346
+ - [Metadata Filters](https://mastra.ai/reference/rag/metadata-filters)
347
+ - [Vector databases](https://mastra.ai/reference/rag/vector-databases)
@@ -29,6 +29,17 @@ export interface GraphChunk {
29
29
  export interface GraphEmbedding {
30
30
  vector: number[];
31
31
  }
32
+ /**
33
+ * JSON-safe snapshot of a GraphRAG instance, produced by `serialize()` and
34
+ * restored with `GraphRAG.deserialize()`.
35
+ */
36
+ export interface GraphRAGSnapshot {
37
+ version: 1;
38
+ dimension: number;
39
+ threshold: number;
40
+ nodes: GraphNode[];
41
+ edges: GraphEdge[];
42
+ }
32
43
  export declare class GraphRAG {
33
44
  private nodes;
34
45
  private edges;
@@ -40,6 +51,23 @@ export declare class GraphRAG {
40
51
  getNodes(): GraphNode[];
41
52
  getEdges(): GraphEdge[];
42
53
  getEdgesByType(type: string): GraphEdge[];
54
+ /**
55
+ * Produce a JSON-safe snapshot of the graph so it can be persisted and
56
+ * restored later instead of rebuilt with `createGraph`.
57
+ *
58
+ * The snapshot is a deep copy, including nested node metadata, so mutating it
59
+ * does not affect this instance.
60
+ * Note that every node carries its full embedding, so snapshots of large
61
+ * graphs can be several megabytes of JSON.
62
+ */
63
+ serialize(): GraphRAGSnapshot;
64
+ /**
65
+ * Rebuild a GraphRAG instance from a snapshot produced by `serialize()`.
66
+ *
67
+ * @throws if the snapshot version is unsupported, a node embedding does not
68
+ * match the snapshot dimension, or an edge references an unknown node.
69
+ */
70
+ static deserialize(snapshot: GraphRAGSnapshot): GraphRAG;
43
71
  clear(): void;
44
72
  updateNodeContent(id: string, newContent: string): void;
45
73
  private getNeighbors;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/graph-rag/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,KAAK,iBAAiB,GAAG,UAAU,CAAC;AACpC,KAAK,aAAa,GAAG,MAAM,CAAC,MAA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,CAAC;QACrB,MAAM,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;KACjC,GAAG,UAAU,EAAE;CA+DjB"}
package/dist/index.cjs CHANGED
@@ -6224,7 +6224,8 @@ async function rerank(results, query, model, options) {
6224
6224
  }
6225
6225
  //#endregion
6226
6226
  //#region src/graph-rag/index.ts
6227
- var GraphRAG = class {
6227
+ const GRAPH_RAG_SNAPSHOT_VERSION = 1;
6228
+ var GraphRAG = class GraphRAG {
6228
6229
  nodes;
6229
6230
  edges;
6230
6231
  dimension;
@@ -6259,6 +6260,49 @@ var GraphRAG = class {
6259
6260
  getEdgesByType(type) {
6260
6261
  return this.edges.filter((edge) => edge.type === type);
6261
6262
  }
6263
+ /**
6264
+ * Produce a JSON-safe snapshot of the graph so it can be persisted and
6265
+ * restored later instead of rebuilt with `createGraph`.
6266
+ *
6267
+ * The snapshot is a deep copy, including nested node metadata, so mutating it
6268
+ * does not affect this instance.
6269
+ * Note that every node carries its full embedding, so snapshots of large
6270
+ * graphs can be several megabytes of JSON.
6271
+ */
6272
+ serialize() {
6273
+ return {
6274
+ version: GRAPH_RAG_SNAPSHOT_VERSION,
6275
+ dimension: this.dimension,
6276
+ threshold: this.threshold,
6277
+ nodes: Array.from(this.nodes.values()).map((node) => ({
6278
+ ...node,
6279
+ ...node.embedding ? { embedding: [...node.embedding] } : {},
6280
+ ...node.metadata ? { metadata: structuredClone(node.metadata) } : {}
6281
+ })),
6282
+ edges: this.edges.map((edge) => ({ ...edge }))
6283
+ };
6284
+ }
6285
+ /**
6286
+ * Rebuild a GraphRAG instance from a snapshot produced by `serialize()`.
6287
+ *
6288
+ * @throws if the snapshot version is unsupported, a node embedding does not
6289
+ * match the snapshot dimension, or an edge references an unknown node.
6290
+ */
6291
+ static deserialize(snapshot) {
6292
+ if (snapshot?.version !== GRAPH_RAG_SNAPSHOT_VERSION) throw new Error(`Unsupported GraphRAG snapshot version: ${snapshot?.version}`);
6293
+ const graph = new GraphRAG(snapshot.dimension, snapshot.threshold);
6294
+ for (const node of snapshot.nodes ?? []) graph.addNode({
6295
+ ...node,
6296
+ ...node.embedding ? { embedding: [...node.embedding] } : {},
6297
+ ...node.metadata ? { metadata: structuredClone(node.metadata) } : {}
6298
+ });
6299
+ for (const edge of snapshot.edges ?? []) {
6300
+ if (!graph.nodes.has(edge.source)) throw new Error(`Edge references unknown node: ${edge.source}`);
6301
+ if (!graph.nodes.has(edge.target)) throw new Error(`Edge references unknown node: ${edge.target}`);
6302
+ }
6303
+ graph.edges = (snapshot.edges ?? []).map((edge) => ({ ...edge }));
6304
+ return graph;
6305
+ }
6262
6306
  clear() {
6263
6307
  this.nodes.clear();
6264
6308
  this.edges = [];