@botpress/cognitive 0.1.39 → 0.1.41
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 +30 -35
- package/dist/index.cjs.map +2 -2
- package/dist/index.d.ts +30 -4
- package/dist/index.mjs +30 -35
- package/dist/index.mjs.map +2 -2
- 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.41 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.41 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 9466ms
|
|
14
|
+
DTS dist/index.d.ts 624.13 KB
|
|
15
15
|
|
|
16
|
-
> @botpress/cognitive@0.1.
|
|
16
|
+
> @botpress/cognitive@0.1.41 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[1m8.
|
|
23
|
+
Size: [32m[1m8.49 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[1m8.
|
|
27
|
+
Size: [32m[1m8.36 kB[22m[39m [90mbrotlied[39m
|
|
28
28
|
|
package/dist/index.cjs
CHANGED
|
@@ -651,58 +651,57 @@ var import_exponential_backoff = __toESM(require_backoff());
|
|
|
651
651
|
var isBrowser = () => typeof window !== "undefined" && typeof window.fetch === "function";
|
|
652
652
|
var CognitiveBeta = class {
|
|
653
653
|
_axiosClient;
|
|
654
|
-
|
|
654
|
+
_apiUrl;
|
|
655
|
+
_timeout;
|
|
656
|
+
_withCredentials;
|
|
657
|
+
_headers;
|
|
655
658
|
constructor(props) {
|
|
656
|
-
this.
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
659
|
+
this._apiUrl = props.apiUrl || "https://api.botpress.cloud";
|
|
660
|
+
this._timeout = props.timeout || 60001;
|
|
661
|
+
this._withCredentials = props.withCredentials || false;
|
|
662
|
+
this._headers = { ...props.headers };
|
|
663
|
+
if (props.botId) {
|
|
664
|
+
this._headers["X-Bot-Id"] = props.botId;
|
|
665
|
+
}
|
|
666
|
+
if (props.token) {
|
|
667
|
+
this._headers["Authorization"] = `Bearer ${props.token}`;
|
|
668
|
+
}
|
|
664
669
|
this._axiosClient = import_axios.default.create({
|
|
665
|
-
headers:
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
...this._config.headers
|
|
669
|
-
},
|
|
670
|
-
withCredentials: this._config.withCredentials,
|
|
671
|
-
baseURL: this._config.baseUrl
|
|
670
|
+
headers: this._headers,
|
|
671
|
+
withCredentials: this._withCredentials,
|
|
672
|
+
baseURL: this._apiUrl
|
|
672
673
|
});
|
|
673
674
|
}
|
|
674
675
|
async generateText(input, options = {}) {
|
|
675
|
-
const signal = options.signal ?? AbortSignal.timeout(this.
|
|
676
|
+
const signal = options.signal ?? AbortSignal.timeout(this._timeout);
|
|
676
677
|
const { data } = await this._withServerRetry(
|
|
677
|
-
() => this._axiosClient.post("/
|
|
678
|
+
() => this._axiosClient.post("/v2/cognitive/generate-text", input, {
|
|
678
679
|
signal,
|
|
679
|
-
timeout: options.timeout ?? this.
|
|
680
|
+
timeout: options.timeout ?? this._timeout
|
|
680
681
|
})
|
|
681
682
|
);
|
|
682
683
|
return data;
|
|
683
684
|
}
|
|
684
685
|
async listModels(input, options = {}) {
|
|
685
|
-
const signal = options.signal ?? AbortSignal.timeout(this.
|
|
686
|
+
const signal = options.signal ?? AbortSignal.timeout(this._timeout);
|
|
686
687
|
const { data } = await this._withServerRetry(
|
|
687
|
-
() => this._axiosClient.post("/
|
|
688
|
+
() => this._axiosClient.post("/v2/cognitive/models", input, {
|
|
688
689
|
signal,
|
|
689
|
-
timeout: options.timeout ?? this.
|
|
690
|
+
timeout: options.timeout ?? this._timeout
|
|
690
691
|
})
|
|
691
692
|
);
|
|
692
693
|
return data;
|
|
693
694
|
}
|
|
694
695
|
async *generateTextStream(request, options = {}) {
|
|
695
|
-
const signal = options.signal ?? AbortSignal.timeout(this.
|
|
696
|
+
const signal = options.signal ?? AbortSignal.timeout(this._timeout);
|
|
696
697
|
if (isBrowser()) {
|
|
697
|
-
const res2 = await fetch(`${this.
|
|
698
|
+
const res2 = await fetch(`${this._apiUrl}/v2/cognitive/generate-text-stream`, {
|
|
698
699
|
method: "POST",
|
|
699
700
|
headers: {
|
|
700
|
-
|
|
701
|
-
"
|
|
702
|
-
"Content-Type": "application/json",
|
|
703
|
-
...this._config.headers
|
|
701
|
+
...this._headers,
|
|
702
|
+
"Content-Type": "application/json"
|
|
704
703
|
},
|
|
705
|
-
credentials: this.
|
|
704
|
+
credentials: this._withCredentials ? "include" : "omit",
|
|
706
705
|
body: JSON.stringify({ ...request, stream: true }),
|
|
707
706
|
signal
|
|
708
707
|
});
|
|
@@ -740,7 +739,7 @@ var CognitiveBeta = class {
|
|
|
740
739
|
{
|
|
741
740
|
responseType: "stream",
|
|
742
741
|
signal,
|
|
743
|
-
timeout: options.timeout ?? this.
|
|
742
|
+
timeout: options.timeout ?? this._timeout
|
|
744
743
|
}
|
|
745
744
|
)
|
|
746
745
|
);
|
|
@@ -1151,11 +1150,7 @@ var Cognitive = class _Cognitive {
|
|
|
1151
1150
|
if (!this._useBeta) {
|
|
1152
1151
|
return this._generateContent(input);
|
|
1153
1152
|
}
|
|
1154
|
-
const betaClient = new CognitiveBeta(
|
|
1155
|
-
headers: this._client.config.headers,
|
|
1156
|
-
withCredentials: this._client.config.withCredentials,
|
|
1157
|
-
baseUrl: this._client.config.apiUrl.includes(".cloud") ? "https://cognitive.botpress.cloud" : "https://cognitive.botpress.dev"
|
|
1158
|
-
});
|
|
1153
|
+
const betaClient = new CognitiveBeta(this._client.config);
|
|
1159
1154
|
const response = await betaClient.generateText(input);
|
|
1160
1155
|
return {
|
|
1161
1156
|
output: {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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/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 withCredentials: this._client.config.withCredentials,\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 withCredentials?: boolean\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 withCredentials: props.withCredentials || false,\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 withCredentials: this._config.withCredentials,\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 ...this._config.headers,\n },\n credentials: this._config.withCredentials ? 'include' : 'omit',\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,IAAAA,SAAA,sBAAA;;;;;;;;;ACxBA,aAAgB,WAAW,OAAa;AACpC,UAAM,gBAAgB,KAAK,OAAM,IAAK;AACtC,aAAO,KAAK,MAAM,aAAa;IACnC;AAHA,IAAAC,SAAA,aAAA;;;;;;;;;ACAA,aAAgB,SAAS,OAAa;AAClC,aAAO;IACX;AAFA,IAAAC,SAAA,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,IAAAC,SAAA,gBAAA;;;;;;;;;ACJA,QAAA,mBAAA;AAEA,QAAA;;OAAA,WAAA;AAEE,i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MAC/E;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,YAAY,OAAO,QAAQ;AAE7C,WAAO,KAAK,aAAa,SAAS,IAAI,UAAU,MAAM;AAAA,EACxD;AACF;",
|
|
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(this._client.config as any)\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 apiUrl?: string\n timeout?: number\n botId?: string\n token?: string\n withCredentials?: boolean\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 _apiUrl: string\n private readonly _timeout: number\n private readonly _withCredentials: boolean\n private readonly _headers: Record<string, string>\n\n public constructor(props: ClientProps) {\n this._apiUrl = props.apiUrl || 'https://api.botpress.cloud'\n this._timeout = props.timeout || 60_001\n this._withCredentials = props.withCredentials || false\n this._headers = { ...props.headers }\n\n if (props.botId) {\n this._headers['X-Bot-Id'] = props.botId\n }\n\n if (props.token) {\n this._headers['Authorization'] = `Bearer ${props.token}`\n }\n\n this._axiosClient = axios.create({\n headers: this._headers,\n withCredentials: this._withCredentials,\n baseURL: this._apiUrl,\n })\n }\n\n public async generateText(input: CognitiveRequest, options: RequestOptions = {}) {\n const signal = options.signal ?? AbortSignal.timeout(this._timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<CognitiveResponse>('/v2/cognitive/generate-text', input, {\n signal,\n timeout: options.timeout ?? this._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._timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<Model[]>('/v2/cognitive/models', input, {\n signal,\n timeout: options.timeout ?? this._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._timeout)\n\n if (isBrowser()) {\n const res = await fetch(`${this._apiUrl}/v2/cognitive/generate-text-stream`, {\n method: 'POST',\n headers: {\n ...this._headers,\n 'Content-Type': 'application/json',\n },\n credentials: this._withCredentials ? 'include' : 'omit',\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._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,IAAAA,SAAA,sBAAA;;;;;;;;;ACxBA,aAAgB,WAAW,OAAa;AACpC,UAAM,gBAAgB,KAAK,OAAM,IAAK;AACtC,aAAO,KAAK,MAAM,aAAa;IACnC;AAHA,IAAAC,SAAA,aAAA;;;;;;;;;ACAA,aAAgB,SAAS,OAAa;AAClC,aAAO;IACX;AAFA,IAAAC,SAAA,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,IAAAC,SAAA,gBAAA;;;;;;;;;ACJA,QAAA,mBAAA;AAEA,QAAA;;OAAA,WAAA;AAEE,iBAAAC,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,WAAW,SAAS,MAAK,aAAa;UAAtC,CAAuC;QACvE;AAEO,Q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qB;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
6
|
"names": ["exports", "exports", "exports", "exports", "Delay", "exports", "SkipFirstDelay", "exports", "AlwaysDelay", "exports", "exports", "backOff", "exports", "BackOff", "import_exponential_backoff", "axios", "res", "ref"]
|
|
7
7
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -2060,6 +2060,7 @@ interface CreateMessageRequestBody {
|
|
|
2060
2060
|
*/
|
|
2061
2061
|
delay?: number;
|
|
2062
2062
|
};
|
|
2063
|
+
origin?: "synthetic";
|
|
2063
2064
|
}
|
|
2064
2065
|
type CreateMessageInput = CreateMessageRequestBody & CreateMessageRequestHeaders & CreateMessageRequestQuery & CreateMessageRequestParams;
|
|
2065
2066
|
interface CreateMessageResponse {
|
|
@@ -2107,6 +2108,10 @@ interface CreateMessageResponse {
|
|
|
2107
2108
|
tags: {
|
|
2108
2109
|
[k: string]: string;
|
|
2109
2110
|
};
|
|
2111
|
+
/**
|
|
2112
|
+
* Origin of the message (`synthetic`).
|
|
2113
|
+
*/
|
|
2114
|
+
origin?: "synthetic";
|
|
2110
2115
|
};
|
|
2111
2116
|
}
|
|
2112
2117
|
|
|
@@ -2154,6 +2159,7 @@ interface GetOrCreateMessageRequestBody {
|
|
|
2154
2159
|
*/
|
|
2155
2160
|
delay?: number;
|
|
2156
2161
|
};
|
|
2162
|
+
origin?: "synthetic";
|
|
2157
2163
|
/**
|
|
2158
2164
|
* Optional list of tag names to use for strict matching when looking up existing messages. If provided, all specified tags must match exactly for a message to be considered a match. For example, with an existing message whose tags are {"foo": "a", "bar": "b", baz: "c"}: Without this parameter, ALL tags must match exactly. With ["bar","baz"], all listed tags must match their values, and other tags are not considered.
|
|
2159
2165
|
*/
|
|
@@ -2205,6 +2211,10 @@ interface GetOrCreateMessageResponse {
|
|
|
2205
2211
|
tags: {
|
|
2206
2212
|
[k: string]: string;
|
|
2207
2213
|
};
|
|
2214
|
+
/**
|
|
2215
|
+
* Origin of the message (`synthetic`).
|
|
2216
|
+
*/
|
|
2217
|
+
origin?: "synthetic";
|
|
2208
2218
|
};
|
|
2209
2219
|
}
|
|
2210
2220
|
|
|
@@ -2263,6 +2273,10 @@ interface GetMessageResponse {
|
|
|
2263
2273
|
tags: {
|
|
2264
2274
|
[k: string]: string;
|
|
2265
2275
|
};
|
|
2276
|
+
/**
|
|
2277
|
+
* Origin of the message (`synthetic`).
|
|
2278
|
+
*/
|
|
2279
|
+
origin?: "synthetic";
|
|
2266
2280
|
};
|
|
2267
2281
|
}
|
|
2268
2282
|
|
|
@@ -2333,6 +2347,10 @@ interface UpdateMessageResponse {
|
|
|
2333
2347
|
tags: {
|
|
2334
2348
|
[k: string]: string;
|
|
2335
2349
|
};
|
|
2350
|
+
/**
|
|
2351
|
+
* Origin of the message (`synthetic`).
|
|
2352
|
+
*/
|
|
2353
|
+
origin?: "synthetic";
|
|
2336
2354
|
};
|
|
2337
2355
|
}
|
|
2338
2356
|
|
|
@@ -2392,6 +2410,10 @@ interface ListMessagesResponse {
|
|
|
2392
2410
|
tags: {
|
|
2393
2411
|
[k: string]: string;
|
|
2394
2412
|
};
|
|
2413
|
+
/**
|
|
2414
|
+
* Origin of the message (`synthetic`).
|
|
2415
|
+
*/
|
|
2416
|
+
origin?: "synthetic";
|
|
2395
2417
|
}[];
|
|
2396
2418
|
meta: {
|
|
2397
2419
|
/**
|
|
@@ -3531,7 +3553,7 @@ interface CreateWorkflowRequestBody {
|
|
|
3531
3553
|
tags?: {
|
|
3532
3554
|
[k: string]: string;
|
|
3533
3555
|
};
|
|
3534
|
-
status: "pending" | "in_progress";
|
|
3556
|
+
status: "pending" | "in_progress" | "listening";
|
|
3535
3557
|
/**
|
|
3536
3558
|
* Event id must be specified if the workflow is created with the status in_progress
|
|
3537
3559
|
*/
|
|
@@ -3943,7 +3965,7 @@ interface GetOrCreateWorkflowRequestBody {
|
|
|
3943
3965
|
tags?: {
|
|
3944
3966
|
[k: string]: string;
|
|
3945
3967
|
};
|
|
3946
|
-
status: "pending" | "in_progress";
|
|
3968
|
+
status: "pending" | "in_progress" | "listening";
|
|
3947
3969
|
/**
|
|
3948
3970
|
* Event id must be specified if the workflow is created with the status in_progress
|
|
3949
3971
|
*/
|
|
@@ -18085,6 +18107,7 @@ declare class Client extends Client$1 implements IClient {
|
|
|
18085
18107
|
tags: {
|
|
18086
18108
|
[k: string]: string;
|
|
18087
18109
|
};
|
|
18110
|
+
origin?: "synthetic";
|
|
18088
18111
|
}>;
|
|
18089
18112
|
users: (props: {
|
|
18090
18113
|
tags?: {
|
|
@@ -19065,7 +19088,7 @@ type Model = {
|
|
|
19065
19088
|
};
|
|
19066
19089
|
|
|
19067
19090
|
type ClientProps = {
|
|
19068
|
-
|
|
19091
|
+
apiUrl?: string;
|
|
19069
19092
|
timeout?: number;
|
|
19070
19093
|
botId?: string;
|
|
19071
19094
|
token?: string;
|
|
@@ -19078,7 +19101,10 @@ type RequestOptions = {
|
|
|
19078
19101
|
};
|
|
19079
19102
|
declare class CognitiveBeta {
|
|
19080
19103
|
private _axiosClient;
|
|
19081
|
-
private readonly
|
|
19104
|
+
private readonly _apiUrl;
|
|
19105
|
+
private readonly _timeout;
|
|
19106
|
+
private readonly _withCredentials;
|
|
19107
|
+
private readonly _headers;
|
|
19082
19108
|
constructor(props: ClientProps);
|
|
19083
19109
|
generateText(input: CognitiveRequest, options?: RequestOptions): Promise<CognitiveResponse>;
|
|
19084
19110
|
listModels(input: void, options?: RequestOptions): Promise<Model[]>;
|
package/dist/index.mjs
CHANGED
|
@@ -636,58 +636,57 @@ import axios from "axios";
|
|
|
636
636
|
var isBrowser = () => typeof window !== "undefined" && typeof window.fetch === "function";
|
|
637
637
|
var CognitiveBeta = class {
|
|
638
638
|
_axiosClient;
|
|
639
|
-
|
|
639
|
+
_apiUrl;
|
|
640
|
+
_timeout;
|
|
641
|
+
_withCredentials;
|
|
642
|
+
_headers;
|
|
640
643
|
constructor(props) {
|
|
641
|
-
this.
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
644
|
+
this._apiUrl = props.apiUrl || "https://api.botpress.cloud";
|
|
645
|
+
this._timeout = props.timeout || 60001;
|
|
646
|
+
this._withCredentials = props.withCredentials || false;
|
|
647
|
+
this._headers = { ...props.headers };
|
|
648
|
+
if (props.botId) {
|
|
649
|
+
this._headers["X-Bot-Id"] = props.botId;
|
|
650
|
+
}
|
|
651
|
+
if (props.token) {
|
|
652
|
+
this._headers["Authorization"] = `Bearer ${props.token}`;
|
|
653
|
+
}
|
|
649
654
|
this._axiosClient = axios.create({
|
|
650
|
-
headers:
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
...this._config.headers
|
|
654
|
-
},
|
|
655
|
-
withCredentials: this._config.withCredentials,
|
|
656
|
-
baseURL: this._config.baseUrl
|
|
655
|
+
headers: this._headers,
|
|
656
|
+
withCredentials: this._withCredentials,
|
|
657
|
+
baseURL: this._apiUrl
|
|
657
658
|
});
|
|
658
659
|
}
|
|
659
660
|
async generateText(input, options = {}) {
|
|
660
|
-
const signal = options.signal ?? AbortSignal.timeout(this.
|
|
661
|
+
const signal = options.signal ?? AbortSignal.timeout(this._timeout);
|
|
661
662
|
const { data } = await this._withServerRetry(
|
|
662
|
-
() => this._axiosClient.post("/
|
|
663
|
+
() => this._axiosClient.post("/v2/cognitive/generate-text", input, {
|
|
663
664
|
signal,
|
|
664
|
-
timeout: options.timeout ?? this.
|
|
665
|
+
timeout: options.timeout ?? this._timeout
|
|
665
666
|
})
|
|
666
667
|
);
|
|
667
668
|
return data;
|
|
668
669
|
}
|
|
669
670
|
async listModels(input, options = {}) {
|
|
670
|
-
const signal = options.signal ?? AbortSignal.timeout(this.
|
|
671
|
+
const signal = options.signal ?? AbortSignal.timeout(this._timeout);
|
|
671
672
|
const { data } = await this._withServerRetry(
|
|
672
|
-
() => this._axiosClient.post("/
|
|
673
|
+
() => this._axiosClient.post("/v2/cognitive/models", input, {
|
|
673
674
|
signal,
|
|
674
|
-
timeout: options.timeout ?? this.
|
|
675
|
+
timeout: options.timeout ?? this._timeout
|
|
675
676
|
})
|
|
676
677
|
);
|
|
677
678
|
return data;
|
|
678
679
|
}
|
|
679
680
|
async *generateTextStream(request, options = {}) {
|
|
680
|
-
const signal = options.signal ?? AbortSignal.timeout(this.
|
|
681
|
+
const signal = options.signal ?? AbortSignal.timeout(this._timeout);
|
|
681
682
|
if (isBrowser()) {
|
|
682
|
-
const res2 = await fetch(`${this.
|
|
683
|
+
const res2 = await fetch(`${this._apiUrl}/v2/cognitive/generate-text-stream`, {
|
|
683
684
|
method: "POST",
|
|
684
685
|
headers: {
|
|
685
|
-
|
|
686
|
-
"
|
|
687
|
-
"Content-Type": "application/json",
|
|
688
|
-
...this._config.headers
|
|
686
|
+
...this._headers,
|
|
687
|
+
"Content-Type": "application/json"
|
|
689
688
|
},
|
|
690
|
-
credentials: this.
|
|
689
|
+
credentials: this._withCredentials ? "include" : "omit",
|
|
691
690
|
body: JSON.stringify({ ...request, stream: true }),
|
|
692
691
|
signal
|
|
693
692
|
});
|
|
@@ -725,7 +724,7 @@ var CognitiveBeta = class {
|
|
|
725
724
|
{
|
|
726
725
|
responseType: "stream",
|
|
727
726
|
signal,
|
|
728
|
-
timeout: options.timeout ?? this.
|
|
727
|
+
timeout: options.timeout ?? this._timeout
|
|
729
728
|
}
|
|
730
729
|
)
|
|
731
730
|
);
|
|
@@ -1136,11 +1135,7 @@ var Cognitive = class _Cognitive {
|
|
|
1136
1135
|
if (!this._useBeta) {
|
|
1137
1136
|
return this._generateContent(input);
|
|
1138
1137
|
}
|
|
1139
|
-
const betaClient = new CognitiveBeta(
|
|
1140
|
-
headers: this._client.config.headers,
|
|
1141
|
-
withCredentials: this._client.config.withCredentials,
|
|
1142
|
-
baseUrl: this._client.config.apiUrl.includes(".cloud") ? "https://cognitive.botpress.cloud" : "https://cognitive.botpress.dev"
|
|
1143
|
-
});
|
|
1138
|
+
const betaClient = new CognitiveBeta(this._client.config);
|
|
1144
1139
|
const response = await betaClient.generateText(input);
|
|
1145
1140
|
return {
|
|
1146
1141
|
output: {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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/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 withCredentials: this._client.config.withCredentials,\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 withCredentials?: boolean\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 withCredentials: props.withCredentials || false,\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 withCredentials: this._config.withCredentials,\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 ...this._config.headers,\n },\n credentials: this._config.withCredentials ? 'include' : 'omit',\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,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AA,MAC/E;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,YAAY,OAAO,QAAQ;AAE7C,WAAO,KAAK,aAAa,SAAS,IAAI,UAAU,MAAM;AAAA,EACxD;AACF;",
|
|
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(this._client.config as any)\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 apiUrl?: string\n timeout?: number\n botId?: string\n token?: string\n withCredentials?: boolean\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 _apiUrl: string\n private readonly _timeout: number\n private readonly _withCredentials: boolean\n private readonly _headers: Record<string, string>\n\n public constructor(props: ClientProps) {\n this._apiUrl = props.apiUrl || 'https://api.botpress.cloud'\n this._timeout = props.timeout || 60_001\n this._withCredentials = props.withCredentials || false\n this._headers = { ...props.headers }\n\n if (props.botId) {\n this._headers['X-Bot-Id'] = props.botId\n }\n\n if (props.token) {\n this._headers['Authorization'] = `Bearer ${props.token}`\n }\n\n this._axiosClient = axios.create({\n headers: this._headers,\n withCredentials: this._withCredentials,\n baseURL: this._apiUrl,\n })\n }\n\n public async generateText(input: CognitiveRequest, options: RequestOptions = {}) {\n const signal = options.signal ?? AbortSignal.timeout(this._timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<CognitiveResponse>('/v2/cognitive/generate-text', input, {\n signal,\n timeout: options.timeout ?? this._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._timeout)\n\n const { data } = await this._withServerRetry(() =>\n this._axiosClient.post<Model[]>('/v2/cognitive/models', input, {\n signal,\n timeout: options.timeout ?? this._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._timeout)\n\n if (isBrowser()) {\n const res = await fetch(`${this._apiUrl}/v2/cognitive/generate-text-stream`, {\n method: 'POST',\n headers: {\n ...this._headers,\n 'Content-Type': 'application/json',\n },\n credentials: this._withCredentials ? 'include' : 'omit',\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._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}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