@intelliweave/embedded 1.7.58 → 1.7.59
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 +6 -3
- package/dist/component/component.js +20 -16
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +147 -14
- package/dist/node/node.js +4 -4
- package/dist/react/react.d.ts +1 -1
- package/dist/react/react.js +22 -18
- package/dist/script-tag/script-tag.js +25 -21
- package/dist/webpack/index.d.ts +119 -90
- package/dist/webpack/index.js +21 -17
- 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
|
*/
|
|
@@ -988,7 +977,7 @@ declare class IntelliWeave extends EventTarget {
|
|
|
988
977
|
setModel(id: string): void;
|
|
989
978
|
private _lastSystemMsg;
|
|
990
979
|
/** Get the system message prefix, before the KB entries are added */
|
|
991
|
-
getContextPrefix(): Promise<
|
|
980
|
+
getContextPrefix(): Promise<string>;
|
|
992
981
|
/** Get system message to send to the AI */
|
|
993
982
|
onBeforeMessageProcessing(): Promise<void>;
|
|
994
983
|
private _lastOutput?;
|
|
@@ -1152,6 +1141,150 @@ interface KnowledgeBaseWebhookActionResponse {
|
|
|
1152
1141
|
updateItems?: KnowledgeBaseItem[];
|
|
1153
1142
|
}
|
|
1154
1143
|
|
|
1144
|
+
/**
|
|
1145
|
+
* Base class for custom Web Components, with some utility functions on it.
|
|
1146
|
+
*
|
|
1147
|
+
* Version 1.1
|
|
1148
|
+
* Created by: jjv360
|
|
1149
|
+
*/
|
|
1150
|
+
declare class BaseComponent extends HTMLElement {
|
|
1151
|
+
/** Attributes to monitor */
|
|
1152
|
+
static observedAttributes: string[];
|
|
1153
|
+
/** Component tag name */
|
|
1154
|
+
static tagName: string;
|
|
1155
|
+
/** True if this component is already registered */
|
|
1156
|
+
static _isRegistered: boolean;
|
|
1157
|
+
/** Contains the shadow DOM */
|
|
1158
|
+
_shadow?: ShadowRoot;
|
|
1159
|
+
/** Get the root node for this element's shadow DOM */
|
|
1160
|
+
get root(): ShadowRoot | undefined;
|
|
1161
|
+
/** Register the component */
|
|
1162
|
+
static register(): void;
|
|
1163
|
+
/** Create a new element of this type */
|
|
1164
|
+
static create(attrs?: any, content?: string): BaseComponent;
|
|
1165
|
+
/** Add the html for a component */
|
|
1166
|
+
static add(attrs?: any, content?: string): string;
|
|
1167
|
+
/** Create an element of this kind. Same as document.createElement(), but also ensures the component is registered. */
|
|
1168
|
+
static createElement(): HTMLElement;
|
|
1169
|
+
/** Called when the element is added to the DOM */
|
|
1170
|
+
connectedCallback(): void;
|
|
1171
|
+
/** Called when the element is removed */
|
|
1172
|
+
disconnectedCallback(): void;
|
|
1173
|
+
/** @abstract Get the HTML layout */
|
|
1174
|
+
html(): string;
|
|
1175
|
+
/** @abstract Called before the HTML is created for the first time */
|
|
1176
|
+
onBeforeCreate(): void;
|
|
1177
|
+
/** @abstract Called when the component is created */
|
|
1178
|
+
onCreate(): void;
|
|
1179
|
+
/** @abstract Called when the UI should be updated with the current values */
|
|
1180
|
+
onUpdate(): void;
|
|
1181
|
+
/** @abstract Called when the component is created */
|
|
1182
|
+
onDestroy(): void;
|
|
1183
|
+
/** @abstract Called when an observed attribute changes */
|
|
1184
|
+
attributeChangedCallback(name: string, oldValue: any, newValue: any): void;
|
|
1185
|
+
/** Internal attribute proxy */
|
|
1186
|
+
private _attrProxy?;
|
|
1187
|
+
/** Helper for getting attributes */
|
|
1188
|
+
get attr(): any;
|
|
1189
|
+
/** Internal for state */
|
|
1190
|
+
private _stateProxy?;
|
|
1191
|
+
private _state;
|
|
1192
|
+
/** Helper for state variables. When anything inside here changes, onUpdate is called. */
|
|
1193
|
+
get state(): any;
|
|
1194
|
+
/** Check if a child with the ID exists */
|
|
1195
|
+
hasChild(id: string): boolean;
|
|
1196
|
+
/** Get a child element by it's ID */
|
|
1197
|
+
child(id: string): BaseComponent;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
/** Main embed web component */
|
|
1201
|
+
declare class WebWeaverEmbed extends BaseComponent {
|
|
1202
|
+
/** Element tag name */
|
|
1203
|
+
static tagName: string;
|
|
1204
|
+
/** Attributes we monitor for changes */
|
|
1205
|
+
static observedAttributes: string[];
|
|
1206
|
+
/** ChatGPT reference */
|
|
1207
|
+
ai: IntelliWeave;
|
|
1208
|
+
/** Currently loaded configuration */
|
|
1209
|
+
config: Partial<WebWeaverGPTConfig>;
|
|
1210
|
+
/** Responses the AI has suggested for the next user message */
|
|
1211
|
+
suggestions: string[];
|
|
1212
|
+
/** Constructor */
|
|
1213
|
+
constructor();
|
|
1214
|
+
/** Content */
|
|
1215
|
+
html: () => string;
|
|
1216
|
+
/** On create */
|
|
1217
|
+
onCreate(): void;
|
|
1218
|
+
private _lastLogo?;
|
|
1219
|
+
private _lastBackground?;
|
|
1220
|
+
private _lastTextColor?;
|
|
1221
|
+
/** Apply UI styles from config and attributes, prioritizing attributes */
|
|
1222
|
+
private applyConfigStylesAndAttributes;
|
|
1223
|
+
/** Called on update */
|
|
1224
|
+
onUpdate(): void;
|
|
1225
|
+
/** Called when the component is created */
|
|
1226
|
+
onDestroy(): void;
|
|
1227
|
+
/** Called when the container is clicked */
|
|
1228
|
+
onContainerClick(e: Event): void;
|
|
1229
|
+
/** Called when the logo is clicked */
|
|
1230
|
+
onLogoClick(e: Event): void;
|
|
1231
|
+
/** Open the interaction panel */
|
|
1232
|
+
open(): void;
|
|
1233
|
+
/** Close the interaction panel */
|
|
1234
|
+
close(): void;
|
|
1235
|
+
/** Reset conversation UI */
|
|
1236
|
+
resetConversation(): void;
|
|
1237
|
+
/** True if busy processing */
|
|
1238
|
+
private _isProcessing;
|
|
1239
|
+
/** Process input text from the user */
|
|
1240
|
+
processInput(inputText: string): Promise<void>;
|
|
1241
|
+
/** Called when the AI responds with some text */
|
|
1242
|
+
onAIMessage(msg: string): Promise<void>;
|
|
1243
|
+
/** Called when the AI starts running a tool */
|
|
1244
|
+
onAIToolStart(toolName: string, args: any): void;
|
|
1245
|
+
/** Called when a suggestion button is clicked */
|
|
1246
|
+
onSuggestionClick(e: Event, suggestion: string): void;
|
|
1247
|
+
/** Called when an LLM model is selected */
|
|
1248
|
+
onLLMModelSelect(e: CustomEvent): void;
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
/** Utility to trim whitespace from blocks of text */
|
|
1252
|
+
declare function trimWhitespaceInText(text: string): string;
|
|
1253
|
+
/** Get the global object */
|
|
1254
|
+
declare function intelliweaveGlobalThis(): any;
|
|
1255
|
+
/**
|
|
1256
|
+
* Global type declarations for the IntelliWeave library
|
|
1257
|
+
*/
|
|
1258
|
+
interface IntelliWeaveGlobalConfig {
|
|
1259
|
+
apiKey?: string;
|
|
1260
|
+
analytics?: boolean;
|
|
1261
|
+
debug?: boolean;
|
|
1262
|
+
context?: string;
|
|
1263
|
+
introductionMessage?: string;
|
|
1264
|
+
introductionSuggestions?: string[];
|
|
1265
|
+
knowledgeBase?: KnowledgeBaseItem[];
|
|
1266
|
+
sources?: any[];
|
|
1267
|
+
offsetX?: number;
|
|
1268
|
+
offsetY?: number;
|
|
1269
|
+
userID?: string;
|
|
1270
|
+
hubAPI?: string;
|
|
1271
|
+
backgroundColor?: string;
|
|
1272
|
+
/** Extra data that will be passed to external knowledge base actions. */
|
|
1273
|
+
extra: any;
|
|
1274
|
+
/** @deprecated Override the AI system context prefix. This should be controlled from the Hub now. */
|
|
1275
|
+
pageSummary?: string | (() => string) | (() => Promise<string>);
|
|
1276
|
+
/** List of knowledge base sources */
|
|
1277
|
+
knowledgeBaseSources?: KnowledgeBaseSource[];
|
|
1278
|
+
/** When the built-in UI is used, this contains the instance being rendered on the page */
|
|
1279
|
+
embed?: WebWeaverEmbed;
|
|
1280
|
+
}
|
|
1281
|
+
/** Get the global IntelliWeave configuration object that has been created for this document, or create it if necessary. */
|
|
1282
|
+
declare function intelliweaveConfig(): IntelliWeaveGlobalConfig;
|
|
1283
|
+
/** An async generator which yields events from an SSE fetch request body (a readable stream) */
|
|
1284
|
+
declare function sseEvents(stream: ReadableStream<Uint8Array>): AsyncGenerator<any, void, unknown>;
|
|
1285
|
+
/** Get or create a user ID for this device. */
|
|
1286
|
+
declare function getDefaultUserID(): string;
|
|
1287
|
+
|
|
1155
1288
|
/** Class to help with logging */
|
|
1156
1289
|
declare class Logging {
|
|
1157
1290
|
/** Current module */
|
|
@@ -1161,7 +1294,7 @@ declare class Logging {
|
|
|
1161
1294
|
/** Enable debug logging */
|
|
1162
1295
|
static debug: boolean;
|
|
1163
1296
|
/** Check if verbose logging is enabled */
|
|
1164
|
-
get debugEnabled():
|
|
1297
|
+
get debugEnabled(): boolean | undefined;
|
|
1165
1298
|
/** Log a message */
|
|
1166
1299
|
log(...args: any[]): void;
|
|
1167
1300
|
/** Debug message */
|
|
@@ -1227,4 +1360,4 @@ interface IntelliWeaveStreamTextOutputEvent extends IntelliWeaveStreamEvent {
|
|
|
1227
1360
|
text: string;
|
|
1228
1361
|
}
|
|
1229
1362
|
|
|
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 };
|
|
1363
|
+
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,15 +1,15 @@
|
|
|
1
1
|
import{v4 as W}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 L={};function
|
|
3
|
+
`)}var L={};function I(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:L}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=W(),localStorage.setItem("intelliweave.uid",c),c)}else return W()}var
|
|
9
|
+
`,yield*e()}function K(){if(g().userID)return g().userID||"";if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=W(),localStorage.setItem("intelliweave.uid",c),c)}else return W()}var T=class T{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return T.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)}};T.debug=!1;var f=T;var y=new f("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 U=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 R=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 k}from"gpt-tokenizer";import{v4 as J}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
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=k(e.content)+k(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=J());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:k(t.content)+k(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 f("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 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 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 q={name:"@intelliweave/embedded",version:"1.7.59",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+`
|
|
13
13
|
|
|
14
14
|
`+JSON.stringify(e))||"";if(n.toLowerCase().includes("true"))return!0;if(n.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+n)}async choose(t,e,s){s=s.map(u=>u.trim());let n=this.ai.clone();n.resetConversation(),n.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let i=await n.sendMessage("question:"+t+`
|
|
15
15
|
|
|
@@ -23,4 +23,4 @@ data:`+JSON.stringify(e)+`
|
|
|
23
23
|
extractions:`+JSON.stringify(n))||"";u=u.replace(/```json/g,"").replace(/```/g,"").replace(/\n/g,"");let l=u.split(",").map(r=>r.trim()).join(",");return JSON.parse(l)}async generateMarkdown(t,e){return this.instruct("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.",t,e)}async instruct(t,e,s){let n=this.ai.clone();return n.resetConversation(),n.getContextPrefix=async()=>t,s&&n.addEventListener("output",u=>{s(u.detail.message)}),await n.sendMessage(e)}};var p=new f("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()=>{p.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(),p.debug("Config loaded successfully:",this.config),this.config&&p.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(n){p.error("Failed to parse JSON response:",n);try{let i=await s.clone().text();p.error("Raw response that failed parsing:",i)}catch{p.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){p.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 p.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)})+`
|
|
24
24
|
`});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):(p.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 p.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=>{p.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=q.version;var A=D;var G=new f("Stream"),z=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
25
|
|
|
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(),G.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){G.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){G.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,U as FixedBufferStream,A as IntelliWeave,z as IntelliWeaveStream,E as KnowledgeBase,f as Logging,N as ONNXModel,R 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,
|
|
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(),G.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){G.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){G.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,U as FixedBufferStream,A as IntelliWeave,z as IntelliWeaveStream,E as KnowledgeBase,f as Logging,N as ONNXModel,R 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};
|
package/dist/react/react.d.ts
CHANGED
|
@@ -593,7 +593,7 @@ declare class IntelliWeave extends EventTarget {
|
|
|
593
593
|
setModel(id: string): void;
|
|
594
594
|
private _lastSystemMsg;
|
|
595
595
|
/** Get the system message prefix, before the KB entries are added */
|
|
596
|
-
getContextPrefix(): Promise<
|
|
596
|
+
getContextPrefix(): Promise<string>;
|
|
597
597
|
/** Get system message to send to the AI */
|
|
598
598
|
onBeforeMessageProcessing(): Promise<void>;
|
|
599
599
|
private _lastOutput?;
|