All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ape9527.core.service.AIService Maven / Gradle / Ivy

The newest version!
package com.ape9527.core.service;

import com.ape9527.auth.service.LoginUserService;
import com.ape9527.core.entity.GPTHistory;
import com.ape9527.core.entity.GPTHistoryDetail;
import com.ape9527.core.mapper.BaseDataMapper;
import com.ape9527.core.mapper.GPTHistoryMapper;
import com.ape9527.utils.openai.model.ChatMessage;
import org.springframework.stereotype.Service;

/**
 * @author YuanShuai[[email protected]]
 */
@Service
public class AIService {

    private final LoginUserService loginUserService;

    private final GPTHistoryMapper historyMapper;

    private final BaseDataMapper baseDataMapper;

    public AIService(LoginUserService loginUserService, GPTHistoryMapper historyMapper, BaseDataMapper baseDataMapper) {
        this.loginUserService = loginUserService;
        this.historyMapper = historyMapper;
        this.baseDataMapper = baseDataMapper;
    }

    /**
     * 针对当前用户创建新聊天
     * @return
     */
    public GPTHistory createChat() {
        String userId = loginUserService.getUserId();

        String uuid = baseDataMapper.selectUuid();

        GPTHistory history = new GPTHistory();
        history.setUuid(uuid);
        history.setUserName(userId);
        history.setHistoryName("新聊天");
        history.setTotalTokens(0);
        int i = historyMapper.insertHistory(history);
        if(i == 0){
            history.setUuid(null);
        }
        return history;
    }

    /**
     * 创建一条历史记录明细(即记录 user or ai的content)
     * @param historyId
     * @param chatMessage
     * @param tokens
     * @return
     */
    public GPTHistoryDetail createChatMessage(String historyId, ChatMessage chatMessage, Integer tokens) {
        String uuid = baseDataMapper.selectUuid();
        GPTHistoryDetail historyDetail = new GPTHistoryDetail();
        historyDetail.setUuid(uuid);
        historyDetail.setRole(chatMessage.getRole());
        historyDetail.setContent(chatMessage.getContent());
        historyDetail.setTokens(tokens);
        historyDetail.setHistoryName(historyId);
        int i = historyMapper.insertHistoryDetail(historyDetail);
        if(i == 0){
            return null;
        }
        return historyDetail;
    }

    /**
     * 更新历史记录明细消耗的tokens
     * @param historyDetailId
     * @param tokens
     */
    public void updateHistoryDetailTokens(String historyDetailId, Integer tokens) {
        historyMapper.updateHistoryDetailTokens(historyDetailId, tokens);
    }

    public void updateHistoryTokens(String historyId, Integer totalTokens) {
        historyMapper.updateHistoryTokens(historyId, totalTokens);
    }

    public void updateHistoryName(String historyId, String content) {
        historyMapper.updateHistoryName(historyId, content);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy