Upgrade to version 0.3.0

new QML Chat
Qwen chat model
This commit is contained in:
Petr Mironychev
2024-10-14 00:09:08 +02:00
parent 5c98de7440
commit 0c045e65df
71 changed files with 1920 additions and 1070 deletions

View File

@ -1,192 +0,0 @@
/*
* Copyright (C) 2024 Petr Mironychev
*
* This file is part of QodeAssist.
*
* QodeAssist is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QodeAssist is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QodeAssist. If not, see <https://www.gnu.org/licenses/>.
*/
#include "ChatClientInterface.hpp"
#include "LLMProvidersManager.hpp"
#include "PromptTemplateManager.hpp"
#include "QodeAssistUtils.hpp"
#include "settings/ContextSettings.hpp"
#include "settings/GeneralSettings.hpp"
#include "settings/PresetPromptsSettings.hpp"
#include <QJsonArray>
#include <QJsonDocument>
#include <QUuid>
namespace QodeAssist::Chat {
int ChatHistory::estimateTokenCount(const QString &text) const
{
return text.length() / 4;
}
void ChatHistory::addMessage(ChatMessage::Role role, const QString &content)
{
int tokenCount = estimateTokenCount(content);
m_messages.append({role, content, tokenCount});
m_totalTokens += tokenCount;
trim();
}
void ChatHistory::clear()
{
m_messages.clear();
m_totalTokens = 0;
}
QVector<ChatMessage> ChatHistory::getMessages() const
{
return m_messages;
}
QString ChatHistory::getSystemPrompt() const
{
return m_systemPrompt;
}
void ChatHistory::setSystemPrompt(const QString &prompt)
{
m_systemPrompt = prompt;
}
void ChatHistory::trim()
{
while (m_messages.size() > MAX_HISTORY_SIZE || m_totalTokens > MAX_TOKENS) {
if (!m_messages.isEmpty()) {
m_totalTokens -= m_messages.first().tokenCount;
m_messages.removeFirst();
} else {
break;
}
}
}
ChatClientInterface::ChatClientInterface(QObject *parent)
: QObject(parent)
, m_requestHandler(new LLMRequestHandler(this))
{
connect(m_requestHandler,
&LLMRequestHandler::completionReceived,
this,
[this](const QString &completion, const QJsonObject &, bool isComplete) {
handleLLMResponse(completion, isComplete);
});
connect(m_requestHandler,
&LLMRequestHandler::requestFinished,
this,
[this](const QString &, bool success, const QString &errorString) {
if (!success) {
emit errorOccurred(errorString);
}
});
m_chatHistory.setSystemPrompt("You are a helpful C++ and QML programming assistant.");
}
ChatClientInterface::~ChatClientInterface() = default;
void ChatClientInterface::sendMessage(const QString &message)
{
logMessage("Sending message: " + message);
logMessage("chatProvider " + Settings::generalSettings().chatLlmProviders.stringValue());
logMessage("chatTemplate " + Settings::generalSettings().chatPrompts.stringValue());
auto chatTemplate = PromptTemplateManager::instance().getCurrentChatTemplate();
auto chatProvider = LLMProvidersManager::instance().getCurrentChatProvider();
ContextData context;
context.prefix = message;
context.suffix = "";
if (Settings::contextSettings().useSpecificInstructions())
context.instriuctions = Settings::contextSettings().specificInstractions();
QJsonObject providerRequest;
providerRequest["model"] = Settings::generalSettings().chatModelName();
providerRequest["stream"] = true;
providerRequest["messages"] = prepareMessagesForRequest();
chatTemplate->prepareRequest(providerRequest, context);
chatProvider->prepareRequest(providerRequest);
LLMConfig config;
config.requestType = RequestType::Chat;
config.provider = chatProvider;
config.promptTemplate = chatTemplate;
config.url = QString("%1%2").arg(Settings::generalSettings().chatUrl(),
Settings::generalSettings().chatEndPoint());
config.providerRequest = providerRequest;
QJsonObject request;
request["id"] = QUuid::createUuid().toString();
m_accumulatedResponse.clear();
m_chatHistory.addMessage(ChatMessage::Role::User, message);
m_requestHandler->sendLLMRequest(config, request);
}
void ChatClientInterface::clearMessages()
{
m_chatHistory.clear();
m_accumulatedResponse.clear();
logMessage("Chat history cleared");
}
QVector<ChatMessage> ChatClientInterface::getChatHistory() const
{
return m_chatHistory.getMessages();
}
void ChatClientInterface::handleLLMResponse(const QString &response, bool isComplete)
{
m_accumulatedResponse += response;
if (isComplete) {
logMessage("Message completed. Final response: " + m_accumulatedResponse);
emit messageReceived(m_accumulatedResponse.trimmed());
m_chatHistory.addMessage(ChatMessage::Role::Assistant, m_accumulatedResponse.trimmed());
m_accumulatedResponse.clear();
}
}
QJsonArray ChatClientInterface::prepareMessagesForRequest() const
{
QJsonArray messages;
messages.append(QJsonObject{{"role", "system"}, {"content", m_chatHistory.getSystemPrompt()}});
for (const auto &message : m_chatHistory.getMessages()) {
QString role;
switch (message.role) {
case ChatMessage::Role::User:
role = "user";
break;
case ChatMessage::Role::Assistant:
role = "assistant";
break;
default:
continue;
}
messages.append(QJsonObject{{"role", role}, {"content", message.content}});
}
return messages;
}
} // namespace QodeAssist::Chat

View File

@ -1,83 +0,0 @@
/*
* Copyright (C) 2024 Petr Mironychev
*
* This file is part of QodeAssist.
*
* QodeAssist is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QodeAssist is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QodeAssist. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <QObject>
#include <QString>
#include <QVector>
#include "QodeAssistData.hpp"
#include "core/LLMRequestHandler.hpp"
namespace QodeAssist::Chat {
struct ChatMessage
{
enum class Role { System, User, Assistant };
Role role;
QString content;
int tokenCount;
};
class ChatHistory
{
public:
void addMessage(ChatMessage::Role role, const QString &content);
void clear();
QVector<ChatMessage> getMessages() const;
QString getSystemPrompt() const;
void setSystemPrompt(const QString &prompt);
void trim();
private:
QVector<ChatMessage> m_messages;
QString m_systemPrompt;
int m_totalTokens = 0;
static const int MAX_HISTORY_SIZE = 50;
static const int MAX_TOKENS = 4000;
int estimateTokenCount(const QString &text) const;
};
class ChatClientInterface : public QObject
{
Q_OBJECT
public:
explicit ChatClientInterface(QObject *parent = nullptr);
~ChatClientInterface();
void sendMessage(const QString &message);
void clearMessages();
QVector<ChatMessage> getChatHistory() const;
signals:
void messageReceived(const QString &message);
void errorOccurred(const QString &error);
private:
void handleLLMResponse(const QString &response, bool isComplete);
QJsonArray prepareMessagesForRequest() const;
LLMRequestHandler *m_requestHandler;
QString m_accumulatedResponse;
ChatHistory m_chatHistory;
};
} // namespace QodeAssist::Chat

View File

@ -19,7 +19,7 @@
#pragma once
#include "ChatWidget.h"
#include "chatview/ChatWidget.hpp"
#include <coreplugin/ioutputpane.h>
namespace QodeAssist::Chat {

View File

@ -1,147 +0,0 @@
/*
* Copyright (C) 2024 Petr Mironychev
*
* This file is part of QodeAssist.
*
* QodeAssist is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QodeAssist is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QodeAssist. If not, see <https://www.gnu.org/licenses/>.
*/
#include "ChatWidget.h"
#include "QodeAssistUtils.hpp"
#include <QCoreApplication>
#include <QDateTime>
#include <QScrollBar>
#include <QVBoxLayout>
#include <QtCore/qtimer.h>
namespace QodeAssist::Chat {
ChatWidget::ChatWidget(QWidget *parent)
: QWidget(parent)
, m_showTimestamp(false)
, m_chatClient(new ChatClientInterface(this))
{
setupUi();
connect(m_sendButton, &QPushButton::clicked, this, &ChatWidget::sendMessage);
connect(m_messageInput, &QLineEdit::returnPressed, this, &ChatWidget::sendMessage);
connect(m_chatClient, &ChatClientInterface::messageReceived, this, &ChatWidget::receiveMessage);
connect(m_chatClient, &ChatClientInterface::errorOccurred, this, &ChatWidget::handleError);
logMessage("ChatWidget initialized");
}
void ChatWidget::setupUi()
{
m_chatDisplay = new QTextEdit(this);
m_chatDisplay->setReadOnly(true);
m_messageInput = new QLineEdit(this);
m_sendButton = new QPushButton("Send", this);
QHBoxLayout *inputLayout = new QHBoxLayout;
inputLayout->addWidget(m_messageInput);
inputLayout->addWidget(m_sendButton);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(m_chatDisplay);
mainLayout->addLayout(inputLayout);
setLayout(mainLayout);
}
void ChatWidget::sendMessage()
{
QString message = m_messageInput->text().trimmed();
if (!message.isEmpty()) {
logMessage("Sending message: " + message);
addMessage(message, true);
m_chatClient->sendMessage(message);
m_messageInput->clear();
addMessage("AI is typing...", false);
}
}
void ChatWidget::receiveMessage(const QString &message)
{
updateLastAIMessage(message);
}
void ChatWidget::receivePartialMessage(const QString &partialMessage)
{
logMessage("Received partial message: " + partialMessage);
m_currentAIResponse += partialMessage;
updateLastAIMessage(m_currentAIResponse);
}
void ChatWidget::onMessageCompleted()
{
updateLastAIMessage(m_currentAIResponse);
m_currentAIResponse.clear();
scrollToBottom();
}
void ChatWidget::handleError(const QString &error)
{
logMessage("Error occurred: " + error);
addMessage("Error: " + error, false);
}
void ChatWidget::addMessage(const QString &message, bool fromUser)
{
auto prefix = fromUser ? "You: " : "AI: ";
QString timestamp = m_showTimestamp ? QDateTime::currentDateTime().toString("[hh:mm:ss] ") : "";
QString fullMessage = timestamp + prefix + message;
m_chatDisplay->append(fullMessage);
scrollToBottom();
}
void ChatWidget::updateLastAIMessage(const QString &message)
{
QTextCursor cursor = m_chatDisplay->textCursor();
cursor.movePosition(QTextCursor::End);
cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
cursor.removeSelectedText();
QString timestamp = m_showTimestamp ? QDateTime::currentDateTime().toString("[hh:mm:ss] ") : "";
cursor.insertText(timestamp + "AI: " + message);
cursor.movePosition(QTextCursor::End);
m_chatDisplay->setTextCursor(cursor);
scrollToBottom();
m_chatDisplay->repaint();
}
void ChatWidget::clear()
{
m_chatDisplay->clear();
m_currentAIResponse.clear();
m_chatClient->clearMessages();
}
void ChatWidget::scrollToBottom()
{
QScrollBar *scrollBar = m_chatDisplay->verticalScrollBar();
scrollBar->setValue(scrollBar->maximum());
}
void ChatWidget::setShowTimestamp(bool show)
{
m_showTimestamp = show;
}
} // namespace QodeAssist::Chat

View File

@ -1,63 +0,0 @@
/*
* Copyright (C) 2024 Petr Mironychev
*
* This file is part of QodeAssist.
*
* QodeAssist is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QodeAssist is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QodeAssist. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QWidget>
#include "ChatClientInterface.hpp"
namespace QodeAssist::Chat {
class ChatWidget : public QWidget
{
Q_OBJECT
public:
explicit ChatWidget(QWidget *parent = nullptr);
void clear();
void scrollToBottom();
void setShowTimestamp(bool show);
void receiveMessage(const QString &message);
private slots:
void sendMessage();
void receivePartialMessage(const QString &partialMessage);
void onMessageCompleted();
void handleError(const QString &error);
private:
QTextEdit *m_chatDisplay;
QLineEdit *m_messageInput;
QPushButton *m_sendButton;
bool m_showTimestamp;
ChatClientInterface *m_chatClient;
QString m_currentAIResponse;
void setupUi();
void addMessage(const QString &message, bool fromUser = true);
void updateLastAIMessage(const QString &message);
};
} // namespace QodeAssist::Chat

View File

@ -19,7 +19,7 @@
#include "NavigationPanel.hpp"
#include "chatview/BaseChatWidget.hpp"
#include "chatview/ChatWidget.hpp"
namespace QodeAssist::Chat {
@ -37,7 +37,7 @@ NavigationPanel::~NavigationPanel()
Core::NavigationView NavigationPanel::createWidget()
{
Core::NavigationView view;
view.widget = new BaseChatWidget;
view.widget = new ChatWidget;
return view;
}