Call chatgpt api in C#


  • As a language model, ChatGPT can provide answers to a wide range of questions and can be accessed using various programming languages including C#. Here's an example of how you can use ChatGPT in a C# program
  • Here are the general steps to get an OpenAI API key:
  • Go to the OpenAI website:?https://openai.com/
  • Click on the "Sign up" button in the top right corner of the page.
  • Fill in your details to create an account.
  • Once you're logged in, go to the API page:?https://beta.openai.com/docs/api-reference/introduction
  • Follow the instructions to create an API key, and you should be good to go!
  • First, you need to create an API client to connect to the OpenAI API that powers ChatGPT.
  • You can use the?HttpClient?class to make HTTP requests to the API.

using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class OpenAIApiClient
{
??? private readonly HttpClient _httpClient;
??? private readonly string _apiKey;
??? public OpenAIApiClient(string apiKey)

??? {
??????? _apiKey = apiKey;
??????? _httpClient = new HttpClient();
??????? _httpClient.BaseAddress = new Uri("https://api.openai.com/v1/");
??????? _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
??? }?

??? public async Task<string> SendPrompt(string prompt, string model)
??? {
??????? var requestBody = new
??????? {
??????????? prompt = prompt,
??????????? model = model,
??????????? max_tokens = 150,
??????????? temperature = 0.5
??????? };?

??????? var response = await _httpClient.PostAsJsonAsync("completions", requestBody);
??????? response.EnsureSuccessStatusCode();
??????? var responseBody = await response.Content.ReadAsStringAsync();
??????? return responseBody;
??? }
}

Once you have an API client, you can use it to send prompts to ChatGPT and get responses.

var openAIApiClient = new OpenAIApiClient("your-api-key-here");
var response = await openAIApiClient.SendPrompt("Hello, ChatGPT!", "davinci");
Console.WriteLine(response);
        

  • In the example above, we created an instance of the?OpenAIApiClient?class and called its?SendPrompt?method with a prompt and the name of the ChatGPT model we want to use (in this case, the?davinci?model).
  • The method returns the response from ChatGPT as a string, which we then print to the console.
  • You can customize the parameters of the API request to get different types of responses from ChatGPT. For more information on the available parameters, you can refer to the OpenAI API documentation.

要查看或添加评论,请登录

Avadhesh Sengar的更多文章

社区洞察

其他会员也浏览了