gptbots_chat_logic.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package xiaoice
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/suyuan32/simple-admin-common/msg/errormsg"
  8. "github.com/zeromicro/go-zero/core/errorx"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "strconv"
  13. "wechat-api/internal/svc"
  14. "wechat-api/internal/types"
  15. "github.com/zeromicro/go-zero/core/logx"
  16. )
  17. type GptbotsChatLogic struct {
  18. logx.Logger
  19. ctx context.Context
  20. svcCtx *svc.ServiceContext
  21. }
  22. func NewGptbotsChatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GptbotsChatLogic {
  23. return &GptbotsChatLogic{
  24. Logger: logx.WithContext(ctx),
  25. ctx: ctx,
  26. svcCtx: svcCtx}
  27. }
  28. func (l *GptbotsChatLogic) GptbotsChat(req *types.ChatReq) (resp *types.BaseDataInfo, err error) {
  29. apikeyMap := map[string]string{
  30. "VHPF0W063": "app-hQL7oVq57McK5VBHlsMfhtUD",
  31. "VHPTL3UAP": "app-2T9KkC9CTwxjzRKQSSM1REmJ",
  32. }
  33. apikey := apikeyMap[*req.AvatarId]
  34. if apikey == "" {
  35. return nil, fmt.Errorf("未知虚拟人id")
  36. }
  37. conversationId, err := l.GetConversation(apikey, strconv.FormatUint(*req.UserId, 10))
  38. if conversationId == nil || err != nil {
  39. return nil, err
  40. }
  41. baseURL, err := url.Parse("https://api.gptbots.ai/v1/conversation/message")
  42. if err != nil {
  43. return nil, errorx.NewDefaultError(fmt.Sprintf("生成内容失败: %+v", err))
  44. }
  45. // 构建请求体
  46. requestBody := map[string]string{
  47. "text": *req.Text,
  48. "conversation_id": *conversationId,
  49. "response_mode": "blocking",
  50. }
  51. jsonBody, err := json.Marshal(requestBody)
  52. if err != nil {
  53. return nil, errorx.NewDefaultError(fmt.Sprintf("生成内容失败: %+v", err))
  54. }
  55. // 创建HTTP请求
  56. httpReq, err := http.NewRequest("POST", baseURL.String(), bytes.NewBuffer(jsonBody))
  57. if err != nil {
  58. return nil, errorx.NewDefaultError(fmt.Sprintf("生成内容失败: %+v", err))
  59. }
  60. // 添加必要的Header信息
  61. httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apikey))
  62. httpReq.Header.Set("Content-Type", "application/json")
  63. // 创建HTTP客户端并执行请求
  64. client := &http.Client{}
  65. response, err := client.Do(httpReq)
  66. if err != nil {
  67. return nil, errorx.NewDefaultError(fmt.Sprintf("生成内容失败: %+v", err))
  68. }
  69. defer func(Body io.ReadCloser) {
  70. err := Body.Close()
  71. if err != nil {
  72. l.Error("生成内容失败: %v", err)
  73. }
  74. }(response.Body)
  75. // 读取和输出响应
  76. body, err := io.ReadAll(response.Body)
  77. if err != nil {
  78. return nil, errorx.NewDefaultError(fmt.Sprintf("生成内容失败: %+v", err))
  79. }
  80. // 检查响应状态
  81. if response.StatusCode != http.StatusOK {
  82. //log.Fatalf("请求失败,状态码:%d,响应: %s", response.StatusCode, string(body))
  83. return nil, errorx.NewDefaultError(fmt.Sprintf("生成内容失败:%d,响应: %s", response.StatusCode, string(body)))
  84. }
  85. // 解析 JSON 响应
  86. var responseMap types.GptbotsMessageResp
  87. if err := json.Unmarshal(body, &responseMap); err != nil {
  88. return nil, errorx.NewDefaultError(fmt.Sprintf("生成内容失败: %+v", err))
  89. }
  90. data := ""
  91. if responseMap.FlowOutput != nil && len(responseMap.FlowOutput) > 0 {
  92. data = TrimHtml(Markdown2Html(responseMap.FlowOutput[0].Content))
  93. }
  94. return &types.BaseDataInfo{Msg: errormsg.Success, Data: data}, nil
  95. }
  96. func (l *GptbotsChatLogic) GetConversation(apikey string, userId string) (conversationId *string, err error) {
  97. val, _ := l.svcCtx.Rds.HGet(l.ctx, "xiaoice_conversation", userId).Result()
  98. if val == "" {
  99. baseURL, err := url.Parse("https://api.gptbots.ai/v1/conversation")
  100. if err != nil {
  101. return nil, err
  102. }
  103. // 构建请求体
  104. requestBody := map[string]string{
  105. "user_id": userId,
  106. }
  107. jsonBody, err := json.Marshal(requestBody)
  108. if err != nil {
  109. return nil, err
  110. }
  111. // 创建HTTP请求
  112. req, err := http.NewRequest("POST", baseURL.String(), bytes.NewBuffer(jsonBody))
  113. if err != nil {
  114. return nil, err
  115. }
  116. // 添加必要的Header信息
  117. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apikey))
  118. req.Header.Set("Content-Type", "application/json")
  119. // 创建HTTP客户端并执行请求
  120. client := &http.Client{}
  121. response, err := client.Do(req)
  122. if err != nil {
  123. return nil, err
  124. }
  125. defer func(Body io.ReadCloser) {
  126. err := Body.Close()
  127. if err != nil {
  128. l.Error("创建会话失败败: %v", err)
  129. }
  130. }(response.Body)
  131. // 读取和输出响应
  132. body, err := io.ReadAll(response.Body)
  133. if err != nil {
  134. return nil, err
  135. }
  136. // 检查响应状态
  137. if response.StatusCode != http.StatusOK {
  138. //log.Fatalf("请求失败,状态码:%d,响应: %s", response.StatusCode, string(body))
  139. return nil, errorx.NewDefaultError(fmt.Sprintf("创建会话失败:%d,响应: %s", response.StatusCode, string(body)))
  140. }
  141. // 解析 JSON 响应
  142. var responseMap types.ConversationResp
  143. if err := json.Unmarshal(body, &responseMap); err != nil {
  144. return nil, err
  145. }
  146. l.svcCtx.Rds.HSet(l.ctx, "xiaoice_conversation", userId, *responseMap.ConversationId)
  147. return responseMap.ConversationId, nil
  148. }
  149. return &val, nil
  150. }