adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Allow passing a preconfigured google.genai.Client to google.adk.models.Gemini

Open martina-zxy opened this issue 1 year ago • 14 comments

When using the Python ADK with Gemini models, the Gemini class internally creates its own google.genai.Client based on environment variables or ADC. There is no way to inject a preconfigured genai.Client instance directly. This makes it impossible to control the underlying genai.Client entirely in code (e.g., to avoid environment variable reliance or to set vertexai=True, project, and location programmatically). In contrast, the Java ADK’s Gemini wrapper accepts a Client object, which allows this flexibility and makes the model configuration explicit when called, as can be seen from the docs

// --- Example #2: using a powerful Gemini Pro model with API Key in model ---
LlmAgent agentGeminiPro =
    LlmAgent.builder()
        // Use the latest generally available Pro model identifier
        .model(new Gemini("gemini-2.5-pro-preview-03-25",
            Client.builder()
                .vertexAI(false)
                .apiKey("API_KEY") // Set the API Key (or) project/ location
                .build()))
        // Or, you can also directly pass the API_KEY
        // .model(new Gemini("gemini-2.5-pro-preview-03-25", "API_KEY"))
        .name("gemini_pro_agent")
        .instruction("You are a powerful and knowledgeable Gemini assistant.")
        // ... other agent parameters
        .build();

Is your feature request related to a problem? Please describe. I need more fine-grained control over the configuration of Gemini models - specifically the ability to set different locations (and other client settings) for different agents running within the same Python ADK application. Currently, model configuration is determined globally via environment variables or ADC, which makes it difficult to run agents in the same process that target different Vertex AI regions.

Describe the solution you'd like Add support for passing an existing google.genai.Client instance into the Gemini model constructor (similar to the Java ADK API). Example desired usage:

from google import genai
from google.adk.models import Gemini
from google.adk.agents import LlmAgent

client = genai.Client(vertexai=True, project="my-project", location="us-central1")
gemini_model = Gemini(model="gemini-2.5-flash", client=client)  # or api_client=client

agent = LlmAgent(name="my_agent", model=gemini_model, instruction="Be concise.")

Describe alternatives you've considered

  • Environment variables: Setting GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_CLOUD_PROJECT, and GOOGLE_CLOUD_LOCATION programmatically before importing ADK. This works, but is indirect, less explicit, and affects the entire process environment - e.g., it prevents using different locations for different model.

  • Custom BaseLlm wrapper: Creating a BaseLlm subclass that uses google.genai.Client directly. This is more verbose, requires reimplementing request/response mapping logic that already exists in ADK, and adds maintenance overhead.

Additional context Since this is already possible in the Java ADK, adding the same capability to the Python ADK would:

  • Improve cross-language parity.
  • Make the model configuration explicit and local to the code using it.
  • Reduce reliance on environment variable management in containerized or sandboxed environments.
  • Enable scenarios where multiple agents in the same application require different Vertex AI regions or other client-level settings.

martina-zxy avatar Aug 15 '25 11:08 martina-zxy

The Gemini._live_api_client also needs this feature.

mikeedjones avatar Aug 29 '25 10:08 mikeedjones

We had resources mostly in same region not us-central1. As model endpoint and agent engine region are somehow attached (this issue). Agent engine also behaves differently in Asia-east1 and us-central as a result. live-api will certainly amplify such needs further. We hope at least to bring back agent engine to nearby region closer to assets specially cloud sql and users despite latency of inter continental Gemini calls before endpoints propagate to more regions!

surfai avatar Sep 04 '25 16:09 surfai

@martina-zxy could you confirm which language are you using? You sample reference Java, but you're stating you use ADK Python.

Jacksunwei avatar Sep 12 '25 21:09 Jacksunwei

@Jacksunwei I’m using Python. I included the Java code snippet to show that this feature is already available in the Java SDK.

martina-zxy avatar Sep 12 '25 23:09 martina-zxy

suggesting a workaround here, let me know if this works.

from google import genai
from google.adk.models import google_llm
from google.adk.agents import LlmAgent

MODEL_NAME = "gemini-2.5-flash"

client = genai.Client(vertexai=True, project=PROJECT_ID, location=REGION)

gemini_model = google_llm.Gemini(model=MODEL_NAME)
gemini_model.api_client = client

agent = LlmAgent(name="my_agent", model=gemini_model, instruction="...")

jwdjj avatar Sep 30 '25 19:09 jwdjj

Yes that's what we've been doing and works fine but think it should still be explicitly injectable. The workaround could end up quite fragile! Also, the _live_api_client is still a "private" property so likely to be even more fragile.

mikeedjones avatar Oct 03 '25 14:10 mikeedjones

suggesting a workaround here, let me know if this works.

from google import genai
from google.adk.models import google_llm
from google.adk.agents import LlmAgent

MODEL_NAME = "gemini-2.5-flash"

client = genai.Client(vertexai=True, project=PROJECT_ID, location=REGION)

gemini_model = google_llm.Gemini(model=MODEL_NAME)
gemini_model.api_client = client

agent = LlmAgent(name="my_agent", model=gemini_model, instruction="...")

This workaround works when running locally, but when I try to deploy this to Agent Engine, it fails with the following error

TypeError: cannot pickle '_thread.lock' object
Exception ignored in: <function Client.__del__ at 0x11c82c860>
Traceback (most recent call last):
  File "/Users/abhi/adk-base-template/.venv/lib/python3.12/site-packages/google/genai/client.py", line 400, in __del__
    self.close()
  File "/Users/abhi/adk-base-template/.venv/lib/python3.12/site-packages/google/genai/client.py", line 386, in close
    self._api_client.close()
    ^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute '_api_client'

Please help add full support for using a custom gen ai client or is there something that can be done for this issue in the meantime?

abhinavtk97 avatar Oct 14 '25 04:10 abhinavtk97

New fix has been added for next release. Please reopen if this does not fix it!

GWeale avatar Oct 28 '25 19:10 GWeale

I'm not sure what fix you're referring to, but you can't set the client in the Gemini initialisation in 1.18.0 which was the next release follwing @GWeale 's comment.

mikeedjones avatar Nov 12 '25 12:11 mikeedjones

Hi @martina-zxy @mikeedjones cc. @GWeale,

I made a simple PR #4345 to support custom client injection when initializing Gemini.

Yes that's what we've been doing and works fine but think it should still be explicitly injectable. The workaround could end up quite fragile! Also, the _live_api_client is still a "private" property so likely to be even more fragile.

I agree with what @mikeedjones mentioned, so I created a dedicated argument to inject the client when initializing the Gemini. Also added frozen=True to make them immutable.

The PR will not effect users not using custom clients. The import of google.genai.Client is moved out of the TYPE_CHECKING scope for custom client attributes, but I think it would be fine.


Although six months is a long time, but if you are interested with the improvement I've suggested, you may take a look at the PR I've opened, and give it a try. :)

Any suggestions and corrections are welcome.

challenger71498 avatar Feb 01 '26 07:02 challenger71498

Reopening as this will be fixed in release 1.27 not release 1.26

GWeale avatar Feb 24 '26 20:02 GWeale

@GWeale this needs to be opened again. The commit pulling it from 1.26 re-closed it.

mynewestgitaccount avatar Mar 11 '26 23:03 mynewestgitaccount

Hi, just wondering if this was added on release 1.27, I don't see it in the changelog.

jibone avatar Mar 13 '26 04:03 jibone

Hi, just wondering if this was added on release 1.27, I don't see it in the changelog.

The comment saying it would be in 1.27 was wrong. @GWeale or @sasha-gitg any help?

mynewestgitaccount avatar Mar 20 '26 09:03 mynewestgitaccount