ai_file.go 13 KB

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