Automatically generate title tags & meta descriptions with GPT-3

Use GPT-3 to input a keyword and automatically generate a page title and meta description πŸš€ πŸ€–

Check out the GIF to see it in action πŸŽ₯


How to add the Script to Google Sheets

1. Sign up to OpenAI

Sign up to OpenAI here: https://beta.openai.com/signup (there’s no longer a waiting list, so you’ll get access right away).

If you haven’t heard of GPT-3, where have you been? It provides a wide variety of natural language tasks from copywriting, summarising, classifying text, translation (and even writing code). Check this out: https://copilot.github.com/

You get $18 credit in the free account, and on the main engine, davinci, every request will cost you $0.02 – so not bad. There are other fast, cheaper engines too which I’ll explain below.


2. Get your API Key

You can copy your API key from here: https://beta.openai.com/account/api-keys


3. Copy the script below:

/**
 * Use GPT-3 to input a keyword and automatically generate a page title and meta description
 * 
 * @param {"what is artificial intelligence"} keyword - enter your keyword
 * @customfunction
 */
function meta(keyword) {
  
  // add your apiKey from OpenAi here. Found at: https://beta.openai.com/account/api-keys

  const apiKey = "";

  // Prompt copied exactly from 'View code' in GPT-3 Playground: https://beta.openai.com/playground/
  const prompt = "If you input a keyword, I will create a meta title and description for an attractive search result on Google in the United Kingdom for 2021. \n\nKeyword: Cheesecake recipes\nPage title: 65 Best Easy Cheesecake Recipes - How To Make Homemade Cheesecake\nMeta description: Making cheesecake is easier than you think! Whip up one of these easy, homemade cheesecake recipes to impress your friends.\n\nKeyword: VPN\nPage title: The Best VPN Services for 2021\nMeta description: A VPN, or virtual private network, is an easy way to improve your online privacy. We've reviewed scores of them, and these are the best VPN services we've tested.\n\nKeyword: Leather sofas\nPage title: Leather Sofas: Leather Sofas, Settees & Suites\nMeta description: Our leather sofas offer durability & unmatched comfort in a range of sizes & styles.\n\nKeyword: CRM\nPage title: What is Customer Relationship Management (CRM) Software?\nMeta description: Learn how to create order with a customer relationship management (CRM) system and keep everything you need to know about your customers in one place.\n\nKeyword: How to lose weight fast\nPage title: How to Lose Weight Fast in 3 Simple Steps\nMeta description: This simple 3-step plan can help you lose weight fast. Read about the 3-step plan, along with other science-backed weight loss tips, here.\n\nKeyword: things to do in london\nPage title: Over 165 Incredible Things To Do In London\nMeta description: From pop-up bars and beautiful experiences to escape rooms, crazy golf courses and more. Check out our guide to all of the amazing things to do in London, whatever the weather, month or day of the week.\n\n";

  const apiCall = (prompt) => {

    // increase temperature for more randomness, and variations of the output. Max tokens set at 240 characters (could be lower).
    // using Keyword: as a stop sequence so that it only generates one result.

    const parameters = {
      'prompt': prompt + 'Keyword:' + keyword,
      'max_tokens': 60,
      'temperature': 0.3,
      'stop': '["Keyword:"]'
    };

    const options = {
      'method': 'post',
      'contentType': 'application/json',
      'payload': JSON.stringify(parameters),
      'headers': {
        Authorization: 'Bearer ' + apiKey,
      },
    };

    // fetch from GPT-3 - Engines can be changed. eg. https://api.openai.com/v1/engines/curie/completions
    // worth exploring each individual Engine in more detail here:https://beta.openai.com/docs/engines

    const response = UrlFetchApp.fetch('https://api.openai.com/v1/engines/davinci/completions', options,);

    return JSON.parse(response.getContentText())['choices'][0]['text'];
  }

  const output = apiCall(prompt);

  const pageTitle = output.match(/Page title:\s*(.*)/, 1)[1];
  const metaDescription = output.match(/Meta description:\s*(.*)/, 1)[1];

  return [["Title", "Meta Description"], [pageTitle, metaDescription]]

}

4. Head over to Google Sheets

Or if you’re really smart, create a new sheet by going to: https://sheets.new

Select Script editor from the Tools menu.

Paste the script and replace line 11 with your API key:

  const apiKey = 'addapikeyhere';

Save it.


5. Add the formula to any cell in your sheet

=meta("what is artificial intelligence")

Add any keyword to the formula and it will output a title tag and meta description. You can cut and paste the formula with the same keyword and you’ll receive different outputs (great for inspirationπŸ’‘). I’d recommend doing this to get the best possible output.

How does it work?

GPT-3 uses a prompt which is a bunch of random keyword, page title and meta description variants I extracted from search results.

Alongside the prompt, I also described to the engine what I’d like the output to be. You can see it below in the Playground:

It’s quite a large prompt, which increases the token size and the speed/cost.

I don’t understand enough about GPT-3 yet to know whether this will bias the outcome – you can let me know in the comments πŸ‘‡

I didn’t spent too much time on it, but I tried to vary the keyword categories; travel, affiliate, informational, recipes, as well as how the page titles look. I also included ‘2021’ and the ‘United Kingdom’ so that the outcome doesn’t include older dates and were specific to the UK. In my tests, this doesn’t always work.

Where you can go with it

There are so many ways you can improve this script. Hopefully, I’ve just provided you with the foundations to build something that will support you with title tag and meta description automation, or at least inspiration.

Ways to make it better:

  • Create dynamic prompts from Google Sheets data. For example, you could include your own title tags and meta descriptions, so the output is aligned to what you’re already doing.
  • Experiment with the temperature settings. This controls randomness, and you could potentially improve the creative output by increasing it.
  • Create separate functions for search result types. For example, you could set up prompts that exclusively use informational or transactional search results.
  • You should also experiment with different engines to save on speed and cost. The different engines are described here: https://beta.openai.com/docs/engines. I’ve personally used Curie and it worked very well.

If you do build something with this, I’d love to hear from you (and potentially feature you on Keywords in Sheets). Please get in touch!


Thanks for stopping by πŸ‘‹

I’m Andrew Charlton, the Google Sheets nerd behind Keywords in Sheets. πŸ€“

Questions? Get in touch with me on social or comment below πŸ‘‡


More Scripts

Submit your response

Your email address will not be published.

8 Responses on this post

  1. Got to say, impressive and awesome! Using this is going to make things run more efficiently.

    It’s not perfect, but it pretty much does 80% of the job.

  2. Great script! Only thing which would further improve it is some sort of language choice option. For instance, about 90% of our clients have dutch websites because we are a dutch company, thus english and german title tags + meta descriptions are of no use. Any way of adding this into the script?

    1. Yeah I think this is possible. Alternatively, you could translate the prompt I’ve added into your target language – that should also work πŸ™‚

  3. Thank you Andrew for you SUPER work and for share it with ROTW πŸ˜‰
    I’m doing something wrong and I geet this error: Fejl
    Exception: Request failed for https://api.openai.com returned code 401. Truncated server response: { “error”: { “message”: “You didn’t provide an API key. You need to provide your API key in an Authorization header using Bearer auth (… (use muteHttpExceptions option to examine full response) (linje 40).

    Kan you help me with this.
    Thanks.
    Have a nice day.
    Cheers
    Oscar

    1. Thanks so much! It looks like you haven’t added your API key. You’ll need to register with OpenAI, copy your API key and then add it to the sheet πŸ˜€

      Thanks,
      Andrew