How to Use the Anthropic SDK with Google Vertex AI: Complete Setup Guide
Use the AnthropicVertex or AsyncAnthropicVertex client classes from the anthropic[vertex] extra to authenticate with Google Application Default Credentials and call Claude models hosted on Vertex AI.
The anthropics/anthropic-sdk-python repository provides specialized client classes that bridge the standard Anthropic API interface with Google Vertex AI's model-hosting infrastructure. These clients handle the complex request transformation, authentication, and URL rewriting required to communicate with Vertex AI endpoints, allowing you to use familiar SDK patterns while targeting Google's managed infrastructure.
Installing the Vertex AI Extension
The Vertex AI integration requires additional dependencies not included in the base SDK installation. You must install the vertex extra to access the Google authentication libraries and Vertex-specific client implementations.
pip install "anthropic[vertex]"
If you attempt to use the Vertex clients without this extra, the SDK raises a helpful error in src/anthropic/lib/vertex/_auth.py directing you to install with pip install anthropic[vertex].
Authentication and Client Initialization
The AnthropicVertex and AsyncAnthropicVertex classes extend BaseVertexClient (located in src/anthropic/lib/vertex/_client.py) to manage Google Cloud authentication and regional endpoint configuration.
Environment Variable Configuration
The client automatically detects configuration from environment variables, following Google's standard patterns:
CLOUD_ML_REGION– Specifies the Vertex AI region (e.g.,us-central1,us-east5)ANTHROPIC_VERTEX_PROJECT_ID– Your Google Cloud project IDANTHROPIC_VERTEX_BASE_URL– Optional override for the generated endpoint URL
from anthropic import AnthropicVertex
# Reads CLOUD_ML_REGION and ANTHROPIC_VERTEX_PROJECT_ID from environment
client = AnthropicVertex()
Explicit Configuration
You can bypass environment variables by passing region and project_id directly to the constructor:
client = AnthropicVertex(
region="us-central1",
project_id="my-gcp-project-123"
)
When the project_id is not provided via argument or environment variable, the client attempts to infer it from the loaded Google credentials in src/anthropic/lib/vertex/_client.py.
Custom Credentials
For advanced use cases, supply a pre-configured Google credentials object to bypass Application Default Credentials:
from google.auth.credentials import Credentials
from anthropic import AnthropicVertex
creds = Credentials(
token="ya29.a0ARrdaM...",
expired=False,
refresh_token=None
)
client = AnthropicVertex(credentials=creds)
The _auth.py module handles token refresh automatically, injecting a bearer token into the Authorization header before each request.
Making API Calls
Once initialized, the Vertex clients expose the same messages and beta resources as the standard Anthropic client. The SDK handles request translation transparently.
Synchronous Requests
Use AnthropicVertex for standard synchronous operations. The example below demonstrates calling a model hosted on Vertex AI:
from anthropic import AnthropicVertex
client = AnthropicVertex()
response = client.messages.create(
model="claude-sonnet-4@20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain quantum computing"}]
)
print(response.content)
See the complete example in examples/vertex.py for additional context.
Asynchronous Requests
For high-concurrency applications, use AsyncAnthropicVertex with async/await patterns:
import asyncio
from anthropic import AsyncAnthropicVertex
async def main():
client = AsyncAnthropicVertex()
response = await client.messages.create(
model="claude-sonnet-4@20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello from async!"}]
)
print(response.to_json())
asyncio.run(main())
Both sync and async implementations reuse the existing Stream and AsyncStream infrastructure for handling streaming responses.
How Request Rewriting Works
The Vertex client transforms standard Anthropic API calls into Vertex AI-compatible requests through the _prepare_options method in src/anthropic/lib/vertex/_client.py.
URL Transformation
Standard Anthropic paths like /v1/messages or /v1/messages/count_tokens are rewritten to Vertex's publishing format:
projects/{project_id}/locations/{region}/publishers/anthropic/models/{model}:rawPredict
For streaming requests, the endpoint uses :streamRawPredict instead of :rawPredict.
Request Flow
- The client loads Google credentials and generates an access token
_prepare_optionsvalidates thatproject_idis available (raising an error if missing)- The method constructs the full Vertex AI URL using the region and project ID
- The request executes via
httpxwith standard retry logic inherited fromBaseClient
This translation layer allows you to use standard SDK parameters (max_tokens, messages, system prompts) without modifying your code for Vertex-specific requirements.
Error Handling and Dependencies
The Vertex client relies on the SDK's standard exception hierarchy defined in src/anthropic/_exceptions.py. When Vertex AI returns HTTP errors (such as authentication failures or quota limits), the client maps these to familiar Anthropic exception types.
Important Dependencies
- google-auth – Handles OAuth2 token generation and refresh cycles
- httpx – Underlying HTTP client for all requests
If google-auth is not installed, the initialization fails with a clear message pointing to the anthropic[vertex] installation requirement.
Summary
- Install the Vertex extension using
pip install "anthropic[vertex]"to accessAnthropicVertexandAsyncAnthropicVertex - Authenticate using Google Application Default Credentials, environment variables (
CLOUD_ML_REGION,ANTHROPIC_VERTEX_PROJECT_ID), or explicit constructor arguments - Initialize clients identically to standard Anthropic clients—they share the same
messages.create()interface - Understand that requests automatically rewrite to Vertex's
rawPredictendpoints via_prepare_optionsinsrc/anthropic/lib/vertex/_client.py - Reuse existing async patterns and streaming infrastructure without code changes
Frequently Asked Questions
Do I need to modify my existing Anthropic SDK code to use Vertex AI?
No. The AnthropicVertex client maintains API parity with the standard Anthropic client. Your existing code for creating messages, handling streaming, and managing token counts works without modification. The client intercepts requests in _prepare_options and translates them to Vertex AI's format automatically.
What authentication methods does the Vertex client support?
The client supports Google Application Default Credentials (ADC) via the google-auth library, explicit credential objects passed to the credentials parameter, and implicit project detection from your GCP environment. If no credentials are provided, the SDK attempts to load them from your environment using standard Google Cloud authentication chains.
Which Vertex AI regions support Anthropic models?
The region must be specified via the CLOUD_ML_REGION environment variable or the region constructor argument. Common valid regions include us-central1, us-east5, and europe-west1, though availability depends on your Google Cloud project and model provisioning. The client constructs the endpoint URL as projects/{project_id}/locations/{region}/publishers/anthropic/models/{model}.
Can I use streaming and tool use with the Vertex client?
Yes. The AnthropicVertex and AsyncAnthropicVertex clients fully support streaming responses via stream=True and the beta tools API. The streaming infrastructure reuses the SDK's standard Stream class, routing through Vertex's :streamRawPredict endpoint while maintaining identical response parsing to direct Anthropic API calls.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →