Skip to content

Cannot Use Gemini 3 with Agent Engine #3628

Closed

Description

@lambda72453

** Please make sure you read the contribution guide and file the issues in the right place. **
Contribution guide.

Describe the bug
A clear and concise description of what the bug is.

Only Global endpoint is currently available for gemini 3, so GOOGLE_CLOUD_LOCATION needs to be set to global in order to use model (model=gemini-3-pro-preview). However, i believe GOOGLE_CLOUD_LOCATION is also used to determine the region for establishing a agent engine session. This is causing conflicts and failing as im not able to set my Gemini region to global and agent engine session to us-central1.

To Reproduce
Please share a minimal code and data to reproduce your problem.

Deploy host in cloudrun and configure get_fast_api_app to use agent engine for sessions. (I used agent starter pack for deployment https://github.com/GoogleCloudPlatform/agent-starter-pack)

Steps to reproduce the behavior:
session_service_uri = "agentengine://<agent_engine_id>"

app: FastAPI = get_fast_api_app(
agents_dir=AGENT_DIR,
web=True,
artifact_service_uri=bucket_name,
allow_origins=allow_origins,
session_service_uri=session_service_uri,
)

Set GOOGLE_CLOUD_LOCATION=global and deploy to cloudrun . Try to create a new session or run a query.

Note: This works fine setting region to global when running locally since agent engine isnt involved (adk web)

Expected behavior
There should be an option to set the region used for the LLM separately from agent engine

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. macOS, Linux, Windows] Cloud Run
  • Python version(python -V): 3.13
  • ADK version(pip show google-adk): 1.19

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used(e.g. gemini-2.5-pro) : gemini-3-pro-preview

Additional context
Add any other context about the problem here.
I tried using litellm w/ vertex ai as a workaround but that also failed for a separate reason . created a separate issue for that here #3627 . In the meantime im still looking for a way to use gemini 3 in our gcp env

Activity

  1. DeanChensj commented on Nov 20, 2025

    @DeanChensj
    Collaborator

    Hi @lambda72453 , could you do something like this:

    root_agent = LlmAgent( name='orchestrator_agent', model='projects/cloud-llm-preview1/locations/global/publishers/google/models/gemini-2.5-flash', description="""Cool dude""", tools=[], )

  2. DeanChensj commented on Nov 20, 2025

    @DeanChensj
    Collaborator
  3. added
    models
    agent engine
    on Nov 20, 2025
  4. lambda72453 commented on Nov 21, 2025

    @lambda72453
    Author

    @DeanChensj That worked for gemini-2.5-flash . But not for gemini-3-pro-preview . I got the following :
    {"error": "404 NOT_FOUND. {'error': {'code': 404, 'message': 'Publisher Model projects/<my_project>/locations/global/publishers/google/models/gemini-3-pro-preview was not found or your project does not have access to it. Please ensure you are using a valid model version. For more information, see: https://cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versions', 'status': 'NOT_FOUND'}}"}

    In the mean time I have a work around by using an AI Studio API key

  5. kashirin-dm commented on Nov 22, 2025

    @kashirin-dm

    same

  6. Infinnerty commented on Nov 24, 2025

    @Infinnerty

    Same for me,

    • Gemini 3 models require GOOGLE_CLOUD_LOCATION=global (only available on global endpoint)
    • Agent Engine requires GOOGLE_CLOUD_LOCATION=us-central1 (or other regional deployment)
    • Same environment variable controls both LLM routing and Agent Engine session region
    • Agent Engine reserves and overrides GOOGLE_CLOUD_LOCATION to deployment region

    Attempted Workarounds (All Failed)

    1. Full resource path format
      model = "projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3-pro-preview"
      Result: 404 NOT_FOUND - Full resource path format doesn't work for Gemini foundation models (even locally)
    2. Custom BaseLlm wrapper with genai.Client(location="global")
    class GlobalGemini(BaseLlm):
        def _get_client(self):
            return genai.Client(vertexai=True, location="global")
    
    1. Result: ModuleNotFoundError during unpickling in Agent Engine (custom classes that import project modules fail)
    2. Environment variable override in deployment
      Result: Agent Engine reserves GOOGLE_CLOUD_LOCATION - cannot be overridden via env_vars parameter

    ✅ Works locally:
    GOOGLE_CLOUD_LOCATION=global
    model = "gemini-3-pro-preview"

    ❌ Fails with 404 (even locally):
    model = "projects/.../locations/global/.../gemini-3-pro-preview"

    Conclusion: Cannot deploy agents using Gemini 3 models to Agent Engine until either:

    • ADK supports separate location parameters for LLM vs Agent Engine
    • Gemini 3 models are available on regional endpoints (us-central1, etc.)
  7. SatohJohn commented on Dec 1, 2025

    @SatohJohn

    I would like to suggest a workaround by subclassing the Gemini model class to override the api_client property.

    The standard initialization might rely on default location logic that doesn't align with specific model availability (e.g., models requiring the global endpoint) or might miss specific HttpOptions. By explicitly instantiating google.genai.Client within a subclass, we can enforce location="global" and ensure that _tracking_headers and retry_options are correctly propagated.

    Here is a sample implementation demonstrating how to inject the custom client configuration:

    from functools import cached_property
    import os
    from google.adk.models import Gemini
    from google.genai import Client, types
    
    
    class Gemini3(Gemini):
    
        @cached_property
        def api_client(self) -> Client:
            """Provides the api client with explicit configuration.
    
            Returns:
            The api client initialized with specific location and http_options.
            """
            # Ensure project ID is retrieved, falling back to a placeholder or raising an error if needed.
            project = os.getenv("GOOGLE_CLOUD_PROJECT", "xxxxx")
            
            # Explicitly setting location to 'global' to avoid regional endpoint resolution issues
            location = "global"
    
            return Client(
                project=project,
                location=location,
                http_options=types.HttpOptions(
                    headers=self._tracking_headers,
                    retry_options=self.retry_options,
                )
            )
    
    # Example usage within an LlmAgent
    agent = LlmAgent(
                name="image_generation_agent",
                # Instantiate the customized model class
                model=Gemini3(model="gemini-3-pro-image-preview"),
                description="AI agent that generates images based on text prompts",
    )
    

    This approach provides granular control over the Client instantiation, which should resolve connectivity or configuration issues related to the underlying API client.

  8. eliasecchig commented on Dec 17, 2025

    @eliasecchig

    You can also check out how it's done in goo.gle/agent-starter-pack
    uvx agent-starter-pack create --adk

    The issue is that the AdkApp template, when running the set_up method, will override the GOOGLE_CLOUD_LOCATION

    The Fix:
    You must capture the environment variable before initializing the app and manually restore it at the end of your set_up override.

    import os
    import vertexai
    from vertexai.agent_engines.templates.adk import AdkApp
    
    # 1. Capture the original location BEFORE the app initializes
    gemini_location = os.environ.get("GOOGLE_CLOUD_LOCATION")
    
    class AgentEngineApp(AdkApp):
        def set_up(self) -> None:
            """Initialize the app while preserving the location environment variable."""
            vertexai.init()
            
            # 2. super().set_up() is where the override occurs
            super().set_up()
            
            # ... your other setup code (logging, telemetry) ...
    
            # 3. Restore the location so Gemini uses the correct endpoint
            if gemini_location:
                os.environ["GOOGLE_CLOUD_LOCATION"] = gemini_location
    
    # 4. Instantiate the app
    agent_engine = AgentEngineApp(
        app=adk_app,
        artifact_service_builder=...
    )

    Why this is necessary:

    The parent AdkApp.set_up() call resets the environment to match the Agent Engine's deployment region. By "caching" your intended location in a variable and re-applying it after the parent setup finishes, you ensure that both the Agent Engine and Gemini remain configured correctly.

  9. klmiller-merge commented on Dec 31, 2025

    @klmiller-merge

    We've implemented the fix you suggested (capturing GOOGLE_CLOUD_LOCATION before initialization and restoring it after super().set_up()), but we're still experiencing issues with Gemini 3 Flash in Agent Engine. We're hoping someone can help identify what we might be missing.

    What We Implemented
    Following your guidance, here's our setup:

    1. Environment Variable Capture (before AdkApp initialization):

    agent_engine_app.py

    from vertexai.preview.reasoning_engines import AdkApp

    CRITICAL: Capture location for Gemini 3 BEFORE AdkApp initializes

    AdkApp.set_up() will override this, so we need to restore it

    See: #3628

    _GEMINI_LOCATION = "global"
    os.environ["GOOGLE_CLOUD_LOCATION"] = _GEMINI_LOCATION

    class ProductResearchApp(AdkApp):
    def set_up(self) -> None:
    # This call will reset GOOGLE_CLOUD_LOCATION to the deployment region (us-central1)
    super().set_up()

        # CRITICAL: Restore the global location for Gemini 3 Flash
        # This is the fix from the GitHub thread - AdkApp.set_up() overrides the location,
        # so we restore it here to ensure Gemini 3 uses the global endpoint
        os.environ["GOOGLE_CLOUD_LOCATION"] = _GEMINI_LOCATION
    
        # Pre-warm the global client to ensure it initializes with correct environment
        _get_global_client()
    
        # ... rest of setup code
    
    1. Additional Workarounds (Custom Model Class):

    Since the environment variable fix alone wasn't sufficient, we implemented a custom Gemini3Flash model class with these techniques:

    gemini3_model.py

    from google.adk.models import Gemini
    from google.genai import Client, types

    def _get_global_client() -> Client:
    """Singleton factory that creates and protects the Gemini 3 Flash client."""
    global _GLOBAL_GEMINI_CLIENT

    if _GLOBAL_GEMINI_CLIENT is None:
        # CRITICAL: base_url directly sets the API endpoint, completely bypassing
        # environment variables, metadata server, and regional enforcement
        client = Client(
            vertexai=True,
            project=project_id,
            location="global",
            http_options=types.HttpOptions(
                api_version="v1beta",
                base_url="https://aiplatform.googleapis.com"  # Forces global endpoint directly
            )
        )
    
        # Prevent ADK from closing the client
        client.close = lambda: None
    
        # Force async initialization early to avoid lazy loading issues
        if hasattr(client, 'aio'):
            client.aio.close = lambda: None
    
        _GLOBAL_GEMINI_CLIENT = client
    
    return _GLOBAL_GEMINI_CLIENT
    

    class Gemini3Flash(Gemini):
    """Gemini 3 Flash model with explicit global location."""

    def __init__(self, **kwargs):
        kwargs['model'] = 'gemini-3-flash-preview'
        kwargs['location'] = 'global'
        super().__init__(**kwargs)
    
        # Pre-fetch the global client to initialize early
        _get_global_client()
    
        # Clear state to force property usage
        self._clear_client_state()
    
    @property
    def _client(self) -> Client:
        return _get_global_client()
    
    @property
    def api_client(self) -> Client:
        return _get_global_client()
    
    # ... other property overrides
    

    Our Setup
    Agent Engine Location: us-central1
    Gemini 3 Flash Location: global (required)
    ADK Version: google-adk==1.21.0
    Deployment: Vertex AI Agent Engine (Cloud Run backend streams results)
    Architecture: Multi-agent orchestrator with 4 specialist agents using Gemini 3 Flash
    What's Still Failing
    Despite implementing:

    ✅ Your environment variable capture/restore pattern
    ✅ Custom model class with property overrides
    ✅ Direct base_url override to force global endpoint
    ✅ Singleton client factory to prevent re-initialization
    ✅ Client close prevention (client.close = lambda: None)
    We're still unable to reliably use Gemini 3 Flash with Agent Engine. The issue appears to be that Agent Engine's regional deployment (us-central1) continues to enforce regional endpoints even after all these workarounds.

    Questions for the Community
    Has anyone successfully deployed Gemini 3 Flash models to Agent Engine?
    Are there additional configuration steps needed beyond the environment variable fix?
    Is there a fundamental incompatibility between Gemini 3 Flash (global-only) and Agent Engine (regional deployment)?
    Should we be using a different approach entirely (e.g., different model, different deployment method)?
    Logs/Evidence
    When the agent runs, we can see requests going to the regional endpoint instead of global, suggesting the location override isn't being respected downstream in the Agent Engine runtime.

    Any guidance would be greatly appreciated! We'd love to use Gemini 3 Flash for its improved capabilities, but we may need to fall back to Gemini 2.5 Pro if there's no viable solution.

  10. yacinebouaouni commented on Jan 29, 2026

    @yacinebouaouni

    I found a workaround for using the global Gemini endpoint with Agent Engine in a specific a location. The idea is to go through LiteLLM with vertex_location set to global. This way you can keep the location in your ENV variables to the one used by Agent Engine.

    root_agent = Agent(
        name="agent",
        model=LiteLlm(
            "vertex_ai/gemini-3-pro-preview",
            vertex_location="global"
        )
    )
  11. added theissue type on Feb 2, 2026
  12. 5 remaining items

  13. added
    stale
    on Feb 12, 2026
  14. juszzz commented on Feb 13, 2026

    @juszzz

    @SatohJohn's workaround worked for us. I will caution that the @cached_property decorator did cause some asyncio lock contention issues in our multithreaded test suite, but switching to an @property decorator resolved this for us.

  15. removed
    stale
    on Feb 13, 2026
  16. BurgherJon commented on Mar 8, 2026

    @BurgherJon

    I was able to do this by using the following changes:

    In .env:
    `GOOGLE_CLOUD_PROJECT=my-project

    GOOGLE_CLOUD_LOCATION=global

    GOOGLE_GENAI_USE_VERTEXAI=TRUE`

    in agent.py (at the very top):
    `import os

    os.environ['GOOGLE_CLOUD_LOCATION'] = 'global'`

    Obviously, I had to specify the region when doing the deploy... This is working for both gemini pro 3.1, and gemini 3 flash (I use both in the agent). Implemented code is in this repo (it's a little bit more parameterized than the above...): https://github.com/BurgherJon/growth_coach

  17. william-yucciolino commented on Apr 15, 2026

    @william-yucciolino

    Hey guys!

    It worked for me just passing the model name directly to the agent configuration and setting the following environment variables:

    GOOGLE_GENAI_USE_VERTEXAI=FALSE
    GOOGLE_API_KEY=<secret>
    GOOGLE_CLOUD_LOCATION=global
    
    root_agent = Agent(
        name="agent",
        model="gemini-3.1-flash-lite-preview"
    )
    

    In the LOCATION environment variable, I used the fixed value "global," and in the deploy command, I used "us-central1".

  18. self-assigned this
    on Apr 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

agent enginemodelsrequest clarification

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions