alnzng commented on code in PR #128:
URL: https://github.com/apache/flink-agents/pull/128#discussion_r2308074731


##########
python/flink_agents/integrations/chat_models/openai/openai_chat_model.py:
##########
@@ -0,0 +1,280 @@
+################################################################################
+#  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.
+#################################################################################
+from typing import Any, Dict, List, Literal, Optional, Sequence
+
+import httpx
+from openai import NOT_GIVEN, OpenAI
+from pydantic import Field, PrivateAttr
+
+from flink_agents.api.chat_message import ChatMessage
+from flink_agents.api.chat_models.chat_model import (
+    BaseChatModelConnection,
+    BaseChatModelSetup,
+)
+from flink_agents.api.tools.tool import BaseTool
+from flink_agents.integrations.chat_models.openai.utils import (
+    convert_from_openai_message,
+    convert_to_openai_messages,
+    resolve_openai_credentials,
+)
+from flink_agents.integrations.chat_models.utils import to_openai_tool
+
+DEFAULT_OPENAI_MODEL = "gpt-3.5-turbo"
+
+
+class OpenAIChatModelConnection(BaseChatModelConnection):
+    """The connection to the OpenAI LLM.
+
+    Attributes:
+    ----------
+    api_key : str
+        The OpenAI API key.
+    api_base_url : str
+        The base URL for OpenAI API.
+    api_version : str
+        The API version for OpenAI API.
+    max_retries : int
+        The maximum number of API retries.
+    timeout : float
+        How long to wait, in seconds, for an API call before failing.
+    default_headers : Optional[Dict[str, str]]
+        The default headers for API requests.
+    reuse_client : bool
+        Whether to reuse the OpenAI client between requests.
+    """
+
+    api_key: str = Field(default=None, description="The OpenAI API key.")
+    api_base_url: str = Field(description="The base URL for OpenAI API.")
+    api_version: str = Field(description="The API version for OpenAI API.")
+    max_retries: int = Field(
+        default=3,
+        description="The maximum number of API retries.",
+        ge=0,
+    )
+    timeout: float = Field(
+        default=60.0,
+        description="The timeout, in seconds, for API requests.",
+        ge=0,
+    )
+    default_headers: Optional[Dict[str, str]] = Field(
+        default=None, description="The default headers for API requests."
+    )
+    reuse_client: bool = Field(
+        default=True,
+        description=(
+            "Reuse the OpenAI client between requests. When doing anything 
with large "
+            "volumes of async API calls, setting this to false can improve 
stability."
+        ),
+    )
+
+    _client: Optional[OpenAI] = PrivateAttr(default=None)
+    _http_client: Optional[httpx.Client] = PrivateAttr()
+
+    def __init__(
+        self,
+        *,
+        api_key: Optional[str] = None,
+        api_base_url: Optional[str] = None,
+        api_version: Optional[str] = None,
+        max_retries: int = 3,
+        timeout: float = 60.0,
+        reuse_client: bool = True,
+        http_client: Optional[httpx.Client] = None,
+        async_http_client: Optional[httpx.AsyncClient] = None,
+        **kwargs: Any,
+    ) -> None:
+        """Init method."""
+        api_key, api_base_url, api_version = resolve_openai_credentials(
+            api_key=api_key,
+            api_base_url=api_base_url,
+            api_version=api_version,
+        )
+        super().__init__(
+            api_key=api_key,
+            api_base_url=api_base_url,
+            api_version=api_version,
+            max_retries=max_retries,
+            timeout=timeout,
+            reuse_client=reuse_client,
+            **kwargs,
+        )
+
+        self._http_client = http_client
+        self._async_http_client = async_http_client
+
+    @property
+    def client(self) -> OpenAI:
+        """Get OpenAI client."""
+        config = self.__get_credential_kwargs()
+
+        if not self.reuse_client:
+            return OpenAI(**config)
+
+        if self._client is None:
+            self._client = OpenAI(**config)
+        return self._client
+
+    def __get_credential_kwargs(self) -> Dict[str, Any]:
+        return {
+            "api_key": self.api_key,
+            "base_url": self.api_base_url,
+            "max_retries": self.max_retries,
+            "timeout": self.timeout,
+            "default_headers": self.default_headers,
+            "http_client": self._http_client,
+        }
+
+    def chat(
+        self,
+        messages: Sequence[ChatMessage],
+        tools: Optional[List[BaseTool]] = None,
+        **kwargs: Any,
+    ) -> ChatMessage:
+        """Direct communication with model service for chat conversation.
+
+        Parameters
+        ----------
+        messages : Sequence[ChatMessage]
+            Input message sequence
+        tools : Optional[List]
+            List of tools that can be called by the model
+        **kwargs : Any
+            Additional parameters passed to the model service (e.g., 
temperature,
+            max_tokens, etc.)
+
+        Returns:
+        -------
+        ChatMessage
+            Model response message
+        """
+        tool_specs = None
+        if tools is not None:
+            tool_specs = [to_openai_tool(tool.metadata) for tool in tools]
+            strict = kwargs.get("strict", False)
+            for tool_spec in tool_specs:
+                if tool_spec["type"] == "function":
+                    tool_spec["function"]["strict"] = strict
+                    
tool_spec["function"]["parameters"]["additionalProperties"] = False
+
+        response = self.client.chat.completions.create(

Review Comment:
   >But I think we also need provide implementation base on the Chat 
Completions API, for many platforms have built-in compatibility with it but 
have not support Responses API.
   
   This basically my question in this comment: 
https://github.com/apache/flink-agents/pull/128#discussion_r2308056685
   
   If this chat model implementation is inended for OpenAI service dedicately, 
then we don't need to worry about the API compatibility with other LLM 
providers.



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