This Unity script allows you to send chat requests to OpenAI's GPT-3 API and receive responses. It is composed of a single static class, ChatGPTApi, which has the following features:
- A
SendChatRequestfunction that sends a chat request to the GPT-3 API and invokes a callback with the response. - An
OnMessageReceivedaction that you can subscribe to in order to receive chat responses. - A
tokenfield that you should set to your OpenAI API key in order to authenticate your requests.
To use the ChatGPTApi class, you will need to do the following:
- Obtain an API key from here.
- Set the
tokenfield to your API key:
private static string token = "TOKEN";
- Subscribe to the
OnMessageReceivedaction in order to receive chat responses:
ChatGPTApi.OnMessageReceived += OnMessageReceived;
void OnMessageReceived(ChatGPTResponse chatResponse) { // Handle the chat response here }
- Create a
ChatGPTRequestobject and send it to the GPT-3 API using theSendChatRequestfunction:
ChatGPTRequest chatRequest = new ChatGPTRequest { prompt = "Hello, how are you?", max_tokens = 1024 };
ChatGPTApi.SendChatRequest(chatRequest);
- The
SendChatRequestfunction sends a POST request to the OpenAI API and expects a JSON response. - The
ChatGPTRequestandChatGPTResponseobjects are serialized and deserialized using Newtonsoft.Json. You will need to have the Newtonsoft.Json package installed in your Unity project in order to use this script. - The
SendChatRequestfunction uses Unity'sUnityWebRequestclass to send the request and receive the response. It is asynchronous and invokes a callback when the request is completed.