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. Maybe, there is something else, like using a different thread, or maybe the writing is blocked by not using a different thread for this writing, I don’t know so I need you to check my code, and find the problem or what is causing to not write it as soon as the token arrives.
What I already tried:
- Using wxThread, didn’t work correctly at all, and gave compilation errors.
- Using std::future, didn’t work, didn’t even print the messages.
- Using std::thread, this is my last implementation, works but doesn’t print it as soon as they arrive, this is what worked the best.
I asked another LLM AI, and it told me this, maybe we can follow this lead:
How can I deal with the way the message are received and then written out in real time instead of the application getting blocked until all message parts are completed?
In C++, you can achieve non-blocking message processing using threads and synchronization mechanisms like condition variables or semaphores. Here's a general outline of how you can implement real-time message processing without blocking the application in C++:
- Set up a message queue to store incoming message parts.
- Create a separate thread to continuously check for new message parts in the queue.
- When a new message part arrives, add it to the queue.
- In the separate thread, continuously check if there are complete messages in the queue.
- If a complete message is found, process it (e.g., write it out) and remove it from the queue.
- If no complete message is found, wait for a short period of time before checking again.
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 <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::vector<nlohmann::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"].get<std::string>()}
});
if (eventHandler)
{
wxLogDebug("Received chunk: %s", jsonChunk.dump().c_str());
wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED);
event.SetString(jsonChunk["message"]["content"].get<std::string>());
wxQueueEvent(eventHandler, event.Clone());
}
}
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<bool>())
{
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<bool>())
{
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<bool>());
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::vector<nlohmann::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"].get<std::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_guard<std::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"].get<std::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"].get<std::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());
}
}