The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

0 votes

I've been trying to use chatgpt to create a AI that responds to text and etc. I've gotten this far but whenever I run the game I keep getting an 401 error. What am I doing wrong?

var http_request: HTTPRequest
var api_key: String = "MY API KEY"

func _ready():
    http_request = HTTPRequest.new()
    http_request.request
    http_request.request_completed.connect(self._on_request_completed)
    add_child(http_request)
    var body = JSON.new().stringify({"prompt": "Hello, world!", "max_tokens": 50})
    var header = {"Authorization": "Bearer " + api_key,"Content-Type":"application/json"}
    http_request.request("https://api.openai.com/v1/chat/completions", [header], HTTPClient.METHOD_POST, body)

func _on_request_completed(result, response_code, headers, body):
    if response_code == 200:
        var response = JSON.new()
        var json_error = response.open_and_parse(body)
        if json_error != OK:
            print("JSON parsing error:", json_error)
        else:
            var generated_text = response.get_var("choices/0/text")
            print("Generated text:", generated_text)
    else:
        print("Request failed with code:", response_code)
Godot version latest
in Engine by (19 points)

1 Answer

+1 vote
Best answer

The headers should be a PackedStringArray, in this case they seem to be a Dictionary. I think this might work:

var header = PackedStringArray([
    "Authorization: Bearer " + api_key,
    "Content-Type: application/json"
])

Don't forget to remove the brackets around header on the request function

by (82 points)
selected by

It's going through but I keep getting 400 errors is something wrong with:

var body = JSON.new().stringify({"prompt": "Hello, world!", "max_tokens": 50})

In the docs, it's just JSON.stringify(): https://docs.godotengine.org/en/4.0/classes/class_json.html

If that's not the reason, maybe the server expects the body to be an array of bytes instead of a string. In that case you could try the HTTPRequest.request_raw() instead of the regular request(). You can convert the body to bytes inside the request_raw function with body.to_utf8_buffer( )

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.