🐍 OpenAI with Python

Learn how to start using OpenAI with Python

Would you like to connect your software to OpenAI but you don't know how? Don't worry, here I provide you a snippet to start using OpenAI API. For this example first you will need to install the requests module:

$ pip install requests

Generate Text

In this example we will use the API for generate text, using model text-davinci-002.

import requests

def generate_text(prompt):
    api_key = "your_api_key_here"
    model = "text-davinci-002"
    completions_endpoint = "https://api.openai.com/v1/engines/{}/completions".format(model)
    
    response = requests.post(completions_endpoint,
                             headers={"Content-Type": "application/json",
                                      "Authorization": "Bearer {}".format(api_key)},
                             json={"prompt": prompt, "max_tokens": 50})
    
    if response.status_code == 200:
        completions = response.json()['choices'][0]['text']
        return completions
    else:
        return "Request failed with status code {}".format(response.status_code)

generated_text = generate_text("What is the meaning of life?")
print(generated_text)

Analyze Sentiment

Generating Images

Question Answering

Translation

Last updated