ChatGPTTools.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using OpenAI.GPT3;
  2. using OpenAI.GPT3.Managers;
  3. using OpenAI.GPT3.ObjectModels;
  4. using OpenAI.GPT3.ObjectModels.RequestModels;
  5. namespace OASystem.API.OAMethodLib.ChatGPT
  6. {
  7. /// <summary>
  8. /// ChatGPT 3.5
  9. /// </summary>
  10. public static class ChatGPTTools
  11. {
  12. private readonly static string _appKey = "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";
  13. private readonly static HttpClient _httpClient = new HttpClient { BaseAddress = new Uri("https://api.openai.com") };
  14. /// <summary>
  15. /// ChatGPT - Completions 自动补全
  16. /// </summary>
  17. /// <param name="prompt">提示(问题)</param>
  18. /// <returns></returns>
  19. public static async Task<Result> Completions(string prompt)
  20. {
  21. var result = new Result();
  22. string url = string.Format("{0}", "/v1/completions");
  23. var reqData = new CompletionCreateRequest()
  24. {
  25. Prompt = prompt, //提示(问题) 你向API提供的提示,即你提出的问题
  26. Temperature = 0.3f, //创新采样 取值范围0-1,当设置为0时,对于相同的问题,模型始终返回相同或者相近的结果,
  27. //设置1则与上次的回答更加不同。默认1
  28. TopP = 1f, //默认1。替代temperature使用,考虑了模型质量,0.1为生成结果的质量为10%,建议使用1。
  29. N = 1, //默认1。针对提示所生成结果的次数,会大量消耗令牌。
  30. Stream = false, //默认false。是否以流式返回部分进度,流完成后会发送终止消息data:[DONE]
  31. Echo = false, //默认false,在返回结果外,还显示用户给的问题
  32. //Stop = "", //最多四个序列,返回的文本不包括停止序列
  33. MaxTokens = 1024, //默认16,大多数模型支持最大为204
  34. };
  35. return await PostChatGPT(url, reqData);
  36. }
  37. /// <summary>
  38. /// post 访问
  39. /// </summary>
  40. /// <param name="url">接口路径</param>
  41. /// <param name="formData">请求参数</param>
  42. /// <returns></returns>
  43. public static async Task<Result> PostChatGPT(string url, CompletionCreateRequest reqData)
  44. {
  45. Result result = new Result();
  46. OpenAIService service = new OpenAIService(new OpenAiOptions() { ApiKey = _appKey });
  47. var res = await service.Completions.CreateCompletion(reqData, Models.TextDavinciV3);
  48. if (res.Successful)
  49. {
  50. result.Code = 0;
  51. result.Data = new { Text = res.Choices.FirstOrDefault().Text };
  52. }
  53. else result.Msg = "访问失败!";
  54. return result;
  55. }
  56. }
  57. }