- Edited
Problem
I am trying to use OpenAI Chat Completion(GPT-3/4) in GDScript at runtime, not in editor. The problem is that I can't get it work with 'stream' option enabled.
What I've tried
I successfully made code to call Chat API, but the operation is very slow.
I found that I can get generated character one by one if stream=true. So, I want to use it.
I followed the guide here, but I can't get it work.
This is the working code with stream=false.
extends Node
class_name OpenAIChatCompletion
signal chat_completed(end, content)
export(String, "gpt-3.5-turbo", "gpt-4") var model = "gpt-4"
export var temperature = 1.0
var is_completed = true
var url = "https://api.openai.com/v1/chat/completions"
var headers = ["Content-Type: application/json", "Authorization: Bearer "]
var http_request
var stream = false
func _ready():
http_request = HTTPRequest.new()
add_child(http_request)
http_request.connect("request_completed", self, "_http_request_completed")
func _http_request_completed(result, response_code, headers, body):
print("result: " + str(result))
var response = parse_json(body.get_string_from_utf8())
print(response)
emit_signal("chat_completed", true, response.choices[0].message.content)
is_completed = true
func send(api_key, messages):
var headers_with_api = headers.duplicate()
headers_with_api[1] = headers_with_api[1] + api_key
var body = to_json(
{
"model": model,
"messages": messages,
"temperature" : temperature,
"stream" : stream
}
)
is_completed = false
var error = http_request.request(url, headers_with_api, true, HTTPClient.METHOD_POST, body)
if error != OK:
push_error("An error occurred in the HTTP request.")
is_completed = true
If I make 'stream' variable true, then 'response' variable in _http_request_completed function should return an array(or a dicrionary?) containing multiple responses.
But print(response) returns NULL and the following code gives an error.
for chunk in response:
print(chunk)
Question
Does anyone know how to get it work? Any advice would be appreciated.