DeepSeekAI.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. private const string HUOSHAN_BASE_PATH = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
  14. /// <summary>
  15. /// DeepSeek配置
  16. /// </summary>
  17. private Configuration configuration;
  18. /// <summary>
  19. /// 设置API KEY
  20. /// </summary>
  21. /// <param name="apiKey"></param>
  22. /// <exception cref="ArgumentException"></exception>
  23. public DeepSeekAI(string apiKey)
  24. {
  25. if (string.IsNullOrEmpty(apiKey))
  26. {
  27. throw new ArgumentException("api key is null",nameof(apiKey));
  28. }
  29. configuration=new Configuration(apiKey);
  30. }
  31. /// <summary>
  32. /// 发送对话结束消息内容到DeepSeek
  33. /// </summary>
  34. public async CTask<ChatCompletionResponse> SendChatCompletionToDeepSeek(ChatCompletionRequest requestMessage)
  35. {
  36. //把消息对象序列成Json字符串
  37. string jsonMessage = JsonConvert.SerializeObject(requestMessage);
  38. var client = new HttpClient();
  39. var request = new HttpRequestMessage(HttpMethod.Post, HUOSHAN_BASE_PATH);
  40. request.Headers.Add("Accept", "application/json");
  41. request.Headers.Add("Authorization", $"Bearer {configuration.ApiKey}");
  42. var content = new StringContent(jsonMessage, null, "application/json");
  43. Debug.Log("DeepSeek SendRequest:" + jsonMessage);
  44. request.Content = content;
  45. //发送API请求
  46. var response = await client.SendAsync(request);
  47. //验证响应码是否是200 如果是200则说明接口请求成功
  48. response.EnsureSuccessStatusCode();
  49. //读取API响应内容
  50. string reslutJson = await response.Content.ReadAsStringAsync();
  51. Debug.Log("DeepSeek Response:" + reslutJson);
  52. return JsonConvert.DeserializeObject<ChatCompletionResponse>(reslutJson);
  53. }
  54. }