Home > database >  OpenAI Unity - POST Request not working properly (400 status)
OpenAI Unity - POST Request not working properly (400 status)

Time:01-12

I'm connecting GPT3 OpenAI but I just cant manage to make a proper POST request to it (I'm following some guides but for them it works...).

private IEnumerator Upload ( )
{
    WWWForm form = new WWWForm();
    form.AddField ( "prompt", prompt );
    form.AddField ( "max_tokens", maxTokens );
    form.AddField ( "model", model );
    form.AddField ( "temperature", temperature );

    using ( UnityWebRequest wR = UnityWebRequest.Post ( "https://api.openai.com/v1/completions", form ) )
    {
        wR.SetRequestHeader ( "Authorization", "Bearer "   apiKey );
        wR.SetRequestHeader ( "Content-Type", "json" );
        yield return wR.SendWebRequest ( );
        if ( wR.result != UnityWebRequest.Result.Success )
        {
            Debug.Log ( "ERROR:\n"   wR.error );
        }
        else
        {
            Debug.Log ( "Success:\n"   wR.result   "\nUpload Completed!);
        }
    }
}

My code is always returning me a bad request (a.k.a 400 Bad Request).

CodePudding user response:

Remove the "Content-Type" from the headers. The content is not JSON, it's form data.

i.e.

using ( UnityWebRequest wR = UnityWebRequest.Post ( "https://api.openai.com/v1/completions", form ) )
{
    wR.SetRequestHeader ( "Authorization", "Bearer "   apiKey );
    //wR.SetRequestHeader ( "Content-Type", "json" );
    yield return wR.SendWebRequest ( );
    if ( wR.result != UnityWebRequest.Result.Success )
    {
        Debug.Log ( "ERROR:\n"   wR.error );
    }
    else
    {
        Debug.Log ( "Success:\n"   wR.result   "\nUpload Completed!);
    }
}
  • Related