Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: many more examples #84

Merged
merged 2 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ This library requires Java 8 or later.

## Usage

See the [`anthropic-java-example`](anthropic-java-example/src/main/java/com/anthropic/example) directory for complete and runnable examples.

### Configure the client

Use `AnthropicOkHttpClient.builder()` to configure the client.
Expand Down
4 changes: 2 additions & 2 deletions anthropic-java-example/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ dependencies {

tasks.withType<JavaCompile>().configureEach {
// Allow using more modern APIs, like `List.of` and `Map.of`, in examples.
options.release.set(9)
options.release.set(11)
}

application {
mainClass = "com.anthropic.example.Main"
mainClass = "com.anthropic.example.MessagesExample"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package com.anthropic.example;

import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.core.http.AsyncStreamResponse;
import com.anthropic.models.*;
import com.anthropic.models.MessageBatch.ProcessingStatus;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

public final class BatchAsyncExample {
private BatchAsyncExample() {}

public static void main(String[] args) throws Exception {
// Configures using the `ANTHROPIC_API_KEY` environment variable
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();

MessageBatchCreateParams createParams = MessageBatchCreateParams.builder()
.addRequest(MessageBatchCreateParams.Request.builder()
.customId("best-sdk")
.params(MessageBatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("Tell me a story about building the best SDK!")
.build())
.build())
.build())
.addRequest(MessageBatchCreateParams.Request.builder()
.customId("sdk-company")
.params(MessageBatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("Which company made of metal generates SDKs?")
.build())
.build())
.build())
.build();

client.messages()
.batches()
.create(createParams)
.thenComposeAsync(batch -> pollBatch(client, batch))
.thenComposeAsync(batch -> {
System.out.println();

CompletableFuture<MessageBatch> batchFuture = new CompletableFuture<>();

// TODO: Update this example once we support expose an `onCompleteFuture()` method.
client.messages()
.batches()
.resultsStreaming(MessageBatchResultsParams.builder()
.messageBatchId(batch.id())
.build())
.subscribe(new AsyncStreamResponse.Handler<>() {
@Override
public void onNext(MessageBatchIndividualResponse response) {
System.out.println(response.customId());
Message message =
response.result().asSucceeded().message();
message.content().stream()
.flatMap(contentBlock -> contentBlock.text().stream())
.forEach(textBlock -> System.out.println(textBlock.text()));
}

@Override
public void onComplete(Optional<Throwable> error) {
error.ifPresentOrElse(
batchFuture::completeExceptionally, () -> batchFuture.complete(batch));
}
});
return batchFuture;
})
.thenComposeAsync(batch -> client.messages()
.batches()
.delete(MessageBatchDeleteParams.builder()
.messageBatchId(batch.id())
.build()))
.thenAccept(deletedMessageBatch -> System.out.println("Batch deleted: " + deletedMessageBatch.id()))
.join();
}

private static CompletableFuture<MessageBatch> pollBatch(AnthropicClientAsync client, MessageBatch batch) {
if (!batch.processingStatus().equals(ProcessingStatus.IN_PROGRESS)) {
return CompletableFuture.completedFuture(batch);
}

System.out.println("Polling batch...");
try {
java.lang.Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

return client.messages()
.batches()
.retrieve(MessageBatchRetrieveParams.builder()
.messageBatchId(batch.id())
.build())
.thenComposeAsync(newBatch -> pollBatch(client, newBatch));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.anthropic.example;

import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.*;
import com.anthropic.models.MessageBatch.ProcessingStatus;

public final class BatchExample {
private BatchExample() {}

public static void main(String[] args) throws Exception {
// Configures using the `ANTHROPIC_API_KEY` environment variable
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

MessageBatchCreateParams createParams = MessageBatchCreateParams.builder()
.addRequest(MessageBatchCreateParams.Request.builder()
.customId("best-sdk")
.params(MessageBatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("Tell me a story about building the best SDK!")
.build())
.build())
.build())
.addRequest(MessageBatchCreateParams.Request.builder()
.customId("sdk-company")
.params(MessageBatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("Which company made of metal generates SDKs?")
.build())
.build())
.build())
.build();

MessageBatch batch = client.messages().batches().create(createParams);
while (batch.processingStatus().equals(ProcessingStatus.IN_PROGRESS)) {
System.out.println("Polling batch...");
Thread.sleep(2000);
batch = client.messages()
.batches()
.retrieve(MessageBatchRetrieveParams.builder()
.messageBatchId(batch.id())
.build());
}
System.out.println();

try (StreamResponse<MessageBatchIndividualResponse> streamResponse = client.messages()
.batches()
.resultsStreaming(MessageBatchResultsParams.builder()
.messageBatchId(batch.id())
.build())) {
streamResponse.stream().forEach(response -> {
System.out.println(response.customId());
Message message = response.result().asSucceeded().message();
message.content().stream()
.flatMap(contentBlock -> contentBlock.text().stream())
.forEach(textBlock -> System.out.println(textBlock.text()));
});
}
System.out.println();

DeletedMessageBatch deletedMessageBatch = client.messages()
.batches()
.delete(MessageBatchDeleteParams.builder()
.messageBatchId(batch.id())
.build());
System.out.println("Batch deleted: " + deletedMessageBatch.id());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.anthropic.example;

import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.models.MessageCreateParams;
import com.anthropic.models.MessageParam;
import com.anthropic.models.MessageParam.Role;
import com.anthropic.models.Model;

public final class MessagesAsyncExample {
private MessagesAsyncExample() {}

public static void main(String[] args) {
// Configures using the `ANTHROPIC_API_KEY` environment variable
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();

MessageCreateParams createParams = MessageCreateParams.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(Role.USER)
.content("Tell me a story about building the best SDK!")
.build())
.build();

client.messages()
.create(createParams)
.thenAccept(message -> message.content().stream()
.flatMap(contentBlock -> contentBlock.text().stream())
.forEach(textBlock -> System.out.println(textBlock.text())))
.join();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.anthropic.example;

import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.models.MessageCreateParams;
import com.anthropic.models.MessageParam;
import com.anthropic.models.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_3_5_SONNET_LATEST)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("Tell me a story about building the best SDK!")
.build());

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)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("But why?" + "?".repeat(index))
.build());
});
}

future.join();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,28 @@

import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.*;
import com.anthropic.models.Message;
import com.anthropic.models.MessageCreateParams;
import com.anthropic.models.MessageParam;
import com.anthropic.models.Model;

public final class Main {
private Main() {}
public final class MessagesConversationExample {
private MessagesConversationExample() {}

public static void main(String[] args) {
// Configures using the `ANTHROPIC_API_KEY` environment variable
AnthropicClient client = AnthropicOkHttpClient.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_3_5_SONNET_LATEST)
.maxTokens(1000)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content(MessageParam.Content.ofString("Tell me a story about building the best SDK!"))
.content("Tell me a story about building the best SDK!")
.build());

// Having a conversation in a loop
for (int i = 0; i < 4; i++) {
Message message = client.messages().create(createParamsBuilder.build());

Expand All @@ -29,22 +34,11 @@ public static void main(String[] args) {
System.out.println("\n-----------------------------------\n");

createParamsBuilder
.addMessage(message.toParam())
.addMessage(message)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content(MessageParam.Content.ofString("But why???"))
.content("But why?" + "?".repeat(i))
.build());
}

// Streaming example
try (StreamResponse<RawMessageStreamEvent> streamResponse =
client.messages().createStreaming(createParamsBuilder.build())) {
streamResponse.stream()
.flatMap(event -> event.contentBlockDelta().stream())
.flatMap(deltaEvent -> deltaEvent.delta().text().stream())
.forEach(textDelta -> System.out.print(textDelta.text()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.anthropic.example;

import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.MessageCreateParams;
import com.anthropic.models.MessageParam;
import com.anthropic.models.MessageParam.Role;
import com.anthropic.models.Model;

public final class MessagesExample {
private MessagesExample() {}

public static void main(String[] args) {
// Configures using the `ANTHROPIC_API_KEY` environment variable
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

MessageCreateParams createParams = MessageCreateParams.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(2048)
.addMessage(MessageParam.builder()
.role(Role.USER)
.content("Tell me a story about building the best SDK!")
.build())
.build();

client.messages().create(createParams).content().stream()
.flatMap(contentBlock -> contentBlock.text().stream())
.forEach(textBlock -> System.out.println(textBlock.text()));
}
}
Loading
Loading