gpt4all/network.cpp

364 lines
10 KiB
C++
Raw Normal View History

#include "network.h"
#include "llm.h"
#include <QCoreApplication>
#include <QUuid>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QSettings>
#include <QNetworkRequest>
//#define DEBUG
class MyNetwork: public Network { };
Q_GLOBAL_STATIC(MyNetwork, networkInstance)
Network *Network::globalInstance()
{
return networkInstance();
}
Network::Network()
: QObject{nullptr}
, m_isActive(false)
2023-04-28 10:54:05 -04:00
, m_usageStatsActive(false)
2023-04-26 22:05:56 -04:00
, m_shouldSendStartup(false)
{
QSettings settings;
settings.sync();
m_uniqueId = settings.value("uniqueId", generateUniqueId()).toString();
settings.setValue("uniqueId", m_uniqueId);
settings.sync();
2023-04-28 10:54:05 -04:00
m_isActive = settings.value("network/isActive", false).toBool();
if (m_isActive)
sendHealth();
m_usageStatsActive = settings.value("network/usageStatsActive", false).toBool();
if (m_usageStatsActive)
2023-04-26 22:05:56 -04:00
sendIpify();
2023-04-24 17:52:19 -04:00
connect(&m_networkManager, &QNetworkAccessManager::sslErrors, this,
&Network::handleSslErrors);
}
void Network::setActive(bool b)
{
QSettings settings;
settings.setValue("network/isActive", b);
settings.sync();
m_isActive = b;
emit activeChanged();
if (m_isActive)
sendHealth();
}
2023-04-28 10:54:05 -04:00
void Network::setUsageStatsActive(bool b)
{
QSettings settings;
settings.setValue("network/usageStatsActive", b);
settings.sync();
m_usageStatsActive = b;
emit usageStatsActiveChanged();
if (!m_usageStatsActive)
sendOptOut();
else {
// model might be loaded already when user opt-in for first time
sendStartup();
sendIpify();
}
}
QString Network::generateUniqueId() const
{
return QUuid::createUuid().toString(QUuid::WithoutBraces);
}
2023-04-23 21:05:38 -04:00
bool Network::packageAndSendJson(const QString &ingestId, const QString &json)
{
if (!m_isActive)
return false;
QJsonParseError err;
QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8(), &err);
if (err.error != QJsonParseError::NoError) {
qDebug() << "Couldn't parse: " << json << err.errorString();
return false;
}
Q_ASSERT(doc.isObject());
QJsonObject object = doc.object();
object.insert("source", "gpt4all-chat");
object.insert("agent_id", LLM::globalInstance()->modelName());
object.insert("submitter_id", m_uniqueId);
2023-04-23 21:05:38 -04:00
object.insert("ingest_id", ingestId);
QSettings settings;
settings.sync();
2023-04-28 10:54:05 -04:00
QString attribution = settings.value("network/attribution", QString()).toString();
if (!attribution.isEmpty())
2023-04-28 10:54:05 -04:00
object.insert("network/attribution", attribution);
QJsonDocument newDoc;
newDoc.setObject(object);
#if defined(DEBUG)
2023-04-26 22:05:56 -04:00
printf("%s\n", qPrintable(newDoc.toJson(QJsonDocument::Indented)));
fflush(stdout);
#endif
2023-04-26 22:05:56 -04:00
2023-04-23 21:05:38 -04:00
QUrl jsonUrl("https://api.gpt4all.io/v1/ingest/chat");
QNetworkRequest request(jsonUrl);
2023-04-24 00:05:06 -04:00
QSslConfiguration conf = request.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(conf);
QByteArray body(newDoc.toJson());
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply *jsonReply = m_networkManager.post(request, body);
connect(jsonReply, &QNetworkReply::finished, this, &Network::handleJsonUploadFinished);
m_activeUploads.append(jsonReply);
return true;
}
void Network::handleJsonUploadFinished()
{
QNetworkReply *jsonReply = qobject_cast<QNetworkReply *>(sender());
if (!jsonReply)
return;
m_activeUploads.removeAll(jsonReply);
QVariant response = jsonReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
Q_ASSERT(response.isValid());
bool ok;
int code = response.toInt(&ok);
if (!ok)
2023-04-23 21:05:38 -04:00
qWarning() << "ERROR: ingest invalid response.";
if (code != 200) {
2023-04-23 21:05:38 -04:00
qWarning() << "ERROR: ingest response != 200 code:" << code;
sendHealth();
}
QByteArray jsonData = jsonReply->readAll();
QJsonParseError err;
QJsonDocument document = QJsonDocument::fromJson(jsonData, &err);
if (err.error != QJsonParseError::NoError) {
qDebug() << "ERROR: Couldn't parse: " << jsonData << err.errorString();
return;
}
#if defined(DEBUG)
2023-04-26 22:05:56 -04:00
printf("%s\n", qPrintable(document.toJson(QJsonDocument::Indented)));
fflush(stdout);
#endif
jsonReply->deleteLater();
}
2023-04-24 17:52:19 -04:00
void Network::handleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
QUrl url = reply->request().url();
for (auto e : errors)
qWarning() << "ERROR: Received ssl error:" << e.errorString() << "for" << url;
}
2023-04-28 10:54:05 -04:00
void Network::sendOptOut()
{
QJsonObject properties;
properties.insert("token", "ce362e568ddaee16ed243eaffb5860a2");
properties.insert("time", QDateTime::currentSecsSinceEpoch());
properties.insert("distinct_id", m_uniqueId);
properties.insert("$insert_id", generateUniqueId());
QJsonObject event;
event.insert("event", "opt_out");
event.insert("properties", properties);
QJsonArray array;
array.append(event);
QJsonDocument doc;
doc.setArray(array);
2023-04-29 11:05:44 -04:00
sendMixpanel(doc.toJson(), true /*isOptOut*/);
2023-04-28 10:54:05 -04:00
#if defined(DEBUG)
printf("%s %s\n", qPrintable("opt_out"), qPrintable(doc.toJson(QJsonDocument::Indented)));
fflush(stdout);
#endif
}
2023-04-26 22:05:56 -04:00
void Network::sendModelLoaded()
{
2023-04-28 10:54:05 -04:00
if (!m_usageStatsActive)
2023-04-26 22:05:56 -04:00
return;
sendMixpanelEvent("model_load");
}
void Network::sendResetContext()
{
2023-04-28 10:54:05 -04:00
if (!m_usageStatsActive)
2023-04-26 22:05:56 -04:00
return;
sendMixpanelEvent("reset_context");
}
void Network::sendStartup()
{
2023-04-28 10:54:05 -04:00
if (!m_usageStatsActive)
2023-04-26 22:05:56 -04:00
return;
m_shouldSendStartup = true;
if (m_ipify.isEmpty())
return; // when it completes it will send
sendMixpanelEvent("startup");
}
2023-04-27 07:41:23 -04:00
void Network::sendCheckForUpdates()
{
2023-04-28 10:54:05 -04:00
if (!m_usageStatsActive)
2023-04-27 07:41:23 -04:00
return;
sendMixpanelEvent("check_for_updates");
}
2023-04-26 22:05:56 -04:00
void Network::sendMixpanelEvent(const QString &ev)
{
2023-04-28 10:54:05 -04:00
if (!m_usageStatsActive)
2023-04-26 22:05:56 -04:00
return;
QJsonObject properties;
properties.insert("token", "ce362e568ddaee16ed243eaffb5860a2");
properties.insert("time", QDateTime::currentSecsSinceEpoch());
properties.insert("distinct_id", m_uniqueId);
properties.insert("$insert_id", generateUniqueId());
properties.insert("$os", QSysInfo::prettyProductName());
if (!m_ipify.isEmpty())
properties.insert("ip", m_ipify);
properties.insert("name", QCoreApplication::applicationName() + " v"
+ QCoreApplication::applicationVersion());
properties.insert("model", LLM::globalInstance()->modelName());
QJsonObject event;
event.insert("event", ev);
event.insert("properties", properties);
QJsonArray array;
array.append(event);
QJsonDocument doc;
doc.setArray(array);
sendMixpanel(doc.toJson());
#if defined(DEBUG)
printf("%s %s\n", qPrintable(ev), qPrintable(doc.toJson(QJsonDocument::Indented)));
fflush(stdout);
#endif
}
void Network::sendIpify()
{
2023-04-28 10:54:05 -04:00
if (!m_usageStatsActive || !m_ipify.isEmpty())
2023-04-26 22:05:56 -04:00
return;
QUrl ipifyUrl("https://api.ipify.org");
QNetworkRequest request(ipifyUrl);
QSslConfiguration conf = request.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(conf);
QNetworkReply *reply = m_networkManager.get(request);
connect(reply, &QNetworkReply::finished, this, &Network::handleIpifyFinished);
}
2023-04-29 11:05:44 -04:00
void Network::sendMixpanel(const QByteArray &json, bool isOptOut)
2023-04-26 22:05:56 -04:00
{
2023-04-29 11:05:44 -04:00
if (!m_usageStatsActive && !isOptOut)
2023-04-26 22:05:56 -04:00
return;
QUrl trackUrl("https://api.mixpanel.com/track");
QNetworkRequest request(trackUrl);
QSslConfiguration conf = request.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(conf);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply *trackReply = m_networkManager.post(request, json);
connect(trackReply, &QNetworkReply::finished, this, &Network::handleMixpanelFinished);
}
void Network::handleIpifyFinished()
{
2023-04-28 10:54:05 -04:00
Q_ASSERT(m_usageStatsActive);
2023-04-26 22:05:56 -04:00
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
if (!reply)
return;
QVariant response = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
Q_ASSERT(response.isValid());
bool ok;
int code = response.toInt(&ok);
if (!ok)
qWarning() << "ERROR: ipify invalid response.";
if (code != 200)
qWarning() << "ERROR: ipify response != 200 code:" << code;
m_ipify = qPrintable(reply->readAll());
#if defined(DEBUG)
printf("ipify finished %s\n", m_ipify.toLatin1().constData());
fflush(stdout);
#endif
reply->deleteLater();
if (m_shouldSendStartup)
sendStartup();
}
void Network::handleMixpanelFinished()
{
2023-04-28 10:54:05 -04:00
Q_ASSERT(m_usageStatsActive);
2023-04-26 22:05:56 -04:00
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
if (!reply)
return;
QVariant response = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
Q_ASSERT(response.isValid());
bool ok;
int code = response.toInt(&ok);
if (!ok)
qWarning() << "ERROR: track invalid response.";
if (code != 200)
qWarning() << "ERROR: track response != 200 code:" << code;
#if defined(DEBUG)
printf("mixpanel finished %s\n", qPrintable(reply->readAll()));
fflush(stdout);
#endif
reply->deleteLater();
}
2023-04-23 21:05:38 -04:00
bool Network::sendConversation(const QString &ingestId, const QString &conversation)
{
2023-04-23 21:05:38 -04:00
return packageAndSendJson(ingestId, conversation);
}
void Network::sendHealth()
{
2023-04-23 21:05:38 -04:00
QUrl healthUrl("https://api.gpt4all.io/v1/health");
QNetworkRequest request(healthUrl);
2023-04-24 00:05:06 -04:00
QSslConfiguration conf = request.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(conf);
QNetworkReply *healthReply = m_networkManager.get(request);
connect(healthReply, &QNetworkReply::finished, this, &Network::handleHealthFinished);
}
void Network::handleHealthFinished()
{
QNetworkReply *healthReply = qobject_cast<QNetworkReply *>(sender());
if (!healthReply)
return;
QVariant response = healthReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
Q_ASSERT(response.isValid());
bool ok;
int code = response.toInt(&ok);
if (!ok)
2023-04-23 21:05:38 -04:00
qWarning() << "ERROR: health invalid response.";
if (code != 200) {
2023-04-23 21:05:38 -04:00
qWarning() << "ERROR: health response != 200 code:" << code;
emit healthCheckFailed(code);
setActive(false);
}
healthReply->deleteLater();
}