Following on from:
https://www.b4x.com/android/forum/threads/gpt-3.145654/post-923913
and seeing as a ChatGPT API has emerged, I have cobbled together the following raw ChatGPT class.
You can take it in all sorts of directions from here...
I haven't tested it but it should also work in B4i and B4J.
You can call it with code like:
The really cool bit is using ChatGPT to generate the JSON parsing subroutine.
https://www.b4x.com/android/forum/threads/gpt-3.145654/post-923913
and seeing as a ChatGPT API has emerged, I have cobbled together the following raw ChatGPT class.
You can take it in all sorts of directions from here...
I haven't tested it but it should also work in B4i and B4J.
B4X:
'This class is now very loosely based on:
'https://www.b4x.com/android/forum/threads/gpt-3.145654/#content
'by Abdull Cadre to which I say thanks again
Sub Class_Globals
End Sub
'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
End Sub
Public Sub Query(system_string As String, query_string As String) As ResumableSub
'For complete documentation you should look at:
'https://platform.openai.com/docs/api-reference/chat
Try
Dim chat_string As String
chat_string = "{""model"":""gpt-3.5-turbo"",""messages"":[{""role"": ""system"", ""content"":""" & _
system_string & """},{""role"": ""user"", ""content"":""" & _
query_string & "?""}]}"
'Uncomment this line if you want to see raw input string
'Log(chat_string)
'You can add optional parameters by just adding them to the end, e.g.:
'chat_string = "{""model"":""gpt-3.5-turbo"",""messages"":[{""role"": ""system"", ""content"":""" & _
' system_string & """},{""role"": ""user"", ""content"":""" & _
' query_string & "?""}],""temperature"":""2""}"
'for details of all options available see reference given above
Dim response As String
Dim req As Http_Job
req.Initialize("", Me)
req.PostString("https://api.openai.com/v1/chat/completions", chat_string)
'You can quite easily generate your own account API key by following
'https://accessibleai.dev/post/generating_text_with_gpt_and_python/
'under heading [Getting a GPT-3 API Key]
req.GetRequest.SetHeader("Authorization", "Bearer sk-xxx")
'And if you have an organisation key...
'If your account default organisation is "Personal" then you can supply
'a blank organisation key - or just comment this line out
'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
req.GetRequest.SetHeader("OpenAI-Organization", "")
req.GetRequest.SetContentType("application/json")
Wait For (req) JobDone(req As Http_Job)
If req.Success Then
'Uncomment this line if you want to see raw JSON response
'Log(req.GetString)
response = ParseJson(req.GetString)
Else
response = "ERROR: " & req.ErrorMessage
End If
req.Release
Catch
response = "ERROR: " & LastException
End Try
Return response
End Sub
'I did as JohnC suggested in:
'https://www.b4x.com/android/forum/threads/lost-in-chatgpt-json.146738/post-930211
'and asked ChatGPT:
'using b4a how do I parse this json string: "{""id"":""chatcmpl-6t2JQdgU1ypn0ayhONAkE6bAEoGkz"",""object"":""chat.completion"",""created"":1678574948,""model"":""gpt-3.5-turbo-0301"",""usage"":{""prompt_tokens"":25,""completion_tokens"":110,""total_tokens"":135},""choices"":[{""message"":{""role"":""assistant"",""content"":""Ahoy matey, ye be askin' a great question. The worst investment be ones that promise quick riches without flappin' yer sails too much, like the \""get rich quick\"" schemes, ponzi schemes Or pyramid schemes. These scams be all about misuse of trust And deceivin' the inexperienced. They be luring investors with high promised returns, but in the end, they just take yer doubloons and disappear into the horizon. Stay away from such crooks and keep yer treasure safe, me hearty!""},""finish_reason"":""stop"",""index"":0}]}" for content
'and it responded with this - except it used a variable named "object" which
'B4A objected to that I had to change to "object_string"
'I also had to change the management of the variable "content" so the subroutine would return a result
Sub ParseJson(json As String) As String
Dim parser As JSONParser
parser.Initialize(json)
Dim root As Map
root = parser.NextObject
Dim id As String
id = root.Get("id")
Dim object_string As String
object_string = root.Get("object")
Dim created As Long
created = root.Get("created")
Dim model As String
model = root.Get("model")
Dim usage As Map
usage = root.Get("usage")
Dim promptTokens As Int
promptTokens = usage.Get("prompt_tokens")
Dim completionTokens As Int
completionTokens = usage.Get("completion_tokens")
Dim totalTokens As Int
totalTokens = usage.Get("total_tokens")
Dim choices As List
choices = root.Get("choices")
Dim choiceIndex As Int
Dim content As String
For choiceIndex = 0 To choices.Size - 1
Dim choice As Map
choice = choices.Get(choiceIndex)
Dim message As Map
message = choice.Get("message")
Dim role As String
role = message.Get("role")
If content <> "" Then content = content & CRLF
content = content & message.Get("content")
Dim finishReason As String
finishReason = choice.Get("finish_reason")
Log("Choice " & choiceIndex)
Log("Role: " & role)
Log("Content: " & content)
Log("Finish Reason: " & finishReason)
Next
Return content
End Sub
You can call it with code like:
B4X:
Private wrk_chat As ChatGPT
wrk_chat.Initialize
Wait For (wrk_chat.Query("Assistant should act like a pirate", "what is the absolute worst investment")) Complete (response As String)
Log(response)
The really cool bit is using ChatGPT to generate the JSON parsing subroutine.
Last edited: