forked from anthropics/anthropic-sdk-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessagesConversationAsyncExample.java
More file actions
40 lines (32 loc) · 1.81 KB
/
Copy pathMessagesConversationAsyncExample.java
File metadata and controls
40 lines (32 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.anthropic.example;
import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import java.util.concurrent.CompletableFuture;
public final class MessagesConversationAsyncExample {
private MessagesConversationAsyncExample() {}
public static void main(String[] args) {
// Configures using the `ANTHROPIC_API_KEY` environment variable
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();
// Use a builder so that we can append more messages to it below.
// Each time we call .build()` we get an immutable object that's unaffected by future mutations of the builder.
MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()
.model(Model.CLAUDE_SONNET_4_20250514)
.maxTokens(2048)
.addUserMessage("Tell me a story about building the best SDK!");
CompletableFuture<Void> future = CompletableFuture.completedFuture(null);
for (int i = 0; i < 4; i++) {
final int index = i;
future = future.thenComposeAsync(unused -> client.messages().create(createParamsBuilder.build()))
.thenAccept(message -> {
message.content().stream()
.flatMap(contentBlock -> contentBlock.text().stream())
.forEach(textBlock -> System.out.println(textBlock.text()));
System.out.println("\n-----------------------------------\n");
createParamsBuilder.addMessage(message).addUserMessage("But why?" + "?".repeat(index));
});
}
future.join();
}
}