LobsterOutboundQualityGate.java 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. package com.fs.company.service.workflow.execution;
  2. import com.fs.company.service.workflow.QualityScoringService;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.stereotype.Service;
  8. import java.util.Map;
  9. /**
  10. * 统一出站前 8 维质量评分:AI 生成 / fallback / 沉默唤醒等必须评分后才可发送;租户配置话术跳过。
  11. */
  12. @Service
  13. public class LobsterOutboundQualityGate {
  14. private static final Logger log = LoggerFactory.getLogger(LobsterOutboundQualityGate.class);
  15. public static final String VAR_SKIP_QUALITY_SCORE = "_skipQualityScore";
  16. public static final String VAR_QUALITY_SCORED = "_qualityScoredAtOutbound";
  17. public static final String VAR_OUTBOUND_SOURCE = "_outboundSource";
  18. @Autowired(required = false)
  19. private QualityScoringService qualityScoringService;
  20. @Value("${lobster.outbound.quality-gate.enabled:true}")
  21. private boolean enabled;
  22. public static void markTenantConfiguredScript(Map<String, Object> variables) {
  23. if (variables == null) {
  24. return;
  25. }
  26. variables.put(VAR_SKIP_QUALITY_SCORE, Boolean.TRUE);
  27. variables.put(VAR_OUTBOUND_SOURCE, "tenant_script");
  28. }
  29. public static void markAiGenerated(Map<String, Object> variables, String source) {
  30. if (variables == null) {
  31. return;
  32. }
  33. variables.remove(VAR_SKIP_QUALITY_SCORE);
  34. variables.remove(VAR_QUALITY_SCORED);
  35. if (source != null && !source.isBlank()) {
  36. variables.put(VAR_OUTBOUND_SOURCE, source);
  37. }
  38. }
  39. public static void markScoredInEvolution(Map<String, Object> variables) {
  40. if (variables == null) {
  41. return;
  42. }
  43. variables.put(VAR_QUALITY_SCORED, Boolean.TRUE);
  44. }
  45. public static boolean shouldSkip(Map<String, Object> variables) {
  46. if (variables == null) {
  47. return false;
  48. }
  49. if (Boolean.TRUE.equals(variables.get(VAR_SKIP_QUALITY_SCORE))) {
  50. return true;
  51. }
  52. return Boolean.TRUE.equals(variables.get(VAR_QUALITY_SCORED));
  53. }
  54. /**
  55. * @return 评分通过后的正文;null 表示拦截不发
  56. */
  57. public String applyBeforeDeliver(Long companyId, String message, Map<String, Object> variables) {
  58. if (message == null || message.isBlank()) {
  59. return message;
  60. }
  61. if (!enabled || shouldSkip(variables)) {
  62. return message;
  63. }
  64. if (LobsterMessageTemplateRenderer.isInternalInstructionText(message)) {
  65. log.warn("[OutboundQualityGate] block internal instruction text companyId={}", companyId);
  66. return null;
  67. }
  68. if (qualityScoringService == null) {
  69. log.warn("[OutboundQualityGate] QualityScoringService unavailable, block AI outbound companyId={}",
  70. companyId);
  71. return null;
  72. }
  73. String userQuestion = resolveUserQuestion(variables);
  74. String knowledgeBase = variables.get("_uddWebResearch") != null
  75. ? variables.get("_uddWebResearch").toString() : "";
  76. String goal = variables.get("_lastOutboundNodeCode") != null
  77. ? variables.get("_lastOutboundNodeCode").toString()
  78. : (variables.get("_greetNodeCode") != null ? variables.get("_greetNodeCode").toString() : "");
  79. String templateHint = variables.get("nodeMessageTemplate") != null
  80. ? variables.get("nodeMessageTemplate").toString() : "";
  81. String source = variables.get(VAR_OUTBOUND_SOURCE) != null
  82. ? variables.get(VAR_OUTBOUND_SOURCE).toString() : "outbound";
  83. try {
  84. QualityScoringService.ScoringResult scoring = qualityScoringService.scoreWithRetry(
  85. companyId, message, userQuestion, knowledgeBase, goal, templateHint, source, null);
  86. if (scoring == null) {
  87. log.warn("[OutboundQualityGate] scoring null, block companyId={}", companyId);
  88. return null;
  89. }
  90. String finalContent = scoring.getFinalContent() != null ? scoring.getFinalContent().trim() : "";
  91. if (finalContent.isEmpty()) {
  92. log.warn("[OutboundQualityGate] empty after scoring, block companyId={}", companyId);
  93. return null;
  94. }
  95. if (LobsterMessageTemplateRenderer.isInternalInstructionText(finalContent)) {
  96. log.warn("[OutboundQualityGate] block instruction-like content after scoring companyId={}", companyId);
  97. return null;
  98. }
  99. if (!scoring.isFinalPassed()) {
  100. log.warn("[OutboundQualityGate] scoring not passed companyId={} reason={} score={}",
  101. companyId, scoring.getReason(), scoring.getFirstScore());
  102. return null;
  103. }
  104. if (variables != null) {
  105. variables.put(VAR_QUALITY_SCORED, Boolean.TRUE);
  106. variables.put("_lastOutboundQualityScore", scoring.getFirstScore());
  107. }
  108. return finalContent;
  109. } catch (Exception e) {
  110. log.warn("[OutboundQualityGate] scoring failed, block companyId={}: {}", companyId, e.getMessage());
  111. return null;
  112. }
  113. }
  114. private static String resolveUserQuestion(Map<String, Object> variables) {
  115. if (variables == null) {
  116. return "";
  117. }
  118. for (String key : new String[]{"lastReply", "customerMessage", "_silenceWakeCustomerMessage"}) {
  119. Object val = variables.get(key);
  120. if (val != null && !val.toString().isBlank()) {
  121. String text = val.toString().trim();
  122. if (text.startsWith("[silence_wakeup]") || text.startsWith("[wait_wake]")) {
  123. return "";
  124. }
  125. return text;
  126. }
  127. }
  128. return "";
  129. }
  130. }