Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions packages/genkit-anthropic/src/genkit_anthropic/_secrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,8 @@ def context_api_key(context: Mapping[str, object] | None) -> str | None:
)
bag = cast(Mapping[str, object], secrets)
for slot in _KEY_SLOTS:
value = bag.get(slot)
if value is not None:
return _clean_key(value, slot)
if slot in bag:
return _clean_key(bag[slot], slot)
return None


Expand Down
32 changes: 22 additions & 10 deletions packages/genkit-anthropic/tests/anthropic_generate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,23 +281,35 @@ async def test_generate_claude_top_level_context_api_key_is_ignored() -> None:


@pytest.mark.parametrize(
'secrets',
('secrets', 'match'),
[
{'api_key': ''},
{'api_key': ' '},
{'apiKey': ''},
{'apiKey': ' '},
{'api_key': '', 'apiKey': TENANT_KEY},
({'api_key': None}, 'must be a string'),
({'apiKey': None}, 'must be a string'),
({'api_key': ''}, 'is blank'),
({'api_key': ' '}, 'is blank'),
({'apiKey': ''}, 'is blank'),
({'apiKey': ' '}, 'is blank'),
({'api_key': '', 'apiKey': TENANT_KEY}, 'is blank'),
({'api_key': None, 'apiKey': TENANT_KEY}, 'must be a string'),
],
ids=[
'api_key-none',
'apiKey-none',
'api_key-empty',
'api_key-whitespace',
'apiKey-empty',
'apiKey-whitespace',
'blank-api_key-shadows-apiKey',
'none-api_key-shadows-apiKey',
],
ids=['api_key-empty', 'api_key-whitespace', 'apiKey-empty', 'apiKey-whitespace', 'blank-api_key-shadows-apiKey'],
)
@pytest.mark.parametrize('plugin_key', [PLUGIN_KEY, None], ids=['plugin-key', 'no-plugin-key'])
@pytest.mark.asyncio
@pytest.mark.usefixtures('no_env_key')
async def test_generate_claude_blank_secrets_key_fails_instead_of_using_plugin_key(
secrets: dict[str, str], plugin_key: str | None
secrets: dict[str, object], match: str, plugin_key: str | None
) -> None:
"""A set but blank secrets key fails INVALID_ARGUMENT instead of running on the plugin key; nothing is sent."""
"""A set but None or blank secrets key fails INVALID_ARGUMENT instead of running on the plugin key."""
api = FakeClaudeApi()
ai = _genkit(api, api_key=plugin_key)

Expand All @@ -306,7 +318,7 @@ async def test_generate_claude_blank_secrets_key_fails_instead_of_using_plugin_k
assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
assert response.error.status == 'INVALID_ARGUMENT'
assert 'is blank' in response.error.message
assert match in response.error.message
assert "context={'secrets': {'api_key': ...}}" in response.error.message
assert TENANT_KEY not in response.error.message
assert api.requests == []
Expand Down
2 changes: 2 additions & 0 deletions packages/genkit-google-genai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ To use Google AI models, obtain an API key from [Google AI Studio](https://aistu
export GEMINI_API_KEY='<your-api-key>'
```

`GOOGLE_API_KEY` and `GOOGLE_GENAI_API_KEY` are read next, in that order. For a per-tenant key, start `GoogleAI()` with no key and pass `context={'secrets': {'api_key': tenant_key}}` on each `generate`, `generate_operation`, `embed`, or `embed_many` call. With no key from any of these, `GoogleAI()` logs one warning when it's constructed (to stderr unless your app configures `logging`), and a call with no plugin key and no secret fails with `FAILED_PRECONDITION`. A key the API rejects fails with `UNAUTHENTICATED` and the API's message.

### Vertex AI (Google Cloud)

To use Vertex AI models, ensure you have a Google Cloud project and Application Default Credentials (ADC) set up:
Expand Down
13 changes: 11 additions & 2 deletions packages/genkit-google-genai/src/genkit_google_genai/_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

from google.auth.exceptions import DefaultCredentialsError, GoogleAuthError, RefreshError, TransportError

from genkit import ErrorReason
from genkit.plugin_api import provider_error

GOOGLE_AUTH_ERRORS: tuple[type[GoogleAuthError], ...] = (DefaultCredentialsError, RefreshError, TransportError)
Expand All @@ -40,17 +41,25 @@ def raise_auth_error(error: GoogleAuthError) -> NoReturn:
``RefreshError`` raised from a ``TransportError`` with
``retryable=False``, so the cause is checked too.

A non-transient ``RefreshError`` is the token endpoint turning the
credential down, so it carries reason ``INVALID_CREDENTIALS``. A
``DefaultCredentialsError`` means ADC found nothing usable and nothing was
sent, so it has no reason.

Args:
error: The DefaultCredentialsError, RefreshError, or TransportError that was caught.

Raises:
GenkitError: UNAVAILABLE for a transient failure, else UNAUTHENTICATED,
with ``error`` as the cause.
GenkitError: UNAVAILABLE for a transient failure, else UNAUTHENTICATED
(with reason INVALID_CREDENTIALS for a rejected credential), with
``error`` as the cause.
"""
if isinstance(error, TransportError) or error.retryable or isinstance(error.__cause__, TransportError):
raise provider_error(error, status='UNAVAILABLE') from error
rejected = not isinstance(error, DefaultCredentialsError)
raise provider_error(
error,
status='UNAUTHENTICATED',
message='Google Cloud credentials are missing or were rejected',
reason=ErrorReason.INVALID_CREDENTIALS if rejected else None,
) from error
122 changes: 88 additions & 34 deletions packages/genkit-google-genai/src/genkit_google_genai/_google.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
from __future__ import annotations

import asyncio
import logging
import os
from collections.abc import Callable, Mapping
from typing import Any, NoReturn
Expand All @@ -64,7 +65,7 @@
from pydantic import BaseModel

import genkit_google_genai._constants as const
from genkit import GenkitError, ModelResponse, Operation
from genkit import FlowContext, GenkitError, ModelResponse, Operation
from genkit.embedder import Embedder, EmbedderRef, EmbedRequest, EmbedResponse
from genkit.model import (
BackgroundModel,
Expand Down Expand Up @@ -131,6 +132,7 @@
list_known_deep_research_models,
list_known_lyria_models,
)
from genkit_google_genai._models._interactions_utils import get_api_key_from_env
from genkit_google_genai._models._model_refs import (
family_embedder_ref,
family_model_ref,
Expand All @@ -140,7 +142,12 @@
is_unsupported_image_model_name,
strip_ref_prefixes,
)
from genkit_google_genai._models._sdk_config import check_timeout_seconds, timeout_seconds_to_ms
from genkit_google_genai._models._sdk_config import (
check_timeout_seconds,
request_client_kwargs,
timeout_seconds_to_ms,
)
from genkit_google_genai._models._secrets import MISSING_API_KEY_MESSAGE, context_api_key, missing_api_key_error
from genkit_google_genai._models._veo import (
GOOGLEAI_KNOWN_VEO,
VERTEX_KNOWN_VEO,
Expand All @@ -161,6 +168,12 @@
)
from genkit_google_genai._provider_errors import TRANSPORT_ERRORS, api_error, transport_error

# The missing-key warning fires in GoogleAI() before Genkit() runs and outside
# any trace, so genkit.get_logger's Dev UI routing has nothing to attach it to.
# That logger is structlog, which prints to stdout; stdlib logging with no
# handlers falls back to stderr, and an app's own logging config still applies.
_setup_logger = logging.getLogger(__name__) # noqa: TID251


class GenaiModels:
"""Container for models discovered dynamically from the Google GenAI API.
Expand Down Expand Up @@ -273,11 +286,26 @@ def _plugin_client(client_kwargs: dict[str, Any]) -> genai.Client:
raise_auth_error(e)


def _call_client(plugin: GoogleAI | VertexAI, context: dict[str, Any] | None) -> genai.Client:
"""Client for an action that does not build its own request client (embedders).

Order: ``context.secrets.api_key``, then the plugin key or credentials,
else ``FAILED_PRECONDITION``. The plugin client is only built when the
plugin has auth: ``genai.Client(api_key=None)`` raises ``ValueError``.
"""
secret = context_api_key(context or {})
if secret is not None:
return _plugin_client(request_client_kwargs(plugin._loop_client_kwargs(), api_key=secret))
if plugin._has_plugin_auth():
return plugin._runtime_client()
raise missing_api_key_error()


def _new_gemini(plugin: GoogleAI | VertexAI, clean_name: str) -> GeminiModel:
"""Construct a GeminiModel using the plugin's loop-local client."""
"""Construct a GeminiModel on the plugin's loop-local client, or None when keyless."""
return GeminiModel(
clean_name,
plugin._runtime_client(),
plugin._model_client(),
client_kwargs=plugin._loop_client_kwargs(),
base_url_pinned=plugin._base_url_pinned,
legacy_response_schema=plugin._legacy_response_schema,
Expand Down Expand Up @@ -315,14 +343,15 @@ def vertexai_name(name: str) -> str:

def _create_embedder_action(
name: str,
client_getter: Callable[[], genai.Client],
client_getter: Callable[[dict[str, Any]], genai.Client],
plugin_name: str,
) -> Action:
"""Create an Action object for an embedder.

Args:
name: The embedder id without the plugin prefix.
client_getter: Function returning the loop-local Google GenAI client.
client_getter: Takes the call's context and returns the client: a
tenant client for ``context.secrets.api_key``, else the plugin's.
plugin_name: The name of the plugin (googleai or vertexai).

Returns:
Expand All @@ -336,10 +365,10 @@ def _create_embedder_action(
is_vertex=(plugin_name == VERTEXAI_PLUGIN_NAME),
)

async def _run(request: EmbedRequest[EmbeddingConfig]) -> EmbedResponse:
async def _run(request: EmbedRequest[EmbeddingConfig], ctx: FlowContext[Any]) -> EmbedResponse:
embedder_client = GoogleEmbedder(
version=name,
client=client_getter(),
client=client_getter(ctx.context),
is_vertex=(plugin_name == VERTEXAI_PLUGIN_NAME),
)
return await embedder_client.generate(request)
Expand All @@ -349,7 +378,7 @@ async def _run(request: EmbedRequest[EmbeddingConfig]) -> EmbedResponse:

def _create_veo_background_model(
name: str,
client_getter: Callable[[], genai.Client],
client_getter: Callable[[], genai.Client | None],
plugin_name: str,
client_kwargs: Callable[[], dict[str, Any]] | None = None,
) -> BackgroundModel:
Expand All @@ -362,7 +391,8 @@ def _create_veo_background_model(

Args:
name: The model id without the plugin prefix.
client_getter: Function returning the loop-local Google GenAI client.
client_getter: Returns the plugin's loop-local client, or None when the
plugin booted keyless (VeoModel then builds one from context.secrets).
plugin_name: The name of the plugin (googleai or vertexai).
client_kwargs: Returns the plugin-level client kwargs for the running
loop, cloned when a call overrides the key or endpoint.
Expand Down Expand Up @@ -603,8 +633,13 @@ def __init__(

Args:
api_key: The API key for authenticating with the Google AI service.
If not provided, it defaults to reading from the 'GEMINI_API_KEY'
environment variable.
If not provided, reads ``GEMINI_API_KEY``, then ``GOOGLE_API_KEY``,
then ``GOOGLE_GENAI_API_KEY``. With no key and no ``credentials``
the plugin still loads and logs one warning: each call then needs
``context={'secrets': {'api_key': ...}}``, and a call without
one fails with ``FAILED_PRECONDITION`` (``generate`` returns
it on ``response.error``; ``embed`` and
``generate_operation`` raise ``GenkitError``).
credentials: Google Cloud credentials for authentication.
Defaults to None, in which case the client uses default authentication
mechanisms (e.g., application default credentials or API key).
Expand Down Expand Up @@ -666,22 +701,15 @@ def __init__(
``responseSchema`` field instead of ``responseJsonSchema``,
converted to its format; a schema that cannot be converted
raises ``INVALID_ARGUMENT``. Defaults to False.

Raises:
ValueError: If `api_key` is not provided and the 'GEMINI_API_KEY'
environment variable is not set.
"""
api_key = api_key if api_key else os.getenv('GEMINI_API_KEY')
# A missing key is not an error here: BYOK gateways boot keyless and
# pass context.secrets per call. _call_client raises on the first call
# without one. Warn now, since generate returns that failure on
# response.error instead of raising, and a quickstart would otherwise
# print an empty line and exit 0.
api_key = api_key or get_api_key_from_env()
if not api_key and credentials is None:
msg = (
'\n[Genkit] GEMINI_API_KEY environment variable not set.\n\n'
'To get started with Google AI models:\n'
'1. Obtain an API key from Google AI Studio: https://aistudio.google.com/app/apikey\n'
'2. Set your key in the terminal environment:\n'
' export GEMINI_API_KEY="your-api-key"\n\n'
'Documentation: https://genkit.dev/docs/python/integrations/google-genai/\n'
)
raise ValueError(msg)
_setup_logger.warning(MISSING_API_KEY_MESSAGE)

self._client_kwargs: dict[str, Any] = {
'vertexai': self._vertexai,
Expand Down Expand Up @@ -734,6 +762,22 @@ def _plugin_api_key(self) -> str | None:
raw = self._client_kwargs.get('api_key')
return raw if isinstance(raw, str) else None

def _has_plugin_auth(self) -> bool:
"""True when the plugin can build its own client (a key or credentials)."""
return bool(self._client_kwargs.get('api_key')) or self._client_kwargs.get('credentials') is not None

async def _listed_models(self) -> GenaiModels:
"""Models from the API, or none for a keyless plugin (no key to list with)."""
if not self._has_plugin_auth():
return GenaiModels()
return await _list_genai_models(self._runtime_client(), is_vertex=False)

def _model_client(self) -> genai.Client | None:
return self._runtime_client() if self._has_plugin_auth() else None

def _embed_client(self, context: dict[str, Any]) -> genai.Client:
return _call_client(self, context)

async def init(self) -> list[Action | BackgroundAction[Any, Any]]:
"""Initialize the plugin with static known models and embedders.

Expand Down Expand Up @@ -833,7 +877,7 @@ def _resolve_veo_model(self, name: str) -> BackgroundModel:
Returns:
BackgroundModel for the Veo model.
"""
return _create_veo_background_model(name, self._runtime_client, GOOGLEAI_PLUGIN_NAME, self._loop_client_kwargs)
return _create_veo_background_model(name, self._model_client, GOOGLEAI_PLUGIN_NAME, self._loop_client_kwargs)

def _resolve_model(self, name: str) -> Action | None:
"""Create an Action object for a Google AI model.
Expand Down Expand Up @@ -907,7 +951,7 @@ def _resolve_embedder(self, name: str) -> Action:
Returns:
Action object for the embedder.
"""
return _create_embedder_action(name, self._runtime_client, GOOGLEAI_PLUGIN_NAME)
return _create_embedder_action(name, self._embed_client, GOOGLEAI_PLUGIN_NAME)

async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]:
"""Generate a list of available actions or models.
Expand All @@ -927,7 +971,7 @@ async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]:
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)
genai_models = await self._listed_models()

for name in genai_models.gemini:
if (model_action := self._resolve_model(name)) is not None:
Expand All @@ -938,7 +982,7 @@ async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]:
for name in genai_models.veo:
veo_action = _create_veo_background_model(
name,
self._runtime_client,
self._model_client,
GOOGLEAI_PLUGIN_NAME,
client_kwargs=self._loop_client_kwargs,
)
Expand All @@ -947,7 +991,7 @@ async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]:
seen_names.add(veo_action.name)

for name in genai_models.embedders:
embedder_action = _create_embedder_action(name, self._runtime_client, GOOGLEAI_PLUGIN_NAME)
embedder_action = _create_embedder_action(name, self._embed_client, GOOGLEAI_PLUGIN_NAME)
if embedder_action.name not in seen_names:
actions_list.append(embedder_action)
seen_names.add(embedder_action.name)
Expand Down Expand Up @@ -1221,6 +1265,16 @@ 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)

def _has_plugin_auth(self) -> bool:
# Vertex falls back to ADC; the client itself reports missing credentials.
return True

def _model_client(self) -> genai.Client | None:
return self._runtime_client() if self._has_plugin_auth() else None

def _embed_client(self, context: dict[str, Any]) -> genai.Client:
return _call_client(self, context)

async def init(self) -> list[Action | BackgroundAction[Any, Any]]:
"""Initialize the plugin with static known models and embedders.

Expand Down Expand Up @@ -1298,7 +1352,7 @@ def _resolve_veo_model(self, name: str) -> BackgroundModel:
Returns:
BackgroundModel for the Veo model.
"""
return _create_veo_background_model(name, self._runtime_client, VERTEXAI_PLUGIN_NAME, self._loop_client_kwargs)
return _create_veo_background_model(name, self._model_client, VERTEXAI_PLUGIN_NAME, self._loop_client_kwargs)

def _resolve_model(self, name: str) -> Action | None:
"""Create an Action object for a Vertex AI model.
Expand Down Expand Up @@ -1384,7 +1438,7 @@ def _resolve_embedder(self, name: str) -> Action:
Returns:
Action object for the embedder.
"""
return _create_embedder_action(name, self._runtime_client, VERTEXAI_PLUGIN_NAME)
return _create_embedder_action(name, self._embed_client, VERTEXAI_PLUGIN_NAME)

async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]:
"""Generate a list of available actions or models.
Expand Down Expand Up @@ -1415,7 +1469,7 @@ async def list_actions(self) -> list[Action | BackgroundAction[Any, Any]]:
for name in genai_models.veo:
veo_action = _create_veo_background_model(
name,
self._runtime_client,
self._model_client,
VERTEXAI_PLUGIN_NAME,
client_kwargs=self._loop_client_kwargs,
)
Expand Down
Loading
Loading