unity3d 为什么在Unity中向OpenAI发布请求会导致错误400?

9jyewag0  于 2023-02-19  发布在  其他
关注(0)|答案(1)|浏览(243)

我尝试在我制作的游戏中使用GPT 3,但我似乎无法正确调用OpenAI API。我从Unity文档中获得了大部分信息。以下是我使用的代码:

public class gpt3_complete : MonoBehaviour
{
    public string model;
    public string prompt;
    public int len;
    public string temp;
    public string api_key = "<key>";
    void Start()
    {
        StartCoroutine(Upload());
    }

    IEnumerator Upload()
    {
        WWWForm form = new WWWForm();
        form.AddField("model", model);
        form.AddField("prompt", prompt);
        form.AddField("max_tokens", len);
        form.AddField("temperature", temp);
        //form.headers.Add("Authorization", "Bearer "+api_key);


        using (UnityWebRequest www = UnityWebRequest.Post("https://api.openai.com/v1/completions", form))
        {
            www.SetRequestHeader("Authorization", "Bearer " + api_key);
            www.SetRequestHeader("Content-Type", "application/json");

            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.result);
                Debug.Log("Form upload complete!");
            }
        }
    }
}

这始终返回:400错误请求。GPT 3文档可以在这里找到:https://beta.openai.com/docs/api-reference/completions/create
你知道为什么吗?这是我第一次在unity上做任何网络请求,所以我可能错过了一些明显的东西。谢谢!

aor9mmx1

aor9mmx11#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;

public class OpenAIRequest : MonoBehaviour
{
    public string apiKey = "YOUR_API_KEY_HERE";
    public string prompt = "Once upon a time, in a land far far away, there lived a brave knight";
    public string model = "text-davinci-002";
    public int maxTokens = 100;

    void Start()
    {
        StartCoroutine(GetOpenAIResponse());
    }

    IEnumerator GetOpenAIResponse()
    {
        string url = "https://api.openai.com/v1/engines/" + model + "/completions";
        string requestData = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + "}";

        UnityWebRequest request = new UnityWebRequest(url, "POST");
        byte[] bodyRaw = Encoding.UTF8.GetBytes(requestData);
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Authorization", "Bearer " + apiKey);

        yield return request.SendWebRequest();

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(request.error);
        }
        else
        {
            string response = request.downloadHandler.text;
            Debug.Log(response);
        }
    }
}

result

相关问题