Generate Subtle Tweets From an Essay in the Style of the Author

Table of Contents

This script will take your essay text, extract key points, and use function-calling to create a subtle thread composed of your ideas. It works and it’s damn better than any tweet generator I’ve ever seen yet, personally, but it could be improved and refined in many ways.

You must update: OPENAI_API_KEY and YOUR-INPUT-TEXT.txt. import os import openai import requests import re import json

Load API key from .env file

openai.api_key = ‘YOUR_OPENAI_API_KEY’

def remove_hashtags_from_list(text_list): return [re.sub(r’#\w+’, ”, text) for text in text_list]

def generate_tweets(article_content): completion = openai.Completion.create( model=“gpt-3.5-turbo-instruct”, prompt=f”You recently graduated with an English degree from Harvard and now I’ve hired you as a writer.
I will give you an essay that you wrote, and you will write 15 tweets from it, according to 15 templates I will give you.
If you write anything corny, cliché, unthoughtful, pretentious, vulgar, crass, or strident, your career will be over.
Write the tweets in the same style and tone as the essay.
Write all tweets in the first person voice (for example, ‘I think’) because you wrote the essay.
Do not refer to ‘the essay’ or ‘the article’ or ‘the author’.
Do not use any hashtags or emoji under any circumstances, or you will be fired.
Here is the essay: {article_content}
Here are the templates:\

  • I just published a post on $MainTopic1, $MainTopic2, and $MainTopic3\
  • Summarize the main point of the essay.\
  • Extract a quote that best approximates the main idea of the essay.\
  • Paraphrase the Key Quote Tweet without using quotes.\
  • Extract a quote that represents the most surprising claim in the essay.\
  • Extract as a quote a whole paragraph that captures the essay’s best moment.\
  • Paraphrase the most surprising claim in the essay.\
  • Pose three question that the essay raises but may not fully answer.\
  • Highlight any statistic or data point from the essay. If there is none, ignore this and don’t tell me about it.\
  • Make a point, suggested by the essay, which goes against conventional wisdom.\
  • Make a light-hearted or humorous comment related to the essay in all lowercase.\
  • Ask for readers’ opinions or experiences related to one of the essay’s topics.\
  • Summarize a claim from the essay that is likely to spark debate or outrage.\
  • Create a poll related to a contentious issue raised by the essay.\
  • Write the most insane and outrageous declaration you can think of, based on the essay.

    Format your reply as a list of 15.” , max_tokens=1000, temperature=.25 ) tweets = completion.choices[0].text.strip().split(‘\n’) return tweets

thread_custom_functions = [ { ‘name’: ‘extract_main_topic_and_key_ideas’, ‘description’: ‘extract main topic and key ideas’, ‘parameters’: { ‘type’: ‘object’, ‘properties’: { ‘MainIdea’: { ‘type’: ‘string’, ‘description’: ‘Main idea of the thread’ }, ‘KeyIdea1’: { ‘type’: ‘string’, ‘description’: ‘First key idea of the thread.’ }, ‘KeyIdea2’: { ‘type’: ‘string’, ‘description’: ‘Second key idea of the thread.’ }, ‘KeyIdea3’: { ‘type’: ‘string’, ‘description’: ‘Third key idea of the thread.’ } } } }

def extract_ideas(tweets): response = openai.ChatCompletion.create( model=“gpt-4”, messages=[ { ‘role’: ‘system’, ‘content’: ‘You are a helpful assistant that extracts ideas from text.’ }, { ‘role’: ‘user’, ‘content’: f’{tweets}’ } ], max_tokens=300, temperature=.25, functions = thread_custom_functions, function_call = ‘auto’ )

ideas = json.loads(response[‘choices’][0][‘message’][‘function_call’][‘arguments’]) return ideas

def hook_tweet(ideas): """Insert the ideas into a hook tweet"""

return ( f”I’m interested in {ideas[‘MainIdea’][0].lower() + ideas[‘MainIdea’][1:]}\n” f”\n” f”- {ideas[‘KeyIdea1’]}\n” f”- {ideas[‘KeyIdea2’]}\n” f”- {ideas[‘KeyIdea3’]}” )

def generate_thread_with_hook(tweets): """Generate a Twitter thread with a hook tweet"""

hook = hook_tweet(extract_ideas(tweets))

Call OpenAI API to generate a Twitter thread

response = openai.ChatCompletion.create( model=“gpt-4”, messages=[ { ‘role’: ‘system’, ‘content’: ‘You are a helpful assistant that generates Twitter threads. ’ }, { ‘role’: ‘user’, ‘content’: f’Your job is to write a Twitter thread with the following information: """{tweets}"""\n Your thread must start with this tweet verbatim:\n {hook} 1/\n’ } ], max_tokens=300, temperature=.15 )

thread = response[‘choices’][0][‘message’][‘content’].split(‘\n’) return thread

if name == “main”:

Read the content from ‘text.txt’

with open(‘YOUR-INPUT-TEXT.txt’, ‘r’) as f: article_content = f.read()

Generate tweets and remove hashtags

tweets = generate_tweets(article_content) tweets = remove_hashtags_from_list(tweets)

Extract ideas and generate hook

ideas = extract_ideas(tweets) hook = hook_tweet(ideas)

Generate thread with hook

thread = generate_thread_with_hook(tweets) thread = remove_hashtags_from_list(thread)

Write the generated tweets, thread, hook and extracted ideas to ‘output.txt’

tweets_str = “\n”.join(tweets) thread_str = “\n”.join(thread) ideas_str = json.dumps(ideas, indent=4)

output_str = f”Tweets:\n{tweets_str}\n\nThread:\n{thread_str}\n\nHook:\n{hook}\n\nExtracted Ideas:\n{ideas_str}”

with open(‘output.txt’, ‘w’) as f: f.write(output_str)