Consume ChatGPT Open AI API Inside .Net Core Application Using Razor Pages

Overview

This article demonstrates how to develop a ChatGPT application utilizing Razor pages and the OpenAI API in an ASP.Net Core web application. The "OpenAI Quickstart - pet name generator" application works similarly in that you enter some text as a prompt, and the API returns a text completion that tries to fit the instructions or context you provided.

ChatGPT - Introduction

  • ChatGPT - a generative pre-trained transformer (GPT)
  • It is an AI language model developed by Open AI.
  • It is a machine learning model designed to understand and generate natural language responses.
  • It is designed to understand natural language, generate responses to various questions, and provide information on multiple topics.
  • Its purpose is to provide conversational assistance to users.

Capabilities

  • Remembers what the user said earlier in the conversation
  • Allows users to provide follow-up corrections
  • Trained to decline inappropriate requests

The technology used to build Chat GPT

  • Technologies combination - Natural Language Processing (NLP), Machine Learning (ML), and Deep Learning (DL).
  • Core Architecture - deep neural network called a transformer
  • Programming language - Python
  • Libraries - TensorFlow, PyTorch, and Keras
  • Others - cloud computing platforms, big data technologies, and software development frameworks 

ChatGPT application utilizing Razor pages and OpenAI API in ASP.Net Core

Step 1. Create a solution in the asp.net core web app with some basic setup

Step 2. Edit the index.cshtml, index.cshtml.cs file for consuming open AI API (follow the code below)

Step 3. Sign up for the ChatGPT application (https://platform.openai.com/) and get API Key (so that we can have permission to consume the API) 

Step 4. Run the application with the following screen as output

This is index.cshtml.cs page

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace OpenAI_Quickstart.Pages;

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    [BindProperty]
    public string AnimalInput { get; set; }
    public string Result { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        try
        {

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY_GOES_HERE");

            var request = new OpenAIRequest
            {
                Model = "text-davinci-002",
                Prompt = generatePrompt(AnimalInput), //$"Name my {AnimalInput}",
                Temperature = 0.7f,
                MaxTokens = 50
            };
            var json = JsonSerializer.Serialize(request);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var response = await client.PostAsync("https://api.openai.com/v1/completions", content);
            var resjson = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var errorResponse = JsonSerializer.Deserialize<OpenAIErrorResponse>(resjson);
                throw new System.Exception(errorResponse.Error.Message);
            }
            //var data = JsonSerializer.Deserialize<OpenAIResponse>(resjson);
            var data = JsonSerializer.Deserialize<Root>(resjson);
            //var data = JsonSerializer.Deserialize(resjson, typeof(object));
            Result = data.choices[0].text;
        }
        catch (System.Exception ex)
        {
            _logger.LogError(ex, "An error occurred while making the OpenAI API request");
            Result = $"An error occurred: {ex.Message}";
        }
        return Page();
    }
    public string generatePrompt(string animal)
    {
        var capitalizedAnimal = animal.Trim();
        return "Suggest three names for an animal that is a superhero." +
                "Animal: Cat" +
                "Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline" +
                "Animal: Dog" +
                "Names: Ruff the Protector, Wonder Canine, Sir Barks - a - Lot" +
                "Animal: " + capitalizedAnimal + " " +
                "Names:";
    }
}
public class Choice
{
    public string text { get; set; }
    public int index { get; set; }
    public object logprobs { get; set; }
    public string finish_reason { get; set; }
}
public class Root
{
    public string id { get; set; }
    public string @object { get; set; }
    public int created { get; set; }
    public string model { get; set; }
    public List<Choice> choices { get; set; }
    public Usage usage { get; set; }
}
public class Usage
{
    public int prompt_tokens { get; set; }
    public int completion_tokens { get; set; }
    public int total_tokens { get; set; }
}
public class OpenAIChoice
{
    public string text { get; set; }
    public float probability { get; set; }
    public float[] logprobs { get; set; }
    public int[] finish_reason { get; set; }
}
public class OpenAIRequest
{
    [JsonPropertyName("model")]
    public string Model { get; set; }

    [JsonPropertyName("prompt")]
    public string Prompt { get; set; }

    [JsonPropertyName("temperature")]
    public float Temperature { get; set; }

    [JsonPropertyName("max_tokens")]
    public int MaxTokens { get; set; }
}
public class OpenAIErrorResponse
{
    [JsonPropertyName("error")]
    public OpenAIError Error { get; set; }
}
public class OpenAIError
{
    [JsonPropertyName("message")]
    public string Message { get; set; }

    [JsonPropertyName("type")]
    public string Type { get; set; }

    [JsonPropertyName("param")]
    public string Param { get; set; }

    [JsonPropertyName("code")]
    public string Code { get; set; }
}

This is the index.cshtml razor page

@page
@model OpenAI_Quickstart.Pages.IndexModel
@{
    ViewData["Title"] = "pet name generator";
}

<h1>OpenAI Quickstart - pet name generator</h1>
<hr />
<br />

<form method="post">
    <div>
        <label for="animal-input">Enter an animal:</label>
        <input id="animal-input" type="text" name="AnimalInput" value="@Model.AnimalInput" />
    </div>
    <div>
        <button type="submit">Generate names</button>
    </div>
</form>
<br/>
<br/>

@if (!string.IsNullOrEmpty(Model.Result))
{
    <div>
        <h3>Result:</h3>
        <p style="color:blue">@Model.Result</p>
    </div>
}

Output

For more info, visit the official site of Chat GPT https://platform.openai.com/

!!! Happy Coding !!!