Perfect, I am right now in the process of writing each of these tokens or message parts into a wxRichTextCtrl, which is the chat interface that has the messages both of the user and the AI LLM. So far, I successfully used threads and events to send each token to the Chat class, which is in charge of writing each of these chat messages to the wxRichTextCtrl, and even though, the code seems to work correctly in theory, in practice, it only shows the tokens at the end of the communication with the server, I don’t understand why is this happening, it should be writing them as soon as they arrive, and you can check this from the code.
The issue seems to be that all token messages are being delayed until the entire response is received.
I tried change the wxQueueEvent for a wxCallAfter but it is giving me errors, help me fix it and follow my idea of using the wxCallAfter:
/home/.../src/Network.cpp: In member function ‘std::string Network::HTTPPostStream(wxEvtHandler*, const std::string&, const std::string&, const std::string&, const std::string&, int)’:
/home/.../src/Network.cpp:186:33: error: ‘wxCallAfter’ was not declared in this scope
186 | wxCallAfter(eventHandler, event{
| ^~~~~~~~~~~
Here is the code of my Frame, Network, and Chat classes:
#include “Chat.h”
#include <wx/event.h>
#include <wx/string.h>
#include <wx/timer.h>
class FrameMain : public FrameMainView
{
public:
//…
void OnSendClick(wxCommandEvent& event) override;
private:
//…
void StartChat();
//…
Chat* chat;
};
void FrameMain::OnSendClick(wxCommandEvent& event)
{
wxString userMessage = textCtrlChatInput->GetValue();
if (!userMessage.empty())
{
chat->SendMessage(userMessage);
textCtrlChatInput->Clear();
}
}
void FrameMain::StartChat()
{
EnableChatControls(true);
richTextChatBox->Clear();
chat = new Chat(host, bcomboBoxModel->GetStringSelection(), keepAliveMinutes, streaming, richTextChatBox);
}
#include
#include <cpp-httplib/httplib.h>
#include <wx/event.h>
class Network
{
public:
//… singleton and other methods
std::string HTTPPostStream(wxEvtHandler* eventHandler, const std::string& host, const std::string& requestPath, const std::string& requestPayload, const std::string& contentType, int timeoutSec = -1);
private:
//…
std::string host;
httplib::Client* client = nullptr;
};
#include “Network.h”
#include
#include
#include
#include
#include <wx/wx.h>
#include <nlohmann/json.hpp>
// This method has two returning ways, one is returning each token using the event handler, so each token can be written down, and the full
// std::string with the full message, so that way it can be saved in the chat history.
std::string Network::HTTPPostStream(wxEvtHandler* eventHandler, const std::string& host, const std::string& requestPath, const std::string& requestPayload, const std::string& contentType, int timeoutSec)
{
InitializeClient(host);
if (timeoutSec > 0)
{
client->set_connection_timeout(timeoutSec, 0);
client->set_read_timeout(timeoutSec, 0);
}
std::vectornlohmann::json jsonChunks;
nlohmann::json finalJson;
auto res = client->Post(requestPath.c_str(), requestPayload.c_str(), contentType.c_str());
// Ensure the request was successful
if (res && res->status == 200)
{
try
{
do
{
std::istringstream responseStream(res->body);
std::string line;
while (std::getline(responseStream, line))
{
if (line.empty())
{
continue;
}
try
{
auto jsonChunk = nlohmann::json::parse(line);
if (jsonChunk.contains(“message”) && jsonChunk[“message”].contains(“content”))
{
jsonChunks.push_back({
{“role”, “assistant”},
{“content”, jsonChunk[“message”][“content”].getstd::string()}
});
if (eventHandler)
{
wxLogDebug("Received chunk: %s", jsonChunk.dump().c_str());
wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED);
event.SetString(jsonChunk["message"]["content"].getstd::string());
wxCallAfter(eventHandler, event{
wxEvent* clonedEvent = event.Clone();
if (clonedEvent)
{
eventHandler->AddPendingEvent(*clonedEvent);
delete clonedEvent;
}
});
}
}
finalJson[“model”] = jsonChunk[“model”];
finalJson[“created_at”] = jsonChunk[“created_at”];
finalJson[“done”] = jsonChunk[“done”];
if (jsonChunk.contains(“total_duration”)) finalJson[“total_duration”] = jsonChunk[“total_duration”];
if (jsonChunk.contains(“load_duration”)) finalJson[“load_duration”] = jsonChunk[“load_duration”];
if (jsonChunk.contains(“prompt_eval_count”)) finalJson[“prompt_eval_count”] = jsonChunk[“prompt_eval_count”];
if (jsonChunk.contains(“prompt_eval_duration”)) finalJson[“prompt_eval_duration”] = jsonChunk[“prompt_eval_duration”];
if (jsonChunk.contains(“eval_count”)) finalJson[“eval_count”] = jsonChunk[“eval_count”];
if (jsonChunk.contains(“eval_duration”)) finalJson[“eval_duration”] = jsonChunk[“eval_duration”];
if (jsonChunk[“done”].get())
{
break;
}
}
catch (const nlohmann::json::parse_error& e)
{
std::cerr << “Error parsing JSON chunk: " << e.what() << std::endl;
}
}
// Prepare for the next request if not done
if (!finalJson[“done”].get())
{
res = client->Get(”/“);
if (!(res && res->status == 200))
{
std::cerr << “Failed to get the subsequent chunk with status: " << (res ? res->status : 0) << std::endl;
break;
}
}
} while (!finalJson[“done”].get());
finalJson[“message”] = {
{“role”, “assistant”},
{“content”, “”}
};
std::string content;
for (const auto& chunk : jsonChunks)
{
content += chunk[“content”];
}
finalJson[“message”][“content”] = content;
return finalJson.dump();
}
catch (const std::exception& e)
{
std::cerr << “Error processing JSON response: " << e.what() << std::endl;
}
}
else
{
std::cerr << “POST request failed with status: " << res->status << std::endl;
}
throw std::runtime_error(“HTTP POST Stream request failed with status: " + std::to_string(res ? res->status : 0));
}
#include
#include
#include
#include
#include <wx/wx.h>
#include <wx/event.h>
#include <wx/string.h>
#include <wx/richtext/richtextctrl.h>
#include <nlohmann/json.hpp>
class Chat : public wxEvtHandler
{
public:
Chat(const wxString& host, const wxString& modelName, uint32_t keepAliveMinutes, bool streaming, wxRichTextCtrl* richTextChatBox);
~Chat();
void SendMessage(const wxString& userMessage);
wxString GetLastUserMessage() const;
private:
void AppendMessage(const wxString& message, const wxString& role);
void OnNewToken(wxCommandEvent& event);
void SendMessageAsync(const wxString& userMessage);
wxString host;
wxString modelName;
uint32_t keepAliveMinutes;
bool streaming;
wxRichTextCtrl* richTextChatBox;
std::vectornlohmann::json chatHistory;
std::thread* workerThread = nullptr;
std::mutex mutex;
};
#include “Chat.h”
#include “Network.h”
#include
#include <wx/log.h>
Chat::Chat(const wxString& host, const wxString& modelName, uint32_t keepAliveMinutes, bool streaming, wxRichTextCtrl* richTextChatBox) : host(host), modelName(modelName), keepAliveMinutes(keepAliveMinutes), streaming(streaming), richTextChatBox(richTextChatBox)
{
Bind(wxEVT_COMMAND_TEXT_UPDATED, &Chat::OnNewToken, this);
}
Chat::~Chat()
{
if (workerThread && workerThread->joinable())
{
workerThread->join();
}
delete workerThread;
}
void Chat::SendMessage(const wxString& userMessage)
{
AppendMessage(userMessage, “user”);
chatHistory.push_back({
{“role”, “user”},
{“content”, std::string(userMessage.utf8_str())}
});
if (workerThread && workerThread->joinable())
{
workerThread->join();
delete workerThread;
workerThread = nullptr;
}
workerThread = new std::thread(&Chat::SendMessageAsync, this, userMessage);
}
wxString Chat::GetLastUserMessage() const
{
wxString message = wxEmptyString;
for (auto it = chatHistory.rbegin(); it != chatHistory.rend(); ++it)
{
if ((*it)[“role”] == “user”)
{
message = wxString::FromUTF8((*it)[“content”].getstd::string().c_str());
break;
}
}
return message;
}
void Chat::AppendMessage(const wxString& message, const wxString& role)
{
wxTextAttr style;
if (role == “user”)
{
style.SetAlignment(wxTEXT_ALIGNMENT_LEFT);
style.SetBackgroundColour(wxColour(”#4A67CF”));
style.SetTextColour(wxColour(”#FFFFFF”));
style.SetLeftIndent(20);
style.SetRightIndent(5);
}
else
{
style.SetAlignment(wxTEXT_ALIGNMENT_LEFT);
style.SetBackgroundColour(wxColour(”#2B651A"));
style.SetTextColour(wxColour(“#FFFFFF”));
style.SetLeftIndent(5);
style.SetRightIndent(20);
}
{
std::lock_guardstd::mutex lock(mutex);
richTextChatBox->Freeze();
richTextChatBox->SetInsertionPointEnd();
richTextChatBox->BeginStyle(style);
richTextChatBox->WriteText(message + (streaming ? “” : “\n”));
richTextChatBox->EndStyle();
richTextChatBox->SetInsertionPointEnd();
richTextChatBox->ShowPosition(richTextChatBox->GetLastPosition());
richTextChatBox->Thaw();
richTextChatBox->Update();
richTextChatBox->Refresh();
}
}
void Chat::OnNewToken(wxCommandEvent& event)
{
wxMutexGuiEnter();
wxLogDebug(“OnNewToken: %s”, event.GetString().c_str());
AppendMessage(event.GetString(), “assistant”);
wxMutexGuiLeave();
}
void Chat::SendMessageAsync(const wxString& userMessage)
{
nlohmann::json requestBody = {
{“model”, modelName.ToStdString()},
{“messages”, chatHistory},
{“stream”, streaming},
{“keep_alive”, keepAliveMinutes > 0 ? (std::to_string(keepAliveMinutes) + “m”) : std::to_string(keepAliveMinutes)}
};
wxLogDebug(“Constructed request body: %s”, requestBody.dump().c_str());
try
{
Network& network = Network::GetInstance();
AppendMessage(“\n”, “assistant”);
if (streaming)
{
std::string response = network.HTTPPostStream(this, host.ToStdString(), “/api/chat”, requestBody.dump(), “application/json”, 120);
if (!response.empty())
{
nlohmann::json j = nlohmann::json::parse(response);
wxLogDebug(“Parsed JSON: %s”, j.dump().c_str());
if (j.contains(“message”) && j[“message”].contains(“content”))
{
std::string aiMessage = j[“message”][“content”].getstd::string();
wxLogDebug(“AI message content: %s”, aiMessage.c_str());
chatHistory.push_back({
{“role”, “assistant”},
{“content”, aiMessage}
});
}
else
{
wxLogDebug(“Parsed JSON does not contain required fields.”);
}
}
else
{
wxLogDebug(“Received empty response from server”);
}
}
else
{
std::string response = network.HTTPPost(host.ToStdString(), “/api/chat”, requestBody.dump(), “application/json”, 120);
wxLogDebug(“Raw response: %s”, response.c_str());
if (!response.empty())
{
nlohmann::json j = nlohmann::json::parse(response);
wxLogDebug(“Parsed JSON: %s”, j.dump().c_str());
if (j.contains(“message”) && j[“message”].contains(“content”))
{
std::string aiMessage = j[“message”][“content”].getstd::string();
wxLogDebug(“AI message content: %s”, aiMessage.c_str());
AppendMessage(wxString::FromUTF8(aiMessage.c_str()), “assistant”);
chatHistory.push_back({
{“role”, “assistant”},
{“content”, aiMessage}
});
}
else
{
wxLogDebug(“Parsed JSON does not contain required fields.”);
}
}
else
{
wxLogDebug(“Received empty response from server”);
}
}
}
catch (const std::exception& e)
{
wxLogError(“Failed to communicate with the server: %s”, e.what());
}
}