xli1996 commented on code in PR #320: URL: https://github.com/apache/flink-agents/pull/320#discussion_r2558417812
########## integrations/chat-models/openai/src/main/java/org/apache/flink/agents/integrations/chatmodels/openai/OpenAIChatModelConnection.java: ########## @@ -0,0 +1,410 @@ +/* + * 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.agents.integrations.chatmodels.openai; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.openai.client.OpenAIClient; +import com.openai.client.okhttp.OpenAIOkHttpClient; +import com.openai.core.JsonValue; +import com.openai.models.ChatModel; +import com.openai.models.FunctionDefinition; +import com.openai.models.FunctionParameters; +import com.openai.models.chat.completions.ChatCompletion; +import com.openai.models.chat.completions.ChatCompletionAssistantMessageParam; +import com.openai.models.chat.completions.ChatCompletionCreateParams; +import com.openai.models.chat.completions.ChatCompletionFunctionTool; +import com.openai.models.chat.completions.ChatCompletionMessage; +import com.openai.models.chat.completions.ChatCompletionMessageFunctionToolCall; +import com.openai.models.chat.completions.ChatCompletionMessageParam; +import com.openai.models.chat.completions.ChatCompletionMessageToolCall; +import com.openai.models.chat.completions.ChatCompletionSystemMessageParam; +import com.openai.models.chat.completions.ChatCompletionTool; +import com.openai.models.chat.completions.ChatCompletionToolMessageParam; +import com.openai.models.chat.completions.ChatCompletionUserMessageParam; +import org.apache.flink.agents.api.chat.messages.ChatMessage; +import org.apache.flink.agents.api.chat.messages.MessageRole; +import org.apache.flink.agents.api.chat.model.BaseChatModelConnection; +import org.apache.flink.agents.api.resource.Resource; +import org.apache.flink.agents.api.resource.ResourceDescriptor; +import org.apache.flink.agents.api.resource.ResourceType; +import org.apache.flink.agents.api.tools.Tool; +import org.apache.flink.agents.api.tools.ToolMetadata; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.stream.Collectors; + +/** + * A chat model integration for the OpenAI Chat Completions service using the official Java SDK. + * + * <p>Supported connection parameters: + * + * <ul> + * <li><b>api_key</b> (required): OpenAI API key + * <li><b>api_base_url</b> (optional): Base URL for OpenAI API (defaults to + * https://api.openai.com/v1) + * <li><b>timeout</b> (optional): Timeout in seconds for API requests + * <li><b>max_retries</b> (optional): Maximum number of retry attempts (default: 2) + * <li><b>default_headers</b> (optional): Map of default headers to include in all requests + * <li><b>model</b> (optional): Default model to use if not specified in setup + * </ul> + * + * <p>Example usage: + * + * <pre>{@code + * public class MyAgent extends Agent { + * @ChatModelConnection + * public static ResourceDesc openAI() { + * return ResourceDescriptor.Builder.newBuilder(OpenAIChatModelConnection.class.getName()) + * .addInitialArgument("api_key", System.getenv("OPENAI_API_KEY")) + * .addInitialArgument("api_base_url", "https://api.openai.com/v1") + * .addInitialArgument("timeout", 120) + * .addInitialArgument("max_retries", 3) + * .addInitialArgument("default_headers", Map.of("X-Custom-Header", "value")) + * .build(); + * } + * } + * }</pre> + */ +public class OpenAIChatModelConnection extends BaseChatModelConnection { + + private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {}; + + private final ObjectMapper mapper = new ObjectMapper(); + private final OpenAIClient client; + private final String defaultModel; + + public OpenAIChatModelConnection( + ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) { + super(descriptor, getResource); + + String apiKey = descriptor.getArgument("api_key"); + if (apiKey == null || apiKey.isBlank()) { + throw new IllegalArgumentException("api_key should not be null or empty."); + } + + OpenAIOkHttpClient.Builder builder = new OpenAIOkHttpClient.Builder().apiKey(apiKey); + + String apiBaseUrl = descriptor.getArgument("api_base_url"); + if (apiBaseUrl != null && !apiBaseUrl.isBlank()) { + builder.baseUrl(apiBaseUrl); + } + + Integer timeoutSeconds = descriptor.getArgument("timeout"); + if (timeoutSeconds != null && timeoutSeconds > 0) { + builder.timeout(Duration.ofSeconds(timeoutSeconds)); + } + + Integer maxRetries = descriptor.getArgument("max_retries"); + if (maxRetries != null && maxRetries >= 0) { + builder.maxRetries(maxRetries); + } + + Map<String, String> defaultHeaders = descriptor.getArgument("default_headers"); + if (defaultHeaders != null && !defaultHeaders.isEmpty()) { + for (Map.Entry<String, String> header : defaultHeaders.entrySet()) { + builder.putHeader(header.getKey(), header.getValue()); + } + } + + this.defaultModel = descriptor.getArgument("model"); + this.client = builder.build(); + } + + @Override + public ChatMessage chat( + List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) { + try { + ChatCompletionCreateParams params = buildRequest(messages, tools, arguments); + ChatCompletion completion = client.chat().completions().create(params); + return convertResponse(completion); + } catch (Exception e) { + throw new RuntimeException("Failed to call OpenAI chat completions API.", e); + } + } + + private ChatCompletionCreateParams buildRequest( + List<ChatMessage> messages, List<Tool> tools, Map<String, Object> rawArguments) { + Map<String, Object> arguments = + rawArguments != null ? new HashMap<>(rawArguments) : new HashMap<>(); + + boolean strictMode = Boolean.TRUE.equals(arguments.remove("strict")); + String modelName = (String) arguments.remove("model"); + if (modelName == null || modelName.isBlank()) { + modelName = this.defaultModel; + } + + ChatCompletionCreateParams.Builder builder = + ChatCompletionCreateParams.builder() + .model(ChatModel.of(modelName)) + .messages( + messages.stream() + .map(this::convertToOpenAIMessage) + .collect(Collectors.toList())); + + if (tools != null && !tools.isEmpty()) { + builder.tools(convertTools(tools, strictMode)); + } + + @SuppressWarnings("unchecked") + Map<String, Object> additionalKwargs = + (Map<String, Object>) arguments.remove("additional_kwargs"); + if (additionalKwargs != null) { + additionalKwargs.forEach( + (key, value) -> builder.putAdditionalBodyProperty(key, toJsonValue(value))); + } + Review Comment: thanks for catching it, I have fixed it. -- 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]
