Develop an AI Writer with Open AI in 4 steps (Free C# Source Code)

AI Writer with Open AI and c#

Table of Contents

Spread the love

Today, let's make an AI Writer with Open AI. You can do this in any language such as python. But I'll do it in C# and (.NET).

I will also be providing you Free Source Code.

You can even modify this Project. Work on it, in a bit more detail, and you can easily turn this into a Good AI Content Generator. Which people are paying to use these days.

AI Writer with Open AI
AI Writer with Open AI

????If you want to make your own AI Content Writer, or answer Writer. Read this Post till the end.????

You won't Regret it.

Also, this can be Helpful in making AI Assistants or Chat bots, for fun. Like Jarvis or Siri Clones.

As this AI can answer any Question. Surprising isn't it?????

The scope and possibilities of this Projects are vast. So pay attention. And Let's get into the Project.

I Decided To Ask The AI, What will happen in 2030? So I created a small .Net Project with C# and Connected it with OpenAI GPT-3 Model to ask any questions!

Before I show you the Code, Let's discuss some important terms which will help you Understand and Implement this Project Successfully.

I also recommend watching this Full Video, to get a better gist of the Project about AI Writer with Open AI.

AI Writer with Open AI

What is Open AI?

OpenAI is an AI research and deployment company. They recently gave access to their API so any developer can benefit from their powerful AI models in real-life projects.

Our (OpenAI)'s mission is to ensure that artificial general intelligence benefits all of humanity.

(source: https://openai.com/about/)

What is GPT-3?

GPT-3 is a machine learning platform that enables developers to train and deploy AI models. It is also said to be scalable and easy to use.

It was developed by OpenAI, a leading research lab focused on developing advanced machine learning algorithms.

In addition to its ability to generate new sentences, GPT-3 can also perform other natural language tasks such as question answering and information retrieval.

What can I do with OpenAI?

You can develop, your Own AI Assistant like Siri and Jarvis. Or you can develop Chatbots, or AI Content Generators. In a nutshell, Open AI gives Answers to your Questions.

Can I use OpenAI for free?

Yes, Absolutely! Open AI recently gave access to their API so any developer can benefit from their powerful AI models in their projects.

How to Build an AI Writer or Make an AI Content Generator?

You can Develop an AI Writer with Open AI. Use, Open AI, connect it with GPT-3 and use a Programming language of your own choice. I'm using C# for this Tutorial.

Why C# and not Python?

If you worked before with Open AI API, you might have noticed that it is super easy to get the code in Python and use it in your scripts. So I wanted to add a small benefit and show how you can integrate Open AI with .NET apps, as I didn't find clear and straightforward tutorials about this topic while doing my research.

Now let's see the Code and the Process you have to follow, in order to get this Done.

I've tried to cover this step-by-step. But you can also refer to the video, from time to time.

AI Writer with Open AI

First of all Open Visual Studio. If you don't have it downloaded.

Here is a Complete Guide for Visual Studio Installation and Setup. Check it out!

In Visual Studio, as soon as you open it. Simply click on create new project and pick console application. Click next and name it.

Save it to your preferred location that is easily accessible click on create project, and select .NET 5.0

Below is what will happen in the main method, or the basic working of the application.

Code in the Main Method

First we have to record the Question that the user will ask the AI. For that, print on the screen.

//to ask the user to enter their question
console.writeline("Ask your Question.")
//

Now we need to read the users question. To pass it on to the AI. So we will save the user's answer into the variable ‘question'.

//
var question = Console.ReadLine();
//

Now we have to call Open AI and pass it our Question.

 //call the open ai
            var answer = callOpenAI(250, question, "text-davinci-002", 0.7, 1, 0, 0);
            Console.WriteLine(answer);
//

Now above, we use, a method called ‘CallOpenAi.'

Below is given how it functions.

Coding for “Call Open AI Method for AI Writer with Open AI

Head over to Open AI.

AI Writer with Open AI
AI Writer with Open AI

Now you can use this powerful open api and access the gpt 3 models.

These are Simple AI models that are based on neural networks.

In other words you can talk to these models and they understand human language.

Moreover, they can generate text in different languages. (Sometimes better than humans ????)

So, the second step now is to sign up for OPEN-AI. It's totally free.

I will log into my account.

AI Writer with Open AI
AI Writer with Open AI

When you log in you will see a lot of examples on how to use this model.

AI Writer with Open AI
AI Writer with Open AI

But Anyways. What we need now is the playground where we can play with this AI model. 

AI Writer with Open AI
AI Writer with Open AI

For example: Let's ask the AI here.

What is OPEN-AI?

And hit submit.

As you can see below, we got a perfectly crafted answer, with the power of AI. ???? 

AI Writer with Open AI
AI Writer with Open AI

As you can see here, that you can ask any question inside this window.

But in our case we want to integrate this API inside our C# (.NET) application.

And we'll discuss that in a bit.

But if you want the code in another language, You can do this.???? 

AI Writer with Open AI
AI Writer with Open AI

And you will see , that we have python, node, and couple of other programming languages. so look into it, if you want the code.

Simply copy this code and paste.

And you can run it in your own python script.

AI Writer with Open AI
AI Writer with Open AI

But we don't have something for (.NET) ????

????This is why I'm trying here to help you integrate open AI with a C# (.NET) application.

And have created a small method. The functionality is pretty basic. I assume that you have at least a basic understanding of C#, and programming in general.

This is the method that does the real job. And I have generalized it so you can ask Questions from AI, in any future C# application.????

//
private static string callOpenAI(int tokens, string input, string engine,
          double temperature, int topP, int frequencyPenalty, int presencePenalty)
        {

            var openAiKey = "API_KEY";

            var apiCall = "https://api.openai.com/v1/engines/" + engine + "/completions";

            try
            {

                using (var httpClient = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(new HttpMethod("POST"), apiCall))
                    {
                        request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + openAiKey);
                        request.Content = new StringContent("{\n  \"prompt\": \"" + input + "\",\n  \"temperature\": " +
                                                            temperature.ToString(CultureInfo.InvariantCulture) + ",\n  \"max_tokens\": " + tokens + ",\n  \"top_p\": " + topP +
                                                            ",\n  \"frequency_penalty\": " + frequencyPenalty + ",\n  \"presence_penalty\": " + presencePenalty + "\n}");

                        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                        var response = httpClient.SendAsync(request).Result;
                        var json = response.Content.ReadAsStringAsync().Result;

                        dynamic dynObj = JsonConvert.DeserializeObject(json);

                        if (dynObj != null)
                        {
                            return dynObj.choices[0].text.ToString();
                        }


                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }

            return null;


        }

//

As you may have noticed when we call this function in the main method, which we discussed above. We passed some parameters. Those are passed accordingly.

The First one is for the word count. The second for Question. You don't need to worry about the other parameters, as much.

Adding API Key for method of AI Writer with Open AI

As you can see here you need to add your api key.

So, how to get this?

Simply go back use your account view api keys.

Okay and you will see your Api key. Just copy it like this and paste instead of that text before. 

I tried to generalize the method so you can pass all the parameters directly.

Let's call the API through this method.

 //call the open ai
            var answer = callOpenAI(250, question, "text-davinci-002", 0.7, 1, 0, 0);
            
//

For more information about above parameters. 

Let's go and see this playground.

You can see all these parameters the engine, temperature, maximum length, etc.

We can hover over it and read what each means.

AI Writer with Open AI
AI Writer with Open AI

So when we pass the parameters.

Tokens define how many characters or words you want the AI to write.

The Input string which is the question (the user question).

The Engine which is text-da-vinci-002.

Temperature  0.7

top p =1

penalty=0

Percent penalty =0 

To write the answer.

 //call the open ai
            
            Console.WriteLine(answer);
//

????And Congratulations the Application is Ready!????

To sum up. We ask the user for a question we call the api we get the answer and write it back on the console.

The console is the black window that you'll see right now. 

AI Writer with Open AI (Output)

Let's run and Let's ask a question, “What will happen in 2030?” Press enter.

Let's see.

In the world will be a very different place we will have flying cars robots will be doing our household chores and everyone will be wearing virtual reality glasses…

WOW 🙂

You can play with this token number to increase the answer length.

AI Writer with Open AI ( Free Source Code)

Download The Project Source Code

Download Full Source Code

Check On GitHub

Conclusion for AI Writer with Open AI

This Project was intended to make you capable for building your own AI Writer with Open AI. I hope you learned something, and will implement it practically as well.

If you have any queries or Problems. Feel free to post them in the comments below!

We'll be glad to help.

Also Check out our other Tutorials. You won't regret it!

Take Care!


Spread the love