ai_file.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package ai
  2. import (
  3. "encoding/json"
  4. "eta/eta_api/controllers"
  5. "eta/eta_api/models"
  6. "eta/eta_api/models/aimod"
  7. "eta/eta_api/services"
  8. "eta/eta_api/services/aiser"
  9. "eta/eta_api/services/alarm_msg"
  10. "eta/eta_api/utils"
  11. "fmt"
  12. "os"
  13. "path"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. type AiFileController struct {
  19. controllers.BaseAuthController
  20. }
  21. // @Title 文件上传
  22. // @Description 文件上传接口
  23. // @Param File query file true "文件"
  24. // @Param AiChatTopicId query int true "主题id"
  25. // @Success 200 {object} models.ResourceResp
  26. // @router /file/upload [post]
  27. func (this *AiFileController) FileUpload() {
  28. br := new(models.BaseResponse).Init()
  29. defer func() {
  30. this.Data["json"] = br
  31. this.ServeJSON()
  32. }()
  33. f, h, err := this.GetFile("File")
  34. if err != nil {
  35. br.Msg = "获取资源信息失败"
  36. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  37. return
  38. }
  39. model := this.GetString("Model")
  40. aiChatTopicId, _ := this.GetInt("AiChatTopicId")
  41. uploadFileName := h.Filename //上传的文件名
  42. ext := path.Ext(h.Filename)
  43. dateDir := time.Now().Format("20060102")
  44. uploadDir := utils.STATIC_DIR + "ai/" + dateDir
  45. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  46. if err != nil {
  47. br.Msg = "存储目录创建失败"
  48. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  49. return
  50. }
  51. randStr := utils.GetRandStringNoSpecialChar(28)
  52. fileName := randStr + ext
  53. fpath := uploadDir + "/" + fileName
  54. defer f.Close() //关闭上传文件
  55. err = this.SaveToFile("File", fpath)
  56. if err != nil {
  57. br.Msg = "文件上传失败"
  58. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  59. return
  60. }
  61. resourceUrl := ``
  62. ossClient := services.NewOssClient()
  63. if ossClient == nil {
  64. br.Msg = "上传失败"
  65. br.ErrMsg = "初始化OSS服务失败"
  66. return
  67. }
  68. resourceUrl, err = ossClient.UploadFile(fileName, fpath, "")
  69. if err != nil {
  70. br.Msg = "文件上传失败"
  71. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  72. return
  73. }
  74. defer func() {
  75. os.Remove(fpath)
  76. }()
  77. item := new(models.Resource)
  78. item.ResourceUrl = resourceUrl
  79. item.ResourceType = 1
  80. item.CreateTime = time.Now()
  81. newId, err := models.AddResource(item)
  82. if err != nil {
  83. br.Msg = "资源上传失败"
  84. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  85. return
  86. }
  87. //调用AI接口,上传文件
  88. resp := models.ResourceResp{
  89. Id: newId,
  90. ResourceUrl: resourceUrl,
  91. ResourceName: uploadFileName,
  92. }
  93. uploadResult, err := aiser.OpenAiFileUpload(resourceUrl, uploadFileName, model)
  94. if err != nil {
  95. br.Msg = "文件上传失败"
  96. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  97. return
  98. }
  99. var assistantId, threadId string
  100. if aiChatTopicId > 0 {
  101. aiChatTopicObj := new(aimod.AiChatTopic)
  102. aiChatTopicObj.AiChatTopicId = aiChatTopicId
  103. topic, err := aiChatTopicObj.GetAiChatTopicById()
  104. if err != nil {
  105. if err.Error() == utils.ErrNoRow() {
  106. br.Msg = "获取数据失败!"
  107. br.ErrMsg = "获取数据失败,主题不存在,Err:" + err.Error()
  108. return
  109. }
  110. br.Msg = "获取数据失败!"
  111. br.ErrMsg = "获取数据失败,GetAiChatTopicById,Err:" + err.Error()
  112. return
  113. }
  114. assistantId = topic.AssistantId
  115. threadId = topic.ThreadId
  116. }
  117. if aiChatTopicId <= 0 { //新增
  118. topic := new(aimod.AiChatTopic)
  119. var filenameWithSuffix string
  120. filenameWithSuffix = path.Base(uploadFileName)
  121. var fileSuffix string
  122. fileSuffix = path.Ext(filenameWithSuffix)
  123. var filenameOnly string
  124. filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix)
  125. topic.TopicName = filenameOnly
  126. topic.SysUserId = this.SysUser.AdminId
  127. topic.SysUserRealName = this.SysUser.RealName
  128. topic.CreateTime = time.Now()
  129. topic.ModifyTime = time.Now()
  130. topic.AssistantId = assistantId
  131. topic.ThreadId = threadId
  132. topicId, err := aimod.AddAiChatTopic(topic)
  133. if err != nil {
  134. br.Msg = "获取数据失败!"
  135. br.ErrMsg = "生成话题失败,Err:" + err.Error()
  136. return
  137. }
  138. aiChatTopicId = int(topicId)
  139. chatItem := new(aimod.AiChat)
  140. chatItem.AiChatTopicId = aiChatTopicId
  141. chatItem.Ask = uploadFileName
  142. chatItem.AskUuid = utils.MD5(uploadFileName)
  143. chatItem.Model = EnabledModelsForMap[model]
  144. chatItem.SysUserId = this.SysUser.AdminId
  145. chatItem.SysUserRealName = this.SysUser.RealName
  146. if uploadResult != nil && uploadResult.Data != nil {
  147. chatItem.OpenaiFileId = uploadResult.Data.ID
  148. chatItem.OpenaiFileName = uploadFileName
  149. }
  150. chatItem.OpenaiFilePath = resourceUrl
  151. chatItem.CreateTime = time.Now()
  152. chatItem.ModifyTime = time.Now()
  153. bchat, err := json.Marshal(chatItem)
  154. if err != nil {
  155. br.Msg = "获取数据失败!"
  156. br.ErrMsg = "生成话题失败,Err:" + err.Error()
  157. return
  158. }
  159. alarm_msg.SendAlarmMsg(string(bchat), 1)
  160. alarm_msg.SendAlarmMsg(string("cur model:"+model), 1)
  161. _, err = aimod.AddAiChat(chatItem)
  162. if err != nil {
  163. br.Msg = "获取数据失败!"
  164. br.ErrMsg = "生成话题记录失败,Err:" + err.Error()
  165. return
  166. }
  167. } else {
  168. chatItem := new(aimod.AiChat)
  169. chatItem.AiChatTopicId = aiChatTopicId
  170. chatItem.Ask = uploadFileName
  171. chatItem.AskUuid = utils.MD5(fileName)
  172. chatItem.Model = EnabledModelsForMap[model]
  173. chatItem.SysUserId = this.SysUser.AdminId
  174. chatItem.SysUserRealName = this.SysUser.RealName
  175. if uploadResult != nil && uploadResult.Data != nil {
  176. chatItem.OpenaiFileId = uploadResult.Data.ID
  177. chatItem.OpenaiFileName = uploadFileName
  178. }
  179. chatItem.OpenaiFilePath = resourceUrl
  180. chatItem.CreateTime = time.Now()
  181. chatItem.ModifyTime = time.Now()
  182. _, err = aimod.AddAiChat(chatItem)
  183. if err != nil {
  184. br.Msg = "获取数据失败!"
  185. br.ErrMsg = "生成话题记录失败,Err:" + err.Error()
  186. return
  187. }
  188. }
  189. if uploadResult != nil && uploadResult.Data != nil && uploadResult.Data.ID != "" {
  190. uploadObj := new(aimod.FileUploadRecord)
  191. uploadObj.AdminId = this.SysUser.AdminId
  192. uploadObj.FileUrl = resourceUrl
  193. uploadObj.FileName = uploadFileName
  194. uploadObj.OpenaiFileId = uploadResult.Data.ID
  195. uploadObj.OpenaiFileName = uploadResult.Data.FileName
  196. uploadObj.OpenaiObject = uploadResult.Data.Object
  197. uploadObj.OpenaiStatus = uploadResult.Data.Status
  198. uploadObj.OpenaiPurpose = uploadResult.Data.Purpose
  199. uploadObj.OpenaiStatusDetails = uploadResult.Data.StatusDetails
  200. uploadObj.OpenaiCreatedAt = uploadResult.Data.CreatedAt
  201. uploadObj.CreateTime = time.Now()
  202. uploadObj.ModifyTime = time.Now()
  203. _, err = uploadObj.AddFileUploadRecord()
  204. if err != nil {
  205. br.Msg = "上传失败"
  206. br.ErrMsg = "上传失败,Err:" + err.Error()
  207. return
  208. }
  209. resp.OpenaiFileId = uploadObj.OpenaiFileId
  210. }
  211. resp.AiChatTopicId = aiChatTopicId
  212. br.Msg = "上传成功"
  213. br.Ret = 200
  214. br.Success = true
  215. br.Data = resp
  216. return
  217. }
  218. // @Title 文件检索
  219. // @Description 文件检索接口
  220. // @Param request body aimod.FileRetrieveReq true "type json string"
  221. // @Success 200 {object} models.ResourceResp
  222. // @router /file/retrieve [post]
  223. func (this *AiFileController) FileRetrieve() {
  224. br := new(models.BaseResponse).Init()
  225. defer func() {
  226. this.Data["json"] = br
  227. this.ServeJSON()
  228. }()
  229. var req aimod.FileRetrieveReq
  230. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  231. if err != nil {
  232. br.Msg = "参数解析异常!"
  233. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  234. return
  235. }
  236. if req.Ask == "" {
  237. br.Msg = "请输入提问内容!"
  238. br.ErrMsg = "请输入提问内容"
  239. return
  240. }
  241. if utils.Re == nil {
  242. key := "CACHE_CHAT_" + strconv.Itoa(this.SysUser.AdminId)
  243. cacheVal, err := utils.Rc.RedisInt(key)
  244. fmt.Println("RedisString:", cacheVal, "err:", err)
  245. if err != nil && (err.Error() != "redigo: nil returned" && err.Error() != "redis: nil") {
  246. br.Msg = "获取数据失败!"
  247. br.ErrMsg = "获取数据失败,Err:" + err.Error()
  248. return
  249. }
  250. putVal := 0
  251. if cacheVal <= 0 {
  252. putVal = utils.AiChatLimit
  253. } else {
  254. putVal = cacheVal - 1
  255. }
  256. if putVal <= 0 {
  257. br.Msg = "您今日" + strconv.Itoa(utils.AiChatLimit) + "次问答已达上限,请明天再来!"
  258. br.ErrMsg = "您今日" + strconv.Itoa(utils.AiChatLimit) + "次问答已达上限,请明天再来!"
  259. return
  260. }
  261. lastSecond := utils.GetTodayLastSecond()
  262. utils.Rc.Put(key, putVal, lastSecond)
  263. }
  264. //根据提问,获取信息
  265. askUuid := utils.MD5(req.Ask)
  266. //chatMode, err := aimod.GetAiChatByAsk(askUuid)
  267. //if err != nil && err.Error() != utils.ErrNoRow() {
  268. // br.Msg = "获取数据失败!"
  269. // br.ErrMsg = "获取数据失败,GetAiChatByAsk,Err:" + err.Error()
  270. // return
  271. //}
  272. var assistantId, threadId string
  273. if req.AiChatTopicId > 0 {
  274. aiChatTopicObj := new(aimod.AiChatTopic)
  275. aiChatTopicObj.AiChatTopicId = req.AiChatTopicId
  276. topic, err := aiChatTopicObj.GetAiChatTopicById()
  277. if err != nil {
  278. if err.Error() == utils.ErrNoRow() {
  279. br.Msg = "获取数据失败!"
  280. br.ErrMsg = "获取数据失败,主题不存在,Err:" + err.Error()
  281. return
  282. }
  283. br.Msg = "获取数据失败!"
  284. br.ErrMsg = "获取数据失败,GetAiChatTopicById,Err:" + err.Error()
  285. return
  286. }
  287. assistantId = topic.AssistantId
  288. threadId = topic.ThreadId
  289. }
  290. resp := new(aimod.ChatResp)
  291. var answer string
  292. //获取主题下的所有信息
  293. //AiChatTopicId
  294. historyList, err := aimod.GetAiChatList(req.AiChatTopicId)
  295. if err != nil && err.Error() != utils.ErrNoRow() {
  296. br.Msg = "获取主题历史数据失败!"
  297. br.ErrMsg = "获取主题历史数据失败,Err:" + err.Error()
  298. return
  299. }
  300. frList := make([]aimod.HistoryChat, 0)
  301. tmpFileIdList := make([]string, 0)
  302. // 历史消息
  303. for _, v := range historyList {
  304. if v.OpenaiFileId != "" {
  305. tmpFileIdList = append(tmpFileIdList, v.OpenaiFileId)
  306. } else {
  307. historyFr := new(aimod.HistoryChat)
  308. historyFr.Ask = v.Ask
  309. historyFr.Answer = v.Answer
  310. historyFr.OpenaiFileId = tmpFileIdList
  311. frList = append(frList, *historyFr)
  312. tmpFileIdList = []string{}
  313. }
  314. }
  315. // 当前的消息
  316. {
  317. frItem := new(aimod.HistoryChat)
  318. frItem.Ask = req.Ask
  319. frItem.Answer = ""
  320. frItem.OpenaiFileId = tmpFileIdList
  321. frList = append(frList, *frItem)
  322. }
  323. fileRetrieveResp, err := aiser.FileRetrieve(assistantId, threadId, req.Model, frList, req.OpenaiFileId)
  324. if err != nil {
  325. br.Msg = "获取数据失败!"
  326. br.ErrMsg = "获取数据失败,FileRetrieve,Err:" + err.Error()
  327. return
  328. }
  329. if fileRetrieveResp != nil {
  330. if fileRetrieveResp.Ret == 200 {
  331. assistantId = fileRetrieveResp.Data.AssistantId
  332. threadId = fileRetrieveResp.Data.ThreadId
  333. answer = fileRetrieveResp.Data.Answer
  334. } else {
  335. br.Msg = "获取数据失败!"
  336. br.ErrMsg = fileRetrieveResp.Msg
  337. return
  338. }
  339. }
  340. if req.AiChatTopicId <= 0 { //新增
  341. topic := new(aimod.AiChatTopic)
  342. topic.TopicName = req.Ask
  343. topic.SysUserId = this.SysUser.AdminId
  344. topic.SysUserRealName = this.SysUser.RealName
  345. topic.CreateTime = time.Now()
  346. topic.ModifyTime = time.Now()
  347. topic.AssistantId = assistantId
  348. topic.ThreadId = threadId
  349. topicId, err := aimod.AddAiChatTopic(topic)
  350. if err != nil {
  351. br.Msg = "获取数据失败!"
  352. br.ErrMsg = "生成话题失败,Err:" + err.Error()
  353. return
  354. }
  355. chatItem := new(aimod.AiChat)
  356. chatItem.AiChatTopicId = int(topicId)
  357. chatItem.Ask = req.Ask
  358. chatItem.AskUuid = utils.MD5(req.Ask)
  359. chatItem.Answer = answer
  360. chatItem.Model = EnabledModelsForMap[req.Model]
  361. chatItem.SysUserId = this.SysUser.AdminId
  362. chatItem.SysUserRealName = this.SysUser.RealName
  363. chatItem.CreateTime = time.Now()
  364. chatItem.ModifyTime = time.Now()
  365. _, err = aimod.AddAiChat(chatItem)
  366. if err != nil {
  367. br.Msg = "获取数据失败!"
  368. br.ErrMsg = "生成话题记录失败,Err:" + err.Error()
  369. return
  370. }
  371. req.AiChatTopicId = int(topicId)
  372. } else {
  373. chatItem := new(aimod.AiChat)
  374. chatItem.AiChatTopicId = req.AiChatTopicId
  375. chatItem.Ask = req.Ask
  376. chatItem.AskUuid = askUuid
  377. chatItem.Answer = answer
  378. chatItem.Model = EnabledModelsForMap[req.Model]
  379. chatItem.SysUserId = this.SysUser.AdminId
  380. chatItem.SysUserRealName = this.SysUser.RealName
  381. chatItem.CreateTime = time.Now()
  382. chatItem.ModifyTime = time.Now()
  383. _, err = aimod.AddAiChat(chatItem)
  384. if err != nil {
  385. br.Msg = "获取数据失败!"
  386. br.ErrMsg = "生成话题记录失败,Err:" + err.Error()
  387. return
  388. }
  389. //更新 assistantId,threadId
  390. aiChatTopicObj := new(aimod.AiChatTopic)
  391. updateParams := make(map[string]interface{})
  392. updateParams["assistant_id"] = assistantId
  393. updateParams["thread_id"] = threadId
  394. updateParams["modify_time"] = time.Now()
  395. whereParam := make(map[string]interface{})
  396. whereParam["ai_chat_topic_id"] = req.AiChatTopicId
  397. err = aiChatTopicObj.Update(updateParams, whereParam)
  398. if err != nil {
  399. br.Msg = "获取失败!"
  400. br.ErrMsg = "修改助手标识失败,Err:" + err.Error()
  401. return
  402. }
  403. }
  404. resp.Model = aimod.ModelViewMap[req.Model]
  405. resp.AiChatTopicId = req.AiChatTopicId
  406. resp.Ask = req.Ask
  407. resp.Answer = answer
  408. br.Ret = 200
  409. br.Success = true
  410. br.Msg = "获取成功"
  411. br.Data = resp
  412. return
  413. }
  414. var EnabledModelsForMap = map[string]string{
  415. "Kimi": "moonshot-v1-32k",
  416. "GPT-4 Turbo": "gpt-4-1106-preview",
  417. }