Yes, another article about AI. Except this one is really interesting, I promise. In this article, I’ll teach you how to use AI to generate content in Strapi. Strapi right now does not natively allow you to leverage AI for content creation, so we’re going to use Custom Fields. As a matter of fact, we’ll build one from scratch ourselves. A secondary goal of this article is to explain how you can create their Strapi custom field.
Strapi comes equipped with several fields. From a content creator perspective, these fields describe the type of content you will be inputting. They range from rich text to JSON and so many more in between. You can read more about fields in our user documentation.
Custom fields, as the name suggests, let us define fields outside of the default fields Strapi comes with, giving us a cool way to integrate with a wide range of third-party tools. That tool for us today will be Open AI.
Imagine typing text into a text field. When published, we’d have the input text displayed wherever we want to send our content. Similarly, with an AI field, we’d offload most of the writing so that the AI does the heavy lifting, and we proofread it because... Computers are dumb.
At this point, we have a pretty solid idea of what we’ll build. The finished project details are here if you’d like to reference them as we go along this tutorial.
Let’s start by creating a brand new Strapi project in our terminal with the following command:
Npx create-strapi-app@latest plugin-dev —quickstart
Once our project is up and running, create an admin user and log into your admin panel. Next, we need to create a plugin as custom fields work alongside Strapi's Plugin API.
In your terminal, navigate to your project route and enter the following command
npm run strapi generate
Select “plugin” from the list of options and name it ai-text-generation
. After naming the plugin, we need to enable it by adding it to the Strapi plugin config file in ./config/plugins.js
.
If this file doesn’t exist already, you can create it.
1 module.exports = {
2 // ...
3 'ai-text-generation': {
4 enabled: true,
5 resolve: './src/plugins/ai-text-generation'
6
7
8 },
9//...
10
11 }
When we restart the server, we should see our plugin in the Strapi admin panel. We’ll restart the server in watch-mode
so that we don’t have to rebuild our admin app every time we make changes to the admin code. To do that, enter the following command in your terminal:
Npm run develop –watch-admin
Before we can try out our custom field, we have to do a couple of things. First, we need to register it on our server. Go to ./src/plugins/ai-text-generation/server/register.js
and paste the following code.
1'use strict';
2
3module.exports = ({ strapi }) => {
4 strapi.customFields.register({
5 name: 'text-ai',
6 plugin: 'ai-text-generation',
7 type: 'string',
8 });
9};
Second, we need to register our custom field in the admin panel. To do that, go to ./src/plugins/ai-text-generation/admin/src/index.js
and paste the following code:
1import { prefixPluginTranslations } from '@strapi/helper-plugin';
2import pluginPkg from '../../package.json';
3import pluginId from './pluginId';
4import PluginIcon from './components/PluginIcon';
5
6
7const name = pluginPkg.strapi.name;
8
9export default {
10 register(app) {
11
12 app.customFields.register({
13 name: "text-ai",
14 pluginId: "ai-text-generation",
15 type: "string",
16 intlLabel: {
17 id: "ai-text-generation.text-ai.label",
18 defaultMessage: "Text AI",
19 },
20 intlDescription: {
21 id: "ai-text-generation.text-ai.description",
22 defaultMessage: "Let AI do your writing!",
23 },
24 icon: PluginIcon,
25 components: {
26 Input: async () => import(/* webpackChunkName: "input-component" */ "./components/Input"),
27 },
28 options: {
29 },
30 });
31 },
32
33
34
35 bootstrap(app) {},
36 async registerTrads({ locales }) {
37 const importedTrads = await Promise.all(
38 locales.map((locale) => {
39 return import(
40 /* webpackChunkName: "translation-[request]" */ `./translations/${locale}.json`
41 )
42 .then(({ default: data }) => {
43 return {
44 data: prefixPluginTranslations(data, pluginId),
45 locale,
46 };
47 })
48 .catch(() => {
49 return {
50 data: {},
51 locale,
52 };
53 });
54 })
55 );
56
57 return Promise.resolve(importedTrads);
58 },
59};
Don’t worry if your custom field breaks after. When registering our custom field, we do three essential things for a custom field:
type: "string"
- which tells us what type of data our custom field will hold. Depending on what you’re building, you might want to change this. For our use case today, we’ll use type: "string"
.Input
component in ./components/Input
. All custom fields require an Input component that admin users can access in the content manager. We’re at liberty to design the input component as we wish using the Strapi Design System with the constraint of having to return a single value that we store in the database. We’ll see more of this as we create an input component in the next section.icon: PluginIcon
, this helps us identify the custom field in the Content Types Builder. As mentioned above, all custom fields need an Input Component. In ./src/plugins/ai-text-generation/admin/src/components/
, create a folder called Input
. In your Input folder, create a file called index.js
and paste the code below in it:
1import React, { useState } from 'react';
2import { useIntl } from 'react-intl';
3import { TextInput } from '@strapi/design-system/TextInput';
4import { Stack } from '@strapi/design-system/Stack';
5import { Button } from '@strapi/design-system/Button';
6import { Textarea } from '@strapi/design-system';
7import { auth } from '@strapi/helper-plugin'
8
9
10export default function Index({
11 name,
12 error,
13 description,
14 onChange,
15 value,
16 intlLabel,
17 attribute,
18}) {
19 const { formatMessage } = useIntl();
20 const [prompt, setPrompt] = useState('');
21 const [err, setErr] = useState('');
22
23 const generateText = async () => {
24 try {
25 const response = await fetch(`/ai-text-generation/generate-text`, {
26 method: 'POST',
27 headers: {
28 'Content-Type': 'application/json',
29 'Authorization': `Bearer ${auth.getToken()}`
30 },
31 body: JSON.stringify({
32 'model': 'text-davinci-001',
33 'prompt': `${prompt}`,
34 'temperature': 0.4,
35 'max_tokens': 64,
36 'top_p': 1,
37 'frequency_penalty': 0,
38 'presence_penalty': 0
39 })
40 });
41
42 if (!response.ok) {
43 throw new Error(`Error! status: ${response.status}`);
44 }
45
46 const result = await response.json();
47 const parsedResult = result.choices[0].text.replace(/(?:\r\n|\r|\n)/g, '');
48
49 onChange({ target: { name, value: parsedResult, type: attribute.type } })
50 } catch (err) {
51 setErr(err.message);
52 }
53 }
54
55 const clearGeneratedText = async () => {
56 onChange({ target: { name, value: '', type: attribute.type } })
57
58 }
59
60 return (
61 <Stack spacing={1}>
62 <TextInput
63 placeholder="Please write a prompt for content to generate"
64 label="Prompt"
65 name="Prompt"
66 onChange={(e) => setPrompt(e.target.value)}
67 value={prompt}
68 />
69 <Stack padding={4} spacing={2}>
70 <Textarea
71 placeholder="Generated text"
72 label="Content"
73 name="content"
74 onChange={(e) =>
75 onChange({
76 target: { name, value: e.target.value, type: attribute.type },
77 })
78 }
79 >
80 {value}
81 </Textarea>
82 <Stack horizontal spacing={4}>
83 <Button onClick={() => generateText()}>Generate</Button>
84 <Button onClick={() => clearGeneratedText()}>Clear</Button>
85 </Stack>
86 </Stack>
87 </Stack>
88 )
89}
A couple of things happen here. We’ll look at what the main elements do to understand it better.
<TextInput />
: acts as our input for prompts; we use onChange()
‘watcher’ to update the value of our prompt state as we type data. We then store the prompt in a variable called prompt
. TextArea />
: is what we use to store the value of our generated text. We use a <TextArea />
to edit the generated text. We use a special implementation of our onChange()
watcher, which allows us to pass an object of multiple values to update when a change occurs in that component.
We also have two buttons where all the magic happens. One button calls generateText()
- this function uses fetch
to call our backend service, /ai-text-generation/generate-text
that makes authenticated calls to the Open AI API (we’ll create this next). To authenticate this, we use auth
from @strapi/helper-plugin
which helps us make a secure request to the Strapi service we’ll create using the Admins token.
We then parse our result and use the special implementation of onChange()
to pass the parsed response as the content that will get added to our database with onChange({ target: { name, value: parsedResult, type: attribute.type } })
.
The other button calls clearGeneratedText()
- this function clears all the text the AI generated in case we want to start over. At this point, our application should look something like this.
To access Open AI, we need to provide an API KEY; having this key in the admin poses a security risk, and to combat that, we’ll create a custom route that, when called, makes an API call to Open AIs API and returns the generated text that we can then send to the admin.
So start, in our ./config/plugins.js
file add a config object below enabled: true
, your config file after should look like this:
1// …
2'ai-text-generation': {
3 enabled: true,
4 config: {
5 apiToken: process.env.OPEN_AI_API_TOKEN,
6 },
7 resolve: './src/plugins/ai-text-generation'
8 },
Now, create a file called open-ai.js
in ./src/plugins/ai-text-generation/server/services
and paste the following code in it.
For the code to work, you will also have to install axios, for that navigate to your plugin root and type yarn add axios
1'use strict';
2
3const axios = require('axios');
4
5module.exports = ({ strapi }) => ({
6
7 async generateText(prompt) {
8 try {
9 const response = await axios(
10 {
11 url: 'https://api.openai.com/v1/completions',
12 method: 'POST',
13 headers: {
14 'Content-Type': 'application/json',
15 'Authorization': `Bearer ${strapi.plugin('ai-text-generation').config('apiToken')}`
16 },
17 data: JSON.stringify({
18 'model': 'text-davinci-001',
19 'prompt': `${prompt}`,
20 'temperature': 0.4,
21 'max_tokens': 64,
22 'top_p': 1,
23 'frequency_penalty': 0,
24 'presence_penalty': 0
25 })
26 })
27
28 return response.data;
29 }
30 catch (err) {
31 console.log(err.response)
32 }
33
34 }
35
36});
Here we define a function generateText()
that takes a prompt as an argument. We then use prompt as a parameter in our request to Open AI.
Next up, in the same services folder, paste the following code in your index.js
file.
1'use strict';
2
3const openAi = require('./open-ai');
4
5module.exports = {
6 openAi,
7};
This code registers a service in Strapi that we call from a controller, before we do that. We need to create a controller. In ./src/plugins/ai-text-generation/server/controllers
, create a file called ai-controller.js
and paste the following code in it:
1'use strict';
2
3module.exports = ({ strapi }) => ({
4 async generate(ctx) {
5 ctx.body = await strapi
6 .plugin('ai-text-generation')
7 .service('openAi')
8 .generateText(ctx.request.body.prompt);
9 },
10});
In this file, we call the generateText()
function that we defined in the service we just made and pass ctx.request.body.prompt
(from our POST request).
In the same folder, we need to paste the following code in our index.js
file:
1'use strict';
2
3const aiController = require('./ai-controller');
4
5module.exports = {
6 aiController,
7};
Lastly, we must create a route to access the controller we just created. In ./src/plugins/ai-text-generation/server/routes
we need to paste the following code:
1module.exports = [
2 {
3 method: 'POST',
4 path: '/generate-text',
5 handler: 'aiController.generate',
6 config: {
7 policies: [],
8 },
9 },
10];
In this file, we define how our endpoint should behave. With this code, we create a POST
method on the /generate-text
URI and pass the aiController
controller we created to define its behavior.
In your preferred API client, you can now make a request to localhost:1337/ai-text-generation/generate-text
and you should get AI-generated text as a response. Be sure to add your prompt as a parameter and pass your admin JWT for authentication.
We should also get a response when we enter a prompt and click “generate” in our Custom Field.
If you'd like to share your custom field with the community, you can publish it to npm and submit it to the Strapi marketplace.
Maxime from the Strapi team wrote an amazing article on how to publish your plugin to npm. Be sure to:
package.json
with the correct metadata.You can take your custom field to the next level by submitting it to the official Strapi marketplace. This allows others to discover and use your plugin, contributing to the community.
By following this tutorial, you've learned how to build a custom field in Strapi that integrates OpenAI's API for AI-powered text generation. This powerful combination allows you to enhance your content creation process, boost productivity, and streamline your workflows. Custom fields and plugins in Strapi provide a flexible way to extend the CMS to meet your specific needs.
Feel free to customize and expand upon this foundation to build even more advanced features. Happy coding!
Developer Relations @ Weaviate | Developer Education and Experience | Builder and International Speaker