API response?

Hello,

I’m using this code to send an API request to https://api.openai.com/v1/chat/completions:

var request_data As New JSONItem
Var message_data As New JSONItem

message_data.Value("role") = "user"
message_data.Value("content") = Window1.TextArea1.Text

request_data.Value("model") = Window1.Textfield1.Text
request_data.Value("messages") = message_data

URLConnection1.RequestHeader("Content-Type") = "application/json"
URLConnection1.RequestHeader("Authorization") = "Bearer " + App.api_key
If App.org_key <> "" Then
  URLConnection1.RequestHeader("OpenAI-Organization") = App.org_key
End If
URLConnection1.SetRequestContent(request_data.ToString, "application/json")

URLConnection1.Send("POST", App.api_url)

As a result, I get:

{
"error": {
"message": "internal error",
"type": "invalid_request_error",
"param": null,
"code": null
}
}

What does that mean? Am I doing something wrong, or is it OpenAI API?

probably means your request is not well built for the server to understand

I can’t see where I made a mistake.

request_data.Value("model") is gpt-3.5-turbo and App.api_key is my API key.
App.api_url is https://api.openai.com/v1/chat/completions.

Have you seen: GitHub - charonn0/Xojo-OpenAI: A Xojo API for interacting with OpenAI

That may help you.

3 Likes

yes well you need to examine your ‘request_data.ToString’
maybe quote or somehing missing or doubled

1 Like

I have. gpt-3.5-turbo is not yet implemented.

Looks like it is expecting an array in the json and you are not puting an array there.

You should debug the request_data.ToString before sending and compare it with what the server is expecting.

2 Likes
Var request_data As New JSONItem
Var message_data As New JSONItem
Var message_array() As JSONItem

message_data.Value("role") = "user"
message_data.Value("content") = Window1.TextArea1.Text
message_array.AddAt(0, message_data)

request_data.Value("model") = "gpt-3.5-turbo"
request_data.Value("messages") = message_array

URLConnection1.RequestHeader("Content-Type") = "application/json"
URLConnection1.RequestHeader("Authorization") = "Bearer " + App.api_key
If App.org_key <> "" Then
  URLConnection1.RequestHeader("OpenAI-Organization") = App.org_key
End If
URLConnection1.SetRequestContent(request_data.ToString, "application/json")

URLConnection1.Send("POST", App.api_url)

Now I get: root[0]: JSONItem is not a valid JSON type

Error in line 10

What happens if you change:

to

Var message_array As New JSONItem("[]")
1 Like

He didn’t mean use a Xojo array, he meant use a JSON array.

Alberto beat me to it.

1 Like

Yes. Exactly. That worked! Thank you

It is now :slight_smile:

1 Like