LoginSignup
1
0

初めに

この内容では、ChatGPT と Unity の統合について説明し、Unity 環境内で ChatGPT の機能を使用してインタラクティブでインテリジェントなアプリケーションを作成する方法を示します。

デモリポジトリはこちら

🔐 OpenAI APIキーを取得する

OpenAIアカウントを作成し、APIキーを取得します。OpenAIの API docsからキーを発行してもらうことができます。

  1. OpenAI ログイン
  2. カード登録が必須なので、Billingタブに入場してカード登録する
    image.png
    追加で過度な料金発生を予防するためにLimitsタブに移動してUsage limitsを設定する
  3. View API Keysに入場し、New Secret Keyを作成
    image.png
    image.png
    生成できたら、キー値をコピーする(生成されたキーは再照会できないので注意
  4. Key値が正しく生成されたかを確認する
  • 保存されたKey確認
  • サポート中のモデルを確認すること(当該文書では「gpt-3.5-turbo」Modelを使用)

Windows

  1. cURLのインストール確認
curl --version

image.png
2. 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}"

image.png
下線にKeyを入力

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
}'

image.png

⚙️ パッケージのインストールと通信の準備

  1. パッケージマネージャでurlでNuGetForUnityをインストール
    image.png
  2. NuGet PackagesタブでNewtonsoft.Jsonを検索してインストール
    image.png

📜 スクリプト作成

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?

image.png
image.png

🤔 期待できる部分

  • 生成補助機能
  • 教育用クイズゲーム
  • ユーザーカスタマイズ型ストーリージェネレータ
  • ARベースの教育プラットフォーム
    • AR環境で3Dモデルを表示して学習テーマを視覚化
    • ChatGPTによるリアルタイム質問応答および説明提供
  • ARベースの観光ガイド
    • ARを通じて観光地情報を視覚的に提供
    • ChatGPTを使用して観光地に関する追加情報を提供し、質問に答える
  • ARベースのショッピングヘルパー
    • ARを通じて製品情報を視覚的に提供
    • ChatGPTを使用して製品説明および質問応答
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0