@topthink/chat 1.0.30 → 1.0.32

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 t,useState as r,useImperativeHandle as n,memo as o,useMemo as i,useRef as a,createContext as s,useContext as l,Fragment as c,forwardRef as d,useEffect as m}from"react";import{useImmer as h,request as p,isRequestError as u,Lightbox as g,styled as f,Clipboard as b,css as x,formatSize as v,Tooltip as k,useAsync as y,isImageUrl as w}from"@topthink/components";import{jsx as j,jsxs as N,Fragment as z}from"react/jsx-runtime";import M from"react-markdown";import"katex/dist/katex.min.css";import $ from"remark-math";import q from"remark-breaks";import C from"remark-gfm";import E from"rehype-katex";import F from"rehype-highlight";import{codes as R,types as S}from"micromark-util-symbol";import{markdownLineEnding as D}from"micromark-util-character";import{Spinner as T}from"react-bootstrap";import*as _ from"path";import B from"path";import L from"react-textarea-autosize";import O from"use-resize-observer";function A(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 P(e){return e.map((e=>({id:e.id,query:e.query,files:e.files||void 0,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 I(e){let{url:o,onboarding:i,onSuccess:a,ref:s,transformRequest:l,...c}=e;const d=t((e=>{const t=[];if(i&&!1!==i.enable&&i.prologue){const e=A(i.questions);t.push({chunks:[{content:[i.prologue,...e.map((e=>`[${e}](#!question)`))].join("\n"),tools:[]}]})}return e?t.concat(P(e.messages||[])):t}),[i]),[m,g]=h((()=>d(c.conversation))),[f,b]=r(!1),[x,v]=r(c.conversation?.id),k=t((async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(e||t.length>0){b(!0),g((r=>{r.push({query:e,files:t,chunks:[],loading:!0})}));try{let r={method:"post",url:o,data:{query:e,files:t,conversation:x},onMessage:e=>{if(e.data)if("[DONE]"!=e.data)try{const t=JSON.parse(e.data);t.conversation?v(t.conversation):g((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 g((e=>{e[e.length-1].loading=!1}))}};l&&(r=l("chat",r)),await p(r)}catch(e){let t="未知错误";u(e)&&(t=401==e.response?.status?"未授权或授权已过期,请刷新页面后重试":"string"==typeof e.errors?e.errors:Object.values(e.errors).join("\n")),g((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}))}b(!1),a?.()}}),[l,x]),y=t((e=>{f||(v(e?.id),g(d(e)))}),[f,d]);return n(s,(()=>({reset:y,send:k}))),{messages:m,loading:f,send:k,reset:y}}const U=function(e,t,r){function n(t){return t!==R.leftSquareBracket?(e.exit("citeMarker"),e.enter("citeData"),e.enter(S.chunkString,{contentType:"string"}),o(t)):(e.consume(t),n)}function o(n){return n===R.rightSquareBracket?(e.exit(S.chunkString),e.exit("citeData"),e.enter("citeMarker"),function(n){if(n!==R.rightSquareBracket)return r(n);return e.consume(n),e.exit("citeMarker"),e.exit("cite"),t(n)}(n)):D(n)||n===R.eof||n>57||n<48?r(n):(e.consume(n),o)}return function(t){return t!==R.leftSquareBracket?r(t):(e.enter("cite"),e.enter("citeMarker"),n(t))}},H=function(){const e=this.data();e.micromarkExtensions.push({text:{[R.leftSquareBracket]:{tokenize:U}}}),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}}})},K=g.Image,X={pre:e=>{let{children:t}=e;const r=a(null);return N(V,{ref:r,children:[j(Q,{tooltip:!1,content:()=>{const e=r.current?.getElementsByTagName("code");return e?.[0]?.innerText||""}}),t]})},a:e=>{let{node:t,href:r,...n}=e;const o=r?.startsWith("http")?"_blank":"_self";return j("a",{...n,href:r,target:o})},img:e=>{let{node:t,...r}=e;return j(K,{...r})}},J=[[$,{singleDollarTextMath:!1}],C,q],W=[E,[F,{detect:!1,ignoreMissing:!0}]],G=o((e=>{let{content:t,components:r,cite:n}=e;return t=t.replace(/\\\(\s(.+?)\s\\\)/g,"$$$$ $1 $$$$"),j(Y,{remarkPlugins:i((()=>n?[...J,H]:J),[n]),rehypePlugins:W,components:i((()=>({...X,...r})),[r]),children:t})})),Q=f(b)`
1
+ import*as e from"react";import{useCallback as t,useState as r,useRef as n,useImperativeHandle as o,memo as i,useMemo as a,createContext as s,useContext as l,Fragment as c,forwardRef as d,useEffect 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 x,formatSize as v,Tooltip as k,useAsync as y,isImageUrl as w}from"@topthink/components";import{jsx as j,jsxs as N,Fragment as z}from"react/jsx-runtime";import M from"react-markdown";import"katex/dist/katex.min.css";import $ from"remark-math";import q from"remark-breaks";import C from"remark-gfm";import E from"rehype-katex";import F from"rehype-highlight";import{codes as S,types as R}from"micromark-util-symbol";import{markdownLineEnding as D}from"micromark-util-character";import{Spinner as T}from"react-bootstrap";import*as _ from"path";import B from"path";import L from"react-textarea-autosize";import O from"use-resize-observer";function A(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 P(e){return e.map((e=>({id:e.id,query:e.query,files:e.files||void 0,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 I(e){let{url:i,onboarding:a,suggestion:s,onSuccess:l,ref:c,transformRequest:d,...m}=e;const g=t((e=>{const t=[];if(a&&!1!==a.enable&&a.prologue){const e=A(a.questions);t.push({chunks:[{content:[a.prologue,...e.map((e=>`[${e}](#!question)`))].join("\n"),tools:[]}]})}return e?t.concat(P(e.messages||[])):t}),[a]),[f,b]=h((()=>g(m.conversation))),[x,v]=r([]),[k,y]=r(!1),w=n(m.conversation?.id),j=n(null),N=t((async()=>{j.current=new AbortController;try{let e={method:"post",url:`${i}/suggestion`,data:{conversation:w.current},signal:j.current.signal};d&&(e=d("suggestion",e));const t=await u(e);v(t)}catch{}finally{j.current=null}}),[d,i]),z=t((async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(e||t.length>0){j.current&&j.current.abort(),y(!0),v([]),b((r=>{r.push({query:e,files:t,chunks:[],loading:!0})}));try{let r={method:"post",url:i,data:{query:e,files:t,conversation:w.current},onMessage:e=>{if(e.data)if("[DONE]"!=e.data)try{const t=JSON.parse(e.data);t.conversation?w.current=t.conversation:b((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 b((e=>{e[e.length-1].loading=!1}))}};d&&(r=d("chat",r)),await u(r),s?.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")),b((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}))}y(!1),l?.()}}),[d,i]),M=t((e=>{k||(w.current=e?.id,b(g(e)),v([]))}),[k,g]);return o(c,(()=>({reset:M,send:z}))),{messages:f,suggestions:x,loading:k,send:z,reset:M}}const U=function(e,t,r){function n(t){return t!==S.leftSquareBracket?(e.exit("citeMarker"),e.enter("citeData"),e.enter(R.chunkString,{contentType:"string"}),o(t)):(e.consume(t),n)}function o(n){return n===S.rightSquareBracket?(e.exit(R.chunkString),e.exit("citeData"),e.enter("citeMarker"),function(n){if(n!==S.rightSquareBracket)return r(n);return e.consume(n),e.exit("citeMarker"),e.exit("cite"),t(n)}(n)):D(n)||n===S.eof||n>57||n<48?r(n):(e.consume(n),o)}return function(t){return t!==S.leftSquareBracket?r(t):(e.enter("cite"),e.enter("citeMarker"),n(t))}},H=function(){const e=this.data();e.micromarkExtensions.push({text:{[S.leftSquareBracket]:{tokenize:U}}}),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}}})},K=g.Image,X={pre:e=>{let{children:t}=e;const r=n(null);return N(V,{ref:r,children:[j(Q,{tooltip:!1,content:()=>{const e=r.current?.getElementsByTagName("code");return e?.[0]?.innerText||""}}),t]})},a:e=>{let{node:t,href:r,...n}=e;const o=r?.startsWith("http")?"_blank":"_self";return j("a",{...n,href:r,target:o})},img:e=>{let{node:t,...r}=e;return j(K,{...r})}},J=[[$,{singleDollarTextMath:!1}],C,q],W=[E,[F,{detect:!1,ignoreMissing:!0}]],G=i((e=>{let{content:t,components:r,cite:n}=e;return t=t.replace(/\\\(\s(.+?)\s\\\)/g,"$$$$ $1 $$$$"),j(Y,{remarkPlugins:a((()=>n?[...J,H]:J),[n]),rehypePlugins:W,components:a((()=>({...X,...r})),[r]),children:t})})),Q=f(b)`
2
2
  position: absolute;
3
3
  right: 10px;
4
4
  top: 1em;
@@ -325,7 +325,7 @@ import*as e from"react";import{useCallback as t,useState as r,useImperativeHandl
325
325
  }
326
326
  `;function ie(e){let{tool:t}=e;const[n,o]=r(!1),{logLevel:i="none"}=ee();let a=null;t.content&&("string"==typeof t.content?a=j(G,{content:t.content}):"image"===t.content.type&&(a=j(ne,{src:t.content.image})));const s="response"in t;return N(c,{children:["stats"==i&&j("div",{className:"mb-2",children:N("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?j("i",{className:"bi bi-x-circle-fill text-danger"}):j("i",{className:"bi bi-check-circle-fill text-success"}):j(T,{animation:"border",variant:"primary",size:"sm"}),j("span",{className:"text-muted",children:s?"已使用":"正在使用"}),j("span",{children:t.title})]})}),"all"==i&&j("div",{className:"mb-2",children:N("div",n&&s?{className:"shadow-sm rounded bg-white fs-7",children:[N("div",{onClick:()=>o(!1),role:"button",className:"d-flex align-items-center p-1 px-2 gap-2",children:[t.error?j("i",{className:"bi bi-x-circle-fill text-danger"}):j("i",{className:"bi bi-check-circle-fill text-success"}),j("span",{className:"text-muted",children:"已使用"}),j("span",{children:t.title}),j("i",{className:"bi bi-caret-up-fill text-muted"})]}),N("div",{className:"border-top p-2 d-flex flex-column gap-2",children:[N("div",{className:"border rounded bg-light",children:[j("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:j("span",{className:"text-muted",children:"参数"})}),j("div",{className:"border-top p-2 overflow-hidden",children:t.arguments})]}),N("div",{className:"border rounded bg-light",children:[j("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:j("span",{className:"text-muted",children:"响应"})}),j(ae,{className:"border-top p-2 overflow-hidden",children:t.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?t.error?j("i",{className:"bi bi-x-circle-fill text-danger"}):j("i",{className:"bi bi-check-circle-fill text-success"}):j(T,{animation:"border",variant:"primary",size:"sm"}),j("span",{className:"text-muted",children:s?"已使用":"正在使用"}),j("span",{children:t.title}),s&&j("i",{className:"bi bi-caret-down-fill text-muted"})]})}),a]})}const ae=f.div`
327
327
  white-space: pre-wrap;
328
- `;var se,le,ce;function de(){return de=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},de.apply(this,arguments)}const me=t=>e.createElement("svg",de({xmlns:"http://www.w3.org/2000/svg",width:20,height:10,fill:"#fff",viewBox:"0 0 120 30"},t),se||(se=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"}))),le||(le=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"}))),ce||(ce=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 he=function(e){let{ext:t}=e;const{result:r}=y((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?j("img",{width:30,height:30,src:r}):null};function pe(e){let{className:t,name:r,size:n,loading:o,error:i,onRemove:a}=e;const s=B.extname(r).substring(1),l=N(be,{className:t,$error:!!i,children:[N(fe,{children:[j(he,{ext:s}),o&&j(T,{variant:"primary"})]}),N(ge,{children:[j("h4",{children:r}),j("p",{children:v(n,1)})]}),a&&j(ue,{onClick:e=>{e.preventDefault(),a()},children:j("i",{className:"bi bi-trash3"})})]});return i?j(k,{placement:"top",tooltip:i,children:l}):l}const ue=f.div`
328
+ `;var se,le,ce;function de(){return de=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},de.apply(this,arguments)}const me=t=>e.createElement("svg",de({xmlns:"http://www.w3.org/2000/svg",width:20,height:10,fill:"#fff",viewBox:"0 0 120 30"},t),se||(se=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"}))),le||(le=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"}))),ce||(ce=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 he=function(e){let{ext:t}=e;const{result:r}=y((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?j("img",{width:30,height:30,src:r}):null};function ue(e){let{className:t,name:r,size:n,loading:o,error:i,onRemove:a}=e;const s=B.extname(r).substring(1),l=N(be,{className:t,$error:!!i,children:[N(fe,{children:[j(he,{ext:s}),o&&j(T,{variant:"primary"})]}),N(ge,{children:[j("h4",{children:r}),j("p",{children:v(n,1)})]}),a&&j(pe,{onClick:e=>{e.preventDefault(),a()},children:j("i",{className:"bi bi-trash3"})})]});return i?j(k,{placement:"top",tooltip:i,children:l}):l}const pe=f.div`
329
329
  width: 1.75rem;
330
330
  height: 1.75rem;
331
331
  align-items: center;
@@ -415,7 +415,7 @@ import*as e from"react";import{useCallback as t,useState as r,useImperativeHandl
415
415
  background-color: var(--bs-gray-200);
416
416
  }
417
417
  }
418
- `,ke=o((e=>{let{message:t,actions:r,updater:n}=e;const{query:o,files:a=[],chunks:s,annotation:l}=t,{user:d,bot:m,logLevel:h="none"}=ee(),p=i((()=>s?s.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),"")}),""):""),[s]);return N(z,{children:[(o||a.length>0)&&N($e,{$reverse:!0,children:[d&&j(ze,{children:j("img",{src:d.avatar})}),N(Me,{children:[o&&j(G,{content:o}),a.length>0&&a.map(((e,t)=>{let{name:r,size:n,path:o}=e;return w(o)?j(ne,{src:`/uploads/${o}`},t):j(we,{children:j(pe,{name:r,size:n})},t)}))]})]}),s&&N($e,{children:[j(ze,{children:j("img",{src:m.avatar})}),N(Me,{children:[(o||a.length>0)&&N(je,{children:[j(b,{placement:"top",content:p,as:xe,tooltip:!0}),r?.({Component:xe,message:t,content:p,setMessage:n})]}),j(Ne,{children:["stats","all"].includes(h)&&t.stats&&N(z,{children:[N("span",{children:["耗时 ",t.stats.latency/1e3," 秒"]}),N("span",{children:["花费 Token ",t.stats.usage]})]})}),j(ye,{$deleted:!!l,children:s.length>0&&s.map(((e,t)=>N(c,{children:[e.content&&j(G,{content:e.content}),e.tools.map(((e,t)=>j(ie,{tool:e},t))),e.error&&j(G,{content:`[${e.error}]`})]},t)))}),l&&N("div",{children:[N("div",{className:"d-flex align-items-center",children:[j("span",{className:"fs-7 text-secondary me-2",children:"标注的答案"}),j("hr",{className:"flex-fill"})]}),j(G,{content:l.answer})]}),t.loading&&j(me,{})]})]})]})})),ye=f.div`
418
+ `,ke=i((e=>{let{message:t,actions:r,updater:n}=e;const{query:o,files:i=[],chunks:s,annotation:l}=t,{user:d,bot:m,logLevel:h="none"}=ee(),u=a((()=>s?s.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),"")}),""):""),[s]);return N(z,{children:[(o||i.length>0)&&N($e,{$reverse:!0,children:[d&&j(ze,{children:j("img",{src:d.avatar})}),N(Me,{children:[o&&j(G,{content:o}),i.length>0&&i.map(((e,t)=>{let{name:r,size:n,path:o}=e;return w(o)?j(ne,{src:`/uploads/${o}`},t):j(we,{children:j(ue,{name:r,size:n})},t)}))]})]}),s&&N($e,{children:[j(ze,{children:j("img",{src:m.avatar})}),N(Me,{children:[(o||i.length>0)&&N(je,{children:[j(b,{placement:"top",content:u,as:xe,tooltip:!0}),r?.({Component:xe,message:t,content:u,setMessage:n})]}),j(Ne,{children:["stats","all"].includes(h)&&t.stats&&N(z,{children:[N("span",{children:["耗时 ",t.stats.latency/1e3," 秒"]}),N("span",{children:["花费 Token ",t.stats.usage]})]})}),j(ye,{$deleted:!!l,children:s.length>0&&s.map(((e,t)=>N(c,{children:[e.content&&j(G,{content:e.content}),e.tools.map(((e,t)=>j(ie,{tool:e},t))),e.error&&j(G,{content:`[${e.error}]`})]},t)))}),l&&N("div",{children:[N("div",{className:"d-flex align-items-center",children:[j("span",{className:"fs-7 text-secondary me-2",children:"标注的答案"}),j("hr",{className:"flex-fill"})]}),j(G,{content:l.answer})]}),t.loading&&j(me,{})]})]})]})})),ye=f.div`
419
419
  ${e=>e.$deleted&&x`
420
420
  text-decoration-line: line-through;
421
421
  color: var(--bs-secondary);
@@ -509,7 +509,7 @@ import*as e from"react";import{useCallback as t,useState as r,useImperativeHandl
509
509
  }
510
510
  }
511
511
  `};
512
- `,qe=[".txt",".md",".pdf",".docx",".xlsx",".pptx",".png",".jpg"];function Ce(e){let{chat:n,fileTypes:o,scrollRef:i,onMessages:s,minRows:l,toolbar:c,disabled:d,onLoading:g,autoFocus:f}=e;const b=a(null),x=a(null),[v,y]=r(""),[w,z]=h([]),[M,$]=r(!1),q=o&&o.length>0?o:qe,{loading:C,messages:E,send:F}=I({...n,onSuccess(){requestAnimationFrame((()=>{b.current?.focus()})),n.onSuccess?.()}});m((()=>{s(E)}),[E]),m((()=>{g?.(C)}),[C]),m((()=>{!o&&w.length>0&&z([])}),[o]),m((()=>{const e=i.current;if(e&&F){const t=e=>{e.target instanceof HTMLAnchorElement&&"#!question"===e.target.hash&&(e.preventDefault(),F(e.target.text))};return e.addEventListener("click",t),()=>{e.removeEventListener("click",t)}}}),[i,F]);const R=t((e=>{let{target:t}=e;if(t.files){const e=Array.from(t.files).filter((e=>!!q.includes(_.extname(e.name))&&(!(e.size>20971520)&&e))).slice(0,6-w.length);z((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:`${n.url}/upload`,data:t};n.transformRequest&&(r=n.transformRequest("upload",r));const o=await p(r);z((t=>{const r=t.find((t=>t.file===e));r&&(r.path=o.path)}))}catch(t){const r=u(t)?t.message:"unknown error";z((t=>{const n=t.find((t=>t.file===e));n&&(n.error=r)}))}}))}t.value=""}),[w,q]),S=w.flatMap((e=>{let{file:t,path:r}=e;return r?[{name:t.name,size:t.size,path:r}]:[]})),D=()=>{(v||S.length>0)&&(F(v,S),y(""),z([]))};return N(Te,{children:[c,N(De,{$focused:M&&!C,children:[w.length>0&&j(Fe,{children:w.map(((e,t)=>{let{file:r,error:n,path:o}=e;const i=void 0===n&&void 0===o;return j(Ee,{name:r.name,size:r.size,error:n,loading:i,onRemove:()=>{z((e=>{const t=e.findIndex((e=>e.file===r));-1!==t&&e.splice(t,1)}))}},t)}))}),N(Se,{children:[j(L,{disabled:C||d,ref:b,placeholder:"请输入你的问题, Enter+Shift换行, Enter发送",minRows:l,maxRows:5,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),D())},autoFocus:f,onFocus:()=>$(!0),onBlur:()=>$(!1)}),o&&j(k,{tooltip:"可上传不超过6个小于20MB的文件",placement:"top",children:N(Re,{disabled:w.length>=6,onClick:()=>x.current?.click(),children:[j("input",{onChange:R,multiple:!0,accept:q.join(","),ref:x,type:"file",hidden:!0}),j("i",{className:"bi bi-file-earmark-arrow-up"})]})}),j(Re,{className:"text-primary",disabled:!v&&0===S.length,onClick:e=>{e.preventDefault(),D()},children:j("i",{className:"bi bi-send-fill"})})]})]})]})}const Ee=f(pe)`
512
+ `,qe=[".txt",".md",".pdf",".docx",".xlsx",".pptx",".png",".jpg"];function Ce(e){let{chat:o,fileTypes:i,scrollRef:a,onMessages:s,onSuggestions:l,minRows:c,toolbar:d,disabled:g,onLoading:f,autoFocus:b}=e;const x=n(null),v=n(null),[y,w]=r(""),[z,M]=h([]),[$,q]=r(!1),C=i&&i.length>0?i:qe,{loading:E,messages:F,suggestions:S,send:R}=I({...o,onSuccess(){requestAnimationFrame((()=>{x.current?.focus()})),o.onSuccess?.()}});m((()=>{s(F)}),[F]),m((()=>{l(S)}),[S]),m((()=>{f?.(E)}),[E]),m((()=>{!i&&z.length>0&&M([])}),[i]),m((()=>{const e=a.current;if(e&&R){const t=e=>{e.target instanceof HTMLAnchorElement&&"#!question"===e.target.hash&&(e.preventDefault(),R(e.target.text))};return e.addEventListener("click",t),()=>{e.removeEventListener("click",t)}}}),[a,R]);const D=t((e=>{let{target:t}=e;if(t.files){const e=Array.from(t.files).filter((e=>!!C.includes(_.extname(e.name))&&(!(e.size>20971520)&&e))).slice(0,6-z.length);M((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:`${o.url}/upload`,data:t};o.transformRequest&&(r=o.transformRequest("upload",r));const n=await u(r);M((t=>{const r=t.find((t=>t.file===e));r&&(r.path=n.path)}))}catch(t){const r=p(t)?t.message:"unknown error";M((t=>{const n=t.find((t=>t.file===e));n&&(n.error=r)}))}}))}t.value=""}),[z,C]),T=z.flatMap((e=>{let{file:t,path:r}=e;return r?[{name:t.name,size:t.size,path:r}]:[]})),B=()=>{(y||T.length>0)&&(R(y,T),w(""),M([]))};return N(Te,{children:[d,N(De,{$focused:$&&!E,children:[z.length>0&&j(Fe,{children:z.map(((e,t)=>{let{file:r,error:n,path:o}=e;const i=void 0===n&&void 0===o;return j(Ee,{name:r.name,size:r.size,error:n,loading:i,onRemove:()=>{M((e=>{const t=e.findIndex((e=>e.file===r));-1!==t&&e.splice(t,1)}))}},t)}))}),N(Re,{children:[j(L,{disabled:E||g,ref:x,placeholder:"请输入你的问题, Enter+Shift换行, Enter发送",minRows:c,maxRows:5,value:y,onChange:e=>w(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),B())},autoFocus:b,onFocus:()=>q(!0),onBlur:()=>q(!1)}),i&&j(k,{tooltip:"可上传不超过6个小于20MB的文件",placement:"top",children:N(Se,{disabled:z.length>=6,onClick:()=>v.current?.click(),children:[j("input",{onChange:D,multiple:!0,accept:C.join(","),ref:v,type:"file",hidden:!0}),j("i",{className:"bi bi-file-earmark-arrow-up"})]})}),j(Se,{className:"text-primary",disabled:!y&&0===T.length,onClick:e=>{e.preventDefault(),B()},children:j("i",{className:"bi bi-send-fill"})})]})]})]})}const Ee=f(ue)`
513
513
  width: calc((100% - .75rem) / 2);
514
514
  `,Fe=f.div`
515
515
  display: flex;
@@ -517,7 +517,7 @@ import*as e from"react";import{useCallback as t,useState as r,useImperativeHandl
517
517
  padding: .75rem;
518
518
  gap: .75rem;
519
519
  border-bottom: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
520
- `,Re=f.button`
520
+ `,Se=f.button`
521
521
  color: var(--bs-secondary);
522
522
  cursor: pointer;
523
523
  display: flex;
@@ -539,7 +539,7 @@ import*as e from"react";import{useCallback as t,useState as r,useImperativeHandl
539
539
  background-color: var(--bs-gray-200);
540
540
  }
541
541
 
542
- `,Se=f.div`
542
+ `,Re=f.div`
543
543
  display: flex;
544
544
  padding: .5rem .5rem .5rem 1rem;
545
545
  gap: .25rem;
@@ -563,18 +563,35 @@ import*as e from"react";import{useCallback as t,useState as r,useImperativeHandl
563
563
  box-shadow: 0.125rem 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
564
564
  `,Te=f.div`
565
565
  margin: 0 1rem 1rem;
566
- `;function _e(e){let{className:n,bot:o,user:i,input:s,logLevel:l,imageResolver:c,placeholder:d,actions:p,...u}=e;const[f,b]=h((()=>P(u.messages||[]))),[x,v]=r(!1),k=a(!s),y=a(null),w=t((()=>{const e=y.current;e&&requestAnimationFrame((()=>{e.scrollTo({top:e.scrollHeight})}))}),[]),{ref:z,height:M}=O();return m((()=>{!x&&k.current||(x&&(k.current=!0),w())}),[M,x,k]),j(te,{bot:o,user:i,logLevel:l,imageResolver:c,children:j(Oe,{className:n,children:N(g,{children:[j(Be,{ref:y,children:N(Le,{ref:z,children:[0===f.length&&d,f.slice(-30).map(((e,t)=>j(ke,{actions:p,message:e,updater:t=>{b((r=>{const n=r.findIndex((t=>t.id===e.id));-1!==n&&t(r[n])}))}},t)))]})}),s&&j(Ce,{onMessages:b,scrollRef:y,onLoading:v,...s})]})})})}const Be=f.div`
566
+ `;function _e(e){let{className:o,bot:i,user:a,input:s,logLevel:l,imageResolver:c,placeholder:d,actions:u,...p}=e;const[f,b]=h((()=>P(p.messages||[]))),[x,v]=r(!1),k=n(!s),y=n(null),w=t((()=>{const e=y.current;e&&requestAnimationFrame((()=>{e.scrollTo({top:e.scrollHeight})}))}),[]),{ref:z,height:M}=O(),[$,q]=r([]);return m((()=>{!x&&k.current||(x&&(k.current=!0),w())}),[M,x,k]),m((()=>{w()}),[$]),j(te,{bot:i,user:a,logLevel:l,imageResolver:c,children:j(Ae,{className:o,children:N(g,{children:[j(Le,{ref:y,children:N(Oe,{ref:z,children:[0===f.length&&d,f.slice(-30).map(((e,t)=>j(ke,{actions:u,message:e,updater:t=>{b((r=>{const n=r.findIndex((t=>t.id===e.id));-1!==n&&t(r[n])}))}},t))),$.length>0&&j(Be,{children:$.map(((e,t)=>j("a",{href:"#!question",children:e},t)))})]})}),s&&j(Ce,{onMessages:b,onSuggestions:q,scrollRef:y,onLoading:v,...s})]})})})}const Be=f.div`
567
+ display: flex;
568
+ flex-direction: column;
569
+ align-items: flex-start;
570
+ gap: .5rem;
571
+ padding: 1rem 0 1rem 45px;
572
+
573
+ a {
574
+ background: rgb(243, 243, 243);
575
+ padding: .5rem 1rem;
576
+ border-radius: var(--bs-border-radius-lg);
577
+
578
+ &:hover {
579
+ color: inherit;
580
+ background: var(--bs-secondary-bg-subtle);
581
+ }
582
+ }
583
+ `,Le=f.div`
567
584
  display: flex;
568
585
  flex-direction: column;
569
586
  flex: 1;
570
587
  overflow-y: auto;
571
588
  padding: 0 1rem;
572
589
  margin-bottom: .5rem;
573
- `,Le=f.div`
590
+ `,Oe=f.div`
574
591
  display: flex;
575
592
  flex-direction: column;
576
593
  flex: 1;
577
- `,Oe=f.div`
594
+ `,Ae=f.div`
578
595
  display: flex;
579
596
  flex-direction: column;
580
597
  height: 100%;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@topthink/chat",
3
- "version": "1.0.30",
3
+ "version": "1.0.32",
4
4
  "scripts": {
5
5
  "prebuild": "rimraf es types",
6
6
  "build": "rollup -c --environment NODE_ENV:production",
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "dependencies": {
19
19
  "@babel/runtime": "^7.11.2",
20
- "@topthink/components": "^1.0.93",
20
+ "@topthink/components": "^1.0.94",
21
21
  "@types/mdast": "^4.0.4",
22
22
  "katex": "^0.16.9",
23
23
  "mdast-util-from-markdown": "^2.0.1",
@@ -65,5 +65,5 @@
65
65
  },
66
66
  "author": "yunwuxin <tzzhangyajun@qq.com> (https://github.com/yunwuxin)",
67
67
  "license": "MIT",
68
- "gitHead": "afc5154914b1f3a021798d6e947cc0e3050bde26"
68
+ "gitHead": "85a643b8133bb947e5f6bef3bcf5f8e9c335c68f"
69
69
  }
@@ -7,10 +7,11 @@ interface Props {
7
7
  minRows?: number;
8
8
  scrollRef: MutableRefObject<HTMLDivElement | null>;
9
9
  onMessages: (messages: Message[]) => void;
10
+ onSuggestions: (suggestions: string[]) => void;
10
11
  toolbar?: ReactNode;
11
12
  disabled?: boolean;
12
13
  onLoading?: (loading: boolean) => void;
13
14
  autoFocus?: boolean;
14
15
  }
15
- export default function ({ chat, fileTypes, scrollRef, onMessages, minRows, toolbar, disabled, onLoading, autoFocus }: Props): JSX.Element;
16
+ export default function ({ chat, fileTypes, scrollRef, onMessages, onSuggestions, minRows, toolbar, disabled, onLoading, autoFocus }: Props): JSX.Element;
16
17
  export {};
@@ -3,18 +3,22 @@ import { Chat, Conversation, Message } from '../types';
3
3
  import { RequestConfig } from '@topthink/components';
4
4
  export interface ChatOptions {
5
5
  url: string;
6
- transformRequest?: (scene: 'chat' | 'upload', config: Exclude<RequestConfig, string>) => Exclude<RequestConfig, string>;
6
+ transformRequest?: (scene: 'chat' | 'upload' | 'suggestion', config: Exclude<RequestConfig, string>) => Exclude<RequestConfig, string>;
7
7
  onSuccess?: () => void;
8
8
  onboarding?: {
9
9
  enable?: boolean;
10
10
  prologue: string;
11
11
  questions: string[];
12
12
  };
13
+ suggestion?: {
14
+ enable?: boolean;
15
+ };
13
16
  conversation?: Conversation;
14
17
  ref?: MutableRefObject<Chat | null>;
15
18
  }
16
- export default function useChat({ url, onboarding, onSuccess, ref, transformRequest, ...props }: ChatOptions): {
19
+ export default function useChat({ url, onboarding, suggestion, onSuccess, ref, transformRequest, ...props }: ChatOptions): {
17
20
  messages: Message[];
21
+ suggestions: string[];
18
22
  loading: boolean;
19
23
  send: (query: string, files?: Message['files']) => Promise<void>;
20
24
  reset: (conversation?: Conversation) => void;