Skip to content

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

Closed
huangjeff5 wants to merge 2 commits into
mainfrom
exp/py-anthropic-google-cloud
Closed

huangjeff5 wants to merge 2 commits into
mainfrom
exp/py-anthropic-google-cloud

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Stack (merge in order): #151 (Anthropic(backend=GoogleCloud())) → #196 (OpenAICompatible) → #197 (OpenAICompatible(backend=GoogleCloud())) → #198 (deprecate genkit-vertexai)

Anthropic(backend=GoogleCloud(...)) serves Claude from Google Cloud, billed to your project and authenticated with application default credentials. Refs, AnthropicConfig and .prompt files are the same as on the Anthropic API, so changing who pays for Claude means changing one constructor argument.

Today, Claude billed to a Google Cloud project goes through ModelGarden instead. It has its own namespace (modelgarden/anthropic/claude-...), only takes string refs, and its .prompt files only work with that billing setup. Under the hood, ModelGarden already runs Claude through genkit_anthropic.AnthropicModel on Anthropic's own AsyncAnthropicVertex client. This PR uses that same path from the Anthropic plugin.

# 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 the two auth modes fails at setup, on the user's line
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. No gcloud login yet: the error names the fix instead of coming back as 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

  • backend= on Anthropic, and a new exported GoogleCloud. GoogleCloud(project=None, location=None) is a frozen, keyword-only dataclass. Leaving backend out keeps today's behavior. With a GoogleCloud, the plugin builds Anthropic's AsyncAnthropicVertex instead of AsyncAnthropic. The SDK moves the model into the URL (:rawPredict), adds anthropic_version to the body, and refreshes the Google token.
    • Project: project=, then GCLOUD_PROJECT, then GOOGLE_CLOUD_PROJECT, then the ADC project. The ADC lookup runs once, in a thread, on the first generate.
    • Location: location=, then GOOGLE_CLOUD_LOCATION, then global. Every project that enables Claude gets global quota; regional endpoints need regional quota.
    • No project anywhere: generate fails with FAILED_PRECONDITION naming GoogleCloud(project=...) and GOOGLE_CLOUD_PROJECT.
  • Only backend= switches backends. A missing ANTHROPIC_API_KEY never falls back to ADC. The SDK's own ANTHROPIC_VERTEX_PROJECT_ID and CLOUD_ML_REGION are ignored.
    • api_key= with GoogleCloud raises ValueError. A backend that isn't a GoogleCloud raises TypeError.
    • A context.secrets key fails with FAILED_PRECONDITION, before the ADC lookup.
  • A missing or stale Google login fails with the command that fixes it. On the first call, the plugin loads application default credentials and refreshes them. If there are no credentials, or the login needs refreshing, the call fails with FAILED_PRECONDITION naming gcloud auth application-default login. Without this, the SDK raises google-auth's error mid-request, and the caller sees INTERNAL: internal error.
    • A failed load isn't cached, so the next call works once the user logs in, without restarting the app.
    • Transient TransportError and retryable RefreshError blips map to UNAVAILABLE so Retry middleware can retry them.
    • An access_token or credentials in client_options is used as is, and ADC isn't loaded.
  • Google Cloud gets the model name Google Cloud uses. On Google Cloud, Claude is named without a date: claude-haiku-4-5, not the Anthropic API's pinned claude-haiku-4-5-20251001. Each backend now picks the id it sends. The Anthropic API sends the catalog's pinned id, and Google Cloud sends the name as given. Without this, Haiku 4.5, Sonnet 4.5 and Opus 4.5 would 404 on Google Cloud. ModelGarden had the same bug, and now sends the dateless name too.
  • client_options is checked against the client that's built. With GoogleCloud, it takes AsyncAnthropicVertex options (access_token, credentials, timeout, ...), and the error names that class. region and project_id are reserved for GoogleCloud.
  • task_budget works on Google Cloud. The Anthropic API gets the default beta headers; Google Cloud gets none. Vertex rejects task_budget without its header (400 output_config.task_budget: Extra inputs are not permitted), so a set task_budget brings task-budgets-2026-03-13 on every backend. An explicit betas list still replaces the defaults.
  • list_actions returns the built-in catalog on Google Cloud. Vertex has no Models API, so the Dev UI lists SUPPORTED_ANTHROPIC_MODELS and makes no call. Any other Claude id still resolves on demand.
  • New google-cloud extra → anthropic[vertex], which brings google-auth. Without it, Anthropic(backend=GoogleCloud()) raises ImportError on the constructor line, with the uv add command.
  • README setup guide for first-time Google Cloud users. It walks through installing gcloud, a billing project, turning on the API, enabling Claude in Model Garden, the ADC login, and the service-account role for Cloud Run. It also lists what each error means and the step that fixes it. The Anthropic API stays first; Google Cloud comes after it.

Decisions

  • Google Cloud settings live in one GoogleCloud(...) object, not as more arguments on Anthropic(): Most people on this plugin call the Anthropic API, so Anthropic()'s arguments stay about that path (api_key, base_url).
    • The first revision added google_cloud=True, project=..., location=... directly on Anthropic(). That showed three Google Cloud arguments to every Anthropic API user. It also needed a runtime check for project= without google_cloud=True, which the Anthropic API would otherwise silently ignore.
    • backend=GoogleCloud(project=..., location=...) keeps that config in one typed object that only Google Cloud users import, and makes the invalid combination impossible to write.
    • A later AmazonBedrock(region=...) would work the same way, without touching Anthropic()'s signature.
  • The ref names the model, not who pays: Anthropic.claude('claude-sonnet-5-5') resolves to anthropic/claude-sonnet-5-5 on both backends, the same rule docs: propose one GoogleGenAI plugin with an enterprise flag #138 uses for Gemini. The cost is one Claude backend per app, since both register under anthropic/.
  • No automatic fallback to ADC: Picking a backend from whichever credential happens to be present means a missing env var silently moves billing to another account. An explicit argument beats an environment variable.
  • One private class per backend; the plugin and model don't branch on it: Anthropic.__init__ picks the backend once (_backend_for). After that, AnthropicApiBackend and GoogleCloudBackend each own their SDK client, who pays for a call (plugin key, per-request key, or ADC project), the model id sent, model listing, and default betas. AnthropicModel only maps requests and responses, with no isinstance checks on the client. Adding AmazonBedrock(region=...) would mean one new backend class, one branch in _backend_for, and no change to generate or AnthropicModel.

What differs on Google Cloud

This is documented for users in the README's What's different on Google Cloud section, based on sending every AnthropicConfig field to 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 give identical results through ModelGarden.
    • These ran on the first (google_cloud=True) revision. The backend= refactor and the backend split since then don't change requests, URLs or credentials, and haven't been re-run live.
  • Unit: packages/genkit-anthropic 417 passed, 5 skipped (live tests, no ANTHROPIC_API_KEY); packages/genkit-vertexai 53 passed. _backend.py, _anthropic_api.py and _google_cloud.py are at 100% line coverage.
  • Mutation pass: I deleted or inverted each new branch, one at a time (26 mutants, including every guard in _backend_for, both backends, client_kwargs and load_adc), and reran the package tests. Every mutant fails at least one test. The tests for default betas and credentials go through ai.generate, against a fake HTTP API or a stubbed Vertex client.
  • No-ADC probe: I ran against an empty gcloud config with no credentials. Both GoogleCloud() and GoogleCloud(project=...) return FAILED_PRECONDITION with the login command. Before this change, the second one returned INTERNAL.
  • Static checks:
    • ruff format/check and ty pass.
    • pyright reports 8 errors and pyrefly 7. These are the same errors as before this PR's backend split, and none are in changed files.
  • Not run locally: addlicense. New files carry the Apache header.

Breaking changes

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

Open questions

  1. Go and JS. Go's anthropic plugin already documents Vertex through Opts. JS would need the same option.

Follow-ups

@huangjeff5
huangjeff5 force-pushed the exp/py-anthropic-google-cloud branch from afc38ba to 9330299 Compare November 30, 2026 21:40
Resolve semantic conflict with #147 (0d096ca): update
test_generate_claude_sends_back_empty_signed_thinking_before_tool_use
to stub plugin._backend.client instead of the removed
plugin._runtime_client.
@huangjeff5

Copy link
Copy Markdown
Collaborator Author

Superseded by #257 in a fresh clean stack off latest main (#257 → #258 → #259 → #260 → #261 [Draft]).

@huangjeff5 huangjeff5 closed this Nov 30, 2026
@huangjeff5
huangjeff5 deleted the exp/py-anthropic-google-cloud branch November 30, 2026 22:40
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.

1 participant