DeepSeekAI.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Net.Http;
  4. using System.Threading.Tasks;
  5. using Fort23.Core;
  6. using UnityEngine;
  7. public class DeepSeekAI
  8. {
  9. /// <summary>
  10. /// DeepSeek APi 访问地址
  11. /// </summary>
  12. private const string BASE_PATH = "https://api.deepseek.com/chat/completions";
  13. /// <summary>
  14. /// DeepSeek配置
  15. /// </summary>
  16. private Configuration configuration;
  17. /// <summary>
  18. /// 设置API KEY
  19. /// </summary>
  20. /// <param name="apiKey"></param>
  21. /// <exception cref="ArgumentException"></exception>
  22. public DeepSeekAI(string apiKey)
  23. {
  24. if (string.IsNullOrEmpty(apiKey))
  25. {
  26. throw new ArgumentException("api key is null",nameof(apiKey));
  27. }
  28. configuration=new Configuration(apiKey);
  29. }
  30. /// <summary>
  31. /// 发送对话结束消息内容到DeepSeek
  32. /// </summary>
  33. public async CTask<ChatCompletionResponse> SendChatCompletionToDeepSeek(ChatCompletionRequest requestMessage)
  34. {
  35. //把消息对象序列成Json字符串
  36. string jsonMessage = JsonConvert.SerializeObject(requestMessage);
  37. var client = new HttpClient();
  38. var request = new HttpRequestMessage(HttpMethod.Post, BASE_PATH);
  39. request.Headers.Add("Accept", "application/json");
  40. request.Headers.Add("Authorization", $"Bearer {configuration.ApiKey}");
  41. var content = new StringContent(jsonMessage, null, "application/json");
  42. Debug.Log("DeepSeek SendRequest:" + jsonMessage);
  43. request.Content = content;
  44. //发送API请求
  45. var response = await client.SendAsync(request);
  46. //验证响应码是否是200 如果是200则说明接口请求成功
  47. response.EnsureSuccessStatusCode();
  48. //读取API响应内容
  49. string reslutJson = await response.Content.ReadAsStringAsync();
  50. Debug.Log("DeepSeek Response:" + reslutJson);
  51. return JsonConvert.DeserializeObject<ChatCompletionResponse>(reslutJson);
  52. }
  53. }