-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathopenai_request.cpp
366 lines (313 loc) · 10.3 KB
/
openai_request.cpp
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QHttpMultiPart>
#include <QHttpPart>
#include "openai_request.hpp"
OpenAIRequest::OpenAIRequest(QObject *parent)
: QObject(parent)
, m_networkAccessManager(new QNetworkAccessManager(this))
, m_accessToken("")
, m_model("")
, m_prompt("")
, m_filePath("")
, m_generatedText("")
, m_errorString("")
, m_status(RequestStatus::Idle)
, m_maxTokens(100)
, m_temperature(0.3)
, m_topP(1.0)
, m_frequencyPenalty(0.0)
, m_presencePenalty(0.0)
{
connect(this, &OpenAIRequest::requestFinished, this, [this](const QString& generatedText) {
m_generatedText = generatedText;
emit generatedTextChanged();
m_status = RequestStatus::Success;
emit statusChanged();
});
connect(this, &OpenAIRequest::requestError, this, [this](const QString& errorString) {
m_errorString = errorString;
emit errorStringChanged();
m_status = RequestStatus::Error;
emit statusChanged();
});
}
OpenAIRequest::~OpenAIRequest()
{
for (OpenAIMessage *message : m_messages) {
message->deleteLater();
}
m_messages.clear();
}
void OpenAIRequest::execute()
{
if (m_model.startsWith("whisper")) {
sendMultiPartRequest();
}
else if (m_model.startsWith("gpt-3")) {
sendChatRequest();
}
else {
sendRequest();
}
}
// Send a request to the OpenAI API
void OpenAIRequest::sendRequest()
{
// Set up the API endpoint URL
const QUrl endpointUrl("https://api.openai.com/v1/completions");
// Set up the request headers
QNetworkRequest request(endpointUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Authorization", ("Bearer " + m_accessToken).toUtf8());
// Set up the request body
QJsonObject requestBody;
requestBody.insert("model", m_model);
requestBody.insert("prompt", m_prompt);
requestBody.insert("max_tokens", m_maxTokens);
requestBody.insert("temperature", m_temperature);
requestBody.insert("top_p", m_topP);
requestBody.insert("frequency_penalty", m_frequencyPenalty);
requestBody.insert("presence_penalty", m_presencePenalty);
QJsonDocument requestBodyJson(requestBody);
QByteArray requestBodyBytes = requestBodyJson.toJson();
// Send the request
QNetworkReply *reply = m_networkAccessManager->post(request, requestBodyBytes);
m_status = RequestStatus::InProgress;
emit statusChanged();
// Connect signals and slots to handle the response
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
if (reply->error() == QNetworkReply::NoError) {
const QByteArray responseBytes = reply->readAll();
const QJsonDocument responseJson = QJsonDocument::fromJson(responseBytes);
// Handle the response
const QString generatedText = responseJson.object().value("choices").toArray().at(0).toObject().value("text").toString();
emit requestFinished(generatedText);
} else {
emit requestError(reply->errorString());
}
reply->deleteLater();
});
}
void OpenAIRequest::sendChatRequest()
{
// Set up the API endpoint URL
const QUrl endpointUrl("https://api.openai.com/v1/chat/completions");
// Set up the request headers
QNetworkRequest request(endpointUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Authorization", ("Bearer " + m_accessToken).toUtf8());
// Set up the request body
QJsonObject requestBody;
requestBody.insert("model", m_model);
requestBody.insert("max_tokens", m_maxTokens);
requestBody.insert("temperature", m_temperature);
requestBody.insert("top_p", m_topP);
requestBody.insert("frequency_penalty", m_frequencyPenalty);
requestBody.insert("presence_penalty", m_presencePenalty);
QJsonArray messageArray;
auto addMessageArray = [this, &messageArray](OpenAIMessage* message) {
if (message->content().isEmpty())
return;
QJsonObject messageObject;
messageObject.insert("role", OpenAIMessage::roleToString(message->role()));
messageObject.insert("content", message->content());
messageArray.append(messageObject);
};
for (OpenAIMessage *message : m_messages) {
addMessageArray(message);
}
requestBody.insert("messages", messageArray);
QJsonDocument requestBodyJson(requestBody);
QByteArray requestBodyBytes = requestBodyJson.toJson();
// Send the request
QNetworkReply *reply = m_networkAccessManager->post(request, requestBodyBytes);
m_status = RequestStatus::InProgress;
emit statusChanged();
// Connect signals and slots to handle the response
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
if (reply->error() == QNetworkReply::NoError) {
const QByteArray responseBytes = reply->readAll();
const QJsonDocument responseJson = QJsonDocument::fromJson(responseBytes);
// Handle the response
const auto message = responseJson.object().value("choices").toArray().at(0).toObject().value("message").toObject();
//addMessage(OpenAIMessage::roleFromString(message.value("role").toString()), message.value("content").toString());
emit requestFinished(message.value("content").toString());
} else {
emit requestError(reply->errorString() + reply->readAll());
}
reply->deleteLater();
});
}
void OpenAIRequest::sendMultiPartRequest()
{
// Set up the API endpoint URL
const QUrl endpointUrl("https://api.openai.com/v1/audio/transcriptions");
// Set up the request headers
QNetworkRequest request(endpointUrl);
request.setRawHeader("Authorization", ("Bearer " + m_accessToken).toUtf8());
// Set up the form data
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
// Add a JSON parameter
QHttpPart modelPart;
modelPart.setHeader(QNetworkRequest::ContentTypeHeader, "text/plain");
modelPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"model\"");
modelPart.setBody(m_model.toUtf8());
QHttpPart filePart;
filePart.setHeader(QNetworkRequest::ContentTypeHeader, "audio/wav");
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"file\"; filename=\"audio.wav\"");
QFile *file = new QFile(m_filePath);
file->open(QIODevice::ReadOnly);
filePart.setBodyDevice(file);
file->setParent(multiPart); // Ownership transfer
multiPart->append(filePart);
multiPart->append(modelPart);
// Send the request
QNetworkReply *reply = m_networkAccessManager->post(request, multiPart);
multiPart->setParent(reply); // Ownership transfer
m_status = RequestStatus::InProgress;
emit statusChanged();
// Connect signals and slots to handle the response
connect(reply, &QNetworkReply::finished, this, [this, file, reply]() {
file->close();
if (reply->error() == QNetworkReply::NoError) {
const QByteArray responseBytes = reply->readAll();
const QJsonDocument responseJson = QJsonDocument::fromJson(responseBytes);
// Handle the response
const QString generatedText = responseJson.object().value("text").toString();
emit requestFinished(generatedText);
} else {
qDebug() << reply->errorString();
emit requestError(reply->errorString());
}
reply->deleteLater();
});
}
QString OpenAIRequest::accessToken() const
{
return m_accessToken;
}
void OpenAIRequest::setAccessToken(const QString& accessToken)
{
if (m_accessToken == accessToken)
return;
m_accessToken = accessToken;
emit accessTokenChanged();
}
QString OpenAIRequest::model() const
{
return m_model;
}
void OpenAIRequest::setModel(const QString& model)
{
if (m_model == model)
return;
m_model = model;
emit modelChanged();
}
QString OpenAIRequest::prompt() const
{
return m_prompt;
}
void OpenAIRequest::setPrompt(const QString& prompt)
{
if (m_prompt == prompt)
return;
m_prompt = prompt;
emit promptChanged();
}
QString OpenAIRequest::filePath() const
{
return m_filePath;
}
void OpenAIRequest::setFilePath(const QString& filePath)
{
if (m_filePath == filePath)
return;
m_filePath = filePath;
emit filePathChanged();
}
QString OpenAIRequest::generatedText() const
{
return m_generatedText;
}
QString OpenAIRequest::errorString() const
{
return m_errorString;
}
OpenAIRequest::RequestStatus OpenAIRequest::status() const
{
return m_status;
}
int OpenAIRequest::maxTokens() const
{
return m_maxTokens;
}
void OpenAIRequest::setMaxTokens(int maxTokens)
{
if (m_maxTokens == maxTokens)
return;
m_maxTokens = maxTokens;
emit maxTokensChanged();
}
double OpenAIRequest::temperature() const
{
return m_temperature;
}
void OpenAIRequest::setTemperature(double temperature)
{
if (qFuzzyCompare(m_temperature, temperature))
return;
m_temperature = temperature;
emit temperatureChanged();
}
double OpenAIRequest::topP() const
{
return m_topP;
}
void OpenAIRequest::setTopP(double topP)
{
if (qFuzzyCompare(m_topP, topP))
return;
m_topP = topP;
emit topPChanged();
}
double OpenAIRequest::frequencyPenalty() const
{
return m_frequencyPenalty;
}
void OpenAIRequest::setFrequencyPenalty(double frequencyPenalty)
{
if (qFuzzyCompare(m_frequencyPenalty, frequencyPenalty))
return;
m_frequencyPenalty = frequencyPenalty;
emit frequencyPenaltyChanged();
}
double OpenAIRequest::presencePenalty() const
{
return m_presencePenalty;
}
void OpenAIRequest::setPresencePenalty(double presencePenalty)
{
if (qFuzzyCompare(m_presencePenalty, presencePenalty))
return;
m_presencePenalty = presencePenalty;
emit presencePenaltyChanged();
}
QList<OpenAIMessage*> OpenAIRequest::messages() const
{
return m_messages;
}
void OpenAIRequest::setMessages(const QList<OpenAIMessage *> &newMessages)
{
if (m_messages == newMessages)
return;
m_messages = newMessages;
emit messagesChanged();
}