DEV Community

Akira Game
Akira Game

Posted on

AR Game ~ ChatGPT API ~

Table of contents

  • Background
  • What is ChatGPT API
  • Implementation of ChatGPT API
  • Execution of ChatGPT API
  • Next Step

Background

I will develop AR Game with Unity, AR foundation and so on. To learn AR development, I am researching about AR and the software related it. This blog shows the research and the process of developing AR game. If you have a question, I am happy to answer it.

In my AR game, Chat GPT will be used to create automatically character dialog. Therefore, this post will show how to implement ChatGPT API on Unity.

What is ChatGPT API

These days, everyone probably knows ChatGPT. Chat GPT API is a feature that allows you to use ChatGPT via an API. Also, it is available on Unity.

Implementation of ChatGPT API

Obtain API key from Open AI

To use ChatGPT API, it is necessary to get API KEY from Open AI.

  1. Access Open AI platform
    Open AI

  2. Click DashBoard > API keys

  3. Click "Create new secret key"

Image description

Request

To confirm the dialog, I implemented two text filed and the button. When the button was clicked, it requests Chat GPT API.

Image description

Sample



// Open API Endpoint
var apiUrl = "https://api.openai.com/v1/chat/completions";

// Add message into list
_messageList.Add(new ChatGPTMessageModel {role = "user", content = userMessage});

// Header Information
var headers = new Dictionary<string, string>
{
{
"Authorization", "Bearer " + _apiKey
},
{
"Content-type", "application/json"
}
};

// Request Opiton
var options = new ChatGPTCompletionRequestModel()
{
model = "gpt-3.5-turbo",
messages = _messageList
};
var jsonOptions = JsonUtility.ToJson(options);

using var request = new UnityWebRequest(apiUrl,
"POST")
{
uploadHandler = new UploadHandlerRaw(
Encoding.UTF8.GetBytes(jsonOptions)),
downloadHandler = new DownloadHandlerBuffer()
};

// Set Request Header
foreach (var header in headers)
{
request.SetRequestHeader(header.Key, header.Value);
}

// Request
await request.SendWebRequest();

// Process Request
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError(request.error);
throw new Exception();
}
else
{
var responseString = request.downloadHandler.text;
var responseObject = JsonUtility.FromJson<ChatGPTResponseModel>(responseString);

_messageList.Add(responseObject.choices[0].message);
return responseObject;
}

Enter fullscreen mode Exit fullscreen mode




Set initial message

Dialog can be changed by setting initial message. At this time, I changed it to speak more like a German.



new ChatGPTMessageModel() {role = "system", content = "You are German. Please reply like German in English"});

Enter fullscreen mode Exit fullscreen mode




Execution of ChatGPT API on Unity

This video shows the dialog that used Chat GPT API.

Next Step

Top comments (0)