java changedcli-sdks-libraries/sdks/java
Nearest release: v2.1.309, published 3 hours before this site recorded the change. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.
Recorded here
Lines+197added
Lines−186removed
From line
47
where the diff opens
First seen
14 Aug 2026
this site's first read of the page
Recorded edits25to this page, all time
The whole hunk
from line 47, old and new numbered
/
from line 47
4747import com.anthropic.models.messages.MessageCreateParams;
4848import com.anthropic.models.messages.Model;
4949
50// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties
51// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables
50// Configures using the `anthropic.apiKey`, `anthropic.authToken`, and `anthropic.baseUrl` system properties
51// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, and `ANTHROPIC_BASE_URL` environment variables
5252AnthropicClient client = AnthropicOkHttpClient.fromEnv();
5353
5454MessageCreateParams params = MessageCreateParams.builder()
55 .maxTokens(1024L)
56 .addUserMessage("Hello, Claude")
57 .model(Model.CLAUDE_OPUS_5_5)
58 .build();
55 .maxTokens(1024L)
56 .addUserMessage("Hello, Claude")
57 .model(Model.CLAUDE_OPUS_5_5)
58 .build();
5959
6060Message message = client.messages().create(params);
6161```
from line 70
7070import com.anthropic.client.AnthropicClient;
7171import com.anthropic.client.okhttp.AnthropicOkHttpClient;
7272
73// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties
74// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables
73// Configures using the `anthropic.apiKey`, `anthropic.authToken`, and `anthropic.baseUrl` system properties
74// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, and `ANTHROPIC_BASE_URL` environment variables
7575AnthropicClient client = AnthropicOkHttpClient.fromEnv();
7676```
7777
from line 82
8282import com.anthropic.client.okhttp.AnthropicOkHttpClient;
8383
8484AnthropicClient client = AnthropicOkHttpClient.builder()
85 .apiKey("my-anthropic-api-key")
86 .build();
85 .apiKey("my-anthropic-api-key")
86 .build();
8787```
8888
8989Or use a combination of both approaches:
from line 93
9393import com.anthropic.client.okhttp.AnthropicOkHttpClient;
9494
9595AnthropicClient client = AnthropicOkHttpClient.builder()
96 // Configures using system properties or environment variables
97 .fromEnv()
98 .apiKey("my-anthropic-api-key")
99 .build();
96 // Configures using system properties or environment variables
97 .fromEnv()
98 .apiKey("my-anthropic-api-key")
99 .build();
100100```
101101
102102For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) that isn't scoped to a workspace, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK.
from line 123
123123import com.anthropic.client.AnthropicClient;
124124
125125AnthropicClient clientWithOptions = client.withOptions(optionsBuilder -> {
126 optionsBuilder.baseUrl("https://example.com");
127 optionsBuilder.maxRetries(42);
126 optionsBuilder.baseUrl("https://example.com");
127 optionsBuilder.maxRetries(42);
128128});
129129```
130130
from line 144
144144AnthropicClient client = AnthropicOkHttpClient.fromEnv();
145145
146146MessageCreateParams params = MessageCreateParams.builder()
147 .maxTokens(1024L)
148 .addUserMessage("Hello, Claude")
149 .model(Model.CLAUDE_OPUS_5_5)
150 .build();
147 .maxTokens(1024L)
148 .addUserMessage("Hello, Claude")
149 .model(Model.CLAUDE_OPUS_5_5)
150 .build();
151151
152152CompletableFuture<Message> message = client.async().messages().create(params);
153153```
from line 164
164164AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();
165165
166166MessageCreateParams params = MessageCreateParams.builder()
167 .maxTokens(1024L)
168 .addUserMessage("Hello, Claude")
169 .model(Model.CLAUDE_OPUS_5_5)
170 .build();
167 .maxTokens(1024L)
168 .addUserMessage("Hello, Claude")
169 .model(Model.CLAUDE_OPUS_5_5)
170 .build();
171171
172172CompletableFuture<Message> message = client.messages().create(params);
173173```
from line 256
256256import com.anthropic.client.okhttp.AnthropicOkHttpClient;
257257
258258AnthropicClient client = AnthropicOkHttpClient.builder()
259 .fromEnv()
260 .streamHandlerExecutor(Executors.newFixedThreadPool(4))
261 .build();
259 .fromEnv()
260 .streamHandlerExecutor(Executors.newFixedThreadPool(4))
261 .build();
262262```
263263
264264### Streaming with message accumulator
from line 278
278278try (StreamResponse<RawMessageStreamEvent> streamResponse =
279279 client.messages().createStreaming(createParams)) {
280280 streamResponse.stream()
281 .peek(messageAccumulator::accumulate)
282 .flatMap(event -> event.contentBlockDelta().stream())
283 .flatMap(deltaEvent -> deltaEvent.delta().text().stream())
284 .forEach(textDelta -> IO.print(textDelta.text()));
281 .peek(messageAccumulator::accumulate)
282 .flatMap(event -> event.contentBlockDelta().stream())
283 .flatMap(deltaEvent -> deltaEvent.delta().text().stream())
284 .forEach(textDelta -> IO.print(textDelta.text()));
285285}
286286
287287Message message = messageAccumulator.message();
from line 296
296296MessageAccumulator messageAccumulator = MessageAccumulator.create();
297297
298298client.async().messages()
299 .createStreaming(createParams)
300 .subscribe(event -> messageAccumulator.accumulate(event).contentBlockDelta().stream()
301 .flatMap(deltaEvent -> deltaEvent.delta().text().stream())
302 .forEach(textDelta -> IO.print(textDelta.text())))
303 .onCompleteFuture()
304 .join();
299 .createStreaming(createParams)
300 .subscribe(event -> messageAccumulator.accumulate(event).contentBlockDelta().stream()
301 .flatMap(deltaEvent -> deltaEvent.delta().text().stream())
302 .forEach(textDelta -> IO.print(textDelta.text())))
303 .onCompleteFuture()
304 .join();
305305
306306Message message = messageAccumulator.message();
307307```
from line 331
331331import com.fasterxml.jackson.annotation.JsonPropertyDescription;
332332
333333enum Unit {
334 CELSIUS,
335 FAHRENHEIT;
334 CELSIUS,
335 FAHRENHEIT;
336336
337 public String toString() {
338 return switch (this) {
339 case CELSIUS -> "C";
340 case FAHRENHEIT -> "F";
341 };
342 }
337 public String toString() {
338 return switch (this) {
339 case CELSIUS -> "C";
340 case FAHRENHEIT -> "F";
341 };
342 }
343343
344 public double fromKelvin(double temperatureK) {
345 return switch (this) {
346 case CELSIUS -> temperatureK - 273.15;
347 case FAHRENHEIT -> (temperatureK - 273.15) * 1.8 + 32.0;
348 };
349 }
344 public double fromKelvin(double temperatureK) {
345 return switch (this) {
346 case CELSIUS -> temperatureK - 273.15;
347 case FAHRENHEIT -> (temperatureK - 273.15) * 1.8 + 32.0;
348 };
349 }
350350}
351351
352352@JsonClassDescription("Get the weather in a given location")
353353static class GetWeather {
354354
355 @JsonPropertyDescription("The city and state, e.g. San Francisco, CA")
356 public String location;
355 @JsonPropertyDescription("The city and state, e.g. San Francisco, CA")
356 public String location;
357357
358 @JsonPropertyDescription("The unit of temperature")
359 public Unit unit;
358 @JsonPropertyDescription("The unit of temperature")
359 public Unit unit;
360360
361 public Weather execute() {
362 double temperatureK = switch (location) {
363 case "San Francisco, CA" -> 300.0;
364 case "New York, NY" -> 310.0;
365 case "Dallas, TX" -> 305.0;
366 default -> 295;
367 };
368 return new Weather(String.format("%.0f%s", unit.fromKelvin(temperatureK), unit));
369 }
361 public Weather execute() {
362 double temperatureK = switch (location) {
363 case "San Francisco, CA" -> 300.0;
364 case "New York, NY" -> 310.0;
365 case "Dallas, TX" -> 305.0;
366 default -> 295;
367 };
368 return new Weather(String.format("%.0f%s", unit.fromKelvin(temperatureK), unit));
369 }
370370}
371371
372372static class Weather {
373373
374 public String temperature;
374 public String temperature;
375375
376 public Weather(String temperature) {
377 this.temperature = temperature;
378 }
376 public Weather(String temperature) {
377 this.temperature = temperature;
378 }
379379}
380380```
381381
from line 394
394394AnthropicClient client = AnthropicOkHttpClient.fromEnv();
395395
396396MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()
397 .model(Model.CLAUDE_OPUS_5_5)
398 .maxTokens(2048)
399 .addTool(GetWeather.class)
400 .addUserMessage("What's the temperature in New York?");
397 .model(Model.CLAUDE_OPUS_5_5)
398 .maxTokens(2048)
399 .addTool(GetWeather.class)
400 .addUserMessage("What's the temperature in New York?");
401401
402402client.beta().messages().create(createParamsBuilder.build()).content().stream()
403 .flatMap(contentBlock -> contentBlock.toolUse().stream())
404 .forEach(toolUseBlock -> createParamsBuilder
405 // Add a message indicating that the tool use was requested.
406 .addAssistantMessageOfContentBlockParams(
407 List.of(BetaContentBlockParam.ofToolUse(BetaToolUseBlockParam.builder()
408 .name(toolUseBlock.name())
409 .id(toolUseBlock.id())
410 .input(toolUseBlock._input())
411 .build())))
412 // Add a message with the result of the requested tool use.
413 .addUserMessageOfContentBlockParams(
414 List.of(BetaContentBlockParam.ofToolResult(BetaToolResultBlockParam.builder()
415 .toolUseId(toolUseBlock.id())
416 .contentAsJson(callTool(toolUseBlock))
417 .build()))));
403 .flatMap(contentBlock -> contentBlock.toolUse().stream())
404 .forEach(toolUseBlock -> createParamsBuilder
405 // Add a message indicating that the tool use was requested.
406 .addAssistantMessageOfContentBlockParams(
407 List.of(BetaContentBlockParam.ofToolUse(BetaToolUseBlockParam.builder()
408 .name(toolUseBlock.name())
409 .id(toolUseBlock.id())
410 .input(toolUseBlock._input())
411 .build())))
412 // Add a message with the result of the requested tool use.
413 .addUserMessageOfContentBlockParams(
414 List.of(BetaContentBlockParam.ofToolResult(BetaToolResultBlockParam.builder()
415 .toolUseId(toolUseBlock.id())
416 .contentAsJson(callTool(toolUseBlock))
417 .build()))));
418418
419419client.beta().messages().create(createParamsBuilder.build()).content().stream()
420 .flatMap(contentBlock -> contentBlock.text().stream())
421 .forEach(textBlock -> IO.println(textBlock.text()));
420 .flatMap(contentBlock -> contentBlock.text().stream())
421 .forEach(textBlock -> IO.println(textBlock.text()));
422422
423423private static Object callTool(BetaToolUseBlock toolUseBlock) {
424 if (!"get_weather".equals(toolUseBlock.name())) {
425 throw new IllegalArgumentException("Unknown tool: " + toolUseBlock.name());
426 }
424 if (!"get_weather".equals(toolUseBlock.name())) {
425 throw new IllegalArgumentException("Unknown tool: " + toolUseBlock.name());
426 }
427427
428 GetWeather tool = toolUseBlock.input(GetWeather.class);
429 return tool != null ? tool.execute() : new Weather("unknown");
428 GetWeather tool = toolUseBlock.input(GetWeather.class);
429 return tool != null ? tool.execute() : new Weather("unknown");
430430}
431431```
432432
from line 440
440440
441441```java
442442MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()
443 .model(Model.CLAUDE_OPUS_5_5)
444 .maxTokens(2048)
445 .addTool(GetWeather.class, JsonSchemaLocalValidation.NO)
446 .addUserMessage("What's the temperature in New York?");
443 .model(Model.CLAUDE_OPUS_5_5)
444 .maxTokens(2048)
445 .addTool(GetWeather.class, JsonSchemaLocalValidation.NO)
446 .addUserMessage("What's the temperature in New York?");
447447```
448448
449449### Annotating tool classes
from line 470
470470import com.anthropic.models.files.FileUploadParams;
471471
472472FileUploadParams params = FileUploadParams.builder()
473 .file(
474 MultipartField.<InputStream>builder()
475 .value(Files.newInputStream(Paths.get("/path/to/file.pdf")))
476 .contentType("application/pdf")
477 .build()
478 )
479 .build();
473 .file(
474 MultipartField.<InputStream>builder()
475 .value(Files.newInputStream(Paths.get("/path/to/file.pdf")))
476 .contentType("application/pdf")
477 .build()
478 )
479 .build();
480480
481481FileMetadata fileMetadata = client.files().upload(params);
482482```
from line 489
489489import com.anthropic.models.files.FileUploadParams;
490490
491491FileUploadParams params = FileUploadParams.builder()
492 .file(
493 MultipartField.<InputStream>builder()
494 .value(URI.create("https://example.com/path/to/file").toURL().openStream())
495 .filename("document.pdf")
496 .contentType("application/pdf")
497 .build()
498 )
499 .build();
492 .file(
493 MultipartField.<InputStream>builder()
494 .value(URI.create("https://example.com/path/to/file").toURL().openStream())
495 .filename("document.pdf")
496 .contentType("application/pdf")
497 .build()
498 )
499 .build();
500500
501501FileMetadata fileMetadata = client.files().upload(params);
502502```
from line 509
509509import com.anthropic.models.files.FileUploadParams;
510510
511511FileUploadParams params = FileUploadParams.builder()
512 .file(
513 MultipartField.<InputStream>builder()
514 .value(new ByteArrayInputStream("content".getBytes()))
515 .filename("document.txt")
516 .contentType("text/plain")
517 .build()
518 )
519 .build();
512 .file(
513 MultipartField.<InputStream>builder()
514 .value(new ByteArrayInputStream("content".getBytes()))
515 .filename("document.txt")
516 .contentType("text/plain")
517 .build()
518 )
519 .build();
520520
521521FileMetadata fileMetadata = client.files().upload(params);
522522```
from line 637
637637import com.anthropic.client.AnthropicClient;
638638import com.anthropic.client.okhttp.AnthropicOkHttpClient;
639639
640AnthropicClient client = AnthropicOkHttpClient.builder().fromEnv().maxRetries(4).build();
640AnthropicClient client = AnthropicOkHttpClient.builder()
641 .fromEnv()
642 .maxRetries(4)
643 .build();
641644```
642645
643646## Timeouts
from line 671
668671import com.anthropic.models.messages.Message;
669672
670673Message message = client
671 .messages()
672 .create(params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build());
674 .messages()
675 .create(params, RequestOptions.builder()
676 .timeout(Duration.ofSeconds(30))
677 .build());
673678```
674679
675680Or configure the default for all method calls at the client level:
from line 684
679684import com.anthropic.client.okhttp.AnthropicOkHttpClient;
680685
681686AnthropicClient client = AnthropicOkHttpClient.builder()
682 .fromEnv()
683 .timeout(Duration.ofSeconds(30))
684 .build();
687 .fromEnv()
688 .timeout(Duration.ofSeconds(30))
689 .build();
685690```
686691
687692## Long requests
from line 802
797802
798803```java
799804MessageCreateParams params = MessageCreateParams.builder()
800 .maxTokens(1024L)
801 .addUserMessage("Hello, Claude")
802 .model(Model.CLAUDE_OPUS_5_5)
803 .build();
805 .maxTokens(1024L)
806 .addUserMessage("Hello, Claude")
807 .model(Model.CLAUDE_OPUS_5_5)
808 .build();
804809
805810// Create a modified copy using toBuilder()
806MessageCreateParams modified = params.toBuilder().maxTokens(2048L).build();
811MessageCreateParams modified = params.toBuilder()
812 .maxTokens(2048L)
813 .build();
807814```
808815
809816Because each class is immutable, builder modification never affects already built class instances.
from line 830
823830import com.anthropic.models.messages.MessageCreateParams;
824831
825832MessageCreateParams params = MessageCreateParams.builder()
826 .putAdditionalHeader("Secret-Header", "42")
827 .putAdditionalQueryParam("secret_query_param", "42")
828 .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
829 .build();
833 .putAdditionalHeader("Secret-Header", "42")
834 .putAdditionalQueryParam("secret_query_param", "42")
835 .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
836 .build();
830837```
831838
832839These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.
from line 850
843850import com.anthropic.models.messages.Metadata;
844851
845852MessageCreateParams params = MessageCreateParams.builder()
846 .metadata(
847 Metadata.builder().putAdditionalProperty("secretProperty", JsonValue.from("42")).build()
848 )
849 .build();
853 .metadata(
854 Metadata.builder()
855 .putAdditionalProperty("secretProperty", JsonValue.from("42"))
856 .build()
857 )
858 .build();
850859```
851860
852861These properties can be accessed on the nested built object later using the `_additionalProperties()` method.
from line 868
859868import com.anthropic.models.messages.Model;
860869
861870MessageCreateParams params = MessageCreateParams.builder()
862 .maxTokens(JsonValue.from(3.14))
863 .addUserMessage("Hello, Claude")
864 .model(Model.CLAUDE_OPUS_5_5)
865 .build();
871 .maxTokens(JsonValue.from(3.14))
872 .addUserMessage("Hello, Claude")
873 .model(Model.CLAUDE_OPUS_5_5)
874 .build();
866875```
867876
868877### JsonValue creation
from line 911
902911import com.anthropic.models.messages.Model;
903912
904913MessageCreateParams params = MessageCreateParams.builder()
905 .addUserMessage("Hello, world")
906 .model(Model.CLAUDE_OPUS_5_5)
907 .maxTokens(JsonMissing.of())
908 .build();
914 .addUserMessage("Hello, world")
915 .model(Model.CLAUDE_OPUS_5_5)
916 .maxTokens(JsonMissing.of())
917 .build();
909918```
910919
911920### Response properties
from line 925
916925import com.anthropic.core.JsonValue;
917926
918927Map<String, JsonValue> additionalProperties = client
919 .messages()
920 .create(params)
921 ._additionalProperties();
928 .messages()
929 .create(params)
930 ._additionalProperties();
922931
923932JsonValue secretPropertyValue = additionalProperties.get("secretProperty");
924933
from line 962
953962JsonField<StopReason> stopReason = client.messages().create(params)._stopReason();
954963
955964if (stopReason.isMissing()) {
956 // The property is absent from the JSON response
965 // The property is absent from the JSON response
957966} else if (stopReason.isNull()) {
958 // The property was set to literal null
967 // The property was set to literal null
959968} else {
960 // Check if value was provided as a string
961 // Other methods include `asNumber()`, `asBoolean()`, etc.
962 Optional<String> jsonString = stopReason.asString();
969 // Check if value was provided as a string
970 // Other methods include `asNumber()` and `asBoolean()`.
971 Optional<String> jsonString = stopReason.asString();
963972
964 // Try to deserialize into a custom type
965 MyClass myObject = stopReason.asUnknown().orElseThrow().convert(MyClass.class);
973 // Try to deserialize into a custom type
974 MyClass myObject = stopReason.asUnknown().orElseThrow().convert(MyClass.class);
966975}
967976```
968977
from line 993
984993import com.anthropic.models.messages.Message;
985994
986995Message message = client
987 .messages()
988 .create(params, RequestOptions.builder().responseValidation(true).build());
996 .messages()
997 .create(params, RequestOptions.builder()
998 .responseValidation(true)
999 .build());
9891000```
9901001
9911002Or configure the default for all method calls at the client level:
from line 1006
9951006import com.anthropic.client.okhttp.AnthropicOkHttpClient;
9961007
9971008AnthropicClient client = AnthropicOkHttpClient.builder()
998 .fromEnv()
999 .responseValidation(true)
1000 .build();
1009 .fromEnv()
1010 .responseValidation(true)
1011 .build();
10011012```
10021013
10031014## HTTP client customization
from line 1021
10101021import java.net.Proxy;
10111022
10121023AnthropicClient client = AnthropicOkHttpClient.builder()
1013 .fromEnv()
1014 .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https://example.com", 8080)))
1015 .build();
1024 .fromEnv()
1025 .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https://example.com", 8080)))
1026 .build();
10161027```
10171028
10181029### HTTPS / SSL configuration
from line 1037
10261037import com.anthropic.client.okhttp.AnthropicOkHttpClient;
10271038
10281039AnthropicClient client = AnthropicOkHttpClient.builder()
1029 .fromEnv()
1030 .sslSocketFactory(yourSSLSocketFactory)
1031 .trustManager(yourTrustManager)
1032 .hostnameVerifier(yourHostnameVerifier)
1033 .build();
1040 .fromEnv()
1041 .sslSocketFactory(yourSSLSocketFactory)
1042 .trustManager(yourTrustManager)
1043 .hostnameVerifier(yourHostnameVerifier)
1044 .build();
10341045```
10351046
10361047### Custom HTTP client
from line 1115
11041115import com.anthropic.models.messages.Model;
11051116
11061117MessageCreateParams params = MessageCreateParams.builder()
1107 .maxTokens(1024L)
1108 .addUserMessage("Hello, Claude")
1109 .model(Model.CLAUDE_OPUS_5_5)
1110 .build();
1118 .maxTokens(1024L)
1119 .addUserMessage("Hello, Claude")
1120 .model(Model.CLAUDE_OPUS_5_5)
1121 .build();
11111122
11121123HttpResponseFor<Message> message = client.messages().withRawResponse().create(params);
11131124
from line 1201
11901201import com.anthropic.models.messages.MessageCreateParams;
11911202
11921203MessageCreateParams params = MessageCreateParams.builder()
1193 .model("some-new-model") // same as .model(Model.of("some-new-model"))
1194 .maxTokens(1024L)
1195 .addUserMessage("Hello, Claude")
1196 .build();
1204 .model("some-new-model") // same as .model(Model.of("some-new-model"))
1205 .maxTokens(1024L)
1206 .addUserMessage("Hello, Claude")
1207 .build();
11971208```
11981209
11991210Prefer the well-typed constants (for example, `Model.CLAUDE_OPUS_5`) so you get auto-complete and deprecation warnings. The `String` overloads and `of(...)` are primarily for setting the field to an undocumented or not yet supported value while waiting for an SDK release that includes it.
No line in this hunk matches that.