create request to openai in python

To create a request to OpenAI in Python, you can use the requests library to send a POST request to the OpenAI API. Here's an example of how to do it:

main.py
import requests
import json

# Set your API key
api_key = "YOUR_API_KEY"

# Set the API endpoint and headers
endpoint = "https://api.openai.com/v1/completions"
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

# Set the request body
body = {
    "model": "text-davinci-002",
    "prompt": "Write a poem about a cat",
    "max_tokens": 1024,
    "temperature": 0.7
}

# Send the request
response = requests.post(endpoint, headers=headers, data=json.dumps(body))

# Check the response status code
if response.status_code == 200:
    # Get the response text
    response_text = response.json()["choices"][0]["text"]
    print(response_text)
else:
    print(f"Error: {response.status_code}")
734 chars
32 lines

Make sure to replace YOUR_API_KEY with your actual OpenAI API key. This code sends a POST request to the OpenAI API with a prompt and returns the response text.

You can also use the openai library, which is a Python wrapper for the OpenAI API. You can install it using pip:

pip install openai
19 chars
2 lines

Here's an example of how to use the openai library:

main.py
import openai

# Set your API key
openai.api_key = "YOUR_API_KEY"

# Set the model and prompt
model = "text-davinci-002"
prompt = "Write a poem about a cat"

# Send the request
response = openai.Completion.create(model=model, prompt=prompt, max_tokens=1024, temperature=0.7)

# Get the response text
response_text = response["choices"][0]["text"]
print(response_text)
368 chars
16 lines

Note that you'll need to have an OpenAI API key to use either of these methods. You can sign up for an API key on the OpenAI website.

related categories

gistlibby LogSnag