@bikdotai/bik-component-library 0.0.720-beta.2 → 0.0.720-beta.4
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/cjs/components/bik-chatbot/services/aiService.js +1 -1
- package/dist/cjs/components/bik-chatbot/services/callToChatbot.js +1 -1
- package/dist/cjs/components/bik-chatbot/services/db.d.ts +2 -0
- package/dist/cjs/components/bik-chatbot/services/db.js +1 -1
- package/dist/cjs/components/bik-chatbot/services/useAIChat.js +1 -1
- package/dist/esm/components/bik-chatbot/services/aiService.js +1 -1
- package/dist/esm/components/bik-chatbot/services/callToChatbot.js +1 -1
- package/dist/esm/components/bik-chatbot/services/db.d.ts +2 -0
- package/dist/esm/components/bik-chatbot/services/db.js +1 -1
- package/dist/esm/components/bik-chatbot/services/useAIChat.js +1 -1
- package/package.json +1 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("../utils/guardrails.js"),s=require("./callToChatbot.js");exports.AIService=class{constructor(e){if(Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatchMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"customFunctions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessageReceived",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"displayInUI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxToolCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiAdapter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.dispatchMessage=e.dispatchMessage,this.customFunctions=e.customFunctions,this.functionHandler=e.functionHandler,this.onMessageReceived=e.onMessageReceived,this.displayInUI=!1!==e.displayInUI,this.maxToolCalls=e.maxToolCalls||10,this.maxTokens=e.maxTokens,this.apiAdapter=e.apiAdapter,this.responseFormat=e.responseFormat,!this.apiAdapter)throw new Error("Chatbot authentication not configured: RequestExecutor is required")}sanitizeToolOutput(t,s){try{if(null!==s&&"object"==typeof s){const t=s,{success:i}=t,a=e.__rest(t,["success"]);return JSON.stringify(a)}return"string"==typeof s?s:String(s)}catch(e){return"string"==typeof s?s:String(s)}}tryParseAssistantJson(e){if(!e)return null;let t=e.trim();t=t.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/g,"").trim();try{return JSON.parse(t)}catch(s){try{const e=`[${t.replace(/}\s*{/g,"},{")}]`;return JSON.parse(e)}catch(t){return e}}}dispatchParsedResponses(e){const t=Date.now();e.forEach(((e,s)=>{let i="",a="assistant";if(e&&"object"==typeof e){const t=e;"string"==typeof t.response?i=t.response:"string"==typeof t.content&&(i=t.content),"system"===t.role&&(a="system")}else"string"==typeof e&&(i=e);i
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("../utils/guardrails.js"),s=require("./callToChatbot.js");exports.AIService=class{constructor(e){if(Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatchMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"customFunctions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessageReceived",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"displayInUI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxToolCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiAdapter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.dispatchMessage=e.dispatchMessage,this.customFunctions=e.customFunctions,this.functionHandler=e.functionHandler,this.onMessageReceived=e.onMessageReceived,this.displayInUI=!1!==e.displayInUI,this.maxToolCalls=e.maxToolCalls||10,this.maxTokens=e.maxTokens,this.apiAdapter=e.apiAdapter,this.responseFormat=e.responseFormat,!this.apiAdapter)throw new Error("Chatbot authentication not configured: RequestExecutor is required")}sanitizeToolOutput(t,s){try{if(null!==s&&"object"==typeof s){const t=s,{success:i}=t,a=e.__rest(t,["success"]);return JSON.stringify(a)}return"string"==typeof s?s:String(s)}catch(e){return"string"==typeof s?s:String(s)}}tryParseAssistantJson(e){if(!e)return null;let t=e.trim();t=t.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/g,"").trim();try{return JSON.parse(t)}catch(s){try{const e=`[${t.replace(/}\s*{/g,"},{")}]`;return JSON.parse(e)}catch(t){return e}}}dispatchParsedResponses(e){console.log(`🤖 [AIService] dispatchParsedResponses called with ${e.length} items, displayInUI: ${this.displayInUI}`);const t=Date.now();e.forEach(((e,s)=>{let i="",a="assistant";if(e&&"object"==typeof e){const t=e;"string"==typeof t.response?i=t.response:"string"==typeof t.content&&(i=t.content),"system"===t.role&&(a="system")}else"string"==typeof e&&(i=e);if(i){const e={id:`m-${t}-${s}`,role:a,content:i,timestamp:t+s};console.log("📨 [AIService] Dispatching AI response:",{messageId:e.id,role:e.role,content:i.substring(0,100)+(i.length>100?"...":""),displayInUI:this.displayInUI}),this.dispatchMessage(e)}}))}makeSystemMessage(){return{role:"system",content:t.injectSafetyPrompt(this.system.systemPrompt)}}generate(s,i){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default",n=arguments.length>3?arguments[3]:void 0;return e.__awaiter(this,void 0,void 0,(function*(){const e=s.map((e=>({role:e.role,text:t.sanitizeUserInput(e.content)}))),o=[{role:"system",text:this.makeSystemMessage().content},...e];return this.generateWithRecursiveToolCalls(o,i,a,n)}))}generateWithRecursiveToolCalls(t,i,a,n){var o,r,l,c,d,h,p,u,m,y;return e.__awaiter(this,void 0,void 0,(function*(){const e=t.map((e=>({role:e.role,text:e.text})));let g,f=n,v=0;for(;v<this.maxToolCalls;){let t;v++;try{if(g)t=g,g=void 0;else{let n;if(1===v&&f){const t=[...e].reverse().find((e=>"user"===e.role));t&&(n=[{role:"user",content:t.text}])}t=yield s.callToChatbot(e,a,i,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,n,this.system.tools,this.maxTokens)}}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`AI error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{}}if(f=t.responseId,!t.toolCall){if(t.assistantText)if("json"===this.responseFormat){const e=null!==(o=t.parsed)&&void 0!==o?o:this.tryParseAssistantJson(t.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(r=this.onMessageReceived)||void 0===r||r.call(this,e)}else{const e=t.assistantText.trim();this.displayInUI&&e&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:e,timestamp:Date.now()}),null===(l=this.onMessageReceived)||void 0===l||l.call(this,t.assistantText)}}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:t.assistantText,timestamp:Date.now()}),null===(c=this.onMessageReceived)||void 0===c||c.call(this,t.assistantText);return{responseId:f}}const{name:n,args:b,toolCallId:I,callId:x}=t.toolCall;I&&e.push({role:"assistant",text:"",toolCallId:I,toolName:n,toolArgs:JSON.stringify(b)});try{const t="string"==typeof b?(()=>{try{return JSON.parse(b)}catch(e){return b}})():b;null===(d=this.onMessageReceived)||void 0===d||d.call(this,{type:"TOOL_CALL",data:{name:n,args:t}});const o=yield this.functionHandler(n,t);if(I?e.push({role:"tool",text:JSON.stringify(o),toolCallId:I}):e.push({role:"tool",text:JSON.stringify(o)}),x){const t="object"==typeof o&&null!==o?o:String(o),r=this.sanitizeToolOutput(n,t);try{const e="string"==typeof t?t:JSON.stringify(t);null===(h=this.onMessageReceived)||void 0===h||h.call(this,{type:"TOOL_RESULT",data:{name:n,preview:e.slice(0,1e3)}})}catch(e){}const l=[{type:"function_call_output",call_id:x,output:r}],c=yield s.callToChatbot(e,a,i,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,l,this.system.tools,this.maxTokens);if(f=c.responseId,!c.toolCall){if(c.assistantText)if("json"===this.responseFormat){const e=null!==(p=c.parsed)&&void 0!==p?p:this.tryParseAssistantJson(c.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(u=this.onMessageReceived)||void 0===u||u.call(this,e)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(m=this.onMessageReceived)||void 0===m||m.call(this,c.assistantText)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(y=this.onMessageReceived)||void 0===y||y.call(this,c.assistantText);return{responseId:f}}g=c}else;}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Tool error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{responseId:f}}}return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Maximum tool call iterations (${this.maxToolCalls}) reached.`,timestamp:Date.now()}),{responseId:f}}))}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),o=require("../types/ai.js");exports.callToChatbot=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default-session",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"generic",r=arguments.length>4?arguments[4]:void 0,l=arguments.length>5?arguments[5]:void 0,a=arguments.length>6?arguments[6]:void 0,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:o.DEFAULT_MODEL,u=arguments.length>8?arguments[8]:void 0,p=arguments.length>9?arguments[9]:void 0,c=arguments.length>10?arguments[10]:void 0;return e.__awaiter(this,void 0,void 0,(function*(){if(!r)throw new Error("Chatbot authentication not configured: RequestExecutor is required");const e=u&&u.length>0?u:function(e){return e.map((e=>{let{role:o,text:t}=e;return{role:o,content:t}}))}(t),o={input:e,intent:n,conversationId:s,systemId:i,previousResponseId:l,customFunctions:a,builtinTools:p,model:d,maxTokens:null!=c?c:4e3};return yield r(o)}))},exports.createExecutorApiAdapter=function(o,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/openaiApiFunctions-callChatbot";return s=>e.__awaiter(this,void 0,void 0,(function*(){var e,i,r,l;const{input:a,model:d,maxTokens:u=4e3,previousResponseId:p,customFunctions:c,builtinTools:v,conversationId:g}=s;console.log("🌐 [API Adapter] Making API call:",{conversationId:g,previousResponseId:p,inputMessages:a.length,model:d,maxTokens:u});const h={input:a,tools:[...(v||[]).map((e=>({type:e}))),...(_=c,_&&0!==_.length?_.map((e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))):[])],model:d,max_output_tokens:u,previous_response_id:p,conversation_id:g};var _;console.log("📡 [API Adapter] Backend request payload:",{conversation_id:h.conversation_id,previous_response_id:h.previous_response_id,input_count:h.input.length,tools_count:h.tools.length});const I=`${t.replace(/\/$/,"")}${n}`,{status:m,data:x,error:T}=yield o.sendData({apiPath:I,apiMethod:"POST",requestBody:h});if(200!==m||!(null==x?void 0:x.success)){const o=(null===(i=null===(e=null==x?void 0:x.errors)||void 0===e?void 0:e[0])||void 0===i?void 0:i.message)||T;throw console.error("❌ [API Adapter] Backend error:",{status:m,errorMessage:o,data:x}),new Error("Backend error: "+(o?` - ${String(o)}`:""))}const f=function(e){const o={assistantText:e.assistantText,parsed:e.parsed,lastResponseId:e.lastResponseId,responseId:e.responseId};return e.toolCall&&(o.toolCall={name:e.toolCall.name,args:e.toolCall.args,toolCallId:e.toolCall.id,callId:e.toolCall.call_id}),o}(x.data);return console.log("✅ [API Adapter] Backend response received:",{responseId:f.responseId,lastResponseId:f.lastResponseId,assistantText:(null===(r=f.assistantText)||void 0===r?void 0:r.substring(0,100))+((null===(l=f.assistantText)||void 0===l?void 0:l.length)>100?"...":""),hasToolCall:!!f.toolCall}),f}))};
|
|
@@ -4,3 +4,5 @@ export declare function saveSession(sessionId: string, record: SessionRecord): P
|
|
|
4
4
|
export declare function loadSession(sessionId: string): Promise<SessionRecord | null>;
|
|
5
5
|
export declare function deleteSession(sessionId: string): Promise<void>;
|
|
6
6
|
export declare function listSessions(): Promise<string[]>;
|
|
7
|
+
/** Get all sessions (useful for debugging) */
|
|
8
|
+
export declare function getAllSessions(): Promise<SessionRecord[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js");const o="BIKChatbotDB",s=1,t="sessions";let n=null;function r(){return e.__awaiter(this,void 0,void 0,(function*(){return n||new Promise(((e,r)=>{console.log(`🗄️ [DB] Opening database: ${o}`);const a=indexedDB.open(o,s);a.onerror=()=>{console.error("❌ [DB] Failed to open database:",a.error),r(a.error)},a.onsuccess=()=>{n=a.result,console.log("✅ [DB] Database opened successfully"),e(n)},a.onupgradeneeded=e=>{console.log("🔄 [DB] Database upgrade needed");const o=e.target.result;if(!o.objectStoreNames.contains(t)){o.createObjectStore(t,{keyPath:"sessionId"}).createIndex("updatedAt","updatedAt",{unique:!1}),console.log(`📦 [DB] Created object store: ${t}`)}}}))}))}exports.loadSession=function(o){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield r();return new Promise(((s,n)=>{const r=e.transaction([t],"readonly").objectStore(t).get(o);r.onsuccess=()=>{const e=r.result;e?console.log("📁 [DB] Loaded session:",{sessionId:o,messageCount:e.messages.length,messageRoles:e.messages.map((e=>e.role)),createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}):console.log(`📁 [DB] No session found for sessionId: ${o}`),s(e||null)},r.onerror=()=>{console.error("❌ [DB] Failed to load session:",r.error),n(r.error)}}))}))},exports.saveSession=function(o,s){var n;return e.__awaiter(this,void 0,void 0,(function*(){console.log("💾 [DB] Saving session:",{sessionId:o,messageCount:s.messages.length,lastMessage:(null===(n=s.messages[s.messages.length-1])||void 0===n?void 0:n.role)||"none",updatedAt:new Date(s.updatedAt).toISOString()});const e=yield r();return new Promise(((n,r)=>{const a=e.transaction([t],"readwrite").objectStore(t).put(s);a.onsuccess=()=>{console.log(`✅ [DB] Session saved successfully: ${o}`),n()},a.onerror=()=>{console.error("❌ [DB] Failed to save session:",a.error),r(a.error)}}))}))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var s=require("../../../_virtual/_tslib.js"),e=require("react"),a=require("../types/chat.js"),t=require("./aiService.js"),n=require("./db.js");exports.useAIChat=function(o){var i=this;let{system:l,conversationId:d,skipInitialization:g=!1,customFunctions:c,functionHandler:r,responseFormat:u,onMessageReceived:I,displayInUI:m,maxToolCalls:p,maxTokens:v,apiAdapter:b}=o;const[h,j]=e.useState((()=>a.createSessionRecord(d))),[O,A]=e.useState([]),[f,y]=e.useState(),[C,S]=e.useState(!1);e.useEffect((()=>{console.log(`🔄 [useAIChat] Loading session for conversationId: ${d}, displayInUI: ${m}`),n.loadSession(d).then((s=>{var e,a;if(s){if(console.log("📁 [useAIChat] Session loaded:",{sessionId:s.sessionId,totalMessages:s.messages.length,messageRoles:s.messages.map((s=>s.role)),lastResponseId:null===(e=s.metadata)||void 0===e?void 0:e.lastResponseId}),j(s),m)console.log(`👁️ [useAIChat] displayInUI=true - Loading ALL ${s.messages.length} messages to UI`),A(s.messages);else{const e=s.messages.filter((s=>"user"===s.role));console.log(`🔇 [useAIChat] displayInUI=false - Loading only ${e.length} user messages to UI (${s.messages.length} total in session)`),A(e)}y(null===(a=s.metadata)||void 0===a?void 0:a.lastResponseId)}else console.log(`📁 [useAIChat] No existing session found for conversationId: ${d}`)}))}),[d,m]);const w=e.useMemo((()=>g?null:new t.AIService({system:Object.assign(Object.assign({},l),{handleCallback:(s,e)=>{var a;null===(a=l.handleCallback)||void 0===a||a.call(l,s,e)}}),dispatchMessage:s=>{console.log("💬 [useAIChat] dispatchMessage called:",{messageId:s.id,role:s.role,content:s.content.substring(0,100)+(s.content.length>100?"...":""),displayInUI:m}),j((e=>{const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving message to session - Total messages now: ${a.messages.length}`),n.saveSession(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:f})})),a})),m?(console.log("👁️ [useAIChat] displayInUI=true - Adding message to UI state"),A((e=>[...e,s]))):console.log("🔇 [useAIChat] displayInUI=false - Message saved to session but NOT added to UI state")},customFunctions:c,functionHandler:r,responseFormat:u,onMessageReceived:I,displayInUI:m,maxToolCalls:p,maxTokens:v,apiAdapter:b})),[l.id,g,v]);return{messages:O,conversation:h,sendMessage:function(e){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";return s.__awaiter(i,void 0,void 0,(function*(){if(!w)return void console.warn("⚠️ [useAIChat] sendMessage called but service is null");const s={id:`u-${Date.now()}`,role:"user",content:e,timestamp:Date.now()};console.log("📤 [useAIChat] Sending user message:",{messageId:s.id,content:e.substring(0,100)+(e.length>100?"...":""),conversationId:d,displayInUI:m}),A((e=>[...e,s])),j((e=>{const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving user message to session - Total messages now: ${a.messages.length}`),n.saveSession(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:f})})),a})),S(!0);try{const e=yield w.generate([...O,s].map((s=>({role:s.role,content:s.content}))),d,a,f);(null==e?void 0:e.responseId)&&(y(e.responseId),j((s=>{const a=Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:e.responseId})});return n.saveSession(a.sessionId,a),a})))}catch(s){const e=(null==s?void 0:s.message)||"Something went wrong. Please try again.",a={id:`err-${Date.now()}`,role:"system",content:e,timestamp:Date.now()};A((s=>[...s,a])),j((s=>{const e=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,a]});return n.saveSession(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:f})})),e}))}finally{S(!1)}}))},isApiCallInProgress:C}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{injectSafetyPrompt as s,sanitizeUserInput as i}from"../utils/guardrails.js";import{callToChatbot as a}from"./callToChatbot.js";class
|
|
1
|
+
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{injectSafetyPrompt as s,sanitizeUserInput as i}from"../utils/guardrails.js";import{callToChatbot as a}from"./callToChatbot.js";class n{constructor(e){if(Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dispatchMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"customFunctions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessageReceived",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"displayInUI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxToolCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiAdapter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.dispatchMessage=e.dispatchMessage,this.customFunctions=e.customFunctions,this.functionHandler=e.functionHandler,this.onMessageReceived=e.onMessageReceived,this.displayInUI=!1!==e.displayInUI,this.maxToolCalls=e.maxToolCalls||10,this.maxTokens=e.maxTokens,this.apiAdapter=e.apiAdapter,this.responseFormat=e.responseFormat,!this.apiAdapter)throw new Error("Chatbot authentication not configured: RequestExecutor is required")}sanitizeToolOutput(t,s){try{if(null!==s&&"object"==typeof s){const t=s,{success:i}=t,a=e(t,["success"]);return JSON.stringify(a)}return"string"==typeof s?s:String(s)}catch(e){return"string"==typeof s?s:String(s)}}tryParseAssistantJson(e){if(!e)return null;let t=e.trim();t=t.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/g,"").trim();try{return JSON.parse(t)}catch(s){try{const e=`[${t.replace(/}\s*{/g,"},{")}]`;return JSON.parse(e)}catch(t){return e}}}dispatchParsedResponses(e){console.log(`🤖 [AIService] dispatchParsedResponses called with ${e.length} items, displayInUI: ${this.displayInUI}`);const t=Date.now();e.forEach(((e,s)=>{let i="",a="assistant";if(e&&"object"==typeof e){const t=e;"string"==typeof t.response?i=t.response:"string"==typeof t.content&&(i=t.content),"system"===t.role&&(a="system")}else"string"==typeof e&&(i=e);if(i){const e={id:`m-${t}-${s}`,role:a,content:i,timestamp:t+s};console.log("📨 [AIService] Dispatching AI response:",{messageId:e.id,role:e.role,content:i.substring(0,100)+(i.length>100?"...":""),displayInUI:this.displayInUI}),this.dispatchMessage(e)}}))}makeSystemMessage(){return{role:"system",content:s(this.system.systemPrompt)}}generate(e,s){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default",n=arguments.length>3?arguments[3]:void 0;return t(this,void 0,void 0,(function*(){const t=e.map((e=>({role:e.role,text:i(e.content)}))),o=[{role:"system",text:this.makeSystemMessage().content},...t];return this.generateWithRecursiveToolCalls(o,s,a,n)}))}generateWithRecursiveToolCalls(e,s,i,n){var o,r,l,c,d,h,p,u,m,y;return t(this,void 0,void 0,(function*(){const t=e.map((e=>({role:e.role,text:e.text})));let g,f=n,v=0;for(;v<this.maxToolCalls;){let e;v++;try{if(g)e=g,g=void 0;else{let n;if(1===v&&f){const e=[...t].reverse().find((e=>"user"===e.role));e&&(n=[{role:"user",content:e.text}])}e=yield a(t,i,s,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,n,this.system.tools,this.maxTokens)}}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`AI error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{}}if(f=e.responseId,!e.toolCall){if(e.assistantText)if("json"===this.responseFormat){const t=null!==(o=e.parsed)&&void 0!==o?o:this.tryParseAssistantJson(e.assistantText);if(null!=t){const e=Array.isArray(t)?t:[t];this.displayInUI&&this.dispatchParsedResponses(e),null===(r=this.onMessageReceived)||void 0===r||r.call(this,t)}else{const t=e.assistantText.trim();this.displayInUI&&t&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:t,timestamp:Date.now()}),null===(l=this.onMessageReceived)||void 0===l||l.call(this,e.assistantText)}}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:e.assistantText,timestamp:Date.now()}),null===(c=this.onMessageReceived)||void 0===c||c.call(this,e.assistantText);return{responseId:f}}const{name:n,args:b,toolCallId:I,callId:x}=e.toolCall;I&&t.push({role:"assistant",text:"",toolCallId:I,toolName:n,toolArgs:JSON.stringify(b)});try{const e="string"==typeof b?(()=>{try{return JSON.parse(b)}catch(e){return b}})():b;null===(d=this.onMessageReceived)||void 0===d||d.call(this,{type:"TOOL_CALL",data:{name:n,args:e}});const o=yield this.functionHandler(n,e);if(I?t.push({role:"tool",text:JSON.stringify(o),toolCallId:I}):t.push({role:"tool",text:JSON.stringify(o)}),x){const e="object"==typeof o&&null!==o?o:String(o),r=this.sanitizeToolOutput(n,e);try{const t="string"==typeof e?e:JSON.stringify(e);null===(h=this.onMessageReceived)||void 0===h||h.call(this,{type:"TOOL_RESULT",data:{name:n,preview:t.slice(0,1e3)}})}catch(e){}const l=[{type:"function_call_output",call_id:x,output:r}],c=yield a(t,i,s,this.system.id,this.apiAdapter,f,this.system.functions,this.system.model,l,this.system.tools,this.maxTokens);if(f=c.responseId,!c.toolCall){if(c.assistantText)if("json"===this.responseFormat){const e=null!==(p=c.parsed)&&void 0!==p?p:this.tryParseAssistantJson(c.assistantText);if(null!=e){const t=Array.isArray(e)?e:[e];this.displayInUI&&this.dispatchParsedResponses(t),null===(u=this.onMessageReceived)||void 0===u||u.call(this,e)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(m=this.onMessageReceived)||void 0===m||m.call(this,c.assistantText)}else this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"assistant",content:c.assistantText,timestamp:Date.now()}),null===(y=this.onMessageReceived)||void 0===y||y.call(this,c.assistantText);return{responseId:f}}g=c}else;}catch(e){return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Tool error: ${String((null==e?void 0:e.message)||e)}`,timestamp:Date.now()}),{responseId:f}}}return this.displayInUI&&this.dispatchMessage({id:`m-${Date.now()}`,role:"system",content:`Maximum tool call iterations (${this.maxToolCalls}) reached.`,timestamp:Date.now()}),{responseId:f}}))}}export{n as AIService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as
|
|
1
|
+
import{__awaiter as e}from"../../../_virtual/_tslib.js";import{DEFAULT_MODEL as o}from"../types/ai.js";function t(o,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/openaiApiFunctions-callChatbot";return s=>e(this,void 0,void 0,(function*(){var e,i,l,r;const{input:a,model:d,maxTokens:u=4e3,previousResponseId:p,customFunctions:c,builtinTools:v,conversationId:g}=s;console.log("🌐 [API Adapter] Making API call:",{conversationId:g,previousResponseId:p,inputMessages:a.length,model:d,maxTokens:u});const h={input:a,tools:[...(v||[]).map((e=>({type:e}))),...(m=c,m&&0!==m.length?m.map((e=>({type:"function",name:e.name,description:e.description,parameters:e.parameters}))):[])],model:d,max_output_tokens:u,previous_response_id:p,conversation_id:g};var m;console.log("📡 [API Adapter] Backend request payload:",{conversation_id:h.conversation_id,previous_response_id:h.previous_response_id,input_count:h.input.length,tools_count:h.tools.length});const I=`${t.replace(/\/$/,"")}${n}`,{status:_,data:f,error:x}=yield o.sendData({apiPath:I,apiMethod:"POST",requestBody:h});if(200!==_||!(null==f?void 0:f.success)){const o=(null===(i=null===(e=null==f?void 0:f.errors)||void 0===e?void 0:e[0])||void 0===i?void 0:i.message)||x;throw console.error("❌ [API Adapter] Backend error:",{status:_,errorMessage:o,data:f}),new Error("Backend error: "+(o?` - ${String(o)}`:""))}const T=function(e){const o={assistantText:e.assistantText,parsed:e.parsed,lastResponseId:e.lastResponseId,responseId:e.responseId};return e.toolCall&&(o.toolCall={name:e.toolCall.name,args:e.toolCall.args,toolCallId:e.toolCall.id,callId:e.toolCall.call_id}),o}(f.data);return console.log("✅ [API Adapter] Backend response received:",{responseId:T.responseId,lastResponseId:T.lastResponseId,assistantText:(null===(l=T.assistantText)||void 0===l?void 0:l.substring(0,100))+((null===(r=T.assistantText)||void 0===r?void 0:r.length)>100?"...":""),hasToolCall:!!T.toolCall}),T}))}function n(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"default-session",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"generic",l=arguments.length>4?arguments[4]:void 0,r=arguments.length>5?arguments[5]:void 0,a=arguments.length>6?arguments[6]:void 0,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:o,u=arguments.length>8?arguments[8]:void 0,p=arguments.length>9?arguments[9]:void 0,c=arguments.length>10?arguments[10]:void 0;return e(this,void 0,void 0,(function*(){if(!l)throw new Error("Chatbot authentication not configured: RequestExecutor is required");const e=u&&u.length>0?u:function(e){return e.map((e=>{let{role:o,text:t}=e;return{role:o,content:t}}))}(t),o={input:e,intent:n,conversationId:s,systemId:i,previousResponseId:r,customFunctions:a,builtinTools:p,model:d,maxTokens:null!=c?c:4e3};return yield l(o)}))}export{n as callToChatbot,t as createExecutorApiAdapter};
|
|
@@ -4,3 +4,5 @@ export declare function saveSession(sessionId: string, record: SessionRecord): P
|
|
|
4
4
|
export declare function loadSession(sessionId: string): Promise<SessionRecord | null>;
|
|
5
5
|
export declare function deleteSession(sessionId: string): Promise<void>;
|
|
6
6
|
export declare function listSessions(): Promise<string[]>;
|
|
7
|
+
/** Get all sessions (useful for debugging) */
|
|
8
|
+
export declare function getAllSessions(): Promise<SessionRecord[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as
|
|
1
|
+
import{__awaiter as e}from"../../../_virtual/_tslib.js";const o="BIKChatbotDB",s=1,t="sessions";let n=null;function r(){return e(this,void 0,void 0,(function*(){return n||new Promise(((e,r)=>{console.log(`🗄️ [DB] Opening database: ${o}`);const a=indexedDB.open(o,s);a.onerror=()=>{console.error("❌ [DB] Failed to open database:",a.error),r(a.error)},a.onsuccess=()=>{n=a.result,console.log("✅ [DB] Database opened successfully"),e(n)},a.onupgradeneeded=e=>{console.log("🔄 [DB] Database upgrade needed");const o=e.target.result;if(!o.objectStoreNames.contains(t)){o.createObjectStore(t,{keyPath:"sessionId"}).createIndex("updatedAt","updatedAt",{unique:!1}),console.log(`📦 [DB] Created object store: ${t}`)}}}))}))}function a(o,s){var n;return e(this,void 0,void 0,(function*(){console.log("💾 [DB] Saving session:",{sessionId:o,messageCount:s.messages.length,lastMessage:(null===(n=s.messages[s.messages.length-1])||void 0===n?void 0:n.role)||"none",updatedAt:new Date(s.updatedAt).toISOString()});const e=yield r();return new Promise(((n,r)=>{const a=e.transaction([t],"readwrite").objectStore(t).put(s);a.onsuccess=()=>{console.log(`✅ [DB] Session saved successfully: ${o}`),n()},a.onerror=()=>{console.error("❌ [DB] Failed to save session:",a.error),r(a.error)}}))}))}function d(o){return e(this,void 0,void 0,(function*(){const e=yield r();return new Promise(((s,n)=>{const r=e.transaction([t],"readonly").objectStore(t).get(o);r.onsuccess=()=>{const e=r.result;e?console.log("📁 [DB] Loaded session:",{sessionId:o,messageCount:e.messages.length,messageRoles:e.messages.map((e=>e.role)),createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}):console.log(`📁 [DB] No session found for sessionId: ${o}`),s(e||null)},r.onerror=()=>{console.error("❌ [DB] Failed to load session:",r.error),n(r.error)}}))}))}export{d as loadSession,a as saveSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as s}from"../../../_virtual/_tslib.js";import{useState as e,useEffect as
|
|
1
|
+
import{__awaiter as s}from"../../../_virtual/_tslib.js";import{useState as e,useEffect as a,useMemo as t}from"react";import{createSessionRecord as n}from"../types/chat.js";import{AIService as o}from"./aiService.js";import{loadSession as i,saveSession as l}from"./db.js";function g(g){var d=this;let{system:c,conversationId:r,skipInitialization:m=!1,customFunctions:I,functionHandler:u,responseFormat:p,onMessageReceived:b,displayInUI:h,maxToolCalls:j,maxTokens:v,apiAdapter:O}=g;const[f,A]=e((()=>n(r))),[y,C]=e([]),[w,U]=e(),[R,$]=e(!1);a((()=>{console.log(`🔄 [useAIChat] Loading session for conversationId: ${r}, displayInUI: ${h}`),i(r).then((s=>{var e,a;if(s){if(console.log("📁 [useAIChat] Session loaded:",{sessionId:s.sessionId,totalMessages:s.messages.length,messageRoles:s.messages.map((s=>s.role)),lastResponseId:null===(e=s.metadata)||void 0===e?void 0:e.lastResponseId}),A(s),h)console.log(`👁️ [useAIChat] displayInUI=true - Loading ALL ${s.messages.length} messages to UI`),C(s.messages);else{const e=s.messages.filter((s=>"user"===s.role));console.log(`🔇 [useAIChat] displayInUI=false - Loading only ${e.length} user messages to UI (${s.messages.length} total in session)`),C(e)}U(null===(a=s.metadata)||void 0===a?void 0:a.lastResponseId)}else console.log(`📁 [useAIChat] No existing session found for conversationId: ${r}`)}))}),[r,h]);const M=t((()=>m?null:new o({system:Object.assign(Object.assign({},c),{handleCallback:(s,e)=>{var a;null===(a=c.handleCallback)||void 0===a||a.call(c,s,e)}}),dispatchMessage:s=>{console.log("💬 [useAIChat] dispatchMessage called:",{messageId:s.id,role:s.role,content:s.content.substring(0,100)+(s.content.length>100?"...":""),displayInUI:h}),A((e=>{const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving message to session - Total messages now: ${a.messages.length}`),l(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:w})})),a})),h?(console.log("👁️ [useAIChat] displayInUI=true - Adding message to UI state"),C((e=>[...e,s]))):console.log("🔇 [useAIChat] displayInUI=false - Message saved to session but NOT added to UI state")},customFunctions:I,functionHandler:u,responseFormat:p,onMessageReceived:b,displayInUI:h,maxToolCalls:j,maxTokens:v,apiAdapter:O})),[c.id,m,v]);return{messages:y,conversation:f,sendMessage:function(e){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";return s(d,void 0,void 0,(function*(){if(!M)return void console.warn("⚠️ [useAIChat] sendMessage called but service is null");const s={id:`u-${Date.now()}`,role:"user",content:e,timestamp:Date.now()};console.log("📤 [useAIChat] Sending user message:",{messageId:s.id,content:e.substring(0,100)+(e.length>100?"...":""),conversationId:r,displayInUI:h}),C((e=>[...e,s])),A((e=>{const a=Object.assign(Object.assign({},e),{updatedAt:Date.now(),messages:[...e.messages,s]});return console.log(`💾 [useAIChat] Saving user message to session - Total messages now: ${a.messages.length}`),l(a.sessionId,Object.assign(Object.assign({},a),{metadata:Object.assign(Object.assign({},a.metadata||{}),{lastResponseId:w})})),a})),$(!0);try{const e=yield M.generate([...y,s].map((s=>({role:s.role,content:s.content}))),r,a,w);(null==e?void 0:e.responseId)&&(U(e.responseId),A((s=>{const a=Object.assign(Object.assign({},s),{metadata:Object.assign(Object.assign({},s.metadata||{}),{lastResponseId:e.responseId})});return l(a.sessionId,a),a})))}catch(s){const e=(null==s?void 0:s.message)||"Something went wrong. Please try again.",a={id:`err-${Date.now()}`,role:"system",content:e,timestamp:Date.now()};C((s=>[...s,a])),A((s=>{const e=Object.assign(Object.assign({},s),{updatedAt:Date.now(),messages:[...s.messages,a]});return l(e.sessionId,Object.assign(Object.assign({},e),{metadata:Object.assign(Object.assign({},e.metadata||{}),{lastResponseId:w})})),e}))}finally{$(!1)}}))},isApiCallInProgress:R}}export{g as useAIChat};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bikdotai/bik-component-library",
|
|
3
|
-
"version": "0.0.720-beta.
|
|
3
|
+
"version": "0.0.720-beta.4",
|
|
4
4
|
"description": "Bik Component Library",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -59,7 +59,6 @@
|
|
|
59
59
|
"chart.js": "^3.9.1",
|
|
60
60
|
"chartjs-plugin-datalabels": "^2.2.0",
|
|
61
61
|
"emoji-picker-react": "^4.4.9",
|
|
62
|
-
"idb-keyval": "^6.2.2",
|
|
63
62
|
"lodash": "^4.17.21",
|
|
64
63
|
"phone": "^3.1.37",
|
|
65
64
|
"react-beautiful-dnd": "^13.1.1",
|