Using ChatGPT library for grammar checker API

ChatGPT grammar checker

In this article, we’ll show you a way for using my new ChatGPT library for a grammar checker API: the ChatGPT API takes a paragraph and corrects it for grammar and spelling and return it to the user. In other words, we are creating an API inside an API.

Here are a few links about other my posts related to ChatGPT:

Project Setup

First, 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 is installed, open Visual Studio and choose a new ASP.NET Core Web API.

Create a new project with Visual Studio - Using ChatGPT library for grammar checker API
Create a new project with Visual Studio

Add the new GrammarFixerController

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

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ChatGPTGrammarApi.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;
        }
    }
}

Set the version

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

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

Create the API for the version

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.Http;
using Microsoft.AspNetCore.Mvc;

namespace ChatGPTGrammarApi.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;
        }

        /// <summary>
        /// Versions this instance.
        /// </summary>
        /// <returns>System.String.</returns>
        [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:

ChatGPT Custom API - Version - Using ChatGPT library for grammar checker API
ChatGPT Custom API – Version

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

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. If you need some details on how to do it, please see my other post.

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>"
}

Add the FixGrammar endpoint

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";
}

Now, this method receives as a parameter the SentencePayloadRequest defined as the following:

public class SentencePayloadRequest
{
    /// <summary>
    /// Gets or sets the raw sentence.
    /// </summary>
    /// <value>The raw sentence.</value>
    [JsonPropertyName("rawSentence")]
    public string? RawSentence { get; set; }
}

Add ChatGPT library for C#

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 PSC.CSharp.Library.ChatGPT in your Nuget manager and install it into your project:

Add PSC.CSharp.Library.ChatGPT to the project
Add PSC.CSharp.Library.ChatGPT to the project

First, I define the model for the response called SentencePayloadResponse

public class SentencePayloadResponse
{
    /// <summary>
    /// Gets or sets the fixed sentence.
    /// </summary>
    /// <value>The fixed sentence.</value>
    [JsonPropertyName("fixedSentence")]
    public string? FixedSentence { get; set; }
}

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 ChatGPT.");

    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 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 behaviour. 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 Swagger.

Example of how to use the FixGrammar API
Example of how to use the FixGrammar API

Wrap up

So, in this post, I have just shown you a simple API using my new ChatGPT library for C# to check and fix the grammar of a sentence. If you have more ideas or want to extend this example, please do it and send me your code.

Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.