Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

rubyonsoft/ChatGPT-API-unity

Repository files navigation

ChatGPT-API-unity

Binds ChatGPT chat completion API to pure C# on Unity.

See also official document.

How to import by UnityPackageManager

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",.

How to use chat completion by ChatGPT API

  1. Generate API key on OpenAI. (Take care your API key, this is a secret information then you should not open.)
  2. You can specify chat model. (Available models are defined by Model.)
  3. Create an instance of ChatCompletionAPIConnection with API key and chat model. (This instance memorizes old messages in session.)
  4. You can set system message (prompt) to instruct assistant with your situation by constructor of ChatCompletionAPIConnection.
  5. Input user message and call ChatCompletionAPIConnection.CompleteChatAsync().
  6. 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.

How to use chat completion by ChatGPT API more resilient

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",
 ...
 }
}

Changelog

See CHANGELOG

3rd Party Notices

See NOTICE.

License

MIT License

About

Binds ChatGPT chat completion API to pure C# on Unity.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

Contributors

Languages

  • C# 100.0%

AltStyle によって変換されたページ (->オリジナル) /