RepoOpenAIOpenAIpublished Oct 25, 2020seen 5d

openai/openai-python

Python

Open original ↗

Captured source

source ↗
published Oct 25, 2020seen 5dcaptured 8hhttp 200method plain

openai/openai-python

Description: The official Python library for the OpenAI API

Language: Python

License: Apache-2.0

Stars: 30961

Forks: 4832

Open issues: 524

Created: 2020-10-25T23:23:54Z

Pushed: 2026-06-10T16:09:43Z

Default branch: main

Fork: no

Archived: no

README:

OpenAI Python API library

The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.9+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

It is generated from our OpenAPI specification with Stainless.

Documentation

The REST API documentation can be found on platform.openai.com. The full API of this library can be found in [api.md](api.md).

Installation

# install from PyPI
pip install openai

Usage

The full API of this library can be found in [api.md](api.md).

The primary API for interacting with OpenAI models is the Responses API. You can generate text from the model with the code below.

import os
from openai import OpenAI

client = OpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)

response = client.responses.create(
model="gpt-5.5",
instructions="You are a coding assistant that talks like a pirate.",
input="How do I check if a Python object is an instance of a class?",
)

print(response.output_text)

The previous standard (supported indefinitely) for generating text is the Chat Completions API. You can use that API to generate text from the model with the code below.

from openai import OpenAI

client = OpenAI()

completion = client.chat.completions.create(
model="gpt-5.5",
messages=[
{"role": "developer", "content": "Talk like a pirate."},
{
"role": "user",
"content": "How do I check if a Python object is an instance of a class?",
},
],
)

print(completion.choices[0].message.content)

While you can provide an api_key keyword argument, we recommend using python-dotenv to add OPENAI_API_KEY="My API Key" to your .env file so that your API key is not stored in source control. Get an API key here.

Workload Identity Authentication

For secure, automated environments like cloud-managed Kubernetes, Azure, and Google Cloud Platform, you can use workload identity authentication with short-lived tokens from cloud identity providers instead of long-lived API keys.

Kubernetes (service account tokens)

from openai import OpenAI
from openai.auth import k8s_service_account_token_provider

client = OpenAI(
workload_identity={
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": k8s_service_account_token_provider(
"/var/run/secrets/kubernetes.io/serviceaccount/token"
),
},
)

response = client.chat.completions.create(
model="gpt-5.5",
messages=[{"role": "user", "content": "Hello!"}],
)

Azure (managed identity)

from openai import OpenAI
from openai.auth import azure_managed_identity_token_provider

client = OpenAI(
workload_identity={
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": azure_managed_identity_token_provider(
resource="https://management.azure.com/",
),
},
)

Google Cloud Platform (compute engine metadata)

from openai import OpenAI
from openai.auth import gcp_id_token_provider

client = OpenAI(
workload_identity={
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": gcp_id_token_provider(audience="https://api.openai.com/v1"),
},
)

Custom subject token provider

from openai import OpenAI

def get_custom_token() -> str:
return "your-jwt-token"

client = OpenAI(
workload_identity={
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": {
"token_type": "jwt",
"get_token": get_custom_token,
},
}
)

You can also customize the token refresh buffer (default is 1200 seconds (20 minutes) before expiration):

from openai import OpenAI
from openai.auth import k8s_service_account_token_provider

client = OpenAI(
workload_identity={
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": k8s_service_account_token_provider("/var/token"),
"refresh_buffer_seconds": 120.0,
}
)

Vision

With an image URL:

prompt = "What is in this image?"
img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg"

response = client.responses.create(
model="gpt-5.5",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{"type": "input_image", "image_url": f"{img_url}"},
],
}
],
)

With the image as a base64 encoded string:

import base64
from openai import OpenAI

client = OpenAI()

prompt = "What is in this image?"
with open("path/to/image.png", "rb") as image_file:
b64_image = base64.b64encode(image_file.read()).decode("utf-8")

response = client.responses.create(
model="gpt-5.5",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"},
],
}
],
)

Async usage

Simply import AsyncOpenAI instead of OpenAI and use await with each API call:

import os
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)

async def main() -> None:
response = await client.responses.create(
model="gpt-5.5", input="Explain disestablishmentarianism to a smart five year old."
)
print(response.output_text)

asyncio.run(main())

Functionality between the synchronous and asynchronous clients is otherwise identical.

With aiohttp

By default, the async client uses httpx for HTTP requests. However, for improved concurrency performance you may also use aiohttp as the HTTP backend.

You can enable this by installing aiohttp:

# install from PyPI
pip install openai[aiohttp]

Then you can enable it by instantiating the client with…

Excerpt shown — open the source for the full document.