Understading https request

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By TrippleDLee

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()
	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)
			var generated_text = response.get_var("choices/0/text")
			print("Generated text:", generated_text)
		print("Request failed with code:", response_code)
:bust_in_silhouette: Reply From: umaruru

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

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})

TrippleDLee | 2023-05-29 22:40

In the docs, it’s just JSON.stringify(): JSON — Godot Engine (4.0) documentation in English

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( )

umaruru | 2023-05-29 23:14