feat: 用量统计支持用户维度报表
- 新增 ai_usage_records.user_id 与 (user_id, occurred_at) 索引,NULL 表示未归属 - 归属标记跟着请求走:AiServiceClient 提交任务时带上顶层 callerRef(当前用户 id), lpt-ai 原样透传,上报后落到 user_id。取不到身份就不带,绝不让 AI 调用因此失败 - breakdown 支持 groupBy=user,新增 label(登录名,未归属为「未归属」); summary/series/breakdown 支持 userId 过滤
This commit is contained in:
+69
-24
@@ -6,6 +6,7 @@ import com.guo.learningprogresstracker.common.TenantContext;
|
||||
import com.guo.learningprogresstracker.config.AiUsageProperties;
|
||||
import com.guo.learningprogresstracker.dto.AiUsageBalance;
|
||||
import com.guo.learningprogresstracker.dto.AiUsageBreakdownItem;
|
||||
import com.guo.learningprogresstracker.dto.AiUsageBreakdownRow;
|
||||
import com.guo.learningprogresstracker.dto.AiUsageIngestResult;
|
||||
import com.guo.learningprogresstracker.dto.AiUsageSeriesPoint;
|
||||
import com.guo.learningprogresstracker.dto.AiUsageSummary;
|
||||
@@ -33,6 +34,8 @@ import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -51,6 +54,10 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
private static final String BUCKET_HOUR = "hour";
|
||||
private static final String GROUP_BY_TASK_TYPE = "taskType";
|
||||
private static final String GROUP_BY_MODEL = "model";
|
||||
private static final String GROUP_BY_USER = "user";
|
||||
|
||||
/** 未归属({@code user_id} 为 null)在面板上的展示名;契约 v2 第 4.2 节要求它单独可见 */
|
||||
private static final String UNASSIGNED_LABEL = "未归属";
|
||||
|
||||
private final AiUsageRecordMapper aiUsageRecordMapper;
|
||||
private final UserService userService;
|
||||
@@ -126,6 +133,9 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
entity.setOccurredAt(parseUtc(record.getOccurredAt()));
|
||||
entity.setTaskType(record.getTaskType());
|
||||
entity.setTaskId(record.getTaskId());
|
||||
// 归属标记原样落库:lpt-ai 不解释它的含义,这里也不校验它是否真是个存在的用户——
|
||||
// 查不到用户名时面板回退显示用户 id(见 breakdown),比把整条用量丢掉强
|
||||
entity.setUserId(record.getCallerRef());
|
||||
entity.setModel(record.getModel());
|
||||
entity.setAttempts(record.getAttempts());
|
||||
entity.setIsLlmCall(record.getIsLlmCall());
|
||||
@@ -175,9 +185,9 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
public AiUsageSummary summary(AiUsageQuery query) {
|
||||
ResolvedFilter filter = resolve(query);
|
||||
AiUsageSummaryRow row = aiUsageRecordMapper.selectSummary(
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model());
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId());
|
||||
Integer p95DurationMs = aiUsageRecordMapper.selectP95DurationMs(
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model());
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId());
|
||||
|
||||
long cacheHitTokens = nullToZero(row.getCacheHitTokens());
|
||||
long cacheMissTokens = nullToZero(row.getCacheMissTokens());
|
||||
@@ -209,7 +219,7 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
String bucket = requireBucket(query == null ? null : query.getBucket());
|
||||
|
||||
return aiUsageRecordMapper.selectSeries(
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model(), bucket)
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), bucket)
|
||||
.stream()
|
||||
.map(row -> {
|
||||
AiUsageSeriesPoint point = new AiUsageSeriesPoint();
|
||||
@@ -230,26 +240,60 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
ResolvedFilter filter = resolve(query);
|
||||
String groupBy = requireGroupBy(query == null ? null : query.getGroupBy());
|
||||
|
||||
return aiUsageRecordMapper.selectBreakdown(
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model(), groupBy)
|
||||
.stream()
|
||||
.map(row -> {
|
||||
AiUsageBreakdownItem item = new AiUsageBreakdownItem();
|
||||
item.setKey(row.getGroupKey());
|
||||
item.setCalls(nullToZero(row.getCalls()));
|
||||
item.setSuccessCalls(nullToZero(row.getSuccessCalls()));
|
||||
item.setFailedCalls(nullToZero(row.getFailedCalls()));
|
||||
item.setPromptTokens(nullToZero(row.getPromptTokens()));
|
||||
item.setCompletionTokens(nullToZero(row.getCompletionTokens()));
|
||||
item.setCacheHitTokens(nullToZero(row.getCacheHitTokens()));
|
||||
item.setCostUsd(nullToZero(row.getCostUsd()));
|
||||
item.setAvgDurationMs(row.getAvgDurationMs() == null
|
||||
? null : Math.round(row.getAvgDurationMs()));
|
||||
return item;
|
||||
})
|
||||
List<AiUsageBreakdownRow> rows = aiUsageRecordMapper.selectBreakdown(
|
||||
filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), groupBy);
|
||||
// groupBy=user 的分组键是用户 id,前端要显示登录名;一次批量查完,不要按分组逐条查
|
||||
Map<String, String> userNames = GROUP_BY_USER.equals(groupBy) ? loadUserNames(rows) : Map.of();
|
||||
|
||||
return rows.stream()
|
||||
.map(row -> toBreakdownItem(row, groupBy, userNames))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/** 分组键就是用户 id:去重后一次查完登录名(未归属的 null 键不参与查询) */
|
||||
private Map<String, String> loadUserNames(List<AiUsageBreakdownRow> rows) {
|
||||
Set<String> userIds = rows.stream()
|
||||
.map(AiUsageBreakdownRow::getGroupKey)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
return userService.getUserNamesByIds(userIds);
|
||||
}
|
||||
|
||||
private static AiUsageBreakdownItem toBreakdownItem(AiUsageBreakdownRow row, String groupBy,
|
||||
Map<String, String> userNames) {
|
||||
String key = row.getGroupKey();
|
||||
AiUsageBreakdownItem item = new AiUsageBreakdownItem();
|
||||
item.setKey(key);
|
||||
item.setLabel(breakdownLabel(key, groupBy, userNames));
|
||||
item.setCalls(nullToZero(row.getCalls()));
|
||||
item.setSuccessCalls(nullToZero(row.getSuccessCalls()));
|
||||
item.setFailedCalls(nullToZero(row.getFailedCalls()));
|
||||
item.setPromptTokens(nullToZero(row.getPromptTokens()));
|
||||
item.setCompletionTokens(nullToZero(row.getCompletionTokens()));
|
||||
item.setCacheHitTokens(nullToZero(row.getCacheHitTokens()));
|
||||
item.setCostUsd(nullToZero(row.getCostUsd()));
|
||||
item.setAvgDurationMs(row.getAvgDurationMs() == null
|
||||
? null : Math.round(row.getAvgDurationMs()));
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分组的展示名(契约 v2 第 4.2 节)。
|
||||
*
|
||||
* <p>非 user 分组下 label 就是 key:前端统一渲染 {@code label} 即可,不必按维度分支。
|
||||
* user 分组下换成登录名;未归属(key 为 null)显示「未归属」,否则归属链路断了也看不出来;
|
||||
* 查不到登录名时回退成用户 id,总比整行显示空白强。</p>
|
||||
*/
|
||||
private static String breakdownLabel(String key, String groupBy, Map<String, String> userNames) {
|
||||
if (!GROUP_BY_USER.equals(groupBy)) {
|
||||
return key;
|
||||
}
|
||||
if (key == null) {
|
||||
return UNASSIGNED_LABEL;
|
||||
}
|
||||
return userNames.getOrDefault(key, key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AiUsageBalance balance() {
|
||||
return aiUsageClient.fetchBalance();
|
||||
@@ -268,7 +312,8 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
: LocalDateTime.ofInstant(Instant.ofEpochMilli(to), ZoneOffset.UTC);
|
||||
return new ResolvedFilter(fromTime, toTime,
|
||||
query == null ? null : query.getTaskType(),
|
||||
query == null ? null : query.getModel());
|
||||
query == null ? null : query.getModel(),
|
||||
query == null ? null : query.getUserId());
|
||||
}
|
||||
|
||||
private static String requireBucket(String bucket) throws ErrorParameterException {
|
||||
@@ -287,8 +332,8 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
return GROUP_BY_TASK_TYPE;
|
||||
}
|
||||
String value = groupBy.trim();
|
||||
if (!GROUP_BY_TASK_TYPE.equals(value) && !GROUP_BY_MODEL.equals(value)) {
|
||||
throw new ErrorParameterException("分组维度只支持 taskType 或 model");
|
||||
if (!GROUP_BY_TASK_TYPE.equals(value) && !GROUP_BY_MODEL.equals(value) && !GROUP_BY_USER.equals(value)) {
|
||||
throw new ErrorParameterException("分组维度只支持 taskType、model 或 user");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -302,6 +347,6 @@ public class AiUsageServiceImpl implements AiUsageService {
|
||||
}
|
||||
|
||||
/** 解析后的查询条件(时间已转成 UTC 本地时间) */
|
||||
private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model) {
|
||||
private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model, String userId) {
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user