Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

.Net Core- Integrates OpenAI ChatGPT APIs in .Net Core Web Api

ChatGPT is a natural language processing model created as an AI-powered chatbot. It is designed to help customers interface with businesses more efficiently and effectively, providing human-like responses in real-time. The model is trained to recognize the context of customer requests, understand the content of conversations, and generate answers to customer queries.

By integrating ChatGPT with our .Net Core Web Api, we can elevate our aplication’s capabilities and provide users with a more interactive experience.

Here we are going to see the step-by-step integration of OpenAI’s ChatGPT APIs into .Net Core Web API.

Signup for an OpenAI API Key

To use the OpenAI’s ChatGPT APIs in your .Net Core Web Api, the first step is to signup for API Key. Go to OpenAI website and create your account by providing your details like name, email address and password.Once you have created your account, create your API key as shown below-

Its important to keep your API key safe and secure, as it provides access to use OpenAI’s ChatGPT APIs. Once you have your API key, you are ready to move on to the next step.

Create .Net Core Web Api project

Create new .Net Core Web Api project in Visual Studio. On the start screen select “ASP.Net Core Web Api” from the list of templates and give your project name. Select the appropriate .Net version (in this case .Net 7.0) in “Additional information” page.

Once your project is created, add the OpenAI API client package to your project.

Install the OpenAI Api package

To install the OpenAI API client package in your project, use the Package Manager Console.

  1. Open Visual studio and Open your .Net Core Web Api project
  2. In the menu bar, navigate Tools > Nuget Package Manger > Package Manage Console
  3. In the Package Manager Console window, type the following command and Enter:
    Install-Package OpenAI

Create ChatGPT API client and generate the response

After installing the OpenAI API client package, you can create a ChatGPT Api client in your Web Api project.

To simplify the implementation, add a new controller file in your project called "OpenAIController" in controller folder. In this controller file create the ChatGPT api client, which you can use to make request to OpenAI API.

OpenAIController.cs
using Microsoft.AspNetCore.Mvc;
using OpenAI_API;
using OpenAI_API.Completions;

namespace DotNetChatGpt_SampleApplication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OpenAIController : ControllerBase
    {
        [HttpGet]
        [Route("ChatGpt")]
        public async TaskChatGpt(string query)
        {
            string result=string.Empty;
            var openAi = new OpenAIAPI("ApiKey"); // Pass your Api Key
            CompletionRequest completionRequest=new CompletionRequest();
            completionRequest.Prompt=query;
            completionRequest.Model = OpenAI_API.Models.Model.DavinciText;
            completionRequest.MaxTokens=1024;
            var completions = await openAi.Completions.CreateCompletionAsync(completionRequest);
            foreach(var completion in completions.Completions)
            {
                result += completion.Text;
            }
            return Ok(result);
        }
    }
}

Below is the explanation of the code in OpenAIController.cs file.

  1. Below line will create a new instance of OpenAIAPI class with the provided API key.
    var openAi = new OpenAIAPI("ApiKey");
  2. Below lines will create a new instance of CompletionRequest class and sets the prompt and model properties. The MaxTokens property specifies the maximum number of words or phrases to generate in the completion.
    CompletionRequest completionRequest=new CompletionRequest();
    completionRequest.Prompt=query;
    completionRequest.Model = OpenAI_API.Models.Model.DavinciText;
    completionRequest.MaxTokens=1024;
    
  3. Below line sends the completion request to the OpenAI API and awaits to response.
    var completions = await openAi.Completions.CreateCompletionAsync(completionRequest);
  4. Below for loop extracts the generated response from the Completion object and concatenate them to result variable. Finally returns the generated text and HTTP 200 OK response.
    foreach(var completion in completions.Completions)
    {
      result += completion.Text;
    }
    return Ok(result);
    

After completing the above steps, final step uis to run the project and test the API using swagger. You can find the complete code from GitHub.

Demo



This post first appeared on Dot Net World, please read the originial post: here

Share the post

.Net Core- Integrates OpenAI ChatGPT APIs in .Net Core Web Api

×

Subscribe to Dot Net World

Get updates delivered right to your inbox!

Thank you for your subscription

×