Copilot commented on code in PR #6060:
URL: https://github.com/apache/shenyu/pull/6060#discussion_r2280395008
##########
shenyu-common/src/main/java/org/apache/shenyu/common/dto/convert/rule/AiProxyHandle.java:
##########
@@ -218,24 +242,212 @@ public boolean equals(final Object o) {
&& Objects.equals(model, that.model)
&& Objects.equals(temperature, that.temperature)
&& Objects.equals(maxTokens, that.maxTokens)
- && Objects.equals(stream, that.stream);
+ && Objects.equals(stream, that.stream)
+ && Objects.equals(fallbackConfig, that.fallbackConfig);
}
-
+
@Override
public int hashCode() {
- return Objects.hash(provider, baseUrl, apiKey, model, temperature,
maxTokens, stream);
+ return Objects.hash(provider, baseUrl, apiKey, model, temperature,
maxTokens, stream, fallbackConfig);
}
-
+
@Override
public String toString() {
return "AiProxyHandle{"
+ "provider='" + provider + '\''
+ ", baseUrl='" + baseUrl + '\''
- + ", apiKey='" + apiKey + '\''
+ + ", apiKey='" + maskApiKey(apiKey) + '\''
+ ", model='" + model + '\''
+ ", temperature=" + temperature
+ ", maxTokens=" + maxTokens
+ ", stream=" + stream
+ + ", fallbackConfig=" + fallbackConfig
+ '}';
}
-}
+
+ public static String maskApiKey(final String apiKey) {
+ if (Objects.isNull(apiKey) || apiKey.length() <= 7) {
+ return apiKey;
+ }
+ if (Objects.isNull(apiKey) || apiKey.isEmpty()) {
Review Comment:
This null check is redundant as it was already performed on line 269. The
condition `apiKey.length() <= 7` on line 269 would have thrown a
NullPointerException if apiKey was null, so this check should be removed or the
logic should be restructured.
```suggestion
if (apiKey.isEmpty()) {
```
##########
shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy-enhanced/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/handler/AiProxyPluginHandler.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.ai.proxy.enhanced.handler;
+
+import org.apache.shenyu.common.constant.Constants;
+import org.apache.shenyu.common.dto.PluginData;
+import org.apache.shenyu.common.dto.SelectorData;
+import org.apache.shenyu.common.dto.convert.rule.AiProxyHandle;
+import org.apache.shenyu.common.enums.PluginEnum;
+import org.apache.shenyu.common.utils.GsonUtils;
+import org.apache.shenyu.plugin.ai.proxy.enhanced.cache.ChatClientCache;
+import org.apache.shenyu.plugin.base.cache.CommonHandleCache;
+import org.apache.shenyu.plugin.base.handler.PluginDataHandler;
+import org.apache.shenyu.plugin.base.utils.CacheKeyUtils;
+
+import java.util.Objects;
+
+/**
+ * this is ai proxy plugin handler.
+ */
+public class AiProxyPluginHandler implements PluginDataHandler {
+
+ private final CommonHandleCache<String, AiProxyHandle>
selectorCachedHandle = new CommonHandleCache<>();
+
+ private final ChatClientCache chatClientCache;
+
+ public AiProxyPluginHandler(final ChatClientCache chatClientCache) {
+ this.chatClientCache = chatClientCache;
+ }
+
+ @Override
+ public void handlerPlugin(final PluginData pluginData) {
+ // Note: The logic for handling global plugin configuration with
Singleton has been removed
+ // as it's part of the legacy pattern we are moving away from.
+ // Global configs should be managed as Spring beans if needed.
Review Comment:
[nitpick] This comment explains removed functionality rather than
documenting current behavior. Consider updating to describe what the method
currently does: 'Currently no global plugin configuration handling is
performed.'
```suggestion
// No global plugin configuration handling is performed.
```
##########
shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy-enhanced/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyExecutorService.java:
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.plugin.ai.proxy.enhanced.service;
+
+import org.apache.shenyu.plugin.ai.common.strategy.SimpleModelFallbackStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.ai.chat.client.ChatClient;
+import org.springframework.ai.chat.model.ChatResponse;
+import org.springframework.ai.retry.NonTransientAiException;
+import org.springframework.stereotype.Service;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+import reactor.core.scheduler.Schedulers;
+import reactor.util.retry.Retry;
+
+import java.time.Duration;
+import java.util.Optional;
+
+/**
+ * AI proxy executor service.
+ */
+@Service
+public class AiProxyExecutorService {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(AiProxyExecutorService.class);
+
+ /**
+ * Execute the AI call with retry and fallback.
+ *
+ * @param mainClient the main chat client
+ * @param fallbackClientOpt the optional fallback chat client
+ * @param requestBody the request body
+ * @return a Mono containing the ChatResponse
+ */
+ public Mono<ChatResponse> execute(final ChatClient mainClient, final
Optional<ChatClient> fallbackClientOpt, final String requestBody) {
+ final Mono<ChatResponse> mainCall = doChatCall(mainClient,
requestBody);
+
+ return mainCall
+ .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))
+ .filter(throwable -> !(throwable instanceof
NonTransientAiException))
+ .onRetryExhaustedThrow((retryBackoffSpec, retrySignal)
-> {
+ LOG.warn("Retries exhausted for AI call after {}
attempts.",
+ retrySignal.totalRetries(),
retrySignal.failure());
+ return new NonTransientAiException("Retries
exhausted. Triggering fallback.",
+ retrySignal.failure());
+ }))
+ .onErrorResume(NonTransientAiException.class,
+ throwable -> handleFallback(throwable,
fallbackClientOpt, requestBody));
+ }
+
+ protected Mono<ChatResponse> doChatCall(final ChatClient client, final
String requestBody) {
+ return Mono.fromCallable(() ->
client.prompt().user(requestBody).call().chatResponse())
+ .subscribeOn(Schedulers.boundedElastic());
+ }
+
+ private Mono<ChatResponse> handleFallback(final Throwable throwable, final
Optional<ChatClient> fallbackClientOpt, final String requestBody) {
+ LOG.warn("AI main call failed or retries exhausted, attempting to
fallback...", throwable);
+
+ if (fallbackClientOpt.isEmpty()) {
+ return Mono.error(throwable);
+ }
+
+ return
SimpleModelFallbackStrategy.INSTANCE.fallback(fallbackClientOpt.get(),
requestBody, throwable);
+ }
+
+ /**
+ * Execute the AI call with retry and fallback.
+ *
+ * @param mainClient the main chat client
+ * @param fallbackClientOpt the optional fallback chat client
+ * @param requestBody the request body
+ * @return a Flux containing the ChatResponse
+ */
+ public Flux<ChatResponse> executeStream(final ChatClient mainClient, final
Optional<ChatClient> fallbackClientOpt, final String requestBody) {
+ final Flux<ChatResponse> mainStream = doChatStream(mainClient,
requestBody);
+
+ return mainStream
+ .retryWhen(Retry.max(1)
+ .onRetryExhaustedThrow((retryBackoffSpec, retrySignal)
-> {
+ LOG.warn("Retrying stream once failed. Attempts:
{}. Triggering fallback.",
+ retrySignal.totalRetries(),
retrySignal.failure());
+ return new NonTransientAiException("Stream failed
after 1 retry. Triggering fallback.");
Review Comment:
The NonTransientAiException constructor call is missing the cause parameter.
It should include the original failure: `new NonTransientAiException("Stream
failed after 1 retry. Triggering fallback.", retrySignal.failure())`
```suggestion
return new NonTransientAiException("Stream
failed after 1 retry. Triggering fallback.", retrySignal.failure());
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]