ChatMessage.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import { useMemo, useState } from 'react';
  2. import { useAppContext } from '../utils/app.context';
  3. import { Message, PendingMessage } from '../utils/types';
  4. import { classNames } from '../utils/misc';
  5. import MarkdownDisplay, { CopyButton } from './MarkdownDisplay';
  6. import {
  7. ArrowPathIcon,
  8. ChevronLeftIcon,
  9. ChevronRightIcon,
  10. PencilSquareIcon,
  11. } from '@heroicons/react/24/outline';
  12. import ChatInputExtraContextItem from './ChatInputExtraContextItem';
  13. import { BtnWithTooltips } from '../utils/common';
  14. interface SplitMessage {
  15. content: PendingMessage['content'];
  16. thought?: string;
  17. isThinking?: boolean;
  18. }
  19. export default function ChatMessage({
  20. msg,
  21. siblingLeafNodeIds,
  22. siblingCurrIdx,
  23. id,
  24. onRegenerateMessage,
  25. onEditMessage,
  26. onChangeSibling,
  27. isPending,
  28. }: {
  29. msg: Message | PendingMessage;
  30. siblingLeafNodeIds: Message['id'][];
  31. siblingCurrIdx: number;
  32. id?: string;
  33. onRegenerateMessage(msg: Message): void;
  34. onEditMessage(msg: Message, content: string): void;
  35. onChangeSibling(sibling: Message['id']): void;
  36. isPending?: boolean;
  37. }) {
  38. const { viewingChat, config } = useAppContext();
  39. const [editingContent, setEditingContent] = useState<string | null>(null);
  40. const timings = useMemo(
  41. () =>
  42. msg.timings
  43. ? {
  44. ...msg.timings,
  45. prompt_per_second:
  46. (msg.timings.prompt_n / msg.timings.prompt_ms) * 1000,
  47. predicted_per_second:
  48. (msg.timings.predicted_n / msg.timings.predicted_ms) * 1000,
  49. }
  50. : null,
  51. [msg.timings]
  52. );
  53. const nextSibling = siblingLeafNodeIds[siblingCurrIdx + 1];
  54. const prevSibling = siblingLeafNodeIds[siblingCurrIdx - 1];
  55. // for reasoning model, we split the message into content and thought
  56. // TODO: implement this as remark/rehype plugin in the future
  57. const { content, thought, isThinking }: SplitMessage = useMemo(() => {
  58. if (msg.content === null || msg.role !== 'assistant') {
  59. return { content: msg.content };
  60. }
  61. const REGEX_THINK_OPEN = /<think>|<\|channel\|>analysis<\|message\|>/;
  62. const REGEX_THINK_CLOSE = /<\/think>|<\|end\|>/;
  63. let actualContent = '';
  64. let thought = '';
  65. let isThinking = false;
  66. let thinkSplit = msg.content.split(REGEX_THINK_OPEN, 2);
  67. actualContent += thinkSplit[0];
  68. while (thinkSplit[1] !== undefined) {
  69. // <think> tag found
  70. thinkSplit = thinkSplit[1].split(REGEX_THINK_CLOSE, 2);
  71. thought += thinkSplit[0];
  72. isThinking = true;
  73. if (thinkSplit[1] !== undefined) {
  74. // </think> closing tag found
  75. isThinking = false;
  76. thinkSplit = thinkSplit[1].split(REGEX_THINK_OPEN, 2);
  77. actualContent += thinkSplit[0];
  78. }
  79. }
  80. return { content: actualContent, thought, isThinking };
  81. }, [msg]);
  82. if (!viewingChat) return null;
  83. const isUser = msg.role === 'user';
  84. return (
  85. <div
  86. className="group"
  87. id={id}
  88. role="group"
  89. aria-description={`Message from ${msg.role}`}
  90. >
  91. <div
  92. className={classNames({
  93. chat: true,
  94. 'chat-start': !isUser,
  95. 'chat-end': isUser,
  96. })}
  97. >
  98. {msg.extra && msg.extra.length > 0 && (
  99. <ChatInputExtraContextItem items={msg.extra} clickToShow />
  100. )}
  101. <div
  102. className={classNames({
  103. 'chat-bubble markdown': true,
  104. 'chat-bubble bg-transparent': !isUser,
  105. })}
  106. >
  107. {/* textarea for editing message */}
  108. {editingContent !== null && (
  109. <>
  110. <textarea
  111. dir="auto"
  112. className="textarea textarea-bordered bg-base-100 text-base-content max-w-2xl w-[calc(90vw-8em)] h-24"
  113. value={editingContent}
  114. onChange={(e) => setEditingContent(e.target.value)}
  115. ></textarea>
  116. <br />
  117. <button
  118. className="btn btn-ghost mt-2 mr-2"
  119. onClick={() => setEditingContent(null)}
  120. >
  121. Cancel
  122. </button>
  123. <button
  124. className="btn mt-2"
  125. onClick={() => {
  126. if (msg.content !== null) {
  127. setEditingContent(null);
  128. onEditMessage(msg as Message, editingContent);
  129. }
  130. }}
  131. >
  132. Submit
  133. </button>
  134. </>
  135. )}
  136. {/* not editing content, render message */}
  137. {editingContent === null && (
  138. <>
  139. {content === null ? (
  140. <>
  141. {/* show loading dots for pending message */}
  142. <span className="loading loading-dots loading-md"></span>
  143. </>
  144. ) : (
  145. <>
  146. {/* render message as markdown */}
  147. <div dir="auto" tabIndex={0}>
  148. {thought && (
  149. <ThoughtProcess
  150. isThinking={!!isThinking && !!isPending}
  151. content={thought}
  152. open={config.showThoughtInProgress}
  153. />
  154. )}
  155. <MarkdownDisplay
  156. content={content}
  157. isGenerating={isPending}
  158. />
  159. </div>
  160. </>
  161. )}
  162. {/* render timings if enabled */}
  163. {timings && config.showTokensPerSecond && (
  164. <div className="dropdown dropdown-hover dropdown-top mt-2">
  165. <div
  166. tabIndex={0}
  167. role="button"
  168. className="cursor-pointer font-semibold text-sm opacity-60"
  169. >
  170. Speed: {timings.predicted_per_second.toFixed(1)} t/s
  171. </div>
  172. <div className="dropdown-content bg-base-100 z-10 w-64 p-2 shadow mt-4">
  173. <b>Prompt</b>
  174. <br />- Tokens: {timings.prompt_n}
  175. <br />- Time: {timings.prompt_ms} ms
  176. <br />- Speed: {timings.prompt_per_second.toFixed(1)} t/s
  177. <br />
  178. <b>Generation</b>
  179. <br />- Tokens: {timings.predicted_n}
  180. <br />- Time: {timings.predicted_ms} ms
  181. <br />- Speed: {timings.predicted_per_second.toFixed(1)} t/s
  182. <br />
  183. </div>
  184. </div>
  185. )}
  186. </>
  187. )}
  188. </div>
  189. </div>
  190. {/* actions for each message */}
  191. {msg.content !== null && (
  192. <div
  193. className={classNames({
  194. 'flex items-center gap-2 mx-4 mt-2 mb-2': true,
  195. 'flex-row-reverse': msg.role === 'user',
  196. })}
  197. >
  198. {siblingLeafNodeIds && siblingLeafNodeIds.length > 1 && (
  199. <div
  200. className="flex gap-1 items-center opacity-60 text-sm"
  201. role="navigation"
  202. aria-description={`Message version ${siblingCurrIdx + 1} of ${siblingLeafNodeIds.length}`}
  203. >
  204. <button
  205. className={classNames({
  206. 'btn btn-sm btn-ghost p-1': true,
  207. 'opacity-20': !prevSibling,
  208. })}
  209. onClick={() => prevSibling && onChangeSibling(prevSibling)}
  210. aria-label="Previous message version"
  211. >
  212. <ChevronLeftIcon className="h-4 w-4" />
  213. </button>
  214. <span>
  215. {siblingCurrIdx + 1} / {siblingLeafNodeIds.length}
  216. </span>
  217. <button
  218. className={classNames({
  219. 'btn btn-sm btn-ghost p-1': true,
  220. 'opacity-20': !nextSibling,
  221. })}
  222. onClick={() => nextSibling && onChangeSibling(nextSibling)}
  223. aria-label="Next message version"
  224. >
  225. <ChevronRightIcon className="h-4 w-4" />
  226. </button>
  227. </div>
  228. )}
  229. {/* user message */}
  230. {msg.role === 'user' && (
  231. <BtnWithTooltips
  232. className="btn-mini w-8 h-8"
  233. onClick={() => setEditingContent(msg.content)}
  234. disabled={msg.content === null}
  235. tooltipsContent="Edit message"
  236. >
  237. <PencilSquareIcon className="h-4 w-4" />
  238. </BtnWithTooltips>
  239. )}
  240. {/* assistant message */}
  241. {msg.role === 'assistant' && (
  242. <>
  243. {!isPending && (
  244. <BtnWithTooltips
  245. className="btn-mini w-8 h-8"
  246. onClick={() => {
  247. if (msg.content !== null) {
  248. onRegenerateMessage(msg as Message);
  249. }
  250. }}
  251. disabled={msg.content === null}
  252. tooltipsContent="Regenerate response"
  253. >
  254. <ArrowPathIcon className="h-4 w-4" />
  255. </BtnWithTooltips>
  256. )}
  257. </>
  258. )}
  259. <CopyButton className="btn-mini w-8 h-8" content={msg.content} />
  260. </div>
  261. )}
  262. </div>
  263. );
  264. }
  265. function ThoughtProcess({
  266. isThinking,
  267. content,
  268. open,
  269. }: {
  270. isThinking: boolean;
  271. content: string;
  272. open: boolean;
  273. }) {
  274. return (
  275. <div
  276. role="button"
  277. aria-label="Toggle thought process display"
  278. tabIndex={0}
  279. className={classNames({
  280. 'collapse bg-none': true,
  281. })}
  282. >
  283. <input type="checkbox" defaultChecked={open} />
  284. <div className="collapse-title px-0">
  285. <div className="btn rounded-xl">
  286. {isThinking ? (
  287. <span>
  288. <span
  289. className="loading loading-spinner loading-md mr-2"
  290. style={{ verticalAlign: 'middle' }}
  291. ></span>
  292. Thinking
  293. </span>
  294. ) : (
  295. <>Thought Process</>
  296. )}
  297. </div>
  298. </div>
  299. <div
  300. className="collapse-content text-base-content/70 text-sm p-1"
  301. tabIndex={0}
  302. aria-description="Thought process content"
  303. >
  304. <div className="border-l-2 border-base-content/20 pl-4 mb-4">
  305. <MarkdownDisplay content={content} />
  306. </div>
  307. </div>
  308. </div>
  309. );
  310. }