用unity 写一份与https://api.openai.com/v1/chat/completions通讯的代码
时间: 2023-10-08 11:07:28 浏览: 184
UGUI Super ScrollView 2.5.3 最新版本,原版本https://assetstore.unity.cn
下面是一个简单的 Unity C# 代码示例,用于与 OpenAI GPT-3 的 API 进行通信,以获得 AI 回复:
```csharp
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class OpenAIChat : MonoBehaviour
{
public string apiKey;
public string prompt;
public int maxTokens;
public float temperature;
public Text responseText;
private const string API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions";
public void SendRequest()
{
StartCoroutine(GetResponse());
}
private IEnumerator GetResponse()
{
var requestJson = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + ", \"temperature\": " + temperature + "}";
var request = UnityWebRequest.Post(API_URL, requestJson);
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer " + apiKey);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(request.error);
yield break;
}
var responseJson = request.downloadHandler.text;
var response = JsonUtility.FromJson<OpenAIResponse>(responseJson);
if (response.choices == null || response.choices.Length == 0)
{
Debug.LogError("Invalid response from OpenAI API");
yield break;
}
responseText.text = response.choices[0].text;
}
[System.Serializable]
public class OpenAIResponse
{
public Choice[] choices;
}
[System.Serializable]
public class Choice
{
public string text;
public float logprobs;
public float finishReason;
}
}
```
要使用此代码,请将其添加到 Unity 游戏对象上,并在编辑器中设置 API 密钥、提示、最大标记和温度。然后,在您的 UI 上添加一个按钮或其他交互元素,以调用 SendRequest 方法并显示响应文本。
请注意,此示例使用 UnityWebRequest 类与 OpenAI API 进行通信。您还可以使用其他网络库,如 HttpClient 或 RestSharp。
阅读全文