@intelliweave/embedded 1.7.58 → 1.8.60
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/custom.d.ts +0 -24
- package/dist/component/component.d.ts +52 -37
- package/dist/component/component.js +32 -22
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +193 -48
- package/dist/node/node.js +19 -13
- package/dist/react/react.d.ts +47 -35
- package/dist/react/react.js +34 -24
- package/dist/script-tag/script-tag.js +36 -26
- package/dist/webpack/index.d.ts +165 -124
- package/dist/webpack/index.js +33 -23
- package/package.json +1 -1
package/dist/node/node.d.ts
CHANGED
|
@@ -385,17 +385,6 @@ function int16ToFloat32BitPCM(input) {
|
|
|
385
385
|
return output;
|
|
386
386
|
}
|
|
387
387
|
|
|
388
|
-
/** Utility to trim whitespace from blocks of text */
|
|
389
|
-
declare function trimWhitespaceInText(text: string): string;
|
|
390
|
-
/** Get the global object */
|
|
391
|
-
declare function intelliweaveGlobalThis(): any;
|
|
392
|
-
/** Get the global IntelliWeave configuration object that has been created for this document, or create it if necessary. */
|
|
393
|
-
declare function intelliweaveConfig(): any;
|
|
394
|
-
/** An async generator which yields events from an SSE fetch request body (a readable stream) */
|
|
395
|
-
declare function sseEvents(stream: ReadableStream<Uint8Array>): AsyncGenerator<any, void, unknown>;
|
|
396
|
-
/** Get or create a user ID for this device. */
|
|
397
|
-
declare function getDefaultUserID(): string;
|
|
398
|
-
|
|
399
388
|
/**
|
|
400
389
|
* This class helps organize groups of tokenized text along with removing items when the window is full.
|
|
401
390
|
*/
|
|
@@ -600,6 +589,14 @@ declare class WebWeaverSpeechOutput extends EventTarget {
|
|
|
600
589
|
/** Current player vars */
|
|
601
590
|
private currentPlayerVolume?;
|
|
602
591
|
private currentPlayer?;
|
|
592
|
+
/** The audio analyser node */
|
|
593
|
+
private analyserNode?;
|
|
594
|
+
/** The audio analyser buffer */
|
|
595
|
+
private analyserBuffer?;
|
|
596
|
+
/** @private Maximum volume heard this session */
|
|
597
|
+
private maxVolumeHeard;
|
|
598
|
+
/** Get current (realtime) audio output volume level, from 0 to 1 */
|
|
599
|
+
get volumeLevel(): number;
|
|
603
600
|
/** Speak the text */
|
|
604
601
|
speak(text: string): Promise<void>;
|
|
605
602
|
private _speakWithLock;
|
|
@@ -777,9 +774,9 @@ declare class WebWeaverSpeechRecognition extends EventTarget {
|
|
|
777
774
|
/** True if recognition is running */
|
|
778
775
|
isRunning: boolean;
|
|
779
776
|
/** The audio analyser node */
|
|
780
|
-
analyserNode
|
|
777
|
+
private analyserNode?;
|
|
781
778
|
/** The audio analyser buffer */
|
|
782
|
-
analyserBuffer
|
|
779
|
+
private analyserBuffer?;
|
|
783
780
|
/** The microphone stream */
|
|
784
781
|
micStream?: MediaStream;
|
|
785
782
|
/** Returns true if speech recognition is supported by this persona and browser */
|
|
@@ -838,49 +835,53 @@ declare class AILogic {
|
|
|
838
835
|
/** Constructor */
|
|
839
836
|
constructor(ai: IntelliWeave);
|
|
840
837
|
/** Ask the AI a yes/no question associated with the specified data. Data must be JSON-serializable, or a string of any kind of data. */
|
|
841
|
-
boolean(
|
|
842
|
-
/**
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
*/
|
|
848
|
-
choose(question: string, data: any, options: string[]): Promise<string | undefined>;
|
|
838
|
+
boolean(config: IntelliWeaveInstructConfig): Promise<boolean>;
|
|
839
|
+
/** Ask the AI to select a choice from a list of options. */
|
|
840
|
+
choose(config: IntelliWeaveInstructConfig & {
|
|
841
|
+
/** List of choices the AI can pick from. */
|
|
842
|
+
options: string[];
|
|
843
|
+
}): Promise<string | undefined>;
|
|
849
844
|
/**
|
|
850
|
-
* Ask the AI to extract data from
|
|
851
|
-
* Example: extract(myData, true, [
|
|
852
|
-
* { name: "id", type: "string", description: "The user's ID number." },
|
|
853
|
-
* { name: "firstName", type: "string", description: "The user's first name" },
|
|
854
|
-
* ])
|
|
855
|
-
* @param question The question to ask the AI.
|
|
856
|
-
* @param data The data to provide to the AI. This can be a string or a JSON-serializable object.
|
|
857
|
-
* @param allowMultiple Whether to allow multiple extractions or not.
|
|
858
|
-
* @param extractions The list of extractions to perform. Each extraction is an object with the following properties:
|
|
859
|
-
* - name: The name of the extraction. This will be the key in the returned object.
|
|
860
|
-
* - type: The type of the extraction. This can be "string", "number", "boolean", "date", "email", "url", "phone", "address", "name", "organization", "person", "location", "time", "duration", "money", "percentage", "quantity", "custom".
|
|
861
|
-
* - description: A description of the extraction. This is optional.
|
|
845
|
+
* Ask the AI to extract data from input data. The AI will return the extracted data. Possibly an array of multiple extractions.
|
|
862
846
|
*/
|
|
863
|
-
extract
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
847
|
+
extract<T = any>(config: IntelliWeaveInstructConfig & {
|
|
848
|
+
/** Allow multiple items to be returned. If true, returns an array instead of an object. */
|
|
849
|
+
allowMultiple?: boolean;
|
|
850
|
+
/** Fields to extract in each object. */
|
|
851
|
+
extractions: {
|
|
852
|
+
/** Field name */
|
|
853
|
+
name: string;
|
|
854
|
+
/** Field data type */
|
|
855
|
+
type: 'string' | 'number' | 'boolean' | 'date' | 'email' | 'phone' | 'address';
|
|
856
|
+
/** Describe to the AI what data to put in this field. */
|
|
857
|
+
description?: string;
|
|
858
|
+
}[];
|
|
859
|
+
}): Promise<T[]>;
|
|
868
860
|
/**
|
|
869
|
-
* Generate a Markdown document based on the
|
|
861
|
+
* Generate a Markdown document based on the data from the user.
|
|
870
862
|
*
|
|
871
863
|
* @param query The query to generate the document from.
|
|
872
|
-
* @param
|
|
864
|
+
* @param config Instruct config.
|
|
873
865
|
*/
|
|
874
|
-
generateMarkdown(
|
|
866
|
+
generateMarkdown(config: Omit<IntelliWeaveInstructConfig, 'instruction'>): Promise<string>;
|
|
875
867
|
/**
|
|
876
868
|
* Perform an instruction.
|
|
877
869
|
*
|
|
878
|
-
* @param
|
|
879
|
-
* @param query The user query to pass to the AI.
|
|
880
|
-
* @param callback The callback that will be called when streaming the response. Each call will contain the full text that has been generated so far.
|
|
870
|
+
* @param config Instruct config.
|
|
881
871
|
* @returns The final response from the AI.
|
|
882
872
|
*/
|
|
883
|
-
instruct(
|
|
873
|
+
instruct(config: IntelliWeaveInstructConfig): Promise<string>;
|
|
874
|
+
}
|
|
875
|
+
/** Config for any instruct call */
|
|
876
|
+
interface IntelliWeaveInstructConfig {
|
|
877
|
+
/** Instruction */
|
|
878
|
+
instruction: string;
|
|
879
|
+
/** Input data or query to process */
|
|
880
|
+
data: any;
|
|
881
|
+
/** Whether to allow the AI to use the knowledge base or not. If false, the AI will not use the knowledge base. */
|
|
882
|
+
allowKB?: boolean;
|
|
883
|
+
/** Callback that will be called when streaming the response. Each call will contain the full text that has been generated so far. */
|
|
884
|
+
callback?: (txt: string) => void;
|
|
884
885
|
}
|
|
885
886
|
|
|
886
887
|
/** Persona config received from the hub */
|
|
@@ -988,7 +989,7 @@ declare class IntelliWeave extends EventTarget {
|
|
|
988
989
|
setModel(id: string): void;
|
|
989
990
|
private _lastSystemMsg;
|
|
990
991
|
/** Get the system message prefix, before the KB entries are added */
|
|
991
|
-
getContextPrefix(): Promise<
|
|
992
|
+
getContextPrefix(): Promise<string>;
|
|
992
993
|
/** Get system message to send to the AI */
|
|
993
994
|
onBeforeMessageProcessing(): Promise<void>;
|
|
994
995
|
private _lastOutput?;
|
|
@@ -1152,6 +1153,150 @@ interface KnowledgeBaseWebhookActionResponse {
|
|
|
1152
1153
|
updateItems?: KnowledgeBaseItem[];
|
|
1153
1154
|
}
|
|
1154
1155
|
|
|
1156
|
+
/**
|
|
1157
|
+
* Base class for custom Web Components, with some utility functions on it.
|
|
1158
|
+
*
|
|
1159
|
+
* Version 1.1
|
|
1160
|
+
* Created by: jjv360
|
|
1161
|
+
*/
|
|
1162
|
+
declare class BaseComponent extends HTMLElement {
|
|
1163
|
+
/** Attributes to monitor */
|
|
1164
|
+
static observedAttributes: string[];
|
|
1165
|
+
/** Component tag name */
|
|
1166
|
+
static tagName: string;
|
|
1167
|
+
/** True if this component is already registered */
|
|
1168
|
+
static _isRegistered: boolean;
|
|
1169
|
+
/** Contains the shadow DOM */
|
|
1170
|
+
_shadow?: ShadowRoot;
|
|
1171
|
+
/** Get the root node for this element's shadow DOM */
|
|
1172
|
+
get root(): ShadowRoot | undefined;
|
|
1173
|
+
/** Register the component */
|
|
1174
|
+
static register(): void;
|
|
1175
|
+
/** Create a new element of this type */
|
|
1176
|
+
static create(attrs?: any, content?: string): BaseComponent;
|
|
1177
|
+
/** Add the html for a component */
|
|
1178
|
+
static add(attrs?: any, content?: string): string;
|
|
1179
|
+
/** Create an element of this kind. Same as document.createElement(), but also ensures the component is registered. */
|
|
1180
|
+
static createElement(): HTMLElement;
|
|
1181
|
+
/** Called when the element is added to the DOM */
|
|
1182
|
+
connectedCallback(): void;
|
|
1183
|
+
/** Called when the element is removed */
|
|
1184
|
+
disconnectedCallback(): void;
|
|
1185
|
+
/** @abstract Get the HTML layout */
|
|
1186
|
+
html(): string;
|
|
1187
|
+
/** @abstract Called before the HTML is created for the first time */
|
|
1188
|
+
onBeforeCreate(): void;
|
|
1189
|
+
/** @abstract Called when the component is created */
|
|
1190
|
+
onCreate(): void;
|
|
1191
|
+
/** @abstract Called when the UI should be updated with the current values */
|
|
1192
|
+
onUpdate(): void;
|
|
1193
|
+
/** @abstract Called when the component is created */
|
|
1194
|
+
onDestroy(): void;
|
|
1195
|
+
/** @abstract Called when an observed attribute changes */
|
|
1196
|
+
attributeChangedCallback(name: string, oldValue: any, newValue: any): void;
|
|
1197
|
+
/** Internal attribute proxy */
|
|
1198
|
+
private _attrProxy?;
|
|
1199
|
+
/** Helper for getting attributes */
|
|
1200
|
+
get attr(): any;
|
|
1201
|
+
/** Internal for state */
|
|
1202
|
+
private _stateProxy?;
|
|
1203
|
+
private _state;
|
|
1204
|
+
/** Helper for state variables. When anything inside here changes, onUpdate is called. */
|
|
1205
|
+
get state(): any;
|
|
1206
|
+
/** Check if a child with the ID exists */
|
|
1207
|
+
hasChild(id: string): boolean;
|
|
1208
|
+
/** Get a child element by it's ID */
|
|
1209
|
+
child(id: string): BaseComponent;
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
/** Main embed web component */
|
|
1213
|
+
declare class WebWeaverEmbed extends BaseComponent {
|
|
1214
|
+
/** Element tag name */
|
|
1215
|
+
static tagName: string;
|
|
1216
|
+
/** Attributes we monitor for changes */
|
|
1217
|
+
static observedAttributes: string[];
|
|
1218
|
+
/** ChatGPT reference */
|
|
1219
|
+
ai: IntelliWeave;
|
|
1220
|
+
/** Currently loaded configuration */
|
|
1221
|
+
config: Partial<WebWeaverGPTConfig>;
|
|
1222
|
+
/** Responses the AI has suggested for the next user message */
|
|
1223
|
+
suggestions: string[];
|
|
1224
|
+
/** Constructor */
|
|
1225
|
+
constructor();
|
|
1226
|
+
/** Content */
|
|
1227
|
+
html: () => string;
|
|
1228
|
+
/** On create */
|
|
1229
|
+
onCreate(): void;
|
|
1230
|
+
private _lastLogo?;
|
|
1231
|
+
private _lastBackground?;
|
|
1232
|
+
private _lastTextColor?;
|
|
1233
|
+
/** Apply UI styles from config and attributes, prioritizing attributes */
|
|
1234
|
+
private applyConfigStylesAndAttributes;
|
|
1235
|
+
/** Called on update */
|
|
1236
|
+
onUpdate(): void;
|
|
1237
|
+
/** Called when the component is created */
|
|
1238
|
+
onDestroy(): void;
|
|
1239
|
+
/** Called when the container is clicked */
|
|
1240
|
+
onContainerClick(e: Event): void;
|
|
1241
|
+
/** Called when the logo is clicked */
|
|
1242
|
+
onLogoClick(e: Event): void;
|
|
1243
|
+
/** Open the interaction panel */
|
|
1244
|
+
open(): void;
|
|
1245
|
+
/** Close the interaction panel */
|
|
1246
|
+
close(): void;
|
|
1247
|
+
/** Reset conversation UI */
|
|
1248
|
+
resetConversation(): void;
|
|
1249
|
+
/** True if busy processing */
|
|
1250
|
+
private _isProcessing;
|
|
1251
|
+
/** Process input text from the user */
|
|
1252
|
+
processInput(inputText: string): Promise<void>;
|
|
1253
|
+
/** Called when the AI responds with some text */
|
|
1254
|
+
onAIMessage(msg: string): Promise<void>;
|
|
1255
|
+
/** Called when the AI starts running a tool */
|
|
1256
|
+
onAIToolStart(toolName: string, args: any): void;
|
|
1257
|
+
/** Called when a suggestion button is clicked */
|
|
1258
|
+
onSuggestionClick(e: Event, suggestion: string): void;
|
|
1259
|
+
/** Called when an LLM model is selected */
|
|
1260
|
+
onLLMModelSelect(e: CustomEvent): void;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** Utility to trim whitespace from blocks of text */
|
|
1264
|
+
declare function trimWhitespaceInText(text: string): string;
|
|
1265
|
+
/** Get the global object */
|
|
1266
|
+
declare function intelliweaveGlobalThis(): any;
|
|
1267
|
+
/**
|
|
1268
|
+
* Global type declarations for the IntelliWeave library
|
|
1269
|
+
*/
|
|
1270
|
+
interface IntelliWeaveGlobalConfig {
|
|
1271
|
+
apiKey?: string;
|
|
1272
|
+
analytics?: boolean;
|
|
1273
|
+
debug?: boolean;
|
|
1274
|
+
context?: string;
|
|
1275
|
+
introductionMessage?: string;
|
|
1276
|
+
introductionSuggestions?: string[];
|
|
1277
|
+
knowledgeBase?: KnowledgeBaseItem[];
|
|
1278
|
+
sources?: any[];
|
|
1279
|
+
offsetX?: number;
|
|
1280
|
+
offsetY?: number;
|
|
1281
|
+
userID?: string;
|
|
1282
|
+
hubAPI?: string;
|
|
1283
|
+
backgroundColor?: string;
|
|
1284
|
+
/** Extra data that will be passed to external knowledge base actions. */
|
|
1285
|
+
extra: any;
|
|
1286
|
+
/** @deprecated Override the AI system context prefix. This should be controlled from the Hub now. */
|
|
1287
|
+
pageSummary?: string | (() => string) | (() => Promise<string>);
|
|
1288
|
+
/** List of knowledge base sources */
|
|
1289
|
+
knowledgeBaseSources?: KnowledgeBaseSource[];
|
|
1290
|
+
/** When the built-in UI is used, this contains the instance being rendered on the page */
|
|
1291
|
+
embed?: WebWeaverEmbed;
|
|
1292
|
+
}
|
|
1293
|
+
/** Get the global IntelliWeave configuration object that has been created for this document, or create it if necessary. */
|
|
1294
|
+
declare function intelliweaveConfig(): IntelliWeaveGlobalConfig;
|
|
1295
|
+
/** An async generator which yields events from an SSE fetch request body (a readable stream) */
|
|
1296
|
+
declare function sseEvents(stream: ReadableStream<Uint8Array>): AsyncGenerator<any, void, unknown>;
|
|
1297
|
+
/** Get or create a user ID for this device. */
|
|
1298
|
+
declare function getDefaultUserID(): string;
|
|
1299
|
+
|
|
1155
1300
|
/** Class to help with logging */
|
|
1156
1301
|
declare class Logging {
|
|
1157
1302
|
/** Current module */
|
|
@@ -1161,7 +1306,7 @@ declare class Logging {
|
|
|
1161
1306
|
/** Enable debug logging */
|
|
1162
1307
|
static debug: boolean;
|
|
1163
1308
|
/** Check if verbose logging is enabled */
|
|
1164
|
-
get debugEnabled():
|
|
1309
|
+
get debugEnabled(): boolean | undefined;
|
|
1165
1310
|
/** Log a message */
|
|
1166
1311
|
log(...args: any[]): void;
|
|
1167
1312
|
/** Debug message */
|
|
@@ -1227,4 +1372,4 @@ interface IntelliWeaveStreamTextOutputEvent extends IntelliWeaveStreamEvent {
|
|
|
1227
1372
|
text: string;
|
|
1228
1373
|
}
|
|
1229
1374
|
|
|
1230
|
-
export { type BufferType, BufferedWebSocket, ChatGPT, type ChatGPTConfig, type ChatGPTMessage, type ChatGPTToolConfig, FixedBufferStream, IntelliWeave, IntelliWeaveStream, type IntelliWeaveStreamErrorEvent, type IntelliWeaveStreamEvent, type IntelliWeaveStreamTextOutputEvent, KnowledgeBase, type KnowledgeBaseItem, type KnowledgeBaseSource, type KnowledgeBaseWebhookActionResponse, type KnowledgeBaseWebhookRequest, type KnowledgeBaseWebhookSearchResponse, Logging, ONNXModel, type ONNXTensors, Resampler, type SupportedArrayBuffers, TokenWindow, TokenWindowGroup, type TokenWindowGroupItem, type WebWeaverGPTConfig, audioToWav, floatTo16BitPCM, floatTo64BitPCM, getDefaultUserID, int16ToFloat32BitPCM, intelliweaveConfig, intelliweaveGlobalThis, sseEvents, trimWhitespaceInText };
|
|
1375
|
+
export { type BufferType, BufferedWebSocket, ChatGPT, type ChatGPTConfig, type ChatGPTMessage, type ChatGPTToolConfig, FixedBufferStream, IntelliWeave, type IntelliWeaveGlobalConfig, IntelliWeaveStream, type IntelliWeaveStreamErrorEvent, type IntelliWeaveStreamEvent, type IntelliWeaveStreamTextOutputEvent, KnowledgeBase, type KnowledgeBaseItem, type KnowledgeBaseSource, type KnowledgeBaseWebhookActionResponse, type KnowledgeBaseWebhookRequest, type KnowledgeBaseWebhookSearchResponse, Logging, ONNXModel, type ONNXTensors, Resampler, type SupportedArrayBuffers, TokenWindow, TokenWindowGroup, type TokenWindowGroupItem, type WebWeaverGPTConfig, audioToWav, floatTo16BitPCM, floatTo64BitPCM, getDefaultUserID, int16ToFloat32BitPCM, intelliweaveConfig, intelliweaveGlobalThis, sseEvents, trimWhitespaceInText };
|
package/dist/node/node.js
CHANGED
|
@@ -1,26 +1,32 @@
|
|
|
1
|
-
import{v4 as
|
|
1
|
+
import{v4 as G}from"uuid";function P(c){let t=(c||"").split(`
|
|
2
2
|
`);for(;t.length>0&&t[0].trim()=="";)t.shift();for(;t.length>0&&t[t.length-1].trim()=="";)t.pop();let e=1/0;for(let s of t){let n=s.match(/^\s*/)?.[0].length||0;e=Math.min(e,n)}return e>0&&e<1/0&&(t=t.map(s=>s.substring(e))),t.join(`
|
|
3
|
-
`)}var
|
|
3
|
+
`)}var J={};function I(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:J}function g(){return I().intelliweave=I().intelliweave||I().webWeaver||{},I().intelliweave}async function*_(c){let t="",e=function*(){for(;;){let i=t.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);if(i==-1)break;let u=t.slice(0,i);t=t.slice(i+2);let l={},r=u.split(`
|
|
6
6
|
`);for(let o of r){i=o.indexOf(": ");let a=o.slice(0,i),d=o.slice(i+2);i==-1&&(a=o,d=""),a&&(l[a]!==void 0?l[a]+=`
|
|
7
7
|
`+d:l[a]=d)}yield l}},s=new TextDecoder,n=c.getReader();for(;;){let{done:i,value:u}=await n.read();if(i)break;t+=s.decode(u,{stream:!0}),yield*e()}t+=s.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function K(){if(g().userID)return g().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=
|
|
10
|
-
`;this.itemPadding=0;this.sortFunction=(t,e)=>t.sortOrder!==e.sortOrder?t.sortOrder-e.sortOrder:t.dateAdded!==e.dateAdded?t.dateAdded-e.dateAdded:t.content.localeCompare(e.content)}setItemPadding(t){return this.itemPadding=t,this.recalculateTokens(),this}sortBy(t){return this.sortFunction=t,this.items.sort(this.sortFunction),this}setSeparator(t){return this.separator==t?this:(this.separator=t,this.recalculateTokens(),this)}setWeight(t){return this.weight=t,this}recalculateTokens(){this.tokenCount=this.items.reduce((t,e)=>(e.tokenCount=
|
|
9
|
+
`,yield*e()}function K(){if(g().userID)return g().userID||"";if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=G(),localStorage.setItem("intelliweave.uid",c),c)}else return G()}var k=class k{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return k.debug?!0:typeof window<"u"&&g().debug}log(...t){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...t)}debug(...t){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...t)}info(...t){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...t)}warn(...t){console.warn(`[IntelliWeave > ${this.module}]`,...t)}error(...t){console.error(`[IntelliWeave > ${this.module}]`,...t)}timer(t,...e){let s=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...n)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...n)}};k.debug=!1;var p=k;var y=new p("ONNXModel"),N=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,y.debug(`Model input parameters: ${t.inputNames.join(", ")}`),y.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!c.lib}static async load(t){if(!c.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(y.debug("Loading ONNX runtime"),this.onnx=await c.lib()),y.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let n=1;for(let u of e)n*=u;let i;if(t=="float32")i=new c.onnx.Tensor(new Float32Array(n),e);else if(t=="int8")i=new c.onnx.Tensor(new Int8Array(n),e);else if(t=="int16")i=new c.onnx.Tensor(new Int16Array(n),e);else if(t=="int32")i=new c.onnx.Tensor(new Int32Array(n),e);else if(t=="int64")i=new c.onnx.Tensor(new BigInt64Array(n),e);else if(t=="uint8")i=new c.onnx.Tensor(new Uint8Array(n),e);else if(t=="uint16")i=new c.onnx.Tensor(new Uint16Array(n),e);else if(t=="uint32")i=new c.onnx.Tensor(new Uint32Array(n),e);else if(t=="uint64")i=new c.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?i.data.fill(BigInt(s)):s!==0&&i.data.fill(s),i}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,s,n=0){return this.registerConstant(t,this.makeTensor(e,s,n))}registerState(t,e,s){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:s},s}makeState(t,e,s,n,i=0){return this.registerState(t,e,this.makeTensor(s,n,i))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return y.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let s in this.stateTensors){let n=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=n}return e}finally{this._runActive=!1}}resetState(){y.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function se(c,t){let e=t.reduce((r,o)=>r+o.byteLength,0),s=new DataView(new ArrayBuffer(44));s.setUint8(0,82),s.setUint8(1,73),s.setUint8(2,70),s.setUint8(3,70),s.setUint32(4,44+e,!0),s.setUint8(8,87),s.setUint8(9,65),s.setUint8(10,86),s.setUint8(11,69);let n=1,i=32,u=n*i/8,l=c*u;return s.setUint8(12,102),s.setUint8(13,109),s.setUint8(14,116),s.setUint8(15,32),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,n,!0),s.setUint32(24,c,!0),s.setUint32(28,l,!0),s.setUint16(32,u,!0),s.setUint16(34,i,!0),s.setUint8(36,100),s.setUint8(37,97),s.setUint8(38,116),s.setUint8(39,97),s.setUint32(40,e,!0),new File([s,...t],"audio.wav",{type:"audio/wav"})}var $=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var R=class{constructor(t,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!t)throw new Error(`Invalid array class: ${t}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=t,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((t,e)=>t+e.length,0)}feed(t){this.partialBuffers.push(t)}get canDrain(){return this.partialBuffers.reduce((e,s)=>e+s.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let t=this.ArrayClass,e=new t(this.outputBufferSize),s=0;for(;s!=e.length;){if(s>e.length)throw new Error(`Buffer overflow: ${s} > ${e.length}`);let n=e.length-s,i=this.partialBuffers[0],u=i.length-this.partialBufferOffset;u<n?(e.set(i.subarray(this.partialBufferOffset),s),s+=u,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(i.subarray(this.partialBufferOffset,this.partialBufferOffset+n),s),s+=n,this.partialBufferOffset+=n)}return e}pad(){let t=this.queuedSize%this.outputBufferSize;if(t==0)return;let e=this.ArrayClass,s=new e(t);this.feed(s)}};var U=class{constructor(t,e,s,n){if(!t||!e||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=s||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=t=>t,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(t){try{return this.outputBuffer.subarray(0,t)}catch{try{return this.outputBuffer.length=t,this.outputBuffer}catch{return this.outputBuffer.slice(0,t)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=t=>{let e=t.length,s=this.channels,n,i,u,l,r,o,a,d,h;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,i=this.ratioWeight,u=this.lastWeight,l=0,r=0,o=0,a=0,d=this.outputBuffer;u<1;u+=i)for(r=u%1,l=1-r,this.lastWeight=u%1,h=0;h<this.channels;++h)d[a++]=this.lastOutput[h]*l+t[h]*r;for(u-=1,e-=s,o=Math.floor(u)*s;a<n&&o<e;){for(r=u%1,l=1-r,h=0;h<this.channels;++h)d[a++]=t[o+(h>0?h:0)]*l+t[o+(s+h)]*r;u+=i,o=Math.floor(u)*s}for(h=0;h<s;++h)this.lastOutput[h]=t[o++];return this.bufferSlice(a)}}multiTap(){this.resampler=t=>{let e=t.length,s,n,i=this.channels,u,l,r,o,a,d,h,b,x;if(e%i!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=[],u=this.ratioWeight,l=0,o=0,a=0,d=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,b=0,x=0,r=0;r<i;++r)n[r]=0;do{if(d)for(l=u,r=0;r<i;++r)n[r]=0;else{for(l=this.lastWeight,r=0;r<i;++r)n[r]=this.lastOutput[r];d=!0}for(;l>0&&o<e;)if(a=1+o-x,l>=a){for(r=0;r<i;++r)n[r]+=t[o++]*a;x=o,l-=a}else{for(r=0;r<i;++r)n[r]+=t[o+(r>0?r:0)]*l;x+=l,l=0;break}if(l===0)for(r=0;r<i;++r)h[b++]=n[r]/u;else{for(this.lastWeight=l,r=0;r<i;++r)this.lastOutput[r]=n[r];this.tailExists=!0;break}}while(o<e&&b<s);return this.bufferSlice(b)}}resample(t){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(t)}};function oe(c){let t=c.length,e=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=s<0?s*32768:s*32767}return e}function ae(c){let t=c.length,e=new BigInt64Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return e}function le(c){let t=c.length,e=new Float32Array(t);for(;t--;){let s=c[t];e[t]=s>=32768?-(65536-s)/32768:s/32767}return e}import{countTokens as T}from"gpt-tokenizer";import{v4 as q}from"uuid";var C=class{constructor(){this.size=4096;this.groups=[]}createGroup(t){let e=new O;return e.id=t,this.groups.push(e),e}group(t){return this.groups.find(e=>e.id===t)}countTokens(){return this.groups.reduce((t,e)=>t+e.tokenCount,0)}removeOverflow(){let t=this.countTokens(),e=this.groups.reduce((s,n)=>s+n.weight,0);for(;t>this.size;){let s=this.groups.slice().sort((i,u)=>{let l=Math.floor(i.weight/e*this.size),r=Math.floor(u.weight/e*this.size),o=i.tokenCount-l;return u.tokenCount-r-o}),n=this.removeOneItem(s);if(!n)throw new Error("Too many items in the token window that cannot be removed.");t-=n.tokenCount}}removeOneItem(t){for(let e of t){let s=e.items.findIndex(i=>!i.cannotRemove);if(s===-1)continue;let n=e.items[s];return e.items.splice(s,1),e.tokenCount-=n.tokenCount,n}return null}},O=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
|
+
`;this.itemPadding=0;this.sortFunction=(t,e)=>t.sortOrder!==e.sortOrder?t.sortOrder-e.sortOrder:t.dateAdded!==e.dateAdded?t.dateAdded-e.dateAdded:t.content.localeCompare(e.content)}setItemPadding(t){return this.itemPadding=t,this.recalculateTokens(),this}sortBy(t){return this.sortFunction=t,this.items.sort(this.sortFunction),this}setSeparator(t){return this.separator==t?this:(this.separator=t,this.recalculateTokens(),this)}setWeight(t){return this.weight=t,this}recalculateTokens(){this.tokenCount=this.items.reduce((t,e)=>(e.tokenCount=T(e.content)+T(this.separator)+this.itemPadding,t+e.tokenCount),0)}add(t){typeof t=="string"&&(t={content:t});let e=t;e.id===void 0&&(e.id=q());let s=this.items.find(n=>n.id===e.id);return s?(this.tokenCount-=s.tokenCount,Object.assign(s,e),e=s):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.tokenCount=e.disabled?0:T(t.content)+T(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(t=>t.content).join(this.separator)}getAll(){return this.items.filter(t=>!t.disabled)}empty(){this.items=[],this.tokenCount=0}};var v=1,m=new p("ChatGPT"),S=class{constructor(t){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let t=new C;return t.createGroup("context").setSeparator(`
|
|
11
11
|
|
|
12
|
-
`),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config={...this.config,...t},this.tokenWindow.size=this.config.maxTokens||4096}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(e),customData:e}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(t=>t.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),m.debugEnabled&&m.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(s=>s.customData),messages:this.messageGroup.items.map(s=>s.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let s of e.tool_calls)await this.processToolCall(s);await this.processMessages()}}async trimMessages(){for(this.tokenWindow.removeOverflow();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendToAPI(t){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let r=this.messageGroup.items.length-1;r>=0;r--){let o=this.messageGroup.items[r].customData;if(o.role=="assistant"&&o.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(o.role=="user")break}m.debugEnabled&&m.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(r=>r.customData),messages:this.messageGroup.items.map(r=>r.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(r=>r.customData)]};for(let r of this.toolGroup.getAll()){let o=r.customData;o.description&&o.description.length>1024&&m.warn(`Tool description for "${o.name}" is too long, it will be truncated.`);let a={type:"function",function:{name:o.name,description:(o.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(o.params))for(let d of o.params)a.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(o.params){let d=o.params;for(let h in d)a.function.parameters.properties[h]={type:"string",description:d[h]}}s.tools.push(a)}s.user||delete s.user,s.tools.length||delete s.tools;let n={};if(n["Content-Type"]="application/json",this.config.apiKey&&(n.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let i=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:n,body:JSON.stringify(s)});if(!i.ok){let r=`${i.status} ${i.statusText}`;try{let a=await i.json();r=a.errorText||a.error?.message||a.error||r}catch{}let o=new Error(r);throw o.code=i.status,o}let u=null,l=null;if(this.config.stream)for await(let r of _(i.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let o=JSON.parse(r.data);if(l){for(let a in o.choices[0].delta)if(typeof o.choices[0].delta[a]=="string"){if(a=="role"&&l[a]==o.choices[0].delta[a])continue;l[a]=(l[a]||"")+o.choices[0].delta[a]}for(let a of o.choices[0].delta.tool_calls||[]){if(l.tool_calls||(l.tool_calls=[]),!l.tool_calls[a.index]){l.tool_calls[a.index]=a;continue}let d=l.tool_calls[a.index];d.function=d.function||{},d.function.name=(d.function.name||"")+(a.function?.name||""),d.function.arguments=(d.function.arguments||"")+(a.function?.arguments||"")}}else l={chunkID:o.id,...o.choices[0].delta};l?.content&&!l.content.startsWith("{")&&this.config.onAIMessage?.(l.content,!0)}else u=await i.json(),this.stats.tokensUsed+=u.usage?.total_tokens||0,m.debug(`Used ${u.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),l=u.choices?.[0]?.message;if(l||(m.warn("No response block in API response."),l={role:"assistant",content:""}),l.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(l),this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(l),customData:l}),l.content&&this.config.onAIMessage?.(l.content,!1)}processIncomingMessage(t){}registerTool(t){this.toolGroup.add({id:t.name,cannotRemove:!t.canRemove,content:JSON.stringify(t),customData:t})}async processToolCall(t){try{let s=this.toolGroup.items.find(l=>l.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let n=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,n);let i=await s.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let u={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(u),customData:u})}catch(e){m.warn(`Unable to process tool call for "${t?.function?.name}"`,e);let s={role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(s),customData:s})}}resetConversation(){this.messageGroup.empty()}};import H from"minisearch";var j=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(c,t)=>{let e=await t.knowledgeBase.search(c.query),s=t;s._lastKBsearch=c.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let n=e.filter(u=>u.type!="action").map(u=>"id="+u.id).join(", ")||"(none)",i=e.filter(u=>u.type=="action").map(u=>"name="+u._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${i}.`}}];var w=new f("KnowledgeBase"),F=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>j}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${F++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return typeof window<"u"&&g().knowledgeBaseSources&&(t=t.concat(g().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){w.debug(`Searching knowledge base for: ${t}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=t,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let n=(await Promise.all(this.sources.map(async r=>{try{let o=Date.now(),a=await r.query(t);return w.debug(`Source '${r.id}' took ${Date.now()-o}ms`),a||[]}catch(o){return w.warn(`Knowledge source '${r.id}' failed:`,o),[]}}))).flat();n=n.concat(e.entries),n=n.concat(this.manualEntries),g().knowledgeBase&&(n=n.concat(g().knowledgeBase)),n=n.filter(r=>r&&!r.disabled);for(let r=0;r<n.length;r++){let o=n[r];if(o.id=o.id||`temp.${r}`,o._functionID=o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!o.action&&o.type=="tour"&&(o.action=a=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!o.action&&o.type=="info"&&(o.action=a=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),o.parameters&&!Array.isArray(o.parameters)){let a=o.parameters,d=[];for(let h in a)d.push({name:h,type:"string",description:o.parameters[h]});o.parameters=d}}let i=new H({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});i.addAll(n);let l=i.search(t).map(r=>n.find(o=>o.id==r.id));for(let r of n)r.isContext&&(l.find(o=>o.id===r.id)||l.push(r));return this.lastResults=l,w.debug("Found results:",l),l}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${F++}`),w.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,u=async(r,o)=>{w.debug(`Calling remote knowledge base action: ${r.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:r.id,parameters:o},d=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return l(h.updateItems||[]),h.response},l=r=>{for(let o of r){if(!o.id){w.warn("KB item skipped since it has no ID.",o);continue}let a=s.find(d=>d.id==o.id);if(a){a.name=o.name||a.name||"",a.content=o.content||a.content||"",a.disabled=o.disabled??a.disabled,a.isContext=o.isContext??a.isContext,a.parameters=o.parameters||a.parameters||[],a.tags=o.tags||a.tags,a.type=o.type||a.type;continue}s.push({...o,action:d=>u(o,d)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let o={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:r},a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let d=await a.json();return i=!d.noCache,n.includes(r)||n.push(r),l(d.items),s})}clone(){let t=new c(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}};import{v4 as M}from"uuid";var q={name:"@intelliweave/embedded",version:"1.7.58",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var B=class{constructor(t){this.ai=t}async boolean(t,e){let s=this.ai.clone();s.resetConversation(),s.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let n=await s.sendMessage(t+`
|
|
12
|
+
`),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config={...this.config,...t},this.tokenWindow.size=this.config.maxTokens||4096}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(e),customData:e}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(t=>t.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),m.debugEnabled&&m.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(s=>s.customData),messages:this.messageGroup.items.map(s=>s.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let s of e.tool_calls)await this.processToolCall(s);await this.processMessages()}}async trimMessages(){for(this.tokenWindow.removeOverflow();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendToAPI(t){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let r=this.messageGroup.items.length-1;r>=0;r--){let o=this.messageGroup.items[r].customData;if(o.role=="assistant"&&o.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(o.role=="user")break}m.debugEnabled&&m.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(r=>r.customData),messages:this.messageGroup.items.map(r=>r.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(r=>r.customData)]};for(let r of this.toolGroup.getAll()){let o=r.customData;o.description&&o.description.length>1024&&m.warn(`Tool description for "${o.name}" is too long, it will be truncated.`);let a={type:"function",function:{name:o.name,description:(o.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(o.params))for(let d of o.params)a.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(o.params){let d=o.params;for(let h in d)a.function.parameters.properties[h]={type:"string",description:d[h]}}s.tools.push(a)}s.user||delete s.user,s.tools.length||delete s.tools;let n={};if(n["Content-Type"]="application/json",this.config.apiKey&&(n.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let i=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:n,body:JSON.stringify(s)});if(!i.ok){let r=`${i.status} ${i.statusText}`;try{let a=await i.json();r=a.errorText||a.error?.message||a.error||r}catch{}let o=new Error(r);throw o.code=i.status,o}let u=null,l=null;if(this.config.stream)for await(let r of _(i.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let o=JSON.parse(r.data);if(l){for(let a in o.choices[0].delta)if(typeof o.choices[0].delta[a]=="string"){if(a=="role"&&l[a]==o.choices[0].delta[a])continue;l[a]=(l[a]||"")+o.choices[0].delta[a]}for(let a of o.choices[0].delta.tool_calls||[]){if(l.tool_calls||(l.tool_calls=[]),!l.tool_calls[a.index]){l.tool_calls[a.index]=a;continue}let d=l.tool_calls[a.index];d.function=d.function||{},d.function.name=(d.function.name||"")+(a.function?.name||""),d.function.arguments=(d.function.arguments||"")+(a.function?.arguments||"")}}else l={chunkID:o.id,...o.choices[0].delta};l?.content&&!l.content.startsWith("{")&&this.config.onAIMessage?.(l.content,!0)}else u=await i.json(),this.stats.tokensUsed+=u.usage?.total_tokens||0,m.debug(`Used ${u.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),l=u.choices?.[0]?.message;if(l||(m.warn("No response block in API response."),l={role:"assistant",content:""}),l.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(l),this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(l),customData:l}),l.content&&this.config.onAIMessage?.(l.content,!1)}processIncomingMessage(t){}registerTool(t){this.toolGroup.add({id:t.name,cannotRemove:!t.canRemove,content:JSON.stringify(t),customData:t})}async processToolCall(t){try{let s=this.toolGroup.items.find(l=>l.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let n=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,n);let i=await s.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let u={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(u),customData:u})}catch(e){m.warn(`Unable to process tool call for "${t?.function?.name}"`,e);let s={role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+v++,content:JSON.stringify(s),customData:s})}}resetConversation(){this.messageGroup.empty()}};import H from"minisearch";var j=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(c,t)=>{let e=await t.knowledgeBase.search(c.query),s=t;s._lastKBsearch=c.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let n=e.filter(u=>u.type!="action").map(u=>"id="+u.id).join(", ")||"(none)",i=e.filter(u=>u.type=="action").map(u=>"name="+u._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${i}.`}}];var w=new p("KnowledgeBase"),F=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>j}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${F++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return g().knowledgeBaseSources&&(t=t.concat(g().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){w.debug(`Searching knowledge base for: ${t}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=t,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let n=(await Promise.all(this.sources.map(async r=>{try{let o=Date.now(),a=await r.query(t);return w.debug(`Source '${r.id}' took ${Date.now()-o}ms`),a||[]}catch(o){return w.warn(`Knowledge source '${r.id}' failed:`,o),[]}}))).flat();n=n.concat(e.entries),n=n.concat(this.manualEntries),g().knowledgeBase&&(n=n.concat(g().knowledgeBase)),n=n.filter(r=>r&&!r.disabled);for(let r=0;r<n.length;r++){let o=n[r];if(o.id=o.id||`temp.${r}`,o._functionID=o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!o.action&&o.type=="tour"&&(o.action=a=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!o.action&&o.type=="info"&&(o.action=a=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),o.parameters&&!Array.isArray(o.parameters)){let a=o.parameters,d=[];for(let h in a)d.push({name:h,type:"string",description:o.parameters[h]});o.parameters=d}}let i=new H({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});i.addAll(n);let l=i.search(t).map(r=>n.find(o=>o.id==r.id));for(let r of n)r.isContext&&(l.find(o=>o.id===r.id)||l.push(r));return this.lastResults=l,w.debug("Found results:",l),l}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${F++}`),w.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,u=async(r,o)=>{w.debug(`Calling remote knowledge base action: ${r.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:r.id,parameters:o},d=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return l(h.updateItems||[]),h.response},l=r=>{for(let o of r){if(!o.id){w.warn("KB item skipped since it has no ID.",o);continue}let a=s.find(d=>d.id==o.id);if(a){a.name=o.name||a.name||"",a.content=o.content||a.content||"",a.disabled=o.disabled??a.disabled,a.isContext=o.isContext??a.isContext,a.parameters=o.parameters||a.parameters||[],a.tags=o.tags||a.tags,a.type=o.type||a.type;continue}s.push({...o,action:d=>u(o,d)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let o={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:r},a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let d=await a.json();return i=!d.noCache,n.includes(r)||n.push(r),l(d.items),s})}clone(){let t=new c(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}};import{v4 as M}from"uuid";var z={name:"@intelliweave/embedded",version:"1.8.60",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var B=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
Reply only with one of the following options:
|
|
17
|
+
${t.options.map(s=>`- "${s}"`).join(`
|
|
18
|
+
`)}
|
|
17
19
|
|
|
18
|
-
options
|
|
19
|
-
|
|
20
|
+
Do not include any additional text or explanations.`});return t.options.includes(e)?e:t.options.find(s=>e.toLowerCase().includes(s.toLowerCase()))}async extract(t){let e=`
|
|
21
|
+
You will receive some data. Extraction instructions: ${t.instruction}
|
|
20
22
|
|
|
21
|
-
|
|
23
|
+
${t.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
|
|
22
24
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
Objects should have the following keys:
|
|
26
|
+
${t.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
|
|
27
|
+
`)}
|
|
28
|
+
`,s=await this.instruct({...t,instruction:e});if(s=s.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),t.allowMultiple){let n=s.split(`
|
|
29
|
+
`).map(u=>u.trim()).filter(u=>!!u.trim()),i=[];for(let u of n)try{i.push(JSON.parse(u))}catch(l){console.error("Failed to parse line as JSON:",u,l.message)}return i}else return[JSON.parse(s.trim())]}async generateMarkdown(t){return this.instruct({...t,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(t){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>t.instruction,t.callback&&e.addEventListener("output",s=>{t.callback(s.detail.message)}),t.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof t.data=="string"?t.data:JSON.stringify(t.data))||""}};var f=new p("Main"),D=class D extends EventTarget{constructor(){super(...arguments);this.conversationID=M();this.knowledgeBase=new E(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new B(this);this.userID=K();this.extra=g().extra||{};this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1}get loaded(){return!!(this.config&&this.currentModel)}async load(e){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{f.debug("Loading configuration...");let s=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!s.ok)throw new Error(`Failed to load configuration: ${s.status} ${s.statusText}`);try{this.config=await s.json(),f.debug("Config loaded successfully:",this.config),this.config&&f.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(n){f.error("Failed to parse JSON response:",n);try{let i=await s.clone().text();f.error("Raw response that failed parsing:",i)}catch{f.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${n}`)}})(),(async()=>{try{let s=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!s.ok)throw new Error(`Failed to load VAD model: ${s.status} ${s.statusText}`);this.vadModel=await s.blob()}catch(s){f.warn(`Failed to load VAD model, some features will be unavailable. ${s.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let s of this.config.knowledge||[])s.url&&this.knowledgeBase.registerSourceFromURL(s.url);for(let s of this.config.knowledge||[])s.entries?.length&&this.knowledgeBase.registerSource(s.id,()=>s.entries||[]);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(s){throw f.warn("Failed to load:",s),this.error=s,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:s}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:s}})),s}}setModel(e){let s=this.models.find(n=>n.id==e);if(!s)throw new Error(`Model with ID "${e}" not found.`);this.currentModel=new S({...s.config,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(n,i)=>{let u=this.knowledgeBase.getCachedEntry(n);this.onAIToolStart?.(u?.id||n,i)}}),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let e=g().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:e}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,content:'You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time). Current info and tour items:'});let s=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;for(let i of s)if(i.type=="info"||i.type=="tour"||i.type=="input-event")this.currentModel.contextGroup.add({id:i.id,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify({id:i.id,type:i.type,name:i.name,content:P(typeof i.content=="function"?i.content():i.content)})+`
|
|
30
|
+
`});else if(i.type=="action"){let u={name:i._functionID,description:P(typeof i.content=="function"?i.content():i.content),params:i.parameters||[{name:"value",type:"string",description:"Input"}],removeFromMessageHistory:!!i.removeFromMessageHistory,callback:l=>this.toolRunKBAction(i,l),kb:i};this.currentModel.toolGroup.add({id:i._functionID,customData:u,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify(u)})}else continue;let n=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=n&&(this._lastSystemMsg=n,this.submitAnalyticsEvent({type:"system-msg",txt:n}))}processIncomingMessage(e,s){s||this.submitAnalyticsEvent({type:"message",role:"assistant",message:e});let n="";this._lastOutput===void 0?(n=e,this._lastOutput=e):e.startsWith(this._lastOutput)?(n=e.substring(this._lastOutput.length),this._lastOutput=e):(f.warn("Message was changed during chunking. This should not happen.",e,this._lastOutput),n=e,this._lastOutput=e),s||(this._lastOutput=void 0),this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:s,message:e,messageChunk:n}})),this.onAIMessage?.(e,!!s)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return f.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{return this.submitAnalyticsEvent({type:"message",role:"user",message:e}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),await this.currentModel.sendMessage(e)}finally{this.isProcessing=!1}}async toolRunKBAction(e,s){try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:s,ai:this}}));let n=await e.action(s,this);return this.submitAnalyticsEvent({type:"action",action:e.id,value:s,result:n}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,result:n}})),n}catch(n){throw this.submitAnalyticsEvent({type:"action",action:e.id,value:s,error:n.message}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,error:n}})),n}}submitAnalyticsEvent(e){g().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(s=>{f.debug("Failed to submit analytics event:",s)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this.conversationID=M(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");let s={role:"assistant",content:e};this.currentModel.messageGroup.add({id:M(),content:JSON.stringify(s),customData:s})}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let s of e.messages)this.currentModel.messageGroup.add({id:M(),content:JSON.stringify(s),customData:s})}clone(){let e=new D;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.extra=this.extra,e.knowledgeBase=this.knowledgeBase.clone(),e}};D.version=z.version;var A=D;var W=new p("Stream"),L=class extends A{constructor(){super(...arguments);this.pendingEvents=[];this._isProcessingEvents=!1}async getContextPrefix(){let e=`You will receive an event stream, a list of JSON objects, one on each line. Respond with tool calls only and no text output.
|
|
25
31
|
|
|
26
|
-
`;return e+=await super.getContextPrefix(),e}postEvent(e){if(!e.eventName)throw new Error("Missing event name");if(e.direction||(e.direction="input"),e.direction!="input")throw new Error('Invalid event direction, must be "input".');e.timestamp||(e.timestamp=Date.now()),e.timestampDate=new Date(e.timestamp).toString(),
|
|
32
|
+
`;return e+=await super.getContextPrefix(),e}postEvent(e){if(!e.eventName)throw new Error("Missing event name");if(e.direction||(e.direction="input"),e.direction!="input")throw new Error('Invalid event direction, must be "input".');e.timestamp||(e.timestamp=Date.now()),e.timestampDate=new Date(e.timestamp).toString(),W.log("Event in",JSON.stringify(e)),this.pendingEvents.push(e),this.processEvents()}async toolRunKBAction(e,s){if(e.type!="output-event")return await super.toolRunKBAction(e,s);this.emitEvent({...s,eventName:e.id,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}emitEvent(e){W.log("Event out",JSON.stringify(e)),this.dispatchEvent(new CustomEvent("event",{detail:{ai:this,event:e}}))}async processEvents(){if(!this._isProcessingEvents){this._isProcessingEvents=!0;try{let e=this.pendingEvents.shift();if(!e)return;let s=this.knowledgeBase.getCachedEntry(e.eventName);s&&(e.assistantHint=typeof s.content=="function"?s.content():s.content);let n=JSON.stringify(e),i=await this.sendMessage(n)||"";if(!i.trim())return;this.emitEvent({eventName:"text",text:i,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}catch(e){W.error("Error processing events:",e),this.emitEvent({eventName:"error",timestamp:Date.now(),timestampDate:new Date().toString(),errorMessage:e.message,direction:"output"})}finally{this._isProcessingEvents=!1,this.pendingEvents.length>0&&this.processEvents()}}}};export{$ as BufferedWebSocket,S as ChatGPT,R as FixedBufferStream,A as IntelliWeave,L as IntelliWeaveStream,E as KnowledgeBase,p as Logging,N as ONNXModel,U as Resampler,C as TokenWindow,O as TokenWindowGroup,se as audioToWav,oe as floatTo16BitPCM,ae as floatTo64BitPCM,K as getDefaultUserID,le as int16ToFloat32BitPCM,g as intelliweaveConfig,I as intelliweaveGlobalThis,_ as sseEvents,P as trimWhitespaceInText};
|