OpenAI API – or How I Made My Python Code Intelligent

5/5 - (1 vote)

In this quick tutorial, I’ll show you how I integrated ChatGPT intelligence into an app I’m currently working on. It’s really simple, so let’s get started!

Step 1: Create a Paid Account with OpenAI

I’m not affiliated with OpenAI in any way. However, to use it, you need to create a (paid) account to create an API key that you’ll need in order to connect ChatGPT with your code.

👉 Click here to create an account and connect it with your credit card

I use it a lot and pay only a couple of cents per day so it’s really inexpensive for now.

Step 2: Get Your API Key

Open the link https://beta.openai.com/playground and navigate to Personal > View API keys.

Now, click the + Create new secret key button to create a new API key:

Now copy the API key to your clipboard:

Step 3: Pip Install OpenAI

Use your version of pip to install the openai module by running a command similar to the following (depending on your local environment):

  • pip install openai
  • pip3 install openai
  • pip3.11 install openai

As I’ve installed Python 3.9 at the point of writing, I used pip3.9 install openai:

You can check your Python version here and learn how to install a module here.

Step 4: Python Code to Access OpenAI

Copy and paste the following code into a Python script (e.g., named code.py) and also paste your API key from Step 2 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. 😉