gptbots_message_logic.go 4.7 KB

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