实现要求
1、能向OpenAI官网发送消息
API官网:https://api.openai.com/v1/chat/completions
2、拥有自己的APIKey
实现步骤
1、明确发送消息的格式
// 定义对话历史
string conversation = "[{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}," +//确定是跟哪个对话窗口发送消息
"{\"role\": \"user\", \"content\": \""+ message+"\"}]";//发送的消息
// 构建请求体
string requestBody = "{\"messages\": " + conversation + ", \"max_tokens\": 1024, " +//max_tokens 是收到消息的字节长度 一个token是四个字节 maxtoken越长收到的消息就越长
"\"model\": \"gpt-3.5-turbo\"}"; // 设置使用的模型引擎按照你自己Key的模型这个是3.5的模型
2、明确收取消息的格式
{
"id": "Key来源账户的ID",
"object": "chat.completion",
"created": 1691993667,
"model": "gpt-3.5-turbo-0613",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "收到的消息类型"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 19,
"completion_tokens": 18,
"total_tokens": 37 //消息消耗的Token数量
}
}
转化成对象类
public class ChatGPTJsonObjec
{
public string id;
public string @object;
public string created;
public string model;
public Choices[] choices;
public Usage usage;
}
[System.Serializable]
public class Choices
{
public float index;
public Message message;//消息放在这个类里下面有解释
public string finish_reason;
}
[System.Serializable]
public class Message
{
public string role;
public string content;//收到的回复消息只要这个就行其他的都是一些用户信息没啥用
}
[System.Serializable]
public class Usage
{
public int prompt_tokens;
public int completion_tokens;
public int total_tokens;//这条消息消耗的Token 一个token等于四个字节
}
实现脚本
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.Text;
/// <summary>
/// 脚本功能:ChatGTP发送消息
/// </summary>
public class BebornMemoryChatGPT : MonoBehaviour
{
//去API官网弄,有小白弄不来的私信我我告诉你哪里有
public string apiKey = "key";
private string apiUrl = "https://api.openai.com/v1/chat/completions";
public Button button;
public InputField inputField;
private void Awake()
{
SendMessageToChatGPT("你好");//发送你好,里面的内容是啥都行
}
public void ToJson()
{
ChatGPTJsonObjec chatGPTJsonObjec = new ChatGPTJsonObjec();
string json = JsonUtility.ToJson(chatGPTJsonObjec, true);
Debug.Log(json);
}
/// <summary>
/// 携程收发消息
/// </summary>
/// <param name="message">发送的消息</param>
private void SendMessageToChatGPT(string message)
{
// 定义对话历史
string conversation = "[{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}," +//确定是跟哪个对话窗口发送消息
"{\"role\": \"user\", \"content\": \""+ message+"\"}]";//发送的消息
// 构建请求体
string requestBody = "{\"messages\": " + conversation + ", \"max_tokens\": 1024, " +//max_tokens 是收到消息的字节长度 一个token是四个字节 maxtoken越长收到的消息就越长
"\"model\": \"gpt-3.5-turbo\"}"; // 设置使用的模型引擎
StartCoroutine(AsyncSendMessageToChatGPT(requestBody));
Debug.Log("发送:"+ message);
}
private IEnumerator AsyncSendMessageToChatGPT(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
using(UnityWebRequest www = new UnityWebRequest(apiUrl, "POST"))
{
www.uploadHandler = new UploadHandlerRaw(data);//设置上传的数据是字符数组
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
www.SetRequestHeader("Authorization", "Bearer " + apiKey);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Protocol Error: " + www.error);
Debug.LogError("Error Response: " + www.downloadHandler.text);
Debug.LogError("发送的消息失败,请重新创建链接,需要全局科学上网哦"+ www.result);
}
else
{
string receive = www.downloadHandler.text;
Debug.Log(receive);//输出收到的所有Json信息
ChatGPTJsonObjec chatGPTJsonObjec = JsonUtility.FromJson<ChatGPTJsonObjec>(receive);
//chatGPTJsonObjec.choices[0].message.content 这个就是你收到的回复
Debug.Log("收到的回复:"+chatGPTJsonObjec.choices[0].message.content);
}
}
}
}
#region JsonData
public class ChatGPTJsonObjec
{
public string id;
public string @object;
public string created;
public string model;
public Choices[] choices;
public Usage usage;
}
[System.Serializable]
public class Choices
{
public float index;
public Message message;
public string finish_reason;
}
[System.Serializable]
public class Message
{
public string role;
public string content;
}
[System.Serializable]
public class Usage
{
public int prompt_tokens;
public int completion_tokens;
public int total_tokens;
}
#endregion
实现效果
文章来源:https://www.toymoban.com/news/detail-831832.html
小结
能一本正经地回答一些呆瓜问题,挺好玩的,聊得越多越了解你,经过一定训练能当游戏的NPC。文章来源地址https://www.toymoban.com/news/detail-831832.html
到了这里,关于Unity接入ChatGPT实现NPC聊天的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!