-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenAIAPIController.java
More file actions
174 lines (159 loc) · 7.1 KB
/
OpenAIAPIController.java
File metadata and controls
174 lines (159 loc) · 7.1 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package com.UoB.AILearningTool;
import com.UoB.AILearningTool.model.ChatEntity;
import org.json.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springframework.stereotype.Service;
@Service
public class OpenAIAPIController {
private final Logger log = LoggerFactory.getLogger(OpenAIAPIController.class);
private final OpenAIAuthenticator authenticator;
public OpenAIAPIController() {
this.authenticator = new OpenAIAuthenticator();
}
// Creates a new empty thread
public String createThread() {
HttpRequest request = HttpRequest
.newBuilder(URI.create("https://api.openai.com/v1/threads"))
.headers("Content-Type", "application/json",
"OpenAI-Beta", "assistants=v2",
"Authorization", "Bearer " + authenticator.getBearerToken())
.POST(HttpRequest.BodyPublishers.noBody())
.build();
try {
HttpResponse<String> response = HttpClient
.newBuilder()
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
if (statusCode == 200) {
log.info("New OpenAI thread created. {}", new JSONObject(response.body()).getString("id"));
return new JSONObject(response.body()).getString("id");
} else {
// If OpenAI API request returned a status code other than 200, return error 500 and error message.
log.warn("Unable to create OpenAI thread., {}", statusCode);
return null;
}
} catch (Exception e) {
log.error("Exception {}\n", e.toString());
return null;
}
}
// Run OpenAI thread.
public int runThread(String threadID) {
JSONObject runRequestBody = new JSONObject();
runRequestBody.put("assistant_id", "asst_bVvnON3FADuXiLKbnihGY1iH");
HttpRequest runRequest = HttpRequest
.newBuilder(URI.create("https://api.openai.com/v1/threads/" + threadID + "/runs"))
.headers("Content-Type", "application/json",
"Authorization", "Bearer " + authenticator.getBearerToken(),
"OpenAI-Beta", "assistants=v2")
.POST(HttpRequest.BodyPublishers.ofString(runRequestBody.toString()))
.build();
try {
HttpResponse<String> runResponse = HttpClient
.newBuilder()
.build()
.send(runRequest, HttpResponse.BodyHandlers.ofString());
if (runResponse.statusCode() == 200) {
log.info("Thread run initialised.");
return 200;
} else {
log.warn("Unable to run a thread.");
return runResponse.statusCode();
}
} catch (Exception e) {
log.error("Exception {}\n", e.toString());
return 500;
}
}
// Check if a run is in progress for a thread
public boolean isLocked(ChatEntity chat) {
HttpRequest listMessagesRequest = HttpRequest
.newBuilder(URI.create("https://api.openai.com/v1/threads/" + chat.getThreadID() + "/runs"))
.headers("Content-Type", "application/json",
"Authorization", "Bearer " + authenticator.getBearerToken(),
"OpenAI-Beta", "assistants=v2")
.GET()
.build();
try {
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(listMessagesRequest, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
String status = new JSONObject(response.body()).getJSONArray("data").getJSONObject(0).getString("status");
return !status.equals("completed");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return false;
}
// Receive the latest message from the thread
public WatsonxResponse getLastThreadMessage(String threadID) {
String requestURL = "https://api.openai.com/v1/threads/" + threadID + "/messages?order=desc&limit=1";
HttpRequest listMessagesRequest = HttpRequest
.newBuilder(URI.create(requestURL))
.headers("Content-Type", "application/json",
"Authorization", "Bearer " + authenticator.getBearerToken(),
"OpenAI-Beta", "assistants=v2")
.GET()
.build();
try {
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(listMessagesRequest, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return new WatsonxResponse(
200,
new JSONObject(response.body())
.getJSONArray("data")
.getJSONObject(0)
.getJSONArray("content")
.getJSONObject(0)
.getJSONObject("text")
.getString("value")
);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return new WatsonxResponse(404, "Unable to get last thread message.");
}
// Add a message to an OpenAI thread.
public Integer sendUserMessage(ChatEntity chat, String message) {
// Creating a request body
JSONObject newMessage = new JSONObject();
newMessage.put("role", "user");
newMessage.put("content", message);
// Create HTTP request for OpenAI with API key in header and message history in request body.
HttpRequest request = HttpRequest
.newBuilder(URI.create("https://api.openai.com/v1/threads/" + chat.getThreadID() + "/messages"))
.headers("Content-Type", "application/json",
"Authorization", "Bearer " + authenticator.getBearerToken(),
"OpenAI-Beta", "assistants=v2")
.POST(HttpRequest.BodyPublishers.ofString(newMessage.toString()))
.build();
// Try sending an HTTPS request to OpenAI API.
try {
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
if (statusCode == 200) {
log.info("200 OpenAI message has been created.");
return 200;
} else {
return 412;
}
} catch (Exception e) {
log.error("Exception {}\nHTTP status code: {}", e, 500);
return 500;
}
}
}