Open AI API Automation with Linux Cron Job

Open AI API Automation with Linux Cron Job

Generate catchy marketing tag lines using text completion prediction in 4 steps.

Jan 2, 2023ยท

4 min read

Play this article

Objectives ๐Ÿš€

  • Introduction to Cron for automating Linux tasks.

  • Use Open AI API for text completion predictions.

Prerequisites ๐ŸŽข

  1. Linux OS on the user's system.

  2. Root or sudo privileges for the system user.

  3. Basic ability to use the command line interface.

  4. Cron is often already pre-installed in your Linux system. Install cron using sudo apt install cron if it is not installed.

  5. A user account on Open AI with access to API secret keys.

What is a cron job? ๐Ÿšง

Cron is a popular Linux tool used for workload automation. Using Cron, a user can schedule Linux tasks that will run automatically after the specific date/time or interval defined during the job set-up.

Cron jobs are created as shell scripts or commands defined in a crontab file. The cron daemon runs continually as a background service to monitor the crontab files and execute them based on the preset schedule. Every minute, Cron examines all stored crontabs and sees if any command needs to be executed in the current minute.

Setting up a Cron Job โ›”

1. Create a Task for Automated Execution

Pull the task code from the remote repo in GitHub. Follow the steps in the file to run the job defined in the file.

A Python script is used to query the Open AI API for text completion prediction. A request to the API generates three marketing tagline messages that are related to a specified word and updates the response as a new line in a text file output.txt.

import openai
from datetime import datetime
from dotenv import load_dotenv

import os

openai.api_key = os.environ.get('OPENAI_API_KEY')

def generate_message():
    word = "love"
    response = openai.Completion.create(
    return response

def generate_prompt(word):
    return """Suggest three word and a marketing message.

Word: happy
Message: Act the way you want to feel, Do not Be Afraid To Be Happy, Happiness Goes Where Happiness Is
Word: tall
Message: Practice safety at a height, The height of quality, We go to great heights for you
Word: {}

result = generate_message()
text = result.choices[0]['text']

def write_to_file(filename, output):
    with open(filename, 'a') as file:
        time = str(
        file.write(time + ' ' + output + '\n')

write_to_file('output.txt', text)

2. Check for Active Cron Jobs Running

List all cron jobs that have been scheduled by the current user.

 crontab -l

3. Open the crontab File for Editing

Open a configuration file called a crontab (cron table). This opens using the default editor for your system. If you are opening the crontab for the first time, you may be asked to select your default editor.

 crontab -e

4. Add a Cron job in the crontab

Include the line below to the opened crontab file. This job changes to the project directory, activates a virtual environment and runs the file every minute.

* * * * * cd /Users/uffamodey/projects/open_ai_cron_job ; source bin/activate ; python3

Save and exit the editor.

Use crontab -l to confirm that the cron job is running.

Task Review ๐Ÿ†

The crontab file specifies the intervals at which Cron should run the commands. The commands are separated using semi-colons.

The first five arguments represent the execution time. The sixth argument is the command to be executed.

[minute] [hour] [day of month] [month] [day of week] [command]
FieldAllowed values
day of month1-31
month1-12 (or names: JAN - DEC)
day of week0-6 (or names: SUN - SAT)
Special field valueDescriptionExample
AsteriskAn asterisk represents every allowed value (first to last).* (run every hour, month, etc.)

Conclusion โœ…

This tutorial showcase how a Cron job may be set up on a Linux machine to automatically run a Python script every minute. The Python script contains a function that generates catchy marketing taglines that relates to a specified word using Open AI text completion prediction API. The output of the function is updated as a new line of a text file.

Further Reading ๐Ÿ“™

Did you find this article valuable?

Support Uffa Modey by becoming a sponsor. Any amount is appreciated!