CCDChatSystem.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <template>
  2. <view-full-screen :is-full-screen="true" class="right">
  3. <div :class="bodyClass">
  4. <div ref="scrollView" :style="{ 'overflow-y': 'scroll', 'height': 'calc(100% - ' + (52 + safeAreaInsets.bottom) + 'px)' }">
  5. <template v-for="cell in model">
  6. <CCDChatCell :cell-type="cell.type" :message="cell.content" @shutdown="doShutdown"></CCDChatCell>
  7. </template>
  8. <div style="height: 30px"></div>
  9. </div>
  10. <div class="bottomAskBar" style="height: 50px; padding-right: 4px">
  11. <div style="height: 50px; width: calc(100% - 50px);">
  12. <input v-if="allowInput" ref="inputAsk" @keyup.enter="doPostMessage" type="text" placeholder="输入问题..." value=""/>
  13. <input v-else value=" 请等待AI回复" style="text-align: center" disabled/>
  14. </div>
  15. <button v-if="allowInput" @click="doPostMessage" :style="{
  16. height: '50px',
  17. width: '50px',
  18. right: '0px',
  19. top: 'calc(100% - ' + (50 + safeAreaInsets.bottom) + 'px)',
  20. position: 'absolute',
  21. float: 'right',
  22. background: 'transparent',
  23. border: 'none'
  24. }">
  25. <img src="../assets/run.png" style="width: calc(100% - 1px); height: calc(100% - 3px)">
  26. </button>
  27. </div>
  28. </div>
  29. </view-full-screen>
  30. </template>
  31. <style>
  32. p {
  33. color: white;
  34. }
  35. .bodyBackground_normal {
  36. width: 100%;
  37. height: 100%;
  38. background-color: #1f1f1f;
  39. }
  40. .bodyBackground_xcwk {
  41. width: 100%;
  42. height: 100%;
  43. background-color: #1f1f1f00;
  44. }
  45. </style>
  46. <style scoped>
  47. input {
  48. background-color: transparent;
  49. color: white;
  50. border: 0px solid;
  51. height: 100%;
  52. width: 100%;
  53. font-size: large;
  54. text-indent: 10px;
  55. outline: none;
  56. }
  57. .bottomAskBar {
  58. box-shadow: 0 -15px 10px -15px gray;
  59. }
  60. </style>
  61. <script>
  62. import CCDChatCell from "@/components/CCDChatCell";
  63. import { fetchEventSource } from '@microsoft/fetch-event-source';
  64. let websocketAPIURL = "wss://chat.forgetive.net/free_chat"
  65. let sseAPIURL = "https://notebook.forgetive.net/freeai/llm"
  66. export default {
  67. name: 'CCDChatSystem',
  68. components: {CCDChatCell},
  69. data() {
  70. return {
  71. allowInput: true,
  72. model: [
  73. {
  74. "type" : "title"
  75. },
  76. {
  77. "type" : "tip",
  78. "content" : "您好,我是 C Code Develop & C Notebook AI助手,可以帮您解决代码问题。从编程技巧到历史人文,我无所不知。快来跟我聊天吧~"
  79. }
  80. ],
  81. history: [],
  82. socketObject: null,
  83. wannaKill: false,
  84. sseInstance: null,
  85. abortController: null,
  86. bodyClass: "bodyBackground_xcwk",
  87. safeAreaInsets: {
  88. left: 0,
  89. top: 0,
  90. right: 0,
  91. bottom: 0
  92. },
  93. isHostInApp: false,
  94. inAppPendingCard: null,
  95. inAppSSEHandle: null
  96. }
  97. },
  98. mounted() {
  99. let self = this
  100. try {
  101. if (__private_xcwk_webViewId == undefined) {
  102. self.bodyClass = "bodyBackground_normal"
  103. } else {
  104. self.bodyClass = "bodyBackground_xcwk"
  105. self.isHostInApp = true
  106. }
  107. __xcwk_js2na("xcwkstd/getSafeAreaInsets", { }, function (safeAreaInsets) {
  108. self.safeAreaInsets = safeAreaInsets
  109. })
  110. __xcwk_na2js(function (key, params) {
  111. if (key == "keyboardWillShow") {
  112. if (params.dict && params.dict.webViewId == __private_xcwk_webViewId) {
  113. self.keyboardWillShow(params)
  114. }
  115. }
  116. else if (key == "keyboardWillHide") {
  117. if (params.dict && params.dict.webViewId == __private_xcwk_webViewId) {
  118. self.keyboardWillHide(params)
  119. }
  120. }
  121. else if (key == "sseRequestUpdate") {
  122. self.doInAppSSE_ReceiveMessage(params.dict)
  123. }
  124. })
  125. __xcwk_js2na("xcwkstd/isLogin", { }, function (params) {
  126. if (!params.isLogin) {
  127. __xcwk_js2na("notebook/launchLogin", { }, function (params) { });
  128. }
  129. });
  130. } catch (err) {
  131. self.bodyClass = "bodyBackground_normal"
  132. }
  133. },
  134. methods: {
  135. keyboardWillShow(params) {
  136. this.safeAreaInsets.bottom = 0
  137. },
  138. keyboardWillHide(params) {
  139. let self = this
  140. __xcwk_js2na("xcwkstd/getSafeAreaInsets", { }, function (safeAreaInsets) {
  141. self.safeAreaInsets = safeAreaInsets
  142. })
  143. },
  144. scrollViewScrollToBottom() {
  145. let self = this
  146. this.$nextTick(function () {
  147. self.$refs.scrollView.scrollTo({
  148. top: self.$refs.scrollView.scrollHeight,
  149. behavior: 'smooth'
  150. });
  151. });
  152. },
  153. insertMessageBlock(data) {
  154. this.model.push(data)
  155. this.scrollViewScrollToBottom()
  156. },
  157. doPostMessage() {
  158. if (this.sseInstance) {
  159. return;
  160. }
  161. let question = this.$refs.inputAsk.value
  162. if (question.length == 0) {
  163. this.insertMessageBlock({
  164. "type" : "answer",
  165. "content" : "先输入一个问题吧"
  166. })
  167. return
  168. }
  169. this.insertMessageBlock({
  170. "type" : "ask",
  171. "content" : question
  172. })
  173. this.$refs.inputAsk.value = ""
  174. this.doChatWithMessage(question)
  175. },
  176. doChatWithMessage(message) {
  177. if (this.isHostInApp) {
  178. let self = this
  179. __xcwk_js2na("xcwkstd/isLogin", {}, function (params) {
  180. if (params.isLogin) {
  181. self.doInAppSSE(message)
  182. } else {
  183. __xcwk_js2na("notebook/launchLogin", {}, function (params) { });
  184. self.insertMessageBlock({
  185. "type" : "answer",
  186. "content" : "请先登录App"
  187. })
  188. self.$refs.inputAsk.value = message
  189. }
  190. });
  191. } else {
  192. this.doAsyncSSE(message)
  193. }
  194. },
  195. doInAppSSE(message) {
  196. let self = this
  197. self.allowInput = false
  198. let messageCard = {
  199. "type" : "answer",
  200. "content" : ""
  201. }
  202. self.inAppPendingCard = messageCard
  203. let messageModel = []
  204. for (let index in self.model) {
  205. let model = self.model[index]
  206. if (model.type == "ask") {
  207. messageModel.push({
  208. "role" : "user",
  209. "content" : model.content
  210. })
  211. }
  212. else if (model.type == "answer") {
  213. messageModel.push({
  214. "role" : "assistant",
  215. "content" : model.content
  216. })
  217. }
  218. }
  219. self.insertMessageBlock(messageCard)
  220. self.insertMessageBlock({
  221. "type" : "answerTyping",
  222. "content" : ""
  223. })
  224. __xcwk_js2na("xcwkstd/sseRequest", {
  225. "path" : "/freeai/llm",
  226. "data" : {
  227. "stream" : true,
  228. "messages" : messageModel
  229. }
  230. }, function (params) {
  231. self.inAppSSEHandle = params.sseId
  232. });
  233. },
  234. doInAppSSE_ReceiveMessage(message) {
  235. let self = this
  236. let messageCard = self.inAppPendingCard
  237. if (message.sseId != self.inAppSSEHandle) {
  238. return
  239. }
  240. console.log(JSON.stringify(message))
  241. switch (message.type) {
  242. case 0x1: { // data
  243. let partModel = JSON.parse(message.data)
  244. if (partModel["v"] != null) {
  245. messageCard.content += partModel["v"]
  246. self.scrollViewScrollToBottom()
  247. }
  248. break
  249. }
  250. case 0x3: { // error
  251. if (messageCard.content.length < 5) {
  252. messageCard.content = "回答出了一点问题"
  253. }
  254. self.sseInstance = null
  255. self.allowInput = true
  256. self.doShutdown()
  257. break
  258. }
  259. case 0x4: { // close
  260. self.sseInstance = null
  261. self.allowInput = true
  262. self.abortController = null
  263. self.inAppPendingCard = null
  264. self.inAppSSEHandle = null
  265. for (let id = 0; id < self.model.length; id++) {
  266. if (self.model[id].type == "answerTyping") {
  267. self.model.splice(id, 1)
  268. id--;
  269. }
  270. }
  271. break
  272. }
  273. }
  274. },
  275. doAsyncSSE(message) {
  276. let self = this
  277. self.allowInput = false
  278. let messageCard = {
  279. "type" : "answer",
  280. "content" : ""
  281. }
  282. let messageModel = []
  283. for (let index in self.model) {
  284. let model = self.model[index]
  285. if (model.type == "ask") {
  286. messageModel.push({
  287. "role" : "user",
  288. "content" : model.content
  289. })
  290. }
  291. else if (model.type == "answer") {
  292. messageModel.push({
  293. "role" : "assistant",
  294. "content" : model.content
  295. })
  296. }
  297. }
  298. self.insertMessageBlock(messageCard)
  299. self.insertMessageBlock({
  300. "type" : "answerTyping",
  301. "content" : ""
  302. })
  303. self.abortController = new AbortController()
  304. let eventSource = fetchEventSource(sseAPIURL, {
  305. method: 'POST',
  306. signal: self.abortController.signal,
  307. headers: {
  308. "Content-Type": 'application/json',
  309. "Access-Control-Allow-Origin": true
  310. },
  311. body: JSON.stringify({
  312. "stream" : true,
  313. "messages" : messageModel
  314. }),
  315. onmessage(event) {
  316. let partModel = JSON.parse(event.data)
  317. if (partModel["v"] != null) {
  318. messageCard.content += partModel["v"]
  319. self.scrollViewScrollToBottom()
  320. }
  321. },
  322. onerror(err) {
  323. if (messageCard.content.length < 5) {
  324. messageCard.content = "回答出了一点问题"
  325. }
  326. self.sseInstance = null
  327. self.allowInput = true
  328. self.doShutdown()
  329. throw err
  330. },
  331. onclose() {
  332. self.sseInstance = null
  333. self.allowInput = true
  334. self.abortController = null
  335. for (let id = 0; id < self.model.length; id++) {
  336. if (self.model[id].type == "answerTyping") {
  337. self.model.splice(id, 1)
  338. id--;
  339. }
  340. }
  341. }
  342. })
  343. self.sseInstance = eventSource
  344. },
  345. doAsyncChat(message) {
  346. this.allowInput = false
  347. let self = this
  348. let socket = new WebSocket(websocketAPIURL)
  349. self.socketObject = socket
  350. self.wannaKill = false
  351. let messageCard = {
  352. "type" : "answer",
  353. "content" : ""
  354. }
  355. let isFinished = false
  356. function finishBlock(success) {
  357. if (isFinished) {
  358. return
  359. }
  360. isFinished = true
  361. self.socketObject = null
  362. self.allowInput = true
  363. self.wannaKill = false
  364. while (self.history.length >= 3) {
  365. self.history.pop()
  366. }
  367. self.history.push([
  368. message,
  369. messageCard.content
  370. ])
  371. for (let id = 0; id < self.model.length; id++) {
  372. if (self.model[id].type == "answerTyping") {
  373. self.model.splice(id, 1)
  374. id--;
  375. }
  376. }
  377. }
  378. socket.onopen = function (event) {
  379. self.insertMessageBlock(messageCard)
  380. self.insertMessageBlock({
  381. "type" : "answerTyping",
  382. "content" : ""
  383. })
  384. let request = {
  385. "history" : self.history,
  386. "question" : message
  387. }
  388. socket.send(JSON.stringify(request))
  389. }
  390. socket.onmessage = function (event) {
  391. messageCard.content += event.data
  392. if (self.wannaKill) {
  393. socket.send("k")
  394. } else {
  395. socket.send("n")
  396. }
  397. self.scrollViewScrollToBottom()
  398. }
  399. socket.onclose = function (event) {
  400. finishBlock(true)
  401. }
  402. socket.onerror = function (error) {
  403. alert("不好意思,出错了,请稍后再试")
  404. finishBlock(false)
  405. }
  406. },
  407. doShutdown() {
  408. let self = this
  409. if (self.socketObject != null) {
  410. self.socketObject.close(1000)
  411. }
  412. if (self.abortController != null) {
  413. self.abortController.abort()
  414. self.sseInstance = null
  415. self.allowInput = true
  416. self.abortController = null
  417. for (let id = 0; id < self.model.length; id++) {
  418. if (self.model[id].type == "answerTyping") {
  419. self.model.splice(id, 1)
  420. id--;
  421. }
  422. }
  423. }
  424. if (self.inAppSSEHandle != null) {
  425. __xcwk_js2na("xcwkstd/cancelSSERequest", {
  426. "sseId" : self.inAppSSEHandle
  427. }, function (params) { })
  428. self.inAppSSEHandle = null
  429. self.sseInstance = null
  430. self.allowInput = true
  431. self.abortController = null
  432. self.inAppPendingCard = null
  433. for (let id = 0; id < self.model.length; id++) {
  434. if (self.model[id].type == "answerTyping") {
  435. self.model.splice(id, 1)
  436. id--;
  437. }
  438. }
  439. }
  440. }
  441. }
  442. }
  443. </script>
  444. <style scoped>
  445. </style>