-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenAIAPIManager.cs
75 lines (62 loc) · 2.11 KB
/
OpenAIAPIManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class OpenAIAPIManager : MonoBehaviour
{
public string model = "gpt-3.5-turbo";
[System.Serializable]
public class ChatCompletionResponse
{
public Choice[] choices;
}
[System.Serializable]
public class Choice
{
public Message message;
}
[System.Serializable]
public class Message
{
public string role;
public string content;
}
public string API_KEY;
private const string API_URL = "https://api.openai.com/v1/chat/completions";
public void GenerateCompletion(string prompt, Action<string> callback)
{
StartCoroutine(SendRequest(prompt, callback));
}
private IEnumerator SendRequest(string prompt, Action<string> callback)
{
// Update jsonBody to use the model variable
string jsonBody = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}";
UnityWebRequest request = new UnityWebRequest(API_URL, "POST");
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonBody);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer " + API_KEY);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + request.error);
callback(null);
}
else
{
string response = request.downloadHandler.text;
string completion = ParseResponse(response);
callback(completion);
}
}
private string ParseResponse(string response)
{
ChatCompletionResponse chatCompletionResponse = JsonUtility.FromJson<ChatCompletionResponse>(response);
if (chatCompletionResponse.choices.Length > 0)
{
return chatCompletionResponse.choices[0].message.content;
}
return "";
}
}