llm_service.go 6.9 KB

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