ai_file.go 12 KB

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