llm_service.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package facade
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_api/models/rag"
  6. localService "eta/eta_api/services/llm"
  7. "eta/eta_api/services/llm/facade/bus_response"
  8. "eta/eta_api/utils"
  9. "eta/eta_api/utils/llm"
  10. "eta/eta_api/utils/llm/eta_llm/eta_llm_http"
  11. "eta/eta_api/utils/ws"
  12. "fmt"
  13. "github.com/gorilla/websocket"
  14. "github.com/rdlucklib/rdluck_tools/uuid"
  15. "gorm.io/gorm"
  16. "os"
  17. "strings"
  18. "time"
  19. )
  20. var (
  21. llmService, _ = llm.GetInstance(llm.ETA_LLM_CLIENT)
  22. )
  23. func generateSessionCode() (code string) {
  24. return fmt.Sprintf("%s%s", "llm_session_", uuid.NewUUID().Hex32())
  25. }
  26. // AddSession 创建会话session
  27. func AddSession(userId int, conn *websocket.Conn) {
  28. sessionId := generateSessionCode()
  29. session := ws.NewSession(userId, sessionId, conn)
  30. ws.Manager().AddSession(session)
  31. }
  32. // LLMKnowledgeBaseSearchDocs 搜索知识库
  33. func LLMKnowledgeBaseSearchDocs(search LLMKnowledgeSearch) (resp bus_response.SearchDocsEtaResponse, err error) {
  34. docs, err := llmService.SearchKbDocs(search.Query, search.KnowledgeBaseName)
  35. if err != nil {
  36. return
  37. }
  38. for _, doc := range docs.([]eta_llm_http.SearchDocsResponse) {
  39. resp.Content = resp.Content + doc.PageContent
  40. }
  41. resp.Docs = docs.([]eta_llm_http.SearchDocsResponse)
  42. return
  43. }
  44. // AIGCBaseOnPromote aigc 生成内容
  45. func AIGCBaseOnPromote(aigc AIGC) (resp bus_response.AIGCEtaResponse, err error) {
  46. mapping, queryErr := rag.GetArticleKbMapping(aigc.ArticleId)
  47. if queryErr != nil && !errors.Is(queryErr, gorm.ErrRecordNotFound) {
  48. utils.FileLog.Error("获取文章知识库信息失败,err: %v", queryErr)
  49. err = fmt.Errorf("获取文章知识库信息失败,err: %v", queryErr)
  50. return
  51. } else {
  52. var kbId string
  53. var file *os.File
  54. params := make(map[string]interface{})
  55. if mapping.Id == 0 || mapping.KbId == "" {
  56. article, fileErr := rag.GetArticleById(aigc.ArticleId)
  57. if fileErr != nil {
  58. // 找不到就处理失败
  59. utils.FileLog.Error("公众号文章不存在")
  60. err = fmt.Errorf("公众号文章不存在")
  61. return
  62. }
  63. // 文章加入到知识库
  64. path, fileErr := localService.CreateArticleFile(article)
  65. if fileErr != nil {
  66. utils.FileLog.Error("创建文章文件失败,err: %v", fileErr)
  67. err = fmt.Errorf("创建文章文件失败,err: %v", fileErr)
  68. return
  69. }
  70. defer func() {
  71. _ = os.Remove(path)
  72. }()
  73. file, err = os.Open(path)
  74. if err != nil {
  75. utils.FileLog.Error("打开文件失败,err:", err)
  76. return
  77. }
  78. uploadResp, httpErr := llmService.UploadFileToTemplate([]*os.File{file}, params)
  79. if httpErr != nil {
  80. utils.FileLog.Error("上传文件失败,err:", err.Error())
  81. err = fmt.Errorf("上传文件失败,err:%v", httpErr)
  82. return
  83. }
  84. data := uploadResp.(eta_llm_http.UploadDocsResponse)
  85. //保存映射关系到数据库
  86. if data.Id == "" {
  87. utils.FileLog.Error("上传文件失败,向量库Id获取失败")
  88. err = fmt.Errorf("上传文件失败,向量库Id获取失败")
  89. return
  90. }
  91. err = rag.CreateArticleKbMapping(rag.ArticleKbMapping{
  92. WechatArticleId: aigc.ArticleId,
  93. KbId: data.Id,
  94. CreatedTime: time.Now(),
  95. })
  96. if err != nil {
  97. utils.FileLog.Warn("创建文章知识库映射关系失败,err:", err.Error())
  98. }
  99. kbId = data.Id
  100. } else {
  101. kbId = mapping.KbId
  102. }
  103. //知识库对话
  104. response, httpErr := llmService.FileChat(aigc.Promote, kbId, nil)
  105. if httpErr != nil {
  106. utils.FileLog.Error("内容生成失败,err:", err.Error())
  107. err = fmt.Errorf("内容生成失败,err:%v", httpErr)
  108. return
  109. }
  110. if !response.Success {
  111. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", response.Ret, response.Msg)
  112. err = fmt.Errorf("内容生成失败,code:%v,msg:%v", response.Ret, response.Msg)
  113. return
  114. } else {
  115. dataStr := string(response.Data)
  116. // 去除 "data: " 前缀
  117. if strings.HasPrefix(dataStr, "data: ") {
  118. dataStr = strings.TrimPrefix(dataStr, "data: ")
  119. parseErr := json.Unmarshal([]byte(dataStr), &resp)
  120. if parseErr != nil {
  121. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  122. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  123. return
  124. }
  125. return
  126. } else {
  127. var baseResp eta_llm_http.RagBaseResponse
  128. parseErr := json.Unmarshal([]byte(dataStr), &baseResp)
  129. if parseErr != nil {
  130. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  131. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  132. return
  133. }
  134. if baseResp.Code == 404 {
  135. params["PrevId"] = kbId
  136. _, putErr := llmService.UploadFileToTemplate([]*os.File{file}, params)
  137. if putErr != nil {
  138. utils.FileLog.Error("内容生成失败,err:", err.Error())
  139. err = fmt.Errorf("内容生成失败,err:%v", httpErr)
  140. return
  141. }
  142. } else {
  143. utils.FileLog.Error("内容生成失败,code:%v", baseResp.Code)
  144. err = fmt.Errorf("内容生成失败,code:%v", baseResp.Code)
  145. return
  146. }
  147. }
  148. gcResp, gcErr := llmService.FileChat(aigc.Promote, kbId, nil)
  149. if gcErr != nil {
  150. utils.FileLog.Error("内容生成失败,err:%v", gcErr.Error())
  151. err = fmt.Errorf("内容生成失败,err:%v", gcErr)
  152. return
  153. }
  154. if !gcResp.Success {
  155. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", gcResp.Ret, gcResp.Msg)
  156. err = fmt.Errorf("内容生成失败,err:%v", gcResp.Msg)
  157. }
  158. dataStr = string(gcResp.Data)
  159. // 去除 "data: " 前缀
  160. if strings.HasPrefix(dataStr, "data: ") {
  161. dataStr = strings.TrimPrefix(dataStr, "data: ")
  162. parseErr := json.Unmarshal([]byte(dataStr), &resp)
  163. if parseErr != nil {
  164. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  165. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  166. return
  167. }
  168. } else {
  169. var baseResp eta_llm_http.RagBaseResponse
  170. parseErr := json.Unmarshal([]byte(dataStr), &baseResp)
  171. if parseErr != nil {
  172. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  173. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  174. return
  175. }
  176. utils.FileLog.Error("内容生成失败,code:%v", baseResp.Code)
  177. err = fmt.Errorf("内容生成失败,code:%v", baseResp.Code)
  178. return
  179. }
  180. }
  181. }
  182. return
  183. }
  184. type LLMKnowledgeSearch struct {
  185. Query string `json:"Query"`
  186. KnowledgeBaseName string `json:"KnowledgeBaseName"`
  187. }
  188. type AIGC struct {
  189. Promote string
  190. ArticleId int
  191. }