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, 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 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.
Create a little form, with a title input, and a body textarea. Then add a button that uses similar code to below.
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
)" portion of the code.
"${title}" in html
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
This tutorial will get you started quick Setup a Node Express API with TypeScript (2021)
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".
//router.js, or if you followed the tutorial above, index.ts
router.route('/ai')
.get(expressAsyncHandler(Ai))
;
Next create the route function.
//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.
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.
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 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.
Please feel free to share your thoughts, opinions, suggestions and corrections.
--DeChamp
Top comments (4)
It's useful as an example of how to use the openai API but please don't actually do this!
Ok, what is your view on why not to do this? I'd love to hear your opinion on it.
This technology is going to be built/already being built into a lot of things, like how Microsoft threw money at it and put it in Bing.
If people want to know about something, they'll type it in there and see an immediately-generated result. There's literally no benefit to doing this yourself and making a blog of it. Nobody will subscribe to something they can get directly themselves.
More importantly, the results coming out of ChatGPT are unreliable. If it is anything you know about, you'll need to pour over it looking for mistakes. If it's something you don't know much about, you'll end up promoting disinformation and people will lose faith in you and abandon the blog.
I'm not saying don't use tools like this to help you write blog posts, but I am saying don't unleash potentially misleading information on the world and pretend it's real.
I hear parts of what you're saying. I feel like you might need to read the article again. I mentioned in the article that I personally use it as a guide or idea generator and rewrite most of what is generated, also to add this is only for my site, not dev.to or other sites where personal thought is important.
A lot of people build and use AI tools daily, I do not find it convenient to leave my blog and go to AI. It's much more convenient to type a title, push a button and be on my way. If you don't like it, try saying you don't like the idea instead of telling me it's a bad idea because everyone is doing it. Everyone is building websites too, so maybe we shouldn't build websites? See what I mean?
I gather that it's more of the unleashing the generic AI response to the public is what seems to bother you. I would agree but then you could argue endlessly on this forever. I saw it with digital art, photoshop came around and people felt it wasn't fair because it generated your art for you, but go up to a person who's spent their career using it and tell them they're not a real artist and I'm sure they'll argue you.
AI is here, it's going to stick around. I choose to get comfortable with it. I choose too use it before it replaces me. :)