« MBS Xojo Plugins, ver… | Home | Rectify document rect… »

Using ChatGPT in Xojo

From time to time we get asked to provide an example for ChatGPT. Since this is just another web service, we can just handle it with the MBS Xojo CURL Plugin. But since we don’t like to block the user interface while ChatGPT processes the request, we use our CURLSMultiMBS class to run it in the background. Later when finished, it performs a delegate to call our Finished method to process the result.

The request is build with the JSONItem class to fill in the various values. We include a system message with the request, e.g. “Please translate text to English.” and then pass the text to translate in the user role. This way the user should not be able to provide instructions to the LLM in their text.

To test the project, please get an account for OpenAI. In the headers we need to pass your organization ID from and the bearer token you got there. Each query will use some tokens, but we limit the answer to 100 tokens.

Here is the full method to start the query:

Sub RunQuery() Dim curl As New CURLSMBS dim MessageSystem as new JSONItem MessageSystem.Value("role") = "system" MessageSystem.Value("content") = SystemField.Text dim MessageUser as new JSONItem MessageUser.Value("role") = "user" MessageUser.Value("content") = UserField.Text dim messages as new JSONItem messages.Add MessageSystem messages.Add MessageUser dim j as new JSONItem j.Value("model") = "gpt-4o-mini" j.Value("max_tokens") = 100 j.Value("messages") = messages curl.SetOptionHTTPHeader _ array(_ "OpenAI-Organization: " +OrganizationField.text, _ "Authorization: Bearer " +BearerTokenField.text, _ "Content-Type: application/json" ) curl.OptionPostFields = j.ToString curl.OptionURL = "https://api.openai.com/v1/chat/completions" call CURLSMultiMBS.SharedInstance.AddCURL curl, AddressOf Finished End Sub

Here is the finished method, which gets called when the transfer is done. The script parameter is the CURL session reference number. We query debug messages and the result as JSON. We can then pick the output message from the JSON and show it in the field:

Sub Finished(curl as CURLSMBS, ErrorCode as Integer) // we got a result asynchronously ResultLabel.Text = ErrorCode.ToString+" "+curl.LastErrorText DebugField.Text = curl.DebugMessages ResultField.Text = curl.OutputData RunButton.Enabled = true Dim j As New JSONItem(curl.OutputData) If j.HasKey("choices") Then Dim choices As JSONItem = j.Value("choices") Dim choice As JSONItem = choices.ChildAt(0) Dim message As JSONItem = choice.Value("message") Dim content As String = message.Value("content") ResultField.Text = content End If Exception je As JSONException // handle? End Sub

Please try and see whether this can help you add ChatGPT to the projects. Translation is a good thing and you can even specify whether you like formal or informal text. We will include the example file with the next plugin for you to use.

18 10 24 - 11:47