diff --git a/packages/genkit-anthropic/README.md b/packages/genkit-anthropic/README.md index e352ffbe..26d35301 100644 --- a/packages/genkit-anthropic/README.md +++ b/packages/genkit-anthropic/README.md @@ -29,7 +29,7 @@ ai = Genkit(plugins=[Anthropic()]) async def main() -> None: res = await ai.generate( - model=Anthropic.claude('claude-sonnet-4-6'), + model=Anthropic.claude('claude-sonnet-5-5'), prompt='Explain recursion in 10 words.', ) print(res.text) @@ -41,6 +41,9 @@ if __name__ == '__main__': ``` Set `ANTHROPIC_API_KEY` in the environment, or pass `api_key=` to `Anthropic()`. +Create a key in the [Anthropic Console](https://console.anthropic.com/settings/keys). +To run Claude through Google Cloud instead, see +[Claude on Google Cloud](#claude-on-google-cloud). `base_url=` points the plugin at another server. Pass the origin with no `/v1` suffix; the SDK appends `/v1/messages`. Any other `AsyncAnthropic` setting goes in `client_options`: @@ -53,6 +56,202 @@ Anthropic( ) ``` +## Claude on Google Cloud + +You can also run the same Claude models through Google Cloud. Usage is billed +to your Google Cloud project instead of an Anthropic account, and you +authenticate with your Google login instead of an API key. Your code doesn't +change apart from one constructor argument: refs, `AnthropicConfig` and +`.prompt` files work the same on both. + +```python +# Anthropic API (ANTHROPIC_API_KEY) +Anthropic() + +# Google Cloud (your gcloud login and project) +Anthropic(backend=GoogleCloud()) +``` + +Most users of this plugin call the Anthropic API, so `Anthropic()`'s own +arguments (`api_key`, `base_url`) are about that. Everything Google Cloud needs +goes in the one `GoogleCloud(...)` object instead of adding more arguments to +`Anthropic()`. + +### First-time setup + +This takes about five minutes the first time. If you already use Vertex AI +(now Gemini Enterprise Agent Platform) and have Claude enabled in a project, +skip to step 5. + +1. **Install the gcloud CLI** ([install guide](https://cloud.google.com/sdk/docs/install)), + then log in: + + ```bash + gcloud auth login + ``` + +2. **Pick a project with billing turned on.** To make a new one, use + [Create a project](https://console.cloud.google.com/projectcreate), then + link a billing account on the [Billing page](https://console.cloud.google.com/billing). + Then make it your default project: + + ```bash + gcloud config set project YOUR_PROJECT_ID + ``` + +3. **Turn on the API** that serves Claude on Google Cloud: + + ```bash + gcloud services enable aiplatform.googleapis.com + ``` + +4. **Enable Claude for the project.** Open the model's card in Model Garden, + e.g. [Claude Sonnet 5.5](https://console.cloud.google.com/agent-platform/publishers/anthropic/model-garden/claude-sonnet-5-5), + click **Enable**, and accept Anthropic's terms. You do this once per model, + per project. If you didn't create the project yourself, ask its owner for + the *Consumer Procurement Entitlement Manager* role (to enable models) and + the *Agent Platform User* role (to call them). + +5. **Give your code access to your login:** + + ```bash + gcloud auth application-default login + gcloud auth application-default set-quota-project YOUR_PROJECT_ID + ``` + + The second command is optional. It stops google-auth from warning that + your login has no quota project. + +6. **Install the extra and call Claude:** + + ```bash + uv add 'genkit-anthropic[google-cloud]' + ``` + + ```python + from genkit import Genkit + from genkit_anthropic import Anthropic, GoogleCloud + + # 1. Project comes from `gcloud config set project`; location defaults to 'global' + ai = Genkit(plugins=[Anthropic(backend=GoogleCloud())]) + + + async def main() -> None: + # 2. Same typed ref and config as the Anthropic API + res = await ai.generate( + model=Anthropic.claude('claude-sonnet-5-5'), + prompt='Suggest a dish for a guest with a shellfish allergy.', + ) + print(res.text) + # => Herb-Roasted Chicken with Lemon Rice + + + if __name__ == '__main__': + ai.run_main(main()) + ``` + +### Deploying to Google Cloud + +On Cloud Run, GKE or Compute Engine, skip steps 1 and 5. The code runs as the +service's service account, and `GoogleCloud()` picks up the project from the +environment. The service account needs the *Agent Platform User* role: + +```bash +gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \ + --member=serviceAccount:YOUR_SERVICE_ACCOUNT_EMAIL \ + --role=roles/aiplatform.user +``` + +### If a call fails + +The error comes back on `response.error`, and the Dev UI shows it on the run. + +- **`FAILED_PRECONDITION` ... found no Google Cloud credentials**, or + **... could not refresh Google Cloud credentials**: run step 5 again. The + next call picks up the new login; you don't need to restart the app. +- **`FAILED_PRECONDITION` ... needs a Google Cloud project**: run + `gcloud config set project YOUR_PROJECT_ID`, set `GOOGLE_CLOUD_PROJECT`, or + pass `GoogleCloud(project='YOUR_PROJECT_ID')`. +- **`PERMISSION_DENIED`, ... API has not been used in project ... or it is + disabled**: run step 3. It can take a few minutes to take effect. +- **`PERMISSION_DENIED` naming `aiplatform.endpoints.predict`**: your login or + service account needs the *Agent Platform User* role (step 4, or + [Deploying to Google Cloud](#deploying-to-google-cloud)). +- **`NOT_FOUND` for the model**: enable that model for this project (step 4), + and check the model id. +- **`RESOURCE_EXHAUSTED`**: the project is out of quota for that model. Check + the model's quota on the [Quotas page](https://console.cloud.google.com/iam-admin/quotas), + and request more there if you need it. + +### Settings + +- `project` is taken from, in order: `GoogleCloud(project=...)`, + `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, then your credentials (your + `gcloud config` project locally, the service's project on Google Cloud). +- `location` is taken from `GoogleCloud(location=...)`, then + `GOOGLE_CLOUD_LOCATION`, then `global`. Every project that enables Claude + gets quota on the `global` endpoint; regional endpoints need regional quota. +- Only `backend=` switches to Google Cloud. A missing `ANTHROPIC_API_KEY` + never falls back to it, and `api_key=` with `backend=GoogleCloud()` raises + `ValueError`. +- `client_options` go to `AsyncAnthropicVertex`. Pass `credentials=` or + `access_token=` there to use your own credential instead of your gcloud + login; then set the project with `project=` or an environment variable. +- Google Cloud has no Models API, so the Dev UI lists the plugin's built-in + Claude catalog. Any other Claude id still resolves when you call it. +- Model names on Google Cloud have no date: `Anthropic.claude('claude-haiku-4-5')` + is sent as `claude-haiku-4-5`. On the Anthropic API, the plugin sends the + pinned id (`claude-haiku-4-5-20251001`) for you. + +### What's different on Google Cloud + +Most of `AnthropicConfig` behaves the same on both backends. These are the +places it doesn't. + +**Works differently:** + +- **Images must be inline.** Google Cloud rejects image URLs + (`INVALID_ARGUMENT`, `URL sources are not supported`). Send the image as a + base64 data URL instead: + + ```python + import base64 + + from genkit import Part + + # 1. Inline the image; a https:// URL fails on Google Cloud + photo = 'data:image/jpeg;base64,' + base64.b64encode(jpeg_bytes).decode() + + # 2. Same call on both backends + res = await ai.generate( + model=Anthropic.claude('claude-sonnet-5-5'), + prompt=[Part.from_text('Is this dish shellfish-free?'), Part.from_media(url=photo)], + ) + ``` + +- **No default beta headers.** On the Anthropic API, beta calls carry the + plugin's default betas (Files API, effort, structured outputs, task + budgets). Google Cloud doesn't offer all of them, so it gets none. Setting + `task_budget` still sends the one header it needs. To send others, list them + in `betas`. +- **An organization policy can block features.** If your organization sets + `constraints/vertexai.allowedPartnerModelFeatures`, it can turn off native + structured output and web search for Claude. Genkit uses native structured + output for cataloged models, so JSON output fails in that case. Pass + `output_constrained=False` to have Genkit ask for JSON in the prompt + instead, or ask your admin to allow the feature. +- **No per-request keys.** Every call bills the project, so a key in + `context={'secrets': {'api_key': ...}}` fails with `FAILED_PRECONDITION`. + +**Not available on Google Cloud:** + +- `service_tier` and `inference_geo` in `extra`. +- The Files API, web fetch and code execution betas. + +**Works the same:** prompt caching (`cache_control`, with cache reads and +writes in `usage`), citations, base64 images, thinking and `effort`, +`user_id`, `version`, `api_version='beta'`, and an explicit `betas` list. + ## Typed config `AnthropicConfig` is flat. Choices are exported Literals (`ThinkingMode`, @@ -79,7 +278,7 @@ config = AnthropicConfig( # 2. Generate with it await ai.generate( - model=Anthropic.claude('claude-opus-4-6'), + model=Anthropic.claude('claude-sonnet-5-5'), prompt='Plan a tasting menu.', config=config, ) @@ -92,6 +291,9 @@ await ai.generate( - A `thinking_budget` alone means `thinking='enabled'`. `'enabled'` needs a budget from some config layer; `'adaptive'` doesn't send one, and `'disabled'` sends neither the budget nor the display. +- Models after the 4.6 generation (Opus 4.7 and later) take only + `'adaptive'` thinking; steer it with `effort`. `'enabled'` with a budget is + deprecated on Opus 4.6 and Sonnet 4.6, and works on earlier models. - `task_budget` is a beta field, so it sends the call to the beta API. - To send a shape the flat fields don't cover, put Anthropic's object in `extra`, e.g. `extra={'thinking': {...}}`. It replaces the built object. @@ -105,7 +307,7 @@ or back on without restating the budget: ```python # 1. Model default with extended thinking on -claude = Anthropic.claude('claude-sonnet-4-6', config=AnthropicConfig(thinking='enabled', thinking_budget=4096)) +claude = Anthropic.claude('claude-haiku-4-5', config=AnthropicConfig(thinking='enabled', thinking_budget=4096)) # 2. Turn it off for one call; the inherited budget isn't sent await ai.generate(model=claude, prompt='Is shellfish safe for this guest?', config={'thinking': 'disabled'}) @@ -131,7 +333,7 @@ as a flat flag: ```python # 1. Require one tool call, and only one res = await ai.generate( - model='anthropic/claude-sonnet-4-6', + model='anthropic/claude-sonnet-5-5', prompt='Is the pho in stock?', tools=['lookup_menu'], tool_choice='required', @@ -157,7 +359,7 @@ To bill a call to someone else's Anthropic account, pass their key in ```python res = await ai.generate( - model='anthropic/claude-sonnet-4-6', + model='anthropic/claude-sonnet-5-5', prompt='hi', context={'secrets': {'api_key': tenant_key}}, ) @@ -174,7 +376,7 @@ res = await ai.generate( - A client whose credential can't be swapped refuses a tenant key with `FAILED_PRECONDITION` rather than billing its own account: an `Anthropic(client_options={'auth_token': ...})` client, one whose `default_headers` pin - `x-api-key` or `Authorization`, and Claude on Vertex AI Model Garden, which + `x-api-key` or `Authorization`, and `Anthropic(backend=GoogleCloud())`, which authenticates with Google Cloud credentials. ## Disclaimer diff --git a/packages/genkit-anthropic/pyproject.toml b/packages/genkit-anthropic/pyproject.toml index d904ba0b..1f58fbea 100644 --- a/packages/genkit-anthropic/pyproject.toml +++ b/packages/genkit-anthropic/pyproject.toml @@ -56,6 +56,10 @@ readme = "README.md" requires-python = ">=3.10" version = "0.14.0" +[project.optional-dependencies] +# Anthropic(backend=GoogleCloud()): google-auth for application default credentials. +google-cloud = ["anthropic[vertex]>=0.98.0,<1"] + [project.urls] "Bug Tracker" = "https://github.com/genkit-ai/genkit-python/issues" Changelog = "https://github.com/genkit-ai/genkit-python/releases" diff --git a/packages/genkit-anthropic/src/genkit_anthropic/__init__.py b/packages/genkit-anthropic/src/genkit_anthropic/__init__.py index 1effef23..a9eba987 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/__init__.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/__init__.py @@ -30,9 +30,9 @@ async def main() -> None: - # 2. Generate with Claude Sonnet 4.6 + # 2. Generate with Claude Sonnet 5 res = await ai.generate( - model=Anthropic.claude('claude-sonnet-4-6'), + model=Anthropic.claude('claude-sonnet-5-5'), prompt='Explain recursion in 10 words.', ) @@ -50,17 +50,24 @@ async def main() -> None: can bring its own key as ``context={'secrets': {'api_key': ...}}``; a plugin with no key of its own serves only those calls. + ``Anthropic(backend=GoogleCloud(project=...))`` serves the same models from + Google Cloud instead, authenticated with application default credentials + and billed to the project (``uv add 'genkit-anthropic[google-cloud]'``). + Refs, config and ``.prompt`` files stay the same. + See Also: - Anthropic documentation: https://docs.anthropic.com/ """ from genkit_anthropic._config import AnthropicConfig, Effort, ThinkingDisplay, ThinkingMode +from genkit_anthropic._google_cloud import GoogleCloud from genkit_anthropic._plugin import Anthropic __all__ = [ 'Anthropic', 'AnthropicConfig', 'Effort', + 'GoogleCloud', 'ThinkingDisplay', 'ThinkingMode', ] diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_anthropic_api.py b/packages/genkit-anthropic/src/genkit_anthropic/_anthropic_api.py new file mode 100644 index 00000000..25f16efc --- /dev/null +++ b/packages/genkit-anthropic/src/genkit_anthropic/_anthropic_api.py @@ -0,0 +1,139 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The Anthropic API as a backend: API keys, per-request keys, and the Models API.""" + +import os +from collections.abc import Mapping +from typing import Any +from urllib.parse import urlsplit + +from anthropic import AsyncAnthropic + +from genkit import GenkitError +from genkit_anthropic._backend import Backend, client_kwargs +from genkit_anthropic._model_info import get_model_info +from genkit_anthropic._models import TASK_BUDGET_BETA + +# Sent on every beta-surface call to the Anthropic API, matching the JS plugin. +BETA_APIS: tuple[str, ...] = ( + 'files-api-2025-04-14', + 'effort-2025-11-24', + 'structured-outputs-2025-11-13', + TASK_BUDGET_BETA, +) + + +class AnthropicApiBackend(Backend[AsyncAnthropic]): + """Claude on the Anthropic API, billed to an Anthropic key.""" + + default_betas = BETA_APIS + + def __init__(self, *, api_key: str | None, base_url: str | None, client_options: Mapping[str, Any] | None) -> None: + """Validate the client settings at setup, on the user's line. + + Raises: + TypeError: An unknown or repeated ``client_options`` key. + ValueError: The base URL ends in ``/v1``. + """ + self._options = client_kwargs(AsyncAnthropic, client_options, api_key=api_key, base_url=base_url) + if 'base_url' in self._options: + _reject_v1_suffix(self._options['base_url'], source='base_url') + else: + _reject_v1_suffix(os.environ.get('ANTHROPIC_BASE_URL'), source='ANTHROPIC_BASE_URL') + + def _new_client(self) -> AsyncAnthropic: + return AsyncAnthropic(**self._options) + + async def request_client(self, api_key: str | None) -> AsyncAnthropic: + """The plugin's client, or a copy on the caller's key. + + A client that can't swap its credential raises rather than sending the + call on the plugin's own key, because whoever passed a key expects + that account to be billed. + """ + client = self.client() + if api_key is None: + # A plugin built without a credential serves only callers who bring a key. + if not _has_credential(client): + raise _missing_key_error() + return client + + reason = None + # copy() cannot unset these, so the override would leave the base credential authenticating the request. + if client.auth_token is not None: + reason = 'the plugin client authenticates with an auth token' + elif (header := _pinned_credential_header(client)) is not None: + reason = f'the plugin client sets its own {header} header' + if reason is not None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'A per-request API key from context.secrets cannot be used: {reason}.', + ) + # copy() keeps every other client setting and shares the pooled HTTP transport. + return client.copy(api_key=api_key) + + def api_model_id(self, name: str) -> str: + """The catalog's pinned id, e.g. ``claude-haiku-4-5-20251001``; an unknown id goes as is.""" + versions = get_model_info(name).versions + return versions[0] if versions else name + + async def list_model_ids(self) -> list[str]: + """Every model id the Models API lists, in API order. + + Uses the beta models endpoint (matching JS, so both stable and beta + models are discovered) and fully paginates via ``async for`` (matching + Go's completeness, rather than JS's first-page-only read). + """ + return [model.id async for model in self.client().beta.models.list() if model.id] + + +def _reject_v1_suffix(base_url: str | None, *, source: str) -> None: + """The SDK appends ``/v1/messages``, so a base URL ending in ``/v1`` would send ``/v1/v1/messages``.""" + if base_url and urlsplit(base_url).path.rstrip('/').endswith('/v1'): + raise ValueError( + f'{source} {base_url!r} ends in /v1, but the Anthropic SDK appends /v1/messages itself; ' + 'pass the origin, e.g. https://claude-proxy.example.com' + ) + + +def _pinned_credential_header(client: AsyncAnthropic) -> str | None: + """The credential header ``client`` pins in ``default_headers``, if any. + + ``copy(api_key=...)`` keeps custom headers, so a pinned ``x-api-key`` or + ``Authorization`` would still go out next to a tenant key and could + authenticate the call. + """ + for name in client._custom_headers: # noqa: SLF001 + if name.lower() in ('x-api-key', 'authorization'): + return name + return None + + +def _has_credential(client: AsyncAnthropic) -> bool: + if client.api_key is not None or client.auth_token is not None or client.credentials is not None: + return True + return _pinned_credential_header(client) is not None + + +def _missing_key_error() -> GenkitError: + return GenkitError( + status='FAILED_PRECONDITION', + message=( + 'Anthropic needs an API key: set ANTHROPIC_API_KEY or pass Anthropic(api_key=...), ' + "or send a per-request key as context={'secrets': {'api_key': ...}}." + ), + ) diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_backend.py b/packages/genkit-anthropic/src/genkit_anthropic/_backend.py new file mode 100644 index 00000000..d5e8ba36 --- /dev/null +++ b/packages/genkit-anthropic/src/genkit_anthropic/_backend.py @@ -0,0 +1,106 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 + +"""What differs between the places the Anthropic plugin serves Claude from.""" + +import inspect +from abc import ABC, abstractmethod +from collections.abc import Mapping +from typing import Any, ClassVar, Generic, TypeVar + +from genkit.plugin_api import loop_local_client +from genkit_anthropic._models import ClaudeClient + +ClientT_co = TypeVar('ClientT_co', bound=ClaudeClient, covariant=True) + + +class Backend(ABC, Generic[ClientT_co]): + """One place Claude is served from, e.g. the Anthropic API or Google Cloud. + + The plugin and ``AnthropicModel`` are the same for every backend. A backend + owns only what differs: the SDK client it builds, how a call gets its + credential, which models it can list, and which beta headers it offers. + """ + + # Sent on beta-surface calls that don't pass their own betas. + default_betas: ClassVar[tuple[str, ...]] = () + + @abstractmethod + def _new_client(self) -> ClientT_co: + """Build the SDK client from the backend's settings.""" + + @loop_local_client + def client(self) -> ClientT_co: + """The shared SDK client for the running event loop. + + Calls go through ``request_client``, which runs the backend's checks + first; only tests reach for this directly. + """ + return self._new_client() + + @abstractmethod + async def request_client(self, api_key: str | None) -> ClientT_co: + """The client for one call, given the caller's ``context.secrets`` key, if any. + + Raises: + GenkitError: FAILED_PRECONDITION when the call can't be authenticated. + """ + + @abstractmethod + def api_model_id(self, name: str) -> str: + """The id this backend expects as ``model`` for the plugin's model ``name``.""" + + @abstractmethod + async def list_model_ids(self) -> list[str]: + """Model ids the backend reports; the plugin adds its built-in catalog.""" + + +def client_kwargs( + client_cls: type[ClaudeClient], + client_options: Mapping[str, Any] | None, + *, + reserved: frozenset[str] = frozenset(), + api_key: str | None = None, + base_url: str | None = None, +) -> dict[str, Any]: + """Merge the plugin's typed settings into ``client_options`` for ``client_cls``. + + Args: + client_cls: The SDK client the options are for. + client_options: The user's ``client_options``. + reserved: Constructor keys the backend sets itself, so users can't. + api_key: The plugin's ``api_key`` argument; None means unset. + base_url: The plugin's ``base_url`` argument; None means unset. + + Raises: + TypeError: A ``client_options`` key ``client_cls`` doesn't take, or a + setting given both as an argument and in ``client_options``. + """ + allowed = frozenset(inspect.signature(client_cls.__init__).parameters) - {'self'} - reserved + options = dict(client_options or {}) + for key in options: + if key not in allowed: + raise TypeError( + f'Anthropic got an unexpected client_options key {key!r}; ' + f'{client_cls.__name__} accepts {", ".join(sorted(k for k in allowed if not k.startswith("_")))}' + ) + for name, value in (('api_key', api_key), ('base_url', base_url)): + if value is None: + continue + if name in options: + raise TypeError(f'Anthropic got {name} both as an argument and in client_options; pass it once') + options[name] = value + return options diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_google_cloud.py b/packages/genkit-anthropic/src/genkit_anthropic/_google_cloud.py new file mode 100644 index 00000000..c2ccba60 --- /dev/null +++ b/packages/genkit-anthropic/src/genkit_anthropic/_google_cloud.py @@ -0,0 +1,248 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Google Cloud as a backend for the Anthropic plugin.""" + +import asyncio +import os +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + +from anthropic import NOT_GIVEN, AsyncAnthropicVertex + +from genkit import GenkitError +from genkit.plugin_api import provider_error +from genkit_anthropic._backend import Backend, client_kwargs + +# Every project that enables Claude gets quota on the global endpoint; +# regional endpoints need regional quota. +DEFAULT_LOCATION = 'global' + + +@dataclass(frozen=True, kw_only=True) +class GoogleCloud: + """Serve Claude from Google Cloud, billed to a Google Cloud project. + + This is Claude from Vertex AI Model Garden: enable the model there, then + pass ``Anthropic(backend=GoogleCloud(...))``. Requests authenticate + with application default credentials, so there is no API key. Refs, + ``AnthropicConfig`` and ``.prompt`` files are the same as on the + Anthropic API. + + Example: + ```python + from genkit import Genkit + from genkit_anthropic import Anthropic, GoogleCloud + + # 1. Bill Claude to your Google Cloud project instead of an Anthropic key + ai = Genkit(plugins=[Anthropic(backend=GoogleCloud(project='bistro-prod'))]) + + # 2. Same typed ref and config as the Anthropic API + res = await ai.generate( + model=Anthropic.claude('claude-sonnet-5-5'), + prompt='Suggest a dish for a guest with a shellfish allergy.', + ) + print(res.text) + # => Herb-Roasted Chicken with Lemon Rice + + # 3. On Cloud Run, the project comes from the environment + Anthropic(backend=GoogleCloud()) + # => project from GOOGLE_CLOUD_PROJECT or the credentials, location 'global' + ``` + + Attributes: + project: Google Cloud project. Defaults to ``GCLOUD_PROJECT``, then + ``GOOGLE_CLOUD_PROJECT``, then the credentials' project. + location: Google Cloud location. Defaults to ``GOOGLE_CLOUD_LOCATION``, + then ``global``. + """ + + project: str | None = None + location: str | None = None + + +def resolve_project(backend: GoogleCloud) -> str | None: + """The project from the argument or the environment; None means ask the credentials.""" + return backend.project or os.environ.get('GCLOUD_PROJECT') or os.environ.get('GOOGLE_CLOUD_PROJECT') or None + + +def resolve_location(backend: GoogleCloud) -> str: + """The location from the argument or the environment, else ``global``.""" + return backend.location or os.environ.get('GOOGLE_CLOUD_LOCATION') or DEFAULT_LOCATION + + +def require_google_auth() -> None: + """Fail at setup, on the user's line, when the google-cloud extra isn't installed. + + Raises: + ImportError: ``google-auth`` or its ``requests`` transport isn't installed. + """ + # Optional dependency: google-auth[requests] ships with the [google-cloud] extra only. + try: + import google.auth # noqa: F401, PLC0415 + import google.auth.transport.requests # noqa: F401, PLC0415 + except ImportError as e: + raise ImportError( + "Anthropic(backend=GoogleCloud()) needs the google-cloud extra: uv add 'genkit-anthropic[google-cloud]'" + ) from e + + +# The scope AsyncAnthropicVertex asks for when it loads credentials itself. +_SCOPES = ('https://www.googleapis.com/auth/cloud-platform',) +_LOGIN_FIX = ( + 'run `gcloud auth application-default login` on your machine, ' + 'or give the service account roles/aiplatform.user when running on Google Cloud' +) + + +def load_adc() -> tuple[Any, str | None]: # noqa: ANN401 - google.auth credentials are untyped + """Application default credentials, refreshed, and their project (blocking: may hit the metadata server). + + Refreshing here makes a missing or stale login fail on the first call + with the command that fixes it. Inside the SDK it surfaces mid-request + as an unmapped google.auth error, which reaches the caller as INTERNAL. + + Raises: + GenkitError: FAILED_PRECONDITION when there are no credentials or + they need a fresh login; UNAVAILABLE when the refresh hit a + transient network or metadata-server failure. + """ + # Optional dependency, checked by require_google_auth at setup. + import google.auth # noqa: PLC0415 + from google.auth.exceptions import DefaultCredentialsError, RefreshError, TransportError # noqa: PLC0415 + from google.auth.transport.requests import Request # noqa: PLC0415 + + try: + credentials, project = google.auth.default(scopes=list(_SCOPES)) + credentials.refresh(Request()) + except TransportError as e: + raise provider_error(e, status='UNAVAILABLE') from e + except DefaultCredentialsError as e: + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'Anthropic(backend=GoogleCloud()) found no Google Cloud credentials: {_LOGIN_FIX}', + cause=e, + ) from e + except RefreshError as e: + if e.retryable or isinstance(e.__cause__, TransportError): + raise provider_error(e, status='UNAVAILABLE') from e + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'Anthropic(backend=GoogleCloud()) could not refresh Google Cloud credentials: {_LOGIN_FIX}', + cause=e, + ) from e + return credentials, project + + +# region and project_id come from GoogleCloud(project=..., location=...), so they aren't client options. +_SET_BY_GOOGLE_CLOUD = frozenset({'region', 'project_id'}) +# Either one in client_options means the caller brings their own credential, so ADC isn't loaded. +_OWN_CREDENTIAL = frozenset({'access_token', 'credentials'}) + + +class GoogleCloudBackend(Backend[AsyncAnthropicVertex]): + """Claude on Google Cloud, authenticated with application default credentials.""" + + # Vertex doesn't offer every Anthropic API beta, so none are assumed. + default_betas = () + + def __init__( + self, + config: GoogleCloud, + *, + api_key: str | None, + base_url: str | None, + client_options: Mapping[str, Any] | None, + ) -> None: + """Validate the client settings at setup, on the user's line. + + Raises: + ValueError: ``api_key`` was passed; Google Cloud doesn't use one. + ImportError: The ``google-cloud`` extra isn't installed. + TypeError: An unknown or repeated ``client_options`` key. + """ + if api_key is not None: + raise ValueError( + 'Anthropic(backend=GoogleCloud()) authenticates with Google Cloud credentials; drop api_key' + ) + require_google_auth() + # Vertex URLs end in /v1, so the Anthropic API's /v1 guard doesn't apply to base_url here. + self._options = client_kwargs( + AsyncAnthropicVertex, client_options, reserved=_SET_BY_GOOGLE_CLOUD, base_url=base_url + ) + # An explicit setting beats the environment; the SDK's own + # ANTHROPIC_VERTEX_PROJECT_ID / CLOUD_ML_REGION never pick these. + self._project = resolve_project(config) + self._location = resolve_location(config) + self._uses_adc = not (_OWN_CREDENTIAL & self._options.keys()) + self._ready = False + + def _new_client(self) -> AsyncAnthropicVertex: + # Callers await request_client first, which resolves the project; NOT_GIVEN is only for tests. + # With ADC, request_client has also put the loaded credentials into the options. + project_id = self._project if self._project is not None else NOT_GIVEN + return AsyncAnthropicVertex(region=self._location, project_id=project_id, **self._options) + + async def request_client(self, api_key: str | None) -> AsyncAnthropicVertex: + """The plugin's client, once its credentials and project are known. + + Raises: + GenkitError: FAILED_PRECONDITION for a ``context.secrets`` key, no + usable credentials, or no project. + """ + if api_key is not None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'A per-request API key from context.secrets cannot be used: ' + 'Anthropic(backend=GoogleCloud()) authenticates with Google Cloud credentials.' + ), + ) + await self._prepare() + return self.client() + + def api_model_id(self, name: str) -> str: + """The name as given: Google Cloud names Claude without a date, e.g. ``claude-haiku-4-5``.""" + return name + + async def list_model_ids(self) -> list[str]: + """Nothing: Google Cloud has no Models API, so the built-in catalog is the whole list.""" + return [] + + async def _prepare(self) -> None: + """Load credentials and find the project, before the first client is built. + + With ADC, the credentials load once and their project fills in when + none was passed or set, as on Cloud Run. The lookup can hit the + metadata server, so it runs in a thread. A failure isn't cached, so the + next call retries after the user logs in. + """ + if self._ready: + return + if self._uses_adc: + credentials, adc_project = await asyncio.to_thread(load_adc) + self._options['credentials'] = credentials + self._project = self._project or adc_project + if self._project is None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'Anthropic(backend=GoogleCloud()) needs a Google Cloud project: pass GoogleCloud(project=...), ' + 'set GOOGLE_CLOUD_PROJECT, or run `gcloud config set project PROJECT_ID`' + ), + ) + self._ready = True diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_models.py b/packages/genkit-anthropic/src/genkit_anthropic/_models.py index a0818f0b..4aac2810 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_models.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_models.py @@ -25,7 +25,8 @@ """ import json -from typing import Any, Literal, Protocol, cast +from collections.abc import Sequence +from typing import Any, Literal, Protocol, TypeAlias, cast import httpx from anthropic import ( @@ -35,6 +36,7 @@ APIStatusError, APITimeoutError, AsyncAnthropic, + AsyncAnthropicVertex, ) from anthropic.types import Message as AnthropicMessage @@ -43,7 +45,6 @@ from genkit.plugin_api import StatusName, provider_error from genkit_anthropic._config import AnthropicConfig from genkit_anthropic._model_info import get_model_info -from genkit_anthropic._secrets import context_api_key from genkit_anthropic._utils import ( build_cache_usage, get_cache_control, @@ -56,12 +57,11 @@ logger = get_logger(__name__) DEFAULT_MAX_OUTPUT_TOKENS = 4096 -BETA_APIS: tuple[str, ...] = ( - 'files-api-2025-04-14', - 'effort-2025-11-24', - 'structured-outputs-2025-11-13', - 'task-budgets-2026-03-13', -) +# Vertex rejects task_budget without this header, so the field brings it on every backend. +TASK_BUDGET_BETA = 'task-budgets-2026-03-13' + +# Every SDK client AnthropicModel sends through; they share messages and beta.messages. +ClaudeClient: TypeAlias = AsyncAnthropic | AsyncAnthropicVertex class _ModelDumpable(Protocol): @@ -313,17 +313,12 @@ def _merge_config_extra(params: dict[str, Any], extra: dict[str, Any] | None) -> params['extra_body'] = extra_body -def pinned_credential_header(client: AsyncAnthropic) -> str | None: - """The credential header ``client`` pins in ``default_headers``, if any. - - ``copy(api_key=...)`` keeps custom headers, so a pinned ``x-api-key`` or - ``Authorization`` would still go out next to a tenant key and could - authenticate the call. - """ - for name in client._custom_headers: # noqa: SLF001 - if name.lower() in ('x-api-key', 'authorization'): - return name - return None +def _request_betas(default_betas: Sequence[str], config: AnthropicConfig) -> list[str]: + """The backend's default beta headers plus any that a set beta-only field needs.""" + headers = list(default_betas) + if config.task_budget is not None and TASK_BUDGET_BETA not in headers: + headers.append(TASK_BUDGET_BETA) + return headers class AnthropicModel: @@ -342,25 +337,33 @@ class AnthropicModel: def __init__( self, model_name: str, - client: AsyncAnthropic, + client: ClaudeClient, default_api_version: Literal['stable', 'beta'] | None = None, + default_betas: Sequence[str] = (), + api_model_id: str | None = None, ) -> None: """Initialize Anthropic model. - Sets up the client for communicating with the Anthropic API - and stores the model name. + The client arrives ready to send: the backend has already picked its + credential, so this class only maps requests and responses. Args: model_name: Name of the Anthropic model. - client: AsyncAnthropic client instance. + client: SDK client for the backend serving the model. default_api_version: Default API surface when a request does not provide an explicit ``apiVersion``. + default_betas: Beta headers sent on beta-surface calls that don't + pass their own ``betas``. Backends differ in which betas they + offer, so none are assumed. + api_model_id: The id sent as ``model``. Defaults to the catalog's + pinned Anthropic API id; other backends name models their own way. """ model_info = get_model_info(model_name) self._model_info = model_info - self.model_name = model_info.versions[0] if model_info.versions else model_name + self.model_name = api_model_id or (model_info.versions[0] if model_info.versions else model_name) self.client = client self._default_api_version = default_api_version + self._default_betas = tuple(default_betas) async def generate(self, request: ModelRequest, ctx: ModelContext | None = None) -> ModelResponse: """Generate response from Anthropic. @@ -372,8 +375,7 @@ async def generate(self, request: ModelRequest, ctx: ModelContext | None = None) Returns: Generated response. """ - context = ctx.context if ctx is not None and isinstance(ctx.context, dict) else None - client = self._client_for_key(context_api_key(context)) + client = self.client # A config that fails validation, a bad thinking budget, or a malformed # data URI is caller input, so retry skips it. Pydantic's # ValidationError is a ValueError. @@ -469,33 +471,6 @@ def _build_usage(self, response: AnthropicMessage, basic_usage: GenerationUsage) cache_read_input_tokens=raw_read if isinstance(raw_read, int) and not isinstance(raw_read, bool) else 0, ) - def _client_for_key(self, api_key: str | None) -> object: - """Return the request client, re-credentialed with the caller's key when one was given. - - A client that can't swap its credential raises rather than sending the - call on the plugin's own key, because whoever passed a key expects - that account to be billed. - """ - if api_key is None: - return self.client - - reason = None - if not isinstance(self.client, AsyncAnthropic): - reason = 'this client uses its own cloud credentials, not an Anthropic API key' - # copy() cannot unset these, so the override would leave the base credential authenticating the request. - elif self.client.auth_token is not None: - reason = 'the plugin client authenticates with an auth token' - elif (header := pinned_credential_header(self.client)) is not None: - reason = f'the plugin client sets its own {header} header' - if reason is not None: - raise GenkitError( - status='FAILED_PRECONDITION', - message=f'A per-request API key from context.secrets cannot be used: {reason}.', - ) - - # copy() keeps every other client setting and shares the pooled HTTP transport. - return self.client.copy(api_key=api_key) - def _uses_beta_api(self, config: AnthropicConfig) -> bool: """Whether this request should use the Anthropic beta API surface. @@ -533,9 +508,8 @@ def _build_params( params['max_tokens'] = max_tokens if use_beta: - # Resold surfaces (Vertex, Bedrock) do not offer every default beta, so only the direct API gets them. - default_betas = list(BETA_APIS) if isinstance(self.client, AsyncAnthropic) else [] - beta_headers = betas if betas is not None else default_betas + # An explicit betas list replaces the defaults, including the one a field brings. + beta_headers = betas if betas is not None else _request_betas(self._default_betas, config) # The Python SDK serializes [] as an empty anthropic-beta header, # which the API rejects. Omit the kwarg to request no beta headers. if beta_headers: diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py b/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py index c99ac064..4b0ac427 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py @@ -16,13 +16,8 @@ """Anthropic plugin for Genkit.""" -import inspect -import os from collections.abc import Mapping from typing import Any, Literal -from urllib.parse import urlsplit - -from anthropic import AsyncAnthropic from genkit import GenkitError, ModelResponse, get_logger from genkit.model import Model, ModelContext, ModelRef, ModelRequest @@ -30,68 +25,49 @@ Action, ActionKind, Plugin, - loop_local_client, ) +from genkit_anthropic._anthropic_api import AnthropicApiBackend +from genkit_anthropic._backend import Backend from genkit_anthropic._config import AnthropicConfig +from genkit_anthropic._google_cloud import GoogleCloud, GoogleCloudBackend from genkit_anthropic._model_info import SUPPORTED_ANTHROPIC_MODELS, KnownClaude, get_model_info -from genkit_anthropic._models import AnthropicModel, pinned_credential_header +from genkit_anthropic._models import AnthropicModel, ClaudeClient from genkit_anthropic._secrets import context_api_key, reject_config_api_key logger = get_logger(__name__) ANTHROPIC_PLUGIN_NAME = 'anthropic' -_CLIENT_OPTION_KEYS = frozenset(inspect.signature(AsyncAnthropic.__init__).parameters) - {'self'} +def _backend_for( + config: GoogleCloud | None, + *, + api_key: str | None, + base_url: str | None, + client_options: Mapping[str, Any] | None, +) -> Backend[ClaudeClient]: + """Turn the public ``backend=`` value into the backend that serves the models. + + ``GoogleCloud`` is the public choice; ``GoogleCloudBackend`` implements it. + This is the only place a backend is picked; past it, the plugin treats + every backend the same. -def _client_kwargs( - *, api_key: str | None, base_url: str | None, client_options: Mapping[str, Any] | None -) -> dict[str, Any]: - """Merge the typed settings into ``client_options`` for ``AsyncAnthropic``. + Every backend takes the same arguments and rejects the ones it can't use. Raises: - TypeError: A ``client_options`` key ``AsyncAnthropic`` doesn't take, or - ``api_key``/``base_url`` given both as an argument and in ``client_options``. + TypeError: ``backend`` isn't ``None`` or a ``GoogleCloud``. """ - options = dict(client_options or {}) - for key in options: - if key not in _CLIENT_OPTION_KEYS: - raise TypeError( - f'Anthropic got an unexpected client_options key {key!r}; ' - f'AsyncAnthropic accepts {", ".join(sorted(k for k in _CLIENT_OPTION_KEYS if not k.startswith("_")))}' - ) - for name, value in (('api_key', api_key), ('base_url', base_url)): - if value is None: - continue - if name in options: - raise TypeError(f'Anthropic got {name} both as an argument and in client_options; pass it once') - options[name] = value - return options - - -def _reject_v1_suffix(base_url: str | None, *, source: str) -> None: - """The SDK appends ``/v1/messages``, so a base URL ending in ``/v1`` would send ``/v1/v1/messages``.""" - if base_url and urlsplit(base_url).path.rstrip('/').endswith('/v1'): - raise ValueError( - f'{source} {base_url!r} ends in /v1, but the Anthropic SDK appends /v1/messages itself; ' - 'pass the origin, e.g. https://claude-proxy.example.com' + if config is None: + return AnthropicApiBackend(api_key=api_key, base_url=base_url, client_options=client_options) + if not isinstance(config, GoogleCloud): + got = type(config) + hint = ( + f'{got.__module__}.{got.__name__}; import GoogleCloud from genkit_anthropic' + if got.__name__ == 'GoogleCloud' + else got.__name__ ) - - -def _has_credential(client: AsyncAnthropic) -> bool: - if client.api_key is not None or client.auth_token is not None or client.credentials is not None: - return True - return pinned_credential_header(client) is not None - - -def _missing_key_error() -> GenkitError: - return GenkitError( - status='FAILED_PRECONDITION', - message=( - 'Anthropic needs an API key: set ANTHROPIC_API_KEY or pass Anthropic(api_key=...), ' - "or send a per-request key as context={'secrets': {'api_key': ...}}." - ), - ) + raise TypeError(f'Anthropic backend must be GoogleCloud(...) or None, got {hint}') + return GoogleCloudBackend(config, api_key=api_key, base_url=base_url, client_options=client_options) # Only this plugin's namespace. A vertexai/ paste is a different name — @@ -134,7 +110,7 @@ class Anthropic(Plugin): @classmethod def claude(cls, name: KnownClaude | str, *, config: AnthropicConfig | None = None) -> ModelRef[AnthropicConfig]: - """Typed ref for a Claude model, e.g. ``Anthropic.claude('claude-sonnet-4-6')``. + """Typed ref for a Claude model, e.g. ``Anthropic.claude('claude-sonnet-5-5')``. Unknown ids are allowed so new Claude releases work before this plugin learns their names; every Anthropic generate model takes @@ -156,46 +132,60 @@ def __init__( base_url: str | None = None, api_version: Literal['stable', 'beta'] | None = None, client_options: Mapping[str, Any] | None = None, + backend: GoogleCloud | None = None, ) -> None: """Initializes Anthropic plugin with given configuration. Any Claude model id resolves on demand, so there is no model list to pass. + Example: + ```python + # 1. Claude on the Anthropic API (ANTHROPIC_API_KEY) + Anthropic() + + # 2. Claude on Google Cloud, billed to your project (application default credentials) + Anthropic(backend=GoogleCloud(project='bistro-prod')) + + # 3. Refs, config and .prompt files don't change between the two + await ai.generate(model=Anthropic.claude('claude-sonnet-5-5'), prompt='Suggest a dish.') + ``` + Args: - api_key: Anthropic API key. Defaults to ``ANTHROPIC_API_KEY``. + api_key: Anthropic API key. Defaults to ``ANTHROPIC_API_KEY``. Not + used with ``backend=GoogleCloud(...)``. base_url: Anthropic API origin with no ``/v1`` suffix, e.g. ``https://claude-proxy.example.com``; the SDK appends ``/v1/messages``. Defaults to ``ANTHROPIC_BASE_URL``, then the - public API. A value ending in ``/v1`` raises. + public API. A value ending in ``/v1`` raises. With + ``backend=GoogleCloud(...)`` it overrides the Google Cloud endpoint. api_version: Default API surface unless overridden by per-request config. An explicit config ``apiVersion`` always takes precedence. Defaults to stable. - client_options: Other ``AsyncAnthropic`` settings, such as - ``auth_token``, ``timeout``, ``max_retries``, ``default_headers``, - or ``http_client``. + client_options: Other SDK client settings, such as ``timeout``, + ``max_retries``, ``default_headers``, or ``http_client`` + (``AsyncAnthropic``, or ``AsyncAnthropicVertex`` with + ``backend=GoogleCloud(...)``). + backend: Where the models are served. ``None`` (the default) is the + Anthropic API; ``GoogleCloud(project=..., location=...)`` + serves them from Google Cloud with application default + credentials. Needs the ``google-cloud`` extra. Raises: ValueError: If ``api_version`` is not ``'stable'``, ``'beta'``, or - ``None``, or the base URL ends in ``/v1``. - TypeError: If ``client_options`` has a key ``AsyncAnthropic`` doesn't - take, or repeats ``api_key`` or ``base_url``. + ``None``, the base URL ends in ``/v1``, or ``api_key`` is + passed with ``backend=GoogleCloud(...)``. + TypeError: If ``backend`` isn't a ``GoogleCloud``, or + ``client_options`` has a key the SDK client doesn't take or + repeats ``api_key`` or ``base_url``. + ImportError: ``backend=GoogleCloud(...)`` without the ``google-cloud`` extra. """ if api_version not in (None, 'stable', 'beta'): raise ValueError("api_version must be 'stable', 'beta', or None") - options = _client_kwargs(api_key=api_key, base_url=base_url, client_options=client_options) - if 'base_url' in options: - _reject_v1_suffix(options['base_url'], source='base_url') - else: - _reject_v1_suffix(os.environ.get('ANTHROPIC_BASE_URL'), source='ANTHROPIC_BASE_URL') + self._backend = _backend_for(backend, api_key=api_key, base_url=base_url, client_options=client_options) self._default_api_version: Literal['stable', 'beta'] | None = api_version - self._options = options self._list_actions_cache: list[Action] | None = None - @loop_local_client - def _runtime_client(self) -> AsyncAnthropic: - return AsyncAnthropic(**self._options) - async def init(self) -> list[Action]: """Initialize plugin. @@ -233,14 +223,13 @@ def _create_model_action(self, name: str) -> Action: async def _generate(request: ModelRequest[AnthropicConfig], ctx: ModelContext) -> ModelResponse: # A key in config is the more specific error, so it wins over a missing plugin key. reject_config_api_key(request.config) - client = self._runtime_client() - # A plugin built without a credential serves only callers who bring a key. - if not _has_credential(client) and context_api_key(ctx.context) is None: - raise _missing_key_error() + client = await self._backend.request_client(context_api_key(ctx.context)) model = AnthropicModel( model_name=name, client=client, default_api_version=self._default_api_version, + default_betas=self._backend.default_betas, + api_model_id=self._backend.api_model_id(name), ) return await model.generate(request, ctx) @@ -258,29 +247,14 @@ async def _generate(request: ModelRequest[AnthropicConfig], ctx: ModelContext) - }, ) - async def _fetch_dynamic_model_ids(self) -> list[str]: - """Fetch all available model ids from the Anthropic API. - - Uses the beta models endpoint (matching JS, so both stable and beta - models are discovered) and fully paginates via ``async for`` (matching - Go's completeness, rather than JS's first-page-only read). - - Returns: - Model ids in API order. - """ - model_ids: list[str] = [] - async for model in self._runtime_client().beta.models.list(): - if model.id: - model_ids.append(model.id) - return model_ids - async def list_actions(self) -> list[Action]: """List available Anthropic models. - Queries the Anthropic API for currently available models and returns - the union of API-discovered models and any statically known models - not already covered by the API response (API ids first, in API - order, then remaining static ids, deduplicated by bare id). The + Asks the backend for the models it serves and returns the union of + those and any statically known models not already covered (backend + ids first, in backend order, then remaining static ids, deduplicated + by bare id). A backend without a Models API, such as Google Cloud, + lists only the static models. The successful result is cached for the lifetime of the plugin instance. If the API call fails, logs a warning and returns the static model list only, without caching the failure, so the next call retries the @@ -293,9 +267,9 @@ async def list_actions(self) -> list[Action]: return self._list_actions_cache try: - model_ids = await self._fetch_dynamic_model_ids() + model_ids = await self._backend.list_model_ids() except Exception as e: - logger.warning('Failed to list Anthropic models from API, using static model list', error=str(e)) + logger.warning('Failed to list Anthropic models, using static model list', error=str(e)) return [self._create_model_action(model_id) for model_id in SUPPORTED_ANTHROPIC_MODELS] seen: set[str] = set() diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_secrets.py b/packages/genkit-anthropic/src/genkit_anthropic/_secrets.py index e2fe37b0..b2c08af3 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_secrets.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_secrets.py @@ -37,16 +37,6 @@ def misplaced_key_error() -> GenkitError: ) -def missing_key_error() -> GenkitError: - return GenkitError( - status='FAILED_PRECONDITION', - message=( - 'Anthropic needs an API key: set ANTHROPIC_API_KEY or pass Anthropic(api_key=...), ' - "or send a per-request key as context={'secrets': {'api_key': ...}}." - ), - ) - - def _has_key(bag: Mapping[str, object]) -> bool: return any(bag.get(slot) is not None for slot in _KEY_SLOTS) diff --git a/packages/genkit-anthropic/tests/anthropic_backend_test.py b/packages/genkit-anthropic/tests/anthropic_backend_test.py new file mode 100644 index 00000000..46ba139d --- /dev/null +++ b/packages/genkit-anthropic/tests/anthropic_backend_test.py @@ -0,0 +1,60 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Tests for the backend seam: what each backend owns, checked without a plugin around it.""" + +import pytest +from anthropic import AsyncAnthropic, AsyncAnthropicVertex +from genkit_anthropic._anthropic_api import BETA_APIS, AnthropicApiBackend +from genkit_anthropic._backend import client_kwargs + + +@pytest.mark.asyncio +async def test_anthropic_api_secrets_key_copy_keeps_client_settings_and_transport() -> None: + """A per-request key yields a request-scoped copy that keeps client settings and transport.""" + backend = AnthropicApiBackend( + api_key='base-key', base_url=None, client_options={'default_headers': {'X-Custom': 'yes'}} + ) + base_client = backend.client() + + client = await backend.request_client('request-key') + + assert client is not base_client + assert client.api_key == 'request-key' + assert client.default_headers.get('X-Custom') == 'yes' + assert client._client is base_client._client + assert await backend.request_client(None) is base_client + + +def test_anthropic_api_offers_the_default_betas() -> None: + """Only the Anthropic API backend sends the default beta headers.""" + assert AnthropicApiBackend.default_betas == BETA_APIS + + +def test_client_kwargs_names_the_client_it_validated_against() -> None: + """The allowlist and the error both come from the client class, so each backend reports its own client.""" + with pytest.raises(TypeError, match='AsyncAnthropic accepts'): + client_kwargs(AsyncAnthropic, {'region': 'us-east5'}) + with pytest.raises(TypeError, match='AsyncAnthropicVertex accepts'): + client_kwargs(AsyncAnthropicVertex, {'region': 'us-east5'}, reserved=frozenset({'region'})) + + +def test_client_kwargs_rejects_a_setting_passed_twice() -> None: + """A typed setting and the same client_options key is ambiguous, so it raises naming the setting.""" + with pytest.raises(TypeError, match='base_url both as an argument and in client_options'): + client_kwargs(AsyncAnthropic, {'base_url': 'https://a'}, base_url='https://b') + + assert client_kwargs(AsyncAnthropic, {'timeout': 5}, base_url=None) == {'timeout': 5} diff --git a/packages/genkit-anthropic/tests/anthropic_generate_test.py b/packages/genkit-anthropic/tests/anthropic_generate_test.py index ef1c414b..512a1f7b 100644 --- a/packages/genkit-anthropic/tests/anthropic_generate_test.py +++ b/packages/genkit-anthropic/tests/anthropic_generate_test.py @@ -27,6 +27,7 @@ import httpx import pytest from genkit_anthropic import Anthropic, AnthropicConfig +from genkit_anthropic._anthropic_api import BETA_APIS from genkit import FinishReason, Genkit, GenkitError, Message, Part, Role from genkit.middleware import Middleware @@ -936,3 +937,33 @@ async def test_generate_claude_sends_system_cache_control() -> None: ) assert api.body()['system'] == [{'type': 'text', 'text': 'Long reference.', 'cache_control': cache}] + + +# --- default betas ------------------------------------------------------------- + + +@pytest.mark.parametrize( + 'config', + [{'apiVersion': 'beta'}, {'taskBudget': 20000}], + ids=['beta-surface', 'task-budget-already-in-defaults'], +) +@pytest.mark.asyncio +async def test_generate_claude_beta_call_sends_the_default_betas_once(config: dict[str, Any]) -> None: + """A beta call on the Anthropic API sends the default beta headers, each once, even when task_budget needs one.""" + api = FakeClaudeApi() + ai = _genkit(api) + + await ai.generate(model=MODEL, prompt='hi', config=config) + + assert api.requests[-1].headers['anthropic-beta'].split(',') == list(BETA_APIS) + + +@pytest.mark.asyncio +async def test_generate_claude_sends_the_pinned_api_id_for_a_cataloged_model() -> None: + """On the Anthropic API, a cataloged model with a dated snapshot is sent as that snapshot.""" + api = FakeClaudeApi() + ai = _genkit(api) + + await ai.generate(model='anthropic/claude-haiku-4-5', prompt='hi') + + assert api.body()['model'] == 'claude-haiku-4-5-20251001' diff --git a/packages/genkit-anthropic/tests/anthropic_google_cloud_test.py b/packages/genkit-anthropic/tests/anthropic_google_cloud_test.py new file mode 100644 index 00000000..3a2d31aa --- /dev/null +++ b/packages/genkit-anthropic/tests/anthropic_google_cloud_test.py @@ -0,0 +1,404 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Tests for Anthropic(backend=GoogleCloud(...)): Claude served from Google Cloud.""" + +import asyncio +import builtins +from dataclasses import FrozenInstanceError +from typing import Any, cast +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from anthropic import AsyncAnthropicVertex +from genkit_anthropic import Anthropic, GoogleCloud +from genkit_anthropic._google_cloud import load_adc +from genkit_anthropic._model_info import SUPPORTED_ANTHROPIC_MODELS +from google.auth.exceptions import DefaultCredentialsError, RefreshError, TransportError + +from genkit import FinishReason, Genkit, GenkitError + +_GCP_ENV = ('GCLOUD_PROJECT', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION', 'ANTHROPIC_API_KEY') + + +@pytest.fixture(autouse=True) +def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + for name in _GCP_ENV: + monkeypatch.delenv(name, raising=False) + + +# Stands in for the machine's ADC so no test reads real credentials or calls Google. +FAKE_CREDENTIALS = MagicMock(name='adc-credentials') + + +@pytest.fixture(autouse=True) +def fake_adc() -> Any: # noqa: ANN401 - the patched loader + with patch('genkit_anthropic._google_cloud.load_adc', return_value=(FAKE_CREDENTIALS, None)) as adc: + yield adc + + +def _client(plugin: Anthropic) -> Any: # noqa: ANN401 - the SDK client under test + async def _get() -> Any: # noqa: ANN401 + return plugin._backend.client() + + return asyncio.run(_get()) + + +def test_google_cloud_builds_vertex_client_with_project_and_location() -> None: + """The plugin's client is AsyncAnthropicVertex for the configured project and location.""" + client = _client(Anthropic(backend=GoogleCloud(project='bistro-prod', location='us-east5'))) + + assert isinstance(client, AsyncAnthropicVertex) + assert client.project_id == 'bistro-prod' + assert client.region == 'us-east5' + + +def test_google_cloud_reads_project_and_location_from_env(monkeypatch: pytest.MonkeyPatch) -> None: + """GCLOUD_PROJECT wins over GOOGLE_CLOUD_PROJECT; location falls back to GOOGLE_CLOUD_LOCATION.""" + monkeypatch.setenv('GCLOUD_PROJECT', 'from-gcloud') + monkeypatch.setenv('GOOGLE_CLOUD_PROJECT', 'from-google-cloud') + monkeypatch.setenv('GOOGLE_CLOUD_LOCATION', 'europe-west1') + + client = _client(Anthropic(backend=GoogleCloud())) + + assert client.project_id == 'from-gcloud' + assert client.region == 'europe-west1' + + +def test_google_cloud_defaults_to_global_location() -> None: + """With no location passed or set, Claude is served from the global endpoint.""" + client = _client(Anthropic(backend=GoogleCloud(project='bistro-prod'))) + + assert client.region == 'global' + + +def test_google_cloud_rejects_api_key() -> None: + """An API key can't authenticate a Google Cloud call, so passing one fails at setup.""" + with pytest.raises(ValueError, match='drop api_key'): + Anthropic(backend=GoogleCloud(), api_key='sk-ant-test') + + +def test_backend_must_be_google_cloud() -> None: + """A backend that isn't GoogleCloud fails at setup instead of silently using the Anthropic API.""" + with pytest.raises(TypeError, match='GoogleCloud'): + Anthropic(backend=cast(Any, 'google_cloud')) + + +def test_backend_rejects_google_cloud_from_another_package() -> None: + """Passing another plugin's GoogleCloud names the module and tells the caller where to import it.""" + foreign_google_cloud = type('GoogleCloud', (), {'__module__': 'genkit_openai._google_cloud'})() + + with pytest.raises( + TypeError, match=r'genkit_openai\._google_cloud\.GoogleCloud; import GoogleCloud from genkit_anthropic' + ): + Anthropic(backend=cast(Any, foreign_google_cloud)) + + +def test_google_cloud_is_frozen() -> None: + """GoogleCloud is a frozen value, so one instance can be shared safely.""" + backend = GoogleCloud(project='bistro-prod') + with pytest.raises(FrozenInstanceError): + backend.project = 'other' # type: ignore[misc] + + +def test_google_cloud_validates_client_options_against_vertex_client() -> None: + """Vertex-only options pass; Anthropic-API-only options name the Vertex client in the error.""" + plugin = Anthropic(backend=GoogleCloud(project='p'), client_options={'access_token': 'tok', 'max_retries': 1}) + assert _client(plugin).max_retries == 1 + + with pytest.raises(TypeError, match='AsyncAnthropicVertex accepts'): + Anthropic(backend=GoogleCloud(project='p'), client_options={'auth_token': 'tok'}) + + +@pytest.mark.parametrize('key', ['region', 'project_id']) +def test_google_cloud_reserves_region_and_project_id(key: str) -> None: + """GoogleCloud(project=..., location=...) sets these, so client_options can't contradict them.""" + with pytest.raises(TypeError, match=f"unexpected client_options key '{key}'"): + Anthropic(backend=GoogleCloud(project='p'), client_options={key: 'other'}) + + +def test_google_cloud_accepts_v1_base_url() -> None: + """Google Cloud endpoints end in /v1, so the direct-API /v1 guard doesn't apply.""" + client = _client( + Anthropic(backend=GoogleCloud(project='p'), base_url='https://us-east5-aiplatform.googleapis.com/v1') + ) + + assert str(client.base_url).rstrip('/') == 'https://us-east5-aiplatform.googleapis.com/v1' + + +@pytest.mark.parametrize( + ('blocked', 'exc'), + [ + ('google.auth', ModuleNotFoundError("No module named 'google.auth'", name='google.auth')), + ( + 'google.auth.transport.requests', + ImportError('The requests library is not installed from please install the requests package'), + ), + ], + ids=['no-google-auth', 'no-requests-transport'], +) +def test_google_cloud_without_google_auth_names_the_extra(blocked: str, exc: ImportError) -> None: + """A missing google-auth or requests transport fails on the constructor line with the install command.""" + real_import = builtins.__import__ + + def _blocked_import(name: str, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + if name == blocked or name.startswith(f'{blocked}.'): + raise exc + return real_import(name, *args, **kwargs) + + with ( + patch('builtins.__import__', _blocked_import), + pytest.raises(ImportError, match=r'genkit-anthropic\[google-cloud\]'), + ): + Anthropic(backend=GoogleCloud(project='p')) + + +@pytest.mark.asyncio +async def test_google_cloud_list_actions_uses_static_catalog_without_calling_api() -> None: + """Google Cloud has no Models API, so listing returns the catalog and makes no call.""" + plugin = Anthropic(backend=GoogleCloud(project='p')) + client = MagicMock() + plugin._backend.client = client + + actions = await plugin.list_actions() + again = await plugin.list_actions() + + client.assert_not_called() + assert [a.name for a in actions] == [f'anthropic/{m}' for m in SUPPORTED_ANTHROPIC_MODELS] + assert again is actions + + +def _vertex_response() -> MagicMock: + response = MagicMock() + response.content = [MagicMock(type='text', text='Grilled salmon')] + response.usage = MagicMock(input_tokens=1, output_tokens=2) + response.stop_reason = 'end_turn' + return response + + +@pytest.mark.asyncio +async def test_google_cloud_generate_needs_no_api_key() -> None: + """A Google Cloud plugin generates without ANTHROPIC_API_KEY; the request goes to the Vertex client.""" + plugin = Anthropic(backend=GoogleCloud(project='bistro-prod')) + ai = Genkit(plugins=[plugin]) + with patch( + 'anthropic.resources.messages.AsyncMessages.create', AsyncMock(return_value=_vertex_response()) + ) as create: + response = await ai.generate(model=Anthropic.claude('claude-sonnet-4-6'), prompt='Suggest a dish.') + + assert response.text == 'Grilled salmon' + create.assert_awaited_once() + assert create.call_args.kwargs['model'] == 'claude-sonnet-4-6' + + +@pytest.mark.asyncio +async def test_google_cloud_generate_takes_project_and_credentials_from_adc_once(fake_adc: MagicMock) -> None: + """With no project set, ADC supplies it; the credentials load once and the client reuses them.""" + fake_adc.return_value = (FAKE_CREDENTIALS, 'adc-project') + plugin = Anthropic(backend=GoogleCloud()) + ai = Genkit(plugins=[plugin]) + with patch('anthropic.resources.messages.AsyncMessages.create', AsyncMock(return_value=_vertex_response())): + await ai.generate(model=Anthropic.claude('claude-sonnet-4-6'), prompt='One.') + await ai.generate(model=Anthropic.claude('claude-sonnet-4-6'), prompt='Two.') + + fake_adc.assert_called_once() + client = plugin._backend.client() + assert isinstance(client, AsyncAnthropicVertex) + assert client.project_id == 'adc-project' + assert client.credentials is FAKE_CREDENTIALS + + +@pytest.mark.asyncio +async def test_google_cloud_explicit_project_beats_adc_project(fake_adc: MagicMock) -> None: + """GoogleCloud(project=...) wins over the project the credentials carry.""" + fake_adc.return_value = (FAKE_CREDENTIALS, 'adc-project') + plugin = Anthropic(backend=GoogleCloud(project='bistro-prod')) + + client = await plugin._backend.request_client(None) + + assert isinstance(client, AsyncAnthropicVertex) + assert client.project_id == 'bistro-prod' + + +@pytest.mark.parametrize('own', [{'access_token': 'tok'}, {'credentials': MagicMock(name='service-account')}]) +@pytest.mark.asyncio +async def test_google_cloud_own_credential_skips_adc(fake_adc: MagicMock, own: dict[str, Any]) -> None: + """An access_token or credentials in client_options is used as is; ADC isn't loaded.""" + plugin = Anthropic(backend=GoogleCloud(project='bistro-prod'), client_options=own) + + await plugin._backend.request_client(None) + + fake_adc.assert_not_called() + + +@pytest.mark.asyncio +async def test_google_cloud_without_credentials_names_the_login_command(fake_adc: MagicMock) -> None: + """No ADC fails FAILED_PRECONDITION with the gcloud command, not an opaque INTERNAL from inside the SDK.""" + fake_adc.side_effect = GenkitError(status='FAILED_PRECONDITION', message='no creds: gcloud auth ...') + ai = Genkit(plugins=[Anthropic(backend=GoogleCloud(project='bistro-prod'))]) + with patch('anthropic.resources.messages.AsyncMessages.create', AsyncMock()) as create: + response = await ai.generate(model=Anthropic.claude('claude-sonnet-4-6'), prompt='Suggest a dish.') + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + create.assert_not_called() + + +@pytest.mark.asyncio +async def test_google_cloud_retries_credentials_after_a_failed_load(fake_adc: MagicMock) -> None: + """A failed load isn't cached, so the next call works once the user has logged in.""" + fake_adc.side_effect = [ + GenkitError(status='FAILED_PRECONDITION', message='no creds'), + (FAKE_CREDENTIALS, None), + ] + plugin = Anthropic(backend=GoogleCloud(project='bistro-prod')) + + with pytest.raises(GenkitError): + await plugin._backend.request_client(None) + client = await plugin._backend.request_client(None) + + assert client.credentials is FAKE_CREDENTIALS + assert fake_adc.call_count == 2 + + +def test_load_adc_refreshes_and_returns_project() -> None: + """load_adc asks for the cloud-platform scope and refreshes now, so a stale login fails on the first call.""" + credentials = MagicMock(name='user-credentials') + with patch('google.auth.default', return_value=(credentials, 'gcloud-project')) as default: + assert load_adc() == (credentials, 'gcloud-project') + + assert default.call_args.kwargs['scopes'] == ['https://www.googleapis.com/auth/cloud-platform'] + credentials.refresh.assert_called_once() + + +@pytest.mark.parametrize( + ('failure', 'match'), + [ + (DefaultCredentialsError('Your default credentials were not found.'), 'found no Google Cloud credentials'), + (RefreshError('Reauthentication is needed.'), 'could not refresh Google Cloud credentials'), + ], + ids=['no-adc', 'stale-login'], +) +def test_load_adc_failures_name_the_fix(failure: Exception, match: str) -> None: + """A missing or stale login is a setup problem, reported with the command that fixes it.""" + credentials = MagicMock(name='user-credentials') + if isinstance(failure, RefreshError): + credentials.refresh.side_effect = failure + default = patch('google.auth.default', return_value=(credentials, None)) + else: + default = patch('google.auth.default', side_effect=failure) + + with default, pytest.raises(GenkitError) as exc_info: + load_adc() + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert match in str(exc_info.value) + assert 'gcloud auth application-default login' in str(exc_info.value) + + +def _refresh_caused_by_transport() -> RefreshError: + err = RefreshError('Metadata server unreachable.') + err.__cause__ = TransportError('connection reset') + return err + + +@pytest.mark.parametrize( + 'failure', + [ + TransportError('connection reset'), + RefreshError('Temporary backend error.', retryable=True), + _refresh_caused_by_transport(), + ], + ids=['transport-error', 'retryable-refresh', 'refresh-caused-by-transport'], +) +def test_load_adc_transient_failures_are_unavailable(failure: Exception) -> None: + """Transient network or metadata-server blips map to UNAVAILABLE so Retry middleware retries them.""" + credentials = MagicMock(name='user-credentials') + credentials.refresh.side_effect = failure + + with patch('google.auth.default', return_value=(credentials, None)), pytest.raises(GenkitError) as exc_info: + load_adc() + + assert exc_info.value.status == 'UNAVAILABLE' + + +@pytest.mark.asyncio +async def test_google_cloud_generate_without_any_project_fails_precondition() -> None: + """No project anywhere is a setup problem, reported as FAILED_PRECONDITION naming the fix.""" + plugin = Anthropic(backend=GoogleCloud()) + ai = Genkit(plugins=[plugin]) + response = await ai.generate(model=Anthropic.claude('claude-sonnet-4-6'), prompt='Suggest a dish.') + + assert response.finish_reason == FinishReason.FAILED + assert 'GOOGLE_CLOUD_PROJECT' in str(response.finish_message) + + +@pytest.mark.asyncio +async def test_google_cloud_rejects_secrets_key_before_looking_up_project() -> None: + """A context.secrets key can't bill Google Cloud, so the call fails without an ADC lookup or a request.""" + plugin = Anthropic(backend=GoogleCloud()) + ai = Genkit(plugins=[plugin]) + with ( + patch('genkit_anthropic._google_cloud.load_adc') as adc, + patch('anthropic.resources.messages.AsyncMessages.create', AsyncMock()) as create, + ): + response = await ai.generate( + model=Anthropic.claude('claude-sonnet-4-6'), + prompt='Suggest a dish.', + context={'secrets': {'api_key': 'tenant-key'}}, + ) + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'Google Cloud credentials' in response.error.message + assert 'tenant-key' not in response.error.message + adc.assert_not_called() + create.assert_not_called() + + +@pytest.mark.parametrize( + ('config', 'betas'), + [ + ({'apiVersion': 'beta'}, None), + ({'taskBudget': 20000}, ['task-budgets-2026-03-13']), + ], + ids=['beta-surface-no-defaults', 'task-budget-brings-its-header'], +) +@pytest.mark.asyncio +async def test_google_cloud_sends_only_the_betas_a_field_needs(config: dict[str, Any], betas: list[str] | None) -> None: + """The Anthropic API's default betas stay off Google Cloud; task_budget still brings its own header.""" + plugin = Anthropic(backend=GoogleCloud(project='bistro-prod')) + ai = Genkit(plugins=[plugin]) + # The Vertex client has its own beta resource, so stub this loop's client rather than an SDK class. + client = plugin._backend.client() + with patch.object(client.beta.messages, 'create', AsyncMock(return_value=_vertex_response())) as create: + await ai.generate(model=Anthropic.claude('claude-sonnet-4-6'), prompt='Suggest a dish.', config=config) + + create.assert_awaited_once() + assert create.call_args.kwargs.get('betas') == betas + + +@pytest.mark.parametrize('model', ['claude-haiku-4-5', 'claude-sonnet-5-5']) +@pytest.mark.asyncio +async def test_google_cloud_sends_the_dateless_model_name(model: str) -> None: + """Google Cloud names Claude without a date, so a cataloged model goes as named, not as its pinned API id.""" + ai = Genkit(plugins=[Anthropic(backend=GoogleCloud(project='bistro-prod'))]) + with patch( + 'anthropic.resources.messages.AsyncMessages.create', AsyncMock(return_value=_vertex_response()) + ) as create: + await ai.generate(model=Anthropic.claude(model), prompt='Suggest a dish.') + + assert create.call_args.kwargs['model'] == model diff --git a/packages/genkit-anthropic/tests/anthropic_models_test.py b/packages/genkit-anthropic/tests/anthropic_models_test.py index 4648762c..4d14cf0a 100644 --- a/packages/genkit-anthropic/tests/anthropic_models_test.py +++ b/packages/genkit-anthropic/tests/anthropic_models_test.py @@ -22,9 +22,9 @@ import pytest from anthropic import AsyncAnthropic, AsyncAnthropicVertex from genkit_anthropic import Anthropic, _models as anthropic_models +from genkit_anthropic._anthropic_api import BETA_APIS from genkit_anthropic._config import AnthropicConfig from genkit_anthropic._models import ( - BETA_APIS, AnthropicModel, _to_anthropic_output_config, _to_anthropic_thinking, @@ -894,10 +894,6 @@ def _mock_client_for_generate() -> MagicMock: mock_response.stop_reason = 'end_turn' mock_client.messages.create = AsyncMock(return_value=mock_response) mock_client.beta.messages.create = AsyncMock(return_value=mock_response) - # The real client only gains these on instantiation; _client_for_key reads them. - mock_client.auth_token = None - mock_client._custom_headers = {} - mock_client.copy = MagicMock(return_value=mock_client) return mock_client @@ -1002,6 +998,7 @@ async def test_default_api_version_beta_routes_streaming() -> None: model_name='claude-sonnet-4-6', client=mock_client, default_api_version='beta', + default_betas=BETA_APIS, ) ctx = MagicMock() ctx.is_streaming = True @@ -1015,9 +1012,9 @@ async def test_default_api_version_beta_routes_streaming() -> None: @pytest.mark.asyncio async def test_beta_surface_sends_default_betas() -> None: - """Beta calls send the same default beta headers as the JS plugin.""" + """Beta calls send the backend's default beta headers; the Anthropic API's match the JS plugin.""" mock_client = _mock_client_for_generate() - model = AnthropicModel(model_name='claude-sonnet-4-6', client=mock_client) + model = AnthropicModel(model_name='claude-sonnet-4-6', client=mock_client, default_betas=BETA_APIS) await model.generate(_text_request({'apiVersion': 'beta'})) @@ -1045,7 +1042,7 @@ async def test_beta_surface_preserves_empty_betas_opt_out() -> None: @pytest.mark.asyncio async def test_resold_surface_omits_default_betas() -> None: - """Resold surfaces do not offer every default beta, so none are assumed.""" + """A model built without default betas (Google Cloud's backend) sends none.""" mock_client = _mock_vertex_client_for_generate() model = AnthropicModel(model_name='claude-sonnet-4-6', client=mock_client) @@ -1056,8 +1053,8 @@ async def test_resold_surface_omits_default_betas() -> None: @pytest.mark.asyncio -async def test_resold_surface_beta_only_field_routes_beta_without_defaults() -> None: - """A beta-only field still selects the beta surface without assuming default headers.""" +async def test_resold_surface_task_budget_sends_its_own_beta() -> None: + """task_budget routes to beta and brings its header; Vertex rejects the field without it.""" mock_client = _mock_vertex_client_for_generate() model = AnthropicModel(model_name='claude-sonnet-4-6', client=mock_client) @@ -1065,6 +1062,17 @@ async def test_resold_surface_beta_only_field_routes_beta_without_defaults() -> mock_client.beta.messages.create.assert_awaited_once() mock_client.messages.create.assert_not_called() + assert mock_client.beta.messages.create.call_args.kwargs['betas'] == ['task-budgets-2026-03-13'] + + +@pytest.mark.asyncio +async def test_resold_surface_explicit_betas_replace_task_budget_beta() -> None: + """An explicit betas list wins over the derived header, as it does over the direct-API defaults.""" + mock_client = _mock_vertex_client_for_generate() + model = AnthropicModel(model_name='claude-sonnet-4', client=mock_client) + + await model.generate(_text_request({'taskBudget': 20000, 'betas': []})) + assert 'betas' not in mock_client.beta.messages.create.call_args.kwargs @@ -1304,20 +1312,6 @@ async def test_beta_config_uses_beta_sdk_and_sends_betas() -> None: assert kwargs['betas'] == ['token-efficient-tools-2025'] -def test_secrets_key_copy_keeps_client_settings_and_transport() -> None: - """A per-request key yields a request-scoped copy that keeps client settings and transport.""" - base_client = AsyncAnthropic(api_key='base-key', default_headers={'X-Custom': 'yes'}) - model = AnthropicModel(model_name='claude-sonnet-4-6', client=base_client) - - client = model._client_for_key('request-key') - - assert client is not base_client - assert isinstance(client, AsyncAnthropic) - assert client.api_key == 'request-key' - assert client.default_headers.get('X-Custom') == 'yes' - assert client._client is base_client._client - - def test_build_params_consumes_client_level_keys_silently() -> None: """apiVersion is honored elsewhere and must not be logged as ignored.""" mock_client = MagicMock() @@ -1854,7 +1848,7 @@ async def test_generate_claude_drops_thinking_part_without_thought_signature( # The plugin checks the client for a credential before each call. mock_client.api_key = 'test-key' plugin = Anthropic(api_key='test-key') - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client ai = Genkit(plugins=[plugin]) history = [ Message(role=Role.USER, content=[Part.from_text('what is 17 * 23?')]), @@ -1903,7 +1897,7 @@ async def test_generate_claude_sends_back_empty_signed_thinking_before_tool_use( # The plugin checks the client for a credential before each call. mock_client.api_key = 'test-key' plugin = Anthropic(api_key='test-key') - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client ai = Genkit(plugins=[plugin]) history = [ Message(role=Role.USER, content=[Part.from_text('what is the weather in Paris?')]), diff --git a/packages/genkit-anthropic/tests/anthropic_plugin_test.py b/packages/genkit-anthropic/tests/anthropic_plugin_test.py index 118423c2..2feeec5c 100644 --- a/packages/genkit-anthropic/tests/anthropic_plugin_test.py +++ b/packages/genkit-anthropic/tests/anthropic_plugin_test.py @@ -50,12 +50,12 @@ def test_init_without_api_key_raises() -> None: plugin = Anthropic() async def _has_client() -> bool: - return plugin._runtime_client() is not None + return plugin._backend.client() is not None assert asyncio.run(_has_client()) -@patch('genkit_anthropic._plugin.AsyncAnthropic') +@patch('genkit_anthropic._anthropic_api.AsyncAnthropic') def test_api_version_is_stored_without_leaking_to_sdk(mock_client_ctor: MagicMock) -> None: """Plugin API version is a model default, not an AsyncAnthropic kwarg.""" mock_client = MagicMock() @@ -63,7 +63,7 @@ def test_api_version_is_stored_without_leaking_to_sdk(mock_client_ctor: MagicMoc plugin = Anthropic(api_key='test-key', api_version='beta') async def _get_client() -> object: - return plugin._runtime_client() + return plugin._backend.client() assert asyncio.run(_get_client()) is mock_client assert plugin._default_api_version == 'beta' @@ -76,7 +76,7 @@ def test_invalid_api_version_fails_fast() -> None: Anthropic(api_version=cast(Any, 'Beta')) -@patch('genkit_anthropic._plugin.AsyncAnthropic') +@patch('genkit_anthropic._anthropic_api.AsyncAnthropic') @pytest.mark.asyncio async def test_plugin_beta_default_routes_action_run_to_beta_surface(mock_client_ctor: MagicMock) -> None: """The plugin-wide beta default reaches models resolved as public actions.""" @@ -122,7 +122,7 @@ async def test_resolve_action_model() -> None: assert action.kind == ActionKind.MODEL -@patch('genkit_anthropic._plugin.AsyncAnthropic') +@patch('genkit_anthropic._anthropic_api.AsyncAnthropic') @pytest.mark.asyncio async def test_anthropic_runtime_clients_are_loop_local(mock_client_ctor: MagicMock) -> None: """Runtime Anthropic clients are cached per event loop.""" @@ -137,15 +137,15 @@ def _new_client(**kwargs: object) -> object: # noqa: ANN003 mock_client_ctor.side_effect = _new_client plugin = Anthropic(api_key='test-key') - first = plugin._runtime_client() - second = plugin._runtime_client() + first = plugin._backend.client() + second = plugin._backend.client() assert first is second q: queue.Queue[object] = queue.Queue() def _other_thread() -> None: async def _get_client() -> object: - return plugin._runtime_client() + return plugin._backend.client() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) @@ -275,7 +275,7 @@ async def test_list_actions_dynamic_union_dedup_and_fallback_info() -> None: SimpleNamespace(id='claude-unknown-xyz'), # unknown id -> generic fallback info ] mock_client.beta.models.list = MagicMock(return_value=_FakeModelPage(api_items)) - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client actions = await plugin.list_actions() names = [a.name for a in actions] @@ -315,7 +315,7 @@ async def test_list_actions_falls_back_to_static_on_error_uncached() -> None: plugin = Anthropic(api_key='test-key') mock_client = MagicMock() mock_client.beta.models.list = MagicMock(side_effect=RuntimeError('boom')) - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client actions = await plugin.list_actions() names = {a.name for a in actions} @@ -331,7 +331,7 @@ async def test_list_actions_caches_on_success() -> None: plugin = Anthropic(api_key='test-key') mock_client = MagicMock() mock_client.beta.models.list = MagicMock(return_value=_FakeModelPage([SimpleNamespace(id='claude-sonnet-4-6')])) - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client first = await plugin.list_actions() second = await plugin.list_actions() @@ -350,7 +350,7 @@ async def test_list_actions_skips_empty_model_ids() -> None: SimpleNamespace(id=None), # missing id -> dropped ] mock_client.beta.models.list = MagicMock(return_value=_FakeModelPage(api_items)) - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client actions = await plugin.list_actions() names = [a.name for a in actions] @@ -369,7 +369,7 @@ async def test_list_actions_empty_api_response_returns_and_caches_statics() -> N plugin = Anthropic(api_key='test-key') mock_client = MagicMock() mock_client.beta.models.list = MagicMock(return_value=_FakeModelPage([])) - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client actions = await plugin.list_actions() names = {a.name for a in actions} @@ -419,7 +419,7 @@ async def test_list_actions_advertises_anthropic_config() -> None: plugin = Anthropic(api_key='test-key') mock_client = MagicMock() mock_client.beta.models.list = MagicMock(side_effect=RuntimeError('offline')) - plugin._runtime_client = lambda: mock_client + plugin._backend.client = lambda: mock_client actions = await plugin.list_actions() diff --git a/packages/genkit-anthropic/tests/anthropic_sdk_contract_test.py b/packages/genkit-anthropic/tests/anthropic_sdk_contract_test.py index 3636ba86..3ba8b455 100644 --- a/packages/genkit-anthropic/tests/anthropic_sdk_contract_test.py +++ b/packages/genkit-anthropic/tests/anthropic_sdk_contract_test.py @@ -48,7 +48,8 @@ def test_sdk_transport_is_httpx() -> None: def test_declared_anthropic_range_excludes_1x() -> None: - """``genkit-anthropic`` caps ``anthropic`` below 1.0 until it supports 1.x.""" + """``genkit-anthropic`` caps ``anthropic`` below 1.0 until it supports 1.x, in the base deps and every extra.""" reqs = [Requirement(r) for r in requires('genkit-anthropic') or [] if re.match(r'anthropic\b', r)] - assert len(reqs) == 1, reqs - assert '1.0.0' not in reqs[0].specifier, reqs[0] + assert reqs + for req in reqs: + assert '1.0.0' not in req.specifier, req diff --git a/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py b/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py index 66a1756d..c344c1e7 100644 --- a/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py +++ b/packages/genkit-vertexai/src/genkit_vertexai/_model_garden/_anthropic.py @@ -18,9 +18,8 @@ """Anthropic models.""" from collections.abc import Awaitable, Callable -from typing import cast -from anthropic import AsyncAnthropic, AsyncAnthropicVertex +from anthropic import AsyncAnthropicVertex from genkit_anthropic import AnthropicConfig # Private import across packages, on purpose. genkit-anthropic and @@ -76,7 +75,9 @@ async def _generate(request: ModelRequest, ctx: ModelContext) -> ModelResponse: reject_secrets_api_key(ctx.context) model = AnthropicModel( model_name=self._model_name, - client=cast(AsyncAnthropic, self._runtime_client()), + client=self._runtime_client(), + # Vertex names Claude without the Anthropic API's date suffix. + api_model_id=self._model_name, ) return await model.generate(request, ctx) diff --git a/packages/genkit-vertexai/tests/model_garden/model_garden_test.py b/packages/genkit-vertexai/tests/model_garden/model_garden_test.py index 98dd7f6e..6edc253f 100644 --- a/packages/genkit-vertexai/tests/model_garden/model_garden_test.py +++ b/packages/genkit-vertexai/tests/model_garden/model_garden_test.py @@ -357,7 +357,8 @@ async def test_generate_model_garden_claude_registers_full_publisher_path() -> N assert response.text == 'hello' sent = client.messages.create.await_args or client.beta.messages.create.await_args assert sent is not None - assert sent.kwargs['model'].startswith('claude-sonnet-4-5') + # Vertex names Claude without a date; the Anthropic API's pinned id would 404 there. + assert sent.kwargs['model'] == 'claude-sonnet-4-5' assert action is not None assert action.name == 'modelgarden/anthropic/claude-sonnet-4-5' diff --git a/uv.lock b/uv.lock index c282e259..0366e6d8 100644 --- a/uv.lock +++ b/uv.lock @@ -147,6 +147,11 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a9/26/ea71185027956325be1903d4fcaf7461d5ef40ca8f0e64f992e24ea9db0e/anthropic-0.112.0-py3-none-any.whl", hash = "sha256:bcc6268612c716dbb77133dd60fc41d26016d1b81dee9a52314d210193638751", size = 931954, upload-time = "2026-06-24T18:45:58.205Z" }, ] +[package.optional-dependencies] +vertex = [ + { name = "google-auth", extra = ["requests"] }, +] + [[package]] name = "anthropic-sample" version = "0.1.0" @@ -1336,11 +1341,18 @@ dependencies = [ { name = "genkit" }, ] +[package.optional-dependencies] +google-cloud = [ + { name = "anthropic", extra = ["vertex"] }, +] + [package.metadata] requires-dist = [ { name = "anthropic", specifier = ">=0.98.0,<1" }, + { name = "anthropic", extras = ["vertex"], marker = "extra == 'google-cloud'", specifier = ">=0.98.0,<1" }, { name = "genkit", editable = "packages/genkit" }, ] +provides-extras = ["google-cloud"] [[package]] name = "genkit-django"