You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "josix (via GitHub)" <gi...@apache.org> on 2024/08/17 15:28:22 UTC

[PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

josix opened a new pull request, #41554:
URL: https://github.com/apache/airflow/pull/41554

   <!--
    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.
    -->
   
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   closes: #41336 
   - [x] Hook that supports batch api related operation
   - [x] Operator/Trigger for Batch API
   - [ ] Unit tests for new added behaviors to hook
   - [ ] Unit tests for new added behaviors to operator
   - [ ] Unit tests for new added behaviors to trigger
   
   <!-- Please keep an empty line above the dashes. -->
   ---
   **^ Add meaningful description above**
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723262151


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")

Review Comment:
   I changed to use a customized one (`OpenAIBatchTimeout`) for this type of timeout.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1724641016


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +417,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise OpenAIBatchTimeout(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if BatchStatus.is_in_progress(batch.status):
+                continue
+            if batch.status == BatchStatus.COMPLETED:
+                return
+            if batch.status == BatchStatus.FAILED:
+                raise OpenAIBatchJobException(f"Batch failed - \n{batch_id}")
+            elif batch.status in (BatchStatus.CANCELLED, BatchStatus.CANCELLING):
+                raise OpenAIBatchJobException(f"Batch failed - batch was cancelled:\n{batch_id}")
+            elif batch.status == BatchStatus.EXPIRED:
+                raise OpenAIBatchJobException(
+                    f"Batch failed - batch couldn't be completed within the hour time window :\n{batch_id}"
+                )
+
+            raise OpenAIBatchJobException(
+                f"Batch failed - encountered unexpected status `{batch.status}` for batch_id `{batch_id}`"
+            )

Review Comment:
   ```suggestion
               if BatchStatus.is_in_progress(batch.status):
                   time.sleep(wait_seconds)
                   continue
               elif batch.status == BatchStatus.COMPLETED:
                   return
               elif batch.status == BatchStatus.FAILED:
                   raise OpenAIBatchJobException(f"Batch failed - \n{batch_id}")
               elif batch.status in (BatchStatus.CANCELLED, BatchStatus.CANCELLING):
                   raise OpenAIBatchJobException(f"Batch failed - batch was cancelled:\n{batch_id}")
               elif batch.status == BatchStatus.EXPIRED:
                   raise OpenAIBatchJobException(
                       f"Batch failed - batch couldn't be completed within the hour time window :\n{batch_id}"
                   )
               
               raise OpenAIBatchJobException(
                   f"Batch failed - encountered unexpected status `{batch.status}` for batch_id `{batch_id}`"
               )
   ```
   
   I think we can reduce one wait by this change and would be better if we could unify if, if-else usage



##########
airflow/providers/openai/exceptions.py:
##########
@@ -0,0 +1,31 @@
+#
+# 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 __future__ import annotations
+
+from airflow.exceptions import AirflowException
+
+# Note: Any AirflowException raised is expected to cause the TaskInstance
+#       to be marked in an ERROR state

Review Comment:
   I'm okay, but just not sure whether we actually need this 🤔 



##########
tests/system/providers/openai/example_trigger_batch_operator.py:
##########
@@ -0,0 +1,117 @@
+# 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 __future__ import annotations
+
+from typing import Any, Literal
+
+from airflow.decorators import dag, task
+
+OPENAI_CONN_ID = "openai_default"
+
+POKEMONS = [
+    "pikachu",
+    "charmander",
+    "bulbasaur",

Review Comment:
   😆 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723089576


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if batch.status in {BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING}:

Review Comment:
   yeah, it's a minor difference that it would run in sequential lookup or hash lookup. Both are okay to me.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1724629700


##########
airflow/providers/openai/exceptions.py:
##########
@@ -0,0 +1,31 @@
+#
+# 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 __future__ import annotations
+
+from airflow.exceptions import AirflowException
+
+# Note: Any AirflowException raised is expected to cause the TaskInstance
+#       to be marked in an ERROR state

Review Comment:
   I'm okay with it, but just not sure whether we actually need this 🤔 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1722284792


##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,86 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if self.deferrable:
+            self.defer(
+                timeout=self.execution_timeout,
+                trigger=OpenAIBatchTrigger(
+                    conn_id=self.conn_id,
+                    batch_id=self.batch_id,
+                    poll_interval=60,
+                    end_time=time.time() + self.timeout,
+                ),
+                method_name="execute_complete",
+            )
+        else:
+            self.log.info("Waiting for batch %s to complete", self.batch_id)
+            self.hook.wait_for_batch(self.batch_id, wait_seconds=self.wait_seconds, timeout=self.timeout)

Review Comment:
   I'll leave it to you that decision but usually in Airflow we use a flag `wait_for_completion` which configure whether the operator waits. In your case I think that can be useful, some users might want to trigger a batch without waiting?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723257205


##########
airflow/providers/openai/triggers/openai.py:
##########
@@ -0,0 +1,116 @@
+# 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 __future__ import annotations
+
+import asyncio
+import time
+from typing import Any, AsyncIterator
+
+from airflow.providers.openai.hooks.openai import BatchStatus, OpenAIHook
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+class OpenAIBatchTrigger(BaseTrigger):
+    """Triggers OpenAI Batch API."""
+
+    def __init__(
+        self,
+        conn_id: str,
+        batch_id: str,
+        poll_interval: float,
+        end_time: float,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.poll_interval = poll_interval
+        self.batch_id = batch_id
+        self.end_time = end_time
+
+    def serialize(self) -> tuple[str, dict[str, Any]]:
+        """Serialize OpenAIBatchTrigger arguments and class path."""
+        return (
+            "airflow.providers.openai.triggers.openai.OpenAIBatchTrigger",
+            {
+                "conn_id": self.conn_id,
+                "batch_id": self.batch_id,
+                "poll_interval": self.poll_interval,
+                "end_time": self.end_time,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        """Make connection to OpenAI Client, and poll the status of batch."""
+        hook = OpenAIHook(conn_id=self.conn_id)
+        try:
+            while (batch := hook.get_batch(self.batch_id)) and batch.status in {
+                BatchStatus.VALIDATING,
+                BatchStatus.IN_PROGRESS,
+                BatchStatus.FINALIZING,
+            }:

Review Comment:
   I made this check as a class method of BatchStatus so that the binding between status and the check could be stronger.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723087191


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",

Review Comment:
   The Batch API document said[ that it only accept `24h` now](https://platform.openai.com/docs/guides/batch/3-creating-the-batch), so I would prefer to  set it as literal `24h` for now.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723107795


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",

Review Comment:
   sounds good 👍 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723161345


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -43,9 +46,26 @@
         ChatCompletionUserMessageParam,
     )
 
+from airflow.exceptions import AirflowException
 from airflow.hooks.base import BaseHook
 
 
+class BatchStatus(str, Enum):
+    """Enum for the status of a batch."""
+
+    VALIDATING = "validating"
+    FAILED = "failed"
+    IN_PROGRESS = "in_progress"
+    FINALIZING = "finalizing"
+    COMPLETED = "completed"
+    EXPIRED = "expired"
+    CANCELLING = "cancelling"
+    CANCELLED = "cancelled"
+
+    def __str__(self) -> str:
+        return str(self.value)

Review Comment:
   I think it is better to keep it for easier compatible with `Literal` type in [`Batch.status`](https://github.com/openai/openai-python/blob/main/src/openai/types/batch.py#L39), which is derived from Pydantic BaseModel. With that, it would be easier to pass the enum member to the model when we want to build a mock batch like [this](https://github.com/apache/airflow/pull/41554/files#diff-e0e2387fb039e0c87d941ba74fbf721c61ed06ddd9e877444cabab494bab4485R119) since it would be automatically casting to string from `BatchStatus` Enum type. Removing that would cause some annoying validation errors like 
   ```console
   FAILED tests/providers/openai/triggers/test_openai.py::TestOpenAIBatchTrigger::test_openai_batch_for_timeout[in_progress] - pydantic_core._pydantic_core.ValidationError: 1 validation error for Batch
   status
     Input should be 'validating', 'failed', 'in_progress', 'finalizing', 'completed', 'expired', 'cancelling' or 'cancelled' [type=literal_error, input_value=<BatchStatus.IN_PROGRESS: 'in_progress'>, input_type=BatchStatus]
       For further information visit https://errors.pydantic.dev/2.8/v/literal_error
   ```
   Even passing string type like `str(BatchStatus.VALIDATING)` it would still get invalid string value as follows
   ```console
   FAILED tests/providers/openai/triggers/test_openai.py::TestOpenAIBatchTrigger::test_openai_batch_for_timeout[BatchStatus.VALIDATING] - pydantic_core._pydantic_core.ValidationError: 1 validation error for Batch
   status
     Input should be 'validating', 'failed', 'in_progress', 'finalizing', 'completed', 'expired', 'cancelling' or 'cancelled' [type=literal_error, input_value='BatchStatus.VALIDATING', input_type=str]
       For further information visit https://errors.pydantic.dev/2.8/v/literal_error
   ```



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1722639512


##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,86 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if self.deferrable:
+            self.defer(
+                timeout=self.execution_timeout,
+                trigger=OpenAIBatchTrigger(
+                    conn_id=self.conn_id,
+                    batch_id=self.batch_id,
+                    poll_interval=60,
+                    end_time=time.time() + self.timeout,
+                ),
+                method_name="execute_complete",
+            )
+        else:
+            self.log.info("Waiting for batch %s to complete", self.batch_id)
+            self.hook.wait_for_batch(self.batch_id, wait_seconds=self.wait_seconds, timeout=self.timeout)

Review Comment:
   Yes, exactly. Thank you for pointing that out. I've added a 'wait_for_completion' parameter to the operator. If set to False, the operator will return the batch immediately, allowing users to proceed with downstream tasks without waiting.



##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,86 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if self.deferrable:
+            self.defer(
+                timeout=self.execution_timeout,
+                trigger=OpenAIBatchTrigger(
+                    conn_id=self.conn_id,
+                    batch_id=self.batch_id,
+                    poll_interval=60,
+                    end_time=time.time() + self.timeout,
+                ),
+                method_name="execute_complete",
+            )
+        else:
+            self.log.info("Waiting for batch %s to complete", self.batch_id)
+            self.hook.wait_for_batch(self.batch_id, wait_seconds=self.wait_seconds, timeout=self.timeout)

Review Comment:
   Yes, exactly. Thank you for pointing that out. I've added a `wait_for_completion` parameter to the operator. If set to False, the operator will return the batch immediately, allowing users to proceed with downstream tasks without waiting.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723257205


##########
airflow/providers/openai/triggers/openai.py:
##########
@@ -0,0 +1,116 @@
+# 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 __future__ import annotations
+
+import asyncio
+import time
+from typing import Any, AsyncIterator
+
+from airflow.providers.openai.hooks.openai import BatchStatus, OpenAIHook
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+class OpenAIBatchTrigger(BaseTrigger):
+    """Triggers OpenAI Batch API."""
+
+    def __init__(
+        self,
+        conn_id: str,
+        batch_id: str,
+        poll_interval: float,
+        end_time: float,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.poll_interval = poll_interval
+        self.batch_id = batch_id
+        self.end_time = end_time
+
+    def serialize(self) -> tuple[str, dict[str, Any]]:
+        """Serialize OpenAIBatchTrigger arguments and class path."""
+        return (
+            "airflow.providers.openai.triggers.openai.OpenAIBatchTrigger",
+            {
+                "conn_id": self.conn_id,
+                "batch_id": self.batch_id,
+                "poll_interval": self.poll_interval,
+                "end_time": self.end_time,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        """Make connection to OpenAI Client, and poll the status of batch."""
+        hook = OpenAIHook(conn_id=self.conn_id)
+        try:
+            while (batch := hook.get_batch(self.batch_id)) and batch.status in {
+                BatchStatus.VALIDATING,
+                BatchStatus.IN_PROGRESS,
+                BatchStatus.FINALIZING,
+            }:

Review Comment:
   I made this check as a class method of BatchStatus so that the binding between stause and the check could be deeper.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723688798


##########
tests/providers/openai/operators/test_openai.py:
##########
@@ -48,3 +51,55 @@ def test_execute_with_invalid_input(invalid_input):
     context = Context()
     with pytest.raises(ValueError):
         operator.execute(context)
+
+
+def test_openai_trigger_batch_operator():
+    operator = OpenAITriggerBatchOperator(
+        task_id="TaskId",
+        conn_id="test_conn_id",
+        file_id="file_id",
+        endpoint="/v1/chat/completions",
+    )
+    mock_batch = Batch(
+        id="batch_id",
+        object="batch",
+        completion_window="24h",
+        created_at=1699061776,
+        endpoint="/v1/chat/completions",
+        input_file_id="file_id",
+        status="completed",
+    )
+    mock_hook_instance = Mock()
+    mock_hook_instance.get_batch.return_value = mock_batch
+    mock_hook_instance.create_batch.return_value = mock_batch
+    operator.hook = mock_hook_instance
+
+    context = Context()
+    batch_id = operator.execute(context)
+    assert batch_id == "batch_id"
+
+
+def test_openai_trigger_batch_operator_with_deferred():

Review Comment:
   Where? I cannot see 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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W merged PR #41554:
URL: https://github.com/apache/airflow/pull/41554


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723161345


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -43,9 +46,26 @@
         ChatCompletionUserMessageParam,
     )
 
+from airflow.exceptions import AirflowException
 from airflow.hooks.base import BaseHook
 
 
+class BatchStatus(str, Enum):
+    """Enum for the status of a batch."""
+
+    VALIDATING = "validating"
+    FAILED = "failed"
+    IN_PROGRESS = "in_progress"
+    FINALIZING = "finalizing"
+    COMPLETED = "completed"
+    EXPIRED = "expired"
+    CANCELLING = "cancelling"
+    CANCELLED = "cancelled"
+
+    def __str__(self) -> str:
+        return str(self.value)

Review Comment:
   I think it is better to keep it for easier compatible with `Literal` type in [`Batch.status`](https://github.com/openai/openai-python/blob/main/src/openai/types/batch.py#L39), which is derived from Pydantic BaseModel. With that, it would be easier to pass the enum member to the model argument when we want to build a mock batch like [this](https://github.com/apache/airflow/pull/41554/files#diff-e0e2387fb039e0c87d941ba74fbf721c61ed06ddd9e877444cabab494bab4485R119) since it would be automatically casting to string from `BatchStatus` Enum type. Removing that would cause some annoying validation errors like 
   ```console
   FAILED tests/providers/openai/triggers/test_openai.py::TestOpenAIBatchTrigger::test_openai_batch_for_timeout[in_progress] - pydantic_core._pydantic_core.ValidationError: 1 validation error for Batch
   status
     Input should be 'validating', 'failed', 'in_progress', 'finalizing', 'completed', 'expired', 'cancelling' or 'cancelled' [type=literal_error, input_value=<BatchStatus.IN_PROGRESS: 'in_progress'>, input_type=BatchStatus]
       For further information visit https://errors.pydantic.dev/2.8/v/literal_error
   ```
   Even passing string type like `str(BatchStatus.VALIDATING)` it would still get invalid string value as follows
   ```console
   FAILED tests/providers/openai/triggers/test_openai.py::TestOpenAIBatchTrigger::test_openai_batch_for_timeout[BatchStatus.VALIDATING] - pydantic_core._pydantic_core.ValidationError: 1 validation error for Batch
   status
     Input should be 'validating', 'failed', 'in_progress', 'finalizing', 'completed', 'expired', 'cancelling' or 'cancelled' [type=literal_error, input_value='BatchStatus.VALIDATING', input_type=str]
       For further information visit https://errors.pydantic.dev/2.8/v/literal_error
   ```



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723161345


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -43,9 +46,26 @@
         ChatCompletionUserMessageParam,
     )
 
+from airflow.exceptions import AirflowException
 from airflow.hooks.base import BaseHook
 
 
+class BatchStatus(str, Enum):
+    """Enum for the status of a batch."""
+
+    VALIDATING = "validating"
+    FAILED = "failed"
+    IN_PROGRESS = "in_progress"
+    FINALIZING = "finalizing"
+    COMPLETED = "completed"
+    EXPIRED = "expired"
+    CANCELLING = "cancelling"
+    CANCELLED = "cancelled"
+
+    def __str__(self) -> str:
+        return str(self.value)

Review Comment:
   I think it is better to keep it for easier compatible with `Literal` type in [`Batch.status`](https://github.com/openai/openai-python/blob/main/src/openai/types/batch.py#L39), which is derived from Pydantic BaseModel. With that, it would be easier to pass the enum member to the model when we want to build a mock batch like [this](https://github.com/apache/airflow/pull/41554/files#diff-e0e2387fb039e0c87d941ba74fbf721c61ed06ddd9e877444cabab494bab4485R119) since it would be automatically casting to string from `BatchStatus` Enum type. Removing that would cause some annoying validation errors like 
   ```console
   FAILED tests/providers/openai/triggers/test_openai.py::TestOpenAIBatchTrigger::test_openai_batch_for_timeout[in_progress] - pydantic_core._pydantic_core.ValidationError: 1 validation error for Batch
   status
     Input should be 'validating', 'failed', 'in_progress', 'finalizing', 'completed', 'expired', 'cancelling' or 'cancelled' [type=literal_error, input_value=<BatchStatus.IN_PROGRESS: 'in_progress'>, input_type=BatchStatus]
       For further information visit https://errors.pydantic.dev/2.8/v/literal_error
   ```
   Even passing string type like `str(BatchStatus.VALIDATING)` it would still get invalid string value, as shown below
   ```console
   FAILED tests/providers/openai/triggers/test_openai.py::TestOpenAIBatchTrigger::test_openai_batch_for_timeout[BatchStatus.VALIDATING] - pydantic_core._pydantic_core.ValidationError: 1 validation error for Batch
   status
     Input should be 'validating', 'failed', 'in_progress', 'finalizing', 'completed', 'expired', 'cancelling' or 'cancelled' [type=literal_error, input_value='BatchStatus.VALIDATING', input_type=str]
       For further information visit https://errors.pydantic.dev/2.8/v/literal_error
   ```



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723720593


##########
tests/providers/openai/operators/test_openai.py:
##########
@@ -43,8 +65,53 @@ def test_execute_with_input_text():
 @pytest.mark.parametrize("invalid_input", ["", None, 123])
 def test_execute_with_invalid_input(invalid_input):
     operator = OpenAIEmbeddingOperator(
-        task_id="TaskId", conn_id="test_conn_id", model="test_model", input_text=invalid_input
+        task_id=TASK_ID, conn_id=CONN_ID, model="test_model", input_text=invalid_input
     )
     context = Context()
     with pytest.raises(ValueError):
         operator.execute(context)
+
+
+@pytest.mark.parametrize("wait_for_completion", [True, False])

Review Comment:
   no worries 😄



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723033501


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -43,9 +46,26 @@
         ChatCompletionUserMessageParam,
     )
 
+from airflow.exceptions import AirflowException
 from airflow.hooks.base import BaseHook
 
 
+class BatchStatus(str, Enum):
+    """Enum for the status of a batch."""
+
+    VALIDATING = "validating"
+    FAILED = "failed"
+    IN_PROGRESS = "in_progress"
+    FINALIZING = "finalizing"
+    COMPLETED = "completed"
+    EXPIRED = "expired"
+    CANCELLING = "cancelling"
+    CANCELLED = "cancelled"
+
+    def __str__(self) -> str:
+        return str(self.value)

Review Comment:
   Do we need this method?



##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if batch.status in {BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING}:
+                continue
+            if batch.status == BatchStatus.COMPLETED:
+                break
+            if batch.status == BatchStatus.FAILED:
+                raise AirflowException(f"Batch failed - \n{batch_id}")

Review Comment:
   It would be better if we could create custom exceptions for these few and not use `AirflowException` here. We could inherit it thought



##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if batch.status in {BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING}:
+                continue
+            if batch.status == BatchStatus.COMPLETED:
+                break
+            if batch.status == BatchStatus.FAILED:
+                raise AirflowException(f"Batch failed - \n{batch_id}")
+            elif batch.status in {BatchStatus.CANCELLED, BatchStatus.CANCELLING}:
+                raise AirflowException(f"Batch failed - batch was cancelled:\n{batch_id}")
+            elif batch.status == BatchStatus.EXPIRED:
+                raise AirflowException(
+                    f"Batch failed - batch couldn't be completed within the hour time window :\n{batch_id}"
+                )
+            else:
+                raise AirflowException(
+                    f"Batch failed - encountered unexpected status `{batch.status}` for batch_id `{batch_id}`"
+                )

Review Comment:
   ```suggestion
   
               raise AirflowException(
                   f"Batch failed - encountered unexpected status `{batch.status}` for batch_id `{batch_id}`"
               )
   ```



##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",

Review Comment:
   Should it be a string instead? Looks like this can be any value



##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if batch.status in {BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING}:

Review Comment:
   ```suggestion
               if batch.status in (BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING):
   ```
   
   I guess we don't need a set?



##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")

Review Comment:
   It would be better if we could create a customer exception (or maybe there's already a suitable one in airflow.exceptions). `AirflowException` is a bit too broad for this one



##########
airflow/providers/openai/triggers/openai.py:
##########
@@ -0,0 +1,116 @@
+# 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 __future__ import annotations
+
+import asyncio
+import time
+from typing import Any, AsyncIterator
+
+from airflow.providers.openai.hooks.openai import BatchStatus, OpenAIHook
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+class OpenAIBatchTrigger(BaseTrigger):
+    """Triggers OpenAI Batch API."""
+
+    def __init__(
+        self,
+        conn_id: str,
+        batch_id: str,
+        poll_interval: float,
+        end_time: float,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.poll_interval = poll_interval
+        self.batch_id = batch_id
+        self.end_time = end_time
+
+    def serialize(self) -> tuple[str, dict[str, Any]]:
+        """Serialize OpenAIBatchTrigger arguments and class path."""
+        return (
+            "airflow.providers.openai.triggers.openai.OpenAIBatchTrigger",
+            {
+                "conn_id": self.conn_id,
+                "batch_id": self.batch_id,
+                "poll_interval": self.poll_interval,
+                "end_time": self.end_time,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        """Make connection to OpenAI Client, and poll the status of batch."""
+        hook = OpenAIHook(conn_id=self.conn_id)
+        try:
+            while (batch := hook.get_batch(self.batch_id)) and batch.status in {
+                BatchStatus.VALIDATING,
+                BatchStatus.IN_PROGRESS,
+                BatchStatus.FINALIZING,
+            }:
+                if self.end_time < time.time():
+                    yield TriggerEvent(
+                        {
+                            "status": "error",
+                            "message": f"Batch {self.batch_id} has not reached a terminal status after "
+                            f"{time.time() - self.end_time} seconds.",
+                            "batch_id": self.batch_id,
+                        }
+                    )
+                    return
+                await asyncio.sleep(self.poll_interval)
+            if batch.status == BatchStatus.COMPLETED:
+                yield TriggerEvent(
+                    {
+                        "status": "success",
+                        "message": f"Batch {self.batch_id} has completed successfully.",
+                        "batch_id": self.batch_id,
+                    }
+                )
+            elif batch.status in {BatchStatus.CANCELLED, BatchStatus.CANCELLING}:
+                yield TriggerEvent(
+                    {
+                        "status": "cancelled",
+                        "message": f"Batch {self.batch_id} has been cancelled.",
+                        "batch_id": self.batch_id,
+                    }
+                )
+            elif batch.status == BatchStatus.FAILED:
+                yield TriggerEvent(
+                    {
+                        "status": "error",
+                        "message": f"Batch failed:\n{self.batch_id}",
+                        "batch_id": self.batch_id,
+                    }
+                )
+            elif batch.status == BatchStatus.EXPIRED:
+                yield TriggerEvent(
+                    {
+                        "status": "error",
+                        "message": f"Batch couldn't be completed within the hour time window :\n{self.batch_id}",
+                        "batch_id": self.batch_id,
+                    }
+                )
+            else:
+                yield TriggerEvent(
+                    {
+                        "status": "error",
+                        "message": f"Batch {self.batch_id} has failed.",
+                        "batch_id": self.batch_id,
+                    }
+                )

Review Comment:
   ```suggestion
   
               yield TriggerEvent(
                   {
                       "status": "error",
                       "message": f"Batch {self.batch_id} has failed.",
                       "batch_id": self.batch_id,
                   }
               )
   ```



##########
airflow/providers/openai/triggers/openai.py:
##########
@@ -0,0 +1,116 @@
+# 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 __future__ import annotations
+
+import asyncio
+import time
+from typing import Any, AsyncIterator
+
+from airflow.providers.openai.hooks.openai import BatchStatus, OpenAIHook
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+class OpenAIBatchTrigger(BaseTrigger):
+    """Triggers OpenAI Batch API."""
+
+    def __init__(
+        self,
+        conn_id: str,
+        batch_id: str,
+        poll_interval: float,
+        end_time: float,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.poll_interval = poll_interval
+        self.batch_id = batch_id
+        self.end_time = end_time
+
+    def serialize(self) -> tuple[str, dict[str, Any]]:
+        """Serialize OpenAIBatchTrigger arguments and class path."""
+        return (
+            "airflow.providers.openai.triggers.openai.OpenAIBatchTrigger",
+            {
+                "conn_id": self.conn_id,
+                "batch_id": self.batch_id,
+                "poll_interval": self.poll_interval,
+                "end_time": self.end_time,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        """Make connection to OpenAI Client, and poll the status of batch."""
+        hook = OpenAIHook(conn_id=self.conn_id)
+        try:
+            while (batch := hook.get_batch(self.batch_id)) and batch.status in {
+                BatchStatus.VALIDATING,
+                BatchStatus.IN_PROGRESS,
+                BatchStatus.FINALIZING,
+            }:

Review Comment:
   This combination is used for a few times. Might worth making it a variable



##########
airflow/providers/openai/triggers/openai.py:
##########
@@ -0,0 +1,116 @@
+# 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 __future__ import annotations
+
+import asyncio
+import time
+from typing import Any, AsyncIterator
+
+from airflow.providers.openai.hooks.openai import BatchStatus, OpenAIHook
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+class OpenAIBatchTrigger(BaseTrigger):
+    """Triggers OpenAI Batch API."""
+
+    def __init__(
+        self,
+        conn_id: str,
+        batch_id: str,
+        poll_interval: float,
+        end_time: float,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.poll_interval = poll_interval
+        self.batch_id = batch_id
+        self.end_time = end_time
+
+    def serialize(self) -> tuple[str, dict[str, Any]]:
+        """Serialize OpenAIBatchTrigger arguments and class path."""
+        return (
+            "airflow.providers.openai.triggers.openai.OpenAIBatchTrigger",
+            {
+                "conn_id": self.conn_id,
+                "batch_id": self.batch_id,
+                "poll_interval": self.poll_interval,
+                "end_time": self.end_time,
+            },
+        )
+
+    async def run(self) -> AsyncIterator[TriggerEvent]:
+        """Make connection to OpenAI Client, and poll the status of batch."""
+        hook = OpenAIHook(conn_id=self.conn_id)
+        try:
+            while (batch := hook.get_batch(self.batch_id)) and batch.status in {
+                BatchStatus.VALIDATING,
+                BatchStatus.IN_PROGRESS,
+                BatchStatus.FINALIZING,
+            }:

Review Comment:
   ```suggestion
               while (batch := hook.get_batch(self.batch_id)) and batch.status in (
                   BatchStatus.VALIDATING,
                   BatchStatus.IN_PROGRESS,
                   BatchStatus.FINALIZING,
               ):
   ```



##########
airflow/providers/openai/triggers/openai.py:
##########
@@ -0,0 +1,116 @@
+# 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 __future__ import annotations
+
+import asyncio
+import time
+from typing import Any, AsyncIterator
+
+from airflow.providers.openai.hooks.openai import BatchStatus, OpenAIHook
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+class OpenAIBatchTrigger(BaseTrigger):
+    """Triggers OpenAI Batch API."""
+
+    def __init__(
+        self,
+        conn_id: str,
+        batch_id: str,
+        poll_interval: float,
+        end_time: float,
+    ):

Review Comment:
   ```suggestion
       ) -> None:
   ```



##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,92 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+    :param wait_for_completion: Optional. Whether to wait for the batch to complete. If set to False, the operator
+        will return immediately after triggering the batch. Defaults to True.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        wait_for_completion: bool = True,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.wait_for_completion = wait_for_completion
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if not self.wait_for_completion:
+            return self.batch_id
+        if self.deferrable:
+            self.defer(
+                timeout=self.execution_timeout,
+                trigger=OpenAIBatchTrigger(
+                    conn_id=self.conn_id,
+                    batch_id=self.batch_id,
+                    poll_interval=60,
+                    end_time=time.time() + self.timeout,
+                ),
+                method_name="execute_complete",
+            )
+        else:
+            self.log.info("Waiting for batch %s to complete", self.batch_id)
+            self.hook.wait_for_batch(self.batch_id, wait_seconds=self.wait_seconds, timeout=self.timeout)
+        return self.batch_id
+
+    def execute_complete(self, context: Context, event: Any = None) -> str:
+        """
+        Invoke this callback when the trigger fires; return immediately.
+
+        Relies on trigger to throw an exception, otherwise it assumes execution was
+        successful.
+        """
+        if event["status"] == "error":
+            raise AirflowException(event["message"])

Review Comment:
   Custom error would be better



##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,92 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+    :param wait_for_completion: Optional. Whether to wait for the batch to complete. If set to False, the operator
+        will return immediately after triggering the batch. Defaults to True.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        wait_for_completion: bool = True,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.wait_for_completion = wait_for_completion
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if not self.wait_for_completion:
+            return self.batch_id
+        if self.deferrable:
+            self.defer(
+                timeout=self.execution_timeout,
+                trigger=OpenAIBatchTrigger(
+                    conn_id=self.conn_id,
+                    batch_id=self.batch_id,
+                    poll_interval=60,
+                    end_time=time.time() + self.timeout,
+                ),
+                method_name="execute_complete",
+            )
+        else:
+            self.log.info("Waiting for batch %s to complete", self.batch_id)
+            self.hook.wait_for_batch(self.batch_id, wait_seconds=self.wait_seconds, timeout=self.timeout)
+        return self.batch_id
+
+    def execute_complete(self, context: Context, event: Any = None) -> str:
+        """
+        Invoke this callback when the trigger fires; return immediately.
+
+        Relies on trigger to throw an exception, otherwise it assumes execution was
+        successful.
+        """
+        if event["status"] == "error":
+            raise AirflowException(event["message"])
+
+        self.log.info("%s completed successfully.", self.task_id)
+        return event["batch_id"]
+
+    def on_kill(self):

Review Comment:
   ```suggestion
       def on_kill(self) -> None:
   ```



##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if batch.status in {BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING}:
+                continue
+            if batch.status == BatchStatus.COMPLETED:
+                break
+            if batch.status == BatchStatus.FAILED:
+                raise AirflowException(f"Batch failed - \n{batch_id}")
+            elif batch.status in {BatchStatus.CANCELLED, BatchStatus.CANCELLING}:

Review Comment:
   ```suggestion
               elif batch.status in (BatchStatus.CANCELLED, BatchStatus.CANCELLING):
   ```



##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if batch.status in {BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING}:
+                continue
+            if batch.status == BatchStatus.COMPLETED:
+                break

Review Comment:
   I guess we can just return here?
   ```suggestion
                   return
   ```



##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,92 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+    :param wait_for_completion: Optional. Whether to wait for the batch to complete. If set to False, the operator
+        will return immediately after triggering the batch. Defaults to True.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        wait_for_completion: bool = True,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.wait_for_completion = wait_for_completion
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if not self.wait_for_completion:
+            return self.batch_id

Review Comment:
   We probably would want to handle the case that `not self.wait_for_completion and self.deferrable` to avoid confusion



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723260595


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise AirflowException(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if batch.status in {BatchStatus.IN_PROGRESS, BatchStatus.VALIDATING, BatchStatus.FINALIZING}:
+                continue
+            if batch.status == BatchStatus.COMPLETED:
+                break
+            if batch.status == BatchStatus.FAILED:
+                raise AirflowException(f"Batch failed - \n{batch_id}")

Review Comment:
   Changed to use `OpenAIBatchJobException`



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723715879


##########
tests/providers/openai/operators/test_openai.py:
##########
@@ -43,8 +65,53 @@ def test_execute_with_input_text():
 @pytest.mark.parametrize("invalid_input", ["", None, 123])
 def test_execute_with_invalid_input(invalid_input):
     operator = OpenAIEmbeddingOperator(
-        task_id="TaskId", conn_id="test_conn_id", model="test_model", input_text=invalid_input
+        task_id=TASK_ID, conn_id=CONN_ID, model="test_model", input_text=invalid_input
     )
     context = Context()
     with pytest.raises(ValueError):
         operator.execute(context)
+
+
+@pytest.mark.parametrize("wait_for_completion", [True, False])
+def test_openai_trigger_batch_operator_not_deferred(mock_batch, wait_for_completion):
+    operator = OpenAITriggerBatchOperator(
+        task_id=TASK_ID,
+        conn_id=CONN_ID,
+        file_id=FILE_ID,
+        endpoint=BATCH_ENDPOINT,
+        wait_for_completion=wait_for_completion,
+        deferrable=False,
+    )
+    mock_hook_instance = Mock()
+    mock_hook_instance.get_batch.return_value = mock_batch
+    mock_hook_instance.create_batch.return_value = mock_batch
+    operator.hook = mock_hook_instance
+
+    context = Context()
+    batch_id = operator.execute(context)
+    assert batch_id == BATCH_ID
+
+
+@pytest.mark.parametrize("wait_for_completion", [True, False])

Review Comment:
   ditto. cc @vincbeck 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723718574


##########
tests/providers/openai/operators/test_openai.py:
##########
@@ -43,8 +65,53 @@ def test_execute_with_input_text():
 @pytest.mark.parametrize("invalid_input", ["", None, 123])
 def test_execute_with_invalid_input(invalid_input):
     operator = OpenAIEmbeddingOperator(
-        task_id="TaskId", conn_id="test_conn_id", model="test_model", input_text=invalid_input
+        task_id=TASK_ID, conn_id=CONN_ID, model="test_model", input_text=invalid_input
     )
     context = Context()
     with pytest.raises(ValueError):
         operator.execute(context)
+
+
+@pytest.mark.parametrize("wait_for_completion", [True, False])

Review Comment:
   My bad!



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723383044


##########
tests/providers/openai/operators/test_openai.py:
##########
@@ -48,3 +51,55 @@ def test_execute_with_invalid_input(invalid_input):
     context = Context()
     with pytest.raises(ValueError):
         operator.execute(context)
+
+
+def test_openai_trigger_batch_operator():
+    operator = OpenAITriggerBatchOperator(
+        task_id="TaskId",
+        conn_id="test_conn_id",
+        file_id="file_id",
+        endpoint="/v1/chat/completions",
+    )
+    mock_batch = Batch(
+        id="batch_id",
+        object="batch",
+        completion_window="24h",
+        created_at=1699061776,
+        endpoint="/v1/chat/completions",
+        input_file_id="file_id",
+        status="completed",
+    )
+    mock_hook_instance = Mock()
+    mock_hook_instance.get_batch.return_value = mock_batch
+    mock_hook_instance.create_batch.return_value = mock_batch
+    operator.hook = mock_hook_instance
+
+    context = Context()
+    batch_id = operator.execute(context)
+    assert batch_id == "batch_id"
+
+
+def test_openai_trigger_batch_operator_with_deferred():

Review Comment:
   Maybe add a test with `wait_for_completion=False`?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1724699557


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +417,76 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
+        """
+        Poll a batch to check if it finishes.
+
+        :param batch_id: Id of the Batch to wait for.
+        :param wait_seconds: Optional. Number of seconds between checks.
+        :param timeout: Optional. How many seconds wait for batch to be ready.
+            Used only if not ran in deferred operator.
+        """
+        start = time.monotonic()
+        while True:
+            if start + timeout < time.monotonic():
+                self.cancel_batch(batch_id=batch_id)
+                raise OpenAIBatchTimeout(f"Timeout: OpenAI Batch {batch_id} is not ready after {timeout}s")
+            time.sleep(wait_seconds)
+            batch = self.get_batch(batch_id=batch_id)
+
+            if BatchStatus.is_in_progress(batch.status):
+                continue
+            if batch.status == BatchStatus.COMPLETED:
+                return
+            if batch.status == BatchStatus.FAILED:
+                raise OpenAIBatchJobException(f"Batch failed - \n{batch_id}")
+            elif batch.status in (BatchStatus.CANCELLED, BatchStatus.CANCELLING):
+                raise OpenAIBatchJobException(f"Batch failed - batch was cancelled:\n{batch_id}")
+            elif batch.status == BatchStatus.EXPIRED:
+                raise OpenAIBatchJobException(
+                    f"Batch failed - batch couldn't be completed within the hour time window :\n{batch_id}"
+                )
+
+            raise OpenAIBatchJobException(
+                f"Batch failed - encountered unexpected status `{batch.status}` for batch_id `{batch_id}`"
+            )

Review Comment:
   Nice Catch!



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "ginger0207 (via GitHub)" <gi...@apache.org>.
ginger0207 commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1721328153


##########
airflow/providers/openai/hooks/openai.py:
##########
@@ -393,3 +413,74 @@ def delete_vector_store_file(self, vector_store_id: str, file_id: str) -> Vector
         """
         response = self.conn.beta.vector_stores.files.delete(vector_store_id=vector_store_id, file_id=file_id)
         return response
+
+    def create_batch(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        metadata: dict[str, str] | None = None,
+        completion_window: Literal["24h"] = "24h",
+    ) -> Batch:
+        """
+        Create a batch for a given model and files.
+
+        :param file_id: The ID of the file to be used for this batch.
+        :param endpoint: The endpoint to use for this batch. Allowed values include:
+            '/v1/chat/completions', '/v1/embeddings', '/v1/completions'.
+        :param metadata: A set of key-value pairs that can be attached to an object.
+        :param completion_window: The time window for the batch to complete. Default is 24 hours.
+        """
+        batch = self.conn.batches.create(
+            input_file_id=file_id, endpoint=endpoint, metadata=metadata, completion_window=completion_window
+        )
+        return batch
+
+    def get_batch(self, batch_id: str) -> Batch:
+        """
+        Get the status of a batch.
+
+        :param batch_id: The ID of the batch to get the status of.
+        """
+        batch = self.conn.batches.retrieve(batch_id=batch_id)
+        return batch
+
+    def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float | None = 3600) -> None:

Review Comment:
   ```suggestion
       def wait_for_batch(self, batch_id: str, wait_seconds: float = 3, timeout: float = 3600) -> None:
   ```



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723257847


##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,92 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+    :param wait_for_completion: Optional. Whether to wait for the batch to complete. If set to False, the operator
+        will return immediately after triggering the batch. Defaults to True.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        wait_for_completion: bool = True,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.wait_for_completion = wait_for_completion
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if not self.wait_for_completion:
+            return self.batch_id
+        if self.deferrable:
+            self.defer(
+                timeout=self.execution_timeout,
+                trigger=OpenAIBatchTrigger(
+                    conn_id=self.conn_id,
+                    batch_id=self.batch_id,
+                    poll_interval=60,
+                    end_time=time.time() + self.timeout,
+                ),
+                method_name="execute_complete",
+            )
+        else:
+            self.log.info("Waiting for batch %s to complete", self.batch_id)
+            self.hook.wait_for_batch(self.batch_id, wait_seconds=self.wait_seconds, timeout=self.timeout)
+        return self.batch_id
+
+    def execute_complete(self, context: Context, event: Any = None) -> str:
+        """
+        Invoke this callback when the trigger fires; return immediately.
+
+        Relies on trigger to throw an exception, otherwise it assumes execution was
+        successful.
+        """
+        if event["status"] == "error":
+            raise AirflowException(event["message"])

Review Comment:
   Changed to use `OpenAIBatchJobException`



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723260101


##########
airflow/providers/openai/operators/openai.py:
##########
@@ -74,3 +78,92 @@ def execute(self, context: Context) -> list[float]:
         embeddings = self.hook.create_embeddings(self.input_text, model=self.model, **self.embedding_kwargs)
         self.log.info("Generated embeddings for %d items", len(embeddings))
         return embeddings
+
+
+class OpenAITriggerBatchOperator(BaseOperator):
+    """
+    Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
+
+    :param file_id: Required. The ID of the batch file to trigger.
+    :param endpoint: Required. The OpenAI Batch API endpoint to trigger.
+    :param conn_id: Optional. The OpenAI connection ID to use. Defaults to 'openai_default'.
+    :param deferrable: Optional. Run operator in the deferrable mode.
+    :param wait_seconds: Optional. Number of seconds between checks. Only used when ``deferrable`` is False.
+        Defaults to 3 seconds.
+    :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
+        Only used when ``deferrable`` is False. Defaults to 24 hour, which is the SLA for OpenAI Batch API.
+    :param wait_for_completion: Optional. Whether to wait for the batch to complete. If set to False, the operator
+        will return immediately after triggering the batch. Defaults to True.
+
+    .. seealso::
+        For more information on how to use this operator, please take a look at the guide:
+        :ref:`howto/operator:OpenAITriggerBatchOperator`
+    """
+
+    template_fields: Sequence[str] = ("file_id",)
+
+    def __init__(
+        self,
+        file_id: str,
+        endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
+        conn_id: str = OpenAIHook.default_conn_name,
+        deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+        wait_seconds: float = 3,
+        timeout: float = 24 * 60 * 60,
+        wait_for_completion: bool = True,
+        **kwargs: Any,
+    ):
+        super().__init__(**kwargs)
+        self.conn_id = conn_id
+        self.file_id = file_id
+        self.endpoint = endpoint
+        self.deferrable = deferrable
+        self.wait_seconds = wait_seconds
+        self.timeout = timeout
+        self.wait_for_completion = wait_for_completion
+        self.batch_id: str | None = None
+
+    @cached_property
+    def hook(self) -> OpenAIHook:
+        """Return an instance of the OpenAIHook."""
+        return OpenAIHook(conn_id=self.conn_id)
+
+    def execute(self, context: Context) -> str:
+        batch = self.hook.create_batch(file_id=self.file_id, endpoint=self.endpoint)
+        self.batch_id = batch.id
+        if not self.wait_for_completion:
+            return self.batch_id

Review Comment:
   I move the check of whether to wait for completion as an outer check block, and deferrable one in the in inner. Hope this would help others to understand it. PTAL, thanks!



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723614414


##########
tests/providers/openai/operators/test_openai.py:
##########
@@ -48,3 +51,55 @@ def test_execute_with_invalid_input(invalid_input):
     context = Context()
     with pytest.raises(ValueError):
         operator.execute(context)
+
+
+def test_openai_trigger_batch_operator():
+    operator = OpenAITriggerBatchOperator(
+        task_id="TaskId",
+        conn_id="test_conn_id",
+        file_id="file_id",
+        endpoint="/v1/chat/completions",
+    )
+    mock_batch = Batch(
+        id="batch_id",
+        object="batch",
+        completion_window="24h",
+        created_at=1699061776,
+        endpoint="/v1/chat/completions",
+        input_file_id="file_id",
+        status="completed",
+    )
+    mock_hook_instance = Mock()
+    mock_hook_instance.get_batch.return_value = mock_batch
+    mock_hook_instance.create_batch.return_value = mock_batch
+    operator.hook = mock_hook_instance
+
+    context = Context()
+    batch_id = operator.execute(context)
+    assert batch_id == "batch_id"
+
+
+def test_openai_trigger_batch_operator_with_deferred():

Review Comment:
   Sure, I updated it, thanks!



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(providers/openai): support batch api in hook/operator/trigger [airflow]

Posted by "josix (via GitHub)" <gi...@apache.org>.
josix commented on code in PR #41554:
URL: https://github.com/apache/airflow/pull/41554#discussion_r1723715459


##########
tests/providers/openai/operators/test_openai.py:
##########
@@ -43,8 +65,53 @@ def test_execute_with_input_text():
 @pytest.mark.parametrize("invalid_input", ["", None, 123])
 def test_execute_with_invalid_input(invalid_input):
     operator = OpenAIEmbeddingOperator(
-        task_id="TaskId", conn_id="test_conn_id", model="test_model", input_text=invalid_input
+        task_id=TASK_ID, conn_id=CONN_ID, model="test_model", input_text=invalid_input
     )
     context = Context()
     with pytest.raises(ValueError):
         operator.execute(context)
+
+
+@pytest.mark.parametrize("wait_for_completion", [True, False])

Review Comment:
   Hi @vincbeck, here is the change for testing `wait_for_completion`



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org