Results 1 to 17 of 17

Thread: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Resolved [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    What's the best way to read the answer? using e.g. http://www.ediy.co.nz/vbjson-json-pa...xidc55680.html ? or other way?


    code draft in VB6 to execute the OpenAI API:
    Code:
    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}}



    view of form:
    Name:  Zrzut ekranu 2023-02-01 160950.jpg
Views: 874
Size:  24.0 KB

    References used:
    set Microsoft WinHTTP Services, version 5.1
    https://learn.microsoft.com/en-us/wi...ttp-start-page
    Last edited by Krzysztof#; Feb 19th, 2023 at 12:02 PM.

  2. #2
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,092

    Re: chatbotGPT WinHttpRequest

    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.

    cheers,
    </wqw>

  3. #3
    Fanatic Member
    Join Date
    Oct 2005
    Posts
    558

    Re: chatbotGPT WinHttpRequest

    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.

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Re: chatbotGPT WinHttpRequest

    wqweto, I still don't get over it :\




    Darkbob, great! thanks (:


    here is the result:
    Name:  Zrzut ekranu 2023-02-01 195946.jpg
Views: 757
Size:  15.6 KB


    in text1.text you need to enter your api key

    button redirects to the page where it can be generated


    Name:  Zrzut ekranu 2023-02-01 200057.jpg
Views: 781
Size:  21.7 KB











    project files:
    Attached Files Attached Files
    Last edited by Krzysztof#; Feb 1st, 2023 at 04:54 PM.

  5. #5
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,092

    Re: chatbotGPT WinHttpRequest

    Here is how to use JsonValue, JsonDump and JsonParseObject procedures from mdJson.bas module to prepare JSON request and parse JSON response according to ChatGPT API documentation for endpoint POST /v1/completions:

    Code:
    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
    cheers,
    </wqw>

  6. #6
    Fanatic Member
    Join Date
    Oct 2005
    Posts
    558

    Re: chatbotGPT WinHttpRequest

    Sure. Either way. JUST KIDDING. Use wqweto's way! That said, wqweto's sample is turning up a blank response but mine actually works. At least for me.
    Last edited by Darkbob; Feb 1st, 2023 at 05:36 PM.

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Re: chatbotGPT WinHttpRequest

    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.

  8. #8
    Fanatic Member
    Join Date
    Oct 2005
    Posts
    558

    Re: [RESOLVED] chatbotGPT WinHttpRequest

    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.

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Re: [RESOLVED] chatbotGPT WinHttpRequest

    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.

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Re: [RESOLVED] chatbotGPT WinHttpRequest

    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,

    Name:  Zrzut ekranu 2023-02-02 083330.jpg
Views: 742
Size:  18.0 KB


    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
    Attached Files Attached Files
    Last edited by Krzysztof#; Feb 2nd, 2023 at 06:38 AM.

  11. #11
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,092

    Re: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    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.

    cheers,
    </wqw>

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Re: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    Quote Originally Posted by wqweto View Post
    "You exceeded your current quota, please check your plan and billing details" error
    </wqw>
    if I had seen "You exceeded your current quota, please check your plan and billing details" error, I would look here: https://platform.openai.com/account/usage

  13. #13
    Frenzied Member VanGoghGaming's Avatar
    Join Date
    Jan 2020
    Location
    Eve Online - Mining, Missions & Market Trading!
    Posts
    1,294

    Re: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    Now you need to pay to talk to Skynet?

  14. #14
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,092

    Re: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    Quote Originally Posted by Krzysztof# View Post
    if I had seen "You exceeded your current quota, please check your plan and billing details" error, I would look here: https://platform.openai.com/account/usage
    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?

  15. #15
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    Quote Originally Posted by VanGoghGaming View Post
    Now you need to pay to talk to Skynet?
    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.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    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

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Re: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    Quote Originally Posted by wqweto View Post
    What happened with the JSON parsers in question?
    the time needed for json is disproportionate to the acceptable effect,

    I'm stuck here
    Code:
    112             MsgBox "Base item count: " & p.Count
    114             MsgBox "JSON toString: " & Left(JSON.toString(p), 1000)
    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.

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Oct 2015
    Posts
    93

    Re: [RESOLVED] chatbotGPT WinHttpRequest (with TTS)

    Quote Originally Posted by wqweto View Post
    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}}

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width