Download src/test/java/com/anthony/failsafeapi/service/AiEngineServiceTest.java from tonyy1/tickets: direct link, hf CLI and curl.
- Browser
- Download file 30.4 kB
-
https://huggingface.co/spaces/tonyy1/tickets/resolve/main/src/test/java/com/anthony/failsafeapi/service/AiEngineServiceTest.java
- Command line
-
hf download hf://spaces/tonyy1/tickets/src/test/java/com/anthony/failsafeapi/service/AiEngineServiceTest.java
-
curl -L -o AiEngineServiceTest.java https://huggingface.co/spaces/tonyy1/tickets/resolve/main/src/test/java/com/anthony/failsafeapi/service/AiEngineServiceTest.java
30.4 kB
| package com.anthony.failsafeapi.service; | |
| import com.anthony.failsafeapi.event.AiCallEvent; | |
| import com.anthony.failsafeapi.exception.AIModelCallException; | |
| import com.anthony.failsafeapi.exception.AIResponseParseException; | |
| import com.anthony.failsafeapi.model.ProcessingContext; | |
| import com.anthony.failsafeapi.model.TicketResponse; | |
| import com.anthony.failsafeapi.util.constants.AuditStatus; | |
| import com.anthony.failsafeapi.util.constants.ProcessingStatus; | |
| import com.anthony.failsafeapi.config.GeminiConfig; | |
| import com.anthony.failsafeapi.config.GroqConfig; | |
| import io.github.resilience4j.circuitbreaker.CircuitBreaker; | |
| import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; | |
| import io.micrometer.core.instrument.*; | |
| import org.junit.jupiter.api.BeforeEach; | |
| import org.junit.jupiter.api.DisplayName; | |
| import org.junit.jupiter.api.Nested; | |
| import org.junit.jupiter.api.Test; | |
| import org.junit.jupiter.api.extension.ExtendWith; | |
| import org.mockito.ArgumentCaptor; | |
| import org.mockito.Mock; | |
| import org.mockito.junit.jupiter.MockitoExtension; | |
| import org.springframework.ai.chat.client.ChatClient; | |
| import org.springframework.ai.chat.model.ChatResponse; | |
| import org.springframework.ai.chat.model.Generation; | |
| import org.springframework.ai.chat.messages.AssistantMessage; | |
| import org.springframework.ai.chat.metadata.ChatResponseMetadata; | |
| import org.springframework.ai.chat.metadata.Usage; | |
| import org.springframework.context.ApplicationEventPublisher; | |
| import io.micrometer.core.instrument.simple.SimpleMeterRegistry; | |
| import java.math.BigDecimal; | |
| import java.util.function.Consumer; | |
| import static org.assertj.core.api.Assertions.assertThat; | |
| import static org.assertj.core.api.Assertions.assertThatThrownBy; | |
| import static org.mockito.ArgumentMatchers.*; | |
| import static org.mockito.Mockito.*; | |
| /** | |
| * Tests unitarios para AiEngineService. | |
| * | |
| * Estrategia de mocking para ChatClient (Spring AI 1.1.4): | |
| * El API de ChatClient usa un builder fluent con varios tipos intermedios. | |
| * Creamos un helper setupChatClientChain() que mockea toda la cadena | |
| * para que cada test solo configure lo que le importa. | |
| * | |
| * Cadena completa: | |
| * chatClient.prompt() | |
| * β ChatClientRequestSpec | |
| * .system(Consumer<SystemSpec>) | |
| * β ChatClientRequestSpec | |
| * .user(String) | |
| * β ChatClientRequestSpec | |
| * .call() | |
| * β CallResponseSpec | |
| * .chatResponse() | |
| * β ChatResponse | |
| */ | |
| class AiEngineServiceTest { | |
| // ββ Dependencias del servicio ββββββββββββββββββββββββββββββββββββββββββββββ | |
| private ChatClient chatClient; | |
| private ChatClient geminiChatClient; | |
| private GroqConfig groqConfig; | |
| private GeminiConfig geminiConfig; | |
| private SimpleMeterRegistry meterRegistry; | |
| private InferenceSecurityService aiLocal; | |
| private PromptCacheService promptCacheService; | |
| private ApplicationEventPublisher eventPublisher; | |
| private CircuitBreakerRegistry circuitBreakerRegistry; | |
| // ββ Mocks de la cadena fluent de ChatClient ββββββββββββββββββββββββββββββββ | |
| private ChatClient.ChatClientRequestSpec groqRequestSpec; | |
| private ChatClient.CallResponseSpec groqCallSpec; | |
| private ChatClient.ChatClientRequestSpec geminiRequestSpec; | |
| private ChatClient.CallResponseSpec geminiCallSpec; | |
| // ββ Circuit Breakers ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| private CircuitBreaker groqCircuitBreaker; | |
| private CircuitBreaker geminiCircuitBreaker; | |
| // ββ Sistema bajo prueba βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| private AiEngineService aiEngineService; | |
| // ββ JSON mΓnimo vΓ‘lido que el BeanOutputConverter puede parsear ββββββββββββ | |
| private static final String VALID_JSON_RESPONSE = """ | |
| { | |
| "category": "URGENTE", | |
| "provider": "groq/llama", | |
| "status": "SUCCESS", | |
| "inputTokens": 100, | |
| "outputTokens": 50, | |
| "estimatedCostUsd": 0.00001, | |
| "latencyMs": 300, | |
| "piiDetected": false, | |
| "securityLayersPassed": [], | |
| "securityLayersWithTiming": [], | |
| "maskedDescription": "texto", | |
| "processedAt": "2024-01-01T00:00:00Z", | |
| "circuitBreakerState": "CLOSED" | |
| } | |
| """; | |
| void setUp() { | |
| meterRegistry = new SimpleMeterRegistry(); | |
| // ConstrucciΓ³n manual porque @InjectMocks no distingue los dos ChatClient | |
| aiEngineService = new AiEngineService( | |
| chatClient, | |
| geminiChatClient, | |
| geminiConfig, | |
| meterRegistry, | |
| aiLocal, | |
| promptCacheService, | |
| groqConfig, | |
| eventPublisher, | |
| circuitBreakerRegistry | |
| ); | |
| // Circuit Breaker de Groq por defecto | |
| lenient().when(circuitBreakerRegistry.circuitBreaker("aiClassification")) | |
| .thenReturn(groqCircuitBreaker); | |
| lenient().when(groqCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.CLOSED); | |
| // Circuit Breaker de Gemini por defecto | |
| lenient().when(circuitBreakerRegistry.circuitBreaker("geminiClassification")) | |
| .thenReturn(geminiCircuitBreaker); | |
| lenient().when(geminiCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.CLOSED); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // HELPERS | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| /** | |
| * Monta la cadena fluent de Groq ChatClient para que devuelva el texto dado. | |
| */ | |
| private void setupGroqChain(String responseText) { | |
| ChatResponse chatResponse = buildChatResponse(responseText, 100, 50); | |
| when(chatClient.prompt()).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.call()).thenReturn(groqCallSpec); | |
| when(groqCallSpec.chatResponse()).thenReturn(chatResponse); | |
| } | |
| /** | |
| * Monta la cadena fluent de Gemini ChatClient para que devuelva el texto dado. | |
| */ | |
| private void setupGeminiChain(String responseText) { | |
| ChatResponse chatResponse = buildChatResponse(responseText, 80, 40); | |
| when(geminiChatClient.prompt()).thenReturn(geminiRequestSpec); | |
| when(geminiRequestSpec.system(any(Consumer.class))).thenReturn(geminiRequestSpec); | |
| when(geminiRequestSpec.user(anyString())).thenReturn(geminiRequestSpec); | |
| when(geminiRequestSpec.call()).thenReturn(geminiCallSpec); | |
| when(geminiCallSpec.chatResponse()).thenReturn(chatResponse); | |
| } | |
| /** | |
| * Construye un ChatResponse con los tokens y texto dados. | |
| * Usa mocks porque ChatResponse no tiene constructor pΓΊblico directo. | |
| */ | |
| private ChatResponse buildChatResponse(String text, int inputTokens, int outputTokens) { | |
| ChatResponse response = mock(ChatResponse.class); | |
| Generation generation = mock(Generation.class); | |
| AssistantMessage assistantMessage = mock(AssistantMessage.class); | |
| ChatResponseMetadata metadata = mock(ChatResponseMetadata.class); | |
| Usage usage = mock(Usage.class); | |
| when(response.getResult()).thenReturn(generation); | |
| when(generation.getOutput()).thenReturn(assistantMessage); | |
| when(assistantMessage.getText()).thenReturn(text); | |
| when(response.getMetadata()).thenReturn(metadata); | |
| when(metadata.getUsage()).thenReturn(usage); | |
| when(usage.getPromptTokens()).thenReturn(inputTokens); | |
| when(usage.getCompletionTokens()).thenReturn(outputTokens); | |
| return response; | |
| } | |
| /** | |
| * Configura los configs de Groq con valores por defecto para tests. | |
| */ | |
| private void setupGroqConfig() { | |
| lenient().when(groqConfig.getModel()).thenReturn("groq/llama"); | |
| lenient().when(groqConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("0.05")); | |
| lenient().when(groqConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("0.10")); | |
| } | |
| /** | |
| * Configura los configs de Gemini con valores por defecto para tests. | |
| */ | |
| private void setupGeminiConfig() { | |
| lenient().when(geminiConfig.getModel()).thenReturn("gemini-2.5-flash"); | |
| lenient().when(geminiConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("0.01")); | |
| lenient().when(geminiConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("0.02")); | |
| } | |
| private ProcessingContext buildContext() { | |
| return new ProcessingContext(); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // LLAMADA EXITOSA A GROQ | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class CallLlmSuccessTests { | |
| void setUp() { | |
| when(promptCacheService.getPrompt()).thenReturn("system prompt template {format}"); | |
| setupGroqConfig(); | |
| } | |
| void shouldReturnTicketResponseWithCorrectCategory() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("Mi pedido llegΓ³ roto", buildContext()); | |
| assertThat(result).isNotNull(); | |
| assertThat(result.category()).isEqualTo("URGENTE"); | |
| assertThat(result.status()).isEqualTo(ProcessingStatus.SUCCESS.name()); | |
| verifyNoInteractions(geminiChatClient); | |
| } | |
| void shouldUseGroqModelAsProvider() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.provider()).isEqualTo("groq/llama"); | |
| } | |
| void shouldSetInputAndOutputTokens() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.inputTokens()).isEqualTo(100); | |
| assertThat(result.outputTokens()).isEqualTo(50); | |
| } | |
| void shouldCalculatePositiveCost() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.estimatedCostUsd()).isGreaterThan(BigDecimal.ZERO); | |
| } | |
| void shouldHaveNonNegativeLatency() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.latencyMs()).isGreaterThanOrEqualTo(0L); | |
| } | |
| void shouldPublishSuccessEvent() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| ArgumentCaptor<AiCallEvent> eventCaptor = ArgumentCaptor.forClass(AiCallEvent.class); | |
| verify(eventPublisher).publishEvent(eventCaptor.capture()); | |
| AiCallEvent event = eventCaptor.getValue(); | |
| assertThat(event.status()).isEqualTo(AuditStatus.SUCCESS); | |
| assertThat(event.provider()).isEqualTo("groq/llama"); | |
| } | |
| void shouldReflectCircuitBreakerState() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.circuitBreakerState()).isEqualTo("CLOSED"); | |
| } | |
| void shouldPropagateProcessingContextData() { | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| ProcessingContext ctx = buildContext(); | |
| ctx.markPiiDetected(); | |
| ctx.setMaskedDescription("texto con [EMAIL]"); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", ctx); | |
| assertThat(result.piiDetected()).isTrue(); | |
| assertThat(result.maskedDescription()).isEqualTo("texto con [EMAIL]"); | |
| } | |
| void shouldExtractJsonFromMarkdownFence() { | |
| String withFence = "```json\n" + VALID_JSON_RESPONSE + "\n```"; | |
| setupGroqChain(withFence); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.category()).isEqualTo("URGENTE"); | |
| } | |
| void shouldExtractJsonWithSurroundingText() { | |
| String withText = "AquΓ estΓ‘ la clasificaciΓ³n:\n" + VALID_JSON_RESPONSE + "\nEspero que ayude."; | |
| setupGroqChain(withText); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.category()).isEqualTo("URGENTE"); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // ERRORES EN LLAMADA A GROQ | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class CallLlmErrorTests { | |
| void setUp() { | |
| when(promptCacheService.getPrompt()).thenReturn("system prompt {format}"); | |
| setupGroqConfig(); | |
| } | |
| void shouldThrowAIModelCallExceptionOnHttpFailure() { | |
| when(chatClient.prompt()).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.call()).thenThrow(new RuntimeException("Connection refused")); | |
| assertThatThrownBy(() -> aiEngineService.callLlm("descripciΓ³n", buildContext())) | |
| .isInstanceOf(AIModelCallException.class) | |
| .hasMessageContaining("Error llamando al LLM externo"); | |
| } | |
| void shouldThrowAIResponseParseExceptionWhenPromptFails() { | |
| when(promptCacheService.getPrompt()).thenThrow(new RuntimeException("File not found")); | |
| assertThatThrownBy(() -> aiEngineService.callLlm("descripciΓ³n", buildContext())) | |
| .isInstanceOf(AIResponseParseException.class) | |
| .hasMessageContaining("Error cargando la plantilla del prompt"); | |
| } | |
| void shouldRecordErrorMetricOnHttpFailure() { | |
| when(chatClient.prompt()).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.call()).thenThrow(new RuntimeException("timeout")); | |
| assertThatThrownBy(() -> aiEngineService.callLlm("descripciΓ³n", buildContext())) | |
| .isInstanceOf(AIModelCallException.class); | |
| // Verificamos que la mΓ©trica se registrΓ³ realmente en el registry | |
| // (no solo que se llamΓ³ al mΓ©todo). SimpleMeterRegistry mantiene todo en memoria. | |
| Timer errorTimer = meterRegistry.find("ai.call.latency") | |
| .tag("provider", "groq") | |
| .tag("status", "error") | |
| .timer(); | |
| assertThat(errorTimer).isNotNull(); | |
| assertThat(errorTimer.count()).isEqualTo(1); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // FALLBACK β GROQ FALLA β GEMINI | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class FallbackToGeminiTests { | |
| void setUp() { | |
| when(promptCacheService.getPrompt()).thenReturn("system prompt {format}"); | |
| setupGeminiConfig(); | |
| } | |
| void shouldCallGeminiWhenGroqFails() { | |
| String geminiJson = VALID_JSON_RESPONSE | |
| .replace("\"URGENTE\"", "\"NORMAL\"") | |
| .replace("\"groq/llama\"", "\"gemini-2.5-flash\""); | |
| setupGeminiChain(geminiJson); | |
| when(geminiCircuitBreaker.executeSupplier(any())).thenAnswer(inv -> { | |
| java.util.function.Supplier<?> supplier = inv.getArgument(0); | |
| return supplier.get(); | |
| }); | |
| TicketResponse result = aiEngineService.fallbackClassify( | |
| "descripciΓ³n", | |
| buildContext(), | |
| new AIModelCallException("Groq down", new RuntimeException()) | |
| ); | |
| assertThat(result).isNotNull(); | |
| assertThat(result.category()).isEqualTo("NORMAL"); | |
| assertThat(result.provider()).isEqualTo("gemini-2.5-flash"); | |
| } | |
| void shouldUseGeminiModelAsProvider() { | |
| String jsonSinProvider = """ | |
| { | |
| "category": "URGENTE", | |
| "status": "SUCCESS", | |
| "inputTokens": 100, | |
| "outputTokens": 50, | |
| "estimatedCostUsd": 0.00001, | |
| "latencyMs": 300, | |
| "piiDetected": false, | |
| "securityLayersPassed": [], | |
| "securityLayersWithTiming": [], | |
| "maskedDescription": "texto", | |
| "processedAt": "2024-01-01T00:00:00Z", | |
| "circuitBreakerState": "CLOSED" | |
| } | |
| """; | |
| setupGeminiChain(jsonSinProvider); | |
| when(geminiCircuitBreaker.executeSupplier(any())).thenAnswer(inv -> { | |
| java.util.function.Supplier<?> supplier = inv.getArgument(0); | |
| return supplier.get(); | |
| }); | |
| TicketResponse result = aiEngineService.fallbackClassify( | |
| "descripciΓ³n", | |
| buildContext(), | |
| new AIModelCallException("error", new RuntimeException()) | |
| ); | |
| assertThat(result.provider()).isEqualTo("gemini-2.5-flash"); | |
| } | |
| void shouldPublishSuccessEventForGemini() { | |
| setupGeminiChain(VALID_JSON_RESPONSE); | |
| when(geminiCircuitBreaker.executeSupplier(any())).thenAnswer(inv -> { | |
| java.util.function.Supplier<?> supplier = inv.getArgument(0); | |
| return supplier.get(); | |
| }); | |
| aiEngineService.fallbackClassify( | |
| "descripciΓ³n", | |
| buildContext(), | |
| new AIModelCallException("error", new RuntimeException()) | |
| ); | |
| ArgumentCaptor<AiCallEvent> captor = ArgumentCaptor.forClass(AiCallEvent.class); | |
| verify(eventPublisher).publishEvent(captor.capture()); | |
| assertThat(captor.getValue().status()).isEqualTo(AuditStatus.SUCCESS); | |
| assertThat(captor.getValue().provider()).isEqualTo("gemini-2.5-flash"); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // EXTRACCIΓN DE JSON β extractJson | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class JsonExtractionTests { | |
| void setUp() { | |
| when(promptCacheService.getPrompt()).thenReturn("prompt {format}"); | |
| setupGroqConfig(); | |
| } | |
| void shouldParseJsonInCodeBlockWithoutLanguage() { | |
| String withFenceNoLang = "```\n" + VALID_JSON_RESPONSE + "\n```"; | |
| setupGroqChain(withFenceNoLang); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.category()).isEqualTo("URGENTE"); | |
| } | |
| void shouldParseJsonWithPreamble() { | |
| String withPreamble = "La categorΓa del ticket es:\n" + VALID_JSON_RESPONSE; | |
| setupGroqChain(withPreamble); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.category()).isEqualTo("URGENTE"); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // ESTADO DEL CIRCUIT BREAKER | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class CircuitBreakerStateTests { | |
| void setUp() { | |
| when(promptCacheService.getPrompt()).thenReturn("prompt {format}"); | |
| setupGroqConfig(); | |
| } | |
| void shouldReflectOpenState() { | |
| when(groqCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.OPEN); | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.circuitBreakerState()).isEqualTo("OPEN"); | |
| } | |
| void shouldReflectHalfOpenState() { | |
| when(groqCircuitBreaker.getState()).thenReturn(CircuitBreaker.State.HALF_OPEN); | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.circuitBreakerState()).isEqualTo("HALF_OPEN"); | |
| } | |
| void shouldReturnUnknownWhenCircuitBreakerNotFound() { | |
| when(circuitBreakerRegistry.circuitBreaker("aiClassification")) | |
| .thenThrow(new RuntimeException("Not registered")); | |
| setupGroqChain(VALID_JSON_RESPONSE); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.circuitBreakerState()).isEqualTo("UNKNOWN"); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // CΓLCULO DE COSTOS | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class CostCalculationTests { | |
| void setUp() { | |
| when(promptCacheService.getPrompt()).thenReturn("prompt {format}"); | |
| } | |
| void costShouldBeZeroWhenTokensAreZero() { | |
| when(groqConfig.getModel()).thenReturn("groq/llama"); | |
| when(groqConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("0.05")); | |
| when(groqConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("0.10")); | |
| // Respuesta con 0 tokens | |
| ChatResponse response = mock(ChatResponse.class); | |
| Generation generation = mock(Generation.class); | |
| AssistantMessage msg = mock(AssistantMessage.class); | |
| ChatResponseMetadata metadata = mock(ChatResponseMetadata.class); | |
| Usage usage = mock(Usage.class); | |
| when(response.getResult()).thenReturn(generation); | |
| when(generation.getOutput()).thenReturn(msg); | |
| when(msg.getText()).thenReturn(VALID_JSON_RESPONSE); | |
| when(response.getMetadata()).thenReturn(metadata); | |
| when(metadata.getUsage()).thenReturn(usage); | |
| when(usage.getPromptTokens()).thenReturn(0); | |
| when(usage.getCompletionTokens()).thenReturn(0); | |
| when(chatClient.prompt()).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.system(any(Consumer.class))).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.user(anyString())).thenReturn(groqRequestSpec); | |
| when(groqRequestSpec.call()).thenReturn(groqCallSpec); | |
| when(groqCallSpec.chatResponse()).thenReturn(response); | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.estimatedCostUsd()).isEqualByComparingTo(BigDecimal.ZERO); | |
| } | |
| void shouldCalculateCostCorrectly() { | |
| // 1_000_000 tokens a $1.00/millΓ³n = $1.00 | |
| // Para 100 tokens input a $1.00/M y 50 tokens output a $2.00/M: | |
| // inputCost = 100 / 1_000_000 * 1.00 = 0.0001 | |
| // outputCost = 50 / 1_000_000 * 2.00 = 0.0001 | |
| // total = 0.0002 | |
| when(groqConfig.getModel()).thenReturn("groq/llama"); | |
| when(groqConfig.getCostPerMillionInput()).thenReturn(new BigDecimal("1.00")); | |
| when(groqConfig.getCostPerMillionOutput()).thenReturn(new BigDecimal("2.00")); | |
| setupGroqChain(VALID_JSON_RESPONSE); // 100 input, 50 output | |
| TicketResponse result = aiEngineService.callLlm("descripciΓ³n", buildContext()); | |
| assertThat(result.estimatedCostUsd()) | |
| .isEqualByComparingTo(new BigDecimal("0.0002")); | |
| } | |
| } | |
| } | |
| } |