Getting Started with the OpenAI API in Python

Create an OpenAI API key, install the SDK and call OpenAI models from Python safely.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 0 · Lesson 5 of 9 · Beginner

Getting Started with the OpenAI API in Python

Create an OpenAI API key, install the SDK and call OpenAI models from Python safely.

Most of this tutorial uses Claude for generation, but many RAG projects use OpenAI models instead, or alongside. This lesson shows how to create an OpenAI API key, install the official Python SDK, make your first request with the Responses API, stream output, create embeddings and handle errors. Everything here follows OpenAI's official Python SDK documentation.

What you will learn

  • How to create and store an OpenAI API key safely
  • How to install the openai Python package and make a first request
  • The difference between the Responses API and the Chat Completions API
  • How to stream responses, create embeddings and handle API errors
  • How to choose an OpenAI model for RAG

Prerequisites

Step 1: Create an API key

  1. Sign in to the OpenAI platform and open the API keys page in your project settings.
  2. Create a new secret key, give it a descriptive name (for example "rag-tutorial-laptop") and copy it. It is shown only once.
  3. Set a monthly budget limit in the billing settings, so a bug in a loop cannot run up a large bill.

Store the key in a .env file in your project folder, never in your code:

.env
OPENAI_API_KEY=your-key-here

Make sure .env is listed in .gitignore. If a key is ever exposed, delete it in the dashboard and create a new one.

Step 2: Install the SDK

pip install openai python-dotenv

The client reads the OPENAI_API_KEY environment variable automatically, so you do not pass the key in code.

Step 3: Your first request with the Responses API

The Responses API is OpenAI's primary interface for generating text. It accepts an input (a string or a list of messages) and optional instructions (similar to a system prompt), and the generated text is available as response.output_text.

openai_hello.py
import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                                   # loads OPENAI_API_KEY from .env
client = OpenAI()                               # reads OPENAI_API_KEY automatically
MODEL = os.getenv("OPENAI_MODEL", "gpt-6.2-sol")

response = client.responses.create(
    model=MODEL,
    instructions="You are a concise assistant for software developers.",
    input="Explain Retrieval-Augmented Generation in two sentences.",
)
print(response.output_text)
Retrieval-Augmented Generation (RAG) retrieves relevant passages from an external
knowledge source and adds them to the model's prompt. The model then answers from
that evidence instead of relying only on what it learned during training.

Your wording will differ: model output is not deterministic.

Model names

At the time of writing (November 2026), OpenAI's models page recommends gpt-6.2-astra as its flagship model, gpt-6.2-sol as a balance of intelligence and cost, and gpt-6-luna for high-volume, cost-sensitive tasks. Model names change regularly, so the examples read the model from an OPENAI_MODEL environment variable. Check the models page for current IDs and prices.

The Chat Completions API

Many existing tutorials and libraries use the older Chat Completions API, which OpenAI continues to support. It takes a list of messages with roles and returns choices:

completion = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "developer", "content": "You are a concise assistant."},
        {"role": "user", "content": "What is a vector database?"},
    ],
)
print(completion.choices[0].message.content)

For new code, prefer the Responses API. Use Chat Completions when a library or an OpenAI-compatible server (such as vLLM or Ollama's compatibility endpoint) expects it.

Step 4: A RAG-style prompt

RAG means passing retrieved text to the model with instructions to answer from it. The pattern is the same as with any provider:

context = """<source id="1">Employees get 18 days of paid leave in their first year.</source>
<source id="2">Up to 5 unused days can be carried over to the next year.</source>"""

response = client.responses.create(
    model=MODEL,
    instructions="Answer only from the sources. Cite source ids like [1]. "
                 "If the sources do not contain the answer, say you don't know.",
    input=f"{context}\n\nQuestion: Can I carry over unused leave?",
)
print(response.output_text)
Yes. You can carry over up to 5 unused days to the next year [2].

Step 5: Streaming

Pass stream=True to receive events as the model writes. Text arrives in events of type response.output_text.delta:

stream = client.responses.create(
    model=MODEL,
    input="List three benefits of RAG, one line each.",
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
print()

Step 6: Embeddings

OpenAI's embedding models turn text into vectors for semantic search. text-embedding-3-small returns 1,536 dimensions and text-embedding-3-large returns 3,072; both accept a dimensions parameter to return shorter vectors.

result = client.embeddings.create(
    model="text-embedding-3-small",
    input=["How do I reset my password?", "Steps to change your login credentials"],
)
vectors = [item.embedding for item in result.data]
print(len(vectors), len(vectors[0]))     # 2 1536

The next lessons compare OpenAI embeddings with local alternatives: Generating Embeddings with OpenAI, Ollama and Hugging Face.

Step 7: Handle errors

The SDK raises typed exceptions and retries connection errors, rate limits (429) and server errors automatically (twice by default). Catch the specific classes you can act on:

import openai

try:
    response = client.responses.create(model=MODEL, input="Hello")
    print(response.output_text)
except openai.AuthenticationError:
    print("Invalid or missing API key. Check OPENAI_API_KEY.")
except openai.RateLimitError:
    print("Rate limit or quota exceeded. Wait, or check your billing limits.")
except openai.NotFoundError:
    print(f"Model '{MODEL}' not found. Check the model name.")
except openai.APIConnectionError:
    print("Network problem: could not reach the API.")
except openai.APIStatusError as e:
    print(f"API error {e.status_code}: {e.message}")

Increase retries for batch jobs with OpenAI(max_retries=5).

Common errors and troubleshooting

ErrorCauseFix
AuthenticationError (401)Key missing, mistyped or deletedCheck that .env is loaded from the folder you run the script in
RateLimitError (429) with "insufficient_quota"No credit or budget limit reachedAdd credit or raise the project budget
NotFoundError (404) for the modelWrong or retired model ID, or no accessCopy the ID from the models page
ModuleNotFoundError: openaiPackage installed in another environmentActivate the virtual environment and reinstall
BadRequestError (400)Invalid parameter or input too longRead the error message; shorten the input

Best practices

  • Use one API key per project or environment, and set budget limits.
  • Keep the model name in configuration, not scattered through code.
  • Log the request ID (response._request_id) when reporting problems.
  • Count tokens and cost per request in production (Cost Optimization).

Key takeaways

  • Store OPENAI_API_KEY in an environment variable or a git-ignored .env file.
  • client.responses.create() generates text; read it with response.output_text.
  • client.embeddings.create() creates vectors with the text-embedding-3 models.
  • Catch typed exceptions such as RateLimitError and keep model IDs configurable.

Frequently asked questions

Should I use the Responses API or Chat Completions?

Use the Responses API for new projects. Chat Completions remains supported and is useful when working with libraries or servers that expect it.

Can I use OpenAI and Claude in the same RAG system?

Yes. Retrieval does not depend on the generation model. Many teams use one provider's embeddings and another provider's LLM. See Model-Agnostic RAG when it is available, or keep your model calls behind one small function.

Is my data used for training?

Check the provider's current data-usage and retention policies for API traffic before sending confidential documents, and choose the data controls your organisation requires.

Practice exercises

  1. Change the RAG prompt so the answer must be a bulleted list with one citation per bullet.
  2. Stream a long answer and measure the time until the first text appears.
  3. Embed five sentences and print the pairwise cosine similarities with NumPy.

Related tutorials