ChatGPT.vue 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <script setup lang="ts">
  2. import Icon, { SendOutlined } from '@ant-design/icons-vue'
  3. import { useGettext } from 'vue3-gettext'
  4. import { storeToRefs } from 'pinia'
  5. import { marked } from 'marked'
  6. import hljs from 'highlight.js'
  7. import type { Ref } from 'vue'
  8. import { urlJoin } from '@/lib/helper'
  9. import { useSettingsStore, useUserStore } from '@/pinia'
  10. import 'highlight.js/styles/vs2015.css'
  11. import type { ChatComplicationMessage } from '@/api/openai'
  12. import openai from '@/api/openai'
  13. import ChatGPT_logo from '@/assets/svg/ChatGPT_logo.svg'
  14. const props = defineProps<{
  15. content: string
  16. path?: string
  17. historyMessages: ChatComplicationMessage[]
  18. }>()
  19. const emit = defineEmits(['update:history_messages'])
  20. const { $gettext } = useGettext()
  21. const { language: current } = storeToRefs(useSettingsStore())
  22. const history_messages = computed(() => props.historyMessages)
  23. const messages = ref([]) as Ref<ChatComplicationMessage[]>
  24. onMounted(() => {
  25. messages.value = props.historyMessages
  26. })
  27. watch(history_messages, () => {
  28. messages.value = props.historyMessages
  29. })
  30. const loading = ref(false)
  31. const ask_buffer = ref('')
  32. // eslint-disable-next-line sonarjs/cognitive-complexity
  33. async function request() {
  34. loading.value = true
  35. const t = ref({
  36. role: 'assistant',
  37. content: '',
  38. })
  39. const user = useUserStore()
  40. const { token } = storeToRefs(user)
  41. console.log('fetching...')
  42. messages.value.push(t.value)
  43. emit('update:history_messages', messages.value)
  44. const res = await fetch(urlJoin(window.location.pathname, '/api/chat_gpt'), {
  45. method: 'POST',
  46. headers: { Accept: 'text/event-stream', Authorization: token.value },
  47. body: JSON.stringify({ messages: messages.value.slice(0, messages.value?.length - 1) }),
  48. })
  49. // read body as stream
  50. console.info('reading...')
  51. const reader = res.body!.getReader()
  52. // read stream
  53. console.info('reading stream...')
  54. let buffer = ''
  55. let hasCodeBlockIndicator = false
  56. while (true) {
  57. const { done, value } = await reader.read()
  58. if (done) {
  59. console.info('done')
  60. setTimeout(() => {
  61. scrollToBottom()
  62. }, 500)
  63. loading.value = false
  64. store_record()
  65. break
  66. }
  67. apply(value!)
  68. }
  69. function apply(input: Uint8Array) {
  70. const decoder = new TextDecoder('utf-8')
  71. const raw = decoder.decode(input)
  72. // console.log(input, raw)
  73. const line = raw.split('\n\n')
  74. line?.forEach(v => {
  75. const data = v.slice('event:message\ndata:'.length)
  76. if (!data)
  77. return
  78. const content = JSON.parse(data).content
  79. if (!hasCodeBlockIndicator)
  80. hasCodeBlockIndicator = content.includes('`')
  81. for (const c of content) {
  82. buffer += c
  83. if (hasCodeBlockIndicator) {
  84. if (isCodeBlockComplete(buffer)) {
  85. t.value.content = buffer
  86. hasCodeBlockIndicator = false
  87. }
  88. else {
  89. t.value.content = `${buffer}\n\`\`\``
  90. }
  91. }
  92. else {
  93. t.value.content = buffer
  94. }
  95. }
  96. // keep container scroll to bottom
  97. scrollToBottom()
  98. })
  99. }
  100. function isCodeBlockComplete(text: string) {
  101. const codeBlockRegex = /```/g
  102. const matches = text.match(codeBlockRegex)
  103. if (matches)
  104. return matches.length % 2 === 0
  105. else
  106. return true
  107. }
  108. function scrollToBottom() {
  109. const container = document.querySelector('.right-settings .ant-card-body')
  110. if (container)
  111. container.scrollTop = container.scrollHeight
  112. }
  113. }
  114. async function send() {
  115. if (!messages.value)
  116. messages.value = []
  117. if (messages.value.length === 0) {
  118. console.log(current.value)
  119. messages.value.push({
  120. role: 'user',
  121. content: `${props.content}\n\nCurrent Language Code: ${current.value}`,
  122. })
  123. }
  124. else {
  125. messages.value.push({
  126. role: 'user',
  127. content: ask_buffer.value,
  128. })
  129. ask_buffer.value = ''
  130. }
  131. await request()
  132. }
  133. const renderer = new marked.Renderer()
  134. renderer.code = (code, lang: string) => {
  135. const language = hljs.getLanguage(lang) ? lang : 'nginx'
  136. const highlightedCode = hljs.highlight(code, { language }).value
  137. return `<pre><code class="hljs ${language}">${highlightedCode}</code></pre>`
  138. }
  139. marked.setOptions({
  140. renderer,
  141. pedantic: false,
  142. gfm: true,
  143. breaks: false,
  144. })
  145. function store_record() {
  146. openai.store_record({
  147. file_name: props.path,
  148. messages: messages.value,
  149. })
  150. }
  151. function clear_record() {
  152. openai.store_record({
  153. file_name: props.path,
  154. messages: [],
  155. })
  156. messages.value = []
  157. emit('update:history_messages', [])
  158. }
  159. const editing_idx = ref(-1)
  160. async function regenerate(index: number) {
  161. editing_idx.value = -1
  162. messages.value = messages.value.slice(0, index)
  163. await request()
  164. }
  165. const show = computed(() => !messages.value || messages.value?.length === 0)
  166. </script>
  167. <template>
  168. <div
  169. v-if="show"
  170. class="chat-start"
  171. >
  172. <AButton
  173. :loading="loading"
  174. @click="send"
  175. >
  176. <Icon
  177. v-if="!loading"
  178. :component="ChatGPT_logo"
  179. />
  180. {{ $gettext('Ask ChatGPT for Help') }}
  181. </AButton>
  182. </div>
  183. <div
  184. v-else
  185. class="chatgpt-container"
  186. >
  187. <AList
  188. class="chatgpt-log"
  189. item-layout="horizontal"
  190. :data-source="messages"
  191. >
  192. <template #renderItem="{ item, index }">
  193. <AListItem>
  194. <AComment :author="item.role === 'assistant' ? $gettext('Assistant') : $gettext('User')">
  195. <template #content>
  196. <div
  197. v-if="item.role === 'assistant' || editing_idx !== index"
  198. class="content"
  199. v-html="marked.parse(item.content)"
  200. />
  201. <AInput
  202. v-else
  203. v-model:value="item.content"
  204. style="padding: 0"
  205. :bordered="false"
  206. />
  207. </template>
  208. <template #actions>
  209. <span
  210. v-if="item.role === 'user' && editing_idx !== index"
  211. @click="editing_idx = index"
  212. >
  213. {{ $gettext('Modify') }}
  214. </span>
  215. <template v-else-if="editing_idx === index">
  216. <span @click="regenerate(index + 1)">{{ $gettext('Save') }}</span>
  217. <span @click="editing_idx = -1">{{ $gettext('Cancel') }}</span>
  218. </template>
  219. <span
  220. v-else-if="!loading"
  221. @click="regenerate(index)"
  222. >
  223. {{ $gettext('Reload') }}
  224. </span>
  225. </template>
  226. </AComment>
  227. </AListItem>
  228. </template>
  229. </AList>
  230. <div class="input-msg">
  231. <div class="control-btn">
  232. <ASpace v-show="!loading">
  233. <APopconfirm
  234. :cancel-text="$gettext('No')"
  235. :ok-text="$gettext('OK')"
  236. :title="$gettext('Are you sure you want to clear the record of chat?')"
  237. @confirm="clear_record"
  238. >
  239. <AButton type="text">
  240. {{ $gettext('Clear') }}
  241. </AButton>
  242. </APopconfirm>
  243. <AButton
  244. type="text"
  245. @click="regenerate(messages?.length - 1)"
  246. >
  247. {{ $gettext('Regenerate response') }}
  248. </AButton>
  249. </ASpace>
  250. </div>
  251. <ATextarea
  252. v-model:value="ask_buffer"
  253. auto-size
  254. />
  255. <div class="send-btn">
  256. <AButton
  257. size="small"
  258. type="text"
  259. :loading="loading"
  260. @click="send"
  261. >
  262. <SendOutlined />
  263. </AButton>
  264. </div>
  265. </div>
  266. </div>
  267. </template>
  268. <style lang="less" scoped>
  269. .chatgpt-container {
  270. margin: 0 auto;
  271. max-width: 800px;
  272. .chatgpt-log {
  273. .content {
  274. width: 100%;
  275. :deep(.hljs) {
  276. border-radius: 5px;
  277. }
  278. }
  279. :deep(.ant-list-item) {
  280. padding: 0;
  281. }
  282. :deep(.ant-comment-content) {
  283. width: 100%;
  284. }
  285. :deep(.ant-comment) {
  286. width: 100%;
  287. }
  288. :deep(.ant-comment-content-detail) {
  289. width: 100%;
  290. p {
  291. margin-bottom: 10px;
  292. }
  293. }
  294. :deep(.ant-list-item:first-child) {
  295. display: none;
  296. }
  297. }
  298. .input-msg {
  299. position: relative;
  300. .control-btn {
  301. display: flex;
  302. justify-content: center;
  303. }
  304. .send-btn {
  305. position: absolute;
  306. right: 0;
  307. bottom: 3px;
  308. }
  309. }
  310. }
  311. </style>