Junjie
3 天以前 63b01db83d9aad8a15276b4236a9a22e4aeef065
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package com.zy.ai.gateway;
 
import com.zy.ai.entity.LlmCallLog;
import com.zy.ai.entity.LlmRouteConfig;
import com.zy.ai.gateway.adapter.AiProviderException;
import com.zy.ai.gateway.adapter.AiProviderAdapter;
import com.zy.ai.gateway.adapter.AiProviderAdapterRegistry;
import com.zy.ai.gateway.model.AiMessage;
import com.zy.ai.gateway.model.AiRequest;
import com.zy.ai.gateway.model.AiResponse;
import com.zy.ai.gateway.model.AiStreamEvent;
import com.zy.ai.service.LlmCallLogService;
import com.zy.ai.service.LlmRoutingService;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import reactor.core.publisher.Flux;
 
import java.util.List;
import java.util.Map;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
 
class AiGatewayServiceTest {
 
    @Test
    void generateSwitchesToNextRouteWhenFirstRouteFails() {
        LlmRouteConfig firstRoute = route(1L, "first");
        LlmRouteConfig secondRoute = route(2L, "second");
        LlmRoutingService routingService = mock(LlmRoutingService.class);
        when(routingService.listAvailableRoutes()).thenReturn(List.of(firstRoute, secondRoute));
 
        AiProviderAdapter adapter = new FailingThenSuccessAdapter();
        LlmCallLogService callLogService = mock(LlmCallLogService.class);
        AiGatewayService gatewayService = new AiGatewayService(
                routingService,
                new AiProviderAdapterRegistry(List.of(adapter)),
                callLogService
        );
 
        AiResponse response = gatewayService.generate(new AiRequest());
 
        assertEquals("ok", response.getText());
        verify(routingService).markFailure(1L, "first failed", true, 300);
        verify(routingService).markSuccess(2L);
        ArgumentCaptor<LlmCallLog> logCaptor = ArgumentCaptor.forClass(LlmCallLog.class);
        verify(callLogService, times(2)).saveIgnoreError(logCaptor.capture());
        List<LlmCallLog> logs = logCaptor.getAllValues();
        assertNotNull(logs.get(0).getTraceId());
        assertFalse(logs.get(0).getTraceId().isBlank());
        assertEquals(logs.get(0).getTraceId(), logs.get(1).getTraceId());
    }
 
    @Test
    void generateAcceptsToolOnlyResponse() {
        LlmRouteConfig route = route(1L, "tool-route");
        LlmRoutingService routingService = mock(LlmRoutingService.class);
        when(routingService.listAvailableRoutes()).thenReturn(List.of(route));
        LlmCallLogService callLogService = mock(LlmCallLogService.class);
 
        AiGatewayService gatewayService = new AiGatewayService(
                routingService,
                new AiProviderAdapterRegistry(List.of(new ToolOnlyAdapter())),
                callLogService
        );
 
        AiResponse response = gatewayService.generate(new AiRequest());
 
        assertNotNull(response.getMessage().getToolCalls());
        assertEquals("call_1", ((Map<?, ?>) response.getMessage().getToolCalls().get(0)).get("id"));
        verify(routingService).markSuccess(1L);
    }
 
    @Test
    void generateUsesSwitchOnQuotaForQuotaFailures() {
        LlmRouteConfig firstRoute = route(1L, "first");
        firstRoute.setSwitchOnError((short) 0);
        firstRoute.setSwitchOnQuota((short) 1);
        LlmRouteConfig secondRoute = route(2L, "second");
 
        LlmRoutingService routingService = mock(LlmRoutingService.class);
        when(routingService.listAvailableRoutes()).thenReturn(List.of(firstRoute, secondRoute));
        LlmCallLogService callLogService = mock(LlmCallLogService.class);
 
        AiGatewayService gatewayService = new AiGatewayService(
                routingService,
                new AiProviderAdapterRegistry(List.of(new QuotaThenSuccessAdapter())),
                callLogService
        );
 
        AiResponse response = gatewayService.generate(new AiRequest());
 
        assertEquals("ok", response.getText());
        verify(routingService).markFailure(1L, "quota exceeded", true, 300);
        verify(routingService).markSuccess(2L);
    }
 
    private LlmRouteConfig route(Long id, String name) {
        LlmRouteConfig route = new LlmRouteConfig();
        route.setId(id);
        route.setName(name);
        route.setBaseUrl("https://example.com/v1");
        route.setApiKey("sk-test");
        route.setModel("gpt-test");
        route.setProviderType("OPENAI_COMPATIBLE");
        route.setProtocolType("OPENAI_CHAT_COMPLETIONS");
        route.setSwitchOnError((short) 1);
        route.setCooldownSeconds(300);
        return route;
    }
 
    private static class FailingThenSuccessAdapter implements AiProviderAdapter {
 
        @Override
        public boolean supports(LlmRouteConfig routeConfig, AiRequest request) {
            return true;
        }
 
        @Override
        public AiResponse generate(LlmRouteConfig routeConfig, AiRequest request) {
            if ("first".equals(routeConfig.getName())) {
                throw new IllegalStateException("first failed");
            }
            AiResponse response = new AiResponse();
            response.setText("ok");
            return response;
        }
 
        @Override
        public Flux<AiStreamEvent> stream(LlmRouteConfig routeConfig, AiRequest request) {
            return Flux.empty();
        }
    }
 
    private static class ToolOnlyAdapter implements AiProviderAdapter {
 
        @Override
        public boolean supports(LlmRouteConfig routeConfig, AiRequest request) {
            return true;
        }
 
        @Override
        public AiResponse generate(LlmRouteConfig routeConfig, AiRequest request) {
            AiMessage message = new AiMessage();
            message.setRole("assistant");
            message.setToolCalls(List.of(Map.of("id", "call_1")));
 
            AiResponse response = new AiResponse();
            response.setMessage(message);
            return response;
        }
 
        @Override
        public Flux<AiStreamEvent> stream(LlmRouteConfig routeConfig, AiRequest request) {
            return Flux.empty();
        }
    }
 
    private static class QuotaThenSuccessAdapter implements AiProviderAdapter {
 
        @Override
        public boolean supports(LlmRouteConfig routeConfig, AiRequest request) {
            return true;
        }
 
        @Override
        public AiResponse generate(LlmRouteConfig routeConfig, AiRequest request) {
            if ("first".equals(routeConfig.getName())) {
                throw new AiProviderException("quota exceeded", routeConfig.getId(), 429, "insufficient_quota");
            }
            AiResponse response = new AiResponse();
            response.setText("ok");
            return response;
        }
 
        @Override
        public Flux<AiStreamEvent> stream(LlmRouteConfig routeConfig, AiRequest request) {
            return Flux.empty();
        }
    }
}