Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
O

openai-python

> AI 编程
Open source

The official Python library for the OpenAI API

31.3K stars0 likes0 views
WebsiteGitHub

About

The official Python library for the OpenAI API

OpenAI Python API library

)

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

It is generated from our OpenAPI specification.

Documentation

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

Installation

bash
# install from PyPI
pip install openai

Usage

The full API of this library can be found in 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.

python
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.

python
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)

python
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)

python
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)

python
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

python
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):

python
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,
    }
)

X.509 workload identity (mutual TLS)

For X.509 workload identity federation, configure the client certificate and server trust on an HTTPX2 client, then pass only the identity-provider and service-account IDs to the SDK:

…

X.509 mode defaults to https://mtls.api.openai.com/v1 when neither base_url nor OPENAI_BASE_URL is set. The same configured HTTP client presents its certificate to the fixed mTLS token-exchange endpoint and to the API. Tokens are exchanged lazily, cached, and refreshed automatically. Certificate files, private keys, passwords, server trust, proxies, and rotation remain application and transport concerns.

X.509 API requests require HTTPS and must stay on the configured API origin. The effective HTTP Host authority must match that origin. Provider API-key and proxy-only headers cannot be sent to the API alongside X.509 authentication. Token exchanges do not inherit API request hooks, authentication, or cookies. Identity settings are captured when the client is constructed; create a new client to change the identity. Azure clients do not support X.509 workload identity.

For asynchronous requests, use AsyncOpenAI with DefaultAsyncHttpx2Client. See the complete sync rollout-toggle example and async rollout-toggle example, which select API-key or X.509 authentication with the application-owned OPENAI_AUTH_MODE environment variable. X.509 workload identity currently supports HTTP APIs; Realtime and WebSockets are not included.

Vision

With an image URL:

python
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:

python
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:

python
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 HTTPX2. For improved concurrency performance, you may also use aiohttp as the HTTPX2 transport.

You can enable this by installing aiohttp:

bash
# install from PyPI
pip install openai[aiohttp]

Then you can enable it by instantiating the client with http_client=DefaultAioHttpClient():

…

HTTPX2 migration

HTTPX2 is the default HTTP client. If you configure a custom HTTP client, transport, timeout, authentication handler, event hook, or request mock, see the HTTPX2 migration guide.

Streaming responses

We provide support for streaming responses using Server Side Events (SSE).

python
from openai import OpenAI

client = OpenAI()

stream = client.responses.create(
    model="gpt-5.5",
    input="Write a one-sentence bedtime story about a unicorn.",
    stream=True,
)

for event in stream:
    print(event)

The async client uses the exact same interface.

python
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI()

async def main():
    stream = await client.responses.create(
        model="gpt-5.5",
        input="Write a one-sentence bedtime story about a unicorn.",
        stream=True,
    )

    async for event in stream:
        print(event)

asyncio.run(main())

Realtime API

The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as function calling through a WebSocket connection.

Under the hood the SDK uses the websockets library to manage connections.

The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found here and a guide can be found here.

Basic text based example:

…

However the real magic of the Realtime API is handling audio inputs / outputs, see this example TUI script for a fully fledged example.

Realtime error handling

Whenever an error occurs, the Realtime API will send an error event and the connection will stay open and remain usable. This means you need to handle it yourself, as no errors are raised directly by the SDK when an error event comes in.

python
client = AsyncOpenAI()

async with client.realtime.connect(model="gpt-realtime-2") as connection:
    ...
    async for event in connection:
        if event.type == 'error':
            print(event.error.type)
            print(event.error.code)
            print(event.error.event_id)
            print(event.error.message)

Using types

Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:

  • Serializing back into JSON, model.to_json()
  • Converting to a dictionary, model.to_dict()

Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set python.analysis.typeCheckingMode to basic.

Pagination

List methods in the OpenAI API are paginated.

This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:

python
from openai import OpenAI

client = OpenAI()

all_jobs = []
# Automatically fetc

Issues· 143 open

View all issuesOpen on GitHub
  • #3777

    Blocking the event loop since 3.x ?

    bugUpdated Sep 30, 2026
  • #3561

    Aborting a streaming Responses API request drops the function_call item, breaking the next turn with 400 "No tool call found for function call output"

    bugUpdated Sep 30, 2026
  • #3071

    OpenAI Batch API returns 404 with GPT-5.x models

    bugupstreamUpdated Sep 29, 2026
  • #3966

    fix(lib): handle null and empty text in parse_text

    Updated Sep 29, 2026
  • #3063

    Response.output_text and responses.parse fail when an output_text item has text: null

    bugUpdated Sep 29, 2026
  • #3271

    AzureOpenAI/Foundry: promote x-ms-served-model header into Response.model for the Responses API (parity with OpenAI/Azure Chat Completions)

    Updated Sep 25, 2026
  • #3962

    Typo: Duplicate header name in authentication error message

    Updated Sep 25, 2026
  • #2629

    Add ``__reduce__`` method to Exception types

    Updated Sep 25, 2026
  • #3294

    Bug:- websocket_base_url derivation corrupts URLs containing http:// in query params

    upstreamUpdated Sep 25, 2026
  • #2927

    Empty OPENAI_BASE_URL prevents fallback to default API endpoint

    bugUpdated Sep 25, 2026

> Tags

Pythonopenaipython

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 30, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.