using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.Networking; [System.Serializable] public struct WenXinRequestMessage { public string role; public string content; public static WenXinRequestMessage UserMessage(string message) { WenXinRequestMessage result; result.role = "user"; result.content = message; return result; } } [System.Serializable] public struct WenXinRequestStruct { public List messages; public string system; } public class WenXinRequest { #region Define #endregion private const string API_KEY = "X8BRDILN7eCD1R2UvUMNBZsN"; private const string SECRET_KEY = "Nwerie6mJqQJm98GyssJtkrbSCwhhc41"; private const string URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?"; private static string s_accessToken; private string m_response; public string Response { get { return m_response; } } public string GetUrl() { return $"{URL}access_token={s_accessToken}"; } private IEnumerator GetAccessToken() { var reqParams = new Dictionary() { {"grant_type", "client_credentials"}, {"client_id", API_KEY}, {"client_secret", SECRET_KEY}, }; using (var req = UnityWebRequest.Post("https://aip.baidubce.com/oauth/2.0/token", reqParams)) { yield return req.SendWebRequest(); if (req.result == UnityWebRequest.Result.ConnectionError) { Debug.LogError("Winxin connection error"); yield break; } JObject obj = JObject.Parse(req.downloadHandler.text); s_accessToken = obj["access_token"].ToString(); Debug.Log($"Access token got {s_accessToken}"); } } public IEnumerator Post(MonoBehaviour context, WenXinRequestStruct winXinRequestStruct) { string bodyJsonString = JsonUtility.ToJson(winXinRequestStruct); if (string.IsNullOrEmpty(s_accessToken)) { yield return context.StartCoroutine(GetAccessToken()); } using (var req = new UnityWebRequest(GetUrl(), "POST")) { byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString); req.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); req.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); req.SetRequestHeader("Content-Type", "application/json"); yield return req.SendWebRequest(); if (req.result == UnityWebRequest.Result.ConnectionError) { Debug.LogError("Winxin connection error"); yield break; } JObject obj = JObject.Parse(req.downloadHandler.text); if (obj == null) { Debug.LogError("Request is null, why?"); yield break; } m_response = obj["result"].ToString(); Debug.Log(m_response); } } }