Python OpenAI API Cheat Sheet (Free)

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: https://blog.finxter.com/wp-content/uploads/2023/04/Finxter_OpenAI_Python_API.pdf

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 code.py) 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(
    model="text-davinci-003",
    prompt="What is the answer to all questions?",
    temperature=0.7,
    max_tokens=100,
    top_p=1,
    frequency_penalty=0,
    presence_penalty=0
)

print(response)

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: ๐Ÿ‘‡
openai.api_key = 'sk-XXXXXXXXXXXXXXXXXXXXXXXXXXX'

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

response = openai.Image.create(
    prompt=prompt,
    n=1,
    size="256x256",
)

print(response["data"][0]["url"])

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

https://oaidalleapiprodscus.blob.core.windows.net/private/org-CR1YqwB9GAtSsAKHpN1935Dy/user-57ZUj7285WTxwzVJdiweq6JS/img-n9aRtAjhyJMeOzZTXztvkGGD.png?st=2023-04-25T07%3A19%3A14Z&se=2023-04-25T09%3A19%3A14Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-04-25T08%3A17%3A09Z&ske=2023-04-26T08%3A17%3A09Z&sks=b&skv=2021-08-06&sig=57InZSNLylU1peJpPN8yynKvbiKBaLqhVn3l5c9oOSk%3D

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."
}

๐ŸŽ™๏ธ 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)