当前位置:   article > 正文

Unity接入ChatGPT实现NPC聊天_unity中如何实现chatgpt聊天机器人

unity中如何实现chatgpt聊天机器人

实现要求

1、能向OpenAI官网发送消息

        API官网:https://api.openai.com/v1/chat/completions

2、拥有自己的APIKey

实现步骤

1、明确发送消息的格式

  1. // 定义对话历史
  2. string conversation = "[{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}," +//确定是跟哪个对话窗口发送消息
  3. "{\"role\": \"user\", \"content\": \""+ message+"\"}]";//发送的消息
  4. // 构建请求体
  5. string requestBody = "{\"messages\": " + conversation + ", \"max_tokens\": 1024, " +//max_tokens 是收到消息的字节长度 一个token是四个字节 maxtoken越长收到的消息就越长
  6. "\"model\": \"gpt-3.5-turbo\"}"; // 设置使用的模型引擎按照你自己Key的模型这个是3.5的模型

2、明确收取消息的格式

  1. {
  2. "id": "Key来源账户的ID",
  3. "object": "chat.completion",
  4. "created": 1691993667,
  5. "model": "gpt-3.5-turbo-0613",
  6. "choices": [
  7. {
  8. "index": 0,
  9. "message": {
  10. "role": "assistant",
  11. "content": "收到的消息类型"
  12. },
  13. "finish_reason": "stop"
  14. }
  15. ],
  16. "usage": {
  17. "prompt_tokens": 19,
  18. "completion_tokens": 18,
  19. "total_tokens": 37 //消息消耗的Token数量
  20. }
  21. }


转化成对象类

  1. public class ChatGPTJsonObjec
  2. {
  3. public string id;
  4. public string @object;
  5. public string created;
  6. public string model;
  7. public Choices[] choices;
  8. public Usage usage;
  9. }
  10. [System.Serializable]
  11. public class Choices
  12. {
  13. public float index;
  14. public Message message;//消息放在这个类里下面有解释
  15. public string finish_reason;
  16. }
  17. [System.Serializable]
  18. public class Message
  19. {
  20. public string role;
  21. public string content;//收到的回复消息只要这个就行其他的都是一些用户信息没啥用
  22. }
  23. [System.Serializable]
  24. public class Usage
  25. {
  26. public int prompt_tokens;
  27. public int completion_tokens;
  28. public int total_tokens;//这条消息消耗的Token 一个token等于四个字节
  29. }

实现脚本

  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.Networking;
  4. using UnityEngine.UI;
  5. using System.Text;
  6. /// <summary>
  7. /// 脚本功能:ChatGTP发送消息
  8. /// </summary>
  9. public class BebornMemoryChatGPT : MonoBehaviour
  10. {
  11. //去API官网弄,有小白弄不来的私信我我告诉你哪里有
  12. public string apiKey = "key";
  13. private string apiUrl = "https://api.openai.com/v1/chat/completions";
  14. public Button button;
  15. public InputField inputField;
  16. private void Awake()
  17. {
  18. SendMessageToChatGPT("你好");//发送你好,里面的内容是啥都行
  19. }
  20. public void ToJson()
  21. {
  22. ChatGPTJsonObjec chatGPTJsonObjec = new ChatGPTJsonObjec();
  23. string json = JsonUtility.ToJson(chatGPTJsonObjec, true);
  24. Debug.Log(json);
  25. }
  26. /// <summary>
  27. /// 携程收发消息
  28. /// </summary>
  29. /// <param name="message">发送的消息</param>
  30. private void SendMessageToChatGPT(string message)
  31. {
  32. // 定义对话历史
  33. string conversation = "[{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}," +//确定是跟哪个对话窗口发送消息
  34. "{\"role\": \"user\", \"content\": \""+ message+"\"}]";//发送的消息
  35. // 构建请求体
  36. string requestBody = "{\"messages\": " + conversation + ", \"max_tokens\": 1024, " +//max_tokens 是收到消息的字节长度 一个token是四个字节 maxtoken越长收到的消息就越长
  37. "\"model\": \"gpt-3.5-turbo\"}"; // 设置使用的模型引擎
  38. StartCoroutine(AsyncSendMessageToChatGPT(requestBody));
  39. Debug.Log("发送:"+ message);
  40. }
  41. private IEnumerator AsyncSendMessageToChatGPT(string message)
  42. {
  43. byte[] data = Encoding.UTF8.GetBytes(message);
  44. using(UnityWebRequest www = new UnityWebRequest(apiUrl, "POST"))
  45. {
  46. www.uploadHandler = new UploadHandlerRaw(data);//设置上传的数据是字符数组
  47. www.downloadHandler = new DownloadHandlerBuffer();
  48. www.SetRequestHeader("Content-Type", "application/json");
  49. www.SetRequestHeader("Authorization", "Bearer " + apiKey);
  50. yield return www.SendWebRequest();
  51. if (www.result != UnityWebRequest.Result.Success)
  52. {
  53. Debug.LogError("Protocol Error: " + www.error);
  54. Debug.LogError("Error Response: " + www.downloadHandler.text);
  55. Debug.LogError("发送的消息失败,请重新创建链接,需要全局科学上网哦"+ www.result);
  56. }
  57. else
  58. {
  59. string receive = www.downloadHandler.text;
  60. Debug.Log(receive);//输出收到的所有Json信息
  61. ChatGPTJsonObjec chatGPTJsonObjec = JsonUtility.FromJson<ChatGPTJsonObjec>(receive);
  62. //chatGPTJsonObjec.choices[0].message.content 这个就是你收到的回复
  63. Debug.Log("收到的回复:"+chatGPTJsonObjec.choices[0].message.content);
  64. }
  65. }
  66. }
  67. }
  68. #region JsonData
  69. public class ChatGPTJsonObjec
  70. {
  71. public string id;
  72. public string @object;
  73. public string created;
  74. public string model;
  75. public Choices[] choices;
  76. public Usage usage;
  77. }
  78. [System.Serializable]
  79. public class Choices
  80. {
  81. public float index;
  82. public Message message;
  83. public string finish_reason;
  84. }
  85. [System.Serializable]
  86. public class Message
  87. {
  88. public string role;
  89. public string content;
  90. }
  91. [System.Serializable]
  92. public class Usage
  93. {
  94. public int prompt_tokens;
  95. public int completion_tokens;
  96. public int total_tokens;
  97. }
  98. #endregion

实现效果

 

小结

能一本正经地回答一些呆瓜问题,挺好玩的,聊得越多越了解你,经过一定训练能当游戏的NPC。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/376288
推荐阅读
相关标签
  

闽ICP备14008679号