Skip to content

Instantly share code, notes, and snippets.

@laura-dietz
Created May 15, 2024 18:40
Show Gist options
  • Save laura-dietz/f0b7bc8a7f0453dbdd742805be9a5ed6 to your computer and use it in GitHub Desktop.
Save laura-dietz/f0b7bc8a7f0453dbdd742805be9a5ed6 to your computer and use it in GitHub Desktop.
Examples for how to use the ChatGPT API from python
import os
from openai import OpenAI
# 1. Must create an OpenAI account
# 2. Must generate a personalized API key at https://platform.openai.com/api-keys
# 3. Never save API keys in code, instead save as environment variable with `export OPEN_API_KEY=your_key`
if os.environ['OPENAI_API_KEY'] is None:
raise RuntimeError ("Must set environment variable \"OPENAI_API_KEY\"")
client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an assistant that completes sentences."},
{"role": "user", "content": "The weather will"},
{"role": "assistant", "content": "be variable in New England."},
{"role": "user", "content": "The sky will"}
]
)
print(completion.choices[0].message)
print(completion.usage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment