Skip to content

feat(py): serve Claude from Google Cloud with Anthropic(backend=GoogleCloud()) - #257

Merged
huangjeff5 merged 1 commit into
mainfrom
feat/py-anthropic-google-cloud
Dec 1, 2026
Merged

huangjeff5 merged 1 commit into
mainfrom
feat/py-anthropic-google-cloud

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Stack (merge in order): #257 (Anthropic(backend=GoogleCloud())) → #258 (OpenAICompatible) → #259 (OpenAICompatible(backend=GoogleCloud())) → #260 (deprecate genkit-vertexai)

Anthropic(backend=GoogleCloud(...)) runs Claude on Google Cloud using your project's billing and application default credentials. Model refs, AnthropicConfig, and .prompt files stay identical to the direct Anthropic API, so switching backends is a one-line constructor change.

Today, running Claude on Google Cloud requires ModelGarden, which uses a separate modelgarden/anthropic/... namespace, only accepts string refs, and ties .prompt files to Vertex. ModelGarden already delegates to genkit_anthropic.AnthropicModel via Anthropic's AsyncAnthropicVertex client; this PR exposes that path directly on Anthropic.

# uv add 'genkit-anthropic[google-cloud]'
from genkit import Genkit
from genkit_anthropic import Anthropic, GoogleCloud

# 1. Same plugin as the Anthropic API, billed to your Google Cloud project
ai = Genkit(plugins=[Anthropic(backend=GoogleCloud(project='bistro-prod', location='global'))])

# 2. Same typed ref and config as the direct API
response = await ai.generate(
    model=Anthropic.claude('claude-sonnet-5-5'),
    prompt='Suggest a dish for a guest with a shellfish allergy.',
)
print(response.text)
# => Herb-Roasted Chicken with Lemon Rice

# 3. On Cloud Run, the project comes from the environment or the credentials
Anthropic(backend=GoogleCloud())
# => project from GCLOUD_PROJECT, GOOGLE_CLOUD_PROJECT, then ADC; location 'global'

# 4. Mixing auth modes fails at construction
Anthropic(backend=GoogleCloud(), api_key='sk-ant-...')
# => ValueError: Anthropic(backend=GoogleCloud()) authenticates with Google Cloud credentials; drop api_key

# 5. A tenant key can't bill a Google Cloud project, so the call fails before any lookup
await ai.generate(model=..., prompt='...', context={'secrets': {'api_key': 'sk-ant-...'}})
# => response.error.status == 'FAILED_PRECONDITION'

# 6. Missing gcloud login returns FAILED_PRECONDITION with the login command instead of INTERNAL
await ai.generate(model=..., prompt='...')
# => FAILED_PRECONDITION: Anthropic(backend=GoogleCloud()) found no Google Cloud credentials:
#    run `gcloud auth application-default login` on your machine, ...

Changes

  • New backend= parameter and GoogleCloud config: GoogleCloud(project=None, location=None) is a frozen, keyword-only dataclass exported from genkit_anthropic. Passing backend=GoogleCloud(...) builds Anthropic's AsyncAnthropicVertex client instead of AsyncAnthropic, which routes requests to :rawPredict, injects anthropic_version, and refreshes Google tokens.
    • Project resolution: project=, then GCLOUD_PROJECT, then GOOGLE_CLOUD_PROJECT, then the ADC project (loaded once in a worker thread on first generate). A missing project fails with FAILED_PRECONDITION pointing to GoogleCloud(project=...) and GOOGLE_CLOUD_PROJECT.
    • Location resolution: location=, then GOOGLE_CLOUD_LOCATION, then 'global' (projects with Claude enabled get global quota by default; regional endpoints require regional quota).
  • Explicit backend selection and auth checks: A missing ANTHROPIC_API_KEY never falls back to ADC, and Anthropic's ANTHROPIC_VERTEX_PROJECT_ID / CLOUD_ML_REGION env vars are ignored. Passing api_key= with GoogleCloud raises ValueError; passing a non-GoogleCloud backend raises TypeError (with a module-qualified hint if a GoogleCloud from another package is passed); passing a context.secrets key fails with FAILED_PRECONDITION before ADC lookup.
  • Clear ADC error handling: On first call, the plugin loads and refreshes ADC. Missing or expired credentials return FAILED_PRECONDITION with the gcloud auth application-default login command instead of surfacing as INTERNAL. Failed loads are not cached (so logging in works without restarting). Transient TransportError and retryable RefreshError map to UNAVAILABLE for Retry middleware. If access_token or credentials is passed in client_options, ADC is skipped.
  • Backend-specific model IDs: Google Cloud expects dateless Claude IDs (claude-haiku-4-5), while the Anthropic API uses dated catalog IDs (claude-haiku-4-5-20251001). Each backend now formats its own model ID, fixing 404s for Haiku 4.5, Sonnet 4.5, and Opus 4.5 on Google Cloud (and fixing the same bug in ModelGarden).
  • client_options validation: Validated against AsyncAnthropicVertex when using GoogleCloud (region and project_id are reserved for GoogleCloud).
  • task_budget beta header: Google Cloud omits default beta headers, and Vertex rejects task_budget without its header (400 output_config.task_budget: Extra inputs are not permitted). Setting task_budget now adds task-budgets-2026-03-13 on both backends unless betas is explicitly overridden.
  • Static list_actions on Google Cloud: Vertex has no Models API, so list_actions returns SUPPORTED_ANTHROPIC_MODELS without making a network call. Unlisted Claude IDs still resolve on demand.
  • New google-cloud extra: Adds anthropic[vertex]>=0.98.0,<1 (which pulls in google-auth[requests]). If google-auth or google.auth.transport.requests is missing, Anthropic(backend=GoogleCloud()) raises ImportError with the uv add command.
  • README: Adds a Google Cloud setup section (after the direct API docs) covering gcloud, project/API/Model Garden setup, ADC login, Cloud Run IAM roles, and common errors.

Decisions

  • Put Google Cloud options on GoogleCloud(...) instead of Anthropic(...): Most callers use the Anthropic API directly, so Anthropic() shouldn't grow google_cloud, project, and location kwargs that don't apply to them. Grouping those fields on backend=GoogleCloud(project=..., location=...) keeps them out of the default signature, avoids invalid combinations like project=... without google_cloud=True, and leaves room for other backends (e.g. AmazonBedrock) without adding more top-level kwargs.
  • Keep the anthropic/ namespace on both backends: Anthropic.claude('claude-sonnet-5-5') resolves to anthropic/claude-sonnet-5-5 whether billed to Anthropic or Google Cloud, so switching backends doesn't require rewriting refs or .prompt files. Anthropic doesn't expose a name= parameter yet (unlike OpenAICompatible, which already lets you set a custom namespace), so an app registers one Anthropic instance for now; adding an optional name= later is purely additive.
  • Require backend=GoogleCloud() explicitly (no ADC fallback): Falling back to ADC when ANTHROPIC_API_KEY is missing would silently move billing to a Google Cloud project on a misconfigured environment.
  • Isolate backend differences behind a private Backend interface: Anthropic.__init__ resolves the backend once into either AnthropicApiBackend or GoogleCloudBackend. Each backend owns client construction, auth, model ID formatting, model listing, and default betas, so AnthropicModel stays focused on request/response mapping without isinstance checks on the SDK client.

What differs on Google Cloud

Documented in the README's What's different on Google Cloud section, based on testing every AnthropicConfig field against Vertex:

  • image URLs are rejected, so send base64;
  • no default beta headers;
  • an organization policy can block native structured output (output_constrained=False works around it);
  • no service_tier/inference_geo, and no Files API, web fetch, or code execution betas.

Verification

  • Live, against a Google Cloud project with claude-sonnet-5-5 in global:
    • Passed: text, structured output, tools, streaming, adaptive thinking, effort, task_budget, static list_actions. The same cases produce identical results through ModelGarden.
    • These ran on the first (google_cloud=True) revision; subsequent refactors did not change request shapes, URLs, or credentials and haven't been re-run live.
  • Unit tests: packages/genkit-anthropic, packages/genkit-vertexai, and tests/version_bounds_guard_test.py — 538 passed, 5 skipped (live tests, no ANTHROPIC_API_KEY).
  • No-ADC probe: Tested against an empty gcloud config with no credentials. Both GoogleCloud() and GoogleCloud(project=...) return FAILED_PRECONDITION with the login command (previously the second returned INTERNAL).
  • Static & repo checks: ruff, ty, pyrefly (0 errors), scripts/check_consistency.py, uv lock --check, and addlicense -check all pass (pyright runs in CI).

Breaking changes

None. backend is optional and the direct-API path is unchanged.

Follow-ups

@pavelgj pavelgj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@huangjeff5
huangjeff5 force-pushed the feat/py-anthropic-google-cloud branch from 026ca2e to c9ab258 Compare December 1, 2026 21:20
@huangjeff5
huangjeff5 merged commit 8386edd into main Dec 1, 2026
21 checks passed
@huangjeff5
huangjeff5 deleted the feat/py-anthropic-google-cloud branch December 1, 2026 21:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants