Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] OpenAI API – or How I Made My Python Code Intelligent
1
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.

[Image: 1f449.png] 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
Code:
Personal > View API keys
.

[Image: image-301-1024x721.png]

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

[Image: image-302-1024x569.png]

Now copy the API key to your clipboard:

[Image: image-303-1024x538.png]

Step 3: Pip Install OpenAI

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

  • Code:
    pip3 install openai

  • Code:
    pip3.11 install openai

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

[Image: image-304-1024x810.png]

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:
code.py
) and also paste your API key from Step 2 into the highlighted line (string):

Code:
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
Code:
"What is the answer to all questions?"
to customize your input prompt. The output after a few seconds will look like this:

Code:
{ "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. [Image: 1f609.png]
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: