How do I call ChatGPT API with python code?

Hi!
I have been trying to find code that call the API but nothing seems to work. Do any of you know code I can use?

Hi!

  1. go to the docs
  2. look for the api you want
  3. click curl
  4. go to chatgpt: “can you turn this curl into a native python thing that I can run in jupyter?”
import requests
import json
import os

openai_api_key = # put yout api key here
if openai_api_key is None:
    raise ValueError("OpenAI API key is not set in environment variables.")

url = "https://api.openai.com/v1/chat/completions"

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {openai_api_key}"
}

data = {
    "model": "gpt-3.5-turbo",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "Hello!"
        }
    ]
}

response = requests.post(url, headers=headers, json=data)

# Check if the request was successful
if response.status_code == 200:
    print("Response from OpenAI:", response.json())
    print('\n')
    print(response.json()['choices'][0]['message']['content'])
else:
    print("Error:", response.status_code, response.text)
2 Likes

Better. Set environment variable OPENAI_API_KEY to your key, and at a command shell get the latest library:

pip install --upgrade openai

Then that code above certainly is longer than a demonstration in frugality…

#!pip install --upgrade openai  # uncomment for Jupyter installing
import openai as oa;cl=oa.OpenAI();cc=cl.chat.completions.create(
messages=[
{"role": "system", "content": "You are FunnyBot"},
{"role": "assistant", "content": "relevant: farts exert force"}, # RAG
{"role": "user", "content": "Do penguin farts propel?"}
], stream=True, max_tokens=420, top_p=.69, model="gpt-3.5-turbo")
print(*(ck.choices[0].delta.content or "" for ck in cc), sep="", end="")