llm_service.go 8.6 KB

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