My experience with Open AI and Python to write automated blogs
Tags: openai, python, productivity, seo
Published: 2024-02-04 14:23:15

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rifnpyalyaggf3f9biw7.jpeg)

Staring at a blank page was a every time phenomena while writing blogs for [SuperPlugs](https://superplugs.co). And I wondered, if I could imagine a time where AI writes my blog posts while I sip coffee and brainstorm ideas. :) 

I knew about OpenAI, the research powerhouse behind groundbreaking language models, is diving headfirst into this very experiment. So I thought, why not ask OpenAI to generate automated content for me. And if that works, can I also auto publish them?

In this blog, we'll go through my journey of writing and publishing blogs in an automated way through OpenAI and my favorite language Python.

**A bit about Open AI**
When I was researching more about Open AI, I realized, 
OpenAI offers several ways to help with blog writing. 

Here are some potential benefits:

1. Brainstorming and Inspiration: Idea generation, Research and analysis
2. Writing Assistance: Outlining, Content expansion, Translations
3. Editing and Improvement: Fact checking, SEO Optimization, Grammar and styling

**Back to my experiment**

Anyway, to satisfy my curiosity and being productive for SuperPlugs, I started to dabble with the Open AI APIs. 

<u>Step1: Creating a script to generate content for a blog</u>

I stumbled upon the `ChatCompletion` API which is available as part of python's `openai==0.28 version`. I'm using python3.

A little bit of playing around with the API, here's a piece of code I came up with. As you can see, I'm using the `gpt-3.5-turbo` model to generate content.

**blog.py**

```
# Install openai library with pip and set the API key
# Please note: we are using openai==0.28 version
import openai
openai.api_key = "sk-dwqwefdfvfdg"
```

```
# Add your prompt to open API
prompt = "Generate a 100 word article on Customer Feedback"
model = "gpt-3.5-turbo"
```

```
completion = openai.ChatCompletion.create(
  # Use GPT 3.5 as the LLM
  model="gpt-3.5-turbo",

  # Pre-define conversation messages for the possible roles 
  messages=[
      {"role": "system", "content": "You are a helpful 
            assistant."},
      {"role": "user", "content": prompt}
 ]
)
```

```
# Print the returned output from the LLM model and convert it to HTML format
article = completion.choices[0].message
articleHtml = article["content"].replace('\n\n', '</p><p>')

```

That's it! Now if you run the script, you will see a nicely generated article.

```
python3 blog.py
```

Here's how the output looks like

`Customer feedback is an invaluable tool for any business. It provides insight into the customer experience, allowing businesses to identify strengths, weaknesses, and areas for improvement. Gathering feedback can be done through surveys, online reviews, or direct communication with customers. By actively listening to customer feedback, businesses can better understand their customers' needs and expectations. This information can then be used to make strategic decisions that enhance the overall customer experience and improve business operations. Additionally, responding to feedback in a timely and professional manner can help build trust and loyalty with customers. Ultimately, customer feedback is an essential part of building a successful and customer-centric business.`

Well that was quite impressive, it generated a quick 100 word note on customer feedback with in few seconds.

<u>Step2: Posting the blog to Ghost</u>

My expectations raised further and I thought why not automatically post this content as a post on [SuperPlugs blog](https://blog.superplugs.co/)? For context, SuperPlugs blog is hosted on Ghost. So I quickly went through the Ghost API documentation and enhanced my script to take the content generated by OpenAI to post it to Ghost as a blog. 
Here's how the code looked like -

```
import requests # pip install requests
import jwt      # pip install pyjwt
from datetime import datetime as date

# Admin API key goes here
key = '6adawq6y76tyutyh74e:ca89dqwewqe5ca'

# Split the key into ID and SECRET
id, secret = key.split(':')

# Prepare header and payload
iat = int(date.now().timestamp())

header = {'alg': 'HS256', 'typ': 'JWT', 'kid': id}
payload = {
    'iat': iat,
    'exp': iat + 5 * 60,
    'aud': '/admin/'
}

# Create the token (including decoding secret)
token = jwt.encode(payload, bytes.fromhex(secret), algorithm='HS256', headers=header)

# Make an authenticated request to create a post
url = 'https://blog.superplugs.co/ghost/api/admin/posts/?source=html'
headers = {'Authorization': 'Ghost {}'.format(token)}

# Blog post body that includes title, slug, tag
body = {'posts': [{
		"title": "What is Customer Feeedback?",
		"slug": "what-is-customer-feedback",
		"tags": [
			{ "name": "Customer Feedback", "description": "customer feedback tag" },
		],
    "source": "html",
    "html": "<p>" + articleHtml + "</p>",
    "featured": False,
    "custom_excerpt": "This article covers Customer Feedback",
		"status": "draft",
    "feature_image": ""
	}]}
r = requests.post(url, json=body, headers=headers)
```

Wow! That was cool, the post content got generated in step1 via OpenAI and then the blog got auto published to Ghost in step 2. :) Much better than what I had initially thought of.

<u>Step3: Taking it further?</u>

Here's the wonderful part. I took this even further. :) I asked my team to give me a list of blogs they wanted to write, added them as topics with title, slug, tag in a CSV file. 

I further enhanced the script to read the CSV file, generate content with OpenAI and publish content as Posts in Ghost (Draft mode), all at once. Whoa! :) I was crushing it like crazy :)

**Caveats**

While all this sounds too rosy, please remember -
1. OpenAI is a tool, not a replacement for human creativity. 
2. Blog generated by OpenAI in the above code does not handle other technical aspects of SEO - cross linking, external linking, images, but that can be achieved via other APIs of Open AI.

**Conclusion**

My curiousity got the better of me. I learnt many things that I hadn't exposed myself to in the past. I now understand how OpenAI is useful and it's limitation in the context of generating content for writing blogs.

That was me! Over to you, how was your experience with AI? Eager to hear from you. :)