Unity DeepSeek API 聊天接入教程(0基础教学)
1.DeepSeek 介绍
DeepSeek是杭州深度求索人工智能基础技术研究有限公司推出的一款大语言模型。2025年1月20日,DeepSeek-R1正式上线,和当前市面上的主流AI相比,它在仅有极少标注数据的情况下,极大提升了模型推理能力。在数学、代码、自然语言推理等任务上,性能比肩 OpenAI o1 正式版。作为一款开源国产AI模型,它兼具普惠性和优越性能,非常适合大众开发者。我们也可以在Unity中调用它的强大功能,接下来将用一个简单例子介绍DeepSeek的接入和使用。
2.接入流程
Unity 接入DeepSeek API 实现聊天分为3个步骤
1.DeepSeek API Key 获取
首先我们需要到 DeepSeek API 开放平台 https://platform.deepseek.com/usage 获取API Key,用来和DeepSeek API接口进行数据通讯。
跳转到网页后点击 Keys
然后执行以下步骤:
注意:API Key创建成功后,要及时截图或妥善保存。因为API Key只有在创建成功的时候,才会暴露Key值全量字符串。一但关闭该面板,将无法在查看到本次创建的API Key值。
2.DeepSeek API 数据通讯模型声明
1.这一步我们要去获取到 DeepSeek API 标准的通讯协议格式,否则DeepSeek API 将无法识别我们发送的数据。即无法与其进行会话和通讯。
获取方式如下:
2.这一步展示了如何获取API(HTTP) 接口的请求地址,和API Key的传参示例,以及请求的Json数据的格式。
3.这一步展示了如何通过HTTP向DeepSeek发送消息,HTTP响应中的Json结构体内容。
以及DeepSeek对每一个字段的使用方式的介绍
拿到这些数据后,我们就可以回到Unity中进行制作功能了。
3.异步收发消息
下面展示一下DeepSeek API 数据模型和HTTP请求响应处理代码。
1.DeepSeek数据模型代码
/*----------------------------------------------------------------------------
* Title: #Title#
*
* Author: 铸梦
*
* Date: #CreateTime#
*
* Description:
*
* Remarks: QQ:975659933 邮箱:zhumengxyedu@163.com
*
* 教学网站:www.yxtown.com/user/38633b977fadc0db8e56483c8ee365a2cafbe96b
----------------------------------------------------------------------------*/
using System.Collections.Generic;#region DeepSeek API Key 配置数据模型
public class Configuration
{ public string ApiKey { get; }public Configuration(string apiKey){ApiKey=apiKey;}
}
#endregion#region DeepSeek 请求数据模型
/// <summary>
/// 聊天对话消息完成请求
/// </summary>
public class ChatCompletionRequest
{/// <summary>/// 消息列表/// </summary>public List<ChatMessage> messages;/// <summary>/// AI模型,是聊天模型还是推理模型/// </summary>public string model;/// <summary>/// 如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。/// </summary>public bool stream;
}
public class ChatMessage
{/// <summary>/// 消息内容/// </summary>public string content;/// <summary>/// 角色,是哪个角色的消息(是用户消息还是DP系统消息又或者是我们自定义的NPC角色消息)/// </summary>public string role;
}
#endregion# region DeepSeek 响应数据模型
public class ChatCompletionResponse
{/// <summary>/// iD/// </summary>public string id;/// <summary>/// 创建时间/// </summary>public long created;/// <summary>/// AI模型,是聊天模型还是推理模型/// </summary>public string model;/// <summary>/// 可选择的消息内容/// </summary>public List<ChatResponseMessage> choices;
}
public class ChatResponseMessage
{ /// <summary>/// 消息索引/// </summary>public int index;/// <summary>/// 消息列表/// </summary>public ChatMessage message;/// <summary>/// AI模型,是聊天模型还是推理模型/// </summary>public string finish_reason;}#endregion
2.DeepSeekAPI 请求和响应处理脚本
/*----------------------------------------------------------------------------
* Title: #Title#
*
* Author: 铸梦
*
* Date: #CreateTime#
*
* Description:
*
* Remarks: QQ:975659933 邮箱:zhumengxyedu@163.com
*
* 教学网站:www.yxtown.com/user/38633b977fadc0db8e56483c8ee365a2cafbe96b
----------------------------------------------------------------------------*/
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;public class DeepSeekAI
{/// <summary>/// DeepSeek APi 访问地址/// </summary>private const string BASE_PATH = "https://api.deepseek.com/chat/completions";/// <summary>/// DeepSeek配置/// </summary>private Configuration configuration;/// <summary>/// 构造函数(使用DeekSeekAI时必须要指定APIKey) /// </summary>/// <param name="apiKey"></param>/// <exception cref="ArgumentException"></exception>public DeepSeekAI(string apiKey){if (string.IsNullOrEmpty(apiKey)){throw new ArgumentException("api key is null",nameof(apiKey));}configuration=new Configuration(apiKey);}/// <summary>/// 发送对话结束消息内容到DeepSeek/// </summary>public async Task<ChatCompletionResponse> SendChatCompletionToDeepSeek(ChatCompletionRequest requestMessage){//把消息对象序列成Json字符串string jsonMessage = JsonConvert.SerializeObject(requestMessage);var client = new HttpClient();var request = new HttpRequestMessage(HttpMethod.Post, BASE_PATH);request.Headers.Add("Accept", "application/json");request.Headers.Add("Authorization", $"Bearer {configuration.ApiKey}");var content = new StringContent(jsonMessage, null, "application/json");Debug.Log("DeepSeek SendRequest:" + jsonMessage);request.Content = content;//发送API请求var response = await client.SendAsync(request);//验证响应码是否是200 如果是200则说明接口请求成功response.EnsureSuccessStatusCode();//读取API响应内容string reslutJson = await response.Content.ReadAsStringAsync();Debug.Log("DeepSeek Response:" + reslutJson);return JsonConvert.DeserializeObject<ChatCompletionResponse>(reslutJson);}}
3.DeepSeekWindow UI窗口
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using TMPro;namespace DeepSeek
{public class DeepSeekChatWindow : MonoBehaviour{[SerializeField] private TMP_InputField inputField;[SerializeField] private Button sendButton;[SerializeField] private ScrollRect chatScroll;[SerializeField] private RectTransform sent;[SerializeField] private RectTransform received;private float contentHeight;private DeepSeekAI deepSeekAI = new DeepSeekAI("You DeepSeek Api Key");private List<ChatMessage> messages = new List<ChatMessage>();private string initialPrompt = "Act as a helpful assistant.";private void Start(){sendButton.onClick.AddListener(SendMessage);}/// <summary>/// 追加聊天消息到Canvas上/// </summary>/// <param name="message">消息模型</param>/// <param name="isUser">是否是用户</param>private void AppendMessageToCanvs(string message,bool isUser){chatScroll.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 0);var item = Instantiate(isUser ? sent : received, chatScroll.content);item.GetChild(0).GetChild(0).GetComponent<Text>().text = message;item.anchoredPosition = new Vector2(0, -contentHeight);LayoutRebuilder.ForceRebuildLayoutImmediate(item);contentHeight += item.sizeDelta.y;chatScroll.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, contentHeight);chatScroll.verticalNormalizedPosition = 0;}private async void SendMessage(){//创建聊天消息var userMessage = new ChatMessage{role = "user",content = inputField.text};//显示消息AppendMessageToCanvs(userMessage.content, true);//添加消息messages.Add(userMessage);//创建消息交互请求var request = new ChatCompletionRequest{model = "deepseek-chat",messages = messages,};//发送对话完成消息到DeepSeekvar response = await deepSeekAI.SendChatCompletionToDeepSeek(request);//处理响应if (response?.choices != null && response.choices.Count > 0){var assistantMessage = response.choices[0].message;messages.Add(assistantMessage);//显示消息AppendMessageToCanvs(assistantMessage.content, false);}else{Debug.LogWarning("No response from DeepSeek.");}inputField.text = "";}}
}
Josn数据需要使用NewtonSoftJson.dll库进行序列化和反序列化,这里就不在提供了。
3.源码工程
https://www.yxtown.com/user/38633b977fadc0db8e56483c8ee365a2cafbe96b