fix: fixed bug for concurrency risk for getting token for chat histroy with issue #92

This commit is contained in:
RockYang 2024-01-04 09:03:19 +08:00
parent d8e4308b1b
commit 039b70eed2
2 changed files with 6 additions and 5 deletions

View File

@ -338,8 +338,9 @@ func (h *ChatHandler) sendMessage(ctx context.Context, session *types.ChatSessio
// Tokens 统计 token 数量 // Tokens 统计 token 数量
func (h *ChatHandler) Tokens(c *gin.Context) { func (h *ChatHandler) Tokens(c *gin.Context) {
var data struct { var data struct {
Text string `json:"text"` Text string `json:"text"`
Model string `json:"model"` Model string `json:"model"`
ChatId string `json:"chat_id"`
} }
if err := c.ShouldBindJSON(&data); err != nil { if err := c.ShouldBindJSON(&data); err != nil {
resp.ERROR(c, types.InvalidArgs) resp.ERROR(c, types.InvalidArgs)
@ -347,10 +348,10 @@ func (h *ChatHandler) Tokens(c *gin.Context) {
} }
// 如果没有传入 text 字段,则说明是获取当前 reply 总的 token 消耗(带上下文) // 如果没有传入 text 字段,则说明是获取当前 reply 总的 token 消耗(带上下文)
if data.Text == "" { if data.Text == "" && data.ChatId != "" {
var item model.HistoryMessage var item model.HistoryMessage
userId, _ := c.Get(types.LoginUserID) userId, _ := c.Get(types.LoginUserID)
res := h.db.Where("user_id = ?", userId).Last(&item) res := h.db.Where("user_id = ?", userId).Where("chat_id = ?", data.ChatId).Last(&item)
if res.Error != nil { if res.Error != nil {
resp.ERROR(c, res.Error.Error()) resp.ERROR(c, res.Error.Error())
return return

View File

@ -634,7 +634,7 @@ const connect = function (chat_id, role_id) {
// token // token
const reply = chatData.value[chatData.value.length - 1] const reply = chatData.value[chatData.value.length - 1]
httpPost("/api/chat/tokens", {text: "", model: getModelValue(modelID.value)}).then(res => { httpPost("/api/chat/tokens", {text: "", model: getModelValue(modelID.value), chat_id: chat_id}).then(res => {
reply['created_at'] = new Date().getTime(); reply['created_at'] = new Date().getTime();
reply['tokens'] = res.data; reply['tokens'] = res.data;
// //