import{a7 as he,j as e,a8 as ue,R as x,aZ as pe,h as d,s as F,S as p,D as me,H as Z,aD as xe,aB as N,C as V,T as J,ay as ge,a1 as ye,a2 as fe}from"./vendor-ClLR6ncd.js";import{d as je}from"./Delete-BD9BsoWc.js";import{b as ee,a as ve,d as be,ar as u,i as Se,g as H,L as G,h as te,E as Ce}from"./index-OtVJl4GC.js";import{h as B}from"./model-Cx9iH8L7.js";import"./lodash-ZyeDnt0e.js";import{a as we,d as Qe,g as Ee,h as $e}from"./model-B1_e74fU.js";import{S as De}from"./SmallStandardSelect-7k6-Wr8Q.js";import{E as R}from"./Messages-BRmQDxrZ.js";import{u as Y}from"./model-BBaroEiB.js";import{t as Me,I as Be}from"./index-BzW9WBaB.js";import{s as D}from"./model-Dfrorm_S.js";import{C as Re}from"./CreateDialogContext-Buan56-U.js";import{D as Ae}from"./index-DY-IkI-n.js";import{r as M}from"./model-C9Idzwgo.js";import{p as C}from"./model-DAvH-x8m.js";import{u as U,r as re}from"./model-CvVGVe3F.js";import{M as qe}from"./MultilineTextField-C_a3SiQT.js";import{L as Q}from"./Link-BLwKPJFF.js";import{D as ae}from"./Divider-DZzUGEvZ.js";import"./model-BneMh0-t.js";import"./model-DgFcCvKB.js";import"./index-PJ52zw2m.js";import"./MenuItem-CCerWMyq.js";import"./dividerClasses-DvO85-mA.js";import"./useSaveAsQuery-DVU3wx0g.js";import"./Person-UulRDhfg.js";import"./Storage-DvymGqui.js";import"./Box-Co2WcNPC.js";import"./object_hash-DuPyIO4t.js";import"./_commonjs-dynamic-modules-TDtrdbi3.js";import"./ui-C5v50YHw.js";import"./ui-DWck426r.js";import"./useBlockingServerSyncIndicator-BOWZddDC.js";import"./ArrowDropDown-DBkU36zR.js";import"./Add-CLrXAvOx.js";import"./ButtonGroup-TnfpCz53.js";import"./Tabs-dk9tYIBM.js";import"./highlightSearch-BTHB3jgf.js";import"./WithMeasure-BDk9QPMF.js";import"./TableRow-CGDSOtFZ.js";import"./TableSortLabel-BJFq2axQ.js";import"./TypographyWithTooltip-BFAG3Va9.js";import"./DialogContent-DR8Wx7Lo.js";import"./DialogTitle-i0lt2jWQ.js";var k={},Te=ue;Object.defineProperty(k,"__esModule",{value:!0});var se=k.default=void 0,ze=Te(he()),Le=e;se=k.default=(0,ze.default)((0,Le.jsx)("path",{d:"M2.01 21 23 12 2.01 3 2 10l15 2-15 2z"}),"Send");const{useDialogContext:ie,DialogContextProvider:Fe}=Re();function He({disabled:t}){const r=ie();return e.jsx(Z,{disabled:t,size:"small",style:{marginRight:"3px"},startIcon:e.jsx(je,{}),variant:"outlined",color:"error",onClick:()=>{r.open()},children:"clear history"})}function ke({mutation:t,chatBotId:r}){const a=ie();return e.jsx(Ae,{...a,dialogTitle:"Clear history",dialogBodyMessage:`Do you want to clear ${r} history permanently?`,submitTitle:"Clear",onSubmit:t.mutate})}const j=t=>{const{catalogId:r,repositoryId:a}=C(t);return[r,a,"feed"]};function Oe(t){const{catalogId:r,repositoryId:a}=C(t),n=`SELECT ?user ?bot ?query ?prompt ${E.slice(1,-1).map(o=>"?"+o).join(" ")} {
  ?x rdf:type <http://franz.com/chatState/Exchange> ;
     <http://franz.com/chatState/user> ?user ;
     <http://franz.com/chatState/bot> ?bot ;
     <http://franz.com/chatState/prompt> ?prompt ;
     <http://franz.com/chatState/exchange-index> ?index .
     optional {
      ?y rdf:type <http://franz.com/chatState/ExtraInformation> ;
    <http://franz.com/chatState/exchange-index> ?index ;
    <http://franz.com/chatState/query> ?query ;
     ${E.slice(1,-1).map(o=>`<http://franz.com/chatState/${o}> ?${o}`).join(` ;
     `)} .
     }
}
ORDER BY ?index`;return Ce(j(t),async()=>(await B({urlSuffix:H({catalogId:r,repositoryId:a}),queryText:n})).data.values.map(([l,c,i,g,...y])=>({user:D(l).replace(/\\n/g,`
`),bot:D(c).replace(/\\n/g,`
`),fullInfo:Object.assign({prompt:g,query:i&&i.startsWith('"')?D(i).replace(/\\n/g,`
`):i},...y.map((h,f)=>({[E[f+1]]:h})))})),{enabled:!!t})}const E=["response","score","citationId","citedText","source","feed","story","expertiseMatchString","expertiseMatches","expertiseHints","historyMatchString","historyMatches","historyHints","prompt"],X=(t,r)=>{const a=E.map(n=>"?"+n).join(" ");return`PREFIX llm: <http://franz.com/ns/allegrograph/8.0.0/llm/>
SELECT ${a} {
  (${a})
    llm:chatState (
      """${t.replaceAll('"""',"\\\\u0022\\\\u0022\\\\u0022")}"""
      "${r.evdb}"
      ${r.expertiseMaxMatches}
      ${r.expertiseMinScore}
      "${r.hvdb}"
      ${r.historyMaxMatches}
      ${r.historyMinScore}
      "${r.id}"
    )
}`};function We(t){return te(async(r,a)=>(await B({urlSuffix:a,queryText:X(r,t)})).data,{onMutate:r=>{u.setQueryData(j(t.hvdb),a=>(a||[]).concat({user:r,bot:void 0,fullInfo:void 0}))},onSuccess:async(r,a)=>{const n=X(a,t),o=Object.assign({query:`'''${n.replaceAll("'''","\\'\\'\\'")}'''`},...E.slice(1).map((c,i)=>({[c]:r.values[0][i+1].replaceAll('\\\\\\"','\\"')})));u.setQueryData(j(t.hvdb),c=>{const i=c.at(-1);return c.slice(0,-1).concat({...i,bot:D(r.values[0][0]),fullInfo:o})});const l=u.getQueryData(j(t.hvdb));if(!(!Array.isArray(l)||l.length===0)){try{const c=l.length-1;await B({urlSuffix:H(C(t.hvdb)),queryText:`insert data {
_:a rdf:type <http://franz.com/chatState/ExtraInformation> ;
    <http://franz.com/chatState/exchange-index> "${c}"^^<http://www.w3.org/2001/XMLSchema#integer> ;
${Object.entries(o).map(([i,g])=>`<http://franz.com/chatState/${i}> ${g}`).join("; ")} .
}`})}catch(c){console.error("Failed to save extra information",c)}u.invalidateQueries(j(t.hvdb))}},onError:()=>{u.setQueryData(j(t.hvdb),r=>r.slice(0,-1)),u.invalidateQueries(j(t.hvdb))}})}function Pe({historyVdb:t,error:r,botName:a,userName:n}){var y;const{setExchange:o,exchange:l}=Ie(),c=xe(),i=Oe(t),g=x.useRef();return x.useEffect(()=>{const h=g.current;h&&(h.scrollTop=h.scrollHeight)},[i.data]),e.jsxs(p,{ref:g,p:1,flexGrow:1,minHeight:0,overflow:"auto",bgcolor:c.palette.grey[100],children:[i.isSuccess?i.data.map(({user:h,bot:f},s)=>e.jsxs(x.Fragment,{children:[e.jsxs(p,{alignItems:"flex-end",bgcolor:s===l?"orange":void 0,children:[e.jsx(d,{variant:"subtitle2",children:n}),e.jsx(N,{sx:{p:1,maxWidth:"500px",borderRadius:"8px",bgcolor:"primary.appBar"},children:e.jsx(d,{whiteSpace:"pre-wrap",children:h})})]}),e.jsxs(p,{alignItems:"flex-start",bgcolor:s===l?"orange":void 0,children:[e.jsx(d,{variant:"subtitle2",children:a}),e.jsx(N,{sx:{p:1,maxWidth:"500px",borderRadius:"8px"},children:f===void 0?e.jsxs(p,{direction:"row",alignItems:"center",justifyContent:"center",spacing:1,children:[e.jsx(V,{style:{height:"1em",width:"1em"}}),e.jsx(d,{fontStyle:"italic",color:"text.disabled",children:"Thinking..."})]}):e.jsx(d,{whiteSpace:"pre-wrap",children:f})}),f!==void 0?e.jsx(J,{title:"Show bot logic for this exchange",children:e.jsx(Z,{variant:"contained",sx:{mt:.5,pt:0,pb:0,pl:.75,pr:.5},size:"small",startIcon:e.jsx(ge,{}),onClick:()=>{o(s)},children:"Show bot logic"})}):null]})]},s)):null,r?e.jsx(R,{error:r}):i.isLoading||i.isFetching?e.jsxs(p,{direction:"row",alignItems:"center",justifyContent:"center",spacing:1,children:[e.jsx(V,{style:{height:"1rem",width:"1rem"}}),e.jsx(d,{children:"Loading..."})]}):i.isError?e.jsx(R,{error:`Failed to load feed from ${t} vector db`}):((y=i.data)==null?void 0:y.length)===0?e.jsx(d,{textAlign:"center",color:"text.disabled",children:"Please say something to the bot"}):e.jsx("br",{})]})}function _e({chatBot:t,setChatBot:r,chatBotOptions:a}){return a?e.jsxs(p,{spacing:1,direction:"row",alignItems:"end",p:1,children:[e.jsx(d,{children:"Pick a chatbot from the dropdown"}),e.jsx(De,{fullWidth:!1,sx:{minWidth:"100px"},value:t,onChange:n=>r(n.target.value),items:a})]}):null}function Ke(t,r){const{catalogId:a}=ee(),n=(t==null?void 0:t.hvdb)||`${a}:${t==null?void 0:t.id}-history-vdb-${me(5)}`,o=Ee(t==null?void 0:t.id,n),{catalogId:l}=C(n);return te(async(c,i)=>{await $e(n,r),await u.invalidateQueries(re(n)),t.hvdb||await B({urlSuffix:i,queryText:`insert data { ${o} }`})},{invalidateRepoKeysOnSuccess:["chat-bot-list"],onSuccess:()=>{u.invalidateQueries(M(l))}})}const ne=x.createContext();function Ie(){return x.useContext(ne)}function Ne({hvdb:t,exchange:r,close:a}){var l;const n=u.getQueryData(j(t)),o=(l=n==null?void 0:n[r])==null?void 0:l.fullInfo;return e.jsxs(p,{textAlign:"left",maxWidth:.6,minWidth:"300px",children:[e.jsxs(p,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(d,{variant:"h5",children:"Bot Logic for the highlighted exchange"}),e.jsx(Be,{onClick:a,sizeInRem:1.5,color:"error",sx:{m:1,p:1.5,mr:0},children:e.jsx(fe,{})})]}),o?e.jsx(p,{spacing:1,children:Object.entries(o).map(([c,i])=>e.jsxs(d,{whiteSpace:"pre-wrap",sx:{wordBreak:"break-all"},children:[e.jsxs(d,{fontWeight:"bold",component:"span",children:[c,":"," "]}),i]},c))}):e.jsx(d,{children:"No data available"})]})}function b({children:t,sx:r,hvdb:a}){const[n,o]=x.useState(-1),l=x.useCallback(()=>{o(-1)},[]),c=n===-1;return e.jsx(ne.Provider,{value:{exchange:n,setExchange:o},children:e.jsxs(p,{overflow:"auto",width:1,direction:"row",spacing:1,divider:e.jsx(ae,{orientation:"vertical",flexItem:!0}),height:`calc(100% - ${Me}px)`,justifyContent:c?"center":void 0,pr:1,pl:1,children:[e.jsx(p,{textAlign:"left",sx:r,maxWidth:800,minWidth:400,flexGrow:1,children:t}),c||!a?null:e.jsx(Ne,{hvdb:a,exchange:n,close:l})]})})}function Ve({disabled:t,chatBotMutation:r}){const[a,n]=x.useState(""),o=()=>{r.mutate(a.trim()),n("")},l=!a.trim(),c=t||r.isLoading;return e.jsxs(p,{component:"form",pt:1,pb:1,onSubmit:i=>{i.preventDefault(),o()},direction:"row",alignItems:"center",children:[e.jsx(qe,{disabled:c,placeholder:"Write message to the bot here. Press enter to send or click the icon button on the right side.",fullWidth:!0,name:"question",variant:"outlined",value:a,disableSubmit:l,formSubmit:o,onChange:i=>{n(i.target.value)}}),e.jsx(J,{title:"Send the question to the chatbot",children:e.jsx("span",{children:e.jsx(ye,{disabled:l||c,type:"submit",children:e.jsx(se,{})})})})]})}function Ht(){var P,_,K,I;const{catalogId:t,repoConnection:r,currentQuery:a}=ee(),{addOpenedChatBotQuery:n,getOpenedQueries:o}=ve(),l=Y("new-webview.html#Managing-Query-options"),c=Y("llm-chat-state.html"),i=((P=o(r)[a])==null?void 0:P.chatBotId)||"",g=x.useCallback(m=>{n(r,{id:a,...m!==void 0?{chatBotId:m}:{}})},[n,a,r]),y=we(),h=x.useMemo(()=>{var m,S;return(S=(m=y.data)==null?void 0:m.chatBots)==null?void 0:S.map(({id:$})=>({label:$,value:$}))},[(_=y.data)==null?void 0:_.chatBots]),f=i&&(Array.isArray(h)?!h.find(({value:m})=>m===i):!1)||!o(r)[a];x.useEffect(()=>{f&&g("")},[g,f]);const s=(I=(K=y.data)==null?void 0:K.chatBots)==null?void 0:I.find(m=>m.id===i),O=We(s),oe=!!pe(M(t)),A=Qe(),v=Ke(s,A),W=U(s==null?void 0:s.hvdb),ce=s?!(s!=null&&s.hvdb)||!W.data:!1,le=U(s==null?void 0:s.evdb),de=!(s!=null&&s.evdb)||!le.data,q=ce&&W.isSuccess&&!y.isFetching&&!oe&&!f&&!v.isLoading&&!v.isError;x.useEffect(()=>{q&&v.mutate()},[v,q]);const T=be(async()=>{await Se({method:"delete",url:H(C(s.hvdb))})},{onSuccess:()=>{const{catalogId:m}=C(s.hvdb);u.setQueryData(j(s.hvdb),[]),u.setQueryData(M(m),S=>Array.isArray(S)?S.filter(({id:$})=>$!==s.hvdb):S),u.invalidateQueries(M(m)),u.invalidateQueries(re(s.hvdb))}});if(!r||!t||!Array.isArray(h)||A===null)return e.jsx(b,{children:e.jsx(G,{})});const z=A===void 0,L=h.length===0;if(z||L)return e.jsxs(b,{sx:{p:2},children:[e.jsx(d,{variant:"h4",children:`Fix problem${z&&L?"s":""} below to query a chatbot:`}),e.jsxs("ul",{children:[z?e.jsxs(d,{component:"li",sx:{pl:1},children:["Set openaiApiKey query option. You can read"," ",e.jsx(Q,{href:l,target:"query-option-documentation",children:"documentation"})," ","to see how it can be done or"," ",e.jsx(Q,{component:F,to:"../../../control/options",relative:"path",children:"navigate to the page"})," ","right away."]}):null,L?e.jsxs(d,{component:"li",sx:{pl:1},children:["Create a chatbot. Your AG instance must have a vector database (you can create one"," ",e.jsx(Q,{component:F,to:"../../../control/llm-embedding",relative:"path",children:"here"}),") . After making sure that you have a vector database, you can create a chatbot on"," ",e.jsx(Q,{component:F,to:"../../../control/chat-bot/new",relative:"path",children:"this page"}),". To read more about chatbots please see"," ",e.jsx(Q,{href:c,target:"llm-chat-state",children:"documentation"}),"."]}):null]})]});const w=e.jsx(_e,{chatBot:i,setChatBot:g,chatBotOptions:h});return i?s?de?e.jsxs(b,{children:[w,e.jsx(R,{error:`Missing expertise vector database for ${s.id}`})]}):v.isError?e.jsxs(b,{children:[w,e.jsx(R,{error:`Failed to create history vector database for ${s.id}. Error: ${v.error}`,resetError:v.reset})]}):q||v.isLoading?e.jsxs(b,{children:[w,e.jsx(d,{children:"History vector database not found for the user. Trying to create one..."})]}):e.jsx(Fe,{children:e.jsxs(b,{hvdb:s==null?void 0:s.hvdb,children:[e.jsx(ke,{chatBotId:i,mutation:T}),e.jsxs(p,{direction:"row",justifyContent:"space-between",spacing:1,alignItems:"center",children:[w,e.jsx(He,{disabled:T.isLoading})]}),e.jsx(ae,{flexItem:!0,sx:{pb:1}}),e.jsx(Pe,{historyVdb:s.hvdb,error:O.error,botName:s.bot,userName:s.human}),e.jsx(Ve,{disabled:T.isLoading,chatBotMutation:O})]})}):e.jsx(b,{children:e.jsx(G,{})}):e.jsx(b,{children:w})}export{Ht as default};
