Repository navigation
Expand file tree
/
Copy pathCompletionsConversationAsyncExample.java
More file actions
56 lines (46 loc) · 2.58 KB
/
Copy pathCompletionsConversationAsyncExample.java
File metadata and controls
56 lines (46 loc) · 2.58 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.openai.example;
import static java.util.stream.Collectors.toList;
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.openai.models.chat.completions.ChatCompletionMessage;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public final class CompletionsConversationAsyncExample {
private CompletionsConversationAsyncExample() {}
public static void main(String[] args) {
// Configures using one of:
// - The `OPENAI_API_KEY` environment variable
// - The `OPENAI_BASE_URL` and `AZURE_OPENAI_KEY` environment variables
OpenAIClientAsync client = OpenAIOkHttpClientAsync.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.
ChatCompletionCreateParams.Builder createParamsBuilder = ChatCompletionCreateParams.builder()
.model(ChatModel.GPT_3_5_TURBO)
.maxCompletionTokens(2048)
.addDeveloperMessage("Make sure you mention Stainless!")
.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.chat().completions().create(createParamsBuilder.build()))
.thenAccept(completion -> {
List<ChatCompletionMessage> messages = completion.choices().stream()
.map(ChatCompletion.Choice::message)
.collect(toList());
messages.stream()
.flatMap(message -> message.content().stream())
.forEach(System.out::println);
System.out.println("\n-----------------------------------\n");
messages.forEach(createParamsBuilder::addMessage);
createParamsBuilder
.addDeveloperMessage("Be as snarky as possible when replying!" + "!".repeat(index))
.addUserMessage("But why?" + "?".repeat(index));
});
}
future.join();
}
}