diff --git a/packages/genkit-google-genai/README.md b/packages/genkit-google-genai/README.md index 04e78c1e6..638dd2df5 100644 --- a/packages/genkit-google-genai/README.md +++ b/packages/genkit-google-genai/README.md @@ -62,7 +62,7 @@ print(await greet('Grace')) ### Dynamic Models -The plugin automatically discovers available models from the API upon initialization. You can use any model name supported by the API via model reference constructors (e.g., `GoogleAI.gemini('gemini-flash-latest')`, `VertexAI.gemini('gemini-3.1-pro-preview')`). +The plugin registers a static catalog of known models at startup, with no network call, so a rate-limited or offline project still starts. Any other model id resolves by name on first use. The live model list is fetched only when the Dev UI lists actions, then cached for the process. You can use any model name supported by the API via model reference constructors (e.g., `GoogleAI.gemini('gemini-flash-latest')`, `VertexAI.gemini('gemini-3.1-pro-preview')`). ### Typed config diff --git a/packages/genkit-google-genai/src/genkit_google_genai/__init__.py b/packages/genkit-google-genai/src/genkit_google_genai/__init__.py index 0f3a118c0..3af7d0e02 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/__init__.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/__init__.py @@ -18,8 +18,9 @@ """Google GenAI plugin for Genkit. This plugin provides integration with Google's generative AI models through -either Google AI (Gemini API) or Google Cloud Vertex AI. It dynamically discovers -and registers available models and embedders at runtime. +either Google AI (Gemini API) or Google Cloud Vertex AI. It registers known +models and embedders at init with no network call and resolves any other model +id by name on first use. Example: Using GoogleAI (Gemini API) with typed flat config: diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_google.py b/packages/genkit-google-genai/src/genkit_google_genai/_google.py index 864fe63ed..68a6da3c2 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -18,8 +18,9 @@ """Google AI and Vertex AI plugin implementations for Genkit. This module provides the GoogleAI and VertexAI plugins that enable Genkit to use -Google's generative AI models. Both plugins use dynamic model discovery via the -Google GenAI SDK to detect and register available models at runtime. +Google's generative AI models. Both plugins register a static catalog of known +models at init with no network call, resolve any other model id by name on first +use, and list the live catalog only when the Dev UI asks for it. Supported capabilities include text generation (Gemini/Gemma), text embeddings, image generation (Gemini native image), and video generation (Veo). @@ -29,10 +30,10 @@ from genkit import Genkit from genkit_google_genai import GoogleAI - # 1. Initialize Genkit with dynamic model discovery + # 1. Initialize Genkit; no model listing happens at startup ai = Genkit(plugins=[GoogleAI()]) - # 2. Generate content using any discovered Gemini model + # 2. Generate with any Gemini model id the API serves response = await ai.generate( model=GoogleAI.gemini('gemini-flash-latest'), prompt='Suggest 3 names for a space-themed coffee shop.', @@ -48,6 +49,7 @@ from __future__ import annotations +import asyncio import os from collections.abc import Callable, Mapping from typing import Any, NoReturn @@ -89,13 +91,16 @@ deep_research_model, ) from genkit_google_genai._models._embedder import ( + GOOGLEAI_KNOWN_EMBEDDERS, VERTEX_KNOWN_EMBEDDERS, Embedder as GoogleEmbedder, EmbeddingConfig, get_embedder_info, ) from genkit_google_genai._models._gemini import ( + GOOGLEAI_KNOWN_MODELS, SUPPORTED_MODELS, + VERTEX_KNOWN_MODELS, GeminiConfig, GeminiImageConfig, GeminiModel, @@ -137,6 +142,8 @@ ) from genkit_google_genai._models._sdk_config import check_timeout_seconds, timeout_seconds_to_ms from genkit_google_genai._models._veo import ( + GOOGLEAI_KNOWN_VEO, + VERTEX_KNOWN_VEO, KnownGoogleAIVeo, KnownVertexAIVeo, VeoConfig, @@ -447,11 +454,13 @@ def embedder(cls, name: str, *, config: EmbeddingConfig | None = None) -> Embedd class GoogleAI(GoogleFamilyRefs, Plugin): - """GoogleAI plugin for Genkit with dynamic model discovery. + """GoogleAI plugin for Genkit. This plugin provides access to Google AI models (Gemini, embedders, Veo) - through the Google AI Studio API. Models are discovered dynamically at - initialization time, ensuring new models are available without SDK updates. + through the Google AI Studio API. Known models register at init with no + network call. Any other model id resolves by name on first use, so new + models work without an SDK update. The live catalog is listed only when + the Dev UI asks for it, then cached. Model Types: | Type | Action Kind | Example | @@ -465,7 +474,7 @@ class GoogleAI(GoogleFamilyRefs, Plugin): from genkit import Genkit from genkit_google_genai import GoogleAI - # 1. Initialize Genkit with dynamic model discovery + # 1. Initialize Genkit; no model listing happens at startup ai = Genkit(plugins=[GoogleAI()]) # 2. Generate text using Gemini Flash @@ -696,6 +705,10 @@ def _runtime_client(self) -> genai.Client: # One client per event loop, used everywhere in plugin runtime paths. return _plugin_client(self._loop_client_kwargs()) + @loop_local_client + def _list_actions_lock(self) -> asyncio.Lock: + return asyncio.Lock() + def _loop_client_kwargs(self) -> dict[str, Any]: """Client kwargs carrying this loop's client from ``http_client_factory``, if one was given.""" return _with_loop_http_client(self._client_kwargs, self._http_client_factory) @@ -722,21 +735,29 @@ def _plugin_api_key(self) -> str | None: return raw if isinstance(raw, str) else None async def init(self) -> list[Action | BackgroundAction[Any, Any]]: - """Initialize the plugin. + """Initialize the plugin with static known models and embedders. + + Registration is static-first and requires no network requests, + preventing startup rate limits (429) on unbilled/free-tier projects. + Unknown or dynamic models resolve lazily on-demand. Returns: Actions and background models for known/supported models. """ - genai_models = await _list_genai_models(self._runtime_client(), is_vertex=False) + # Build this loop's http client now so a factory that returns the wrong + # type raises TypeError here, at setup, not inside the first model run. + if self._http_client_factory is not None: + self._http_client_factory() actions: list[Action | BackgroundAction[Any, Any]] = [] - # Gemini Models - for name in genai_models.gemini: + + # Gemini / Gemma Models + for name in GOOGLEAI_KNOWN_MODELS: if action := self._resolve_model(name): actions.append(action) # Veo Models (background models) - for name in genai_models.veo: + for name in GOOGLEAI_KNOWN_VEO: actions.append(self._resolve_veo_model(name)) client_options = self._interactions_client_options() @@ -767,7 +788,7 @@ async def init(self) -> list[Action | BackgroundAction[Any, Any]]: ) # Embedders - for name in genai_models.embedders: + for name in GOOGLEAI_KNOWN_EMBEDDERS: actions.append(self._resolve_embedder(name)) return actions @@ -891,56 +912,58 @@ def _resolve_embedder(self, name: str) -> Action: async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]: """Generate a list of available actions or models. + Dynamic discovery is performed lazily and cached across calls. + Returns: list[Action | BackgroundAction[Any, Any]]: Actions and background models. """ if self._list_actions_cache is not None: return self._list_actions_cache - genai_models = await _list_genai_models(self._runtime_client(), is_vertex=False) - actions_list: list[Action | BackgroundAction[Any, Any]] = [] - for name in genai_models.gemini: - if (model_action := self._resolve_model(name)) is not None: - actions_list.append(model_action) + async with self._list_actions_lock(): + if self._list_actions_cache is not None: + return self._list_actions_cache + + actions_list = list(await self.init()) + seen_names = {a.name for a in actions_list} + + genai_models = await _list_genai_models(self._runtime_client(), is_vertex=False) + + for name in genai_models.gemini: + if (model_action := self._resolve_model(name)) is not None: + if model_action.name not in seen_names: + actions_list.append(model_action) + seen_names.add(model_action.name) - for name in genai_models.veo: - actions_list.append( - _create_veo_background_model( + for name in genai_models.veo: + veo_action = _create_veo_background_model( name, self._runtime_client, GOOGLEAI_PLUGIN_NAME, client_kwargs=self._loop_client_kwargs, ) - ) - - for name in list_known_deep_research_models(): - actions_list.append( - create_deep_research_background_model( - googleai_name(name), - plugin_api_key=self._plugin_api_key(), - client_options=self._interactions_client_options(), - ) - ) - for name in list_known_antigravity_models(): - if (model_action := self._resolve_model(name)) is not None: - actions_list.append(model_action) - for name in list_known_lyria_models(): - if (model_action := self._resolve_model(name)) is not None: - actions_list.append(model_action) + if veo_action.name not in seen_names: + actions_list.append(veo_action) + seen_names.add(veo_action.name) - for name in genai_models.embedders: - actions_list.append(_create_embedder_action(name, self._runtime_client, GOOGLEAI_PLUGIN_NAME)) + for name in genai_models.embedders: + embedder_action = _create_embedder_action(name, self._runtime_client, GOOGLEAI_PLUGIN_NAME) + if embedder_action.name not in seen_names: + actions_list.append(embedder_action) + seen_names.add(embedder_action.name) - self._list_actions_cache = actions_list - return actions_list + self._list_actions_cache = actions_list + return actions_list class VertexAI(GoogleFamilyRefs, Plugin): - """Vertex AI plugin for Genkit with dynamic model discovery. + """Vertex AI plugin for Genkit. This plugin provides access to Google Cloud Vertex AI models including - Gemini, Veo, and embedders. Models are discovered dynamically, - ensuring new models are available without SDK updates. + Gemini, Veo, and embedders. Known models register at init with no network + call. Any other model id resolves by name on first use, so new models work + without an SDK update. The live catalog is listed only when the Dev UI asks + for it, then cached. Vertex AI vs Google AI: Vertex AI provides enterprise features including: @@ -1190,25 +1213,38 @@ def _runtime_client(self) -> genai.Client: # One client per event loop, used everywhere in plugin runtime paths. return _plugin_client(self._loop_client_kwargs()) + @loop_local_client + def _list_actions_lock(self) -> asyncio.Lock: + return asyncio.Lock() + def _loop_client_kwargs(self) -> dict[str, Any]: """Client kwargs carrying this loop's client from ``http_client_factory``, if one was given.""" return _with_loop_http_client(self._client_kwargs, self._http_client_factory) async def init(self) -> list[Action | BackgroundAction[Any, Any]]: - """Initialize the plugin. + """Initialize the plugin with static known models and embedders. + + Registration is static-first and requires no network requests, + preventing startup rate limits (429) on unbilled/free-tier projects. + Unknown or dynamic models resolve lazily on-demand. Returns: Actions and background models for known/supported models. """ - genai_models = await _list_genai_models(self._runtime_client(), is_vertex=True) + # Build this loop's http client now so a factory that returns the wrong + # type raises TypeError here, at setup, not inside the first model run. + if self._http_client_factory is not None: + self._http_client_factory() + actions: list[Action | BackgroundAction[Any, Any]] = [] - for name in genai_models.gemini: + # Gemini Models (Vertex does not serve rotating -latest aliases or Gemma via generate_content) + for name in VERTEX_KNOWN_MODELS: if action := self._resolve_model(name): actions.append(action) # Veo Models (background models) - for name in genai_models.veo: + for name in VERTEX_KNOWN_VEO: actions.append(self._resolve_veo_model(name)) for name in VERTEX_KNOWN_VIRTUAL_TRY_ON: @@ -1353,37 +1389,42 @@ def _resolve_embedder(self, name: str) -> Action: async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]: """Generate a list of available actions or models. + Dynamic discovery is performed lazily and cached across calls. + Returns: list[Action | BackgroundAction[Any, Any]]: Actions and background models. """ if self._list_actions_cache is not None: return self._list_actions_cache - genai_models = await _list_genai_models(self._runtime_client(), is_vertex=True) - actions_list: list[Action | BackgroundAction[Any, Any]] = [] - for name in genai_models.gemini: - if (model_action := self._resolve_model(name)) is not None: - actions_list.append(model_action) + async with self._list_actions_lock(): + if self._list_actions_cache is not None: + return self._list_actions_cache + + actions_list = list(await self.init()) + seen_names = {a.name for a in actions_list} - for name in genai_models.veo: - actions_list.append( - _create_veo_background_model( + genai_models = await _list_genai_models(self._runtime_client(), is_vertex=True) + + for name in genai_models.gemini: + if (model_action := self._resolve_model(name)) is not None: + if model_action.name not in seen_names: + actions_list.append(model_action) + seen_names.add(model_action.name) + + for name in genai_models.veo: + veo_action = _create_veo_background_model( name, self._runtime_client, VERTEXAI_PLUGIN_NAME, client_kwargs=self._loop_client_kwargs, ) - ) - - for name in VERTEX_KNOWN_VIRTUAL_TRY_ON: - if (action := self._resolve_model(name)) is not None: - actions_list.append(action) - - for name in VERTEX_KNOWN_EMBEDDERS: - actions_list.append(_create_embedder_action(name, self._runtime_client, VERTEXAI_PLUGIN_NAME)) + if veo_action.name not in seen_names: + actions_list.append(veo_action) + seen_names.add(veo_action.name) - self._list_actions_cache = actions_list - return actions_list + self._list_actions_cache = actions_list + return actions_list def _loop_local_http_client( diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_embedder.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_embedder.py index bf156c034..bb571a0af 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_embedder.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_embedder.py @@ -122,6 +122,12 @@ class EmbeddingConfig(GenkitConfig): } +# Curated set of Google AI embedders registered at init without a discovery +# round-trip. text-embedding-004 is left out: the Gemini API shut it down on +# 2026-01-14. Any other id still resolves on demand. +GOOGLEAI_KNOWN_EMBEDDERS: tuple[str, ...] = ('gemini-embedding-001', 'gemini-embedding-2') + + # Curated set of Vertex AI embedders that are verified to be callable. # The Vertex catalog over-lists embedders (and returns supported_actions=None), # so embedders are advertised from this list rather than discovered. Multimodal diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index 5887515f3..35ae3caf1 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -1236,6 +1236,22 @@ def _add_model(model_info: ModelInfo, names: list[str]) -> None: # resolve() writes into SUPPORTED_MODELS later. GEMINI_CATALOG_IDS = frozenset(SUPPORTED_MODELS) +GOOGLEAI_KNOWN_MODELS: tuple[str, ...] = tuple( + sorted({ + *get_args(KnownGoogleAIGemini), + *get_args(KnownGeminiTts), + *get_args(KnownGeminiImage), + *get_args(KnownGemma), + }) +) +VERTEX_KNOWN_MODELS: tuple[str, ...] = tuple( + sorted({ + *get_args(KnownVertexAIGemini), + *get_args(KnownGeminiTts), + *get_args(KnownGeminiImage), + }) +) + DEFAULT_SUPPORTS_MODEL = ModelSupports( multiturn=True, diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py index 966934b19..27344b3b4 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py @@ -21,7 +21,7 @@ import base64 from collections.abc import Mapping -from typing import Any, Literal, TypeAlias +from typing import Any, Literal, TypeAlias, get_args from genkit_google_genai._auth import GOOGLE_AUTH_ERRORS, raise_auth_error from genkit_google_genai._constants import is_multi_regional_location, multi_regional_base_url @@ -57,6 +57,9 @@ 'veo-3.1-lite-generate-001', ] +GOOGLEAI_KNOWN_VEO: tuple[str, ...] = get_args(KnownGoogleAIVeo) +VERTEX_KNOWN_VEO: tuple[str, ...] = get_args(KnownVertexAIVeo) + VideoCompressionQuality: TypeAlias = Literal['OPTIMIZED', 'LOSSLESS'] """Values of ``genai_types.VideoCompressionQuality``.""" diff --git a/packages/genkit-google-genai/tests/google_genai_plugin_test.py b/packages/genkit-google-genai/tests/google_genai_plugin_test.py index 8098b7105..715d2461c 100644 --- a/packages/genkit-google-genai/tests/google_genai_plugin_test.py +++ b/packages/genkit-google-genai/tests/google_genai_plugin_test.py @@ -995,17 +995,21 @@ async def test_vertexai_resolve_veo_background_model(mock_list_models: MagicMock @patch('genkit_google_genai._google.genai.client.Client') @patch('genkit_google_genai._google._list_genai_models') @pytest.mark.asyncio -async def test_vertexai_init_registers_veo_as_background(mock_list_models: MagicMock, mock_client: MagicMock) -> None: - """Vertex init registers Veo start/check, never a blocking MODEL action.""" +async def test_vertexai_list_actions_registers_veo_as_background( + mock_list_models: MagicMock, mock_client: MagicMock +) -> None: + """Vertex list_actions registers Veo start/check, never a blocking MODEL action.""" models = GenaiModels() models.veo = ['veo-3.1-generate-001'] mock_list_models.return_value = models plugin = VertexAI(project='test-project') - actions = await plugin.init() + actions = await plugin.list_actions() - # init returns the BackgroundModel itself; the registry files start + check. - veo = [a for a in actions if 'veo' in a.name] + # list_actions returns the BackgroundModel itself; the registry files start + check. + # Static Veo ids are listed too; none of them is a plain MODEL action. + assert all(isinstance(a, BackgroundModel) for a in actions if 'veo' in a.name) + veo = [a for a in actions if a.name == 'vertexai/veo-3.1-generate-001'] assert len(veo) == 1 assert isinstance(veo[0], BackgroundModel) assert {a.kind for a in veo[0].actions} == {ActionKind.BACKGROUND_MODEL, ActionKind.CHECK_OPERATION} @@ -1035,9 +1039,9 @@ async def test_list_actions_advertises_veo_as_background( plugin = VertexAI(project='test-project') actions = await plugin.list_actions() - veo_entries = [a for a in actions if 'veo' in a.name] + # Static and discovered ids are deduplicated, so the listed id appears once. + veo_entries = [a for a in actions if a.name == f'{backend}/{veo_id}'] assert len(veo_entries) == 1 - assert veo_entries[0].name == f'{backend}/{veo_id}' assert veo_entries[0].kind == ActionKind.BACKGROUND_MODEL diff --git a/packages/genkit-google-genai/tests/google_plugin_test.py b/packages/genkit-google-genai/tests/google_plugin_test.py index 176e32cb9..ca2906c01 100644 --- a/packages/genkit-google-genai/tests/google_plugin_test.py +++ b/packages/genkit-google-genai/tests/google_plugin_test.py @@ -935,8 +935,8 @@ def test_vertexai_positional_project_raises_type_error() -> None: @pytest.mark.asyncio -async def test_googleai_init_rejected_key_is_unauthenticated(googleai_plugin_instance: GoogleAI) -> None: - """A bad API key fails the model listing in init with UNAUTHENTICATED, not a raw SDK error.""" +async def test_googleai_list_actions_rejected_key_is_unauthenticated(googleai_plugin_instance: GoogleAI) -> None: + """A bad API key fails model listing in list_actions with UNAUTHENTICATED, not a raw SDK error.""" message = 'API key not valid. Please pass a valid API key.' error_info = { '@type': 'type.googleapis.com/google.rpc.ErrorInfo', @@ -954,7 +954,7 @@ async def test_googleai_init_rejected_key_is_unauthenticated(googleai_plugin_ins googleai_plugin_instance._runtime_client = lambda: mock_client with pytest.raises(GenkitError) as raised: - await googleai_plugin_instance.init() + await googleai_plugin_instance.list_actions() assert raised.value.status == 'UNAUTHENTICATED' assert raised.value.__cause__ is rejected @@ -969,23 +969,23 @@ async def test_googleai_init_rejected_key_is_unauthenticated(googleai_plugin_ins (httpx.ConnectError('[Errno 61] Connection refused'), 'UNAVAILABLE'), ], ) -async def test_vertexai_init_classifies_model_listing_failure( +async def test_vertexai_list_actions_classifies_model_listing_failure( vertexai_plugin_instance: VertexAI, failure: Exception, status: str ) -> None: - """Model listing in init maps provider, credential, and connection failures like a generate call.""" + """Model listing in list_actions maps provider, credential, and connection failures like a generate call.""" mock_client = MagicMock() mock_client.aio.models.list = AsyncMock(side_effect=failure) vertexai_plugin_instance._runtime_client = lambda: mock_client with pytest.raises(GenkitError) as raised: - await vertexai_plugin_instance.init() + await vertexai_plugin_instance.list_actions() assert raised.value.status == status assert raised.value.__cause__ is failure @pytest.mark.asyncio -async def test_vertexai_init_listing_unknown_failure_stays_raw(vertexai_plugin_instance: VertexAI) -> None: +async def test_vertexai_list_actions_listing_unknown_failure_stays_raw(vertexai_plugin_instance: VertexAI) -> None: """A listing failure that is not a provider, credential, or connection error keeps its own type.""" boom = RuntimeError('SDK bug') mock_client = MagicMock() @@ -993,7 +993,7 @@ async def test_vertexai_init_listing_unknown_failure_stays_raw(vertexai_plugin_i vertexai_plugin_instance._runtime_client = lambda: mock_client with pytest.raises(RuntimeError) as raised: - await vertexai_plugin_instance.init() + await vertexai_plugin_instance.list_actions() assert raised.value is boom @@ -1004,7 +1004,7 @@ async def _pager_failing_after(first: Any, failure: BaseException) -> AsyncItera @pytest.mark.asyncio -async def test_googleai_init_classifies_failure_while_paging_models(googleai_plugin_instance: GoogleAI) -> None: +async def test_googleai_list_actions_classifies_failure_while_paging_models(googleai_plugin_instance: GoogleAI) -> None: """An API error the pager raises after the first page is classified too.""" first = MagicMock() first.name = 'models/gemini-2.5-flash' @@ -1015,7 +1015,195 @@ async def test_googleai_init_classifies_failure_while_paging_models(googleai_plu googleai_plugin_instance._runtime_client = lambda: mock_client with pytest.raises(GenkitError) as raised: - await googleai_plugin_instance.init() + await googleai_plugin_instance.list_actions() assert raised.value.status == 'PERMISSION_DENIED' assert raised.value.__cause__ is denied + + +@pytest.mark.asyncio +async def test_googleai_init_is_static_first_with_zero_network_calls(googleai_plugin_instance: GoogleAI) -> None: + """Plugin init is static-first and never calls models.list(), avoiding startup 429s.""" + mock_client = MagicMock() + mock_client.aio.models.list = AsyncMock(side_effect=AssertionError('models.list should not be called in init()')) + googleai_plugin_instance._runtime_client = lambda: mock_client + + actions = await googleai_plugin_instance.init() + assert len(actions) > 0 + mock_client.aio.models.list.assert_not_called() + + +@pytest.mark.asyncio +async def test_vertexai_init_is_static_first_with_zero_network_calls(vertexai_plugin_instance: VertexAI) -> None: + """Vertex init is static-first and never calls models.list(), avoiding startup 429s.""" + mock_client = MagicMock() + mock_client.aio.models.list = AsyncMock(side_effect=AssertionError('models.list should not be called in init()')) + vertexai_plugin_instance._runtime_client = lambda: mock_client + + actions = await vertexai_plugin_instance.init() + assert len(actions) > 0 + mock_client.aio.models.list.assert_not_called() + + +@pytest.mark.asyncio +async def test_googleai_list_actions_caches_dynamic_discovery(googleai_plugin_instance: GoogleAI) -> None: + """Dynamic discovery in list_actions is cached across subsequent calls.""" + mock_client = MagicMock() + mock_model = MagicMock() + mock_model.name = 'models/gemini-custom-experiment' + mock_model.supported_actions = ['generateContent'] + mock_client.aio.models.list = AsyncMock(return_value=_single_page_iter([mock_model])) + googleai_plugin_instance._runtime_client = lambda: mock_client + + first_actions = await googleai_plugin_instance.list_actions() + assert any('gemini-custom-experiment' in a.name for a in first_actions) + assert mock_client.aio.models.list.call_count == 1 + + second_actions = await googleai_plugin_instance.list_actions() + assert second_actions is first_actions + assert mock_client.aio.models.list.call_count == 1 + + +async def _single_page_iter(items: list[Any]) -> AsyncIterator[Any]: + for item in items: + yield item + + +@pytest.mark.asyncio +async def test_googleai_init_registers_known_embedders_and_veo(googleai_plugin_instance: GoogleAI) -> None: + """Init registers the live Gemini embedders and known Veo ids, never the retired text-embedding-004.""" + names = {a.name for a in await googleai_plugin_instance.init()} + + assert {'googleai/gemini-embedding-001', 'googleai/gemini-embedding-2'} <= names + assert 'googleai/text-embedding-004' not in names + assert 'googleai/veo-3.1-generate-preview' in names + + +@pytest.mark.asyncio +async def test_vertexai_init_registers_known_veo(vertexai_plugin_instance: VertexAI) -> None: + """Vertex init registers known Veo ids as background models without listing the catalog.""" + actions = await vertexai_plugin_instance.init() + + veo = [a for a in actions if a.name == 'vertexai/veo-3.1-generate-001'] + assert len(veo) == 1 + assert isinstance(veo[0], BackgroundModel) + + +@pytest.mark.asyncio +async def test_googleai_resolves_unlisted_model_without_listing(googleai_plugin_instance: GoogleAI) -> None: + """A model id missing from the static catalog resolves by name with no models.list() call.""" + mock_client = MagicMock() + mock_client.aio.models.list = AsyncMock(side_effect=AssertionError('resolve must not list models')) + googleai_plugin_instance._runtime_client = lambda: mock_client + + action = await googleai_plugin_instance.resolve(ActionKind.MODEL, 'gemini-custom-experiment') + + assert action is not None + assert action.name == 'googleai/gemini-custom-experiment' + mock_client.aio.models.list.assert_not_called() + + +@pytest.mark.asyncio +async def test_failed_listing_keeps_static_catalog_and_retries() -> None: + """With no network, the Dev UI catalog still shows static models, and the next listing tries again.""" + plugin = GoogleAI(api_key='k') + mock_client = MagicMock() + mock_client.aio.models.list = AsyncMock(side_effect=httpx.ConnectError('[Errno 61] Connection refused')) + plugin._runtime_client = lambda: mock_client + ai = Genkit(plugins=[plugin]) + + catalog = await ai._registry.list_actions() + await ai._registry.list_actions() + + assert '/model/googleai/gemini-2.5-flash' in catalog + assert '/embedder/googleai/gemini-embedding-001' in catalog + assert mock_client.aio.models.list.call_count == 2 + + +@pytest.mark.asyncio +async def test_vertexai_list_actions_caches_dynamic_discovery(vertexai_plugin_instance: VertexAI) -> None: + """Vertex list_actions caches discovered models across subsequent calls.""" + mock_client = MagicMock() + mock_model = MagicMock() + mock_model.name = 'publishers/google/models/gemini-custom-experiment' + mock_model.supported_actions = None + mock_model.description = '' + mock_client.aio.models.list = AsyncMock(return_value=_single_page_iter([mock_model])) + vertexai_plugin_instance._runtime_client = lambda: mock_client + + first_actions = await vertexai_plugin_instance.list_actions() + assert any(a.name == 'vertexai/gemini-custom-experiment' for a in first_actions) + assert mock_client.aio.models.list.call_count == 1 + + second_actions = await vertexai_plugin_instance.list_actions() + assert second_actions is first_actions + assert mock_client.aio.models.list.call_count == 1 + + +@pytest.mark.asyncio +async def test_list_actions_deduplicates_concurrent_cold_calls( + googleai_plugin_instance: GoogleAI, vertexai_plugin_instance: VertexAI +) -> None: + """Concurrent cold list_actions calls share one models.list() request instead of racing.""" + for plugin, prefix in ( + (googleai_plugin_instance, 'models/'), + (vertexai_plugin_instance, 'publishers/google/models/'), + ): + gate = asyncio.Event() + entered = asyncio.Event() + mock_model = MagicMock() + mock_model.name = f'{prefix}gemini-concurrent-exp' + mock_model.supported_actions = ['generateContent'] + mock_model.description = '' + + async def slow_list( + item: Any = mock_model, enter: asyncio.Event = entered, wait: asyncio.Event = gate + ) -> AsyncIterator[Any]: + enter.set() + await wait.wait() + return _single_page_iter([item]) + + mock_client = MagicMock() + mock_client.aio.models.list = AsyncMock(side_effect=slow_list) + plugin._runtime_client = lambda c=mock_client: c # type: ignore[misc] + + t1 = asyncio.create_task(plugin.list_actions()) + t2 = asyncio.create_task(plugin.list_actions()) + await entered.wait() + gate.set() + r1, r2 = await asyncio.gather(t1, t2) + + assert r1 is r2 + assert mock_client.aio.models.list.call_count == 1 + + +@pytest.mark.asyncio +async def test_vertexai_resolves_unlisted_and_tuned_models_without_listing(vertexai_plugin_instance: VertexAI) -> None: + """Vertex resolve builds unlisted Gemini and tuned endpoint actions with no models.list() call.""" + mock_client = MagicMock() + mock_client.aio.models.list = AsyncMock(side_effect=AssertionError('resolve must not list models')) + vertexai_plugin_instance._runtime_client = lambda: mock_client + + unlisted = await vertexai_plugin_instance.resolve(ActionKind.MODEL, 'gemini-custom-experiment') + tuned = await vertexai_plugin_instance.resolve(ActionKind.MODEL, 'endpoints/1234567890') + + assert unlisted is not None and unlisted.name == 'vertexai/gemini-custom-experiment' + assert tuned is not None and tuned.name == 'vertexai/endpoints/1234567890' + mock_client.aio.models.list.assert_not_called() + + +@pytest.mark.asyncio +async def test_static_init_catalog_matches_backend_capabilities( + googleai_plugin_instance: GoogleAI, vertexai_plugin_instance: VertexAI +) -> None: + """GoogleAI init registers Gemma 3/4 and -latest; VertexAI skips them; neither registers retired previews.""" + google_names = {a.name for a in await googleai_plugin_instance.init()} + vertex_names = {a.name for a in await vertexai_plugin_instance.init()} + + assert {'googleai/gemma-3-12b-it', 'googleai/gemma-4-31b-it', 'googleai/gemini-flash-latest'} <= google_names + assert 'googleai/gemini-2.5-pro-exp-03-25' not in google_names + assert 'googleai/gemini-2.5-flash-image-preview' not in google_names + + assert not any('gemma-' in name for name in vertex_names) + assert not any(name.endswith('-latest') for name in vertex_names) + assert 'vertexai/gemini-2.5-pro-exp-03-25' not in vertex_names diff --git a/packages/genkit-google-genai/tests/plugin_network_test.py b/packages/genkit-google-genai/tests/plugin_network_test.py index 17497bf0a..aa89d1f75 100644 --- a/packages/genkit-google-genai/tests/plugin_network_test.py +++ b/packages/genkit-google-genai/tests/plugin_network_test.py @@ -170,6 +170,7 @@ async def test_google_ai_sends_requests_through_your_http_client() -> None: ai = Genkit(plugins=[plugin]) await plugin.init() + await plugin.list_actions() response = await ai.generate(model='googleai/gemini-2.5-flash', prompt='Suggest a dish.') assert response.text == 'Smoked Salmon Tartine' @@ -185,6 +186,7 @@ async def test_vertex_ai_sends_requests_through_your_http_client() -> None: ai = Genkit(plugins=[plugin]) await plugin.init() + await plugin.list_actions() response = await ai.generate( model='vertexai/gemini-2.5-flash', prompt='Suggest a dish.',