Table of contents
- Background
- What is ChatGPT API
- Implementation of ChatGPT API
- Execution of ChatGPT API
- Next Step
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.
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.
Obtain API key from Open AI
To use ChatGPT API, it is necessary to get API KEY from Open AI.
Access Open AI platform
Open AIClick DashBoard > API keys
Click “Create new secret key”
Request
To confirm the dialog, I implemented two text filed and the button. When the button was clicked, it requests Chat GPT API.
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;
}
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"});
This video shows the dialog that used Chat GPT API.