Module 5: Getting Started with OpenAI API
What is the OpenAI API?
The OpenAI API allows you to access powerful large language models like GPT-3.5 and GPT-4 via a simple HTTP-based interface.
You can use it for:
- Chatbots
- Content creation
- Text summarization
- Translation
- Code generation
- Audio transcription
- Image generation
- Embedding generation
Create an OpenAI Account
- Go to https://platform.openai.com
- Sign up using your email, Google, or GitHub.
- Navigate to https://platform.openai.com/account/api-keys
- Click “Create new secret key”
- Copy and store your key securely.
Warning
Your secret key starts with sk- and should never be shared publicly.
Install the OpenAI Python Package
Set Up Your API Key in Python
You can use your API key in two ways:
Option 1: Set directly in code (for testing only)
Option 2: Use environment variables (recommended)
Available Functionalities in openai>=1.0.0
1. Chat Completion
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain photosynthesis in simple words."}
]
)
print(response.choices[0].message.content)2. Image Generation
response = client.images.generate(
model="dall-e-3",
prompt="A futuristic city floating in the sky",
size="1024x1024",
quality="standard",
n=1
)
image_url = response.data[0].url
print(image_url)3. Embeddings
response = client.embeddings.create(
input="Machine learning is fun.",
model="text-embedding-ada-002"
)
print(response.data[0].embedding)4. Audio Transcription (Whisper)
with open("speech.mp3", "rb") as audio_file:
transcript = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
print(transcript.text)Summary
- Use
OpenAI()to create a client with your API key. - Modern usage recommends
client.chat.completions.create()for chat interactions. - You can also generate images, extract embeddings, and transcribe audio using a consistent client interface.