eta_llm_client.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package eta_llm
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "eta/eta_api/models"
  8. "eta/eta_api/utils"
  9. "eta/eta_api/utils/llm"
  10. "eta/eta_api/utils/llm/eta_llm/eta_llm_http"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "strings"
  15. "sync"
  16. )
  17. var (
  18. dsOnce sync.Once
  19. etaLlmClient *ETALLMClient
  20. )
  21. const (
  22. KNOWLEDEG_CHAT_MODE = "local_kb"
  23. DEFALUT_PROMPT_NAME = "default"
  24. CONTENT_TYPE_JSON = "application/json"
  25. KNOWLEDGE_BASE_CHAT_API = "/chat/kb_chat"
  26. DOCUMENT_CHAT_API = "/chat/file_chat"
  27. KNOWLEDGE_BASE_SEARCH_DOCS_API = "/knowledge_base/search_docs"
  28. )
  29. type ETALLMClient struct {
  30. *llm.LLMClient
  31. LlmModel string
  32. }
  33. type LLMConfig struct {
  34. LlmAddress string `json:"llm_server"`
  35. LlmModel string `json:"llm_model"`
  36. }
  37. func GetInstance() llm.LLMService {
  38. dsOnce.Do(func() {
  39. confStr := models.BusinessConfMap[models.LLMInitConfig]
  40. if confStr == "" {
  41. utils.FileLog.Error("LLM配置为空")
  42. return
  43. }
  44. var config LLMConfig
  45. err := json.Unmarshal([]byte(confStr), &config)
  46. if err != nil {
  47. utils.FileLog.Error("LLM配置错误")
  48. }
  49. if etaLlmClient == nil {
  50. etaLlmClient = &ETALLMClient{
  51. LLMClient: llm.NewLLMClient(config.LlmAddress, 120),
  52. LlmModel: config.LlmModel,
  53. }
  54. }
  55. })
  56. return etaLlmClient
  57. }
  58. func (ds *ETALLMClient) DocumentChat(query string, KnowledgeId string, history []json.RawMessage, stream bool) (llmRes *http.Response, err error) {
  59. ChatHistory := make([]eta_llm_http.HistoryContent, 0)
  60. for _, historyItemStr := range history {
  61. var historyItem eta_llm_http.HistoryContent
  62. parseErr := json.Unmarshal(historyItemStr, &historyItem)
  63. if parseErr != nil {
  64. continue
  65. }
  66. //str := strings.Split(historyItemStr, "-")
  67. //historyItem := eta_llm_http.HistoryContent{
  68. // Role: str[0],
  69. // Content: str[1],
  70. //}
  71. ChatHistory = append(ChatHistory, historyItem)
  72. }
  73. kbReq := eta_llm_http.DocumentChatRequest{
  74. Query: query,
  75. KnowledgeId: KnowledgeId,
  76. History: ChatHistory,
  77. TopK: 3,
  78. //ScoreThreshold: 0.5,
  79. ScoreThreshold: 2,
  80. Stream: stream,
  81. ModelName: ds.LlmModel,
  82. //Temperature: 0.7,
  83. Temperature: 0.01,
  84. MaxTokens: 0,
  85. //PromptName: DEFALUT_PROMPT_NAME,
  86. }
  87. //fmt.Printf("%v", kbReq.History)
  88. body, err := json.Marshal(kbReq)
  89. fmt.Println(string(body))
  90. if err != nil {
  91. return
  92. }
  93. return ds.DoStreamPost(DOCUMENT_CHAT_API, body)
  94. }
  95. func (ds *ETALLMClient) KnowledgeBaseChat(query string, KnowledgeBaseName string, history []json.RawMessage) (llmRes *http.Response, err error) {
  96. ChatHistory := make([]eta_llm_http.HistoryContent, 0)
  97. for _, historyItemStr := range history {
  98. var historyItem eta_llm_http.HistoryContentWeb
  99. parseErr := json.Unmarshal(historyItemStr, &historyItem)
  100. if parseErr != nil {
  101. continue
  102. }
  103. ChatHistory = append(ChatHistory, eta_llm_http.HistoryContent{
  104. Content: historyItem.Content,
  105. Role: historyItem.Role,
  106. })
  107. }
  108. kbReq := eta_llm_http.KbChatRequest{
  109. Query: query,
  110. Mode: KNOWLEDEG_CHAT_MODE,
  111. KbName: KnowledgeBaseName,
  112. History: ChatHistory,
  113. TopK: 3,
  114. ScoreThreshold: 0.5,
  115. Stream: true,
  116. Model: ds.LlmModel,
  117. Temperature: 0.7,
  118. MaxTokens: 0,
  119. PromptName: DEFALUT_PROMPT_NAME,
  120. ReturnDirect: false,
  121. }
  122. fmt.Printf("%v", kbReq.History)
  123. body, err := json.Marshal(kbReq)
  124. if err != nil {
  125. return
  126. }
  127. return ds.DoStreamPost(KNOWLEDGE_BASE_CHAT_API, body)
  128. }
  129. func (ds *ETALLMClient) SearchKbDocs(query string, KnowledgeBaseName string) (content interface{}, err error) {
  130. kbReq := eta_llm_http.KbSearchDocsRequest{
  131. Query: query,
  132. KnowledgeBaseName: KnowledgeBaseName,
  133. TopK: 10,
  134. ScoreThreshold: 0.5,
  135. Metadata: struct{}{},
  136. }
  137. body, err := json.Marshal(kbReq)
  138. if err != nil {
  139. return
  140. }
  141. resp, err := ds.DoPost(KNOWLEDGE_BASE_SEARCH_DOCS_API, body)
  142. if !resp.Success {
  143. err = errors.New(resp.Msg)
  144. return
  145. }
  146. if resp.Data != nil {
  147. var kbSearchRes []eta_llm_http.SearchDocsResponse
  148. err = json.Unmarshal(resp.Data, &kbSearchRes)
  149. if err != nil {
  150. err = errors.New("搜索知识库失败")
  151. return
  152. }
  153. content = kbSearchRes
  154. return
  155. }
  156. err = errors.New("搜索知识库失败")
  157. return
  158. }
  159. func init() {
  160. err := llm.Register(llm.ETA_LLM_CLIENT, GetInstance())
  161. if err != nil {
  162. utils.FileLog.Error("注册eta_llm_server服务失败:", err)
  163. }
  164. }
  165. func (ds *ETALLMClient) DoPost(apiUrl string, body []byte) (baseResp eta_llm_http.BaseResponse, err error) {
  166. requestReader := bytes.NewReader(body)
  167. response, err := ds.HttpClient.Post(ds.BaseURL+apiUrl, CONTENT_TYPE_JSON, requestReader)
  168. if err != nil {
  169. return
  170. }
  171. return parseResponse(response)
  172. }
  173. func (ds *ETALLMClient) DoStreamPost(apiUrl string, body []byte) (baseResp *http.Response, err error) {
  174. requestReader := bytes.NewReader(body)
  175. return ds.HttpClient.Post(ds.BaseURL+apiUrl, CONTENT_TYPE_JSON, requestReader)
  176. }
  177. func parseResponse(response *http.Response) (baseResp eta_llm_http.BaseResponse, err error) {
  178. defer func() {
  179. _ = response.Body.Close()
  180. }()
  181. baseResp.Ret = response.StatusCode
  182. if response.StatusCode != http.StatusOK {
  183. baseResp.Msg = fmt.Sprintf("请求失败,状态码:%d, 状态信息:%s", response.StatusCode, http.StatusText(response.StatusCode))
  184. return
  185. }
  186. bodyBytes, err := io.ReadAll(response.Body)
  187. if err != nil {
  188. err = fmt.Errorf("读取响应体失败: %w", err)
  189. return
  190. }
  191. baseResp.Success = true
  192. baseResp.Data = bodyBytes
  193. return
  194. }
  195. func ParseStreamResponse(response *http.Response) (contentChan chan string, errChan chan error, closeChan chan struct{}) {
  196. contentChan = make(chan string, 10)
  197. errChan = make(chan error, 10)
  198. closeChan = make(chan struct{})
  199. go func() {
  200. defer close(contentChan)
  201. defer close(errChan)
  202. defer close(closeChan)
  203. scanner := bufio.NewScanner(response.Body)
  204. scanner.Split(bufio.ScanLines)
  205. for scanner.Scan() {
  206. line := scanner.Text()
  207. if line == "" {
  208. continue
  209. }
  210. // 忽略 "ping" 行
  211. if strings.HasPrefix(line, ": ping") {
  212. continue
  213. }
  214. // 去除 "data: " 前缀
  215. if strings.HasPrefix(line, "data: ") {
  216. line = strings.TrimPrefix(line, "data: ")
  217. }
  218. var chunk eta_llm_http.ChunkResponse
  219. if err := json.Unmarshal([]byte(line), &chunk); err != nil {
  220. fmt.Println("解析错误的line:" + line)
  221. errChan <- fmt.Errorf("解析 JSON 块失败: %w", err)
  222. return
  223. }
  224. // 处理每个 chunk
  225. if chunk.Choices != nil && len(chunk.Choices) > 0 {
  226. for _, choice := range chunk.Choices {
  227. if choice.Delta.Content != "" {
  228. contentChan <- choice.Delta.Content
  229. }
  230. }
  231. }
  232. }
  233. if err := scanner.Err(); err != nil {
  234. errChan <- fmt.Errorf("读取响应体失败: %w", err)
  235. return
  236. }
  237. }()
  238. return
  239. }