@intelliweave/embedded 1.6.47 → 1.6.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/component/component.js +41 -16
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.js +1 -1
- package/dist/react/react.js +43 -18
- package/dist/script-tag/script-tag.js +42 -17
- package/dist/webpack/index.js +44 -19
- package/package.json +1 -1
package/dist/node/node.js
CHANGED
|
@@ -6,7 +6,7 @@ import{v4 as C}from"uuid";function A(c){let t=(c||"").split(`
|
|
|
6
6
|
`);for(let r of n){o=r.indexOf(": ");let u=r.slice(0,o),d=r.slice(o+2);o==-1&&(u=r,d=""),u&&(a[u]!==void 0?a[u]+=`
|
|
7
7
|
`+d:a[u]=d)}yield a}},s=new TextDecoder,i=c.getReader();for(;;){let{done:o,value:l}=await i.read();if(o)break;t+=s.decode(l,{stream:!0}),yield*e()}t+=s.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function O(){if(f().userID)return f().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=C(),localStorage.setItem("intelliweave.uid",c),c)}else return C()}var I=class I{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return I.debug?!0:typeof window<"u"&&f().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),(...i)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...i)}};I.debug=!1;var g=I;var w=new g("ONNXModel"),D=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,w.debug(`Model input parameters: ${t.inputNames.join(", ")}`),w.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||(w.debug("Loading ONNX runtime"),this.onnx=await c.lib()),w.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let i=1;for(let l of e)i*=l;let o;if(t=="float32")o=new c.onnx.Tensor(new Float32Array(i),e);else if(t=="int8")o=new c.onnx.Tensor(new Int8Array(i),e);else if(t=="int16")o=new c.onnx.Tensor(new Int16Array(i),e);else if(t=="int32")o=new c.onnx.Tensor(new Int32Array(i),e);else if(t=="int64")o=new c.onnx.Tensor(new BigInt64Array(i),e);else if(t=="uint8")o=new c.onnx.Tensor(new Uint8Array(i),e);else if(t=="uint16")o=new c.onnx.Tensor(new Uint16Array(i),e);else if(t=="uint32")o=new c.onnx.Tensor(new Uint32Array(i),e);else if(t=="uint64")o=new c.onnx.Tensor(new BigUint64Array(i),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?o.data.fill(BigInt(s)):s!==0&&o.data.fill(s),o}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,i=0){return this.registerConstant(t,this.makeTensor(e,s,i))}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,i,o=0){return this.registerState(t,e,this.makeTensor(s,i,o))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return w.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 i=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=i}return e}finally{this._runActive=!1}}resetState(){w.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function V(c,t){let e=t.reduce((n,r)=>n+r.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 i=1,o=32,l=i*o/8,a=c*l;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,i,!0),s.setUint32(24,c,!0),s.setUint32(28,a,!0),s.setUint16(32,l,!0),s.setUint16(34,o,!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 W=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 _=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 i=e.length-s,o=this.partialBuffers[0],l=o.length-this.partialBufferOffset;l<i?(e.set(o.subarray(this.partialBufferOffset),s),s+=l,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+i),s),s+=i,this.partialBufferOffset+=i)}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 K=class{constructor(t,e,s,i){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=i,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,i,o,l,a,n,r,u,d,h;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(i=this.outputBufferSize,o=this.ratioWeight,l=this.lastWeight,a=0,n=0,r=0,u=0,d=this.outputBuffer;l<1;l+=o)for(n=l%1,a=1-n,this.lastWeight=l%1,h=0;h<this.channels;++h)d[u++]=this.lastOutput[h]*a+t[h]*n;for(l-=1,e-=s,r=Math.floor(l)*s;u<i&&r<e;){for(n=l%1,a=1-n,h=0;h<this.channels;++h)d[u++]=t[r+(h>0?h:0)]*a+t[r+(s+h)]*n;l+=o,r=Math.floor(l)*s}for(h=0;h<s;++h)this.lastOutput[h]=t[r++];return this.bufferSlice(u)}}multiTap(){this.resampler=t=>{let e=t.length,s,i,o=this.channels,l,a,n,r,u,d,h,v,x;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,i=[],l=this.ratioWeight,a=0,r=0,u=0,d=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,v=0,x=0,n=0;n<o;++n)i[n]=0;do{if(d)for(a=l,n=0;n<o;++n)i[n]=0;else{for(a=this.lastWeight,n=0;n<o;++n)i[n]=this.lastOutput[n];d=!0}for(;a>0&&r<e;)if(u=1+r-x,a>=u){for(n=0;n<o;++n)i[n]+=t[r++]*u;x=r,a-=u}else{for(n=0;n<o;++n)i[n]+=t[r+(n>0?n:0)]*a;x+=a,a=0;break}if(a===0)for(n=0;n<o;++n)h[v++]=i[n]/l;else{for(this.lastWeight=a,n=0;n<o;++n)this.lastOutput[n]=i[n];this.tailExists=!0;break}}while(r<e&&v<s);return this.bufferSlice(v)}}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 te(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 se(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 ne(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}var p=new g("ChatGPT"),S=class{constructor(t){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...t}}async sendMessage(t){this.messages.push({role:"user",content:t}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),p.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t=this.messages[this.messages.length-1];if(t?.role=="user"||t?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(t?.role=="assistant"&&t?.tool_calls?.length){for(let e of t.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let t=await this.sendToAPI(!0);if(JSON.stringify(t).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){p.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(t){let e=0;for(let n=this.messages.length-1;n>=0;n--)if(this.messages[n].role=="assistant"&&this.messages[n].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[n].role=="user")break;p.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});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.config.systemMessage},...this.messages]};for(let n of this.tools){n.description&&n.description.length>1024&&p.warn(`Tool description for "${n.name}" is too long, it will be truncated.`);let r={type:"function",function:{name:n.name,description:(n.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(n.params))for(let u of n.params)r.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(n.params){let u=n.params;for(let d in u)r.function.parameters.properties[d]={type:"string",description:u[d]}}s.tools.push(r)}s.user||delete s.user,s.tools.length||delete s.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(s)});if(!o.ok){let n=`${o.status} ${o.statusText}`;try{let u=await o.json();n=u.errorText||u.error?.message||u.error||n}catch{}let r=new Error(n);throw r.code=o.status,r}let l=null,a=null;if(this.config.stream)for await(let n of P(o.body)){if(n.data=="[DONE]")break;if(!n.data)continue;let r=JSON.parse(n.data);if(a){for(let u in r.choices[0].delta)if(typeof r.choices[0].delta[u]=="string"){if(u=="role"&&a[u]==r.choices[0].delta[u])continue;a[u]=(a[u]||"")+r.choices[0].delta[u]}for(let u of r.choices[0].delta.tool_calls||[]){if(a.tool_calls||(a.tool_calls=[]),!a.tool_calls[u.index]){a.tool_calls[u.index]=u;continue}let d=a.tool_calls[u.index];d.function=d.function||{},d.function.name=(d.function.name||"")+(u.function?.name||""),d.function.arguments=(d.function.arguments||"")+(u.function?.arguments||"")}}else a={chunkID:r.id,...r.choices[0].delta};a?.content&&!a.content.startsWith("{")&&this.config.onAIMessage?.(a.content,!0)}else l=await o.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,p.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),a=l.choices?.[0]?.message;if(a||(p.warn("No response block in API response."),a={role:"assistant",content:""}),a.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(a),this.messages.push(a),a.content&&this.config.onAIMessage?.(a.content,!1)}processIncomingMessage(t){}registerTool(t){this.tools.push(t)}async processToolCall(t){try{let e=this.tools.find(o=>o.name==t.function.name);if(!e)throw new Error(`Tool "${t.function.name}" not found.`);let s=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,s);let i=await e.callback(s);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){p.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.tool_calls?.find(l=>l.id==t.id));return}else e.removeFromMessageHistory&&p.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:t.id})}catch(e){p.warn(`Unable to process tool call for "${t?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id})}}resetConversation(){this.messages=[]}};import F from"minisearch";var N=[{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);t.updateKnowledgeBase(e),t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=e.filter(o=>o.type=="action").map(o=>"name="+o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,t)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return t.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var y=new g("KnowledgeBase"),$=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>N}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${$++}`),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"&&f().knowledgeBaseSources&&(t=t.concat(f().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){y.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 i=(await Promise.all(this.sources.map(async n=>{try{return await n.query(t)}catch(r){return y.warn(`Knowledge source '${n.id}' failed:`,r),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),f().knowledgeBase&&(i=i.concat(f().knowledgeBase)),i=i.filter(n=>n&&!n.disabled);for(let n=0;n<i.length;n++){let r=i[n];if(r.id=r.id||`temp.${n}`,!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),r.parameters&&!Array.isArray(r.parameters)){let u=r.parameters,d=[];for(let h in u)d.push({name:h,type:"string",description:r.parameters[h]});r.parameters=d}r.content=A(typeof r.content=="function"?r.content():r.content)}let o=new F({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let a=o.search(t).map(n=>i.find(r=>r.id==n.id));for(let n of i)n.isContext&&(a.find(r=>r.id===n.id)||a.push(n));return this.lastResults=a,y.debug("Found results:",a),a}getCachedEntry(t){return this.lastResults.find(e=>e.id==t)}registerSourceFromURL(t,e){e||(e=`external.${$++}`),y.debug(`Registering remote knowledge base source: ${t}`);let s=[],i=async(l,a)=>{y.debug(`Calling remote knowledge base action: ${l.id}`);let n={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:a},r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return o(u.updateItems||[]),u.response},o=l=>{for(let a of l){if(!a.id){y.warn("KB item skipped since it has no ID.",a);continue}let n=s.find(r=>r.id==a.id);if(n){n.name=a.name||n.name||"",n.content=a.content||n.content||"",n.disabled=a.disabled??n.disabled,n.isContext=a.isContext??n.isContext,n.parameters=a.parameters||n.parameters||[],n.tags=a.tags||n.tags,n.type=a.type||n.type;continue}s.push({...a,action:r=>i(a,r)})}};this.registerSource(e,async l=>{let a={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok)throw new Error(`HTTP Error ${n.status} ${n.statusText}`);let r=await n.json();return o(r.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 R}from"uuid";var U={name:"@intelliweave/embedded",version:"1.6.47",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:{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",uuid:"^10.0.0"}};var T=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 i=await s.sendMessage(t+`
|
|
9
|
+
`,yield*e()}function O(){if(f().userID)return f().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=C(),localStorage.setItem("intelliweave.uid",c),c)}else return C()}var I=class I{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return I.debug?!0:typeof window<"u"&&f().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),(...i)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...i)}};I.debug=!1;var g=I;var w=new g("ONNXModel"),D=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,w.debug(`Model input parameters: ${t.inputNames.join(", ")}`),w.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||(w.debug("Loading ONNX runtime"),this.onnx=await c.lib()),w.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let i=1;for(let l of e)i*=l;let o;if(t=="float32")o=new c.onnx.Tensor(new Float32Array(i),e);else if(t=="int8")o=new c.onnx.Tensor(new Int8Array(i),e);else if(t=="int16")o=new c.onnx.Tensor(new Int16Array(i),e);else if(t=="int32")o=new c.onnx.Tensor(new Int32Array(i),e);else if(t=="int64")o=new c.onnx.Tensor(new BigInt64Array(i),e);else if(t=="uint8")o=new c.onnx.Tensor(new Uint8Array(i),e);else if(t=="uint16")o=new c.onnx.Tensor(new Uint16Array(i),e);else if(t=="uint32")o=new c.onnx.Tensor(new Uint32Array(i),e);else if(t=="uint64")o=new c.onnx.Tensor(new BigUint64Array(i),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?o.data.fill(BigInt(s)):s!==0&&o.data.fill(s),o}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,i=0){return this.registerConstant(t,this.makeTensor(e,s,i))}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,i,o=0){return this.registerState(t,e,this.makeTensor(s,i,o))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return w.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 i=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=i}return e}finally{this._runActive=!1}}resetState(){w.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function V(c,t){let e=t.reduce((n,r)=>n+r.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 i=1,o=32,l=i*o/8,a=c*l;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,i,!0),s.setUint32(24,c,!0),s.setUint32(28,a,!0),s.setUint16(32,l,!0),s.setUint16(34,o,!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 W=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 _=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 i=e.length-s,o=this.partialBuffers[0],l=o.length-this.partialBufferOffset;l<i?(e.set(o.subarray(this.partialBufferOffset),s),s+=l,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+i),s),s+=i,this.partialBufferOffset+=i)}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 K=class{constructor(t,e,s,i){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=i,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,i,o,l,a,n,r,u,d,h;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(i=this.outputBufferSize,o=this.ratioWeight,l=this.lastWeight,a=0,n=0,r=0,u=0,d=this.outputBuffer;l<1;l+=o)for(n=l%1,a=1-n,this.lastWeight=l%1,h=0;h<this.channels;++h)d[u++]=this.lastOutput[h]*a+t[h]*n;for(l-=1,e-=s,r=Math.floor(l)*s;u<i&&r<e;){for(n=l%1,a=1-n,h=0;h<this.channels;++h)d[u++]=t[r+(h>0?h:0)]*a+t[r+(s+h)]*n;l+=o,r=Math.floor(l)*s}for(h=0;h<s;++h)this.lastOutput[h]=t[r++];return this.bufferSlice(u)}}multiTap(){this.resampler=t=>{let e=t.length,s,i,o=this.channels,l,a,n,r,u,d,h,v,x;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,i=[],l=this.ratioWeight,a=0,r=0,u=0,d=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,v=0,x=0,n=0;n<o;++n)i[n]=0;do{if(d)for(a=l,n=0;n<o;++n)i[n]=0;else{for(a=this.lastWeight,n=0;n<o;++n)i[n]=this.lastOutput[n];d=!0}for(;a>0&&r<e;)if(u=1+r-x,a>=u){for(n=0;n<o;++n)i[n]+=t[r++]*u;x=r,a-=u}else{for(n=0;n<o;++n)i[n]+=t[r+(n>0?n:0)]*a;x+=a,a=0;break}if(a===0)for(n=0;n<o;++n)h[v++]=i[n]/l;else{for(this.lastWeight=a,n=0;n<o;++n)this.lastOutput[n]=i[n];this.tailExists=!0;break}}while(r<e&&v<s);return this.bufferSlice(v)}}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 te(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 se(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 ne(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}var p=new g("ChatGPT"),S=class{constructor(t){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...t}}async sendMessage(t){this.messages.push({role:"user",content:t}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),p.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t=this.messages[this.messages.length-1];if(t?.role=="user"||t?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(t?.role=="assistant"&&t?.tool_calls?.length){for(let e of t.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let t=await this.sendToAPI(!0);if(JSON.stringify(t).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){p.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(t){let e=0;for(let n=this.messages.length-1;n>=0;n--)if(this.messages[n].role=="assistant"&&this.messages[n].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[n].role=="user")break;p.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});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.config.systemMessage},...this.messages]};for(let n of this.tools){n.description&&n.description.length>1024&&p.warn(`Tool description for "${n.name}" is too long, it will be truncated.`);let r={type:"function",function:{name:n.name,description:(n.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(n.params))for(let u of n.params)r.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(n.params){let u=n.params;for(let d in u)r.function.parameters.properties[d]={type:"string",description:u[d]}}s.tools.push(r)}s.user||delete s.user,s.tools.length||delete s.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(s)});if(!o.ok){let n=`${o.status} ${o.statusText}`;try{let u=await o.json();n=u.errorText||u.error?.message||u.error||n}catch{}let r=new Error(n);throw r.code=o.status,r}let l=null,a=null;if(this.config.stream)for await(let n of P(o.body)){if(n.data=="[DONE]")break;if(!n.data)continue;let r=JSON.parse(n.data);if(a){for(let u in r.choices[0].delta)if(typeof r.choices[0].delta[u]=="string"){if(u=="role"&&a[u]==r.choices[0].delta[u])continue;a[u]=(a[u]||"")+r.choices[0].delta[u]}for(let u of r.choices[0].delta.tool_calls||[]){if(a.tool_calls||(a.tool_calls=[]),!a.tool_calls[u.index]){a.tool_calls[u.index]=u;continue}let d=a.tool_calls[u.index];d.function=d.function||{},d.function.name=(d.function.name||"")+(u.function?.name||""),d.function.arguments=(d.function.arguments||"")+(u.function?.arguments||"")}}else a={chunkID:r.id,...r.choices[0].delta};a?.content&&!a.content.startsWith("{")&&this.config.onAIMessage?.(a.content,!0)}else l=await o.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,p.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),a=l.choices?.[0]?.message;if(a||(p.warn("No response block in API response."),a={role:"assistant",content:""}),a.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(a),this.messages.push(a),a.content&&this.config.onAIMessage?.(a.content,!1)}processIncomingMessage(t){}registerTool(t){this.tools.push(t)}async processToolCall(t){try{let e=this.tools.find(o=>o.name==t.function.name);if(!e)throw new Error(`Tool "${t.function.name}" not found.`);let s=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,s);let i=await e.callback(s);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){p.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.tool_calls?.find(l=>l.id==t.id));return}else e.removeFromMessageHistory&&p.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:t.id})}catch(e){p.warn(`Unable to process tool call for "${t?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id})}}resetConversation(){this.messages=[]}};import F from"minisearch";var N=[{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);t.updateKnowledgeBase(e),t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=e.filter(o=>o.type=="action").map(o=>"name="+o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,t)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return t.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var y=new g("KnowledgeBase"),$=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>N}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${$++}`),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"&&f().knowledgeBaseSources&&(t=t.concat(f().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){y.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 i=(await Promise.all(this.sources.map(async n=>{try{return await n.query(t)}catch(r){return y.warn(`Knowledge source '${n.id}' failed:`,r),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),f().knowledgeBase&&(i=i.concat(f().knowledgeBase)),i=i.filter(n=>n&&!n.disabled);for(let n=0;n<i.length;n++){let r=i[n];if(r.id=r.id||`temp.${n}`,!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),r.parameters&&!Array.isArray(r.parameters)){let u=r.parameters,d=[];for(let h in u)d.push({name:h,type:"string",description:r.parameters[h]});r.parameters=d}r.content=A(typeof r.content=="function"?r.content():r.content)}let o=new F({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let a=o.search(t).map(n=>i.find(r=>r.id==n.id));for(let n of i)n.isContext&&(a.find(r=>r.id===n.id)||a.push(n));return this.lastResults=a,y.debug("Found results:",a),a}getCachedEntry(t){return this.lastResults.find(e=>e.id==t)}registerSourceFromURL(t,e){e||(e=`external.${$++}`),y.debug(`Registering remote knowledge base source: ${t}`);let s=[],i=async(l,a)=>{y.debug(`Calling remote knowledge base action: ${l.id}`);let n={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:a},r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return o(u.updateItems||[]),u.response},o=l=>{for(let a of l){if(!a.id){y.warn("KB item skipped since it has no ID.",a);continue}let n=s.find(r=>r.id==a.id);if(n){n.name=a.name||n.name||"",n.content=a.content||n.content||"",n.disabled=a.disabled??n.disabled,n.isContext=a.isContext??n.isContext,n.parameters=a.parameters||n.parameters||[],n.tags=a.tags||n.tags,n.type=a.type||n.type;continue}s.push({...a,action:r=>i(a,r)})}};this.registerSource(e,async l=>{let a={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok)throw new Error(`HTTP Error ${n.status} ${n.statusText}`);let r=await n.json();return o(r.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 R}from"uuid";var U={name:"@intelliweave/embedded",version:"1.6.49",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:{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",uuid:"^10.0.0"}};var T=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 i=await s.sendMessage(t+`
|
|
10
10
|
|
|
11
11
|
`+JSON.stringify(e))||"";if(i.toLowerCase().includes("true"))return!0;if(i.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+i)}async choose(t,e,s){s=s.map(l=>l.trim());let i=this.ai.clone();i.resetConversation(),i.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 o=await i.sendMessage("question:"+t+`
|
|
12
12
|
|