@topthink/chat 1.0.44-alpha.0 → 1.0.45

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/es/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as e from"react";import{useCallback as r,useEffect as t,useState as n,useRef as o,useImperativeHandle as i,memo as a,useMemo as s,createContext as l,useContext as c,Fragment as d,forwardRef as m}from"react";import{useImmer as h,request as u,isRequestError as p,Lightbox as g,styled as f,Clipboard as b,css as v,formatSize as x,Tooltip as y,useAsync as k,isImageUrl as w,Form as j,Toast as N}from"@topthink/components";import{jsx as q,jsxs as z,Fragment as $}from"react/jsx-runtime";import M from"react-markdown";import"katex/dist/katex.min.css";import C from"remark-math";import E from"remark-breaks";import F from"remark-gfm";import S from"rehype-katex";import D from"rehype-highlight";import{codes as R,types as T}from"micromark-util-symbol";import{markdownLineEnding as _}from"micromark-util-character";import A from"lodash/isEqual";import{Spinner as B,OverlayTrigger as L,Popover as O,CloseButton as P}from"react-bootstrap";import*as I from"path";import U from"path";import H from"react-textarea-autosize";import K from"use-resize-observer";function Q(e){if((e=e.filter((e=>!!e.trim()))).length>3){const r=[...e];let t=e.length-3;for(;t--;){let e=Math.floor(Math.random()*r.length);r.splice(e,1)}e=r}return e}function X(e){return e.map((e=>({id:e.id,query:e.query,quote:e.quote||void 0,files:e.files||void 0,variables:e.variables,chunks:e.chunks.map((e=>{let{content:r="",error:t,tools:n=[]}=e;return{content:r,error:t,tools:n}})),annotation:e.annotation,stats:{usage:e.usage,latency:e.latency}})))}function J(e){let{url:a,onboarding:s,suggestion:l,onSuccess:c,ref:d,transformRequest:m,...g}=e;const f=r((e=>{const r=[];if(s&&!1!==s.enable){const e=Q(s.questions||[]);r.push({chunks:[{content:[s.prologue,...e.map((e=>`[${e}](#!question)`))].join("\n"),tools:[]}],loading:s.loading})}return e?r.concat(X(e.messages||[])):r}),[s]),[b,v]=h((()=>f(g.conversation)));t((()=>{v(f(g.conversation))}),[s]);const[x,y]=n([]),[k,w]=n(!1),j=o(g.conversation?.id),N=o(null),q=r((async()=>{N.current=new AbortController;try{let e={method:"post",url:`${a}/suggestion`,data:{conversation:j.current},signal:N.current.signal};m&&(e=m("suggestion",e));const r=await u(e);y(r)}catch{}finally{N.current=null}}),[m,a]),z=r((async function(e){if("string"==typeof e){for(var r=arguments.length,t=new Array(r>1?r-1:0),n=1;n<r;n++)t[n-1]=arguments[n];e={query:e,...t}}const{query:o,files:i=[],variables:s={},quote:d}=e;if(o||i.length>0){N.current&&N.current.abort(),w(!0),y([]),v((e=>{e.push({query:o,quote:d,files:i,variables:s,chunks:[],loading:!0})}));try{let e={method:"post",url:a,data:{query:o,quote:d,files:i,variables:s,conversation:j.current},onMessage:e=>{if(e.data)if("[DONE]"!=e.data)try{const r=JSON.parse(e.data);r.conversation?j.current=r.conversation:v((e=>{const t=e[e.length-1];if(t.chunks)if(r.chunks){const e=r.chunks.index;if(t.chunks[e]||(t.chunks[e]={content:"",tools:[]}),r.chunks.error)t.chunks[e].error=r.chunks.error;else if(r.chunks.tools){const n=r.chunks.tools.index;"response"in r.chunks.tools?(t.chunks[e].tools[n].response=r.chunks.tools.response,t.chunks[e].tools[n].error=r.chunks.tools.error,t.chunks[e].tools[n].content=r.chunks.tools.content):t.chunks[e].tools[n]={name:r.chunks.tools.name,title:r.chunks.tools.title,arguments:r.chunks.tools.arguments}}else r.chunks.content&&(t.chunks[e].content+=r.chunks.content)}else r.stats&&(t.stats=r.stats)}))}catch(e){console.error(e)}else v((e=>{e[e.length-1].loading=!1}))}};m&&(e=m("chat",e)),await u(e),l?.enable&&q()}catch(e){let r="未知错误";p(e)&&(r=401==e.response?.status?"未授权或授权已过期,请刷新页面后重试":"string"==typeof e.errors?e.errors:Object.values(e.errors).join("\n")),v((e=>{const t=e[e.length-1];t.chunks&&(0===t.chunks.length?t.chunks=[{content:`[${r}]`,tools:[]}]:t.chunks[t.chunks.length-1].content=`[${r}]`),t.loading=!1}))}w(!1),c?.()}}),[m,a]),$=r((e=>{k||(j.current=e?.id,v(f(e)),y([]))}),[k,f]);return i(d,(()=>({reset:$,send:z}))),{messages:b,suggestions:x,loading:k,send:z,reset:$}}const W=function(e,r,t){function n(r){return r!==R.leftSquareBracket?(e.exit("citeMarker"),e.enter("citeData"),e.enter(T.chunkString,{contentType:"string"}),o(r)):(e.consume(r),n)}function o(n){return n===R.rightSquareBracket?(e.exit(T.chunkString),e.exit("citeData"),e.enter("citeMarker"),function(n){if(n!==R.rightSquareBracket)return t(n);return e.consume(n),e.exit("citeMarker"),e.exit("cite"),r(n)}(n)):_(n)||n===R.eof||n>57||n<48?t(n):(e.consume(n),o)}return function(r){return r!==R.leftSquareBracket?t(r):(e.enter("cite"),e.enter("citeMarker"),n(r))}},Y=function(){const e=this.data();e.micromarkExtensions.push({text:{[R.leftSquareBracket]:{tokenize:W}}}),e.fromMarkdownExtensions.push({enter:{cite:function(e){this.enter({type:"cite",data:{hName:"cite",hChildren:[{type:"text",value:""}]}},e)},citeData:function(){this.buffer()}},exit:{cite:function(e){this.exit(e)},citeData:function(){const e=this.resume();this.stack[this.stack.length-1].data.hChildren[0].value=e}}})},G=g.Image,V={pre:e=>{let{children:r}=e;const t=o(null);return z(ne,{ref:t,children:[q(te,{tooltip:!1,content:()=>{const e=t.current?.getElementsByTagName("code");return e?.[0]?.innerText||""}}),r]})},a:e=>{let{node:r,href:t,...n}=e;const o=t?.startsWith("http")?"_blank":"_self";return q("a",{...n,href:t,target:o})},img:e=>{let{node:r,...t}=e;return q(G,{...t})}},Z=[[C,{singleDollarTextMath:!1}],F,E],ee=[S,[D,{detect:!1,ignoreMissing:!0}]],re=a((e=>{let{content:r,components:t,cite:n}=e;r=r.replace(/\\\(\s(.+?)\s\\\)/g,"$$$$ $1 $$$$");const o=s((()=>{const e={...V,...t};return n&&(e.cite=n),e}),[t,n]),i=s((()=>n?[...Z,Y]:Z),[n]);return q(oe,{remarkPlugins:i,rehypePlugins:ee,components:o,children:r})}),A),te=f(b)`
1
+ import*as e from"react";import{useCallback as t,useEffect as r,useState as n,useRef as i,useImperativeHandle as o,memo as a,useMemo as s,createContext as l,useContext as c,Fragment as d,forwardRef as m}from"react";import{useImmer as u,request as h,isRequestError as p,Lightbox as g,styled as f,Clipboard as b,css as v,formatSize as x,Tooltip as y,useAsync as k,isImageUrl as w,Form as j,Toast as E}from"@topthink/components";import{jsx as N,jsxs as M,Fragment as q}from"react/jsx-runtime";import C from"react-markdown";import"katex/dist/katex.min.css";import z from"remark-math";import $ from"remark-breaks";import S from"remark-gfm";import F from"rehype-katex";import R from"rehype-highlight";import{codes as D,types as T}from"micromark-util-symbol";import{markdownLineEnding as A}from"micromark-util-character";import B from"lodash/isEqual";import{Spinner as P,OverlayTrigger as _,Popover as L,CloseButton as O}from"react-bootstrap";import*as I from"path";import U from"path";import H from"react-textarea-autosize";import K from"eventemitter3";import Q from"use-resize-observer";function X(e){if((e=e.filter((e=>!!e.trim()))).length>3){const t=[...e];let r=e.length-3;for(;r--;){let e=Math.floor(Math.random()*t.length);t.splice(e,1)}e=t}return e}function J(e){return e.map((e=>({id:e.id,query:e.query,quote:e.quote||void 0,files:e.files||void 0,variables:e.variables,chunks:e.chunks.map((e=>{let{content:t="",error:r,tools:n=[]}=e;return{content:t,error:r,tools:n}})),annotation:e.annotation,stats:{usage:e.usage,latency:e.latency}})))}function W(e){let{url:a,onboarding:s,suggestion:l,onSuccess:c,ref:d,transformRequest:m,...g}=e;const f=t((e=>{const t=[];if(s&&!1!==s.enable){const e=X(s.questions||[]);t.push({chunks:[{content:[s.prologue,...e.map((e=>`[${e}](#!question)`))].join("\n"),tools:[]}],loading:s.loading})}return e?t.concat(J(e.messages||[])):t}),[s]),[b,v]=u((()=>f(g.conversation)));r((()=>{v(f(g.conversation))}),[s]);const[x,y]=n([]),[k,w]=n(!1),j=i(g.conversation?.id),E=i(null),N=t((async()=>{E.current=new AbortController;try{let e={method:"post",url:`${a}/suggestion`,data:{conversation:j.current},signal:E.current.signal};m&&(e=m("suggestion",e));const t=await h(e);y(t)}catch{}finally{E.current=null}}),[m,a]),M=t((async function(e){if("string"==typeof e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];e={query:e,...r}}const{query:i,files:o=[],variables:s={},quote:d}=e;if(i||o.length>0){E.current&&E.current.abort(),w(!0),y([]),v((e=>{e.push({query:i,quote:d,files:o,variables:s,chunks:[],loading:!0})}));try{let e={method:"post",url:a,data:{query:i,quote:d,files:o,variables:s,conversation:j.current},onMessage:e=>{if(e.data)if("[DONE]"!=e.data)try{const t=JSON.parse(e.data);t.conversation?j.current=t.conversation:v((e=>{const r=e[e.length-1];if(r.chunks)if(t.chunks){const e=t.chunks.index;if(r.chunks[e]||(r.chunks[e]={content:"",tools:[]}),t.chunks.error)r.chunks[e].error=t.chunks.error;else if(t.chunks.tools){const n=t.chunks.tools.index;"response"in t.chunks.tools?(r.chunks[e].tools[n].response=t.chunks.tools.response,r.chunks[e].tools[n].error=t.chunks.tools.error,r.chunks[e].tools[n].content=t.chunks.tools.content):r.chunks[e].tools[n]={name:t.chunks.tools.name,title:t.chunks.tools.title,arguments:t.chunks.tools.arguments}}else t.chunks.content&&(r.chunks[e].content+=t.chunks.content)}else t.stats&&(r.stats=t.stats)}))}catch(e){console.error(e)}else v((e=>{e[e.length-1].loading=!1}))}};m&&(e=m("chat",e)),await h(e),l?.enable&&N()}catch(e){let t="未知错误";p(e)&&(t=401==e.response?.status?"未授权或授权已过期,请刷新页面后重试":"string"==typeof e.errors?e.errors:Object.values(e.errors).join("\n")),v((e=>{const r=e[e.length-1];r.chunks&&(0===r.chunks.length?r.chunks=[{content:`[${t}]`,tools:[]}]:r.chunks[r.chunks.length-1].content=`[${t}]`),r.loading=!1}))}w(!1),c?.()}}),[m,a]),q=t((e=>{k||(j.current=e?.id,v(f(e)),y([]))}),[k,f]);return o(d,(()=>({reset:q,send:M}))),{messages:b,suggestions:x,loading:k,send:M,reset:q}}const Y=function(e,t,r){function n(t){return t!==D.leftSquareBracket?(e.exit("citeMarker"),e.enter("citeData"),e.enter(T.chunkString,{contentType:"string"}),i(t)):(e.consume(t),n)}function i(n){return n===D.rightSquareBracket?(e.exit(T.chunkString),e.exit("citeData"),e.enter("citeMarker"),function(n){if(n!==D.rightSquareBracket)return r(n);return e.consume(n),e.exit("citeMarker"),e.exit("cite"),t(n)}(n)):A(n)||n===D.eof||n>57||n<48?r(n):(e.consume(n),i)}return function(t){return t!==D.leftSquareBracket?r(t):(e.enter("cite"),e.enter("citeMarker"),n(t))}},G=function(){const e=this.data();e.micromarkExtensions.push({text:{[D.leftSquareBracket]:{tokenize:Y}}}),e.fromMarkdownExtensions.push({enter:{cite:function(e){this.enter({type:"cite",data:{hName:"cite",hChildren:[{type:"text",value:""}]}},e)},citeData:function(){this.buffer()}},exit:{cite:function(e){this.exit(e)},citeData:function(){const e=this.resume();this.stack[this.stack.length-1].data.hChildren[0].value=e}}})},V=g.Image,Z={pre:e=>{let{children:t}=e;const r=i(null);return M(ie,{ref:r,children:[N(ne,{tooltip:!1,content:()=>{const e=r.current?.getElementsByTagName("code");return e?.[0]?.innerText||""}}),t]})},a:e=>{let{node:t,href:r,...n}=e;const i=r?.startsWith("http")?"_blank":"_self";return N("a",{...n,href:r,target:i})},img:e=>{let{node:t,...r}=e;return N(V,{...r})}},ee=[[z,{singleDollarTextMath:!1}],S,$],te=[F,[R,{detect:!1,ignoreMissing:!0}]],re=a((e=>{let{content:t,components:r,cite:n}=e;t=t.replace(/\\\(\s(.+?)\s\\\)/g,"$$$$ $1 $$$$");const i=s((()=>{const e={...Z,...r};return n&&(e.cite=n),e}),[r,n]),o=s((()=>n?[...ee,G]:ee),[n]);return N(oe,{remarkPlugins:o,rehypePlugins:te,components:i,children:t})}),B),ne=f(b)`
2
2
  position: absolute;
3
3
  right: 10px;
4
4
  top: 1em;
@@ -18,17 +18,17 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
18
18
  &:hover {
19
19
  opacity: 1;
20
20
  }
21
- `,ne=f.pre`
21
+ `,ie=f.pre`
22
22
  position: relative;
23
23
 
24
24
  &:hover {
25
- ${te} {
25
+ ${ne} {
26
26
  pointer-events: all;
27
27
  transform: translateX(0px);
28
28
  opacity: 0.5;
29
29
  }
30
30
  }
31
- `,oe=f(M)`
31
+ `,oe=f(C)`
32
32
  -ms-text-size-adjust: 100%;
33
33
  -webkit-text-size-adjust: 100%;
34
34
  line-height: 1.8;
@@ -298,7 +298,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
298
298
  .hljs-strong {
299
299
  font-weight: 700;
300
300
  }
301
- `,ie=l(null);function ae(){const e=c(ie);if(!e)throw new Error("useContext must be used within a Provider");return e}function se(e){let{children:r,...t}=e;return q(ie.Provider,{value:t,children:r})}const le=g.Image;function ce(e){let{src:r,...t}=e;const{imageResolver:n}=ae();return n&&r&&(r=n(r)),q(de,{children:q(le,{src:r,...t})})}const de=f.div`
301
+ `,ae=l(null);function se(){const e=c(ae);if(!e)throw new Error("useContext must be used within a Provider");return e}function le(e){let{children:t,...r}=e;return N(ae.Provider,{value:r,children:t})}const ce=g.Image;function de(e){let{src:t,...r}=e;const{imageResolver:n}=se();return n&&t&&(t=n(t)),N(me,{children:N(ce,{src:t,...r})})}const me=f.div`
302
302
  margin-bottom: .5rem;
303
303
  margin-top: .5rem;
304
304
  border: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
@@ -323,9 +323,9 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
323
323
  max-height: 100%;
324
324
  max-width: 100%;
325
325
  }
326
- `;function me(e){let{tool:r}=e;const[t,o]=n(!1),{logLevel:i="none"}=ae();let a=null;r.content&&("string"==typeof r.content?a=q(re,{content:r.content}):"image"===r.content.type&&(a=q(ce,{src:r.content.image})));const s="response"in r;return z(d,{children:["stats"==i&&q("div",{className:"mb-2",children:z("div",{role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?r.error?q("i",{className:"bi bi-x-circle-fill text-danger"}):q("i",{className:"bi bi-check-circle-fill text-success"}):q(B,{animation:"border",variant:"primary",size:"sm"}),q("span",{className:"text-muted",children:s?"已使用":"正在使用"}),q("span",{children:r.title})]})}),"all"==i&&q("div",{className:"mb-2",children:z("div",t&&s?{className:"shadow-sm rounded bg-white fs-7",children:[z("div",{onClick:()=>o(!1),role:"button",className:"d-flex align-items-center p-1 px-2 gap-2",children:[r.error?q("i",{className:"bi bi-x-circle-fill text-danger"}):q("i",{className:"bi bi-check-circle-fill text-success"}),q("span",{className:"text-muted",children:"已使用"}),q("span",{children:r.title}),q("i",{className:"bi bi-caret-up-fill text-muted"})]}),z("div",{className:"border-top p-2 d-flex flex-column gap-2",children:[z("div",{className:"border rounded bg-light",children:[q("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:q("span",{className:"text-muted",children:"参数"})}),q("div",{className:"border-top p-2 overflow-hidden",children:r.arguments})]}),z("div",{className:"border rounded bg-light",children:[q("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:q("span",{className:"text-muted",children:"响应"})}),q(he,{className:"border-top p-2 overflow-hidden",children:r.response||"None"})]})]})]}:{onClick:()=>o(s),role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?r.error?q("i",{className:"bi bi-x-circle-fill text-danger"}):q("i",{className:"bi bi-check-circle-fill text-success"}):q(B,{animation:"border",variant:"primary",size:"sm"}),q("span",{className:"text-muted",children:s?"已使用":"正在使用"}),q("span",{children:r.title}),s&&q("i",{className:"bi bi-caret-down-fill text-muted"})]})}),a]})}const he=f.div`
326
+ `;function ue(e){let{tool:t}=e;const[r,i]=n(!1),{logLevel:o="none"}=se();let a=null;t.content&&("string"==typeof t.content?a=N(re,{content:t.content}):"image"===t.content.type&&(a=N(de,{src:t.content.image})));const s="response"in t;return M(d,{children:["stats"==o&&N("div",{className:"mb-2",children:M("div",{role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?t.error?N("i",{className:"bi bi-x-circle-fill text-danger"}):N("i",{className:"bi bi-check-circle-fill text-success"}):N(P,{animation:"border",variant:"primary",size:"sm"}),N("span",{className:"text-muted",children:s?"已使用":"正在使用"}),N("span",{children:t.title})]})}),"all"==o&&N("div",{className:"mb-2",children:M("div",r&&s?{className:"shadow-sm rounded bg-white fs-7",children:[M("div",{onClick:()=>i(!1),role:"button",className:"d-flex align-items-center p-1 px-2 gap-2",children:[t.error?N("i",{className:"bi bi-x-circle-fill text-danger"}):N("i",{className:"bi bi-check-circle-fill text-success"}),N("span",{className:"text-muted",children:"已使用"}),N("span",{children:t.title}),N("i",{className:"bi bi-caret-up-fill text-muted"})]}),M("div",{className:"border-top p-2 d-flex flex-column gap-2",children:[M("div",{className:"border rounded bg-light",children:[N("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:N("span",{className:"text-muted",children:"参数"})}),N("div",{className:"border-top p-2 overflow-hidden",children:t.arguments})]}),M("div",{className:"border rounded bg-light",children:[N("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:N("span",{className:"text-muted",children:"响应"})}),N(he,{className:"border-top p-2 overflow-hidden",children:t.response||"None"})]})]})]}:{onClick:()=>i(s),role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?t.error?N("i",{className:"bi bi-x-circle-fill text-danger"}):N("i",{className:"bi bi-check-circle-fill text-success"}):N(P,{animation:"border",variant:"primary",size:"sm"}),N("span",{className:"text-muted",children:s?"已使用":"正在使用"}),N("span",{children:t.title}),s&&N("i",{className:"bi bi-caret-down-fill text-muted"})]})}),a]})}const he=f.div`
327
327
  white-space: pre-wrap;
328
- `;var ue,pe,ge;function fe(){return fe=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},fe.apply(this,arguments)}const be=r=>e.createElement("svg",fe({xmlns:"http://www.w3.org/2000/svg",width:20,height:10,fill:"#fff",viewBox:"0 0 120 30"},r),ue||(ue=e.createElement("circle",{cx:15,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))),pe||(pe=e.createElement("circle",{cx:60,cy:15,r:9,fill:"#3c60ff",fillOpacity:.3},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:9,repeatCount:"indefinite",to:9,values:"9;15;9"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:.5,repeatCount:"indefinite",to:.5,values:".5;1;.5"}))),ge||(ge=e.createElement("circle",{cx:105,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))));const ve=function(e){let{ext:r}=e;const{result:t}=k((async e=>(await function(e){switch(e){case"../../images/file/docx.svg":return import("./docx-nWXnlyT_.js");case"../../images/file/jpg.svg":return import("./jpg-6tBxSzWk.js");case"../../images/file/md.svg":return import("./md-GZ3HJPcw.js");case"../../images/file/pdf.svg":return import("./pdf-pVX1_E6T.js");case"../../images/file/png.svg":return import("./png-u0o1NMqQ.js");case"../../images/file/pptx.svg":return import("./pptx-Hprz0cON.js");case"../../images/file/txt.svg":return import("./txt-eHeCpvNO.js");case"../../images/file/xlsx.svg":return import("./xlsx-uOft-SV2.js");default:return new Promise((function(r,t){("function"==typeof queueMicrotask?queueMicrotask:setTimeout)(t.bind(null,new Error("Unknown variable dynamic import: "+e)))}))}}(`../../images/file/${e}.svg`)).default),[r]);return t?q("img",{width:30,height:30,src:t}):null};function xe(e){let{className:r,name:t,size:n,loading:o,error:i,onRemove:a}=e;const s=U.extname(t).substring(1),l=z(je,{className:r,$error:!!i,children:[z(we,{children:[q(ve,{ext:s}),o&&q(B,{variant:"primary"})]}),z(ke,{children:[q("h4",{children:t}),q("p",{children:x(n,1)})]}),a&&q(ye,{onClick:e=>{e.preventDefault(),a()},children:q("i",{className:"bi bi-trash3"})})]});return i?q(y,{placement:"top",tooltip:i,children:l}):l}const ye=f.div`
328
+ `;var pe,ge,fe;function be(){return be=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},be.apply(this,arguments)}const ve=t=>e.createElement("svg",be({xmlns:"http://www.w3.org/2000/svg",width:20,height:10,fill:"#fff",viewBox:"0 0 120 30"},t),pe||(pe=e.createElement("circle",{cx:15,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))),ge||(ge=e.createElement("circle",{cx:60,cy:15,r:9,fill:"#3c60ff",fillOpacity:.3},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:9,repeatCount:"indefinite",to:9,values:"9;15;9"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:.5,repeatCount:"indefinite",to:.5,values:".5;1;.5"}))),fe||(fe=e.createElement("circle",{cx:105,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))));const xe=function(e){let{ext:t}=e;const{result:r}=k((async e=>(await function(e){switch(e){case"../../images/file/docx.svg":return import("./docx-nWXnlyT_.js");case"../../images/file/jpg.svg":return import("./jpg-6tBxSzWk.js");case"../../images/file/md.svg":return import("./md-GZ3HJPcw.js");case"../../images/file/pdf.svg":return import("./pdf-pVX1_E6T.js");case"../../images/file/png.svg":return import("./png-u0o1NMqQ.js");case"../../images/file/pptx.svg":return import("./pptx-Hprz0cON.js");case"../../images/file/txt.svg":return import("./txt-eHeCpvNO.js");case"../../images/file/xlsx.svg":return import("./xlsx-uOft-SV2.js");default:return new Promise((function(t,r){("function"==typeof queueMicrotask?queueMicrotask:setTimeout)(r.bind(null,new Error("Unknown variable dynamic import: "+e)))}))}}(`../../images/file/${e}.svg`)).default),[t]);return r?N("img",{width:30,height:30,src:r}):null};function ye(e){let{className:t,name:r,size:n,loading:i,error:o,onRemove:a}=e;const s=U.extname(r).substring(1),l=M(Ee,{className:t,$error:!!o,children:[M(je,{children:[N(xe,{ext:s}),i&&N(P,{variant:"primary"})]}),M(we,{children:[N("h4",{children:r}),N("p",{children:x(n,1)})]}),a&&N(ke,{onClick:e=>{e.preventDefault(),a()},children:N("i",{className:"bi bi-trash3"})})]});return o?N(y,{placement:"top",tooltip:o,children:l}):l}const ke=f.div`
329
329
  width: 1.75rem;
330
330
  height: 1.75rem;
331
331
  align-items: center;
@@ -340,7 +340,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
340
340
  color: var(--bs-danger);
341
341
  background-color: var(--bs-danger-bg-subtle);
342
342
  }
343
- `,ke=f.div`
343
+ `,we=f.div`
344
344
  flex: 1;
345
345
  overflow: hidden;
346
346
 
@@ -361,7 +361,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
361
361
  line-height: 20px;
362
362
  margin-bottom: 0;
363
363
  }
364
- `,we=f.div`
364
+ `,je=f.div`
365
365
  position: relative;
366
366
  width: 3rem;
367
367
  height: 3rem;
@@ -375,7 +375,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
375
375
  position: absolute;
376
376
  }
377
377
 
378
- `,je=f.div`
378
+ `,Ee=f.div`
379
379
  display: flex;
380
380
  gap: .5rem;
381
381
  padding: .5rem;
@@ -391,7 +391,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
391
391
  ${e=>e.$error&&v`
392
392
  border-color: var(--bs-danger) !important;
393
393
  `}
394
- `;var Ne=m((function(e,r){let{children:t,tooltip:n,onClick:o,...i}=e;const a=q(qe,{ref:r,onClick:o,...i,children:t});return n?q(y,{tooltip:n,placement:"top",children:a}):a}));const qe=f.div`
394
+ `;var Ne=m((function(e,t){let{children:r,tooltip:n,onClick:i,...o}=e;const a=N(Me,{ref:t,onClick:i,...o,children:r});return n?N(y,{tooltip:n,placement:"top",children:a}):a}));const Me=f.div`
395
395
  align-items: center;
396
396
  justify-content: center;
397
397
  border-radius: .375rem;
@@ -415,7 +415,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
415
415
  background-color: var(--bs-gray-200);
416
416
  }
417
417
  }
418
- `,ze=a((e=>{let{message:r,actions:t,updater:n,cite:i}=e;const{query:a,quote:l,files:c=[],chunks:m,annotation:h}=r,{user:u,bot:p,logLevel:g="none"}=ae(),f=s((()=>m?m.reduce((function(e,r){return e+r.content+"\n"+r.tools.reduce(((e,r)=>r.content&&"string"==typeof r.content?e+r.content+"\n":e),"")}),""):""),[m]),v=o(null);return z($,{children:[(a||c.length>0)&&z(Ae,{$reverse:!0,children:[u&&q(Re,{children:q("img",{src:u.avatar})}),q(Te,{}),z(_e,{ref:v,children:[a&&q(re,{content:a}),l&&q(L,{trigger:"click",container:v,rootClose:!0,placement:"bottom",overlay:q($e,{body:!0,children:l}),children:q(Ce,{children:q(Me,{children:l})})}),c.length>0&&c.map(((e,r)=>{let{name:t,size:n,path:o}=e;return w(o)?q(ce,{src:`/uploads/${o}`},r):q(Fe,{children:q(xe,{name:t,size:n})},r)}))]})]}),m&&z(Ae,{children:[q(Re,{children:q("img",{src:p.avatar})}),q(Te,{}),z(_e,{children:[(a||c.length>0)&&z(Se,{children:[q(b,{placement:"top",content:f,as:Ne,tooltip:!0}),t?.({Component:Ne,message:r,content:f,setMessage:n})]}),q(De,{children:["stats","all"].includes(g)&&r.stats&&z($,{children:[z("span",{children:["耗时 ",r.stats.latency/1e3," 秒"]}),z("span",{children:["花费 Token ",r.stats.usage]})]})}),q(Ee,{$deleted:!!h,children:m.length>0&&m.map(((e,r)=>z(d,{children:[e.content&&q(re,{cite:i,content:e.content}),e.tools.map(((e,r)=>q(me,{tool:e},r))),e.error&&q(re,{content:`[${e.error}]`})]},r)))}),h&&z("div",{children:[z("div",{className:"d-flex align-items-center",children:[q("span",{className:"fs-7 text-secondary me-2",children:"标注的答案"}),q("hr",{className:"flex-fill"})]}),q(re,{content:h.answer})]}),r.loading&&q(be,{})]})]})]})})),$e=f(O)`
418
+ `,qe=a((e=>{let{message:t,actions:r,updater:n,cite:o}=e;const{query:a,quote:l,files:c=[],chunks:m,annotation:u}=t,{user:h,bot:p,logLevel:g="none"}=se(),f=s((()=>m?m.reduce((function(e,t){return e+t.content+"\n"+t.tools.reduce(((e,t)=>t.content&&"string"==typeof t.content?e+t.content+"\n":e),"")}),""):""),[m]),v=i(null);return M(q,{children:[(a||c.length>0)&&M(Pe,{$reverse:!0,children:[h&&N(Te,{children:N("img",{src:h.avatar})}),N(Ae,{}),M(Be,{ref:v,children:[a&&N(re,{content:a}),l&&N(_,{trigger:"click",container:v,rootClose:!0,placement:"bottom",overlay:N(Ce,{body:!0,children:l}),children:N($e,{children:N(ze,{children:l})})}),c.length>0&&c.map(((e,t)=>{let{name:r,size:n,path:i}=e;return w(i)?N(de,{src:`/uploads/${i}`},t):N(Fe,{children:N(ye,{name:r,size:n})},t)}))]})]}),m&&M(Pe,{children:[N(Te,{children:N("img",{src:p.avatar})}),N(Ae,{}),M(Be,{children:[(a||c.length>0)&&M(Re,{children:[N(b,{placement:"top",content:f,as:Ne,tooltip:!0}),r?.({Component:Ne,message:t,content:f,setMessage:n})]}),N(De,{children:["stats","all"].includes(g)&&t.stats&&M(q,{children:[M("span",{children:["耗时 ",t.stats.latency/1e3," 秒"]}),M("span",{children:["花费 Token ",t.stats.usage]})]})}),N(Se,{$deleted:!!u,children:m.length>0&&m.map(((e,t)=>M(d,{children:[e.content&&N(re,{cite:o,content:e.content}),e.tools.map(((e,t)=>N(ue,{tool:e},t))),e.error&&N(re,{content:`[${e.error}]`})]},t)))}),u&&M("div",{children:[M("div",{className:"d-flex align-items-center",children:[N("span",{className:"fs-7 text-secondary me-2",children:"标注的答案"}),N("hr",{className:"flex-fill"})]}),N(re,{content:u.answer})]}),t.loading&&N(ve,{})]})]})]})})),Ce=f(L)`
419
419
  max-width: calc(100% - .875rem * 2);
420
420
  width: calc(100% - .875rem * 2);
421
421
  font-size: 1rem;
@@ -424,20 +424,20 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
424
424
  .popover-body {
425
425
  padding: .5rem .75rem;
426
426
  }
427
- `,Me=f.div`
427
+ `,ze=f.div`
428
428
  overflow: hidden;
429
429
  text-overflow: ellipsis;
430
430
  word-break: break-all;
431
431
  -webkit-line-clamp: 2;
432
432
  -webkit-box-orient: vertical;
433
433
  display: -webkit-box;
434
- `,Ce=f.div`
434
+ `,$e=f.div`
435
435
  padding: .5rem .75rem;
436
436
  color: var(--bs-secondary);
437
437
  border-radius: var(--bs-border-radius-lg);
438
438
  background: #FFFFFF;
439
439
  cursor: pointer;
440
- `,Ee=f.div`
440
+ `,Se=f.div`
441
441
  ${e=>e.$deleted&&v`
442
442
  text-decoration-line: line-through;
443
443
  color: var(--bs-secondary);
@@ -454,7 +454,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
454
454
  &:last-child {
455
455
  margin-bottom: 0;
456
456
  }
457
- `,Se=f.div`
457
+ `,Re=f.div`
458
458
  position: absolute;
459
459
  top: -1.1rem;
460
460
  right: 0;
@@ -475,7 +475,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
475
475
  display: flex;
476
476
  opacity: 0;
477
477
  z-index: 1;
478
- `,Re=f.div`
478
+ `,Te=f.div`
479
479
  width: 35px;
480
480
  height: 35px;
481
481
  border-radius: 50%;
@@ -485,14 +485,14 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
485
485
  width: 100%;
486
486
  height: 100%;
487
487
  }
488
- `,Te=f.div`
488
+ `,Ae=f.div`
489
489
  width: 0;
490
490
  height: 0;
491
491
  content: "";
492
492
  border: 5px solid transparent;
493
493
  border-right-color: #f3f3f3;
494
494
  transform: translateY(10px);
495
- `,_e=f.div`
495
+ `,Be=f.div`
496
496
  padding: .875rem;
497
497
  background-color: rgb(243, 243, 243);
498
498
  border-radius: var(--bs-border-radius-lg);
@@ -500,52 +500,27 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
500
500
  position: relative;
501
501
 
502
502
  &:hover {
503
- ${De}, ${Se} {
503
+ ${De}, ${Re} {
504
504
  opacity: 1;
505
505
  }
506
506
  }
507
- `,Ae=f.div`
507
+ `,Pe=f.div`
508
508
  display: flex;
509
509
  justify-content: flex-start;
510
510
  padding: 1rem 0 1rem 0;
511
511
  ${e=>e.$reverse&&v`
512
512
  flex-direction: row-reverse;
513
513
 
514
- ${Te} {
514
+ ${Ae} {
515
515
  border-left-color: rgba(var(--bs-primary-rgb), 0.1);
516
516
  border-right-color: transparent;
517
517
  }
518
518
 
519
- ${_e} {
519
+ ${Be} {
520
520
  background: rgba(var(--bs-primary-rgb), 0.1);
521
521
  }
522
522
  `};
523
- `,Be=[".txt",".md",".pdf",".docx",".xlsx",".pptx",".png",".jpg"];function Le(e){let{variables:r,values:t,onSubmit:n,onChange:o,children:i}=e;const a={},s=[],l={};return r.forEach((e=>{a[e.key]={type:"string",title:e.label},"textarea"===e.type?l[e.key]={"ui:widget":"textarea"}:"select"===e.type&&e.options&&(a[e.key].enum=e.options,a[e.key].enumNames=e.options,e.options.length>0&&(a[e.key].default=e.options[0])),e.required&&s.push(e.key)})),q(j,{schema:{type:"object",properties:a,required:s},formData:t,omitExtraData:!0,uiSchema:l,submitText:"开始对话",onSubmit:n,onChange:o,children:i})}var Oe=m((function(e,a){let{chat:s,fileTypes:l,scrollRef:c,onMessages:d,onSuggestions:m,variables:g,minRows:f,toolbar:b,disabled:v,onLoading:x,autoFocus:k}=e;const w=o(null),j=o(null),[$,M]=n(""),[C,E]=n(""),[F,S]=h([]),[D,R]=n(!1),T=l&&l.length>0?l:Be,{loading:_,messages:A,suggestions:B,send:L,reset:O}=J({...s,onSuccess(){requestAnimationFrame((()=>{w.current?.focus()})),s.onSuccess?.()}}),[U,K]=n((()=>{const e=A.filter((e=>!!e.query));if(e.length>0){return e[e.length-1].variables}}));t((()=>{d(A)}),[A]),t((()=>{m(B)}),[B]),t((()=>{x?.(_)}),[_]),t((()=>{!l&&F.length>0&&S([])}),[l]),t((()=>{const e=c.current;if(e&&L){const r=e=>{e.target instanceof HTMLAnchorElement&&"#!question"===e.target.hash&&(e.preventDefault(),L(e.target.text))};return e.addEventListener("click",r),()=>{e.removeEventListener("click",r)}}}),[c,L]);const Q=r((e=>{let{target:r}=e;if(r.files){const e=Array.from(r.files).filter((e=>!!T.includes(I.extname(e.name))&&(!(e.size>20971520)&&e))).slice(0,6-F.length);S((r=>{r.push(...e.map((e=>({file:e}))))})),e.forEach((async e=>{try{const r=new FormData;r.set("file",e);let t={method:"POST",url:`${s.url}/upload`,data:r};s.transformRequest&&(t=s.transformRequest("upload",t));const n=await u(t);S((r=>{const t=r.find((r=>r.file===e));t&&(t.path=n.path)}))}catch(r){const t=p(r)?r.message:"unknown error";S((r=>{const n=r.find((r=>r.file===e));n&&(n.error=t)}))}}))}r.value=""}),[F,T]),X=F.flatMap((e=>{let{file:r,path:t}=e;return t?[{name:r.name,size:r.size,path:t}]:[]})),W=r((()=>{if($||X.length>0){const e={query:$,files:X};g&&(e.variables={...U,...g.values}),C&&(e.quote=C),L(e),M(""),E(""),S([])}}),[$,X,g,C]);if(i(a,(()=>({setQuery:M,setQuote:E,reset:O,send:L,focus(){w.current?.focus()}}))),g){const e=g.config.filter((e=>!(e.key in(g.values||{})))),r=function(r){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return!!r&&e.every((e=>{const n=!e.required||r?.[e.key];return!n&&t&&N.error("请完善必填信息"),n}))};if(e.length>0&&!r(U))return q(Ie,{children:q(Pe,{children:q(Le,{values:U,variables:e,onSubmit:e=>{let{formData:t}=e;if(r(t,!0))return K(t),!0}})})})}return z(We,{children:[b,z(Je,{$focused:D&&!_,children:[F.length>0&&q(He,{children:F.map(((e,r)=>{let{file:t,error:n,path:o}=e;const i=void 0===n&&void 0===o;return q(Ue,{name:t.name,size:t.size,error:n,loading:i,onRemove:()=>{S((e=>{const r=e.findIndex((e=>e.file===t));-1!==r&&e.splice(r,1)}))}},r)}))}),!!C&&z(Xe,{children:[q("i",{className:"bi bi-quote"}),q("p",{children:C}),q(P,{onClick:()=>E("")})]}),z(Qe,{children:[q(H,{disabled:_||v,ref:w,placeholder:"请输入你的问题, Enter+Shift换行, Enter发送",minRows:f,maxRows:5,value:$,onChange:e=>M(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),W())},autoFocus:k,onFocus:()=>R(!0),onBlur:()=>R(!1)}),l&&q(y,{tooltip:"可上传不超过6个小于20MB的文件",placement:"top",children:z(Ke,{disabled:F.length>=6,onClick:()=>j.current?.click(),children:[q("input",{onChange:Q,multiple:!0,accept:T.join(","),ref:j,type:"file",hidden:!0}),q("i",{className:"bi bi-file-earmark-arrow-up"})]})}),q(Ke,{className:"text-primary",disabled:!$&&0===X.length,onClick:e=>{e.preventDefault(),W()},children:q("i",{className:"bi bi-send-fill"})})]})]})]})}));const Pe=f.div`
524
- border-radius: var(--bs-border-radius-lg);
525
- box-shadow: var(--bs-box-shadow-sm);
526
- margin: 1rem;
527
- padding: 1rem;
528
- width: 100%;
529
- max-width: 500px;
530
- `,Ie=f.div`
531
- position: absolute;
532
- left: 0;
533
- right: 0;
534
- top: 0;
535
- bottom: 0;
536
- background: #FFF;
537
- display: flex;
538
- justify-content: center;
539
- align-items: center;
540
- `,Ue=f(xe)`
541
- width: calc((100% - .75rem) / 2);
542
- `,He=f.div`
543
- display: flex;
544
- flex-wrap: wrap;
545
- padding: .75rem;
546
- gap: .75rem;
547
- border-bottom: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
548
- `,Ke=f.button`
523
+ `,_e=[".txt",".md",".pdf",".docx",".xlsx",".pptx",".png",".jpg"];function Le(e){let{variables:t,values:r,onSubmit:n,onChange:i,children:o}=e;const a={},s=[],l={};return t.forEach((e=>{a[e.key]={type:"string",title:e.label},"textarea"===e.type?l[e.key]={"ui:widget":"textarea"}:"select"===e.type&&e.options&&(a[e.key].enum=e.options,a[e.key].enumNames=e.options,e.options.length>0&&(a[e.key].default=e.options[0])),e.required&&s.push(e.key)})),N(j,{schema:{type:"object",properties:a,required:s},formData:r,omitExtraData:!0,uiSchema:l,submitText:"开始对话",onSubmit:n,onChange:i,children:o})}const Oe=f.button`
549
524
  color: var(--bs-secondary);
550
525
  cursor: pointer;
551
526
  display: flex;
@@ -558,6 +533,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
558
533
  border: none;
559
534
  background: transparent;
560
535
  font-size: 1.2rem;
536
+ position: relative;
561
537
 
562
538
  &:disabled {
563
539
  color: var(--bs-gray-400) !important;
@@ -567,7 +543,37 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
567
543
  background-color: var(--bs-gray-200);
568
544
  }
569
545
 
570
- `,Qe=f.div`
546
+ `;class Ie{#e;#t;constructor(){this.#t=new K}onResult(e){this.#t.on("result",e)}onRecording(e){this.#t.on("recording",e)}onTranscribing(e){this.#t.on("transcribing",e)}start(){if(!this.#e){const e=window.SpeechRecognition||window.webkitSpeechRecognition;if(!e)return void E.error("浏览器不支持语音识别");const t=new e;t.continuous=!0,t.lang=navigator.language,t.onresult=e=>{const t=Array.from(e.results).at(-1)?.item(0).transcript;t&&this.#t.emit("result",t)},t.onspeechend=()=>{this.#t.emit("recording",!1)},t.onerror=()=>{this.#t.emit("recording",!1)},this.#e=t}this.#t.emit("recording",!0),this.#e.start()}stop(){this.#e?.stop(),this.#t.emit("recording",!1)}}class Ue{#t;#r;#n;#i;#o;constructor(e,t){this.#r=e,this.#n=t,this.#t=new K}async start(){this.#i=await navigator.mediaDevices.getUserMedia({audio:!0}),this.#o=new AudioContext;const e=this.#o.createScriptProcessor(0,1,1);this.#o.createMediaStreamSource(this.#i).connect(e),e.connect(this.#o.destination);let t=[],r=0;e.onaudioprocess=e=>{const n=e.playbackTime,i=e.inputBuffer.getChannelData(0);let o=!0;for(let e=0;e<i.length;e++)if(Math.abs(i[e])>.01){o=!1;break}if(o){const e=n-r;e>1&&(t.length>1&&(this.save(t),t=[]),e>10&&this.stop())}else t.push(new Float32Array(i)),r=n},this.#t.emit("recording",!0)}convertBuffer(e){const t=new Float32Array(e),r=new Int16Array(e.length);for(let e=0;e<t.length;e++){const n=Math.max(-1,Math.min(1,t[e]));r[e]=n<0?32768*n:32767*n}return r}async encodeMP3(e){const{Mp3Encoder:t}=await import("lamejs"),r=new t(1,44100,128),n=[];for(const t of e){const e=this.convertBuffer(t),i=1152;let o=e.length;for(let t=0;o>=0;t+=i){const a=e.subarray(t,t+i),s=r.encodeBuffer(a);n.push(new Int8Array(s)),o-=i}}return n.push(r.flush()),new Blob(n,{type:"audio/mp3"})}async save(e){const t=await this.encodeMP3(e),r=new FormData;r.append("file",t,"audio.mp3"),r.append("model",this.#n);try{this.#t.emit("transcribing",!0);const e=await h({url:this.#r,method:"post",data:r});e.text&&this.#t.emit("result",e.text)}catch(e){}finally{this.#t.emit("transcribing",!1)}}stop(){this.#i&&(this.#i.getTracks().forEach((e=>e.stop())),this.#i=void 0),this.#o&&(this.#o.close(),this.#o=void 0),this.#t.emit("recording",!1)}onResult(e){this.#t.on("result",e)}onRecording(e){this.#t.on("recording",e)}onTranscribing(e){this.#t.on("transcribing",e)}}const He=m(((e,t)=>{let{onResult:a,url:s,model:l="builtin"}=e;const{start:c,stop:d,recording:m,transcribing:u}=function(e){let{onResult:t,url:o,model:a="builtin"}=e;const s=i(),[l,c]=n(!1),[d,m]=n(!1);return r((()=>()=>{s.current&&(s.current.stop(),s.current=void 0)}),[]),{recording:l,transcribing:d,start:async()=>{s.current||(s.current="builtin"===a?new Ie:new Ue(o,a),s.current.onRecording(c),s.current.onTranscribing(m),s.current.onResult(t)),s.current.start()},stop:()=>{s.current&&s.current.stop()}}}({model:l,url:s,onResult:a});return o(t,(()=>({start:c,stop:d})),[c,d]),N(y,{tooltip:m?"停止":"语音输入",placement:"top",children:M(Oe,{onMouseDown:e=>{e.preventDefault(),m?d():c()},children:[u&&N(Ke,{animation:"border",variant:"primary",size:"sm"}),N("i",m?{className:"bi bi-mic-fill text-danger"}:{className:"bi bi-mic"})]})})})),Ke=f(P)`
547
+ position: absolute;
548
+ --bs-spinner-width: .75rem;
549
+ --bs-spinner-height: .75rem;
550
+ --bs-spinner-border-width: 0.1em;
551
+ `;var Qe=m((function(e,a){let{chat:s,fileTypes:l,speech:c,scrollRef:d,onMessages:m,onSuggestions:g,variables:f,minRows:b,toolbar:v,disabled:x,onLoading:k,autoFocus:w}=e;const j=i(null),q=i(null),C=i(null),[z,$]=n(""),[S,F]=n(""),[R,D]=u([]),[T,A]=n(!1),B=l&&l.length>0?l:_e,{loading:P,messages:_,suggestions:L,send:U,reset:K}=W({...s,onSuccess(){requestAnimationFrame((()=>{j.current?.focus()})),s.onSuccess?.()}}),[Q,X]=n((()=>{const e=_.filter((e=>!!e.query));if(e.length>0){return e[e.length-1].variables}}));r((()=>{m(_)}),[_]),r((()=>{g(L)}),[L]),r((()=>{k?.(P)}),[P]),r((()=>{!l&&R.length>0&&D([])}),[l]),r((()=>{const e=d.current;if(e&&U){const t=e=>{e.target instanceof HTMLAnchorElement&&"#!question"===e.target.hash&&(e.preventDefault(),U(e.target.text))};return e.addEventListener("click",t),()=>{e.removeEventListener("click",t)}}}),[d,U]);const J=t((e=>{let{target:t}=e;if(t.files){const e=Array.from(t.files).filter((e=>!!B.includes(I.extname(e.name))&&(!(e.size>20971520)&&e))).slice(0,6-R.length);D((t=>{t.push(...e.map((e=>({file:e}))))})),e.forEach((async e=>{try{const t=new FormData;t.set("file",e);let r={method:"POST",url:`${s.url}/upload`,data:t};s.transformRequest&&(r=s.transformRequest("upload",r));const n=await h(r);D((t=>{const r=t.find((t=>t.file===e));r&&(r.path=n.path)}))}catch(t){const r=p(t)?t.message:"unknown error";D((t=>{const n=t.find((t=>t.file===e));n&&(n.error=r)}))}}))}t.value=""}),[R,B]),Y=R.flatMap((e=>{let{file:t,path:r}=e;return r?[{name:t.name,size:t.size,path:r}]:[]})),G=t((()=>{if(z||Y.length>0){const e={query:z,files:Y};f&&(e.variables={...Q,...f.values}),S&&(e.quote=S),U(e),$(""),F(""),D([]),C.current?.stop(!0)}}),[z,Y,f,S]);if(o(a,(()=>({setQuery:$,setQuote:F,reset:K,send:U,focus(){j.current?.focus()}}))),f){const e=f.config.filter((e=>!(e.key in(f.values||{})))),t=function(t){let r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return!!t&&e.every((e=>{const n=!e.required||t?.[e.key];return!n&&r&&E.error("请完善必填信息"),n}))};if(e.length>0&&!t(Q))return N(Je,{children:N(Xe,{children:N(Le,{values:Q,variables:e,onSubmit:e=>{let{formData:r}=e;if(t(r,!0))return X(r),!0}})})})}return M(et,{children:[v,M(Ze,{$focused:T&&!P,children:[R.length>0&&N(Ye,{children:R.map(((e,t)=>{let{file:r,error:n,path:i}=e;const o=void 0===n&&void 0===i;return N(We,{name:r.name,size:r.size,error:n,loading:o,onRemove:()=>{D((e=>{const t=e.findIndex((e=>e.file===r));-1!==t&&e.splice(t,1)}))}},t)}))}),!!S&&M(Ve,{children:[N("i",{className:"bi bi-quote"}),N("p",{children:S}),N(O,{onClick:()=>F("")})]}),M(Ge,{children:[N(H,{disabled:P||x,ref:j,placeholder:"请输入你的问题, Enter+Shift换行, Enter发送",minRows:b,maxRows:5,value:z,onChange:e=>$(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),G())},autoFocus:w,onFocus:()=>A(!0),onBlur:()=>A(!1)}),l&&N(y,{tooltip:"可上传不超过6个小于20MB的文件",placement:"top",children:M(Oe,{disabled:R.length>=6,onClick:()=>q.current?.click(),children:[N("input",{onChange:J,multiple:!0,accept:B.join(","),ref:q,type:"file",hidden:!0}),N("i",{className:"bi bi-file-earmark-arrow-up"})]})}),c&&N(He,{ref:C,url:`${s.url}/transcriptions`,model:c.model,onResult:e=>{j.current?.focus(),$((t=>t+e+" "))}}),N(Oe,{className:"text-primary",disabled:!z&&0===Y.length,onClick:e=>{e.preventDefault(),G()},children:N("i",{className:"bi bi-send-fill"})})]})]})]})}));const Xe=f.div`
552
+ border-radius: var(--bs-border-radius-lg);
553
+ box-shadow: var(--bs-box-shadow-sm);
554
+ margin: 1rem;
555
+ padding: 1rem;
556
+ width: 100%;
557
+ max-width: 500px;
558
+ `,Je=f.div`
559
+ position: absolute;
560
+ left: 0;
561
+ right: 0;
562
+ top: 0;
563
+ bottom: 0;
564
+ background: #FFF;
565
+ display: flex;
566
+ justify-content: center;
567
+ align-items: center;
568
+ `,We=f(ye)`
569
+ width: calc((100% - .75rem) / 2);
570
+ `,Ye=f.div`
571
+ display: flex;
572
+ flex-wrap: wrap;
573
+ padding: .75rem;
574
+ gap: .75rem;
575
+ border-bottom: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
576
+ `,Ge=f.div`
571
577
  display: flex;
572
578
  padding: .5rem .5rem .5rem 1rem;
573
579
  gap: .25rem;
@@ -584,7 +590,7 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
584
590
  color: rgba(54, 54, 54, .3);
585
591
  }
586
592
  }
587
- `,Xe=f.div`
593
+ `,Ve=f.div`
588
594
  margin: .75rem .75rem 0 .75rem;
589
595
  padding: 4px 8px;
590
596
  display: flex;
@@ -605,14 +611,14 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
605
611
  -webkit-box-orient: vertical;
606
612
  display: -webkit-box;
607
613
  }
608
- `,Je=f.div`
614
+ `,Ze=f.div`
609
615
  background: #FFF;
610
616
  border: var(--bs-border-width) var(--bs-border-style) ${e=>e.$focused?"var(--bs-primary)":"var(--bs-border-color)"};
611
617
  border-radius: var(--bs-border-radius-lg);
612
618
  box-shadow: 0.125rem 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
613
- `,We=f.div`
619
+ `,et=f.div`
614
620
  margin: 0 1rem 1rem;
615
- `,Ye=a((e=>{let{className:i,bot:a,user:s,input:l,logLevel:c,imageResolver:d,placeholder:m,actions:u,messages:p=[],cite:f}=e;const[b,v]=h((()=>X(p))),[x,y]=n(!1),k=o(!l),w=o(null),j=r((()=>{const e=w.current;e&&requestAnimationFrame((()=>{e.scrollTo({top:e.scrollHeight})}))}),[]),{ref:N,height:$}=K(),[M,C]=n([]);return t((()=>{(x||!k.current)&&b.length>0&&(x&&(k.current=!0),j())}),[$,x,k,b]),t((()=>{M.length>0&&j()}),[M]),q(se,{bot:a,user:s,logLevel:c,imageResolver:d,children:q(er,{className:i,children:z(g,{children:[q(Ve,{ref:w,children:z(Ze,{ref:N,children:[0===b.length&&m,b.slice(-30).map(((e,r)=>q(ze,{actions:u,cite:f,message:e,updater:r=>{v((t=>{const n=t.findIndex((r=>r.id===e.id));-1!==n&&r(t[n])}))}},r))),M.length>0&&q(Ge,{children:M.map(((e,r)=>q("a",{href:"#!question",children:e},r)))})]})}),l&&q(Oe,{...l,onMessages:v,onSuggestions:C,scrollRef:w,onLoading:y})]})})})}),A),Ge=f.div`
621
+ `,tt=a((e=>{let{className:o,bot:a,user:s,input:l,logLevel:c,imageResolver:d,placeholder:m,actions:h,messages:p=[],cite:f}=e;const[b,v]=u((()=>J(p))),[x,y]=n(!1),k=i(!l),w=i(null),j=t((()=>{const e=w.current;e&&requestAnimationFrame((()=>{e.scrollTo({top:e.scrollHeight})}))}),[]),{ref:E,height:q}=Q(),[C,z]=n([]);return r((()=>{(x||!k.current)&&b.length>0&&(x&&(k.current=!0),j())}),[q,x,k,b]),r((()=>{C.length>0&&j()}),[C]),N(le,{bot:a,user:s,logLevel:c,imageResolver:d,children:N(ot,{className:o,children:M(g,{children:[N(nt,{ref:w,children:M(it,{ref:E,children:[0===b.length&&m,b.slice(-30).map(((e,t)=>N(qe,{actions:h,cite:f,message:e,updater:t=>{v((r=>{const n=r.findIndex((t=>t.id===e.id));-1!==n&&t(r[n])}))}},t))),C.length>0&&N(rt,{children:C.map(((e,t)=>N("a",{href:"#!question",children:e},t)))})]})}),l&&N(Qe,{...l,onMessages:v,onSuggestions:z,scrollRef:w,onLoading:y})]})})})}),B),rt=f.div`
616
622
  display: flex;
617
623
  flex-direction: column;
618
624
  align-items: flex-start;
@@ -629,20 +635,20 @@ import*as e from"react";import{useCallback as r,useEffect as t,useState as n,use
629
635
  background: var(--bs-secondary-bg-subtle);
630
636
  }
631
637
  }
632
- `,Ve=f.div`
638
+ `,nt=f.div`
633
639
  display: flex;
634
640
  flex-direction: column;
635
641
  flex: 1;
636
642
  overflow-y: auto;
637
643
  padding: 0 1rem;
638
644
  margin-bottom: .5rem;
639
- `,Ze=f.div`
645
+ `,it=f.div`
640
646
  display: flex;
641
647
  flex-direction: column;
642
648
  flex: 1;
643
- `,er=f.div`
649
+ `,ot=f.div`
644
650
  display: flex;
645
651
  flex-direction: column;
646
652
  height: 100%;
647
653
  position: relative;
648
- `;export{re as Markdown,Ye as MessageBox,Le as VariableForm,Q as pickQuestions,J as useChat};
654
+ `;export{re as Markdown,tt as MessageBox,Le as VariableForm,X as pickQuestions,W as useChat};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@topthink/chat",
3
- "version": "1.0.44-alpha.0+693f354",
3
+ "version": "1.0.45",
4
4
  "scripts": {
5
5
  "prebuild": "rimraf es types",
6
6
  "build": "rollup -c --environment NODE_ENV:production",
@@ -17,9 +17,11 @@
17
17
  ],
18
18
  "dependencies": {
19
19
  "@babel/runtime": "^7.11.2",
20
- "@topthink/components": "^1.0.102-alpha.0+693f354",
20
+ "@topthink/components": "^1.0.103",
21
21
  "@types/mdast": "^4.0.4",
22
+ "eventemitter3": "^5.0.1",
22
23
  "katex": "^0.16.9",
24
+ "lamejs": "github:zhuker/lamejs",
23
25
  "mdast-util-from-markdown": "^2.0.1",
24
26
  "micromark-util-character": "^2.1.0",
25
27
  "micromark-util-symbol": "^2.0.0",
@@ -32,10 +34,7 @@
32
34
  "remark-gfm": "^3.0.1",
33
35
  "remark-math": "^5.1.1",
34
36
  "unified": "^10.0.0",
35
- "use-resize-observer": "^9.1.0",
36
- "vega": "^5.30.0",
37
- "vega-embed": "^6.25.0",
38
- "vega-lite": "^5.19.0"
37
+ "use-resize-observer": "^9.1.0"
39
38
  },
40
39
  "peerDependencies": {
41
40
  "lodash": "*",
@@ -55,6 +54,7 @@
55
54
  "@rollup/plugin-terser": "^0.4.4",
56
55
  "@rollup/plugin-typescript": "^11.1.5",
57
56
  "@svgr/rollup": "^8.1.0",
57
+ "@types/dom-speech-recognition": "^0.0.4",
58
58
  "@types/lodash": "^4.14.161",
59
59
  "@types/node": "^18.11.18",
60
60
  "@types/react": "^17.0.0",
@@ -65,5 +65,5 @@
65
65
  },
66
66
  "author": "yunwuxin <tzzhangyajun@qq.com> (https://github.com/yunwuxin)",
67
67
  "license": "MIT",
68
- "gitHead": "693f354a4e7b1f57e63ccd487575b1b229d123b3"
68
+ "gitHead": "d7a5591cfeb4c32e37a598a052b0b4817da57cb0"
69
69
  }
@@ -20,6 +20,9 @@ interface Props {
20
20
  input?: {
21
21
  disabled?: boolean;
22
22
  fileTypes?: string[];
23
+ speech?: {
24
+ model?: string;
25
+ };
23
26
  minRows?: number;
24
27
  chat: ChatOptions;
25
28
  toolbar?: ReactNode;
@@ -1,6 +1,6 @@
1
1
  import { MutableRefObject, ReactNode } from 'react';
2
- import { Input, Message, Variable } from '../../types';
3
- import { ChatOptions } from '../../hooks/use-chat';
2
+ import { Input, Message, Variable } from '../../../types';
3
+ import { ChatOptions } from '../../../hooks/use-chat';
4
4
  interface Props {
5
5
  chat: ChatOptions;
6
6
  variables?: {
@@ -8,6 +8,9 @@ interface Props {
8
8
  values?: Record<string, string>;
9
9
  };
10
10
  fileTypes?: string[];
11
+ speech?: {
12
+ model?: string;
13
+ };
11
14
  minRows?: number;
12
15
  scrollRef: MutableRefObject<HTMLDivElement | null>;
13
16
  onMessages: (messages: Message[]) => void;
@@ -0,0 +1,3 @@
1
+ import { ButtonHTMLAttributes, ComponentType, DetailedHTMLProps } from 'react';
2
+ declare const InputButton: ComponentType<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>>;
3
+ export default InputButton;
@@ -0,0 +1,12 @@
1
+ /// <reference types="react" />
2
+ export interface Mic {
3
+ start: () => void;
4
+ stop: (force?: boolean) => void;
5
+ }
6
+ interface Props {
7
+ model?: string;
8
+ url: string;
9
+ onResult: (transcript: string) => void;
10
+ }
11
+ declare const MicButton: import("react").ForwardRefExoticComponent<Props & import("react").RefAttributes<Mic>>;
12
+ export default MicButton;
@@ -0,0 +1,10 @@
1
+ import { Recognition } from '../../types';
2
+ export default class Builtin implements Recognition {
3
+ #private;
4
+ constructor();
5
+ onResult(onResult: (transcript: string) => void): void;
6
+ onRecording(onRecording: (recording: boolean) => void): void;
7
+ onTranscribing(onTranscribing: (transcribing: boolean) => void): void;
8
+ start(): void;
9
+ stop(): void;
10
+ }
@@ -0,0 +1,13 @@
1
+ import { Recognition } from '../../types';
2
+ export default class Custom implements Recognition {
3
+ #private;
4
+ constructor(url: string, model: string);
5
+ start(): Promise<void>;
6
+ private convertBuffer;
7
+ private encodeMP3;
8
+ private save;
9
+ stop(): void;
10
+ onResult(onResult: (transcript: string) => void): void;
11
+ onRecording(onRecording: (recording: boolean) => void): void;
12
+ onTranscribing(onTranscribing: (transcribing: boolean) => void): void;
13
+ }
@@ -0,0 +1,12 @@
1
+ interface Config {
2
+ model?: string;
3
+ url: string;
4
+ onResult: (transcript: string) => void;
5
+ }
6
+ export default function useRecognition({ onResult, url, model }: Config): {
7
+ recording: boolean;
8
+ transcribing: boolean;
9
+ start: () => Promise<void>;
10
+ stop: () => void;
11
+ };
12
+ export {};
package/types/types.d.ts CHANGED
@@ -86,3 +86,10 @@ export interface Input extends Chat {
86
86
  setQuote(quote: string): void;
87
87
  focus(): void;
88
88
  }
89
+ export interface Recognition {
90
+ start(): void;
91
+ stop(): void;
92
+ onResult(onResult: (transcript: string) => void): void;
93
+ onRecording(onRecording: (recording: boolean) => void): void;
94
+ onTranscribing(onTranscribing: (transcribing: boolean) => void): void;
95
+ }
@@ -1,6 +0,0 @@
1
- /// <reference types="react" />
2
- interface Props {
3
- spec: string;
4
- }
5
- export default function Chart({ spec }: Props): JSX.Element | null;
6
- export {};