You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "jrmccluskey (via GitHub)" <gi...@apache.org> on 2025/05/23 13:43:16 UTC

[PR] Introduce Gemini Model Handler [beam]

jrmccluskey opened a new pull request, #35036:
URL: https://github.com/apache/beam/pull/35036

   Introduces a basic Gemini Model Handler along with an example and tests. Currently provides a function for text prompts and responses, but is written to be extensible by allowing for custom request functions. The Gemini SDK contains a large amount of options, so this allows for the most general model handler possible (although post-processing to pull the responses out of the nested return type will still be necessary.)
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/actions/workflows/build_wheels.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/actions/workflows/python_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/actions/workflows/java_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/actions/workflows/go_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
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: github-unsubscribe@beam.apache.org

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


Re: [PR] Introduce Gemini Model Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35036:
URL: https://github.com/apache/beam/pull/35036#issuecomment-2905069837

   Assigning reviewers:
   
   R: @liferoad for label python.
   
   
   Note: If you would like to opt out of this review, comment `assign to next reviewer`.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
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: github-unsubscribe@beam.apache.org

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


Re: [PR] Introduce Gemini Model Handler [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on code in PR #35036:
URL: https://github.com/apache/beam/pull/35036#discussion_r2109321204


##########
sdks/python/apache_beam/ml/inference/gemini_inference.py:
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+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 google import genai
+from google.genai import errors
+
+from apache_beam.ml.inference import utils
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import RemoteModelHandler
+
+LOGGER = logging.getLogger("GeminiModelHandler")
+
+
+def _retry_on_appropriate_service_error(exception: Exception) -> bool:
+  """
+  Retry filter that returns True if a returned HTTP error code is 5xx or 429.
+  This is used to retry remote requests that fail, most notably 429
+  (throttling by the service)
+
+  Args:
+    exception: the returned exception encountered during the request/response
+      loop.
+
+  Returns:
+    boolean indication whether or not the exception is a ServerError (5xx) or
+      a 429 error.
+  """
+  if not isinstance(exception, errors.APIError):
+    return False
+  return exception.code == 429 or exception.code >= 500
+
+
+def generate_from_string(
+    model_name: str,
+    batch: Sequence[str],
+    model: genai.Client,
+    inference_args: dict[str, Any]):
+  return model.models.generate_content(
+      model=model_name, contents=batch, **inference_args)
+
+
+class GeminiModelHandler(RemoteModelHandler[Any, PredictionResult,
+                                            genai.Client]):
+  def __init__(
+      self,
+      model_name: str,
+      request_fn: Callable[[str, Sequence[Any], genai.Client, dict[str, Any]],
+                           Any],
+      api_key: Optional[str] = None,
+      project: Optional[str] = None,
+      location: Optional[str] = None,
+      *,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      max_batch_duration_secs: Optional[int] = None,
+      **kwargs):
+    """Implementation of the ModelHandler interface for Google Gemini.
+    **NOTE:** This API and its implementation are under development and
+    do not provide backward compatibility guarantees.
+    Gemini can be accessed through either the Vertex AI API or the Gemini
+    Developer API, and this handler chooses which to connect to based upon
+    the arguments provided. As written, this model handler operates solely on
+    string input.
+
+    Args:
+      model_name: the Gemini model to send the request to
+      api_key: the Gemini Developer API key to use for the requests. Setting
+        this parameter sends requests for this job to the Gemini Developer API.
+        If this paramter is provided, do not set the project or location
+        parameters.
+      project: the GCP project to use for Vertex AI requests. Setting this
+        parameter routes requests to Vertex AI. If this paramter is provided,
+        location must also be provided and api_key should not be set.
+      location: the GCP project to use for Vertex AI requests. Setting this 
+        parameter routes requests to Vertex AI. If this paramter is provided,
+        project must also be provided and api_key should not be set.
+      min_batch_size: optional. the minimum batch size to use when batching
+        inputs.
+      max_batch_size: optional. the maximum batch size to use when batching
+        inputs.
+      max_batch_duration_secs: optional. the maximum amount of time to buffer 
+        a batch before emitting; used in streaming contexts.
+    """
+    self._batching_kwargs = {}
+    self._env_vars = kwargs.get('env_vars', {})
+    if min_batch_size is not None:
+      self._batching_kwargs["min_batch_size"] = min_batch_size
+    if max_batch_size is not None:
+      self._batching_kwargs["max_batch_size"] = max_batch_size
+    if max_batch_duration_secs is not None:
+      self._batching_kwargs["max_batch_duration_secs"] = max_batch_duration_secs
+
+    self.model_name = model_name
+    self.request_fn = request_fn
+
+    if api_key:
+      if project or location:
+        raise ValueError("project and location must be None if api_key is set")
+      self.api_key = api_key
+      self.use_vertex = False
+    else:
+      if project is None or location is None:
+        raise ValueError(
+            "project and location must both be provided if api_key is None")
+      self.project = project
+      self.location = location
+      self.use_vertex = True
+
+    super().__init__(
+        namespace='GeminiModelHandler',
+        retry_filter=_retry_on_appropriate_service_error,
+        **kwargs)
+
+  def create_client(self) -> genai.Client:
+    """Creates the GenAI client used to send requests. Creates a version for
+    the Vertex AI API or the Gemini Developer API based on the arguments
+    provided when the GeminiModelHandler class is instantiated.
+    """
+    if self.use_vertex:
+      return genai.Client(
+          vertexai=True, project=self.project, location=self.location)
+    return genai.Client(api_key=self.api_key)
+
+  def request(
+      self,
+      batch: Sequence[Any],
+      model: genai.Client,
+      inference_args: Optional[dict[str, Any]] = None
+  ) -> Iterable[PredictionResult]:
+    """ Sends a prediction request to a Gemini service containing a batch
+    of inputs and matches that input with the prediction response from
+    the endpoint as an iterable of PredictionResults.
+
+    Args:
+      batch: a sequence of any values to be passed to the Gemini service.
+        Should be a list of strings.

Review Comment:
   Ah yeah that was a missed line, I originally wrote this as string-only but decided it was better in the long-term to go ahead and make it more general. Let me update that docstring



-- 
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: github-unsubscribe@beam.apache.org

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


Re: [PR] Introduce Gemini Model Handler [beam]

Posted by "liferoad (via GitHub)" <gi...@apache.org>.
liferoad commented on code in PR #35036:
URL: https://github.com/apache/beam/pull/35036#discussion_r2105176381


##########
sdks/python/apache_beam/ml/inference/gemini_inference.py:
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+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 google import genai
+from google.genai import errors
+
+from apache_beam.ml.inference import utils
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import RemoteModelHandler
+
+LOGGER = logging.getLogger("GeminiModelHandler")
+
+
+def _retry_on_appropriate_service_error(exception: Exception) -> bool:
+  """
+  Retry filter that returns True if a returned HTTP error code is 5xx or 429.
+  This is used to retry remote requests that fail, most notably 429
+  (throttling by the service)
+
+  Args:
+    exception: the returned exception encountered during the request/response
+      loop.
+
+  Returns:
+    boolean indication whether or not the exception is a ServerError (5xx) or
+      a 429 error.
+  """
+  if not isinstance(exception, errors.APIError):
+    return False
+  return exception.code == 429 or exception.code >= 500
+
+
+def generate_from_string(
+    model_name: str,
+    batch: Sequence[str],
+    model: genai.Client,
+    inference_args: dict[str, Any]):
+  return model.models.generate_content(
+      model=model_name, contents=batch, **inference_args)
+
+
+class GeminiModelHandler(RemoteModelHandler[Any, PredictionResult,
+                                            genai.Client]):
+  def __init__(
+      self,
+      model_name: str,
+      request_fn: Callable[[str, Sequence[Any], genai.Client, dict[str, Any]],
+                           Any],
+      api_key: Optional[str] = None,
+      project: Optional[str] = None,
+      location: Optional[str] = None,
+      *,
+      min_batch_size: Optional[int] = None,
+      max_batch_size: Optional[int] = None,
+      max_batch_duration_secs: Optional[int] = None,
+      **kwargs):
+    """Implementation of the ModelHandler interface for Google Gemini.
+    **NOTE:** This API and its implementation are under development and
+    do not provide backward compatibility guarantees.
+    Gemini can be accessed through either the Vertex AI API or the Gemini
+    Developer API, and this handler chooses which to connect to based upon
+    the arguments provided. As written, this model handler operates solely on
+    string input.
+
+    Args:
+      model_name: the Gemini model to send the request to
+      api_key: the Gemini Developer API key to use for the requests. Setting
+        this parameter sends requests for this job to the Gemini Developer API.
+        If this paramter is provided, do not set the project or location
+        parameters.
+      project: the GCP project to use for Vertex AI requests. Setting this
+        parameter routes requests to Vertex AI. If this paramter is provided,
+        location must also be provided and api_key should not be set.
+      location: the GCP project to use for Vertex AI requests. Setting this 
+        parameter routes requests to Vertex AI. If this paramter is provided,
+        project must also be provided and api_key should not be set.
+      min_batch_size: optional. the minimum batch size to use when batching
+        inputs.
+      max_batch_size: optional. the maximum batch size to use when batching
+        inputs.
+      max_batch_duration_secs: optional. the maximum amount of time to buffer 
+        a batch before emitting; used in streaming contexts.
+    """
+    self._batching_kwargs = {}
+    self._env_vars = kwargs.get('env_vars', {})
+    if min_batch_size is not None:
+      self._batching_kwargs["min_batch_size"] = min_batch_size
+    if max_batch_size is not None:
+      self._batching_kwargs["max_batch_size"] = max_batch_size
+    if max_batch_duration_secs is not None:
+      self._batching_kwargs["max_batch_duration_secs"] = max_batch_duration_secs
+
+    self.model_name = model_name
+    self.request_fn = request_fn
+
+    if api_key:
+      if project or location:
+        raise ValueError("project and location must be None if api_key is set")
+      self.api_key = api_key
+      self.use_vertex = False
+    else:
+      if project is None or location is None:
+        raise ValueError(
+            "project and location must both be provided if api_key is None")
+      self.project = project
+      self.location = location
+      self.use_vertex = True
+
+    super().__init__(
+        namespace='GeminiModelHandler',
+        retry_filter=_retry_on_appropriate_service_error,
+        **kwargs)
+
+  def create_client(self) -> genai.Client:
+    """Creates the GenAI client used to send requests. Creates a version for
+    the Vertex AI API or the Gemini Developer API based on the arguments
+    provided when the GeminiModelHandler class is instantiated.
+    """
+    if self.use_vertex:
+      return genai.Client(
+          vertexai=True, project=self.project, location=self.location)
+    return genai.Client(api_key=self.api_key)
+
+  def request(
+      self,
+      batch: Sequence[Any],
+      model: genai.Client,
+      inference_args: Optional[dict[str, Any]] = None
+  ) -> Iterable[PredictionResult]:
+    """ Sends a prediction request to a Gemini service containing a batch
+    of inputs and matches that input with the prediction response from
+    the endpoint as an iterable of PredictionResults.
+
+    Args:
+      batch: a sequence of any values to be passed to the Gemini service.
+        Should be a list of strings.

Review Comment:
   Sequence[Any]: I assume we plan to support other types soon. So we use Any here, right?



-- 
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: github-unsubscribe@beam.apache.org

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


Re: [PR] Introduce Gemini Model Handler [beam]

Posted by "liferoad (via GitHub)" <gi...@apache.org>.
liferoad commented on code in PR #35036:
URL: https://github.com/apache/beam/pull/35036#discussion_r2105166752


##########
sdks/python/apache_beam/examples/inference/gemini_text_classification.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.
+#
+
+""" A sample pipeline using the RunInference API to classify text using an LLM.
+This pipeline creates a set of prompts and sends it to a Gemini service then
+returns the predictions from the classifier model. This example uses the
+gemini-2.0-flash-001 model.

Review Comment:
   probably need to update sdks/python/apache_beam/examples/inference/README.md with a new remote handler section.



-- 
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: github-unsubscribe@beam.apache.org

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


Re: [PR] Introduce Gemini Model Handler [beam]

Posted by "liferoad (via GitHub)" <gi...@apache.org>.
liferoad commented on code in PR #35036:
URL: https://github.com/apache/beam/pull/35036#discussion_r2105172911


##########
sdks/python/apache_beam/ml/inference/gemini_inference.py:
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+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 google import genai
+from google.genai import errors
+
+from apache_beam.ml.inference import utils
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import RemoteModelHandler
+
+LOGGER = logging.getLogger("GeminiModelHandler")
+
+
+def _retry_on_appropriate_service_error(exception: Exception) -> bool:
+  """
+  Retry filter that returns True if a returned HTTP error code is 5xx or 429.
+  This is used to retry remote requests that fail, most notably 429
+  (throttling by the service)
+
+  Args:
+    exception: the returned exception encountered during the request/response
+      loop.
+
+  Returns:
+    boolean indication whether or not the exception is a ServerError (5xx) or
+      a 429 error.
+  """
+  if not isinstance(exception, errors.APIError):
+    return False
+  return exception.code == 429 or exception.code >= 500

Review Comment:
   Shall we log these to make this more explicit to users?



-- 
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: github-unsubscribe@beam.apache.org

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


Re: [PR] Introduce Gemini Model Handler [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on code in PR #35036:
URL: https://github.com/apache/beam/pull/35036#discussion_r2109317818


##########
sdks/python/apache_beam/ml/inference/gemini_inference.py:
##########
@@ -0,0 +1,168 @@
+#
+# 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.
+#
+
+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 google import genai
+from google.genai import errors
+
+from apache_beam.ml.inference import utils
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import RemoteModelHandler
+
+LOGGER = logging.getLogger("GeminiModelHandler")
+
+
+def _retry_on_appropriate_service_error(exception: Exception) -> bool:
+  """
+  Retry filter that returns True if a returned HTTP error code is 5xx or 429.
+  This is used to retry remote requests that fail, most notably 429
+  (throttling by the service)
+
+  Args:
+    exception: the returned exception encountered during the request/response
+      loop.
+
+  Returns:
+    boolean indication whether or not the exception is a ServerError (5xx) or
+      a 429 error.
+  """
+  if not isinstance(exception, errors.APIError):
+    return False
+  return exception.code == 429 or exception.code >= 500

Review Comment:
   exceptions get logged by the RemoteModelHandler, no need to log them here (https://github.com/apache/beam/blob/34efdd432630030afc907909f0c83b0b9e5fe401/sdks/python/apache_beam/ml/inference/base.py#L449)



-- 
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: github-unsubscribe@beam.apache.org

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


Re: [PR] Introduce Gemini Model Handler [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey merged PR #35036:
URL: https://github.com/apache/beam/pull/35036


-- 
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: github-unsubscribe@beam.apache.org

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