Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Openai Openai python OpenAI Client Init

From Leeroopedia
Knowledge Sources
Domains API_Client, SDK_Infrastructure
Last Updated 2026-02-15 00:00 GMT

Overview

Concrete tool for establishing authenticated API connections provided by the OpenAI Python SDK.

Description

The OpenAI and AsyncOpenAI classes are the primary entry points for all OpenAI API interactions. They extend SyncAPIClient and AsyncAPIClient respectively, configuring an httpx-based HTTP client with authentication, retry logic, and typed resource properties. All API resources (chat, audio, images, responses, embeddings, fine-tuning, etc.) are accessible as properties on the client instance.

Usage

Import and instantiate at the start of any script or application that calls the OpenAI API. Use OpenAI for synchronous code and AsyncOpenAI for async/await patterns. The Realtime API requires AsyncOpenAI.

Code Reference

Source Location

  • Repository: openai-python
  • File: src/openai/_client.py
  • Lines: L86-441 (OpenAI), L443-798 (AsyncOpenAI)

Signature

class OpenAI(SyncAPIClient):
    def __init__(
        self,
        *,
        api_key: str | None | Callable[[], str] = None,
        organization: str | None = None,
        project: str | None = None,
        base_url: str | httpx.URL | None = None,
        websocket_base_url: str | httpx.URL | None = None,
        timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
        max_retries: int = DEFAULT_MAX_RETRIES,
        default_headers: Mapping[str, str] | None = None,
        default_query: Mapping[str, object] | None = None,
        http_client: httpx.Client | None = None,
        _strict_response_validation: bool = False,
    ) -> None:
        """
        Args:
            api_key: API key or env OPENAI_API_KEY. Can be a callable returning the key.
            organization: Organization ID or env OPENAI_ORG_ID.
            project: Project ID or env OPENAI_PROJECT_ID.
            base_url: Custom base URL for the API (overrides default).
            websocket_base_url: Custom WebSocket base URL for Realtime API.
            timeout: Request timeout (default NOT_GIVEN uses httpx defaults).
            max_retries: Maximum number of retries on failure (default 2).
            default_headers: Additional headers sent with every request.
            default_query: Additional query parameters for every request.
            http_client: Pre-configured httpx.Client instance.
        """
class AsyncOpenAI(AsyncAPIClient):
    def __init__(
        self,
        *,
        api_key: str | None | Callable[[], str] | Callable[[], Awaitable[str]] = None,
        organization: str | None = None,
        project: str | None = None,
        base_url: str | httpx.URL | None = None,
        websocket_base_url: str | httpx.URL | None = None,
        timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
        max_retries: int = DEFAULT_MAX_RETRIES,
        default_headers: Mapping[str, str] | None = None,
        default_query: Mapping[str, object] | None = None,
        http_client: httpx.AsyncClient | None = None,
        _strict_response_validation: bool = False,
    ) -> None:
        """
        Same as OpenAI but with async http_client and async-capable api_key callable.
        """

Import

from openai import OpenAI, AsyncOpenAI

I/O Contract

Inputs

Name Type Required Description
api_key None | Callable No API key; falls back to OPENAI_API_KEY env var
organization None No Organization ID; falls back to OPENAI_ORG_ID env var
project None No Project ID; falls back to OPENAI_PROJECT_ID env var
base_url httpx.URL | None No Custom API base URL
websocket_base_url httpx.URL | None No Custom WebSocket URL for Realtime API
timeout Timeout | None No Request timeout configuration
max_retries int No Max retries on transient failures (default 2)
http_client None No Pre-configured HTTP client

Outputs

Name Type Description
client OpenAI or AsyncOpenAI Configured client with resource accessors
client.chat Chat resource Access to chat completions API
client.responses Responses resource Access to Responses API
client.audio Audio resource Access to TTS, transcription, translation
client.images Images resource Access to image generation/editing
client.embeddings Embeddings resource Access to embedding generation
client.fine_tuning FineTuning resource Access to fine-tuning jobs
client.files Files resource Access to file management
client.beta.realtime Realtime resource Access to Realtime WebSocket API

Usage Examples

Basic Synchronous Client

from openai import OpenAI

# Uses OPENAI_API_KEY environment variable
client = OpenAI()

# With explicit API key
client = OpenAI(api_key="sk-...")

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

Async Client

import asyncio
from openai import AsyncOpenAI

async def main():
    client = AsyncOpenAI()
    response = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(response.choices[0].message.content)

asyncio.run(main())

Custom Configuration

from openai import OpenAI

client = OpenAI(
    api_key="sk-...",
    organization="org-...",
    project="proj-...",
    max_retries=5,
    timeout=30.0,
)

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment