What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Integrate Python with OpenAI’s cloud API using the official openai package: install the SDK, set an OPENAI_API_KEY environment variable, create an OpenAI client, and send a request with the Responses API. This connects your Python application to OpenAI models; it does not connect to the ChatGPT desktop app.

What you need to connect Python to OpenAI

  • Python 3.10 or later. The official OpenAI Python library describes itself as providing access to the OpenAI REST API from Python 3.10+ applications.
  • An OpenAI API key created in the OpenAI dashboard. API access and billing are separate from using the ChatGPT app.
  • The official openai Python package, installed in the environment where your script runs.

For a new integration, the SDK documentation identifies the Responses API as its primary interface. Chat Completions remains documented for existing applications, but its message format and capabilities differ, so choose based on your application’s needs and model availability.

Install the SDK and make your first request

  1. Install the package in your active Python environment:
    pip install openai
  2. Create an API key in the OpenAI dashboard. Set it in the environment rather than embedding it in your Python file. On macOS or Linux, for example:
    export OPENAI_API_KEY="your_api_key_here"

    In Windows, set the environment variable through your shell or system environment settings before launching Python.

  3. Save this as example.py, replacing <current-model> with a model available to your account:
    from openai import OpenAI
    
    client = OpenAI()  # reads OPENAI_API_KEY from the environment
    response = client.responses.create(
        model="<current-model>",
        input="Explain how Python decorators work in one paragraph.",
    )
    print(response.output_text)
  4. Run the script from the same environment where the SDK and API key are available:
    python example.py

The result is printed from response.output_text. The SDK also supports passing an explicit api_key to OpenAI, but environment-based configuration avoids placing the credential in source code. For local development that needs a .env file, the SDK documentation describes using python-dotenv; ensure that file is excluded from source control.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep the API key out of your code and repository

Do not commit an API key to Git or include it in a script, notebook, public issue, or client-side application. Anyone who obtains the key may use the associated API account. Read it from an environment variable, and store production credentials in the secrets mechanism provided by your deployment platform. If a key is exposed, revoke it and replace it.

Choose the API pattern that fits the application

For a new Python project, begin with client.responses.create(...). Responses supports a broader set of tools and multimodal inputs than the legacy message-based pattern. If an existing application uses Chat Completions, keep its current integration where appropriate or plan a deliberate migration rather than changing endpoints without checking how conversation state, inputs, and tool workflows are represented.

Before deployment, confirm that the model name you intend to use is available to your account and supports the capabilities your application needs. Model availability can change; the placeholder in the example is intentionally not a fixed model recommendation.

Use asynchronous requests when your application is asynchronous

In an async application, use AsyncOpenAI and await the request instead of making a synchronous call that blocks the event loop:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import asyncio
from openai import AsyncOpenAI

async def main():
    client = AsyncOpenAI()
    response = await client.responses.create(
        model="<current-model>",
        input="Explain how Python decorators work in one paragraph.",
    )
    print(response.output_text)

asyncio.run(main())

Use this pattern when the surrounding framework or workload benefits from async I/O; a regular OpenAI client is simpler for ordinary scripts.

Stream output as it is generated

Set stream=True to receive events incrementally rather than waiting for the complete response. The SDK supports synchronous iteration and asynchronous iteration over streamed events. A minimal synchronous pattern is:

from openai import OpenAI

client = OpenAI()
stream = client.responses.create(
    model="<current-model>",
    input="Explain how Python decorators work in one paragraph.",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)

Handle the stream’s completion and error events as appropriate for your application; do not assume every event contains text.

Add tools or application-defined functions

Built-in tools such as web search and file search can extend a basic request. Function calling lets a model request that your application run a function; the model does not execute your Python code itself. Your program receives the requested function and arguments, validates them, runs only permitted operations, and returns the result to the model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For function arguments, OpenAI’s guidance says strict: true constrains generated arguments to the supplied schema when that schema uses the supported JSON Schema subset and meets strict-mode requirements. Strict schema adherence does not replace application-level authorization, validation of business rules, or safeguards around consequential actions.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle API failures and support diagnostics

Production code should distinguish expected API errors from unexpected failures. The SDK documents typed exceptions for common HTTP status categories:

Status Meaning to check
401 Authentication failed; check that the key exists, is valid, and is being loaded by the running process.
403 The request is not permitted; check account permissions and access to the requested capability.
404 The requested resource or endpoint was not found; check the model name and request target.
422 The request failed validation; inspect input fields and schema requirements.
429 The request hit a rate limit; use appropriate retry handling and respect any retry guidance.
500+ A server-side failure occurred; handle transient errors without assuming the request succeeded.

Capture the request ID associated with failed calls and include it when contacting support. Avoid logging API keys or sensitive prompt content. The API reference covers authentication, request schemas, streaming events, errors, rate limits, and request IDs.

Common setup problems

  • Authentication error: confirm that OPENAI_API_KEY is set in the shell or service process that actually runs Python. A variable set in one terminal may not be available to another process.
  • Module not found: install openai using the same Python environment or virtual environment used to run the script.
  • Model or permission error: verify the model name and account access; do not assume every model or tool is enabled for every account.
  • Unexpected response format: check the endpoint and SDK documentation for the API pattern in use. Responses and Chat Completions are not interchangeable in every detail.

Official references

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.