ChatGPT.vue 8.0 KB

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