Skip to content

Commit ecb7f6d

Browse files
sodracbcardos
and
bcardos
authored
BAEL-9060 - OpenAI API Client in Java (#18327)
* BAEL-9060 - OpenAI API Client in Java - update pom - fix dependencies and lib conflicts - add code example for the article * BAEL-9060 - update pom * BAEL-9060 - update pom format * BAEL-9060 - update pom * BAEL-9060 - update package name * BAEL-9060 update xml formatting --------- Co-authored-by: bcardos <[email protected]>
1 parent 1ccaa17 commit ecb7f6d

File tree

7 files changed

+287
-6
lines changed

7 files changed

+287
-6
lines changed

libraries-ai/libs/h2o-genmodel.jar

-4.81 MB
Binary file not shown.

libraries-ai/pom.xml

+40-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<project xmlns="http://maven.apache.org/POM/4.0.0"
3-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
53
<modelVersion>4.0.0</modelVersion>
64
<artifactId>libraries-ai</artifactId>
75
<name>libraries-ai</name>
@@ -24,8 +22,6 @@
2422
<groupId>ai.h2o</groupId>
2523
<artifactId>h2o-genmodel</artifactId>
2624
<version>${h2o-genmodel.version}</version>
27-
<scope>system</scope>
28-
<systemPath>${project.basedir}/libs/h2o-genmodel.jar</systemPath>
2925
</dependency>
3026
<dependency>
3127
<groupId>edu.stanford.nlp</groupId>
@@ -51,11 +47,48 @@
5147
<groupId>com.theokanning.openai-gpt3-java</groupId>
5248
<artifactId>client</artifactId>
5349
<version>${theokanning.gpt}</version>
50+
<exclusions>
51+
<exclusion>
52+
<groupId>com.squareup.okhttp3</groupId>
53+
<artifactId>okhttp</artifactId>
54+
</exclusion>
55+
<exclusion>
56+
<groupId>com.fasterxml.jackson.core</groupId>
57+
<artifactId>jackson-annotations</artifactId>
58+
</exclusion>
59+
<exclusion>
60+
<groupId>com.fasterxml.jackson.core</groupId>
61+
<artifactId>jackson-core</artifactId>
62+
</exclusion>
63+
<exclusion>
64+
<groupId>com.fasterxml.jackson.core</groupId>
65+
<artifactId>jackson-databind</artifactId>
66+
</exclusion>
67+
</exclusions>
5468
</dependency>
5569
<dependency>
5670
<groupId>com.theokanning.openai-gpt3-java</groupId>
5771
<artifactId>service</artifactId>
5872
<version>${theokanning.gpt}</version>
73+
<exclusions>
74+
<exclusion>
75+
<groupId>com.fasterxml.jackson.core</groupId>
76+
<artifactId>jackson-annotations</artifactId>
77+
</exclusion>
78+
<exclusion>
79+
<groupId>com.fasterxml.jackson.core</groupId>
80+
<artifactId>jackson-core</artifactId>
81+
</exclusion>
82+
<exclusion>
83+
<groupId>com.fasterxml.jackson.core</groupId>
84+
<artifactId>jackson-databind</artifactId>
85+
</exclusion>
86+
</exclusions>
87+
</dependency>
88+
<dependency>
89+
<groupId>com.openai</groupId>
90+
<artifactId>openai-java</artifactId>
91+
<version>${openai.version}</version>
5992
</dependency>
6093
</dependencies>
6194

@@ -64,7 +97,8 @@
6497
<opennlp-tools.version>2.1.1</opennlp-tools.version>
6598
<neuroph.version>2.92</neuroph.version>
6699
<theokanning.gpt>0.18.2</theokanning.gpt>
67-
<h2o-genmodel.version>1.0</h2o-genmodel.version>
100+
<h2o-genmodel.version>3.46.0.6</h2o-genmodel.version>
101+
<openai.version>0.22.0</openai.version>
68102
</properties>
69103

70104
</project>

libraries-ai/src/main/java/baeldungassistant/BaeldungLearningAssistant.java

+1
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ public static void main(String[] args) {
5858
System.out.print("Anything else?\n");
5959
String nextLine = scanner.nextLine();
6060
if (nextLine.equalsIgnoreCase("exit")) {
61+
scanner.close();
6162
System.exit(0);
6263
}
6364
messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package com.baeldung.openai;
2+
3+
import java.util.Scanner;
4+
5+
import com.openai.client.OpenAIClient;
6+
import com.openai.client.okhttp.OpenAIOkHttpClient;
7+
import com.openai.models.*;
8+
import com.openai.models.Thread;
9+
10+
public class BaeldungOpenAiAssistant {
11+
12+
private static final String ASSISTANT_NAME = "Baeldung Tutor";
13+
14+
public static void main(String[] args) throws InterruptedException {
15+
16+
Scanner scanner = new Scanner(System.in);
17+
18+
System.out.println(Consts.INITIAL_MESSAGE);
19+
20+
String userMessage = scanner.next();
21+
22+
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
23+
24+
Assistant assistant = client.beta()
25+
.assistants()
26+
.create(BetaAssistantCreateParams.builder()
27+
.name(ASSISTANT_NAME)
28+
.instructions(Consts.ASSISTANT_INSTRUCTION)
29+
.model(ChatModel.GPT_4O_MINI)
30+
.build());
31+
32+
Thread thread =
33+
client.beta()
34+
.threads()
35+
.create(BetaThreadCreateParams.builder()
36+
.build());
37+
38+
client.beta()
39+
.threads()
40+
.messages()
41+
.create(BetaThreadMessageCreateParams.builder()
42+
.threadId(thread.id())
43+
.role(BetaThreadMessageCreateParams.Role.USER)
44+
.content(userMessage)
45+
.build());
46+
47+
Run run = client.beta()
48+
.threads()
49+
.runs()
50+
.create(BetaThreadRunCreateParams.builder()
51+
.threadId(thread.id())
52+
.assistantId(assistant.id())
53+
.instructions(Consts.DEVELOPER_MESSAGE)
54+
.build());
55+
56+
while (run.status()
57+
.equals(RunStatus.QUEUED)
58+
|| run.status()
59+
.equals(RunStatus.IN_PROGRESS)) {
60+
System.out.println("Polling run...");
61+
java.lang.Thread.sleep(500);
62+
run = client.beta()
63+
.threads()
64+
.runs()
65+
.retrieve(BetaThreadRunRetrieveParams.builder()
66+
.threadId(thread.id())
67+
.runId(run.id())
68+
.build());
69+
}
70+
71+
System.out.println("Run completed with status: " + run.status() + "\n");
72+
73+
if (!run.status()
74+
.equals(RunStatus.COMPLETED)) {
75+
scanner.close();
76+
return;
77+
}
78+
79+
BetaThreadMessageListPage page = client.beta()
80+
.threads()
81+
.messages()
82+
.list(BetaThreadMessageListParams.builder()
83+
.threadId(thread.id())
84+
.order(BetaThreadMessageListParams.Order.ASC)
85+
.build());
86+
87+
page.autoPager()
88+
.stream()
89+
.forEach(currentMessage -> {
90+
System.out.println(currentMessage.role()
91+
.toString()
92+
.toUpperCase());
93+
currentMessage.content()
94+
.stream()
95+
.flatMap(content -> content.text()
96+
.stream())
97+
.forEach(textBlock -> System.out.println(textBlock.text()
98+
.value()));
99+
System.out.println();
100+
});
101+
102+
AssistantDeleted assistantDeleted = client.beta()
103+
.assistants()
104+
.delete(BetaAssistantDeleteParams.builder()
105+
.assistantId(assistant.id())
106+
.build());
107+
108+
System.out.println("Assistant deleted: " + assistantDeleted.deleted());
109+
110+
scanner.close();
111+
}
112+
113+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.baeldung.openai;
2+
3+
import java.util.Scanner;
4+
5+
import com.openai.client.OpenAIClient;
6+
import com.openai.client.okhttp.OpenAIOkHttpClient;
7+
import com.openai.models.ChatCompletionCreateParams;
8+
import com.openai.models.ChatCompletionCreateParams.Builder;
9+
import com.openai.models.ChatModel;
10+
11+
public class BaeldungOpenAiCompletion {
12+
13+
public static void main(String[] args) {
14+
15+
Scanner scanner = new Scanner(System.in);
16+
17+
System.out.println(Consts.INITIAL_MESSAGE);
18+
19+
String userMessage = scanner.next();
20+
21+
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
22+
23+
Builder createParams = ChatCompletionCreateParams.builder()
24+
.model(ChatModel.GPT_4O_MINI)
25+
.addDeveloperMessage(Consts.DEVELOPER_MESSAGE)
26+
.addUserMessage(userMessage);
27+
28+
client.chat()
29+
.completions()
30+
.create(createParams.build())
31+
.choices()
32+
.stream()
33+
.flatMap(choice -> choice.message()
34+
.content()
35+
.stream())
36+
.forEach(System.out::println);
37+
38+
scanner.close();
39+
40+
}
41+
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.baeldung.openai;
2+
3+
import java.util.List;
4+
import java.util.Scanner;
5+
6+
import com.openai.client.OpenAIClient;
7+
import com.openai.client.okhttp.OpenAIOkHttpClient;
8+
import com.openai.models.ChatCompletion;
9+
import com.openai.models.ChatCompletionCreateParams;
10+
import com.openai.models.ChatCompletionCreateParams.Builder;
11+
import com.openai.models.ChatCompletionMessage;
12+
import com.openai.models.ChatModel;
13+
14+
public class BaeldungOpenAiConversation {
15+
16+
public static void main(String[] args) {
17+
18+
Scanner scanner = new Scanner(System.in);
19+
20+
System.out.println(Consts.INITIAL_MESSAGE);
21+
22+
String userMessage = scanner.next();
23+
24+
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
25+
26+
Builder createParamsBuilder = ChatCompletionCreateParams.builder()
27+
.model(ChatModel.GPT_4O_MINI)
28+
.maxCompletionTokens(2048)
29+
.addDeveloperMessage(Consts.DEVELOPER_MESSAGE)
30+
.addUserMessage(userMessage);
31+
32+
do {
33+
34+
List<ChatCompletionMessage> messages = client.chat()
35+
.completions()
36+
.create(createParamsBuilder.build())
37+
.choices()
38+
.stream()
39+
.map(ChatCompletion.Choice::message)
40+
.toList();
41+
42+
messages.stream()
43+
.flatMap(message -> message.content()
44+
.stream())
45+
.forEach(System.out::println);
46+
47+
System.out.println("-----------------------------------");
48+
System.out.println(Consts.AI_MESSAGE);
49+
50+
String userMessageConversation = scanner.next();
51+
52+
if ("exit".equalsIgnoreCase(userMessageConversation)) {
53+
scanner.close();
54+
return;
55+
}
56+
57+
messages.forEach(createParamsBuilder::addMessage);
58+
createParamsBuilder.addDeveloperMessage(Consts.DEVELOPER_MESSAGE_CONVERSATION)
59+
.addUserMessage(userMessageConversation);
60+
61+
} while (true);
62+
63+
}
64+
65+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.openai;
2+
3+
public class Consts {
4+
5+
private Consts() {
6+
}
7+
8+
static final String INITIAL_MESSAGE = "Hello! What do you want to learn?";
9+
10+
static final String DEVELOPER_MESSAGE = "You're helping me to create a curriculum"
11+
+ "to learn programming."
12+
+ "I want to use Baedlung website as the base."
13+
+ "I will tell you the topic,"
14+
+ "and you should return me the list of articles"
15+
+ "and tutorials with links."
16+
+ "Order the articles from beginner to more advanced,"
17+
+ "so I can learn them one-by-one."
18+
+ "Use only the articles from www.baeldung.com.";
19+
20+
static final String DEVELOPER_MESSAGE_CONVERSATION = "Continue providing help following the same rules as before.";
21+
22+
static final String ASSISTANT_INSTRUCTION = "You're a personal programming tutor specialized in research online learning courses.";
23+
24+
static final String AI_MESSAGE = "Anything else you would like to know? Otherwise type EXIT to stop the program.";
25+
26+
}

0 commit comments

Comments
 (0)