@botpress/cognitive 0.1.36 → 0.1.38
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 +7 -7
- package/dist/index.cjs +212 -7
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +145 -10
- package/dist/index.mjs +211 -7
- package/dist/index.mjs.map +4 -4
- package/package.json +1 -1
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
|
|
2
|
-
> @botpress/cognitive@0.1.
|
|
2
|
+
> @botpress/cognitive@0.1.38 build /home/runner/work/botpress/botpress/packages/cognitive
|
|
3
3
|
> pnpm build:type && pnpm build:neutral && size-limit
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
> @botpress/cognitive@0.1.
|
|
6
|
+
> @botpress/cognitive@0.1.38 build:type /home/runner/work/botpress/botpress/packages/cognitive
|
|
7
7
|
> tsup --tsconfig tsconfig.build.json ./src/index.ts --dts-resolve --dts-only --clean
|
|
8
8
|
|
|
9
9
|
CLI Building entry: ./src/index.ts
|
|
10
10
|
CLI Using tsconfig: tsconfig.build.json
|
|
11
11
|
CLI tsup v8.0.2
|
|
12
12
|
DTS Build start
|
|
13
|
-
DTS ⚡️ Build success in
|
|
14
|
-
DTS dist/index.d.ts
|
|
13
|
+
DTS ⚡️ Build success in 18531ms
|
|
14
|
+
DTS dist/index.d.ts 623.39 KB
|
|
15
15
|
|
|
16
|
-
> @botpress/cognitive@0.1.
|
|
16
|
+
> @botpress/cognitive@0.1.38 build:neutral /home/runner/work/botpress/botpress/packages/cognitive
|
|
17
17
|
> ts-node -T ./build.ts --neutral
|
|
18
18
|
|
|
19
19
|
Done
|
|
20
20
|
|
|
21
21
|
[1mdist/index.cjs[22m
|
|
22
22
|
Size limit: [32m[1m50 kB[22m[39m
|
|
23
|
-
Size: [32m[
|
|
23
|
+
Size: [32m[1m8.44 kB[22m[39m [90mbrotlied[39m
|
|
24
24
|
|
|
25
25
|
[1mdist/index.mjs[22m
|
|
26
26
|
Size limit: [32m[1m50 kB[22m[39m
|
|
27
|
-
Size: [32m[
|
|
27
|
+
Size: [32m[1m8.31 kB[22m[39m [90mbrotlied[39m
|
|
28
28
|
|
package/dist/index.cjs
CHANGED
|
@@ -502,25 +502,25 @@ var require_backoff = __commonJS({
|
|
|
502
502
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
503
503
|
var options_1 = require_options();
|
|
504
504
|
var delay_factory_1 = require_delay_factory();
|
|
505
|
-
function
|
|
505
|
+
function backOff3(request, options) {
|
|
506
506
|
if (options === void 0) {
|
|
507
507
|
options = {};
|
|
508
508
|
}
|
|
509
509
|
return __awaiter(this, void 0, void 0, function() {
|
|
510
|
-
var sanitizedOptions,
|
|
510
|
+
var sanitizedOptions, backOff4;
|
|
511
511
|
return __generator(this, function(_a) {
|
|
512
512
|
switch (_a.label) {
|
|
513
513
|
case 0:
|
|
514
514
|
sanitizedOptions = options_1.getSanitizedOptions(options);
|
|
515
|
-
|
|
516
|
-
return [4,
|
|
515
|
+
backOff4 = new BackOff(request, sanitizedOptions);
|
|
516
|
+
return [4, backOff4.execute()];
|
|
517
517
|
case 1:
|
|
518
518
|
return [2, _a.sent()];
|
|
519
519
|
}
|
|
520
520
|
});
|
|
521
521
|
});
|
|
522
522
|
}
|
|
523
|
-
exports.backOff =
|
|
523
|
+
exports.backOff = backOff3;
|
|
524
524
|
var BackOff = (
|
|
525
525
|
/** @class */
|
|
526
526
|
function() {
|
|
@@ -599,13 +599,14 @@ var require_backoff = __commonJS({
|
|
|
599
599
|
var src_exports = {};
|
|
600
600
|
__export(src_exports, {
|
|
601
601
|
Cognitive: () => Cognitive,
|
|
602
|
+
CognitiveBeta: () => CognitiveBeta,
|
|
602
603
|
ModelProvider: () => ModelProvider,
|
|
603
604
|
RemoteModelProvider: () => RemoteModelProvider
|
|
604
605
|
});
|
|
605
606
|
module.exports = __toCommonJS(src_exports);
|
|
606
607
|
|
|
607
608
|
// src/client.ts
|
|
608
|
-
var
|
|
609
|
+
var import_exponential_backoff2 = __toESM(require_backoff());
|
|
609
610
|
|
|
610
611
|
// ../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
611
612
|
var createNanoEvents = () => ({
|
|
@@ -664,6 +665,159 @@ var getExtendedClient = (_client) => {
|
|
|
664
665
|
};
|
|
665
666
|
};
|
|
666
667
|
|
|
668
|
+
// src/cognitive_beta/index.ts
|
|
669
|
+
var import_axios = __toESM(require("axios"));
|
|
670
|
+
var import_exponential_backoff = __toESM(require_backoff());
|
|
671
|
+
var isBrowser = () => typeof window !== "undefined" && typeof window.fetch === "function";
|
|
672
|
+
var CognitiveBeta = class {
|
|
673
|
+
_axiosClient;
|
|
674
|
+
_config;
|
|
675
|
+
constructor(props) {
|
|
676
|
+
this._config = {
|
|
677
|
+
baseUrl: props.baseUrl || "https://cognitive.botpress.cloud",
|
|
678
|
+
timeout: props.timeout || 60001,
|
|
679
|
+
token: props.token || "",
|
|
680
|
+
botId: props.botId || "",
|
|
681
|
+
headers: props.headers || {}
|
|
682
|
+
};
|
|
683
|
+
this._axiosClient = import_axios.default.create({
|
|
684
|
+
headers: {
|
|
685
|
+
Authorization: `Bearer ${this._config.token}`,
|
|
686
|
+
"X-Bot-Id": this._config.botId,
|
|
687
|
+
...this._config.headers
|
|
688
|
+
},
|
|
689
|
+
baseURL: this._config.baseUrl
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
async generateText(input, options = {}) {
|
|
693
|
+
const signal = options.signal ?? AbortSignal.timeout(this._config.timeout);
|
|
694
|
+
const { data } = await this._withServerRetry(
|
|
695
|
+
() => this._axiosClient.post("/v1/generate-text", input, {
|
|
696
|
+
signal,
|
|
697
|
+
timeout: options.timeout ?? this._config.timeout
|
|
698
|
+
})
|
|
699
|
+
);
|
|
700
|
+
return data;
|
|
701
|
+
}
|
|
702
|
+
async listModels(input, options = {}) {
|
|
703
|
+
const signal = options.signal ?? AbortSignal.timeout(this._config.timeout);
|
|
704
|
+
const { data } = await this._withServerRetry(
|
|
705
|
+
() => this._axiosClient.post("/v1/models", input, {
|
|
706
|
+
signal,
|
|
707
|
+
timeout: options.timeout ?? this._config.timeout
|
|
708
|
+
})
|
|
709
|
+
);
|
|
710
|
+
return data;
|
|
711
|
+
}
|
|
712
|
+
async *generateTextStream(request, options = {}) {
|
|
713
|
+
const signal = options.signal ?? AbortSignal.timeout(this._config.timeout);
|
|
714
|
+
if (isBrowser()) {
|
|
715
|
+
const res2 = await fetch(`${this._config.baseUrl}/v1/generate-text-stream`, {
|
|
716
|
+
method: "POST",
|
|
717
|
+
headers: {
|
|
718
|
+
Authorization: `Bearer ${this._config.token}`,
|
|
719
|
+
"X-Bot-Id": this._config.botId,
|
|
720
|
+
"Content-Type": "application/json"
|
|
721
|
+
},
|
|
722
|
+
body: JSON.stringify({ ...request, stream: true }),
|
|
723
|
+
signal
|
|
724
|
+
});
|
|
725
|
+
if (!res2.ok) {
|
|
726
|
+
const text = await res2.text().catch(() => "");
|
|
727
|
+
const err = new Error(`HTTP ${res2.status}: ${text || res2.statusText}`);
|
|
728
|
+
err.response = { status: res2.status, data: text };
|
|
729
|
+
throw err;
|
|
730
|
+
}
|
|
731
|
+
const body = res2.body;
|
|
732
|
+
if (!body) {
|
|
733
|
+
throw new Error("No response body received for streaming request");
|
|
734
|
+
}
|
|
735
|
+
const reader = body.getReader();
|
|
736
|
+
const iterable = async function* () {
|
|
737
|
+
for (; ; ) {
|
|
738
|
+
const { value, done } = await reader.read();
|
|
739
|
+
if (done) {
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
if (value) {
|
|
743
|
+
yield value;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
}();
|
|
747
|
+
for await (const obj of this._ndjson(iterable)) {
|
|
748
|
+
yield obj;
|
|
749
|
+
}
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
const res = await this._withServerRetry(
|
|
753
|
+
() => this._axiosClient.post(
|
|
754
|
+
"/v1/generate-text-stream",
|
|
755
|
+
{ ...request, stream: true },
|
|
756
|
+
{
|
|
757
|
+
responseType: "stream",
|
|
758
|
+
signal,
|
|
759
|
+
timeout: options.timeout ?? this._config.timeout
|
|
760
|
+
}
|
|
761
|
+
)
|
|
762
|
+
);
|
|
763
|
+
const nodeStream = res.data;
|
|
764
|
+
if (!nodeStream) {
|
|
765
|
+
throw new Error("No response body received for streaming request");
|
|
766
|
+
}
|
|
767
|
+
for await (const obj of this._ndjson(nodeStream)) {
|
|
768
|
+
yield obj;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
async *_ndjson(stream) {
|
|
772
|
+
const decoder = new TextDecoder("utf-8");
|
|
773
|
+
let buffer = "";
|
|
774
|
+
for await (const chunk of stream) {
|
|
775
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
776
|
+
for (; ; ) {
|
|
777
|
+
const i = buffer.indexOf("\n");
|
|
778
|
+
if (i < 0) {
|
|
779
|
+
break;
|
|
780
|
+
}
|
|
781
|
+
const line = buffer.slice(0, i).replace(/\r$/, "");
|
|
782
|
+
buffer = buffer.slice(i + 1);
|
|
783
|
+
if (!line) {
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
yield JSON.parse(line);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
buffer += decoder.decode();
|
|
790
|
+
const tail = buffer.trim();
|
|
791
|
+
if (tail) {
|
|
792
|
+
yield JSON.parse(tail);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
_isRetryableServerError(error) {
|
|
796
|
+
if (import_axios.default.isAxiosError(error)) {
|
|
797
|
+
if (!error.response) {
|
|
798
|
+
return true;
|
|
799
|
+
}
|
|
800
|
+
const status = error.response?.status;
|
|
801
|
+
if (status && [502, 503, 504].includes(status)) {
|
|
802
|
+
return true;
|
|
803
|
+
}
|
|
804
|
+
if (error.code && ["ECONNABORTED", "ECONNRESET", "ETIMEDOUT", "EAI_AGAIN", "ENOTFOUND", "EPIPE"].includes(error.code)) {
|
|
805
|
+
return true;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return false;
|
|
809
|
+
}
|
|
810
|
+
async _withServerRetry(fn) {
|
|
811
|
+
return (0, import_exponential_backoff.backOff)(fn, {
|
|
812
|
+
numOfAttempts: 3,
|
|
813
|
+
startingDelay: 300,
|
|
814
|
+
timeMultiple: 2,
|
|
815
|
+
jitter: "full",
|
|
816
|
+
retry: (e) => this._isRetryableServerError(e)
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
|
|
667
821
|
// src/errors.ts
|
|
668
822
|
var getActionFromError = (error) => {
|
|
669
823
|
if (!isBotpressError(error)) {
|
|
@@ -916,12 +1070,14 @@ var Cognitive = class {
|
|
|
916
1070
|
_preferences = null;
|
|
917
1071
|
_provider;
|
|
918
1072
|
_downtimes = [];
|
|
1073
|
+
_useBeta = false;
|
|
919
1074
|
_events = createNanoEvents();
|
|
920
1075
|
constructor(props) {
|
|
921
1076
|
this._client = getExtendedClient(props.client);
|
|
922
1077
|
this._provider = props.provider ?? new RemoteModelProvider(props.client);
|
|
923
1078
|
this._timeoutMs = props.timeout ?? this._timeoutMs;
|
|
924
1079
|
this._maxRetries = props.maxRetries ?? this._maxRetries;
|
|
1080
|
+
this._useBeta = props.__experimental_beta ?? false;
|
|
925
1081
|
}
|
|
926
1082
|
get client() {
|
|
927
1083
|
return this._client;
|
|
@@ -1008,6 +1164,54 @@ var Cognitive = class {
|
|
|
1008
1164
|
return def;
|
|
1009
1165
|
}
|
|
1010
1166
|
async generateContent(input) {
|
|
1167
|
+
if (!this._useBeta) {
|
|
1168
|
+
return this._generateContent(input);
|
|
1169
|
+
}
|
|
1170
|
+
const betaClient = new CognitiveBeta({
|
|
1171
|
+
headers: this._client.config.headers,
|
|
1172
|
+
baseUrl: this._client.config.apiUrl.includes(".cloud") ? "https://cognitive.botpress.cloud" : "https://cognitive.botpress.dev"
|
|
1173
|
+
});
|
|
1174
|
+
const response = await betaClient.generateText(input);
|
|
1175
|
+
return {
|
|
1176
|
+
output: {
|
|
1177
|
+
id: "beta-output",
|
|
1178
|
+
provider: response.metadata.provider,
|
|
1179
|
+
model: response.metadata.model,
|
|
1180
|
+
choices: [
|
|
1181
|
+
{
|
|
1182
|
+
type: "text",
|
|
1183
|
+
content: response.output,
|
|
1184
|
+
role: "assistant",
|
|
1185
|
+
index: 0,
|
|
1186
|
+
stopReason: response.metadata.stopReason
|
|
1187
|
+
}
|
|
1188
|
+
],
|
|
1189
|
+
usage: {
|
|
1190
|
+
inputTokens: response.metadata.usage.inputTokens,
|
|
1191
|
+
inputCost: 0,
|
|
1192
|
+
outputTokens: response.metadata.usage.outputTokens,
|
|
1193
|
+
outputCost: response.metadata.cost ?? 0
|
|
1194
|
+
},
|
|
1195
|
+
botpress: {
|
|
1196
|
+
cost: response.metadata.cost ?? 0
|
|
1197
|
+
}
|
|
1198
|
+
},
|
|
1199
|
+
meta: {
|
|
1200
|
+
cached: response.metadata.cached,
|
|
1201
|
+
model: { integration: response.metadata.provider, model: response.metadata.model },
|
|
1202
|
+
latency: response.metadata.latency,
|
|
1203
|
+
cost: {
|
|
1204
|
+
input: 0,
|
|
1205
|
+
output: response.metadata.cost || 0
|
|
1206
|
+
},
|
|
1207
|
+
tokens: {
|
|
1208
|
+
input: response.metadata.usage.inputTokens,
|
|
1209
|
+
output: response.metadata.usage.outputTokens
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
async _generateContent(input) {
|
|
1011
1215
|
const start = Date.now();
|
|
1012
1216
|
const signal = input.signal ?? AbortSignal.timeout(this._timeoutMs);
|
|
1013
1217
|
const client = this._client.abortable(signal);
|
|
@@ -1015,7 +1219,7 @@ var Cognitive = class {
|
|
|
1015
1219
|
let integration;
|
|
1016
1220
|
let model;
|
|
1017
1221
|
this._events.emit("request", props);
|
|
1018
|
-
const { output, meta } = await (0,
|
|
1222
|
+
const { output, meta } = await (0, import_exponential_backoff2.backOff)(
|
|
1019
1223
|
async () => {
|
|
1020
1224
|
const selection = await this._selectModel(input.model ?? "best");
|
|
1021
1225
|
integration = selection.integration;
|
|
@@ -1081,6 +1285,7 @@ var Cognitive = class {
|
|
|
1081
1285
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1082
1286
|
0 && (module.exports = {
|
|
1083
1287
|
Cognitive,
|
|
1288
|
+
CognitiveBeta,
|
|
1084
1289
|
ModelProvider,
|
|
1085
1290
|
RemoteModelProvider
|
|
1086
1291
|
});
|
package/dist/index.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/options.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/full/full.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/no/no.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/jitter.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.base.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/skip-first/skip-first.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/always/always.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/backoff.ts", "../src/index.ts", "../src/client.ts", "../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js", "../src/bp-client.ts", "../src/errors.ts", "../src/interceptors.ts", "../src/models.ts"],
|
|
4
|
-
"sourcesContent": [null, null, null, null, null, null, null, null, null, "export { Events, BotpressClientLike } from './types'\nexport * from './client'\nexport { ModelPreferences, ModelProvider, RemoteModelProvider, Model } from './models'\nexport { type GenerateContentInput, type GenerateContentOutput } from './schemas.gen'\n", "import { backOff } from 'exponential-backoff'\nimport { createNanoEvents, Unsubscribe } from 'nanoevents'\n\nimport { ExtendedClient, getExtendedClient } from './bp-client'\nimport { getActionFromError } from './errors'\nimport { InterceptorManager } from './interceptors'\nimport {\n DOWNTIME_THRESHOLD_MINUTES,\n getBestModels,\n getFastModels,\n Model,\n ModelPreferences,\n ModelProvider,\n ModelRef,\n pickModel,\n RemoteModelProvider,\n} from './models'\nimport { GenerateContentOutput } from './schemas.gen'\nimport { CognitiveProps, Events, InputProps, Request, Response } from './types'\n\nexport class Cognitive {\n public ['$$IS_COGNITIVE'] = true\n\n public static isCognitiveClient(obj: any): obj is Cognitive {\n return obj?.$$IS_COGNITIVE === true\n }\n\n public interceptors = {\n request: new InterceptorManager<Request>(),\n response: new InterceptorManager<Response>(),\n }\n\n protected _models: Model[] = []\n protected _timeoutMs: number = 5 * 60 * 1000 // Default timeout of 5 minutes\n protected _maxRetries: number = 5 // Default max retries\n protected _client: ExtendedClient\n protected _preferences: ModelPreferences | null = null\n protected _provider: ModelProvider\n protected _downtimes: ModelPreferences['downtimes'] = []\n\n private _events = createNanoEvents<Events>()\n\n public constructor(props: CognitiveProps) {\n this._client = getExtendedClient(props.client)\n this._provider = props.provider ?? new RemoteModelProvider(props.client)\n this._timeoutMs = props.timeout ?? this._timeoutMs\n this._maxRetries = props.maxRetries ?? this._maxRetries\n }\n\n public get client(): ExtendedClient {\n return this._client\n }\n\n public clone(): Cognitive {\n const copy = new Cognitive({\n client: this._client.clone(),\n provider: this._provider,\n timeout: this._timeoutMs,\n maxRetries: this._maxRetries,\n })\n\n copy._models = [...this._models]\n copy._preferences = this._preferences ? { ...this._preferences } : null\n copy._downtimes = [...this._downtimes]\n copy.interceptors.request = this.interceptors.request\n copy.interceptors.response = this.interceptors.response\n\n return copy\n }\n\n public on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe {\n return this._events.on(event, cb)\n }\n\n public async fetchInstalledModels(): Promise<Model[]> {\n if (!this._models.length) {\n this._models = await this._provider.fetchInstalledModels()\n }\n\n return this._models\n }\n\n public async fetchPreferences(): Promise<ModelPreferences> {\n if (this._preferences) {\n return this._preferences\n }\n\n this._preferences = await this._provider.fetchModelPreferences()\n\n if (this._preferences) {\n return this._preferences\n }\n\n const models = await this.fetchInstalledModels()\n\n this._preferences = {\n best: getBestModels(models).map((m) => m.ref),\n fast: getFastModels(models).map((m) => m.ref),\n downtimes: [],\n }\n\n await this._provider.saveModelPreferences(this._preferences)\n\n return this._preferences\n }\n\n public async setPreferences(preferences: ModelPreferences, save: boolean = false): Promise<void> {\n this._preferences = preferences\n\n if (save) {\n await this._provider.saveModelPreferences(preferences)\n }\n }\n\n private _cleanupOldDowntimes(): void {\n const now = Date.now()\n const thresholdMs = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n this._preferences!.downtimes = this._preferences!.downtimes.filter((downtime) => {\n const downtimeStart = new Date(downtime.startedAt).getTime()\n return now - downtimeStart <= thresholdMs\n })\n }\n\n private async _selectModel(ref: string): Promise<{ integration: string; model: string }> {\n const parseRef = (ref: string) => {\n const parts = ref.split(':')\n return { integration: parts[0]!, model: parts.slice(1).join(':') }\n }\n\n const preferences = await this.fetchPreferences()\n\n preferences.best ??= []\n preferences.fast ??= []\n preferences.downtimes ??= []\n\n const downtimes = [...preferences.downtimes, ...(this._downtimes ?? [])]\n\n if (ref === 'best') {\n return parseRef(pickModel(preferences.best, downtimes))\n }\n\n if (ref === 'fast') {\n return parseRef(pickModel(preferences.fast, downtimes))\n }\n\n return parseRef(pickModel([ref as ModelRef, ...preferences.best, ...preferences.fast], downtimes))\n }\n\n public async getModelDetails(model: string) {\n await this.fetchInstalledModels()\n const { integration, model: modelName } = await this._selectModel(model)\n const def = this._models.find((m) => m.integration === integration && (m.name === modelName || m.id === modelName))\n if (!def) {\n throw new Error(`Model ${modelName} not found`)\n }\n\n return def\n }\n\n public async generateContent(input: InputProps): Promise<Response> {\n const start = Date.now()\n\n const signal = input.signal ?? AbortSignal.timeout(this._timeoutMs)\n\n const client = this._client.abortable(signal)\n\n let props: Request = { input }\n let integration: string\n let model: string\n\n this._events.emit('request', props)\n\n const { output, meta } = await backOff<{\n output: GenerateContentOutput\n meta: any\n }>(\n async () => {\n const selection = await this._selectModel(input.model ?? 'best')\n\n integration = selection.integration\n model = selection.model\n\n props = await this.interceptors.request.run({ input }, signal)\n\n return client.callAction({\n type: `${integration}:generateContent`,\n input: {\n ...props.input,\n model: { id: model },\n },\n }) as Promise<{ output: GenerateContentOutput; meta: any }>\n },\n {\n retry: async (err, _attempt) => {\n if (signal?.aborted) {\n // We don't want to retry if the request was aborted\n this._events.emit('aborted', props, err)\n signal.throwIfAborted()\n return false\n }\n\n if (_attempt > this._maxRetries) {\n this._events.emit('error', props, err)\n return false\n }\n\n const action = getActionFromError(err)\n\n if (action === 'abort') {\n this._events.emit('error', props, err)\n return false\n }\n\n if (action === 'fallback') {\n // We don't want to retry if the request was already retried with a fallback model\n this._downtimes.push({\n ref: `${integration!}:${model!}`,\n startedAt: new Date().toISOString(),\n reason: 'Model is down',\n })\n\n this._cleanupOldDowntimes()\n\n await this._provider.saveModelPreferences({\n ...(this._preferences ?? { best: [], downtimes: [], fast: [] }),\n downtimes: [...(this._preferences!.downtimes ?? []), ...(this._downtimes ?? [])],\n })\n\n this._events.emit('fallback', props, err)\n return true\n }\n\n this._events.emit('retry', props, err)\n return true\n },\n }\n )\n\n const response = {\n output,\n meta: {\n cached: meta.cached ?? false,\n model: { integration: integration!, model: model! },\n latency: Date.now() - start,\n cost: { input: output.usage.inputCost, output: output.usage.outputCost },\n tokens: { input: output.usage.inputTokens, output: output.usage.outputTokens },\n },\n } satisfies Response\n\n this._events.emit('response', props, response)\n\n return this.interceptors.response.run(response, signal)\n }\n}\n", "export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n", "import { type Client } from '@botpress/client'\nimport { type AxiosInstance } from 'axios'\nimport { BotpressClientLike } from './types'\n\n/** @internal */\nexport type ExtendedClient = Client & {\n botId: string\n axios: AxiosInstance\n clone: () => ExtendedClient\n abortable: (signal: AbortSignal) => ExtendedClient\n}\n\ntype InternalClientType = BotpressClientLike & {\n _client?: InternalClientType\n config: {\n headers: Record<string, string>\n }\n}\n\nexport const getExtendedClient = (_client: unknown): ExtendedClient => {\n const client = _client as InternalClientType\n\n if (!client || client === null || typeof client !== 'object') {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n if (typeof client._client === 'object' && !!client._client) {\n try {\n return getExtendedClient(client._client)\n } catch {}\n }\n\n if (\n typeof client.constructor !== 'function' ||\n typeof client.callAction !== 'function' ||\n !client.config ||\n typeof client.config !== 'object' ||\n !client.config.headers\n ) {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n const botId = client.config.headers['x-bot-id'] as string\n\n if (!botId?.length) {\n throw new Error('Client must be instanciated with Bot ID')\n }\n\n const clone = () => {\n const c = client as any\n if (c.clone && typeof c.clone === 'function') {\n return getExtendedClient(c.clone())\n }\n return getExtendedClient(new c.constructor(c.config))\n }\n\n return {\n ...client,\n botId,\n axios: (client as any).axiosInstance as AxiosInstance,\n clone,\n abortable: (signal: AbortSignal) => {\n const abortable = clone()\n const instance = abortable.axios\n instance.defaults.signal = signal\n return abortable\n },\n } as ExtendedClient\n}\n", "import { type ErrorType } from '@botpress/client'\n\nexport type BotpressError = {\n isApiError: boolean\n code: number\n description: string\n type: ErrorType\n subtype?: string\n error?: unknown\n metadata?: unknown\n message?: string\n id: string\n}\n\ntype Action = 'fallback' | 'retry' | 'abort'\n\nexport const getActionFromError = (error: any): Action => {\n if (!isBotpressError(error)) {\n return 'retry'\n }\n\n if (error.type === 'InvalidDataFormat') {\n if (error.message?.includes('data/model/id')) {\n // Invalid Model ID, so we want to try another model\n return 'fallback'\n }\n\n // Usually means the request was malformed\n return 'abort'\n }\n\n if (\n error.type === 'QuotaExceeded' ||\n error.type === 'RateLimited' ||\n error.type === 'Unknown' ||\n error.type === 'LimitExceeded'\n ) {\n // These errors are usually temporary, so we want to retry\n return 'retry'\n }\n\n const subtype = (error.metadata as any)?.subtype\n if (subtype === 'UPSTREAM_PROVIDER_FAILED') {\n // The model is degraded, so we want to try another model\n return 'fallback'\n }\n\n if (error.type === 'Internal') {\n // This is an internal error, probably a lambda timeout\n return 'retry'\n }\n\n return 'abort'\n}\n\nexport const isNotFoundError = (error: any): boolean => isBotpressError(error) && error.type === 'ResourceNotFound'\n\nexport const isForbiddenOrUnauthorizedError = (error: any): boolean =>\n isBotpressError(error) && (error.type === 'Forbidden' || error.type === 'Unauthorized')\n\nexport const isBotpressError = (error: any): error is BotpressError =>\n typeof error === 'object' &&\n error !== null &&\n 'isApiError' in error &&\n 'code' in error &&\n 'type' in error &&\n 'id' in error\n", "export type Callback<T> = (error: any | null, value: T) => void\nexport type Interceptor<T> = (error: any | null, value: T, next: Callback<T>, done: Callback<T>) => Promise<void> | void\n\nexport class InterceptorManager<T> {\n private _interceptors: Interceptor<T>[] = []\n\n public use(interceptor: Interceptor<T>) {\n this._interceptors.push(interceptor)\n return () => this.remove(interceptor)\n }\n\n public remove(interceptor: Interceptor<T>) {\n this._interceptors = this._interceptors.filter((i) => i !== interceptor)\n }\n\n public async run(value: T, signal: AbortSignal): Promise<T> {\n let error: any | null = null\n let result: T = value\n let done = false\n\n for (const interceptor of this._interceptors) {\n if (done) {\n break\n }\n\n if (signal.aborted) {\n throw signal.reason\n }\n\n await new Promise<void>((resolve) => {\n void interceptor(\n error,\n result,\n (err, val) => {\n error = err\n result = val\n resolve()\n },\n (err, val) => {\n error = err\n result = val\n done = true\n resolve()\n }\n )\n })\n }\n\n if (error) {\n throw error\n }\n\n return result\n }\n}\n", "import { ExtendedClient, getExtendedClient } from './bp-client'\nimport { isForbiddenOrUnauthorizedError, isNotFoundError } from './errors'\nimport { Model as RawModel } from './schemas.gen'\nimport { BotpressClientLike } from './types'\n\nexport const DOWNTIME_THRESHOLD_MINUTES = 5\nconst PREFERENCES_FILE_SUFFIX = 'models.config.json'\n\nexport const DEFAULT_INTEGRATIONS = ['google-ai', 'anthropic', 'openai', 'cerebras', 'fireworks-ai', 'groq']\n\n// Biases for vendors and models\nconst VendorPreferences = ['google-ai', 'anthropic', 'openai']\nconst BestModelPreferences = ['4.1', '4o', '3-5-sonnet', 'gemini-1.5-pro']\nconst FastModelPreferences = ['gemini-1.5-flash', '4.1-mini', '4.1-nano', '4o-mini', 'flash', 'haiku']\n\nconst InputPricePenalty = 3 // $3 per 1M tokens\nconst OutputPricePenalty = 10 // $10 per 1M tokens\nconst LowTokensPenalty = 128_000 // 128k tokens\n\nexport type Model = RawModel & {\n ref: ModelRef\n integration: string\n}\n\nexport type ModelRef = `${string}:${string}`\n\nexport type ModelPreferences = {\n best: ModelRef[]\n fast: ModelRef[]\n downtimes: Array<{ ref: ModelRef; startedAt: string; reason: string }>\n}\n\nconst isRecommended = (model: Model) => model.tags.includes('recommended')\nconst isDeprecated = (model: Model) => model.tags.includes('deprecated')\nconst isLowCost = (model: Model) => model.tags.includes('low-cost')\nconst hasVisionSupport = (model: Model) => model.tags.includes('vision')\nconst isGeneralPurpose = (model: Model) => model.tags.includes('general-purpose')\n\nconst scoreModel = (model: Model, type: 'best' | 'fast', boosts: Record<ModelRef, number> = {}) => {\n let score: number = 0\n\n const scores: Array<[string, boolean, number]> = [\n ['input price penalty', model.input.costPer1MTokens > InputPricePenalty, -1],\n ['output price penalty', model.output.costPer1MTokens > OutputPricePenalty, -1],\n ['low tokens penalty', (model.input.maxTokens ?? 0 + model.output.maxTokens ?? 0) < LowTokensPenalty, -1],\n ['recommended', isRecommended(model), 2],\n ['deprecated', isDeprecated(model), -2],\n ['vision support', hasVisionSupport(model), 1],\n ['general purpose', isGeneralPurpose(model), 1],\n ['vendor preference', VendorPreferences.includes(model.integration), 1],\n ['best model preference', type === 'best' && BestModelPreferences.some((x) => model.id.includes(x)), 1],\n ['fast model preference penalty', type === 'best' && FastModelPreferences.some((x) => model.id.includes(x)), -2],\n ['fast model preference', type === 'fast' && FastModelPreferences.some((x) => model.id.includes(x)), 2],\n ['low cost', type === 'fast' && isLowCost(model), 1],\n ]\n\n for (const rule in boosts) {\n if (model.ref.includes(rule)) {\n scores.push([`boost (${rule})`, true, Number(boosts[rule as ModelRef]) ?? 0] as const)\n }\n }\n\n for (const [, condition, value] of scores) {\n if (condition) {\n score += value\n }\n }\n\n return score\n}\n\nexport const getBestModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'best', boosts) - scoreModel(a, 'best', boosts))\n\nexport const getFastModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'fast', boosts) - scoreModel(a, 'fast', boosts))\n\nexport const pickModel = (models: ModelRef[], downtimes: ModelPreferences['downtimes'] = []) => {\n const copy = [...models]\n const elasped = (date: string) => new Date().getTime() - new Date(date).getTime()\n const DOWNTIME_THRESHOLD = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n if (!copy.length) {\n throw new Error('At least one model is required')\n }\n\n while (copy.length) {\n const ref = copy.shift() as ModelRef\n const downtime = downtimes.find((o) => o.ref === ref && elasped(o.startedAt) < DOWNTIME_THRESHOLD)\n if (downtime) {\n continue\n } else {\n return ref\n }\n }\n\n throw new Error(`All models are down: ${models.join(', ')}`)\n}\n\nexport abstract class ModelProvider {\n public abstract fetchInstalledModels(): Promise<Model[]>\n public abstract fetchModelPreferences(): Promise<ModelPreferences | null>\n public abstract saveModelPreferences(preferences: ModelPreferences): Promise<void>\n public abstract deleteModelPreferences(): Promise<void>\n}\n\nexport class RemoteModelProvider extends ModelProvider {\n private _client: ExtendedClient\n\n public constructor(client: BotpressClientLike) {\n super()\n this._client = getExtendedClient(client)\n }\n\n private async _fetchInstalledIntegrationNames() {\n try {\n const { bot } = await this._client.getBot({ id: this._client.botId })\n const integrations = Object.values(bot.integrations).filter((x) => x.status === 'registered')\n return integrations.map((x) => x.name)\n } catch (err) {\n if (isForbiddenOrUnauthorizedError(err)) {\n // This happens when the bot (with a BAK token) tries to access the .getBot endpoint\n return DEFAULT_INTEGRATIONS\n }\n\n throw err\n }\n }\n\n public async fetchInstalledModels() {\n const integrationNames = await this._fetchInstalledIntegrationNames()\n const models: Model[] = []\n\n await Promise.allSettled(\n integrationNames.map(async (integration) => {\n const { output } = await this._client.callAction({\n type: `${integration}:listLanguageModels`,\n input: {},\n })\n\n if (!output?.models?.length) {\n return\n }\n\n for (const model of output.models as RawModel[]) {\n if (model.name && model.id && model.input && model.tags) {\n models.push({\n ref: `${integration}:${model.id}`,\n integration,\n id: model.id,\n name: model.name,\n description: model.description,\n input: model.input,\n output: model.output,\n tags: model.tags,\n })\n }\n }\n })\n )\n\n return models\n }\n\n public async fetchModelPreferences(): Promise<ModelPreferences | null> {\n try {\n const { file } = await this._client.getFile({ id: this._preferenceFileKey })\n\n if (globalThis.fetch !== undefined) {\n const response = await fetch(file.url)\n return (await response.json()) as ModelPreferences\n } else {\n const { data } = await this._client.axios.get(file.url, {\n // we piggy-back axios to avoid adding a new dependency\n // unset all headers to avoid S3 pre-signed signature mismatch\n headers: Object.keys(this._client.config.headers).reduce(\n (acc, key) => {\n acc[key] = undefined\n return acc\n },\n {} as Record<string, undefined>\n ),\n })\n return data as ModelPreferences\n }\n } catch (err) {\n if (isNotFoundError(err)) {\n return null\n }\n\n throw err\n }\n }\n\n public async saveModelPreferences(preferences: ModelPreferences) {\n await this._client.uploadFile({\n key: this._preferenceFileKey,\n content: JSON.stringify(preferences, null, 2),\n index: false,\n tags: {\n system: 'true',\n purpose: 'config',\n },\n })\n }\n\n public async deleteModelPreferences() {\n await this._client.deleteFile({ id: this._preferenceFileKey }).catch(() => {})\n }\n\n private get _preferenceFileKey() {\n return `bot->${this._client.botId}->${PREFERENCES_FILE_SUFFIX}`\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,QAAM,iBAAkC;MACtC,mBAAmB;MACnB,QAAQ;MACR,UAAU;MACV,eAAe;MACf,OAAO,WAAA;AAAM,eAAA;MAAA;MACb,eAAe;MACf,cAAc;;AAGhB,aAAgB,oBAAoB,SAAuB;AACzD,UAAM,YAAS,SAAA,SAAA,CAAA,GAAyB,cAAc,GAAK,OAAO;AAElE,UAAI,UAAU,gBAAgB,GAAG;AAC/B,kBAAU,gBAAgB;;AAG5B,aAAO;IACT;AARA,YAAA,sBAAA;;;;;;;;;ACxBA,aAAgB,WAAW,OAAa;AACpC,UAAM,gBAAgB,KAAK,OAAM,IAAK;AACtC,aAAO,KAAK,MAAM,aAAa;IACnC;AAHA,YAAA,aAAA;;;;;;;;;ACAA,aAAgB,SAAS,OAAa;AAClC,aAAO;IACX;AAFA,YAAA,WAAA;;;;;;;;;ACCA,QAAA,gBAAA;AACA,QAAA,cAAA;AAIA,aAAgB,cAAc,SAAwB;AACpD,cAAQ,QAAQ,QAAQ;QACtB,KAAK;AACH,iBAAO,cAAA;QAET,KAAK;QACL;AACE,iBAAO,YAAA;;IAEb;AATA,YAAA,gBAAA;;;;;;;;;ACJA,QAAA,mBAAA;AAEA,QAAA;;MAAA,WAAA;AAEE,iBAAAA,OAAoB,SAAwB;AAAxB,eAAA,UAAA;AADV,eAAA,UAAU;QAC2B;AAExC,QAAAA,OAAA,UAAA,QAAP,WAAA;AAAA,cAAA,QAAA;AACE,iBAAO,IAAI,QAAQ,SAAA,SAAO;AAAI,mBAAA,WA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,CAAC,GAAI,GAAI,KAAK,cAAc,CAAC,CAAE;AAAA,YACjF,CAAC;AAED,iBAAK,QAAQ,KAAK,YAAY,OAAO,GAAG;AACxC,mBAAO;AAAA,UACT;AAEA,eAAK,QAAQ,KAAK,SAAS,OAAO,GAAG;AACrC,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WAAW;AAAA,MACf;AAAA,MACA,MAAM;AAAA,QACJ,QAAQ,KAAK,UAAU;AAAA,QACvB,OAAO,EAAE,aAA2B,MAAc;AAAA,QAClD,SAAS,KAAK,IAAI,IAAI;AAAA,QACtB,MAAM,EAAE,OAAO,OAAO,MAAM,WAAW,QAAQ,OAAO,MAAM,WAAW;AAAA,QACvE,QAAQ,EAAE,OAAO,OAAO,MAAM,aAAa,QAAQ,OAAO,MAAM,aAAa;AAAA,MAC/E;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,YAAY,OAAO,QAAQ;AAE7C,WAAO,KAAK,aAAa,SAAS,IAAI,UAAU,MAAM;AAAA,EACxD;AACF;",
|
|
6
|
-
"names": ["Delay", "SkipFirstDelay", "AlwaysDelay", "backOff", "BackOff", "ref"]
|
|
3
|
+
"sources": ["../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/options.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/full/full.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/no/no.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/jitter.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.base.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/skip-first/skip-first.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/always/always.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/backoff.ts", "../src/index.ts", "../src/client.ts", "../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js", "../src/bp-client.ts", "../src/cognitive_beta/index.ts", "../src/errors.ts", "../src/interceptors.ts", "../src/models.ts"],
|
|
4
|
+
"sourcesContent": [null, null, null, null, null, null, null, null, null, "export { Events, BotpressClientLike } from './types'\nexport * from './client'\nexport { ModelPreferences, ModelProvider, RemoteModelProvider, Model } from './models'\nexport { type GenerateContentInput, type GenerateContentOutput } from './schemas.gen'\nexport * from './cognitive_beta'\n", "import { backOff } from 'exponential-backoff'\nimport { createNanoEvents, Unsubscribe } from 'nanoevents'\n\nimport { ExtendedClient, getExtendedClient } from './bp-client'\nimport { CognitiveBeta } from './cognitive_beta'\nimport { getActionFromError } from './errors'\nimport { InterceptorManager } from './interceptors'\nimport {\n DOWNTIME_THRESHOLD_MINUTES,\n getBestModels,\n getFastModels,\n Model,\n ModelPreferences,\n ModelProvider,\n ModelRef,\n pickModel,\n RemoteModelProvider,\n} from './models'\nimport { GenerateContentOutput } from './schemas.gen'\nimport { CognitiveProps, Events, InputProps, Request, Response } from './types'\n\nexport class Cognitive {\n public ['$$IS_COGNITIVE'] = true\n\n public static isCognitiveClient(obj: any): obj is Cognitive {\n return obj?.$$IS_COGNITIVE === true\n }\n\n public interceptors = {\n request: new InterceptorManager<Request>(),\n response: new InterceptorManager<Response>(),\n }\n\n protected _models: Model[] = []\n protected _timeoutMs: number = 5 * 60 * 1000 // Default timeout of 5 minutes\n protected _maxRetries: number = 5 // Default max retries\n protected _client: ExtendedClient\n protected _preferences: ModelPreferences | null = null\n protected _provider: ModelProvider\n protected _downtimes: ModelPreferences['downtimes'] = []\n protected _useBeta: boolean = false\n\n private _events = createNanoEvents<Events>()\n\n public constructor(props: CognitiveProps) {\n this._client = getExtendedClient(props.client)\n this._provider = props.provider ?? new RemoteModelProvider(props.client)\n this._timeoutMs = props.timeout ?? this._timeoutMs\n this._maxRetries = props.maxRetries ?? this._maxRetries\n this._useBeta = props.__experimental_beta ?? false\n }\n\n public get client(): ExtendedClient {\n return this._client\n }\n\n public clone(): Cognitive {\n const copy = new Cognitive({\n client: this._client.clone(),\n provider: this._provider,\n timeout: this._timeoutMs,\n maxRetries: this._maxRetries,\n })\n\n copy._models = [...this._models]\n copy._preferences = this._preferences ? { ...this._preferences } : null\n copy._downtimes = [...this._downtimes]\n copy.interceptors.request = this.interceptors.request\n copy.interceptors.response = this.interceptors.response\n\n return copy\n }\n\n public on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe {\n return this._events.on(event, cb)\n }\n\n public async fetchInstalledModels(): Promise<Model[]> {\n if (!this._models.length) {\n this._models = await this._provider.fetchInstalledModels()\n }\n\n return this._models\n }\n\n public async fetchPreferences(): Promise<ModelPreferences> {\n if (this._preferences) {\n return this._preferences\n }\n\n this._preferences = await this._provider.fetchModelPreferences()\n\n if (this._preferences) {\n return this._preferences\n }\n\n const models = await this.fetchInstalledModels()\n\n this._preferences = {\n best: getBestModels(models).map((m) => m.ref),\n fast: getFastModels(models).map((m) => m.ref),\n downtimes: [],\n }\n\n await this._provider.saveModelPreferences(this._preferences)\n\n return this._preferences\n }\n\n public async setPreferences(preferences: ModelPreferences, save: boolean = false): Promise<void> {\n this._preferences = preferences\n\n if (save) {\n await this._provider.saveModelPreferences(preferences)\n }\n }\n\n private _cleanupOldDowntimes(): void {\n const now = Date.now()\n const thresholdMs = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n this._preferences!.downtimes = this._preferences!.downtimes.filter((downtime) => {\n const downtimeStart = new Date(downtime.startedAt).getTime()\n return now - downtimeStart <= thresholdMs\n })\n }\n\n private async _selectModel(ref: string): Promise<{ integration: string; model: string }> {\n const parseRef = (ref: string) => {\n const parts = ref.split(':')\n return { integration: parts[0]!, model: parts.slice(1).join(':') }\n }\n\n const preferences = await this.fetchPreferences()\n\n preferences.best ??= []\n preferences.fast ??= []\n preferences.downtimes ??= []\n\n const downtimes = [...preferences.downtimes, ...(this._downtimes ?? [])]\n\n if (ref === 'best') {\n return parseRef(pickModel(preferences.best, downtimes))\n }\n\n if (ref === 'fast') {\n return parseRef(pickModel(preferences.fast, downtimes))\n }\n\n return parseRef(pickModel([ref as ModelRef, ...preferences.best, ...preferences.fast], downtimes))\n }\n\n public async getModelDetails(model: string) {\n await this.fetchInstalledModels()\n const { integration, model: modelName } = await this._selectModel(model)\n const def = this._models.find((m) => m.integration === integration && (m.name === modelName || m.id === modelName))\n if (!def) {\n throw new Error(`Model ${modelName} not found`)\n }\n\n return def\n }\n\n public async generateContent(input: InputProps): Promise<Response> {\n if (!this._useBeta) {\n return this._generateContent(input)\n }\n\n const betaClient = new CognitiveBeta({\n headers: this._client.config.headers as Record<string, string>,\n baseUrl: this._client.config.apiUrl.includes('.cloud')\n ? 'https://cognitive.botpress.cloud'\n : 'https://cognitive.botpress.dev',\n })\n\n const response = await betaClient.generateText(input as any)\n return {\n output: {\n id: 'beta-output',\n provider: response.metadata.provider,\n model: response.metadata.model!,\n choices: [\n {\n type: 'text',\n content: response.output,\n role: 'assistant',\n index: 0,\n stopReason: response.metadata.stopReason! as any,\n },\n ],\n usage: {\n inputTokens: response.metadata.usage.inputTokens,\n inputCost: 0,\n outputTokens: response.metadata.usage.outputTokens,\n outputCost: response.metadata.cost ?? 0,\n },\n botpress: {\n cost: response.metadata.cost ?? 0,\n },\n },\n meta: {\n cached: response.metadata.cached,\n model: { integration: response.metadata.provider, model: response.metadata.model! },\n latency: response.metadata.latency!,\n cost: {\n input: 0,\n output: response.metadata.cost || 0,\n },\n tokens: {\n input: response.metadata.usage.inputTokens,\n output: response.metadata.usage.outputTokens,\n },\n },\n }\n }\n\n private async _generateContent(input: InputProps): Promise<Response> {\n const start = Date.now()\n\n const signal = input.signal ?? AbortSignal.timeout(this._timeoutMs)\n\n const client = this._client.abortable(signal)\n\n let props: Request = { input }\n let integration: string\n let model: string\n\n this._events.emit('request', props)\n\n const { output, meta } = await backOff<{\n output: GenerateContentOutput\n meta: any\n }>(\n async () => {\n const selection = await this._selectModel(input.model ?? 'best')\n\n integration = selection.integration\n model = selection.model\n\n props = await this.interceptors.request.run({ input }, signal)\n\n return client.callAction({\n type: `${integration}:generateContent`,\n input: {\n ...props.input,\n model: { id: model },\n },\n }) as Promise<{ output: GenerateContentOutput; meta: any }>\n },\n {\n retry: async (err, _attempt) => {\n if (signal?.aborted) {\n // We don't want to retry if the request was aborted\n this._events.emit('aborted', props, err)\n signal.throwIfAborted()\n return false\n }\n\n if (_attempt > this._maxRetries) {\n this._events.emit('error', props, err)\n return false\n }\n\n const action = getActionFromError(err)\n\n if (action === 'abort') {\n this._events.emit('error', props, err)\n return false\n }\n\n if (action === 'fallback') {\n // We don't want to retry if the request was already retried with a fallback model\n this._downtimes.push({\n ref: `${integration!}:${model!}`,\n startedAt: new Date().toISOString(),\n reason: 'Model is down',\n })\n\n this._cleanupOldDowntimes()\n\n await this._provider.saveModelPreferences({\n ...(this._preferences ?? { best: [], downtimes: [], fast: [] }),\n downtimes: [...(this._preferences!.downtimes ?? []), ...(this._downtimes ?? [])],\n })\n\n this._events.emit('fallback', props, err)\n return true\n }\n\n this._events.emit('retry', props, err)\n return true\n },\n }\n )\n\n const response = {\n output,\n meta: {\n cached: meta.cached ?? false,\n model: { integration: integration!, model: model! },\n latency: Date.now() - start,\n cost: { input: output.usage.inputCost, output: output.usage.outputCost },\n tokens: { input: output.usage.inputTokens, output: output.usage.outputTokens },\n },\n } satisfies Response\n\n this._events.emit('response', props, response)\n\n return this.interceptors.response.run(response, signal)\n }\n}\n", "export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n", "import { type Client } from '@botpress/client'\nimport { type AxiosInstance } from 'axios'\nimport { BotpressClientLike } from './types'\n\n/** @internal */\nexport type ExtendedClient = Client & {\n botId: string\n axios: AxiosInstance\n clone: () => ExtendedClient\n abortable: (signal: AbortSignal) => ExtendedClient\n}\n\ntype InternalClientType = BotpressClientLike & {\n _client?: InternalClientType\n config: {\n headers: Record<string, string>\n }\n}\n\nexport const getExtendedClient = (_client: unknown): ExtendedClient => {\n const client = _client as InternalClientType\n\n if (!client || client === null || typeof client !== 'object') {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n if (typeof client._client === 'object' && !!client._client) {\n try {\n return getExtendedClient(client._client)\n } catch {}\n }\n\n if (\n typeof client.constructor !== 'function' ||\n typeof client.callAction !== 'function' ||\n !client.config ||\n typeof client.config !== 'object' ||\n !client.config.headers\n ) {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n const botId = client.config.headers['x-bot-id'] as string\n\n if (!botId?.length) {\n throw new Error('Client must be instanciated with Bot ID')\n }\n\n const clone = () => {\n const c = client as any\n if (c.clone && typeof c.clone === 'function') {\n return getExtendedClient(c.clone())\n }\n return getExtendedClient(new c.constructor(c.config))\n }\n\n return {\n ...client,\n botId,\n axios: (client as any).axiosInstance as AxiosInstance,\n clone,\n abortable: (signal: AbortSignal) => {\n const abortable = clone()\n const instance = abortable.axios\n instance.defaults.signal = signal\n return abortable\n },\n } as ExtendedClient\n}\n", "import axios, { AxiosInstance } from 'axios'\nimport { backOff } from 'exponential-backoff'\nimport { CognitiveRequest, CognitiveResponse, CognitiveStreamChunk, Model } from './models'\n\nexport { CognitiveRequest, CognitiveResponse, CognitiveStreamChunk }\n\ntype ClientProps = {\n baseUrl?: string\n timeout?: number\n botId?: string\n token?: string\n headers?: Record<string, string>\n}\n\ntype RequestOptions = {\n signal?: AbortSignal\n timeout?: number\n}\n\nconst isBrowser = () => typeof window !== 'undefined' && typeof window.fetch === 'function'\n\nexport class CognitiveBeta {\n private _axiosClient: AxiosInstance\n private readonly _config: Required<ClientProps>\n\n public constructor(props: ClientProps) {\n this._config = {\n baseUrl: props.baseUrl || 'https://cognitive.botpress.cloud',\n timeout: props.timeout || 60_001,\n token: props.token || '',\n botId: props.botId || '',\n headers: props.headers || {},\n }\n\n this._axiosClient = axios.create({\n headers: {\n Authorization: `Bearer ${this._config.token}`,\n 'X-Bot-Id': this._config.botId,\n ...this._config.headers,\n },\n baseURL: this._config.baseUrl,\n })\n }\n\n public async generateText(input: CognitiveRequest, options: RequestOptions = {}) {\n const signal = options.signal ?? AbortSignal.timeout(this._config.timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<CognitiveResponse>('/v1/generate-text', input, {\n signal,\n timeout: options.timeout ?? this._config.timeout,\n })\n )\n\n return data\n }\n\n public async listModels(input: void, options: RequestOptions = {}) {\n const signal = options.signal ?? AbortSignal.timeout(this._config.timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<Model[]>('/v1/models', input, {\n signal,\n timeout: options.timeout ?? this._config.timeout,\n })\n )\n\n return data\n }\n\n public async *generateTextStream(\n request: CognitiveRequest,\n options: RequestOptions = {}\n ): AsyncGenerator<CognitiveStreamChunk, void, unknown> {\n const signal = options.signal ?? AbortSignal.timeout(this._config.timeout)\n\n if (isBrowser()) {\n const res = await fetch(`${this._config.baseUrl}/v1/generate-text-stream`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this._config.token}`,\n 'X-Bot-Id': this._config.botId,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ ...request, stream: true }),\n signal,\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n const err = new Error(`HTTP ${res.status}: ${text || res.statusText}`)\n ;(err as any).response = { status: res.status, data: text }\n throw err\n }\n\n const body = res.body\n if (!body) {\n throw new Error('No response body received for streaming request')\n }\n\n const reader = body.getReader()\n const iterable = (async function* () {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) {\n break\n }\n if (value) {\n yield value\n }\n }\n })()\n\n for await (const obj of this._ndjson<CognitiveStreamChunk>(iterable)) {\n yield obj\n }\n return\n }\n\n const res = await this._withServerRetry(() =>\n this._axiosClient.post(\n '/v1/generate-text-stream',\n { ...request, stream: true },\n {\n responseType: 'stream',\n signal,\n timeout: options.timeout ?? this._config.timeout,\n }\n )\n )\n\n const nodeStream: AsyncIterable<Uint8Array> = res.data as any\n if (!nodeStream) {\n throw new Error('No response body received for streaming request')\n }\n\n for await (const obj of this._ndjson<CognitiveStreamChunk>(nodeStream)) {\n yield obj\n }\n }\n\n private async *_ndjson<T>(stream: AsyncIterable<Uint8Array>): AsyncGenerator<T, void, unknown> {\n const decoder = new TextDecoder('utf-8')\n let buffer = ''\n\n for await (const chunk of stream) {\n buffer += decoder.decode(chunk, { stream: true })\n\n for (;;) {\n const i = buffer.indexOf('\\n')\n if (i < 0) {\n break\n }\n\n const line = buffer.slice(0, i).replace(/\\r$/, '')\n buffer = buffer.slice(i + 1)\n\n if (!line) {\n continue\n }\n\n yield JSON.parse(line) as T\n }\n }\n\n buffer += decoder.decode()\n\n const tail = buffer.trim()\n if (tail) {\n yield JSON.parse(tail) as T\n }\n }\n\n private _isRetryableServerError(error: any): boolean {\n if (axios.isAxiosError(error)) {\n if (!error.response) {\n return true\n }\n\n const status = error.response?.status\n if (status && [502, 503, 504].includes(status)) {\n return true\n }\n\n if (\n error.code &&\n ['ECONNABORTED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', 'ENOTFOUND', 'EPIPE'].includes(error.code)\n ) {\n return true\n }\n }\n\n return false\n }\n\n private async _withServerRetry<T>(fn: () => Promise<T>): Promise<T> {\n return backOff(fn, {\n numOfAttempts: 3,\n startingDelay: 300,\n timeMultiple: 2,\n jitter: 'full',\n retry: (e) => this._isRetryableServerError(e),\n })\n }\n}\n", "import { type ErrorType } from '@botpress/client'\n\nexport type BotpressError = {\n isApiError: boolean\n code: number\n description: string\n type: ErrorType\n subtype?: string\n error?: unknown\n metadata?: unknown\n message?: string\n id: string\n}\n\ntype Action = 'fallback' | 'retry' | 'abort'\n\nexport const getActionFromError = (error: any): Action => {\n if (!isBotpressError(error)) {\n return 'retry'\n }\n\n if (error.type === 'InvalidDataFormat') {\n if (error.message?.includes('data/model/id')) {\n // Invalid Model ID, so we want to try another model\n return 'fallback'\n }\n\n // Usually means the request was malformed\n return 'abort'\n }\n\n if (\n error.type === 'QuotaExceeded' ||\n error.type === 'RateLimited' ||\n error.type === 'Unknown' ||\n error.type === 'LimitExceeded'\n ) {\n // These errors are usually temporary, so we want to retry\n return 'retry'\n }\n\n const subtype = (error.metadata as any)?.subtype\n if (subtype === 'UPSTREAM_PROVIDER_FAILED') {\n // The model is degraded, so we want to try another model\n return 'fallback'\n }\n\n if (error.type === 'Internal') {\n // This is an internal error, probably a lambda timeout\n return 'retry'\n }\n\n return 'abort'\n}\n\nexport const isNotFoundError = (error: any): boolean => isBotpressError(error) && error.type === 'ResourceNotFound'\n\nexport const isForbiddenOrUnauthorizedError = (error: any): boolean =>\n isBotpressError(error) && (error.type === 'Forbidden' || error.type === 'Unauthorized')\n\nexport const isBotpressError = (error: any): error is BotpressError =>\n typeof error === 'object' &&\n error !== null &&\n 'isApiError' in error &&\n 'code' in error &&\n 'type' in error &&\n 'id' in error\n", "export type Callback<T> = (error: any | null, value: T) => void\nexport type Interceptor<T> = (error: any | null, value: T, next: Callback<T>, done: Callback<T>) => Promise<void> | void\n\nexport class InterceptorManager<T> {\n private _interceptors: Interceptor<T>[] = []\n\n public use(interceptor: Interceptor<T>) {\n this._interceptors.push(interceptor)\n return () => this.remove(interceptor)\n }\n\n public remove(interceptor: Interceptor<T>) {\n this._interceptors = this._interceptors.filter((i) => i !== interceptor)\n }\n\n public async run(value: T, signal: AbortSignal): Promise<T> {\n let error: any | null = null\n let result: T = value\n let done = false\n\n for (const interceptor of this._interceptors) {\n if (done) {\n break\n }\n\n if (signal.aborted) {\n throw signal.reason\n }\n\n await new Promise<void>((resolve) => {\n void interceptor(\n error,\n result,\n (err, val) => {\n error = err\n result = val\n resolve()\n },\n (err, val) => {\n error = err\n result = val\n done = true\n resolve()\n }\n )\n })\n }\n\n if (error) {\n throw error\n }\n\n return result\n }\n}\n", "import { ExtendedClient, getExtendedClient } from './bp-client'\nimport { isForbiddenOrUnauthorizedError, isNotFoundError } from './errors'\nimport { Model as RawModel } from './schemas.gen'\nimport { BotpressClientLike } from './types'\n\nexport const DOWNTIME_THRESHOLD_MINUTES = 5\nconst PREFERENCES_FILE_SUFFIX = 'models.config.json'\n\nexport const DEFAULT_INTEGRATIONS = ['google-ai', 'anthropic', 'openai', 'cerebras', 'fireworks-ai', 'groq']\n\n// Biases for vendors and models\nconst VendorPreferences = ['google-ai', 'anthropic', 'openai']\nconst BestModelPreferences = ['4.1', '4o', '3-5-sonnet', 'gemini-1.5-pro']\nconst FastModelPreferences = ['gemini-1.5-flash', '4.1-mini', '4.1-nano', '4o-mini', 'flash', 'haiku']\n\nconst InputPricePenalty = 3 // $3 per 1M tokens\nconst OutputPricePenalty = 10 // $10 per 1M tokens\nconst LowTokensPenalty = 128_000 // 128k tokens\n\nexport type Model = RawModel & {\n ref: ModelRef\n integration: string\n}\n\nexport type ModelRef = `${string}:${string}`\n\nexport type ModelPreferences = {\n best: ModelRef[]\n fast: ModelRef[]\n downtimes: Array<{ ref: ModelRef; startedAt: string; reason: string }>\n}\n\nconst isRecommended = (model: Model) => model.tags.includes('recommended')\nconst isDeprecated = (model: Model) => model.tags.includes('deprecated')\nconst isLowCost = (model: Model) => model.tags.includes('low-cost')\nconst hasVisionSupport = (model: Model) => model.tags.includes('vision')\nconst isGeneralPurpose = (model: Model) => model.tags.includes('general-purpose')\n\nconst scoreModel = (model: Model, type: 'best' | 'fast', boosts: Record<ModelRef, number> = {}) => {\n let score: number = 0\n\n const scores: Array<[string, boolean, number]> = [\n ['input price penalty', model.input.costPer1MTokens > InputPricePenalty, -1],\n ['output price penalty', model.output.costPer1MTokens > OutputPricePenalty, -1],\n ['low tokens penalty', (model.input.maxTokens ?? 0 + model.output.maxTokens ?? 0) < LowTokensPenalty, -1],\n ['recommended', isRecommended(model), 2],\n ['deprecated', isDeprecated(model), -2],\n ['vision support', hasVisionSupport(model), 1],\n ['general purpose', isGeneralPurpose(model), 1],\n ['vendor preference', VendorPreferences.includes(model.integration), 1],\n ['best model preference', type === 'best' && BestModelPreferences.some((x) => model.id.includes(x)), 1],\n ['fast model preference penalty', type === 'best' && FastModelPreferences.some((x) => model.id.includes(x)), -2],\n ['fast model preference', type === 'fast' && FastModelPreferences.some((x) => model.id.includes(x)), 2],\n ['low cost', type === 'fast' && isLowCost(model), 1],\n ]\n\n for (const rule in boosts) {\n if (model.ref.includes(rule)) {\n scores.push([`boost (${rule})`, true, Number(boosts[rule as ModelRef]) ?? 0] as const)\n }\n }\n\n for (const [, condition, value] of scores) {\n if (condition) {\n score += value\n }\n }\n\n return score\n}\n\nexport const getBestModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'best', boosts) - scoreModel(a, 'best', boosts))\n\nexport const getFastModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'fast', boosts) - scoreModel(a, 'fast', boosts))\n\nexport const pickModel = (models: ModelRef[], downtimes: ModelPreferences['downtimes'] = []) => {\n const copy = [...models]\n const elasped = (date: string) => new Date().getTime() - new Date(date).getTime()\n const DOWNTIME_THRESHOLD = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n if (!copy.length) {\n throw new Error('At least one model is required')\n }\n\n while (copy.length) {\n const ref = copy.shift() as ModelRef\n const downtime = downtimes.find((o) => o.ref === ref && elasped(o.startedAt) < DOWNTIME_THRESHOLD)\n if (downtime) {\n continue\n } else {\n return ref\n }\n }\n\n throw new Error(`All models are down: ${models.join(', ')}`)\n}\n\nexport abstract class ModelProvider {\n public abstract fetchInstalledModels(): Promise<Model[]>\n public abstract fetchModelPreferences(): Promise<ModelPreferences | null>\n public abstract saveModelPreferences(preferences: ModelPreferences): Promise<void>\n public abstract deleteModelPreferences(): Promise<void>\n}\n\nexport class RemoteModelProvider extends ModelProvider {\n private _client: ExtendedClient\n\n public constructor(client: BotpressClientLike) {\n super()\n this._client = getExtendedClient(client)\n }\n\n private async _fetchInstalledIntegrationNames() {\n try {\n const { bot } = await this._client.getBot({ id: this._client.botId })\n const integrations = Object.values(bot.integrations).filter((x) => x.status === 'registered')\n return integrations.map((x) => x.name)\n } catch (err) {\n if (isForbiddenOrUnauthorizedError(err)) {\n // This happens when the bot (with a BAK token) tries to access the .getBot endpoint\n return DEFAULT_INTEGRATIONS\n }\n\n throw err\n }\n }\n\n public async fetchInstalledModels() {\n const integrationNames = await this._fetchInstalledIntegrationNames()\n const models: Model[] = []\n\n await Promise.allSettled(\n integrationNames.map(async (integration) => {\n const { output } = await this._client.callAction({\n type: `${integration}:listLanguageModels`,\n input: {},\n })\n\n if (!output?.models?.length) {\n return\n }\n\n for (const model of output.models as RawModel[]) {\n if (model.name && model.id && model.input && model.tags) {\n models.push({\n ref: `${integration}:${model.id}`,\n integration,\n id: model.id,\n name: model.name,\n description: model.description,\n input: model.input,\n output: model.output,\n tags: model.tags,\n })\n }\n }\n })\n )\n\n return models\n }\n\n public async fetchModelPreferences(): Promise<ModelPreferences | null> {\n try {\n const { file } = await this._client.getFile({ id: this._preferenceFileKey })\n\n if (globalThis.fetch !== undefined) {\n const response = await fetch(file.url)\n return (await response.json()) as ModelPreferences\n } else {\n const { data } = await this._client.axios.get(file.url, {\n // we piggy-back axios to avoid adding a new dependency\n // unset all headers to avoid S3 pre-signed signature mismatch\n headers: Object.keys(this._client.config.headers).reduce(\n (acc, key) => {\n acc[key] = undefined\n return acc\n },\n {} as Record<string, undefined>\n ),\n })\n return data as ModelPreferences\n }\n } catch (err) {\n if (isNotFoundError(err)) {\n return null\n }\n\n throw err\n }\n }\n\n public async saveModelPreferences(preferences: ModelPreferences) {\n await this._client.uploadFile({\n key: this._preferenceFileKey,\n content: JSON.stringify(preferences, null, 2),\n index: false,\n tags: {\n system: 'true',\n purpose: 'config',\n },\n })\n }\n\n public async deleteModelPreferences() {\n await this._client.deleteFile({ id: this._preferenceFileKey }).catch(() => {})\n }\n\n private get _preferenceFileKey() {\n return `bot->${this._client.botId}->${PREFERENCES_FILE_SUFFIX}`\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,QAAM,iBAAkC;MACtC,mBAAmB;MACnB,QAAQ;MACR,UAAU;MACV,eAAe;MACf,OAAO,WAAA;AAAM,eAAA;MAAA;MACb,eAAe;MACf,cAAc;;AAGhB,aAAgB,oBAAoB,SAAuB;AACzD,UAAM,YAAS,SAAA,SAAA,CAAA,GAAyB,cAAc,GAAK,OAAO;AAElE,UAAI,UAAU,gBAAgB,GAAG;AAC/B,kBAAU,gBAAgB;;AAG5B,aAAO;IACT;AARA,YAAA,sBAAA;;;;;;;;;ACxBA,aAAgB,WAAW,OAAa;AACpC,UAAM,gBAAgB,KAAK,OAAM,IAAK;AACtC,aAAO,KAAK,MAAM,aAAa;IACnC;AAHA,YAAA,aAAA;;;;;;;;;ACAA,aAAgB,SAAS,OAAa;AAClC,aAAO;IACX;AAFA,YAAA,WAAA;;;;;;;;;ACCA,QAAA,gBAAA;AACA,QAAA,cAAA;AAIA,aAAgB,cAAc,SAAwB;AACpD,cAAQ,QAAQ,QAAQ;QACtB,KAAK;AACH,iBAAO,cAAA;QAET,KAAK;QACL;AACE,iBAAO,YAAA;;IAEb;AATA,YAAA,gBAAA;;;;;;;;;ACJA,QAAA,mBAAA;AAEA,QAAA;;MAAA,WAAA;AAEE,iBAAAA,OAAoB,SAAwB;AAAxB,eAAA,UAAA;AADV,eAAA,UAAU;QAC2B;AAExC,QAAAA,OAAA,UAAA,QAAP,WAAA;AA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K,GAAG,eAAgB;AAAA,cACxB,WAAW,IAAI,KAAK,EAAE,YAAY;AAAA,cAClC,QAAQ;AAAA,YACV,CAAC;AAED,iBAAK,qBAAqB;AAE1B,kBAAM,KAAK,UAAU,qBAAqB;AAAA,cACxC,GAAI,KAAK,gBAAgB,EAAE,MAAM,CAAC,GAAG,WAAW,CAAC,GAAG,MAAM,CAAC,EAAE;AAAA,cAC7D,WAAW,CAAC,GAAI,KAAK,aAAc,aAAa,CAAC,GAAI,GAAI,KAAK,cAAc,CAAC,CAAE;AAAA,YACjF,CAAC;AAED,iBAAK,QAAQ,KAAK,YAAY,OAAO,GAAG;AACxC,mBAAO;AAAA,UACT;AAEA,eAAK,QAAQ,KAAK,SAAS,OAAO,GAAG;AACrC,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WAAW;AAAA,MACf;AAAA,MACA,MAAM;AAAA,QACJ,QAAQ,KAAK,UAAU;AAAA,QACvB,OAAO,EAAE,aAA2B,MAAc;AAAA,QAClD,SAAS,KAAK,IAAI,IAAI;AAAA,QACtB,MAAM,EAAE,OAAO,OAAO,MAAM,WAAW,QAAQ,OAAO,MAAM,WAAW;AAAA,QACvE,QAAQ,EAAE,OAAO,OAAO,MAAM,aAAa,QAAQ,OAAO,MAAM,aAAa;AAAA,MAC/E;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,YAAY,OAAO,QAAQ;AAE7C,WAAO,KAAK,aAAa,SAAS,IAAI,UAAU,MAAM;AAAA,EACxD;AACF;",
|
|
6
|
+
"names": ["Delay", "SkipFirstDelay", "AlwaysDelay", "backOff", "BackOff", "import_exponential_backoff", "axios", "res", "ref"]
|
|
7
7
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -127,7 +127,7 @@ type GenerateContentOutput = {
|
|
|
127
127
|
cost: number;
|
|
128
128
|
};
|
|
129
129
|
};
|
|
130
|
-
type Model$
|
|
130
|
+
type Model$2 = {
|
|
131
131
|
id: string;
|
|
132
132
|
name: string;
|
|
133
133
|
description: string;
|
|
@@ -144,7 +144,7 @@ type Model$1 = {
|
|
|
144
144
|
};
|
|
145
145
|
};
|
|
146
146
|
|
|
147
|
-
type Model = Model$
|
|
147
|
+
type Model$1 = Model$2 & {
|
|
148
148
|
ref: ModelRef;
|
|
149
149
|
integration: string;
|
|
150
150
|
};
|
|
@@ -159,7 +159,7 @@ type ModelPreferences = {
|
|
|
159
159
|
}>;
|
|
160
160
|
};
|
|
161
161
|
declare abstract class ModelProvider {
|
|
162
|
-
abstract fetchInstalledModels(): Promise<Model[]>;
|
|
162
|
+
abstract fetchInstalledModels(): Promise<Model$1[]>;
|
|
163
163
|
abstract fetchModelPreferences(): Promise<ModelPreferences | null>;
|
|
164
164
|
abstract saveModelPreferences(preferences: ModelPreferences): Promise<void>;
|
|
165
165
|
abstract deleteModelPreferences(): Promise<void>;
|
|
@@ -168,7 +168,7 @@ declare class RemoteModelProvider extends ModelProvider {
|
|
|
168
168
|
private _client;
|
|
169
169
|
constructor(client: BotpressClientLike);
|
|
170
170
|
private _fetchInstalledIntegrationNames;
|
|
171
|
-
fetchInstalledModels(): Promise<Model[]>;
|
|
171
|
+
fetchInstalledModels(): Promise<Model$1[]>;
|
|
172
172
|
fetchModelPreferences(): Promise<ModelPreferences | null>;
|
|
173
173
|
saveModelPreferences(preferences: ModelPreferences): Promise<void>;
|
|
174
174
|
deleteModelPreferences(): Promise<void>;
|
|
@@ -212,6 +212,8 @@ type CognitiveProps = {
|
|
|
212
212
|
timeout?: number;
|
|
213
213
|
/** Max retry attempts */
|
|
214
214
|
maxRetries?: number;
|
|
215
|
+
/** Whether to use the beta client. Restricted to authorized users. */
|
|
216
|
+
__experimental_beta?: boolean;
|
|
215
217
|
};
|
|
216
218
|
type Events = {
|
|
217
219
|
aborted: (req: Request, reason?: string) => void;
|
|
@@ -18001,7 +18003,7 @@ declare function toApiError(err: unknown): Error;
|
|
|
18001
18003
|
type IClient = Simplify<Client$1 & {
|
|
18002
18004
|
uploadFile: (input: UploadFileInput) => Promise<UploadFileOutput>;
|
|
18003
18005
|
}>;
|
|
18004
|
-
type ClientProps = CommonClientProps & {
|
|
18006
|
+
type ClientProps$2 = CommonClientProps & {
|
|
18005
18007
|
integrationId?: string;
|
|
18006
18008
|
workspaceId?: string;
|
|
18007
18009
|
botId?: string;
|
|
@@ -18009,7 +18011,7 @@ type ClientProps = CommonClientProps & {
|
|
|
18009
18011
|
};
|
|
18010
18012
|
declare class Client extends Client$1 implements IClient {
|
|
18011
18013
|
readonly config: Readonly<ClientConfig>;
|
|
18012
|
-
constructor(clientProps?: ClientProps);
|
|
18014
|
+
constructor(clientProps?: ClientProps$2);
|
|
18013
18015
|
get list(): {
|
|
18014
18016
|
conversations: (props: {
|
|
18015
18017
|
tags?: {
|
|
@@ -18931,25 +18933,158 @@ declare class Cognitive {
|
|
|
18931
18933
|
request: InterceptorManager<Request>;
|
|
18932
18934
|
response: InterceptorManager<Response>;
|
|
18933
18935
|
};
|
|
18934
|
-
protected _models: Model[];
|
|
18936
|
+
protected _models: Model$1[];
|
|
18935
18937
|
protected _timeoutMs: number;
|
|
18936
18938
|
protected _maxRetries: number;
|
|
18937
18939
|
protected _client: ExtendedClient;
|
|
18938
18940
|
protected _preferences: ModelPreferences | null;
|
|
18939
18941
|
protected _provider: ModelProvider;
|
|
18940
18942
|
protected _downtimes: ModelPreferences['downtimes'];
|
|
18943
|
+
protected _useBeta: boolean;
|
|
18941
18944
|
private _events;
|
|
18942
18945
|
constructor(props: CognitiveProps);
|
|
18943
18946
|
get client(): ExtendedClient;
|
|
18944
18947
|
clone(): Cognitive;
|
|
18945
18948
|
on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe;
|
|
18946
|
-
fetchInstalledModels(): Promise<Model[]>;
|
|
18949
|
+
fetchInstalledModels(): Promise<Model$1[]>;
|
|
18947
18950
|
fetchPreferences(): Promise<ModelPreferences>;
|
|
18948
18951
|
setPreferences(preferences: ModelPreferences, save?: boolean): Promise<void>;
|
|
18949
18952
|
private _cleanupOldDowntimes;
|
|
18950
18953
|
private _selectModel;
|
|
18951
|
-
getModelDetails(model: string): Promise<Model>;
|
|
18954
|
+
getModelDetails(model: string): Promise<Model$1>;
|
|
18952
18955
|
generateContent(input: InputProps): Promise<Response>;
|
|
18956
|
+
private _generateContent;
|
|
18953
18957
|
}
|
|
18954
18958
|
|
|
18955
|
-
|
|
18959
|
+
type Models = 'auto' | 'auto-best' | 'auto-fast' | 'auto-reasoning' | 'auto-cheapest' | 'auto-balance' | 'anthropic:claude-3-5-haiku-20241022' | 'anthropic:claude-3-5-sonnet-20240620' | 'anthropic:claude-3-5-sonnet-20241022' | 'anthropic:claude-3-7-sonnet-20250219' | 'anthropic:claude-3-haiku-20240307' | 'anthropic:claude-sonnet-4-20250514' | 'cerebras:gpt-oss-120b' | 'cerebras:llama-4-scout-17b-16e-instruct' | 'cerebras:llama3.1-8b' | 'cerebras:llama3.3-70b' | 'cerebras:qwen-3-32b' | 'google-ai:gemini-2.5-flash' | 'google-ai:gemini-2.5-pro' | 'google-ai:models/gemini-2.0-flash' | 'groq:openai/gpt-oss-120b' | 'groq:openai/gpt-oss-20b' | 'openai:gpt-4.1-2025-04-14' | 'openai:gpt-4.1-mini-2025-04-14' | 'openai:gpt-4.1-nano-2025-04-14' | 'openai:gpt-4o-2024-11-20' | 'openai:gpt-4o-mini-2024-07-18' | 'openai:gpt-5-2025-08-07' | 'openai:gpt-5-mini-2025-08-07' | 'openai:gpt-5-nano-2025-08-07' | 'openai:o1-2024-12-17' | 'openai:o1-mini-2024-09-12' | 'openai:o3-2025-04-16' | 'openai:o3-mini-2025-01-31' | 'openai:o4-mini-2025-04-16' | 'openrouter:gpt-oss-120b' | ({} & string);
|
|
18960
|
+
type CognitiveRequest = {
|
|
18961
|
+
/**
|
|
18962
|
+
* @minItems 1
|
|
18963
|
+
*/
|
|
18964
|
+
messages: {
|
|
18965
|
+
role: 'user' | 'assistant' | 'system';
|
|
18966
|
+
content: string | {
|
|
18967
|
+
type: 'text' | 'image';
|
|
18968
|
+
text?: string;
|
|
18969
|
+
url?: string;
|
|
18970
|
+
mimeType?: string;
|
|
18971
|
+
[k: string]: any;
|
|
18972
|
+
}[];
|
|
18973
|
+
type?: string;
|
|
18974
|
+
}[];
|
|
18975
|
+
/**
|
|
18976
|
+
* Model to query. Additional models are used as fallback if the main model is unavailable
|
|
18977
|
+
*/
|
|
18978
|
+
model?: Models | Models[];
|
|
18979
|
+
systemPrompt?: string;
|
|
18980
|
+
temperature?: number;
|
|
18981
|
+
maxTokens?: number;
|
|
18982
|
+
stopSequences?: string | string[];
|
|
18983
|
+
stream?: boolean;
|
|
18984
|
+
responseFormat?: 'text' | 'json';
|
|
18985
|
+
reasoningEffort?: 'low' | 'medium' | 'high';
|
|
18986
|
+
};
|
|
18987
|
+
type CognitiveStreamChunk = {
|
|
18988
|
+
output?: string;
|
|
18989
|
+
created: number;
|
|
18990
|
+
finished?: boolean;
|
|
18991
|
+
metadata?: {
|
|
18992
|
+
provider: string;
|
|
18993
|
+
model?: string;
|
|
18994
|
+
usage: {
|
|
18995
|
+
inputTokens: number;
|
|
18996
|
+
outputTokens: number;
|
|
18997
|
+
reasoningTokens?: number;
|
|
18998
|
+
};
|
|
18999
|
+
cost?: number;
|
|
19000
|
+
cached?: boolean;
|
|
19001
|
+
latency?: number;
|
|
19002
|
+
stopReason?: string;
|
|
19003
|
+
reasoningEffort?: string;
|
|
19004
|
+
warnings?: {
|
|
19005
|
+
type: 'parameter_ignored' | 'provider_limitation' | 'deprecated_model' | 'fallback_used';
|
|
19006
|
+
message: string;
|
|
19007
|
+
}[];
|
|
19008
|
+
/**
|
|
19009
|
+
* List of models that were tried and failed
|
|
19010
|
+
*/
|
|
19011
|
+
fallbackPath?: string[];
|
|
19012
|
+
debug?: {
|
|
19013
|
+
[k: string]: string;
|
|
19014
|
+
};
|
|
19015
|
+
};
|
|
19016
|
+
};
|
|
19017
|
+
type CognitiveResponse = {
|
|
19018
|
+
output: string;
|
|
19019
|
+
metadata: {
|
|
19020
|
+
provider: string;
|
|
19021
|
+
model?: string;
|
|
19022
|
+
usage: {
|
|
19023
|
+
inputTokens: number;
|
|
19024
|
+
outputTokens: number;
|
|
19025
|
+
reasoningTokens?: number;
|
|
19026
|
+
};
|
|
19027
|
+
cost?: number;
|
|
19028
|
+
cached?: boolean;
|
|
19029
|
+
latency?: number;
|
|
19030
|
+
stopReason?: string;
|
|
19031
|
+
reasoningEffort?: string;
|
|
19032
|
+
warnings?: {
|
|
19033
|
+
type: 'parameter_ignored' | 'provider_limitation' | 'deprecated_model' | 'fallback_used';
|
|
19034
|
+
message: string;
|
|
19035
|
+
}[];
|
|
19036
|
+
/**
|
|
19037
|
+
* List of models that were tried and failed
|
|
19038
|
+
*/
|
|
19039
|
+
fallbackPath?: string[];
|
|
19040
|
+
debug?: {
|
|
19041
|
+
[k: string]: string;
|
|
19042
|
+
};
|
|
19043
|
+
};
|
|
19044
|
+
error?: string;
|
|
19045
|
+
};
|
|
19046
|
+
type Model = {
|
|
19047
|
+
id: string;
|
|
19048
|
+
name: string;
|
|
19049
|
+
description: string;
|
|
19050
|
+
tags?: ('recommended' | 'deprecated' | 'general-purpose' | 'low-cost' | 'flagship' | 'vision' | 'coding' | 'agents' | 'function-calling' | 'roleplay' | 'storytelling' | 'reasoning' | 'preview')[];
|
|
19051
|
+
input: {
|
|
19052
|
+
maxTokens: number;
|
|
19053
|
+
/**
|
|
19054
|
+
* Cost per 1 million tokens, in U.S. dollars
|
|
19055
|
+
*/
|
|
19056
|
+
costPer1MTokens: number;
|
|
19057
|
+
};
|
|
19058
|
+
output: {
|
|
19059
|
+
maxTokens: number;
|
|
19060
|
+
/**
|
|
19061
|
+
* Cost per 1 million tokens, in U.S. dollars
|
|
19062
|
+
*/
|
|
19063
|
+
costPer1MTokens: number;
|
|
19064
|
+
};
|
|
19065
|
+
};
|
|
19066
|
+
|
|
19067
|
+
type ClientProps = {
|
|
19068
|
+
baseUrl?: string;
|
|
19069
|
+
timeout?: number;
|
|
19070
|
+
botId?: string;
|
|
19071
|
+
token?: string;
|
|
19072
|
+
headers?: Record<string, string>;
|
|
19073
|
+
};
|
|
19074
|
+
type RequestOptions = {
|
|
19075
|
+
signal?: AbortSignal;
|
|
19076
|
+
timeout?: number;
|
|
19077
|
+
};
|
|
19078
|
+
declare class CognitiveBeta {
|
|
19079
|
+
private _axiosClient;
|
|
19080
|
+
private readonly _config;
|
|
19081
|
+
constructor(props: ClientProps);
|
|
19082
|
+
generateText(input: CognitiveRequest, options?: RequestOptions): Promise<CognitiveResponse>;
|
|
19083
|
+
listModels(input: void, options?: RequestOptions): Promise<Model[]>;
|
|
19084
|
+
generateTextStream(request: CognitiveRequest, options?: RequestOptions): AsyncGenerator<CognitiveStreamChunk, void, unknown>;
|
|
19085
|
+
private _ndjson;
|
|
19086
|
+
private _isRetryableServerError;
|
|
19087
|
+
private _withServerRetry;
|
|
19088
|
+
}
|
|
19089
|
+
|
|
19090
|
+
export { type BotpressClientLike, Cognitive, CognitiveBeta, type CognitiveRequest, type CognitiveResponse, type CognitiveStreamChunk, type Events, type GenerateContentInput, type GenerateContentOutput, type Model$1 as Model, type ModelPreferences, ModelProvider, RemoteModelProvider };
|
package/dist/index.mjs
CHANGED
|
@@ -497,25 +497,25 @@ var require_backoff = __commonJS({
|
|
|
497
497
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
498
498
|
var options_1 = require_options();
|
|
499
499
|
var delay_factory_1 = require_delay_factory();
|
|
500
|
-
function
|
|
500
|
+
function backOff3(request, options) {
|
|
501
501
|
if (options === void 0) {
|
|
502
502
|
options = {};
|
|
503
503
|
}
|
|
504
504
|
return __awaiter(this, void 0, void 0, function() {
|
|
505
|
-
var sanitizedOptions,
|
|
505
|
+
var sanitizedOptions, backOff4;
|
|
506
506
|
return __generator(this, function(_a) {
|
|
507
507
|
switch (_a.label) {
|
|
508
508
|
case 0:
|
|
509
509
|
sanitizedOptions = options_1.getSanitizedOptions(options);
|
|
510
|
-
|
|
511
|
-
return [4,
|
|
510
|
+
backOff4 = new BackOff(request, sanitizedOptions);
|
|
511
|
+
return [4, backOff4.execute()];
|
|
512
512
|
case 1:
|
|
513
513
|
return [2, _a.sent()];
|
|
514
514
|
}
|
|
515
515
|
});
|
|
516
516
|
});
|
|
517
517
|
}
|
|
518
|
-
exports.backOff =
|
|
518
|
+
exports.backOff = backOff3;
|
|
519
519
|
var BackOff = (
|
|
520
520
|
/** @class */
|
|
521
521
|
function() {
|
|
@@ -591,7 +591,7 @@ var require_backoff = __commonJS({
|
|
|
591
591
|
});
|
|
592
592
|
|
|
593
593
|
// src/client.ts
|
|
594
|
-
var
|
|
594
|
+
var import_exponential_backoff2 = __toESM(require_backoff());
|
|
595
595
|
|
|
596
596
|
// ../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
597
597
|
var createNanoEvents = () => ({
|
|
@@ -650,6 +650,159 @@ var getExtendedClient = (_client) => {
|
|
|
650
650
|
};
|
|
651
651
|
};
|
|
652
652
|
|
|
653
|
+
// src/cognitive_beta/index.ts
|
|
654
|
+
var import_exponential_backoff = __toESM(require_backoff());
|
|
655
|
+
import axios from "axios";
|
|
656
|
+
var isBrowser = () => typeof window !== "undefined" && typeof window.fetch === "function";
|
|
657
|
+
var CognitiveBeta = class {
|
|
658
|
+
_axiosClient;
|
|
659
|
+
_config;
|
|
660
|
+
constructor(props) {
|
|
661
|
+
this._config = {
|
|
662
|
+
baseUrl: props.baseUrl || "https://cognitive.botpress.cloud",
|
|
663
|
+
timeout: props.timeout || 60001,
|
|
664
|
+
token: props.token || "",
|
|
665
|
+
botId: props.botId || "",
|
|
666
|
+
headers: props.headers || {}
|
|
667
|
+
};
|
|
668
|
+
this._axiosClient = axios.create({
|
|
669
|
+
headers: {
|
|
670
|
+
Authorization: `Bearer ${this._config.token}`,
|
|
671
|
+
"X-Bot-Id": this._config.botId,
|
|
672
|
+
...this._config.headers
|
|
673
|
+
},
|
|
674
|
+
baseURL: this._config.baseUrl
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
async generateText(input, options = {}) {
|
|
678
|
+
const signal = options.signal ?? AbortSignal.timeout(this._config.timeout);
|
|
679
|
+
const { data } = await this._withServerRetry(
|
|
680
|
+
() => this._axiosClient.post("/v1/generate-text", input, {
|
|
681
|
+
signal,
|
|
682
|
+
timeout: options.timeout ?? this._config.timeout
|
|
683
|
+
})
|
|
684
|
+
);
|
|
685
|
+
return data;
|
|
686
|
+
}
|
|
687
|
+
async listModels(input, options = {}) {
|
|
688
|
+
const signal = options.signal ?? AbortSignal.timeout(this._config.timeout);
|
|
689
|
+
const { data } = await this._withServerRetry(
|
|
690
|
+
() => this._axiosClient.post("/v1/models", input, {
|
|
691
|
+
signal,
|
|
692
|
+
timeout: options.timeout ?? this._config.timeout
|
|
693
|
+
})
|
|
694
|
+
);
|
|
695
|
+
return data;
|
|
696
|
+
}
|
|
697
|
+
async *generateTextStream(request, options = {}) {
|
|
698
|
+
const signal = options.signal ?? AbortSignal.timeout(this._config.timeout);
|
|
699
|
+
if (isBrowser()) {
|
|
700
|
+
const res2 = await fetch(`${this._config.baseUrl}/v1/generate-text-stream`, {
|
|
701
|
+
method: "POST",
|
|
702
|
+
headers: {
|
|
703
|
+
Authorization: `Bearer ${this._config.token}`,
|
|
704
|
+
"X-Bot-Id": this._config.botId,
|
|
705
|
+
"Content-Type": "application/json"
|
|
706
|
+
},
|
|
707
|
+
body: JSON.stringify({ ...request, stream: true }),
|
|
708
|
+
signal
|
|
709
|
+
});
|
|
710
|
+
if (!res2.ok) {
|
|
711
|
+
const text = await res2.text().catch(() => "");
|
|
712
|
+
const err = new Error(`HTTP ${res2.status}: ${text || res2.statusText}`);
|
|
713
|
+
err.response = { status: res2.status, data: text };
|
|
714
|
+
throw err;
|
|
715
|
+
}
|
|
716
|
+
const body = res2.body;
|
|
717
|
+
if (!body) {
|
|
718
|
+
throw new Error("No response body received for streaming request");
|
|
719
|
+
}
|
|
720
|
+
const reader = body.getReader();
|
|
721
|
+
const iterable = async function* () {
|
|
722
|
+
for (; ; ) {
|
|
723
|
+
const { value, done } = await reader.read();
|
|
724
|
+
if (done) {
|
|
725
|
+
break;
|
|
726
|
+
}
|
|
727
|
+
if (value) {
|
|
728
|
+
yield value;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}();
|
|
732
|
+
for await (const obj of this._ndjson(iterable)) {
|
|
733
|
+
yield obj;
|
|
734
|
+
}
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
const res = await this._withServerRetry(
|
|
738
|
+
() => this._axiosClient.post(
|
|
739
|
+
"/v1/generate-text-stream",
|
|
740
|
+
{ ...request, stream: true },
|
|
741
|
+
{
|
|
742
|
+
responseType: "stream",
|
|
743
|
+
signal,
|
|
744
|
+
timeout: options.timeout ?? this._config.timeout
|
|
745
|
+
}
|
|
746
|
+
)
|
|
747
|
+
);
|
|
748
|
+
const nodeStream = res.data;
|
|
749
|
+
if (!nodeStream) {
|
|
750
|
+
throw new Error("No response body received for streaming request");
|
|
751
|
+
}
|
|
752
|
+
for await (const obj of this._ndjson(nodeStream)) {
|
|
753
|
+
yield obj;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
async *_ndjson(stream) {
|
|
757
|
+
const decoder = new TextDecoder("utf-8");
|
|
758
|
+
let buffer = "";
|
|
759
|
+
for await (const chunk of stream) {
|
|
760
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
761
|
+
for (; ; ) {
|
|
762
|
+
const i = buffer.indexOf("\n");
|
|
763
|
+
if (i < 0) {
|
|
764
|
+
break;
|
|
765
|
+
}
|
|
766
|
+
const line = buffer.slice(0, i).replace(/\r$/, "");
|
|
767
|
+
buffer = buffer.slice(i + 1);
|
|
768
|
+
if (!line) {
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
yield JSON.parse(line);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
buffer += decoder.decode();
|
|
775
|
+
const tail = buffer.trim();
|
|
776
|
+
if (tail) {
|
|
777
|
+
yield JSON.parse(tail);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
_isRetryableServerError(error) {
|
|
781
|
+
if (axios.isAxiosError(error)) {
|
|
782
|
+
if (!error.response) {
|
|
783
|
+
return true;
|
|
784
|
+
}
|
|
785
|
+
const status = error.response?.status;
|
|
786
|
+
if (status && [502, 503, 504].includes(status)) {
|
|
787
|
+
return true;
|
|
788
|
+
}
|
|
789
|
+
if (error.code && ["ECONNABORTED", "ECONNRESET", "ETIMEDOUT", "EAI_AGAIN", "ENOTFOUND", "EPIPE"].includes(error.code)) {
|
|
790
|
+
return true;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
return false;
|
|
794
|
+
}
|
|
795
|
+
async _withServerRetry(fn) {
|
|
796
|
+
return (0, import_exponential_backoff.backOff)(fn, {
|
|
797
|
+
numOfAttempts: 3,
|
|
798
|
+
startingDelay: 300,
|
|
799
|
+
timeMultiple: 2,
|
|
800
|
+
jitter: "full",
|
|
801
|
+
retry: (e) => this._isRetryableServerError(e)
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
|
|
653
806
|
// src/errors.ts
|
|
654
807
|
var getActionFromError = (error) => {
|
|
655
808
|
if (!isBotpressError(error)) {
|
|
@@ -902,12 +1055,14 @@ var Cognitive = class {
|
|
|
902
1055
|
_preferences = null;
|
|
903
1056
|
_provider;
|
|
904
1057
|
_downtimes = [];
|
|
1058
|
+
_useBeta = false;
|
|
905
1059
|
_events = createNanoEvents();
|
|
906
1060
|
constructor(props) {
|
|
907
1061
|
this._client = getExtendedClient(props.client);
|
|
908
1062
|
this._provider = props.provider ?? new RemoteModelProvider(props.client);
|
|
909
1063
|
this._timeoutMs = props.timeout ?? this._timeoutMs;
|
|
910
1064
|
this._maxRetries = props.maxRetries ?? this._maxRetries;
|
|
1065
|
+
this._useBeta = props.__experimental_beta ?? false;
|
|
911
1066
|
}
|
|
912
1067
|
get client() {
|
|
913
1068
|
return this._client;
|
|
@@ -994,6 +1149,54 @@ var Cognitive = class {
|
|
|
994
1149
|
return def;
|
|
995
1150
|
}
|
|
996
1151
|
async generateContent(input) {
|
|
1152
|
+
if (!this._useBeta) {
|
|
1153
|
+
return this._generateContent(input);
|
|
1154
|
+
}
|
|
1155
|
+
const betaClient = new CognitiveBeta({
|
|
1156
|
+
headers: this._client.config.headers,
|
|
1157
|
+
baseUrl: this._client.config.apiUrl.includes(".cloud") ? "https://cognitive.botpress.cloud" : "https://cognitive.botpress.dev"
|
|
1158
|
+
});
|
|
1159
|
+
const response = await betaClient.generateText(input);
|
|
1160
|
+
return {
|
|
1161
|
+
output: {
|
|
1162
|
+
id: "beta-output",
|
|
1163
|
+
provider: response.metadata.provider,
|
|
1164
|
+
model: response.metadata.model,
|
|
1165
|
+
choices: [
|
|
1166
|
+
{
|
|
1167
|
+
type: "text",
|
|
1168
|
+
content: response.output,
|
|
1169
|
+
role: "assistant",
|
|
1170
|
+
index: 0,
|
|
1171
|
+
stopReason: response.metadata.stopReason
|
|
1172
|
+
}
|
|
1173
|
+
],
|
|
1174
|
+
usage: {
|
|
1175
|
+
inputTokens: response.metadata.usage.inputTokens,
|
|
1176
|
+
inputCost: 0,
|
|
1177
|
+
outputTokens: response.metadata.usage.outputTokens,
|
|
1178
|
+
outputCost: response.metadata.cost ?? 0
|
|
1179
|
+
},
|
|
1180
|
+
botpress: {
|
|
1181
|
+
cost: response.metadata.cost ?? 0
|
|
1182
|
+
}
|
|
1183
|
+
},
|
|
1184
|
+
meta: {
|
|
1185
|
+
cached: response.metadata.cached,
|
|
1186
|
+
model: { integration: response.metadata.provider, model: response.metadata.model },
|
|
1187
|
+
latency: response.metadata.latency,
|
|
1188
|
+
cost: {
|
|
1189
|
+
input: 0,
|
|
1190
|
+
output: response.metadata.cost || 0
|
|
1191
|
+
},
|
|
1192
|
+
tokens: {
|
|
1193
|
+
input: response.metadata.usage.inputTokens,
|
|
1194
|
+
output: response.metadata.usage.outputTokens
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
async _generateContent(input) {
|
|
997
1200
|
const start = Date.now();
|
|
998
1201
|
const signal = input.signal ?? AbortSignal.timeout(this._timeoutMs);
|
|
999
1202
|
const client = this._client.abortable(signal);
|
|
@@ -1001,7 +1204,7 @@ var Cognitive = class {
|
|
|
1001
1204
|
let integration;
|
|
1002
1205
|
let model;
|
|
1003
1206
|
this._events.emit("request", props);
|
|
1004
|
-
const { output, meta } = await (0,
|
|
1207
|
+
const { output, meta } = await (0, import_exponential_backoff2.backOff)(
|
|
1005
1208
|
async () => {
|
|
1006
1209
|
const selection = await this._selectModel(input.model ?? "best");
|
|
1007
1210
|
integration = selection.integration;
|
|
@@ -1066,6 +1269,7 @@ var Cognitive = class {
|
|
|
1066
1269
|
};
|
|
1067
1270
|
export {
|
|
1068
1271
|
Cognitive,
|
|
1272
|
+
CognitiveBeta,
|
|
1069
1273
|
ModelProvider,
|
|
1070
1274
|
RemoteModelProvider
|
|
1071
1275
|
};
|
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/options.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/full/full.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/no/no.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/jitter.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.base.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/skip-first/skip-first.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/always/always.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/backoff.ts", "../src/client.ts", "../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js", "../src/bp-client.ts", "../src/errors.ts", "../src/interceptors.ts", "../src/models.ts"],
|
|
4
|
-
"sourcesContent": [null, null, null, null, null, null, null, null, null, "import { backOff } from 'exponential-backoff'\nimport { createNanoEvents, Unsubscribe } from 'nanoevents'\n\nimport { ExtendedClient, getExtendedClient } from './bp-client'\nimport { getActionFromError } from './errors'\nimport { InterceptorManager } from './interceptors'\nimport {\n DOWNTIME_THRESHOLD_MINUTES,\n getBestModels,\n getFastModels,\n Model,\n ModelPreferences,\n ModelProvider,\n ModelRef,\n pickModel,\n RemoteModelProvider,\n} from './models'\nimport { GenerateContentOutput } from './schemas.gen'\nimport { CognitiveProps, Events, InputProps, Request, Response } from './types'\n\nexport class Cognitive {\n public ['$$IS_COGNITIVE'] = true\n\n public static isCognitiveClient(obj: any): obj is Cognitive {\n return obj?.$$IS_COGNITIVE === true\n }\n\n public interceptors = {\n request: new InterceptorManager<Request>(),\n response: new InterceptorManager<Response>(),\n }\n\n protected _models: Model[] = []\n protected _timeoutMs: number = 5 * 60 * 1000 // Default timeout of 5 minutes\n protected _maxRetries: number = 5 // Default max retries\n protected _client: ExtendedClient\n protected _preferences: ModelPreferences | null = null\n protected _provider: ModelProvider\n protected _downtimes: ModelPreferences['downtimes'] = []\n\n private _events = createNanoEvents<Events>()\n\n public constructor(props: CognitiveProps) {\n this._client = getExtendedClient(props.client)\n this._provider = props.provider ?? new RemoteModelProvider(props.client)\n this._timeoutMs = props.timeout ?? this._timeoutMs\n this._maxRetries = props.maxRetries ?? this._maxRetries\n }\n\n public get client(): ExtendedClient {\n return this._client\n }\n\n public clone(): Cognitive {\n const copy = new Cognitive({\n client: this._client.clone(),\n provider: this._provider,\n timeout: this._timeoutMs,\n maxRetries: this._maxRetries,\n })\n\n copy._models = [...this._models]\n copy._preferences = this._preferences ? { ...this._preferences } : null\n copy._downtimes = [...this._downtimes]\n copy.interceptors.request = this.interceptors.request\n copy.interceptors.response = this.interceptors.response\n\n return copy\n }\n\n public on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe {\n return this._events.on(event, cb)\n }\n\n public async fetchInstalledModels(): Promise<Model[]> {\n if (!this._models.length) {\n this._models = await this._provider.fetchInstalledModels()\n }\n\n return this._models\n }\n\n public async fetchPreferences(): Promise<ModelPreferences> {\n if (this._preferences) {\n return this._preferences\n }\n\n this._preferences = await this._provider.fetchModelPreferences()\n\n if (this._preferences) {\n return this._preferences\n }\n\n const models = await this.fetchInstalledModels()\n\n this._preferences = {\n best: getBestModels(models).map((m) => m.ref),\n fast: getFastModels(models).map((m) => m.ref),\n downtimes: [],\n }\n\n await this._provider.saveModelPreferences(this._preferences)\n\n return this._preferences\n }\n\n public async setPreferences(preferences: ModelPreferences, save: boolean = false): Promise<void> {\n this._preferences = preferences\n\n if (save) {\n await this._provider.saveModelPreferences(preferences)\n }\n }\n\n private _cleanupOldDowntimes(): void {\n const now = Date.now()\n const thresholdMs = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n this._preferences!.downtimes = this._preferences!.downtimes.filter((downtime) => {\n const downtimeStart = new Date(downtime.startedAt).getTime()\n return now - downtimeStart <= thresholdMs\n })\n }\n\n private async _selectModel(ref: string): Promise<{ integration: string; model: string }> {\n const parseRef = (ref: string) => {\n const parts = ref.split(':')\n return { integration: parts[0]!, model: parts.slice(1).join(':') }\n }\n\n const preferences = await this.fetchPreferences()\n\n preferences.best ??= []\n preferences.fast ??= []\n preferences.downtimes ??= []\n\n const downtimes = [...preferences.downtimes, ...(this._downtimes ?? [])]\n\n if (ref === 'best') {\n return parseRef(pickModel(preferences.best, downtimes))\n }\n\n if (ref === 'fast') {\n return parseRef(pickModel(preferences.fast, downtimes))\n }\n\n return parseRef(pickModel([ref as ModelRef, ...preferences.best, ...preferences.fast], downtimes))\n }\n\n public async getModelDetails(model: string) {\n await this.fetchInstalledModels()\n const { integration, model: modelName } = await this._selectModel(model)\n const def = this._models.find((m) => m.integration === integration && (m.name === modelName || m.id === modelName))\n if (!def) {\n throw new Error(`Model ${modelName} not found`)\n }\n\n return def\n }\n\n public async generateContent(input: InputProps): Promise<Response> {\n const start = Date.now()\n\n const signal = input.signal ?? AbortSignal.timeout(this._timeoutMs)\n\n const client = this._client.abortable(signal)\n\n let props: Request = { input }\n let integration: string\n let model: string\n\n this._events.emit('request', props)\n\n const { output, meta } = await backOff<{\n output: GenerateContentOutput\n meta: any\n }>(\n async () => {\n const selection = await this._selectModel(input.model ?? 'best')\n\n integration = selection.integration\n model = selection.model\n\n props = await this.interceptors.request.run({ input }, signal)\n\n return client.callAction({\n type: `${integration}:generateContent`,\n input: {\n ...props.input,\n model: { id: model },\n },\n }) as Promise<{ output: GenerateContentOutput; meta: any }>\n },\n {\n retry: async (err, _attempt) => {\n if (signal?.aborted) {\n // We don't want to retry if the request was aborted\n this._events.emit('aborted', props, err)\n signal.throwIfAborted()\n return false\n }\n\n if (_attempt > this._maxRetries) {\n this._events.emit('error', props, err)\n return false\n }\n\n const action = getActionFromError(err)\n\n if (action === 'abort') {\n this._events.emit('error', props, err)\n return false\n }\n\n if (action === 'fallback') {\n // We don't want to retry if the request was already retried with a fallback model\n this._downtimes.push({\n ref: `${integration!}:${model!}`,\n startedAt: new Date().toISOString(),\n reason: 'Model is down',\n })\n\n this._cleanupOldDowntimes()\n\n await this._provider.saveModelPreferences({\n ...(this._preferences ?? { best: [], downtimes: [], fast: [] }),\n downtimes: [...(this._preferences!.downtimes ?? []), ...(this._downtimes ?? [])],\n })\n\n this._events.emit('fallback', props, err)\n return true\n }\n\n this._events.emit('retry', props, err)\n return true\n },\n }\n )\n\n const response = {\n output,\n meta: {\n cached: meta.cached ?? false,\n model: { integration: integration!, model: model! },\n latency: Date.now() - start,\n cost: { input: output.usage.inputCost, output: output.usage.outputCost },\n tokens: { input: output.usage.inputTokens, output: output.usage.outputTokens },\n },\n } satisfies Response\n\n this._events.emit('response', props, response)\n\n return this.interceptors.response.run(response, signal)\n }\n}\n", "export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n", "import { type Client } from '@botpress/client'\nimport { type AxiosInstance } from 'axios'\nimport { BotpressClientLike } from './types'\n\n/** @internal */\nexport type ExtendedClient = Client & {\n botId: string\n axios: AxiosInstance\n clone: () => ExtendedClient\n abortable: (signal: AbortSignal) => ExtendedClient\n}\n\ntype InternalClientType = BotpressClientLike & {\n _client?: InternalClientType\n config: {\n headers: Record<string, string>\n }\n}\n\nexport const getExtendedClient = (_client: unknown): ExtendedClient => {\n const client = _client as InternalClientType\n\n if (!client || client === null || typeof client !== 'object') {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n if (typeof client._client === 'object' && !!client._client) {\n try {\n return getExtendedClient(client._client)\n } catch {}\n }\n\n if (\n typeof client.constructor !== 'function' ||\n typeof client.callAction !== 'function' ||\n !client.config ||\n typeof client.config !== 'object' ||\n !client.config.headers\n ) {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n const botId = client.config.headers['x-bot-id'] as string\n\n if (!botId?.length) {\n throw new Error('Client must be instanciated with Bot ID')\n }\n\n const clone = () => {\n const c = client as any\n if (c.clone && typeof c.clone === 'function') {\n return getExtendedClient(c.clone())\n }\n return getExtendedClient(new c.constructor(c.config))\n }\n\n return {\n ...client,\n botId,\n axios: (client as any).axiosInstance as AxiosInstance,\n clone,\n abortable: (signal: AbortSignal) => {\n const abortable = clone()\n const instance = abortable.axios\n instance.defaults.signal = signal\n return abortable\n },\n } as ExtendedClient\n}\n", "import { type ErrorType } from '@botpress/client'\n\nexport type BotpressError = {\n isApiError: boolean\n code: number\n description: string\n type: ErrorType\n subtype?: string\n error?: unknown\n metadata?: unknown\n message?: string\n id: string\n}\n\ntype Action = 'fallback' | 'retry' | 'abort'\n\nexport const getActionFromError = (error: any): Action => {\n if (!isBotpressError(error)) {\n return 'retry'\n }\n\n if (error.type === 'InvalidDataFormat') {\n if (error.message?.includes('data/model/id')) {\n // Invalid Model ID, so we want to try another model\n return 'fallback'\n }\n\n // Usually means the request was malformed\n return 'abort'\n }\n\n if (\n error.type === 'QuotaExceeded' ||\n error.type === 'RateLimited' ||\n error.type === 'Unknown' ||\n error.type === 'LimitExceeded'\n ) {\n // These errors are usually temporary, so we want to retry\n return 'retry'\n }\n\n const subtype = (error.metadata as any)?.subtype\n if (subtype === 'UPSTREAM_PROVIDER_FAILED') {\n // The model is degraded, so we want to try another model\n return 'fallback'\n }\n\n if (error.type === 'Internal') {\n // This is an internal error, probably a lambda timeout\n return 'retry'\n }\n\n return 'abort'\n}\n\nexport const isNotFoundError = (error: any): boolean => isBotpressError(error) && error.type === 'ResourceNotFound'\n\nexport const isForbiddenOrUnauthorizedError = (error: any): boolean =>\n isBotpressError(error) && (error.type === 'Forbidden' || error.type === 'Unauthorized')\n\nexport const isBotpressError = (error: any): error is BotpressError =>\n typeof error === 'object' &&\n error !== null &&\n 'isApiError' in error &&\n 'code' in error &&\n 'type' in error &&\n 'id' in error\n", "export type Callback<T> = (error: any | null, value: T) => void\nexport type Interceptor<T> = (error: any | null, value: T, next: Callback<T>, done: Callback<T>) => Promise<void> | void\n\nexport class InterceptorManager<T> {\n private _interceptors: Interceptor<T>[] = []\n\n public use(interceptor: Interceptor<T>) {\n this._interceptors.push(interceptor)\n return () => this.remove(interceptor)\n }\n\n public remove(interceptor: Interceptor<T>) {\n this._interceptors = this._interceptors.filter((i) => i !== interceptor)\n }\n\n public async run(value: T, signal: AbortSignal): Promise<T> {\n let error: any | null = null\n let result: T = value\n let done = false\n\n for (const interceptor of this._interceptors) {\n if (done) {\n break\n }\n\n if (signal.aborted) {\n throw signal.reason\n }\n\n await new Promise<void>((resolve) => {\n void interceptor(\n error,\n result,\n (err, val) => {\n error = err\n result = val\n resolve()\n },\n (err, val) => {\n error = err\n result = val\n done = true\n resolve()\n }\n )\n })\n }\n\n if (error) {\n throw error\n }\n\n return result\n }\n}\n", "import { ExtendedClient, getExtendedClient } from './bp-client'\nimport { isForbiddenOrUnauthorizedError, isNotFoundError } from './errors'\nimport { Model as RawModel } from './schemas.gen'\nimport { BotpressClientLike } from './types'\n\nexport const DOWNTIME_THRESHOLD_MINUTES = 5\nconst PREFERENCES_FILE_SUFFIX = 'models.config.json'\n\nexport const DEFAULT_INTEGRATIONS = ['google-ai', 'anthropic', 'openai', 'cerebras', 'fireworks-ai', 'groq']\n\n// Biases for vendors and models\nconst VendorPreferences = ['google-ai', 'anthropic', 'openai']\nconst BestModelPreferences = ['4.1', '4o', '3-5-sonnet', 'gemini-1.5-pro']\nconst FastModelPreferences = ['gemini-1.5-flash', '4.1-mini', '4.1-nano', '4o-mini', 'flash', 'haiku']\n\nconst InputPricePenalty = 3 // $3 per 1M tokens\nconst OutputPricePenalty = 10 // $10 per 1M tokens\nconst LowTokensPenalty = 128_000 // 128k tokens\n\nexport type Model = RawModel & {\n ref: ModelRef\n integration: string\n}\n\nexport type ModelRef = `${string}:${string}`\n\nexport type ModelPreferences = {\n best: ModelRef[]\n fast: ModelRef[]\n downtimes: Array<{ ref: ModelRef; startedAt: string; reason: string }>\n}\n\nconst isRecommended = (model: Model) => model.tags.includes('recommended')\nconst isDeprecated = (model: Model) => model.tags.includes('deprecated')\nconst isLowCost = (model: Model) => model.tags.includes('low-cost')\nconst hasVisionSupport = (model: Model) => model.tags.includes('vision')\nconst isGeneralPurpose = (model: Model) => model.tags.includes('general-purpose')\n\nconst scoreModel = (model: Model, type: 'best' | 'fast', boosts: Record<ModelRef, number> = {}) => {\n let score: number = 0\n\n const scores: Array<[string, boolean, number]> = [\n ['input price penalty', model.input.costPer1MTokens > InputPricePenalty, -1],\n ['output price penalty', model.output.costPer1MTokens > OutputPricePenalty, -1],\n ['low tokens penalty', (model.input.maxTokens ?? 0 + model.output.maxTokens ?? 0) < LowTokensPenalty, -1],\n ['recommended', isRecommended(model), 2],\n ['deprecated', isDeprecated(model), -2],\n ['vision support', hasVisionSupport(model), 1],\n ['general purpose', isGeneralPurpose(model), 1],\n ['vendor preference', VendorPreferences.includes(model.integration), 1],\n ['best model preference', type === 'best' && BestModelPreferences.some((x) => model.id.includes(x)), 1],\n ['fast model preference penalty', type === 'best' && FastModelPreferences.some((x) => model.id.includes(x)), -2],\n ['fast model preference', type === 'fast' && FastModelPreferences.some((x) => model.id.includes(x)), 2],\n ['low cost', type === 'fast' && isLowCost(model), 1],\n ]\n\n for (const rule in boosts) {\n if (model.ref.includes(rule)) {\n scores.push([`boost (${rule})`, true, Number(boosts[rule as ModelRef]) ?? 0] as const)\n }\n }\n\n for (const [, condition, value] of scores) {\n if (condition) {\n score += value\n }\n }\n\n return score\n}\n\nexport const getBestModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'best', boosts) - scoreModel(a, 'best', boosts))\n\nexport const getFastModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'fast', boosts) - scoreModel(a, 'fast', boosts))\n\nexport const pickModel = (models: ModelRef[], downtimes: ModelPreferences['downtimes'] = []) => {\n const copy = [...models]\n const elasped = (date: string) => new Date().getTime() - new Date(date).getTime()\n const DOWNTIME_THRESHOLD = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n if (!copy.length) {\n throw new Error('At least one model is required')\n }\n\n while (copy.length) {\n const ref = copy.shift() as ModelRef\n const downtime = downtimes.find((o) => o.ref === ref && elasped(o.startedAt) < DOWNTIME_THRESHOLD)\n if (downtime) {\n continue\n } else {\n return ref\n }\n }\n\n throw new Error(`All models are down: ${models.join(', ')}`)\n}\n\nexport abstract class ModelProvider {\n public abstract fetchInstalledModels(): Promise<Model[]>\n public abstract fetchModelPreferences(): Promise<ModelPreferences | null>\n public abstract saveModelPreferences(preferences: ModelPreferences): Promise<void>\n public abstract deleteModelPreferences(): Promise<void>\n}\n\nexport class RemoteModelProvider extends ModelProvider {\n private _client: ExtendedClient\n\n public constructor(client: BotpressClientLike) {\n super()\n this._client = getExtendedClient(client)\n }\n\n private async _fetchInstalledIntegrationNames() {\n try {\n const { bot } = await this._client.getBot({ id: this._client.botId })\n const integrations = Object.values(bot.integrations).filter((x) => x.status === 'registered')\n return integrations.map((x) => x.name)\n } catch (err) {\n if (isForbiddenOrUnauthorizedError(err)) {\n // This happens when the bot (with a BAK token) tries to access the .getBot endpoint\n return DEFAULT_INTEGRATIONS\n }\n\n throw err\n }\n }\n\n public async fetchInstalledModels() {\n const integrationNames = await this._fetchInstalledIntegrationNames()\n const models: Model[] = []\n\n await Promise.allSettled(\n integrationNames.map(async (integration) => {\n const { output } = await this._client.callAction({\n type: `${integration}:listLanguageModels`,\n input: {},\n })\n\n if (!output?.models?.length) {\n return\n }\n\n for (const model of output.models as RawModel[]) {\n if (model.name && model.id && model.input && model.tags) {\n models.push({\n ref: `${integration}:${model.id}`,\n integration,\n id: model.id,\n name: model.name,\n description: model.description,\n input: model.input,\n output: model.output,\n tags: model.tags,\n })\n }\n }\n })\n )\n\n return models\n }\n\n public async fetchModelPreferences(): Promise<ModelPreferences | null> {\n try {\n const { file } = await this._client.getFile({ id: this._preferenceFileKey })\n\n if (globalThis.fetch !== undefined) {\n const response = await fetch(file.url)\n return (await response.json()) as ModelPreferences\n } else {\n const { data } = await this._client.axios.get(file.url, {\n // we piggy-back axios to avoid adding a new dependency\n // unset all headers to avoid S3 pre-signed signature mismatch\n headers: Object.keys(this._client.config.headers).reduce(\n (acc, key) => {\n acc[key] = undefined\n return acc\n },\n {} as Record<string, undefined>\n ),\n })\n return data as ModelPreferences\n }\n } catch (err) {\n if (isNotFoundError(err)) {\n return null\n }\n\n throw err\n }\n }\n\n public async saveModelPreferences(preferences: ModelPreferences) {\n await this._client.uploadFile({\n key: this._preferenceFileKey,\n content: JSON.stringify(preferences, null, 2),\n index: false,\n tags: {\n system: 'true',\n purpose: 'config',\n },\n })\n }\n\n public async deleteModelPreferences() {\n await this._client.deleteFile({ id: this._preferenceFileKey }).catch(() => {})\n }\n\n private get _preferenceFileKey() {\n return `bot->${this._client.botId}->${PREFERENCES_FILE_SUFFIX}`\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,QAAM,iBAAkC;MACtC,mBAAmB;MACnB,QAAQ;MACR,UAAU;MACV,eAAe;MACf,OAAO,WAAA;AAAM,eAAA;MAAA;MACb,eAAe;MACf,cAAc;;AAGhB,aAAgB,oBAAoB,SAAuB;AACzD,UAAM,YAAS,SAAA,SAAA,CAAA,GAAyB,cAAc,GAAK,OAAO;AAElE,UAAI,UAAU,gBAAgB,GAAG;AAC/B,kBAAU,gBAAgB;;AAG5B,aAAO;IACT;AARA,YAAA,sBAAA;;;;;;;;;ACxBA,aAAgB,WAAW,OAAa;AACpC,UAAM,gBAAgB,KAAK,OAAM,IAAK;AACtC,aAAO,KAAK,MAAM,aAAa;IACnC;AAHA,YAAA,aAAA;;;;;;;;;ACAA,aAAgB,SAAS,OAAa;AAClC,aAAO;IACX;AAFA,YAAA,WAAA;;;;;;;;;ACCA,QAAA,gBAAA;AACA,QAAA,cAAA;AAIA,aAAgB,cAAc,SAAwB;AACpD,cAAQ,QAAQ,QAAQ;QACtB,KAAK;AACH,iBAAO,cAAA;QAET,KAAK;QACL;AACE,iBAAO,YAAA;;IAEb;AATA,YAAA,gBAAA;;;;;;;;;ACJA,QAAA,mBAAA;AAEA,QAAA;;MAAA,WAAA;AAEE,iB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AAI,KAAK,gBAAgB,EAAE,MAAM,CAAC,GAAG,WAAW,CAAC,GAAG,MAAM,CAAC,EAAE;AAAA,cAC7D,WAAW,CAAC,GAAI,KAAK,aAAc,aAAa,CAAC,GAAI,GAAI,KAAK,cAAc,CAAC,CAAE;AAAA,YACjF,CAAC;AAED,iBAAK,QAAQ,KAAK,YAAY,OAAO,GAAG;AACxC,mBAAO;AAAA,UACT;AAEA,eAAK,QAAQ,KAAK,SAAS,OAAO,GAAG;AACrC,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WAAW;AAAA,MACf;AAAA,MACA,MAAM;AAAA,QACJ,QAAQ,KAAK,UAAU;AAAA,QACvB,OAAO,EAAE,aAA2B,MAAc;AAAA,QAClD,SAAS,KAAK,IAAI,IAAI;AAAA,QACtB,MAAM,EAAE,OAAO,OAAO,MAAM,WAAW,QAAQ,OAAO,MAAM,WAAW;AAAA,QACvE,QAAQ,EAAE,OAAO,OAAO,MAAM,aAAa,QAAQ,OAAO,MAAM,aAAa;AAAA,MAC/E;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,YAAY,OAAO,QAAQ;AAE7C,WAAO,KAAK,aAAa,SAAS,IAAI,UAAU,MAAM;AAAA,EACxD;AACF;",
|
|
6
|
-
"names": ["Delay", "SkipFirstDelay", "AlwaysDelay", "backOff", "BackOff", "ref"]
|
|
3
|
+
"sources": ["../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/options.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/full/full.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/no/no.jitter.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/jitter/jitter.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.base.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/skip-first/skip-first.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/always/always.delay.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/delay/delay.factory.ts", "../../../node_modules/.pnpm/exponential-backoff@3.1.1/node_modules/exponential-backoff/src/backoff.ts", "../src/client.ts", "../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js", "../src/bp-client.ts", "../src/cognitive_beta/index.ts", "../src/errors.ts", "../src/interceptors.ts", "../src/models.ts"],
|
|
4
|
+
"sourcesContent": [null, null, null, null, null, null, null, null, null, "import { backOff } from 'exponential-backoff'\nimport { createNanoEvents, Unsubscribe } from 'nanoevents'\n\nimport { ExtendedClient, getExtendedClient } from './bp-client'\nimport { CognitiveBeta } from './cognitive_beta'\nimport { getActionFromError } from './errors'\nimport { InterceptorManager } from './interceptors'\nimport {\n DOWNTIME_THRESHOLD_MINUTES,\n getBestModels,\n getFastModels,\n Model,\n ModelPreferences,\n ModelProvider,\n ModelRef,\n pickModel,\n RemoteModelProvider,\n} from './models'\nimport { GenerateContentOutput } from './schemas.gen'\nimport { CognitiveProps, Events, InputProps, Request, Response } from './types'\n\nexport class Cognitive {\n public ['$$IS_COGNITIVE'] = true\n\n public static isCognitiveClient(obj: any): obj is Cognitive {\n return obj?.$$IS_COGNITIVE === true\n }\n\n public interceptors = {\n request: new InterceptorManager<Request>(),\n response: new InterceptorManager<Response>(),\n }\n\n protected _models: Model[] = []\n protected _timeoutMs: number = 5 * 60 * 1000 // Default timeout of 5 minutes\n protected _maxRetries: number = 5 // Default max retries\n protected _client: ExtendedClient\n protected _preferences: ModelPreferences | null = null\n protected _provider: ModelProvider\n protected _downtimes: ModelPreferences['downtimes'] = []\n protected _useBeta: boolean = false\n\n private _events = createNanoEvents<Events>()\n\n public constructor(props: CognitiveProps) {\n this._client = getExtendedClient(props.client)\n this._provider = props.provider ?? new RemoteModelProvider(props.client)\n this._timeoutMs = props.timeout ?? this._timeoutMs\n this._maxRetries = props.maxRetries ?? this._maxRetries\n this._useBeta = props.__experimental_beta ?? false\n }\n\n public get client(): ExtendedClient {\n return this._client\n }\n\n public clone(): Cognitive {\n const copy = new Cognitive({\n client: this._client.clone(),\n provider: this._provider,\n timeout: this._timeoutMs,\n maxRetries: this._maxRetries,\n })\n\n copy._models = [...this._models]\n copy._preferences = this._preferences ? { ...this._preferences } : null\n copy._downtimes = [...this._downtimes]\n copy.interceptors.request = this.interceptors.request\n copy.interceptors.response = this.interceptors.response\n\n return copy\n }\n\n public on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe {\n return this._events.on(event, cb)\n }\n\n public async fetchInstalledModels(): Promise<Model[]> {\n if (!this._models.length) {\n this._models = await this._provider.fetchInstalledModels()\n }\n\n return this._models\n }\n\n public async fetchPreferences(): Promise<ModelPreferences> {\n if (this._preferences) {\n return this._preferences\n }\n\n this._preferences = await this._provider.fetchModelPreferences()\n\n if (this._preferences) {\n return this._preferences\n }\n\n const models = await this.fetchInstalledModels()\n\n this._preferences = {\n best: getBestModels(models).map((m) => m.ref),\n fast: getFastModels(models).map((m) => m.ref),\n downtimes: [],\n }\n\n await this._provider.saveModelPreferences(this._preferences)\n\n return this._preferences\n }\n\n public async setPreferences(preferences: ModelPreferences, save: boolean = false): Promise<void> {\n this._preferences = preferences\n\n if (save) {\n await this._provider.saveModelPreferences(preferences)\n }\n }\n\n private _cleanupOldDowntimes(): void {\n const now = Date.now()\n const thresholdMs = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n this._preferences!.downtimes = this._preferences!.downtimes.filter((downtime) => {\n const downtimeStart = new Date(downtime.startedAt).getTime()\n return now - downtimeStart <= thresholdMs\n })\n }\n\n private async _selectModel(ref: string): Promise<{ integration: string; model: string }> {\n const parseRef = (ref: string) => {\n const parts = ref.split(':')\n return { integration: parts[0]!, model: parts.slice(1).join(':') }\n }\n\n const preferences = await this.fetchPreferences()\n\n preferences.best ??= []\n preferences.fast ??= []\n preferences.downtimes ??= []\n\n const downtimes = [...preferences.downtimes, ...(this._downtimes ?? [])]\n\n if (ref === 'best') {\n return parseRef(pickModel(preferences.best, downtimes))\n }\n\n if (ref === 'fast') {\n return parseRef(pickModel(preferences.fast, downtimes))\n }\n\n return parseRef(pickModel([ref as ModelRef, ...preferences.best, ...preferences.fast], downtimes))\n }\n\n public async getModelDetails(model: string) {\n await this.fetchInstalledModels()\n const { integration, model: modelName } = await this._selectModel(model)\n const def = this._models.find((m) => m.integration === integration && (m.name === modelName || m.id === modelName))\n if (!def) {\n throw new Error(`Model ${modelName} not found`)\n }\n\n return def\n }\n\n public async generateContent(input: InputProps): Promise<Response> {\n if (!this._useBeta) {\n return this._generateContent(input)\n }\n\n const betaClient = new CognitiveBeta({\n headers: this._client.config.headers as Record<string, string>,\n baseUrl: this._client.config.apiUrl.includes('.cloud')\n ? 'https://cognitive.botpress.cloud'\n : 'https://cognitive.botpress.dev',\n })\n\n const response = await betaClient.generateText(input as any)\n return {\n output: {\n id: 'beta-output',\n provider: response.metadata.provider,\n model: response.metadata.model!,\n choices: [\n {\n type: 'text',\n content: response.output,\n role: 'assistant',\n index: 0,\n stopReason: response.metadata.stopReason! as any,\n },\n ],\n usage: {\n inputTokens: response.metadata.usage.inputTokens,\n inputCost: 0,\n outputTokens: response.metadata.usage.outputTokens,\n outputCost: response.metadata.cost ?? 0,\n },\n botpress: {\n cost: response.metadata.cost ?? 0,\n },\n },\n meta: {\n cached: response.metadata.cached,\n model: { integration: response.metadata.provider, model: response.metadata.model! },\n latency: response.metadata.latency!,\n cost: {\n input: 0,\n output: response.metadata.cost || 0,\n },\n tokens: {\n input: response.metadata.usage.inputTokens,\n output: response.metadata.usage.outputTokens,\n },\n },\n }\n }\n\n private async _generateContent(input: InputProps): Promise<Response> {\n const start = Date.now()\n\n const signal = input.signal ?? AbortSignal.timeout(this._timeoutMs)\n\n const client = this._client.abortable(signal)\n\n let props: Request = { input }\n let integration: string\n let model: string\n\n this._events.emit('request', props)\n\n const { output, meta } = await backOff<{\n output: GenerateContentOutput\n meta: any\n }>(\n async () => {\n const selection = await this._selectModel(input.model ?? 'best')\n\n integration = selection.integration\n model = selection.model\n\n props = await this.interceptors.request.run({ input }, signal)\n\n return client.callAction({\n type: `${integration}:generateContent`,\n input: {\n ...props.input,\n model: { id: model },\n },\n }) as Promise<{ output: GenerateContentOutput; meta: any }>\n },\n {\n retry: async (err, _attempt) => {\n if (signal?.aborted) {\n // We don't want to retry if the request was aborted\n this._events.emit('aborted', props, err)\n signal.throwIfAborted()\n return false\n }\n\n if (_attempt > this._maxRetries) {\n this._events.emit('error', props, err)\n return false\n }\n\n const action = getActionFromError(err)\n\n if (action === 'abort') {\n this._events.emit('error', props, err)\n return false\n }\n\n if (action === 'fallback') {\n // We don't want to retry if the request was already retried with a fallback model\n this._downtimes.push({\n ref: `${integration!}:${model!}`,\n startedAt: new Date().toISOString(),\n reason: 'Model is down',\n })\n\n this._cleanupOldDowntimes()\n\n await this._provider.saveModelPreferences({\n ...(this._preferences ?? { best: [], downtimes: [], fast: [] }),\n downtimes: [...(this._preferences!.downtimes ?? []), ...(this._downtimes ?? [])],\n })\n\n this._events.emit('fallback', props, err)\n return true\n }\n\n this._events.emit('retry', props, err)\n return true\n },\n }\n )\n\n const response = {\n output,\n meta: {\n cached: meta.cached ?? false,\n model: { integration: integration!, model: model! },\n latency: Date.now() - start,\n cost: { input: output.usage.inputCost, output: output.usage.outputCost },\n tokens: { input: output.usage.inputTokens, output: output.usage.outputTokens },\n },\n } satisfies Response\n\n this._events.emit('response', props, response)\n\n return this.interceptors.response.run(response, signal)\n }\n}\n", "export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n", "import { type Client } from '@botpress/client'\nimport { type AxiosInstance } from 'axios'\nimport { BotpressClientLike } from './types'\n\n/** @internal */\nexport type ExtendedClient = Client & {\n botId: string\n axios: AxiosInstance\n clone: () => ExtendedClient\n abortable: (signal: AbortSignal) => ExtendedClient\n}\n\ntype InternalClientType = BotpressClientLike & {\n _client?: InternalClientType\n config: {\n headers: Record<string, string>\n }\n}\n\nexport const getExtendedClient = (_client: unknown): ExtendedClient => {\n const client = _client as InternalClientType\n\n if (!client || client === null || typeof client !== 'object') {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n if (typeof client._client === 'object' && !!client._client) {\n try {\n return getExtendedClient(client._client)\n } catch {}\n }\n\n if (\n typeof client.constructor !== 'function' ||\n typeof client.callAction !== 'function' ||\n !client.config ||\n typeof client.config !== 'object' ||\n !client.config.headers\n ) {\n throw new Error('Client must be a valid instance of a Botpress client (@botpress/client)')\n }\n\n const botId = client.config.headers['x-bot-id'] as string\n\n if (!botId?.length) {\n throw new Error('Client must be instanciated with Bot ID')\n }\n\n const clone = () => {\n const c = client as any\n if (c.clone && typeof c.clone === 'function') {\n return getExtendedClient(c.clone())\n }\n return getExtendedClient(new c.constructor(c.config))\n }\n\n return {\n ...client,\n botId,\n axios: (client as any).axiosInstance as AxiosInstance,\n clone,\n abortable: (signal: AbortSignal) => {\n const abortable = clone()\n const instance = abortable.axios\n instance.defaults.signal = signal\n return abortable\n },\n } as ExtendedClient\n}\n", "import axios, { AxiosInstance } from 'axios'\nimport { backOff } from 'exponential-backoff'\nimport { CognitiveRequest, CognitiveResponse, CognitiveStreamChunk, Model } from './models'\n\nexport { CognitiveRequest, CognitiveResponse, CognitiveStreamChunk }\n\ntype ClientProps = {\n baseUrl?: string\n timeout?: number\n botId?: string\n token?: string\n headers?: Record<string, string>\n}\n\ntype RequestOptions = {\n signal?: AbortSignal\n timeout?: number\n}\n\nconst isBrowser = () => typeof window !== 'undefined' && typeof window.fetch === 'function'\n\nexport class CognitiveBeta {\n private _axiosClient: AxiosInstance\n private readonly _config: Required<ClientProps>\n\n public constructor(props: ClientProps) {\n this._config = {\n baseUrl: props.baseUrl || 'https://cognitive.botpress.cloud',\n timeout: props.timeout || 60_001,\n token: props.token || '',\n botId: props.botId || '',\n headers: props.headers || {},\n }\n\n this._axiosClient = axios.create({\n headers: {\n Authorization: `Bearer ${this._config.token}`,\n 'X-Bot-Id': this._config.botId,\n ...this._config.headers,\n },\n baseURL: this._config.baseUrl,\n })\n }\n\n public async generateText(input: CognitiveRequest, options: RequestOptions = {}) {\n const signal = options.signal ?? AbortSignal.timeout(this._config.timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<CognitiveResponse>('/v1/generate-text', input, {\n signal,\n timeout: options.timeout ?? this._config.timeout,\n })\n )\n\n return data\n }\n\n public async listModels(input: void, options: RequestOptions = {}) {\n const signal = options.signal ?? AbortSignal.timeout(this._config.timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<Model[]>('/v1/models', input, {\n signal,\n timeout: options.timeout ?? this._config.timeout,\n })\n )\n\n return data\n }\n\n public async *generateTextStream(\n request: CognitiveRequest,\n options: RequestOptions = {}\n ): AsyncGenerator<CognitiveStreamChunk, void, unknown> {\n const signal = options.signal ?? AbortSignal.timeout(this._config.timeout)\n\n if (isBrowser()) {\n const res = await fetch(`${this._config.baseUrl}/v1/generate-text-stream`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this._config.token}`,\n 'X-Bot-Id': this._config.botId,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ ...request, stream: true }),\n signal,\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n const err = new Error(`HTTP ${res.status}: ${text || res.statusText}`)\n ;(err as any).response = { status: res.status, data: text }\n throw err\n }\n\n const body = res.body\n if (!body) {\n throw new Error('No response body received for streaming request')\n }\n\n const reader = body.getReader()\n const iterable = (async function* () {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) {\n break\n }\n if (value) {\n yield value\n }\n }\n })()\n\n for await (const obj of this._ndjson<CognitiveStreamChunk>(iterable)) {\n yield obj\n }\n return\n }\n\n const res = await this._withServerRetry(() =>\n this._axiosClient.post(\n '/v1/generate-text-stream',\n { ...request, stream: true },\n {\n responseType: 'stream',\n signal,\n timeout: options.timeout ?? this._config.timeout,\n }\n )\n )\n\n const nodeStream: AsyncIterable<Uint8Array> = res.data as any\n if (!nodeStream) {\n throw new Error('No response body received for streaming request')\n }\n\n for await (const obj of this._ndjson<CognitiveStreamChunk>(nodeStream)) {\n yield obj\n }\n }\n\n private async *_ndjson<T>(stream: AsyncIterable<Uint8Array>): AsyncGenerator<T, void, unknown> {\n const decoder = new TextDecoder('utf-8')\n let buffer = ''\n\n for await (const chunk of stream) {\n buffer += decoder.decode(chunk, { stream: true })\n\n for (;;) {\n const i = buffer.indexOf('\\n')\n if (i < 0) {\n break\n }\n\n const line = buffer.slice(0, i).replace(/\\r$/, '')\n buffer = buffer.slice(i + 1)\n\n if (!line) {\n continue\n }\n\n yield JSON.parse(line) as T\n }\n }\n\n buffer += decoder.decode()\n\n const tail = buffer.trim()\n if (tail) {\n yield JSON.parse(tail) as T\n }\n }\n\n private _isRetryableServerError(error: any): boolean {\n if (axios.isAxiosError(error)) {\n if (!error.response) {\n return true\n }\n\n const status = error.response?.status\n if (status && [502, 503, 504].includes(status)) {\n return true\n }\n\n if (\n error.code &&\n ['ECONNABORTED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', 'ENOTFOUND', 'EPIPE'].includes(error.code)\n ) {\n return true\n }\n }\n\n return false\n }\n\n private async _withServerRetry<T>(fn: () => Promise<T>): Promise<T> {\n return backOff(fn, {\n numOfAttempts: 3,\n startingDelay: 300,\n timeMultiple: 2,\n jitter: 'full',\n retry: (e) => this._isRetryableServerError(e),\n })\n }\n}\n", "import { type ErrorType } from '@botpress/client'\n\nexport type BotpressError = {\n isApiError: boolean\n code: number\n description: string\n type: ErrorType\n subtype?: string\n error?: unknown\n metadata?: unknown\n message?: string\n id: string\n}\n\ntype Action = 'fallback' | 'retry' | 'abort'\n\nexport const getActionFromError = (error: any): Action => {\n if (!isBotpressError(error)) {\n return 'retry'\n }\n\n if (error.type === 'InvalidDataFormat') {\n if (error.message?.includes('data/model/id')) {\n // Invalid Model ID, so we want to try another model\n return 'fallback'\n }\n\n // Usually means the request was malformed\n return 'abort'\n }\n\n if (\n error.type === 'QuotaExceeded' ||\n error.type === 'RateLimited' ||\n error.type === 'Unknown' ||\n error.type === 'LimitExceeded'\n ) {\n // These errors are usually temporary, so we want to retry\n return 'retry'\n }\n\n const subtype = (error.metadata as any)?.subtype\n if (subtype === 'UPSTREAM_PROVIDER_FAILED') {\n // The model is degraded, so we want to try another model\n return 'fallback'\n }\n\n if (error.type === 'Internal') {\n // This is an internal error, probably a lambda timeout\n return 'retry'\n }\n\n return 'abort'\n}\n\nexport const isNotFoundError = (error: any): boolean => isBotpressError(error) && error.type === 'ResourceNotFound'\n\nexport const isForbiddenOrUnauthorizedError = (error: any): boolean =>\n isBotpressError(error) && (error.type === 'Forbidden' || error.type === 'Unauthorized')\n\nexport const isBotpressError = (error: any): error is BotpressError =>\n typeof error === 'object' &&\n error !== null &&\n 'isApiError' in error &&\n 'code' in error &&\n 'type' in error &&\n 'id' in error\n", "export type Callback<T> = (error: any | null, value: T) => void\nexport type Interceptor<T> = (error: any | null, value: T, next: Callback<T>, done: Callback<T>) => Promise<void> | void\n\nexport class InterceptorManager<T> {\n private _interceptors: Interceptor<T>[] = []\n\n public use(interceptor: Interceptor<T>) {\n this._interceptors.push(interceptor)\n return () => this.remove(interceptor)\n }\n\n public remove(interceptor: Interceptor<T>) {\n this._interceptors = this._interceptors.filter((i) => i !== interceptor)\n }\n\n public async run(value: T, signal: AbortSignal): Promise<T> {\n let error: any | null = null\n let result: T = value\n let done = false\n\n for (const interceptor of this._interceptors) {\n if (done) {\n break\n }\n\n if (signal.aborted) {\n throw signal.reason\n }\n\n await new Promise<void>((resolve) => {\n void interceptor(\n error,\n result,\n (err, val) => {\n error = err\n result = val\n resolve()\n },\n (err, val) => {\n error = err\n result = val\n done = true\n resolve()\n }\n )\n })\n }\n\n if (error) {\n throw error\n }\n\n return result\n }\n}\n", "import { ExtendedClient, getExtendedClient } from './bp-client'\nimport { isForbiddenOrUnauthorizedError, isNotFoundError } from './errors'\nimport { Model as RawModel } from './schemas.gen'\nimport { BotpressClientLike } from './types'\n\nexport const DOWNTIME_THRESHOLD_MINUTES = 5\nconst PREFERENCES_FILE_SUFFIX = 'models.config.json'\n\nexport const DEFAULT_INTEGRATIONS = ['google-ai', 'anthropic', 'openai', 'cerebras', 'fireworks-ai', 'groq']\n\n// Biases for vendors and models\nconst VendorPreferences = ['google-ai', 'anthropic', 'openai']\nconst BestModelPreferences = ['4.1', '4o', '3-5-sonnet', 'gemini-1.5-pro']\nconst FastModelPreferences = ['gemini-1.5-flash', '4.1-mini', '4.1-nano', '4o-mini', 'flash', 'haiku']\n\nconst InputPricePenalty = 3 // $3 per 1M tokens\nconst OutputPricePenalty = 10 // $10 per 1M tokens\nconst LowTokensPenalty = 128_000 // 128k tokens\n\nexport type Model = RawModel & {\n ref: ModelRef\n integration: string\n}\n\nexport type ModelRef = `${string}:${string}`\n\nexport type ModelPreferences = {\n best: ModelRef[]\n fast: ModelRef[]\n downtimes: Array<{ ref: ModelRef; startedAt: string; reason: string }>\n}\n\nconst isRecommended = (model: Model) => model.tags.includes('recommended')\nconst isDeprecated = (model: Model) => model.tags.includes('deprecated')\nconst isLowCost = (model: Model) => model.tags.includes('low-cost')\nconst hasVisionSupport = (model: Model) => model.tags.includes('vision')\nconst isGeneralPurpose = (model: Model) => model.tags.includes('general-purpose')\n\nconst scoreModel = (model: Model, type: 'best' | 'fast', boosts: Record<ModelRef, number> = {}) => {\n let score: number = 0\n\n const scores: Array<[string, boolean, number]> = [\n ['input price penalty', model.input.costPer1MTokens > InputPricePenalty, -1],\n ['output price penalty', model.output.costPer1MTokens > OutputPricePenalty, -1],\n ['low tokens penalty', (model.input.maxTokens ?? 0 + model.output.maxTokens ?? 0) < LowTokensPenalty, -1],\n ['recommended', isRecommended(model), 2],\n ['deprecated', isDeprecated(model), -2],\n ['vision support', hasVisionSupport(model), 1],\n ['general purpose', isGeneralPurpose(model), 1],\n ['vendor preference', VendorPreferences.includes(model.integration), 1],\n ['best model preference', type === 'best' && BestModelPreferences.some((x) => model.id.includes(x)), 1],\n ['fast model preference penalty', type === 'best' && FastModelPreferences.some((x) => model.id.includes(x)), -2],\n ['fast model preference', type === 'fast' && FastModelPreferences.some((x) => model.id.includes(x)), 2],\n ['low cost', type === 'fast' && isLowCost(model), 1],\n ]\n\n for (const rule in boosts) {\n if (model.ref.includes(rule)) {\n scores.push([`boost (${rule})`, true, Number(boosts[rule as ModelRef]) ?? 0] as const)\n }\n }\n\n for (const [, condition, value] of scores) {\n if (condition) {\n score += value\n }\n }\n\n return score\n}\n\nexport const getBestModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'best', boosts) - scoreModel(a, 'best', boosts))\n\nexport const getFastModels = (models: Model[], boosts: Record<ModelRef, number> = {}) =>\n models.sort((a, b) => scoreModel(b, 'fast', boosts) - scoreModel(a, 'fast', boosts))\n\nexport const pickModel = (models: ModelRef[], downtimes: ModelPreferences['downtimes'] = []) => {\n const copy = [...models]\n const elasped = (date: string) => new Date().getTime() - new Date(date).getTime()\n const DOWNTIME_THRESHOLD = 1000 * 60 * DOWNTIME_THRESHOLD_MINUTES\n\n if (!copy.length) {\n throw new Error('At least one model is required')\n }\n\n while (copy.length) {\n const ref = copy.shift() as ModelRef\n const downtime = downtimes.find((o) => o.ref === ref && elasped(o.startedAt) < DOWNTIME_THRESHOLD)\n if (downtime) {\n continue\n } else {\n return ref\n }\n }\n\n throw new Error(`All models are down: ${models.join(', ')}`)\n}\n\nexport abstract class ModelProvider {\n public abstract fetchInstalledModels(): Promise<Model[]>\n public abstract fetchModelPreferences(): Promise<ModelPreferences | null>\n public abstract saveModelPreferences(preferences: ModelPreferences): Promise<void>\n public abstract deleteModelPreferences(): Promise<void>\n}\n\nexport class RemoteModelProvider extends ModelProvider {\n private _client: ExtendedClient\n\n public constructor(client: BotpressClientLike) {\n super()\n this._client = getExtendedClient(client)\n }\n\n private async _fetchInstalledIntegrationNames() {\n try {\n const { bot } = await this._client.getBot({ id: this._client.botId })\n const integrations = Object.values(bot.integrations).filter((x) => x.status === 'registered')\n return integrations.map((x) => x.name)\n } catch (err) {\n if (isForbiddenOrUnauthorizedError(err)) {\n // This happens when the bot (with a BAK token) tries to access the .getBot endpoint\n return DEFAULT_INTEGRATIONS\n }\n\n throw err\n }\n }\n\n public async fetchInstalledModels() {\n const integrationNames = await this._fetchInstalledIntegrationNames()\n const models: Model[] = []\n\n await Promise.allSettled(\n integrationNames.map(async (integration) => {\n const { output } = await this._client.callAction({\n type: `${integration}:listLanguageModels`,\n input: {},\n })\n\n if (!output?.models?.length) {\n return\n }\n\n for (const model of output.models as RawModel[]) {\n if (model.name && model.id && model.input && model.tags) {\n models.push({\n ref: `${integration}:${model.id}`,\n integration,\n id: model.id,\n name: model.name,\n description: model.description,\n input: model.input,\n output: model.output,\n tags: model.tags,\n })\n }\n }\n })\n )\n\n return models\n }\n\n public async fetchModelPreferences(): Promise<ModelPreferences | null> {\n try {\n const { file } = await this._client.getFile({ id: this._preferenceFileKey })\n\n if (globalThis.fetch !== undefined) {\n const response = await fetch(file.url)\n return (await response.json()) as ModelPreferences\n } else {\n const { data } = await this._client.axios.get(file.url, {\n // we piggy-back axios to avoid adding a new dependency\n // unset all headers to avoid S3 pre-signed signature mismatch\n headers: Object.keys(this._client.config.headers).reduce(\n (acc, key) => {\n acc[key] = undefined\n return acc\n },\n {} as Record<string, undefined>\n ),\n })\n return data as ModelPreferences\n }\n } catch (err) {\n if (isNotFoundError(err)) {\n return null\n }\n\n throw err\n }\n }\n\n public async saveModelPreferences(preferences: ModelPreferences) {\n await this._client.uploadFile({\n key: this._preferenceFileKey,\n content: JSON.stringify(preferences, null, 2),\n index: false,\n tags: {\n system: 'true',\n purpose: 'config',\n },\n })\n }\n\n public async deleteModelPreferences() {\n await this._client.deleteFile({ id: this._preferenceFileKey }).catch(() => {})\n }\n\n private get _preferenceFileKey() {\n return `bot->${this._client.botId}->${PREFERENCES_FILE_SUFFIX}`\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,QAAM,iBAAkC;MACtC,mBAAmB;MACnB,QAAQ;MACR,UAAU;MACV,eAAe;MACf,OAAO,WAAA;AAAM,eAAA;MAAA;MACb,eAAe;MACf,cAAc;;AAGhB,aAAgB,oBAAoB,SAAuB;AACzD,UAAM,YAAS,SAAA,SAAA,CAAA,GAAyB,cAAc,GAAK,OAAO;AAElE,UAAI,UAAU,gBAAgB,GAAG;AAC/B,kBAAU,gBAAgB;;AAG5B,aAAO;IACT;AARA,YAAA,sBAAA;;;;;;;;;ACxBA,aAAgB,WAAW,OAAa;AACpC,UAAM,gBAAgB,KAAK,OAAM,IAAK;AACtC,aAAO,KAAK,MAAM,aAAa;IACnC;AAHA,YAAA,aAAA;;;;;;;;;ACAA,aAAgB,SAAS,OAAa;AAClC,aAAO;IACX;AAFA,YAAA,WAAA;;;;;;;;;ACCA,QAAA,gBAAA;AACA,QAAA,cAAA;AAIA,aAAgB,cAAc,SAAwB;AACpD,cAAQ,QAAQ,QAAQ;QACtB,KAAK;AACH,iBAAO,cAAA;QAET,KAAK;QACL;AACE,iBAAO,YAAA;;IAEb;AATA,YAAA,gBAAA;;;;;;;;;ACJA,QAAA,mBAAA;AAEA,QAAA;;MAAA,WAAA;AAEE,iBAAAA,OAAoB,SAAwB;AAAxB,eAAA,UAAA;AADV,eAAA,UAAU;QAC2B;AAExC,QAAAA,OAAA,UAAA,QAAP,WAAA;AAAA,cAAA,QAAA;AACE,iBAAO,IAA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