How to integrate OpenAI API (Text, Codex, DALL-e, ChatGPT coming soon) in your .NET Core app in 15 minutes

OpenAI API overview (from Open AI)

The OpenAI API can be applied to virtually any task that involves understanding or generating natural language or code. We offer a spectrum of models with different levels of power suitable for different tasks, as well as the ability to fine-tune your own custom models. These models can be used for everything from content generation to semantic search and classification.

To makes it a little more understandable, so with OpenAI API you can : generate and edit text, generate/edit/explain code, generate and edit images, train a model, search, classify and comapre text. Checkt the documentation here.

We will use DaVinci GPT-3 model in our app, but you can try other models :

LATEST MODELDESCRIPTIONMAX REQUESTTRAINING DATA
text-davinci-003Most capable GPT-3 model. Can do any task the other models can do, often with higher quality, longer output and better instruction-following. Also supports inserting completions within text.4,000 tokensUp to Jun 2021
text-curie-001Very capable, but faster and lower cost than Davinci.2,048 tokensUp to Oct 2019
text-babbage-001Capable of straightforward tasks, very fast, and lower cost.2,048 tokensUp to Oct 2019
text-ada-001Capable of very simple tasks, usually the fastest model in the GPT-3 series, and lowest cost.2,048 tokensUp to Oct 2019

Important : today (02/17/2023), ChatGPT API is not yet available but OpenAI indicates that it will come soon.

Phase 1 : get your secret API key

  1. Go to the OpenAI website and create a new account
  2. Signup for an OpenAI account
  3. Confirm your email address
  4. Log in to your account and navigate to the ‘View API keys’ dashboard
  5. Click on ‘Create a new secret key’

Store your API key in a secure location. You can test the API right now, but if you intend to use OpenAI API in a real workld case scanerio, check OpenAI documentation for details on usage and pricing.

 Phase 2 : create you .NET Core project to consume OpenAI API

  1. Open Visual Studio 2022
  2. Create a new .NET Core project (in my case a Web API)
  3. Install the ‘OpenAI‘ NuGet package as below :

4. In your program.cs file, just copy the following code (replace the apiKey with yours, generated in phase 1)

using OpenAI_API;
using OpenAI_API.Completions;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseHttpsRedirection();

app.MapGet("/givemesecretoftheuniverse", (string prompt) =>
{
    var apiKey = "sk-5ucaz1m00000000000000000000000000000000";
    var answer = string.Empty;

    var openAIAPI = new OpenAIAPI(apiKey);

    var completionRequest = new CompletionRequest
    {
        Prompt = prompt,
        Model = OpenAI_API.Models.Model.DavinciText,
        MaxTokens = 2000
    };

    try
    {
        var result = openAIAPI.Completions.CreateCompletionAsync(completionRequest);

        if (result != null)
        {
            foreach (var item in result.Result.Completions)
            {
                answer += item.Text;
            }
            return Results.Text("Answer of the universe : " + answer);
        }
        else
        {
            return Results.BadRequest("Not found");
        }
    }
    catch (Exception)
    {
        return Results.Problem("OpenAI API is not available or key are incorrect");
    }
});

app.Run();

5. Run your application, and open your Postman app or your favorite web browser to open the following URL : https://<your computer ip / localhost>:<your project port>/givemesecretoftheuniverse?prompt=what is the secret of the universe

6. The flow of the power of OpenAI will flow throught your screen 😁🚀🌚

More possibilities 🚀😁

As said earlier, you can use Codex, Dall-E, etc from OpenAI just by changing the Model = OpenAI_API.Models.Model statement and adapt your code consequently. Today, ChatGPT API is not yet available but OpenAI indicates that it will come soon.

You can also try this .NET library which is pretty cool as well : https://github.com/betalgo/openai

Conclusion

Integrating OpenAI APIs into your application is just as easy as creating a minimal API with .NET Core, so test it, learn it, and make our world a better one. With ChatGPT coming soon, accessible AI is becoming a reality.

[20th anniversary of .NET] Best of C# : null operators

In this series, I’d like to share with you my best experiences with .NET / C# and the best evolutions the .NET team brings us over the time.

Today I’d like to talk about null operators 🙂 C# provides 3 operatrs to make it easier to with with nulls :

  1. Null conditional operator
  2. Null coalescing operator
  3. Null coalescing assignment (new in C# 8)

You can find more details about these operators in this great book => Amazon.fr – C# 10 in a Nutshell: The Definitive Reference – Albahari, Joseph – Livres

Null-conditional operator

The ?. operator is also called the Elvis operator and as originally introduced in C# 6. It allows you to call methods and access members like the . operator except that if the left operand is null, the expression is evaluate to null without throwing the killer exception ‘NullReferenceException‘.

string s = null;
string sUpper = sb?.ToUpper(); // sUpper is null

The only condition is that the final expression/assignment is capable of accepting a null (exit all value type) :

string s = null;
int lengthS = s?.Length; // Won't compile

Then use a Nullable :

string s = null;
int? lengthS = s?.Length; // Ok

Null-coalescing operator

The very useful ?? operator tells to return the value of the left operand if it’s not null, else return the specify value (right operand – example : default value)

string s = null;
string sDefault = s ?? "My default value"; // sDefault is "My default value"

Another good use of this operator is to check an assignment and rise an exception if null (example in ASP.NET controller or anywhere else) :

_companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository));

Null-coalescing assignment (C# 8)

The ??= operator assigns a variable only if it’s not null. So it’s a sugar syntax to replace this :

if (s != null) s = "Hello world";

with this :

s ??= "Hello world";

MVP ComCamp 2015 : les ressources

flyer_comcamp2015

L’évènement étant fini, je vous communique les liens vers les présentations de ces deux sessions :

Sitôt fini qu’on me demande déjà de rejouer cette présentation et d’y apporter quelques ajouts (et allégements … je sais je suis bavard !). A suivre donc …

P1010332 (Large)