useMsg.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. // 消息数组
  2. import { ref, reactive, nextTick, inject } from 'vue'
  3. import { storeToRefs } from 'pinia'
  4. import avator from '@/public/icon/32.png'
  5. import moment from 'moment'
  6. import {
  7. getFormKey,
  8. hepl,
  9. formatMessage,
  10. sendMessage
  11. } from '../utils/ai-service.js'
  12. import { ElMessage } from 'element-plus'
  13. import { getPageInfo } from '../utils/index.js'
  14. import { mockData, mockData2 } from '../mock'
  15. import { useMsgStore } from '@/store/modules/msg'
  16. import { FunctionList } from '../mock'
  17. export function useMsg(scrollbar?: any) {
  18. const { messages, msgUuid } = storeToRefs(useMsgStore())
  19. const indexTemp = ref(0)
  20. const taklToHtml = ref<any>(false)
  21. const sendLoading = ref(false)
  22. const pageInfo = ref<any>({})
  23. const type = ref(FunctionList.File_Operation)
  24. const formMap = ref([])
  25. // 获取父组件提供的 Hook 实例
  26. const { useStore } = inject('indexedDBHook') as any
  27. const getFileSummary = async (file: any) => {
  28. const obj = reactive({
  29. id: moment(),
  30. username: '用户1',
  31. rawContent: '',
  32. content: '解析文件中',
  33. timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
  34. isSelf: false,
  35. avatar: avator,
  36. addToHistory: !taklToHtml.value
  37. })
  38. try {
  39. sendLoading.value = true
  40. messages.value.push(obj)
  41. nextTick(() => scrollbar.value?.setScrollTop(99999))
  42. const res = await getFileValue(file)
  43. console.log(res.data, file)
  44. await streamRes()
  45. } catch (error) {
  46. obj.content = '解析出错'
  47. } finally {
  48. sendLoading.value = false
  49. }
  50. }
  51. const getFormKeyAndValue = async (file: any, form?: any) => {
  52. // const obj = reactive({
  53. // id: moment(),
  54. // username: '用户1',
  55. // rawContent: '',
  56. // content: '解析文件中',
  57. // timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
  58. // isSelf: false,
  59. // avatar: avator,
  60. // addToHistory: !taklToHtml.value
  61. // })
  62. try {
  63. sendLoading.value = true
  64. // messages.value.push(obj)
  65. const response = await getFormKey({
  66. body: form,
  67. input_data: file
  68. })
  69. return response
  70. } catch (error) {
  71. // obj.content = '解析出错'
  72. } finally {
  73. sendLoading.value = false
  74. }
  75. }
  76. // 发送消息
  77. // const handleSend = async (msg: any) => {
  78. // if ( msg?.startsWith('/')) {
  79. // if (!taklToHtml.value)
  80. // return messages.value.push({
  81. // id: messages.value.length + 1,
  82. // username: '用户1',
  83. // content: '请打开与页面对话!',
  84. // rawContent: '请打开与页面对话!',
  85. // timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
  86. // isSelf: false,
  87. // avatar: avator,
  88. // addToHistory: false
  89. // })
  90. // indexTemp.value = 0
  91. // fetchRes(msg)
  92. // }
  93. // }
  94. async function awaitFindForm(obj: any) {
  95. return await new Promise((res, rej) => {
  96. chrome.runtime.sendMessage(
  97. {
  98. type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM'
  99. },
  100. ({ status, data }) => {
  101. if (status === 'error') {
  102. obj.content = '当前页面未找到表单'
  103. res({ status })
  104. }
  105. if (status === 'ok') {
  106. obj.content = '请上传数据'
  107. res({ status, data })
  108. }
  109. if (status === 'select') {
  110. obj.content = '检测到左侧页面中有多个表单,请选择要填写的表单。'
  111. function handle(message, sender, sendResponse) {
  112. if (message.type === 'TO_SIDE_PANEL_FORM_INFO') {
  113. console.log('收到一次性消息:', message.data)
  114. res({ status: 'ok', data: message.data })
  115. obj.content = '请上传数据'
  116. console.log(565656)
  117. // 销毁监听器(确保只触发一次)
  118. chrome.runtime.onMessage.removeListener(handle)
  119. }
  120. }
  121. chrome.runtime.onMessage.addListener(handle)
  122. }
  123. }
  124. )
  125. })
  126. }
  127. const fetchRes = async (msg: any) => {
  128. indexTemp.value = 0
  129. sendLoading.value = true
  130. const obj: any = reactive({
  131. id: messages.value.length + 1,
  132. username: '用户1',
  133. content: '',
  134. timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
  135. isSelf: false,
  136. avatar: avator,
  137. addToHistory: !taklToHtml.value
  138. })
  139. messages.value.push(obj)
  140. msg = msg.split('/智能填表')[1]
  141. nextTick(() => scrollbar.value?.setScrollTop(99999))
  142. if (!msg) {
  143. sendLoading.value = false
  144. const res = await awaitFindForm(obj)
  145. return res
  146. }
  147. const res = await fetchDataAndProcess(msg, obj)
  148. type.value = ''
  149. sendLoading.value = false
  150. if (res.status === 'ok') {
  151. await new Promise((res: any) =>
  152. setTimeout(() => {
  153. res()
  154. }, 2000)
  155. )
  156. const res = await awaitFindForm(obj)
  157. return res
  158. }
  159. }
  160. let str = ''
  161. async function fetchDataAndProcess(input: any, obj: any) {
  162. str = input
  163. console.log(str)
  164. const pageInfo = await getPageInfo()
  165. await new Promise((res: any) =>
  166. setTimeout(() => {
  167. res()
  168. }, 2000)
  169. )
  170. const res = await hepl({
  171. input_data: input,
  172. body: pageInfo.content.mainContent
  173. })
  174. // const res: any = await new Promise((resolve, reject) => {
  175. // setTimeout(() => {
  176. // resolve({
  177. // data:
  178. // pageInfo.title === '智能招采'
  179. // ? mockData[indexTemp.value]
  180. // : mockData2[indexTemp.value]
  181. // })
  182. // }, 1000)
  183. // })
  184. if (!res.data.tag || res.data.tag === 'undefined') {
  185. ElMessage({
  186. message: '未找到标签,请重试',
  187. type: 'error',
  188. duration: 4 * 1000,
  189. grouping: true
  190. })
  191. obj.content = '未找到标签,请重试'
  192. return { status: 'error' }
  193. }
  194. await new Promise((resolve) => setTimeout(resolve, 2000))
  195. obj.content = `点击${res.data.tag}元素`
  196. const res2 = await new Promise((resolve, rej) => {
  197. chrome.runtime.sendMessage(
  198. {
  199. type: 'FROM_SIDE_PANEL_TO_ACTION',
  200. data: res.data
  201. },
  202. async ({ data, status }) => {
  203. if (chrome.runtime.lastError) {
  204. console.error('消息发送错误:', chrome.runtime.lastError)
  205. } else {
  206. if (status === 'error') {
  207. obj.content = data
  208. resolve({ data, status })
  209. console.log(222);
  210. }
  211. if (res.data.next === '是') {
  212. const arr = str.split(',')
  213. arr.shift()
  214. str = arr.join(',')
  215. indexTemp.value++
  216. const res = await fetchDataAndProcess(str, obj)
  217. resolve(res)
  218. } else resolve({ status: 'ok' })
  219. }
  220. }
  221. )
  222. })
  223. return res2
  224. }
  225. /**
  226. *
  227. * @param addHtml 是否添加页面信息
  228. */
  229. const streamRes = async (addHtml: any = false) => {
  230. pageInfo.value = await getPageInfo()
  231. sendLoading.value = true
  232. const obj = reactive<any>({
  233. id: messages.value.length + 1,
  234. username: '用户1',
  235. content: '',
  236. rawContent: '', // 存储原始内容
  237. timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
  238. isSelf: false,
  239. avatar: avator,
  240. addToHistory: !taklToHtml.value
  241. })
  242. let history = []
  243. if (taklToHtml.value) {
  244. if (addHtml) {
  245. history.push({
  246. role: 'user',
  247. content: `页面主要内容${pageInfo.value.content.mainContent}`
  248. })
  249. }
  250. history.push({
  251. role: 'user',
  252. content: messages.value[messages.value.length - 1].rawContent
  253. })
  254. } else {
  255. history = messages.value
  256. .filter((item: any) => item.addToHistory)
  257. .slice(-20)
  258. .map((item: any) => ({
  259. role: item.isSelf ? 'user' : 'system',
  260. content: item.rawContent
  261. }))
  262. }
  263. messages.value.push(obj)
  264. nextTick(() => {
  265. scrollbar.value?.setScrollTop(99999)
  266. })
  267. const iterator = await sendMessage(history)
  268. for await (const chunk of iterator) {
  269. if (chunk) {
  270. const decodedChunk = chunk.choices[0].delta.content
  271. if (decodedChunk) {
  272. // 保存原始内容
  273. obj.rawContent += decodedChunk
  274. // 实时格式化显示内容
  275. obj.content = formatMessage(obj.rawContent)
  276. // if (type.value === '2') obj.content = obj.content.replace(/item/g, '表单项').replace(/excelColumn/g, '对应数据源')
  277. }
  278. }
  279. scrollbar.value?.setScrollTop(99999)
  280. }
  281. //添加到存储历史
  282. useStore(msgUuid.value).add({ ...obj })
  283. // 处理最终内容
  284. sendLoading.value = false
  285. nextTick(() => {
  286. scrollbar.value?.setScrollTop(99999)
  287. })
  288. return obj.rawContent
  289. }
  290. async function requestFlowFn(data: any[]) {
  291. sendLoading.value = true
  292. const obj = reactive<any>({
  293. id: messages.value.length + 1,
  294. username: '用户1',
  295. content: '',
  296. rawContent: '', // 存储原始内容
  297. timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
  298. isSelf: false,
  299. avatar: avator,
  300. addToHistory: !taklToHtml.value
  301. })
  302. messages.value.push(obj)
  303. scrollbar.value?.setScrollTop(99999)
  304. const iterator = await sendMessage(data)
  305. if (iterator.error) {
  306. // 实时格式化显示内容
  307. obj.content = iterator.error
  308. } else {
  309. for await (const chunk of iterator) {
  310. if (chunk) {
  311. const decodedChunk = chunk.choices[0].delta.content
  312. if (decodedChunk) {
  313. // 保存原始内容
  314. obj.rawContent += decodedChunk
  315. // 实时格式化显示内容
  316. obj.content = formatMessage(obj.rawContent)
  317. }
  318. }
  319. scrollbar.value?.setScrollTop(99999)
  320. }
  321. }
  322. //添加到存储历史
  323. useStore(msgUuid.value).add({ ...obj })
  324. // 处理最终内容
  325. sendLoading.value = false
  326. nextTick(() => {
  327. scrollbar.value?.setScrollTop(99999)
  328. })
  329. }
  330. return {
  331. indexTemp,
  332. taklToHtml,
  333. sendLoading,
  334. type,
  335. fetchRes,
  336. streamRes,
  337. getFormKeyAndValue,
  338. getFileSummary,
  339. requestFlowFn
  340. }
  341. }