Calling ChatGPT using .NET Core

 Hi Guys,

With the immense hype created by ChatGPT every technology is adopting ways to integrate ChatGPT to their frameworks. Hence, a brilliant team led by Hassan Habib has managed to give .NET Developers a way to call ChatGPT programmatically and get the responses.

Remember this is still a new project you might encounter some issues, but the Standard.AI.OpenAI team is ready to help us developers in this journey.

The source code can be found here.

1) First you must register yourself at https://platform.openai.com

2) Then you must generate an API Key as shown below.











3) Now you can start integrating your .NET Core applications to use openai. For this purpose I use a console application (.NET 7). 

4) Install the Nuget package Standard.AI.OpenAI

5) Copy paste the below code

using Microsoft.AspNetCore.Mvc;
using Standard.AI.OpenAI.Brokers.DateTimes;
using Standard.AI.OpenAI.Clients.OpenAIs;
using Standard.AI.OpenAI.Models.Configurations;
using Standard.AI.OpenAI.Models.Services.Foundations.ChatCompletions;


OpenAIConfigurations openAIConfigurations = new OpenAIConfigurations() { 
     ApiKey = "<YOURAPIKEY>",
     OrganizationId = "<YOURORGID>",

};



OpenAIClient openAIClient = new OpenAIClient(openAIConfigurations);

ChatCompletion chatCompletion = new ChatCompletion() { 
Request = new ChatCompletionRequest() {
    Model = "gpt-3.5-turbo",
    Messages = new ChatCompletionMessage[]
                    {
                        new ChatCompletionMessage
                        {
                            Content = "What is Java?",
                            Role = "user",
                        }
                    }

}
};

ChatCompletion resultChatCompletion = await openAIClient.ChatCompletions.SendChatCompletionAsync(chatCompletion);


Array.ForEach(
    resultChatCompletion.Response.Choices,
    choice => Console.WriteLine(
        value: $"{choice.Message.Role}: {choice.Message.Content}"));


Console.Read();

6) Final Result








Comments