Initial Python rewrite
This commit is contained in:
@@ -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