Repository navigation
Expand file tree
/
Copy path_client.py
More file actions
1926 lines (1484 loc) · 67.7 KB
/
Copy path_client.py
File metadata and controls
1926 lines (1484 loc) · 67.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File generated from our OpenAPI spec by Castiron. See CONTRIBUTING.md for details.
from __future__ import annotations, annotations as annotations
import os as os
from typing import (
TYPE_CHECKING as TYPE_CHECKING,
Any as Any,
Mapping as Mapping,
Callable as Callable,
Iterable as Iterable,
Awaitable as Awaitable,
cast as cast,
)
from typing_extensions import Self as Self, Unpack as Unpack, override as override
import httpx2 as httpx2
from . import _exceptions as _exceptions
from ._qs import Querystring as Querystring
from .auth import (
WorkloadIdentity as WorkloadIdentity,
WorkloadIdentityAuth as WorkloadIdentityAuth,
X509WorkloadIdentity as X509WorkloadIdentity,
)
from ._types import (
Omit as Omit,
Query as Query,
Headers as Headers,
Timeout as Timeout,
NotGiven as NotGiven,
Transport as Transport,
ProxiesTypes as ProxiesTypes,
HttpxSendArgs as HttpxSendArgs,
RequestOptions as RequestOptions,
omit as omit,
not_given as not_given,
)
from ._utils import (
is_given as is_given,
is_mapping as is_mapping,
is_mapping_t as is_mapping_t,
get_async_library as get_async_library,
)
from ._compat import cached_property as cached_property
from ._httpx2 import (
normalize_httpx_url as normalize_httpx_url,
is_httpx2_sync_client as is_httpx2_sync_client,
is_httpx2_async_client as is_httpx2_async_client,
)
from ._models import SecurityOptions as SecurityOptions, FinalRequestOptions as FinalRequestOptions
from ._version import __version__ as __version__
from ._provider import (
_Provider as _Provider,
_provider_name as _provider_name,
_ProviderRuntime as _ProviderRuntime,
_configure_provider as _configure_provider,
)
from ._streaming import Stream as Stream, AsyncStream as AsyncStream
from .auth._x509 import (
MTLS_API_BASE_URL as MTLS_API_BASE_URL,
SyncX509WorkloadIdentityAuth as SyncX509WorkloadIdentityAuth,
AsyncX509WorkloadIdentityAuth as AsyncX509WorkloadIdentityAuth,
validate_x509_api_url as validate_x509_api_url,
is_x509_workload_identity as is_x509_workload_identity,
x509_data_residency_base_url as x509_data_residency_base_url,
validate_x509_api_credentials as validate_x509_api_credentials,
x509_safe_environment_headers as x509_safe_environment_headers,
validate_x509_request_authority as validate_x509_request_authority,
)
from ._exceptions import OpenAIError as OpenAIError, APIStatusError as APIStatusError
from ._base_client import (
DEFAULT_MAX_RETRIES as DEFAULT_MAX_RETRIES,
SyncAPIClient as SyncAPIClient,
AsyncAPIClient as AsyncAPIClient,
_merge_mappings as _merge_mappings,
)
from ._data_residency import DataResidency as DataResidency, resolve_data_residency as resolve_data_residency
from .lib._client_auth import _has_header as _has_header, _has_omitted_header as _has_omitted_header
if TYPE_CHECKING:
from .resources import (
beta as _beta,
chat as _chat,
live as _live,
admin as _admin,
audio as _audio,
evals as _evals,
files as _files,
images as _images,
models as _models,
safety as _safety,
skills as _skills,
videos as _videos,
batches as _batches,
uploads as _uploads,
realtime as _realtime,
webhooks as _webhooks,
decisions as _decisions,
responses as _responses,
containers as _containers,
embeddings as _embeddings,
completions as _completions,
fine_tuning as _fine_tuning,
moderations as _moderations,
conversations as _conversations,
vector_stores as _vector_stores,
content_provenance_checks as _content_provenance_checks,
)
from .resources.files import Files, AsyncFiles
from .resources.images import Images, AsyncImages
from .resources.models import Models, AsyncModels
from .resources.videos import Videos, AsyncVideos
from .resources.batches import Batches, AsyncBatches
from .resources.beta.beta import Beta, AsyncBeta
from .resources.chat.chat import Chat, AsyncChat
from .resources.decisions import Decisions, AsyncDecisions
from .resources.live.live import Live, AsyncLive
from .resources.embeddings import Embeddings, AsyncEmbeddings
from .resources.admin.admin import Admin, AsyncAdmin
from .resources.audio.audio import Audio, AsyncAudio
from .resources.completions import Completions, AsyncCompletions
from .resources.evals.evals import Evals, AsyncEvals
from .resources.moderations import Moderations, AsyncModerations
from .resources.safety.safety import Safety, AsyncSafety
from .resources.skills.skills import Skills, AsyncSkills
from .resources.uploads.uploads import Uploads, AsyncUploads
from .resources.realtime.realtime import Realtime, AsyncRealtime
from .resources.webhooks.webhooks import Webhooks, AsyncWebhooks
from .resources.responses.responses import Responses, AsyncResponses
from .resources.containers.containers import Containers, AsyncContainers
from .resources.fine_tuning.fine_tuning import FineTuning, AsyncFineTuning
from .resources.content_provenance_checks import ContentProvenanceChecks, AsyncContentProvenanceChecks
from .resources.conversations.conversations import Conversations, AsyncConversations
from .resources.vector_stores.vector_stores import VectorStores, AsyncVectorStores
__all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "OpenAI", "AsyncOpenAI", "Client", "AsyncClient"]
WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER = "workload-identity-auth"
class OpenAI(SyncAPIClient):
workload_identity: WorkloadIdentity | X509WorkloadIdentity | None
_workload_identity_auth: WorkloadIdentityAuth | SyncX509WorkloadIdentityAuth | None
_provider: _Provider | None
_provider_runtime: _ProviderRuntime | None
_base_url_was_default: bool
_data_residency: DataResidency | None
_ambient_authorizations: frozenset[str]
_api_key_provider: Callable[[], str] | None
# client options
api_key: str
admin_api_key: str | None
organization: str | None
project: str | None
webhook_secret: str | None
websocket_base_url: str | httpx2.URL | None
"""Base URL for WebSocket connections.
If not specified, the default base URL will be used, with 'wss://' replacing the
'http://' or 'https://' scheme. For example: 'http://example.com' becomes
'wss://example.com'
"""
@property
@override
def base_url(
self,
) -> httpx2.URL:
from .lib._client_auth import syncbase_url
return syncbase_url(self)
@base_url.setter
def base_url(
self,
url: httpx2.URL | str,
) -> None:
from .lib._client_auth import syncbase_url_set
return syncbase_url_set(self, url)
def _send_with_auth_retry(
self,
request: httpx2.Request,
*,
stream: bool,
retried: bool = False,
**kwargs: Unpack[HttpxSendArgs],
) -> httpx2.Response:
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import sync_send_with_auth_retry
return sync_send_with_auth_retry(
_runtime_cast(_RuntimeAny, super()).__thisclass__, self, request, stream=stream, retried=retried, **kwargs
)
@override
def _send_request(
self,
request: httpx2.Request,
*,
stream: bool,
**kwargs: Unpack[HttpxSendArgs],
) -> httpx2.Response:
from .lib._client_auth import sync_send_request
return sync_send_request(self, request, stream=stream, **kwargs)
@property
@override
def auth_headers(
self,
) -> dict[str, str]:
from .lib._client_auth import syncauth_headers
return syncauth_headers(self)
@override
def _prepare_options(
self,
options: FinalRequestOptions,
) -> FinalRequestOptions:
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import sync_prepare_options
return sync_prepare_options(_runtime_cast(_RuntimeAny, super()).__thisclass__, self, options)
@override
def _prepare_request(
self,
request: httpx2.Request,
) -> None:
from .lib._client_auth import sync_prepare_request
return sync_prepare_request(self, request)
@override
def _custom_auth(
self,
security: SecurityOptions,
) -> httpx2.Auth | None:
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import sync_custom_auth
return sync_custom_auth(_runtime_cast(_RuntimeAny, super()).__thisclass__, self, security)
def _refresh_api_key(
self,
) -> str:
from .lib._client_auth import sync_refresh_api_key
return sync_refresh_api_key(self)
def _websocket_query_params_fallback(self, url: httpx2.URL, extra_query: Query) -> httpx2.QueryParams:
# Remove replaced logical defaults before encoding nested query values.
overridden = dict.fromkeys(extra_query, omit)
overridden_prefixes = tuple(f"{key}[" for key in overridden)
defaults = _merge_mappings(self.default_query, overridden)
params = httpx2.QueryParams(self.qs.stringify(cast(Any, defaults))).merge(url.params)
params = httpx2.QueryParams(
[
(key, value)
for key, value in params.multi_items()
if key not in overridden and not key.startswith(overridden_prefixes)
]
)
if isinstance(extra_query, httpx2.QueryParams):
return params.merge(extra_query)
# Per-call None and sequences retain blank values and repeated keys;
# defaults continue to use the REST encoder's configured array format.
values = _merge_mappings({}, extra_query)
for key, value in values.items():
if value is None:
values[key] = ""
elif isinstance(value, (list, tuple)):
values[key] = ["" if item is None else item for item in cast(Iterable[object], value)]
return params.merge(self.qs.stringify(cast(Any, values), array_format="repeat"))
def __init__(
self,
*,
api_key: str | Callable[[], str] | None = None,
admin_api_key: str | None = None,
workload_identity: WorkloadIdentity | X509WorkloadIdentity | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
provider: _Provider | None = None,
base_url: str | httpx2.URL | None | NotGiven = not_given,
data_residency: DataResidency | None = None,
websocket_base_url: str | httpx2.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: httpx2.Client | None = None,
_strict_response_validation: bool = False,
_enforce_credentials: bool = True,
) -> None:
"""Construct a new synchronous OpenAI client instance.
This automatically infers the following arguments from their corresponding environment variables if they are not provided:
- `api_key` from `OPENAI_API_KEY`
- `admin_api_key` from `OPENAI_ADMIN_KEY`
- `organization` from `OPENAI_ORG_ID`
- `project` from `OPENAI_PROJECT_ID`
- `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
When `provider` is supplied, authentication and the base URL are configured by that provider instead.
`data_residency` selects an OpenAI regional endpoint and cannot be combined with
`base_url`, `websocket_base_url`, or `provider`.
"""
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import sync__init__
return sync__init__(
_runtime_cast(_RuntimeAny, super()).__thisclass__,
self,
api_key=api_key,
admin_api_key=admin_api_key,
workload_identity=workload_identity,
organization=organization,
project=project,
webhook_secret=webhook_secret,
provider=provider,
base_url=base_url,
data_residency=data_residency,
websocket_base_url=websocket_base_url,
timeout=timeout,
max_retries=max_retries,
default_headers=default_headers,
default_query=default_query,
http_client=http_client,
_strict_response_validation=_strict_response_validation,
_enforce_credentials=_enforce_credentials,
)
@cached_property
def decisions(self) -> Decisions:
from .resources.decisions import Decisions
return Decisions(self)
@cached_property
def completions(self) -> Completions:
"""
Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
"""
from .resources.completions import Completions
return Completions(self)
@cached_property
def chat(self) -> Chat:
from .resources.chat import Chat
return Chat(self)
@cached_property
def embeddings(self) -> Embeddings:
"""
Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
"""
from .resources.embeddings import Embeddings
return Embeddings(self)
@cached_property
def files(self) -> Files:
"""
Files are used to upload documents that can be used with features like Assistants and Fine-tuning.
"""
from .resources.files import Files
return Files(self)
@cached_property
def images(self) -> Images:
"""Given a prompt and/or an input image, the model will generate a new image."""
from .resources.images import Images
return Images(self)
@cached_property
def content_provenance_checks(self) -> ContentProvenanceChecks:
from .resources.content_provenance_checks import ContentProvenanceChecks
return ContentProvenanceChecks(self)
@cached_property
def audio(self) -> Audio:
from .resources.audio import Audio
return Audio(self)
@cached_property
def moderations(self) -> Moderations:
"""
Given text and/or image inputs, classifies if those inputs are potentially harmful.
"""
from .resources.moderations import Moderations
return Moderations(self)
@cached_property
def models(self) -> Models:
"""List and describe the various models available in the API."""
from .resources.models import Models
return Models(self)
@cached_property
def fine_tuning(self) -> FineTuning:
from .resources.fine_tuning import FineTuning
return FineTuning(self)
@cached_property
def vector_stores(self) -> VectorStores:
from .resources.vector_stores import VectorStores
return VectorStores(self)
@cached_property
def safety(self) -> Safety:
from .resources.safety import Safety
return Safety(self)
@cached_property
def webhooks(self) -> Webhooks:
from .resources.webhooks import Webhooks
return Webhooks(self)
@cached_property
def beta(self) -> Beta:
from .resources.beta import Beta
return Beta(self)
@cached_property
def batches(self) -> Batches:
"""Create large batches of API requests to run asynchronously."""
from .resources.batches import Batches
return Batches(self)
@cached_property
def uploads(self) -> Uploads:
"""Use Uploads to upload large files in multiple parts."""
from .resources.uploads import Uploads
return Uploads(self)
@cached_property
def admin(self) -> Admin:
from .resources.admin import Admin
return Admin(self)
@cached_property
def responses(self) -> Responses:
"""Create and manage model responses."""
from .resources.responses import Responses
return Responses(self)
@cached_property
def live(self) -> Live:
from .resources.live import Live
return Live(self)
@cached_property
def realtime(self) -> Realtime:
from .resources.realtime import Realtime
return Realtime(self)
@cached_property
def conversations(self) -> Conversations:
"""Manage conversations and conversation items."""
from .resources.conversations import Conversations
return Conversations(self)
@cached_property
def evals(self) -> Evals:
"""Manage and run evals in the OpenAI platform."""
from .resources.evals import Evals
return Evals(self)
@cached_property
def containers(self) -> Containers:
from .resources.containers import Containers
return Containers(self)
@cached_property
def skills(self) -> Skills:
from .resources.skills import Skills
return Skills(self)
@cached_property
def videos(self) -> Videos:
from .resources.videos import Videos
return Videos(self)
@cached_property
def with_raw_response(self) -> OpenAIWithRawResponse:
return OpenAIWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> OpenAIWithStreamedResponse:
return OpenAIWithStreamedResponse(self)
@property
@override
def qs(self) -> Querystring:
return Querystring(array_format="brackets")
@override
def _auth_headers(
self,
security: SecurityOptions,
) -> dict[str, str]:
from .lib._client_auth import sync_auth_headers
return sync_auth_headers(self, security)
@property
def _bearer_auth(
self,
) -> dict[str, str]:
from .lib._client_auth import sync_bearer_auth
return sync_bearer_auth(self)
@property
def _admin_api_key_auth(self) -> dict[str, str]:
admin_api_key = self.admin_api_key
if admin_api_key is None:
return {}
return {"Authorization": f"Bearer {admin_api_key}"}
@property
@override
def default_headers(self) -> dict[str, str | Omit]:
return {
**super().default_headers,
"X-Stainless-Async": "false",
"OpenAI-Organization": self.organization if self.organization is not None else Omit(),
"OpenAI-Project": self.project if self.project is not None else Omit(),
**self._custom_headers,
}
@override
def _validate_headers(
self,
headers: Headers,
custom_headers: Headers,
) -> None:
from .lib._client_auth import sync_validate_headers
return sync_validate_headers(self, headers, custom_headers)
def copy(
self,
*,
api_key: str | Callable[[], str] | None = None,
admin_api_key: str | None = None,
workload_identity: WorkloadIdentity | X509WorkloadIdentity | None = None,
provider: _Provider | None | NotGiven = not_given,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
websocket_base_url: str | httpx2.URL | None = None,
base_url: str | httpx2.URL | None | NotGiven = not_given,
data_residency: DataResidency | None = None,
timeout: float | Timeout | None | NotGiven = not_given,
http_client: httpx2.Client | None = None,
max_retries: int | NotGiven = not_given,
default_headers: Mapping[str, str] | None = None,
set_default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
set_default_query: Mapping[str, object] | None = None,
_enforce_credentials: bool | None = None,
_extra_kwargs: Mapping[str, Any] = {},
) -> Self:
"""
Create a new client instance re-using the same options given to the current client with optional overriding.
`data_residency` replaces the inherited HTTP and WebSocket endpoints, without changing this client.
"""
from .lib._client_auth import synccopy
return synccopy(
self,
api_key=api_key,
admin_api_key=admin_api_key,
workload_identity=workload_identity,
provider=provider,
organization=organization,
project=project,
webhook_secret=webhook_secret,
websocket_base_url=websocket_base_url,
base_url=base_url,
data_residency=data_residency,
timeout=timeout,
http_client=http_client,
max_retries=max_retries,
default_headers=default_headers,
set_default_headers=set_default_headers,
default_query=default_query,
set_default_query=set_default_query,
_enforce_credentials=_enforce_credentials,
_extra_kwargs=_extra_kwargs,
)
# Alias for `copy` for nicer inline usage, e.g.
# client.with_options(timeout=10).foo.create(...)
with_options = copy
@override
def _make_status_error(
self,
err_msg: str,
*,
body: object,
response: httpx2.Response,
) -> APIStatusError:
data = body.get("error", body) if is_mapping(body) else body
if response.status_code == 400:
return _exceptions.BadRequestError(err_msg, response=response, body=data)
if response.status_code == 401:
return _exceptions.AuthenticationError(err_msg, response=response, body=data)
if response.status_code == 403:
return _exceptions.PermissionDeniedError(err_msg, response=response, body=data)
if response.status_code == 404:
return _exceptions.NotFoundError(err_msg, response=response, body=data)
if response.status_code == 409:
return _exceptions.ConflictError(err_msg, response=response, body=data)
if response.status_code == 422:
return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data)
if response.status_code == 429:
return _exceptions.RateLimitError(err_msg, response=response, body=data)
if response.status_code >= 500:
return _exceptions.InternalServerError(err_msg, response=response, body=data)
return APIStatusError(err_msg, response=response, body=data)
class AsyncOpenAI(AsyncAPIClient):
workload_identity: WorkloadIdentity | X509WorkloadIdentity | None
_workload_identity_auth: WorkloadIdentityAuth | AsyncX509WorkloadIdentityAuth | None
_provider: _Provider | None
_provider_runtime: _ProviderRuntime | None
_base_url_was_default: bool
_data_residency: DataResidency | None
_ambient_authorizations: frozenset[str]
_api_key_provider: Callable[[], Awaitable[str]] | None
# client options
api_key: str
admin_api_key: str | None
organization: str | None
project: str | None
webhook_secret: str | None
websocket_base_url: str | httpx2.URL | None
"""Base URL for WebSocket connections.
If not specified, the default base URL will be used, with 'wss://' replacing the
'http://' or 'https://' scheme. For example: 'http://example.com' becomes
'wss://example.com'
"""
@property
@override
def base_url(
self,
) -> httpx2.URL:
from .lib._client_auth import asyncbase_url
return asyncbase_url(self)
@base_url.setter
def base_url(
self,
url: httpx2.URL | str,
) -> None:
from .lib._client_auth import asyncbase_url_set
return asyncbase_url_set(self, url)
async def _send_with_auth_retry(
self,
request: httpx2.Request,
*,
stream: bool,
retried: bool = False,
**kwargs: Unpack[HttpxSendArgs],
) -> httpx2.Response:
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import async_send_with_auth_retry
return await async_send_with_auth_retry(
_runtime_cast(_RuntimeAny, super()).__thisclass__, self, request, stream=stream, retried=retried, **kwargs
)
@override
async def _send_request(
self,
request: httpx2.Request,
*,
stream: bool,
**kwargs: Unpack[HttpxSendArgs],
) -> httpx2.Response:
from .lib._client_auth import async_send_request
return await async_send_request(self, request, stream=stream, **kwargs)
@property
@override
def auth_headers(
self,
) -> dict[str, str]:
from .lib._client_auth import asyncauth_headers
return asyncauth_headers(self)
@override
async def _prepare_options(
self,
options: FinalRequestOptions,
) -> FinalRequestOptions:
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import async_prepare_options
return await async_prepare_options(_runtime_cast(_RuntimeAny, super()).__thisclass__, self, options)
@override
async def _prepare_request(
self,
request: httpx2.Request,
) -> None:
from .lib._client_auth import async_prepare_request
return await async_prepare_request(self, request)
@property
@override
def custom_auth(
self,
) -> httpx2.Auth | None:
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import asynccustom_auth
return asynccustom_auth(_runtime_cast(_RuntimeAny, super()).__thisclass__, self)
async def _refresh_api_key(
self,
) -> str:
from .lib._client_auth import async_refresh_api_key
return await async_refresh_api_key(self)
def _websocket_query_params_fallback(self, url: httpx2.URL, extra_query: Query) -> httpx2.QueryParams:
# Remove replaced logical defaults before encoding nested query values.
overridden = dict.fromkeys(extra_query, omit)
overridden_prefixes = tuple(f"{key}[" for key in overridden)
defaults = _merge_mappings(self.default_query, overridden)
params = httpx2.QueryParams(self.qs.stringify(cast(Any, defaults))).merge(url.params)
params = httpx2.QueryParams(
[
(key, value)
for key, value in params.multi_items()
if key not in overridden and not key.startswith(overridden_prefixes)
]
)
if isinstance(extra_query, httpx2.QueryParams):
return params.merge(extra_query)
# Per-call None and sequences retain blank values and repeated keys;
# defaults continue to use the REST encoder's configured array format.
values = _merge_mappings({}, extra_query)
for key, value in values.items():
if value is None:
values[key] = ""
elif isinstance(value, (list, tuple)):
values[key] = ["" if item is None else item for item in cast(Iterable[object], value)]
return params.merge(self.qs.stringify(cast(Any, values), array_format="repeat"))
def __init__(
self,
*,
api_key: str | Callable[[], Awaitable[str]] | None = None,
admin_api_key: str | None = None,
workload_identity: WorkloadIdentity | X509WorkloadIdentity | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
provider: _Provider | None = None,
base_url: str | httpx2.URL | None | NotGiven = not_given,
data_residency: DataResidency | None = None,
websocket_base_url: str | httpx2.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: httpx2.AsyncClient | None = None,
_strict_response_validation: bool = False,
_enforce_credentials: bool = True,
) -> None:
"""Construct a new async AsyncOpenAI client instance.
This automatically infers the following arguments from their corresponding environment variables if they are not provided:
- `api_key` from `OPENAI_API_KEY`
- `admin_api_key` from `OPENAI_ADMIN_KEY`
- `organization` from `OPENAI_ORG_ID`
- `project` from `OPENAI_PROJECT_ID`
- `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
When `provider` is supplied, authentication and the base URL are configured by that provider instead.
`data_residency` selects an OpenAI regional endpoint and cannot be combined with
`base_url`, `websocket_base_url`, or `provider`.
"""
from typing import Any as _RuntimeAny, cast as _runtime_cast
from .lib._client_auth import async__init__
return async__init__(
_runtime_cast(_RuntimeAny, super()).__thisclass__,
self,
api_key=api_key,
admin_api_key=admin_api_key,
workload_identity=workload_identity,
organization=organization,
project=project,
webhook_secret=webhook_secret,
provider=provider,
base_url=base_url,
data_residency=data_residency,
websocket_base_url=websocket_base_url,
timeout=timeout,
max_retries=max_retries,
default_headers=default_headers,
default_query=default_query,
http_client=http_client,
_strict_response_validation=_strict_response_validation,
_enforce_credentials=_enforce_credentials,
)
@cached_property
def decisions(self) -> AsyncDecisions:
from .resources.decisions import AsyncDecisions
return AsyncDecisions(self)
@cached_property
def completions(self) -> AsyncCompletions:
"""
Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
"""
from .resources.completions import AsyncCompletions
return AsyncCompletions(self)
@cached_property
def chat(self) -> AsyncChat:
from .resources.chat import AsyncChat
return AsyncChat(self)
@cached_property
def embeddings(self) -> AsyncEmbeddings:
"""
Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
"""
from .resources.embeddings import AsyncEmbeddings
return AsyncEmbeddings(self)
@cached_property
def files(self) -> AsyncFiles:
"""
Files are used to upload documents that can be used with features like Assistants and Fine-tuning.
"""
from .resources.files import AsyncFiles
return AsyncFiles(self)
@cached_property
def images(self) -> AsyncImages:
"""Given a prompt and/or an input image, the model will generate a new image."""
from .resources.images import AsyncImages
return AsyncImages(self)
@cached_property
def content_provenance_checks(self) -> AsyncContentProvenanceChecks:
from .resources.content_provenance_checks import AsyncContentProvenanceChecks
return AsyncContentProvenanceChecks(self)
@cached_property
def audio(self) -> AsyncAudio:
from .resources.audio import AsyncAudio
return AsyncAudio(self)
@cached_property
def moderations(self) -> AsyncModerations:
"""
Given text and/or image inputs, classifies if those inputs are potentially harmful.
"""
from .resources.moderations import AsyncModerations
return AsyncModerations(self)
@cached_property
def models(self) -> AsyncModels:
"""List and describe the various models available in the API."""
from .resources.models import AsyncModels
return AsyncModels(self)
@cached_property
def fine_tuning(self) -> AsyncFineTuning:
from .resources.fine_tuning import AsyncFineTuning
return AsyncFineTuning(self)
@cached_property
def vector_stores(self) -> AsyncVectorStores:
from .resources.vector_stores import AsyncVectorStores
return AsyncVectorStores(self)
@cached_property
def safety(self) -> AsyncSafety:
from .resources.safety import AsyncSafety
return AsyncSafety(self)
@cached_property
def webhooks(self) -> AsyncWebhooks:
from .resources.webhooks import AsyncWebhooks
return AsyncWebhooks(self)
@cached_property
def beta(self) -> AsyncBeta:
from .resources.beta import AsyncBeta
return AsyncBeta(self)
@cached_property
def batches(self) -> AsyncBatches:
"""Create large batches of API requests to run asynchronously."""
from .resources.batches import AsyncBatches
return AsyncBatches(self)
@cached_property
def uploads(self) -> AsyncUploads:
"""Use Uploads to upload large files in multiple parts."""
from .resources.uploads import AsyncUploads
return AsyncUploads(self)
@cached_property
def admin(self) -> AsyncAdmin:
from .resources.admin import AsyncAdmin
return AsyncAdmin(self)
@cached_property
def responses(self) -> AsyncResponses:
"""Create and manage model responses."""
from .resources.responses import AsyncResponses