send an openai prompt in csharp

You can send an OpenAI prompt in C# by making an HTTP POST request to the OpenAI API. Here's an example code snippet using the HttpClient class to send a prompt and receive a response from the OpenAI API:

main.cs
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var prompt = "Once upon a time";
        var apiKey = "your-api-key";
        var apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        var requestBody = new {
            prompt = prompt,
            max_tokens = 10,
            n = 1,
            stop = "."
        };

        var requestBodyJson = JsonSerializer.Serialize(requestBody);
        var httpContent = new StringContent(requestBodyJson, System.Text.Encoding.UTF8, "application/json");

        var httpResponse = await httpClient.PostAsync(apiUrl, httpContent);
        var httpResponseContent = await httpResponse.Content.ReadAsStringAsync();
        var responseObject = JsonSerializer.Deserialize<OpenAiResponse>(httpResponseContent);

        Console.WriteLine(responseObject.choices[0].text);
    }
}

class OpenAiResponse
{
    public OpenAiChoice[] choices { get; set; }
}

class OpenAiChoice
{
    public string text { get; set; }
    public double logprobs { get; set; }
    public int finish_reason { get; set; }
}
1308 chars
46 lines

This example uses the HttpClient class to HTTP POST the prompt to the OpenAI API using a JSON payload, and then deserializes the JSON response into an object that you can manipulate in your C# code.

Note that you need an OpenAI API key to use this code, which you can get by following the instructions on the OpenAI website.

related categories

gistlibby LogSnag