index.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import { useRef, useState, useEffect, useMemo } from 'react';
  2. import Layout from '@/components/layout';
  3. import styles from '@/styles/Home.module.css';
  4. import { Message } from '@/types/chat';
  5. import { fetchEventSource } from '@microsoft/fetch-event-source';
  6. import Image from 'next/image';
  7. import ReactMarkdown from 'react-markdown';
  8. import LoadingDots from '@/components/ui/LoadingDots';
  9. export default function Home() {
  10. const [query, setQuery] = useState<string>('');
  11. const [loading, setLoading] = useState<boolean>(false);
  12. const [messageState, setMessageState] = useState<{
  13. messages: Message[];
  14. pending?: string;
  15. history: [string, string][];
  16. }>({
  17. messages: [
  18. {
  19. message: 'Hi there its Tom! What would like to learn about notion?',
  20. type: 'apiMessage',
  21. },
  22. ],
  23. history: [],
  24. });
  25. const { messages, pending, history } = messageState;
  26. const messageListRef = useRef<HTMLDivElement>(null);
  27. const textAreaRef = useRef<HTMLTextAreaElement>(null);
  28. useEffect(() => {
  29. textAreaRef.current?.focus();
  30. }, []);
  31. //handle form submission
  32. async function handleSubmit(e: any) {
  33. e.preventDefault();
  34. if (!query) {
  35. alert('Please input a question');
  36. return;
  37. }
  38. const question = query.trim();
  39. setMessageState((state) => ({
  40. ...state,
  41. messages: [
  42. ...state.messages,
  43. {
  44. type: 'userMessage',
  45. message: question,
  46. },
  47. ],
  48. pending: undefined,
  49. }));
  50. setLoading(true);
  51. setQuery('');
  52. setMessageState((state) => ({ ...state, pending: '' }));
  53. const ctrl = new AbortController();
  54. try {
  55. fetchEventSource('/api/chat', {
  56. method: 'POST',
  57. headers: {
  58. 'Content-Type': 'application/json',
  59. },
  60. body: JSON.stringify({
  61. question,
  62. history,
  63. }),
  64. signal: ctrl.signal,
  65. onmessage: (event) => {
  66. if (event.data === '[DONE]') {
  67. setMessageState((state) => ({
  68. history: [...state.history, [question, state.pending ?? '']],
  69. messages: [
  70. ...state.messages,
  71. {
  72. type: 'apiMessage',
  73. message: state.pending ?? '',
  74. },
  75. ],
  76. pending: undefined,
  77. }));
  78. setLoading(false);
  79. ctrl.abort();
  80. } else {
  81. const data = JSON.parse(event.data);
  82. setMessageState((state) => ({
  83. ...state,
  84. pending: (state.pending ?? '') + data.data,
  85. }));
  86. }
  87. },
  88. });
  89. } catch (error) {
  90. setLoading(false);
  91. console.log('error', error);
  92. }
  93. }
  94. //prevent empty submissions
  95. const handleEnter = (e: any) => {
  96. if (e.key === 'Enter' && query) {
  97. handleSubmit(e);
  98. } else if (e.key == 'Enter') {
  99. e.preventDefault();
  100. }
  101. };
  102. const chatMessages = useMemo(() => {
  103. return [
  104. ...messages,
  105. ...(pending ? [{ type: 'apiMessage', message: pending }] : []),
  106. ];
  107. }, [messages, pending]);
  108. return (
  109. <>
  110. <Layout>
  111. <div className="mx-auto flex flex-col gap-4">
  112. <h1 className="text-2xl font-bold leading-[1.1] tracking-tighter text-center">
  113. Thomas Frank Notion Guide ChatBot
  114. </h1>
  115. <main className={styles.main}>
  116. <div className={styles.cloud}>
  117. <div ref={messageListRef} className={styles.messagelist}>
  118. {chatMessages.map((message, index) => {
  119. let icon;
  120. let className;
  121. if (message.type === 'apiMessage') {
  122. icon = (
  123. <Image
  124. src="/Thomas-Frank-Avatar.jpg"
  125. alt="AI"
  126. width="40"
  127. height="40"
  128. className={styles.boticon}
  129. priority
  130. />
  131. );
  132. className = styles.apimessage;
  133. } else {
  134. icon = (
  135. <Image
  136. src="/usericon.png"
  137. alt="Me"
  138. width="30"
  139. height="30"
  140. className={styles.usericon}
  141. priority
  142. />
  143. );
  144. // The latest message sent by the user will be animated while waiting for a response
  145. className =
  146. loading && index === chatMessages.length - 1
  147. ? styles.usermessagewaiting
  148. : styles.usermessage;
  149. }
  150. return (
  151. <div key={index} className={className}>
  152. {icon}
  153. <div className={styles.markdownanswer}>
  154. <ReactMarkdown linkTarget="_blank">
  155. {message.message}
  156. </ReactMarkdown>
  157. </div>
  158. </div>
  159. );
  160. })}
  161. </div>
  162. </div>
  163. <div className={styles.center}>
  164. <div className={styles.cloudform}>
  165. <form onSubmit={handleSubmit}>
  166. <textarea
  167. disabled={loading}
  168. onKeyDown={handleEnter}
  169. ref={textAreaRef}
  170. autoFocus={false}
  171. rows={1}
  172. maxLength={512}
  173. id="userInput"
  174. name="userInput"
  175. placeholder={
  176. loading
  177. ? 'Waiting for response...'
  178. : 'How does notion api work?'
  179. }
  180. value={query}
  181. onChange={(e) => setQuery(e.target.value)}
  182. className={styles.textarea}
  183. />
  184. <button
  185. type="submit"
  186. disabled={loading}
  187. className={styles.generatebutton}
  188. >
  189. {loading ? (
  190. <div className={styles.loadingwheel}>
  191. <LoadingDots color="#000" />
  192. </div>
  193. ) : (
  194. // Send icon SVG in input field
  195. <svg
  196. viewBox="0 0 20 20"
  197. className={styles.svgicon}
  198. xmlns="http://www.w3.org/2000/svg"
  199. >
  200. <path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"></path>
  201. </svg>
  202. )}
  203. </button>
  204. </form>
  205. </div>
  206. </div>
  207. </main>
  208. </div>
  209. <footer className="m-auto">
  210. <a href="https://twitter.com/mayowaoshin">
  211. Powered by LangChain. Demo built by Mayo (Twitter: @mayowaoshin).
  212. </a>
  213. </footer>
  214. </Layout>
  215. </>
  216. );
  217. }