.
This commit is contained in:
214
src.bak/main/java/com/example/service/base/DataPurgeService.java
Normal file
214
src.bak/main/java/com/example/service/base/DataPurgeService.java
Normal file
@@ -0,0 +1,214 @@
|
||||
|
||||
package com.example.service.base;
|
||||
|
||||
|
||||
|
||||
import com.example.repository.FirestoreBaseRepository;
|
||||
|
||||
import com.google.cloud.firestore.CollectionReference;
|
||||
|
||||
import com.google.cloud.firestore.Firestore;
|
||||
|
||||
import com.google.cloud.firestore.QueryDocumentSnapshot;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
import org.springframework.data.redis.core.ReactiveRedisTemplate;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
|
||||
|
||||
@Service
|
||||
|
||||
public class DataPurgeService {
|
||||
|
||||
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DataPurgeService.class);
|
||||
|
||||
|
||||
|
||||
private final ReactiveRedisTemplate<String, ?> redisTemplate;
|
||||
|
||||
private final FirestoreBaseRepository firestoreBaseRepository;
|
||||
|
||||
|
||||
|
||||
private final Firestore firestore;
|
||||
|
||||
|
||||
|
||||
@Autowired
|
||||
|
||||
public DataPurgeService(
|
||||
|
||||
@Qualifier("reactiveRedisTemplate") ReactiveRedisTemplate<String, ?> redisTemplate,
|
||||
|
||||
FirestoreBaseRepository firestoreBaseRepository, Firestore firestore) {
|
||||
|
||||
this.redisTemplate = redisTemplate;
|
||||
|
||||
this.firestoreBaseRepository = firestoreBaseRepository;
|
||||
|
||||
this.firestore = firestore;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Mono<Void> purgeAllData() {
|
||||
|
||||
return purgeRedis()
|
||||
|
||||
.then(purgeFirestore());
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
private Mono<Void> purgeRedis() {
|
||||
|
||||
logger.info("Starting Redis data purge.");
|
||||
|
||||
return redisTemplate.getConnectionFactory().getReactiveConnection().serverCommands().flushAll()
|
||||
|
||||
.doOnSuccess(v -> logger.info("Successfully purged all data from Redis."))
|
||||
|
||||
.doOnError(e -> logger.error("Error purging data from Redis.", e))
|
||||
|
||||
.then();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
private Mono<Void> purgeFirestore() {
|
||||
|
||||
logger.info("Starting Firestore data purge.");
|
||||
|
||||
return Mono.fromRunnable(() -> {
|
||||
|
||||
try {
|
||||
|
||||
String appId = firestoreBaseRepository.getAppId();
|
||||
|
||||
String conversationsCollectionPath = String.format("artifacts/%s/conversations", appId);
|
||||
|
||||
String notificationsCollectionPath = String.format("artifacts/%s/notifications", appId);
|
||||
|
||||
|
||||
|
||||
// Delete 'mensajes' sub-collections in 'conversations'
|
||||
|
||||
logger.info("Deleting 'mensajes' sub-collections from '{}'", conversationsCollectionPath);
|
||||
|
||||
try {
|
||||
|
||||
List<QueryDocumentSnapshot> conversationDocuments = firestore.collection(conversationsCollectionPath).get().get().getDocuments();
|
||||
|
||||
for (QueryDocumentSnapshot document : conversationDocuments) {
|
||||
|
||||
String messagesCollectionPath = document.getReference().getPath() + "/mensajes";
|
||||
|
||||
logger.info("Deleting sub-collection: {}", messagesCollectionPath);
|
||||
|
||||
firestoreBaseRepository.deleteCollection(messagesCollectionPath, 50);
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
if (e.getMessage().contains("NOT_FOUND")) {
|
||||
|
||||
logger.warn("Collection '{}' not found, skipping.", conversationsCollectionPath);
|
||||
|
||||
} else {
|
||||
|
||||
throw e;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Delete the 'conversations' collection
|
||||
|
||||
logger.info("Deleting collection: {}", conversationsCollectionPath);
|
||||
|
||||
try {
|
||||
|
||||
firestoreBaseRepository.deleteCollection(conversationsCollectionPath, 50);
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
if (e.getMessage().contains("NOT_FOUND")) {
|
||||
|
||||
logger.warn("Collection '{}' not found, skipping.", conversationsCollectionPath);
|
||||
|
||||
}
|
||||
|
||||
else {
|
||||
|
||||
throw e;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Delete the 'notifications' collection
|
||||
|
||||
logger.info("Deleting collection: {}", notificationsCollectionPath);
|
||||
|
||||
try {
|
||||
|
||||
firestoreBaseRepository.deleteCollection(notificationsCollectionPath, 50);
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
if (e.getMessage().contains("NOT_FOUND")) {
|
||||
|
||||
logger.warn("Collection '{}' not found, skipping.", notificationsCollectionPath);
|
||||
|
||||
} else {
|
||||
|
||||
throw e;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
logger.info("Successfully purged Firestore collections.");
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
logger.error("Error purging Firestore collections.", e);
|
||||
|
||||
throw new RuntimeException("Failed to purge Firestore collections.", e);
|
||||
|
||||
}
|
||||
|
||||
}).subscribeOn(Schedulers.boundedElastic()).then();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.base;
|
||||
|
||||
import com.example.mapper.conversation.DialogflowRequestMapper;
|
||||
import com.example.mapper.conversation.DialogflowResponseMapper;
|
||||
import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
|
||||
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
||||
import com.example.exception.DialogflowClientException;
|
||||
import com.google.api.gax.rpc.ApiException;
|
||||
import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest;
|
||||
import com.google.cloud.dialogflow.cx.v3.QueryParameters;
|
||||
import com.google.cloud.dialogflow.cx.v3.SessionsClient;
|
||||
import com.google.cloud.dialogflow.cx.v3.SessionName;
|
||||
import com.google.cloud.dialogflow.cx.v3.SessionsSettings;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
/**
|
||||
* Service for interacting with the Dialogflow CX API to detect user DetectIntent.
|
||||
* It encapsulates the low-level API calls, handling request mapping from DTOs,
|
||||
* managing the `SessionsClient`, and translating API responses into DTOs,
|
||||
* all within a reactive programming context.
|
||||
*/
|
||||
@Service
|
||||
public class DialogflowClientService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DialogflowClientService.class);
|
||||
|
||||
private final String dialogflowCxProjectId;
|
||||
private final String dialogflowCxLocation;
|
||||
private final String dialogflowCxAgentId;
|
||||
|
||||
private final DialogflowRequestMapper dialogflowRequestMapper;
|
||||
private final DialogflowResponseMapper dialogflowResponseMapper;
|
||||
private SessionsClient sessionsClient;
|
||||
|
||||
public DialogflowClientService(
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${dialogflow.cx.project-id}") String dialogflowCxProjectId,
|
||||
@org.springframework.beans.factory.annotation.Value("${dialogflow.cx.location}") String dialogflowCxLocation,
|
||||
@org.springframework.beans.factory.annotation.Value("${dialogflow.cx.agent-id}") String dialogflowCxAgentId,
|
||||
DialogflowRequestMapper dialogflowRequestMapper,
|
||||
DialogflowResponseMapper dialogflowResponseMapper)
|
||||
throws IOException {
|
||||
|
||||
this.dialogflowCxProjectId = dialogflowCxProjectId;
|
||||
this.dialogflowCxLocation = dialogflowCxLocation;
|
||||
this.dialogflowCxAgentId = dialogflowCxAgentId;
|
||||
this.dialogflowRequestMapper = dialogflowRequestMapper;
|
||||
this.dialogflowResponseMapper = dialogflowResponseMapper;
|
||||
|
||||
try {
|
||||
String regionalEndpoint = String.format("%s-dialogflow.googleapis.com:443", dialogflowCxLocation);
|
||||
SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
|
||||
.setEndpoint(regionalEndpoint)
|
||||
.build();
|
||||
this.sessionsClient = SessionsClient.create(sessionsSettings);
|
||||
logger.info("Dialogflow CX SessionsClient initialized successfully for endpoint: {}", regionalEndpoint);
|
||||
logger.info("Dialogflow CX SessionsClient initialized successfully for agent - Test Agent version: {}", dialogflowCxAgentId);
|
||||
} catch (IOException e) {
|
||||
logger.error("Failed to create Dialogflow CX SessionsClient: {}", e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void closeSessionsClient() {
|
||||
if (sessionsClient != null) {
|
||||
sessionsClient.close();
|
||||
logger.info("Dialogflow CX SessionsClient closed.");
|
||||
}
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO> detectIntent(
|
||||
String sessionId,
|
||||
DetectIntentRequestDTO request) {
|
||||
|
||||
Objects.requireNonNull(sessionId, "Dialogflow session ID cannot be null.");
|
||||
Objects.requireNonNull(request, "Dialogflow request DTO cannot be null.");
|
||||
|
||||
logger.info("Initiating detectIntent for session: {}", sessionId);
|
||||
|
||||
DetectIntentRequest.Builder detectIntentRequestBuilder;
|
||||
try {
|
||||
detectIntentRequestBuilder = dialogflowRequestMapper.mapToDetectIntentRequestBuilder(request);
|
||||
logger.debug("Obtained partial DetectIntentRequest.Builder from mapper for session: {}", sessionId);
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error(" Failed to map DTO to partial Protobuf request for session {}: {}", sessionId, e.getMessage());
|
||||
return Mono.error(new IllegalArgumentException("Invalid Dialogflow request input: " + e.getMessage()));
|
||||
}
|
||||
|
||||
SessionName sessionName = SessionName.newBuilder()
|
||||
.setProject(dialogflowCxProjectId)
|
||||
.setLocation(dialogflowCxLocation)
|
||||
.setAgent(dialogflowCxAgentId)
|
||||
.setSession(sessionId)
|
||||
.build();
|
||||
detectIntentRequestBuilder.setSession(sessionName.toString());
|
||||
logger.debug("Set session path {} on the request builder for session: {}", sessionName.toString(), sessionId);
|
||||
|
||||
QueryParameters.Builder queryParamsBuilder;
|
||||
if (detectIntentRequestBuilder.hasQueryParams()) {
|
||||
queryParamsBuilder = detectIntentRequestBuilder.getQueryParams().toBuilder();
|
||||
} else {
|
||||
queryParamsBuilder = QueryParameters.newBuilder();
|
||||
}
|
||||
|
||||
detectIntentRequestBuilder.setQueryParams(queryParamsBuilder.build());
|
||||
|
||||
// Build the final DetectIntentRequest Protobuf object
|
||||
DetectIntentRequest detectIntentRequest = detectIntentRequestBuilder.build();
|
||||
return Mono.fromCallable(() -> {
|
||||
logger.debug("Calling Dialogflow CX detectIntent for session: {}", sessionId);
|
||||
return sessionsClient.detectIntent(detectIntentRequest);
|
||||
})
|
||||
|
||||
.retryWhen(reactor.util.retry.Retry.backoff(3, java.time.Duration.ofSeconds(1))
|
||||
.filter(throwable -> {
|
||||
if (throwable instanceof ApiException apiException) {
|
||||
com.google.api.gax.rpc.StatusCode.Code code = apiException.getStatusCode().getCode();
|
||||
boolean isRetryable = code == com.google.api.gax.rpc.StatusCode.Code.INTERNAL ||
|
||||
code == com.google.api.gax.rpc.StatusCode.Code.UNAVAILABLE;
|
||||
if (isRetryable) {
|
||||
logger.warn("Retrying Dialogflow CX call for session {} due to transient error: {}", sessionId, code);
|
||||
}
|
||||
return isRetryable;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.doBeforeRetry(retrySignal -> logger.debug("Retry attempt #{} for session {}",
|
||||
retrySignal.totalRetries() + 1, sessionId))
|
||||
.onRetryExhaustedThrow((retrySpec, retrySignal) -> {
|
||||
logger.error("Dialogflow CX retries exhausted for session {}", sessionId);
|
||||
return retrySignal.failure();
|
||||
})
|
||||
)
|
||||
.onErrorMap(ApiException.class, e -> {
|
||||
String statusCode = e.getStatusCode().getCode().name();
|
||||
String message = e.getMessage();
|
||||
String detailedLog = message;
|
||||
|
||||
if (e.getCause() instanceof io.grpc.StatusRuntimeException grpcEx) {
|
||||
detailedLog = String.format("Status: %s, Message: %s, Trailers: %s",
|
||||
grpcEx.getStatus().getCode(),
|
||||
grpcEx.getStatus().getDescription(),
|
||||
grpcEx.getTrailers());
|
||||
}
|
||||
|
||||
logger.error("Dialogflow CX API error for session {}: details={}",
|
||||
sessionId, detailedLog, e);
|
||||
|
||||
return new DialogflowClientException(
|
||||
"Dialogflow CX API error: " + statusCode + " - " + message, e);
|
||||
})
|
||||
.map(dfResponse -> this.dialogflowResponseMapper.mapFromDialogflowResponse(dfResponse, sessionId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.base;
|
||||
|
||||
import com.example.exception.GeminiClientException;
|
||||
import com.google.genai.Client;
|
||||
import com.google.genai.errors.GenAiIOException;
|
||||
import com.google.genai.types.Content;
|
||||
import com.google.genai.types.GenerateContentConfig;
|
||||
import com.google.genai.types.GenerateContentResponse;
|
||||
import com.google.genai.types.Part;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Service for interacting with the Gemini API to generate content.
|
||||
* It encapsulates the low-level API calls, handling prompt configuration,
|
||||
* and error management to provide a clean and robust content generation interface.
|
||||
*/
|
||||
@Service
|
||||
public class GeminiClientService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(GeminiClientService.class);
|
||||
private final Client geminiClient;
|
||||
|
||||
public GeminiClientService(Client geminiClient) {
|
||||
this.geminiClient = geminiClient;
|
||||
}
|
||||
|
||||
public String generateContent(String prompt, Float temperature, Integer maxOutputTokens, String modelName,Float topP) throws GeminiClientException {
|
||||
try {
|
||||
Content content = Content.fromParts(Part.fromText(prompt));
|
||||
GenerateContentConfig config = GenerateContentConfig.builder()
|
||||
.temperature(temperature)
|
||||
.maxOutputTokens(maxOutputTokens)
|
||||
.topP(topP)
|
||||
.build();
|
||||
|
||||
logger.debug("Sending request to Gemini model '{}'", modelName);
|
||||
GenerateContentResponse response = geminiClient.models.generateContent(modelName, content, config);
|
||||
|
||||
if (response != null && response.text() != null) {
|
||||
return response.text();
|
||||
} else {
|
||||
logger.warn("Gemini returned no content or an unexpected response structure for model '{}'.", modelName);
|
||||
throw new GeminiClientException("No content generated or unexpected response structure.");
|
||||
}
|
||||
} catch (GenAiIOException e) {
|
||||
logger.error("Gemini API I/O error while calling model '{}': {}", modelName, e.getMessage(), e);
|
||||
throw new GeminiClientException("An API communication issue occurred: " + e.getMessage(), e);
|
||||
} catch (Exception e) {
|
||||
logger.error("An unexpected error occurred during Gemini content generation for model '{}': {}", modelName, e.getMessage(), e);
|
||||
throw new GeminiClientException("An unexpected issue occurred during content generation.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.base;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* Classifies a user's text input into a predefined category using a Gemini
|
||||
* model.
|
||||
* It analyzes the user's query in the context of a conversation history and any
|
||||
* relevant notifications to determine if the message is part of the ongoing
|
||||
* dialogue
|
||||
* or an interruption. The classification is used to route the request to the
|
||||
* appropriate handler (e.g., a standard conversational flow or a specific
|
||||
* notification processor).
|
||||
*/
|
||||
@Service
|
||||
public class MessageEntryFilter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageEntryFilter.class);
|
||||
private final GeminiClientService geminiService;
|
||||
|
||||
@Value("${messagefilter.geminimodel:gemini-2.0-flash-001}")
|
||||
private String geminiModelNameClassifier;
|
||||
|
||||
@Value("${messagefilter.temperature:0.1f}")
|
||||
private Float classifierTemperature;
|
||||
|
||||
@Value("${messagefilter.maxOutputTokens:10}")
|
||||
private Integer classifierMaxOutputTokens;
|
||||
|
||||
@Value("${messagefilter.topP:0.1f}")
|
||||
private Float classifierTopP;
|
||||
|
||||
@Value("${messagefilter.prompt:prompts/message_filter_prompt.txt}")
|
||||
private String promptFilePath;
|
||||
|
||||
public static final String CATEGORY_CONVERSATION = "CONVERSATION";
|
||||
public static final String CATEGORY_NOTIFICATION = "NOTIFICATION";
|
||||
public static final String CATEGORY_UNKNOWN = "UNKNOWN";
|
||||
public static final String CATEGORY_ERROR = "ERROR";
|
||||
|
||||
private String promptTemplate;
|
||||
|
||||
public MessageEntryFilter(GeminiClientService geminiService) {
|
||||
this.geminiService = Objects.requireNonNull(geminiService,
|
||||
"GeminiClientService cannot be null for MessageEntryFilter.");
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void loadPromptTemplate() {
|
||||
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(promptFilePath)) {
|
||||
if (inputStream == null) {
|
||||
throw new IOException("Resource not found: " + promptFilePath);
|
||||
}
|
||||
byte[] fileBytes = inputStream.readAllBytes();
|
||||
this.promptTemplate = new String(fileBytes, StandardCharsets.UTF_8);
|
||||
logger.info("Successfully loaded prompt template from '" + promptFilePath + "'.");
|
||||
} catch (IOException e) {
|
||||
logger.error("Failed to load prompt template from '" + promptFilePath
|
||||
+ "'. Please ensure the file exists. Error: " + e.getMessage());
|
||||
throw new IllegalStateException("Could not load prompt template.", e);
|
||||
}
|
||||
}
|
||||
public String classifyMessage(String queryInputText, String notificationsJson, String conversationJson) {
|
||||
if (queryInputText == null || queryInputText.isBlank()) {
|
||||
logger.warn("Query input text for classification is null or blank. Returning {}.", CATEGORY_UNKNOWN);
|
||||
return CATEGORY_UNKNOWN;
|
||||
}
|
||||
|
||||
String interruptingNotification = (notificationsJson != null && !notificationsJson.isBlank()) ?
|
||||
notificationsJson : "No interrupting notification.";
|
||||
|
||||
String conversationHistory = (conversationJson != null && !conversationJson.isBlank()) ?
|
||||
conversationJson : "No conversation history.";
|
||||
|
||||
String classificationPrompt = String.format(
|
||||
this.promptTemplate,
|
||||
conversationHistory,
|
||||
interruptingNotification,
|
||||
queryInputText
|
||||
);
|
||||
|
||||
logger.debug("Sending classification request to Gemini for input (first 100 chars): '{}'...",
|
||||
queryInputText.substring(0, Math.min(queryInputText.length(), 100)));
|
||||
|
||||
try {
|
||||
String geminiResponse = geminiService.generateContent(
|
||||
classificationPrompt,
|
||||
classifierTemperature,
|
||||
classifierMaxOutputTokens,
|
||||
geminiModelNameClassifier,
|
||||
classifierTopP
|
||||
);
|
||||
|
||||
String resultCategory = switch (geminiResponse != null ? geminiResponse.strip().toUpperCase() : "") {
|
||||
case CATEGORY_CONVERSATION -> {
|
||||
logger.info("Classified as {}.", CATEGORY_CONVERSATION);
|
||||
yield CATEGORY_CONVERSATION;
|
||||
}
|
||||
case CATEGORY_NOTIFICATION -> {
|
||||
logger.info("Classified as {}.", CATEGORY_NOTIFICATION);
|
||||
yield CATEGORY_NOTIFICATION;
|
||||
}
|
||||
default -> {
|
||||
logger.warn("Gemini returned an unrecognised classification or was null/blank: '{}'. Expected '{}' or '{}'. Returning {}.",
|
||||
geminiResponse, CATEGORY_CONVERSATION, CATEGORY_NOTIFICATION, CATEGORY_UNKNOWN);
|
||||
yield CATEGORY_UNKNOWN;
|
||||
}
|
||||
};
|
||||
return resultCategory;
|
||||
} catch (Exception e) {
|
||||
logger.error("An error occurred during Gemini content generation for message classification.", e);
|
||||
return CATEGORY_UNKNOWN;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.base;
|
||||
|
||||
import com.example.service.notification.MemoryStoreNotificationService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Resolves the conversational context of a user query by leveraging a large
|
||||
* language model (LLM). This service evaluates a user's question in the context
|
||||
* of a specific notification and conversation history, then decides if the
|
||||
* query
|
||||
* can be answered by the LLM or if it should be handled by a standard
|
||||
* Dialogflow agent.
|
||||
* The class loads an LLM prompt from an external file and dynamically
|
||||
* formats it with a user's query and other context to drive its decision-making
|
||||
* process.
|
||||
*/
|
||||
@Service
|
||||
public class NotificationContextResolver {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NotificationContextResolver.class);
|
||||
private final GeminiClientService geminiService;
|
||||
|
||||
@Value("${notificationcontext.geminimodel:gemini-2.0-flash-001}")
|
||||
private String geminiModelNameResolver;
|
||||
|
||||
@Value("${notificationcontext.temperature:0.1f}")
|
||||
private Float resolverTemperature;
|
||||
|
||||
@Value("${notificationcontext.maxOutputTokens:1024}")
|
||||
private Integer resolverMaxOutputTokens;
|
||||
|
||||
@Value("${notificationcontext.topP:0.1f}")
|
||||
private Float resolverTopP;
|
||||
|
||||
@Value("${notificationcontext.prompt:prompts/notification_context_resolver.txt}")
|
||||
private String promptFilePath;
|
||||
|
||||
public static final String CATEGORY_DIALOGFLOW = "DIALOGFLOW";
|
||||
|
||||
private String promptTemplate;
|
||||
|
||||
public NotificationContextResolver(GeminiClientService geminiService,
|
||||
MemoryStoreNotificationService memoryStoreNotificationService) {
|
||||
this.geminiService = Objects.requireNonNull(geminiService,
|
||||
"GeminiClientService cannot be null for NotificationContextResolver.");
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void loadPromptTemplate() {
|
||||
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(promptFilePath)) {
|
||||
if (inputStream == null) {
|
||||
throw new IOException("Resource not found: " + promptFilePath);
|
||||
}
|
||||
byte[] fileBytes = inputStream.readAllBytes();
|
||||
this.promptTemplate = new String(fileBytes, StandardCharsets.UTF_8);
|
||||
logger.info("Successfully loaded prompt template from '" + promptFilePath + "'.");
|
||||
} catch (IOException e) {
|
||||
logger.error("Failed to load prompt template from '" + promptFilePath
|
||||
+ "'. Please ensure the file exists. Error: " + e.getMessage());
|
||||
throw new IllegalStateException("Could not load prompt template.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String resolveContext(String queryInputText, String notificationsJson, String conversationJson,
|
||||
String metadata, String userId, String sessionId, String userPhoneNumber) {
|
||||
logger.debug("resolveContext -> queryInputText: {}, notificationsJson: {}, conversationJson: {}, metadata: {}",
|
||||
queryInputText, notificationsJson, conversationJson, metadata);
|
||||
if (queryInputText == null || queryInputText.isBlank()) {
|
||||
logger.warn("Query input text for context resolution is null or blank.", CATEGORY_DIALOGFLOW);
|
||||
return CATEGORY_DIALOGFLOW;
|
||||
}
|
||||
|
||||
String notificationContent = (notificationsJson != null && !notificationsJson.isBlank()) ? notificationsJson
|
||||
: "No metadata in notification.";
|
||||
|
||||
String conversationHistory = (conversationJson != null && !conversationJson.isBlank()) ? conversationJson
|
||||
: "No conversation history.";
|
||||
|
||||
String contextPrompt = String.format(
|
||||
this.promptTemplate,
|
||||
conversationHistory,
|
||||
notificationContent,
|
||||
metadata,
|
||||
queryInputText);
|
||||
|
||||
logger.debug("Sending context resolution request to Gemini for input (first 100 chars): '{}'...",
|
||||
queryInputText.substring(0, Math.min(queryInputText.length(), 100)));
|
||||
|
||||
try {
|
||||
String geminiResponse = geminiService.generateContent(
|
||||
contextPrompt,
|
||||
resolverTemperature,
|
||||
resolverMaxOutputTokens,
|
||||
geminiModelNameResolver,
|
||||
resolverTopP);
|
||||
|
||||
if (geminiResponse != null && !geminiResponse.isBlank()) {
|
||||
if (geminiResponse.trim().equalsIgnoreCase(CATEGORY_DIALOGFLOW)) {
|
||||
logger.debug("Resolved to {}. Input: '{}'", CATEGORY_DIALOGFLOW, queryInputText);
|
||||
return CATEGORY_DIALOGFLOW;
|
||||
} else {
|
||||
logger.debug("Resolved to a specific response. Input: '{}'", queryInputText);
|
||||
return geminiResponse;
|
||||
}
|
||||
} else {
|
||||
logger.warn("Gemini returned a null or blank response",
|
||||
queryInputText, CATEGORY_DIALOGFLOW);
|
||||
return CATEGORY_DIALOGFLOW;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("An error occurred during Gemini content generation for context resolution.", e);
|
||||
return CATEGORY_DIALOGFLOW;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.conversation;
|
||||
|
||||
import com.example.dto.dialogflow.conversation.ConversationMessageDTO;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.domain.Range;
|
||||
import org.springframework.data.redis.core.ReactiveRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
/**
|
||||
Service for managing the lifecycle and data hygiene of conversation histories stored in MemoryStore.
|
||||
It encapsulates the logic for pruning conversation logs to enforce data retention policies.
|
||||
Its primary function, pruneHistory, operates on a Redis Sorted Set (ZSET) for a given session,
|
||||
performing two main tasks:
|
||||
|
||||
1) removing all messages older than a configurable time limit (e.g., 30 days)
|
||||
based on their timestamp score,
|
||||
|
||||
2) trimming the remaining set to a maximum message count
|
||||
(e.g., 60) by removing the oldest entries, all within a reactive programming context.
|
||||
*/
|
||||
@Service
|
||||
public class ConversationHistoryService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ConversationHistoryService.class);
|
||||
|
||||
private static final String MESSAGES_KEY_PREFIX = "conversation:messages:";
|
||||
|
||||
private final ReactiveRedisTemplate<String, ConversationMessageDTO> messageRedisTemplate;
|
||||
|
||||
@Value("${conversation.context.message.limit:60}")
|
||||
private int messageLimit;
|
||||
|
||||
@Value("${conversation.context.days.limit:30}")
|
||||
private int daysLimit;
|
||||
|
||||
@Autowired
|
||||
public ConversationHistoryService(ReactiveRedisTemplate<String, ConversationMessageDTO> messageRedisTemplate) {
|
||||
this.messageRedisTemplate = messageRedisTemplate;
|
||||
}
|
||||
|
||||
public Mono<Void> pruneHistory(String sessionId) {
|
||||
logger.info("Pruning history for sessionId: {}", sessionId);
|
||||
String messagesKey = MESSAGES_KEY_PREFIX + sessionId;
|
||||
|
||||
Instant cutoff = Instant.now().minus(daysLimit, ChronoUnit.DAYS);
|
||||
Range<Double> scoreRange = Range.of(Range.Bound.inclusive(0d), Range.Bound.inclusive((double) cutoff.toEpochMilli()));
|
||||
logger.info("Removing messages older than {} for sessionId: {}", cutoff, sessionId);
|
||||
Mono<Long> removeByScore = messageRedisTemplate.opsForZSet().removeRangeByScore(messagesKey, scoreRange)
|
||||
.doOnSuccess(count -> logger.info("Removed {} old messages for sessionId: {}", count, sessionId));
|
||||
|
||||
|
||||
Mono<Long> trimToSize = messageRedisTemplate.opsForZSet().size(messagesKey)
|
||||
.flatMap(size -> {
|
||||
if (size > messageLimit) {
|
||||
logger.info("Current message count {} exceeds limit {} for sessionId: {}. Trimming...", size, messageLimit, sessionId);
|
||||
Range<Long> rankRange = Range.of(Range.Bound.inclusive(0L), Range.Bound.inclusive(size - messageLimit - 1));
|
||||
return messageRedisTemplate.opsForZSet().removeRange(messagesKey, rankRange)
|
||||
.doOnSuccess(count -> logger.info("Trimmed {} messages for sessionId: {}", count, sessionId));
|
||||
}
|
||||
return Mono.just(0L);
|
||||
});
|
||||
return removeByScore.then(trimToSize).then()
|
||||
.doOnSuccess(v -> logger.info("Successfully pruned history for sessionId: {}", sessionId))
|
||||
.doOnError(e -> logger.error("Error pruning history for sessionId: {}", sessionId, e));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.conversation;
|
||||
|
||||
import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
|
||||
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
||||
import com.example.dto.dialogflow.conversation.*;
|
||||
import com.example.dto.dialogflow.notification.EventInputDTO;
|
||||
import com.example.dto.dialogflow.notification.NotificationDTO;
|
||||
import com.example.mapper.conversation.ConversationEntryMapper;
|
||||
import com.example.mapper.conversation.ExternalConvRequestMapper;
|
||||
import com.example.mapper.messagefilter.ConversationContextMapper;
|
||||
import com.example.mapper.messagefilter.NotificationContextMapper;
|
||||
import com.example.service.base.DialogflowClientService;
|
||||
import com.example.service.base.MessageEntryFilter;
|
||||
import com.example.service.base.NotificationContextResolver;
|
||||
import com.example.service.notification.MemoryStoreNotificationService;
|
||||
import com.example.service.quickreplies.QuickRepliesManagerService;
|
||||
import com.example.service.llm.LlmResponseTunerService;
|
||||
import com.example.util.SessionIdGenerator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
Service acting as the central orchestrator for managing user conversations.
|
||||
It integrates Data Loss Prevention (DLP) for message obfuscation, multi-stage routing,
|
||||
hybrid AI logic, and a reactive write-back persistence layer for conversation history.
|
||||
|
||||
Routes traffic based on session context:
|
||||
If a 'pantallaContexto' (screen context) is present, it delegates to the QuickRepliesManagerService.
|
||||
Otherwise, it uses a Gemini-based MessageEntryFilter to classify the message against
|
||||
active notifications and history, routing to one of two main flows:
|
||||
a) Standard Conversation (proceedWithConversation): Handles regular dialogue,
|
||||
|
||||
managing 30-minute session timeouts and injecting conversation history parameter to Dialogflow.
|
||||
|
||||
b) Notifications (startNotificationConversation):
|
||||
It first asks a Gemini model (NotificationContextResolver) if it can answer the
|
||||
query. If yes, it saves the LLM's response and sends an 'LLM_RESPONSE_PROCESSED'
|
||||
event to Dialogflow. If no ("DIALOGFLOW"), it sends the user's original text
|
||||
to Dialogflow for intent matching.
|
||||
|
||||
All conversation turns (user, agent, and LLM) are persisted using a reactive write-back
|
||||
cache pattern, saving to Memorystore (Redis) first and then asynchronously to a
|
||||
Firestore subcollection data model (persistConversationTurn).
|
||||
*/
|
||||
@Service
|
||||
public class ConversationManagerService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ConversationManagerService.class);
|
||||
|
||||
private static final long SESSION_RESET_THRESHOLD_MINUTES = 30;
|
||||
private static final long SCREEN_CONTEXT_TIMEOUT_MINUTES = 10; // fix for the quick replies screen
|
||||
private static final String CONV_HISTORY_PARAM = "conversation_history";
|
||||
private static final String HISTORY_PARAM = "historial";
|
||||
private final ExternalConvRequestMapper externalRequestToDialogflowMapper;
|
||||
private final DialogflowClientService dialogflowServiceClient;
|
||||
private final FirestoreConversationService firestoreConversationService;
|
||||
private final MemoryStoreConversationService memoryStoreConversationService;
|
||||
private final QuickRepliesManagerService quickRepliesManagerService;
|
||||
private final MessageEntryFilter messageEntryFilter;
|
||||
private final MemoryStoreNotificationService memoryStoreNotificationService;
|
||||
private final NotificationContextMapper notificationContextMapper;
|
||||
private final ConversationContextMapper conversationContextMapper;
|
||||
private final DataLossPrevention dataLossPrevention;
|
||||
private final String dlpTemplateCompleteFlow;
|
||||
|
||||
private final NotificationContextResolver notificationContextResolver;
|
||||
private final LlmResponseTunerService llmResponseTunerService;
|
||||
private final ConversationEntryMapper conversationEntryMapper;
|
||||
|
||||
public ConversationManagerService(
|
||||
DialogflowClientService dialogflowServiceClient,
|
||||
FirestoreConversationService firestoreConversationService,
|
||||
MemoryStoreConversationService memoryStoreConversationService,
|
||||
ExternalConvRequestMapper externalRequestToDialogflowMapper,
|
||||
QuickRepliesManagerService quickRepliesManagerService,
|
||||
MessageEntryFilter messageEntryFilter,
|
||||
MemoryStoreNotificationService memoryStoreNotificationService,
|
||||
NotificationContextMapper notificationContextMapper,
|
||||
ConversationContextMapper conversationContextMapper,
|
||||
DataLossPrevention dataLossPrevention,
|
||||
NotificationContextResolver notificationContextResolver,
|
||||
LlmResponseTunerService llmResponseTunerService,
|
||||
ConversationEntryMapper conversationEntryMapper,
|
||||
@Value("${google.cloud.dlp.dlpTemplateCompleteFlow}") String dlpTemplateCompleteFlow) {
|
||||
this.dialogflowServiceClient = dialogflowServiceClient;
|
||||
this.firestoreConversationService = firestoreConversationService;
|
||||
this.memoryStoreConversationService = memoryStoreConversationService;
|
||||
this.externalRequestToDialogflowMapper = externalRequestToDialogflowMapper;
|
||||
this.quickRepliesManagerService = quickRepliesManagerService;
|
||||
this.messageEntryFilter = messageEntryFilter;
|
||||
this.memoryStoreNotificationService = memoryStoreNotificationService;
|
||||
this.notificationContextMapper = notificationContextMapper;
|
||||
this.conversationContextMapper = conversationContextMapper;
|
||||
this.dataLossPrevention = dataLossPrevention;
|
||||
this.dlpTemplateCompleteFlow = dlpTemplateCompleteFlow;
|
||||
this.notificationContextResolver = notificationContextResolver;
|
||||
this.llmResponseTunerService = llmResponseTunerService;
|
||||
this.conversationEntryMapper = conversationEntryMapper;
|
||||
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO> manageConversation(ExternalConvRequestDTO externalrequest) {
|
||||
return dataLossPrevention.getObfuscatedString(externalrequest.message(), dlpTemplateCompleteFlow)
|
||||
.flatMap(obfuscatedMessage -> {
|
||||
ExternalConvRequestDTO obfuscatedRequest = new ExternalConvRequestDTO(
|
||||
obfuscatedMessage,
|
||||
externalrequest.user(),
|
||||
externalrequest.channel(),
|
||||
externalrequest.tipo(),
|
||||
externalrequest.pantallaContexto());
|
||||
return memoryStoreConversationService.getSessionByTelefono(externalrequest.user().telefono())
|
||||
.flatMap(session -> {
|
||||
boolean isContextStale = false;
|
||||
if (session.lastModified() != null) {
|
||||
long minutesSinceLastUpdate = java.time.Duration.between(session.lastModified(), java.time.Instant.now()).toMinutes();
|
||||
if (minutesSinceLastUpdate > SCREEN_CONTEXT_TIMEOUT_MINUTES) {
|
||||
isContextStale = true;
|
||||
}
|
||||
}
|
||||
if (session != null && session.pantallaContexto() != null && !session.pantallaContexto().isBlank() && !isContextStale) {
|
||||
logger.info("Detected 'pantallaContexto' in session. Delegating to QuickRepliesManagerService.");
|
||||
return quickRepliesManagerService.manageConversation(obfuscatedRequest);
|
||||
}
|
||||
// Remove the old QR and continue as normal conversation.
|
||||
if (isContextStale && session.pantallaContexto() != null) {
|
||||
logger.info("Detected STALE 'pantallaContexto'. Ignoring and proceeding with normal flow.");
|
||||
}
|
||||
return continueManagingConversation(obfuscatedRequest);
|
||||
})
|
||||
.switchIfEmpty(continueManagingConversation(obfuscatedRequest));
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> continueManagingConversation(ExternalConvRequestDTO externalrequest) {
|
||||
final DetectIntentRequestDTO request;
|
||||
try {
|
||||
request = externalRequestToDialogflowMapper.mapExternalRequestToDetectIntentRequest(externalrequest);
|
||||
logger.debug("Successfully pre-mapped ExternalRequestDTO to DetectIntentRequestDTO");
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("Error during pre-mapping: {}", e.getMessage());
|
||||
return Mono.error(new IllegalArgumentException(
|
||||
"Failed to process external request due to mapping error: " + e.getMessage(), e));
|
||||
}
|
||||
|
||||
Map<String, Object> params = Optional.ofNullable(request.queryParams())
|
||||
.map(queryParamsDTO -> queryParamsDTO.parameters())
|
||||
.orElse(Collections.emptyMap());
|
||||
|
||||
Object telefonoObj = params.get("telefono");
|
||||
if (!(telefonoObj instanceof String) || ((String) telefonoObj).isBlank()) {
|
||||
logger.error("Critical error: parameter is missing, not a String, or blank after mapping.");
|
||||
return Mono.error(new IllegalStateException("Internal error: parameter is invalid."));
|
||||
}
|
||||
|
||||
String primaryPhoneNumber = (String) telefonoObj;
|
||||
String resolvedUserId = params.get("usuario_id") instanceof String ? (String) params.get("usuario_id") : null;
|
||||
String userMessageText = request.queryInput().text().text();
|
||||
final ConversationContext context = new ConversationContext(resolvedUserId, null, userMessageText, primaryPhoneNumber);
|
||||
|
||||
return continueConversationFlow(context, request);
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> continueConversationFlow(ConversationContext context,
|
||||
DetectIntentRequestDTO request) {
|
||||
final String userId = context.userId();
|
||||
final String userMessageText = context.userMessageText();
|
||||
final String userPhoneNumber = context.primaryPhoneNumber();
|
||||
|
||||
if (userPhoneNumber == null || userPhoneNumber.isBlank()) {
|
||||
logger.warn("No phone number provided in request. Cannot manage conversation session without it.");
|
||||
return Mono
|
||||
.error(new IllegalArgumentException("Phone number is required to manage conversation sessions."));
|
||||
}
|
||||
|
||||
logger.info("Primary Check (MemoryStore): Looking up session for phone number: {}", userPhoneNumber);
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.flatMap(session -> handleMessageClassification(context, request, session))
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
logger.info("No session found in MemoryStore. Performing full lookup to Firestore.");
|
||||
return fullLookupAndProcess(null, request, userId, userMessageText, userPhoneNumber);
|
||||
}))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("Overall error handling conversation in ConversationManagerService: {}",
|
||||
e.getMessage(), e);
|
||||
return Mono
|
||||
.error(new RuntimeException("Failed to process conversation due to an internal error.", e));
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> handleMessageClassification(ConversationContext context,
|
||||
DetectIntentRequestDTO request, ConversationSessionDTO session) {
|
||||
final String userPhoneNumber = context.primaryPhoneNumber();
|
||||
final String userMessageText = context.userMessageText();
|
||||
|
||||
return memoryStoreNotificationService.getNotificationIdForPhone(userPhoneNumber)
|
||||
.flatMap(notificationId -> memoryStoreNotificationService.getCachedNotificationSession(notificationId))
|
||||
.map(notificationSession -> notificationSession.notificaciones().stream()
|
||||
.filter(notification -> "active".equalsIgnoreCase(notification.status()))
|
||||
.max(java.util.Comparator.comparing(NotificationDTO::timestampCreacion))
|
||||
.orElse(null))
|
||||
.filter(Objects::nonNull)
|
||||
.flatMap((NotificationDTO notification) -> {
|
||||
return memoryStoreConversationService.getMessages(session.sessionId()).collectList()
|
||||
.map(conversationContextMapper::toTextFromMessages)
|
||||
.defaultIfEmpty("")
|
||||
.flatMap(conversationHistory -> {
|
||||
String notificationText = notificationContextMapper.toText(notification);
|
||||
String classification = messageEntryFilter.classifyMessage(userMessageText, notificationText,
|
||||
conversationHistory);
|
||||
if (MessageEntryFilter.CATEGORY_NOTIFICATION.equals(classification)) {
|
||||
return startNotificationConversation(context, request, notification);
|
||||
} else {
|
||||
return proceedWithConversation(context, request, session);
|
||||
}
|
||||
});
|
||||
})
|
||||
.switchIfEmpty(proceedWithConversation(context, request, session));
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> proceedWithConversation(ConversationContext context,
|
||||
DetectIntentRequestDTO request, ConversationSessionDTO session) {
|
||||
Instant now = Instant.now();
|
||||
if (Duration.between(session.lastModified(), now).toMinutes() < SESSION_RESET_THRESHOLD_MINUTES) {
|
||||
logger.info("Recent Session Found: Session {} is within the 30-minute threshold. Proceeding to Dialogflow.",
|
||||
session.sessionId());
|
||||
return processDialogflowRequest(session, request, context.userId(), context.userMessageText(),
|
||||
context.primaryPhoneNumber(), false);
|
||||
} else {
|
||||
|
||||
|
||||
logger.info(
|
||||
"Old Session Found: Session {} is older than the 30-minute threshold.",
|
||||
session.sessionId());
|
||||
// Generar un nuevo ID de sesión
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.info("Creating new session {} from old session {} due to timeout.", newSessionId, session.sessionId());
|
||||
|
||||
// Crear un nuevo DTO de sesión basado en la antigua, pero con el nuevo ID
|
||||
ConversationSessionDTO newSession = ConversationSessionDTO.create(newSessionId, context.userId(), context.primaryPhoneNumber());
|
||||
|
||||
return memoryStoreConversationService.getMessages(session.sessionId())
|
||||
.collectList()
|
||||
// Adding use the TextWithLimits to truncate according to business rule 30 days/60 messages
|
||||
.map(messages -> conversationContextMapper.toTextWithLimits(session, messages))
|
||||
.defaultIfEmpty("")
|
||||
.flatMap(conversationHistory -> {
|
||||
// Inject historial (max 60 msgs / 30 días / 50KB)
|
||||
DetectIntentRequestDTO newRequest = request.withParameter(CONV_HISTORY_PARAM, conversationHistory);
|
||||
return processDialogflowRequest(newSession, newRequest, context.userId(), context.userMessageText(),
|
||||
context.primaryPhoneNumber(), false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> fullLookupAndProcess(ConversationSessionDTO oldSession,
|
||||
DetectIntentRequestDTO request, String userId, String userMessageText, String userPhoneNumber) {
|
||||
return firestoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.flatMap(session -> firestoreConversationService.getMessages(session.sessionId()).collectList()
|
||||
.map(conversationContextMapper::toTextFromMessages)
|
||||
.defaultIfEmpty("")
|
||||
.flatMap(conversationHistory -> {
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.info("Creating new session {} after full lookup.", newSessionId);
|
||||
ConversationSessionDTO newSession = ConversationSessionDTO.create(newSessionId, userId,
|
||||
userPhoneNumber);
|
||||
DetectIntentRequestDTO newRequest = request.withParameter(CONV_HISTORY_PARAM, conversationHistory);
|
||||
return processDialogflowRequest(newSession, newRequest, userId, userMessageText, userPhoneNumber,
|
||||
true);
|
||||
}))
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.info("Creating new session {} after full lookup.", newSessionId);
|
||||
ConversationSessionDTO newSession = ConversationSessionDTO.create(newSessionId, userId,
|
||||
userPhoneNumber);
|
||||
return processDialogflowRequest(newSession, request, userId, userMessageText, userPhoneNumber,
|
||||
true);
|
||||
}));
|
||||
}
|
||||
|
||||
private Mono<DetectIntentResponseDTO> processDialogflowRequest(ConversationSessionDTO session,
|
||||
DetectIntentRequestDTO request, String userId, String userMessageText, String userPhoneNumber,
|
||||
boolean newSession) {
|
||||
final String finalSessionId = session.sessionId();
|
||||
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(userMessageText);
|
||||
|
||||
return this.persistConversationTurn(session, conversationEntryMapper.toConversationMessageDTO(userEntry))
|
||||
.doOnSuccess(v -> logger.debug(
|
||||
"User entry successfully persisted for session {}. Proceeding to Dialogflow...",
|
||||
finalSessionId))
|
||||
.doOnError(e -> logger.error("Error during user entry persistence for session {}: {}", finalSessionId,
|
||||
e.getMessage(), e))
|
||||
.then(Mono.defer(() -> dialogflowServiceClient.detectIntent(finalSessionId, request)
|
||||
.flatMap(response -> {
|
||||
logger.debug(
|
||||
"RTest eceived Dialogflow CX response for session {}. Initiating agent response persistence.",
|
||||
finalSessionId);
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO.forAgent(response.queryResult());
|
||||
return persistConversationTurn(session, conversationEntryMapper.toConversationMessageDTO(agentEntry))
|
||||
.thenReturn(response);
|
||||
})
|
||||
.doOnError(
|
||||
error -> logger.error("Overall error during conversation management for session {}: {}",
|
||||
finalSessionId, error.getMessage(), error))));
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO> startNotificationConversation(ConversationContext context,
|
||||
DetectIntentRequestDTO request, NotificationDTO notification) {
|
||||
final String userId = context.userId();
|
||||
final String userMessageText = context.userMessageText();
|
||||
final String userPhoneNumber = context.primaryPhoneNumber();
|
||||
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.warn("No existing conversation session found for notification reply on phone {}. This is unexpected. Creating new session: {}",
|
||||
userPhoneNumber, newSessionId);
|
||||
return Mono.just(ConversationSessionDTO.create(newSessionId, userId, userPhoneNumber));
|
||||
}))
|
||||
.flatMap(session -> {
|
||||
final String sessionId = session.sessionId();
|
||||
return memoryStoreConversationService.getMessages(sessionId).collectList()
|
||||
.map(conversationContextMapper::toTextFromMessages)
|
||||
.defaultIfEmpty("")
|
||||
.flatMap(conversationHistory -> {
|
||||
String notificationText = notificationContextMapper.toText(notification);
|
||||
|
||||
Map<String, Object> filteredParams = notification.parametros().entrySet().stream()
|
||||
.filter(entry -> entry.getKey().startsWith("notification_po_"))
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
|
||||
String resolvedContext = notificationContextResolver.resolveContext(userMessageText,
|
||||
notificationText, conversationHistory, filteredParams.toString(), userId, sessionId,
|
||||
userPhoneNumber);
|
||||
if (!resolvedContext.trim().toUpperCase().contains(NotificationContextResolver.CATEGORY_DIALOGFLOW)) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
llmResponseTunerService.setValue(uuid, resolvedContext).subscribe();
|
||||
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(userMessageText,
|
||||
notification.parametros());
|
||||
ConversationEntryDTO llmEntry = ConversationEntryDTO.forLlmConversation(resolvedContext,
|
||||
notification.parametros());
|
||||
|
||||
return persistConversationTurn(session, conversationEntryMapper.toConversationMessageDTO(userEntry))
|
||||
.then(persistConversationTurn(session, conversationEntryMapper.toConversationMessageDTO(llmEntry)))
|
||||
.then(Mono.defer(() -> {
|
||||
EventInputDTO eventInput = new EventInputDTO("LLM_RESPONSE_PROCESSED");
|
||||
QueryInputDTO queryInput = new QueryInputDTO(null, eventInput,
|
||||
request.queryInput().languageCode());
|
||||
DetectIntentRequestDTO newRequest = new DetectIntentRequestDTO(queryInput,
|
||||
request.queryParams())
|
||||
.withParameter("llm_reponse_uuid", uuid);
|
||||
|
||||
return dialogflowServiceClient.detectIntent(sessionId, newRequest)
|
||||
.flatMap(response -> {
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO
|
||||
.forAgent(response.queryResult());
|
||||
return persistConversationTurn(session, conversationEntryMapper.toConversationMessageDTO(agentEntry))
|
||||
.thenReturn(response);
|
||||
});
|
||||
}));
|
||||
} else {
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(userMessageText,
|
||||
notification.parametros());
|
||||
|
||||
DetectIntentRequestDTO finalRequest;
|
||||
Instant now = Instant.now();
|
||||
if (Duration.between(session.lastModified(), now).toMinutes() < SESSION_RESET_THRESHOLD_MINUTES) {
|
||||
finalRequest = request.withParameters(notification.parametros());
|
||||
} else {
|
||||
finalRequest = request.withParameter(CONV_HISTORY_PARAM, conversationHistory)
|
||||
.withParameters(notification.parametros());
|
||||
}
|
||||
return persistConversationTurn(session, conversationEntryMapper.toConversationMessageDTO(userEntry))
|
||||
.then(dialogflowServiceClient.detectIntent(sessionId, finalRequest)
|
||||
.flatMap(response -> {
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO
|
||||
.forAgent(response.queryResult());
|
||||
return persistConversationTurn(session, conversationEntryMapper.toConversationMessageDTO(agentEntry))
|
||||
.thenReturn(response);
|
||||
}));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Void> persistConversationTurn(ConversationSessionDTO session, ConversationMessageDTO message) {
|
||||
logger.debug("Starting Write-Back persistence for session {}. Type: {}. Writing to Redis first.", session.sessionId(),
|
||||
message.type().name());
|
||||
ConversationSessionDTO updatedSession = session.withLastMessage(message.text());
|
||||
return memoryStoreConversationService.saveSession(updatedSession)
|
||||
.then(memoryStoreConversationService.saveMessage(session.sessionId(), message))
|
||||
.doOnSuccess(v -> logger.info(
|
||||
"Entry saved to Redis for session {}. Type: {}. Kicking off async Firestore write-back.",
|
||||
session.sessionId(), message.type().name()))
|
||||
.then(firestoreConversationService.saveSession(updatedSession)
|
||||
.then(firestoreConversationService.saveMessage(session.sessionId(), message))
|
||||
.doOnSuccess(fsVoid -> logger.debug(
|
||||
"Asynchronously (Write-Back): Entry successfully saved to Firestore for session {}. Type: {}.",
|
||||
session.sessionId(), message.type().name()))
|
||||
.doOnError(fsError -> logger.error(
|
||||
"Asynchronously (Write-Back): Failed to save entry to Firestore for session {}. Type: {}: {}",
|
||||
session.sessionId(), message.type().name(), fsError.getMessage(), fsError)))
|
||||
.doOnError(e -> logger.error("Error during primary Redis write for session {}. Type: {}: {}", session.sessionId(),
|
||||
message.type().name(), e.getMessage(), e));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.conversation;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface DataLossPrevention {
|
||||
Mono<String> getObfuscatedString(String textToInspect, String templateId);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.conversation;
|
||||
|
||||
import com.google.api.core.ApiFuture;
|
||||
import com.google.api.core.ApiFutureCallback;
|
||||
import com.google.api.core.ApiFutures;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.google.cloud.dlp.v2.DlpServiceClient;
|
||||
import com.google.privacy.dlp.v2.ByteContentItem;
|
||||
import com.google.privacy.dlp.v2.ContentItem;
|
||||
import com.google.privacy.dlp.v2.InspectConfig;
|
||||
import com.google.privacy.dlp.v2.InspectContentRequest;
|
||||
import com.google.privacy.dlp.v2.InspectContentResponse;
|
||||
import com.google.privacy.dlp.v2.Likelihood;
|
||||
import com.google.privacy.dlp.v2.LocationName;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.example.util.TextObfuscator;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
Implements a data loss prevention service by integrating with the
|
||||
Google Cloud Data Loss Prevention (DLP) API. This service is responsible for
|
||||
scanning a given text input to identify and obfuscate sensitive information based on
|
||||
a specified DLP template. If the DLP API detects sensitive findings, the
|
||||
original text is obfuscated to protect user data; otherwise, the original
|
||||
text is returned.
|
||||
*/
|
||||
@Service
|
||||
public class DataLossPreventionImpl implements DataLossPrevention {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DataLossPreventionImpl.class);
|
||||
|
||||
private final String projectId;
|
||||
private final String location;
|
||||
private final DlpServiceClient dlpServiceClient;
|
||||
|
||||
public DataLossPreventionImpl(
|
||||
DlpServiceClient dlpServiceClient,
|
||||
@Value("${google.cloud.project}") String projectId,
|
||||
@Value("${google.cloud.location}") String location) {
|
||||
this.dlpServiceClient = dlpServiceClient;
|
||||
this.projectId = projectId;
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<String> getObfuscatedString(String text, String templateId) {
|
||||
ByteContentItem byteContentItem = ByteContentItem.newBuilder()
|
||||
.setType(ByteContentItem.BytesType.TEXT_UTF8)
|
||||
.setData(ByteString.copyFromUtf8(text))
|
||||
.build();
|
||||
ContentItem contentItem = ContentItem.newBuilder().setByteItem(byteContentItem).build();
|
||||
|
||||
Likelihood minLikelihood = Likelihood.VERY_UNLIKELY;
|
||||
|
||||
InspectConfig.FindingLimits findingLimits = InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(0)
|
||||
.build();
|
||||
|
||||
InspectConfig inspectConfig = InspectConfig.newBuilder()
|
||||
.setMinLikelihood(minLikelihood)
|
||||
.setLimits(findingLimits)
|
||||
.setIncludeQuote(true)
|
||||
.build();
|
||||
|
||||
String inspectTemplateName = String.format("projects/%s/locations/%s/inspectTemplates/%s", projectId, location,
|
||||
templateId);
|
||||
InspectContentRequest request = InspectContentRequest.newBuilder()
|
||||
.setParent(LocationName.of(projectId, location).toString())
|
||||
.setInspectTemplateName(inspectTemplateName)
|
||||
.setInspectConfig(inspectConfig)
|
||||
.setItem(contentItem)
|
||||
.build();
|
||||
|
||||
ApiFuture<InspectContentResponse> futureResponse = dlpServiceClient.inspectContentCallable()
|
||||
.futureCall(request);
|
||||
|
||||
return Mono.<InspectContentResponse>create(
|
||||
sink -> ApiFutures.addCallback(
|
||||
futureResponse,
|
||||
new ApiFutureCallback<>() {
|
||||
@Override
|
||||
public void onFailure(Throwable t) {
|
||||
sink.error(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSuccess(InspectContentResponse result) {
|
||||
sink.success(result);
|
||||
}
|
||||
},
|
||||
Runnable::run))
|
||||
.map(response -> {
|
||||
logger.info("DLP {} Findings: {}", templateId, response.getResult().getFindingsCount());
|
||||
return response.getResult().getFindingsCount() > 0
|
||||
? TextObfuscator.obfuscate(response, text)
|
||||
: text;
|
||||
}).onErrorResume(e -> {
|
||||
e.printStackTrace();
|
||||
return Mono.just(text);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.conversation;
|
||||
|
||||
import com.example.dto.dialogflow.conversation.ConversationMessageDTO;
|
||||
import com.example.dto.dialogflow.conversation.ConversationSessionDTO;
|
||||
import com.example.exception.FirestorePersistenceException;
|
||||
import com.example.mapper.conversation.ConversationMessageMapper;
|
||||
import com.example.mapper.conversation.FirestoreConversationMapper;
|
||||
import com.example.repository.FirestoreBaseRepository;
|
||||
import com.google.cloud.firestore.DocumentReference;
|
||||
import com.google.cloud.firestore.DocumentSnapshot;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
@Service
|
||||
public class FirestoreConversationService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FirestoreConversationService.class);
|
||||
private static final String CONVERSATION_COLLECTION_PATH_FORMAT = "artifacts/%s/conversations";
|
||||
private static final String MESSAGES_SUBCOLLECTION = "mensajes";
|
||||
private final FirestoreBaseRepository firestoreBaseRepository;
|
||||
private final FirestoreConversationMapper firestoreConversationMapper;
|
||||
private final ConversationMessageMapper conversationMessageMapper;
|
||||
|
||||
public FirestoreConversationService(FirestoreBaseRepository firestoreBaseRepository, FirestoreConversationMapper firestoreConversationMapper, ConversationMessageMapper conversationMessageMapper) {
|
||||
this.firestoreBaseRepository = firestoreBaseRepository;
|
||||
this.firestoreConversationMapper = firestoreConversationMapper;
|
||||
this.conversationMessageMapper = conversationMessageMapper;
|
||||
}
|
||||
|
||||
public Mono<Void> saveSession(ConversationSessionDTO session) {
|
||||
return Mono.fromRunnable(() -> {
|
||||
DocumentReference sessionDocRef = getSessionDocumentReference(session.sessionId());
|
||||
try {
|
||||
firestoreBaseRepository.setDocument(sessionDocRef, firestoreConversationMapper.createSessionMap(session));
|
||||
} catch (ExecutionException | InterruptedException e) {
|
||||
handleException(e, session.sessionId());
|
||||
}
|
||||
}).subscribeOn(Schedulers.boundedElastic()).then();
|
||||
}
|
||||
|
||||
public Mono<Void> saveMessage(String sessionId, ConversationMessageDTO message) {
|
||||
return Mono.fromRunnable(() -> {
|
||||
DocumentReference messageDocRef = getSessionDocumentReference(sessionId).collection(MESSAGES_SUBCOLLECTION).document();
|
||||
try {
|
||||
firestoreBaseRepository.setDocument(messageDocRef, conversationMessageMapper.toMap(message));
|
||||
} catch (ExecutionException | InterruptedException e) {
|
||||
handleException(e, sessionId);
|
||||
}
|
||||
}).subscribeOn(Schedulers.boundedElastic()).then();
|
||||
}
|
||||
|
||||
public Flux<ConversationMessageDTO> getMessages(String sessionId) {
|
||||
String messagesPath = getConversationCollectionPath() + "/" + sessionId + "/" + MESSAGES_SUBCOLLECTION;
|
||||
return firestoreBaseRepository.getDocuments(messagesPath)
|
||||
.map(documentSnapshot -> {
|
||||
if (documentSnapshot != null && documentSnapshot.exists()) {
|
||||
return conversationMessageMapper.fromMap(documentSnapshot.getData());
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Objects::nonNull);
|
||||
}
|
||||
|
||||
public Mono<ConversationSessionDTO> getConversationSession(String sessionId) {
|
||||
logger.info("Attempting to retrieve conversation session for session {}.", sessionId);
|
||||
return Mono.fromCallable(() -> {
|
||||
DocumentReference sessionDocRef = getSessionDocumentReference(sessionId);
|
||||
try {
|
||||
DocumentSnapshot documentSnapshot = firestoreBaseRepository.getDocumentSnapshot(sessionDocRef);
|
||||
if (documentSnapshot != null && documentSnapshot.exists()) {
|
||||
ConversationSessionDTO sessionDTO = firestoreConversationMapper.mapFirestoreDocumentToConversationSessionDTO(documentSnapshot);
|
||||
logger.info("Successfully retrieved and mapped conversation session for session {}.", sessionId);
|
||||
return sessionDTO;
|
||||
}
|
||||
logger.info("Conversation session not found for session {}.", sessionId);
|
||||
return null;
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
handleException(e, sessionId);
|
||||
return null;
|
||||
}
|
||||
}).subscribeOn(Schedulers.boundedElastic());
|
||||
}
|
||||
|
||||
public Mono<ConversationSessionDTO> getSessionByTelefono(String userPhoneNumber) {
|
||||
return firestoreBaseRepository.getDocumentsByField(getConversationCollectionPath(), "telefono", userPhoneNumber)
|
||||
.map(documentSnapshot -> {
|
||||
if (documentSnapshot != null && documentSnapshot.exists()) {
|
||||
ConversationSessionDTO sessionDTO = firestoreConversationMapper.mapFirestoreDocumentToConversationSessionDTO(documentSnapshot);
|
||||
logger.info("Successfully retrieved and mapped conversation session for session {}.", sessionDTO.sessionId());
|
||||
return sessionDTO;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public Mono<Void> deleteSession(String sessionId) {
|
||||
logger.info("Attempting to delete conversation session for session {}.", sessionId);
|
||||
return Mono.fromRunnable(() -> {
|
||||
DocumentReference sessionDocRef = getSessionDocumentReference(sessionId);
|
||||
try {
|
||||
firestoreBaseRepository.deleteDocumentAndSubcollections(sessionDocRef, MESSAGES_SUBCOLLECTION);
|
||||
logger.info("Successfully deleted conversation session for session {}.", sessionId);
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
handleException(e, sessionId);
|
||||
}
|
||||
}).subscribeOn(Schedulers.boundedElastic()).then();
|
||||
}
|
||||
|
||||
private String getConversationCollectionPath() {
|
||||
return String.format(CONVERSATION_COLLECTION_PATH_FORMAT, firestoreBaseRepository.getAppId());
|
||||
}
|
||||
|
||||
private DocumentReference getSessionDocumentReference(String sessionId) {
|
||||
String collectionPath = getConversationCollectionPath();
|
||||
return firestoreBaseRepository.getDocumentReference(collectionPath, sessionId);
|
||||
}
|
||||
|
||||
private void handleException(Exception e, String sessionId) {
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
logger.error("Error processing Firestore operation for session {}: {}", sessionId, e.getMessage(), e);
|
||||
throw new FirestorePersistenceException("Failed to process Firestore operation for session " + sessionId, e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.conversation;
|
||||
|
||||
import com.example.dto.dialogflow.conversation.ConversationMessageDTO;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Range;
|
||||
import org.springframework.data.redis.core.ReactiveRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.example.dto.dialogflow.conversation.ConversationSessionDTO;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import java.time.Duration;
|
||||
|
||||
|
||||
@Service
|
||||
public class MemoryStoreConversationService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MemoryStoreConversationService.class);
|
||||
private static final String SESSION_KEY_PREFIX = "conversation:session:";
|
||||
private static final String PHONE_TO_SESSION_KEY_PREFIX = "conversation:phone_to_session:";
|
||||
private static final String MESSAGES_KEY_PREFIX = "conversation:messages:";
|
||||
private static final Duration SESSION_TTL = Duration.ofDays(30);
|
||||
private final ReactiveRedisTemplate<String, ConversationSessionDTO> redisTemplate;
|
||||
private final ReactiveRedisTemplate<String, String> stringRedisTemplate;
|
||||
private final ReactiveRedisTemplate<String, ConversationMessageDTO> messageRedisTemplate;
|
||||
private final ConversationHistoryService conversationHistoryService;
|
||||
|
||||
|
||||
@Autowired
|
||||
public MemoryStoreConversationService(
|
||||
ReactiveRedisTemplate<String, ConversationSessionDTO> redisTemplate,
|
||||
ReactiveRedisTemplate<String, String> stringRedisTemplate,
|
||||
ReactiveRedisTemplate<String, ConversationMessageDTO> messageRedisTemplate,
|
||||
ConversationHistoryService conversationHistoryService) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
this.messageRedisTemplate = messageRedisTemplate;
|
||||
this.conversationHistoryService = conversationHistoryService;
|
||||
}
|
||||
|
||||
|
||||
public Mono<Void> saveMessage(String sessionId, ConversationMessageDTO message) {
|
||||
String messagesKey = MESSAGES_KEY_PREFIX + sessionId;
|
||||
double score = message.timestamp().toEpochMilli();
|
||||
return messageRedisTemplate.opsForZSet().add(messagesKey, message, score)
|
||||
.then(conversationHistoryService.pruneHistory(sessionId));
|
||||
}
|
||||
|
||||
public Mono<Void> saveSession(ConversationSessionDTO session) {
|
||||
String sessionKey = SESSION_KEY_PREFIX + session.sessionId();
|
||||
String phoneToSessionKey = PHONE_TO_SESSION_KEY_PREFIX + session.telefono();
|
||||
return redisTemplate.opsForValue().set(sessionKey, session, SESSION_TTL)
|
||||
.then(stringRedisTemplate.opsForValue().set(phoneToSessionKey, session.sessionId(), SESSION_TTL))
|
||||
.then();
|
||||
}
|
||||
|
||||
public Flux<ConversationMessageDTO> getMessages(String sessionId) {
|
||||
String messagesKey = MESSAGES_KEY_PREFIX + sessionId;
|
||||
return messageRedisTemplate.opsForZSet().range(messagesKey, Range.of(Range.Bound.inclusive(0L), Range.Bound.inclusive(-1L)));
|
||||
}
|
||||
|
||||
public Mono<ConversationSessionDTO> getSessionByTelefono(String telefono) {
|
||||
if (telefono == null || telefono.isBlank()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
String phoneToSessionKey = PHONE_TO_SESSION_KEY_PREFIX + telefono;
|
||||
return stringRedisTemplate.opsForValue().get(phoneToSessionKey)
|
||||
.flatMap(sessionId -> redisTemplate.opsForValue().get(SESSION_KEY_PREFIX + sessionId))
|
||||
.doOnSuccess(session -> {
|
||||
if (session != null) {
|
||||
logger.info("Successfully retrieved session by phone number");
|
||||
} else {
|
||||
logger.info("No session found in Redis for phone number.");
|
||||
}
|
||||
})
|
||||
.doOnError(e -> logger.error("Error retrieving session by phone number: {}", e));
|
||||
}
|
||||
|
||||
public Mono<Void> updateSession(ConversationSessionDTO session) {
|
||||
String sessionKey = SESSION_KEY_PREFIX + session.sessionId();
|
||||
logger.info("Attempting to update session {} in Memorystore.", session.sessionId());
|
||||
return redisTemplate.opsForValue().set(sessionKey, session).then();
|
||||
}
|
||||
|
||||
public Mono<Void> deleteSession(String sessionId) {
|
||||
String sessionKey = SESSION_KEY_PREFIX + sessionId;
|
||||
String messagesKey = MESSAGES_KEY_PREFIX + sessionId;
|
||||
logger.info("Deleting session {} from Memorystore.", sessionId);
|
||||
|
||||
return redisTemplate.opsForValue().get(sessionKey)
|
||||
.flatMap(session -> {
|
||||
if (session != null && session.telefono() != null) {
|
||||
String phoneToSessionKey = PHONE_TO_SESSION_KEY_PREFIX + session.telefono();
|
||||
return redisTemplate.opsForValue().delete(sessionKey)
|
||||
.then(stringRedisTemplate.opsForValue().delete(phoneToSessionKey))
|
||||
.then(messageRedisTemplate.delete(messagesKey));
|
||||
} else {
|
||||
return redisTemplate.opsForValue().delete(sessionKey)
|
||||
.then(messageRedisTemplate.delete(messagesKey));
|
||||
}
|
||||
}).then();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.llm;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface LlmResponseTunerService {
|
||||
Mono<String> getValue(String key);
|
||||
Mono<Void> setValue(String key, String value);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.llm;
|
||||
|
||||
import java.time.Duration;
|
||||
import org.springframework.data.redis.core.ReactiveRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class LlmResponseTunerServiceImpl implements LlmResponseTunerService {
|
||||
|
||||
private final ReactiveRedisTemplate<String, String> reactiveStringRedisTemplate;
|
||||
private final String llmPreResponseCollectionName = "llm-pre-response:";
|
||||
private final Duration ttl = Duration.ofHours(1);
|
||||
|
||||
public LlmResponseTunerServiceImpl(ReactiveRedisTemplate<String, String> reactiveStringRedisTemplate) {
|
||||
this.reactiveStringRedisTemplate = reactiveStringRedisTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<String> getValue(String key) {
|
||||
return reactiveStringRedisTemplate.opsForValue().get(llmPreResponseCollectionName + key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> setValue(String key, String value) {
|
||||
return reactiveStringRedisTemplate.opsForValue().set(llmPreResponseCollectionName + key, value, ttl).then();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.notification;
|
||||
|
||||
import com.example.dto.dialogflow.notification.NotificationDTO;
|
||||
import com.example.exception.FirestorePersistenceException;
|
||||
import com.example.mapper.notification.FirestoreNotificationMapper;
|
||||
import com.example.repository.FirestoreBaseRepository;
|
||||
import com.google.cloud.Timestamp;
|
||||
import com.google.cloud.firestore.DocumentReference;
|
||||
import com.google.cloud.firestore.FieldValue;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
@Service
|
||||
public class FirestoreNotificationService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FirestoreNotificationService.class);
|
||||
private static final String NOTIFICATION_COLLECTION_PATH_FORMAT = "artifacts/%s/notifications";
|
||||
private static final String FIELD_MESSAGES = "notificaciones";
|
||||
private static final String FIELD_LAST_UPDATED = "ultimaActualizacion";
|
||||
private static final String FIELD_PHONE_NUMBER = "telefono";
|
||||
private static final String FIELD_NOTIFICATION_ID = "sessionId";
|
||||
|
||||
private final FirestoreBaseRepository firestoreBaseRepository;
|
||||
private final FirestoreNotificationMapper firestoreNotificationMapper;
|
||||
|
||||
public FirestoreNotificationService(
|
||||
FirestoreBaseRepository firestoreBaseRepository,
|
||||
FirestoreNotificationMapper firestoreNotificationMapper,
|
||||
MemoryStoreNotificationService memoryStoreNotificationService) {
|
||||
this.firestoreBaseRepository = firestoreBaseRepository;
|
||||
this.firestoreNotificationMapper = firestoreNotificationMapper;
|
||||
}
|
||||
|
||||
public Mono<Void> saveOrAppendNotificationEntry(NotificationDTO newEntry) {
|
||||
return Mono.fromRunnable(
|
||||
() -> {
|
||||
String phoneNumber = newEntry.telefono();
|
||||
if (phoneNumber == null || phoneNumber.isBlank()) {
|
||||
throw new IllegalArgumentException(
|
||||
"Phone number is required to manage notification entries.");
|
||||
}
|
||||
// Use the phone number as the document ID for the session.
|
||||
String notificationSessionId = phoneNumber;
|
||||
|
||||
// Synchronize on the notification session ID to prevent race conditions when
|
||||
// creating a new session.
|
||||
synchronized (notificationSessionId.intern()) {
|
||||
DocumentReference notificationDocRef = getNotificationDocumentReference(notificationSessionId);
|
||||
Map<String, Object> entryMap = firestoreNotificationMapper.mapNotificationDTOToMap(newEntry);
|
||||
try {
|
||||
// Check if the session document exists.
|
||||
boolean docExists = firestoreBaseRepository.documentExists(notificationDocRef);
|
||||
|
||||
if (docExists) {
|
||||
// If the document exists, append the new entry to the 'notificaciones' array.
|
||||
Map<String, Object> updates = Map.of(
|
||||
FIELD_MESSAGES, FieldValue.arrayUnion(entryMap),
|
||||
FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
|
||||
firestoreBaseRepository.updateDocument(notificationDocRef, updates);
|
||||
logger.info(
|
||||
"Successfully appended new entry to notification session {} in Firestore.",
|
||||
notificationSessionId);
|
||||
} else {
|
||||
// If the document does not exist, create a new session document.
|
||||
Map<String, Object> newSessionData = Map.of(
|
||||
FIELD_NOTIFICATION_ID,
|
||||
notificationSessionId,
|
||||
FIELD_PHONE_NUMBER,
|
||||
phoneNumber,
|
||||
"fechaCreacion",
|
||||
Timestamp.of(java.util.Date.from(Instant.now())),
|
||||
FIELD_LAST_UPDATED,
|
||||
Timestamp.of(java.util.Date.from(Instant.now())),
|
||||
FIELD_MESSAGES,
|
||||
Collections.singletonList(entryMap));
|
||||
firestoreBaseRepository.setDocument(notificationDocRef, newSessionData);
|
||||
logger.info(
|
||||
"Successfully created a new notification session {} in Firestore.",
|
||||
notificationSessionId);
|
||||
}
|
||||
} catch (ExecutionException e) {
|
||||
logger.error(
|
||||
"Error saving notification to Firestore for phone: {}",
|
||||
e.getMessage(),
|
||||
e);
|
||||
throw new FirestorePersistenceException(
|
||||
"Failed to save notification to Firestore for phone ", e);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
logger.error(
|
||||
"Thread interrupted while saving notification to Firestore for phone {}: {}",
|
||||
phoneNumber,
|
||||
e.getMessage(),
|
||||
e);
|
||||
throw new FirestorePersistenceException(
|
||||
"Saving notification was interrupted for phone ", e);
|
||||
}
|
||||
}
|
||||
})
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.then();
|
||||
}
|
||||
|
||||
private String getNotificationCollectionPath() {
|
||||
return String.format(NOTIFICATION_COLLECTION_PATH_FORMAT, firestoreBaseRepository.getAppId());
|
||||
}
|
||||
|
||||
private DocumentReference getNotificationDocumentReference(String notificationId) {
|
||||
String collectionPath = getNotificationCollectionPath();
|
||||
return firestoreBaseRepository.getDocumentReference(collectionPath, notificationId);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Mono<Void> updateNotificationStatus(String sessionId, String status) {
|
||||
return Mono.fromRunnable(() -> {
|
||||
DocumentReference notificationDocRef = getNotificationDocumentReference(sessionId);
|
||||
try {
|
||||
Map<String, Object> sessionData = firestoreBaseRepository.getDocument(notificationDocRef, Map.class);
|
||||
if (sessionData != null) {
|
||||
List<Map<String, Object>> notifications = (List<Map<String, Object>>) sessionData
|
||||
.get(FIELD_MESSAGES);
|
||||
if (notifications != null) {
|
||||
List<Map<String, Object>> updatedNotifications = new ArrayList<>();
|
||||
for (Map<String, Object> notification : notifications) {
|
||||
Map<String, Object> updatedNotification = new HashMap<>(notification);
|
||||
updatedNotification.put("status", status);
|
||||
updatedNotifications.add(updatedNotification);
|
||||
}
|
||||
Map<String, Object> updates = new HashMap<>();
|
||||
updates.put(FIELD_MESSAGES, updatedNotifications);
|
||||
updates.put(FIELD_LAST_UPDATED, Timestamp.of(java.util.Date.from(Instant.now())));
|
||||
firestoreBaseRepository.updateDocument(notificationDocRef, updates);
|
||||
logger.info("Successfully updated notification status to '{}' for session {} in Firestore.",
|
||||
status, sessionId);
|
||||
}
|
||||
} else {
|
||||
logger.warn("Notification session {} not found in Firestore. Cannot update status.", sessionId);
|
||||
}
|
||||
} catch (ExecutionException e) {
|
||||
logger.error("Error updating notification status in Firestore for session {}: {}", sessionId,
|
||||
e.getMessage(), e);
|
||||
throw new FirestorePersistenceException(
|
||||
"Failed to update notification status in Firestore for session " + sessionId, e);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
logger.error("Thread interrupted while updating notification status in Firestore for session {}: {}",
|
||||
sessionId, e.getMessage(), e);
|
||||
throw new FirestorePersistenceException(
|
||||
"Updating notification status was interrupted for session " + sessionId, e);
|
||||
}
|
||||
})
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.then();
|
||||
}
|
||||
|
||||
public Mono<Void> deleteNotification(String notificationId) {
|
||||
logger.info("Attempting to delete notification session {} from Firestore.", notificationId);
|
||||
return Mono.fromRunnable(() -> {
|
||||
try {
|
||||
DocumentReference notificationDocRef = getNotificationDocumentReference(notificationId);
|
||||
firestoreBaseRepository.deleteDocument(notificationDocRef);
|
||||
logger.info("Successfully deleted notification session {} from Firestore.", notificationId);
|
||||
} catch (ExecutionException e) {
|
||||
logger.error("Error deleting notification session {} from Firestore: {}", notificationId, e.getMessage(), e);
|
||||
throw new FirestorePersistenceException("Failed to delete notification session " + notificationId, e);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
logger.error("Thread interrupted while deleting notification session {} from Firestore: {}", notificationId, e.getMessage(), e);
|
||||
throw new FirestorePersistenceException("Deleting notification session was interrupted for " + notificationId, e);
|
||||
}
|
||||
}).subscribeOn(Schedulers.boundedElastic()).then();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.notification;
|
||||
|
||||
import com.example.dto.dialogflow.notification.NotificationDTO;
|
||||
import com.example.dto.dialogflow.notification.NotificationSessionDTO;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.core.ReactiveRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.time.Instant;
|
||||
|
||||
@Service
|
||||
public class MemoryStoreNotificationService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MemoryStoreNotificationService.class);
|
||||
private final ReactiveRedisTemplate<String, NotificationSessionDTO> notificationRedisTemplate;
|
||||
private final ReactiveRedisTemplate<String, String> stringRedisTemplate;
|
||||
private static final String NOTIFICATION_KEY_PREFIX = "notification:";
|
||||
private static final String PHONE_TO_NOTIFICATION_SESSION_KEY_PREFIX = "notification:phone_to_notification:";
|
||||
private final Duration notificationTtl = Duration.ofDays(30);
|
||||
|
||||
public MemoryStoreNotificationService(
|
||||
ReactiveRedisTemplate<String, NotificationSessionDTO> notificationRedisTemplate,
|
||||
ReactiveRedisTemplate<String, String> stringRedisTemplate,
|
||||
ObjectMapper objectMapper) {
|
||||
this.notificationRedisTemplate = notificationRedisTemplate;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
public Mono<Void> saveOrAppendNotificationEntry(NotificationDTO newEntry) {
|
||||
String phoneNumber = newEntry.telefono();
|
||||
if (phoneNumber == null || phoneNumber.isBlank()) {
|
||||
return Mono.error(new IllegalArgumentException("Phone number is required to manage notification entries."));
|
||||
}
|
||||
//noote: Use the phone number as the session ID for notifications
|
||||
String notificationSessionId = phoneNumber;
|
||||
|
||||
return getCachedNotificationSession(notificationSessionId)
|
||||
.flatMap(existingSession -> {
|
||||
// Session exists, append the new entry
|
||||
List<NotificationDTO> updatedEntries = new ArrayList<>(existingSession.notificaciones());
|
||||
updatedEntries.add(newEntry);
|
||||
NotificationSessionDTO updatedSession = new NotificationSessionDTO(
|
||||
notificationSessionId,
|
||||
phoneNumber,
|
||||
existingSession.fechaCreacion(),
|
||||
Instant.now(),
|
||||
updatedEntries
|
||||
);
|
||||
return Mono.just(updatedSession);
|
||||
})
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
// No session found, create a new one
|
||||
NotificationSessionDTO newSession = new NotificationSessionDTO(
|
||||
notificationSessionId,
|
||||
phoneNumber,
|
||||
Instant.now(),
|
||||
Instant.now(),
|
||||
Collections.singletonList(newEntry)
|
||||
);
|
||||
return Mono.just(newSession);
|
||||
}))
|
||||
.flatMap(this::cacheNotificationSession)
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<Boolean> cacheNotificationSession(NotificationSessionDTO session) {
|
||||
String key = NOTIFICATION_KEY_PREFIX + session.sessionId();
|
||||
String phoneToSessionKey = PHONE_TO_NOTIFICATION_SESSION_KEY_PREFIX + session.telefono();
|
||||
|
||||
return notificationRedisTemplate.opsForValue().set(key, session, notificationTtl)
|
||||
.then(stringRedisTemplate.opsForValue().set(phoneToSessionKey, session.sessionId(), notificationTtl));
|
||||
}
|
||||
|
||||
public Mono<NotificationSessionDTO> getCachedNotificationSession(String sessionId) {
|
||||
String key = NOTIFICATION_KEY_PREFIX + sessionId;
|
||||
return notificationRedisTemplate.opsForValue().get(key)
|
||||
.doOnSuccess(notification -> {
|
||||
if (notification != null) {
|
||||
logger.info("Notification session with ID {} retrieved from MemoryStore.", sessionId);
|
||||
} else {
|
||||
logger.debug("Notification session with ID {} not found in MemoryStore.", sessionId);
|
||||
}
|
||||
})
|
||||
.doOnError(e -> logger.error("Error retrieving notification session with ID {} from MemoryStore: {}", sessionId, e.getMessage(), e));
|
||||
}
|
||||
|
||||
public Mono<String> getNotificationIdForPhone(String phone) {
|
||||
String key = PHONE_TO_NOTIFICATION_SESSION_KEY_PREFIX + phone;
|
||||
return stringRedisTemplate.opsForValue().get(key)
|
||||
.doOnSuccess(sessionId -> {
|
||||
if (sessionId != null) {
|
||||
logger.info("Session ID {} found for phone.", sessionId);
|
||||
} else {
|
||||
logger.debug("Session ID not found for phone.");
|
||||
}
|
||||
})
|
||||
.doOnError(e -> logger.error("Error retrieving session ID for phone from MemoryStore: {}",
|
||||
e.getMessage(), e));
|
||||
}
|
||||
|
||||
public Mono<Void> deleteNotificationSession(String phoneNumber) {
|
||||
String notificationKey = NOTIFICATION_KEY_PREFIX + phoneNumber;
|
||||
String phoneToNotificationKey = PHONE_TO_NOTIFICATION_SESSION_KEY_PREFIX + phoneNumber;
|
||||
logger.info("Deleting notification session for phone number {}.", phoneNumber);
|
||||
return notificationRedisTemplate.opsForValue().delete(notificationKey)
|
||||
.then(stringRedisTemplate.opsForValue().delete(phoneToNotificationKey))
|
||||
.then();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.notification;
|
||||
|
||||
import com.example.dto.dialogflow.notification.ExternalNotRequestDTO;
|
||||
import com.example.dto.dialogflow.base.DetectIntentRequestDTO;
|
||||
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
||||
import com.example.dto.dialogflow.conversation.ConversationEntryDTO;
|
||||
import com.example.dto.dialogflow.conversation.ConversationMessageDTO;
|
||||
import com.example.dto.dialogflow.conversation.ConversationSessionDTO;
|
||||
import com.example.dto.dialogflow.notification.NotificationDTO;
|
||||
import com.example.mapper.conversation.ConversationEntryMapper;
|
||||
import com.example.mapper.notification.ExternalNotRequestMapper;
|
||||
import com.example.service.base.DialogflowClientService;
|
||||
import com.example.service.conversation.DataLossPrevention;
|
||||
import com.example.service.conversation.FirestoreConversationService;
|
||||
import com.example.service.conversation.MemoryStoreConversationService;
|
||||
import com.example.util.SessionIdGenerator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class NotificationManagerService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NotificationManagerService.class);
|
||||
private static final String eventName = "notificacion";
|
||||
private static final String PREFIX_PO_PARAM = "notification_po_";
|
||||
|
||||
private final DialogflowClientService dialogflowClientService;
|
||||
private final FirestoreNotificationService firestoreNotificationService;
|
||||
private final MemoryStoreNotificationService memoryStoreNotificationService;
|
||||
private final ExternalNotRequestMapper externalNotRequestMapper;
|
||||
private final MemoryStoreConversationService memoryStoreConversationService;
|
||||
private final FirestoreConversationService firestoreConversationService;
|
||||
private final DataLossPrevention dataLossPrevention;
|
||||
private final String dlpTemplateCompleteFlow;
|
||||
private final ConversationEntryMapper conversationEntryMapper;
|
||||
|
||||
@Value("${dialogflow.default-language-code:es}")
|
||||
private String defaultLanguageCode;
|
||||
|
||||
public NotificationManagerService(
|
||||
DialogflowClientService dialogflowClientService,
|
||||
FirestoreNotificationService firestoreNotificationService,
|
||||
MemoryStoreNotificationService memoryStoreNotificationService,
|
||||
MemoryStoreConversationService memoryStoreConversationService,
|
||||
FirestoreConversationService firestoreConversationService,
|
||||
|
||||
ExternalNotRequestMapper externalNotRequestMapper,
|
||||
DataLossPrevention dataLossPrevention,
|
||||
ConversationEntryMapper conversationEntryMapper,
|
||||
@Value("${google.cloud.dlp.dlpTemplateCompleteFlow}") String dlpTemplateCompleteFlow) {
|
||||
|
||||
this.dialogflowClientService = dialogflowClientService;
|
||||
this.firestoreNotificationService = firestoreNotificationService;
|
||||
this.memoryStoreNotificationService = memoryStoreNotificationService;
|
||||
this.externalNotRequestMapper = externalNotRequestMapper;
|
||||
this.dataLossPrevention = dataLossPrevention;
|
||||
this.dlpTemplateCompleteFlow = dlpTemplateCompleteFlow;
|
||||
this.memoryStoreConversationService = memoryStoreConversationService;
|
||||
this.firestoreConversationService = firestoreConversationService;
|
||||
this.conversationEntryMapper = conversationEntryMapper;
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO> processNotification(ExternalNotRequestDTO externalRequest) {
|
||||
Objects.requireNonNull(externalRequest, "ExternalNotRequestDTO cannot be null.");
|
||||
|
||||
String telefono = externalRequest.phoneNumber();
|
||||
if (telefono == null || telefono.isBlank()) {
|
||||
logger.warn("No phone number provided in ExternalNotRequestDTO. Cannot process notification.");
|
||||
return Mono.error(new IllegalArgumentException("Phone number is required."));
|
||||
}
|
||||
|
||||
return dataLossPrevention.getObfuscatedString(externalRequest.text(), dlpTemplateCompleteFlow)
|
||||
.flatMap(obfuscatedMessage -> {
|
||||
ExternalNotRequestDTO obfuscatedRequest = new ExternalNotRequestDTO(
|
||||
obfuscatedMessage,
|
||||
externalRequest.phoneNumber(),
|
||||
externalRequest.hiddenParameters()
|
||||
);
|
||||
|
||||
String newNotificationId = SessionIdGenerator.generateStandardSessionId();
|
||||
Map<String, Object> parameters = new HashMap<>();
|
||||
if (obfuscatedRequest.hiddenParameters() != null) {
|
||||
obfuscatedRequest.hiddenParameters().forEach((key, value) -> parameters.put(PREFIX_PO_PARAM + key, value));
|
||||
}
|
||||
|
||||
NotificationDTO newNotificationEntry = new NotificationDTO(newNotificationId, telefono, Instant.now(),
|
||||
obfuscatedRequest.text(), eventName, defaultLanguageCode, parameters, "active");
|
||||
Mono<Void> persistenceMono = memoryStoreNotificationService.saveOrAppendNotificationEntry(newNotificationEntry)
|
||||
.doOnSuccess(v -> {
|
||||
logger.info("Notification for phone {} cached. Kicking off async Firestore write-back.", telefono);
|
||||
firestoreNotificationService.saveOrAppendNotificationEntry(newNotificationEntry)
|
||||
.subscribe(
|
||||
ignored -> logger.debug(
|
||||
"Background: Notification entry persistence initiated for phone {} in Firestore.", telefono),
|
||||
e -> logger.error(
|
||||
"Background: Error during notification entry persistence for phone {} in Firestore: {}",
|
||||
telefono, e.getMessage(), e));
|
||||
});
|
||||
|
||||
Mono<ConversationSessionDTO> sessionMono = memoryStoreConversationService.getSessionByTelefono(telefono)
|
||||
.doOnNext(session -> logger.info("Found existing conversation session {} for phone number {}",
|
||||
session.sessionId(), telefono))
|
||||
.flatMap(session -> {
|
||||
Map<String, Object> prefixedParameters = new HashMap<>();
|
||||
if (obfuscatedRequest.hiddenParameters() != null) {
|
||||
obfuscatedRequest.hiddenParameters()
|
||||
.forEach((key, value) -> prefixedParameters.put(PREFIX_PO_PARAM + key, value));
|
||||
}
|
||||
ConversationEntryDTO systemEntry = ConversationEntryDTO.forSystem(obfuscatedRequest.text(),
|
||||
prefixedParameters);
|
||||
return persistConversationTurn(session, systemEntry)
|
||||
.thenReturn(session);
|
||||
})
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
String newSessionId = SessionIdGenerator.generateStandardSessionId();
|
||||
logger.info("No existing conversation session found for phone number {}. Creating new session: {}",
|
||||
telefono, newSessionId);
|
||||
String userId = "user_by_phone_" + telefono;
|
||||
Map<String, Object> prefixedParameters = new HashMap<>();
|
||||
if (obfuscatedRequest.hiddenParameters() != null) {
|
||||
obfuscatedRequest.hiddenParameters()
|
||||
.forEach((key, value) -> prefixedParameters.put(PREFIX_PO_PARAM + key, value));
|
||||
}
|
||||
ConversationEntryDTO systemEntry = ConversationEntryDTO.forSystem(obfuscatedRequest.text(),
|
||||
prefixedParameters);
|
||||
ConversationSessionDTO newSession = ConversationSessionDTO.create(newSessionId, userId, telefono);
|
||||
return persistConversationTurn(newSession, systemEntry)
|
||||
.then(Mono.just(newSession));
|
||||
}));
|
||||
|
||||
return persistenceMono.then(sessionMono)
|
||||
.flatMap(session -> {
|
||||
final String sessionId = session.sessionId();
|
||||
logger.info("Sending notification text to Dialogflow using conversation session: {}", sessionId);
|
||||
|
||||
DetectIntentRequestDTO detectIntentRequest = externalNotRequestMapper.map(obfuscatedRequest);
|
||||
|
||||
return dialogflowClientService.detectIntent(sessionId, detectIntentRequest);
|
||||
})
|
||||
.doOnSuccess(response -> logger
|
||||
.info("Finished processing notification. Dialogflow response received for phone {}.", telefono))
|
||||
.doOnError(e -> logger.error("Overall error in NotificationManagerService: {}", e.getMessage(), e));
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Void> persistConversationTurn(ConversationSessionDTO session, ConversationEntryDTO entry) {
|
||||
logger.debug("Starting Write-Back persistence for session {}. Type: {}. Writing to Redis first.", session.sessionId(),
|
||||
entry.type().name());
|
||||
ConversationMessageDTO message = conversationEntryMapper.toConversationMessageDTO(entry);
|
||||
ConversationSessionDTO updatedSession = session.withLastMessage(message.text());
|
||||
|
||||
return memoryStoreConversationService.saveSession(updatedSession)
|
||||
.then(memoryStoreConversationService.saveMessage(session.sessionId(), message))
|
||||
.doOnSuccess(v -> {
|
||||
logger.info(
|
||||
"Entry saved to Redis for session {}. Type: {}. Kicking off async Firestore write-back.",
|
||||
session.sessionId(), entry.type().name());
|
||||
|
||||
firestoreConversationService.saveSession(updatedSession)
|
||||
.then(firestoreConversationService.saveMessage(session.sessionId(), message))
|
||||
.subscribe(
|
||||
fsVoid -> logger.debug(
|
||||
"Asynchronously (Write-Back): Entry successfully saved to Firestore for session {}. Type: {}.",
|
||||
session.sessionId(), entry.type().name()),
|
||||
fsError -> logger.error(
|
||||
"Asynchronously (Write-Back): Failed to save entry to Firestore for session {}. Type: {}: {}",
|
||||
session.sessionId(), entry.type().name(), fsError.getMessage(), fsError));
|
||||
})
|
||||
.doOnError(e -> logger.error("Error during primary Redis write for session {}. Type: {}: {}", session.sessionId(),
|
||||
entry.type().name(), e.getMessage(), e));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.quickreplies;
|
||||
|
||||
import com.example.dto.dialogflow.conversation.ConversationEntryDTO;
|
||||
import com.example.dto.dialogflow.conversation.ConversationMessageDTO;
|
||||
import com.example.dto.dialogflow.conversation.ConversationSessionDTO;
|
||||
import com.example.mapper.conversation.ConversationEntryMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.ReactiveRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Service
|
||||
public class MemoryStoreQRService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MemoryStoreQRService.class);
|
||||
private static final String SESSION_KEY_PREFIX = "qr:session:";
|
||||
private static final String PHONE_TO_SESSION_KEY_PREFIX = "qr:phone_to_session:";
|
||||
private static final String MESSAGES_KEY_PREFIX = "qr:messages:";
|
||||
private static final Duration SESSION_TTL = Duration.ofHours(24);
|
||||
private final ReactiveRedisTemplate<String, ConversationSessionDTO> redisTemplate;
|
||||
private final ReactiveRedisTemplate<String, String> stringRedisTemplate;
|
||||
private final ReactiveRedisTemplate<String, ConversationMessageDTO> messageRedisTemplate;
|
||||
private final ConversationEntryMapper conversationEntryMapper;
|
||||
|
||||
@Autowired
|
||||
public MemoryStoreQRService(
|
||||
ReactiveRedisTemplate<String, ConversationSessionDTO> redisTemplate,
|
||||
ReactiveRedisTemplate<String, String> stringRedisTemplate,
|
||||
ReactiveRedisTemplate<String, ConversationMessageDTO> messageRedisTemplate,
|
||||
ConversationEntryMapper conversationEntryMapper) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
this.messageRedisTemplate = messageRedisTemplate;
|
||||
this.conversationEntryMapper = conversationEntryMapper;
|
||||
}
|
||||
|
||||
public Mono<Void> saveEntry(String userId, String sessionId, ConversationEntryDTO newEntry,
|
||||
String userPhoneNumber) {
|
||||
String sessionKey = SESSION_KEY_PREFIX + sessionId;
|
||||
String phoneToSessionKey = PHONE_TO_SESSION_KEY_PREFIX + userPhoneNumber;
|
||||
String messagesKey = MESSAGES_KEY_PREFIX + sessionId;
|
||||
|
||||
logger.info("Attempting to save entry to Redis for quick reply session {}. Entity: {}", sessionId,
|
||||
newEntry.entity().name());
|
||||
|
||||
return redisTemplate.opsForValue().get(sessionKey)
|
||||
.defaultIfEmpty(ConversationSessionDTO.create(sessionId, userId, userPhoneNumber))
|
||||
.flatMap(session -> {
|
||||
ConversationSessionDTO sessionWithUpdatedTelefono = session.withTelefono(userPhoneNumber);
|
||||
ConversationSessionDTO updatedSession = sessionWithUpdatedTelefono.withLastMessage(newEntry.text());
|
||||
ConversationMessageDTO message = conversationEntryMapper.toConversationMessageDTO(newEntry);
|
||||
|
||||
logger.info("Attempting to set updated quick reply session {} with new entry entity {} in Redis.",
|
||||
sessionId, newEntry.entity().name());
|
||||
|
||||
return redisTemplate.opsForValue().set(sessionKey, updatedSession, SESSION_TTL)
|
||||
.then(stringRedisTemplate.opsForValue().set(phoneToSessionKey, sessionId, SESSION_TTL))
|
||||
.then(messageRedisTemplate.opsForList().rightPush(messagesKey, message))
|
||||
.then();
|
||||
})
|
||||
.doOnSuccess(success -> {
|
||||
logger.info(
|
||||
"Successfully saved updated quick reply session and phone mapping to Redis for session {}. Entity Type: {}",
|
||||
sessionId, newEntry.entity().name());
|
||||
})
|
||||
.doOnError(e -> logger.error("Error appending entry to Redis for quick reply session {}: {}", sessionId,
|
||||
e.getMessage(), e));
|
||||
}
|
||||
|
||||
public Mono<ConversationSessionDTO> getSessionByTelefono(String telefono) {
|
||||
if (telefono == null || telefono.isBlank()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
String phoneToSessionKey = PHONE_TO_SESSION_KEY_PREFIX + telefono;
|
||||
return stringRedisTemplate.opsForValue().get(phoneToSessionKey)
|
||||
.flatMap(sessionId -> {
|
||||
logger.debug("Found quick reply session ID {} for phone number {}. Retrieving session data.",
|
||||
sessionId, telefono);
|
||||
return redisTemplate.opsForValue().get(SESSION_KEY_PREFIX + sessionId);
|
||||
})
|
||||
.doOnSuccess(session -> {
|
||||
if (session != null) {
|
||||
logger.info("Successfully retrieved quick reply session {}",
|
||||
session.sessionId());
|
||||
} else {
|
||||
logger.info("No quick reply session found in Redis for phone number");
|
||||
}
|
||||
})
|
||||
.doOnError(e -> logger.error("Error retrieving quick reply session by phone numbe: {}",e.getMessage(), e));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.quickreplies;
|
||||
|
||||
import com.example.dto.dialogflow.base.DetectIntentResponseDTO;
|
||||
import com.example.dto.dialogflow.conversation.*;
|
||||
import com.example.dto.quickreplies.QuickReplyScreenRequestDTO;
|
||||
import com.example.dto.quickreplies.QuestionDTO;
|
||||
import com.example.dto.quickreplies.QuickReplyDTO;
|
||||
import com.example.mapper.conversation.ConversationEntryMapper;
|
||||
import com.example.service.conversation.FirestoreConversationService;
|
||||
import com.example.service.conversation.MemoryStoreConversationService;
|
||||
import com.example.util.SessionIdGenerator;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.service.conversation.ConversationManagerService;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class QuickRepliesManagerService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(QuickRepliesManagerService.class);
|
||||
private final MemoryStoreConversationService memoryStoreConversationService;
|
||||
private final FirestoreConversationService firestoreConversationService;
|
||||
private final QuickReplyContentService quickReplyContentService;
|
||||
private final ConversationManagerService conversationManagerService;
|
||||
private final ConversationEntryMapper conversationEntryMapper;
|
||||
|
||||
public QuickRepliesManagerService(
|
||||
@Lazy ConversationManagerService conversationManagerService,
|
||||
MemoryStoreConversationService memoryStoreConversationService,
|
||||
FirestoreConversationService firestoreConversationService,
|
||||
QuickReplyContentService quickReplyContentService,
|
||||
ConversationEntryMapper conversationEntryMapper) {
|
||||
this.conversationManagerService = conversationManagerService;
|
||||
this.memoryStoreConversationService = memoryStoreConversationService;
|
||||
this.firestoreConversationService = firestoreConversationService;
|
||||
this.quickReplyContentService = quickReplyContentService;
|
||||
this.conversationEntryMapper = conversationEntryMapper;
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO> startQuickReplySession(QuickReplyScreenRequestDTO externalRequest) {
|
||||
String userPhoneNumber = externalRequest.user().telefono();
|
||||
if (userPhoneNumber == null || userPhoneNumber.isBlank()) {
|
||||
logger.warn("No phone number provided in request. Cannot manage conversation session without it.");
|
||||
return Mono
|
||||
.error(new IllegalArgumentException("Phone number is required to manage conversation sessions."));
|
||||
}
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.flatMap(session -> Mono.just(session.sessionId()))
|
||||
.switchIfEmpty(Mono.fromCallable(SessionIdGenerator::generateStandardSessionId))
|
||||
.flatMap(sessionId -> {
|
||||
String userId = "user_by_phone_" + userPhoneNumber.replaceAll("[^0-9]", "");
|
||||
ConversationEntryDTO systemEntry = new ConversationEntryDTO(
|
||||
ConversationEntryEntity.SISTEMA,
|
||||
ConversationEntryType.INICIO,
|
||||
Instant.now(),
|
||||
"Pantalla :" + externalRequest.pantallaContexto() + " Agregada a la conversacion :",
|
||||
null,
|
||||
null);
|
||||
ConversationSessionDTO newSession = ConversationSessionDTO.create(sessionId, userId, userPhoneNumber).withPantallaContexto(externalRequest.pantallaContexto());
|
||||
return persistConversationTurn(newSession, systemEntry)
|
||||
.then(quickReplyContentService.getQuickReplies(externalRequest.pantallaContexto()))
|
||||
.map(quickReplyDTO -> new DetectIntentResponseDTO(sessionId, null, quickReplyDTO));
|
||||
});
|
||||
}
|
||||
|
||||
public Mono<DetectIntentResponseDTO> manageConversation(ExternalConvRequestDTO externalRequest) {
|
||||
String userPhoneNumber = externalRequest.user().telefono();
|
||||
if (userPhoneNumber == null || userPhoneNumber.isBlank()) {
|
||||
logger.warn("No phone number provided in request. Cannot manage conversation session without it.");
|
||||
return Mono
|
||||
.error(new IllegalArgumentException("Phone number is required to manage conversation sessions."));
|
||||
}
|
||||
|
||||
return memoryStoreConversationService.getSessionByTelefono(userPhoneNumber)
|
||||
.switchIfEmpty(Mono.error(
|
||||
new IllegalStateException("No quick reply session found for phone number")))
|
||||
.flatMap(session -> {
|
||||
|
||||
return memoryStoreConversationService.getMessages(session.sessionId()).collectList().flatMap(messages -> {
|
||||
ConversationEntryDTO userEntry = ConversationEntryDTO.forUser(externalRequest.message());
|
||||
|
||||
int lastInitIndex = IntStream.range(0, messages.size())
|
||||
.map(i -> messages.size() - 1 - i)
|
||||
.filter(i -> {
|
||||
ConversationMessageDTO message = messages.get(i);
|
||||
return message.type() == MessageType.SYSTEM;
|
||||
})
|
||||
.findFirst()
|
||||
.orElse(-1);
|
||||
|
||||
long userMessagesCount;
|
||||
if (lastInitIndex != -1) {
|
||||
userMessagesCount = messages.subList(lastInitIndex + 1, messages.size()).stream()
|
||||
.filter(e -> e.type() == MessageType.USER)
|
||||
.count();
|
||||
} else {
|
||||
userMessagesCount = 0;
|
||||
}
|
||||
|
||||
if (userMessagesCount == 0) { // Is the first user message in the Quick-Replies flow
|
||||
// This is the second message of the flow. Return the full list.
|
||||
return persistConversationTurn(session, userEntry)
|
||||
.then(quickReplyContentService.getQuickReplies(session.pantallaContexto()))
|
||||
.flatMap(quickReplyDTO -> {
|
||||
ConversationEntryDTO agentEntry = ConversationEntryDTO
|
||||
.forAgentWithMessage(quickReplyDTO.toString());
|
||||
return persistConversationTurn(session, agentEntry)
|
||||
.thenReturn(new DetectIntentResponseDTO(session.sessionId(), null, quickReplyDTO));
|
||||
});
|
||||
} else if (userMessagesCount == 1) { // Is the second user message in the QR flow
|
||||
// This is the third message of the flow. Filter and end.
|
||||
return persistConversationTurn(session, userEntry)
|
||||
.then(quickReplyContentService.getQuickReplies(session.pantallaContexto()))
|
||||
.flatMap(quickReplyDTO -> {
|
||||
List<QuestionDTO> matchedPreguntas = quickReplyDTO.preguntas().stream()
|
||||
.filter(p -> p.titulo().equalsIgnoreCase(externalRequest.message().trim()))
|
||||
.toList();
|
||||
|
||||
if (!matchedPreguntas.isEmpty()) {
|
||||
// Matched question, return the answer
|
||||
String respuesta = matchedPreguntas.get(0).respuesta();
|
||||
QueryResultDTO queryResult = new QueryResultDTO(respuesta, null);
|
||||
DetectIntentResponseDTO response = new DetectIntentResponseDTO(session.sessionId(),
|
||||
queryResult, null);
|
||||
|
||||
return memoryStoreConversationService
|
||||
.updateSession(session.withPantallaContexto(null))
|
||||
.then(persistConversationTurn(session,
|
||||
ConversationEntryDTO.forAgentWithMessage(respuesta)))
|
||||
.thenReturn(response);
|
||||
} else {
|
||||
// No match, delegate to Dialogflow
|
||||
return memoryStoreConversationService
|
||||
.updateSession(session.withPantallaContexto(null))
|
||||
.then(conversationManagerService.manageConversation(externalRequest));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Should not happen. End the flow.
|
||||
return memoryStoreConversationService.updateSession(session.withPantallaContexto(null))
|
||||
.then(Mono.just(new DetectIntentResponseDTO(session.sessionId(), null,
|
||||
new QuickReplyDTO("Flow Error", null, null, null, Collections.emptyList()))));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Void> persistConversationTurn(ConversationSessionDTO session, ConversationEntryDTO entry) {
|
||||
logger.debug("Starting Write-Back persistence for quick reply session {}. Type: {}. Writing to Redis first.",
|
||||
session.sessionId(), entry.type().name());
|
||||
ConversationMessageDTO message = conversationEntryMapper.toConversationMessageDTO(entry);
|
||||
ConversationSessionDTO updatedSession = session.withLastMessage(message.text());
|
||||
return memoryStoreConversationService.saveSession(updatedSession)
|
||||
.then(memoryStoreConversationService.saveMessage(session.sessionId(), message))
|
||||
.doOnSuccess(v -> logger.info(
|
||||
"Entry saved to Redis for quick reply session {}. Type: {}. Kicking off async Firestore write-back.",
|
||||
session.sessionId(), entry.type().name()))
|
||||
.then(firestoreConversationService.saveSession(updatedSession)
|
||||
.then(firestoreConversationService.saveMessage(session.sessionId(), message))
|
||||
.doOnSuccess(fsVoid -> logger.debug(
|
||||
"Asynchronously (Write-Back): Entry successfully saved to Firestore for quick reply session {}. Type: {}.",
|
||||
session.sessionId(), entry.type().name()))
|
||||
.doOnError(fsError -> logger.error(
|
||||
"Asynchronously (Write-Back): Failed to save entry to Firestore for quick reply session {}. Type: {}: {}",
|
||||
session.sessionId(), entry.type().name(), fsError.getMessage(), fsError)))
|
||||
.doOnError(
|
||||
e -> logger.error("Error during primary Redis write for quick reply session {}. Type: {}: {}",
|
||||
session.sessionId(), entry.type().name(), e.getMessage(), e));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright 2025 Google. This software is provided as-is, without warranty or representation for any use or purpose.
|
||||
* Your use of it is subject to your agreement with Google.
|
||||
*/
|
||||
|
||||
package com.example.service.quickreplies;
|
||||
|
||||
import com.example.dto.quickreplies.QuestionDTO;
|
||||
import com.example.dto.quickreplies.QuickReplyDTO;
|
||||
import com.google.cloud.firestore.DocumentSnapshot;
|
||||
import com.google.cloud.firestore.Firestore;
|
||||
import java.util.Map;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class QuickReplyContentService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(QuickReplyContentService.class);
|
||||
private final Firestore firestore;
|
||||
public QuickReplyContentService(Firestore firestore) {
|
||||
this.firestore = firestore;
|
||||
}
|
||||
public Mono<QuickReplyDTO> getQuickReplies(String collectionId) {
|
||||
logger.info("Fetching quick replies from Firestore for document: {}", collectionId);
|
||||
if (collectionId == null || collectionId.isBlank()) {
|
||||
logger.warn("collectionId is null or empty. Returning empty quick replies.");
|
||||
return Mono.just(new QuickReplyDTO("empty", null, null, null, Collections.emptyList()));
|
||||
}
|
||||
return Mono.fromCallable(() -> {
|
||||
try {
|
||||
return firestore.collection("artifacts")
|
||||
.document("default-app-id")
|
||||
.collection("quick-replies")
|
||||
.document(collectionId)
|
||||
.get()
|
||||
.get();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
})
|
||||
.filter(DocumentSnapshot::exists)
|
||||
.map(document -> {
|
||||
String header = document.getString("header");
|
||||
String body = document.getString("body");
|
||||
String button = document.getString("button");
|
||||
String headerSection = document.getString("header_section");
|
||||
List<Map<String, Object>> preguntasData = (List<Map<String, Object>>) document.get("preguntas");
|
||||
List<QuestionDTO> preguntas = preguntasData.stream()
|
||||
.map(p -> new QuestionDTO((String) p.get("titulo"), (String) p.get("descripcion"), (String) p.get("respuesta")))
|
||||
.toList();
|
||||
return new QuickReplyDTO(header, body, button, headerSection, preguntas);
|
||||
})
|
||||
.doOnSuccess(quickReplyDTO -> {
|
||||
if (quickReplyDTO != null) {
|
||||
logger.info("Successfully fetched {} quick replies for document: {}", quickReplyDTO.preguntas().size(), collectionId);
|
||||
} else {
|
||||
logger.info("No quick reply document found for id: {}", collectionId);
|
||||
}
|
||||
})
|
||||
.doOnError(error -> logger.error("Error fetching quick replies from Firestore for document: {}", collectionId, error))
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
logger.info("No quick reply document found for id: {}", collectionId);
|
||||
return Mono.empty();
|
||||
}));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user