Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / artificial-intelligence / ChatGPT

Integrating ChatGPT API in C#

3.00/5 (5 votes)
2 Apr 2023CPOL2 min read 27.5K  
Integrating ChatGPT-3.5 Turbo API in C#: A Comprehensive Guide
In today's tutorial, we will be exploring how to integrate the powerful ChatGPT-3.5 Turbo API in C#. By the end of this guide, you'll be able to implement this API in your C# projects and take advantage of its capabilities. Let's get started!

Introduction

This article demonstrates how to integrate the ChatGPT-3.5 Turbo API in C#. It solves the problem of implementing a powerful AI language model in your C# applications, opening up possibilities for chatbots, content generation, and more. The code snippet is useful for developers looking to take advantage of the ChatGPT-3.5 Turbo API within their C# projects.

Background

ChatGPT-3.5 Turbo is an advanced language model developed by OpenAI. It can understand and generate human-like text, making it an incredibly valuable tool for various applications such as chatbots, content creation, and more.

Using the Code

Install-Package Betalgo.OpenAI.GPT3

Start by declaring your OpenAI API key. Replace the placeholder with your actual API key.

C#
var apiKey = "Your OpenAi Key here";

Create an instance of the OpenAIService class and pass in your API key.

C#
var gpt3 = new OpenAIService(new OpenAiOptions()
{
    ApiKey = apiKey
});

Create a chat completion request containing the input message, the model, and other parameters.

C#
var completionResult = await gpt3.ChatCompletion.CreateCompletion
                       (new ChatCompletionCreateRequest()
{
    Messages = new List<ChatMessage>(new ChatMessage[] 
    { new ChatMessage("user", "how to learn c# in 24 hours") }),
    Model = Models.ChatGpt3_5Turbo,
    Temperature = 0.5F,
    MaxTokens = 100,
    N = 3
});

In this example, we set the user's prompt as "how to learn C# in 24 hours." We utilize the ChatGpt3_5Turbo model for our request. The Temperature is set to 0.5, influencing the randomness of the output. The MaxTokens parameter is set to 100, limiting the response to a maximum of 100 tokens. Finally, the N parameter is set to 3, which means we will receive three different responses.

After obtaining the completion result, check if it was successful and handle the response accordingly.

C#
if (completionResult.Successful)
{
    foreach (var choice in completionResult.Choices)
    {
        Console.WriteLine(choice.Message.Content);
    }
}
else
{
    if (completionResult.Error == null)
    {
        throw new Exception("Unknown Error");
    }
    Console.WriteLine($"{completionResult.Error.Code}: 
                        {completionResult.Error.Message}");
}

In this block of code, we first check if the request was successful. If so, we loop through the choices and print each response. If the request is unsuccessful, we print the error message. If there's no error information, we throw an exception with the message "Unknown Error."

Here's the Complete Code Snippet

C#
// Declare the API key
var apiKey = "your-api-key-here";

// Create an instance of the OpenAIService class
var gpt3 = new OpenAIService(new OpenAiOptions()
{
    ApiKey = apiKey
});

// Create a chat completion request
var completionResult = await gpt3.ChatCompletion.CreateCompletion
                       (new ChatCompletionCreateRequest()
{
    Messages = new List<ChatMessage>(new ChatMessage[] 
               { new ChatMessage("user", "how to learn c# in 24 hours") }),
    Model = Models.ChatGpt3_5Turbo,
    Temperature = 0.5F,
    MaxTokens = 100,
    N = 3
});

// Check if the completion result was successful and handle the response
if (completionResult.Successful)
{
    foreach (var choice in completionResult.Choices)
    {
        Console.WriteLine(choice.Message.Content);
    }
}
else
{
    if (completionResult.Error == null)
    {
        throw new Exception("Unknown Error");
    }
    Console.WriteLine($"{completionResult.Error.Code}: 
                        {completionResult.Error.Message}");
}

// Keep the console window open
Console.ReadLine();

Here is our response from OpenAI API.

Image 1

Points of Interest

While writing the code, we learned how easy it is to integrate the ChatGPT-3.5 Turbo API into a C# application. By utilizing Betalgo.OpenAI.GPT3, developers can quickly set up the API and begin receiving intelligent responses for various applications. The flexibility of the API and its parameters allow for customization, making it an incredibly useful tool for a wide range of projects.

History

  • 2nd April, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)