diff --git a/src/main/java/com/imyeyu/api/config/RedisConfig.java b/src/main/java/com/imyeyu/api/config/RedisConfig.java index 601de34..26de935 100644 --- a/src/main/java/com/imyeyu/api/config/RedisConfig.java +++ b/src/main/java/com/imyeyu/api/config/RedisConfig.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.imyeyu.api.modules.common.entity.Multilingual; import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiClarificationDraft; import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; import com.imyeyu.api.modules.gao.bean.GaoUserInviteCache; import com.imyeyu.spring.bean.RedisConfigParams; @@ -196,6 +197,12 @@ public class RedisConfig extends AbstractRedisConfig { return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiPendingOperation.class)); } + /// @return AI 待补全操作草稿,草稿 ID: 草稿 + @Bean("redisGaoAiClarification") + public Redis getGaoAiClarificationRedisTemplate() { + return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiClarificationDraft.class)); + } + /// @return AI 待确认操作索引,用户+门店/来源会话: 公开操作 ID @Bean("redisGaoAiOperationIndex") public Redis getGaoAiOperationIndexRedisTemplate() { diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java b/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java index 4a2b6b9..ec40176 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java @@ -42,6 +42,10 @@ public class GaoAiProperties { @Value("${gao.ai.write.result-ttl-seconds:1800}") private long resultTtlSeconds; + /// 待补全操作草稿有效期,单位秒 + @Value("${gao.ai.write.clarification-ttl-seconds:600}") + private long clarificationTtlSeconds; + /// 10 分钟内最大准备次数 @Value("${gao.ai.write.max-prepares-per-10-minutes:10}") private int maxPreparesPer10Minutes; diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationDraft.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationDraft.java new file mode 100644 index 0000000..961f78f --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationDraft.java @@ -0,0 +1,59 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +/// GAO 智能体待补全操作草稿 +/// +/// 仅在写操作返回 `NEEDS_CLARIFICATION` 后保存到服务端 Redis, +/// 下一轮由后端注入工作流,不进入工具输出和模型历史 +/// +/// @author Codex +/// @since 2026-11-27 +@Data +@NoArgsConstructor +public class GaoAiClarificationDraft { + + /// 不可预测的草稿 ID + private String draftId; + + /// 操作编码 + private String operation; + + /// 已提取的标准化业务参数 + private String argumentsJson; + + /// 缺失字段 + private List missingFields = new ArrayList<>(); + + /// 注入工作流的补全上下文 + private String summary; + + /// 登录用户 ID + private String userId; + + /// 固定门店 ID + private String storeId; + + /// Dify 会话 ID,可为空 + private String conversationId; + + /// 创建时间,单位毫秒 + private long createdAt; + + /// 过期时间,单位毫秒 + private long expiresAt; + + /// 判断草稿是否属于指定用户和门店 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @return 是否匹配 + public boolean belongsTo(String userId, String storeId) { + return this.userId != null && this.userId.equals(userId) + && this.storeId != null && this.storeId.equals(storeId); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationService.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationService.java new file mode 100644 index 0000000..d326067 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationService.java @@ -0,0 +1,36 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; + +import java.util.List; + +/// GAO 智能体待补全操作服务 +/// +/// @author Codex +/// @since 2026-11-27 +public interface GaoAiClarificationService { + + /// 保存待补全操作草稿 + /// + /// 同一用户和门店只保留最新一份草稿。 + /// + /// @param session AI 会话 + /// @param operation 操作编码 + /// @param argumentsJson 已提取的业务参数 + /// @param missingFields 缺失字段 + /// @return 草稿 ID,参数不足时返回 null + String save(GaoAiSession session, String operation, String argumentsJson, List missingFields); + + /// 读取并删除当前待补全草稿 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param conversationId Dify 会话 ID,可为空 + /// @return 草稿,无则返回 null + GaoAiClarificationDraft take(String userId, String storeId, String conversationId); + + /// 清理当前待补全草稿 + /// + /// @param session AI 会话 + void clear(GaoAiSession session); +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationServiceImplement.java new file mode 100644 index 0000000..381b14b --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationServiceImplement.java @@ -0,0 +1,158 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.spring.util.Redis; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +import java.security.SecureRandom; +import java.util.Base64; +import java.util.List; + +/// GAO 智能体待补全操作服务实现 +/// +/// @author Codex +/// @since 2026-11-27 +@Service +@RequiredArgsConstructor +public class GaoAiClarificationServiceImplement implements GaoAiClarificationService { + + private static final String ACTIVE_PREFIX = "GAO:AI:CLARIFY:ACTIVE:"; + private static final String DRAFT_PREFIX = "GAO:AI:CLARIFY:DRAFT:"; + private static final String LOCK_PREFIX = "GAO:AI:CLARIFY:LOCK:"; + private static final int SUMMARY_MAX_LENGTH = 3500; + + private final GaoAiProperties properties; + + @Qualifier("redisGaoAiClarification") + private final Redis redis; + + @Qualifier("redisGaoAiOperationIndex") + private final Redis indexRedis; + + @Qualifier("redisLocker") + private final Redis locker; + + private final SecureRandom secureRandom = new SecureRandom(); + + @Override + public String save(GaoAiSession session, String operation, String argumentsJson, List missingFields) { + if (session == null || isBlank(session.getUserId()) || isBlank(session.getStoreId()) || isBlank(operation)) { + return null; + } + long now = System.currentTimeMillis(); + long ttlMs = Math.max(60_000L, properties.getClarificationTtlSeconds() * 1000L); + String lockKey = lockKey(session.getUserId(), session.getStoreId()); + if (!locker.lock(lockKey, 1, 5_000L)) { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在处理,请稍后重试", true); + } + try { + String activeKey = activeKey(session.getUserId(), session.getStoreId()); + String oldDraftId = indexRedis.get(activeKey); + if (!isBlank(oldDraftId)) { + redis.destroy(draftKey(oldDraftId)); + } + List fields = missingFields == null ? List.of() : List.copyOf(missingFields); + GaoAiClarificationDraft draft = new GaoAiClarificationDraft(); + draft.setDraftId(newDraftId()); + draft.setOperation(operation.trim()); + draft.setArgumentsJson(argumentsJson); + draft.setMissingFields(fields); + draft.setSummary(buildSummary(operation.trim(), argumentsJson, fields)); + draft.setUserId(session.getUserId()); + draft.setStoreId(session.getStoreId()); + draft.setConversationId(isBlank(session.getDifyConversationId()) ? null : session.getDifyConversationId().trim()); + draft.setCreatedAt(now); + draft.setExpiresAt(now + ttlMs); + redis.set(draftKey(draft.getDraftId()), draft, ttlMs); + indexRedis.set(activeKey, draft.getDraftId(), ttlMs); + return draft.getDraftId(); + } finally { + locker.releaseLock(lockKey); + } + } + + @Override + public GaoAiClarificationDraft take(String userId, String storeId, String conversationId) { + if (isBlank(userId) || isBlank(storeId)) { + return null; + } + String activeKey = activeKey(userId, storeId); + String lockKey = lockKey(userId, storeId); + if (!locker.lock(lockKey, 1, 5_000L)) { + return null; + } + try { + String draftId = indexRedis.get(activeKey); + if (isBlank(draftId)) { + return null; + } + GaoAiClarificationDraft draft = redis.get(draftKey(draftId)); + if (draft == null || !draft.belongsTo(userId, storeId)) { + indexRedis.destroy(activeKey); + redis.destroy(draftKey(draftId)); + return null; + } + if (draft.getExpiresAt() <= System.currentTimeMillis()) { + indexRedis.destroy(activeKey); + redis.destroy(draftKey(draftId)); + return null; + } + if (!isBlank(conversationId) && !isBlank(draft.getConversationId()) + && !conversationId.equals(draft.getConversationId())) { + return null; + } + indexRedis.destroy(activeKey); + redis.destroy(draftKey(draftId)); + return draft; + } finally { + locker.releaseLock(lockKey); + } + } + + @Override + public void clear(GaoAiSession session) { + if (session == null || isBlank(session.getUserId()) || isBlank(session.getStoreId())) { + return; + } + String activeKey = activeKey(session.getUserId(), session.getStoreId()); + String draftId = indexRedis.get(activeKey); + indexRedis.destroy(activeKey); + if (!isBlank(draftId)) { + redis.destroy(draftKey(draftId)); + } + } + + private String buildSummary(String operation, String argumentsJson, List missingFields) { + String arguments = isBlank(argumentsJson) ? "{}" : argumentsJson; + String fields = missingFields.isEmpty() ? "无" : String.join("、", missingFields); + String summary = "【待补充写操作】\n操作:" + operation + "\n已提取参数:" + arguments + "\n缺失字段:" + fields + + "\n请把店长本轮补充合并进已提取参数,输出完整操作计划;若仍缺少字段,继续放入 missingFields。" + + "\n如果店长本轮并不是在补充该操作,而是提出了新的查询或无关请求,输出 {\"operation\":\"REFUSE\",\"arguments\":{},\"missingFields\":[]}。"; + return summary.length() <= SUMMARY_MAX_LENGTH ? summary : summary.substring(0, SUMMARY_MAX_LENGTH); + } + + private String newDraftId() { + byte[] bytes = new byte[24]; + secureRandom.nextBytes(bytes); + return "clr_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private String activeKey(String userId, String storeId) { + return ACTIVE_PREFIX + userId + ":" + storeId; + } + + private String draftKey(String draftId) { + return DRAFT_PREFIX + draftId; + } + + private String lockKey(String userId, String storeId) { + return LOCK_PREFIX + userId + ":" + storeId; + } + + private boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java index bf929be..3c17a39 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java @@ -39,6 +39,7 @@ public class GaoAiOperationServiceImplement implements GaoAiOperationService { private final GaoAiOperationRegistry registry; private final GaoAiToolAuthorizer authorizer; private final GaoAiPendingOperationService pendingService; + private final GaoAiClarificationService clarificationService; private final GaoAiAttachmentService attachmentService; private final GaoAiAuditService auditService; private final GaoAiOperationSupport support; @@ -135,12 +136,16 @@ public class GaoAiOperationServiceImplement implements GaoAiOperationService { GaoAiPendingOperationService.Created created = pendingService.create(context, definition, requestNo, prepared.getArgumentsJson(), tokens, prepared); GaoAiPendingOperation pending = created.pending(); + clearClarification(session); recordAudit("GAO_AI_WRITE_PREPARE", "SUCCESS", session.getUserId(), session.getStoreId(), session.getDifyConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(), created.token(), pending.getRiskLevel(), null, null, false, null, startedAt); // token 只由服务端下一轮注入,不返回给 Dify 工具输出,避免进入工作流日志和模型上下文 return success(pending, null, false); } catch (GaoAiOperationException e) { + if ("NEEDS_CLARIFICATION".equals(e.getErrorCode()) && definition != null) { + saveClarification(session, definition, argumentsJson, e.getMissingFields()); + } recordAudit("GAO_AI_WRITE_PREPARE", "FAILED", session.getUserId(), session.getStoreId(), session.getDifyConversationId(), definition == null ? operation : definition.code(), null, null, null, definition == null ? null : definition.getRiskLevel().name(), e.getErrorCode(), null, false, @@ -544,6 +549,24 @@ public class GaoAiOperationServiceImplement implements GaoAiOperationService { } } + private void saveClarification(GaoAiSession session, GaoAiOperationDefinition definition, String argumentsJson, + List missingFields) { + try { + clarificationService.save(session, definition.code(), argumentsJson, missingFields); + } catch (RuntimeException e) { + log.warn("GAO AI 保存待补全操作草稿失败:operation={}, userId={}, storeId={}", definition.code(), + session.getUserId(), session.getStoreId(), e); + } + } + + private void clearClarification(GaoAiSession session) { + try { + clarificationService.clear(session); + } catch (RuntimeException e) { + log.warn("GAO AI 清理待补全操作草稿失败:userId={}, storeId={}", session.getUserId(), session.getStoreId(), e); + } + } + private GaoAiPendingOperation safePending(GaoAiPendingOperation pending) { try { return pendingService.requireByOperationId(pending.getOperationId()); diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java index 109e7a6..4e73e1e 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java @@ -9,6 +9,8 @@ import com.imyeyu.api.modules.common.service.SettingService; import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog; import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiClarificationDraft; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiClarificationService; import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperationService; import com.imyeyu.api.modules.gao.ai.service.GaoAiAccessException; @@ -79,6 +81,7 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { private final GaoStoreService storeService; private final GaoAiSessionService sessionService; private final GaoAiPendingOperationService pendingOperationService; + private final GaoAiClarificationService clarificationService; private final GaoAiAuditService auditService; private final SettingService settingService; @@ -247,6 +250,9 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { inputs.put("pendingOperationRisk", ""); inputs.put("pendingOperationRequiredPhrase", ""); inputs.put("pendingOperationExpiresAt", ""); + inputs.put("pendingClarificationToken", ""); + inputs.put("pendingClarificationContext", ""); + inputs.put("pendingClarificationExpiresAt", ""); inputs.put("attachmentTokensJson", writeJson(attachmentTokens == null ? List.of() : attachmentTokens)); GaoAiPendingOperation pending = pendingOperationService.findActive(session.getUserId(), session.getStoreId(), session.getDifyConversationId()); @@ -262,6 +268,17 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { log.warn("GAO 智能体注入待确认操作失败:operationId={}", pending.getOperationId(), e); } } + try { + GaoAiClarificationDraft clarification = clarificationService.take(session.getUserId(), session.getStoreId(), + session.getDifyConversationId()); + if (pending == null && clarification != null) { + inputs.put("pendingClarificationToken", clarification.getDraftId()); + inputs.put("pendingClarificationContext", truncate(clarification.getSummary(), 3500)); + inputs.put("pendingClarificationExpiresAt", String.valueOf(clarification.getExpiresAt())); + } + } catch (RuntimeException e) { + log.warn("GAO 智能体注入待补全操作失败:userId={}, storeId={}", session.getUserId(), session.getStoreId(), e); + } return newDifyRequest("/chat-messages") .timeout(Duration.ofSeconds(readTimeoutSeconds)) .header("X-Timi-AI-Session", session.getSessionId()) diff --git a/src/test/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationServiceTest.java b/src/test/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationServiceTest.java new file mode 100644 index 0000000..6507a20 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiClarificationServiceTest.java @@ -0,0 +1,129 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.spring.util.Redis; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/// 智能体待补全操作草稿服务测试 +/// +/// @author Codex +/// @since 2026-11-27 +class GaoAiClarificationServiceTest { + + private final FakeRedis draftRedis = new FakeRedis<>(); + private final FakeRedis indexRedis = new FakeRedis<>(); + private final FakeRedis locker = new FakeRedis<>(); + private GaoAiClarificationServiceImplement service; + private GaoAiSession session; + + @BeforeEach + void setUp() { + draftRedis.clear(); + indexRedis.clear(); + GaoAiProperties properties = mock(GaoAiProperties.class); + when(properties.getClarificationTtlSeconds()).thenReturn(600L); + service = new GaoAiClarificationServiceImplement(properties, draftRedis, indexRedis, locker); + session = new GaoAiSession(); + session.setUserId("user-1"); + session.setStoreId("store-1"); + session.setDifyConversationId("conversation-1"); + } + + @Test + void saveAndTakeDraftOnce() { + String draftId = service.save(session, "POINT_ADJUST", + "{\"customerKeyword\":\"陈星\",\"pointDelta\":200}", List.of("remark")); + + assertNotNull(draftId); + GaoAiClarificationDraft draft = service.take("user-1", "store-1", "conversation-1"); + assertNotNull(draft); + assertEquals("POINT_ADJUST", draft.getOperation()); + assertEquals(List.of("remark"), draft.getMissingFields()); + assertTrue(draft.getSummary().contains("missingFields")); + assertTrue(draft.getSummary().contains("REFUSE")); + assertNull(service.take("user-1", "store-1", "conversation-1")); + } + + @Test + void expiredDraftIsDiscarded() { + service.save(session, "POINT_ADJUST", "{}", List.of("remark")); + String draftId = indexRedis.get("GAO:AI:CLARIFY:ACTIVE:user-1:store-1"); + draftRedis.get("GAO:AI:CLARIFY:DRAFT:" + draftId).setExpiresAt(System.currentTimeMillis() - 1); + + assertNull(service.take("user-1", "store-1", "conversation-1")); + assertTrue(indexRedis.isEmpty()); + assertTrue(draftRedis.isEmpty()); + } + + @Test + void draftIsKeptForOtherConversation() { + service.save(session, "POINT_ADJUST", "{}", List.of("remark")); + + assertNull(service.take("user-1", "store-1", "conversation-2")); + assertNotNull(service.take("user-1", "store-1", "conversation-1")); + } + + @Test + void clearRemovesDraft() { + service.save(session, "POINT_ADJUST", "{}", List.of("remark")); + + service.clear(session); + assertTrue(indexRedis.isEmpty()); + assertTrue(draftRedis.isEmpty()); + } + + /// 内存 Redis,避免测试依赖真实连接 + private static class FakeRedis extends Redis { + + private final Map values = new HashMap<>(); + + FakeRedis() { + super(null, null); + } + + @Override + public void set(K key, V value, long ms) { + values.put(key, value); + } + + @Override + public V get(K key) { + return values.get(key); + } + + @Override + public boolean destroy(K key) { + return values.remove(key) != null; + } + + @Override + public boolean lock(K key, V value, long timeoutMS) { + return true; + } + + @Override + public void releaseLock(K key) { + } + + void clear() { + values.clear(); + } + + boolean isEmpty() { + return values.isEmpty(); + } + } +}