效果图(根据以下图片完成基本搭建)
注意:一定要导入该博客所带的资源包
【有道云笔记】Json.dll
https://note.youdao.com/s/XoR0WCuq
一、流程设计:
1.前往平台获取API KEY
注意:一定要保存好该密钥
2.获取后的API粘贴到apikey中
二、对话的UI设计
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ChatSystem : MonoBehaviour
{
public InputField chatInputField; // 输入框
public Text chatLog; // 聊天记录显示区域
public Button sendButton; // 发送按钮(可选)
public ScrollRect scrollRect; // 滚动区域(可选)
public DeepSeekAPI deepSeekAPI;
void Start()
{
// 监听发送按钮的点击事件
if (sendButton != null)
{
sendButton.onClick.AddListener(SendMessageToChat);
}
// 监听输入框的回车键事件
chatInputField.onEndEdit.AddListener(OnInputEndEdit);
}
void OnInputEndEdit(string text)
{
// 检查是否按下了回车键
if (Input.GetKey(KeyCode.Return) || Input.GetKey(KeyCode.KeypadEnter))
{
SendMessageToChat();
}
}
void SendMessageToChat()
{
chatInputField.interactable = false;
// 获取输入框中的文字
string message = chatInputField.text;
// 如果消息为空,则不发送
if (string.IsNullOrWhiteSpace(message))
{
return;
}
deepSeekAPI.SendMessageToDeepSeek(message, (info) => { StartTypewriter(info + "\n" + "\n"); });
// 显示用户消息
chatLog.text += "我: " + message + "\n"+"\n";
// 清空输入框
chatInputField.text = "";
// 重新激活输入框
chatInputField.ActivateInputField();
// 调整滚动区域
if (scrollRect != null)
{
Canvas.ForceUpdateCanvases();
scrollRect.verticalNormalizedPosition = 0f;
}
// 模拟AI回复
}
// public Text typewriterText; // 用于显示打字效果的Text组件
private string fullText; // 完整的文本内容
private bool isTyping = false; // 是否正在打字
// 开始打字效果
public void StartTypewriter(string text)
{
if (isTyping)
{
// 如果正在打字,则跳过当前效果
StopAllCoroutines();
// typewriterText.text = fullText;
isTyping = false;
return;
}
// 设置完整文本
fullText = text;
// typewriterText.text = "";
// 启动协程
StartCoroutine(TypeText());
}
// 打字效果协程
IEnumerator TypeText()
{
isTyping = true;
string s = "";
chatLog.text += "DeepSeek:";
// 逐个字符显示文本
for (int i = 0; i < fullText.Length; i++)
{
// s = fullText.Substring(0, i);
chatLog.text += fullText[i];
yield return 1;
}
chatInputField.interactable = true;
scrollRect.verticalNormalizedPosition = 0f;
chatInputField.ActivateInputField();
isTyping = false;
}
}
三、DeepSeekAPI
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using Newtonsoft.Json;
using UnityEngine.UI;
using UnityEngine.Events;
public class DeepSeekAPI : MonoBehaviour
{
private string apiKey = "";
private string apiUrl = "https://api.deepseek.com/v1/chat/completions";
public void SendMessageToDeepSeek(string message,UnityAction<string> callback)
{
StartCoroutine(PostRequest(message, callback));
}
IEnumerator PostRequest(string message, UnityAction<string> callback)
{
// 创建请求体
var requestBody = new
{
model = "deepseek-chat",
messages = new[]
{
new { role = "user", content = message }
}
};
// 使用Newtonsoft.Json序列化
string jsonBody = JsonConvert.SerializeObject(requestBody);
// 创建UnityWebRequest
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonBody);
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.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + request.error);
Debug.LogError("Response: " + request.downloadHandler.text); // 打印详细错误信息
}
else
{
// 处理响应
string responseJson = request.downloadHandler.text;
Debug.Log("Response: " + responseJson);
// 解析响应
var response = JsonConvert.DeserializeObject<DeepSeekResponse>(responseJson);
if (response != null && response.choices.Length > 0)
{
string reply = response.choices[0].message.content;
Debug.Log("DeepSeek says: " + reply);
callback(reply);
}
else
{
Debug.LogError("Failed to parse response.");
}
}
}
// 定义响应数据结构
[System.Serializable]
private class DeepSeekResponse
{
public Choice[] choices;
}
[System.Serializable]
private class Choice
{
public Message message;
}
[System.Serializable]
private class Message
{
public string role;
public string content;
}
}
注意:
1.一定要保存好该密钥
2.deepseek接入unity后,使用可能产生费用可能需要充值