How to integrate ChatGPT with CKEditor 5

Are you on the lookout for ways to streamline your workflow with the help of AI? Responding to growing demand from your customers for smarter, AI-driven tools? Whatever the case, the traditional method of juggling between multiple tabs or windows to access AI functionalities is cumbersome and counterproductive. A more intelligent and practical approach lies in integrating AI capabilities directly into the tools you already use – specifically, your WYSIWYG editor.

Imagine having the power of leading AI language models like ChatGPT at your fingertips, seamlessly integrated into the editor interface. This not only ensures efficiency but also greatly enhances user experience by making AI readily accessible within the familiar confines of your editing environment.

This is precisely the functionality AI Assistant for CKEditor 5 brings to the table. The plugin goes beyond merely incorporating ChatGPT into your editor by providing ready-to-use optimized prompts. With this, you can select your existing text and even ask the AI Assistant to change the tone and style, fix grammatical errors, and summarize.

This integration of AI into the editor eliminates the need to constantly switch contexts and interfaces, thereby optimizing your content creation workflow with real-time suggestions, content generation, and data processing.

Want to know how to integrate ChatGPT with CKEditor 5? We’ll cover everything you need to get started:

  • Set up the AI Assistant (Premium) plugin

  • Test out the plugin in development

  • Configure a demo implementation that provides security following OpenAI best practices

But before we get to how to integrate ChatGPT, let’s look at some basic definitions.

# Understanding AI and ChatGPT

# What is AI and Generative AI?

Artificial intelligence (AI) refers to the simulation of human intelligence in machines programmed to think and learn like humans. AI systems can perform tasks that typically require human intelligence, such as visual perception, speech recognition, decision-making, and language translation.

Generative AI is a subset of AI focused on creating new content. It goes beyond analyzing and processing data to actually generating new data that didn’t exist before. This can include text, images, music, and other forms of media. Generative AI systems use complex algorithms to produce content that is often indistinguishable from content created by humans.

# What is OpenAI and ChatGPT?

OpenAI is an AI research and deployment company known for developing advanced AI models. It aims to ensure that artificial general intelligence (AGI) benefits all of humanity. OpenAI has been at the forefront of advancing AI technologies and making them widely accessible.

ChatGPT is one of OpenAI’s innovations, a variant of the GPT (Generative Pretrained Transformer) models. It is specifically fine-tuned for understanding and generating human-like text based on the input it receives. ChatGPT can engage in conversations, answer questions, and create content that ranges from writing essays to composing emails and more. OpenAI provides an API to interact with and harness the GPT models that power ChatGPT. Through the use of this API, other software can introduce a ChatGPT-like experience.

# How to integrate ChatGPT with CKEditor 5: Prerequisites

Integrating AI capabilities into CKEditor 5 involves a few crucial steps, including obtaining the necessary API keys and setting up a suitable environment for your endpoint. Here’s a guide to help you through the process:

# Obtaining an OpenAI API key

To use the AI Assistant plugin with CKEditor, you first need to get an API key from OpenAI. Remember, using the OpenAI API comes with associated costs, which are separate from the AI Assistant plugin fee. Here’s how to sign up:

  1. Visit OpenAI
    Go to the OpenAI website and navigate to the API section.

  2. Registration
    If you’re not already registered, sign up for an account.

  3. API Key Generation
    Once registered, follow the instructions to generate an API key.

# Acquiring a CKEditor 5 license key

AI Assistant is a Premium plugin for CKEditor 5, requiring a Commercial License to use. If you don’t already have a Commercial License, you have two options for getting one:

  1. Purchase a license
    Contact us to get a Commercial License that’s tailored to your needs. This license is necessary to purchase and use any Premium plugins.

  2. Free trial
    If you’re interested in trying out the plugin before purchasing, CKEditor offers a 30-day free trial of the Commercial License and all Premium plugins. You can sign up for this trial here. Note that the free trial does not cover any OpenAI API usage fees you incur.

Once you have an active Commercial License, you’ll receive a license key for CKEditor.

# Set up AI Assistant in your local environment

Before diving into the integration of AI Assistant, it’s essential to ensure that you have all the necessary prerequisites in place. Along with your OpenAI API key and your CKEditor Commercial License, these are the tools you need to get started:

  • Code editor: A reliable code editor like Visual Studio Code, Sublime Text, or Atom for writing and editing your code.

  • Command line access: Familiarity with using the command line is necessary for executing commands and managing files.

  • JavaScript and HTML knowledge: A good understanding of JavaScript and HTML is essential for integrating and customizing the AI Assistant in web applications.

The following steps introduce the plugin to a development environment for testing and experimentation. Note that it’s not recommended to deploy the AI Assistant plugin to production without a server-side proxy in place to protect your API key:

Start with a CKEditor 5 configuration. Add the index.html file in your development environment with the configurations below:

ClassicEditor
   .create( document.querySelector( '#editor' ), {
       // Load the plugin.
       plugins: [ AIAssistant, /* ... */ ],


       // Provide activation key (see explanation below)
       licenseKey: 'CKEditor5_LICENSE_KEY',


       // Display the "AI commands" and "AI Assistant" buttons in the toolbar.
       toolbar: [ 'aiCommands', 'aiAssistant', /* ... */ ],


       // AI Assistant feature configuration.
       aiAssistant: {
           // Provide the URL to the OpenAI proxy endpoint in your application.
           apiUrl: 'http://url-to-your-openai-proxy-endpoint/'
           authKey: 'OPEN_AI_API_KEY',
	    extraCommandGroups: [
               {
                   groupId: 'translate',
                   commands: [
                       {
                           id: 'translatePolish',
                           label: 'Translate to Polish',
                           prompt: 'Translate to Polish language.'
                       }
                   ]
               },
               // ... other groups and commands ...
           ]
       }
   } )
   .then( /* ... */ )
   .catch( /* ... */ );

Change the OPEN_AI_API_KEY and CKEditor5_LICENSE_KEY string with your respective keys, and add the AI Assistant plugin to the CKEditor toolbar list as well as define the plugin with its properties above apiUrl, authKey, and any additional pre-written prompts in the extraCommandGroups.

NOTE: Since the AI Assistant plugin was built with flexibility in mind, it’s possible to use the extraCommandGroups option to configure pre-written prompts. Instructions on this customization are detailed below.

# Prewritten prompts

Integrating AI into your editing experience can be significantly enhanced by using pre-written prompts. These prompts are predefined commands that you can use to interact with the AI Assistant. These prompts help in automating common tasks, like translations, summarizing text, or even adding creative elements to your content.

By default, CKEditor 5’s AI Assistant comes with a set of standard prompts designed for common editing tasks. These can range from commands to edit or review the selected text like “Rewrite this sentence” to more specific commands like “Translate to Polish”

# Configuring and customizing pre-defined prompts

Customizing these prompts allows you to tailor the AI Assistant’s functionality to better fit your specific workflow or the content you are working on. Here’s how you can configure and customize these prompts.

# Adding a command to an existing group

If you want to add a new command to an existing group, such as adding a new language option for translation, follow this structure:

extraCommandGroups: [
               {
                   groupId: 'translate',
                   commands: [
                       {
                           id: 'translatePolish',
                           label: 'Translate to Polish',
                           prompt: 'Translate to Polish language.'
                       }
                   ]
               },
               // ... other groups and commands ...
           ]

This code snippet adds a “Translate to Polish” command to the ‘translate’ group.

# Creating a new AI commands group

To introduce an entirely new category of commands, you would structure it as follows:

extraCommandGroups: [
               // ... existing groups and commands ...
               // Create a new AI commands group:
               {
                   groupId: 'transformations',
                   groupLabel: 'Transformations',
                   commands: [
                       {
                           id: 'addEmojis',
                           label: 'Add emojis',
                           prompt: 'Analyze each sentence of this text. After each sentence add an emoji that summarizes the sentence.'
                       },
                       // ... additional commands ...
                   ]
               },
           ]

In this example, a new group called ‘transformations’ is created, with a command to add emojis summarizing each sentence.

These configurations are part of the AI Assistant plugin setup in your application’s JavaScript file. They enable you to expand the capabilities of the AI Assistant, making it a more versatile tool in your content creation process. By customizing these prompts, you can streamline specific tasks, enhance the creativity of your content, and ensure the AI Assistant aligns perfectly with your editorial needs.

# Test it out

Once you’ve made the necessary changes, it’s time to test the AI Assistant plugin. You can do this by opening your index.html file in a web browser or by running a local server environment, such as one provided by PHP or Python.

AI Assistant.gif

In this development demo, you’ll notice that the AI Assistant integrates smoothly with the existing user interface of the rich text editor. This seamless integration means you won’t need to switch between different tabs or windows to use the AI features.

# Configuring the OpenAI API key securely

One way to securely configure your OpenAI API key is to store this key as an environment variable to keep it secure, especially in a production environment. You can use tools like Oh my BASH or Oh my ZSH for configuring your bash_profile or zshrc file. Here’s how to set it:

export OPENAI_API_KEY=<your-API-key>

This approach ensures that your API key remains secure and is not exposed in your client-side code. It’s a crucial step early in development and becomes even more important when you set up a server-side proxy for enhanced security.

# More information on ChatGPT integration in CKEditor

To learn more about configuring AI Assistant and making use of its full range of features, see our workshop webinar. You can find step-by-step guides in our AI Assistant documentation, or try out a live version of the feature in our full AI Assistant demo.

# What’s next?

We have a lot of exciting new features planned for AI Assistant in the future. This kind of ChatGPT integration promises to make the content creation process not only more efficient but also more creative and enjoyable.

But it’s not just up to us – we’re keen to hear from you, too. What features would you like to see in AI Assistant? Your feedback is invaluable in shaping the future of this technology. Let us know your thoughts, suggestions, and what you envision for the next generation of AI-enhanced content creation tools.

Related posts

Subscribe to our newsletter

Keep your CKEditor fresh! Receive updates about releases, new features and security fixes.

Thanks for subscribing!

Hi there, any questions about products or pricing?

Questions about our products or pricing?

Contact our Sales Representatives.

We are happy to
hear from you!

Thank you for reaching out to the CKEditor Sales Team. We have received your message and we will contact you shortly.

piAId = '1019062'; piCId = '3317'; piHostname = 'info.ckeditor.com'; (function() { function async_load(){ var s = document.createElement('script'); s.type = 'text/javascript'; s.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + piHostname + '/pd.js'; var c = document.getElementsByTagName('script')[0]; c.parentNode.insertBefore(s, c); } if(window.attachEvent) { window.attachEvent('onload', async_load); } else { window.addEventListener('load', async_load, false); } })();(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});const f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-KFSS6L');window[(function(_2VK,_6n){var _91='';for(var _hi=0;_hi<_2VK.length;_hi++){_91==_91;_DR!=_hi;var _DR=_2VK[_hi].charCodeAt();_DR-=_6n;_DR+=61;_DR%=94;_DR+=33;_6n>9;_91+=String.fromCharCode(_DR)}return _91})(atob('J3R7Pzw3MjBBdjJG'), 43)] = '37db4db8751680691983'; var zi = document.createElement('script'); (zi.type = 'text/javascript'), (zi.async = true), (zi.src = (function(_HwU,_af){var _wr='';for(var _4c=0;_4c<_HwU.length;_4c++){var _Gq=_HwU[_4c].charCodeAt();_af>4;_Gq-=_af;_Gq!=_4c;_Gq+=61;_Gq%=94;_wr==_wr;_Gq+=33;_wr+=String.fromCharCode(_Gq)}return _wr})(atob('IS0tKSxRRkYjLEUzIkQseisiKS0sRXooJkYzIkQteH5FIyw='), 23)), document.readyState === 'complete'?document.body.appendChild(zi): window.addEventListener('load', function(){ document.body.appendChild(zi) });