RagSearchModal.tsx 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import React, { useEffect, useState } from 'react';
  2. import { useForm } from 'react-hook-form';
  3. import { Modal, ModalBody, ModalHeader } from 'reactstrap';
  4. import { apiv3Post } from '~/client/util/apiv3-client';
  5. import { useRagSearchModal } from '~/stores/rag-search';
  6. import loggerFactory from '~/utils/logger';
  7. import { MessageCard } from './MessageCard';
  8. import { useResizableTextarea } from './use-resizable-textarea';
  9. import styles from './RagSearchModal.module.scss';
  10. const moduleClass = styles['rag-search-modal'];
  11. const logger = loggerFactory('growi:clinet:components:RagSearchModal');
  12. type Message = {
  13. id: string,
  14. content: string,
  15. isUserMessage?: boolean,
  16. }
  17. type FormData = {
  18. input: string;
  19. };
  20. const RagSearchModal = (): JSX.Element => {
  21. const form = useForm<FormData>({
  22. defaultValues: {
  23. input: '',
  24. },
  25. });
  26. const resizable = useResizableTextarea();
  27. const [threadId, setThreadId] = useState<string | undefined>();
  28. const [messageLogs, setMessageLogs] = useState<Message[]>([]);
  29. const [lastMessage, setLastMessage] = useState<Message>();
  30. const { data: ragSearchModalData, close: closeRagSearchModal } = useRagSearchModal();
  31. const isOpened = ragSearchModalData?.isOpened ?? false;
  32. useEffect(() => {
  33. // do nothing when modal is not opened
  34. if (!isOpened) {
  35. return;
  36. }
  37. // do nothing when threadId is already set
  38. if (threadId != null) {
  39. return;
  40. }
  41. const createThread = async() => {
  42. // create thread
  43. try {
  44. const res = await apiv3Post('/openai/thread', { threadId });
  45. const thread = res.data.thread;
  46. setThreadId(thread.id);
  47. }
  48. catch (err) {
  49. logger.error(err.toString());
  50. }
  51. };
  52. createThread();
  53. }, [isOpened, threadId]);
  54. const clickSubmitUserMessageHandler = form.handleSubmit(async(data) => {
  55. const { length: logLength } = messageLogs;
  56. // post message
  57. try {
  58. form.clearErrors();
  59. const response = await fetch('/_api/v3/openai/message', {
  60. method: 'POST',
  61. headers: { 'Content-Type': 'application/json' },
  62. body: JSON.stringify({ userMessage: data.input, threadId }),
  63. });
  64. if (!response.ok) {
  65. const resJson = await response.json();
  66. if ('errors' in resJson) {
  67. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  68. const errors = resJson.errors.map(({ message }) => message).join(', ');
  69. form.setError('input', { type: 'manual', message: `[${response.status}] ${errors}` });
  70. }
  71. return;
  72. }
  73. // add user message to the logs
  74. const newUserMessage = { id: logLength.toString(), content: data.input, isUserMessage: true };
  75. setMessageLogs(msgs => [...msgs, newUserMessage]);
  76. // reset form
  77. form.reset();
  78. // add assistant message
  79. const newAssistantMessage = { id: (logLength + 1).toString(), content: '' };
  80. setLastMessage(newAssistantMessage);
  81. const reader = response.body?.getReader();
  82. const decoder = new TextDecoder('utf-8');
  83. const read = async() => {
  84. if (reader == null) return;
  85. const { done, value } = await reader.read();
  86. // add assistant message to the logs
  87. if (done) {
  88. setMessageLogs(msgs => [...msgs, newAssistantMessage]);
  89. setLastMessage(undefined);
  90. return;
  91. }
  92. const chunk = decoder.decode(value);
  93. // Extract text values from the chunk
  94. const textValues = chunk
  95. .split('\n\n')
  96. .filter(line => line.trim().startsWith('data:'))
  97. .map((line) => {
  98. const data = JSON.parse(line.replace('data: ', ''));
  99. return data.content[0].text.value;
  100. });
  101. // append text values to the assistant message
  102. newAssistantMessage.content += textValues.join('');
  103. setLastMessage(newAssistantMessage);
  104. read();
  105. };
  106. read();
  107. }
  108. catch (err) {
  109. logger.error(err.toString());
  110. form.setError('input', { type: 'manual', message: err.toString() });
  111. }
  112. });
  113. return (
  114. <Modal size="lg" isOpen={isOpened} toggle={closeRagSearchModal} className={moduleClass}>
  115. <ModalHeader tag="h4" toggle={closeRagSearchModal} className="pe-4">
  116. <span className="material-symbols-outlined text-primary">psychology</span>
  117. GROWI Assistant
  118. </ModalHeader>
  119. <ModalBody className="px-lg-5 py-4">
  120. <div className="vstack gap-4">
  121. { messageLogs.map(message => (
  122. <MessageCard key={message.id} right={message.isUserMessage}>{message.content}</MessageCard>
  123. )) }
  124. { lastMessage != null && (
  125. <MessageCard>{lastMessage.content}</MessageCard>
  126. )}
  127. </div>
  128. <div>
  129. <form onSubmit={clickSubmitUserMessageHandler} className="hstack gap-2 align-items-end mt-4">
  130. <textarea
  131. {...form.register('input')}
  132. {...resizable.register()}
  133. required
  134. className="form-control textarea-ask"
  135. style={{ resize: 'none' }}
  136. rows={1}
  137. placeholder="ききたいことを入力してください"
  138. />
  139. <button
  140. type="submit"
  141. className="btn btn-submit no-border"
  142. disabled={form.formState.isSubmitting}
  143. >
  144. <span className="material-symbols-outlined">send</span>
  145. </button>
  146. </form>
  147. {form.formState.errors.input != null && (
  148. <span className="text-danger small">{form.formState.errors.input?.message}</span>
  149. )}
  150. </div>
  151. </ModalBody>
  152. </Modal>
  153. );
  154. };
  155. export default RagSearchModal;