ai_file.go 12 KB

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