llm_service.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. var dataStr string
  116. // 按行分割输入
  117. lines := strings.Split(string(response.Data), "\n")
  118. // 遍历每一行,提取以 "data:" 开头的内容
  119. for _, line := range lines {
  120. if !strings.HasPrefix(line, ": ping") && strings.TrimSpace(line) != "" {
  121. // 去掉 "data:" 前缀
  122. dataStr += line
  123. }
  124. }
  125. // 去除 "data: " 前缀
  126. if strings.HasPrefix(dataStr, "data: ") {
  127. dataStr = strings.TrimPrefix(dataStr, "data: ")
  128. parseErr := json.Unmarshal([]byte(dataStr), &resp)
  129. if parseErr != nil {
  130. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  131. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  132. return
  133. }
  134. return
  135. } else {
  136. var baseResp eta_llm_http.RagBaseResponse
  137. parseErr := json.Unmarshal([]byte(dataStr), &baseResp)
  138. if parseErr != nil {
  139. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  140. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  141. return
  142. }
  143. if baseResp.Code == 404 {
  144. params["PrevId"] = kbId
  145. _, putErr := llmService.UploadFileToTemplate([]*os.File{file}, params)
  146. if putErr != nil {
  147. utils.FileLog.Error("内容生成失败,err:", err.Error())
  148. err = fmt.Errorf("内容生成失败,err:%v", httpErr)
  149. return
  150. }
  151. } else {
  152. utils.FileLog.Error("内容生成失败,code:%v", baseResp.Code)
  153. err = fmt.Errorf("内容生成失败,code:%v", baseResp.Code)
  154. return
  155. }
  156. }
  157. gcResp, gcErr := llmService.FileChat(aigc.Promote, kbId, nil)
  158. if gcErr != nil {
  159. utils.FileLog.Error("内容生成失败,err:%v", gcErr.Error())
  160. err = fmt.Errorf("内容生成失败,err:%v", gcErr)
  161. return
  162. }
  163. if !gcResp.Success {
  164. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", gcResp.Ret, gcResp.Msg)
  165. err = fmt.Errorf("内容生成失败,err:%v", gcResp.Msg)
  166. }
  167. var gcStr string
  168. // 按行分割输入
  169. lines = strings.Split(string(gcResp.Data), "\n")
  170. // 遍历每一行,提取以 "data:" 开头的内容
  171. for _, line := range lines {
  172. if !strings.HasPrefix(line, ": ping") && strings.TrimSpace(line) != "" {
  173. // 去掉 "data:" 前缀
  174. gcStr += line
  175. }
  176. }
  177. // 去除 "data: " 前缀
  178. if strings.HasPrefix(dataStr, "data: ") {
  179. dataStr = strings.TrimPrefix(dataStr, "data: ")
  180. parseErr := json.Unmarshal([]byte(dataStr), &resp)
  181. if parseErr != nil {
  182. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  183. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  184. return
  185. }
  186. } else {
  187. var baseResp eta_llm_http.RagBaseResponse
  188. parseErr := json.Unmarshal([]byte(dataStr), &baseResp)
  189. if parseErr != nil {
  190. utils.FileLog.Error("内容生成失败,code:%v,msg:%v", parseErr)
  191. err = fmt.Errorf("内容生成失败,err:%v", parseErr)
  192. return
  193. }
  194. utils.FileLog.Error("内容生成失败,code:%v", baseResp.Code)
  195. err = fmt.Errorf("内容生成失败,code:%v", baseResp.Code)
  196. return
  197. }
  198. }
  199. }
  200. return
  201. }
  202. type LLMKnowledgeSearch struct {
  203. Query string `json:"Query"`
  204. KnowledgeBaseName string `json:"KnowledgeBaseName"`
  205. }
  206. type AIGC struct {
  207. Promote string
  208. ArticleId int
  209. }