@smarter.sh/ui-chat 0.2.5 → 0.2.7
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/smarter-chat-library.es.js +13 -11
- package/dist/smarter-chat-library.es.js.map +1 -1
- package/dist/smarter-chat-library.umd.js +2 -2
- package/dist/smarter-chat-library.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/components/SmarterChat/Component.jsx +36 -32
- package/src/components/SmarterChat/api.js +7 -7
|
@@ -592,8 +592,8 @@ See https://s-c.sh/2BAXzed for more info.`),window[na]+=1);const ai=tn.div`
|
|
|
592
592
|
display: none;
|
|
593
593
|
flex-basis: 0%;
|
|
594
594
|
}
|
|
595
|
-
`,bt={INCOMING:"incoming",OUTGOING:"outgoing"},nt={SYSTEM:"system",ASSISTANT:"assistant",USER:"user",TOOL:"tool",SMARTER:"smarter"},nl=[nt.SYSTEM,nt.ASSISTANT,nt.USER,nt.TOOL],rl=!1,Tb="SmarterChat/1.0",oi="application/json";function dr(e,t=null){let r=null;if(document.cookie&&document.cookie!==""){const
|
|
595
|
+
`,bt={INCOMING:"incoming",OUTGOING:"outgoing"},nt={SYSTEM:"system",ASSISTANT:"assistant",USER:"user",TOOL:"tool",SMARTER:"smarter"},nl=[nt.SYSTEM,nt.ASSISTANT,nt.USER,nt.TOOL],rl=!1,Tb="SmarterChat/1.0",oi="application/json";function dr(e,t=null){console.log("getCookie(): cookie",e);let r=null;const n=e.domain;if(window.location.hostname===n&&document.cookie&&document.cookie!==""){const a=document.cookie.split(";");for(let o=0;o<a.length;o++){const i=a[o].trim();if(i.substring(0,e.name.length+1)===e.name+"="){r=decodeURIComponent(i.substring(e.name.length+1)),console.log("getCookie(): ",e.domain,e.name,r);break}}}return r||t}function ii(e,t){const r=window.location.pathname;if(t){const n=new Date;n.setTime(n.getTime()+e.expiration);const a=n.toUTCString(),o=`${e.name}=${t}; path=${r}; SameSite=Lax; expires=${a}`;document.cookie=o}else{const a=new Date(0).toUTCString(),o=`${e.name}=; path=${r}; SameSite=Lax; expires=${a}`;document.cookie=o}}function Ab(e,t){const r={session_key:t.session_key,messages:e};return JSON.stringify(r)}function al(e){console.log("requestHeadersFactory(): cookies",e);function t(i){return document.cookie.split(";").filter(l=>!l.trim().startsWith(`${i.csrfCookie.name}=`)).join("; ")}const r=t(e),n=dr(e.csrfCookie,""),a=dr(e.authTokenCookie,""),o={Accept:oi,"Content-Type":oi,"X-CSRFToken":n,Origin:window.location.origin,Cookie:r,Authorization:`Bearer ${a}`,"User-Agent":Tb};return console.log("requestHeadersFactory(): requestHeaders",o),o}function ol(e,t){return{method:"POST",credentials:"include",mode:"cors",headers:e,body:t}}function il(e,t,r){e.endsWith("/")||(e+="/"),t=t||"";let n=new URL(t,e);return r&&n.searchParams.append("session_key",r),n.toString()}async function sl(e,t,r){const n=dr(r.debugCookie)==="true";try{(n||rl)&&console.log("getJsonResponse(): url: ",e,", init: ",t,", cookies: ",r);const a=await fetch(e,t),o=a.headers.get("content-type");if(o&&o.includes(oi)){const i=await a.status;if(a.ok){const s=await a.json(),c=await s.data;return(n||rl)&&console.log("getJsonResponse(): response: ",s),c}else return console.error("getJsonResponse(): error: ",i,a.statusText),a}else{const i=await a.text();throw new Error(`getJsonResponse() Unexpected response format: ${i}`)}}catch(a){return a}}async function Mb(e,t,r){console.log("fetchPrompt(): config",e);const n=e.chatbot.url_chatbot,a=dr(r.sessionCookie,""),o=il(n,null,a),i=al(r),s=Ab(t,e),c=ol(i,s),l=await sl(o,c,r);return l&&l.body?(console.log("fetchPrompt(): parsing responseJson.body "),await JSON.parse(l.body)):null}async function Ib(e,t){const r=dr(t.sessionCookie,""),n=al(t),a=JSON.stringify({session_key:r}),o=ol(n,a),i=il(e,"config/",r),s=await sl(i,o,t);return s?(ii(t.sessionCookie,s.session_key),ii(t.debugCookie,s.debug_mode),s):null}function ra(e,t,r){return{name:e,expiration:t,domain:r}}function $b(e,t){var r,n,a;try{const o=(e||[]).map(i=>{if(i.role===nt.USER)return _t(i,i.content,bt.OUTGOING,i.role);if(i.role===nt.SYSTEM)return _t(i,i.content,bt.INCOMING,i.role);if(i.role===nt.ASSISTANT)return _t(i,i.content,bt.INCOMING,i.role);if(i.role===nt.SMARTER)return _t(i,i.content,bt.INCOMING,i.role);if(i.role===nt.TOOL)return _t(i,i.content,bt.INCOMING,i.role);console.error(`chatRestoreFromBackend() Invalid role received: ${i.role}`)}).filter(i=>i&&typeof i=="object"&&!Array.isArray(i));if((a=(n=(r=t==null?void 0:t.choices)==null?void 0:r[0])==null?void 0:n.message)!=null&&a.content){const i=t.choices[0].message,s=i.content;o.push(_t(i,s,bt.INCOMING,nt.ASSISTANT))}return o}catch(o){return console.error(`chatRestoreFromBackend() Error occurred while restoring chat from backend: ${o}`),[]}}const Lb=e=>e.length==0?"":`Some example prompts to get you started:\r
|
|
596
596
|
\r
|
|
597
597
|
`+e.map(t=>t+`\r
|
|
598
|
-
`).join("");function Db(e,t,r){let n=[_t({},t,bt.INCOMING,nt.SYSTEM)];n.push(_t({},e,bt.INCOMING,nt.ASSISTANT));const a=Lb(r);return a&&n.push(_t({},a,bt.INCOMING,nt.ASSISTANT)),n}function Rb(e){if(typeof e!="string")return console.error(`convertMarkdownLinksToHTML() Expected a string but received ${typeof e}`),console.error("convertMarkdownLinksToHTML() broke here",e),e;const t=/\[([^\]]+)\]\(([^)]+)\)/g;return e.replace(t,'<a href="$2">$1</a>')}function _t(e,t,r,n){const a=typeof t=="string"&&t!==null,i={message:a?Rb(t):t,direction:r,sender:n,sentTime:new Date().toLocaleString(),display:a};return e?i.originalMessage=e:i.originalMessage=i,i}function Fb(e){let t=e.originalMessage||{};return t.role=e.originalMessage&&e.originalMessage.role?e.originalMessage.role:e.sender,t.content=e.originalMessage&&e.originalMessage.message?e.originalMessage.message:e.message,t}function zb(e){return e.filter(t=>nl.includes(t.sender)).map((t,r)=>Fb(t))}function Wb(e,t,r,n,a,o){let i=[];return i=$b(a,o),i.length===0&&(i=Db(e,t,r)),i}class cl extends w.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,r){console.error(t,r)}render(){return this.state.hasError?ne.jsx("h1",{children:"Something went wrong."}):this.props.children}}cl.propTypes={children:d.node};const Bb=!1;function Hb({apiUrl:e,apiKey:t,toggleMetadata:r,csrfCookieName:n,debugCookieName:a,debugCookieExpiration:o,sessionCookieName:i,sessionCookieExpiration:s,authSessionCookieName:c,showConsole:l=!0,cookieDomain:u}){const[h,v]=w.useState(e),[g,_]=w.useState(r),[E,$]=w.useState(!1),[L,C]=w.useState({}),[z,f]=w.useState(""),[S,D]=w.useState(""),[F,K]=w.useState(""),[j,M]=w.useState(!1),[B,J]=w.useState(""),[N,pe]=w.useState(""),[re,I]=w.useState(!1),[ce,Oe]=w.useState(!1),[he,A]=w.useState(Bb),[q,X]=w.useState([]),[ae,ee]=w.useState(!1),[le,U]=w.useState(!1),[Q,te]=w.useState(""),[oe,ue]=w.useState(""),Ce=w.useRef(null),G=ra(n,null,u),Pe=ra(c,null,u),Xe=ra(i,s,u),rt=ra(a,o,u),at={authTokenCookie:Pe,csrfCookie:G,sessionCookie:Xe,debugCookie:rt},Dt=async()=>{const de=await Ib(h,at);return de!=null&&de.debug_mode&&(console.log("fetchAndSetConfig()..."),console.log("fetchAndSetConfig() config:",de)),d.checkPropTypes(ya,de,"prop","SmarterChat"),C(de),de},Rt=async()=>{var de;try{const ie=await Dt();console.log("fetchAndSetConfig() config:",ie),f(ie.chatbot.app_placeholder),v(ie.chatbot.url_chatbot),D(ie.chatbot.app_assistant),K(ie.chatbot.app_info_url),M(ie.chatbot.app_file_attachment),I(ie.meta_data.is_valid),Oe(ie.meta_data.is_deployed),A(ie.debug_mode);const we=((de=ie.history)==null?void 0:de.chat_history)||[],Re=Wb(ie.chatbot.app_welcome_message,ie.chatbot.default_system_role,ie.chatbot.app_example_prompts,ie.session_key,we,"BACKEND_CHAT_MOST_RECENT_RESPONSE");X(Re);const Me=`${ie.chatbot.app_name} v${ie.chatbot.version||"1.0.0"}`;J(Me);let Fe=`${ie.chatbot.provider} ${ie.chatbot.default_model}`;ie.plugins.meta_data.total_plugins>0&&(Fe+=` with ${ie.plugins.meta_data.total_plugins} additional plugins`),pe(Fe),$(!0),ee(!1),ie!=null&&ie.debug_mode&&console.log("fetchAndSetConfig() done!")}catch(ie){console.error("Failed to fetch config:",ie)}};w.useEffect(()=>(he&&console.log("ChatApp() component mounted"),Rt(),()=>{he&&console.log("ChatApp() component unmounted")}),[]);function Nt(de,ie){U(!0),ue(de),te(ie)}function Vt(){U(!1)}const wt=()=>{const de=!g;_(de),he&&console.log("showMetadata:",de);const ie=q.map(we=>we.message===null?{...we,display:!1}:["smarter","system","tool"].includes(we.sender)?{...we,display:de}:{...we,display:!0});X(ie)},ct=()=>{ii(at.sessionCookie,""),Rt()};async function He(de,ie=!1){const we=_t({},de,bt.OUTGOING,nt.USER);ie&&console.error("base64 encoding not implemented yet."),X(Re=>{const Me=[...Re,we];return ee(!0),(async()=>{try{he&&console.log("handleApiRequest() messages:",Me);const Fe=zb(Me),Qe=await Mb(L,Fe,at);if(Qe){const vt=Qe.smarter.messages.filter(Ye=>Ye.content!==null).map(Ye=>_t(Ye,Ye.content,bt.INCOMING,Ye.role));X(Ye=>[...Ye,...vt]),ee(!1),Dt()}}catch(Fe){ee(!1),console.error("Api error: ",Fe),Nt("Api error",Fe.message)}})(),Me})}const kt=async()=>{Ce.current.click()};function H(de){const ie=de.target.files[0],we=new FileReader;we.onload=Re=>{const Me=Re.target.result;He(Me,!0)},we.readAsText(ie)}const k=de=>{const ie=de.replace(/<[^>]+>/g,"");ie.trim()&&He(ie,!1)};function T({title:de,isValid:ie,isDeployed:we}){return ne.jsx("div",{children:E?ne.jsxs(ne.Fragment,{children:[de," ",ie?ne.jsx(Ze,{icon:Cu,style:{color:"green"}}):ne.jsx(Ze,{icon:Au,style:{color:"red"}}),we?ne.jsxs(ne.Fragment,{children:[" ",ne.jsx(Ze,{icon:Nu,style:{color:"orange"}})]}):null]}):ne.jsx("div",{children:"Loading..."})})}function Y({i:de,message:ie}){let we="";return ie.sender==="smarter"?we="smarter-message":["tool","system"].includes(ie.sender)&&(we="system-message"),ne.jsx($t,{model:ie,className:we},de)}const Z={width:"100%"},se={backgroundColor:"rgba(0,0,0,0.10)",color:"lightgray"},_e={width:"100%",height:"100%"},ye={...Z,...se};return ne.jsx("div",{id:"smarter_chat_component_container",className:"SmarterChat",children:ne.jsx(jb,{children:ne.jsx(Cb,{children:ne.jsxs(xb,{children:[ne.jsx(Nb,{children:ne.jsx("div",{className:"chat-app",children:ne.jsxs(oc,{style:_e,children:[ne.jsx(cl,{children:ne.jsx(dc,{isModalOpen:le,title:oe,message:Q,onCloseClick:Vt})}),ne.jsxs(tc,{style:ye,children:[ne.jsxs(jt,{children:[ne.jsx(jt.Content,{userName:E?ne.jsx(T,{title:B,isValid:re,isDeployed:ce}):"Configuring workbench...",info:E?N:""}),ne.jsxs(jt.Actions,{children:[ne.jsx(gs,{onClick:ct,title:"Start a new chat"}),r&&ne.jsx(vs,{onClick:wt,title:"Toggle system meta data"})]})]}),ne.jsx(Yt,{style:se,scrollBehavior:"auto",typingIndicator:ae?ne.jsx(uc,{content:S+" is typing"}):null,children:q.filter(de=>de.display).map((de,ie)=>ne.jsx(Y,{i:ie,message:de}))}),ne.jsx(On,{placeholder:z,onSend:k,onAttachClick:kt,attachButton:j,fancyScroll:!1})]}),ne.jsx("input",{type:"file",accept:".py",title:"Select a Python file",ref:Ce,style:{display:"none"},onChange:H})]})})}),l&&ne.jsx(kb,{children:ne.jsx(zo,{config:L})})]})})})})}const Yb="0.2.
|
|
598
|
+
`).join("");function Db(e,t,r){let n=[_t({},t,bt.INCOMING,nt.SYSTEM)];n.push(_t({},e,bt.INCOMING,nt.ASSISTANT));const a=Lb(r);return a&&n.push(_t({},a,bt.INCOMING,nt.ASSISTANT)),n}function Rb(e){if(typeof e!="string")return console.error(`convertMarkdownLinksToHTML() Expected a string but received ${typeof e}`),console.error("convertMarkdownLinksToHTML() broke here",e),e;const t=/\[([^\]]+)\]\(([^)]+)\)/g;return e.replace(t,'<a href="$2">$1</a>')}function _t(e,t,r,n){const a=typeof t=="string"&&t!==null,i={message:a?Rb(t):t,direction:r,sender:n,sentTime:new Date().toLocaleString(),display:a};return e?i.originalMessage=e:i.originalMessage=i,i}function Fb(e){let t=e.originalMessage||{};return t.role=e.originalMessage&&e.originalMessage.role?e.originalMessage.role:e.sender,t.content=e.originalMessage&&e.originalMessage.message?e.originalMessage.message:e.message,t}function zb(e){return e.filter(t=>nl.includes(t.sender)).map((t,r)=>Fb(t))}function Wb(e,t,r,n,a,o){let i=[];return i=$b(a,o),i.length===0&&(i=Db(e,t,r)),i}class cl extends w.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,r){console.error(t,r)}render(){return this.state.hasError?ne.jsx("h1",{children:"Something went wrong."}):this.props.children}}cl.propTypes={children:d.node};const Bb=!1;function Hb({apiUrl:e,apiKey:t,toggleMetadata:r,csrfCookieName:n="csrftoken",debugCookieName:a,debugCookieExpiration:o,sessionCookieName:i="session_key",sessionCookieExpiration:s,authSessionCookieName:c="sessionid",showConsole:l=!0,cookieDomain:u}){const[h,v]=w.useState(e),[g,_]=w.useState(r),[E,$]=w.useState(!1),[L,C]=w.useState({}),[z,f]=w.useState(""),[S,D]=w.useState(""),[F,K]=w.useState(""),[j,M]=w.useState(!1),[B,J]=w.useState(""),[N,pe]=w.useState(""),[re,I]=w.useState(!1),[ce,Oe]=w.useState(!1),[he,A]=w.useState(Bb),[q,X]=w.useState([]),[ae,ee]=w.useState(!1),[le,U]=w.useState(!1),[Q,te]=w.useState(""),[oe,ue]=w.useState(""),Ce=w.useRef(null),G=ra(n,null,u),Pe=ra(c,null,u),Xe=ra(i,s,u),rt=ra(a,o,u),at={authTokenCookie:Pe,csrfCookie:G,sessionCookie:Xe,debugCookie:rt},Dt=async()=>{const de=await Ib(h,at);return de!=null&&de.debug_mode&&(console.log("fetchAndSetConfig()..."),console.log("fetchAndSetConfig() config:",de)),d.checkPropTypes(ya,de,"prop","SmarterChat"),C(de),de},Rt=async()=>{var de;try{const ie=await Dt();console.log("fetchAndSetConfig() config:",ie),f(ie.chatbot.app_placeholder),v(ie.chatbot.url_chatbot),D(ie.chatbot.app_assistant),K(ie.chatbot.app_info_url),M(ie.chatbot.app_file_attachment),I(ie.meta_data.is_valid),Oe(ie.meta_data.is_deployed),A(ie.debug_mode);const we=((de=ie.history)==null?void 0:de.chat_history)||[],Re=Wb(ie.chatbot.app_welcome_message,ie.chatbot.default_system_role,ie.chatbot.app_example_prompts,ie.session_key,we,"BACKEND_CHAT_MOST_RECENT_RESPONSE");X(Re);const Me=`${ie.chatbot.app_name} v${ie.chatbot.version||"1.0.0"}`;J(Me);let Fe=`${ie.chatbot.provider} ${ie.chatbot.default_model}`;ie.plugins.meta_data.total_plugins>0&&(Fe+=` with ${ie.plugins.meta_data.total_plugins} additional plugins`),pe(Fe),$(!0),ee(!1),ie!=null&&ie.debug_mode&&console.log("fetchAndSetConfig() done!")}catch(ie){console.error("Failed to fetch config:",ie)}};w.useEffect(()=>(he&&console.log("ChatApp() component mounted"),Rt(),()=>{he&&console.log("ChatApp() component unmounted")}),[]);function Nt(de,ie){U(!0),ue(de),te(ie)}function Vt(){U(!1)}const wt=()=>{const de=!g;_(de),he&&console.log("showMetadata:",de);const ie=q.map(we=>we.message===null?{...we,display:!1}:["smarter","system","tool"].includes(we.sender)?{...we,display:de}:{...we,display:!0});X(ie)},ct=()=>{ii(at.sessionCookie,""),Rt()};async function He(de,ie=!1){const we=_t({},de,bt.OUTGOING,nt.USER);ie&&console.error("base64 encoding not implemented yet."),X(Re=>{const Me=[...Re,we];return ee(!0),(async()=>{try{he&&console.log("handleApiRequest() messages:",Me);const Fe=zb(Me),Qe=await Mb(L,Fe,at);if(Qe){const vt=Qe.smarter.messages.filter(Ye=>Ye.content!==null).map(Ye=>_t(Ye,Ye.content,bt.INCOMING,Ye.role));X(Ye=>[...Ye,...vt]),ee(!1),Dt()}}catch(Fe){ee(!1),console.error("Api error: ",Fe),Nt("Api error",Fe.message)}})(),Me})}const kt=async()=>{Ce.current.click()};function H(de){const ie=de.target.files[0],we=new FileReader;we.onload=Re=>{const Me=Re.target.result;He(Me,!0)},we.readAsText(ie)}const k=de=>{const ie=de.replace(/<[^>]+>/g,"");ie.trim()&&He(ie,!1)};function T({title:de,isValid:ie,isDeployed:we}){return ne.jsx("div",{children:E?ne.jsxs(ne.Fragment,{children:[de," ",ie?ne.jsx(Ze,{icon:Cu,style:{color:"green"}}):ne.jsx(Ze,{icon:Au,style:{color:"red"}}),we?ne.jsxs(ne.Fragment,{children:[" ",ne.jsx(Ze,{icon:Nu,style:{color:"orange"}})]}):null]}):ne.jsx("div",{children:"Loading..."})})}function Y({i:de,message:ie}){let we="";return ie.sender==="smarter"?we="smarter-message":["tool","system"].includes(ie.sender)&&(we="system-message"),ne.jsx($t,{model:ie,className:we},de)}const Z={width:"100%"},se={backgroundColor:"rgba(0,0,0,0.10)",color:"lightgray"},_e={width:"100%",height:"100%"},ye={...Z,...se};return ne.jsx("div",{id:"smarter_chat_component_container",className:"SmarterChat",children:ne.jsx(jb,{children:ne.jsx(Cb,{children:ne.jsxs(xb,{children:[ne.jsx(Nb,{children:ne.jsx("div",{className:"chat-app",children:ne.jsxs(oc,{style:_e,children:[ne.jsx(cl,{children:ne.jsx(dc,{isModalOpen:le,title:oe,message:Q,onCloseClick:Vt})}),ne.jsxs(tc,{style:ye,children:[ne.jsxs(jt,{children:[ne.jsx(jt.Content,{userName:E?ne.jsx(T,{title:B,isValid:re,isDeployed:ce}):"Configuring workbench...",info:E?N:""}),ne.jsxs(jt.Actions,{children:[ne.jsx(gs,{onClick:ct,title:"Start a new chat"}),r&&ne.jsx(vs,{onClick:wt,title:"Toggle system meta data"})]})]}),ne.jsx(Yt,{style:se,scrollBehavior:"auto",typingIndicator:ae?ne.jsx(uc,{content:S+" is typing"}):null,children:q.filter(de=>de.display).map((de,ie)=>ne.jsx(Y,{i:ie,message:de}))}),ne.jsx(On,{placeholder:z,onSend:k,onAttachClick:kt,attachButton:j,fancyScroll:!1})]}),ne.jsx("input",{type:"file",accept:".py",title:"Select a Python file",ref:Ce,style:{display:"none"},onChange:H})]})})}),l&&ne.jsx(kb,{children:ne.jsx(zo,{config:L})})]})})})})}const Yb="0.2.7";Ge.ConfigPropTypes=ya,Ge.Console=zo,Ge.MenuItems=gt,Ge.MessageDirectionEnum=bt,Ge.SenderRoleEnum=nt,Ge.SmarterChat=Hb,Ge.ValidMessageRolesEnum=nl,Ge.version=Yb,Object.defineProperty(Ge,Symbol.toStringTag,{value:"Module"})});
|
|
599
599
|
//# sourceMappingURL=smarter-chat-library.umd.js.map
|