[Unity] OpenAI API(ChatGPT) 사용해보기
by Sugar0810이 내용에서는 ChatGPT와 Unity의 통합에 대해 설명하고, Unity 환경 내에서 ChatGPT의 기능을 사용하여 인터랙티브하고 지능적인 애플리케이션을 만드는 방법을 보여줍니다.
데모 리포지토리는 여기에서 확인할 수 있습니다.
🔐 OpenAI API 키를 얻기
OpenAI 계정을 생성하고 API 키를 얻습니다. OpenAI의 API 문서에서 키를 발급받을 수 있습니다.
카드 등록이 필수이므로, Billing 탭에 들어가 카드 등록을 합니다.
추가로 과도한 요금 발생을 예방하기 위해 Limits 탭으로 이동하여 Usage limits를 설정합니다.
View API Keys에 들어가 New Secret Key를 생성합니다.
생성된 키 값을 복사합니다 (생성된 키는 다시 조회할 수 없으므로 주의)
키 값이 올바르게 생성되었는지 확인합니다.
- 저장된 키 확인
- 지원하는 모델을 확인합니다. (이 문서에서는 "gpt-3.5-turbo" 모델을 사용합니다)
Windows
cURL 설치 확인
curl --version
cURL 명령 생성
curl https://api.openai.com/v1/chat/completions ^
-H "Content-Type: application/json" ^
-H "Authorization: Bearer YOUR_API_KEY" ^
-d "{\"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \"Say this is a test\"}], \"max_tokens\": 5}"
밑줄에 키를 입력합니다.
MacOS
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "Say this is a test"
}
],
"max_tokens": 5
}'
⚙️ 패키지 설치 및 통신 준비
- 패키지 매니저에서 url로 NuGetForUnity를 설치합니다.
- NuGet Packages 탭에서 Newtonsoft.Json을 검색하여 설치합니다.
📜 스크립트 작성
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json; // Use Newtonsoft.Json
public class OpenAIChatGPT : MonoBehaviour
{
private string apiKey = "YOUR_API_KEY"; // Replace with an actual API key
private string apiUrl = "https://api.openai.com/v1/chat/completions";
public IEnumerator GetChatGPTResponse(string prompt, System.Action<string> callback)
{
// Setting OpenAI API Request Data
var jsonData = new
{
model = "gpt-3.5-turbo",
messages = new[]
{
new { role = "user", content = prompt }
},
max_tokens = 20
};
string jsonString = JsonConvert.SerializeObject(jsonData);
// HTTP request settings
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonString);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer " + apiKey);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + request.error);
}
else
{
var responseText = request.downloadHandler.text;
Debug.Log("Response: " + responseText);
// Parse the JSON response to extract the required parts
var response = JsonConvert.DeserializeObject<OpenAIResponse>(responseText);
callback(response.choices[0].message.content.Trim());
}
}
public class OpenAIResponse
{
public Choice[] choices { get; set; }
}
public class Choice
{
public Message message { get; set; }
}
public class Message
{
public string role { get; set; }
public string content { get; set; }
}
}
using UnityEngine;
public class ChatGPTExample : MonoBehaviour
{
[SerializeField, TextArea(3, 5)] private string prompt;
void Start()
{
OpenAIChatGPT chatGPT = gameObject.AddComponent<OpenAIChatGPT>();
StartCoroutine(chatGPT.GetChatGPTResponse(prompt, OnResponseReceived));
}
void OnResponseReceived(string response)
{
Debug.Log("ChatGPT Response: " + response);
}
}
📗 사용 예시
프롬프트 질문 : In the extended virtual world, what is the newly coined word that combines "meta," which means virtual and transcendent, and "universe," which means world and universe?
🤔 기대할 수 있는 부분
- 생성 보조 기능
- 교육용 퀴즈 게임
- 사용자 맞춤형 스토리 생성기
- AR 기반 교육 플랫폼
- AR 환경에서 3D 모델을 표시하여 학습 주제를 시각화
- ChatGPT를 통한 실시간 질문 응답 및 설명 제공
- AR 기반 관광 가이드
- AR을 통해 관광지 정보를 시각적으로 제공
- ChatGPT를 사용하여 관광지에 대한 추가 정보를 제공하고 질문에 답변
- AR 기반 쇼핑 도우미
- AR을 통해 제품 정보를 시각적으로 제공
- ChatGPT를 사용하여 제품 설명 및 질문 응답
'⚙️ Programming > C# & Unity' 카테고리의 다른 글
Unity 6 Web의 최적화 기법과 WebGL 활용 - 차세대 웹 애플리케이션의 가능성 (1) | 2024.10.02 |
---|---|
[Unity] Google Cloud Speech to Text API + VAD 알고리즘 (0) | 2024.07.01 |
[Unity] Profiling (0) | 2024.01.17 |
[Unity] URP vs Built-In, Stencil과 렌더링 이론, Instancing 기법, SSAO와 Decals (3) | 2024.01.16 |
[Unity] 골드메탈이 추천하는 에셋 10종 리뷰 (0) | 2023.12.12 |
블로그의 정보
Sugar
Sugar0810