実現したいこと
- unityとAPIを連携させて会話ができるNPCを作る
前提
unityでChat GPTをAPIで連携させて会話ができるNPCを作りたいです。
入力欄(InputField)に文字を入力し、送信Buttonを押すと内容が送られ、NPCの回答がTextに表示されます。
APIは個人情報のため、置き換えています。
文字を入力して送信ボタンを押したときに以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
HTTP/1.1 400 Bad Request UnityEngine.Debug:LogError (object) ChatApp/<PostRequest>d__6:MoveNext () (at Assets/ChatApp.cs:67) UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)
ソースコード
C#
1using UnityEngine; 2using UnityEngine.UI; 3using System.Collections; 4using UnityEngine.Networking; 5 6public class ChatApp : MonoBehaviour 7{ 8 public InputField userInputField; 9 public Text chatDisplayText; 10 11 private string apiKey = "my api"; 12 private string openAIEndpoint = "https://api.openai.com/v1/completions"; 13 14 15 void Start() 16 { 17 userInputField = GameObject.Find("InputField").GetComponent<InputField>(); 18 userInputField.gameObject.SetActive(true); 19 20 } 21 22 public void OnSendButtonClick() 23 { 24 userInputField = GameObject.Find("InputField").GetComponent<InputField>(); 25 //string userMessage = userInputField.text; 26 27 if (userInputField != null) // null チェックを追加 28 { 29 string userMessage = userInputField.text; 30 if (!string.IsNullOrEmpty(userMessage)) 31 { 32 StartCoroutine(PostRequest(userMessage)); 33 userInputField.text = ""; 34 } 35 } 36 else 37 { 38 Debug.LogError("userInputField is not set. Make sure it is assigned in the Unity Editor."); 39 } 40 41 /*if (!string.IsNullOrEmpty(userMessage)) 42 { 43 StartCoroutine(PostRequest(userMessage)); 44 userInputField.text = ""; 45 }*/ 46 } 47 48 IEnumerator PostRequest(string userMessage) 49 { 50 string url = openAIEndpoint; 51 string postData = $"{{\"prompt\": \"{userMessage}\", \"temperature\": 0.7, \"max_tokens\": 150}}"; 52 53 using (UnityWebRequest webRequest = UnityWebRequest.Post(url, postData)) 54 { 55 webRequest.SetRequestHeader("Content-Type", "application/json"); 56 webRequest.SetRequestHeader("Authorization", $"Bearer {apiKey}"); 57 58 yield return webRequest.SendWebRequest(); 59 60 if (webRequest.result == UnityWebRequest.Result.Success) 61 { 62 string response = webRequest.downloadHandler.text; 63 DisplayNPCResponse(response); 64 } 65 else 66 { 67 Debug.LogError(webRequest.error); 68 } 69 } 70 } 71 72 private void DisplayNPCResponse(string response) 73 { 74 chatDisplayText.text += $"NPC: {response}\n"; 75 } 76} 77
試したこと
・APIキーの有効性の確認
・ネットワーク接続の確認
補足情報
・unityのエディターバージョンは 2021.3.31f1
・コードはchatGPTが作成しました
・chatGPTのバージョンは3.5
・ソースコードには問題が見つからなかった

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/12/28 12:53
2023/12/29 11:54
2023/12/30 11:59
2023/12/30 12:57
2024/01/02 12:57
2024/01/02 13:05
2024/01/06 07:29