ErnieBotServiceImpl.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. using HTEXGpt.Models;
  2. using Microsoft.AspNetCore.Http;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using System.Text.Json;
  6. using System.Text.Json.Nodes;
  7. namespace HTEXGpt.Services
  8. {
  9. public class ErnieBotServiceImpl : IModelService
  10. {
  11. private readonly string appSecret = "7E0C6SzWE7kb1lSp1Dkb7k6Eg2xFkJoR";
  12. private readonly string apiKey = "vnxaIH9aJLrsiwMI8OchFKEf";
  13. private readonly static string TOKEN_URL_TEMPLATE = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}";
  14. //最大输出Token max_output_tokens=4096
  15. // private readonly static String CHAT_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token={0}";
  16. //最大输出Token max_output_tokens=2048
  17. private readonly static String CHAT_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token={0}";
  18. private readonly string appId = "71670766";
  19. private readonly IHttpClientFactory _httpClientFactory;
  20. public ErnieBotServiceImpl(IHttpClientFactory httpClientFactory)
  21. {
  22. _httpClientFactory=httpClientFactory;
  23. }
  24. public async Task<ChatResponse> ChatMessage(ChatRequest dto, HttpContext httpContext, HttpResponse response)
  25. {
  26. // response.Headers.ContentType="text/event-stream";
  27. //response.Headers.CacheControl="no-cache";
  28. //response.Headers.Connection="keep-alive";
  29. Stopwatch stopwatch = Stopwatch.StartNew(); // 开始计时
  30. ChatResponse chatResponse= new ChatResponse();
  31. try {
  32. var token = await getAccessToken();
  33. JsonElement json = JsonSerializer.Deserialize<JsonElement>(token);
  34. var access_token= json.GetProperty("access_token").GetString();
  35. ErnieBotDTO ernieBotDTO = new ErnieBotDTO
  36. {
  37. messages= dto.messages,
  38. system=dto.system,
  39. stream=false,
  40. // temperature=dto.@params.temperature,
  41. // top_p=dto.@params.top_p,
  42. // max_output_tokens=4096
  43. user_id =dto.uid
  44. };
  45. var httpClient = _httpClientFactory.CreateClient();
  46. string url = string.Format(CHAT_URL, access_token);
  47. var data = JsonSerializer.Serialize(ernieBotDTO);
  48. HttpResponseMessage httpResponse = await httpClient.PostAsJsonAsync(url, ernieBotDTO);
  49. if (httpResponse.IsSuccessStatusCode)
  50. {
  51. var content = await httpResponse.Content.ReadAsStringAsync();
  52. //using (var responseStream = await httpResponse.Content.ReadAsStreamAsync())
  53. //{
  54. // StringBuilder sb = new StringBuilder();
  55. // var buffer = new byte[1024];
  56. // int bytesRead;
  57. // while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
  58. // {
  59. // string contentData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
  60. // Console.WriteLine(contentData);
  61. // await response.WriteAsync($"event:result\n");
  62. // await response.WriteAsync(@$"{contentData}");
  63. // await response.Body.FlushAsync();
  64. // await Task.Delay(500);
  65. // }
  66. //}
  67. StringBuilder sb = new StringBuilder();
  68. var datas = content.Split("data:");
  69. foreach (var jsonData in datas)
  70. {
  71. try
  72. {
  73. JsonNode j = JsonSerializer.Deserialize<JsonNode>(jsonData);
  74. sb.Append($"{j["result"]}");
  75. var total_tokens = j?["usage"]?["total_tokens"];
  76. if (total_tokens!= null)
  77. {
  78. chatResponse.total_tokens=int.Parse($"{total_tokens}");
  79. }
  80. var completion_tokens = j?["usage"]?["completion_tokens"];
  81. if (completion_tokens!= null)
  82. {
  83. chatResponse.completion_tokens=int.Parse($"{completion_tokens}");
  84. }
  85. var prompt_tokens = j?["usage"]?["prompt_tokens"];
  86. if (prompt_tokens!= null)
  87. {
  88. chatResponse.prompt_tokens=int.Parse($"{prompt_tokens}");
  89. }
  90. }
  91. catch { }
  92. }
  93. chatResponse.result= sb.ToString();
  94. chatResponse.statusCode= System.Net.HttpStatusCode.OK;
  95. // await response.WriteAsync(@$"{content}");
  96. // await response.Body.FlushAsync();
  97. }
  98. else {
  99. chatResponse.statusCode=httpResponse.StatusCode;
  100. string content = await httpResponse.Content.ReadAsStringAsync();
  101. chatResponse.error=$"{content}";
  102. }
  103. } catch (Exception ex) {
  104. chatResponse.statusCode=System.Net.HttpStatusCode.InternalServerError;
  105. chatResponse.error=$"{ex.Message},{ex.StackTrace}";
  106. }
  107. finally
  108. {
  109. // response.Body.Close();
  110. stopwatch.Stop(); // 停止计时
  111. chatResponse.time= stopwatch.ElapsedMilliseconds;
  112. }
  113. return chatResponse;
  114. }
  115. private async Task<string> getAccessToken()
  116. {
  117. var token_url= string.Format(TOKEN_URL_TEMPLATE, apiKey, appSecret);
  118. var httpClient = _httpClientFactory.CreateClient();
  119. httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
  120. var response = await httpClient.PostAsJsonAsync(token_url,new { });
  121. if (response.StatusCode==System.Net.HttpStatusCode.OK) {
  122. var content = await response.Content.ReadAsStringAsync();
  123. return content;
  124. }
  125. return null;
  126. }
  127. }
  128. public class ErnieBotDTO
  129. {
  130. public List<MessageDTO> messages { get; set; } = new List<MessageDTO>();
  131. public string? system { get; set; }
  132. public double temperature { get; set; } = 0.95;
  133. public bool stream { get; set; } = true;
  134. public double top_p { get; set; } = 0.7;
  135. public string response_format { get; set; } = "text";
  136. // public double penalty_score { get; set; }
  137. // public bool enable_citation { get; set; }
  138. // public bool disable_search { get; set; }
  139. public string? user_id { get; set; }
  140. }
  141. }