68 lines
2.1 KiB
C#
68 lines
2.1 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
|
|
[Serializable]
|
|
public class ChatGPTMessageStruct
|
|
{
|
|
public string role = "user";
|
|
public string content = "Who are you";
|
|
public ChatGPTMessageStruct() { }
|
|
public ChatGPTMessageStruct(string role, string content)
|
|
{
|
|
this.role = role;
|
|
this.content = content;
|
|
}
|
|
}
|
|
|
|
[Serializable]
|
|
public class ChatGPTRequestStruct
|
|
{
|
|
public string model = "gpt-3.5-turbo-0613";
|
|
public ChatGPTMessageStruct[] messages = new ChatGPTMessageStruct[1]
|
|
{
|
|
new ChatGPTMessageStruct(),
|
|
};
|
|
public float temperature = 0.5f;
|
|
}
|
|
|
|
|
|
public class ChatGPTRequest
|
|
{
|
|
private string defaultModel = "gpt-3.5-turbo-0613";
|
|
private string url = "https://api.openai.com/v1/chat/completions";
|
|
public string response;
|
|
|
|
public IEnumerator Post(ChatGPTRequestStruct gptRequestStruct)
|
|
{
|
|
if (String.IsNullOrEmpty(gptRequestStruct.model))
|
|
{
|
|
gptRequestStruct.model = defaultModel;
|
|
}
|
|
|
|
string bodyJsonString = JsonUtility.ToJson(gptRequestStruct);
|
|
|
|
var request = new UnityWebRequest(url, "POST");
|
|
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
|
|
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
|
|
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
|
|
request.SetRequestHeader("Content-Type", "application/json");
|
|
request.SetRequestHeader("Authorization", "Bearer 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");
|
|
yield return request.SendWebRequest();
|
|
Debug.Log("Status Code: " + request.responseCode);
|
|
Debug.Log(request.downloadHandler.text);
|
|
if (request.result == UnityWebRequest.Result.Success)
|
|
{
|
|
JObject obj = JObject.Parse(request.downloadHandler.text);
|
|
response = (string)((JArray)obj["choices"])[0]["message"]["content"];
|
|
Debug.Log(response);
|
|
}
|
|
request.Dispose();
|
|
}
|
|
}
|