GPT-4 knows the B4X family of languages.
After a bit of back and forth, I got it to write B4J code for calling the OpenAI API.
Here is my prompt:
I had to tell it to use the JobDone event and to write it for a B4XPage. Finally, it produced this:
After a bit of back and forth, I got it to write B4J code for calling the OpenAI API.
Here is my prompt:
Could you write code in b4x that makes a call to the OpenAI API on a button click and returns the result using httpjob?
I had to tell it to use the JobDone event and to write it for a B4XPage. Finally, it produced this:
B4X:
Sub Class_Globals
Private Root As B4XView
Private xui As XUI
Private OpenAIJob As HttpJob
End Sub
Public Sub Initialize
OpenAIJob.Initialize("OpenAIJob", Me)
End Sub
Public Sub B4XPage_Create (MyRoot As Object)
Root = xui.CreatePanel("")
Root.LoadLayout("B4XMainPageLayout")
B4XPages.AddPage("B4XMainPage", Root)
Root.GetView(0).SetOnClickListener("btnCallAPI_Click")
End Sub
Sub btnCallAPI_Click (EventData As Object)
Dim apiKey As String = "your_openai_api_key_here"
Dim conversation As String = "User: Write a short story about a cat and a dog."
Dim model As String = "davinci-codex"
Dim apiUrl As String = $"https://api.openai.com/v1/engines/${model}/completions"$
Dim postData As Map
postData.Initialize
postData.Put("prompt", conversation)
postData.Put("max_tokens", 100)
postData.Put("n", 1)
postData.Put("stop", "User:")
OpenAIJob.PostString(apiUrl, CreateMapToJsonString(postData))
OpenAIJob.GetRequest.SetContentType("application/json")
OpenAIJob.GetRequest.SetHeader("Authorization", $"Bearer ${apiKey}$")
End Sub
Sub CreateMapToJsonString(data As Map) As String
Dim json As JSONGenerator
json.Initialize(data)
Return json.ToString
End Sub
Sub JobDone(j As HttpJob)
If j.Success Then
If j = OpenAIJob Then
Dim response As Map = ParseJSON(j.GetString)
Dim choices As List = response.Get("choices")
If choices.Size > 0 Then
Dim choice As Map = choices.Get(0)
Dim text As String = choice.Get("text")
Log("OpenAI API response: " & text)
Else
Log("No response found")
End If
End If
Else
Log($"Error: ${j.ErrorMessage}, Status code: ${j.Response.StatusCode}"$)
End If
j.Release
End Sub
Sub ParseJSON(json As String) As Map
Dim parser As JSONParser
parser.Initialize(json)
Return parser.NextObject
End Sub