weiqingy commented on code in PR #695:
URL: https://github.com/apache/flink-agents/pull/695#discussion_r3285556334


##########
integrations/chat-models/openai/src/main/java/org/apache/flink/agents/integrations/chatmodels/openai/OpenAIChatCompletionsUtils.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * 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.ObjectMapper;
+import com.openai.core.JsonValue;
+import com.openai.models.chat.completions.ChatCompletionAssistantMessageParam;
+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.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 java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Static helpers for converting between Flink Agents {@link ChatMessage} and 
OpenAI Chat
+ * Completions API message types. Restricted to message conversion (no 
tool-definition conversion —
+ * that stays per-connection).
+ *
+ * <p>Used by both {@code OpenAICompletionsConnection} (OpenAI / 
OpenAI-compatible providers) and
+ * {@code AzureOpenAIChatModelConnection} (Azure OpenAI). Both rely on the 
same openai-java SDK
+ * message types.
+ */
+final class OpenAIChatCompletionsUtils {
+
+    private OpenAIChatCompletionsUtils() {}
+
+    private static final ObjectMapper mapper = new ObjectMapper();
+    private static final TypeReference<Map<String, Object>> MAP_TYPE = new 
TypeReference<>() {};
+
+    /** Convert a list of Flink Agents ChatMessages to OpenAI 
ChatCompletionMessageParams. */
+    public static List<ChatCompletionMessageParam> convertToOpenAIMessages(
+            List<ChatMessage> messages) {
+        return messages.stream()
+                .map(OpenAIChatCompletionsUtils::convertToOpenAIMessage)
+                .collect(Collectors.toList());
+    }
+
+    /** Convert a single Flink Agents ChatMessage to an OpenAI 
ChatCompletionMessageParam. */
+    public static ChatCompletionMessageParam 
convertToOpenAIMessage(ChatMessage message) {
+        MessageRole role = message.getRole();
+        String content = Optional.ofNullable(message.getContent()).orElse("");
+
+        switch (role) {
+            case SYSTEM:
+                return ChatCompletionMessageParam.ofSystem(
+                        
ChatCompletionSystemMessageParam.builder().content(content).build());
+            case USER:
+                return ChatCompletionMessageParam.ofUser(
+                        
ChatCompletionUserMessageParam.builder().content(content).build());
+            case ASSISTANT:
+                ChatCompletionAssistantMessageParam.Builder assistantBuilder =
+                        ChatCompletionAssistantMessageParam.builder();
+                if (!content.isEmpty()) {
+                    assistantBuilder.content(content);
+                }
+                List<Map<String, Object>> toolCalls = message.getToolCalls();
+                if (toolCalls != null && !toolCalls.isEmpty()) {
+                    
assistantBuilder.toolCalls(convertAssistantToolCalls(toolCalls));
+                }
+                Object refusal = message.getExtraArgs().get("refusal");
+                if (refusal instanceof String) {
+                    assistantBuilder.refusal((String) refusal);
+                }
+                return 
ChatCompletionMessageParam.ofAssistant(assistantBuilder.build());
+            case TOOL:
+                ChatCompletionToolMessageParam.Builder toolBuilder =
+                        
ChatCompletionToolMessageParam.builder().content(content);
+                Object toolCallId = message.getExtraArgs().get("externalId");
+                if (toolCallId == null) {
+                    throw new IllegalArgumentException(
+                            "Tool message must have an externalId in 
extraArgs.");
+                }
+                toolBuilder.toolCallId(toolCallId.toString());
+                return ChatCompletionMessageParam.ofTool(toolBuilder.build());
+            default:
+                throw new IllegalArgumentException("Unsupported role: " + 
role);
+        }
+    }
+
+    /**
+     * Convert an OpenAI {@link ChatCompletionMessage} to a Flink Agents 
{@link ChatMessage}.
+     * Caller-provided {@code extraArgs} are copied into the returned 
ChatMessage's own extraArgs
+     * map (the caller's input is treated as read-only; {@code Map.of()} is 
safe). Additionally,
+     * {@code message.refusal()} is written as {@code extraArgs["refusal"]} 
when present, preserving
+     * prior Java behavior.
+     */
+    public static ChatMessage convertFromOpenAIMessage(

Review Comment:
   The `extraArgs` parameter is dead today — both call sites (this one and 
`AzureOpenAIChatModelConnection.chat`) pass `Map.of()`. Also, the body copies 
caller args first (`response.getExtraArgs().putAll(extraArgs)`) and then writes 
`refusal` after, so a caller-supplied `"refusal"` key would be silently 
overwritten by `message.refusal()`. The precedence isn't obvious from the 
signature.
   
   Should we drop the parameter until there's a real caller that needs it? That 
would keep the API surface minimal and avoid locking in surprising precedence. 
Or, if we want to keep it as a forward-looking hook, should we document the 
override behavior in the Javadoc?
   



-- 
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]

Reply via email to