CSharp.net调用chatGPT代码

openai 文章 2023-02-07 17:31 1499 0 全屏看文

AI助手支持GPT4.0

以下是一段使用 .NET 调用 OpenAI 的 GPT-3 的代码示例:

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

namespace ChatGPTExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Enter your question:");
            string question = Console.ReadLine();

            // Replace the API key with your own key
            string apiKey = "your_api_key";
            string prompt = $"{question}";

            // Send the prompt to the OpenAI API to get a response
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            var response = await client.PostAsync("https://api.openai.com/v1/engines/davinci/jobs",
                new StringContent(
                    "{%"prompt%":%"" + prompt + "%",%"max_tokens%":1024,%"temperature%":0.5}",
                    Encoding.UTF8,
                    "application/json"));

            if (response.IsSuccessStatusCode)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                var result = Newtonsoft.Json.JsonConvert.DeserializeObject<OpenAI_Response>(responseString);
                Console.WriteLine("Response: " + result.choices[0].text);
            }
            else
            {
                Console.WriteLine("Error: " + response.StatusCode);
            }
        }
    }

    public class OpenAI_Response
    {
        public Choice[] choices { get; set; }
    }

    public class Choice
    {
        public string text { get; set; }
    }
}


-EOF-

AI助手支持GPT4.0