aiChat.ts 12 KB

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