Browse Source

fix:save 10

jimmyyem 6 months ago
parent
commit
26233782f3

+ 0 - 4
desc/wechat/chat_records.api

@@ -74,10 +74,6 @@ service Wechat {
 	// Get chat records list | 获取ChatRecords列表
 	@handler getApiChatList
 	post /api/chat/list (ChatRecordsListReq) returns (ChatRecordsListResp)
-
-	// Get chat records list | 获取ChatRecords列表
-	@handler saveApiChat
-	post /api/chat/save (ChatRecordsInfo) returns (BaseMsgResp)
 }
 
 @server(

+ 0 - 44
internal/handler/chatrecords/save_api_chat_handler.go

@@ -1,44 +0,0 @@
-package chatrecords
-
-import (
-	"net/http"
-
-	"github.com/zeromicro/go-zero/rest/httpx"
-
-	"wechat-api/internal/logic/chatrecords"
-	"wechat-api/internal/svc"
-	"wechat-api/internal/types"
-)
-
-// swagger:route post /api/chat/save chatrecords SaveApiChat
-//
-// Get chat records list | 获取ChatRecords列表
-//
-// Get chat records list | 获取ChatRecords列表
-//
-// Parameters:
-//  + name: body
-//    require: true
-//    in: body
-//    type: ChatRecordsInfo
-//
-// Responses:
-//  200: BaseMsgResp
-
-func SaveApiChatHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
-	return func(w http.ResponseWriter, r *http.Request) {
-		var req types.ChatRecordsInfo
-		if err := httpx.Parse(r, &req, true); err != nil {
-			httpx.ErrorCtx(r.Context(), w, err)
-			return
-		}
-
-		l := chatrecords.NewSaveApiChatLogic(r.Context(), svcCtx)
-		resp, err := l.SaveApiChat(&req)
-		if err != nil {
-			httpx.ErrorCtx(r.Context(), w, err)
-		} else {
-			httpx.OkJsonCtx(r.Context(), w, resp)
-		}
-	}
-}

+ 0 - 5
internal/handler/routes.go

@@ -1036,11 +1036,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
 					Path:    "/api/chat/list",
 					Handler: chatrecords.GetApiChatListHandler(serverCtx),
 				},
-				{
-					Method:  http.MethodPost,
-					Path:    "/api/chat/save",
-					Handler: chatrecords.SaveApiChatHandler(serverCtx),
-				},
 			}...,
 		),
 		rest.WithJwt(serverCtx.Config.Auth.AccessSecret),

+ 1 - 1
internal/logic/User/do_api_user_login_logic.go

@@ -87,7 +87,7 @@ func (l *DoApiUserLoginLogic) DoApiUserLogin(req *types.UserLoginReq) (*types.Us
 		}
 	}
 
-	//TODO 这里需要改成实际用户的数据
+	// 这里需要改成实际用户的数据
 	dataArray := make([]jwt.Option, 0)
 	dataArray = append(dataArray, jwt.Option{
 		Key: "userId",

+ 0 - 45
internal/logic/chatrecords/save_api_chat_logic.go

@@ -1,45 +0,0 @@
-package chatrecords
-
-import (
-	"context"
-	"github.com/suyuan32/simple-admin-common/msg/errormsg"
-	"github.com/zeromicro/go-zero/core/errorx"
-
-	"wechat-api/internal/svc"
-	"wechat-api/internal/types"
-
-	"github.com/zeromicro/go-zero/core/logx"
-)
-
-type SaveApiChatLogic struct {
-	logx.Logger
-	ctx    context.Context
-	svcCtx *svc.ServiceContext
-}
-
-func NewSaveApiChatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveApiChatLogic {
-	return &SaveApiChatLogic{
-		Logger: logx.WithContext(ctx),
-		ctx:    ctx,
-		svcCtx: svcCtx}
-}
-
-func (l *SaveApiChatLogic) SaveApiChat(req *types.ChatRecordsInfo) (*types.BaseMsgResp, error) {
-	userId := l.ctx.Value("userId").(uint64)
-	sessionId := *req.SessionId
-
-	// 记录下问题
-	_, err := l.svcCtx.DB.ChatRecords.Create().
-		SetUserID(userId).
-		SetSessionID(sessionId).
-		SetBotType(*req.BotType).
-		SetBotID(*req.BotId).
-		SetContentType(2).
-		SetContent(*req.Content).
-		Save(l.ctx)
-	if err != nil {
-		return nil, errorx.NewInternalError(err.Error())
-	}
-
-	return &types.BaseMsgResp{Msg: errormsg.Success}, nil
-}

+ 55 - 6
internal/logic/chatrecords/submit_api_chat_logic.go

@@ -90,18 +90,18 @@ func (l *SubmitApiChatLogic) SubmitApiChat(req *types.ChatRecordsInfo, w http.Re
 		if err != nil {
 			return //TODO 这里应该报错
 		}
-		fastgptSendChat(l, w, *req.Content, card.APIBase, card.APIKey, sessionId, userId)
+		fastgptSendChat(l, w, *req.Content, card.APIBase, card.APIKey, sessionId, userId, *req.BotId, *req.BotType)
 	} else if *req.BotType == 3 { // 从数字员工里获取回答
 		employee, err := l.svcCtx.DB.Employee.Query().Where(employee.ID(*req.BotId)).Only(l.ctx)
 		if err != nil {
 			return //TODO 这里应该报错
 		}
-		difySendChat(l, w, *req.Content, employee.APIBase, employee.APIKey, sessionId, userId)
+		difySendChat(l, w, *req.Content, employee.APIBase, employee.APIKey, sessionId, userId, *req.BotId, *req.BotType)
 	}
 }
 
 // fastgptSendChat 往 FastGPT 发送内容并获得响应信息
-func fastgptSendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiBase, apiKey string, sessionId, userId uint64) {
+func fastgptSendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiBase, apiKey string, sessionId, userId, botId uint64, botType uint8) {
 	userInfo, _ := l.svcCtx.DB.WxCardUser.Query().Where(wxcarduser.ID(userId)).First(l.ctx)
 
 	var chatReq fastgpt.ChatReq
@@ -150,6 +150,13 @@ func fastgptSendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiB
 	w.Header().Set("Connection", "keep-alive")
 	w.Header().Set("Cache-Control", "no-cache")
 
+	flusher, ok := w.(http.Flusher)
+	if !ok {
+		http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
+		return
+	}
+
+	var answer string
 	for {
 		line, err := reader.ReadString('\n')
 		line = strings.Trim(line, " \n")
@@ -182,10 +189,20 @@ func fastgptSendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiB
 			jsonData.Finish = finish
 			lineData, _ := json.Marshal(jsonData)
 
-			_, _ = fmt.Fprintln(w, "data: "+string(lineData)+"\n")
+			// 拼接回答
+			answer = answer + jsonData.Answer
+
+			_, err = fmt.Fprintln(w, "data: "+string(lineData)+"\n")
 			fmt.Printf("response=%v\n", string(lineData))
+			if err != nil {
+				logAnswer(l, userId, sessionId, botId, botType, answer)
+				fmt.Printf("Error writing to client:%v \n", err)
+				break
+			}
+			flusher.Flush()
 
 			if finish {
+				logAnswer(l, userId, sessionId, botId, botType, answer)
 				break
 			}
 		}
@@ -193,7 +210,7 @@ func fastgptSendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiB
 }
 
 // difySendChat 往 Dify 发送内容并获得响应信息
-func difySendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiBase, apiKey string, sessionId, userId uint64) {
+func difySendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiBase, apiKey string, sessionId, userId, botId uint64, botType uint8) {
 	userInfo, _ := l.svcCtx.DB.WxCardUser.Query().Where(wxcarduser.ID(userId)).First(l.ctx)
 
 	var chatReq dify.ChatReq
@@ -237,6 +254,13 @@ func difySendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiBase
 	w.Header().Set("Connection", "keep-alive")
 	w.Header().Set("Cache-Control", "no-cache")
 
+	flusher, ok := w.(http.Flusher)
+	if !ok {
+		http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
+		return
+	}
+
+	var answer string
 	for {
 		line, err := reader.ReadString('\n')
 		line = strings.Trim(line, " \n")
@@ -275,12 +299,37 @@ func difySendChat(l *SubmitApiChatLogic, w http.ResponseWriter, content, apiBase
 			jsonData.ConversationId = chatData.ConversationId
 			lineData, _ := json.Marshal(jsonData)
 
-			_, _ = fmt.Fprintln(w, "data: "+string(lineData)+"\n")
+			// 拼接回答
+			answer = answer + jsonData.Answer
+
+			_, err = fmt.Fprintln(w, "data: "+string(lineData)+"\n")
 			fmt.Printf("response=%v\n", string(lineData))
+			if err != nil {
+				logAnswer(l, userId, sessionId, botId, botType, answer)
+				fmt.Printf("Error writing to client:%v \n", err)
+				break
+			}
+			flusher.Flush()
 
 			if finish {
+				logAnswer(l, userId, sessionId, botId, botType, answer)
 				break
 			}
 		}
 	}
 }
+
+// logAnswer 保存Ai回答的内容
+func logAnswer(l *SubmitApiChatLogic, userId, sessionId, botId uint64, botType uint8, answer string) {
+	_, err := l.svcCtx.DB.ChatRecords.Create().
+		SetUserID(userId).
+		SetSessionID(sessionId).
+		SetBotType(botType).
+		SetBotID(botId).
+		SetContentType(2).
+		SetContent(answer).
+		Save(l.ctx)
+	if err != nil {
+		fmt.Printf("save answer failed: %v", err)
+	}
+}