Using the ChatGPT API in C# and .NET

Michael Gold
5 min readSep 11, 2023

--

Photo by ThisisEngineering RAEng on Unsplash

Introduction

I just finished writing a book on the ChatGPT API and how it can be used for practical applications with Python. It dawned on me that Microsoft also must have added a solution to using OpenAI in their applications as well. In this article we’ll show you how to set up a Saas Endpoint that leverages the ChatGPT API to take a paragraph and correct it for grammar and spelling and return it to the user. In other words, we are creating an API inside an API :-)

Project Setup

To get the best experience creating our web application, we’ll want to use the Visual Studio IDE, which you can download and install here. Once it’s installed, open Visual Studio and choose a new ASP.NET Core Web API.

This will generate a dummy project that can be used to get weather information. We will change this for our purposes. Rename the WeatherForecastController file and class to be called GrammarFixerController.cs. The code for the shell controller is shown below.

using Microsoft.AspNetCore.Mvc;

namespace GrammarHelper.Controllers
{
[ApiController]
[Route("[controller]")]
public class GrammarFixerController : ControllerBase
{
private readonly ILogger<GrammarFixerController> _logger;
private IConfiguration _configuration;

public GrammarFixerController(ILogger<GrammarFixerController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
}
}

Now let’s add a simple Version endpoint to make sure everything is working okay. We are going to place our Version inside of our appsettings.json file so we can alter it easily.

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"VERSION": "1.0"
}

Let’s retrieve the version from appsettings.json using our API. We’ll create a new http GET request to pull the version:

using Microsoft.AspNetCore.Mvc;

namespace GrammarHelper.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class GrammarFixerController : ControllerBase
{
private readonly ILogger<GrammarFixerController> _logger;
private IConfiguration _configuration;

public GrammarFixerController(ILogger<GrammarFixerController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}

[HttpGet("version")]
public string Version()
{
return _configuration["VERSION"];
}
}
}

We are ready to run the code! Run the API from the Visual Studio debugger by hitting F5. This should pull up the swagger endpoint running on localhost in the browser as shown below:

We can run the version endpoint by clicking the Try it out button and by clicking Execute

This shows us the output of our version (1.0) in the response body:

If you were to run the endpoint directly in the browser, you would get a 1.0 in the upper lefthand corner.

Adding our ChatGPT Endpoint

Now comes the fun part, adding our ChatGPT Endpoint to take a raw sentence and return the corrected text. In order to access ChatGPT you’ll need to obtain an openai key from openai. Instructions to do that can be found on the openai page.

Once you’ve retrieved your endpoint from openai, place it into your appsettings.json file:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"VERSION": "1.0",
"OPENAI_API_KEY": "<sk-your-key-here>",
}

Now let’s create our endpoint to accept the sentence to correct. First add the code that will retrieve our api key.

        [HttpPost("fixGrammar")]
public string FixGrammar([FromBody] SentencePayloadRequest request)
{
// retrieve ai key from configuration
var openAiKey = _configuration["OPENAI_API_KEY"];

// add open ai code here
return "fixed sentence";
}

We have the ai key, but we still need to be able to get to the ChatGPT api, hopefully in a convenient way. There is a nuget package that serves just that purpose. Browse for ChatGPT.NET in your nuget manager and install it into your project:

Now we are ready to roll. Let’s complete the method to utilize the power of ChatGPT:

 [HttpPost("fixGrammar")]
public async Task<IActionResult> FixGrammar([FromBody] SentencePayloadRequest request)
{
// retrieve ai key from configuration
var openAiKey = _configuration["OPENAI_API_KEY"];

if (openAiKey == null)
{
return NotFound("key not found");
}

var openai = new ChatGpt(openAiKey);

var fixedSentence = await openai.Ask($"Fix the following sentence for spelling and grammar: {request.RawSentence}");
if (fixedSentence == null)
{
return NotFound("unable to call chat gpt");
}

return Ok(new SentencePayloadResponse() { FixedSentence = fixedSentence });
}

This method gets the api key from the configuration in appsettings.json and uses it to construct the ChatGpt object from the ChatGPT.NET library. It then uses that object to call Ask which sends the prompt to ChatGPT to predict. The prompt is important and instructs chatGPT to fix both grammar and spelling. Ask is an asynchronous method, so we need to make the entire FixGrammar endpoint asynchronous to take advantage of this behavior. In calling Ask, we await the response from ChatGPT and once it has finished its processing, we return the results to the user.

Below is an example of passing a raw sentence payload and retrieving the response inside of swagger.

Conclusion

It is fairly easy to come up with an endpoint and use the power of ChatGPT’s large language model to create a very powerful API of your own. This was an example that required little to no code to create. Of course there are several improvements that can be made to this API like adding bearer tokens, locking the api key in an Azure Vault, and other things involving security, but this will get you started on creating your own powerful endpoints with the help of C# and ChatGPT.

If you want to learn more about the ChatGPT and all the things you can do with it, check out my new book: Crafting Applications with ChatGPT API

--

--