docs
0
# Client Initialization
1
2
Initialize OpenAI and Azure OpenAI clients with API credentials, configuration options, and custom HTTP settings. The library provides both synchronous and asynchronous implementations for all clients.
3
4
## Capabilities
5
6
### OpenAI Client
7
8
Creates a synchronous client for making API calls to OpenAI's services.
9
10
```python { .api }
11
class OpenAI:
12
"""
13
Synchronous client for OpenAI API.
14
15
Automatically infers credentials from environment variables:
16
- api_key from OPENAI_API_KEY
17
- organization from OPENAI_ORG_ID
18
- project from OPENAI_PROJECT_ID
19
- webhook_secret from OPENAI_WEBHOOK_SECRET
20
- base_url from OPENAI_BASE_URL
21
"""
22
23
def __init__(
24
self,
25
*,
26
api_key: str | Callable[[], str] | None = None,
27
organization: str | None = None,
28
project: str | None = None,
29
webhook_secret: str | None = None,
30
base_url: str | httpx.URL | None = None,
31
websocket_base_url: str | httpx.URL | None = None,
32
timeout: float | Timeout | None | NotGiven = not_given,
33
max_retries: int = 2,
34
default_headers: Mapping[str, str] | None = None,
35
default_query: Mapping[str, object] | None = None,
36
http_client: httpx.Client | None = None,
37
_strict_response_validation: bool = False,
38
) -> None:
39
"""
40
Construct a new synchronous OpenAI client instance.
41
42
Args:
43
api_key: OpenAI API key. Can be a string or callable that returns a string.
44
If None, reads from OPENAI_API_KEY environment variable.
45
organization: OpenAI organization ID for multi-org accounts.
46
If None, reads from OPENAI_ORG_ID environment variable.
47
project: OpenAI project ID for project-scoped usage tracking.
48
If None, reads from OPENAI_PROJECT_ID environment variable.
49
webhook_secret: Secret for verifying webhook signatures.
50
If None, reads from OPENAI_WEBHOOK_SECRET environment variable.
51
base_url: Override the default API base URL (https://api.openai.com/v1).
52
If None, reads from OPENAI_BASE_URL environment variable.
53
websocket_base_url: Base URL for WebSocket connections (realtime API).
54
If None, defaults to base_url with wss:// scheme.
55
timeout: Request timeout in seconds. Can be a float or Timeout object.
56
Default is NOT_GIVEN which uses library defaults.
57
max_retries: Maximum number of retry attempts for failed requests.
58
Default is 2.
59
default_headers: Additional HTTP headers to include in all requests.
60
default_query: Additional query parameters to include in all requests.
61
http_client: Custom httpx.Client instance for advanced HTTP configuration.
62
_strict_response_validation: Enable strict API response validation.
63
Raises APIResponseValidationError if API returns invalid data.
64
65
Raises:
66
OpenAIError: If api_key is not provided and OPENAI_API_KEY is not set.
67
"""
68
```
69
70
Usage example:
71
72
```python
73
from openai import OpenAI
74
75
# Basic initialization with API key
76
client = OpenAI(api_key="sk-...")
77
78
# Using environment variable (OPENAI_API_KEY)
79
client = OpenAI()
80
81
# Advanced configuration
82
client = OpenAI(
83
api_key="sk-...",
84
organization="org-...",
85
project="proj_...",
86
timeout=30.0,
87
max_retries=3,
88
default_headers={"X-Custom-Header": "value"}
89
)
90
91
# Dynamic API key with callable
92
def get_api_key() -> str:
93
return retrieve_key_from_secure_storage()
94
95
client = OpenAI(api_key=get_api_key)
96
97
# Custom HTTP client with specific configuration
98
import httpx
99
100
http_client = httpx.Client(
101
limits=httpx.Limits(max_keepalive_connections=10),
102
proxies="http://proxy.example.com:8080"
103
)
104
client = OpenAI(
105
api_key="sk-...",
106
http_client=http_client
107
)
108
```
109
110
### Async OpenAI Client
111
112
Creates an asynchronous client for making non-blocking API calls to OpenAI's services.
113
114
```python { .api }
115
class AsyncOpenAI:
116
"""
117
Asynchronous client for OpenAI API.
118
119
Automatically infers credentials from environment variables:
120
- api_key from OPENAI_API_KEY
121
- organization from OPENAI_ORG_ID
122
- project from OPENAI_PROJECT_ID
123
- webhook_secret from OPENAI_WEBHOOK_SECRET
124
- base_url from OPENAI_BASE_URL
125
"""
126
127
def __init__(
128
self,
129
*,
130
api_key: str | Callable[[], Awaitable[str]] | None = None,
131
organization: str | None = None,
132
project: str | None = None,
133
webhook_secret: str | None = None,
134
base_url: str | httpx.URL | None = None,
135
websocket_base_url: str | httpx.URL | None = None,
136
timeout: float | Timeout | None | NotGiven = not_given,
137
max_retries: int = 2,
138
default_headers: Mapping[str, str] | None = None,
139
default_query: Mapping[str, object] | None = None,
140
http_client: httpx.AsyncClient | None = None,
141
_strict_response_validation: bool = False,
142
) -> None:
143
"""
144
Construct a new asynchronous OpenAI client instance.
145
146
Args:
147
api_key: OpenAI API key. Can be a string, sync callable, or async callable.
148
If None, reads from OPENAI_API_KEY environment variable.
149
organization: OpenAI organization ID for multi-org accounts.
150
If None, reads from OPENAI_ORG_ID environment variable.
151
project: OpenAI project ID for project-scoped usage tracking.
152
If None, reads from OPENAI_PROJECT_ID environment variable.
153
webhook_secret: Secret for verifying webhook signatures.
154
If None, reads from OPENAI_WEBHOOK_SECRET environment variable.
155
base_url: Override the default API base URL (https://api.openai.com/v1).
156
If None, reads from OPENAI_BASE_URL environment variable.
157
websocket_base_url: Base URL for WebSocket connections (realtime API).
158
If None, defaults to base_url with wss:// scheme.
159
timeout: Request timeout in seconds. Can be a float or Timeout object.
160
Default is NOT_GIVEN which uses library defaults.
161
max_retries: Maximum number of retry attempts for failed requests.
162
Default is 2.
163
default_headers: Additional HTTP headers to include in all requests.
164
default_query: Additional query parameters to include in all requests.
165
http_client: Custom httpx.AsyncClient instance for advanced HTTP configuration.
166
_strict_response_validation: Enable strict API response validation.
167
Raises APIResponseValidationError if API returns invalid data.
168
169
Raises:
170
OpenAIError: If api_key is not provided and OPENAI_API_KEY is not set.
171
"""
172
```
173
174
Usage example:
175
176
```python
177
import asyncio
178
from openai import AsyncOpenAI
179
180
async def main():
181
# Basic initialization
182
client = AsyncOpenAI(api_key="sk-...")
183
184
# Using environment variable
185
client = AsyncOpenAI()
186
187
# Make async API calls
188
response = await client.chat.completions.create(
189
model="gpt-4",
190
messages=[{"role": "user", "content": "Hello!"}]
191
)
192
print(response.choices[0].message.content)
193
194
# Custom async HTTP client
195
import httpx
196
197
async with httpx.AsyncClient(
198
limits=httpx.Limits(max_keepalive_connections=10)
199
) as http_client:
200
client = AsyncOpenAI(
201
api_key="sk-...",
202
http_client=http_client
203
)
204
response = await client.chat.completions.create(
205
model="gpt-4",
206
messages=[{"role": "user", "content": "Hello!"}]
207
)
208
209
asyncio.run(main())
210
```
211
212
### Azure OpenAI Client
213
214
Creates a synchronous client for Azure OpenAI Service with Azure-specific authentication and configuration.
215
216
```python { .api }
217
class AzureOpenAI:
218
"""
219
Synchronous client for Azure OpenAI Service.
220
221
Automatically infers credentials from environment variables:
222
- api_key from AZURE_OPENAI_API_KEY
223
- azure_ad_token from AZURE_OPENAI_AD_TOKEN
224
- azure_endpoint from AZURE_OPENAI_ENDPOINT
225
- api_version from OPENAI_API_VERSION
226
- organization from OPENAI_ORG_ID
227
- project from OPENAI_PROJECT_ID
228
"""
229
230
def __init__(
231
self,
232
*,
233
api_version: str | None = None,
234
azure_endpoint: str | None = None,
235
azure_deployment: str | None = None,
236
api_key: str | Callable[[], str] | None = None,
237
azure_ad_token: str | None = None,
238
azure_ad_token_provider: Callable[[], str] | None = None,
239
organization: str | None = None,
240
project: str | None = None,
241
webhook_secret: str | None = None,
242
websocket_base_url: str | httpx.URL | None = None,
243
base_url: str | None = None,
244
timeout: float | Timeout | None | NotGiven = not_given,
245
max_retries: int = 2,
246
default_headers: Mapping[str, str] | None = None,
247
default_query: Mapping[str, object] | None = None,
248
http_client: httpx.Client | None = None,
249
_strict_response_validation: bool = False,
250
) -> None:
251
"""
252
Construct a new synchronous Azure OpenAI client instance.
253
254
Authentication is mutually exclusive - provide only ONE of:
255
- api_key
256
- azure_ad_token
257
- azure_ad_token_provider
258
259
Args:
260
api_version: Azure OpenAI API version (e.g., "2024-02-15-preview").
261
If None, reads from OPENAI_API_VERSION environment variable.
262
azure_endpoint: Azure resource endpoint (e.g., "https://example.azure.openai.com/").
263
If None, reads from AZURE_OPENAI_ENDPOINT environment variable.
264
azure_deployment: Model deployment name. When provided with azure_endpoint,
265
sets base URL to include /deployments/{azure_deployment}.
266
Not supported with Assistants APIs.
267
api_key: Azure OpenAI API key.
268
If None, reads from AZURE_OPENAI_API_KEY environment variable.
269
azure_ad_token: Azure Active Directory (Entra ID) access token.
270
If None, reads from AZURE_OPENAI_AD_TOKEN environment variable.
271
azure_ad_token_provider: Function returning Azure AD token, invoked per request.
272
Useful for automatic token refresh.
273
organization: OpenAI organization ID (optional for Azure).
274
If None, reads from OPENAI_ORG_ID environment variable.
275
project: OpenAI project ID (optional for Azure).
276
If None, reads from OPENAI_PROJECT_ID environment variable.
277
webhook_secret: Secret for verifying webhook signatures.
278
websocket_base_url: Base URL for WebSocket connections.
279
base_url: Override the base URL (alternative to azure_endpoint).
280
timeout: Request timeout in seconds.
281
Default is NOT_GIVEN which uses library defaults.
282
max_retries: Maximum number of retry attempts for failed requests.
283
Default is 2.
284
default_headers: Additional HTTP headers to include in all requests.
285
default_query: Additional query parameters to include in all requests.
286
http_client: Custom httpx.Client instance for advanced HTTP configuration.
287
_strict_response_validation: Enable strict API response validation.
288
289
Raises:
290
OpenAIError: If no authentication credentials are provided.
291
MutuallyExclusiveAuthError: If multiple authentication methods are provided.
292
"""
293
```
294
295
Usage example:
296
297
```python
298
from openai import AzureOpenAI
299
300
# Using API key authentication
301
client = AzureOpenAI(
302
api_key="your-azure-api-key",
303
azure_endpoint="https://your-resource.azure.openai.com/",
304
api_version="2024-02-15-preview"
305
)
306
307
# Using environment variables
308
# Set AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, OPENAI_API_VERSION
309
client = AzureOpenAI()
310
311
# With deployment name (for model-specific endpoints)
312
client = AzureOpenAI(
313
api_key="your-azure-api-key",
314
azure_endpoint="https://your-resource.azure.openai.com/",
315
azure_deployment="gpt-4-deployment",
316
api_version="2024-02-15-preview"
317
)
318
319
# Using Azure AD (Entra ID) authentication
320
client = AzureOpenAI(
321
azure_ad_token="your-azure-ad-token",
322
azure_endpoint="https://your-resource.azure.openai.com/",
323
api_version="2024-02-15-preview"
324
)
325
326
# Using Azure AD with automatic token refresh
327
def get_azure_ad_token() -> str:
328
# Implement token retrieval/refresh logic
329
from azure.identity import DefaultAzureCredential
330
credential = DefaultAzureCredential()
331
token = credential.get_token("https://cognitiveservices.azure.com/.default")
332
return token.token
333
334
client = AzureOpenAI(
335
azure_ad_token_provider=get_azure_ad_token,
336
azure_endpoint="https://your-resource.azure.openai.com/",
337
api_version="2024-02-15-preview"
338
)
339
340
# Make API calls (same interface as OpenAI)
341
response = client.chat.completions.create(
342
model="gpt-4", # Uses deployment if azure_deployment was set
343
messages=[{"role": "user", "content": "Hello!"}]
344
)
345
```
346
347
### Async Azure OpenAI Client
348
349
Creates an asynchronous client for Azure OpenAI Service.
350
351
```python { .api }
352
class AsyncAzureOpenAI:
353
"""
354
Asynchronous client for Azure OpenAI Service.
355
356
Automatically infers credentials from environment variables:
357
- api_key from AZURE_OPENAI_API_KEY
358
- azure_ad_token from AZURE_OPENAI_AD_TOKEN
359
- azure_endpoint from AZURE_OPENAI_ENDPOINT
360
- api_version from OPENAI_API_VERSION
361
- organization from OPENAI_ORG_ID
362
- project from OPENAI_PROJECT_ID
363
"""
364
365
def __init__(
366
self,
367
*,
368
azure_endpoint: str | None = None,
369
azure_deployment: str | None = None,
370
api_version: str | None = None,
371
api_key: str | Callable[[], Awaitable[str]] | None = None,
372
azure_ad_token: str | None = None,
373
azure_ad_token_provider: Callable[[], str | Awaitable[str]] | None = None,
374
organization: str | None = None,
375
project: str | None = None,
376
webhook_secret: str | None = None,
377
base_url: str | None = None,
378
websocket_base_url: str | httpx.URL | None = None,
379
timeout: float | Timeout | None | NotGiven = not_given,
380
max_retries: int = 2,
381
default_headers: Mapping[str, str] | None = None,
382
default_query: Mapping[str, object] | None = None,
383
http_client: httpx.AsyncClient | None = None,
384
_strict_response_validation: bool = False,
385
) -> None:
386
"""
387
Construct a new asynchronous Azure OpenAI client instance.
388
389
Authentication is mutually exclusive - provide only ONE of:
390
- api_key
391
- azure_ad_token
392
- azure_ad_token_provider
393
394
Args:
395
api_version: Azure OpenAI API version (e.g., "2024-02-15-preview").
396
If None, reads from OPENAI_API_VERSION environment variable.
397
azure_endpoint: Azure resource endpoint (e.g., "https://example.azure.openai.com/").
398
If None, reads from AZURE_OPENAI_ENDPOINT environment variable.
399
azure_deployment: Model deployment name. When provided with azure_endpoint,
400
sets base URL to include /deployments/{azure_deployment}.
401
Not supported with Assistants APIs.
402
api_key: Azure OpenAI API key. Can be a string, sync callable, or async callable.
403
If None, reads from AZURE_OPENAI_API_KEY environment variable.
404
azure_ad_token: Azure Active Directory (Entra ID) access token.
405
If None, reads from AZURE_OPENAI_AD_TOKEN environment variable.
406
azure_ad_token_provider: Function returning Azure AD token (sync or async),
407
invoked per request. Useful for automatic token refresh.
408
organization: OpenAI organization ID (optional for Azure).
409
If None, reads from OPENAI_ORG_ID environment variable.
410
project: OpenAI project ID (optional for Azure).
411
If None, reads from OPENAI_PROJECT_ID environment variable.
412
webhook_secret: Secret for verifying webhook signatures.
413
websocket_base_url: Base URL for WebSocket connections.
414
base_url: Override the base URL (alternative to azure_endpoint).
415
timeout: Request timeout in seconds.
416
Default is NOT_GIVEN which uses library defaults.
417
max_retries: Maximum number of retry attempts for failed requests.
418
Default is 2.
419
default_headers: Additional HTTP headers to include in all requests.
420
default_query: Additional query parameters to include in all requests.
421
http_client: Custom httpx.AsyncClient instance for advanced HTTP configuration.
422
_strict_response_validation: Enable strict API response validation.
423
424
Raises:
425
OpenAIError: If no authentication credentials are provided.
426
MutuallyExclusiveAuthError: If multiple authentication methods are provided.
427
"""
428
```
429
430
Usage example:
431
432
```python
433
import asyncio
434
from openai import AsyncAzureOpenAI
435
436
async def main():
437
# Basic async Azure client
438
client = AsyncAzureOpenAI(
439
api_key="your-azure-api-key",
440
azure_endpoint="https://your-resource.azure.openai.com/",
441
api_version="2024-02-15-preview"
442
)
443
444
# Async Azure AD token provider
445
async def get_azure_ad_token() -> str:
446
# Implement async token retrieval
447
from azure.identity.aio import DefaultAzureCredential
448
credential = DefaultAzureCredential()
449
token = await credential.get_token("https://cognitiveservices.azure.com/.default")
450
return token.token
451
452
client = AsyncAzureOpenAI(
453
azure_ad_token_provider=get_azure_ad_token,
454
azure_endpoint="https://your-resource.azure.openai.com/",
455
api_version="2024-02-15-preview"
456
)
457
458
# Make async API calls
459
response = await client.chat.completions.create(
460
model="gpt-4",
461
messages=[{"role": "user", "content": "Hello!"}]
462
)
463
print(response.choices[0].message.content)
464
465
asyncio.run(main())
466
```
467
468
## Types
469
470
```python { .api }
471
from typing import Callable, Mapping, Awaitable
472
import httpx
473
474
# Timeout configuration
475
Timeout = float | httpx.Timeout
476
477
# Sentinel for omitted parameters
478
class NotGiven:
479
"""Sentinel value indicating a parameter was not provided."""
480
481
NOT_GIVEN: NotGiven
482
483
# Azure AD token providers
484
AzureADTokenProvider = Callable[[], str]
485
AsyncAzureADTokenProvider = Callable[[], str | Awaitable[str]]
486
```
487
488
## Client Utility Methods
489
490
All clients provide utility methods for creating client copies with modified configuration and accessing raw HTTP responses.
491
492
### Copy Client with Modified Options
493
494
Create a new client instance reusing the same options with optional overrides.
495
496
```python { .api }
497
def copy(
498
self,
499
*,
500
api_key: str | Callable[[], str] | None = None,
501
organization: str | None = None,
502
project: str | None = None,
503
webhook_secret: str | None = None,
504
websocket_base_url: str | httpx.URL | None = None,
505
base_url: str | httpx.URL | None = None,
506
timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
507
http_client: httpx.Client | None = None,
508
max_retries: int | Omit = omit,
509
default_headers: Mapping[str, str] | None = None,
510
set_default_headers: Mapping[str, str] | None = None,
511
default_query: Mapping[str, object] | None = None,
512
set_default_query: Mapping[str, object] | None = None,
513
) -> OpenAI:
514
"""
515
Create a new client instance re-using the same options with optional overriding.
516
517
Args:
518
api_key: Override API key
519
organization: Override organization
520
project: Override project
521
webhook_secret: Override webhook secret
522
websocket_base_url: Override WebSocket base URL
523
base_url: Override base URL
524
timeout: Override timeout
525
http_client: Override HTTP client
526
max_retries: Override max retries
527
default_headers: Merge these headers with existing default headers
528
set_default_headers: Replace all default headers with these
529
default_query: Merge these query params with existing defaults
530
set_default_query: Replace all default query params with these
531
532
Returns:
533
New client instance with merged configuration.
534
535
Note:
536
- default_headers and set_default_headers are mutually exclusive
537
- default_query and set_default_query are mutually exclusive
538
"""
539
540
# Alias for nicer inline usage
541
with_options = copy
542
```
543
544
Usage example:
545
546
```python
547
from openai import OpenAI
548
549
# Create base client
550
client = OpenAI(api_key="sk-...", timeout=30)
551
552
# Create a copy with longer timeout for specific operations
553
slow_client = client.copy(timeout=120)
554
555
# Or use the with_options alias for inline usage
556
response = client.with_options(timeout=60).chat.completions.create(
557
model="gpt-4",
558
messages=[{"role": "user", "content": "Complex query..."}]
559
)
560
561
# Create a copy with additional headers
562
custom_client = client.copy(
563
default_headers={"X-Request-ID": "abc123"}
564
)
565
566
# Replace all headers
567
new_client = client.copy(
568
set_default_headers={"X-Custom": "value"}
569
)
570
```
571
572
### Access Raw HTTP Responses
573
574
Access the underlying `httpx.Response` object for any API call.
575
576
```python { .api }
577
@property
578
def with_raw_response(self) -> OpenAIWithRawResponse:
579
"""
580
Property that returns a client wrapper providing access to raw HTTP responses.
581
582
All API methods on this wrapper return a response object with:
583
- parsed: The normally returned parsed response object
584
- http_response: The raw httpx.Response object
585
"""
586
```
587
588
Usage example:
589
590
```python
591
from openai import OpenAI
592
593
client = OpenAI()
594
595
# Access raw HTTP response
596
response = client.with_raw_response.chat.completions.create(
597
model="gpt-4",
598
messages=[{"role": "user", "content": "Hello!"}]
599
)
600
601
# Access parsed response
602
completion = response.parsed
603
print(completion.choices[0].message.content)
604
605
# Access raw HTTP response details
606
http_response = response.http_response
607
print(f"Status: {http_response.status_code}")
608
print(f"Headers: {dict(http_response.headers)}")
609
print(f"Request ID: {http_response.headers.get('x-request-id')}")
610
```
611
612
### Stream HTTP Responses
613
614
Stream responses without loading them into memory, useful for large responses like file downloads.
615
616
```python { .api }
617
@property
618
def with_streaming_response(self) -> OpenAIWithStreamedResponse:
619
"""
620
Property that returns a client wrapper for streaming HTTP responses.
621
622
Instead of loading the entire response into memory, returns a response
623
object that can be iterated over in chunks.
624
"""
625
```
626
627
Usage example:
628
629
```python
630
from openai import OpenAI
631
632
client = OpenAI()
633
634
# Stream file content without loading into memory
635
response = client.with_streaming_response.files.content("file-abc123")
636
637
# Stream chunks
638
for chunk in response.iter_bytes(chunk_size=8192):
639
process_chunk(chunk)
640
641
# Or write directly to file
642
with open("output.txt", "wb") as f:
643
for chunk in response.iter_bytes():
644
f.write(chunk)
645
646
# Also works with other endpoints
647
response = client.with_streaming_response.audio.speech.create(
648
model="tts-1",
649
voice="alloy",
650
input="Hello world"
651
)
652
653
with open("speech.mp3", "wb") as f:
654
for chunk in response.iter_bytes():
655
f.write(chunk)
656
```
657
658
Async clients have the same methods:
659
660
```python
661
from openai import AsyncOpenAI
662
663
client = AsyncOpenAI()
664
665
# Raw response (async)
666
response = await client.with_raw_response.chat.completions.create(
667
model="gpt-4",
668
messages=[{"role": "user", "content": "Hello!"}]
669
)
670
671
# Streaming response (async)
672
response = await client.with_streaming_response.files.content("file-abc123")
673
async for chunk in response.iter_bytes():
674
process_chunk(chunk)
675
676
# Copy/with_options (async)
677
slow_client = client.copy(timeout=120)
678
```
679
680
## Client Properties
681
682
All clients (OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI) expose the following resource properties for accessing API endpoints:
683
684
```python { .api }
685
# Core resources
686
client.chat # Chat completions
687
client.completions # Legacy text completions
688
client.embeddings # Vector embeddings
689
client.audio # Audio transcription, translation, TTS
690
client.images # Image generation
691
client.videos # Video generation
692
client.files # File management
693
client.models # Model information
694
client.moderations # Content moderation
695
client.fine_tuning # Fine-tuning jobs
696
client.batches # Batch processing
697
client.vector_stores # Vector stores
698
client.uploads # Multipart uploads
699
client.responses # Responses API
700
client.realtime # Realtime API
701
client.webhooks # Webhook verification
702
client.beta # Beta features (Assistants, Threads, etc.)
703
client.conversations # Conversations API
704
client.evals # Evaluations
705
client.containers # Containers
706
```
707
708
## Error Handling
709
710
All client initialization errors inherit from OpenAIError:
711
712
```python { .api }
713
class OpenAIError(Exception):
714
"""Base exception for all OpenAI errors."""
715
716
class MutuallyExclusiveAuthError(OpenAIError):
717
"""Raised when multiple authentication methods are provided to Azure clients."""
718
```
719
720
Common initialization errors:
721
722
```python
723
from openai import OpenAI, OpenAIError, AzureOpenAI, MutuallyExclusiveAuthError
724
725
# Handle missing API key
726
try:
727
client = OpenAI() # No api_key and OPENAI_API_KEY not set
728
except OpenAIError as e:
729
print(f"Missing API key: {e}")
730
731
# Handle Azure authentication conflicts
732
try:
733
client = AzureOpenAI(
734
api_key="key",
735
azure_ad_token="token" # Can't provide both
736
)
737
except MutuallyExclusiveAuthError as e:
738
print(f"Auth conflict: {e}")
739
```
740