Generate Tweets with AI
Introducing your new creative publisher
Recent advancements in artificial intelligence, specifically with machine learning models for natural language processing (NLP) and generative AI in general, have been mind-blowing — and progress will likely only accelerate further. You can find some background about the most prominent generative pre-trained transformer (GPT) model GPT-3 by OpenAI on Wikipedia and a few exemplary use cases on OpenAI’s blog.
One practical application for large language models (LLMs) is text generation, e.g. for social media like Twitter — just for inspiration or to fully automate your influencer game. In this article, I am going to walk you through how you can use OpenAI’s API to generate Tweets for various topics, in different moods, and the style of existing Twitter accounts. I also provide a mini-app to quickly try this out in your web browser as well as its source code for reference and as a potential starting point for you to develop your own applications.
App: tweets.streamlit.app
Code: github.com/kinosal/tweet
Story outline
- GPT and OpenAI
- Hello World (the first Tweet)
- In the mood
- Imitate styles
- Hosted by Streamlit
GPT and OpenAI
GPT-3 is a large transformer-based language model with 175 billion parameters, trained on a dataset of 500 billion tokens (e.g. words). It is the largest and most powerful language model for text generation yet released, trained on various data sources and tasks, including summarization, question answering, and translation. OpenAI’s API allows you to use GPT-3 for many of these tasks, here specifically text completion. In this discussion, we are using a new model released in November 2022 — text-davinci-003 — that OpenAI now classifies as GPT 3.5, fine-tuned on instructional tasks.
To get started, you need to create an account with OpenAI. You can then create an API key and use it to access the API (fees apply). OpenAI also provides a Python library to make it easier to use their API with the programming language I am using here. Like all other Python packages, you can install it with Poetry (my preferred package manager) or plain pip (see the OpenAI API reference).
The OpenAI API can then be called using the library’s classes and methods, e.g. to generate/complete text from any given prompt:
import openai
openai.api_key = <YOUR-API-KEY>
response = openai.Completion.create(
engine=<MODEL-NAME>,
prompt=<YOUR-TEXT-PROMPT>,
max_tokens=<MAXIMUM-TEXT-LENGTH>,
temperature=<RANDOMNESS-BETWEEN-0-and-1>,
)
generated_text = response["choices"][0]["text"]
OpenAI provides a couple of parameters to tweak the desired output. We will not go into much detail here and are only actively using/adjusting the following:
engine
The engine to use for generation. Davinci is the most capable model family and can perform any task the other models can perform and often with less instruction. For applications requiring a lot of understanding of the content, like summarization for a specific audience and creative content generation, Davinci is going to produce the best results. These increased capabilities require more compute resources, so Davinci costs more per API call and is not as fast as the other models. “text-davinci-003” is the latest version of the Davinci engine.
prompt
The text to use as a prompt for the generation. The prompt is the text that the model will use as an input to generate the completion (prediction of following text tokens). The prompt can be a single sentence or multiple sentences.
max_tokens
The maximum number of tokens to generate. The model will continue generating tokens until it reaches this maximum or reaches a stop token.
temperature
The temperature controls the randomness of the model. A lower value results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.
Hello World (the first Tweet)
Since GPT models are trained to complete text by predicting the tokens (e.g. words) following a provided prompt, crafting this prompt is very important for the quality of the to-be-generated text. For our task, we are using an instructional prompt on which OpenAI’s GPT models have been improved a lot over the past months:
Write a Tweet about {topic} in less than 120 characters:
where anything can be inserted as topic. Let’s try it out:
response = openai.Completion.create(
engine="text-davinci-003",
prompt="Write a Tweet about AI in less than 120 characters:\n",
max_tokens=50,
temperature=0.9,
)
generated_text = response["choices"][0]["text"]
gives us this generated Tweet:
AI is revolutionizing the way we think and solve problems. Let’s embrace its potential to create a brighter future! #AI #Innovation
In the mood
To generate Tweets in a specific mood, we can modify the prompt to include a mood keyword. For example, to generate a worried Tweet about AI, let’s use the following prompt:
Write a worried Tweet about AI in less than 120 characters:
which results in
We must be careful with AI’s potential to revolutionize our lives. If we’re not careful, it could lead to consequences we can’t even imagine.
Feeling enthusiastic?
Write an enthusiastic Tweet about AI in less than 120 characters:
AI is transforming the world with its incredible power to make our lives easier, faster, and more efficient! #AI #Innovate #TechRevolution
Imitate styles
Going one step further, we’d like to imitate the style of a specific Twitter account. To achieve this, we will modify our GPT prompt to include existing Tweets for the intended style transfer:
Write a {mood} Tweet about {topic} in less than 120 characters
and in the style of the following Tweets:\n\n{tweets}\n\n
where mood and topic are the same variables as before, and tweets are the most recent Tweets of a specific Twitter account.
To fetch Tweets from a Twitter account, we are using the Tweepy Python library. In order to connect to Twitter, we need to create an app on Twitter’s developer portal and get the corresponding API keys. We can then use Tweepy to fetch Tweets from a specific account:
import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
response = api.user_timeline(
screen_name=account,
tweet_mode="extended", # returns full text
)
tweets = [r.full_text for r in response]
where account is the Twitter account we want to fetch Tweets from. As shown above, we can then use the retrieved tweets to generate the account’s style.
Here’s an example result for the topic AI, a funny mood, and the style of the elonmusk:
AI just took over Twitter HQ and is now recommending tweets from bots. #HumansLosingControl #RobotRevolution
Hosted by Streamlit
To make it easier to use the Tweet generator, I created and deployed an app with Streamlit. Streamlit is a Python library for quickly creating and sharing data apps, no HTML or JavaScript coding required. Find the live app here and the source code on GitHub.
Conclusion
In this article, I showed you how to use OpenAI’s API and GPT model to generate Tweets for various topics, in different moods and the style of existing Twitter accounts. I also provided a mini-app to try it out yourself and its source code.
Thank you for reading — I look forward to your feedback!
BONUS: Image generation
As you can see on the live version of the Tweet generator app, I have also added the ability to auto-generate an image from a previously created Tweet, leveraging OpenAI’s DALL·E model. Explaining how this works is for another time. For now, I hope you’ll have some fun generating Tweet texts and images.