Feat: Add Claude tools support to plugin (#231)

* feat: Add settings for handle using tools in chat
* feat: Add Claude tools support
* fix: Add ai ignore to read project files list tool
* fix: Add ai ignore to read project file by name tool
* fix: Add ai ignore to read current opened files tool
This commit is contained in:
Petr Mironychev
2025-09-30 23:19:46 +02:00
committed by GitHub
parent 8aa37c5c8c
commit 10b924d78a
23 changed files with 948 additions and 84 deletions

162
providers/ClaudeMessage.cpp Normal file
View File

@ -0,0 +1,162 @@
/*
* Copyright (C) 2025 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 "ClaudeMessage.hpp"
#include "logger/Logger.hpp"
#include <QJsonArray>
#include <QJsonDocument>
namespace QodeAssist {
ClaudeMessage::ClaudeMessage(QObject *parent)
: QObject(parent)
{}
void ClaudeMessage::handleContentBlockStart(
int index, const QString &blockType, const QJsonObject &data)
{
LOG_MESSAGE(QString("ClaudeMessage: handleContentBlockStart index=%1, blockType=%2")
.arg(index)
.arg(blockType));
if (blockType == "text") {
addCurrentContent<LLMCore::TextContent>();
} else if (blockType == "tool_use") {
QString toolId = data["id"].toString();
QString toolName = data["name"].toString();
QJsonObject toolInput = data["input"].toObject();
addCurrentContent<LLMCore::ToolUseContent>(toolId, toolName, toolInput);
m_pendingToolInputs[index] = "";
}
}
void ClaudeMessage::handleContentBlockDelta(
int index, const QString &deltaType, const QJsonObject &delta)
{
if (index >= m_currentBlocks.size()) {
return;
}
if (deltaType == "text_delta") {
if (auto textContent = qobject_cast<LLMCore::TextContent *>(m_currentBlocks[index])) {
textContent->appendText(delta["text"].toString());
}
} else if (deltaType == "input_json_delta") {
QString partialJson = delta["partial_json"].toString();
if (m_pendingToolInputs.contains(index)) {
m_pendingToolInputs[index] += partialJson;
}
}
}
void ClaudeMessage::handleContentBlockStop(int index)
{
if (m_pendingToolInputs.contains(index)) {
QString jsonInput = m_pendingToolInputs[index];
QJsonObject inputObject;
if (!jsonInput.isEmpty()) {
QJsonDocument doc = QJsonDocument::fromJson(jsonInput.toUtf8());
if (doc.isObject()) {
inputObject = doc.object();
}
}
if (index < m_currentBlocks.size()) {
if (auto toolContent = qobject_cast<LLMCore::ToolUseContent *>(m_currentBlocks[index])) {
toolContent->setInput(inputObject);
}
}
m_pendingToolInputs.remove(index);
}
}
void ClaudeMessage::handleStopReason(const QString &stopReason)
{
m_stopReason = stopReason;
updateStateFromStopReason();
}
QJsonObject ClaudeMessage::toProviderFormat() const
{
QJsonObject message;
message["role"] = "assistant";
QJsonArray content;
for (auto block : m_currentBlocks) {
content.append(block->toJson(LLMCore::ProviderFormat::Claude));
}
message["content"] = content;
return message;
}
QJsonArray ClaudeMessage::createToolResultsContent(const QHash<QString, QString> &toolResults) const
{
QJsonArray results;
for (auto toolContent : getCurrentToolUseContent()) {
if (toolResults.contains(toolContent->id())) {
auto toolResult = std::make_unique<LLMCore::ToolResultContent>(
toolContent->id(), toolResults[toolContent->id()]);
results.append(toolResult->toJson(LLMCore::ProviderFormat::Claude));
}
}
return results;
}
QList<LLMCore::ToolUseContent *> ClaudeMessage::getCurrentToolUseContent() const
{
QList<LLMCore::ToolUseContent *> toolBlocks;
for (auto block : m_currentBlocks) {
if (auto toolContent = qobject_cast<LLMCore::ToolUseContent *>(block)) {
toolBlocks.append(toolContent);
}
}
return toolBlocks;
}
void ClaudeMessage::startNewContinuation()
{
LOG_MESSAGE(QString("ClaudeMessage: Starting new continuation"));
m_currentBlocks.clear();
m_pendingToolInputs.clear();
m_stopReason.clear();
m_state = LLMCore::MessageState::Building;
}
void ClaudeMessage::updateStateFromStopReason()
{
if (m_stopReason == "tool_use" && !getCurrentToolUseContent().empty()) {
m_state = LLMCore::MessageState::RequiresToolExecution;
} else if (m_stopReason == "end_turn") {
m_state = LLMCore::MessageState::Final;
} else {
m_state = LLMCore::MessageState::Complete;
}
}
} // namespace QodeAssist

View File

@ -0,0 +1,63 @@
/*
* Copyright (C) 2025 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 <llmcore/ContentBlocks.hpp>
namespace QodeAssist {
class ClaudeMessage : public QObject
{
Q_OBJECT
public:
explicit ClaudeMessage(QObject *parent = nullptr);
void handleContentBlockStart(int index, const QString &blockType, const QJsonObject &data);
void handleContentBlockDelta(int index, const QString &deltaType, const QJsonObject &delta);
void handleContentBlockStop(int index);
void handleStopReason(const QString &stopReason);
QJsonObject toProviderFormat() const;
QJsonArray createToolResultsContent(const QHash<QString, QString> &toolResults) const;
LLMCore::MessageState state() const { return m_state; }
QList<LLMCore::ToolUseContent *> getCurrentToolUseContent() const;
void startNewContinuation();
private:
QString m_stopReason;
LLMCore::MessageState m_state = LLMCore::MessageState::Building;
QList<LLMCore::ContentBlock *> m_currentBlocks;
QHash<int, QString> m_pendingToolInputs;
void updateStateFromStopReason();
template<typename T, typename... Args>
T *addCurrentContent(Args &&...args)
{
T *content = new T(std::forward<Args>(args)...);
content->setParent(this);
m_currentBlocks.append(content);
return content;
}
};
} // namespace QodeAssist

View File

@ -34,6 +34,17 @@
namespace QodeAssist::Providers {
ClaudeProvider::ClaudeProvider(QObject *parent)
: LLMCore::Provider(parent)
, m_toolsManager(new Tools::ToolsManager(this))
{
connect(
m_toolsManager,
&Tools::ToolsManager::toolExecutionComplete,
this,
&ClaudeProvider::onToolExecutionComplete);
}
QString ClaudeProvider::name() const
{
return "Claude";
@ -86,6 +97,15 @@ void ClaudeProvider::prepareRequest(
} else {
applyModelParams(Settings::chatAssistantSettings());
}
if (supportsTools() && type == LLMCore::RequestType::Chat
&& Settings::chatAssistantSettings().useTools()) {
auto toolsDefinitions = m_toolsManager->getToolsDefinitions(Tools::ToolSchemaFormat::Claude);
if (!toolsDefinitions.isEmpty()) {
request["tools"] = toolsDefinitions;
LOG_MESSAGE(QString("Added %1 tools to Claude request").arg(toolsDefinitions.size()));
}
}
}
QList<QString> ClaudeProvider::getInstalledModels(const QString &baseUrl)
@ -146,7 +166,8 @@ QList<QString> ClaudeProvider::validateRequest(const QJsonObject &request, LLMCo
{"top_p", {}},
{"top_k", {}},
{"stop", QJsonArray{}},
{"stream", {}}};
{"stream", {}},
{"tools", {}}};
return LLMCore::ValidationUtils::validateRequestFields(request, templateReq);
}
@ -174,8 +195,12 @@ LLMCore::ProviderID ClaudeProvider::providerID() const
void ClaudeProvider::sendRequest(
const LLMCore::RequestID &requestId, const QUrl &url, const QJsonObject &payload)
{
m_dataBuffers[requestId].clear();
if (!m_messages.contains(requestId)) {
m_dataBuffers[requestId].clear();
}
m_requestUrls[requestId] = url;
m_originalRequests[requestId] = payload;
QNetworkRequest networkRequest(url);
prepareNetworkRequest(networkRequest);
@ -188,52 +213,30 @@ void ClaudeProvider::sendRequest(
emit httpClient()->sendRequest(request);
}
bool ClaudeProvider::supportsTools() const
{
return true;
}
void ClaudeProvider::cancelRequest(const LLMCore::RequestID &requestId)
{
LOG_MESSAGE(QString("ClaudeProvider: Cancelling request %1").arg(requestId));
LLMCore::Provider::cancelRequest(requestId);
cleanupRequest(requestId);
}
void ClaudeProvider::onDataReceived(
const QodeAssist::LLMCore::RequestID &requestId, const QByteArray &data)
{
LLMCore::DataBuffers &buffers = m_dataBuffers[requestId];
QStringList lines = buffers.rawStreamBuffer.processData(data);
QString tempResponse;
bool isComplete = false;
for (const QString &line : lines) {
QJsonObject responseObj = parseEventLine(line);
if (responseObj.isEmpty())
continue;
QString eventType = responseObj["type"].toString();
if (eventType == "message_start") {
QString messageId = responseObj["message"].toObject()["id"].toString();
LOG_MESSAGE(QString("Claude message started: %1").arg(messageId));
} else if (eventType == "content_block_delta") {
QJsonObject delta = responseObj["delta"].toObject();
if (delta["type"].toString() == "text_delta") {
tempResponse += delta["text"].toString();
}
} else if (eventType == "message_delta") {
QJsonObject delta = responseObj["delta"].toObject();
if (delta.contains("stop_reason")) {
isComplete = true;
QJsonObject usage = responseObj["usage"].toObject();
LOG_MESSAGE(QString("Tokens: input=%1, output=%2")
.arg(usage["input_tokens"].toInt())
.arg(usage["output_tokens"].toInt()));
}
}
}
if (!tempResponse.isEmpty()) {
buffers.responseContent += tempResponse;
emit partialResponseReceived(requestId, tempResponse);
}
if (isComplete) {
emit fullResponseReceived(requestId, buffers.responseContent);
m_dataBuffers.remove(requestId);
processStreamEvent(requestId, responseObj);
}
}
@ -243,17 +246,164 @@ void ClaudeProvider::onRequestFinished(
if (!success) {
LOG_MESSAGE(QString("ClaudeProvider request %1 failed: %2").arg(requestId, error));
emit requestFailed(requestId, error);
} else {
if (m_dataBuffers.contains(requestId)) {
const LLMCore::DataBuffers &buffers = m_dataBuffers[requestId];
if (!buffers.responseContent.isEmpty()) {
emit fullResponseReceived(requestId, buffers.responseContent);
}
cleanupRequest(requestId);
return;
}
if (m_messages.contains(requestId)) {
ClaudeMessage *message = m_messages[requestId];
if (message->state() == LLMCore::MessageState::RequiresToolExecution) {
LOG_MESSAGE(QString("Waiting for tools to complete for %1").arg(requestId));
m_dataBuffers.remove(requestId);
return;
}
}
if (m_dataBuffers.contains(requestId)) {
const LLMCore::DataBuffers &buffers = m_dataBuffers[requestId];
if (!buffers.responseContent.isEmpty()) {
LOG_MESSAGE(QString("Emitting full response for %1").arg(requestId));
emit fullResponseReceived(requestId, buffers.responseContent);
}
}
cleanupRequest(requestId);
}
void ClaudeProvider::onToolExecutionComplete(
const QString &requestId, const QHash<QString, QString> &toolResults)
{
if (!m_messages.contains(requestId) || !m_requestUrls.contains(requestId)) {
LOG_MESSAGE(QString("ERROR: Missing data for continuation request %1").arg(requestId));
cleanupRequest(requestId);
return;
}
LOG_MESSAGE(QString("Tool execution complete for Claude request %1").arg(requestId));
ClaudeMessage *message = m_messages[requestId];
QJsonObject continuationRequest = m_originalRequests[requestId];
QJsonArray messages = continuationRequest["messages"].toArray();
messages.append(message->toProviderFormat());
QJsonObject userMessage;
userMessage["role"] = "user";
userMessage["content"] = message->createToolResultsContent(toolResults);
messages.append(userMessage);
continuationRequest["messages"] = messages;
LOG_MESSAGE(QString("Sending continuation request for %1 with %2 tool results")
.arg(requestId)
.arg(toolResults.size()));
sendRequest(requestId, m_requestUrls[requestId], continuationRequest);
}
void ClaudeProvider::processStreamEvent(const QString &requestId, const QJsonObject &event)
{
QString eventType = event["type"].toString();
LOG_MESSAGE(QString("Processing Claude event: type=%1").arg(eventType));
if (eventType == "message_stop") {
return;
}
ClaudeMessage *message = m_messages.value(requestId);
if (!message) {
if (eventType == "message_start") {
message = new ClaudeMessage(this);
m_messages[requestId] = message;
LOG_MESSAGE(QString("Created NEW ClaudeMessage for request %1").arg(requestId));
} else {
return;
}
}
if (eventType == "message_start") {
message->startNewContinuation();
LOG_MESSAGE(QString("Starting NEW continuation for request %1").arg(requestId));
} else if (eventType == "content_block_start") {
int index = event["index"].toInt();
QJsonObject contentBlock = event["content_block"].toObject();
QString blockType = contentBlock["type"].toString();
LOG_MESSAGE(
QString("Adding new content block: type=%1, index=%2").arg(blockType).arg(index));
message->handleContentBlockStart(index, blockType, contentBlock);
} else if (eventType == "content_block_delta") {
int index = event["index"].toInt();
QJsonObject delta = event["delta"].toObject();
QString deltaType = delta["type"].toString();
message->handleContentBlockDelta(index, deltaType, delta);
if (deltaType == "text_delta") {
QString text = delta["text"].toString();
LLMCore::DataBuffers &buffers = m_dataBuffers[requestId];
buffers.responseContent += text;
emit partialResponseReceived(requestId, text);
}
} else if (eventType == "content_block_stop") {
int index = event["index"].toInt();
message->handleContentBlockStop(index);
} else if (eventType == "message_delta") {
QJsonObject delta = event["delta"].toObject();
if (delta.contains("stop_reason")) {
QString stopReason = delta["stop_reason"].toString();
message->handleStopReason(stopReason);
handleMessageComplete(requestId);
}
}
}
void ClaudeProvider::handleMessageComplete(const QString &requestId)
{
if (!m_messages.contains(requestId))
return;
ClaudeMessage *message = m_messages[requestId];
if (message->state() == LLMCore::MessageState::RequiresToolExecution) {
LOG_MESSAGE(QString("Claude message requires tool execution for %1").arg(requestId));
auto toolUseContent = message->getCurrentToolUseContent();
if (toolUseContent.isEmpty()) {
LOG_MESSAGE(QString("No tools to execute for %1").arg(requestId));
return;
}
for (auto toolContent : toolUseContent) {
m_toolsManager->executeToolCall(
requestId, toolContent->id(), toolContent->name(), toolContent->input());
}
} else {
LOG_MESSAGE(QString("Claude message marked as complete for %1").arg(requestId));
}
}
void ClaudeProvider::cleanupRequest(const LLMCore::RequestID &requestId)
{
LOG_MESSAGE(QString("Cleaning up Claude request %1").arg(requestId));
if (m_messages.contains(requestId)) {
ClaudeMessage *message = m_messages.take(requestId);
message->deleteLater();
}
m_dataBuffers.remove(requestId);
m_requestUrls.remove(requestId);
m_originalRequests.remove(requestId);
m_toolsManager->cleanupRequest(requestId);
}
} // namespace QodeAssist::Providers

View File

@ -21,11 +21,17 @@
#include <llmcore/Provider.hpp>
#include "ClaudeMessage.hpp"
#include "tools/ToolsManager.hpp"
namespace QodeAssist::Providers {
class ClaudeProvider : public LLMCore::Provider
{
Q_OBJECT
public:
explicit ClaudeProvider(QObject *parent = nullptr);
QString name() const override;
QString url() const override;
QString completionEndpoint() const override;
@ -45,6 +51,9 @@ public:
void sendRequest(
const LLMCore::RequestID &requestId, const QUrl &url, const QJsonObject &payload) override;
bool supportsTools() const override;
void cancelRequest(const LLMCore::RequestID &requestId) override;
public slots:
void onDataReceived(
const QodeAssist::LLMCore::RequestID &requestId, const QByteArray &data) override;
@ -52,6 +61,20 @@ public slots:
const QodeAssist::LLMCore::RequestID &requestId,
bool success,
const QString &error) override;
private slots:
void onToolExecutionComplete(
const QString &requestId, const QHash<QString, QString> &toolResults);
private:
void processStreamEvent(const QString &requestId, const QJsonObject &event);
void handleMessageComplete(const QString &requestId);
void cleanupRequest(const LLMCore::RequestID &requestId);
QHash<QodeAssist::LLMCore::RequestID, ClaudeMessage *> m_messages;
QHash<QodeAssist::LLMCore::RequestID, QUrl> m_requestUrls;
QHash<QodeAssist::LLMCore::RequestID, QJsonObject> m_originalRequests;
Tools::ToolsManager *m_toolsManager;
};
} // namespace QodeAssist::Providers