Python OpenAI API Cheat Sheet (Free)

5/5 - (12 votes)

You can click on the image or the link below to download your version of the Finxter Python OpenAI API Cheat Sheet for free (PDF format): πŸ‘‡

πŸ”’ Download Link:

For more free cheat sheets and daily programming and tech emails on prompting, coding, artificial intelligence, and blockchain engineering, check out our free email newsletter and download our other cheat sheets here: πŸ‘‡

Getting Started

You can install the Python OpenAI library by following our tutorial on the Finxter blog or by using pip in your command line or terminal (shell):

Basic installation command: πŸ‘‡
pip install openai

Alternative for Python 3: πŸ‘‡
pip3 install openai

βœ… Recommended: Getting Started with OpenAI’s Python API

Your First Python-Based Prompt With Output

Copy and paste the following code into a Python script (e.g., named and also paste your API key into the highlighted line (string):

import os
import openai

openai.api_key = "<copy your secret API key here>"

response = openai.Completion.create(
    prompt="What is the answer to all questions?",


You can modify the other highlighted line "What is the answer to all questions?" to customize your input prompt. The output after a few seconds will look like this:

  "choices": [
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": "\n\nThere is no one answer to all questions as each question has its own unique answer."
  "created": 1674579571,
  "id": "cmpl-6cGvr0TM2PGsExeyG3NEx43CrNwSx",
  "model": "text-davinci-003",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 19,
    "prompt_tokens": 8,
    "total_tokens": 27

Unfortunately, it couldn’t figure out the answer 42. πŸ˜‰

Generating Images Programmatically with DALLΒ·E

To generate an image with DALLΒ·E copy&paste the following code and replace your API key and the string description of the image to be generated (prompt):

import os
import openai

# Your API Key Here: πŸ‘‡

# Your Image Prompt Here: πŸ‘‡
prompt = "An oil painting of a dancing robot in the style of Monet"

response = openai.Image.create(


The output is a URL from where you can download the image:

To learn more, visit my full tutorial on the Finxter blog:

βœ… Recommended: Python OpenAI Generate Image with DALLΒ·E

Getting Started with OpenAI’s Speech Recognition API

The transcriptions endpoint takes as input the audio file you want to transcribe and the desired output file format for the transcription of the audio. OpenAI currently supports multiple input and output file formats.

To transcribe audio, you can use the following Python code:

import openai
audio_file = open("/path/to/file/my_audio.mp3", "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)

If you’re an avid reader of the Finxter blog, you know the vital role of Python one-liners. With OpenAI’s Whisper you can transcribe an audio or video file in a single line of Python code!

import openai;print(openai.Audio.transcribe("whisper-1", open("godfather.mp3", "rb")))

Fantastic! β™₯️

By default, the response type will be JSON, with the raw text included:

  "text": "I'm gonna make him an offer he can't refuse."
OpenAI’s Python 🐍 Speech-to-Text API Made Easy

πŸŽ™οΈ Recommended: OpenAI’s Speech-to-Text API: A Comprehensive Guide

OpenAI Python API Input Arguments

The OpenAI Python API allows you to interact with the OpenAI models, such as GPT-4, for tasks like text completion, translation, and more. Here’s a list of some common input arguments you can pass to the API, along with explanations:

  1. model: The name of the model you want to use, e.g., ‘gpt-4.0-turbo’. This specifies which version of the model you want to interact with.
  2. prompt: The input text that you want to provide to the model. This can be a question, a sentence, or any other text you want the model to process or complete.
  3. max_tokens: The maximum number of tokens (words or word pieces) you want the model to generate in its response. A lower value will result in shorter responses, while a higher value allows for more detailed and longer responses.
  4. temperature: A value between 0 and 1 that controls the randomness of the model’s output. A higher value (e.g., 0.8) will result in more random and creative responses, while a lower value (e.g., 0.2) will produce more focused and deterministic responses.
  5. top_p: A value between 0 and 1 that controls the sampling strategy, also known as nucleus sampling. The model will only consider a subset of tokens whose cumulative probability exceeds top_p. This can be useful for controlling the diversity of generated text.
  6. n: The number of independent completions you want the model to generate for the given input. If you set this to a value greater than 1, the API will return multiple completions, which can be useful for exploring a range of possible responses.
  7. stream: A boolean value (True or False) that specifies whether to use streaming mode for generating results. When set to True, the API will return results incrementally as they become available, which can be useful for real-time applications.
  8. echo: A boolean value (True or False) that controls whether the input prompt should be included in the output. When set to True, the output will include both the input prompt and the model-generated completion.
  9. stop: A string or list of strings that specifies the stopping sequence(s) for the model. When the model encounters any of these sequences, it will stop generating further text.
  10. presence_penalty: A value that controls how much the model should penalize new tokens based on the presence of similar tokens in the prompt. This can be useful for controlling repetition in the generated text.
  11. frequency_penalty: A value that controls how much the model should penalize tokens based on their frequency in the training data. This can be useful for encouraging the model to generate more novel or uncommon phrases.

These input arguments can be combined and customized to achieve the desired behavior when interacting with the OpenAI Python API.

βœ… Recommended: Free ChatGPT Prompting Cheat Sheet (PDF)