@mastra/rag 2.4.0-alpha.0 → 2.4.1-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.
- package/CHANGELOG.md +30 -0
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-rag-chunking-and-embedding.md +2 -0
- package/dist/docs/references/docs-rag-graph-rag.md +2 -0
- package/dist/docs/references/docs-rag-overview.md +2 -0
- package/dist/docs/references/docs-rag-retrieval.md +2 -0
- package/dist/docs/references/reference-rag-chunk.md +4 -2
- package/dist/docs/references/reference-rag-database-config.md +2 -0
- package/dist/docs/references/reference-rag-document.md +2 -0
- package/dist/docs/references/reference-rag-extract-params.md +2 -0
- package/dist/docs/references/reference-rag-graph-rag.md +2 -0
- package/dist/docs/references/reference-rag-rerank.md +2 -0
- package/dist/docs/references/reference-rag-rerankWithScorer.md +2 -0
- package/dist/docs/references/reference-tools-document-chunker-tool.md +2 -0
- package/dist/docs/references/reference-tools-graph-rag-tool.md +3 -1
- package/dist/docs/references/reference-tools-vector-query-tool.md +3 -1
- package/dist/document/transformers/character.d.ts.map +1 -1
- package/dist/index.cjs +79 -48
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +79 -48
- package/dist/index.js.map +1 -1
- package/dist/rerank/index.d.ts.map +1 -1
- package/dist/rerank/relevance/cohere/index.d.ts.map +1 -1
- package/dist/rerank/relevance/mastra-agent/index.d.ts.map +1 -1
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# @mastra/rag
|
|
2
2
|
|
|
3
|
+
## 2.4.1-alpha.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed token chunking to reject overlaps that cannot advance. ([#19213](https://github.com/mastra-ai/mastra/pull/19213))
|
|
8
|
+
|
|
9
|
+
- Fixed RAG rerank observability spans to record scoring failures before rethrowing. ([#19246](https://github.com/mastra-ai/mastra/pull/19246))
|
|
10
|
+
|
|
11
|
+
- Fixed RAG filter parsing to reject JSON string filters that parse to non-object values. ([#19244](https://github.com/mastra-ai/mastra/pull/19244))
|
|
12
|
+
|
|
13
|
+
- Fixed Mastra agent relevance scoring to reject invalid model score output. ([#19251](https://github.com/mastra-ai/mastra/pull/19251))
|
|
14
|
+
|
|
15
|
+
- Fixed character chunking to preserve content with custom length functions. ([#19214](https://github.com/mastra-ai/mastra/pull/19214))
|
|
16
|
+
|
|
17
|
+
- Fixed Cohere relevance scoring to use COHERE_API_KEY by default and accept zero relevance scores. ([#19238](https://github.com/mastra-ai/mastra/pull/19238))
|
|
18
|
+
|
|
19
|
+
- Updated dependencies [[`a5c6337`](https://github.com/mastra-ai/mastra/commit/a5c6337d23c7686c81a32ce62f550f610543a240), [`8b97958`](https://github.com/mastra-ai/mastra/commit/8b979589f9aa59ba67cac565949475f2ffeb4ac3), [`8410541`](https://github.com/mastra-ai/mastra/commit/84105412c60ecd3bb33a9838146f59c4b588228f), [`01b338c`](https://github.com/mastra-ai/mastra/commit/01b338c56271f0219606710e3e8b26dee27ac6c2), [`8b7361d`](https://github.com/mastra-ai/mastra/commit/8b7361d35de68b80d05d30a74e0c69e7218fd612), [`c43f3a9`](https://github.com/mastra-ai/mastra/commit/c43f3a9d1efde99b38789364ba4d0ba670f430e3)]:
|
|
20
|
+
- @mastra/core@1.51.0-alpha.4
|
|
21
|
+
|
|
22
|
+
## 2.4.0
|
|
23
|
+
|
|
24
|
+
### Minor Changes
|
|
25
|
+
|
|
26
|
+
- Added MongoDBConfig to DatabaseConfig, exposing numCandidates for MongoDB Atlas Vector Search queries via the RAG tool layer. ([#18393](https://github.com/mastra-ai/mastra/pull/18393))
|
|
27
|
+
|
|
28
|
+
### Patch Changes
|
|
29
|
+
|
|
30
|
+
- Updated dependencies [[`b9a2961`](https://github.com/mastra-ai/mastra/commit/b9a2961c1be81e3639c0879e58588c26dd0ae866), [`b33c77d`](https://github.com/mastra-ai/mastra/commit/b33c77d5293f14a794f3ec38dc947a6676de2764), [`1274eb3`](https://github.com/mastra-ai/mastra/commit/1274eb3a9508f579ceb3187fbce34408222d4b71), [`cdd5f93`](https://github.com/mastra-ai/mastra/commit/cdd5f939cefa67390629704dce92563ccbf492b2), [`1274eb3`](https://github.com/mastra-ai/mastra/commit/1274eb3a9508f579ceb3187fbce34408222d4b71), [`0ac14ce`](https://github.com/mastra-ai/mastra/commit/0ac14cea48e1b0a7857782153c78f7242fdf7e1a), [`9566d27`](https://github.com/mastra-ai/mastra/commit/9566d27ead3d95bdbe5a69e5a082a68222829cf2), [`8be63b0`](https://github.com/mastra-ai/mastra/commit/8be63b015fb8d72cea1220f05e7dc3bb997cc249), [`1009f77`](https://github.com/mastra-ai/mastra/commit/1009f772aa40016b49267c8566d0c29f6a16aa3c), [`1b8728a`](https://github.com/mastra-ai/mastra/commit/1b8728a57fd844205a452b0b4216d20ff60c784a), [`23c31de`](https://github.com/mastra-ai/mastra/commit/23c31de96ed8153402dcf092ac84b27a0c3638c1), [`0368766`](https://github.com/mastra-ai/mastra/commit/0368766744c7ea3df4d6059e2cc15f7bdf55f5a6), [`6f578ac`](https://github.com/mastra-ai/mastra/commit/6f578acba84930b406b2a0700b17cfdfaf5aae56), [`345eecc`](https://github.com/mastra-ai/mastra/commit/345eecce6ba519b5d987f0e10b5de4c8e5734580), [`1917c53`](https://github.com/mastra-ai/mastra/commit/1917c53b19dac43926f29c496893b0686462dca4), [`c01012f`](https://github.com/mastra-ai/mastra/commit/c01012f50368d29eb3fc3764df42d48291973d23), [`705ba98`](https://github.com/mastra-ai/mastra/commit/705ba98726d388a596e896225f237907ca6807a9), [`95857bc`](https://github.com/mastra-ai/mastra/commit/95857bcd6669da7193f503e803f0d72a2bd66be6), [`e62c108`](https://github.com/mastra-ai/mastra/commit/e62c108409dfd6a6cac0a48ec39c5cc81d24fd52), [`2866f04`](https://github.com/mastra-ai/mastra/commit/2866f04953edb78c1637fa45cc53abe24122edcb), [`ee14cae`](https://github.com/mastra-ai/mastra/commit/ee14cae244805783bde518a6142de28b744b169c), [`e84e791`](https://github.com/mastra-ai/mastra/commit/e84e79174031d7bc8793ca6c805eb38b06e7cfb1), [`c2f0b7f`](https://github.com/mastra-ai/mastra/commit/c2f0b7f1370f4428d165f51f0d1d9a48331cc257), [`213feb8`](https://github.com/mastra-ai/mastra/commit/213feb87bfdd1d8ec00ea660e218f9bcfcb34e7b), [`58e287b`](https://github.com/mastra-ai/mastra/commit/58e287b1edaf978b13745a1795989cad3826e82b), [`e420b3c`](https://github.com/mastra-ai/mastra/commit/e420b3c3ffc98bbc5b791897ea390bb47af99696), [`be875ed`](https://github.com/mastra-ai/mastra/commit/be875ed43f856742ce58529f531b5ea0ae6911f3), [`9eefdc0`](https://github.com/mastra-ai/mastra/commit/9eefdc0ac03f989718c6d835334940a977938895), [`bfbbb01`](https://github.com/mastra-ai/mastra/commit/bfbbb01bd845ba54cdc0c678c277d08a7cb847e4), [`7d112ca`](https://github.com/mastra-ai/mastra/commit/7d112ca17078479b2659b88ba1c85b936cfc111c)]:
|
|
31
|
+
- @mastra/core@1.48.0
|
|
32
|
+
|
|
3
33
|
## 2.4.0-alpha.0
|
|
4
34
|
|
|
5
35
|
### Minor Changes
|
package/dist/docs/SKILL.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# GraphRAG
|
|
2
4
|
|
|
3
5
|
Graph-based retrieval enhances traditional vector search by following relationships between chunks of information. This approach is useful when information is spread across multiple documents or when documents reference each other.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# RAG (Retrieval-Augmented Generation) in Mastra
|
|
2
4
|
|
|
3
5
|
RAG in Mastra helps you enhance LLM outputs by incorporating relevant context from your own data sources, improving accuracy and grounding responses in real information.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# .chunk()
|
|
2
4
|
|
|
3
5
|
The `.chunk()` function splits documents into smaller segments using various strategies and options.
|
|
@@ -176,9 +178,9 @@ The options documented below are passed directly at the top level of the configu
|
|
|
176
178
|
|
|
177
179
|
**joinThreshold** (`number`): Maximum token count for merging related sections. Sections exceeding this limit individually are left intact, but smaller sections are merged with siblings or parents if the combined size stays under this threshold. (Default: `500`)
|
|
178
180
|
|
|
179
|
-
**modelName** (`string`): Name of the model for tokenization. If provided, the model's underlying tokenization
|
|
181
|
+
**modelName** (`string`): Name of the model for tokenization. If provided, the model's underlying tokenization encodingName will be used.
|
|
180
182
|
|
|
181
|
-
**encodingName** (`string`): Name of the token encoding to use. Derived from
|
|
183
|
+
**encodingName** (`string`): Name of the token encoding to use. Derived from modelName if available. (Default: `cl100k_base`)
|
|
182
184
|
|
|
183
185
|
**allowedSpecial** (`Set<string> | 'all'`): Set of special tokens allowed during tokenization, or 'all' to allow all special tokens
|
|
184
186
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# DatabaseConfig
|
|
2
4
|
|
|
3
5
|
The `DatabaseConfig` type allows you to specify database-specific configurations when using vector query tools. These configurations enable you to leverage unique features and optimizations offered by different vector stores.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# GraphRAG
|
|
2
4
|
|
|
3
5
|
The `GraphRAG` class implements a graph-based approach to retrieval augmented generation. It creates a knowledge graph from document chunks where nodes represent documents and edges represent semantic relationships, enabling both direct similarity matching and discovery of related content through graph traversal.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# rerank()
|
|
2
4
|
|
|
3
5
|
The `rerank()` function provides advanced reranking capabilities for vector search results by combining semantic relevance, vector similarity, and position-based scoring.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# rerankWithScorer()
|
|
2
4
|
|
|
3
5
|
The `rerankWithScorer()` function provides advanced reranking capabilities for vector search results by combining semantic relevance, vector similarity, and position-based scoring.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# createDocumentChunkerTool()
|
|
2
4
|
|
|
3
5
|
The `createDocumentChunkerTool()` function creates a tool for splitting documents into smaller chunks for efficient processing and retrieval. It supports different chunking strategies and configurable parameters.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# createGraphRAGTool()
|
|
2
4
|
|
|
3
5
|
The `createGraphRAGTool()` creates a tool that enhances RAG by building a graph of semantic relationships between documents. It uses the `GraphRAG` system under the hood to provide graph-based retrieval, finding relevant content through both direct similarity and connected relationships.
|
|
@@ -51,7 +53,7 @@ const graphTool = createGraphRAGTool({
|
|
|
51
53
|
|
|
52
54
|
**providerOptions** (`Record<string, Record<string, any>>`): Provider-specific options for the embedding model (e.g., outputDimensionality). \*\*Important\*\*: Only works with AI SDK EmbeddingModelV2 models. For V1 models, configure options when creating the model itself.
|
|
53
55
|
|
|
54
|
-
**vectorStore** (`MastraVector | VectorStoreResolver`): Direct vector store instance or a resolver function for dynamic selection. Use a function for multi-tenant applications where the vector store is selected based on request context. When provided,
|
|
56
|
+
**vectorStore** (`MastraVector | VectorStoreResolver`): Direct vector store instance or a resolver function for dynamic selection. Use a function for multi-tenant applications where the vector store is selected based on request context. When provided, vectorStoreName becomes optional.
|
|
55
57
|
|
|
56
58
|
## Returns
|
|
57
59
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
|
|
2
|
+
|
|
1
3
|
# createVectorQueryTool()
|
|
2
4
|
|
|
3
5
|
The `createVectorQueryTool()` function creates a tool for semantic search over vector stores. It supports filtering, reranking, database-specific configurations, and integrates with various vector store backends.
|
|
@@ -69,7 +71,7 @@ const queryTool = createVectorQueryTool({
|
|
|
69
71
|
|
|
70
72
|
**providerOptions** (`Record<string, Record<string, any>>`): Provider-specific options for the embedding model (e.g., outputDimensionality). \*\*Important\*\*: Only works with AI SDK EmbeddingModelV2 models. For V1 models, configure options when creating the model itself.
|
|
71
73
|
|
|
72
|
-
**vectorStore** (`MastraVector | VectorStoreResolver`): Direct vector store instance or a resolver function for dynamic selection. Use a function for multi-tenant applications where the vector store is selected based on request context. When provided,
|
|
74
|
+
**vectorStore** (`MastraVector | VectorStoreResolver`): Direct vector store instance or a resolver function for dynamic selection. Use a function for multi-tenant applications where the vector store is selected based on request context. When provided, vectorStoreName becomes optional.
|
|
73
75
|
|
|
74
76
|
## Returns
|
|
75
77
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"character.d.ts","sourceRoot":"","sources":["../../../src/document/transformers/character.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AA+CzC,qBAAa,oBAAqB,SAAQ,eAAe;IACvD,SAAS,CAAC,SAAS,EAAE,MAAM,CAAC;IAC5B,SAAS,CAAC,gBAAgB,EAAE,OAAO,CAAC;gBAExB,EAAE,SAAkB,EAAE,gBAAwB,EAAE,GAAG,WAAW,EAAE,GAAE,qBAA0B;IAMxG,SAAS,CAAC,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,EAAE;IAqB/C,OAAO,CAAC,YAAY;
|
|
1
|
+
{"version":3,"file":"character.d.ts","sourceRoot":"","sources":["../../../src/document/transformers/character.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AA+CzC,qBAAa,oBAAqB,SAAQ,eAAe;IACvD,SAAS,CAAC,SAAS,EAAE,MAAM,CAAC;IAC5B,SAAS,CAAC,gBAAgB,EAAE,OAAO,CAAC;gBAExB,EAAE,SAAkB,EAAE,gBAAwB,EAAE,GAAG,WAAW,EAAE,GAAE,qBAA0B;IAMxG,SAAS,CAAC,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,EAAE;IAqB/C,OAAO,CAAC,YAAY;CAyDrB;AAED,qBAAa,6BAA8B,SAAQ,eAAe;IAChE,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,CAAC;IAC/B,SAAS,CAAC,gBAAgB,EAAE,OAAO,CAAC;gBAExB,EAAE,UAAU,EAAE,gBAAwB,EAAE,QAAQ,EAAE,GAAG,WAAW,EAAE,GAAE,qBAA0B;IAM1G,OAAO,CAAC,UAAU;IAuDlB,SAAS,CAAC,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,EAAE;IAI/C,MAAM,CAAC,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,GAAE,gBAAqB,GAAG,6BAA6B;IAUtG,MAAM,CAAC,wBAAwB,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,EAAE;CAwa9D"}
|
package/dist/index.cjs
CHANGED
|
@@ -4537,8 +4537,8 @@ var TextTransformer = class {
|
|
|
4537
4537
|
addStartIndex = false,
|
|
4538
4538
|
stripWhitespace = true
|
|
4539
4539
|
}) {
|
|
4540
|
-
if (overlap
|
|
4541
|
-
throw new Error(`
|
|
4540
|
+
if (overlap >= maxSize) {
|
|
4541
|
+
throw new Error(`Chunk overlap (${overlap}) must be smaller than chunk size (${maxSize}).`);
|
|
4542
4542
|
}
|
|
4543
4543
|
this.maxSize = maxSize;
|
|
4544
4544
|
this.overlap = overlap;
|
|
@@ -4707,17 +4707,31 @@ var CharacterTransformer = class extends TextTransformer {
|
|
|
4707
4707
|
}
|
|
4708
4708
|
__splitChunk(text) {
|
|
4709
4709
|
const chunks = [];
|
|
4710
|
-
|
|
4711
|
-
|
|
4712
|
-
|
|
4713
|
-
|
|
4714
|
-
|
|
4715
|
-
|
|
4716
|
-
|
|
4717
|
-
|
|
4710
|
+
const codePointBoundaries = [0];
|
|
4711
|
+
for (const codePoint of text) {
|
|
4712
|
+
codePointBoundaries.push(codePointBoundaries[codePointBoundaries.length - 1] + codePoint.length);
|
|
4713
|
+
}
|
|
4714
|
+
const finalBoundaryIndex = codePointBoundaries.length - 1;
|
|
4715
|
+
let currentBoundaryIndex = 0;
|
|
4716
|
+
while (currentBoundaryIndex < finalBoundaryIndex) {
|
|
4717
|
+
let chunkEndBoundaryIndex = currentBoundaryIndex;
|
|
4718
|
+
while (chunkEndBoundaryIndex < finalBoundaryIndex && this.lengthFunction(
|
|
4719
|
+
text.slice(codePointBoundaries[currentBoundaryIndex], codePointBoundaries[chunkEndBoundaryIndex + 1])
|
|
4720
|
+
) <= this.maxSize) {
|
|
4721
|
+
chunkEndBoundaryIndex++;
|
|
4722
|
+
}
|
|
4723
|
+
if (chunkEndBoundaryIndex === currentBoundaryIndex) {
|
|
4724
|
+
chunkEndBoundaryIndex++;
|
|
4725
|
+
}
|
|
4726
|
+
const chunkEnd = codePointBoundaries[chunkEndBoundaryIndex];
|
|
4727
|
+
const currentChunk = text.slice(codePointBoundaries[currentBoundaryIndex], chunkEnd);
|
|
4718
4728
|
chunks.push(currentChunk);
|
|
4719
|
-
if (
|
|
4720
|
-
|
|
4729
|
+
if (chunkEndBoundaryIndex >= finalBoundaryIndex) break;
|
|
4730
|
+
let nextBoundaryIndex = chunkEndBoundaryIndex;
|
|
4731
|
+
while (this.overlap > 0 && nextBoundaryIndex > currentBoundaryIndex && this.lengthFunction(text.slice(codePointBoundaries[nextBoundaryIndex - 1], chunkEnd)) <= this.overlap) {
|
|
4732
|
+
nextBoundaryIndex--;
|
|
4733
|
+
}
|
|
4734
|
+
currentBoundaryIndex = Math.max(currentBoundaryIndex + 1, nextBoundaryIndex);
|
|
4721
4735
|
}
|
|
4722
4736
|
return chunks;
|
|
4723
4737
|
}
|
|
@@ -6976,10 +6990,13 @@ var CohereRelevanceScorer = class {
|
|
|
6976
6990
|
model;
|
|
6977
6991
|
apiKey;
|
|
6978
6992
|
constructor(model, apiKey) {
|
|
6979
|
-
this.apiKey = apiKey;
|
|
6993
|
+
this.apiKey = apiKey ?? process.env.COHERE_API_KEY;
|
|
6980
6994
|
this.model = model;
|
|
6981
6995
|
}
|
|
6982
6996
|
async getRelevanceScore(query, text) {
|
|
6997
|
+
if (!this.apiKey) {
|
|
6998
|
+
throw new Error("Cohere API key is required. Pass an apiKey or set COHERE_API_KEY.");
|
|
6999
|
+
}
|
|
6983
7000
|
const response = await fetch(`https://api.cohere.com/v2/rerank`, {
|
|
6984
7001
|
method: "POST",
|
|
6985
7002
|
headers: {
|
|
@@ -6998,12 +7015,20 @@ var CohereRelevanceScorer = class {
|
|
|
6998
7015
|
}
|
|
6999
7016
|
const data = await response.json();
|
|
7000
7017
|
const relevanceScore = data.results[0]?.relevance_score;
|
|
7001
|
-
if (!relevanceScore) {
|
|
7018
|
+
if (typeof relevanceScore !== "number" || !Number.isFinite(relevanceScore)) {
|
|
7002
7019
|
throw new Error("No relevance score found on Cohere response");
|
|
7003
7020
|
}
|
|
7004
7021
|
return relevanceScore;
|
|
7005
7022
|
}
|
|
7006
7023
|
};
|
|
7024
|
+
function parseRelevanceScore(responseText) {
|
|
7025
|
+
const trimmed = responseText.trim();
|
|
7026
|
+
const score = Number(trimmed);
|
|
7027
|
+
if (!trimmed || !Number.isFinite(score) || score < 0 || score > 1) {
|
|
7028
|
+
throw new Error(`Invalid relevance score returned by model: ${responseText}`);
|
|
7029
|
+
}
|
|
7030
|
+
return score;
|
|
7031
|
+
}
|
|
7007
7032
|
var MastraAgentRelevanceScorer = class {
|
|
7008
7033
|
agent;
|
|
7009
7034
|
constructor(name14, model) {
|
|
@@ -7032,7 +7057,7 @@ Always return just the number, no explanation.`,
|
|
|
7032
7057
|
} else {
|
|
7033
7058
|
response = await this.agent.generateLegacy(prompt);
|
|
7034
7059
|
}
|
|
7035
|
-
return
|
|
7060
|
+
return parseRelevanceScore(response.text);
|
|
7036
7061
|
}
|
|
7037
7062
|
};
|
|
7038
7063
|
var ZeroEntropyRelevanceScorer = class {
|
|
@@ -7104,35 +7129,41 @@ async function executeRerank({
|
|
|
7104
7129
|
}
|
|
7105
7130
|
const resultLength = results.length;
|
|
7106
7131
|
const queryAnalysis = queryEmbedding ? analyzeQueryEmbedding(queryEmbedding) : null;
|
|
7107
|
-
|
|
7108
|
-
|
|
7109
|
-
|
|
7110
|
-
|
|
7111
|
-
semanticScore =
|
|
7112
|
-
|
|
7113
|
-
|
|
7114
|
-
|
|
7115
|
-
|
|
7116
|
-
|
|
7117
|
-
finalScore =
|
|
7118
|
-
|
|
7119
|
-
|
|
7120
|
-
|
|
7121
|
-
|
|
7122
|
-
|
|
7123
|
-
|
|
7124
|
-
|
|
7125
|
-
|
|
7126
|
-
|
|
7127
|
-
|
|
7128
|
-
|
|
7129
|
-
|
|
7132
|
+
let scoredResults;
|
|
7133
|
+
try {
|
|
7134
|
+
scoredResults = await Promise.all(
|
|
7135
|
+
results.map(async (result, index) => {
|
|
7136
|
+
let semanticScore = 0;
|
|
7137
|
+
if (result?.metadata?.text) {
|
|
7138
|
+
semanticScore = await scorer.getRelevanceScore(query, result?.metadata?.text);
|
|
7139
|
+
}
|
|
7140
|
+
const vectorScore = result.score;
|
|
7141
|
+
const positionScore = calculatePositionScore(index, resultLength);
|
|
7142
|
+
let finalScore = weights.semantic * semanticScore + weights.vector * vectorScore + weights.position * positionScore;
|
|
7143
|
+
if (queryAnalysis) {
|
|
7144
|
+
finalScore = adjustScores(finalScore, queryAnalysis);
|
|
7145
|
+
}
|
|
7146
|
+
return {
|
|
7147
|
+
result,
|
|
7148
|
+
score: finalScore,
|
|
7149
|
+
details: {
|
|
7150
|
+
semantic: semanticScore,
|
|
7151
|
+
vector: vectorScore,
|
|
7152
|
+
position: positionScore,
|
|
7153
|
+
...queryAnalysis && {
|
|
7154
|
+
queryAnalysis: {
|
|
7155
|
+
magnitude: queryAnalysis.magnitude,
|
|
7156
|
+
dominantFeatures: queryAnalysis.dominantFeatures
|
|
7157
|
+
}
|
|
7130
7158
|
}
|
|
7131
7159
|
}
|
|
7132
|
-
}
|
|
7133
|
-
}
|
|
7134
|
-
|
|
7135
|
-
)
|
|
7160
|
+
};
|
|
7161
|
+
})
|
|
7162
|
+
);
|
|
7163
|
+
} catch (err) {
|
|
7164
|
+
rerankSpan?.error({ error: err, endSpan: true });
|
|
7165
|
+
throw err;
|
|
7166
|
+
}
|
|
7136
7167
|
const final = scoredResults.sort((a, b) => b.score - a.score).slice(0, topK);
|
|
7137
7168
|
rerankSpan?.end({ output: { returned: final.length } });
|
|
7138
7169
|
return final;
|
|
@@ -7706,9 +7737,10 @@ function parseFilterValue(filter, logger) {
|
|
|
7706
7737
|
if (!filter) {
|
|
7707
7738
|
return {};
|
|
7708
7739
|
}
|
|
7740
|
+
let parsedFilter = filter;
|
|
7709
7741
|
if (typeof filter === "string") {
|
|
7710
7742
|
try {
|
|
7711
|
-
|
|
7743
|
+
parsedFilter = JSON.parse(filter);
|
|
7712
7744
|
} catch (error) {
|
|
7713
7745
|
if (logger) {
|
|
7714
7746
|
logger.error("Invalid filter", { filter, error });
|
|
@@ -7716,15 +7748,14 @@ function parseFilterValue(filter, logger) {
|
|
|
7716
7748
|
throw new Error(`Invalid filter format: ${error instanceof Error ? error.message : String(error)}`);
|
|
7717
7749
|
}
|
|
7718
7750
|
}
|
|
7719
|
-
if (typeof
|
|
7751
|
+
if (typeof parsedFilter !== "object" || parsedFilter === null || Array.isArray(parsedFilter)) {
|
|
7752
|
+
const receivedType = Array.isArray(parsedFilter) ? "array" : typeof parsedFilter;
|
|
7720
7753
|
if (logger) {
|
|
7721
7754
|
logger.error("Invalid filter", { filter, error: "Filter must be a plain object" });
|
|
7722
7755
|
}
|
|
7723
|
-
throw new Error(
|
|
7724
|
-
`Invalid filter format: expected a plain object, got ${Array.isArray(filter) ? "array" : typeof filter}`
|
|
7725
|
-
);
|
|
7756
|
+
throw new Error(`Invalid filter format: expected a plain object, got ${receivedType}`);
|
|
7726
7757
|
}
|
|
7727
|
-
return
|
|
7758
|
+
return parsedFilter;
|
|
7728
7759
|
}
|
|
7729
7760
|
|
|
7730
7761
|
// src/utils/convert-sources.ts
|