@mastra/rag 0.0.0-commonjs-20250227130920
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/.turbo/turbo-build.log +23 -0
- package/CHANGELOG.md +1151 -0
- package/LICENSE +44 -0
- package/README.md +26 -0
- package/dist/_tsup-dts-rollup.d.cts +620 -0
- package/dist/_tsup-dts-rollup.d.ts +620 -0
- package/dist/index.cjs +2524 -0
- package/dist/index.d.cts +22 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +2505 -0
- package/docker-compose.yaml +22 -0
- package/eslint.config.js +6 -0
- package/package.json +72 -0
- package/src/document/document.test.ts +985 -0
- package/src/document/document.ts +281 -0
- package/src/document/index.ts +2 -0
- package/src/document/transformers/character.ts +279 -0
- package/src/document/transformers/html.ts +346 -0
- package/src/document/transformers/json.ts +265 -0
- package/src/document/transformers/latex.ts +19 -0
- package/src/document/transformers/markdown.ts +244 -0
- package/src/document/transformers/text.ts +134 -0
- package/src/document/transformers/token.ts +148 -0
- package/src/document/transformers/transformer.ts +5 -0
- package/src/document/types.ts +103 -0
- package/src/graph-rag/index.test.ts +235 -0
- package/src/graph-rag/index.ts +306 -0
- package/src/index.ts +6 -0
- package/src/rerank/index.test.ts +150 -0
- package/src/rerank/index.ts +154 -0
- package/src/tools/document-chunker.ts +30 -0
- package/src/tools/graph-rag.ts +117 -0
- package/src/tools/index.ts +3 -0
- package/src/tools/vector-query.ts +90 -0
- package/src/utils/default-settings.ts +33 -0
- package/src/utils/index.ts +2 -0
- package/src/utils/vector-prompts.ts +729 -0
- package/src/utils/vector-search.ts +41 -0
- package/tsconfig.json +5 -0
- package/vitest.config.ts +11 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { MastraAgentRelevanceScorer, CohereRelevanceScorer } from '@mastra/core/relevance';
|
|
2
|
+
import type { RelevanceScoreProvider } from '@mastra/core/relevance';
|
|
3
|
+
import type { QueryResult } from '@mastra/core/vector';
|
|
4
|
+
import type { LanguageModelV1 } from 'ai';
|
|
5
|
+
|
|
6
|
+
// Default weights for different scoring components (must add up to 1)
|
|
7
|
+
const DEFAULT_WEIGHTS = {
|
|
8
|
+
semantic: 0.4,
|
|
9
|
+
vector: 0.4,
|
|
10
|
+
position: 0.2,
|
|
11
|
+
} as const;
|
|
12
|
+
|
|
13
|
+
type WeightConfig = {
|
|
14
|
+
semantic?: number;
|
|
15
|
+
vector?: number;
|
|
16
|
+
position?: number;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
interface ScoringDetails {
|
|
20
|
+
semantic: number;
|
|
21
|
+
vector: number;
|
|
22
|
+
position: number;
|
|
23
|
+
queryAnalysis?: {
|
|
24
|
+
magnitude: number;
|
|
25
|
+
dominantFeatures: number[];
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface RerankResult {
|
|
30
|
+
result: QueryResult;
|
|
31
|
+
score: number;
|
|
32
|
+
details: ScoringDetails;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// For use in the vector store tool
|
|
36
|
+
export interface RerankerOptions {
|
|
37
|
+
weights?: WeightConfig;
|
|
38
|
+
topK?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// For use in the rerank function
|
|
42
|
+
export interface RerankerFunctionOptions {
|
|
43
|
+
weights?: WeightConfig;
|
|
44
|
+
queryEmbedding?: number[];
|
|
45
|
+
topK?: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface RerankConfig {
|
|
49
|
+
options?: RerankerOptions;
|
|
50
|
+
model: LanguageModelV1;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Calculate position score based on position in original list
|
|
54
|
+
function calculatePositionScore(position: number, totalChunks: number): number {
|
|
55
|
+
return 1 - position / totalChunks;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Analyze query embedding features if needed
|
|
59
|
+
function analyzeQueryEmbedding(embedding: number[]): {
|
|
60
|
+
magnitude: number;
|
|
61
|
+
dominantFeatures: number[];
|
|
62
|
+
} {
|
|
63
|
+
// Calculate embedding magnitude
|
|
64
|
+
const magnitude = Math.sqrt(embedding.reduce((sum, val) => sum + val * val, 0));
|
|
65
|
+
|
|
66
|
+
// Find dominant features (highest absolute values)
|
|
67
|
+
const dominantFeatures = embedding
|
|
68
|
+
.map((value, index) => ({ value: Math.abs(value), index }))
|
|
69
|
+
.sort((a, b) => b.value - a.value)
|
|
70
|
+
.slice(0, 5)
|
|
71
|
+
.map(item => item.index);
|
|
72
|
+
|
|
73
|
+
return { magnitude, dominantFeatures };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Adjust scores based on query characteristics
|
|
77
|
+
function adjustScores(score: number, queryAnalysis: { magnitude: number; dominantFeatures: number[] }): number {
|
|
78
|
+
const magnitudeAdjustment = queryAnalysis.magnitude > 10 ? 1.1 : 1;
|
|
79
|
+
|
|
80
|
+
const featureStrengthAdjustment = queryAnalysis.magnitude > 5 ? 1.05 : 1;
|
|
81
|
+
|
|
82
|
+
return score * magnitudeAdjustment * featureStrengthAdjustment;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Takes in a list of results from a vector store and reranks them based on semantic, vector, and position scores
|
|
86
|
+
export async function rerank(
|
|
87
|
+
results: QueryResult[],
|
|
88
|
+
query: string,
|
|
89
|
+
model: LanguageModelV1,
|
|
90
|
+
options: RerankerFunctionOptions,
|
|
91
|
+
): Promise<RerankResult[]> {
|
|
92
|
+
let semanticProvider: RelevanceScoreProvider;
|
|
93
|
+
if (model.modelId === 'rerank-v3.5') {
|
|
94
|
+
semanticProvider = new CohereRelevanceScorer(model.modelId);
|
|
95
|
+
} else {
|
|
96
|
+
semanticProvider = new MastraAgentRelevanceScorer(model.provider, model);
|
|
97
|
+
}
|
|
98
|
+
const { queryEmbedding, topK = 3 } = options;
|
|
99
|
+
const weights = {
|
|
100
|
+
...DEFAULT_WEIGHTS,
|
|
101
|
+
...options.weights,
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
//weights must add up to 1
|
|
105
|
+
const totalWeights = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
|
|
106
|
+
if (totalWeights !== 1) {
|
|
107
|
+
throw new Error('Weights must add up to 1');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const resultLength = results.length;
|
|
111
|
+
|
|
112
|
+
const queryAnalysis = queryEmbedding ? analyzeQueryEmbedding(queryEmbedding) : null;
|
|
113
|
+
|
|
114
|
+
// Get scores for each result
|
|
115
|
+
const scoredResults = await Promise.all(
|
|
116
|
+
results.map(async (result, index) => {
|
|
117
|
+
// Get semantic score from chosen provider
|
|
118
|
+
const semanticScore = await semanticProvider.getRelevanceScore(query, result?.metadata?.text);
|
|
119
|
+
|
|
120
|
+
// Get existing vector score from result
|
|
121
|
+
const vectorScore = result.score;
|
|
122
|
+
|
|
123
|
+
// Get score of vector based on position in original list
|
|
124
|
+
const positionScore = calculatePositionScore(index, resultLength);
|
|
125
|
+
|
|
126
|
+
// Combine scores using weights for each component
|
|
127
|
+
let finalScore =
|
|
128
|
+
weights.semantic * semanticScore + weights.vector * vectorScore + weights.position * positionScore;
|
|
129
|
+
|
|
130
|
+
if (queryAnalysis) {
|
|
131
|
+
finalScore = adjustScores(finalScore, queryAnalysis);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
result,
|
|
136
|
+
score: finalScore,
|
|
137
|
+
details: {
|
|
138
|
+
semantic: semanticScore,
|
|
139
|
+
vector: vectorScore,
|
|
140
|
+
position: positionScore,
|
|
141
|
+
...(queryAnalysis && {
|
|
142
|
+
queryAnalysis: {
|
|
143
|
+
magnitude: queryAnalysis.magnitude,
|
|
144
|
+
dominantFeatures: queryAnalysis.dominantFeatures,
|
|
145
|
+
},
|
|
146
|
+
}),
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}),
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
// Sort by score and take top K
|
|
153
|
+
return scoredResults.sort((a, b) => b.score - a.score).slice(0, topK);
|
|
154
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createTool } from '@mastra/core/tools';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
import type { MDocument, ChunkParams } from '../document';
|
|
5
|
+
|
|
6
|
+
export const createDocumentChunkerTool = ({
|
|
7
|
+
doc,
|
|
8
|
+
params = {
|
|
9
|
+
strategy: 'recursive',
|
|
10
|
+
size: 512,
|
|
11
|
+
overlap: 50,
|
|
12
|
+
separator: '\n',
|
|
13
|
+
},
|
|
14
|
+
}: {
|
|
15
|
+
doc: MDocument;
|
|
16
|
+
params?: ChunkParams;
|
|
17
|
+
}): ReturnType<typeof createTool> => {
|
|
18
|
+
return createTool({
|
|
19
|
+
id: `Document Chunker ${params.strategy} ${params.size}`,
|
|
20
|
+
inputSchema: z.object({}),
|
|
21
|
+
description: `Chunks document using ${params.strategy} strategy with size ${params.size} and ${params.overlap} overlap`,
|
|
22
|
+
execute: async () => {
|
|
23
|
+
const chunks = await doc.chunk(params);
|
|
24
|
+
|
|
25
|
+
return {
|
|
26
|
+
chunks,
|
|
27
|
+
};
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { createTool } from '@mastra/core/tools';
|
|
2
|
+
import type { EmbeddingModel } from 'ai';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
import { GraphRAG } from '../graph-rag';
|
|
6
|
+
import { vectorQuerySearch, defaultGraphRagDescription } from '../utils';
|
|
7
|
+
|
|
8
|
+
export const createGraphRAGTool = ({
|
|
9
|
+
vectorStoreName,
|
|
10
|
+
indexName,
|
|
11
|
+
model,
|
|
12
|
+
enableFilter = false,
|
|
13
|
+
graphOptions = {
|
|
14
|
+
dimension: 1536,
|
|
15
|
+
randomWalkSteps: 100,
|
|
16
|
+
restartProb: 0.15,
|
|
17
|
+
threshold: 0.7,
|
|
18
|
+
},
|
|
19
|
+
id,
|
|
20
|
+
description,
|
|
21
|
+
}: {
|
|
22
|
+
vectorStoreName: string;
|
|
23
|
+
indexName: string;
|
|
24
|
+
model: EmbeddingModel<string>;
|
|
25
|
+
enableFilter?: boolean;
|
|
26
|
+
graphOptions?: {
|
|
27
|
+
dimension?: number;
|
|
28
|
+
randomWalkSteps?: number;
|
|
29
|
+
restartProb?: number;
|
|
30
|
+
threshold?: number;
|
|
31
|
+
};
|
|
32
|
+
id?: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
}): ReturnType<typeof createTool> => {
|
|
35
|
+
const toolId = id || `GraphRAG ${vectorStoreName} ${indexName} Tool`;
|
|
36
|
+
const toolDescription = description || defaultGraphRagDescription(vectorStoreName, indexName);
|
|
37
|
+
|
|
38
|
+
// Initialize GraphRAG
|
|
39
|
+
const graphRag = new GraphRAG(graphOptions.dimension, graphOptions.threshold);
|
|
40
|
+
let isInitialized = false;
|
|
41
|
+
|
|
42
|
+
return createTool({
|
|
43
|
+
id: toolId,
|
|
44
|
+
inputSchema: z.object({
|
|
45
|
+
queryText: z.string(),
|
|
46
|
+
topK: z.number(),
|
|
47
|
+
filter: z.string(),
|
|
48
|
+
}),
|
|
49
|
+
outputSchema: z.object({
|
|
50
|
+
relevantContext: z.any(),
|
|
51
|
+
}),
|
|
52
|
+
description: toolDescription,
|
|
53
|
+
execute: async ({ context: { queryText, topK, filter }, mastra }) => {
|
|
54
|
+
const vectorStore = mastra?.vectors?.[vectorStoreName];
|
|
55
|
+
|
|
56
|
+
if (vectorStore) {
|
|
57
|
+
let queryFilter = {};
|
|
58
|
+
if (enableFilter) {
|
|
59
|
+
queryFilter = filter
|
|
60
|
+
? (() => {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(filter);
|
|
63
|
+
} catch {
|
|
64
|
+
return filter;
|
|
65
|
+
}
|
|
66
|
+
})()
|
|
67
|
+
: filter;
|
|
68
|
+
}
|
|
69
|
+
if (mastra.logger) {
|
|
70
|
+
mastra.logger.debug('Using this filter and topK:', { queryFilter, topK });
|
|
71
|
+
}
|
|
72
|
+
const { results, queryEmbedding } = await vectorQuerySearch({
|
|
73
|
+
indexName,
|
|
74
|
+
vectorStore,
|
|
75
|
+
queryText,
|
|
76
|
+
model,
|
|
77
|
+
queryFilter: Object.keys(queryFilter || {}).length > 0 ? queryFilter : undefined,
|
|
78
|
+
topK,
|
|
79
|
+
includeVectors: true,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Initialize graph if not done yet
|
|
83
|
+
if (!isInitialized) {
|
|
84
|
+
// Get all chunks and embeddings for graph construction
|
|
85
|
+
const chunks = results.map(result => ({
|
|
86
|
+
text: result?.metadata?.text,
|
|
87
|
+
metadata: result.metadata ?? {},
|
|
88
|
+
}));
|
|
89
|
+
const embeddings = results.map(result => ({
|
|
90
|
+
vector: result.vector || [],
|
|
91
|
+
}));
|
|
92
|
+
|
|
93
|
+
graphRag.createGraph(chunks, embeddings);
|
|
94
|
+
isInitialized = true;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Get reranked results using GraphRAG
|
|
98
|
+
const rerankedResults = graphRag.query({
|
|
99
|
+
query: queryEmbedding,
|
|
100
|
+
topK,
|
|
101
|
+
randomWalkSteps: graphOptions.randomWalkSteps,
|
|
102
|
+
restartProb: graphOptions.restartProb,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// Extract and combine relevant chunks
|
|
106
|
+
const relevantChunks = rerankedResults.map(result => result.content);
|
|
107
|
+
return {
|
|
108
|
+
relevantContext: relevantChunks,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
relevantContext: [],
|
|
114
|
+
};
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { createTool } from '@mastra/core/tools';
|
|
2
|
+
import type { EmbeddingModel } from 'ai';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
import { rerank } from '../rerank';
|
|
6
|
+
import type { RerankConfig } from '../rerank';
|
|
7
|
+
import { vectorQuerySearch, defaultVectorQueryDescription } from '../utils';
|
|
8
|
+
|
|
9
|
+
export const createVectorQueryTool = ({
|
|
10
|
+
vectorStoreName,
|
|
11
|
+
indexName,
|
|
12
|
+
model,
|
|
13
|
+
enableFilter = false,
|
|
14
|
+
reranker,
|
|
15
|
+
id,
|
|
16
|
+
description,
|
|
17
|
+
}: {
|
|
18
|
+
vectorStoreName: string;
|
|
19
|
+
indexName: string;
|
|
20
|
+
model: EmbeddingModel<string>;
|
|
21
|
+
enableFilter?: boolean;
|
|
22
|
+
reranker?: RerankConfig;
|
|
23
|
+
id?: string;
|
|
24
|
+
description?: string;
|
|
25
|
+
}): ReturnType<typeof createTool> => {
|
|
26
|
+
const toolId = id || `VectorQuery ${vectorStoreName} ${indexName} Tool`;
|
|
27
|
+
const toolDescription = description || defaultVectorQueryDescription(vectorStoreName, indexName);
|
|
28
|
+
|
|
29
|
+
return createTool({
|
|
30
|
+
id: toolId,
|
|
31
|
+
inputSchema: z.object({
|
|
32
|
+
queryText: z.string(),
|
|
33
|
+
topK: z.number(),
|
|
34
|
+
filter: z.string(),
|
|
35
|
+
}),
|
|
36
|
+
outputSchema: z.object({
|
|
37
|
+
relevantContext: z.any(),
|
|
38
|
+
}),
|
|
39
|
+
description: toolDescription,
|
|
40
|
+
execute: async ({ context: { queryText, topK, filter }, mastra }) => {
|
|
41
|
+
const vectorStore = mastra?.vectors?.[vectorStoreName];
|
|
42
|
+
|
|
43
|
+
// Get relevant chunks from the vector database
|
|
44
|
+
if (vectorStore) {
|
|
45
|
+
let queryFilter = {};
|
|
46
|
+
if (enableFilter) {
|
|
47
|
+
queryFilter = filter
|
|
48
|
+
? (() => {
|
|
49
|
+
try {
|
|
50
|
+
return JSON.parse(filter);
|
|
51
|
+
} catch {
|
|
52
|
+
return filter;
|
|
53
|
+
}
|
|
54
|
+
})()
|
|
55
|
+
: filter;
|
|
56
|
+
}
|
|
57
|
+
if (mastra.logger) {
|
|
58
|
+
mastra.logger.debug('Using this filter and topK:', { queryFilter, topK });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const { results } = await vectorQuerySearch({
|
|
62
|
+
indexName,
|
|
63
|
+
vectorStore,
|
|
64
|
+
queryText,
|
|
65
|
+
model,
|
|
66
|
+
queryFilter: Object.keys(queryFilter || {}).length > 0 ? queryFilter : undefined,
|
|
67
|
+
topK,
|
|
68
|
+
});
|
|
69
|
+
if (reranker) {
|
|
70
|
+
const rerankedResults = await rerank(results, queryText, reranker.model, {
|
|
71
|
+
...reranker.options,
|
|
72
|
+
topK: reranker.options?.topK || topK,
|
|
73
|
+
});
|
|
74
|
+
const relevantChunks = rerankedResults.map(({ result }) => result?.metadata);
|
|
75
|
+
return { relevantContext: relevantChunks };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const relevantChunks = results.map(result => result?.metadata);
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
relevantContext: relevantChunks,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
relevantContext: [],
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const defaultTopK = `You MUST generate for each query:
|
|
2
|
+
topK: number of results to return (REQUIRED) (Default: 10)
|
|
3
|
+
- Generate topK based on exactly what user specifies
|
|
4
|
+
- must be a valid number
|
|
5
|
+
|
|
6
|
+
Notes:
|
|
7
|
+
- If user provides a valid topK, use the topK provided
|
|
8
|
+
- If user does not specify topK or provides an invalid topK, use default topK: 10
|
|
9
|
+
`;
|
|
10
|
+
|
|
11
|
+
export const defaultFilter = `You MUST generate for each query:
|
|
12
|
+
filter: query filter (REQUIRED) (Default: {})
|
|
13
|
+
- Generate filter based on user's explicit query intent
|
|
14
|
+
- Must be valid JSON string
|
|
15
|
+
|
|
16
|
+
Notes:
|
|
17
|
+
- If user provides a valid filter, use the filter provided
|
|
18
|
+
- If user does not specify filter or provides an invalid filter, use default filter: {}
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
export const defaultVectorQueryDescription = (vectorStoreName: string, indexName: string) =>
|
|
22
|
+
`Retrieves relevant information from ${vectorStoreName} using ${indexName} index.
|
|
23
|
+
|
|
24
|
+
${defaultTopK}
|
|
25
|
+
${defaultFilter}
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
export const defaultGraphRagDescription = (vectorStoreName: string, indexName: string) =>
|
|
29
|
+
`Fetches and reranks the most relevant chunks using GraphRAG from the ${vectorStoreName} vector store using the ${indexName} index.
|
|
30
|
+
|
|
31
|
+
${defaultTopK}
|
|
32
|
+
${defaultFilter}
|
|
33
|
+
`;
|