aiChat.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import axios, { cancelToken } from '@/services/config'
  2. import { v4 as uuidv4 } from 'uuid'
  3. import { fetchEventSource } from '@microsoft/fetch-event-source'
  4. import { ref } from 'vue'
  5. const model = {}
  6. let organizeId = ''
  7. const userId2 = ref('')
  8. const userName = ref('')
  9. interface ChatParams {
  10. id: string;
  11. message: string;
  12. userId: string;
  13. model: string;
  14. file_ids: string[];
  15. sound_url: string;
  16. temperature: number;
  17. top_p: number;
  18. max_completion_tokens: number;
  19. stream: boolean;
  20. uid: string;
  21. session_name: string;
  22. tts_language: string;
  23. image_urls: string[];
  24. }
  25. const DEFAULT_PARAMS: Omit<ChatParams, 'message' | 'uid' | 'stream'> = {
  26. id: 'a7741704-ba56-40b7-a6b8-62a423ef9376',
  27. userId: '6c56ec0e-2c74-11ef-bee5-005056b86db5',
  28. model: 'open-doubao',
  29. file_ids: [],
  30. sound_url: '',
  31. // temperature: 0.2,
  32. // top_p: 1,
  33. // max_completion_tokens: 4096,
  34. session_name: 'pptSession_name',
  35. tts_language: 'zh-CN'
  36. }
  37. export const chat_no_stream = (msg: string, agentId: string, userId: string, language: string, session_name?: string, imgUrls: string[] = [], fileid: string[] = []): { promise: Promise<string>; abort: () => void } => {
  38. const source = cancelToken.source()
  39. const promise = (async () => {
  40. const agentData = await getAgentModel(agentId)
  41. const params: ChatParams = {
  42. ...DEFAULT_PARAMS,
  43. id: agentId,
  44. message: `Language: ${language === 'en'
  45. ? 'English'
  46. : language === 'hk'
  47. ? 'Traditional Chinese'
  48. : 'Chinese'
  49. } ${msg} ${language === 'hk' ? '請用繁體中文回复' : language === 'en' ? 'Please reply in English' : '请用中文回复'}`,
  50. uid: uuidv4(),
  51. stream: false,
  52. model: agentData?.modelType || 'open-doubao',
  53. userId: userId,
  54. tts_language: getTtsLanguage(language),
  55. session_name: session_name || uuidv4(),
  56. image_urls: imgUrls,
  57. file_ids: fileid || []
  58. }
  59. try {
  60. const res = await axios.post('https://appapi.cocorobo.cn/api/agentchats/ai_agent_chat', params, {
  61. cancelToken: source.token
  62. })
  63. let content = res?.message || ''
  64. console.log(content)
  65. // 清理可能的 markdown 格式
  66. if (content.includes('```json')) {
  67. // 提取 ```json 和 ``` 之间的内容
  68. const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/)
  69. if (jsonMatch) {
  70. content = jsonMatch[1].trim()
  71. }
  72. }
  73. else if (content.includes('```')) {
  74. // 提取 ``` 和 ``` 之间的内容
  75. const codeMatch = content.match(/```\s*([\s\S]*?)\s*```/)
  76. if (codeMatch) {
  77. content = codeMatch[1].trim()
  78. }
  79. }
  80. return content
  81. }
  82. catch (error) {
  83. console.log(error)
  84. return ''
  85. }
  86. })()
  87. return {
  88. promise,
  89. abort: () => source.cancel('Request canceled by user')
  90. }
  91. }
  92. export const chat_stream = async (
  93. msg: string,
  94. agentId: string,
  95. userId: string,
  96. language: string,
  97. onMessage: (event: { type: 'message' | 'close' | 'error' | 'messageEnd'; data: string }) => void,
  98. session_name?: string,
  99. file_ids?: Array<string>,
  100. model?: string,
  101. imgUrls?: Array<string>,
  102. ): Promise<{ abort: () => void }> => {
  103. const agentData = await getAgentModel(agentId)
  104. const params: ChatParams = {
  105. ...DEFAULT_PARAMS,
  106. id: agentId,
  107. file_ids: file_ids || [],
  108. message: `Language: ${language === 'en'
  109. ? 'English'
  110. : language === 'hk'
  111. ? 'Traditional Chinese'
  112. : 'Chinese'
  113. } ${msg} ${language === 'hk' ? '請用繁體中文回复' : language === 'en' ? 'Please reply in English' : '请用中文回复'}`,
  114. uid: uuidv4(),
  115. stream: true,
  116. model: model || agentData?.modelType || 'open-doubao',
  117. userId: userId,
  118. tts_language: getTtsLanguage(language),
  119. session_name: session_name || uuidv4(),
  120. image_urls: imgUrls
  121. }
  122. const ctrl = new AbortController()
  123. let content = ''
  124. // 开始请求
  125. fetchEventSource('https://appapi.cocorobo.cn/api/agentchats/ai_agent_chat', {
  126. method: 'POST',
  127. body: JSON.stringify(params),
  128. signal: ctrl.signal,
  129. headers: {
  130. 'Content-Type': 'application/json',
  131. },
  132. onmessage(event) {
  133. const data = JSON.parse(event.data)
  134. if (data.content) {
  135. if (data.content != '[DONE]') {
  136. content += data.content
  137. onMessage({
  138. type: 'message',
  139. data: content
  140. })
  141. }
  142. else {
  143. onMessage({
  144. type: 'messageEnd',
  145. data: content
  146. })
  147. }
  148. }
  149. },
  150. onclose() {
  151. onMessage({
  152. type: 'close',
  153. data: 'SSE Connection closed'
  154. })
  155. },
  156. onerror(err) {
  157. onMessage({
  158. type: 'error',
  159. data: err.message || 'Unknown error'
  160. })
  161. // 返回 undefined 以阻止自动重连,如需重连则删除此行
  162. throw err
  163. },
  164. }).catch(err => {
  165. onMessage({
  166. type: 'error',
  167. data: err || 'Unknown error'
  168. })
  169. console.log('err', err)
  170. })
  171. // 返回 abort 方法
  172. return {
  173. abort: () => ctrl.abort()
  174. }
  175. }
  176. export const getAgentModel = async (agentId: string) => {
  177. if (model[agentId]) {
  178. return model[agentId]
  179. }
  180. const res = await axios.get(`https://appapi.cocorobo.cn/api/agents/agent/${agentId}`)
  181. model[agentId] = res
  182. return model[agentId]
  183. }
  184. export const getTtsLanguage = (langCode: string) => {
  185. switch (langCode) {
  186. case 'en':return 'en-US'
  187. case 'hk':return 'yue-CN'
  188. default :return 'zh-CN'
  189. }
  190. }
  191. // AI 模型常量
  192. const AI_MODEL_CONSTANTS = {
  193. // DEFAULT_MODEL: 'gpt-4o-2024-11-20'
  194. DEFAULT_MODEL: 'qwen-flash'
  195. }
  196. export const chat_no_stream2 = async (prompt: any[] = [], response_format = {
  197. 'type': 'text'
  198. }, model = AI_MODEL_CONSTANTS.DEFAULT_MODEL) => {
  199. return await new Promise((resolve) => {
  200. const uid = uuidv4()
  201. const data = JSON.stringify({
  202. model: model,
  203. temperature: 0,
  204. max_tokens: 4096,
  205. top_p: 1,
  206. frequency_penalty: 0,
  207. presence_penalty: 0,
  208. messages: prompt,
  209. uid: uid,
  210. mind_map_question: '',
  211. stream: false,
  212. response_format: response_format
  213. })
  214. const config = {
  215. method: 'post',
  216. url: 'https://appapi.cocorobo.cn/api/common/chat',
  217. headers: {
  218. 'Content-Type': 'application/json'
  219. },
  220. data: data,
  221. }
  222. axios(config)
  223. .then((response) => {
  224. let content = response?.FunctionResponse?.choices[0]?.message?.content || ''
  225. // 清理可能的 markdown 格式
  226. if (content.includes('```json')) {
  227. // 提取 ```json 和 ``` 之间的内容
  228. const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/)
  229. if (jsonMatch) {
  230. content = jsonMatch[1].trim()
  231. }
  232. }
  233. else if (content.includes('```')) {
  234. // 提取 ``` 和 ``` 之间的内容
  235. const codeMatch = content.match(/```\s*([\s\S]*?)\s*```/)
  236. if (codeMatch) {
  237. content = codeMatch[1].trim()
  238. }
  239. }
  240. resolve(content)
  241. })
  242. .catch( (error) => {
  243. console.log(error)
  244. // this.$message.error('服务器繁忙');
  245. resolve(false)
  246. })
  247. })
  248. }
  249. export const agentlistloading = ref(false)
  250. export const getAgentChatList = async (id: string, userId: string): Promise<any[]> => {
  251. if (!id) {
  252. return []
  253. }
  254. agentlistloading.value = true
  255. if (!organizeId || userId2.value !== userId) {
  256. userId2.value = userId
  257. const res = await axios.get('https://pbl.cocorobo.cn/api/pbl/selectUser', {
  258. params: { userid: userId }
  259. })
  260. userName.value = res[0][0].name
  261. organizeId = res[0][0].organizeId
  262. }
  263. try {
  264. const response = await axios.post('https://gpt4.cocorobo.cn/get_agent_chat', {
  265. userid: userId,
  266. groupid: id,
  267. }, {
  268. headers: {
  269. 'Content-Type': 'application/json',
  270. 'hwMac': organizeId,
  271. },
  272. })
  273. const chat_list = JSON.parse(response?.FunctionResponse || '[]')
  274. const messages = []
  275. chat_list.forEach((item: any, index: number) => {
  276. const json: any = {
  277. role: 'user' as const,
  278. userName: item.username,
  279. content: decodeURIComponent(item.problem),
  280. uid: id,
  281. AI: 'AI',
  282. aiContent: decodeURIComponent(item.answer),
  283. reasoning: item.reasoning_content,
  284. oldContent: decodeURIComponent(new DOMParser().parseFromString(
  285. item.answer,
  286. 'text/html'
  287. ).documentElement.textContent),
  288. isShowSynchronization: false,
  289. filename: item.filename,
  290. index: index,
  291. createtime: item.createtime,
  292. is_mind_map: item.problem.includes('思维导图') ||
  293. item.problem.includes('思維導圖') ||
  294. item.problem.includes('mindMap'),
  295. graph: item.problem === '知识图谱', // 使用默认值,因为无法访问this.lang
  296. }
  297. try {
  298. json.jsonData = item.jsonData !== 'undefined' && item.jsonData !== null ? JSON.parse(decodeURIComponent(item.jsonData)) : null
  299. // 从 jsonData 中读取 syncTranscriptionText 值
  300. if (json.jsonData && json.jsonData.syncTranscriptionText !== undefined) {
  301. json.syncTranscriptionText = json.jsonData.syncTranscriptionText
  302. }
  303. else {
  304. // 如果没有 jsonData 或 syncTranscriptionText,使用默认值
  305. json.syncTranscriptionText = false
  306. }
  307. // 从 jsonData 中读取 contentType 值
  308. if (json.jsonData && json.jsonData.contentType !== undefined) {
  309. json.contentType = json.jsonData.contentType
  310. }
  311. else {
  312. // 如果没有 jsonData 或 contentType,使用默认值
  313. json.contentType = 'text'
  314. }
  315. // 新增:从 jsonData 中恢复用户音频播放所需字段
  316. if (json.jsonData && json.jsonData.audio) {
  317. json.audio = json.jsonData.audio
  318. }
  319. if (json.jsonData && json.jsonData.durationSec) {
  320. json.durationSec = json.jsonData.durationSec
  321. }
  322. }
  323. catch (error) {
  324. console.error('Error parsing jsonData:', error)
  325. json.jsonData = null
  326. json.syncTranscriptionText = false
  327. json.contentType = 'text'
  328. agentlistloading.value = false
  329. }
  330. messages.push(json)
  331. })
  332. agentlistloading.value = false
  333. return messages
  334. }
  335. catch (error) {
  336. console.error('Error fetching agent chat list:', error)
  337. return []
  338. }
  339. }
  340. export interface InsertChatParams {
  341. answer: string;
  342. problem: string;
  343. type: string;
  344. alltext: string;
  345. assistant_id: string;
  346. userId: string;
  347. userName: string;
  348. fileId?: string;
  349. latestMessage?: any;
  350. agentHeadUrl?: string;
  351. agentAssistantName?: string;
  352. jsonData?: any;
  353. }
  354. export interface InsertChatResult {
  355. success: boolean;
  356. questions?: string[];
  357. }
  358. export const insertChat = async (params: InsertChatParams): Promise<InsertChatResult> => {
  359. const {
  360. answer,
  361. problem,
  362. type,
  363. alltext,
  364. assistant_id,
  365. fileId,
  366. latestMessage,
  367. agentHeadUrl,
  368. agentAssistantName,
  369. jsonData
  370. } = params
  371. const jsonData2: any = {
  372. headUrl: agentHeadUrl || '',
  373. assistantName: agentAssistantName || '',
  374. ...jsonData
  375. }
  376. try {
  377. const response = await axios.post('https://gpt4.cocorobo.cn/insert_chat', {
  378. userId: userId2.value,
  379. userName: userName.value,
  380. groupId: assistant_id,
  381. answer: encodeURIComponent(answer),
  382. problem: encodeURIComponent(problem),
  383. file_id: type === 'chat' ? '' : fileId,
  384. alltext,
  385. type,
  386. jsonData: encodeURIComponent(JSON.stringify(jsonData))
  387. }, {
  388. headers: {
  389. 'Content-Type': 'application/json',
  390. hwMac: organizeId,
  391. },
  392. })
  393. // 处理返回的问题结果
  394. if (response?.FunctionResponse?.questions_result) {
  395. const data = response?.FunctionResponse.questions_result
  396. if (data.includes('\n')) {
  397. const arr = data.split('\n')
  398. let questions: string[] = []
  399. if (arr.length > 3) {
  400. questions = arr.slice(0, 3)
  401. }
  402. else {
  403. questions = [...arr]
  404. }
  405. return {
  406. success: true,
  407. questions
  408. }
  409. }
  410. }
  411. return {
  412. success: true
  413. }
  414. }
  415. catch (error) {
  416. console.error('Error inserting chat:', error)
  417. return {
  418. success: false
  419. }
  420. }
  421. }