Trying to use ChatGPT API in Unity game but fail

I am very new in codding, especially with ChatGPT, so here is my C# code in unity for a InputText:

using System.Collections;
using System;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class TextHandler : MonoBehaviour
{
    public InputField inputField;
    public Text outputText;

[System.Serializable]
public class GptResponse
{
    public Choice[ ] choices;
}

[System.Serializable]
public class Choice
{
    public string text;
}

    public void HandleInput()
    {

        string userInput = inputField.text;
        StartCoroutine(SendToGPT(userInput));

    }


private IEnumerator SendToGPT(string input)
{
    string apiUrl = "url";

    string requestBody = "{\"prompt\": \"" + input + "\", \"max_tokens\": 500}";

    UnityWebRequest request = UnityWebRequest.PostWwwForm(apiUrl, requestBody);

    request.SetRequestHeader("Content-Type", "application/json");
    request.SetRequestHeader("Authorization", "Bearer myapi");

    yield return request.SendWebRequest();

    if (request.result == UnityWebRequest.Result.Success)
    {
        string responseJson = request.downloadHandler.text;
        
        string generatedText = ParseResponseFromJSON(responseJson);

        yield return generatedText;
    }
    else
    {
        Debug.LogError("Error sending request: " + request.error);
        yield return null;
    }
}
private string ParseResponseFromJSON(string jsonResponse)
{
    try
    {
        GptResponse response = JsonUtility.FromJson<GptResponse>(jsonResponse);

        if (response.choices != null && response.choices.Length > 0)
        {
            string generatedText = response.choices[0].text;
            return generatedText;
        }
        else
        {
            Debug.LogError("No choices found in JSON response.");
            return "Error: No choices found in JSON response.";
        }
    }
    catch (Exception e)
    {
        Debug.LogError("Error parsing JSON response: " + e.Message);
        return "Error parsing JSON response";
    }
}
}

After writing the text in the inputbox it waits for like 2 seconds and gives me this error:

Error sending request: HTTP/1.1 400 Bad Request
UnityEngine.Debug:LogError (object)
TextHandler/d__5:MoveNext () (at Assets/Scripts/TextHandler.cs:67)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)

FYI there is a package you can install through Unity Editor, that sets up python for your project. So you can then follow Python tutorials and use the opena python library, instead of having to roll your own web calls.

But if you really want to write your own, click the error line once in the console to select it, and in the lower part, see the full body of the response, it might give more info like your api key is bad. But its kind of hidden since its on a newline.

If remember right, there was some obtuseness that either the POST request body needed to be encoded in a certain way, or the headers, etc. Maybe switch to using Powershell to make calls first, since it handles request creation better, and ChatGPT is better at designing powershell than unity code imo. Anyway I rolled my own too, and it wasn’t worth it, its hard to learn two things at once.

Edit: assuming you swapped out “myapi” with your real bearer token when sending, in actuality

2 Likes