Skip to content

Commit 9e6ef38

Browse files
committed
docs: async example updates
1 parent 0f7afbe commit 9e6ef38

File tree

2 files changed

+114
-6
lines changed

2 files changed

+114
-6
lines changed
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package com.openai.example;
2+
3+
import com.openai.client.OpenAIClientAsync;
4+
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
5+
import com.openai.models.*;
6+
import java.util.concurrent.CompletableFuture;
7+
8+
public final class AssistantAsyncExample {
9+
private AssistantAsyncExample() {}
10+
11+
public static void main(String[] args) {
12+
// Configures using one of:
13+
// - The `OPENAI_API_KEY` environment variable
14+
// - The `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_KEY` environment variables
15+
OpenAIClientAsync client = OpenAIOkHttpClientAsync.fromEnv();
16+
17+
CompletableFuture<Assistant> assistantFuture = client.beta()
18+
.assistants()
19+
.create(BetaAssistantCreateParams.builder()
20+
.name("Math Tutor")
21+
.instructions("You are a personal math tutor. Write and run code to answer math questions.")
22+
.addTool(CodeInterpreterTool.builder().build())
23+
.model(ChatModel.GPT_4O_MINI)
24+
.build());
25+
CompletableFuture<String> threadIdFuture = client.beta()
26+
.threads()
27+
.create(BetaThreadCreateParams.builder().build())
28+
.thenComposeAsync(thread -> client.beta()
29+
.threads()
30+
.messages()
31+
.create(BetaThreadMessageCreateParams.builder()
32+
.threadId(thread.id())
33+
.role(BetaThreadMessageCreateParams.Role.USER)
34+
.content("I need to solve the equation `3x + 11 = 14`. Can you help me?")
35+
.build()))
36+
.thenApply(Message::threadId);
37+
38+
CompletableFuture<Run> runFuture = CompletableFuture.allOf(assistantFuture, threadIdFuture)
39+
.thenComposeAsync(unused -> client.beta()
40+
.threads()
41+
.runs()
42+
.create(BetaThreadRunCreateParams.builder()
43+
.threadId(threadIdFuture.join())
44+
.assistantId(assistantFuture.join().id())
45+
.instructions("Please address the user as Jane Doe. The user has a premium account.")
46+
.build()));
47+
CompletableFuture<Run> polledRunFuture = runFuture.thenComposeAsync(run -> pollRun(client, run));
48+
49+
polledRunFuture
50+
.thenComposeAsync(run -> {
51+
if (!run.status().equals(RunStatus.COMPLETED)) {
52+
return CompletableFuture.completedFuture(null);
53+
}
54+
55+
return listThreadMessages(client, run.threadId())
56+
.thenComposeAsync(unused -> client.beta()
57+
.assistants()
58+
.delete(BetaAssistantDeleteParams.builder()
59+
.assistantId(assistantFuture.join().id())
60+
.build()))
61+
.thenAccept(assistantDeleted ->
62+
System.out.println("Assistant deleted: " + assistantDeleted.deleted()));
63+
})
64+
.join();
65+
}
66+
67+
private static CompletableFuture<Run> pollRun(OpenAIClientAsync client, Run run) {
68+
if (!run.status().equals(RunStatus.QUEUED) && !run.status().equals(RunStatus.IN_PROGRESS)) {
69+
System.out.println("Run completed with status: " + run.status() + "\n");
70+
return CompletableFuture.completedFuture(run);
71+
}
72+
73+
System.out.println("Polling run...");
74+
try {
75+
java.lang.Thread.sleep(500);
76+
} catch (InterruptedException e) {
77+
throw new RuntimeException(e);
78+
}
79+
80+
return client.beta()
81+
.threads()
82+
.runs()
83+
.retrieve(BetaThreadRunRetrieveParams.builder()
84+
.threadId(run.threadId())
85+
.runId(run.id())
86+
.build())
87+
.thenComposeAsync(newRun -> pollRun(client, newRun));
88+
}
89+
90+
private static CompletableFuture<Void> listThreadMessages(OpenAIClientAsync client, String threadId) {
91+
CompletableFuture<BetaThreadMessageListPageAsync> pageFuture = client.beta()
92+
.threads()
93+
.messages()
94+
.list(BetaThreadMessageListParams.builder()
95+
.threadId(threadId)
96+
.order(BetaThreadMessageListParams.Order.ASC)
97+
.build());
98+
return pageFuture.thenComposeAsync(page -> page.autoPager()
99+
.forEach(
100+
currentMessage -> {
101+
System.out.println(currentMessage.role().toString().toUpperCase());
102+
currentMessage.content().stream()
103+
.flatMap(content -> content.text().stream())
104+
.forEach(textBlock ->
105+
System.out.println(textBlock.text().value()));
106+
System.out.println();
107+
108+
// Keep iterating
109+
return true;
110+
},
111+
pageFuture.defaultExecutor()));
112+
}
113+
}

openai-java-example/src/main/java/com/openai/example/CompletionsConversationAsyncExample.java

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
import com.openai.models.*;
88
import java.util.List;
99
import java.util.concurrent.CompletableFuture;
10-
import java.util.concurrent.ExecutorService;
11-
import java.util.concurrent.Executors;
1210

1311
public final class CompletionsConversationAsyncExample {
1412
private CompletionsConversationAsyncExample() {}
@@ -31,13 +29,11 @@ public static void main(String[] args) {
3129
.content("Tell me a story about building the best SDK!")
3230
.build());
3331

34-
ExecutorService executor = Executors.newCachedThreadPool();
35-
3632
CompletableFuture<Void> future = CompletableFuture.completedFuture(null);
3733
for (int i = 0; i < 4; i++) {
3834
final int index = i;
3935
future = future.thenComposeAsync(
40-
unused -> client.chat().completions().create(createParamsBuilder.build()), executor)
36+
unused -> client.chat().completions().create(createParamsBuilder.build()))
4137
.thenAccept(completion -> {
4238
List<ChatCompletionMessage> messages = completion.choices().stream()
4339
.map(ChatCompletion.Choice::message)
@@ -61,6 +57,5 @@ public static void main(String[] args) {
6157
}
6258

6359
future.join();
64-
executor.shutdown();
6560
}
6661
}

0 commit comments

Comments
 (0)