Добавить новость
smi24.net
News in English
Март
2023

Your SEO guide to the ChatGPT API

0

ChatGPT announced the rollout of its API (GPT 3.5 Turbo) on March 1. 

I’m bullish on ChatGPT’s utility for several different SEO-related functions like keyword research, local SEO, content, and link building. Having spent much time using ChatGPT, I’m also painfully aware of its limitations.

While the API won’t be a panacea (and the web interface is actually much better for some tasks), it can help address some of the shortcomings of the web interface.

This article will show you how to maximize ChatGPT’s API with specific SEO use cases.

How to use the ChatGPT API

To leverage the ChatGPT API, you need to be able to access the API in the first place. ChatGPT’s parent company OpenAI has extensive documentation for using the API.

If you’re looking to learn more about building a tool or interacting directly with the API there’s also a good walk-through here.

You can also use AppsScript to query the ChatGPT API in Google Sheets, which we’ll walk through here step by step.

Regardless of your approach, you’ll need to start by getting an API key.

Getting your ChatGPT API key

Once you have an OpenAI account, you can generate your API key either by following this link while logged in or clicking View API keys in the profile dropdown:

Then click Create new secret key.

Copy the API key you generated.

Connecting the ChatGPT API to Google Sheets

There’s a straightforward way to connect ChatGPT to Google Sheets (h/t Keith Mint).

First, create a new Google Sheet, then click on Extensions and choose Apps Script:

You then paste the following code (with your API key in place of YOUR API KEY):

const SECRET_KEY = "YOUR API KEY";
const MAX_TOKENS = 800;
const TEMPERATURE = 0.9;

function AI_ChatGPT(prompt, temperature = 0.4, model = "gpt-3.5-turbo") {
  const url = "https://api.openai.com/v1/chat/completions";
  const payload = {
    model: model,
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: prompt },
    ],
    temperature: TEMPERATURE,
    max_tokens: MAX_TOKENS,
  };
  const options = {
    contentType: "application/json",
    headers: { Authorization: "Bearer " + SECRET_KEY },
    payload: JSON.stringify(payload),
  };
  const res = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
  return res.choices[0].message.content.trim();
}

Click save within Apps Script:

Then you can use the following function format to apply a prompt to a cell:

=AI_ChatGPT("YOUR PROMPT HERE")

As Mint points out in his article, you can also reference a cell if you want to have multiple cells use prompts that refer back to one cell (like the title or topic of a blog post):

In the example above, I used simple prompts like the one pictured, then created a second paragraph for this topic. (We’ll walk through more specific applications for the API shortly.) 

ChatGPT API pricing

Before you start leveraging the ChatGPT API for SEO tasks, it’s essential to understand the pricing.

The price for the gpt-3.5-turbo API (the ChatGPT API) is $0.002 per 1,000 tokens, which is 10x cheaper than the existing GPT-3.5 API.

To better understand what the pricing actually winds up looking like, you need to understand how tokens work.

ChatGPT API tokens

OpenAI has a good breakdown and a helpful free tokenizer tool to help you determine how many tokens a specific text will be and how the text is broken down (in case you need to reduce the number of tokens for a prompt or response).

A few key things to keep in mind:

  • By default, the API can return a maximum of 4,096 tokens.
  • Tokens are a representation of how much text your prompt and response are. This is a key factor, as longer prompts can shorten your response output.
  • Text is translated into tokens and roughly breaks down to around 4 characters in English.

OpenAI also provided this helpful breakdown of how tokens are calculated from text:

  • 1 token ~= 4 chars in English
  • 1 token ~= ¾ words
  • 100 tokens ~= 75 words

Or

  • 1-2 sentence ~= 30 tokens
  • 1 paragraph ~= 100 tokens
  • 1,500 words ~= 2048 tokens

To get additional context on how tokens stack up, consider this:

  • Wayne Gretzky’s quote, “You miss 100% of the shots you don’t take,” contains 11 tokens.
  • OpenAI’s charter contains 476 tokens.
  • The transcript of the U.S. Declaration of Independence contains 1,695 tokens.

So if you used a short prompt to generate a 1,500-word article, it would be less than half a cent.


Get the daily newsletter search marketers rely on.

Processing…Please wait.


Specific API use cases for SEO

The API can help with a lot of the same SEO-related tasks as the ChatGPT web interface, but the two have some significant differences, making some tasks better for one than the other.

Understanding that will help you determine which to use for SEO tasks.

ChatGPT API vs. web interface

The biggest differences include the following:

Scale and bulk tasks

If you want to integrate ChatGPT with an existing application or spreadsheet, you'll need to use the API. 

Additionally, the API will be your friend if you want to perform a specific function applied across multiple instances (e.g., generate meta descriptions for several keywords).

Fine-tuning and relationship between prompts

Currently, ChatGPT's API does not support fine-tuning. If you create multiple prompts through the API, they won't have a relationship. 

You can create a system message to apply to multiple prompts and responses, but OpenAI has said that these are frequently currently ignored by the gpt-3.5-turbo API. 

This means if you have a task that requires several prompts and for ChatGPT to keep the context of an entire conversation, you'll want to use the web interface.

Character limits

The API has a token limit of 4,096 which translates to around 16,384 characters per interaction for each prompt and response

Character limits for the web interface can vary, but generally, the prompt and response are limited to around 2,048 characters, or 4,096. 

So for tasks that require more extensive prompts or more significant responses, the API will be a better option. 

There are also more options for structuring prompts and tasks in a way that gives you a lengthier combined output if you're using code rather than something like the Google Sheets integration.

Pricing 

Again, the API is priced by usage (and offers a free trial with $18 worth of tokens), and the web interface currently offers a free version and a $20/mo. paid version. 

Example ChatGPT API prompts

Let's look at specific use cases where you'd want to consider the API over the web interface.

Title tags and meta descriptions

An obvious use case where the API makes sense is having ChatGPT generate title tags or meta descriptions at scale.

You can use similar prompts to those that work in the web interface here, but if you structure them properly and lay out your spreadsheet right, you can take the first prompt and then quickly apply that to several URLs or keywords: 

Note that the free plan particularly is rate limited, so you may have errors where the cells time out, in which case you need to delete and re-paste:

And as always, keep in mind that:

  • ChatGPT can't crawl the web, so it's either using prior knowledge of a URL from the training period or an assumption about the URL based on terms in the URL to generate suggestions
  • ChatGPT's output can often be wrong or misleading and needs to be edited.

You can use this same format for title tags. (I'll have an article focusing specifically on using ChatGPT to generate and update title tags coming out soon).

Longer content and post outlines

You can use the web interface in ChatGPT to create chunks of content and outlines pretty easily.

If you want to make a longer article or if you're going to create a series of outlines on different topics, however, it can be a clunky experience.

The API is smoother for these tasks.

First, you can chunk off a post you wrote into sections. Then line up the sections and pull your prompt down:

Alternatively, you could have ChatGPT generate several outlines that you then have a writer (or writers) fill in:

Then, you could have the API write the content one section at a time:

Again, here you could take these prompts, load them one by one across the outline (changing each prompt for the appropriate section), and then just pull the same formulas across multiple outlines and have a lot of text specific to the subsections of each post generated.

My experience is that this helps you steer clear of token limits, and even pedestrian prompts like the one above combined with having ChatGPT create an outline will generate better content than if you ask the tool to "write a blog post." 

Beyond that, you can further improve content quality by doing things like:

  • Ask it to include specific phrases (either because you want them on the page or you want to add internal links for that phrase).
  • Feed it statistics or quotes to work into specific sections of the post. (This is particularly helpful if you have a topic that requires up-to-date tactics and statistics, given that GPT-3 was not trained on recent data.)
  • Tweak your prompts to output the tone and formatting you want (more on this shortly).

And, as always, layer on human editing.

FAQs

There are multiple FAQ-related functions the API can help with.

First off, you can generate a list of FAQ questions to be associated with a blog post:

Next, you can have the ChatGPT API answer these (again: proceed with caution when it comes to output quality and accuracy):

Schema

You can also have ChatGPT generate schemas for you across multiple pages. 

In this case, we can apply FAQ schema to the FAQs it created for us:

Convert content to HTML

Another cool use case for ChatGPT is to convert text to HTML. 

First, let's convert our post from text to HTML:

A few things to note here:

  • As you can see, the headers in each section were initially formatted with paragraph tags. I fixed this in the prompt by adding, "Format the header of the section as an h2, and any other headlines in this section as an h3."
  • I wasn't able to combine the entire post (which was around 1100 words) into one cell to be converted to HTML, so I had to chunk it off and gave specific instructions in my prompt for each cell to make sure ChatGPT didn't layer in the formatting for an entire HTML document in every cell.
  • You may also get some wonky formatting, like additional quotes you didn't expect in the output. 

As with all aspects of ChatGPT, keep refining your prompts and always check the output.

Now that we have our post in HTML, we can start to do some cool things with internal linking.

We can tell ChatGPT to add internal links from specific phrases to specific pages anywhere in the HTML we just generated:

If we were creating a cluster of pages, we could create rules specific to each page and apply them to the relevant HTML.

This way, everything we generate is interlinked the way we want, the HTML is ready to go, and the FAQ schema is added appropriately.

I tried to create a rule that was a little more complicated, asking ChatGPT to hyperlink phrases. Here is what I added to my prompt:

  • "Any time you see the words making and laugh within 5 words of each other, create a link with those two words and all of the words in between them to standupexperience.com/make-them-laugh."

Here is the link that was added:

That's not what I asked for, and also, it didn't link every instance of stand-up as I asked it to.

I'll need to refine my prompts and check my outputs.

Outreach templates

If you're reaching out to multiple places for link outreach or guest post placements, you can use the ChatGPT API to create multiple outreach templates for you:

If you have different kinds of templates, get creative with applying these prompts across different outreach targets.

Using the web interface and the API in tandem (a.k.a., bring your prompts)

Two things are true:

  • The API is better for larger projects and performs many prompts simultaneously.
  • The web interface is frequently better at getting you to an excellent output since you can go back and forth with ChatGPT to give context, review the output, provide feedback, etc.

One way to get the best of both worlds is to create your prompt in the web interface and then apply it to multiple items via the API.

Let's look at a specific example from this post. My internal linking prompt didn't work via the API. It's challenging to troubleshoot via the API because you can't give ChatGPT feedback or ask why the prompt failed.

Enter, prompt generation via the web!

My typical ChatGPT process is to: 

  • Give it chunks of context.
  • Check for understanding. 
  • Review the output for errors and give it additional feedback to achieve my desired result.

To be able to do this for internal linking rules, let's start with the web interface to clean up our ChatGPT prompt.

First, I want to give ChatGPT some context. (Remember: ChatGPT doesn't know about its own API!) 

I want to give it information about the API, share the HTML I'm starting with, share the prompt I used, and share the output I got and then ask ChatGPT to diagnose the issue and rewrite the prompt for me.

Let's see how it goes:

If you don't pre-empt it, ChatGPT will repeatedly interrupt you to fire (frequently irrelevant) answers and suggestions (like an eager student who didn't do the reading).

I copied and pasted the text from this page in four prompts, the HTML I was trying to add links to, the full Sheets function I'd used, and the output I'd gotten.

Next, I finally shared the issue with the output:

And then ChatGPT fixed the prompt for me.

Well, it wasn't actually fixed.

ChatGPT is relentlessly polite even if you're getting a bit testy, and when I shared the prompt, it analyzed it for me:

The suggestions on HTML size are good ones, but I was still getting the error:

This time, the prompt worked!

To address the max tokens issue, I can go to Apps Script to adjust that number:

Or obviously, if I'm not using Sheets, it's not likely to be an issue (until I hit the 4096 tokens).

Get creative and look for solutions

SEO applications for the ChatGPT API go well beyond what's listed here. 

If you're on the lookout for ways to use the platform and can get creative you'll find many more applications like:

  • Programmatic solutions: You can go beyond Google Sheets to find exciting and scalable uses for the ChatGPT API.
  • Combining multiple APIs: Think about how you might be able to use the ChatGPT API in unison with APIs like Google Search Console, Ahrefs, Semrush or similar. What problems do you want to solve? 
  • More efficient or better workflows: Take stock of the tasks you and your team complete daily. Are there items that ChatGPT's API may be able to either allow you to do just as well but more efficiently, or to improve your work product around?

With the recent release of GPT-4, more opportunities for leveraging the platform will likely continue to crop up.

The post Your SEO guide to the ChatGPT API appeared first on Search Engine Land.








В Третьяковке на Кадашевской набережной открылся концертный зал

В России обнаружено более 100 случаев заболевания новым штаммом COVID-19

118 лет назад, 25 июля 1907 года, Ставропольская психиатрическая больница приняла первых 47 пациентов

Баскова, Киркорова и Лазарева погнали с экранов: попались на непотребщине


The Great Indian Kapil Show: Raghav Chadha reveals telling Parineeti Chopra to manifest he will never become the PM; says ‘Yeh jo bolti hai wo ulta hota hai’

UFC Abu Dhabi live blog: Shara Bullet vs. Marc-Andre Barriault

Chat log from R20 of 2025: Richmond vs Collingwood

Kolo Muani: Juventus prepare new offer but face Man United and Chelsea threat


Ана Каспарян поднимает вопросы Геноцида армян, этнических чисток в Арцахе и роли Израиля в конфликте — в откровенном интервью с Такером Карлсоном. ВИДЕО

Как начать петь. Как начать петь песни. Как начать петь с нуля

В мэрии назвали условия присвоения Элджею звания почётного жителя

В этих регионах больше всего пьяных аварий


Ninja Party можно предзаказать в мобильных маркетах с релизом в конце июля

Quarantine Zone creator reveals 3 reasons the zombie sim went viral on TikTok

«Если бы у Наруто и AC Shadows был ребёнок»: Разбор англоязычной версии Where Winds Meet

Brütal Legend is free in honor of Ozzy Osbourne, but only for 666 minutes



Первый прямой рейс Москва – Пхеньян вылетел из Шереметьево

Дорога любви: Жасмин представляет романтичный клип на песню «Ты и я»

Возобновлены прямые рейсы из Москвы в Пхеньян

Как начать петь. Как начать петь песни. Как начать петь с нуля


Пловец из Москвы скончался во время заплыва по Волге в Нижнем Новгороде

Пловец из Москвы погиб во время заплыва на Волге

«В августе будет климатическая угроза»: синоптики дали новый прогноз на конец лета

Нутрициолог Порхун назвала опасные для детей продукты


Самолёт совершил первый прямой авиарейс из Москвы в Пхеньян

Облюбовали «звезды». Историк Васькин назвал самый желаемый дом в Москве

"КИБЕР ПУШКИН": ХОТЬ ДОМ КУЛЬТУРЫ МОЖНО НЕ СНОСИТЬ, НО ОБЯЗАТЕЛЬНО ВСЁ ПРАВИЛЬНО УЛУЧШИТЬ И ДОПОЛНИТЬ! СЕНСАЦИЯ! Россия, США, Европа могут улучшить отношения и здоровье общества!

Специалисты из Москвы прибыли в Тынду для помощи родственникам жертв крушения Ан-24


Россиянин Сидоренко выиграл соревнования по настольному теннису на Универсиаде‑2025

Медведев проиграл Муте четвертьфинал турнира ATP в Вашингтоне

Рахимова обыграла Шарму и вышла в основную сетку турнира WTA в Монреале

Боузкова одержала победу на теннисном турнире в Праге


Семь воздушных судов 28 июля прилетают во Владивосток вне расписания

АРМЕНИЯ. Азербайджан развивает связи с Россией и другими соседями – Гаджиев

Путин поднял флаг на атомном подлодке "Князь Пожарский" в Северодвинске

Столичные нормы: Минтранс утвердил рекомендации для регионов по управлению парковочным пространством


Музыкальные новости

Алексей Учитель снимает фильм о композиторе Дмитрии Шостаковиче

Дорога любви: Жасмин представляет романтичный клип на песню «Ты и я»

Менеджер Песни. Менеджер Релиза Песни. Менеджер вышедшей песни.

Песков: Высоцкий является феноменальной частью российской культуры


Первый прямой рейс Москва – Пхеньян вылетел из Шереметьево

Как начать петь. Как начать петь песни. Как начать петь с нуля

Возобновлены прямые рейсы из Москвы в Пхеньян

ИИ в Подмосковье резко снизил количество жалоб на незаконную торговлю


«Ужас, который я пережила, никому не пожелаю!»  Алёна Блин взяла в заложники ловца в новой серии «Погони» на ТНТ

«Деловые Линии» сократили сроки авиаперевозок по более чем 4400 направлений по России

В аэропорту Пулково в Питере временно приостановили полеты

Бывший боец UFC бразилец Баррозу в Мелитополе попросил гражданство России


Канал, о котором мечтали несколько веков...

Адвокаты  Рублевка, Патриаршие пруды (Патрики), Барвиха, Рождественно, Шульгино, Раздоры, Рублево-Успенское шоссе, Огарево, Жуковка,Крылатское, Хамовники, Дорогомилово, Кунцево, Москва-сити, Филёвский парк, Фили-Давыдково Западного административного округа города Москвы

На МКАД движение транспорта затруднено из-за ДТП

Движение в поселке Восточный ограничили из-за пожара


Путин отметил смелость и героизм морских пехотинцев в бою.

«Подводная лодка, демонтрированная Путину, произвела шок на Западе»

Путин поздравил Жапарова с юбилеем подписания декларации о союзничестве.

Путин в День ВМФ прибыл на территорию Главного Адмиралтейства в Санкт-Петербурге


Профессор Баранова рассказала, кому опасен новый штамм коронавируса

Приговор экс-руководителю компании по производству вакцин против ковида был смягчен.



Выбор клиники гнатологии в Москве

Клиника гнатологии в Москве

Приговор экс-руководителю компании по производству вакцин против ковида был смягчен.

Пьяный сантехник устроил дебош в столичной студии косметологии из-за жалобы


Запад ударил Зеленского по самому больному месту – кошельку: Киев показательно лишили 1,5 миллиардов помощи

Зеленский настаивает: встреча с Путиным до конца августа с участием Европы

Киевский режим применил все 18 пакетов санкций ЕС


27 июля 2012 года открылись XXX летние Олимпийские игры в Лондоне

Канал, о котором мечтали несколько веков...

Пловец из Москвы умер во время соревнований в Нижнем Новгороде

Круговой оформил дубль за 2 минуты и помог ЦСКА впервые победить в новом сезоне РПЛ


Лукашенко получил приглашения от стран Латинской Америки и Азии для визитов.

«Беларусь-1»: Лукашенко дал интервью одному из американских СМИ

Лукашенко дал интервью одному из американских СМИ


Собянин в День работника МФЦ поздравил сотрудников центров госуслуг Москвы

Собянин поздравил работников центров госуслуг с профессиональным праздником

Сергей Собянин. Главное за день

Собянин: На территории промзоны «Кирпичные улицы» будет создана социнфраструктура


Козлов объявил о возможных прямых рейсах из России в курорт Вонсан, КНДР.

Москвичей предупредили об аномальной жаре 28–30 июля

Сняла скальп и утопила на глазах зрителей: как и почему косатка Тиликум начала убивать

Канал, о котором мечтали несколько веков...


В Вашингтоне задержан перелезший через ограду здания Минфина мужчина

Нутрициолог Порхун назвала опасные для детей продукты

В Госдуме РФ назвали сомнительными слухи о блокировке WhatsApp

Семь воздушных судов 28 июля прилетают во Владивосток вне расписания


70 участников СВО в Архангельске показали мотивацию выше госслужащих — Цыбульский

В Архангельске представили киноальманах «Север, я люблю тебя!» по произведениям современных писателей

Путин дал указание рассмотреть проблемы онкологии в Архангельской области.

В музее-заповеднике «Архангельское» пройдут «Jazzовые сезоны»


К парню с костылем подошли трое с требованием уступить. Он был готов, но заступилась бабушка по соседству

Прогноз погоды в Крыму на 27 июля

Крымский мост: информация об очередях на утро воскресенья

В Крыму из-за дыма от пожара столкнулись девять автомобилей


«Не интересует»: КНДР отказалась обсуждать мир с Южной Кореей

Облюбовали «звезды». Историк Васькин назвал самый желаемый дом в Москве

Задержка и отмена рейсов: Калининградский аэропорт "Храброво" сообщает причины

Подросткам могут запретить кататься на питбайках по дорогам














СМИ24.net — правдивые новости, непрерывно 24/7 на русском языке с ежеминутным обновлением *