Hello,
I’m new to web requests but after some time I finally was able to create a request in Unity (C#) without getting back errors.
I am using the following code and got a response (down below) with, as you can see, empty text.
As ChatGPT can’t help me out here atm, I kindly ask for some help from the community.
Best regards
private void ChatGPTRequest()
{
var API_URL = "https://api.openai.com/v1/completions";
var API_KEY = myKey;
string prompt = "What day is today?";
string requestData = "{\"model\": \"text-davinci-003\", " +
"\"prompt\": \"" + prompt + "\", " +
"\"max_tokens\": 7, " +
"\"temperature\": 0.7, " +
"\"top_p\": 1, " +
"\"n\": 1, " +
"\"stream\": false, " +
"\"logprobs\": null, " +
"\"stop\": \"\\n\"}";
UnityWebRequest request = UnityWebRequest.Post(API_URL, "");
byte[] bodyRaw = Encoding.UTF8.GetBytes(requestData);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.disposeUploadHandlerOnDispose = true;
request.disposeCertificateHandlerOnDispose = true;
request.disposeDownloadHandlerOnDispose = true;
request.SetRequestHeader("Authorization", "Bearer " + API_KEY);
request.SetRequestHeader("Content-Type", "application/json");
request.SendWebRequest().completed += operation =>
{
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.DataProcessingError)
{
Debug.Log(request.error);
}
else
{
string responseInfo = request.downloadHandler.text;
Debug.Log("Response: " + responseInfo);
}
};
}
Response: {“id”:“cmpl-70vtw0ROFo2d9EFNK5wXjwRvMinCA”,“object”:“text_completion”,“created”:1680456928,“model”:“text-davinci-003”,“choices”:[{“text”:“”,“index”:0,“logprobs”:null,“finish_reason”:“stop”}],“usage”:{“prompt_tokens”:5,“total_tokens”:5}}