AiResponseAccumulator.java 3.05 KB
package com.xly.entity;

import com.xly.entity.AiResponseDTO;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * AI响应累积器
 */
@Slf4j
public class AiResponseAccumulator {

    private final String requestId;
    private final StringBuilder aiTextBuilder = new StringBuilder();
    private final StringBuilder systemTextBuilder = new StringBuilder();
    private String sSceneName;
    private String sMethodName;
    private String sReturnType;
    private int totalChunks = 0;
    private int processedChunks = 0;
    private final long startTime;

    public AiResponseAccumulator(String requestId) {
        this.requestId = requestId;
        this.startTime = System.currentTimeMillis();
    }

    /**
     * 累积单个AI响应
     */
    public void accumulate(AiResponseDTO response) {
        processedChunks++;

        // 更新总块数
        if (response.getTotalChunks() != null && response.getTotalChunks() > 0) {
            this.totalChunks = response.getTotalChunks();
        }

        // 累积AI文本片段
        if (StrUtil.isNotBlank(response.getTextFragment())) {
            aiTextBuilder.append(response.getTextFragment());
        }

        // 累积系统文本片段
        if (StrUtil.isNotBlank(response.getSystemTextFragment())) {
            systemTextBuilder.append(response.getSystemTextFragment());
        }

        // 更新元数据(取最后一次非空值)
        if (StrUtil.isNotBlank(response.getSSceneName())) {
            this.sSceneName = response.getSSceneName();
        }
        if (StrUtil.isNotBlank(response.getSMethodName())) {
            this.sMethodName = response.getSMethodName();
        }
        if (StrUtil.isNotBlank(response.getSReturnType())) {
            this.sReturnType = response.getSReturnType();
        }

        log.debug("累积进度: requestId={}, 已处理={}/{}块, AI文本长度={}",
                requestId, processedChunks, totalChunks, aiTextBuilder.length());
    }

    /**
     * 获取完整的响应
     */
    public AiResponseDTO getCompleteResponse() {
        AiResponseDTO response = new AiResponseDTO();
        response.setRequestId(requestId);
        response.setAiText(aiTextBuilder.toString());
        response.setSystemText(systemTextBuilder.toString());
        response.setFullAiText(aiTextBuilder.toString());
        response.setFullSystemText(systemTextBuilder.toString());
        response.setSSceneName(sSceneName);
        response.setSMethodName(sMethodName);
        response.setSReturnType(sReturnType != null ? sReturnType : "MARKDOWN");
        response.setTotalChunks(totalChunks);
        response.setChunkIndex(processedChunks - 1);
        response.setIsLastChunk(true);
        response.setElapsedTime(System.currentTimeMillis() - startTime);

        log.info("ERP累积完成: requestId={}, 总块数={}, AI文本长度={}, 系统文本长度={}, 耗时={}ms",
                requestId, totalChunks,
                aiTextBuilder.length(), systemTextBuilder.length(),
                response.getElapsedTime());

        return response;
    }
}