AR Game ~ ChatGPT API ~
Tags: unity3d, gamedev, chatgpt, csharp
Published: 2024-06-11 20:15:02

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](https://platform.openai.com/)

2. Click DashBoard > API keys
3. Click "Create new secret key"


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eoqh13grqyjlx9gdmaig.png)


## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lbzohnjes091c40r125p.png)

### Sample

```C#
// 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;
}
```

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

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

# Execution of ChatGPT API on Unity
This video shows the dialog that used Chat GPT API.

{% youtube https://www.youtube.com/watch?v=mVCrJQuXJmM %}

# Next Step