DALL E AI using NET Core MVC with Open AI API
Guru Prakash May 11, 2023
DALL-E is an artificial intelligence system that converts natural language or text descriptions into realistic images and art. DALL-E is incredible. Following its release, I noticed numerous discussions on the internet. From developers to artists to art enthusiasts, everyone agrees that this technology has advanced to the next level.
I went to the website to look for the documentation. I found API documentation for Node.js, Python, and curl but was unable to locate libraries for.NET, so I decided to share with you how I used the DALL-E API in my .NetCore project.
You do not need to create your project in .Netcore for this demo. I used a pure .NET library, so you can use either .NET Standard or .NetCore. Let's get started on our project :)
DALL-E AI using .NET Core MVC Implementation
In this demonstration, I used Visual Studio 2022 to create this project. The application is an ASP.Net Core Web App (MVC).
I'm gonna name it as "DalleAIDemo
"
The framework is .NET6.0, then the rest as it is. Then click on "Create." button
Generate Open API Key
Before we can use the DALL-E API. First, we must obtain an API key, which must be included in our header so that the API knows who is sending the request.
To obtain an API Key, we must first create an OpenAI account. You can register here.
Following the successful creation of an account. Log in to your account, click on your profile icon, select View API keys from the dropdown menu, and then press the "+ Create new secret key" button.
Copy and save your API Key somewhere temporary, such as Notepad. We'll put it to good use later.
The DALL-E API does not generate images for free, but the cost is very reasonable. Please see the documentation's pricing section.
Now it's time to code.
.NET Core MVC appsettings.json
Add a "OpenAIKey" item and set its value to the API KEY you saved earlier. See an example
{ ... "OpenAIKey": "YOUR API KEY" }
DALL-E AI Request and Response Models
Expand the Models folder in the Solution Explorer, create a new item ResponseModel.cs
, and create three model classes inside "input" to serve as our input model, "Link" to be used in ResponseModel, and the ResponseModel to map the DALL-E API response.
namespace DalleAIDemo.Models { // serves as our input model public class input { //properties } // model for the image url public class Link { //proprties } public class ResponseModel { //properties } }
DALL-E AI MVC Controllers
In the Solution Explorer, expand the Controllers folder and look for HomeController.cs
.
Make a string variable called "_key " and set its value to string.Empty. Inject the IConfiguration interface into the constructor so we can access elements in appsettings.json, then set the value of "_key ".
//HomeControler.cs string _key = string.Empty; public HomeController(IConfiguration _config) { _key = _config.GetSection("OpenAIKey").Value; }
Let's now create an HTTP POST action called GenerateImages
that takes the input model as a parameter from the request body.
Let's make a ResponseModel
class instance and call it resp in the GenerateImages method. Then we'll make a new HttpClient
instance. We'll then clear the default headers because we don't want any extra headers in the request. Then we'll add an Authorization header
, and from there we'll use the _key
.
Then we'll call the _client.PostAsync
Using JsonConvert, call the PostAsync method with the apipath and the serialised input model. As the body, use SerializeObject
and set the contentType
to "application/json."
If the response code is successful, we will read the content and set the value of resp from the deserialized value of the content using the Newtonsoft.json's JsonConvert.DeserializeObject class.
The complete HomeController
should look like this: [Ref: HomeController.cs]
DALL-E AI View
In the Index.cshtml
view page add the following code
@{ ViewData["Title"] = "Home Page"; }DALLE AI: .NET Demo
Your Query:
Loading...
Additional: DALL-E AI Demo using .NET Core MVC with AJAX
On your Solution Explorer, expand the wwwroot
folder, the js folder then open site.js
.
From here, we'll construct a button click event listener and an input object to serve as our request body. Then, with the input object as a parameter, we'll send a post request to HomeController -> GenerateImages
.
$(document).ready(() => { $(".loader").hide(); $('#btnGen').click(function () { var input = {}; input.n = parseInt($('#quantityTxtBx').val()); input.prompt = $('#queryTxtBx').val(); input.size = $('#sizeCmbBx').find(":selected").val(); $.ajax({ url: '/Home/GenerateImages', method: 'post', contentType: 'application/json', data: JSON.stringify(input), beforeSend: function () { $(".loader").show(); }, complete: function () { $(".loader").hide(); }, success: function (data) { if (typeof data.data !== undefined && data.data !== null && data.data != "") { $.each(data.data, function () { $('#genImages').append( '' + ' ' + ''); }); } else { alert("[\"" + input.prompt + "\"]=>" + data.statusMessage); } }, error: function (err) { console.log(err); } }); }); });
If the request is successful, we will receive a response in JSON format and then loop through the data objects containing the URLs of the images. Following that, we'll create a div with an img element, set its source to the DALL-E API response URL, and append it to the display div.
DALL-E AI Demo using .NET Core MVC Output
Run the app, enter your text, select the number of images you want to generate, and then click the Generate button. Here's your DALL-E API Text-to-Image generator in .NET.
You can also clone the whole solution from my repository: https://github.com/guruprakash-c/DalleAIDemo