llm_service.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. if mapping.Id == 0 || mapping.KbId == "" {
  55. article, fileErr := rag.GetArticleById(aigc.ArticleId)
  56. if fileErr != nil {
  57. // 找不到就处理失败
  58. utils.FileLog.Error("公众号文章不存在")
  59. err = fmt.Errorf("公众号文章不存在")
  60. return
  61. }
  62. // 文章加入到知识库
  63. path, fileErr := localService.CreateArticleFile(article)
  64. if fileErr != nil {
  65. utils.FileLog.Error("创建文章文件失败,err: %v", fileErr)
  66. err = fmt.Errorf("创建文章文件失败,err: %v", fileErr)
  67. return
  68. }
  69. defer func() {
  70. _ = os.Remove(path)
  71. }()
  72. file, err = os.Open(path)
  73. if err != nil {
  74. utils.FileLog.Error("打开文件失败,err:", err)
  75. return
  76. }
  77. uploadResp, httpErr := llmService.UploadFileToTemplate([]*os.File{file}, nil)
  78. if httpErr != nil {
  79. utils.FileLog.Error("上传文件失败,err:", err.Error())
  80. err = fmt.Errorf("上传文件失败,err:%v", httpErr)
  81. return
  82. }
  83. data := uploadResp.(eta_llm_http.UploadDocsResponse)
  84. //保存映射关系到数据库
  85. if data.Id == "" {
  86. utils.FileLog.Error("上传文件失败,向量库Id获取失败")
  87. err = fmt.Errorf("上传文件失败,向量库Id获取失败")
  88. return
  89. }
  90. err = rag.CreateArticleKbMapping(rag.ArticleKbMapping{
  91. WechatArticleId: aigc.ArticleId,
  92. KbId: data.Id,
  93. CreatedTime: time.Now(),
  94. })
  95. if err != nil {
  96. utils.FileLog.Warn("创建文章知识库映射关系失败,err:", err.Error())
  97. }
  98. kbId = data.Id
  99. } else {
  100. kbId = mapping.KbId
  101. }
  102. //知识库对话
  103. response, httpErr := llmService.FileChat(aigc.Promote, kbId, nil)
  104. if httpErr != nil {
  105. utils.FileLog.Error("内容生成失败,err:", err.Error())
  106. err = fmt.Errorf("内容生成失败,err:%v", httpErr)
  107. return
  108. }
  109. gcResp, gcErr := dealFileChatResp(response)
  110. if gcErr != nil {
  111. utils.FileLog.Error("内容生成失败,err:%v", gcErr.Error())
  112. err = fmt.Errorf("内容生成失败,err:%v", gcErr)
  113. return
  114. }
  115. if gcResp.Code == 200 {
  116. resp = gcResp.Data
  117. return
  118. }
  119. if gcResp.Code == 404 {
  120. response, httpErr = llmService.FileChat(aigc.Promote, kbId, nil)
  121. if httpErr != nil {
  122. utils.FileLog.Error("内容生成失败,err:%v", httpErr.Error())
  123. err = fmt.Errorf("内容生成失败,err:%v", httpErr)
  124. return
  125. }
  126. gcResp, gcErr = dealFileChatResp(response)
  127. if gcErr != nil {
  128. utils.FileLog.Error("内容生成失败,err:%v", gcErr.Error())
  129. err = fmt.Errorf("内容生成失败,err:%v", gcErr)
  130. return
  131. }
  132. if gcResp.Code == 200 {
  133. resp = gcResp.Data
  134. return
  135. }
  136. utils.FileLog.Error("内容生成失败,err:%v", gcResp.Code, gcResp.Msg)
  137. err = fmt.Errorf("内容生成失败,code:%v,err:%v", gcResp.Code, gcResp.Msg)
  138. return
  139. } else {
  140. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", gcResp.Code, gcResp.Msg)
  141. err = fmt.Errorf("内容生成失败,err:%v", gcResp.Msg)
  142. return
  143. }
  144. }
  145. }
  146. type LLMKnowledgeSearch struct {
  147. Query string `json:"Query"`
  148. KnowledgeBaseName string `json:"KnowledgeBaseName"`
  149. }
  150. type AIGC struct {
  151. Promote string
  152. ArticleId int
  153. }
  154. func dealFileChatResp(response eta_llm_http.BaseResponse) (httpResponse bus_response.FileChatBaseResponse, err error) {
  155. if !response.Success {
  156. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", response.Ret, response.Msg)
  157. err = fmt.Errorf("内容生成失败,code:%v,msg:%v", response.Ret, response.Msg)
  158. return
  159. } else {
  160. var dataStr string
  161. // 按行分割输入
  162. lines := strings.Split(string(response.Data), "\n")
  163. // 遍历每一行,提取以 "data:" 开头的内容
  164. for _, line := range lines {
  165. if !strings.HasPrefix(line, ": ping") && strings.TrimSpace(line) != "" {
  166. // 去掉 "data:" 前缀
  167. dataStr += line
  168. }
  169. }
  170. // 去除 "data: " 前缀
  171. if strings.HasPrefix(dataStr, "data: ") {
  172. dataStr = strings.TrimPrefix(dataStr, "data: ")
  173. var streamResponse bus_response.AIGCEtaResponse
  174. parseErr := json.Unmarshal([]byte(dataStr), &streamResponse)
  175. if parseErr != nil {
  176. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  177. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  178. return
  179. }
  180. httpResponse.Data = streamResponse
  181. httpResponse.Msg = "返回成功"
  182. httpResponse.Code = 200
  183. return
  184. } else {
  185. parseErr := json.Unmarshal([]byte(dataStr), &httpResponse)
  186. if parseErr != nil {
  187. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  188. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  189. return
  190. }
  191. return
  192. }
  193. }
  194. }