B4J Question [SOLVED] No access to ChatGPT despite API key. What am I doing wrong?

Watchkido1

Active Member
Licensed User
Longtime User
Hello folks

I get this error message: "message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username ) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",

Libraries: jCore9.80, jFX 9.8, jOkHttpUtils 3.03, Json 1.21, jXUI 2.20
The credit card is linked at: https://platform.openai.com/settings/organization/billing/overview
API-Key ist okay: https://platform.openai.com/api-keys
What does ChatGPT want from me?

I have the paid version of ChatGPT, the code is entered (key has been changed here) and this is my code:


Main.b4j:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 600
#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI
    Private Button1 As B4XView
    Private Button2 As Button
    'Private http As jOkHttpUtils2
    'Private Json As JSONParser
    Private wrk_chat As ChatGPT
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
End Sub

Sub Button1_Click
 
    wrk_chat.Initialize
    Wait For (wrk_chat.Query("Du bist ein hilfreicher Assisternt", "Wer ist Donald Trump?")) Complete (response As String)
    Log(response)
    Return
End Sub


ChatGPT.bas:
Sub Class_Globals
    Private fx As JFX
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
 
End Sub
'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

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 HttpJob
        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", "sk-proj-puvewkq8j2cApxhxhxhxhxhxhxhxhxhxhxhxhxhxhxh")
 
        '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", "org-bWMtxhxhxhxhxhxhxhxhxhxhxMcH1")
 
        req.GetRequest.SetContentType("application/json")
 
        Wait For (req) JobDone(req As HttpJob)
 
        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
'Ich habe es so gemacht, wie JohnC es vorgeschlagen hat:
'https://www.b4x.com/android/forum/threads/lost-in-chatgpt-json.146738/post-930211
'und habe ChatGPT gefragt:
'Wie analysiere ich mit b4a diesen JSON-String: "{""id"":""chatcmpl-6t2JQdgxhxhxhxhxhxbAEoGkz"",""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"":""Ahoi, Kumpel, das ist eine gute Frage. Die schlechtesten Investitionen sind solche, die schnellen Reichtum versprechen, ohne zu viel mit den Segeln zu flattern, wie die \""schnell reich werden\"-Systeme, Ponzi-Systeme oder Pyramidensysteme. Bei diesen Betrügereien dreht sich alles um Vertrauensmissbrauch und Täuschung der Unerfahrenen. Sie locken Investoren mit hohen versprochenen Renditen, aber am Ende nehmen sie nur Ihre Dublonen und verschwinden am Horizont. Halten Sie sich von solchen Gaunern fern und bewahren Sie Ihren Schatz sicher auf, meine Güte!""},""finish_reason"":""stop"",""index"":0}]}" für Inhalt
'und es antwortete mit folgendem - außer dass es eine Variable namens "Objekt" verwendete, die
'B4A beanstandete, die ich in "Objekt_Zeichenfolge" ändern musste
'Ich musste auch die Verwaltung der Variable "Inhalt" ändern, damit die Subroutine ein Ergebnis zurückgab
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


Does somebody has any idea?
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
Upvote 0
Solution
Top