深度 RESTful 设计模式、MyBatis-Plus 使用方式、数据库表结构
kuai-service 的 API 遵循 RESTful 风格,使用统一的 Result<T> 包装响应。路径前缀按功能域划分:
| 路径前缀 | 功能域 | 认证方式 |
|---|---|---|
/api/prompts | 提示词管理(读取) | 无需登录 |
/api/sso/prompts | 提示词管理(写入) | SSO 登录 |
/kuai/evaluation-app | LLM 评估 | 无需登录 |
/gpt/wechat | 微信机器人回调 | 企微签名验证 |
/api/shared-app | 分享应用 | 混合 |
// 成功响应
{
"code": 200,
"message": "success",
"data": { ... } // 实际业务数据
}
// 错误响应
{
"code": 500,
"message": "创建失败:提示词标题不能为空",
"data": null
}
// 列表响应(带分页)
{
"code": 200,
"data": {
"total": 42,
"pageSize": 42,
"hasNextPage": false,
"list": [ ... ]
}
}
| 操作 | 方法 | 示例路径 | 说明 |
|---|---|---|---|
| 查询列表 | GET | /api/prompts?category=xxx&keyword=xxx | 查询参数筛选 |
| 查询详情 | GET | /api/prompts/{id} | 路径变量 |
| 创建 | POST | /api/sso/prompts | RequestBody JSON |
| 更新 | PUT | /api/sso/prompts/{id} | 路径变量 + RequestBody |
| 删除 | DELETE | /api/sso/prompts/{id} | 路径变量 |
| 状态变更 | PUT | /api/sso/prompts/{id}/publish | 子资源动作 |
| 批量操作 | POST | /kuai/evaluation-app/llmEvaluate/batch | RequestBody 列表 |
| 导出 | POST | /kuai/evaluation-app/.../exportCsv | 返回 CSV 文件流 |
写操作路径包含 /sso/ 前缀,通过 SsoSessionUtil.getUserInfo(httpRequest) 获取当前用户。读操作通常不需要登录。
// 写操作需要 SSO
@PostMapping("/sso/prompts")
public Result createPrompt(@RequestBody CreatePromptRequest request,
HttpServletRequest httpRequest) {
UserInfo userInfo = SsoSessionUtil.getUserInfo(httpRequest);
String currentUser = userInfo.getLdapId();
// ...
}
// 读操作不需要 SSO
@GetMapping("/prompts")
public Result getPromptList(@RequestParam(required=false) String category) {
// 直接查询
}
请求体使用独立的 DTO 类,与数据库实体分离:
// 请求 DTO
entity/dto/CreatePromptRequest.java // 创建提示词请求
entity/dto/CreateVersionRequest.java // 创建版本请求
entity/dto/AppEvaluationRequest.java // 应用评估请求
entity/dto/BatchEvaluationFilterRequest.java // 批量筛选请求
// 查询参数对象
entity/query/TaskEvaluationDetailQuery.java // 任务详情分页查询
entity/query/QueryParams.java // 通用查询参数
// 数据库实体
entity/Prompt.java
entity/fastGpt/LlmTask.java
entity/fastGpt/LlmEvaluationRecord.java
耗时操作采用"提交+轮询"模式:
// 1. 提交任务 → 返回 taskId
POST /kuai/evaluation-app/llmEvaluate/batch
→ { "taskId": "123", "chatCount": 5, "message": "任务已创建" }
// 2. 查询任务状态
GET /kuai/evaluation-app/llmEvaluate/task/123
→ { "taskId": "123", "status": 1, "doneCount": 3, "totalCount": 10, "avgScore": 7.5 }
// 3. 查询任务详情
GET /kuai/evaluation-app/llmEvaluate/task/123/details
// 4. 取消任务
POST /kuai/evaluation-app/llmEvaluate/task/123/cancel
// 5. 删除任务
POST /kuai/evaluation-app/llmEvaluate/task/123/delete
项目中 MyBatis 的使用有两种风格:
直接在 Mapper 接口上写 SQL,适合复杂查询:
@Mapper
public interface LlmTaskMapper {
@Insert("INSERT INTO llm_task " +
"(app_id, total_count, done_count, status, start_time, create_time, update_time) " +
"VALUES (#{appId}, #{totalCount}, 0, #{status}, #{startTime}, #{createTime}, #{updateTime})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insertTask(LlmTask task);
@Select("SELECT id, task_id as taskId, app_id as appId, total_count as totalCount, " +
"done_count as doneCount, status, avg_score as avgScore " +
"FROM llm_task WHERE task_id = #{taskId}")
LlmTask selectByTaskId(@Param("taskId") String taskId);
@Update("UPDATE llm_task SET done_count = done_count + 1, update_time = #{updateTime} " +
"WHERE task_id = #{taskId}")
int incrementDoneCount(@Param("taskId") String taskId, @Param("updateTime") Date updateTime);
}
利用 BaseMapper<T> 提供的通用 CRUD 方法:
@Mapper
public interface LlmEvaluationRecordMapper extends BaseMapper<LlmEvaluationRecord> {
// 继承的方法:insert(), selectById(), updateById(), deleteById() 等
// 自定义复杂查询(动态 SQL)
@Select({
"<script>",
"SELECT * FROM llm_evaluation_record ",
"WHERE taskId = #{taskId} ",
"ORDER BY ",
"<choose>",
"<when test=\"llmScoreOrder == 'asc'\">llmScore ASC</when>",
"<when test=\"llmScoreOrder == 'desc'\">llmScore DESC</when>",
"<otherwise>evalTime DESC</otherwise>",
"</choose>",
"</script>"
})
List<LlmEvaluationRecord> selectByTaskId(
@Param("taskId") String taskId,
@Param("llmScoreOrder") String llmScoreOrder);
}
@Select({"<script>", ...}) 数组语法可以在注解中写 MyBatis 动态 SQL(if/choose/foreach)。
非结构化数据使用 MongoTemplate 或 Spring Data Repository:
// Repository 接口
public interface ChatRepository extends MongoRepository<Chat, String> {
// Spring Data 自动实现:findAll(), findById(), save(), deleteById()
}
// 复杂聚合查询使用 MongoTemplate
@Autowired private MongoTemplate mongoTemplate;
Aggregation agg = Aggregation.newAggregation(
match(Criteria.where("appId").is(appId)),
sort(Sort.by(Sort.Direction.DESC, "createTime")),
skip((long) page * size),
limit(size)
);
AggregationResults<Chat> results = mongoTemplate.aggregate(agg, "chat", Chat.class);
CREATE TABLE llm_task (
id INT AUTO_INCREMENT PRIMARY KEY, -- 自增主键
task_id VARCHAR(64) UNIQUE, -- 任务唯一标识(等于 id 的字符串形式)
app_id VARCHAR(64), -- 应用 ID
total_count INT, -- 总任务数
done_count INT DEFAULT 0, -- 已完成数
status INT DEFAULT 0, -- 0=待开始, 1=执行中, 2=成功, 3=失败, 4=已取消
avg_score DOUBLE, -- 平均分数
start_time DATETIME, -- 开始时间
end_time DATETIME, -- 结束时间
create_time DATETIME, -- 创建时间
update_time DATETIME -- 更新时间
);
CREATE TABLE llm_evaluation_record (
id INT AUTO_INCREMENT PRIMARY KEY,
app_id VARCHAR(64), -- 应用 ID
chat_id VARCHAR(64), -- 会话 ID
task_id VARCHAR(64), -- 关联 llm_task.task_id
_id VARCHAR(64), -- 原始答案唯一 ID
question TEXT, -- 问题内容
answer TEXT, -- AI 回答
llm_answer TEXT, -- LLM 评估回答
llm_score DOUBLE, -- LLM 评分 (0-10)
deep_eval_score DOUBLE, -- DeepEval 评分
deepeval_result TEXT, -- DeepEval 详细结果
eval_time BIGINT, -- 评估时间戳(毫秒)
satisfaction VARCHAR(32), -- 人工满意度
category1 VARCHAR(64), -- 一级分类
category2 VARCHAR(64) -- 二级分类
);
| 表名 | 用途 | 对应 Entity |
|---|---|---|
llm_eval_lock | LLM 评估分布式锁,防止重复评估 | LlmEvalLock |
deepeval_task | DeepEval 批量任务 | DeepEvalTask |
deepeval_lock | DeepEval 分布式锁 | DeepEvalLock |
application_info | 应用基准信息(类型、负责人、模型配置) | ApplicationInfo |
new_robot | 微信机器人 Token 注册 | NewRobot |
evaluation_result | 评估结果汇总 | EvaluationResult |
evaluation_category_override | 评估分类覆盖 | EvaluationCategoryOverride |
prompt | 提示词主表 | Prompt |
prompt_version | 提示词版本 | PromptVersion |
prompt_evaluation | 提示词评估记录 | PromptEvaluation |
| 集合名 | 用途 | 访问方式 |
|---|---|---|
chat | 对话会话记录 | ChatRepository / MongoTemplate |
chat_item | 对话条目(问答对) | ChatItemRepository |
apps_set | 应用集合配置 | AppsSetRepository |
open_apis_set | OpenAPI 配置 | OpenApisSetRepository |
mentor_forward_session | 导师转发会话 | MentorForwardSessionRepository |
appId、chatId 等字段关联。
@Data // getter/setter/toString/equals/hashCode
@NoArgsConstructor // 无参构造
@AllArgsConstructor // 全参构造
@Builder // Builder 模式
@EqualsAndHashCode(callSuper = false)
@Table(name = "llm_task") // JPA 表映射注解
public class LlmTask extends BaseDo implements Serializable {
private Integer id;
private String taskId;
private String appId;
private Integer totalCount;
private Integer doneCount;
private Integer status; // 0=待开始, 1=执行中, 2=成功, 3=失败, 4=已取消
private Double avgScore;
// ...
}
BaseDo,提供通用字段如 createTime、updateTime、createUser、updateUser。
使用 @Select 的 AS 别名实现下划线到驼峰的映射:
@Select("SELECT id, task_id as taskId, app_id as appId, " +
"total_count as totalCount, done_count as doneCount, " +
"avg_score as avgScore, start_time as startTime " +
"FROM llm_task WHERE task_id = #{taskId}")
LlmTask selectByTaskId(@Param("taskId") String taskId);