AiResponseAccumulator.java
3.05 KB
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
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;
}
}