Binds ChatGPT chat completion API to pure C# on Unity.
Add dependencies:
{
"dependencies": {
"com.mochineko.chatgpt-api": "https://github.com/mochi-neko/ChatGPT-API-unity.git?path=/Assets/Mochineko/ChatGPT_API#0.1.0",
"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 and set. (Take care your API key, this is a seclet information then you should not open.)
- Specify chat model. (Latest
gpt-3.5-turbo
or fixedgpt-3.5-turbo-0301
are avairable.) - Create an instance of
ChatGPTConnection
with 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
ChatGPTConnection.AddSystemMessage
. - Input user message and call
ChatGPTConnection.CreateMessageAsync
. - Response message is in
APIResponseBody.ResultMessage
(=APIResponseBody.Choices[0].Message.Content
).
An essensial sample code with UniTask is as follows:
#nullable enable
using System;
using Cysharp.Threading.Tasks;
using Mochineko.ChatGPT_API;
using Mochineko.ChatGPT_API.Formats;
using UnityEngine;
namespace XXX
{
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;
private ChatGPTConnection? connection;
private void Start()
{
// Create instance of ChatGPTConnection with specifying chat model.
connection = new ChatGPTConnection(apiKey, Model.Turbo);
if (!string.IsNullOrEmpty(systemMessage))
{
// Add system message when you input.
connection.AddSystemMessage(systemMessage);
}
}
[ContextMenu(nameof(SendChat))]
public async void SendChat()
{
APIResponseBody result;
try
{
// Create message by ChatGPT chat completion API.
result = await connection
.CreateMessageAsync(message, this.GetCancellationTokenOnDestroy());
}
catch (Exception e)
{
// Exceptions should be caught.
Debug.LogException(e);
return;
}
// Log chat completion result.
Debug.Log($"[ChatGPT_API.Samples] Result:\n{result.ResultMessage}");
}
}
}
See also Sample.
See NOTICE.