Step by step how to connect to OpenAI API and brief introduction.
OpenAI's API is a set of tools and services that allow developers to train and deploy AI models. The API provides access to OpenAI's vast collection of resources, including datasets, algorithms, and pretrained models. The API also allows developers to create and train their own AI models.
from IPython.display import (
HTML, display
)
import os
import dotenv as de
import openai
To install the unofficial API and libraries, just the following command for pip or anaconda:
>>> pip install openai
or
>>> conda install -c conda-forge openai
In order to connect to the OpenAI's API the developer needs access to an API key. To get one, first create an account at beta.openai.com and create a new secret key by accessing their user settings.
After creating, save this secret key somewhere safe and accessible. You won't be able to view it again through your OpenAI account. If you lose this secret key, you'll need to generate a new one. The generated key must seem like:
SECRET KEY | CREATED | LAST USED |
---|---|---|
sk-...Ksf8 | Jan 01, 2022 | Never |
To configure the API with our generated secret key, use the python command:
openai.api_key = <your key here>
In order to protect your key from explicit usage, I strongly recommend using some environment variable method or so. For this example, I'll be using dotenv and an external .env
file.
de.load_dotenv(de.find_dotenv())
API_KEY = os.environ.get("API_KEY")
openai.api_key = API_KEY
PROMPT = "What are Artificial Intelligence and Machine Learning?"
response = openai.Completion.create(
model="text-davinci-003",
prompt=PROMPT,
max_tokens=100
)
print(response["choices"][0]["text"])
Artificial Intelligence (AI) is a broad term used to describe computer systems that can perform tasks that typically require human intelligence, including visual perception, recognition, problem solving, and decision making. Machine learning is a subfield of AI that uses algorithms to learn from data and make predictions or decisions without being explicitly programmed to do so. It is based on the idea that machines can learn and refine their behavior by analyzing data, thus allowing them to improve their accuracy as they gain more data.