使用 .NET MAUI 开发 ChatGPT 客户端的流程(使用内在价值法对股票进行估值的方法)奔走相告

随心笔谈3年前发布 admin
197 0 0

文章摘要

这篇文章介绍了一个C#类,用于通过OpenAI API获取文本数据。该类包含两个静态方法:`GetResponseDataAsync`和`SendApiRequestAsync`,以及一个私有方法`GetRequestBodyJson`。`GetResponseDataAsync`用于设置API URL、解析请求参数(如温度、最大 tokens等)并调用API;`SendApiRequestAsync`负责发送请求并处理响应。`GetRequestBodyJson`方法构建请求体JSON数据。文章重点描述了如何构建一个公开获取数据的API客户端,并处理模型输出。

 public static async Task<CompletionsResponse> GetResponseDataAsync(string prompt)
{
// Set up the API URL and API key
string apiUrl=”https://api.openai.com/v1/completions”;

// Get the request body JSON
decimal temperature=decimal.Parse(Setting.Temperature, CultureInfo.InvariantCulture);
int maxTokens=int.Parse(Setting.MaxTokens, CultureInfo.InvariantCulture);
string requestBodyJson=GetRequestBodyJson(prompt, temperature, maxTokens);

// Send the API request and get the response data
return await SendApiRequestAsync(apiUrl, Setting.ApiKey, requestBodyJson);
}

private static string GetRequestBodyJson(string prompt, decimal temperature, int maxTokens)
{
// Set up the request body
var requestBody=new CompletionsRequestBody
{
Model=”text-davinci-003″,
Prompt=prompt,
Temperature=temperature,
MaxTokens=maxTokens,
TopP=1.0m,
FrequencyPenalty=0.0m,
PresencePenalty=0.0m,
N=1,
Stop=”[END]”,
};

// Create a new JsonSerializerOptions object with the IgnoreNullValues and IgnoreReadOnlyProperties properties set to true
var serializerOptions=new JsonSerializerOptions
{
IgnoreNullValues=true,
IgnoreReadOnlyProperties=true,
};

// Serialize the request body to JSON using the JsonSerializer.Serialize method overload that takes a JsonSerializerOptions parameter
return JsonSerializer.Serialize(requestBody, serializerOptions);
}

private static async Task<CompletionsResponse> SendApiRequestAsync(string apiUrl, string apiKey, string requestBodyJson)
{
// Create a new HttpClient for making the API request
using HttpClient client=new HttpClient();

// Set the API key in the request headers
client.DefaultRequestHeaders.Add(“Authorization”, “Bearer ” + apiKey);

// Create a new StringContent object with the JSON payload and the correct content type
StringContent content=new StringContent(requestBodyJson, Encoding.UTF8, “application/json”);

// Send the API request and get the response
HttpResponseMessage response=await client.PostAsync(apiUrl, content);

// Deserialize the response
var responseBody=await response.Content.ReadAsStringAsync();

// Return the response data
return JsonSerializer.Deserialize<CompletionsResponse>(responseBody);
}

© 版权声明

相关文章