Administrator
2 days ago 726de53a23bd9b6b24ccc3ae6c3b1a6b24b67379
src/main/java/cc/mrbird/febs/ai/service/impl/AiServiceImpl.java
@@ -13,7 +13,10 @@
import cc.mrbird.febs.ai.service.AiProductRoleService;
import cc.mrbird.febs.ai.service.AiService;
import cc.mrbird.febs.ai.service.AiTalkItemService;
import cc.mrbird.febs.ai.strategy.enumerates.LlmStrategyContextEnum;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.mall.entity.DataDictionaryCustom;
import cc.mrbird.febs.mall.mapper.DataDictionaryCustomMapper;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
@@ -74,6 +77,7 @@
    private final AiProductRoleService aiProductRoleService;
    private final ObjectMapper objectMapper;
    private final AiTalkItemService aiTalkItemService;
    private final DataDictionaryCustomMapper dataDictionaryCustomMapper;
    @Value("${ai.service.ak}")
    private String ak;
@@ -109,6 +113,32 @@
        if (service != null) {
            service.shutdownExecutor();
        }
    }
    @Override
    public Integer getSystemSetAiType() {
        Integer type = 2;
        DataDictionaryCustom dataDictionaryCustom = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                LlmStrategyContextEnum.LLM_STRATEGY.getCode(),
                LlmStrategyContextEnum.LLM_STRATEGY.getCode()
        );
        if (dataDictionaryCustom != null) {
            type = Integer.parseInt(dataDictionaryCustom.getValue());
        }
        return type;
    }
    @Override
    public String getSystemSetLTAiPrompt() {
        String prompt = "请将问题转换为中文,并给出一个最详细的答案。";
        DataDictionaryCustom dataDictionaryCustom = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                LlmStrategyContextEnum.LLM_LING_TONG_PROMPT.getCode(),
                LlmStrategyContextEnum.LLM_LING_TONG_PROMPT.getCode()
        );
        if (dataDictionaryCustom != null) {
            prompt = dataDictionaryCustom.getValue();
        }
        return prompt;
    }
    @Override
@@ -418,7 +448,7 @@
                })
                .onErrorResume(throwable -> {
                    log.error("流式调用AI服务失败,问题输入: {}", question, throwable);
                    FebsResponse errorResponse = new FebsResponse().message("AI服务调用失败");
                    FebsResponse errorResponse = new FebsResponse().fail().message("AI服务调用失败");
                    return Flux.just(errorResponse);
                });
    }
@@ -428,31 +458,27 @@
        String question = dto.getQuestion();
        log.info("----- standard request -----");
        // 参数校验
        if (StrUtil.isBlank(question)) {
            return Flux.just(new FebsResponse().fail().message("问题不能为空"));
        }
        List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder()
                .role(ChatMessageRole.SYSTEM)
                .content("你是豆包,是由字节跳动开发的 AI 人工智能助手")
                .content("你是豆包,是由字节跳动开发的 AI 人工智能助手,请使用中文回复")
                .build();
        messages.add(systemMessage);
        //获取消息记录
        if (StrUtil.isNotEmpty(dto.getTalkId())){
        // 获取历史消息记录
        if (StrUtil.isNotEmpty(dto.getTalkId())) {
            List<AiTalkItem> aiTalkItems = aiTalkItemService.getListByTalkId(dto.getTalkId());
            if(CollUtil.isNotEmpty(aiTalkItems)){
                for (AiTalkItem aiTalkItem : aiTalkItems){
                    if (aiTalkItem.getType() == 1){
                        ChatMessage memberMessage = ChatMessage.builder()
                                .role(ChatMessageRole.USER)
                                .content(aiTalkItem.getContext())
                                .build();
                        messages.add(memberMessage);
                    }
                    if (aiTalkItem.getType() == 2){
                        ChatMessage assistantMessage = ChatMessage.builder()
                                .role(ChatMessageRole.ASSISTANT)
                                .content(aiTalkItem.getContext())
                                .build();
                        messages.add(assistantMessage);
            if (CollUtil.isNotEmpty(aiTalkItems)) {
                for (AiTalkItem aiTalkItem : aiTalkItems) {
                    ChatMessage chatMessage = buildChatMessageFromItem(aiTalkItem);
                    if (chatMessage != null) {
                        messages.add(chatMessage);
                    }
                }
            }
@@ -486,27 +512,55 @@
                        return new FebsResponse().success().data("END");
                    }
                    ApiMemberTalkStreamVo apiMemberTalkStreamVo = new ApiMemberTalkStreamVo();
                    // 判断是否触发深度思考,触发则打印模型输出的思维链内容
                    ChatMessage message = choice.getMessage();
                    if (message.getReasoningContent()!= null &&!message.getReasoningContent().isEmpty()) {
                        apiMemberTalkStreamVo.setReasoningContent(message.getReasoningContent());
                        System.out.print(message.getReasoningContent());
                    ApiMemberTalkStreamVo apiMemberTalkStreamVo = new ApiMemberTalkStreamVo();
                    // 处理 reasoning content
                    String reasoningContent = message.getReasoningContent();
                    if (StrUtil.isNotEmpty(reasoningContent)) {
                        apiMemberTalkStreamVo.setReasoningContent(reasoningContent);
                        log.debug("Reasoning Content: {}", reasoningContent);
                    }
                    String content = message.getContent() == null ? "" : message.getContent().toString();
                    // 安全处理 content
                    String content = "";
                    if (message.getContent() != null) {
                        content = message.getContent().toString();
                    }
                    apiMemberTalkStreamVo.setContent(content);
                    System.out.print(content);
                    log.debug("Content: {}", content);
                    return new FebsResponse().success().data(apiMemberTalkStreamVo);
                })
                .onErrorResume(throwable -> {
                    log.error("流式调用AI服务失败,问题输入: {}", question, throwable);
                    FebsResponse errorResponse = new FebsResponse().message("AI服务调用失败");
                    FebsResponse errorResponse = new FebsResponse().fail().message("AI服务调用失败");
                    return Flux.just(errorResponse);
                });
    }
    // 提取为私有方法,提高可读性和复用性
    private ChatMessage buildChatMessageFromItem(AiTalkItem item) {
        if (item == null) return null;
        switch (item.getType()) {
            case 1:
                return ChatMessage.builder()
                        .role(ChatMessageRole.USER)
                        .content(item.getContext())
                        .build();
            case 2:
                return ChatMessage.builder()
                        .role(ChatMessageRole.ASSISTANT)
                        .content(item.getContext())
                        .build();
            default:
                return null;
        }
    }
    private Report tryRepairTruncatedJson(String truncatedJson) {
        String[] repairAttempts = {