0
# Platform Adapters
1
2
The Anthropic Java SDK provides platform adapter modules that enable you to use Claude models on AWS Bedrock and Google Vertex AI, in addition to the direct Anthropic API. Platform adapters handle authentication, request signing, and platform-specific configuration while maintaining the same familiar API interface.
3
4
## Overview
5
6
Platform adapters implement the `Backend` interface to adapt the SDK's core functionality for different cloud platforms:
7
8
- **Direct API** - Default backend for direct Anthropic API access
9
- **AWS Bedrock** - Access Claude models through Amazon Bedrock
10
- **Google Vertex AI** - Access Claude models through Google Cloud Vertex AI
11
12
All backends integrate seamlessly with the SDK's client builders, allowing you to switch platforms with minimal code changes.
13
14
## AWS Bedrock Adapter
15
16
The AWS Bedrock adapter enables access to Claude models through [Amazon Bedrock](https://aws.amazon.com/bedrock/claude/), AWS's managed service for foundation models.
17
18
### Installation
19
20
The Bedrock adapter requires the `anthropic-java-bedrock` library dependency in addition to the core SDK.
21
22
#### Gradle
23
24
```kotlin
25
implementation("com.anthropic:anthropic-java-bedrock:2.11.0")
26
```
27
28
#### Maven
29
30
```xml
31
<dependency>
32
<groupId>com.anthropic</groupId>
33
<artifactId>anthropic-java-bedrock</artifactId>
34
<version>2.11.0</version>
35
</dependency>
36
```
37
38
### BedrockBackend Class
39
40
```java
41
class BedrockBackend { .api }
42
```
43
44
**Location**: `anthropic-java-bedrock/src/main/kotlin/com/anthropic/bedrock/backends/BedrockBackend.kt`
45
46
**Properties**:
47
- `val awsCredentialsProvider: AwsCredentialsProvider?` - AWS credentials provider for authentication
48
- `val apiKey: String?` - API key for Bedrock API key authentication (alternative to credentials)
49
- `val region: Region` - AWS region where Bedrock is accessed
50
- `val awsCredentials: AwsCredentials` - Resolved AWS credentials used for request signing
51
52
**Static Factory Methods**:
53
```java
54
@JvmStatic fun builder(): Builder { .api }
55
```
56
Creates a new builder for constructing a `BedrockBackend`.
57
58
```java
59
@JvmStatic fun fromEnv(): BedrockBackend { .api }
60
```
61
Creates a `BedrockBackend` configured from environment variables and AWS default provider chains.
62
63
### Authentication
64
65
The Bedrock adapter supports two authentication methods:
66
67
#### AWS Credentials
68
69
Standard AWS credentials using access keys and secret keys. Credentials can be provided through:
70
71
- AWS default credentials provider chain
72
- Environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`)
73
- AWS credentials file (`~/.aws/credentials`)
74
- IAM roles for EC2 instances or ECS tasks
75
- Custom `AwsCredentialsProvider` implementations
76
77
#### API Keys
78
79
Bedrock API keys provide an alternative authentication method. API keys can be:
80
81
- Set via the `AWS_BEARER_TOKEN_BEDROCK` environment variable
82
- Passed directly using `BedrockBackend.Builder.apiKey()`
83
84
API keys take precedence over credentials when both are available in the environment.
85
86
### Configuration
87
88
#### Automatic Configuration
89
90
Use `BedrockBackend.fromEnv()` to automatically resolve credentials and region:
91
92
```java
93
import com.anthropic.bedrock.backends.BedrockBackend;
94
import com.anthropic.client.AnthropicClient;
95
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
96
97
AnthropicClient client = AnthropicOkHttpClient.builder()
98
.backend(BedrockBackend.fromEnv())
99
.build();
100
```
101
102
This automatically:
103
- Resolves AWS credentials using the [AWS default credentials provider chain](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials-chain.html)
104
- Resolves AWS region using the [AWS default region provider chain](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html)
105
- Uses API key from `AWS_BEARER_TOKEN_BEDROCK` if available (takes precedence over credentials)
106
107
#### Manual Configuration
108
109
Configure credentials and region explicitly:
110
111
```java
112
import com.anthropic.bedrock.backends.BedrockBackend;
113
import com.anthropic.client.AnthropicClient;
114
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
115
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
116
import software.amazon.awssdk.auth.credentials.AwsCredentials;
117
import software.amazon.awssdk.regions.Region;
118
119
AwsCredentials awsCredentials = AwsBasicCredentials.create(
120
System.getenv("AWS_ACCESS_KEY_ID"),
121
System.getenv("AWS_SECRET_ACCESS_KEY"));
122
123
AnthropicClient client = AnthropicOkHttpClient.builder()
124
.backend(BedrockBackend.builder()
125
.awsCredentials(awsCredentials)
126
.region(Region.US_EAST_1)
127
.build())
128
.build();
129
```
130
131
#### Custom Credentials Provider
132
133
Use a custom AWS credentials provider with additional features:
134
135
```java
136
import com.anthropic.bedrock.backends.BedrockBackend;
137
import com.anthropic.client.AnthropicClient;
138
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
139
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
140
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
141
142
AwsCredentialsProvider awsCredentialsProvider =
143
DefaultCredentialsProvider.builder()
144
.asyncCredentialUpdateEnabled(true)
145
.build();
146
147
AnthropicClient client = AnthropicOkHttpClient.builder()
148
.backend(BedrockBackend.builder()
149
.fromEnv(awsCredentialsProvider)
150
.build())
151
.build();
152
```
153
154
#### API Key Configuration
155
156
Configure using an API key instead of AWS credentials:
157
158
```java
159
import com.anthropic.bedrock.backends.BedrockBackend;
160
import com.anthropic.client.AnthropicClient;
161
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
162
import software.amazon.awssdk.regions.Region;
163
164
AnthropicClient client = AnthropicOkHttpClient.builder()
165
.backend(BedrockBackend.builder()
166
.apiKey(myApiKey)
167
.region(Region.US_EAST_1)
168
.build())
169
.build();
170
```
171
172
### BedrockBackend.Builder
173
174
```java
175
class BedrockBackend.Builder { .api }
176
```
177
178
**Builder Methods**:
179
180
```java
181
fun fromEnv(awsCredentialsProvider: AwsCredentialsProvider? = null): Builder { .api }
182
```
183
Load configuration from environment variables. If `awsCredentialsProvider` is provided, uses it for credentials; otherwise uses default provider chain. Region is resolved from AWS default region provider chain. API key is loaded from `AWS_BEARER_TOKEN_BEDROCK` if available.
184
185
```java
186
fun awsCredentialsProvider(provider: AwsCredentialsProvider): Builder { .api }
187
```
188
Set the AWS credentials provider. Cannot be used with `apiKey()`.
189
190
```java
191
fun awsCredentials(credentials: AwsCredentials): Builder { .api }
192
```
193
Set AWS credentials directly. Cannot be used with `apiKey()` or `awsCredentialsProvider()`.
194
195
```java
196
fun apiKey(apiKey: String): Builder { .api }
197
```
198
Set the Bedrock API key for authentication. Cannot be used with `awsCredentials()` or `awsCredentialsProvider()`.
199
200
```java
201
fun region(region: Region): Builder { .api }
202
```
203
Set the AWS region. Required for both credential-based and API key-based authentication.
204
205
```java
206
fun build(): BedrockBackend { .api }
207
```
208
Build the `BedrockBackend` instance. Throws if required configuration is missing or conflicting.
209
210
### Environment Variables
211
212
- `AWS_ACCESS_KEY_ID` - AWS access key ID (for credentials-based auth)
213
- `AWS_SECRET_ACCESS_KEY` - AWS secret access key (for credentials-based auth)
214
- `AWS_SESSION_TOKEN` - AWS session token (optional, for temporary credentials)
215
- `AWS_BEARER_TOKEN_BEDROCK` - Bedrock API key (for API key-based auth)
216
- `AWS_REGION` - AWS region (used by default region provider chain)
217
- `AWS_DEFAULT_REGION` - Alternative AWS region variable
218
219
### AWS Credentials Provider Chain
220
221
When using `fromEnv()` without a custom provider, credentials are resolved in this order:
222
223
1. Java system properties (`aws.accessKeyId`, `aws.secretAccessKey`)
224
2. Environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`)
225
3. Web identity token from AWS STS (for EKS/ECS)
226
4. AWS credentials file (`~/.aws/credentials`)
227
5. Amazon EC2 instance profile credentials (for EC2 instances)
228
6. Container credentials (for ECS tasks)
229
230
See [AWS documentation](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials-chain.html) for complete details.
231
232
### Usage Examples
233
234
#### Basic Usage with Automatic Configuration
235
236
```java
237
import com.anthropic.bedrock.backends.BedrockBackend;
238
import com.anthropic.client.AnthropicClient;
239
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
240
import com.anthropic.models.messages.Message;
241
import com.anthropic.models.messages.MessageCreateParams;
242
import com.anthropic.models.messages.Model;
243
244
AnthropicClient client = AnthropicOkHttpClient.builder()
245
.backend(BedrockBackend.fromEnv())
246
.build();
247
248
MessageCreateParams params = MessageCreateParams.builder()
249
.maxTokens(1024L)
250
.addUserMessage("Hello, Claude on Bedrock")
251
.model(Model.CLAUDE_SONNET_4_20250514)
252
.build();
253
254
Message message = client.messages().create(params);
255
System.out.println(message.content().get(0).asText().text());
256
```
257
258
#### Explicit Region and Credentials
259
260
```java
261
import com.anthropic.bedrock.backends.BedrockBackend;
262
import com.anthropic.client.AnthropicClient;
263
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
264
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
265
import software.amazon.awssdk.regions.Region;
266
267
AnthropicClient client = AnthropicOkHttpClient.builder()
268
.backend(BedrockBackend.builder()
269
.awsCredentials(AwsBasicCredentials.create(
270
"YOUR_ACCESS_KEY",
271
"YOUR_SECRET_KEY"))
272
.region(Region.US_WEST_2)
273
.build())
274
.build();
275
```
276
277
#### Using API Keys
278
279
```java
280
import com.anthropic.bedrock.backends.BedrockBackend;
281
import com.anthropic.client.AnthropicClient;
282
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
283
import software.amazon.awssdk.regions.Region;
284
285
// From environment variable AWS_BEARER_TOKEN_BEDROCK
286
AnthropicClient client1 = AnthropicOkHttpClient.builder()
287
.backend(BedrockBackend.fromEnv())
288
.build();
289
290
// Explicit API key
291
AnthropicClient client2 = AnthropicOkHttpClient.builder()
292
.backend(BedrockBackend.builder()
293
.apiKey(System.getenv("BEDROCK_API_KEY"))
294
.region(Region.US_EAST_1)
295
.build())
296
.build();
297
```
298
299
#### Custom Credentials Provider
300
301
```java
302
import com.anthropic.bedrock.backends.BedrockBackend;
303
import com.anthropic.client.AnthropicClient;
304
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
305
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
306
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
307
308
// Use specific AWS profile
309
AwsCredentialsProvider provider = ProfileCredentialsProvider.builder()
310
.profileName("production")
311
.build();
312
313
AnthropicClient client = AnthropicOkHttpClient.builder()
314
.backend(BedrockBackend.builder()
315
.fromEnv(provider)
316
.build())
317
.build();
318
```
319
320
### Limitations
321
322
The Bedrock backend currently does not support:
323
324
- **Batch API** - Message batch operations are not available on Bedrock
325
- **Token Counting API** - The `messages().countTokens()` method is not supported
326
327
All other API functionality (messages, streaming, tools, prompt caching) works identically to the direct Anthropic API.
328
329
## Google Vertex AI Adapter
330
331
The Google Vertex AI adapter enables access to Claude models through [Google Cloud Vertex AI](https://cloud.google.com/vertex-ai), Google Cloud's platform for ML models.
332
333
### Installation
334
335
The Vertex AI adapter requires the `anthropic-java-vertex` library dependency in addition to the core SDK.
336
337
#### Gradle
338
339
```kotlin
340
implementation("com.anthropic:anthropic-java-vertex:2.11.0")
341
```
342
343
#### Maven
344
345
```xml
346
<dependency>
347
<groupId>com.anthropic</groupId>
348
<artifactId>anthropic-java-vertex</artifactId>
349
<version>2.11.0</version>
350
</dependency>
351
```
352
353
### VertexBackend Class
354
355
```java
356
class VertexBackend { .api }
357
```
358
359
**Location**: `anthropic-java-vertex/src/main/kotlin/com/anthropic/vertex/backends/VertexBackend.kt`
360
361
**Properties**:
362
- `val googleCredentials: GoogleCredentials` - Google OAuth2 credentials for authentication
363
- `val region: String` - Google Cloud region where Vertex AI is accessed
364
- `val project: String` - Google Cloud project ID
365
366
**Static Factory Methods**:
367
```java
368
@JvmStatic fun builder(): Builder { .api }
369
```
370
Creates a new builder for constructing a `VertexBackend`.
371
372
```java
373
@JvmStatic fun fromEnv(): VertexBackend { .api }
374
```
375
Creates a `VertexBackend` configured from environment variables and Google Application Default Credentials.
376
377
### Authentication
378
379
The Vertex AI adapter uses Google OAuth2 credentials for authentication.
380
381
#### Google Application Default Credentials (ADC)
382
383
The primary authentication method uses [Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc), which automatically discovers credentials in this order:
384
385
1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable pointing to a service account key file
386
2. User credentials from `gcloud auth application-default login`
387
3. Google Compute Engine service account (for GCE instances)
388
4. Google Kubernetes Engine workload identity (for GKE pods)
389
390
#### Service Account Keys
391
392
For service accounts, credentials are loaded from a JSON key file:
393
394
```json
395
{
396
"type": "service_account",
397
"project_id": "your-project-id",
398
"private_key_id": "key-id",
399
"private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
400
"client_email": "service-account@your-project.iam.gserviceaccount.com",
401
"client_id": "123456789",
402
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
403
"token_uri": "https://oauth2.googleapis.com/token"
404
}
405
```
406
407
### Configuration
408
409
#### Automatic Configuration
410
411
Use `VertexBackend.fromEnv()` to automatically resolve credentials, region, and project:
412
413
```java
414
import com.anthropic.client.AnthropicClient;
415
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
416
import com.anthropic.vertex.backends.VertexBackend;
417
418
AnthropicClient client = AnthropicOkHttpClient.builder()
419
.backend(VertexBackend.fromEnv())
420
.build();
421
```
422
423
This automatically:
424
- Resolves credentials using Google Application Default Credentials
425
- Loads region from `CLOUD_ML_REGION` environment variable
426
- Loads project ID from `ANTHROPIC_VERTEX_PROJECT_ID` environment variable
427
428
#### Manual Configuration
429
430
Configure credentials, region, and project explicitly:
431
432
```java
433
import com.anthropic.client.AnthropicClient;
434
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
435
import com.anthropic.vertex.backends.VertexBackend;
436
import com.google.auth.oauth2.AccessToken;
437
import com.google.auth.oauth2.GoogleCredentials;
438
439
String accessToken = System.getenv("GOOGLE_ACCESS_TOKEN");
440
String project = System.getenv("ANTHROPIC_VERTEX_PROJECT_ID");
441
442
GoogleCredentials googleCredentials = GoogleCredentials.create(
443
AccessToken.newBuilder().setTokenValue(accessToken).build());
444
445
AnthropicClient client = AnthropicOkHttpClient.builder()
446
.backend(VertexBackend.builder()
447
.googleCredentials(googleCredentials)
448
.region("us-central1")
449
.project(project)
450
.build())
451
.build();
452
```
453
454
#### Service Account Configuration
455
456
Load credentials from a service account key file:
457
458
```java
459
import com.anthropic.client.AnthropicClient;
460
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
461
import com.anthropic.vertex.backends.VertexBackend;
462
import com.google.auth.oauth2.GoogleCredentials;
463
import java.io.FileInputStream;
464
465
GoogleCredentials credentials = GoogleCredentials.fromStream(
466
new FileInputStream("/path/to/service-account-key.json"));
467
468
AnthropicClient client = AnthropicOkHttpClient.builder()
469
.backend(VertexBackend.builder()
470
.googleCredentials(credentials)
471
.region("us-central1")
472
.project("my-project-id")
473
.build())
474
.build();
475
```
476
477
### VertexBackend.Builder
478
479
```java
480
class VertexBackend.Builder { .api }
481
```
482
483
**Builder Methods**:
484
485
```java
486
fun fromEnv(): Builder { .api }
487
```
488
Load configuration from environment variables. Uses Google Application Default Credentials for authentication. Region is loaded from `CLOUD_ML_REGION`. Project ID is loaded from `ANTHROPIC_VERTEX_PROJECT_ID`.
489
490
```java
491
fun googleCredentials(credentials: GoogleCredentials): Builder { .api }
492
```
493
Set the Google OAuth2 credentials for authentication.
494
495
```java
496
fun region(region: String): Builder { .api }
497
```
498
Set the Google Cloud region (e.g., "us-central1", "europe-west1").
499
500
```java
501
fun project(project: String): Builder { .api }
502
```
503
Set the Google Cloud project ID.
504
505
```java
506
fun build(): VertexBackend { .api }
507
```
508
Build the `VertexBackend` instance. Throws if required configuration is missing.
509
510
### Environment Variables
511
512
- `GOOGLE_APPLICATION_CREDENTIALS` - Path to service account JSON key file (used by ADC)
513
- `CLOUD_ML_REGION` - Google Cloud region for Vertex AI
514
- `ANTHROPIC_VERTEX_PROJECT_ID` - Google Cloud project ID
515
- `GOOGLE_CLOUD_PROJECT` - Alternative project ID variable (lower priority)
516
517
### Usage Examples
518
519
#### Basic Usage with Automatic Configuration
520
521
```java
522
import com.anthropic.client.AnthropicClient;
523
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
524
import com.anthropic.models.messages.Message;
525
import com.anthropic.models.messages.MessageCreateParams;
526
import com.anthropic.models.messages.Model;
527
import com.anthropic.vertex.backends.VertexBackend;
528
529
AnthropicClient client = AnthropicOkHttpClient.builder()
530
.backend(VertexBackend.fromEnv())
531
.build();
532
533
MessageCreateParams params = MessageCreateParams.builder()
534
.maxTokens(1024L)
535
.addUserMessage("Hello, Claude on Vertex AI")
536
.model(Model.CLAUDE_SONNET_4_20250514)
537
.build();
538
539
Message message = client.messages().create(params);
540
System.out.println(message.content().get(0).asText().text());
541
```
542
543
#### Explicit Configuration
544
545
```java
546
import com.anthropic.client.AnthropicClient;
547
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
548
import com.anthropic.vertex.backends.VertexBackend;
549
import com.google.auth.oauth2.GoogleCredentials;
550
551
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
552
553
AnthropicClient client = AnthropicOkHttpClient.builder()
554
.backend(VertexBackend.builder()
555
.googleCredentials(credentials)
556
.region("us-east4")
557
.project("my-gcp-project")
558
.build())
559
.build();
560
```
561
562
#### Using Service Account Key
563
564
```java
565
import com.anthropic.client.AnthropicClient;
566
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
567
import com.anthropic.vertex.backends.VertexBackend;
568
import com.google.auth.oauth2.ServiceAccountCredentials;
569
import java.io.FileInputStream;
570
571
ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream(
572
new FileInputStream("/path/to/key.json"));
573
574
AnthropicClient client = AnthropicOkHttpClient.builder()
575
.backend(VertexBackend.builder()
576
.googleCredentials(credentials)
577
.region("us-central1")
578
.project("my-project")
579
.build())
580
.build();
581
```
582
583
#### User Credentials from gcloud
584
585
```java
586
import com.anthropic.client.AnthropicClient;
587
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
588
import com.anthropic.vertex.backends.VertexBackend;
589
590
// Requires: gcloud auth application-default login
591
AnthropicClient client = AnthropicOkHttpClient.builder()
592
.backend(VertexBackend.fromEnv())
593
.build();
594
```
595
596
### Limitations
597
598
The Vertex AI backend currently does not support:
599
600
- **Batch API** - Message batch operations are not available on Vertex AI
601
602
Token counting **is supported** on Vertex AI (unlike Bedrock). All other API functionality works identically to the direct Anthropic API.
603
604
## Backend Interface
605
606
Platform adapters implement a common `Backend` interface that can be used to create custom platform integrations.
607
608
```java
609
interface Backend { .api }
610
```
611
612
**Location**: `anthropic-java-core/src/main/kotlin/com/anthropic/core/Backend.kt`
613
614
The `Backend` interface defines methods for:
615
- Constructing platform-specific base URLs
616
- Applying platform-specific authentication headers and signatures
617
- Adapting requests and responses for platform requirements
618
619
### Custom Backend Implementation
620
621
To create a custom backend for a different platform:
622
623
```java
624
import com.anthropic.core.Backend;
625
626
class CustomBackend implements Backend {
627
@Override
628
public String baseUrl() {
629
return "https://custom-platform.example.com";
630
}
631
632
// Implement other Backend methods for authentication, signing, etc.
633
}
634
635
AnthropicClient client = AnthropicOkHttpClient.builder()
636
.backend(new CustomBackend())
637
.build();
638
```
639
640
## Client Integration
641
642
All backends integrate with the client using the `.backend()` builder method:
643
644
```java
645
import com.anthropic.client.AnthropicClient;
646
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
647
648
// Direct API (default)
649
AnthropicClient directClient = AnthropicOkHttpClient.fromEnv();
650
651
// AWS Bedrock
652
AnthropicClient bedrockClient = AnthropicOkHttpClient.builder()
653
.backend(BedrockBackend.fromEnv())
654
.build();
655
656
// Google Vertex AI
657
AnthropicClient vertexClient = AnthropicOkHttpClient.builder()
658
.backend(VertexBackend.fromEnv())
659
.build();
660
```
661
662
Once configured, the client API is identical regardless of backend:
663
664
```java
665
MessageCreateParams params = MessageCreateParams.builder()
666
.maxTokens(1024L)
667
.addUserMessage("Hello, Claude")
668
.model(Model.CLAUDE_SONNET_4_20250514)
669
.build();
670
671
Message message = client.messages().create(params);
672
```
673
674
## Credential Resolution
675
676
### Automatic Resolution
677
678
Using `fromEnv()` methods provides automatic credential resolution:
679
680
**AWS Bedrock**:
681
- Credentials: AWS default credentials provider chain
682
- Region: AWS default region provider chain
683
- API Key: `AWS_BEARER_TOKEN_BEDROCK` environment variable
684
685
**Google Vertex AI**:
686
- Credentials: Google Application Default Credentials
687
- Region: `CLOUD_ML_REGION` environment variable
688
- Project: `ANTHROPIC_VERTEX_PROJECT_ID` environment variable
689
690
### Manual Resolution
691
692
For more control, resolve credentials independently and pass them to the builder:
693
694
**AWS Bedrock**:
695
```java
696
AwsCredentialsProvider provider = ProfileCredentialsProvider.builder()
697
.profileName("production")
698
.build();
699
700
BedrockBackend backend = BedrockBackend.builder()
701
.awsCredentialsProvider(provider)
702
.region(Region.US_WEST_2)
703
.build();
704
```
705
706
**Google Vertex AI**:
707
```java
708
GoogleCredentials credentials = ServiceAccountCredentials.fromStream(
709
new FileInputStream(keyPath));
710
711
VertexBackend backend = VertexBackend.builder()
712
.googleCredentials(credentials)
713
.region("us-central1")
714
.project(projectId)
715
.build();
716
```
717
718
## Best Practices
719
720
### Security
721
722
**Never hardcode credentials**:
723
```java
724
// DON'T DO THIS
725
AwsCredentials creds = AwsBasicCredentials.create("AKIAIOSFODNN7EXAMPLE", "secret");
726
```
727
728
**Use environment variables or credential providers**:
729
```java
730
// DO THIS
731
AnthropicClient client = AnthropicOkHttpClient.builder()
732
.backend(BedrockBackend.fromEnv())
733
.build();
734
```
735
736
**Store service account keys securely**:
737
- Never commit service account keys to version control
738
- Use secret management services (AWS Secrets Manager, Google Secret Manager)
739
- Rotate credentials regularly
740
- Use minimal IAM permissions
741
742
### Credential Management
743
744
**Reuse credentials providers**:
745
```java
746
// Create once, reuse for multiple backends
747
AwsCredentialsProvider provider = DefaultCredentialsProvider.builder()
748
.asyncCredentialUpdateEnabled(true)
749
.build();
750
751
BedrockBackend backend1 = BedrockBackend.builder()
752
.fromEnv(provider)
753
.build();
754
```
755
756
**Enable credential caching**:
757
```java
758
// Google credentials with refreshed tokens
759
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
760
.createScoped("https://www.googleapis.com/auth/cloud-platform");
761
```
762
763
### Error Handling
764
765
**Handle authentication errors**:
766
```java
767
try {
768
AnthropicClient client = AnthropicOkHttpClient.builder()
769
.backend(BedrockBackend.fromEnv())
770
.build();
771
772
Message message = client.messages().create(params);
773
} catch (UnauthorizedException e) {
774
// Handle invalid credentials
775
System.err.println("Authentication failed: " + e.getMessage());
776
} catch (PermissionDeniedException e) {
777
// Handle insufficient permissions
778
System.err.println("Insufficient permissions: " + e.getMessage());
779
}
780
```
781
782
**Handle region/project errors**:
783
```java
784
try {
785
VertexBackend backend = VertexBackend.fromEnv();
786
} catch (IllegalStateException e) {
787
// Handle missing CLOUD_ML_REGION or ANTHROPIC_VERTEX_PROJECT_ID
788
System.err.println("Configuration error: " + e.getMessage());
789
}
790
```
791
792
### Resource Management
793
794
**Reuse client instances**:
795
```java
796
// Create once, reuse throughout application
797
AnthropicClient client = AnthropicOkHttpClient.builder()
798
.backend(BedrockBackend.fromEnv())
799
.build();
800
801
// Use for multiple requests
802
Message msg1 = client.messages().create(params1);
803
Message msg2 = client.messages().create(params2);
804
```
805
806
**Close clients when done**:
807
```java
808
try (AnthropicClient client = AnthropicOkHttpClient.builder()
809
.backend(VertexBackend.fromEnv())
810
.build()) {
811
812
Message message = client.messages().create(params);
813
}
814
```
815
816
### Testing
817
818
**Use dependency injection for backends**:
819
```java
820
public class MyService {
821
private final AnthropicClient client;
822
823
public MyService(Backend backend) {
824
this.client = AnthropicOkHttpClient.builder()
825
.backend(backend)
826
.build();
827
}
828
}
829
830
// Production
831
MyService prodService = new MyService(BedrockBackend.fromEnv());
832
833
// Testing
834
MyService testService = new MyService(new MockBackend());
835
```
836
837
### Platform Selection
838
839
Choose the appropriate platform based on your needs:
840
841
**Use Direct API when**:
842
- You need all features (batch API, token counting)
843
- You're not already using AWS or Google Cloud
844
- You want the latest features first
845
846
**Use AWS Bedrock when**:
847
- Your infrastructure is on AWS
848
- You need AWS IAM integration
849
- You want unified billing with other AWS services
850
- You need VPC endpoints for private networking
851
852
**Use Google Vertex AI when**:
853
- Your infrastructure is on Google Cloud
854
- You need Google Cloud IAM integration
855
- You want unified billing with other GCP services
856
- You need integration with other Vertex AI features
857
858
### Configuration Management
859
860
**Use configuration classes**:
861
```java
862
public class BackendConfig {
863
public static Backend createBackend(String platform) {
864
switch (platform.toLowerCase()) {
865
case "bedrock":
866
return BedrockBackend.fromEnv();
867
case "vertex":
868
return VertexBackend.fromEnv();
869
case "direct":
870
default:
871
return null; // Uses default direct API
872
}
873
}
874
}
875
876
// Configure via environment variable
877
String platform = System.getenv("CLAUDE_PLATFORM");
878
AnthropicClient client = AnthropicOkHttpClient.builder()
879
.backend(BackendConfig.createBackend(platform))
880
.build();
881
```
882
883
---
884
885
For more information on client configuration and usage patterns, see [Client Setup](client-setup.md).
886