Binds ChatGPT chat completion API to pure C# on Unity.
See also official document.
Add dependencies:
{
"dependencies": {
"com.mochineko.chatgpt-api": "https://github.com/mochi-neko/ChatGPT-API-unity.git?path=/Assets/Mochineko/ChatGPT_API#0.2.2",
"com.unity.nuget.newtonsoft-json": "3.0.2",
...
}
}to your mainfest.json.
If you have already used Newtonsoft.Json on your project, remove dependency:"com.unity.nuget.newtonsoft-json": "3.0.2",.
- Generate API key on OpenAI. (Take care your API key, this is a secret information then you should not open.)
- You can specify chat model. (Available models are defined by
Model.) - Create an instance of
ChatCompletionAPIConnectionwith API key and chat model. (This instance memorizes old messages in session.) - You can set system message (prompt) to instruct assistant with your situation by constructor of
ChatCompletionAPIConnection. - Input user message and call
ChatCompletionAPIConnection.CompleteChatAsync(). - Response message is in
ChatCompletionResponseBody.ResultMessage(=ChatCompletionResponseBody.Choices[0].Message.Content).
An essential sample code with UniTask is as follows:
#nullable enable using System; using System.Threading; using Cysharp.Threading.Tasks; using Mochineko.ChatGPT_API.Memories; using UnityEngine; 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}"); } } }
See also Sample.
See RelentChatCompletionAPIConnection and RelentChatCompletionSample using Relent.
You can use API with explicit error handling, retry, timeout, bulkhead, and so on.
{
"dependencies": {
"com.mochineko.chatgpt-api": "https://github.com/mochi-neko/ChatGPT-API-unity.git?path=/Assets/Mochineko/ChatGPT_API#0.2.2",
"com.mochineko.chatgpt-api.relent": "https://github.com/mochi-neko/ChatGPT-API-unity.git?path=/Assets/Mochineko/ChatGPT_API.Relent#0.2.2",
"com.unity.nuget.newtonsoft-json": "3.0.2",
...
}
}See CHANGELOG
See NOTICE.