想要使用文心一言,首先要登录百度智能云千帆控制台
https://cloud.baidu.com/product/wenxinworkshop?track=developer_qianfan_tanchuang
1.在控制台找到应用接入 - 然后点击创建应用
2.填写应用信息
3.创建之后,记下API Key 和 Secret Key,等会会用到
4.打开Unity,建一个简单的聊天场景
5.加入测试代码
publicclassChatAI:MonoBehaviour{publicstring token;//这里填写百度千帆大模型里的应用api keypublicstring api_key ="xxxxxx";//这里填写百度千帆大模型里的应用secret keypublicstring secret_key ="xxxxxxxxx";//发送按钮publicButton sendBtn;//输入框publicTMP_InputField info;//AI回应publicTextMeshProUGUI responseText;// 历史对话privateList<message> historyList =newList<message>();publicvoidAwake(){//初始化文心一言,获取tokenStartCoroutine(GetToken());
sendBtn.onClick.AddListener(OnSend);}publicvoidOnSend(){OnSpeak(info.text);}//开始对话publicvoidOnSpeak(string talk ){StartCoroutine(Request(talk));}privateIEnumeratorGetToken(){//获取token的api地址string _token_url =string.Format("https://aip.baidubce.com/oauth/2.0/token"+"?client_id={0}&client_secret={1}&grant_type=client_credentials", api_key, secret_key);using(UnityWebRequest request =newUnityWebRequest(_token_url,"POST")){
request.downloadHandler =(DownloadHandler)newDownloadHandlerBuffer();yieldreturn request.SendWebRequest();if(request.isDone){string msg = request.downloadHandler.text;TokenInfo mTokenInfo = JsonUtility.FromJson<TokenInfo>(msg);//保存Token
token = mTokenInfo.access_token;}}}/// <summary>/// 发送数据/// </summary> /// <param name="_postWord"></param>/// <param name="_callback"></param>/// <returns></returns>publicIEnumeratorRequest(string talk){string url ="https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/";string postUrl = url +GetModelType(ModelType.ERNIE_Bot)+"?access_token="+ token;
historyList.Add(newmessage("user", talk));RequestData postData =newRequestData{
messages = historyList
};using(UnityWebRequest request =newUnityWebRequest(postUrl,"POST")){string jsonData = XJsonParser.ToJson<RequestData>(postData);byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonData);
request.uploadHandler =(UploadHandler)newUploadHandlerRaw(data);
request.downloadHandler =(DownloadHandler)newDownloadHandlerBuffer();
request.SetRequestHeader("Content-Type","application/json");yieldreturn request.SendWebRequest();if(request.responseCode ==200){string _msg = request.downloadHandler.text;ResponseData response;
XJsonParser.ToObject(out response, _msg);//加入历史数据
historyList.Add(newmessage("assistant", response.result));
responseText.text = response.result;}}}/// <summary>/// 获取资源/// </summary>/// <param name="type"></param>/// <returns></returns>privatestringGetModelType(ModelType type){if(type == ModelType.ERNIE_Bot){return"completions";}if(type == ModelType.ERNIE_Bot_turbo){return"eb-instant";}if(type == ModelType.BLOOMZ_7B){return"bloomz_7b1";}if(type == ModelType.Qianfan_BLOOMZ_7B_compressed){return"qianfan_bloomz_7b_compressed";}if(type == ModelType.ChatGLM2_6B_32K){return"chatglm2_6b_32k";}if(type == ModelType.Llama_2_7B_Chat){return"llama_2_7b";}if(type == ModelType.Llama_2_13B_Chat){return"llama_2_13b";}if(type == ModelType.Llama_2_70B_Chat){return"llama_2_70b";}if(type == ModelType.Qianfan_Chinese_Llama_2_7B){return"qianfan_chinese_llama_2_7b";}if(type == ModelType.AquilaChat_7B){return"aquilachat_7b";}return"";}//发送的数据privateclassRequestData{//发送的消息publicList<message> messages =newList<message>();//是否流式输出publicbool stream =false;publicstring user_id =string.Empty;}privateclassmessage{//角色publicstring role =string.Empty;//对话内容publicstring content =string.Empty;publicmessage(){}publicmessage(string _role,string _content ){if(_role !=""){
role = _role;}
content = _content;}}//接收的数据privateclassResponseData{//本轮对话的id publicstring id =string.Empty;publicint created;//表示当前子句的序号,只有在流式接口模式下会返回该字段publicint sentence_id;//表示当前子句是否是最后一句,只有在流式接口模式下会返回该字段publicbool is_end;//表示当前子句是否是最后一句,只有在流式接口模式下会返回该字段publicbool is_truncated;//返回的文本publicstring result =string.Empty;//表示输入是否存在安全publicbool need_clear_history;//当need_clear_history为true时,此字段会告知第几轮对话有敏感信息,如果是当前问题,ban_round=-1publicint ban_round;//token统计信息,token数 = 汉字数+单词数*1.3 publicUsage usage =newUsage();}privateclassUsage{//问题tokens数publicint prompt_tokens;//回答tokens数publicint completion_tokens;//tokens总数publicint total_tokens;}/// <summary>/// 模型名称/// </summary>publicenumModelType{
ERNIE_Bot,
ERNIE_Bot_turbo,
BLOOMZ_7B,
Qianfan_BLOOMZ_7B_compressed,
ChatGLM2_6B_32K,
Llama_2_7B_Chat,
Llama_2_13B_Chat,
Llama_2_70B_Chat,
Qianfan_Chinese_Llama_2_7B,
AquilaChat_7B,}/// <summary>/// 返回的token/// </summary>[System.Serializable]publicclassTokenInfo{publicstring access_token =string.Empty;}}
6.输入问题,然后点击发送。
等待回复会有一点点时间,实际开发的时候,可以加一些过渡动画
7.接收到来着文心一言的回答。
8.本教程只作简单的演示功能,开发者可以根据自己的需求设计出丰富的对话功能。
附官方文档
https://cloud.baidu.com/doc/WENXINWORKSHOP/s/flfmc9do2
9.另外我们平时使用文心一言是免费的,但是代码调用文心一言的API是付费的
本文转载自: https://blog.csdn.net/qq_30144243/article/details/136053004
版权归原作者 张不无-Unity 所有, 如有侵权,请联系我们删除。
版权归原作者 张不无-Unity 所有, 如有侵权,请联系我们删除。