Unity接入 KimiChat 代码示例

代码

using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

public class TestKimi : MonoBehaviour {
    private string apiKey = "Your Key"; // 替换为你的API密钥
    private string apiUrl = "https://api.moonshot.cn/v1/chat/completions"; // KimiChat的API端点

    public void MyBtn() {
        OnUserInput("说下最近天气");
    }

    private void OnUserInput(string input) {
        PostRequest(input);
    }

    // 定义一个异步方法来发送POST请求
    private async Task<string> PostRequest(string jsonData) {
        // 使用using声明确保UnityWebRequest被正确地释放
        using (UnityWebRequest request = new UnityWebRequest(apiUrl, "POST")) {
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Authorization", $"Bearer {apiKey}");

            var chatRequest = new ChatRequest {
                model = "moonshot-v1-8k",
                messages = new ChatMessage[] {
                    new ChatMessage { role = "system", content = "你是 Kimi,由 Moonshot AI 提供的人工智能助手..." },
                    new ChatMessage { role = "user", content = jsonData }
                },
                temperature = 0.3f,
            };

            string str = JsonUtility.ToJson(chatRequest);
            Debug.Log(str);
            Debug.Log("Sending request to: " + request.url);
            request.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(str));
            request.downloadHandler = new DownloadHandlerBuffer();

            // 发送请求并等待异步完成
            await request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.ConnectionError &&
                request.result != UnityWebRequest.Result.ProtocolError) {
                Debug.Log(request.downloadHandler.text);
                return request.downloadHandler.text;
            } else {
                Debug.LogError(request.error);
            }
        }

        return "";
    }
}

public static class ExtensionMethods {
    public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp) {
        var tcs = new TaskCompletionSource<object>();
        asyncOp.completed += obj => { tcs.SetResult(null); };
        return ((Task)tcs.Task).GetAwaiter();
    }
}

[System.Serializable]
public class ChatMessage {
    public string role;
    public string content;
}

[System.Serializable]
public class ChatRequest {
    public string model;
    public ChatMessage[] messages;
    public float temperature;
}

 

posted @ 2024-02-07 17:41  三页菌  阅读(274)  评论(0编辑  收藏  举报