OpenAI API Python Tutorial 2026 | APIMaster.ai
Complete OpenAI API Python tutorial—install the SDK, make chat completions, stream responses, use function calling, and build async apps. Works with APIMaster.ai for discounted access.
OpenAI API Python Tutorial
This tutorial covers using the OpenAI API with Python from installation through advanced use cases. All examples work with APIMaster.ai—just change the api_key and base_url.
Installation
pip install openai
Requires Python 3.8+. The openai package is OpenAI's official Python SDK (version 1.x).
Initial Setup
from openai import OpenAI
client = OpenAI(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai/v1",
)
Or use environment variables (recommended):
export OPENAI_API_KEY="YOUR_APIMASTER_KEY"
export OPENAI_BASE_URL="https://apimaster.ai/v1"
from openai import OpenAI
client = OpenAI() # reads env vars automatically
Basic Chat Completions
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a Python expert."},
{"role": "user", "content": "What is a generator in Python?"},
],
)
print(response.choices[0].message.content)
print(f"Tokens used: {response.usage.total_tokens}")
Streaming Responses
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a binary search in Python."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
print()
Multi-Turn Conversations
messages = [
{"role": "system", "content": "You are a helpful coding assistant."}
]
def send(user_text):
messages.append({"role": "user", "content": user_text})
resp = client.chat.completions.create(model="gpt-4o", messages=messages)
reply = resp.choices[0].message.content
messages.append({"role": "assistant", "content": reply})
return reply
print(send("Explain list comprehensions."))
print(send("Give me a harder example."))
Structured Output (JSON Mode)
Force the model to return valid JSON:
import json
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": "Extract the name, email, and company from: 'Contact Jane Smith (jane@acme.com) at Acme Corp.'",
}
],
response_format={"type": "json_object"},
)
data = json.loads(response.choices[0].message.content)
print(data) # {"name": "Jane Smith", "email": "jane@acme.com", "company": "Acme Corp"}
Function Calling (Tool Use)
import json
tools = [
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Get the current stock price for a ticker symbol",
"parameters": {
"type": "object",
"properties": {
"ticker": {"type": "string", "description": "Stock ticker, e.g. AAPL"},
},
"required": ["ticker"],
},
},
}
]
messages = [{"role": "user", "content": "What's the current price of Apple stock?"}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process tool call
if response.choices[0].finish_reason == "tool_calls":
tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
print(f"Calling {tool_call.function.name} with {args}")
# Simulate function result
result = {"ticker": args["ticker"], "price": 189.50}
# Send result back
messages.append(response.choices[0].message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(model="gpt-4o", messages=messages)
print(final.choices[0].message.content)
Embeddings
response = client.embeddings.create(
model="text-embedding-3-small",
input=["OpenAI API Python tutorial", "Machine learning basics"],
)
embeddings = [item.embedding for item in response.data]
print(f"Embedding dimensions: {len(embeddings[0])}")
Async Usage
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai/v1",
)
async def generate(prompt: str) -> str:
resp = await client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}],
)
return resp.choices[0].message.content
async def main():
# Run 5 requests concurrently
prompts = [f"Explain concept #{i}" for i in range(5)]
results = await asyncio.gather(*[generate(p) for p in prompts])
for r in results:
print(r[:100])
asyncio.run(main())
Error Handling
from openai import OpenAI, AuthenticationError, RateLimitError, APIError
import time
def safe_call(client, **kwargs):
for attempt in range(3):
try:
return client.chat.completions.create(**kwargs)
except AuthenticationError:
raise # Don't retry auth errors
except RateLimitError:
time.sleep(2 ** attempt)
except APIError as e:
if e.status_code >= 500:
time.sleep(1)
else:
raise
raise RuntimeError("Max retries exceeded")
Model Selection Guide
| Task | Model | Why |
|---|---|---|
| Summarization, classification | gpt-4o-mini | Cheapest, fast |
| General coding, writing | gpt-4o | Good balance |
| Complex reasoning | gpt-5 or o3 | Best accuracy |
| Batch processing | gpt-4o-mini | Cost-effective |