ChatMessage.tsx 10 KB

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