2023-10-24 16:13:32 +00:00
|
|
|
#include "embllm.h"
|
2024-06-04 18:47:11 +00:00
|
|
|
|
2023-10-24 16:13:32 +00:00
|
|
|
#include "modellist.h"
|
2024-06-24 22:49:23 +00:00
|
|
|
#include "mysettings.h"
|
2023-10-24 16:13:32 +00:00
|
|
|
|
2024-06-04 18:47:11 +00:00
|
|
|
#include "../gpt4all-backend/llmodel.h"
|
|
|
|
|
|
|
|
#include <QCoreApplication>
|
|
|
|
#include <QDebug>
|
|
|
|
#include <QFile>
|
|
|
|
#include <QFileInfo>
|
|
|
|
#include <QGuiApplication>
|
|
|
|
#include <QIODevice>
|
|
|
|
#include <QJsonArray>
|
|
|
|
#include <QJsonDocument>
|
|
|
|
#include <QJsonObject>
|
|
|
|
#include <QList>
|
2024-06-24 22:49:23 +00:00
|
|
|
#include <QMutexLocker>
|
2024-06-04 18:47:11 +00:00
|
|
|
#include <QNetworkAccessManager>
|
|
|
|
#include <QNetworkReply>
|
|
|
|
#include <QNetworkRequest>
|
|
|
|
#include <QUrl>
|
|
|
|
#include <Qt>
|
|
|
|
#include <QtGlobal>
|
|
|
|
#include <QtLogging>
|
|
|
|
|
|
|
|
#include <exception>
|
|
|
|
#include <utility>
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
using namespace Qt::Literals::StringLiterals;
|
|
|
|
|
|
|
|
static const QString EMBEDDING_MODEL_NAME = u"nomic-embed-text-v1.5"_s;
|
|
|
|
static const QString LOCAL_EMBEDDING_MODEL = u"nomic-embed-text-v1.5.f16.gguf"_s;
|
|
|
|
|
2024-01-22 17:36:01 +00:00
|
|
|
EmbeddingLLMWorker::EmbeddingLLMWorker()
|
|
|
|
: QObject(nullptr)
|
|
|
|
, m_networkManager(new QNetworkAccessManager(this))
|
2024-05-15 14:01:53 +00:00
|
|
|
, m_stopGenerating(false)
|
2023-10-24 16:13:32 +00:00
|
|
|
{
|
2024-01-22 17:36:01 +00:00
|
|
|
moveToThread(&m_workerThread);
|
2024-06-24 22:49:23 +00:00
|
|
|
connect(this, &EmbeddingLLMWorker::requestAtlasQueryEmbedding, this, &EmbeddingLLMWorker::atlasQueryEmbeddingRequested);
|
2024-01-22 17:36:01 +00:00
|
|
|
connect(this, &EmbeddingLLMWorker::finished, &m_workerThread, &QThread::quit, Qt::DirectConnection);
|
|
|
|
m_workerThread.setObjectName("embedding");
|
|
|
|
m_workerThread.start();
|
2023-10-24 16:13:32 +00:00
|
|
|
}
|
|
|
|
|
2024-01-22 17:36:01 +00:00
|
|
|
EmbeddingLLMWorker::~EmbeddingLLMWorker()
|
2023-10-24 16:13:32 +00:00
|
|
|
{
|
2024-05-15 14:01:53 +00:00
|
|
|
m_stopGenerating = true;
|
|
|
|
m_workerThread.quit();
|
|
|
|
m_workerThread.wait();
|
|
|
|
|
2024-01-22 17:36:01 +00:00
|
|
|
if (m_model) {
|
|
|
|
delete m_model;
|
|
|
|
m_model = nullptr;
|
|
|
|
}
|
2023-10-24 16:13:32 +00:00
|
|
|
}
|
|
|
|
|
2024-01-22 17:36:01 +00:00
|
|
|
void EmbeddingLLMWorker::wait()
|
|
|
|
{
|
|
|
|
m_workerThread.wait();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool EmbeddingLLMWorker::loadModel()
|
2023-10-24 16:13:32 +00:00
|
|
|
{
|
2024-06-24 22:49:23 +00:00
|
|
|
m_nomicAPIKey.clear();
|
|
|
|
m_model = nullptr;
|
2023-10-24 16:13:32 +00:00
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
if (MySettings::globalInstance()->localDocsUseRemoteEmbed()) {
|
|
|
|
m_nomicAPIKey = MySettings::globalInstance()->localDocsNomicAPIKey();
|
|
|
|
return true;
|
2023-10-24 16:13:32 +00:00
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
QString filePath = u"%1/../resources/%2"_s.arg(QCoreApplication::applicationDirPath(), LOCAL_EMBEDDING_MODEL);
|
|
|
|
if (!QFileInfo::exists(filePath)) {
|
|
|
|
qWarning() << "WARNING: Local embedding model not found";
|
|
|
|
return false;
|
2024-01-22 17:36:01 +00:00
|
|
|
}
|
|
|
|
|
2024-04-25 17:16:52 +00:00
|
|
|
try {
|
|
|
|
m_model = LLModel::Implementation::construct(filePath.toStdString());
|
|
|
|
} catch (const std::exception &e) {
|
|
|
|
qWarning() << "WARNING: Could not load embedding model:" << e.what();
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
// FIXME(jared): the user may want this to take effect without having to restart
|
|
|
|
int n_threads = MySettings::globalInstance()->threadCount();
|
|
|
|
m_model->setThreadCount(n_threads);
|
|
|
|
|
2024-03-13 22:09:24 +00:00
|
|
|
// NOTE: explicitly loads model on CPU to avoid GPU OOM
|
|
|
|
// TODO(cebtenzzre): support GPU-accelerated embeddings
|
2024-01-31 19:17:44 +00:00
|
|
|
bool success = m_model->loadModel(filePath.toStdString(), 2048, 0);
|
2023-10-24 16:13:32 +00:00
|
|
|
if (!success) {
|
2024-03-13 22:09:24 +00:00
|
|
|
qWarning() << "WARNING: Could not load embedding model";
|
2023-10-24 16:13:32 +00:00
|
|
|
delete m_model;
|
|
|
|
m_model = nullptr;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-03-13 22:09:24 +00:00
|
|
|
if (!m_model->supportsEmbedding()) {
|
|
|
|
qWarning() << "WARNING: Model type does not support embeddings";
|
2023-10-24 16:13:32 +00:00
|
|
|
delete m_model;
|
|
|
|
m_model = nullptr;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
std::vector<float> EmbeddingLLMWorker::generateQueryEmbedding(const QString &text)
|
2023-10-24 16:13:32 +00:00
|
|
|
{
|
2024-06-24 22:49:23 +00:00
|
|
|
{
|
|
|
|
QMutexLocker locker(&m_mutex);
|
2023-10-24 16:13:32 +00:00
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
if (!hasModel() && !loadModel()) {
|
|
|
|
qWarning() << "WARNING: Could not load model for embeddings";
|
|
|
|
return {};
|
|
|
|
}
|
2024-01-22 17:36:01 +00:00
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
if (!isNomic()) {
|
|
|
|
std::vector<float> embedding(m_model->embeddingSize());
|
|
|
|
|
|
|
|
try {
|
|
|
|
m_model->embed({text.toStdString()}, embedding.data(), true);
|
|
|
|
} catch (const std::exception &e) {
|
|
|
|
qWarning() << "WARNING: LLModel::embed failed:" << e.what();
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
|
|
|
return embedding;
|
|
|
|
}
|
2024-03-13 22:09:24 +00:00
|
|
|
}
|
2024-06-24 22:49:23 +00:00
|
|
|
|
|
|
|
EmbeddingLLMWorker worker;
|
|
|
|
emit worker.requestAtlasQueryEmbedding(text);
|
|
|
|
worker.wait();
|
|
|
|
return worker.lastResponse();
|
2023-10-24 16:13:32 +00:00
|
|
|
}
|
2024-01-22 17:36:01 +00:00
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
void EmbeddingLLMWorker::sendAtlasRequest(const QStringList &texts, const QString &taskType, const QVariant &userData)
|
|
|
|
{
|
2024-03-13 22:09:24 +00:00
|
|
|
QJsonObject root;
|
|
|
|
root.insert("model", "nomic-embed-text-v1");
|
|
|
|
root.insert("texts", QJsonArray::fromStringList(texts));
|
|
|
|
root.insert("task_type", taskType);
|
|
|
|
|
|
|
|
QJsonDocument doc(root);
|
|
|
|
|
|
|
|
QUrl nomicUrl("https://api-atlas.nomic.ai/v1/embedding/text");
|
2024-06-24 22:49:23 +00:00
|
|
|
const QString authorization = u"Bearer %1"_s.arg(m_nomicAPIKey).trimmed();
|
2024-03-13 22:09:24 +00:00
|
|
|
QNetworkRequest request(nomicUrl);
|
|
|
|
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
|
|
|
request.setRawHeader("Authorization", authorization.toUtf8());
|
|
|
|
request.setAttribute(QNetworkRequest::User, userData);
|
|
|
|
QNetworkReply *reply = m_networkManager->post(request, doc.toJson(QJsonDocument::Compact));
|
2024-06-04 18:47:11 +00:00
|
|
|
connect(qGuiApp, &QCoreApplication::aboutToQuit, reply, &QNetworkReply::abort);
|
2024-03-13 22:09:24 +00:00
|
|
|
connect(reply, &QNetworkReply::finished, this, &EmbeddingLLMWorker::handleFinished);
|
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
void EmbeddingLLMWorker::atlasQueryEmbeddingRequested(const QString &text)
|
2024-01-22 17:36:01 +00:00
|
|
|
{
|
2024-06-24 22:49:23 +00:00
|
|
|
{
|
|
|
|
QMutexLocker locker(&m_mutex);
|
|
|
|
if (!hasModel() && !loadModel()) {
|
|
|
|
qWarning() << "WARNING: Could not load model for embeddings";
|
|
|
|
return;
|
|
|
|
}
|
2024-01-22 17:36:01 +00:00
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
if (!isNomic()) {
|
|
|
|
qWarning() << "WARNING: Request to generate sync embeddings for local model invalid";
|
|
|
|
return;
|
|
|
|
}
|
2024-01-22 17:36:01 +00:00
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
Q_ASSERT(hasModel());
|
|
|
|
}
|
2024-01-22 17:36:01 +00:00
|
|
|
|
2024-03-13 22:09:24 +00:00
|
|
|
sendAtlasRequest({text}, "search_query");
|
2024-01-22 17:36:01 +00:00
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
void EmbeddingLLMWorker::docEmbeddingsRequested(const QVector<EmbeddingChunk> &chunks)
|
2024-01-22 17:36:01 +00:00
|
|
|
{
|
2024-05-15 14:01:53 +00:00
|
|
|
if (m_stopGenerating)
|
|
|
|
return;
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
bool isNomic;
|
|
|
|
{
|
|
|
|
QMutexLocker locker(&m_mutex);
|
|
|
|
if (!hasModel() && !loadModel()) {
|
|
|
|
qWarning() << "WARNING: Could not load model for embeddings";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
isNomic = this->isNomic();
|
2024-01-22 17:36:01 +00:00
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
if (!isNomic) {
|
2024-01-22 17:36:01 +00:00
|
|
|
QVector<EmbeddingResult> results;
|
|
|
|
results.reserve(chunks.size());
|
2024-06-24 22:49:23 +00:00
|
|
|
for (const auto &c: chunks) {
|
2024-01-22 17:36:01 +00:00
|
|
|
EmbeddingResult result;
|
2024-06-24 22:49:23 +00:00
|
|
|
result.model = c.model;
|
2024-01-22 17:36:01 +00:00
|
|
|
result.folder_id = c.folder_id;
|
|
|
|
result.chunk_id = c.chunk_id;
|
2024-03-13 22:09:24 +00:00
|
|
|
// TODO(cebtenzzre): take advantage of batched embeddings
|
|
|
|
result.embedding.resize(m_model->embeddingSize());
|
2024-06-24 22:49:23 +00:00
|
|
|
|
|
|
|
{
|
|
|
|
QMutexLocker locker(&m_mutex);
|
|
|
|
try {
|
|
|
|
m_model->embed({c.chunk.toStdString()}, result.embedding.data(), false);
|
|
|
|
} catch (const std::exception &e) {
|
|
|
|
qWarning() << "WARNING: LLModel::embed failed:" << e.what();
|
|
|
|
return;
|
|
|
|
}
|
2024-03-13 22:09:24 +00:00
|
|
|
}
|
2024-06-24 22:49:23 +00:00
|
|
|
|
2024-01-22 17:36:01 +00:00
|
|
|
results << result;
|
|
|
|
}
|
|
|
|
emit embeddingsGenerated(results);
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
2024-03-13 22:09:24 +00:00
|
|
|
QStringList texts;
|
|
|
|
for (auto &c: chunks)
|
2024-01-22 17:36:01 +00:00
|
|
|
texts.append(c.chunk);
|
2024-03-13 22:09:24 +00:00
|
|
|
sendAtlasRequest(texts, "search_document", QVariant::fromValue(chunks));
|
2024-01-22 17:36:01 +00:00
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
std::vector<float> jsonArrayToVector(const QJsonArray &jsonArray)
|
|
|
|
{
|
2024-01-22 17:36:01 +00:00
|
|
|
std::vector<float> result;
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
for (const auto &innerValue: jsonArray) {
|
2024-01-22 17:36:01 +00:00
|
|
|
if (innerValue.isArray()) {
|
|
|
|
QJsonArray innerArray = innerValue.toArray();
|
|
|
|
result.reserve(result.size() + innerArray.size());
|
2024-06-24 22:49:23 +00:00
|
|
|
for (const auto &value: innerArray) {
|
2024-01-22 17:36:01 +00:00
|
|
|
result.push_back(static_cast<float>(value.toDouble()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
QVector<EmbeddingResult> jsonArrayToEmbeddingResults(const QVector<EmbeddingChunk>& chunks, const QJsonArray& embeddings)
|
|
|
|
{
|
2024-01-22 17:36:01 +00:00
|
|
|
QVector<EmbeddingResult> results;
|
|
|
|
|
|
|
|
if (chunks.size() != embeddings.size()) {
|
|
|
|
qWarning() << "WARNING: Size of json array result does not match input!";
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (int i = 0; i < chunks.size(); ++i) {
|
|
|
|
const EmbeddingChunk& chunk = chunks.at(i);
|
|
|
|
const QJsonArray embeddingArray = embeddings.at(i).toArray();
|
|
|
|
|
|
|
|
std::vector<float> embeddingVector;
|
2024-06-24 22:49:23 +00:00
|
|
|
for (const auto &value: embeddingArray)
|
2024-01-22 17:36:01 +00:00
|
|
|
embeddingVector.push_back(static_cast<float>(value.toDouble()));
|
|
|
|
|
|
|
|
EmbeddingResult result;
|
2024-06-24 22:49:23 +00:00
|
|
|
result.model = chunk.model;
|
2024-01-22 17:36:01 +00:00
|
|
|
result.folder_id = chunk.folder_id;
|
|
|
|
result.chunk_id = chunk.chunk_id;
|
|
|
|
result.embedding = std::move(embeddingVector);
|
|
|
|
results.push_back(std::move(result));
|
|
|
|
}
|
|
|
|
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
|
|
|
|
void EmbeddingLLMWorker::handleFinished()
|
|
|
|
{
|
|
|
|
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
|
|
|
|
if (!reply)
|
|
|
|
return;
|
|
|
|
|
|
|
|
QVariant retrievedData = reply->request().attribute(QNetworkRequest::User);
|
|
|
|
QVector<EmbeddingChunk> chunks;
|
|
|
|
if (retrievedData.isValid() && retrievedData.canConvert<QVector<EmbeddingChunk>>())
|
|
|
|
chunks = retrievedData.value<QVector<EmbeddingChunk>>();
|
|
|
|
|
|
|
|
QVariant response = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
|
|
|
|
Q_ASSERT(response.isValid());
|
|
|
|
bool ok;
|
|
|
|
int code = response.toInt(&ok);
|
|
|
|
if (!ok || code != 200) {
|
|
|
|
QString errorDetails;
|
|
|
|
QString replyErrorString = reply->errorString().trimmed();
|
|
|
|
QByteArray replyContent = reply->readAll().trimmed();
|
2024-06-24 22:49:23 +00:00
|
|
|
errorDetails = u"ERROR: Nomic Atlas responded with error code \"%1\""_s.arg(code);
|
2024-01-22 17:36:01 +00:00
|
|
|
if (!replyErrorString.isEmpty())
|
2024-06-24 22:49:23 +00:00
|
|
|
errorDetails += u". Error Details: \"%1\""_s.arg(replyErrorString);
|
2024-01-22 17:36:01 +00:00
|
|
|
if (!replyContent.isEmpty())
|
2024-06-24 22:49:23 +00:00
|
|
|
errorDetails += u". Response Content: \"%1\""_s.arg(QString::fromUtf8(replyContent));
|
2024-01-22 17:36:01 +00:00
|
|
|
qWarning() << errorDetails;
|
2024-06-24 22:49:23 +00:00
|
|
|
emit errorGenerated(chunks, errorDetails);
|
2024-01-22 17:36:01 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
QByteArray jsonData = reply->readAll();
|
|
|
|
|
|
|
|
QJsonParseError err;
|
|
|
|
QJsonDocument document = QJsonDocument::fromJson(jsonData, &err);
|
|
|
|
if (err.error != QJsonParseError::NoError) {
|
2024-06-24 22:49:23 +00:00
|
|
|
qWarning() << "ERROR: Couldn't parse Nomic Atlas response:" << jsonData << err.errorString();
|
2024-01-22 17:36:01 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const QJsonObject root = document.object();
|
|
|
|
const QJsonArray embeddings = root.value("embeddings").toArray();
|
|
|
|
|
|
|
|
if (!chunks.isEmpty()) {
|
|
|
|
emit embeddingsGenerated(jsonArrayToEmbeddingResults(chunks, embeddings));
|
|
|
|
} else {
|
|
|
|
m_lastResponse = jsonArrayToVector(embeddings);
|
|
|
|
emit finished();
|
|
|
|
}
|
|
|
|
|
|
|
|
reply->deleteLater();
|
|
|
|
}
|
|
|
|
|
|
|
|
EmbeddingLLM::EmbeddingLLM()
|
|
|
|
: QObject(nullptr)
|
|
|
|
, m_embeddingWorker(new EmbeddingLLMWorker)
|
|
|
|
{
|
2024-06-24 22:49:23 +00:00
|
|
|
connect(this, &EmbeddingLLM::requestDocEmbeddings, m_embeddingWorker,
|
|
|
|
&EmbeddingLLMWorker::docEmbeddingsRequested, Qt::QueuedConnection);
|
2024-01-22 17:36:01 +00:00
|
|
|
connect(m_embeddingWorker, &EmbeddingLLMWorker::embeddingsGenerated, this,
|
|
|
|
&EmbeddingLLM::embeddingsGenerated, Qt::QueuedConnection);
|
|
|
|
connect(m_embeddingWorker, &EmbeddingLLMWorker::errorGenerated, this,
|
|
|
|
&EmbeddingLLM::errorGenerated, Qt::QueuedConnection);
|
|
|
|
}
|
|
|
|
|
|
|
|
EmbeddingLLM::~EmbeddingLLM()
|
|
|
|
{
|
|
|
|
delete m_embeddingWorker;
|
|
|
|
m_embeddingWorker = nullptr;
|
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
QString EmbeddingLLM::model()
|
2024-01-22 17:36:01 +00:00
|
|
|
{
|
2024-06-24 22:49:23 +00:00
|
|
|
return EMBEDDING_MODEL_NAME;
|
|
|
|
}
|
2024-05-02 13:30:36 +00:00
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
// TODO(jared): embed using all necessary embedding models given collection
|
|
|
|
std::vector<float> EmbeddingLLM::generateQueryEmbedding(const QString &text)
|
|
|
|
{
|
|
|
|
return m_embeddingWorker->generateQueryEmbedding(text);
|
2024-01-22 17:36:01 +00:00
|
|
|
}
|
|
|
|
|
2024-06-24 22:49:23 +00:00
|
|
|
void EmbeddingLLM::generateDocEmbeddingsAsync(const QVector<EmbeddingChunk> &chunks)
|
2024-01-22 17:36:01 +00:00
|
|
|
{
|
2024-06-24 22:49:23 +00:00
|
|
|
emit requestDocEmbeddings(chunks);
|
2024-01-22 17:36:01 +00:00
|
|
|
}
|