【Unity+AI01】在Unity中调用DeepSeek大模型!实现AI对话功能!

要在Unity中调用DeepSeek的API并实现用户输入文本后返回对话的功能,你需要遵循以下步骤:

  1. 获取API密钥
    首先,你需要从DeepSeek获取API密钥。这通常涉及到注册账户,并可能需要订阅相应的服务。

  2. 集成HTTP请求库
    Unity本身不直接支持HTTP请求,因此你需要集成一个HTTP请求库,如UnityWebRequest或第三方库如LitJsonNewtonsoft.Json等,用于处理JSON数据的序列化和反序列化。

  3. 编写API调用代码
    在Unity中创建一个脚本,用于处理用户输入和API调用。以下是一个简单的示例,展示了如何使用UnityWebRequest来调用API:

一、搭建场景

一个输入框、一个用于显示的文本框即可,一个按钮,按钮上有个回调函数!

 总共就一个脚本:

你用人家官方的大模型,肯定需要联网调用,去官网(我用的DeepSeek),其他网站都一样!申请个API key 就可以了!代码里面需要是我的API ,里面只有2块钱!仅供大家体验!你可以自己充值,还算便宜!

传送门:DeepSeek这是我的 APIKEY:sk-d17be4a259504db3825c8d20d463dddd 

整个代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.Text;
using TMPro;

public class DeepSeekChat : MonoBehaviour
{
    // 替换为你的 DeepSeek API key
    private string apiKey = "sk-d17be4a259504db3825c8d20d463dddd";
    private string apiUrl = "https://api.deepseek.com/chat/completions";

    // Unity UI 元素
    public TMP_InputField userInputField;
    public TextMeshProUGUI chatOutputText;

    // 用于存储对话历史
    private List<Dictionary<string, string>> messages = new List<Dictionary<string, string>>();

    void Start()
    {
        // 初始化系统消息
        messages.Add(new Dictionary<string, string> { { "role", "system" }, { "content", "You are a helpful assistant." } });
    }

    public void OnSendButtonClicked()
    {
        string userMessage = userInputField.text;
        if (string.IsNullOrEmpty(userMessage)) return;

        // 添加用户消息到对话历史
        messages.Add(new Dictionary<string, string> { { "role", "user" }, { "content", userMessage } });

        // 调用 DeepSeek API
        StartCoroutine(CallDeepSeekAPI());
    }

    private IEnumerator CallDeepSeekAPI()
    {
        // 创建请求数据
        var requestData = new
        {
            model = "deepseek-chat",
            messages = messages,
            stream = false
        };

        string jsonData = JsonConvert.SerializeObject(requestData);

        // 创建 UnityWebRequest
        UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
        byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
        request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Authorization", "Bearer " + apiKey);

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

        if (request.result == UnityWebRequest.Result.Success)
        {
            // 解析响应
            var response = JsonConvert.DeserializeObject<DeepSeekResponse>(request.downloadHandler.text);
            string botMessage = response.choices[0].message.content;

            // 显示响应
            chatOutputText.text += "\nAI: " + botMessage;

            // 添加 AI 消息到对话历史
            messages.Add(new Dictionary<string, string> { { "role", "assistant" }, { "content", botMessage } });
        }
        else
        {
            Debug.LogError("Error: " + request.error);
        }
    }

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

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

    [System.Serializable]
    public class Message
    {
        public string content;
    }
}
  1. 处理用户输入
    你需要在Unity中创建一个用户界面(UI),用于接收用户输入。这可以通过Unity的UI系统来实现,例如使用InputField组件来获取文本输入。

  2. 集成用户输入和API调用
    将用户输入与API调用脚本集成,使得用户输入的文本能够被传递给API,并且API的响应能够被显示在Unity的UI中。

  3. 测试和调试
    在Unity中运行你的应用程序,测试用户输入和API调用的流程,确保一切按预期工作。

请注意,上述代码仅为示例,你需要根据DeepSeek API的具体要求来调整URL、参数和JSON解析逻辑。此外,确保你的Unity项目中包含了所有必要的库,并且你的API密钥是安全的,不要在公共代码库中暴露它。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unity3d青子

难题的解决使成本节约,求打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值