@memberjunction/search-engine 6.2.2 → 6.3.0-edge.1
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 +28 -0
- package/dist/generic/EntitySearchProvider.d.ts.map +1 -1
- package/dist/generic/EntitySearchProvider.js +6 -3
- package/dist/generic/EntitySearchProvider.js.map +1 -1
- package/dist/generic/GraphSearchProvider.d.ts +60 -0
- package/dist/generic/GraphSearchProvider.d.ts.map +1 -0
- package/dist/generic/GraphSearchProvider.js +215 -0
- package/dist/generic/GraphSearchProvider.js.map +1 -0
- package/dist/generic/SearchEngine.d.ts +6 -0
- package/dist/generic/SearchEngine.d.ts.map +1 -1
- package/dist/generic/SearchEngine.js +30 -7
- package/dist/generic/SearchEngine.js.map +1 -1
- package/dist/generic/SearchFusion.d.ts.map +1 -1
- package/dist/generic/SearchFusion.js +9 -1
- package/dist/generic/SearchFusion.js.map +1 -1
- package/dist/generic/StorageSearchProvider.d.ts.map +1 -1
- package/dist/generic/StorageSearchProvider.js +15 -1
- package/dist/generic/StorageSearchProvider.js.map +1 -1
- package/dist/generic/VectorSearchProvider.d.ts.map +1 -1
- package/dist/generic/VectorSearchProvider.js +2 -1
- package/dist/generic/VectorSearchProvider.js.map +1 -1
- package/dist/generic/search.types.d.ts +15 -1
- package/dist/generic/search.types.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/providers/ElasticsearchSearchProvider.js +1 -1
- package/dist/providers/ElasticsearchSearchProvider.js.map +1 -1
- package/dist/rerankers/BGEReRanker.d.ts +18 -4
- package/dist/rerankers/BGEReRanker.d.ts.map +1 -1
- package/dist/rerankers/BGEReRanker.js +66 -92
- package/dist/rerankers/BGEReRanker.js.map +1 -1
- package/dist/rerankers/BGERerankerWorker.d.ts +17 -0
- package/dist/rerankers/BGERerankerWorker.d.ts.map +1 -0
- package/dist/rerankers/BGERerankerWorker.js +31 -0
- package/dist/rerankers/BGERerankerWorker.js.map +1 -0
- package/dist/rerankers/BGERerankerWorkerHandler.d.ts +16 -0
- package/dist/rerankers/BGERerankerWorkerHandler.d.ts.map +1 -0
- package/dist/rerankers/BGERerankerWorkerHandler.js +26 -0
- package/dist/rerankers/BGERerankerWorkerHandler.js.map +1 -0
- package/dist/rerankers/BGERerankerWorkerHost.d.ts +56 -0
- package/dist/rerankers/BGERerankerWorkerHost.d.ts.map +1 -0
- package/dist/rerankers/BGERerankerWorkerHost.js +183 -0
- package/dist/rerankers/BGERerankerWorkerHost.js.map +1 -0
- package/dist/rerankers/BGERerankerWorkerProtocol.d.ts +39 -0
- package/dist/rerankers/BGERerankerWorkerProtocol.d.ts.map +1 -0
- package/dist/rerankers/BGERerankerWorkerProtocol.js +7 -0
- package/dist/rerankers/BGERerankerWorkerProtocol.js.map +1 -0
- package/dist/rerankers/DecisionReRanker.d.ts +64 -0
- package/dist/rerankers/DecisionReRanker.d.ts.map +1 -0
- package/dist/rerankers/DecisionReRanker.js +172 -0
- package/dist/rerankers/DecisionReRanker.js.map +1 -0
- package/dist/rerankers/bgeRuntime.d.ts +27 -0
- package/dist/rerankers/bgeRuntime.d.ts.map +1 -0
- package/dist/rerankers/bgeRuntime.js +106 -0
- package/dist/rerankers/bgeRuntime.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +11 -10
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Decision-model re-ranker for SearchEngine scopes.
|
|
3
|
+
*
|
|
4
|
+
* Scores each candidate with a typed decision: one Likelihood per candidate ("this document bears on
|
|
5
|
+
* the request"), asked through the `Default Decision` prompt (or a configured decision prompt) and its
|
|
6
|
+
* failover chain. A decision call bills input tokens only, so it is a cheap way to rerank a scope
|
|
7
|
+
* without a provider key of its own: it uses whichever decision models the prompt can run on.
|
|
8
|
+
*
|
|
9
|
+
* The scoring itself is the AI layer's `DecisionReranker` (registered by `@memberjunction/ai-reranker`,
|
|
10
|
+
* which both server bootstraps load), resolved through the ClassFactory, so SearchEngine takes no
|
|
11
|
+
* dependency on it. This file adds what scope search needs on top: the scope config mapping, the
|
|
12
|
+
* relevance threshold, and per-search cost reporting from the decision runs' recorded usage.
|
|
13
|
+
*
|
|
14
|
+
* Opt-in per scope: `SearchScope.ScopeConfig.reRanker.driverClass = 'DecisionReRanker'`. No existing
|
|
15
|
+
* scope's reranker changes.
|
|
16
|
+
*
|
|
17
|
+
* @module @memberjunction/search-engine
|
|
18
|
+
*/
|
|
19
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
20
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
21
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
22
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
23
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
24
|
+
};
|
|
25
|
+
import { MJGlobal, RegisterClass } from '@memberjunction/global';
|
|
26
|
+
import { LogError } from '@memberjunction/core';
|
|
27
|
+
import { BaseReranker as AIBaseReranker } from '@memberjunction/ai';
|
|
28
|
+
import { BaseReRanker } from '../generic/BaseReRanker.js';
|
|
29
|
+
/** The AI-layer reranker this one resolves through the ClassFactory. */
|
|
30
|
+
export const DECISION_AI_RERANKER_KEY = 'DecisionReranker';
|
|
31
|
+
/**
|
|
32
|
+
* The pre-call cost estimate per candidate, in cents: about 150 input tokens per question (the
|
|
33
|
+
* candidate's title and snippet plus the shared query) at $0.10 per million input tokens. A decision
|
|
34
|
+
* call bills input tokens only. The actual cost is reported after the call from the runs' usage.
|
|
35
|
+
*/
|
|
36
|
+
export const DECISION_RERANK_ESTIMATED_CENTS_PER_CANDIDATE = 0.0015;
|
|
37
|
+
/**
|
|
38
|
+
* Wraps the AI layer's `DecisionReranker` for scope search: maps the scope config onto its options,
|
|
39
|
+
* applies the threshold, and keeps the call's usage so the cost is reported only for real calls.
|
|
40
|
+
*/
|
|
41
|
+
class DecisionScopeAIReranker extends AIBaseReranker {
|
|
42
|
+
constructor(decision) {
|
|
43
|
+
super('', 'Decision');
|
|
44
|
+
this.decision = decision;
|
|
45
|
+
this.LastCallSucceeded = false;
|
|
46
|
+
this.LastCostCents = null;
|
|
47
|
+
}
|
|
48
|
+
async doRerank(params) {
|
|
49
|
+
this.LastCallSucceeded = false;
|
|
50
|
+
this.LastCostCents = null;
|
|
51
|
+
const config = params.options ?? {};
|
|
52
|
+
const response = await this.decision.Rerank({ ...params, options: decisionOptions(config) });
|
|
53
|
+
if (!response.success) {
|
|
54
|
+
throw new Error(response.errorMessage ?? 'Decision rerank failed');
|
|
55
|
+
}
|
|
56
|
+
this.LastCallSucceeded = true;
|
|
57
|
+
this.LastCostCents = usageCents(response.Usage?.cost, response.Usage?.costCurrency);
|
|
58
|
+
return applyThreshold(response.results, config['minRelevanceThreshold']);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Scope config as the AI-layer `DecisionReranker`'s `DecisionRerankOptions`. */
|
|
62
|
+
function decisionOptions(config) {
|
|
63
|
+
return {
|
|
64
|
+
TimeoutMS: config['timeoutMS'],
|
|
65
|
+
MaxDocumentsPerCall: config['maxDocumentsPerCall'],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** A run's cost in cents, when it is reported in US dollars. */
|
|
69
|
+
function usageCents(cost, currency) {
|
|
70
|
+
if (typeof cost !== 'number' || !Number.isFinite(cost)) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
return !currency || currency.toUpperCase() === 'USD' ? cost * 100 : null;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Drops results below the threshold, unless none reaches it, in which case all are kept, as the
|
|
77
|
+
* other scope rerankers do. The scores are uncalibrated Likelihoods, so keep the threshold low.
|
|
78
|
+
*/
|
|
79
|
+
function applyThreshold(results, threshold) {
|
|
80
|
+
if (typeof threshold !== 'number') {
|
|
81
|
+
return results;
|
|
82
|
+
}
|
|
83
|
+
const kept = results.filter(r => r.relevanceScore >= threshold);
|
|
84
|
+
return kept.length > 0 ? kept : results;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Decision-model re-ranker for SearchEngine. Configured per scope via
|
|
88
|
+
* `SearchScope.ScopeConfig.reRanker.driverClass = 'DecisionReRanker'`.
|
|
89
|
+
*
|
|
90
|
+
* Configuration keys in `ScopeConfig.reRanker.config`:
|
|
91
|
+
* - `promptID`: the decision prompt to ask. Default: `Default Decision`.
|
|
92
|
+
* - `timeoutMS`: the time budget for the decision calls, all together. Default: the AI layer's 15 s.
|
|
93
|
+
* - `maxDocumentsPerCall`: candidates per decision call when no model the prompt runs on declares
|
|
94
|
+
* `Decision.MaxQuestionsPerCall`. Default: the AI layer's 20; larger lists split across parallel calls.
|
|
95
|
+
* - `minRelevanceThreshold`: relevance cutoff (0.0-1.0). The scores are uncalibrated Likelihoods, so
|
|
96
|
+
* start low (0.1). Results below it are dropped, unless none reaches it.
|
|
97
|
+
*
|
|
98
|
+
* The decisions run as the searching user. A failed rerank falls back to the fused order, as every
|
|
99
|
+
* scope reranker does.
|
|
100
|
+
*/
|
|
101
|
+
let DecisionReRanker = class DecisionReRanker extends BaseReRanker {
|
|
102
|
+
constructor() {
|
|
103
|
+
super(...arguments);
|
|
104
|
+
this.currentAIReranker = null;
|
|
105
|
+
}
|
|
106
|
+
get DriverClass() {
|
|
107
|
+
return 'DecisionReRanker';
|
|
108
|
+
}
|
|
109
|
+
get Name() {
|
|
110
|
+
return 'Decision Model';
|
|
111
|
+
}
|
|
112
|
+
get Version() {
|
|
113
|
+
return '1';
|
|
114
|
+
}
|
|
115
|
+
/** Every candidate is one question, so the list is bounded to keep a rerank's calls few and fast. */
|
|
116
|
+
GetMaxResultCount() {
|
|
117
|
+
return 200;
|
|
118
|
+
}
|
|
119
|
+
/** See {@link DECISION_RERANK_ESTIMATED_CENTS_PER_CANDIDATE}. */
|
|
120
|
+
EstimateCostCents(resultCount) {
|
|
121
|
+
return Math.max(1, resultCount) * DECISION_RERANK_ESTIMATED_CENTS_PER_CANDIDATE;
|
|
122
|
+
}
|
|
123
|
+
getAIReranker(config, contextUser) {
|
|
124
|
+
if (this.currentAIReranker)
|
|
125
|
+
return this.currentAIReranker;
|
|
126
|
+
if (!contextUser) {
|
|
127
|
+
LogError('DecisionReRanker: no user to run the decisions as; skipping the rerank.');
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
const promptID = typeof config?.['promptID'] === 'string' ? config['promptID'] : '';
|
|
131
|
+
const decision = MJGlobal.Instance.ClassFactory.TryCreateInstance(AIBaseReranker, DECISION_AI_RERANKER_KEY, '', '', promptID, contextUser);
|
|
132
|
+
if (!decision.Resolved || !decision.Instance) {
|
|
133
|
+
LogError(`DecisionReRanker: the "${DECISION_AI_RERANKER_KEY}" AI reranker is not registered (is @memberjunction/ai-reranker loaded?): ${decision.Reason}`);
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
this.currentAIReranker = new DecisionScopeAIReranker(decision.Instance);
|
|
137
|
+
return this.currentAIReranker;
|
|
138
|
+
}
|
|
139
|
+
/** Reports the decision runs' actual cost (else the estimate) after a successful rerank. */
|
|
140
|
+
async ReRank(query, candidates, topN, contextUser, config) {
|
|
141
|
+
if (topN <= 0 || candidates.length === 0)
|
|
142
|
+
return [];
|
|
143
|
+
this.currentAIReranker = null;
|
|
144
|
+
const aiReranker = this.getAIReranker(config, contextUser);
|
|
145
|
+
try {
|
|
146
|
+
if (!aiReranker) {
|
|
147
|
+
return candidates.slice(0, topN);
|
|
148
|
+
}
|
|
149
|
+
const result = await super.ReRank(query, candidates, topN, contextUser, config);
|
|
150
|
+
if (aiReranker.LastCallSucceeded) {
|
|
151
|
+
this.reportCost(aiReranker.LastCostCents ?? this.EstimateCostCents(candidates.length));
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
this.currentAIReranker = null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
DecisionReRanker = __decorate([
|
|
161
|
+
RegisterClass(BaseReRanker, 'DecisionReRanker')
|
|
162
|
+
], DecisionReRanker);
|
|
163
|
+
export { DecisionReRanker };
|
|
164
|
+
/**
|
|
165
|
+
* Tree-shake prevention helper. Call from a consumer's `public-api.ts` (or from a generated
|
|
166
|
+
* registration manifest) to guarantee the `@RegisterClass` side-effect runs.
|
|
167
|
+
*/
|
|
168
|
+
export function LoadDecisionReRanker() {
|
|
169
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
170
|
+
const _ref = DecisionReRanker;
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=DecisionReRanker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DecisionReRanker.js","sourceRoot":"","sources":["../../src/rerankers/DecisionReRanker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;;;;AAEH,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAY,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,YAAY,IAAI,cAAc,EAA8B,MAAM,oBAAoB,CAAC;AAChG,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAGvD,wEAAwE;AACxE,MAAM,CAAC,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AAE3D;;;;GAIG;AACH,MAAM,CAAC,MAAM,6CAA6C,GAAG,MAAM,CAAC;AAEpE;;;GAGG;AACH,MAAM,uBAAwB,SAAQ,cAAc;IAIhD,YAA6B,QAAwB;QACjD,KAAK,CAAC,EAAE,EA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;YAChF,IAAI,UAAU,CAAC,iBAAiB,EAAE,CAAC;gBAC/B,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,aAAa,IAAI,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;YAC3F,CAAC;YACD,OAAO,MAAM,CAAC;QAClB,CAAC;gBAAS,CAAC;YACP,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;QAClC,CAAC;IACL,CAAC;CACJ,CAAA;AApEY,gBAAgB;IAD5B,aAAa,CAAC,YAAY,EAAE,kBAAkB,CAAC;GACnC,gBAAgB,CAoE5B;;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB;IAChC,6DAA6D;IAC7D,MAAM,IAAI,GAAG,gBAAgB,CAAC;AAClC,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Shared transformers.js runtime for `BGEReRanker` (runs inside the worker thread
|
|
3
|
+
* when available, or in-process as fallback when worker execution is disabled/unavailable).
|
|
4
|
+
*
|
|
5
|
+
* @module @memberjunction/search-engine
|
|
6
|
+
*/
|
|
7
|
+
/** Transformers.js pipeline call shape for cross-encoder text classification. */
|
|
8
|
+
export type RerankPipeline = (inputs: string | Array<string | string[]>, options?: Record<string, unknown>) => Promise<unknown>;
|
|
9
|
+
/** Default mini-batch size for ONNX cross-encoder inference to bound tensor memory and latency. */
|
|
10
|
+
export declare const DEFAULT_BGE_BATCH_SIZE = 32;
|
|
11
|
+
/**
|
|
12
|
+
* Loads (and caches) a quantized `text-classification` pipeline for `modelId`.
|
|
13
|
+
* Clears failed promises from cache so transient load errors can recover on retry.
|
|
14
|
+
*/
|
|
15
|
+
export declare function GetBGEPipeline(modelId: string, cacheDir: string | undefined): Promise<RerankPipeline>;
|
|
16
|
+
/**
|
|
17
|
+
* Normalizes transformers.js text-classification pipeline output into a flat `number[]`
|
|
18
|
+
* with one relevance score per input pair.
|
|
19
|
+
*/
|
|
20
|
+
export declare function ExtractBGEScores(raw: unknown, expectedLength: number): number[];
|
|
21
|
+
/**
|
|
22
|
+
* Scores `[query, document]` pairs in bounded mini-batches against the cached BGE ONNX pipeline.
|
|
23
|
+
*/
|
|
24
|
+
export declare function ScorePairsWithBGEModel(modelId: string, cacheDir: string | undefined, pairs: Array<[string, string]>, batchSize?: number): Promise<number[]>;
|
|
25
|
+
/** Clears cached pipelines and the memoized `@huggingface/transformers` module promise. */
|
|
26
|
+
export declare function ClearBGEPipelines(): void;
|
|
27
|
+
//# sourceMappingURL=bgeRuntime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bgeRuntime.d.ts","sourceRoot":"","sources":["../../src/rerankers/bgeRuntime.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,iFAAiF;AACjF,MAAM,MAAM,cAAc,GAAG,CACzB,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EACzC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAChC,OAAO,CAAC,OAAO,CAAC,CAAC;AAWtB,mGAAmG;AACnG,eAAO,MAAM,sBAAsB,KAAK,CAAC;AAwBzC;;;GAGG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,cAAc,CAAC,CAmB3G;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,MAAM,EAAE,CAmB/E;AAED;;GAEG;AACH,wBAAsB,sBAAsB,CACxC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,KAAK,EAAE,KAAK,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAC9B,SAAS,GAAE,MAA+B,GAC3C,OAAO,CAAC,MAAM,EAAE,CAAC,CAsBnB;AAED,2FAA2F;AAC3F,wBAAgB,iBAAiB,IAAI,IAAI,CAGxC"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Shared transformers.js runtime for `BGEReRanker` (runs inside the worker thread
|
|
3
|
+
* when available, or in-process as fallback when worker execution is disabled/unavailable).
|
|
4
|
+
*
|
|
5
|
+
* @module @memberjunction/search-engine
|
|
6
|
+
*/
|
|
7
|
+
/** Default mini-batch size for ONNX cross-encoder inference to bound tensor memory and latency. */
|
|
8
|
+
export const DEFAULT_BGE_BATCH_SIZE = 32;
|
|
9
|
+
let transformersPromise = null;
|
|
10
|
+
function loadTransformers() {
|
|
11
|
+
if (!transformersPromise) {
|
|
12
|
+
transformersPromise = (async () => {
|
|
13
|
+
try {
|
|
14
|
+
// SearchEngine is ESM ("type": "module"); dynamic import is justified here by
|
|
15
|
+
// CLAUDE.md Rule 8 #2 because '@huggingface/transformers' is an optionalDependency.
|
|
16
|
+
const mod = (await import('@huggingface/transformers'));
|
|
17
|
+
return mod;
|
|
18
|
+
}
|
|
19
|
+
catch (err) {
|
|
20
|
+
throw new Error(`BGEReRanker: could not load '@huggingface/transformers', an optional dependency of @memberjunction/search-engine. It is skipped when its install fails or optional dependencies are omitted (--no-optional, --omit=optional); reinstall with optional dependencies to use the BGE local reranker. Underlying error: ${err instanceof Error ? err.message : String(err)}`);
|
|
21
|
+
}
|
|
22
|
+
})();
|
|
23
|
+
}
|
|
24
|
+
return transformersPromise;
|
|
25
|
+
}
|
|
26
|
+
const pipelineCache = new Map();
|
|
27
|
+
/**
|
|
28
|
+
* Loads (and caches) a quantized `text-classification` pipeline for `modelId`.
|
|
29
|
+
* Clears failed promises from cache so transient load errors can recover on retry.
|
|
30
|
+
*/
|
|
31
|
+
export async function GetBGEPipeline(modelId, cacheDir) {
|
|
32
|
+
const key = `${modelId}|${cacheDir ?? ''}`;
|
|
33
|
+
let cached = pipelineCache.get(key);
|
|
34
|
+
if (!cached) {
|
|
35
|
+
cached = (async () => {
|
|
36
|
+
const transformers = await loadTransformers();
|
|
37
|
+
if (cacheDir) {
|
|
38
|
+
transformers.env.cacheDir = cacheDir;
|
|
39
|
+
}
|
|
40
|
+
return transformers.pipeline('text-classification', modelId, { dtype: 'q8' });
|
|
41
|
+
})();
|
|
42
|
+
pipelineCache.set(key, cached);
|
|
43
|
+
cached.catch(() => {
|
|
44
|
+
if (pipelineCache.get(key) === cached) {
|
|
45
|
+
pipelineCache.delete(key);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
return cached;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Normalizes transformers.js text-classification pipeline output into a flat `number[]`
|
|
53
|
+
* with one relevance score per input pair.
|
|
54
|
+
*/
|
|
55
|
+
export function ExtractBGEScores(raw, expectedLength) {
|
|
56
|
+
if (!Array.isArray(raw)) {
|
|
57
|
+
throw new Error('BGEReRanker: pipeline did not return an array');
|
|
58
|
+
}
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const entry of raw) {
|
|
61
|
+
if (entry && typeof entry === 'object' && 'score' in entry && typeof entry.score === 'number') {
|
|
62
|
+
out.push(entry.score);
|
|
63
|
+
}
|
|
64
|
+
else if (Array.isArray(entry)) {
|
|
65
|
+
const first = entry[0];
|
|
66
|
+
out.push(first && typeof first.score === 'number' ? first.score : 0);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
out.push(0);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (out.length !== expectedLength) {
|
|
73
|
+
throw new Error(`BGEReRanker: pipeline returned ${out.length} scores for ${expectedLength} inputs`);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Scores `[query, document]` pairs in bounded mini-batches against the cached BGE ONNX pipeline.
|
|
79
|
+
*/
|
|
80
|
+
export async function ScorePairsWithBGEModel(modelId, cacheDir, pairs, batchSize = DEFAULT_BGE_BATCH_SIZE) {
|
|
81
|
+
if (pairs.length === 0) {
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
const effectiveBatchSize = Math.max(1, Math.floor(batchSize));
|
|
85
|
+
const scoreFor = await GetBGEPipeline(modelId, cacheDir);
|
|
86
|
+
if (pairs.length <= effectiveBatchSize) {
|
|
87
|
+
const raw = await scoreFor(pairs);
|
|
88
|
+
return ExtractBGEScores(raw, pairs.length);
|
|
89
|
+
}
|
|
90
|
+
const scores = [];
|
|
91
|
+
for (let offset = 0; offset < pairs.length; offset += effectiveBatchSize) {
|
|
92
|
+
const batch = pairs.slice(offset, offset + effectiveBatchSize);
|
|
93
|
+
const raw = await scoreFor(batch);
|
|
94
|
+
const batchScores = ExtractBGEScores(raw, batch.length);
|
|
95
|
+
for (const score of batchScores) {
|
|
96
|
+
scores.push(score);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return scores;
|
|
100
|
+
}
|
|
101
|
+
/** Clears cached pipelines and the memoized `@huggingface/transformers` module promise. */
|
|
102
|
+
export function ClearBGEPipelines() {
|
|
103
|
+
pipelineCache.clear();
|
|
104
|
+
transformersPromise = null;
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=bgeRuntime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bgeRuntime.js","sourceRoot":"","sources":["../../src/rerankers/bgeRuntime.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAiBH,mGAAmG;AACnG,MAAM,CAAC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAEzC,IAAI,mBAAmB,GAAuC,IAAI,CAAC;AAEnE,SAAS,gBAAgB;IACrB,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACvB,mBAAmB,GAAG,CAAC,KAAK,IAAI,EAAE;YAC9B,IAAI,CAAC;gBACD,8EAA8E;gBAC9E,oFAAoF;gBACpF,MAAM,GAAG,GAAG,CAAC,MAAM,MAAM,CAAC,2BAAqC,CA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