chenhj
8 天以前 28cf22aaff7f092256db2ad6df699e17426f62ea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package com.ruoyi.ai.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.ai.dto.AiChatMessageDto;
import com.ruoyi.ai.dto.AiChatSessionDto;
import com.ruoyi.ai.mapper.AiChatSessionMapper;
import com.ruoyi.ai.pojo.AiChatSession;
import com.ruoyi.ai.service.AiChatSessionService;
import com.ruoyi.ai.store.MongoChatMemoryStore;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.LoginUser;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.data.message.UserMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
 
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
 
@Service
@RequiredArgsConstructor
public class AiChatSessionServiceImpl extends ServiceImpl<AiChatSessionMapper, AiChatSession> implements AiChatSessionService {
 
    private static final int TITLE_MAX_LENGTH = 40;
    private static final int LAST_MESSAGE_MAX_LENGTH = 300;
 
    private final MongoChatMemoryStore mongoChatMemoryStore;
 
    @Override
    public void touchSession(String memoryId, LoginUser loginUser, String userMessage) {
        if (!StringUtils.hasText(memoryId) || loginUser == null || loginUser.getUserId() == null) {
            return;
        }
        Date now = new Date();
        AiChatSession session = getSession(memoryId, loginUser.getUserId(), loginUser.getTenantId());
        if (session == null) {
            AiChatSession add = new AiChatSession();
            add.setMemoryId(memoryId);
            add.setUserId(loginUser.getUserId());
            add.setTenantId(loginUser.getTenantId());
            add.setTitle(buildTitle(userMessage));
            add.setLastMessage(trimText(userMessage, LAST_MESSAGE_MAX_LENGTH));
            add.setMessageCount(0);
            add.setLastChatTime(now);
            add.setCreateTime(now);
            add.setUpdateTime(now);
            save(add);
            return;
        }
 
        AiChatSession update = new AiChatSession();
        update.setId(session.getId());
        if (!StringUtils.hasText(session.getTitle())) {
            update.setTitle(buildTitle(userMessage));
        }
        update.setLastMessage(trimText(userMessage, LAST_MESSAGE_MAX_LENGTH));
        update.setLastChatTime(now);
        update.setUpdateTime(now);
        updateById(update);
    }
 
    @Override
    public void refreshSessionStats(String memoryId, LoginUser loginUser) {
        if (!StringUtils.hasText(memoryId) || loginUser == null || loginUser.getUserId() == null) {
            return;
        }
        AiChatSession session = getSession(memoryId, loginUser.getUserId(), loginUser.getTenantId());
        if (session == null) {
            return;
        }
        List<ChatMessage> messages = mongoChatMemoryStore.getMessages(memoryId);
        AiChatSession update = new AiChatSession();
        update.setId(session.getId());
        update.setMessageCount(messages.size());
        update.setLastMessage(trimText(lastMessageText(messages), LAST_MESSAGE_MAX_LENGTH));
        update.setLastChatTime(new Date());
        update.setUpdateTime(new Date());
        updateById(update);
    }
 
    @Override
    public List<AiChatSessionDto> listCurrentUserSessions(LoginUser loginUser) {
        if (loginUser == null || loginUser.getUserId() == null) {
            return new LinkedList<>();
        }
        LambdaQueryWrapper<AiChatSession> queryWrapper = new LambdaQueryWrapper<AiChatSession>()
                .eq(AiChatSession::getUserId, loginUser.getUserId())
                .orderByDesc(AiChatSession::getLastChatTime);
        applyTenantCondition(queryWrapper, loginUser.getTenantId());
        return list(queryWrapper).stream().map(item -> {
            AiChatSessionDto dto = new AiChatSessionDto();
            dto.setMemoryId(item.getMemoryId());
            dto.setTitle(item.getTitle());
            dto.setLastMessage(item.getLastMessage());
            dto.setMessageCount(item.getMessageCount());
            dto.setLastChatTime(item.getLastChatTime());
            return dto;
        }).collect(Collectors.toList());
    }
 
    @Override
    public List<AiChatMessageDto> listCurrentUserMessages(String memoryId, LoginUser loginUser) {
        if (!StringUtils.hasText(memoryId) || loginUser == null || loginUser.getUserId() == null) {
            return new LinkedList<>();
        }
        AiChatSession session = getSession(memoryId, loginUser.getUserId(), loginUser.getTenantId());
        if (session == null) {
            return new LinkedList<>();
        }
        List<ChatMessage> messages = mongoChatMemoryStore.getMessages(memoryId);
        return messages.stream().map(this::convertMessage).collect(Collectors.toList());
    }
 
    @Override
    public boolean deleteCurrentUserSession(String memoryId, LoginUser loginUser) {
        if (!StringUtils.hasText(memoryId) || loginUser == null || loginUser.getUserId() == null) {
            return false;
        }
        LambdaQueryWrapper<AiChatSession> queryWrapper = new LambdaQueryWrapper<AiChatSession>()
                .eq(AiChatSession::getMemoryId, memoryId)
                .eq(AiChatSession::getUserId, loginUser.getUserId());
        applyTenantCondition(queryWrapper, loginUser.getTenantId());
        boolean removed = remove(queryWrapper);
        mongoChatMemoryStore.deleteMessages(memoryId);
        return removed;
    }
 
    private AiChatSession getSession(String memoryId, Long userId, Long tenantId) {
        LambdaQueryWrapper<AiChatSession> queryWrapper = new LambdaQueryWrapper<AiChatSession>()
                .eq(AiChatSession::getMemoryId, memoryId)
                .eq(AiChatSession::getUserId, userId);
        applyTenantCondition(queryWrapper, tenantId);
        return getOne(queryWrapper, false);
    }
 
    private void applyTenantCondition(LambdaQueryWrapper<AiChatSession> queryWrapper, Long tenantId) {
        if (tenantId == null) {
            queryWrapper.isNull(AiChatSession::getTenantId);
            return;
        }
        queryWrapper.eq(AiChatSession::getTenantId, tenantId);
    }
 
    private String buildTitle(String userMessage) {
        if (!StringUtils.hasText(userMessage)) {
            return "新会话";
        }
        return trimText(userMessage, TITLE_MAX_LENGTH);
    }
 
    private String trimText(String text, int maxLength) {
        if (!StringUtils.hasText(text)) {
            return "";
        }
        String source = text.trim();
        if (source.length() <= maxLength) {
            return source;
        }
        return source.substring(0, maxLength) + "...";
    }
 
    private String lastMessageText(List<ChatMessage> messages) {
        if (messages == null || messages.isEmpty()) {
            return "";
        }
        ChatMessage lastMessage = messages.get(messages.size() - 1);
        return convertMessage(lastMessage).getContent();
    }
 
    private AiChatMessageDto convertMessage(ChatMessage message) {
        if (message instanceof UserMessage userMessage) {
            return new AiChatMessageDto("user", userMessage.singleText());
        }
        if (message instanceof AiMessage aiMessage) {
            return new AiChatMessageDto("assistant", aiMessage.text());
        }
        if (message instanceof SystemMessage systemMessage) {
            return new AiChatMessageDto("system", systemMessage.text());
        }
        if (message instanceof ToolExecutionResultMessage toolExecutionResultMessage) {
            return new AiChatMessageDto("tool", toolExecutionResultMessage.text());
        }
        return new AiChatMessageDto("unknown", String.valueOf(message));
    }
}