Using AI to generate your articles
Tags: ai, javascript, tutorial
Published: 2023-02-18 18:28:26

Today I want to show you a basic tutorial on how to hook up AI to your blog platform so that you can easily generate 
posts with the click of a button just from the title alone.

Basic skillset required
- Knowledge of fetching (ajax, fetch, etc)
- ExpressJS would be useful but I list tutorials at the bottom if needed.
- An open ai account, we will help you setup the account in this tutorial

This will involve three parts, the open ai account with an api key (free for most usage), the front end portion for fetching and displaying the generated results and the backend that will hold our code with the secrets for the api endpoints.

For a proof of concept you could use just frontend, but this is a security risk as it exposes your AI api key to the public. 

Let's get you an api key first from OpenAi. Goto [OpenAi.com signup](https://openai.com/api/), and click on the sign up button. You can use an existing email account which i would suggest doing as I've personally had less issues logging in.

Once you have an account, login and then goto [Api Keys](https://platform.openai.com/account/api-keys) and create a new api key. Make sure to note it down as you cannot get it again. If you lose it, just generate a new one.

Save the token for later and we'll come back to it.

Now on the the frontend. I'm using react but any vanilla js would work. 

The frontend is very strait forward so we won't spend much time on it. I'll show you some code and screenshots. If you need more help on this portion, message me and I'll do my best to assist you.

![blog preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bs8izava9gd1uia1t17c.png)

Create a little form, with a title input, and a body textarea. Then add a button that uses similar code to below.

```react
const generateContentFromTitle = async (title: string) => {
    try {
        const confirm = window.confirm('Are you ready to generate the AI feedback? It\'ll replace everything in the textarea');

        if (!confirm) return;

        setIsLoading(true);

/**
 * swap out apiGet for fetch or your own api service. We left an example of how to use fetch below.
 *
 * async function fetchData() {
 *   try {
 *     const response = await fetch('https://example.com/ai?searchTerm=');
 *     const data = await response.json();
 *     console.log(data);
 *   } catch (error) {
 *     console.error(error);
 *   }
 * }
 *
 * fetchData();
 */
 const response = await apiGet(`/ai?searchTerm=${encodeURI(`Write a blog based off the title "${title}" in html`)}`, authToken); //authToken here is for my own security, you would probably just do a straight fetch call.

 const words = await extractPayloadFromResponse(response);

 const foundPost: PostType = {
                ...post,
                body: words,
            };

 setHasPendingChanges(true);

 setPost(foundPost);

 setIsLoading(false);
 } catch(error: any) {
            setMessage(error.message);
        }
 }

```

Pay attention to the "`Write a blog based off the title 
"${title}" in html`)" portion of the code. 

You can tweak this to get better results. For me it works fine as I actually spend a lot of time modifying the response to be mostly my own words and save the generation for ideas. 

If you can fine tune it enough, then you should be able to get post where you only have to modify the response here and there, but that's if you're going for that. 

I personally like to make sure I'm involved in my posts but that's my personal opinion, use AI the way you feel it should be used.

Onto the backend. 

To save myself time, I apologize in advance for not writing step by step down on how to build out an express server, but you can find that same tutorial on dev.to! [setup an express json api ](https://dev.to/search?q=setup%20an%20express%20json%20api%20)

This tutorial will get you started quick [Setup a Node Express API with TypeScript (2021)](https://dev.to/roycechua/setup-a-node-express-api-with-typescript-2021-11o1)

Adding expressjs routes is very easy and straight forward, but if you get stuck, leave a comment or message me. 

We will add an endpoint called "Ai", which will be reached via "get" at the endpoint "/ai".

```js
//router.js, or if you followed the tutorial above, index.ts
router.route('/ai')
    .get(expressAsyncHandler(Ai))
;
```

Next create the route function.

```js
//ai.ts (or ai.js if you're not using typescript)

export default async function Ai(req, res, next) {
    const {searchTerm} = req.query;

    try {
        const chatEntry = await getWords(searchTerm);

        return res.json(chatEntry);
    } catch (error) {
        next(errorsToString(error));
    }
}
```

After you create the route function, we will create the service that actually communicates with Open AI. 

Do the following command in your established project.
`npm i --save openai`

This will give you the package that you need to setup openai. You could use fetch but this makes it cleaner, easier and it's better supported.

If you use environment variables, which you should! You can load your open ai key via the process.env. You'll see the env var OPENAI_API_KEY below as an example.

```js
import {Configuration, OpenAIApi} from "openai";

const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY || 'sk-<Your key>',
});
const openai = new OpenAIApi(configuration);

const getWords = async (prompt: string): Promise<string> => {
    const completion = await openai.createCompletion({
        model: "text-davinci-003",
        prompt,
        temperature: 0.6,
        max_tokens: 2000
    });

    return completion.data.choices[0].text;
};

export default getWords;
```

It's important to note that you can change the settings above, but be careful what you change them to if you don't know what they do. You can read the docs to get better understanding of the settings via [OpenAI Docs](https://platform.openai.com/docs/introduction).

By default you can use the settings above and get a post about 5 to 8 paragraphs long. If you increase/decrease the max_tokens, it'll change the size of response you get back. 

You can check your balance in your Open AI account on the [Usage](https://platform.openai.com/account/usage) page. It's only penny's to operate openai which is amazing. They start you off with a pre-credit or at least at the time of writing this, they did. It's very affordable otherwise.

Now that you have your endpoint working, i would use curl or postman to check your expected response.

Forewarning! When you submit the request, it takes a long time to generate. between 15 seconds to a few minutes. Be patient and if you have issues with timing out, then google how to extend expressjs request timeouts.

Once you've confirmed your endpoint works then you can test your frontend code to make sure you're saving the post into the textarea correctly. 

By now you should have a little blog form that allows you to generate the post based off the title. 

![animation of site in action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wz2wm6c8yj0blnc7f9n3.GIF)

Please feel free to share your thoughts, opinions, suggestions and corrections. 

--DeChamp