@librechat/agents 4.0.6 → 4.1.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/dist/cjs/agents/AgentContext.cjs +6 -4
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/decisions/breaker.cjs +59 -0
- package/dist/cjs/decisions/breaker.cjs.map +1 -0
- package/dist/cjs/decisions/core.cjs +44 -0
- package/dist/cjs/decisions/dialect.cjs +65 -12
- package/dist/cjs/decisions/dialect.cjs.map +1 -1
- package/dist/cjs/decisions/hook.cjs +19 -0
- package/dist/cjs/decisions/hook.cjs.map +1 -0
- package/dist/cjs/decisions/http.cjs +2 -1
- package/dist/cjs/decisions/http.cjs.map +1 -1
- package/dist/cjs/decisions/index.cjs +6 -0
- package/dist/cjs/decisions/node.cjs +315 -0
- package/dist/cjs/decisions/node.cjs.map +1 -0
- package/dist/cjs/decisions/probe.cjs +56 -0
- package/dist/cjs/decisions/probe.cjs.map +1 -0
- package/dist/cjs/decisions/redact.cjs +109 -0
- package/dist/cjs/decisions/redact.cjs.map +1 -0
- package/dist/cjs/decisions/structuredChat.cjs +2 -3
- package/dist/cjs/decisions/structuredChat.cjs.map +1 -1
- package/dist/cjs/decisions/transport.cjs +56 -23
- package/dist/cjs/decisions/transport.cjs.map +1 -1
- package/dist/cjs/decisions/types.cjs +2 -0
- package/dist/cjs/decisions/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -0
- package/dist/cjs/llm/bedrock/cachePoints.cjs +20 -0
- package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +8 -5
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +45 -0
- package/dist/cjs/rerank/bm25.cjs +110 -0
- package/dist/cjs/rerank/bm25.cjs.map +1 -0
- package/dist/cjs/rerank/cache.cjs +50 -0
- package/dist/cjs/rerank/cache.cjs.map +1 -0
- package/dist/cjs/rerank/core.cjs +29 -0
- package/dist/cjs/rerank/crossEncoder.cjs +172 -0
- package/dist/cjs/rerank/crossEncoder.cjs.map +1 -0
- package/dist/cjs/rerank/fallback.cjs +280 -0
- package/dist/cjs/rerank/fallback.cjs.map +1 -0
- package/dist/cjs/rerank/index.cjs +8 -0
- package/dist/cjs/rerank/outcome.cjs +382 -0
- package/dist/cjs/rerank/outcome.cjs.map +1 -0
- package/dist/cjs/rerank/pin.cjs +74 -0
- package/dist/cjs/rerank/pin.cjs.map +1 -0
- package/dist/cjs/rerank/semaphore.cjs +38 -0
- package/dist/cjs/rerank/semaphore.cjs.map +1 -0
- package/dist/cjs/rerank/systemone.cjs +476 -50
- package/dist/cjs/rerank/systemone.cjs.map +1 -1
- package/dist/cjs/session/AgentSession.cjs +1 -1
- package/dist/cjs/session/AgentSession.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalCodingTools.cjs +67 -19
- package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalExecutionTools.cjs +12 -1
- package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
- package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +63 -16
- package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
- package/dist/cjs/tools/local/toolResultCaps.cjs +32 -0
- package/dist/cjs/tools/local/toolResultCaps.cjs.map +1 -0
- package/dist/cjs/utils/schema.cjs +19 -0
- package/dist/cjs/utils/schema.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +7 -5
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/decisions/breaker.mjs +56 -0
- package/dist/esm/decisions/breaker.mjs.map +1 -0
- package/dist/esm/decisions/core.mjs +11 -0
- package/dist/esm/decisions/dialect.mjs +65 -12
- package/dist/esm/decisions/dialect.mjs.map +1 -1
- package/dist/esm/decisions/hook.mjs +19 -0
- package/dist/esm/decisions/hook.mjs.map +1 -0
- package/dist/esm/decisions/http.mjs +2 -1
- package/dist/esm/decisions/http.mjs.map +1 -1
- package/dist/esm/decisions/index.mjs +6 -0
- package/dist/esm/decisions/node.mjs +313 -0
- package/dist/esm/decisions/node.mjs.map +1 -0
- package/dist/esm/decisions/probe.mjs +54 -0
- package/dist/esm/decisions/probe.mjs.map +1 -0
- package/dist/esm/decisions/redact.mjs +108 -0
- package/dist/esm/decisions/redact.mjs.map +1 -0
- package/dist/esm/decisions/structuredChat.mjs +2 -3
- package/dist/esm/decisions/structuredChat.mjs.map +1 -1
- package/dist/esm/decisions/transport.mjs +56 -23
- package/dist/esm/decisions/transport.mjs.map +1 -1
- package/dist/esm/decisions/types.mjs +2 -0
- package/dist/esm/decisions/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -1
- package/dist/esm/llm/bedrock/cachePoints.mjs +20 -1
- package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +7 -4
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/main.mjs +15 -3
- package/dist/esm/rerank/bm25.mjs +108 -0
- package/dist/esm/rerank/bm25.mjs.map +1 -0
- package/dist/esm/rerank/cache.mjs +50 -0
- package/dist/esm/rerank/cache.mjs.map +1 -0
- package/dist/esm/rerank/core.mjs +9 -0
- package/dist/esm/rerank/crossEncoder.mjs +172 -0
- package/dist/esm/rerank/crossEncoder.mjs.map +1 -0
- package/dist/esm/rerank/fallback.mjs +278 -0
- package/dist/esm/rerank/fallback.mjs.map +1 -0
- package/dist/esm/rerank/index.mjs +8 -0
- package/dist/esm/rerank/outcome.mjs +360 -0
- package/dist/esm/rerank/outcome.mjs.map +1 -0
- package/dist/esm/rerank/pin.mjs +73 -0
- package/dist/esm/rerank/pin.mjs.map +1 -0
- package/dist/esm/rerank/semaphore.mjs +38 -0
- package/dist/esm/rerank/semaphore.mjs.map +1 -0
- package/dist/esm/rerank/systemone.mjs +476 -50
- package/dist/esm/rerank/systemone.mjs.map +1 -1
- package/dist/esm/session/AgentSession.mjs +1 -1
- package/dist/esm/session/AgentSession.mjs.map +1 -1
- package/dist/esm/tools/local/LocalCodingTools.mjs +67 -19
- package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
- package/dist/esm/tools/local/LocalExecutionTools.mjs +12 -1
- package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
- package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +63 -17
- package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
- package/dist/esm/tools/local/toolResultCaps.mjs +31 -0
- package/dist/esm/tools/local/toolResultCaps.mjs.map +1 -0
- package/dist/esm/utils/schema.mjs +19 -0
- package/dist/esm/utils/schema.mjs.map +1 -1
- package/dist/types/decisions/breaker.d.ts +37 -0
- package/dist/types/decisions/core.d.ts +19 -0
- package/dist/types/decisions/hook.d.ts +9 -0
- package/dist/types/decisions/index.d.ts +3 -8
- package/dist/types/decisions/node.d.ts +90 -0
- package/dist/types/decisions/probe.d.ts +37 -0
- package/dist/types/decisions/redact.d.ts +22 -0
- package/dist/types/decisions/structuredChat.d.ts +1 -0
- package/dist/types/decisions/transport.d.ts +16 -3
- package/dist/types/decisions/types.d.ts +43 -4
- package/dist/types/llm/bedrock/cachePoints.d.ts +7 -0
- package/dist/types/llm/bedrock/index.d.ts +2 -1
- package/dist/types/rerank/bm25.d.ts +46 -0
- package/dist/types/rerank/cache.d.ts +40 -0
- package/dist/types/rerank/core.d.ts +24 -0
- package/dist/types/rerank/crossEncoder.d.ts +48 -0
- package/dist/types/rerank/fallback.d.ts +67 -0
- package/dist/types/rerank/index.d.ts +1 -3
- package/dist/types/rerank/outcome.d.ts +144 -0
- package/dist/types/rerank/pin.d.ts +48 -0
- package/dist/types/rerank/semaphore.d.ts +9 -0
- package/dist/types/rerank/systemone.d.ts +51 -5
- package/dist/types/rerank/types.d.ts +116 -1
- package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +6 -0
- package/dist/types/tools/local/toolResultCaps.d.ts +16 -0
- package/dist/types/types/tools.d.ts +16 -0
- package/package.json +30 -2
- package/src/agents/AgentContext.ts +33 -4
- package/src/decisions/breaker.ts +110 -0
- package/src/decisions/core.ts +23 -0
- package/src/decisions/dialect.ts +134 -20
- package/src/decisions/hook.ts +32 -0
- package/src/decisions/http.ts +4 -1
- package/src/decisions/index.ts +3 -12
- package/src/decisions/node.ts +671 -0
- package/src/decisions/probe.ts +114 -0
- package/src/decisions/redact.ts +222 -0
- package/src/decisions/structuredChat.ts +6 -8
- package/src/decisions/transport.ts +104 -22
- package/src/decisions/types.ts +46 -5
- package/src/llm/bedrock/cachePoints.ts +47 -0
- package/src/llm/bedrock/index.ts +35 -13
- package/src/rerank/bm25.ts +190 -0
- package/src/rerank/cache.ts +103 -0
- package/src/rerank/core.ts +47 -0
- package/src/rerank/crossEncoder.ts +289 -0
- package/src/rerank/fallback.ts +625 -0
- package/src/rerank/index.ts +1 -3
- package/src/rerank/outcome.ts +767 -0
- package/src/rerank/pin.ts +157 -0
- package/src/rerank/semaphore.ts +47 -0
- package/src/rerank/systemone.ts +914 -88
- package/src/rerank/types.ts +143 -1
- package/src/session/AgentSession.ts +3 -1
- package/src/tools/local/LocalCodingTools.ts +139 -19
- package/src/tools/local/LocalExecutionTools.ts +21 -1
- package/src/tools/local/resolveLocalExecutionTools.ts +116 -11
- package/src/tools/local/toolResultCaps.ts +60 -0
- package/src/types/tools.ts +16 -0
- package/src/utils/schema.ts +29 -1
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
ConverseCommandParams,
|
|
6
6
|
} from '@langchain/aws';
|
|
7
7
|
import type * as Bedrock from '@aws-sdk/client-bedrock-runtime';
|
|
8
|
+
import { modelDisallowsAssistantPrefill } from '@/llm/anthropic/utils/message_inputs';
|
|
8
9
|
|
|
9
10
|
function isConverseCachePoint(block: unknown): boolean {
|
|
10
11
|
return Boolean(
|
|
@@ -84,3 +85,49 @@ export function applyCachePointsToConversePayload(fields: {
|
|
|
84
85
|
tools.push(cacheBlock as unknown as Bedrock.Tool);
|
|
85
86
|
}
|
|
86
87
|
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Drop trailing assistant turns for Claude models that reject a prefill (4.6 and
|
|
91
|
+
* later), mirroring `stripUnsupportedAssistantPrefill` for the Converse payload.
|
|
92
|
+
* A cache point that rode a stripped turn is re-anchored on the new tail when no
|
|
93
|
+
* surviving message carries one, so the request keeps its message caching.
|
|
94
|
+
*/
|
|
95
|
+
export function stripUnsupportedConversePrefill(
|
|
96
|
+
messages: Bedrock.Message[],
|
|
97
|
+
model?: string
|
|
98
|
+
): Bedrock.Message[] {
|
|
99
|
+
if (
|
|
100
|
+
!modelDisallowsAssistantPrefill(model) ||
|
|
101
|
+
messages.length <= 1 ||
|
|
102
|
+
messages[messages.length - 1]?.role !== 'assistant'
|
|
103
|
+
) {
|
|
104
|
+
return messages;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const nextMessages = [...messages];
|
|
108
|
+
let strippedCachePoint: Bedrock.ContentBlock | undefined;
|
|
109
|
+
while (
|
|
110
|
+
nextMessages.length > 1 &&
|
|
111
|
+
nextMessages[nextMessages.length - 1]?.role === 'assistant'
|
|
112
|
+
) {
|
|
113
|
+
const stripped = nextMessages.pop();
|
|
114
|
+
strippedCachePoint ??= stripped?.content?.find((block) =>
|
|
115
|
+
isConverseCachePoint(block)
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const survivorsHaveCachePoint = nextMessages.some((message) =>
|
|
120
|
+
(message.content ?? []).some((block) => isConverseCachePoint(block))
|
|
121
|
+
);
|
|
122
|
+
if (strippedCachePoint == null || survivorsHaveCachePoint) {
|
|
123
|
+
return nextMessages;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const lastIndex = nextMessages.length - 1;
|
|
127
|
+
const tail = nextMessages[lastIndex];
|
|
128
|
+
nextMessages[lastIndex] = {
|
|
129
|
+
...tail,
|
|
130
|
+
content: [...(tail.content ?? []), strippedCachePoint],
|
|
131
|
+
};
|
|
132
|
+
return nextMessages;
|
|
133
|
+
}
|
package/src/llm/bedrock/index.ts
CHANGED
|
@@ -49,12 +49,20 @@ import {
|
|
|
49
49
|
supportsBedrockToolCache,
|
|
50
50
|
type PromptCacheTtl,
|
|
51
51
|
} from '@/messages/cache';
|
|
52
|
-
import {
|
|
52
|
+
import {
|
|
53
|
+
applyCachePointsToConversePayload,
|
|
54
|
+
stripUnsupportedConversePrefill,
|
|
55
|
+
} from './cachePoints';
|
|
56
|
+
import {
|
|
57
|
+
smoothStream,
|
|
58
|
+
resolveStreamDelay,
|
|
59
|
+
isSignalAborted,
|
|
60
|
+
} from '@/llm/stream/smoother';
|
|
61
|
+
import { modelDisallowsAssistantPrefill } from '@/llm/anthropic/utils/message_inputs';
|
|
53
62
|
import { linkStreamLimitCanonical } from '@/llm/streamLimits';
|
|
54
|
-
import { applyCachePointsToConversePayload } from './cachePoints';
|
|
55
|
-
import { insertBedrockToolCachePoint } from './toolCache';
|
|
56
63
|
import { isBedrockOpenAIModel } from './utils/message_inputs';
|
|
57
64
|
import { neutralizeHarmonyToolConfig } from './utils/harmony';
|
|
65
|
+
import { insertBedrockToolCachePoint } from './toolCache';
|
|
58
66
|
|
|
59
67
|
/**
|
|
60
68
|
* A `200 OK` ConverseStream whose event stream closes before a single event: no
|
|
@@ -262,7 +270,10 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
|
|
|
262
270
|
options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,
|
|
263
271
|
runManager?: CallbackManagerForLLMRun
|
|
264
272
|
): Promise<ChatResult> {
|
|
265
|
-
if (
|
|
273
|
+
if (
|
|
274
|
+
isBedrockOpenAIModel(this.model) ||
|
|
275
|
+
modelDisallowsAssistantPrefill(this.model)
|
|
276
|
+
) {
|
|
266
277
|
return this.generateWithLocalConverter(messages, options);
|
|
267
278
|
}
|
|
268
279
|
const originalModel = this.model;
|
|
@@ -283,15 +294,18 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
|
|
|
283
294
|
/**
|
|
284
295
|
* Non-streaming Converse through this package's converter, as the stream already uses.
|
|
285
296
|
* The parent's converter replays reasoning and sends harmony control tokens as written,
|
|
286
|
-
* both of which OpenAI models on Bedrock fail on
|
|
297
|
+
* both of which OpenAI models on Bedrock fail on, and it cannot strip a trailing
|
|
298
|
+
* assistant prefill that Claude 4.6 and later reject.
|
|
287
299
|
*/
|
|
288
300
|
private async generateWithLocalConverter(
|
|
289
301
|
messages: BaseMessage[],
|
|
290
302
|
options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions
|
|
291
303
|
): Promise<ChatResult> {
|
|
292
|
-
const { converseMessages, converseSystem } =
|
|
293
|
-
messages,
|
|
294
|
-
|
|
304
|
+
const { converseMessages: convertedMessages, converseSystem } =
|
|
305
|
+
convertToConverseMessages(messages, { model: this.model });
|
|
306
|
+
const converseMessages = stripUnsupportedConversePrefill(
|
|
307
|
+
convertedMessages,
|
|
308
|
+
this.model
|
|
295
309
|
);
|
|
296
310
|
const params = this.invocationParams(options);
|
|
297
311
|
const modelId = this.getModelId();
|
|
@@ -341,9 +355,11 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
|
|
|
341
355
|
options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,
|
|
342
356
|
runManager?: CallbackManagerForLLMRun
|
|
343
357
|
): AsyncGenerator<ChatGenerationChunk> {
|
|
344
|
-
const { converseMessages, converseSystem } =
|
|
345
|
-
messages,
|
|
346
|
-
|
|
358
|
+
const { converseMessages: convertedMessages, converseSystem } =
|
|
359
|
+
convertToConverseMessages(messages, { model: this.model });
|
|
360
|
+
const converseMessages = stripUnsupportedConversePrefill(
|
|
361
|
+
convertedMessages,
|
|
362
|
+
this.model
|
|
347
363
|
);
|
|
348
364
|
const params = this.invocationParams(options);
|
|
349
365
|
|
|
@@ -541,7 +557,10 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
|
|
|
541
557
|
yield {
|
|
542
558
|
text: '',
|
|
543
559
|
smooth: false,
|
|
544
|
-
emit: (): BedrockEmittedChunk => ({
|
|
560
|
+
emit: (): BedrockEmittedChunk => ({
|
|
561
|
+
chunk: metadataChunk,
|
|
562
|
+
callbackToken: '',
|
|
563
|
+
}),
|
|
545
564
|
};
|
|
546
565
|
} else if (event.contentBlockStop != null) {
|
|
547
566
|
const stopIdx = event.contentBlockStop.contentBlockIndex;
|
|
@@ -571,7 +590,10 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
|
|
|
571
590
|
yield {
|
|
572
591
|
text: '',
|
|
573
592
|
smooth: false,
|
|
574
|
-
emit: (): BedrockEmittedChunk => ({
|
|
593
|
+
emit: (): BedrockEmittedChunk => ({
|
|
594
|
+
chunk: eventChunk,
|
|
595
|
+
callbackToken: '',
|
|
596
|
+
}),
|
|
575
597
|
};
|
|
576
598
|
}
|
|
577
599
|
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import type { RankRequest, RerankOutcome, OutcomeReranker } from './types';
|
|
2
|
+
import {
|
|
3
|
+
isAborted,
|
|
4
|
+
stepOutcome,
|
|
5
|
+
documentCount,
|
|
6
|
+
emptyRerankUsage,
|
|
7
|
+
rankRequestProblem,
|
|
8
|
+
} from './outcome';
|
|
9
|
+
import { DecisionError } from '../decisions/types';
|
|
10
|
+
|
|
11
|
+
const STOP_WORDS: ReadonlySet<string> = new Set(
|
|
12
|
+
'which what where who how does that this the and for with from into over under of to in on at by an a is are be been do did as it its their they them or not no via when after before while than then also each all any some one two'.split(
|
|
13
|
+
' '
|
|
14
|
+
)
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Codegraph's measured BM25 tokenizer for code and its prose: camelCase,
|
|
19
|
+
* snake_case, kebab-case, dotted names, and paths split into words, which
|
|
20
|
+
* are lower-cased; words of two letters or fewer and English stop words are
|
|
21
|
+
* dropped. It keeps only ASCII letters and digits, so CJK text yields no
|
|
22
|
+
* words and accented words split into fragments; pass a `tokenize` of your
|
|
23
|
+
* own for other scripts.
|
|
24
|
+
*/
|
|
25
|
+
export function tokenizeCode(text: string): string[] {
|
|
26
|
+
return text
|
|
27
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
28
|
+
.replace(/[_\-./`]/g, ' ')
|
|
29
|
+
.toLowerCase()
|
|
30
|
+
.split(/[^a-z0-9]+/)
|
|
31
|
+
.filter((word) => word.length > 2 && !STOP_WORDS.has(word));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type Tokenize = (text: string) => string[];
|
|
35
|
+
|
|
36
|
+
export interface CorpusStats {
|
|
37
|
+
/** Okapi idf, +1 smoothed so it is never negative. */
|
|
38
|
+
idf: Map<string, number>;
|
|
39
|
+
/** Mean document length in tokens. */
|
|
40
|
+
avgdl: number;
|
|
41
|
+
/** Documents counted. */
|
|
42
|
+
n: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Statistics over the whole corpus a shortlist is drawn from, not over the shortlist. */
|
|
46
|
+
export function corpusStats(
|
|
47
|
+
documents: Iterable<string>,
|
|
48
|
+
options: { tokenize?: Tokenize } = {}
|
|
49
|
+
): CorpusStats {
|
|
50
|
+
const tokenize = options.tokenize ?? tokenizeCode;
|
|
51
|
+
const frequency = new Map<string, number>();
|
|
52
|
+
let total = 0;
|
|
53
|
+
let n = 0;
|
|
54
|
+
for (const document of documents) {
|
|
55
|
+
const tokens = tokenize(document);
|
|
56
|
+
total += tokens.length;
|
|
57
|
+
n += 1;
|
|
58
|
+
for (const term of new Set(tokens)) {
|
|
59
|
+
frequency.set(term, (frequency.get(term) ?? 0) + 1);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const idf = new Map<string, number>();
|
|
63
|
+
for (const [term, seen] of frequency) {
|
|
64
|
+
idf.set(term, Math.log(1 + (n - seen + 0.5) / (seen + 0.5)));
|
|
65
|
+
}
|
|
66
|
+
return { idf, avgdl: n > 0 ? total / n : 0, n };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface Bm25RerankerOptions {
|
|
70
|
+
/** Corpus idf from `corpusStats`, or a function of the term. */
|
|
71
|
+
idf: ReadonlyMap<string, number> | ((term: string) => number);
|
|
72
|
+
/** The corpus's mean document length in tokens. */
|
|
73
|
+
avgdl: number;
|
|
74
|
+
/** Defaults to 1.2. */
|
|
75
|
+
k1?: number;
|
|
76
|
+
/** Defaults to 0.75. */
|
|
77
|
+
b?: number;
|
|
78
|
+
/** Must match the tokenizer the statistics were built with. Defaults to `tokenizeCode`. */
|
|
79
|
+
tokenize?: Tokenize;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Any `ReadonlyMap`, including a wrapper or a `Map` from another realm, where `instanceof Map` is false. */
|
|
83
|
+
function isIdfMap(value: unknown): value is ReadonlyMap<string, number> {
|
|
84
|
+
return (
|
|
85
|
+
typeof value === 'object' &&
|
|
86
|
+
value !== null &&
|
|
87
|
+
'get' in value &&
|
|
88
|
+
'values' in value &&
|
|
89
|
+
typeof value.get === 'function' &&
|
|
90
|
+
typeof value.values === 'function'
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* In-process Okapi BM25. Corpus statistics are required: idf over a 50-document
|
|
96
|
+
* shortlist alone is close to degenerate. A term the corpus never saw counts
|
|
97
|
+
* as rare as its rarest term. Never throws once built, and costs nothing.
|
|
98
|
+
* Scoring is synchronous: an already-aborted `signal` is `aborted` before any
|
|
99
|
+
* work, and neither an abort nor `deadlineMs` stops a pass once it starts. A
|
|
100
|
+
* query the tokenizer leaves no terms in (only stop words, or a script it
|
|
101
|
+
* does not read) is `unsupported`, not an all-zero ranking, so a chain moves
|
|
102
|
+
* on.
|
|
103
|
+
*/
|
|
104
|
+
export function createBm25Reranker(
|
|
105
|
+
options: Bm25RerankerOptions
|
|
106
|
+
): OutcomeReranker {
|
|
107
|
+
const k1 = options.k1 ?? 1.2;
|
|
108
|
+
const b = options.b ?? 0.75;
|
|
109
|
+
const tokenize = options.tokenize ?? tokenizeCode;
|
|
110
|
+
const { idf, avgdl } = options;
|
|
111
|
+
let idfOf: ((term: string) => number) | undefined;
|
|
112
|
+
if (isIdfMap(idf)) {
|
|
113
|
+
let rarest = 0;
|
|
114
|
+
for (const value of idf.values()) {
|
|
115
|
+
rarest = Math.max(rarest, value);
|
|
116
|
+
}
|
|
117
|
+
idfOf = (term: string): number => idf.get(term) ?? rarest;
|
|
118
|
+
} else if (typeof idf === 'function') {
|
|
119
|
+
idfOf = idf;
|
|
120
|
+
}
|
|
121
|
+
if (
|
|
122
|
+
idfOf === undefined ||
|
|
123
|
+
typeof avgdl !== 'number' ||
|
|
124
|
+
!Number.isFinite(avgdl) ||
|
|
125
|
+
avgdl <= 0 ||
|
|
126
|
+
!Number.isFinite(k1) ||
|
|
127
|
+
k1 < 0 ||
|
|
128
|
+
!Number.isFinite(b) ||
|
|
129
|
+
b < 0 ||
|
|
130
|
+
b > 1 ||
|
|
131
|
+
typeof tokenize !== 'function'
|
|
132
|
+
) {
|
|
133
|
+
throw new DecisionError(
|
|
134
|
+
'bad_request',
|
|
135
|
+
'bm25 reranker requires corpus statistics (corpusStats)',
|
|
136
|
+
{ provider: 'bm25' }
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const termIdf = idfOf;
|
|
140
|
+
const kind = 'bm25' as const;
|
|
141
|
+
const model = 'okapi';
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
id: 'bm25:okapi',
|
|
145
|
+
kind,
|
|
146
|
+
model,
|
|
147
|
+
async rank(request: RankRequest): Promise<RerankOutcome> {
|
|
148
|
+
const startedAt = performance.now();
|
|
149
|
+
const documents = documentCount(request);
|
|
150
|
+
const base = { kind, documents, startedAt, model };
|
|
151
|
+
const problem = rankRequestProblem(request);
|
|
152
|
+
if (problem !== undefined) {
|
|
153
|
+
return stepOutcome({ ...base, reason: problem, called: false });
|
|
154
|
+
}
|
|
155
|
+
// Scoring runs to the end once started, so a cancelled caller is honored only before it.
|
|
156
|
+
if (isAborted(request.signal)) {
|
|
157
|
+
return stepOutcome({ ...base, reason: 'aborted', called: false });
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
const terms = tokenize(request.query);
|
|
161
|
+
if (terms.length === 0) {
|
|
162
|
+
// Every score would be zero: identity order dressed as a ranking.
|
|
163
|
+
return stepOutcome({ ...base, reason: 'unsupported', called: false });
|
|
164
|
+
}
|
|
165
|
+
const scores = request.documents.map((document) => {
|
|
166
|
+
const tokens = tokenize(document);
|
|
167
|
+
const frequency = new Map<string, number>();
|
|
168
|
+
for (const token of tokens) {
|
|
169
|
+
frequency.set(token, (frequency.get(token) ?? 0) + 1);
|
|
170
|
+
}
|
|
171
|
+
const norm = k1 * (1 - b + (b * tokens.length) / avgdl);
|
|
172
|
+
let score = 0;
|
|
173
|
+
for (const term of terms) {
|
|
174
|
+
const seen = frequency.get(term);
|
|
175
|
+
if (seen !== undefined) {
|
|
176
|
+
score += (termIdf(term) * (seen * (k1 + 1))) / (seen + norm);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return Number.isFinite(score) ? score : null;
|
|
180
|
+
});
|
|
181
|
+
if (scores.includes(null)) {
|
|
182
|
+
return stepOutcome({ ...base, reason: 'error' });
|
|
183
|
+
}
|
|
184
|
+
return stepOutcome({ ...base, scores, usage: emptyRerankUsage() });
|
|
185
|
+
} catch {
|
|
186
|
+
return stepOutcome({ ...base, reason: 'error' });
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { DecisionError } from '../decisions/types';
|
|
2
|
+
|
|
3
|
+
/** What a cached score is keyed on: the document text, not an identity that survives edits. */
|
|
4
|
+
export interface RerankCacheKey {
|
|
5
|
+
query: string;
|
|
6
|
+
document: string;
|
|
7
|
+
/** The model that produced the score; only an echo of the configured model is cached. */
|
|
8
|
+
model: string;
|
|
9
|
+
/** Identifies the rubric and instructions the score answers. */
|
|
10
|
+
rubric: string;
|
|
11
|
+
/**
|
|
12
|
+
* The serialized decision state the score was measured in when a custom
|
|
13
|
+
* `state` built it; empty for the default `{ query, document }`.
|
|
14
|
+
*/
|
|
15
|
+
state: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Per-document scores; a host can supply its own (for example, hashed keys or
|
|
20
|
+
* a shared store). Both are synchronous: a throw from either is a miss, `set`
|
|
21
|
+
* is not awaited, and a promise either returns is ignored (its rejection
|
|
22
|
+
* included), so an asynchronous store must be fronted by a synchronous one.
|
|
23
|
+
*/
|
|
24
|
+
export interface RerankScoreCache {
|
|
25
|
+
get(key: RerankCacheKey): number | undefined;
|
|
26
|
+
set(key: RerankCacheKey, score: number): void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface MemoryScoreCache extends RerankScoreCache {
|
|
30
|
+
readonly size: number;
|
|
31
|
+
clear(): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ScoreCacheOptions {
|
|
35
|
+
/** Entries kept, a positive integer, least recently used evicted first. Defaults to 20,000. */
|
|
36
|
+
max?: number;
|
|
37
|
+
/** A positive finite lifetime. Defaults to one day. */
|
|
38
|
+
ttlMs?: number;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A bounded in-memory LRU whose entries expire after `ttlMs`; keys hold the
|
|
44
|
+
* full document text. Throws on a `max` or `ttlMs` that would unbound it.
|
|
45
|
+
*/
|
|
46
|
+
export function createScoreCache(
|
|
47
|
+
options: ScoreCacheOptions = {}
|
|
48
|
+
): MemoryScoreCache {
|
|
49
|
+
const max = options.max ?? 20_000;
|
|
50
|
+
const ttlMs = options.ttlMs ?? 86_400_000;
|
|
51
|
+
if (
|
|
52
|
+
!Number.isSafeInteger(max) ||
|
|
53
|
+
max < 1 ||
|
|
54
|
+
typeof ttlMs !== 'number' ||
|
|
55
|
+
!Number.isFinite(ttlMs) ||
|
|
56
|
+
ttlMs <= 0
|
|
57
|
+
) {
|
|
58
|
+
throw new DecisionError(
|
|
59
|
+
'bad_request',
|
|
60
|
+
'invalid score cache configuration',
|
|
61
|
+
{
|
|
62
|
+
provider: 'score-cache',
|
|
63
|
+
}
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
const now = options.now ?? Date.now;
|
|
67
|
+
const entries = new Map<string, { score: number; at: number }>();
|
|
68
|
+
const keyOf = (key: RerankCacheKey): string =>
|
|
69
|
+
JSON.stringify([key.query, key.document, key.model, key.rubric, key.state]);
|
|
70
|
+
return {
|
|
71
|
+
get(key: RerankCacheKey): number | undefined {
|
|
72
|
+
const id = keyOf(key);
|
|
73
|
+
const entry = entries.get(id);
|
|
74
|
+
if (!entry) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
entries.delete(id);
|
|
78
|
+
if (now() - entry.at > ttlMs) {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
entries.set(id, entry);
|
|
82
|
+
return entry.score;
|
|
83
|
+
},
|
|
84
|
+
set(key: RerankCacheKey, score: number): void {
|
|
85
|
+
const id = keyOf(key);
|
|
86
|
+
entries.delete(id);
|
|
87
|
+
entries.set(id, { score, at: now() });
|
|
88
|
+
while (entries.size > max) {
|
|
89
|
+
const oldest = entries.keys().next();
|
|
90
|
+
if (oldest.done === true) {
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
entries.delete(oldest.value);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
get size(): number {
|
|
97
|
+
return entries.size;
|
|
98
|
+
},
|
|
99
|
+
clear(): void {
|
|
100
|
+
entries.clear();
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Light `@librechat/agents/rerank` entry: the index-based reranking contract,
|
|
3
|
+
* the never-throwing outcome layer, and the System One, cross-encoder, BM25,
|
|
4
|
+
* and fallback rerankers, with no LangChain or other third-party runtime
|
|
5
|
+
* import. The web-search adapter stays on the root entry because it extends
|
|
6
|
+
* the search tool's reranker.
|
|
7
|
+
*/
|
|
8
|
+
export type * from './types';
|
|
9
|
+
export { createSystemOneReranker } from './systemone';
|
|
10
|
+
export type {
|
|
11
|
+
SystemOnePin,
|
|
12
|
+
SystemOneMode,
|
|
13
|
+
SystemOneReranker,
|
|
14
|
+
SystemOneRerankerOptions,
|
|
15
|
+
} from './systemone';
|
|
16
|
+
export { createCrossEncoderReranker } from './crossEncoder';
|
|
17
|
+
export type { CrossEncoderRerankerOptions } from './crossEncoder';
|
|
18
|
+
export { createBm25Reranker, corpusStats, tokenizeCode } from './bm25';
|
|
19
|
+
export type { Bm25RerankerOptions, CorpusStats, Tokenize } from './bm25';
|
|
20
|
+
export { noneReranker, withFallback, STEP_GRACE_MS } from './fallback';
|
|
21
|
+
export type {
|
|
22
|
+
FallbackStep,
|
|
23
|
+
FallbackOptions,
|
|
24
|
+
FallbackReranker,
|
|
25
|
+
} from './fallback';
|
|
26
|
+
export { probePin, PIN_SENTINEL_MODEL } from './pin';
|
|
27
|
+
export type { PinProbe, PinProbeOptions } from './pin';
|
|
28
|
+
export { createSemaphore } from './semaphore';
|
|
29
|
+
export type { RerankSemaphore } from './semaphore';
|
|
30
|
+
export { createScoreCache } from './cache';
|
|
31
|
+
export type {
|
|
32
|
+
RerankCacheKey,
|
|
33
|
+
RerankScoreCache,
|
|
34
|
+
MemoryScoreCache,
|
|
35
|
+
ScoreCacheOptions,
|
|
36
|
+
} from './cache';
|
|
37
|
+
export {
|
|
38
|
+
rerankCost,
|
|
39
|
+
rankedEntries,
|
|
40
|
+
estimatedUsage,
|
|
41
|
+
identityOutcome,
|
|
42
|
+
emptyRerankUsage,
|
|
43
|
+
toOutcomeReranker,
|
|
44
|
+
isRerankPermutation,
|
|
45
|
+
ESTIMATED_TOKENS_PER_DOCUMENT,
|
|
46
|
+
} from './outcome';
|
|
47
|
+
export type { RerankCost, RerankPrice, RerankPrices } from './outcome';
|