Unity接入DeepSeek API指南

1. 准备工作

  • 获取API密钥
    前往DeepSeek官网注册账号,创建应用并获取API密钥(通常格式为sk-xxxxxxxx)。

  • 查看API文档
    获取API端点URL(如https://api.deepseek.com/v1/chat/completions)及参数要求(如modelmessages等)。


2. 创建Unity脚本

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class DeepSeekIntegration : MonoBehaviour
{
    private const string API_URL = "https://api.deepseek.com/v1/chat/completions";
    private const string API_KEY = "YOUR_API_KEY"; // 替换为你的密钥

    public void SendRequest(string userInput)
    {
        StartCoroutine(PostRequest(userInput));
    }

    private IEnumerator PostRequest(string input)
    {
        // 1. 构建请求体
        var requestBody = new RequestData
        {
            model = "deepseek-chat",
            messages = new[]
            {
                new Message { role = "user", content = input }
            }
        };
        string jsonBody = JsonUtility.ToJson(requestBody);

        // 2. 创建UnityWebRequest
        using UnityWebRequest request = new UnityWebRequest(API_URL, "POST");
        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonBody);
        request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = new DownloadHandlerBuffer();

        // 3. 设置请求头
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Authorization", $"Bearer {API_KEY}");

        // 4. 发送请求
        yield return request.SendWebRequest();

        // 5. 处理响应
        if (request.result == UnityWebRequest.Result.Success)
        {
            var response = JsonUtility.FromJson<ResponseData>(request.downloadHandler.text);
            string reply = response.choices[0].message.content;
            Debug.Log("AI回复: " + reply);
            // 在此处处理回复(如更新UI)
        }
        else
        {
            Debug.LogError($"请求失败: {request.error}");
        }
    }

    // 数据模型
    [System.Serializable]
    private class RequestData
    {
        public string model;
        public Message[] messages;
    }

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

    [System.Serializable]
    private class ResponseData
    {
        public Choice[] choices;
    }

    [System.Serializable]
    private class Choice
    {
        public Message message;
    }
}

3. 使用脚本

  1. 将脚本挂载到游戏对象(如GameManager)。
  2. 调用SendRequest方法发送请求:
// 示例:当玩家按下按键时发送请求
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        SendRequest("你好,请介绍一下Unity引擎。");
    }
}

4. 注意事项

  • 密钥安全
    不要将API密钥硬编码在代码中!建议:

    • 使用环境变量

    • 加密存储在配置文件

    • 通过服务器中转请求(更安全)

  • 异步处理
    Unity协程不会阻塞主线程,但需处理加载状态(如显示“等待中”UI)。

  • 跨平台问题
    WebGL需处理CORS,可能需要配置服务器响应头。

  • 错误处理
    添加重试机制、网络检查及详细的错误日志。

  • 速率限制
    查看API文档了解每分钟最大请求数,避免超额调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值