I am making a C++ wxWidgets application, my desktop program is an interface for an LLM…
- User
I am making a C++ wxWidgets application, my desktop program is an interface for an LLM chat external command-line application, called Ollama.
Ollama is a lightweight, extensible framework for building and running language models on the local machine. It provides a simple API for creating, running, and managing models, as well as a library of pre-built models that can be easily used in a variety of applications.
It works like this,
- First, we run in one terminal: "ollama serve", which in that terminal starts a server that listen all the commands and works as a webserver inside localhost, and the only way to turn it off is by killing the process.
- Second, in another terminal, we can use "ollama run MODEL_NAME", to start a chat with said model, communicating with the server using HTTP and JSON.
I Have a Network class using cpp-httplib, with methods like HTTPGet, HTTPPost and HTTPDelete, to deal with the HTTP requests.
And for the JSON part I am using nlohmann/json library.
Tell me if you understand my setup so we can continue with the problems I am having.
- Assistant
Yes, I understand your setup. Here's a quick recap to make sure we're both on the same page:
-
Ollama Framework: You're using the Ollama framework to build and run language models locally. The framework starts a server when you run
ollama serveand it listens for commands, which you then interact with using HTTP requests. -
Communication: For communication with the Ollama server, you have a
Networkclass utilizing thecpp-httpliblibrary to make HTTP requests (GET, POST, DELETE). -
Data Handling: You are using the
nlohmann/jsonlibrary to handle JSON data, which is used for communication with the Ollama server.
You're planning to build a wxWidgets application that acts as an interface to communicate with the Ollama server, allowing you to interact with language models via HTTP and JSON.
Feel free to describe the problems you're encountering, and I'll do my best to help you resolve them.
-
- User
- Assistant
- User
You posted code, but I told you that I already have the Network code already done. Update this example with my own code:
class Network { public: ~Network(); Network(const Network&) = delete; Network operator=(const Network&) = delete; Network(Network&&) noexcept = delete; Network& operator=(Network&&) noexcept = delete; static Network& GetInstance() noexcept; void InitializeClient(const std::string& host); //... std::string HTTPPost(const std::string& host, const std::string& requestPath, const std::string& requestPayload, const std::string& contentType, int timeoutSec = -1);
private: Network(); std::string host; httplib::Client* client = nullptr;};
std::string Network::HTTPPost(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); } auto res = client->Post(requestPath.c_str(), requestPayload.c_str(), contentType.c_str()); if (res && res->status == 200) { return res->body; } throw std::runtime_error("HTTP POST request failed with status: " + std::to_string(res ? res->status : 0)); - Assistant
- User
I like it, but let's move the code to a ChatConversation (or maybe called Chat directly?) class, so we can leave the FrameMain clearer, instead of bloating it with the Chat conversation code. Why is this important? I will add a Save and Load methods to save and load past conversations, as I plan to save them in a file later, when we found out this code works correctly.
- Assistant
- User
- Assistant
- User
curl http://localhost:11434/api/chat -d '{ "model": "gemma:2b", "messages": [ { "role": "user", "content": "Hello!" } ], "stream": false }'
So I added a timeout of 120 seconds just in case, changed the code with your changes, and I tried it.
My message was "Hello!" and the richtextchatbox show this:
"Hello!
"
Then I sent the message "How are you?" the richtextchatbox show this:
"Hello!
How are you? I'm doing well, thank you for asking! I'm enjoying the opportunity to chat and learn more about your needs. What would you like to talk about? "
I tried loading other models and gave me a garbage response and I don't know if this model was good or not, so I tried the first model again using curl the same message to check it's answer:
curl http://localhost:11434/api/chat -d '{
- Assistant
- User
OK I used the get method and it still got a blank message, it is the first message after all but still isn't show:
"Hello
Hello Hello! It's a pleasure to hear from you as well. I'm happy to assist you with any questions or tasks you may have. How can I help you today? "
Then something crossed my mind, I saw the terminal response was Hello with an emoji, so I thought maybe the problem is the richtextbox and the wxString can't deal with emojis, so I tried to send it to get me to shown an emoji and there was the problem:
"Hello
Hello Hello! It's a pleasure to hear from you as well. I'm happy to assist you with any questions or tasks you may have. How can I help you today? Show me an emoji
"
So I thought it was the wxRichTextCtrl that couldn't deal with emojis so I send an emoji in the chat, and to my suprise, it is shown perfectly. So the problem here lies in the JSON parsing into a string, or maybe the Network class?
- Assistant
- User
OK, got the output and it is even weirder than I thought:
The messages were:
"Hello!
How are you? I am doing well, thank you for asking! I am ready to assist you with any questions or tasks you may have. Show me an emoji
"
16:20:46: Debug: Raw response: (null) 16:20:46: Debug: Parsed JSON: (null) 16:20:46: Debug: AI message content: (null) 16:21:26: Debug: Raw response: {"model":"gemma:2b","created_at":"2024-05-22T19:21:26.30786318Z","message":{"role":"assistant","content":"I am doing well, thank you for asking! I am ready to assist you with any questions or tasks you may have."},"done_reason":"stop","done":true,"total_duration":2521193397,"load_duration":2951783,"prompt_eval_count":14,"prompt_eval_duration":434370000,"eval_count":26,"eval_duration":1948360000} 16:21:26: Debug: Parsed JSON: {"created_at":"2024-05-22T19:21:26.30786318Z","done":true,"done_reason":"stop","eval_count":26,"eval_duration":1948360000,"load_duration":2951783,"message":{"content":"I am doing well, thank you for asking! I am ready to assist you with any questions or tasks you may have.","role":"assistant"},"model":"gemma:2b","prompt_eval_count":14,"prompt_eval_duration":434370000,"total_duration":2521193397} 16:21:26: Debug: AI message content: I am doing well, thank you for asking! I am ready to assist you with any questions or tasks you may have. 16:21:45: Debug: Raw response: (null) 16:21:45: Debug: Parsed JSON: (null) 16:21:45: Debug: AI message content: (null)
- Assistant
- User
OK here is the ouput now:
The messages were:
"Hello!
How are you? I am doing well, thank you for asking. I am here to assist you with any questions or tasks you may have. What can I do for you? Show me an emoji
- Assistant
- User
- Assistant
- User
I changed what you told me and now it seems to be working correctly, the messages were like this:
"Hello 👋 Hello! 👋 It's a pleasure to meet you as well. How can I help you today? 😊 How are you? I'm doing well, thank you for asking! I'm happy to be here and ready to assist you with whatever you need. What would you like to talk about? Show me an emoji like this: 👋 Sure, here's an emoji of a smiling face 😊.
Is there anything I can help you with today? "
So far so good, but now I found out a problem, if I click in the richtextbox so the cursor changes the last position, and then I send the message it gets written at this new cursor position instead of the end, how can I deal with this bug?
- Assistant
- User
It works perfectly now! Can also the scroll be moved to the end? It stays in the same position even when the richtextbox vertical scroll is at the top, it should be moved to the bottom.
- Assistant
Absolutely, adjusting the scroll to always focus on the latest message is an essential feature for a chat application. You can achieve this by scrolling the text control to the end after appending new messages.
- User
OK, so I made a mistake doing the keep alive method when loading a model, I used the value directly but that was taken as seconds instead of minutes, here is the faq:
By default models are kept in memory for 5 minutes before being unloaded. This allows for quicker response times if you are making numerous requests to the LLM. You may, however, want to free up the memory before the 5 minutes have elapsed or keep the model loaded indefinitely. Use the keep_alive parameter with /api/chat API endpoint to control how long the model is left in memory.
The keep_alive parameter can be set to:
a duration string (such as "10m" or "24h") a number in seconds (such as 3600) any negative number which will keep the model loaded in memory (e.g. -1 or "-1m") '0' which will unload the model immediately after generating a response
But in my model loading I use it like this:
//FrameMain.h private: //... uint32_t keepAliveMinutes;
//FrameMain.cpp //On loading method:
nlohmann::json requestPayload = { {"model", std::string(modelName.mb_str())}, {"stream", false}, {"keep_alive", keepAliveMinutes}, };
How can I fix this?
- Assistant
- User
Perfect, now I have this question, by default my server stays alive 20m after loaded but then I don't define the keep_alive in each chat message, by default the keep alive after each message is 5m. In this case should I also send this keepAliveMinutes minutes variable in my Chat.cpp, so each message increase the loading time in memory?
Parameters //... Advanced parameters (optional): //... stream: if false the response will be returned as a single response object, rather than a stream of objects keep_alive: controls how long the model will stay loaded into memory following the request (default: 5m)
- Assistant
- User
I found a bug in the way the richtextchatbox shows the text:
In this text: " Hello how are you? As an artificial intelligence text model I don't have feelings or emotions so can not say Hello! How may I assist you with your programming needs today?. Please feel free to ask me anything related to computer science, algorithms, data structures and similar topics.
"
The "topics." part was cut out and shows only "topic" and half the letter "s".
I tried another text and was cut out even worse:
"Nice, now write me a README.md of this code. Sure! Here's an example how you could structure your readme file based on the Python Hello World program provided above:"
The "above:" part was cut out and shows only "abov" and a few pixels of "e".
How can we fix this? The strange thing is this happen only on certains ocassions like these, but not in others. Maybe there is a problem with the border or something, currently the border size of the control is 5 with the flags: wxALL, wxEXPAND.
- Assistant
- User
So I added the code and it is still happening, what is weird is if I resize it I can see the words spacing themselves because of the space changing, but it still doesn't show some last characters, even if I make is really largo crossing two screens it doesn't fix. Sometimes if I maximize, it is set correctly and shows the character correctly. I see that the problem seems to be in the last word of a paragraph, maybe there is a problem there...
Here is my configuration:
wxRichTextCtrl* richTextChatBox;
richTextChatBox = new wxRichTextCtrl( panelMain, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 603,370 ), wxTE_AUTO_URL|wxTE_READONLY|wxVSCROLL ); richTextChatBox->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_INFOTEXT ) );
gbSizerMain->Add( richTextChatBox, wxGBPosition( 0, 3 ), wxGBSpan( 4, 2 ), wxEXPAND|wxALL, 5 );
How can we fix this????
- Assistant
- User
The SetBestFittingSize doesn't exist, so I just added the FitInside() and getparent layout methods only and didn't do much.
I tried several things but I ended up doing a manually indentation so I guess I fixed it, the problem is probably the wxTEXT_ALIGNMENT_RIGHT calculations of indentation and empty space of the string inside.
Now I want to add a shortcut to the send button, instead of pressing it, I want that if the user writes a message and do the combination SHIFT + ENTER, the program should act as if the send button was pressed. How can I do this?
Remember the user writes the messages in a wxTextCtrl named textCtrlChatInput.
- Assistant
- User
it works perfectly! Now something else crossed my mind, in discord when you press up, you can edit the last message, maybe not editing but can we use the up key to rewrite the last message send by the user? Would it be too difficult to do? The problem I see is, the text input control is in the main window and the chat is inside it's own class.
- Assistant
- User
Instead of saving the last message as a wxString, shouldn't be more optimum to just use the std::vectornlohmann::json chatHistory; which has the entire chat history?
- Assistant
- User
Ok, i pressed the up button and it always shows the first message not the last... can we just use diect access since it is a vector?
- Assistant
- User
- Assistant
- User
- Assistant
- User
Does this code support the chunks writing as soon as they arrive instead of waiting all the chunks to be received then writing the full response? Remember the streaming part has the advantage of writing the chunks after each parts so the user can be reading the response partially before the message is sent completely as in non-stream mode.?
- Assistant
- User
- Assistant
- User
Can you write this part again, it looks like it was an error in the message: client->create_and_start_thread(sock, & -> bool {
I think the markdown or something just deleted a character there:
Also that created several errors:
/home/.../src/Network.cpp: In member function ‘void Network::HTTPPostStream(const std::string&, const std::string&, const std::string&, const std::string&, const std::function<void(const std::__cxx11::basic_string&)>&, int)’: /home/.../src/Network.cpp:156:25: error: ‘class httplib::Client’ has no member named ‘create_socket’ 156 | auto sock = client->create_socket(); | ^~~~~~~~~~~~~ /home/.../src/Network.cpp:157:13: error: ‘class httplib::Client’ has no member named ‘create_and_start_thread’ 157 | client->create_and_start_thread(sock, & -> bool | ^~~~~~~~~~~~~~~~~~~~~~~ /home/.../src/Network.cpp:157:45: error: expected primary-expression before ‘->’ token 157 | client->create_and_start_thread(sock, & -> bool | ^~ /home/.../src/Network.cpp:157:48: error: expected unqualified-id before ‘bool’ 157 | client->create_and_start_thread(sock, & -> bool | ^~~~ Process terminated with status 1 (0 minute(s), 2 second(s))
- Assistant
- User
- Assistant