2023-05-15 00:12:15 +00:00
|
|
|
#include "chatgpt.h"
|
|
|
|
|
|
|
|
#include <string>
|
|
|
|
#include <vector>
|
|
|
|
#include <iostream>
|
|
|
|
|
2023-07-11 16:37:21 +00:00
|
|
|
#include <QCoreApplication>
|
2023-05-15 00:12:15 +00:00
|
|
|
#include <QThread>
|
|
|
|
#include <QEventLoop>
|
|
|
|
#include <QJsonDocument>
|
|
|
|
#include <QJsonObject>
|
|
|
|
#include <QJsonArray>
|
|
|
|
|
|
|
|
//#define DEBUG
|
|
|
|
|
|
|
|
ChatGPT::ChatGPT()
|
|
|
|
: QObject(nullptr)
|
|
|
|
, m_modelName("gpt-3.5-turbo")
|
|
|
|
, m_responseCallback(nullptr)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2023-06-26 19:17:34 +00:00
|
|
|
size_t ChatGPT::requiredMem(const std::string &modelPath)
|
|
|
|
{
|
|
|
|
Q_UNUSED(modelPath);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2023-05-15 00:12:15 +00:00
|
|
|
bool ChatGPT::loadModel(const std::string &modelPath)
|
|
|
|
{
|
|
|
|
Q_UNUSED(modelPath);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
void ChatGPT::setThreadCount(int32_t n_threads)
|
|
|
|
{
|
|
|
|
Q_UNUSED(n_threads);
|
|
|
|
qt_noop();
|
|
|
|
}
|
|
|
|
|
2023-05-21 20:45:29 +00:00
|
|
|
int32_t ChatGPT::threadCount() const
|
2023-05-15 00:12:15 +00:00
|
|
|
{
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
ChatGPT::~ChatGPT()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
bool ChatGPT::isModelLoaded() const
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-05-15 22:36:41 +00:00
|
|
|
// All three of the state virtual functions are handled custom inside of chatllm save/restore
|
2023-05-15 00:12:15 +00:00
|
|
|
size_t ChatGPT::stateSize() const
|
|
|
|
{
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t ChatGPT::saveState(uint8_t *dest) const
|
|
|
|
{
|
2023-05-15 22:36:41 +00:00
|
|
|
Q_UNUSED(dest);
|
2023-05-15 00:12:15 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t ChatGPT::restoreState(const uint8_t *src)
|
|
|
|
{
|
2023-05-15 22:36:41 +00:00
|
|
|
Q_UNUSED(src);
|
2023-05-15 00:12:15 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void ChatGPT::prompt(const std::string &prompt,
|
|
|
|
std::function<bool(int32_t)> promptCallback,
|
|
|
|
std::function<bool(int32_t, const std::string&)> responseCallback,
|
|
|
|
std::function<bool(bool)> recalculateCallback,
|
|
|
|
PromptContext &promptCtx) {
|
|
|
|
|
|
|
|
Q_UNUSED(promptCallback);
|
|
|
|
Q_UNUSED(recalculateCallback);
|
|
|
|
|
|
|
|
if (!isModelLoaded()) {
|
|
|
|
std::cerr << "ChatGPT ERROR: prompt won't work with an unloaded model!\n";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-05-16 13:48:21 +00:00
|
|
|
// FIXME: We don't set the max_tokens on purpose because in order to do so safely without encountering
|
|
|
|
// an error we need to be able to count the tokens in our prompt. The only way to do this is to use
|
|
|
|
// the OpenAI tiktokken library or to implement our own tokenization function that matches precisely
|
|
|
|
// the tokenization used by the OpenAI model we're calling. OpenAI has not introduced any means of
|
|
|
|
// using the REST API to count tokens in a prompt.
|
2023-05-15 00:12:15 +00:00
|
|
|
QJsonObject root;
|
|
|
|
root.insert("model", m_modelName);
|
|
|
|
root.insert("stream", true);
|
|
|
|
root.insert("temperature", promptCtx.temp);
|
|
|
|
root.insert("top_p", promptCtx.top_p);
|
|
|
|
|
|
|
|
QJsonArray messages;
|
|
|
|
for (int i = 0; i < m_context.count() && i < promptCtx.n_past; ++i) {
|
|
|
|
QJsonObject message;
|
|
|
|
message.insert("role", i % 2 == 0 ? "assistant" : "user");
|
|
|
|
message.insert("content", m_context.at(i));
|
|
|
|
messages.append(message);
|
|
|
|
}
|
|
|
|
|
|
|
|
QJsonObject promptObject;
|
|
|
|
promptObject.insert("role", "user");
|
|
|
|
promptObject.insert("content", QString::fromStdString(prompt));
|
|
|
|
messages.append(promptObject);
|
|
|
|
root.insert("messages", messages);
|
|
|
|
|
|
|
|
QJsonDocument doc(root);
|
|
|
|
|
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "ChatGPT::prompt begin network request" << qPrintable(doc.toJson());
|
|
|
|
#endif
|
|
|
|
|
2023-07-11 14:08:03 +00:00
|
|
|
m_responseCallback = responseCallback;
|
|
|
|
|
|
|
|
// The following code sets up a worker thread and object to perform the actual api request to
|
|
|
|
// chatgpt and then blocks until it is finished
|
|
|
|
QThread workerThread;
|
|
|
|
ChatGPTWorker worker(this);
|
|
|
|
worker.moveToThread(&workerThread);
|
|
|
|
connect(&worker, &ChatGPTWorker::finished, &workerThread, &QThread::quit, Qt::DirectConnection);
|
|
|
|
connect(this, &ChatGPT::request, &worker, &ChatGPTWorker::request, Qt::QueuedConnection);
|
|
|
|
workerThread.start();
|
|
|
|
emit request(m_apiKey, &promptCtx, doc.toJson(QJsonDocument::Compact));
|
|
|
|
workerThread.wait();
|
|
|
|
|
|
|
|
promptCtx.n_past += 1;
|
|
|
|
m_context.append(QString::fromStdString(prompt));
|
|
|
|
m_context.append(worker.currentResponse());
|
|
|
|
m_responseCallback = nullptr;
|
|
|
|
|
2023-05-15 00:12:15 +00:00
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "ChatGPT::prompt end network request";
|
|
|
|
#endif
|
2023-07-11 14:08:03 +00:00
|
|
|
}
|
2023-05-15 00:12:15 +00:00
|
|
|
|
2023-07-11 14:08:03 +00:00
|
|
|
bool ChatGPT::callResponse(int32_t token, const std::string& string)
|
|
|
|
{
|
|
|
|
Q_ASSERT(m_responseCallback);
|
|
|
|
if (!m_responseCallback) {
|
|
|
|
std::cerr << "ChatGPT ERROR: no response callback!\n";
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return m_responseCallback(token, string);
|
|
|
|
}
|
2023-05-15 00:12:15 +00:00
|
|
|
|
2023-07-11 14:08:03 +00:00
|
|
|
void ChatGPTWorker::request(const QString &apiKey,
|
|
|
|
LLModel::PromptContext *promptCtx,
|
|
|
|
const QByteArray &array)
|
|
|
|
{
|
|
|
|
m_ctx = promptCtx;
|
|
|
|
|
|
|
|
QUrl openaiUrl("https://api.openai.com/v1/chat/completions");
|
2023-07-12 14:47:13 +00:00
|
|
|
const QString authorization = QString("Bearer %1").arg(apiKey).trimmed();
|
2023-07-11 14:08:03 +00:00
|
|
|
QNetworkRequest request(openaiUrl);
|
|
|
|
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
|
|
|
request.setRawHeader("Authorization", authorization.toUtf8());
|
|
|
|
m_networkManager = new QNetworkAccessManager(this);
|
|
|
|
QNetworkReply *reply = m_networkManager->post(request, array);
|
2023-07-11 16:37:21 +00:00
|
|
|
connect(qApp, &QCoreApplication::aboutToQuit, reply, &QNetworkReply::abort);
|
2023-07-11 14:08:03 +00:00
|
|
|
connect(reply, &QNetworkReply::finished, this, &ChatGPTWorker::handleFinished);
|
|
|
|
connect(reply, &QNetworkReply::readyRead, this, &ChatGPTWorker::handleReadyRead);
|
|
|
|
connect(reply, &QNetworkReply::errorOccurred, this, &ChatGPTWorker::handleErrorOccurred);
|
2023-05-15 00:12:15 +00:00
|
|
|
}
|
|
|
|
|
2023-07-11 14:08:03 +00:00
|
|
|
void ChatGPTWorker::handleFinished()
|
2023-05-15 00:12:15 +00:00
|
|
|
{
|
|
|
|
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
|
2023-07-11 14:08:03 +00:00
|
|
|
if (!reply) {
|
|
|
|
emit finished();
|
2023-05-15 00:12:15 +00:00
|
|
|
return;
|
2023-07-11 14:08:03 +00:00
|
|
|
}
|
2023-05-15 00:12:15 +00:00
|
|
|
|
|
|
|
QVariant response = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
|
|
|
|
Q_ASSERT(response.isValid());
|
|
|
|
bool ok;
|
|
|
|
int code = response.toInt(&ok);
|
|
|
|
if (!ok || code != 200) {
|
2023-05-15 22:36:41 +00:00
|
|
|
qWarning() << QString("ERROR: ChatGPT responded with error code \"%1-%2\"")
|
|
|
|
.arg(code).arg(reply->errorString()).toStdString();
|
2023-05-15 00:12:15 +00:00
|
|
|
}
|
|
|
|
reply->deleteLater();
|
2023-07-11 14:08:03 +00:00
|
|
|
emit finished();
|
2023-05-15 00:12:15 +00:00
|
|
|
}
|
|
|
|
|
2023-07-11 14:08:03 +00:00
|
|
|
void ChatGPTWorker::handleReadyRead()
|
2023-05-15 00:12:15 +00:00
|
|
|
{
|
|
|
|
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
|
2023-07-11 14:08:03 +00:00
|
|
|
if (!reply) {
|
|
|
|
emit finished();
|
2023-05-15 00:12:15 +00:00
|
|
|
return;
|
2023-07-11 14:08:03 +00:00
|
|
|
}
|
2023-05-15 00:12:15 +00:00
|
|
|
|
|
|
|
QVariant response = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
|
|
|
|
Q_ASSERT(response.isValid());
|
|
|
|
bool ok;
|
|
|
|
int code = response.toInt(&ok);
|
|
|
|
if (!ok || code != 200) {
|
2023-07-11 14:08:03 +00:00
|
|
|
m_chat->callResponse(-1, QString("\nERROR: 2 ChatGPT responded with error code \"%1-%2\" %3\n")
|
2023-05-15 00:12:15 +00:00
|
|
|
.arg(code).arg(reply->errorString()).arg(qPrintable(reply->readAll())).toStdString());
|
2023-07-11 14:08:03 +00:00
|
|
|
emit finished();
|
2023-05-15 00:12:15 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
while (reply->canReadLine()) {
|
|
|
|
QString jsonData = reply->readLine().trimmed();
|
|
|
|
if (jsonData.startsWith("data:"))
|
|
|
|
jsonData.remove(0, 5);
|
|
|
|
jsonData = jsonData.trimmed();
|
|
|
|
if (jsonData.isEmpty())
|
|
|
|
continue;
|
|
|
|
if (jsonData == "[DONE]")
|
|
|
|
continue;
|
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "line" << qPrintable(jsonData);
|
|
|
|
#endif
|
|
|
|
QJsonParseError err;
|
|
|
|
const QJsonDocument document = QJsonDocument::fromJson(jsonData.toUtf8(), &err);
|
|
|
|
if (err.error != QJsonParseError::NoError) {
|
2023-07-11 14:08:03 +00:00
|
|
|
m_chat->callResponse(-1, QString("\nERROR: ChatGPT responded with invalid json \"%1\"\n")
|
2023-05-15 00:12:15 +00:00
|
|
|
.arg(err.errorString()).toStdString());
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
const QJsonObject root = document.object();
|
|
|
|
const QJsonArray choices = root.value("choices").toArray();
|
|
|
|
const QJsonObject choice = choices.first().toObject();
|
|
|
|
const QJsonObject delta = choice.value("delta").toObject();
|
|
|
|
const QString content = delta.value("content").toString();
|
|
|
|
Q_ASSERT(m_ctx);
|
|
|
|
m_currentResponse += content;
|
2023-07-11 14:08:03 +00:00
|
|
|
if (!m_chat->callResponse(0, content.toStdString())) {
|
2023-05-15 22:36:41 +00:00
|
|
|
reply->abort();
|
2023-07-11 14:08:03 +00:00
|
|
|
emit finished();
|
2023-05-15 22:36:41 +00:00
|
|
|
return;
|
|
|
|
}
|
2023-05-15 00:12:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-11 14:08:03 +00:00
|
|
|
void ChatGPTWorker::handleErrorOccurred(QNetworkReply::NetworkError code)
|
2023-05-15 00:12:15 +00:00
|
|
|
{
|
|
|
|
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
|
2023-07-12 14:34:10 +00:00
|
|
|
if (!reply || reply->error() == QNetworkReply::OperationCanceledError /*when we call abort on purpose*/) {
|
2023-07-11 14:08:03 +00:00
|
|
|
emit finished();
|
2023-05-15 00:12:15 +00:00
|
|
|
return;
|
2023-07-11 14:08:03 +00:00
|
|
|
}
|
2023-05-15 00:12:15 +00:00
|
|
|
|
2023-05-15 22:36:41 +00:00
|
|
|
qWarning() << QString("ERROR: ChatGPT responded with error code \"%1-%2\"")
|
|
|
|
.arg(code).arg(reply->errorString()).toStdString();
|
2023-07-11 14:08:03 +00:00
|
|
|
emit finished();
|
2023-05-15 00:12:15 +00:00
|
|
|
}
|