ChatGPT.vue 7.8 KB

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