文章摘要
这篇文章介绍了一个C#类库,用于异步调用OpenAI的API以获取响应数据。该类库包含以下主要功能:
1. `GetResponseDataAsync`方法:通过设置API URL和密钥,异步发送请求并返回响应数据。
2. `GetRequestBodyJson`方法:构建JSON请求体,包含多个参数如模型、提示内容、温度、最大生成字数等。
3. `SendApiRequestAsync`方法:处理整个请求流程,包括创建HttpClient,设置请求头,发送POST请求,并解密响应。
文章重点描述了如何通过该类库实现与OpenAI 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);
}