- Spec files
pypi-openai
Describes: pkg:pypi/openai@1.106.x
- Description
- Official Python library for the OpenAI API providing chat completions, embeddings, audio, images, and more
- Author
- tessl
- Last updated
client-setup.md docs/
1# Client Setup and Configuration23Client initialization, authentication, configuration options, and Azure integration for both synchronous and asynchronous usage patterns.45## Capabilities67### Basic Client Initialization89Create OpenAI client instances with API key authentication and basic configuration options.1011```python { .api }12class OpenAI:13def __init__(14self,15*,16api_key: str | None = None,17organization: str | None = None,18project: str | None = None,19base_url: str | httpx.URL | None = None,20timeout: Union[float, Timeout, None] = None,21max_retries: int = 2,22default_headers: Mapping[str, str] | None = None,23default_query: Mapping[str, object] | None = None,24http_client: httpx.Client | None = None25): ...26```2728Usage example:2930```python31import openai32from openai import OpenAI3334# Basic initialization with API key35client = OpenAI(api_key="your-api-key-here")3637# With organization and project38client = OpenAI(39api_key="your-api-key-here",40organization="org-your-org-id",41project="proj-your-project-id"42)4344# With custom configuration45client = OpenAI(46api_key="your-api-key-here",47base_url="https://api.openai.com/v1",48timeout=30.0,49max_retries=3,50default_headers={"User-Agent": "MyApp/1.0"}51)52```5354### Async Client Initialization5556Create asynchronous OpenAI client instances for concurrent operations and async/await usage patterns.5758```python { .api }59class AsyncOpenAI:60def __init__(61self,62*,63api_key: str | Callable[[], Awaitable[str]] | None = None,64organization: str | None = None,65project: str | None = None,66base_url: str | httpx.URL | None = None,67timeout: Union[float, Timeout, None] = None,68max_retries: int = 2,69default_headers: Mapping[str, str] | None = None,70default_query: Mapping[str, object] | None = None,71http_client: httpx.AsyncClient | None = None72): ...73```7475Usage example:7677```python78import asyncio79from openai import AsyncOpenAI8081async def main():82# Basic async client83client = AsyncOpenAI(api_key="your-api-key-here")8485# Multiple concurrent requests86tasks = []87for i in range(5):88task = client.chat.completions.create(89model="gpt-3.5-turbo",90messages=[{"role": "user", "content": f"Hello {i}"}]91)92tasks.append(task)9394responses = await asyncio.gather(*tasks)9596await client.close() # Clean up resources9798asyncio.run(main())99```100101### Azure OpenAI Integration102103Azure-specific client configuration for OpenAI services hosted on Microsoft Azure with Azure Active Directory authentication.104105```python { .api }106class AzureOpenAI:107def __init__(108self,109*,110azure_endpoint: str | None = None,111azure_deployment: str | None = None,112api_version: str | None = None,113api_key: str | Callable[[], str] | None = None,114azure_ad_token: str | None = None,115azure_ad_token_provider: AzureADTokenProvider | None = None,116organization: str | None = None,117project: str | None = None,118base_url: str | httpx.URL | None = None,119timeout: Union[float, Timeout, None] = None,120max_retries: int = 2,121default_headers: Mapping[str, str] | None = None,122default_query: Mapping[str, object] | None = None,123http_client: httpx.Client | None = None124): ...125126class AsyncAzureOpenAI:127def __init__(128self,129*,130azure_endpoint: str | None = None,131azure_deployment: str | None = None,132api_version: str | None = None,133api_key: str | Callable[[], Awaitable[str]] | None = None,134azure_ad_token: str | None = None,135azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,136organization: str | None = None,137project: str | None = None,138base_url: str | httpx.URL | None = None,139timeout: Union[float, Timeout, None] = None,140max_retries: int = 2,141default_headers: Mapping[str, str] | None = None,142default_query: Mapping[str, object] | None = None,143http_client: httpx.AsyncClient | None = None144): ...145```146147Usage examples:148149```python150from openai import AzureOpenAI151152# Basic Azure configuration with API key153client = AzureOpenAI(154azure_endpoint="https://your-endpoint.openai.azure.com/",155api_key="your-azure-api-key",156api_version="2024-02-15-preview"157)158159# With Azure AD token160client = AzureOpenAI(161azure_endpoint="https://your-endpoint.openai.azure.com/",162azure_ad_token="your-azure-ad-token",163api_version="2024-02-15-preview"164)165166# With Azure AD token provider167def get_azure_ad_token():168# Your token acquisition logic here169return "token-from-azure-ad"170171client = AzureOpenAI(172azure_endpoint="https://your-endpoint.openai.azure.com/",173azure_ad_token_provider=get_azure_ad_token,174api_version="2024-02-15-preview"175)176177# With specific deployment178client = AzureOpenAI(179azure_endpoint="https://your-endpoint.openai.azure.com/",180azure_deployment="your-deployment-name",181api_key="your-azure-api-key",182api_version="2024-02-15-preview"183)184```185186### Environment-Based Configuration187188Automatic configuration using environment variables for convenient deployment and credential management.189190The library automatically reads configuration from environment variables:191192- `OPENAI_API_KEY` → `api_key`193- `OPENAI_ORG_ID` → `organization`194- `OPENAI_PROJECT_ID` → `project`195- `OPENAI_BASE_URL` → `base_url`196- `AZURE_OPENAI_ENDPOINT` → `azure_endpoint`197- `AZURE_OPENAI_API_KEY` → Azure API key198- `OPENAI_API_VERSION` → `api_version`199200Usage example:201202```python203import os204from openai import OpenAI, AzureOpenAI205206# Set environment variables207os.environ["OPENAI_API_KEY"] = "your-api-key"208os.environ["OPENAI_ORG_ID"] = "your-org-id"209210# Client automatically uses environment variables211client = OpenAI() # No need to pass api_key explicitly212213# Azure with environment variables214os.environ["AZURE_OPENAI_ENDPOINT"] = "https://your-endpoint.openai.azure.com/"215os.environ["AZURE_OPENAI_API_KEY"] = "your-azure-key"216217azure_client = AzureOpenAI() # Automatically configured218```219220### Module-Level Configuration221222Direct API access through module-level configuration for simple usage patterns without explicit client instantiation.223224```python { .api }225# Module-level configuration variables226api_key: str | None = None227organization: str | None = None228project: str | None = None229base_url: str | None = None230timeout: float | None = None231max_retries: int = 2232default_headers: dict[str, str] | None = None233```234235Usage example:236237```python238import openai239240# Configure at module level241openai.api_key = "your-api-key"242openai.organization = "your-org-id"243244# Direct API access without client instantiation245response = openai.chat.completions.create(246model="gpt-3.5-turbo",247messages=[{"role": "user", "content": "Hello!"}]248)249250# Other APIs work similarly251embeddings = openai.embeddings.create(252model="text-embedding-ada-002",253input="Text to embed"254)255```256257### Client Configuration Options258259Advanced configuration options for timeout, retries, HTTP behavior, and custom headers.260261```python { .api }262class Timeout:263def __init__(264self,265total: float | None = None,266connect: float | None = None,267read: float | None = None,268write: float | None = None,269pool: float | None = None270): ...271```272273Usage examples:274275```python276from openai import OpenAI, Timeout277import httpx278279# Custom timeout configuration280timeout = Timeout(281total=60.0, # Total timeout for the request282connect=10.0, # Connection timeout283read=30.0, # Read timeout284write=10.0 # Write timeout285)286287client = OpenAI(288api_key="your-api-key",289timeout=timeout,290max_retries=5,291default_headers={292"User-Agent": "MyApplication/1.0",293"X-Custom-Header": "custom-value"294}295)296297# Custom HTTP client configuration298http_client = httpx.Client(299limits=httpx.Limits(300max_connections=100,301max_keepalive_connections=20302),303proxies="http://proxy.example.com:8080"304)305306client = OpenAI(307api_key="your-api-key",308http_client=http_client309)310311# Custom base URL for OpenAI-compatible APIs312client = OpenAI(313api_key="your-api-key",314base_url="https://api.example.com/v1"315)316```317318### Client Methods and Properties319320Client manipulation methods and response wrapper access for advanced usage patterns.321322```python { .api }323class OpenAI:324def copy(self, **kwargs) -> "OpenAI": ...325def with_options(self, **kwargs) -> "OpenAI": ...326327@property328def with_raw_response(self) -> "OpenAIWithRawResponse": ...329330@property331def with_streaming_response(self) -> "OpenAIWithStreamedResponse": ...332```333334Usage examples:335336```python337from openai import OpenAI338339client = OpenAI(api_key="your-api-key")340341# Create client copy with different configuration342client_with_timeout = client.copy(timeout=30.0)343344# Access raw HTTP responses345raw_client = client.with_raw_response346raw_response = raw_client.chat.completions.create(347model="gpt-3.5-turbo",348messages=[{"role": "user", "content": "Hello!"}]349)350351print(f"Status: {raw_response.status_code}")352print(f"Headers: {raw_response.headers}")353parsed_response = raw_response.parse()354355# Access streaming responses356streaming_client = client.with_streaming_response357stream_response = streaming_client.chat.completions.create(358model="gpt-3.5-turbo",359messages=[{"role": "user", "content": "Hello!"}],360stream=True361)362363for chunk in stream_response:364if chunk.choices[0].delta.content:365print(chunk.choices[0].delta.content, end="")366```367368## Types369370### Configuration Types371372```python { .api }373AzureADTokenProvider = Callable[[], str]374AsyncAzureADTokenProvider = Callable[[], str | Awaitable[str]]375376class Timeout:377total: float | None378connect: float | None379read: float | None380write: float | None381pool: float | None382383RequestOptions = TypedDict('RequestOptions', {384'extra_headers': NotRequired[Headers],385'extra_query': NotRequired[Query],386'extra_body': NotRequired[Body],387'timeout': NotRequired[float | httpx.Timeout | None],388}, total=False)389```390391### Exception Types392393```python { .api }394class MutuallyExclusiveAuthError(OpenAIError):395"""Raised when multiple Azure authentication methods are provided"""396```397398### Constants399400```python { .api }401DEFAULT_TIMEOUT: float = 600.0402DEFAULT_MAX_RETRIES: int = 2403DEFAULT_CONNECTION_LIMITS: dict = {404"max_connections": 1000,405"max_keepalive_connections": 100406}407```