Sxnan commented on code in PR #27163: URL: https://github.com/apache/flink/pull/27163#discussion_r2480363366
########## flink-models/flink-model-openai/src/main/java/org/apache/flink/model/openai/OpenAIOptions.java: ########## @@ -0,0 +1,215 @@ +/* + * 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.flink.model.openai; + +import org.apache.flink.configuration.ConfigOption; +import org.apache.flink.configuration.ConfigOptions; +import org.apache.flink.configuration.description.Description; + +import static org.apache.flink.configuration.description.TextElement.code; +import static org.apache.flink.configuration.description.TextElement.text; + +/** Options for OpenAI API Model Functions. */ +public class OpenAIOptions { + + // ------------------------------------------------------------------------ + // Common Options + // ------------------------------------------------------------------------ + + public static final ConfigOption<String> ENDPOINT = + ConfigOptions.key("endpoint") + .stringType() + .noDefaultValue() + .withDescription( + Description.builder() + .text( + "Full URL of the OpenAI API endpoint, e.g., %s or %s", + code("https://api.openai.com/v1/chat/completions"), + code("https://api.openai.com/v1/embeddings")) + .build()); + + public static final ConfigOption<String> API_KEY = + ConfigOptions.key("api-key") + .stringType() + .noDefaultValue() + .withDescription("OpenAI API key for authentication."); + + public static final ConfigOption<String> MODEL = + ConfigOptions.key("model") + .stringType() + .noDefaultValue() + .withDescription( + Description.builder() + .text( + "Model name, e.g., %s, %s.", + code("gpt-3.5-turbo"), code("text-embedding-ada-002")) + .build()); + + public static final ConfigOption<Integer> MAX_CONTEXT_SIZE = + ConfigOptions.key("max-context-size") + .intType() + .noDefaultValue() + .withDescription( + "Max number of tokens for context. context-overflow-action would be triggered if this threshold is exceeded."); + + public static final ConfigOption<ContextOverflowAction> CONTEXT_OVERFLOW_ACTION = + ConfigOptions.key("context-overflow-action") + .enumType(ContextOverflowAction.class) + .defaultValue(ContextOverflowAction.TRUNCATED_TAIL) + .withDescription( + Description.builder() + .text("Action to handle context overflows. Supported actions:") + .linebreak() + .text(ContextOverflowAction.getAllValuesAndDescriptions()) + .build()); + + public static final ConfigOption<AbstractOpenAIModelFunction.ErrorHandlingStrategy> + ERROR_HANDLING_STRATEGY = + ConfigOptions.key("error-handling-strategy") + .enumType(AbstractOpenAIModelFunction.ErrorHandlingStrategy.class) + .defaultValue(AbstractOpenAIModelFunction.ErrorHandlingStrategy.RETRY) + .withDescription( + Description.builder() + .text( + "Strategy for handling errors during model requests.") + .linebreak() + .text("Supported strategies:") + .linebreak() + .list( + text( + AbstractOpenAIModelFunction + .ErrorHandlingStrategy + .RETRY + + ": Retry sending the request. The retrying behavior is limited by " + + "retry-num and retry-fallback-strategy."), + text( + AbstractOpenAIModelFunction + .ErrorHandlingStrategy + .FAILOVER + + ": Throw exceptions and fail the Flink job."), + text( + AbstractOpenAIModelFunction + .ErrorHandlingStrategy + .IGNORE + + ": Ignore the input that caused the error and continue. The error itself would be recorded in log.")) + .build()); + + // The model service enforces rate-limiting constraints, necessitating retry mechanisms in + // most operational scenarios. + public static final ConfigOption<Integer> RETRY_NUM = + ConfigOptions.key("retry-num") + .intType() + .defaultValue(100) + .withDescription("Number of retry for OpenAI client requests."); + + public static final ConfigOption<AbstractOpenAIModelFunction.ErrorHandlingStrategy> + RETRY_FALLBACK_STRATEGY = + ConfigOptions.key("retry-fallback-strategy") + .enumType(AbstractOpenAIModelFunction.ErrorHandlingStrategy.class) + .defaultValue( + AbstractOpenAIModelFunction.ErrorHandlingStrategy.FAILOVER) + .withDescription( + "Fallback strategy to employ if the retry attempts are exhausted." Review Comment: This is inconsistent with the description in `openai.md`. Can we generate the configuration docs like the other options? ########## flink-models/flink-model-openai/src/main/java/org/apache/flink/model/openai/AbstractOpenAIModelFunction.java: ########## @@ -18,117 +18,86 @@ package org.apache.flink.model.openai; -import org.apache.flink.configuration.ConfigOption; -import org.apache.flink.configuration.ConfigOptions; import org.apache.flink.configuration.ReadableConfig; -import org.apache.flink.configuration.description.Description; -import org.apache.flink.table.api.config.ExecutionConfigOptions; +import org.apache.flink.table.api.DataTypes; import org.apache.flink.table.catalog.Column; import org.apache.flink.table.catalog.ResolvedSchema; +import org.apache.flink.table.data.ArrayData; +import org.apache.flink.table.data.GenericArrayData; +import org.apache.flink.table.data.GenericMapData; +import org.apache.flink.table.data.GenericRowData; import org.apache.flink.table.data.RowData; +import org.apache.flink.table.data.StringData; +import org.apache.flink.table.data.binary.BinaryStringData; import org.apache.flink.table.factories.ModelProviderFactory; import org.apache.flink.table.functions.AsyncPredictFunction; import org.apache.flink.table.functions.FunctionContext; +import org.apache.flink.table.types.DataType; import org.apache.flink.table.types.logical.LogicalType; import org.apache.flink.table.types.logical.VarCharType; +import org.apache.flink.util.ExceptionUtils; +import org.apache.flink.util.Preconditions; import com.openai.client.OpenAIClientAsync; +import com.openai.core.http.Headers; +import com.openai.errors.OpenAIServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.function.Function; import java.util.stream.Collectors; -import static org.apache.flink.configuration.description.TextElement.code; - /** Abstract parent class for {@link AsyncPredictFunction}s for OpenAI API. */ public abstract class AbstractOpenAIModelFunction extends AsyncPredictFunction { private static final Logger LOG = LoggerFactory.getLogger(AbstractOpenAIModelFunction.class); - public static final ConfigOption<String> ENDPOINT = - ConfigOptions.key("endpoint") - .stringType() - .noDefaultValue() - .withDescription( - Description.builder() - .text( - "Full URL of the OpenAI API endpoint, e.g., %s or %s", - code("https://api.openai.com/v1/chat/completions"), - code("https://api.openai.com/v1/embeddings")) - .build()); - - public static final ConfigOption<String> API_KEY = - ConfigOptions.key("api-key") - .stringType() - .noDefaultValue() - .withDescription("OpenAI API key for authentication."); - - public static final ConfigOption<String> MODEL = - ConfigOptions.key("model") - .stringType() - .noDefaultValue() - .withDescription( - Description.builder() - .text( - "Model name, e.g., %s, %s.", - code("gpt-3.5-turbo"), code("text-embedding-ada-002")) - .build()); - - public static final ConfigOption<Integer> MAX_CONTEXT_SIZE = - ConfigOptions.key("max-context-size") - .intType() - .noDefaultValue() - .withDescription( - "Max number of tokens for context. context-overflow-action would be triggered if this threshold is exceeded."); - - public static final ConfigOption<ContextOverflowAction> CONTEXT_OVERFLOW_ACTION = - ConfigOptions.key("context-overflow-action") - .enumType(ContextOverflowAction.class) - .defaultValue(ContextOverflowAction.TRUNCATED_TAIL) - .withDescription( - Description.builder() - .text("Action to handle context overflows. Supported actions:") - .linebreak() - .text(ContextOverflowAction.getAllValuesAndDescriptions()) - .build()); - protected transient OpenAIClientAsync client; + private final ErrorHandlingStrategy errorHandlingStrategy; private final int numRetry; + private final ErrorHandlingStrategy retryFallbackStrategy; private final String baseUrl; private final String apiKey; private final String model; @Nullable private final Integer maxContextSize; private final ContextOverflowAction contextOverflowAction; + protected final List<String> outputColumnNames; public AbstractOpenAIModelFunction( ModelProviderFactory.Context factoryContext, ReadableConfig config) { - String endpoint = config.get(ENDPOINT); + String endpoint = config.get(OpenAIOptions.ENDPOINT); this.baseUrl = endpoint.replaceAll(String.format("/%s/*$", getEndpointSuffix()), ""); - this.apiKey = config.get(API_KEY); - // The model service enforces rate-limiting constraints, necessitating retry mechanisms in - // most operational scenarios. Within the asynchronous operator framework, the system is - // designed to process up to - // config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_LOOKUP_BUFFER_CAPACITY) concurrent - // requests in parallel. To mitigate potential performance degradation from simultaneous - // requests, a dynamic retry strategy is implemented where the maximum retry count is - // directly proportional to the configured parallelism level, ensuring robust error - // resilience while maintaining throughput efficiency. + this.apiKey = config.get(OpenAIOptions.API_KEY); + + this.errorHandlingStrategy = config.get(OpenAIOptions.ERROR_HANDLING_STRATEGY); this.numRetry = - config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_LOOKUP_BUFFER_CAPACITY) * 10; - this.model = config.get(MODEL); - this.maxContextSize = config.get(MAX_CONTEXT_SIZE); - this.contextOverflowAction = config.get(CONTEXT_OVERFLOW_ACTION); + this.errorHandlingStrategy == ErrorHandlingStrategy.RETRY + ? config.get(OpenAIOptions.RETRY_NUM) + : 0; + this.model = config.get(OpenAIOptions.MODEL); + this.maxContextSize = config.get(OpenAIOptions.MAX_CONTEXT_SIZE); + this.contextOverflowAction = config.get(OpenAIOptions.CONTEXT_OVERFLOW_ACTION); + this.retryFallbackStrategy = config.get(OpenAIOptions.RETRY_FALLBACK_STRATEGY); + Preconditions.checkArgument( Review Comment: Can we introduce an enum class, which only contains the valid options, for `RETRY_FALLBACK_STRATEGY` ########## docs/content/docs/connectors/models/openai.md: ########## @@ -157,6 +157,45 @@ FROM ML_PREDICT( </ul> </td> </tr> + <tr> Review Comment: We may want to describe how to use the metadata column to extract the error message and give an example. -- 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]
