llm_service.go 7.8 KB

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