refactor: Adapt provider to clients API

This commit is contained in:
Petr Mironychev
2026-03-30 08:08:49 +02:00
parent e55e96714b
commit 545b8ed000
21 changed files with 697 additions and 2958 deletions

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (C) 2024-2025 Petr Mironychev
*
* This file is part of QodeAssist.
@ -39,12 +39,6 @@ LlamaCppProvider::LlamaCppProvider(QObject *parent)
, m_client(new ::LLMCore::LlamaCppClient(url(), apiKey(), QString(), this))
{
Tools::registerQodeAssistTools(m_client->tools());
connect(
m_client->tools(),
&::LLMCore::ToolsManager::toolExecutionComplete,
this,
&LlamaCppProvider::onToolExecutionComplete);
}
QString LlamaCppProvider::name() const
@ -109,11 +103,6 @@ void LlamaCppProvider::prepareRequest(
}
if (isToolsEnabled) {
PluginLLMCore::RunToolsFilter filter = PluginLLMCore::RunToolsFilter::ALL;
if (type == PluginLLMCore::RequestType::QuickRefactoring) {
filter = PluginLLMCore::RunToolsFilter::OnlyRead;
}
auto toolsDefinitions = m_client->tools()->getToolsDefinitions();
if (!toolsDefinitions.isEmpty()) {
request["tools"] = toolsDefinitions;
@ -183,20 +172,69 @@ PluginLLMCore::ProviderID LlamaCppProvider::providerID() const
void LlamaCppProvider::sendRequest(
const PluginLLMCore::RequestID &requestId, const QUrl &url, const QJsonObject &payload)
{
if (!m_messages.contains(requestId)) {
m_dataBuffers[requestId].clear();
}
QUrl baseUrl(url);
baseUrl.setPath("");
m_client->setUrl(baseUrl.toString());
m_client->setApiKey(apiKey());
m_requestUrls[requestId] = url;
m_originalRequests[requestId] = payload;
::LLMCore::RequestCallbacks callbacks;
QNetworkRequest networkRequest(url);
prepareNetworkRequest(networkRequest);
callbacks.onChunk = [this, requestId](const ::LLMCore::RequestID &, const QString &chunk) {
if (m_awaitingContinuation.remove(requestId)) {
emit continuationStarted(requestId);
}
emit partialResponseReceived(requestId, chunk);
};
LOG_MESSAGE(
QString("LlamaCppProvider: Sending request %1 to %2").arg(requestId, url.toString()));
callbacks.onCompleted
= [this, requestId](const ::LLMCore::RequestID &clientId, const QString &fullText) {
emit fullResponseReceived(requestId, fullText);
m_providerToClientIds.remove(requestId);
m_clientToProviderIds.remove(clientId);
m_awaitingContinuation.remove(requestId);
};
httpClient()->postStreaming(requestId, networkRequest, payload);
callbacks.onFailed
= [this, requestId](const ::LLMCore::RequestID &clientId, const QString &error) {
emit requestFailed(requestId, error);
m_providerToClientIds.remove(requestId);
m_clientToProviderIds.remove(clientId);
m_awaitingContinuation.remove(requestId);
};
callbacks.onThinkingBlock = [this, requestId](const ::LLMCore::RequestID &,
const QString &thinking,
const QString &signature) {
if (m_awaitingContinuation.remove(requestId)) {
emit continuationStarted(requestId);
}
if (thinking.isEmpty()) {
emit redactedThinkingBlockReceived(requestId, signature);
} else {
emit thinkingBlockReceived(requestId, thinking, signature);
}
};
callbacks.onToolStarted = [this, requestId](const ::LLMCore::RequestID &,
const QString &toolId,
const QString &toolName) {
emit toolExecutionStarted(requestId, toolId, toolName);
m_awaitingContinuation.insert(requestId);
};
callbacks.onToolResult = [this, requestId](const ::LLMCore::RequestID &,
const QString &toolId,
const QString &toolName,
const QString &result) {
emit toolExecutionCompleted(requestId, toolId, toolName, result);
};
auto clientId = m_client->sendMessage(payload, callbacks);
m_providerToClientIds[requestId] = clientId;
m_clientToProviderIds[clientId] = requestId;
LOG_MESSAGE(QString("LlamaCppProvider: Sending request %1 (client: %2) to %3")
.arg(requestId, clientId, url.toString()));
}
bool LlamaCppProvider::supportsTools() const
@ -212,228 +250,13 @@ bool LlamaCppProvider::supportImage() const
void LlamaCppProvider::cancelRequest(const PluginLLMCore::RequestID &requestId)
{
LOG_MESSAGE(QString("LlamaCppProvider: Cancelling request %1").arg(requestId));
PluginLLMCore::Provider::cancelRequest(requestId);
cleanupRequest(requestId);
}
void LlamaCppProvider::onDataReceived(
const QodeAssist::PluginLLMCore::RequestID &requestId, const QByteArray &data)
{
PluginLLMCore::DataBuffers &buffers = m_dataBuffers[requestId];
QStringList lines = buffers.rawStreamBuffer.processData(data);
for (const QString &line : lines) {
if (line.trimmed().isEmpty() || line == "data: [DONE]") {
continue;
}
QJsonObject chunk = parseEventLine(line);
if (chunk.isEmpty())
continue;
if (chunk.contains("content")) {
QString content = chunk["content"].toString();
if (!content.isEmpty()) {
buffers.responseContent += content;
emit partialResponseReceived(requestId, content);
}
if (chunk["stop"].toBool()) {
emit fullResponseReceived(requestId, buffers.responseContent);
m_dataBuffers.remove(requestId);
}
} else if (chunk.contains("choices")) {
processStreamChunk(requestId, chunk);
}
if (m_providerToClientIds.contains(requestId)) {
auto clientId = m_providerToClientIds.take(requestId);
m_clientToProviderIds.remove(clientId);
m_client->cancelRequest(clientId);
}
}
void LlamaCppProvider::onRequestFinished(
const QodeAssist::PluginLLMCore::RequestID &requestId, std::optional<QString> error)
{
if (error) {
LOG_MESSAGE(QString("LlamaCppProvider request %1 failed: %2").arg(requestId, *error));
emit requestFailed(requestId, *error);
cleanupRequest(requestId);
return;
}
if (m_messages.contains(requestId)) {
OpenAIMessage *message = m_messages[requestId];
if (message->state() == PluginLLMCore::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 PluginLLMCore::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 LlamaCppProvider::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 llama.cpp request %1").arg(requestId));
for (auto it = toolResults.begin(); it != toolResults.end(); ++it) {
OpenAIMessage *message = m_messages[requestId];
auto toolContent = message->getCurrentToolUseContent();
for (auto tool : toolContent) {
if (tool->id() == it.key()) {
auto toolStringName = m_client->tools()->displayName(tool->name());
emit toolExecutionCompleted(
requestId, tool->id(), toolStringName, toolResults[tool->id()]);
break;
}
}
}
OpenAIMessage *message = m_messages[requestId];
QJsonObject continuationRequest = m_originalRequests[requestId];
QJsonArray messages = continuationRequest["messages"].toArray();
messages.append(message->toProviderFormat());
QJsonArray toolResultMessages = message->createToolResultMessages(toolResults);
for (const auto &toolMsg : toolResultMessages) {
messages.append(toolMsg);
}
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 LlamaCppProvider::processStreamChunk(const QString &requestId, const QJsonObject &chunk)
{
QJsonArray choices = chunk["choices"].toArray();
if (choices.isEmpty()) {
return;
}
QJsonObject choice = choices[0].toObject();
QJsonObject delta = choice["delta"].toObject();
QString finishReason = choice["finish_reason"].toString();
OpenAIMessage *message = m_messages.value(requestId);
if (!message) {
message = new OpenAIMessage(this);
m_messages[requestId] = message;
LOG_MESSAGE(QString("Created NEW OpenAIMessage for llama.cpp request %1").arg(requestId));
if (m_dataBuffers.contains(requestId)) {
emit continuationStarted(requestId);
LOG_MESSAGE(QString("Starting continuation for request %1").arg(requestId));
}
} else if (
m_dataBuffers.contains(requestId)
&& message->state() == PluginLLMCore::MessageState::RequiresToolExecution) {
message->startNewContinuation();
emit continuationStarted(requestId);
LOG_MESSAGE(QString("Cleared message state for continuation request %1").arg(requestId));
}
if (delta.contains("content") && !delta["content"].isNull()) {
QString content = delta["content"].toString();
message->handleContentDelta(content);
PluginLLMCore::DataBuffers &buffers = m_dataBuffers[requestId];
buffers.responseContent += content;
emit partialResponseReceived(requestId, content);
}
if (delta.contains("tool_calls")) {
QJsonArray toolCalls = delta["tool_calls"].toArray();
for (const auto &toolCallValue : toolCalls) {
QJsonObject toolCall = toolCallValue.toObject();
int index = toolCall["index"].toInt();
if (toolCall.contains("id")) {
QString id = toolCall["id"].toString();
QJsonObject function = toolCall["function"].toObject();
QString name = function["name"].toString();
message->handleToolCallStart(index, id, name);
}
if (toolCall.contains("function")) {
QJsonObject function = toolCall["function"].toObject();
if (function.contains("arguments")) {
QString args = function["arguments"].toString();
message->handleToolCallDelta(index, args);
}
}
}
}
if (!finishReason.isEmpty() && finishReason != "null") {
for (int i = 0; i < 10; ++i) {
message->handleToolCallComplete(i);
}
message->handleFinishReason(finishReason);
handleMessageComplete(requestId);
}
}
void LlamaCppProvider::handleMessageComplete(const QString &requestId)
{
if (!m_messages.contains(requestId))
return;
OpenAIMessage *message = m_messages[requestId];
if (message->state() == PluginLLMCore::MessageState::RequiresToolExecution) {
LOG_MESSAGE(QString("llama.cpp 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) {
auto toolStringName = m_client->tools()->displayName(toolContent->name());
emit toolExecutionStarted(requestId, toolContent->id(), toolStringName);
m_client->tools()->executeToolCall(
requestId, toolContent->id(), toolContent->name(), toolContent->input());
}
} else {
LOG_MESSAGE(QString("llama.cpp message marked as complete for %1").arg(requestId));
}
}
void LlamaCppProvider::cleanupRequest(const PluginLLMCore::RequestID &requestId)
{
LOG_MESSAGE(QString("Cleaning up llama.cpp request %1").arg(requestId));
if (m_messages.contains(requestId)) {
OpenAIMessage *message = m_messages.take(requestId);
message->deleteLater();
}
m_dataBuffers.remove(requestId);
m_requestUrls.remove(requestId);
m_originalRequests.remove(requestId);
m_client->tools()->cleanupRequest(requestId);
m_awaitingContinuation.remove(requestId);
}
::LLMCore::ToolsManager *LlamaCppProvider::toolsManager() const