APIMaster.ai

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-5.4",
    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-5.4",
    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-5.4", 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-5.4",
    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-5.4",
    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-5.4", 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-5.4",
        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 Low cost
General coding, writing gpt-5.4 Best balance
Complex reasoning gpt-5.5 or o3 High capability
Batch processing gpt-4o-mini or gpt-5.4 Choose by quality and budget

Frequently Asked Questions

How do I install the OpenAI Python library? Run pip install openai. For APIMaster access, no additional package is needed—just set base_url and api_key when initializing the client.

What Python version is required for the OpenAI library? Python 3.8 or later. The async client requires Python 3.10+ for best compatibility.

How do I handle OpenAI API rate limits in Python? Use exponential backoff—catch RateLimitError and retry with increasing delays. The tenacity library simplifies this. APIMaster's routing provides additional stability.

Can I use the OpenAI Python library with Claude models? Yes—via APIMaster. Set base_url="https://apimaster.ai/v1" and use model IDs like claude-sonnet-4-6. The response format is identical to GPT responses.

How do I use async OpenAI calls in Python? Use AsyncOpenAI instead of OpenAI, and await the API calls. See the async example in the guide above.

Get OpenAI API access via APIMaster →