-
Notifications
You must be signed in to change notification settings - Fork 14
/
ChatCompletionSample.cs
107 lines (91 loc) · 3.12 KB
/
ChatCompletionSample.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#nullable enable
using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using Mochineko.ChatGPT_API.Memory;
using UnityEngine;
using UnityEngine.Serialization;
namespace Mochineko.ChatGPT_API.Samples
{
/// <summary>
/// A sample component to complete chat by ChatGPT API on Unity.
/// </summary>
public sealed class ChatCompletionSample : MonoBehaviour
{
/// <summary>
/// API key generated by OpenAPI.
/// </summary>
[SerializeField] private string apiKey = string.Empty;
/// <summary>
/// System message to instruct assistant.
/// </summary>
[SerializeField, TextArea] private string systemMessage = string.Empty;
/// <summary>
/// Message sent to ChatGPT API.
/// </summary>
[SerializeField, TextArea] private string message = string.Empty;
/// <summary>
/// Max number of chat memory of queue.
/// </summary>
[SerializeField] private int maxMemoryCount = 20;
private ChatCompletionAPIConnection? connection;
private IChatMemory? memory;
private void Start()
{
// API Key must be set.
if (string.IsNullOrEmpty(apiKey))
{
Debug.LogError("OpenAI API key must be set.");
return;
}
memory = new FiniteQueueChatMemory(maxMemoryCount);
// Create instance of ChatGPTConnection with specifying chat model.
connection = new ChatCompletionAPIConnection(
apiKey,
memory,
systemMessage);
}
[ContextMenu(nameof(SendChat))]
public void SendChat()
{
SendChatAsync(this.GetCancellationTokenOnDestroy()).Forget();
}
[ContextMenu(nameof(ClearChatMemory))]
public void ClearChatMemory()
{
memory?.ClearAllMessages();
}
private async UniTask SendChatAsync(CancellationToken cancellationToken)
{
// Validations
if (connection == null)
{
Debug.LogError($"[ChatGPT_API.Samples] Connection is null.");
return;
}
if (string.IsNullOrEmpty(message))
{
Debug.LogError($"[ChatGPT_API.Samples] Chat content is empty.");
return;
}
ChatCompletionResponseBody response;
try
{
await UniTask.SwitchToThreadPool();
// Create message by ChatGPT chat completion API.
response = await connection.CompleteChatAsync(
message,
cancellationToken);
}
catch (Exception e)
{
// Exceptions should be caught.
Debug.LogException(e);
return;
}
await UniTask.SwitchToMainThread(cancellationToken);
// Log chat completion result.
Debug.Log($"[ChatGPT_API.Samples] Result:\n{response.ResultMessage}");
}
}
}