Dim Request As New WinHttpRequest
Dim Response As String
Request.Open "POST", "https://api.openai.com/v1/engines/davinci/jobs", False
Request.SetRequestHeader "Content-Type", "application/json"
Request.SetRequestHeader "Authorization", "Bearer <API_KEY>"
Request.Send "{ ""prompt"": ""What is the meaning of life?"", ""max_tokens"": 100 }"
Response = Request.ResponseText
MsgBox Response
here is working example but
I can't figure out how to use the parser
Code:
Option Explicit
Dim key, strRequest, response As String
Private Sub Command2_Click()
Dim request As New WinHttpRequest
request.Open "POST", "https://api.openai.com/v1/completions", False
request.SetRequestHeader "Content-Type", "application/json"
request.SetRequestHeader "Authorization", "Bearer " + key
request.Send "{ ""model"": ""text-davinci-003"", ""prompt"": " + Chr(34) + strRequest + Chr(34) + ", ""max_tokens"": 100 }"
response = request.ResponseText
Text3.Text = response
End Sub
Private Sub Form_Load()
key = ""
'get key from https://platform.openai.com/account/api-keys
Text1.Text = key
Text2.Text = "What is the meaning of life?"
End Sub
Private Sub Text1_Change()
key = Text1.Text
End Sub
Private Sub Text2_Change()
strRequest = Text2.Text
End Sub
response received:
Code:
{"id":"cmpl-6f7RVYXP0x3oQOJOEwzTERThe9Voj","object":"text_completion","created":1675258077,"model":"text-davinci-003","choices":[{"text":"\n\nThe meaning of life is a philosophical question that has no single definitive answer. Instead, people have different interpretations, opinions, and beliefs about the meaning of life. Some believe living a purposeful and ethical life is the highest pursuit, while others think the purpose of life is to find happiness and fulfillment. Ultimately, the meaning of life is a personal decision and belief that is unique to each individual.","index":0,"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":7,"completion_tokens":81,"total_tokens":88}}
You can try the venerable mdJson.bas from the CodeBank -- it's quite easy esp. for traversing nested heirarchies.
Use JsonValue(oJson, "$.path.to.my.array[0].property") to get (or set) a deeply nested value using standard JSON Path which is a "query language" most other languages/products support natively (e.g. handling JSON in SQL Server).
Here is a sample gist of using real-life JSON request/response with an web API. The idea is that using standard JSON Path one can easily implement request/response schema the API provides.
Lazy guy checking in. I hope somebody will post the full project once you have it all sorted out. I'd love to see this working!
Until somebody figures out the right way to do it, this crude kludge should usually work. Unless ChatGPT responds with the word Index or starts injecting ['s into it's response.
Code:
Response = request.ResponseText
V = InStr(Response, ":[{")
Response = Mid$(Response, V + 15, Len(Response))
V = InStr(Response, "index")
Response = Left$(Response, V - 4)
Last edited by Darkbob; Feb 1st, 2023 at 12:16 PM.
Option Explicit
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private m_strKey As String
Private m_strRequest As String
Private Sub Command1_Click()
Call ShellExecute(0, "open", "https://platform.openai.com/account/api-keys", 0, 0, 1)
End Sub
Private Sub Command2_Click()
Dim oRequest As WinHttpRequest
Dim oJson As Object
Set oRequest = New WinHttpRequest
oRequest.Open "POST", "https://api.openai.com/v1/completions", False
oRequest.SetRequestHeader "Content-Type", "application/json"
oRequest.SetRequestHeader "Authorization", "Bearer " + m_strKey
JsonValue(oJson, "$.model") = "text-davinci-003"
JsonValue(oJson, "$.prompt") = m_strRequest
JsonValue(oJson, "$.max_tokens") = 7
JsonValue(oJson, "$.temperature") = 0
oRequest.Send JsonDump(oJson)
Set oJson = JsonParseObject(oRequest.ResponseText)
If Not IsEmpty(JsonValue(oJson, "$.error")) Then
MsgBox JsonValue(oJson, "$.error.message"), vbExclamation, JsonValue(oJson, "$.error.type")
End If
Text3.Text = Join(JsonValue(oJson, "$.choice[*].text"), vbCrLf & vbCrLf)
End Sub
Private Sub Form_Load()
m_strKey = "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"
m_strRequest = "What is the meaning of life?"
Text1.Text = m_strKey
Text2.Text = m_strRequest
End Sub
Private Sub Text1_Change()
m_strKey = Text1.Text
End Sub
Private Sub Text2_Change()
m_strRequest = Text2.Text
End Sub
wqweto, I tried this example from the forum, without success
going the easy way, use the InStr function or Split
Darkbob yours actually, not sophisticated (; but solves the problem, indeed
in further searches for the response structure, a JSON project with the help of which I get the number of elements
Code:
112 MsgBox "Base item count: " & p.Count
VBJSON, VB6 adaptation of the VBA JSON project at code.google.com/p/vba-json/
Code:
Private Sub cmdReadJSON_Click()
Dim p As Object
100 cd.ShowOpen
102 If cd.FileName <> "" Then
104 Set p = JSON.parse(ReadTextFile(cd.FileName))
106 If Not (p Is Nothing) Then
108 If JSON.GetParserErrors <> "" Then
110 MsgBox JSON.GetParserErrors, vbInformation, "Parsing Error(s) occured"
Else
112 MsgBox "Base item count: " & p.Count
114 MsgBox "JSON toString: " & Left(JSON.toString(p), 1000)
End If
Else
116 MsgBox "An error occurred parsing " & cd.FileName
End If
End If
End Sub
but when specifying I get blank response
Darkbob's code works
Last edited by Krzysztof#; Feb 1st, 2023 at 11:32 PM.
Well.. my code doesn't do fancy stuff like add <CRLF> and it tends to cut off after the first paragraph. The JSON code would be far superior. I'm sure that JSON stuff just needs some tweaking but I'm afraid it's beyond my paygrade.
anyway without parsing, textbox has the Multiline property on, but I can be wrong, the answer should be in consecutive lines i guess
finding how needed string ends and starts, required an exception handler when it contain also the searched string so at the beginning json looked simpler...
Last edited by Krzysztof#; Feb 19th, 2023 at 12:07 PM.
in subsequent works
added saving to and reading the key from the file,
to this experiment
Code:
'Get from File if file exists
If Dir(App.Path + "\key.txt") <> "" Then
'"File exists"
Dim FREFILE2
FREFILE2 = FreeFile
Open Trim(App.Path) + Trim("\key.txt") For Input As FREFILE2
Text1.Text = Input(LOF(FREFILE2), FREFILE2)
Close FREFILE2
Else
'"File does not exist"
End If
Code:
Dim key_string
Dim FREFILE As Integer
Close 'closes all files
key_string= Trim(Text1.Text)
FREFILE = FreeFile
Open App.Path + "\key.txt" For Output As FREFILE
Print #FREFILE, key_string
Close FREFILE
and tests on how it would work with \vb6 samples from Microsoft Speech SDK 5.1 speach package,
Code:
Private Sub Check1_Click()
TTSAppMain.Show , Me
End Sub
Private Sub Text3_Change()
If Check1.Value = 1 And TTSAppMain.Visible Then
TTSAppMain.MainTxtBox.Text = Text3.Text
TTSAppMain.SpeakBtn_Click
Else
Check1.Value = 0
End If
End Sub
requires Microsoft Speech SDK 5.1 speach package installed
to make text-to-speech (TTS) enabled application
Last edited by Krzysztof#; Feb 2nd, 2023 at 06:38 AM.
Just paste some JSON response from ChatGPT API here because I constantly get "You exceeded your current quota, please check your plan and billing details" error so couldn't get an actual response from the API.
Paste a sample JSON response in [code] + [/code] tags, please.
Edit: I can see the bug I did above -- its "choices" plural not "choice" in the Text3.Text = Join(JsonValue(oJson, "$.choices[*].text"), vbCrLf & vbCrLf) line.
JsonValue(oJson, "$.choices[*].text") returns a VB array-of-strings each from text property of all objects inside choices array in the JSON response.
Then you can just Join this VB array-of-strings with double newlines between paragraphs (i.e. vbCrLf & vbCrLf) and put the joined string in Text3.Text.
Does this explanation of the original one-liner make sense? Doubt this is possible with VBA JSON project. Or any other JSON parser for VB6 I've seen before to be honest.
I’m not using ChatGPT at all. My login there is Google integrated so this cannot be leaked/hacked that easy.
They are probably geo-limiting me based on my public IP — bastards! Will buy much VPN and bring the whole AI abomination down before it’s too late :))
What happened with the JSON parsers in question? Why are these so hard to use with you? Probably their public functions (so called API) is very badly designed or something else?
Not too sure in this case. I mean ChatGPT is free to use online but I haven't looked too closely at anything concerning their API.
In any case, rate limiting is a very common thing for online APIs. HTTP requests actually take resources, even without considering responses so if you have a server end-point facing the internet where there is potential for millions of requests to come in, care must be taken to manage that lest your server be brought down due to trying to handle too many requests.
C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter
There's just no reason to use garbage like InputBox. - jmcilhinney
The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber
got value of p.Count
but I don't see where to implement the Ubound statement or similar
What's the best way to read the answer? not necessarily to read the answer with json,
parsing also may be one of the solutions, as example for me it won't be the best, in this case.
comparing to the solution used.
as this project is a side topic, i will come back to this a bit later. at the moment. working version to be developed
is more complex with json for me and code unnecessarily getting bigger with every step further down another cul-de-sac . the project should read the answer in a simple way and i do not feel no lack additional json functions. which I might not even need probably, in this project
Last edited by Krzysztof#; May 19th, 2023 at 07:09 PM.
Paste a sample JSON response in [code] + [/code] tags, please.
</wqw>
code was
Code:
{"id":"cmpl-6f7RVYXP0x3oQOJOEwzTERThe9Voj","object":"text_completion","created":1675258077,"model":"text-davinci-003","choices":[{"text":"\n\nThe meaning of life is a philosophical question that has no single definitive answer. Instead, people have different interpretations, opinions, and beliefs about the meaning of life. Some believe living a purposeful and ethical life is the highest pursuit, while others think the purpose of life is to find happiness and fulfillment. Ultimately, the meaning of life is a personal decision and belief that is unique to each individual.","index":0,"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":7,"completion_tokens":81,"total_tokens":88}}