Unlock the power of AI in your Python applications with the OpenAI Python SDK. In this step‑by‑step tutorial, you’ll learn how to install, authenticate, and make your first API calls. By the end, you’ll be ready to explore text completions, chatbots, embeddings, and more—all with clear, beginner‑friendly examples.
Before diving in, ensure you have:
Open your terminal or command prompt and run:
pip install –upgrade openai |
This installs the latest OpenAI Python SDK. To verify:
python -c “import openai; print(openai.__version__)” |
You should see a version number like 0.27.0 (or newer).
Keep your API key secure. The recommended approach:
export OPENAI_API_KEY=“your_api_key_here” |
setx OPENAI_API_KEY “your_api_key_here” |
Alternatively, you can assign the key in code (less secure):
import openai openai.api_key = “your_api_key_here” |
Tip: Rotate your API keys regularly and never commit them to source control. |
Let’s translate English to French using the text‑davinci-003 model:
import os import openai
# Load API key from environment openai.api_key = os.getenv(“OPENAI_API_KEY”)
response = openai.Completion.create( model=“text-davinci-003”, prompt=“Translate to French: ‘Hello, world!'”, max_tokens=60, temperature=0.3, )
print(response.choices[0].text.strip()) |
response = openai.ChatCompletion.create( model=“gpt-3.5-turbo”, messages=[ {“role”: “system”, “content”: “You are a friendly assistant.”}, {“role”: “user”, “content”: “Tell me a joke.”}, ] ) print(response.choices[0].message.content) |
embedding = openai.Embedding.create( model=“text-embedding-ada-002”, input=“OpenAI SDK tutorial” ) print(embedding[‘data’][0][’embedding’]) |
Wrap API calls in try/except blocks and implement retries with exponential backoff:
import time from openai.error import RateLimitError, APIError for attempt in range(3): try: result = openai.Completion.create(…) break except RateLimitError: wait = 2 ** attempt print(f”Rate limit hit, retrying in {wait}s…”) time.sleep(wait) except APIError as e: print(“API error:”, e) break |
Start experimenting—build a chatbot, a summarization tool, or an AI‑powered search engine. The possibilities are endless!
You’ve now set up the OpenAI Python SDK, made your first API calls, and explored core features. Keep iterating, refine your prompts, and integrate OpenAI’s powerful models into your own Python projects. Happy coding!