jrmccluskey commented on code in PR #40239:
URL: https://github.com/apache/beam/pull/40239#discussion_r4148671890


##########
sdks/python/apache_beam/ml/inference/openai_inference.py:
##########
@@ -0,0 +1,371 @@
+#
+# 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.
+#
+
+"""A ModelHandler for OpenAI models using the OpenAI Python SDK.
+
+This module provides an integration between Apache Beam's RunInference
+transform and OpenAI's API, enabling batch inference and embeddings in
+Beam pipelines.
+
+Example usage::
+
+  import apache_beam as beam
+  from apache_beam.ml.inference.base import RunInference
+  from apache_beam.ml.inference.openai_inference import (
+      OpenAIModelHandler,
+      chat_completion_from_string,
+  )
+
+  # Basic text generation with chat completions
+  model_handler = OpenAIModelHandler(
+      model_name='gpt-4o-mini',
+      api_key='your-api-key',
+      request_fn=chat_completion_from_string,
+  )
+
+  # With system prompt and structured output
+  model_handler = OpenAIModelHandler(
+      model_name='gpt-4o-mini',
+      api_key='your-api-key',
+      request_fn=chat_completion_from_string,
+      system='You are a helpful assistant that responds concisely.',
+      response_format={
+          'type': 'json_schema',
+          'json_schema': {
+              'name': 'answer_response',
+              'schema': {
+                  'type': 'object',
+                  'properties': {
+                      'answer': {'type': 'string'},
+                      'confidence': {'type': 'number'},
+                  },
+                  'required': ['answer', 'confidence'],
+                  'additionalProperties': False,
+              },
+              'strict': True,
+          },
+      },
+  )
+
+  with beam.Pipeline() as p:
+    results = (
+        p
+        | beam.Create(['What is Apache Beam?', 'Explain MapReduce.'])
+        | RunInference(model_handler)
+    )
+"""
+
+import logging
+from collections.abc import Callable
+from collections.abc import Iterable
+from collections.abc import Sequence
+from typing import Any
+from typing import Optional
+from typing import Union
+
+from openai import APIConnectionError
+from openai import APIStatusError
+from openai import OpenAI
+
+from apache_beam.ml.inference import utils
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import RemoteModelHandler
+
+__all__ = [
+    'OpenAIModelHandler',
+    'chat_completion_from_string',
+    'chat_completion_from_conversation',
+    'embedding_from_string',
+]
+
+LOGGER = logging.getLogger("OpenAIModelHandler")
+
+
+def _retry_on_appropriate_error(exception: Exception) -> bool:
+  """Retry filter that returns True for retriable OpenAI API errors.
+
+  Retries on HTTP 429 (rate limiting), HTTP 5xx (server errors), and
+  connection / timeout errors.
+
+  Args:
+    exception: the exception encountered during the request/response loop.
+
+  Returns:
+    True if the exception is retriable (429, 5xx, or connection error),
+    False otherwise.
+  """
+  if isinstance(exception, APIConnectionError):
+    return True
+  if isinstance(exception, APIStatusError):
+    return exception.status_code == 429 or exception.status_code >= 500

Review Comment:
   Yeah that makes sense, didn't realize there was a nested retry in there



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to